Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add unloadMicroApp api #2829

Open
wants to merge 2 commits into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/wet-socks-behave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"qiankun": patch
"@qiankunjs/sandbox": patch
---

feat: add unloadMicroApp api
23 changes: 23 additions & 0 deletions packages/qiankun/src/apis/loadMicroApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,26 @@ export function loadMicroApp<T extends ObjectType>(

return microApp;
}

export function unload(appName: string): Promise<unknown> {
const appConfigCaches = Array.from(appConfigPromiseGetterMap.entries()).filter(([key]) => key.startsWith(appName));
if (appConfigCaches.length) {
return Promise.all(
appConfigCaches.map(([key]) => {
appConfigPromiseGetterMap.delete(key);
const microApps = containerMicroAppsMap.get(key);
if (microApps?.length) {
containerMicroAppsMap.delete(key);
return microApps.map(async (microApp) => {
await microApp.unmount();
// todo microApp.unload
});
}

return;
}),
);
}

return Promise.resolve();
}
11 changes: 11 additions & 0 deletions packages/qiankun/src/apis/unloadMicroApp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { unloadApplication } from 'single-spa';
import { unload } from './loadMicroApp';
import { microApps } from './registerMicroApps';

export async function unloadMicroApp(appName: string): Promise<unknown> {
if (microApps.some((app) => app.name === appName)) {
return unloadApplication(appName, { waitForUnmount: true });
}

return unload(appName);
}
1 change: 1 addition & 0 deletions packages/qiankun/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './apis/loadMicroApp';
export * from './apis/unloadMicroApp';
export * from './apis/registerMicroApps';
export * from './apis/isRuntimeCompatible';
export * from './types';
7 changes: 6 additions & 1 deletion packages/sandbox/src/core/compartment/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// }

import { nativeGlobal } from '../../consts';
import type { Disposable } from '../sandbox/types';

const compartmentGlobalIdPrefix = '__compartment_globalThis__';
const compartmentGlobalIdSuffix = '__';
Expand All @@ -21,7 +22,7 @@ declare global {

let compartmentCounter = 0;

export class Compartment {
export class Compartment implements Disposable {
/**
* Since the time of execution of the code in Compartment is determined by the browser, a unique compartmentSpecifier should be generated in Compartment
*/
Expand Down Expand Up @@ -61,6 +62,10 @@ export class Compartment {
return `;(function(){with(this){${globalObjectOptimizer}${source}\n${sourceMapURL}}}).bind(window.${this.id})();`;
}

dispose() {
delete nativeGlobal[this.id];
}

// TODO add return value
// evaluate(code: string, options?: CompartmentOptions): void {
// const { transforms } = options || {};
Expand Down
111 changes: 14 additions & 97 deletions packages/sandbox/src/core/membrane/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,9 @@
/* eslint-disable no-param-reassign */
import {
create,
defineProperty,
freeze,
getOwnPropertyDescriptor,
getOwnPropertyNames,
hasOwnProperty,
keys,
} from '@qiankunjs/shared';
import { defineProperty, getOwnPropertyDescriptor, hasOwnProperty, keys } from '@qiankunjs/shared';
import { nativeGlobal } from '../../consts';
import { isPropertyFrozen } from '../../utils';
import { globalsInBrowser } from '../globals';
import { array2TruthyObject } from '../utils';
import { rebindTarget2Fn } from './utils';
import type { Disposable } from '../sandbox/types';
import { createMembraneTarget, isNativeGlobalProp, rebindTarget2Fn, uniq } from './utils';

declare global {
interface Window {
Expand Down Expand Up @@ -52,31 +43,17 @@ const useNativeWindowForBindingsProps = new Map<PropertyKey, boolean>([
['mockDomAPIInBlackList', process.env.NODE_ENV === 'test'],
]);

const isPropertyDescriptor = (v: unknown): boolean => {
return (
typeof v === 'object' &&
v !== null &&
['value', 'writable', 'get', 'set', 'configurable', 'enumerable'].some((p) => p in v)
);
};

const cachedGlobalsInBrowser = array2TruthyObject(
globalsInBrowser.concat(process.env.NODE_ENV === 'test' ? ['mockNativeWindowFunction'] : []),
);
const isNativeGlobalProp = (prop: string): boolean => {
return prop in cachedGlobalsInBrowser;
};

export class Membrane {
export class Membrane implements Disposable {
private locking = false;

modifications = new Set<PropertyKey>();
private readonly realmContextHandler: ProxyHandler<MembraneTarget>;
realmContext: WindowProxy;

realmGlobal: WindowProxy;
modifications = new Set<PropertyKey>();

target: MembraneTarget;

latestSetProp: PropertyKey | undefined;
latestSetProp?: PropertyKey;

constructor(
incubatorContext: WindowProxy,
Expand All @@ -93,8 +70,7 @@ export class Membrane {
const { target, propertiesWithGetter } = createMembraneTarget(endowments, incubatorContext);

this.target = target;

this.realmGlobal = new Proxy(this.target, {
this.realmContextHandler = {
set: (membraneTarget, p, value: never) => {
if (!this.locking) {
// sync the property to incubatorContext
Expand Down Expand Up @@ -240,7 +216,8 @@ export class Membrane {
getPrototypeOf() {
return Reflect.getPrototypeOf(incubatorContext);
},
}) as unknown as WindowProxy;
};
this.realmContext = new Proxy(target, this.realmContextHandler) as unknown as WindowProxy;
}

addIntrinsics(
Expand All @@ -261,68 +238,8 @@ export class Membrane {
unlock() {
this.locking = false;
}
}

function createMembraneTarget(
endowments: Endowments = {},
incubatorContext: WindowProxy,
): {
target: MembraneTarget;
propertiesWithGetter: Map<PropertyKey, boolean>;
} {
// map always has the best performance in `has` check scenario
// see https://jsperf.com/array-indexof-vs-set-has/23
const propertiesWithGetter = new Map<PropertyKey, boolean>();
const target: MembraneTarget = keys(endowments).reduce((acc, key) => {
const value = endowments[key];
if (isPropertyDescriptor(value)) {
defineProperty(acc, key, value);
} else {
acc[key] = value;
}
return acc;
}, {} as MembraneTarget);

/*
copy the non-configurable property of incubatorContext to membrane target to avoid TypeError
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/getOwnPropertyDescriptor
> A property cannot be reported as non-configurable, if it does not exist as an own property of the target object or if it exists as a configurable own property of the target object.
*/
getOwnPropertyNames(incubatorContext)
.filter((p) => {
const descriptor = getOwnPropertyDescriptor(incubatorContext, p);
return !hasOwnProperty(endowments, p) && !descriptor?.configurable;
})
.forEach((p) => {
const descriptor = getOwnPropertyDescriptor(incubatorContext, p);
if (descriptor) {
const hasGetter = hasOwnProperty(descriptor, 'get');
if (hasGetter) {
propertiesWithGetter.set(p, true);
}

defineProperty(
target,
p,
// freeze the descriptor to avoid being modified by zone.js
// see https://github.com/angular/zone.js/blob/a5fe09b0fac27ac5df1fa746042f96f05ccb6a00/lib/browser/define-property.ts#L71
freeze(descriptor),
);
}
});

return {
target,
propertiesWithGetter,
};
}

/**
* fastest(at most time) unique array method
* @see https://jsperf.com/array-filter-unique/30
*/
function uniq(array: Array<string | symbol>) {
return array.filter(function (this: Record<string | symbol, boolean>, element) {
return element in this ? false : (this[element] = true);
}, create(null));
dispose() {
Proxy.revocable(this.realmContext, this.realmContextHandler as unknown as ProxyHandler<WindowProxy>);
}
}
93 changes: 91 additions & 2 deletions packages/sandbox/src/core/membrane/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,97 @@
import { defineProperty, getOwnPropertyDescriptor, getOwnPropertyNames, hasOwnProperty } from '@qiankunjs/shared';
import {
create,
defineProperty,
freeze,
getOwnPropertyDescriptor,
getOwnPropertyNames,
hasOwnProperty,
keys,
} from '@qiankunjs/shared';
import { isBoundedFunction, isCallable, isConstructable } from '../../utils';
import { globalsInBrowser } from '../globals';
import { array2TruthyObject } from '../utils';
import type { Endowments, MembraneTarget } from './index';

const functionBoundedValueMap = new WeakMap<CallableFunction, CallableFunction>();
export const isPropertyDescriptor = (v: unknown): boolean => {
return (
typeof v === 'object' &&
v !== null &&
['value', 'writable', 'get', 'set', 'configurable', 'enumerable'].some((p) => p in v)
);
};

const cachedGlobalsInBrowser = array2TruthyObject(
globalsInBrowser.concat(process.env.NODE_ENV === 'test' ? ['mockNativeWindowFunction'] : []),
);
export const isNativeGlobalProp = (prop: string): boolean => {
return prop in cachedGlobalsInBrowser;
};

export function createMembraneTarget(
endowments: Endowments = {},
incubatorContext: WindowProxy,
): {
target: MembraneTarget;
propertiesWithGetter: Map<PropertyKey, boolean>;
} {
// map always has the best performance in `has` check scenario
// see https://jsperf.com/array-indexof-vs-set-has/23
const propertiesWithGetter = new Map<PropertyKey, boolean>();
const target: MembraneTarget = keys(endowments).reduce((acc, key) => {
const value = endowments[key];
if (isPropertyDescriptor(value)) {
defineProperty(acc, key, value);
} else {
acc[key] = value;
}
return acc;
}, {} as MembraneTarget);

/*
copy the non-configurable property of incubatorContext to membrane target to avoid TypeError
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/getOwnPropertyDescriptor
> A property cannot be reported as non-configurable, if it does not exist as an own property of the target object or if it exists as a configurable own property of the target object.
*/
getOwnPropertyNames(incubatorContext)
.filter((p) => {
const descriptor = getOwnPropertyDescriptor(incubatorContext, p);
return !hasOwnProperty(endowments, p) && !descriptor?.configurable;
})
.forEach((p) => {
const descriptor = getOwnPropertyDescriptor(incubatorContext, p);
if (descriptor) {
const hasGetter = hasOwnProperty(descriptor, 'get');
if (hasGetter) {
propertiesWithGetter.set(p, true);
}

defineProperty(
target,
p,
// freeze the descriptor to avoid being modified by zone.js
// see https://github.com/angular/zone.js/blob/a5fe09b0fac27ac5df1fa746042f96f05ccb6a00/lib/browser/define-property.ts#L71
freeze(descriptor),
);
}
});

return {
target,
propertiesWithGetter,
};
}

/**
* fastest(at most time) unique array method
* @see https://jsperf.com/array-filter-unique/30
*/
export function uniq(array: Array<string | symbol>) {
return array.filter(function (this: Record<string | symbol, boolean>, element) {
return element in this ? false : (this[element] = true);
}, create(null));
}

const functionBoundedValueMap = new WeakMap<CallableFunction, CallableFunction>();
export function rebindTarget2Fn<T>(target: unknown, fn: T, receiver: unknown): T {
/*
仅绑定 isCallable && !isBoundedFunction && !isConstructable 的函数对象,如 window.console、window.atob 这类,不然微应用中调用时会抛出 Illegal invocation 异常
Expand Down
15 changes: 5 additions & 10 deletions packages/sandbox/src/core/sandbox/StandardSandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ export class StandardSandbox extends Compartment implements Sandbox {
readonly name: string;

constructor(name: string, globals: Endowments, incubatorContext: WindowProxy = window) {
const getRealmGlobal = () => realmGlobal;
const getRealmGlobal = () => realmContext;
const getTopValue = (p: 'top' | 'parent'): WindowProxy => {
// if your master app in an iframe context, allow these props escape the sandbox
if (incubatorContext === incubatorContext.parent) {
return realmGlobal;
return realmContext;
}
return incubatorContext[p]!;
};
Expand All @@ -38,7 +38,7 @@ export class StandardSandbox extends Compartment implements Sandbox {
hasOwnProperty: {
value: function hasOwnPropertyImpl(this: unknown, key: PropertyKey): boolean {
// calling from hasOwnProperty.call(obj, key)
if (this !== realmGlobal && this !== null && typeof this === 'object') {
if (this !== realmContext && this !== null && typeof this === 'object') {
return hasOwnProperty(this, key);
}

Expand Down Expand Up @@ -84,9 +84,9 @@ export class StandardSandbox extends Compartment implements Sandbox {
endowments: { ...intrinsics, ...globals },
});

const { realmGlobal, target } = membrane;
const { realmContext, target } = membrane;

super(realmGlobal);
super(realmContext);

this.name = name;
this.membrane = membrane;
Expand Down Expand Up @@ -115,9 +115,4 @@ export class StandardSandbox extends Compartment implements Sandbox {

this.membrane.lock();
}

// TODO
// destroy() {
//
// }
}
7 changes: 6 additions & 1 deletion packages/sandbox/src/core/sandbox/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* @author Kuitos
* @since 2019-04-11
*/
import { patchAtBootstrapping, patchAtMounting } from '../../patchers';
import { disposePatcher, patchAtBootstrapping, patchAtMounting } from '../../patchers';
import type { SandboxConfig } from '../../patchers/dynamicAppend/types';
import type { Free, Rebuild } from '../../patchers/types';
import type { Endowments } from '../membrane';
Expand Down Expand Up @@ -91,5 +91,10 @@ export function createSandboxContainer(

sandbox.inactive();
},

async unload() {
sandbox.dispose();
disposePatcher(sandbox);
},
};
}
Loading