UNPKG

vite-plugin-qiankun-lite

Version:

A simple Vite plugin for efficiently running MicroFrontend applications using qiankun

1,282 lines (1,277 loc) 31 kB
import { types, transformAsync } from '@babel/core'; import { load } from 'cheerio'; import { declare } from '@babel/helper-plugin-utils'; import { parse } from '@babel/parser'; const globalBrowserVariables = [ "AbortController", "AbortSignal", "AbsoluteOrientationSensor", "Accelerometer", "AnalyserNode", "Animation", "AnimationEffect", "AnimationEvent", "AnimationPlaybackEvent", "ApplePayError", "ApplePaySession", "ApplicationCache", "ApplicationCacheErrorEvent", "Attr", "Audio", "AudioBuffer", "AudioBufferSourceNode", "AudioContext", "AudioDestinationNode", "AudioListener", "AudioNode", "AudioParam", "AudioParamMap", "AudioProcessingEvent", "AudioScheduledSourceNode", "AudioTrack", "AudioTrackList", "AudioWorklet", "AudioWorkletNode", "AuthenticatorAssertionResponse", "AuthenticatorAttestationResponse", "AuthenticatorResponse", "BarProp", "BaseAudioContext", "BatteryManager", "BeforeInstallPromptEvent", "BeforeLoadEvent", "BeforeUnloadEvent", "BiquadFilterNode", "Blob", "BlobEvent", "Bluetooth", "BluetoothCharacteristicProperties", "BluetoothDevice", "BluetoothRemoteGATTCharacteristic", "BluetoothRemoteGATTDescriptor", "BluetoothRemoteGATTServer", "BluetoothRemoteGATTService", "BluetoothUUID", "BroadcastChannel", "ByteLengthQueuingStrategy", "CDATASection", "CSS", "CSS2Properties", "CSSConditionRule", "CSSCounterStyleRule", "CSSFontFaceRule", "CSSFontFeatureValuesRule", "CSSGroupingRule", "CSSImageValue", "CSSImportRule", "CSSKeyframeRule", "CSSKeyframesRule", "CSSKeywordValue", "CSSMathInvert", "CSSMathMax", "CSSMathMin", "CSSMathNegate", "CSSMathProduct", "CSSMathSum", "CSSMathValue", "CSSMatrixComponent", "CSSMediaRule", "CSSMozDocumentRule", "CSSNamespaceRule", "CSSNumericArray", "CSSNumericValue", "CSSPageRule", "CSSPerspective", "CSSPositionValue", "CSSPrimitiveValue", "CSSRotate", "CSSRule", "CSSRuleList", "CSSScale", "CSSSkew", "CSSSkewX", "CSSSkewY", "CSSStyleDeclaration", "CSSStyleRule", "CSSStyleSheet", "CSSStyleValue", "CSSSupportsRule", "CSSTransformComponent", "CSSTransformValue", "CSSTranslate", "CSSUnitValue", "CSSUnparsedValue", "CSSValue", "CSSValueList", "CSSVariableReferenceValue", "Cache", "CacheStorage", "CanvasCaptureMediaStream", "CanvasCaptureMediaStreamTrack", "CanvasGradient", "CanvasPattern", "CanvasRenderingContext2D", "CaretPosition", "ChannelMergerNode", "ChannelSplitterNode", "CharacterData", "Clipboard", "ClipboardEvent", "CloseEvent", "Comment", "CompositionEvent", "ConstantSourceNode", "ConvolverNode", "CountQueuingStrategy", "Counter", "Credential", "CredentialsContainer", "Crypto", "CryptoKey", "CustomElementRegistry", "CustomEvent", "DOMError", "DOMException", "DOMImplementation", "DOMMatrix", "DOMMatrixReadOnly", "DOMParser", "DOMPoint", "DOMPointReadOnly", "DOMQuad", "DOMRect", "DOMRectList", "DOMRectReadOnly", "DOMRequest", "DOMStringList", "DOMStringMap", "DOMTokenList", "DataCue", "DataTransfer", "DataTransferItem", "DataTransferItemList", "Database", "DelayNode", "DeviceMotionEvent", "DeviceOrientationEvent", "Directory", "Document", "DocumentFragment", "DocumentType", "DragEvent", "DynamicsCompressorNode", "Element", "EnterPictureInPictureEvent", "ErrorEvent", "Event", "EventSource", "EventTarget", "External", "FederatedCredential", "File", "FileError", "FileList", "FileReader", "FileSystem", "FileSystemDirectoryEntry", "FileSystemDirectoryReader", "FileSystemEntry", "FileSystemFileEntry", "FocusEvent", "FontFace", "FontFaceSet", "FontFaceSetLoadEvent", "FormData", "GainNode", "Gamepad", "GamepadButton", "GamepadEvent", "GamepadHapticActuator", "GamepadPose", "GestureEvent", "Gyroscope", "HTMLAllCollection", "HTMLAnchorElement", "HTMLAppletElement", "HTMLAreaElement", "HTMLAudioElement", "HTMLBRElement", "HTMLBaseElement", "HTMLBodyElement", "HTMLButtonElement", "HTMLCanvasElement", "HTMLCollection", "HTMLContentElement", "HTMLDListElement", "HTMLDataElement", "HTMLDataListElement", "HTMLDetailsElement", "HTMLDialogElement", "HTMLDirectoryElement", "HTMLDivElement", "HTMLDocument", "HTMLElement", "HTMLEmbedElement", "HTMLFieldSetElement", "HTMLFontElement", "HTMLFormControlsCollection", "HTMLFormElement", "HTMLFrameElement", "HTMLFrameSetElement", "HTMLHRElement", "HTMLHeadElement", "HTMLHeadingElement", "HTMLHtmlElement", "HTMLIFrameElement", "HTMLImageElement", "HTMLInputElement", "HTMLKeygenElement", "HTMLLIElement", "HTMLLabelElement", "HTMLLegendElement", "HTMLLinkElement", "HTMLMapElement", "HTMLMarqueeElement", "HTMLMediaElement", "HTMLMenuElement", "HTMLMenuItemElement", "HTMLMetaElement", "HTMLMeterElement", "HTMLModElement", "HTMLOListElement", "HTMLObjectElement", "HTMLOptGroupElement", "HTMLOptionElement", "HTMLOptionsCollection", "HTMLOutputElement", "HTMLParagraphElement", "HTMLParamElement", "HTMLPictureElement", "HTMLPreElement", "HTMLProgressElement", "HTMLQuoteElement", "HTMLScriptElement", "HTMLSelectElement", "HTMLShadowElement", "HTMLSlotElement", "HTMLSourceElement", "HTMLSpanElement", "HTMLStyleElement", "HTMLTableCaptionElement", "HTMLTableCellElement", "HTMLTableColElement", "HTMLTableElement", "HTMLTableRowElement", "HTMLTableSectionElement", "HTMLTemplateElement", "HTMLTextAreaElement", "HTMLTimeElement", "HTMLTitleElement", "HTMLTrackElement", "HTMLUListElement", "HTMLUnknownElement", "HTMLVideoElement", "HashChangeEvent", "Headers", "History", "IDBCursor", "IDBCursorWithValue", "IDBDatabase", "IDBFactory", "IDBFileHandle", "IDBFileRequest", "IDBIndex", "IDBKeyRange", "IDBMutableFile", "IDBObjectStore", "IDBOpenDBRequest", "IDBRequest", "IDBTransaction", "IDBVersionChangeEvent", "IIRFilterNode", "IdleDeadline", "Image", "ImageBitmap", "ImageBitmapRenderingContext", "ImageCapture", "ImageData", "InputDeviceCapabilities", "InputDeviceInfo", "InputEvent", "InstallTrigger", "InternalError", "IntersectionObserver", "IntersectionObserverEntry", "KeyEvent", "Keyboard", "KeyboardEvent", "KeyboardLayoutMap", "KeyframeEffect", "LinearAccelerationSensor", "Location", "Lock", "LockManager", "MIDIAccess", "MIDIConnectionEvent", "MIDIInput", "MIDIInputMap", "MIDIMessageEvent", "MIDIOutput", "MIDIOutputMap", "MIDIPort", "MediaCapabilities", "MediaCapabilitiesInfo", "MediaController", "MediaDeviceInfo", "MediaDevices", "MediaElementAudioSourceNode", "MediaEncryptedEvent", "MediaError", "MediaKeyError", "MediaKeyMessageEvent", "MediaKeySession", "MediaKeyStatusMap", "MediaKeySystemAccess", "MediaKeys", "MediaList", "MediaMetadata", "MediaQueryList", "MediaQueryListEvent", "MediaRecorder", "MediaRecorderErrorEvent", "MediaSession", "MediaSettingsRange", "MediaSource", "MediaStream", "MediaStreamAudioDestinationNode", "MediaStreamAudioSourceNode", "MediaStreamEvent", "MediaStreamTrack", "MediaStreamTrackEvent", "MerchantValidationEvent", "MessageChannel", "MessageEvent", "MessagePort", "MimeType", "MimeTypeArray", "MouseEvent", "MouseScrollEvent", "MutationEvent", "MutationObserver", "MutationRecord", "NamedNodeMap", "NavigationPreloadManager", "Navigator", "NetworkInformation", "Node", "NodeFilter", "NodeIterator", "NodeList", "Notification", "OfflineAudioCompletionEvent", "OfflineAudioContext", "OfflineResourceList", "OffscreenCanvas", "OffscreenCanvasRenderingContext2D", "Option", "OrientationSensor", "OscillatorNode", "OverconstrainedError", "OverconstrainedErrorEvent", "OverflowEvent", "PageTransitionEvent", "PaintRequest", "PaintRequestList", "PannerNode", "PasswordCredential", "Path2D", "PaymentAddress", "PaymentInstruments", "PaymentManager", "PaymentMethodChangeEvent", "PaymentRequest", "PaymentRequestUpdateEvent", "PaymentResponse", "Performance", "PerformanceEntry", "PerformanceLongTaskTiming", "PerformanceMark", "PerformanceMeasure", "PerformanceNavigation", "PerformanceNavigationTiming", "PerformanceObserver", "PerformanceObserverEntryList", "PerformancePaintTiming", "PerformanceResourceTiming", "PerformanceServerTiming", "PerformanceTiming", "PeriodicWave", "PermissionStatus", "Permissions", "PhotoCapabilities", "PictureInPictureWindow", "Plugin", "PluginArray", "PointerEvent", "PopStateEvent", "PopupBlockedEvent", "Presentation", "PresentationAvailability", "PresentationConnection", "PresentationConnectionAvailableEvent", "PresentationConnectionCloseEvent", "PresentationConnectionList", "PresentationReceiver", "PresentationRequest", "ProcessingInstruction", "ProgressEvent", "PromiseRejectionEvent", "PublicKeyCredential", "PushManager", "PushSubscription", "PushSubscriptionOptions", "RGBColor", "RTCCertificate", "RTCDTMFSender", "RTCDTMFToneChangeEvent", "RTCDataChannel", "RTCDataChannelEvent", "RTCIceCandidate", "RTCIceTransport", "RTCPeerConnection", "RTCPeerConnectionIceEvent", "RTCRtpReceiver", "RTCRtpSender", "RTCRtpTransceiver", "RTCSessionDescription", "RTCStatsReport", "RTCTrackEvent", "RadioNodeList", "Range", "ReadableStream", "Rect", "RelativeOrientationSensor", "RemotePlayback", "ReportingObserver", "Request", "ResizeObserver", "ResizeObserverEntry", "Response", "SQLError", "SQLResultSet", "SQLResultSetRowList", "SQLTransaction", "SVGAElement", "SVGAltGlyphDefElement", "SVGAltGlyphElement", "SVGAltGlyphItemElement", "SVGAngle", "SVGAnimateColorElement", "SVGAnimateElement", "SVGAnimateMotionElement", "SVGAnimateTransformElement", "SVGAnimatedAngle", "SVGAnimatedBoolean", "SVGAnimatedEnumeration", "SVGAnimatedInteger", "SVGAnimatedLength", "SVGAnimatedLengthList", "SVGAnimatedNumber", "SVGAnimatedNumberList", "SVGAnimatedPreserveAspectRatio", "SVGAnimatedRect", "SVGAnimatedString", "SVGAnimatedTransformList", "SVGAnimationElement", "SVGCircleElement", "SVGClipPathElement", "SVGComponentTransferFunctionElement", "SVGCursorElement", "SVGDefsElement", "SVGDescElement", "SVGDiscardElement", "SVGDocument", "SVGElement", "SVGEllipseElement", "SVGFEBlendElement", "SVGFEColorMatrixElement", "SVGFEComponentTransferElement", "SVGFECompositeElement", "SVGFEConvolveMatrixElement", "SVGFEDiffuseLightingElement", "SVGFEDisplacementMapElement", "SVGFEDistantLightElement", "SVGFEDropShadowElement", "SVGFEFloodElement", "SVGFEFuncAElement", "SVGFEFuncBElement", "SVGFEFuncGElement", "SVGFEFuncRElement", "SVGFEGaussianBlurElement", "SVGFEImageElement", "SVGFEMergeElement", "SVGFEMergeNodeElement", "SVGFEMorphologyElement", "SVGFEOffsetElement", "SVGFEPointLightElement", "SVGFESpecularLightingElement", "SVGFESpotLightElement", "SVGFETileElement", "SVGFETurbulenceElement", "SVGFilterElement", "SVGFontElement", "SVGFontFaceElement", "SVGFontFaceFormatElement", "SVGFontFaceNameElement", "SVGFontFaceSrcElement", "SVGFontFaceUriElement", "SVGForeignObjectElement", "SVGGElement", "SVGGeometryElement", "SVGGlyphElement", "SVGGlyphRefElement", "SVGGradientElement", "SVGGraphicsElement", "SVGHKernElement", "SVGImageElement", "SVGLength", "SVGLengthList", "SVGLineElement", "SVGLinearGradientElement", "SVGMPathElement", "SVGMarkerElement", "SVGMaskElement", "SVGMatrix", "SVGMetadataElement", "SVGMissingGlyphElement", "SVGNumber", "SVGNumberList", "SVGPathElement", "SVGPathSeg", "SVGPathSegArcAbs", "SVGPathSegArcRel", "SVGPathSegClosePath", "SVGPathSegCurvetoCubicAbs", "SVGPathSegCurvetoCubicRel", "SVGPathSegCurvetoCubicSmoothAbs", "SVGPathSegCurvetoCubicSmoothRel", "SVGPathSegCurvetoQuadraticAbs", "SVGPathSegCurvetoQuadraticRel", "SVGPathSegCurvetoQuadraticSmoothAbs", "SVGPathSegCurvetoQuadraticSmoothRel", "SVGPathSegLinetoAbs", "SVGPathSegLinetoHorizontalAbs", "SVGPathSegLinetoHorizontalRel", "SVGPathSegLinetoRel", "SVGPathSegLinetoVerticalAbs", "SVGPathSegLinetoVerticalRel", "SVGPathSegList", "SVGPathSegMovetoAbs", "SVGPathSegMovetoRel", "SVGPatternElement", "SVGPoint", "SVGPointList", "SVGPolygonElement", "SVGPolylineElement", "SVGPreserveAspectRatio", "SVGRadialGradientElement", "SVGRect", "SVGRectElement", "SVGRenderingIntent", "SVGSVGElement", "SVGScriptElement", "SVGSetElement", "SVGStopElement", "SVGStringList", "SVGStyleElement", "SVGSwitchElement", "SVGSymbolElement", "SVGTRefElement", "SVGTSpanElement", "SVGTextContentElement", "SVGTextElement", "SVGTextPathElement", "SVGTextPositioningElement", "SVGTitleElement", "SVGTransform", "SVGTransformList", "SVGUnitTypes", "SVGUseElement", "SVGVKernElement", "SVGViewElement", "SVGViewSpec", "SVGZoomAndPan", "SVGZoomEvent", "Screen", "ScreenOrientation", "ScriptProcessorNode", "ScrollAreaEvent", "SecurityPolicyViolationEvent", "Selection", "Sensor", "SensorErrorEvent", "ServiceWorker", "ServiceWorkerContainer", "ServiceWorkerRegistration", "ShadowRoot", "SharedWorker", "SourceBuffer", "SourceBufferList", "SpeechSynthesis", "SpeechSynthesisErrorEvent", "SpeechSynthesisEvent", "SpeechSynthesisUtterance", "SpeechSynthesisVoice", "StaticRange", "StereoPannerNode", "Storage", "StorageEvent", "StorageManager", "StylePropertyMap", "StylePropertyMapReadOnly", "StyleSheet", "StyleSheetList", "SubtleCrypto", "SyncManager", "TaskAttributionTiming", "Text", "TextDecoderStream", "TextEncoderStream", "TextEvent", "TextMetrics", "TextTrack", "TextTrackCue", "TextTrackCueList", "TextTrackList", "TimeEvent", "TimeRanges", "Touch", "TouchEvent", "TouchList", "TrackEvent", "TransformStream", "TransitionEvent", "TreeWalker", "UIEvent", "USB", "USBAlternateInterface", "USBConfiguration", "USBConnectionEvent", "USBDevice", "USBEndpoint", "USBInTransferResult", "USBInterface", "USBIsochronousInTransferPacket", "USBIsochronousInTransferResult", "USBIsochronousOutTransferPacket", "USBIsochronousOutTransferResult", "USBOutTransferResult", "UserActivation", "UserMessageHandler", "UserMessageHandlersNamespace", "VRDisplay", "VRDisplayCapabilities", "VRDisplayEvent", "VREyeParameters", "VRFieldOfView", "VRFrameData", "VRPose", "VRStageParameters", "VTTCue", "VTTRegion", "ValidityState", "VideoPlaybackQuality", "VideoTrack", "VideoTrackList", "VisualViewport", "WaveShaperNode", "WebGL2RenderingContext", "WebGLActiveInfo", "WebGLBuffer", "WebGLContextEvent", "WebGLFramebuffer", "WebGLProgram", "WebGLQuery", "WebGLRenderbuffer", "WebGLRenderingContext", "WebGLSampler", "WebGLShader", "WebGLShaderPrecisionFormat", "WebGLSync", "WebGLTexture", "WebGLTransformFeedback", "WebGLUniformLocation", "WebGLVertexArrayObject", "WebKitAnimationEvent", "WebKitCSSMatrix", "WebKitMediaKeyError", "WebKitMediaKeyMessageEvent", "WebKitMediaKeyNeededEvent", "WebKitMediaKeySession", "WebKitMediaKeys", "WebKitMutationObserver", "WebKitNamespace", "WebKitPlaybackTargetAvailabilityEvent", "WebKitPoint", "WebKitTransitionEvent", "WebSocket", "WheelEvent", "Window", "Worker", "Worklet", "WritableStream", "XMLDocument", "XMLHttpRequest", "XMLHttpRequestEventTarget", "XMLHttpRequestProgressEvent", "XMLHttpRequestUpload", "XMLSerializer", "XPathEvaluator", "XPathExpression", "XPathResult", "XSLTProcessor", "alert", "applicationCache", "atob", "blur", "btoa", "caches", "cancelAnimationFrame", "cancelIdleCallback", "captureEvents", "chrome", "clientInformation", "close", "closed", "confirm", "content", "createImageBitmap", "crypto", "customElements", "defaultStatus", "defaultstatus", "devicePixelRatio", "document", "dump", "event", "external", "fetch", "find", "focus", "frameElement", "frames", "fullScreen", "getComputedStyle", "getDefaultComputedStyle", "getMatchedCSSRules", "getSelection", "globalThis", "history", "indexedDB", "innerHeight", "innerWidth", "isSecureContext", "localStorage", "location", "locationbar", "matchMedia", "menubar", "moveBy", "moveTo", "mozInnerScreenX", "mozInnerScreenY", "mozPaintCount", "mozRTCIceCandidate", "mozRTCPeerConnection", "mozRTCSessionDescription", "navigator", "netscape", "offscreenBuffering", "onabort", "onabsolutedeviceorientation", "onafterprint", "onanimationcancel", "onanimationend", "onanimationiteration", "onanimationstart", "onappinstalled", "onauxclick", "onbeforeinstallprompt", "onbeforeprint", "onbeforeunload", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondevicelight", "ondevicemotion", "ondeviceorientation", "ondeviceorientationabsolute", "ondeviceproximity", "ondrag", "ondragend", "ondragenter", "ondragexit", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "ongotpointercapture", "onhashchange", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onlanguagechange", "onload", "onloadeddata", "onloadedmetadata", "onloadend", "onloadstart", "onlostpointercapture", "onmessage", "onmessageerror", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onmozfullscreenchange", "onmozfullscreenerror", "onoffline", "ononline", "onpagehide", "onpageshow", "onpause", "onplay", "onplaying", "onpointercancel", "onpointerdown", "onpointerenter", "onpointerleave", "onpointermove", "onpointerout", "onpointerover", "onpointerup", "onpopstate", "onprogress", "onratechange", "onrejectionhandled", "onreset", "onresize", "onscroll", "onsearch", "onseeked", "onseeking", "onselect", "onselectionchange", "onselectstart", "onshow", "onstalled", "onstorage", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "ontransitioncancel", "ontransitionend", "ontransitionrun", "ontransitionstart", "onunhandledrejection", "onunload", "onuserproximity", "onvolumechange", "onvrdisplayactivate", "onvrdisplayconnect", "onvrdisplaydeactivate", "onvrdisplaydisconnect", "onvrdisplaypresentchange", "onwaiting", "onwebkitanimationend", "onwebkitanimationiteration", "onwebkitanimationstart", "onwebkitmouseforcechanged", "onwebkitmouseforcedown", "onwebkitmouseforceup", "onwebkitmouseforcewillbegin", "onwebkittransitionend", "onwheel", "open", "openDatabase", "opener", "origin", "outerHeight", "outerWidth", "pageXOffset", "pageYOffset", "parent", "performance", "personalbar", "postMessage", "print", "prompt", "releaseEvents", "requestAnimationFrame", "requestIdleCallback", "resizeBy", "resizeTo", "safari", "screen", "screenLeft", "screenTop", "screenX", "screenY", "scroll", "scrollBy", "scrollByLines", "scrollByPages", "scrollMaxX", "scrollMaxY", "scrollTo", "scrollX", "scrollY", "scrollbars", "self", "sessionStorage", "setResizable", "showModalDialog", "sidebar", "sizeToContent", "speechSynthesis", "status", "statusbar", "stop", "styleMedia", "toolbar", "top", "uneval", "updateCommands", "visualViewport", "webkitAudioContext", "webkitAudioPannerNode", "webkitCancelAnimationFrame", "webkitCancelRequestAnimationFrame", "webkitConvertPointFromNodeToPage", "webkitConvertPointFromPageToNode", "webkitIndexedDB", "webkitMediaStream", "webkitOfflineAudioContext", "webkitRTCPeerConnection", "webkitRequestAnimationFrame", "webkitRequestFileSystem", "webkitResolveLocalFileSystemURL", "webkitSpeechGrammar", "webkitSpeechGrammarList", "webkitSpeechRecognition", "webkitSpeechRecognitionError", "webkitSpeechRecognitionEvent", "webkitStorageInfo", "webkitURL" ]; const plugin = declare((api, options = {}) => { const replace = { ...options.addWindowPrefix && globalBrowserVariables.reduce( (acc, globalBrowserVariables2) => Object.assign(acc, { [globalBrowserVariables2]: `${options.replace?.window ?? "window"}.${globalBrowserVariables2}` }), {} ), ...options.replace }; return { visitor: { Identifier(path) { if (!isReplaceableIdentifier(path, Object.keys(replace))) return; const replacementIdentifier = parseToMemberExpressionOrIdentifier( replace[path.node.name] ); path.replaceWith(replacementIdentifier); }, MemberExpression(path, state) { const code = state.file.code.substring( // biome-ignore lint/style/noNonNullAssertion: <explanation> path.node.start, // biome-ignore lint/style/noNonNullAssertion: <explanation> path.node.end ); if (!isReplaceableMemberExpression(path, code, Object.keys(replace))) return; const replacementMemberExpression = parseToMemberExpressionOrIdentifier( replace[code] ); path.replaceWith(replacementMemberExpression); } } }; }); function isReplaceableIdentifier(path, fromStrings) { return fromStrings.includes(path.node.name) && !path.scope.hasBinding(path.node.name) && !path.parentPath.isMemberExpression({ property: path.node }) && !path.parentPath.isOptionalMemberExpression({ property: path.node }) && !path.parentPath.isObjectProperty({ key: path.node }) && !path.parentPath.isObjectMethod({ key: path.node }) && !path.parentPath.isClassProperty({ key: path.node }) && !path.parentPath.isClassMethod({ key: path.node }) && !path.parentPath.isPrivateName({ id: path.node }) && !path.parentPath.isExportSpecifier(); } function isReplaceableMemberExpression(path, code, fromStrings) { if (!fromStrings.includes(code)) return false; const deepestNodePath = getDeepestNodePath(path); return types.isIdentifier(deepestNodePath.node) && !deepestNodePath.scope.hasBinding(deepestNodePath.node.name) && !path.parentPath.isMemberExpression({ object: path.node }) && !path.parentPath.isOptionalMemberExpression({ object: path.node }); } function getDeepestNodePath(path) { let deepestNodePath = path; while (deepestNodePath.node.object) { deepestNodePath = deepestNodePath.get("object"); } return deepestNodePath; } const cachedExpressionMap = /* @__PURE__ */ new Map(); function parseToMemberExpressionOrIdentifier(code) { const cachedExpression = cachedExpressionMap.get(code); if (cachedExpression) { return cachedExpression; } const ast = parse(code); const statement = ast.program.body[0]; if (!types.isExpressionStatement(statement)) { throw new Error("Expected ExpressionStatement"); } const expression = statement.expression; if (!types.isMemberExpression(expression) && !types.isIdentifier(expression)) { throw new Error("Expected MemberExpression or Identifier"); } cachedExpressionMap.set(code, expression); return expression; } function viteQiankun(opts) { let config; const qiankunWindow = `__QIANKUN_WINDOW__["${opts.name}"]`; let publicPath = `(${qiankunWindow}.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ || "")`; return [ { name: "qiankun:remain-exports", enforce: "post", apply: "build", options(options) { return { ...options, preserveEntrySignatures: "strict" }; }, transform(code, id) { if (id.endsWith("html") && this.getModuleInfo(id)?.isEntry) { return code.replace( /import\s+(['"])([^'"]+\.(m?js|[jt]sx?))\1/g, "export * from $1$2$1" ); } return null; } }, { name: "qiankun:vite-module-script-transform", enforce: "post", apply: "serve", configureServer(server) { return () => { server.middlewares.use((_, res, next) => { if (config.isProduction) return next(); const end = res.end.bind(res); res.end = (...args) => { let [htmlStr, ...rest] = args; if (typeof htmlStr === "string") { const $ = load(htmlStr); moduleScriptToGeneralScript( $($(`script[src=${config.base}@vite/client]`).get(0)), publicPath ); const moduleScripts$ = $("script:not([src])[type=module]"); moduleScripts$.each((_2, moduleScript) => { const moduleScript$ = $(moduleScript); if (moduleScript$.text().includes(`${config.base}@react-refresh`)) { reactRefreshModuleScriptToGeneralScript( moduleScript$, `${publicPath} + "${config.base}@react-refresh"` ); } }); htmlStr = $.html(); } return end(htmlStr, ...rest); }; next(); }); }; } }, { name: "qiankun:support-sandbox", enforce: "post", async transform(code, id) { const [filepath] = id.split("?"); const jsExts = [/\.[jt]sx?$/, /\.(c|m)?js?$/, /\.vue$/, /\.svelte$/]; if (!jsExts.some((reg) => reg.test(filepath))) return; const baseTransformOptions = { root: process.cwd(), filename: id, sourceFileName: filepath, sourceMaps: true }; if (!opts.sandbox) { const qiankunGlobalVariables = [ "window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__", "window.__POWERED_BY_QIANKUN__" ]; if (!qiankunGlobalVariables.some( (qiankunGlobalVariable) => code.includes(qiankunGlobalVariable) )) return; const result2 = await transformAsync(code, { ...baseTransformOptions, plugins: [ [ plugin, { replace: { ...qiankunGlobalVariables.reduce( (acc, qiankunGlobalVariable) => { acc[qiankunGlobalVariable] = qiankunGlobalVariable.replace( "window", qiankunWindow ); return acc; }, {} ) } } ] ] }); if (result2?.code) { return { code: result2.code, map: result2.map }; } return; } if (!/(document|window|globalThis|self)/g.test(code)) return; const result = await transformAsync(code, { ...baseTransformOptions, plugins: [ [ plugin, { replace: { ...Object.keys(config.define ?? []).reduce( (acc, key) => { acc[key] = `${qiankunWindow}.${key}`; return acc; }, {} ), window: qiankunWindow }, addWindowPrefix: true } ] ] }); if (result?.code) { return { code: result.code, map: result.map }; } } }, { name: "qiankun:html-transform", enforce: "post", configResolved(resolvedConfig) { config = resolvedConfig; if (config.base) { publicPath = `${publicPath}.replace(${new RegExp( `${config.base}$` )}, "")`; } }, transformIndexHtml(html) { const $ = load(html); $("head").prepend(` <script> const nativeGlobal = Function("return this")(); nativeGlobal.__QIANKUN_WINDOW__ = nativeGlobal.__QIANKUN_WINDOW__ || {}; nativeGlobal.__QIANKUN_WINDOW__["${opts.name}"] = nativeGlobal.proxy || nativeGlobal; <\/script> `); const moduleTags = $( 'body script[src][type=module], head script[src][crossorigin=""]' ); if (!moduleTags || !moduleTags.length) { return; } moduleTags.each( (_, moduleTag) => void moduleScriptToGeneralScript($(moduleTag), publicPath) ); const script$ = moduleTags.last(); script$?.html(` window["${opts.name}"] = {}; const lifecycleNames = ["bootstrap", "mount", "unmount", "update"]; ${script$.html()}.then((lifecycleHooks) => { lifecycleNames.forEach((lifecycleName) => window["${opts.name}"][lifecycleName].resolve( lifecycleHooks[lifecycleName], ), ); }); lifecycleNames.forEach((lifecycleName) => { let resolve; const promise = new Promise((_resolve) => (resolve = _resolve)); window["${opts.name}"][lifecycleName] = Object.assign( (...args) => promise.then((lifecycleHook) => lifecycleHook(...args)), { resolve }, ); }); `); return $.html(); } } ]; } function moduleScriptToGeneralScript(script$, publicPath) { const scriptSrc = script$.attr("src"); if (!scriptSrc) return; script$.removeAttr("src").removeAttr("type").html(`import(${publicPath} + "${scriptSrc}")`); return script$; } function reactRefreshModuleScriptToGeneralScript(script$, reactRefreshImportPath) { script$.removeAttr("type").html(` ((window) => { import(${reactRefreshImportPath}).then(({ default: RefreshRuntime }) => { RefreshRuntime.injectIntoGlobalHook(window); window.$RefreshReg$ = () => {}; window.$RefreshSig$ = () => (type) => type; window.__vite_plugin_react_preamble_installed__ = true; }); })(new Function("return this")()); `); return script$; } export { viteQiankun as default };