|
| 1 | +/*--------------------------------------------------------------------------------------------- |
| 2 | + * Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | + * Licensed under the MIT License. See License.txt in the project root for license information. |
| 4 | + *--------------------------------------------------------------------------------------------*/ |
| 5 | + |
| 6 | +import { isESM } from 'vs/base/common/amd'; |
| 7 | +import { AppResourcePath, FileAccess, nodeModulesAsarPath, nodeModulesPath } from 'vs/base/common/network'; |
| 8 | +import * as platform from 'vs/base/common/platform'; |
| 9 | +import { IProductConfiguration } from 'vs/base/common/product'; |
| 10 | +import { URI } from 'vs/base/common/uri'; |
| 11 | + |
| 12 | +class DefineCall { |
| 13 | + constructor( |
| 14 | + public readonly id: string | null | undefined, |
| 15 | + public readonly dependencies: string[] | null | undefined, |
| 16 | + public readonly callback: any |
| 17 | + ) { } |
| 18 | +} |
| 19 | + |
| 20 | +class AMDModuleImporter { |
| 21 | + public static INSTANCE = new AMDModuleImporter(); |
| 22 | + |
| 23 | + private readonly _isWebWorker = (typeof self === 'object' && self.constructor && self.constructor.name === 'DedicatedWorkerGlobalScope'); |
| 24 | + private readonly _isRenderer = typeof document === 'object'; |
| 25 | + |
| 26 | + private readonly _defineCalls: DefineCall[] = []; |
| 27 | + private _initialized = false; |
| 28 | + private _amdPolicy: Pick<TrustedTypePolicy<{ |
| 29 | + createScriptURL(value: string): string; |
| 30 | + }>, 'name' | 'createScriptURL'> | undefined; |
| 31 | + |
| 32 | + constructor() { } |
| 33 | + |
| 34 | + private _initialize(): void { |
| 35 | + if (this._initialized) { |
| 36 | + return; |
| 37 | + } |
| 38 | + this._initialized = true; |
| 39 | + |
| 40 | + (<any>globalThis).define = (id: any, dependencies: any, callback: any) => { |
| 41 | + if (typeof id !== 'string') { |
| 42 | + callback = dependencies; |
| 43 | + dependencies = id; |
| 44 | + id = null; |
| 45 | + } |
| 46 | + if (typeof dependencies !== 'object' || !Array.isArray(dependencies)) { |
| 47 | + callback = dependencies; |
| 48 | + dependencies = null; |
| 49 | + } |
| 50 | + // if (!dependencies) { |
| 51 | + // dependencies = ['require', 'exports', 'module']; |
| 52 | + // } |
| 53 | + this._defineCalls.push(new DefineCall(id, dependencies, callback)); |
| 54 | + }; |
| 55 | + |
| 56 | + (<any>globalThis).define.amd = true; |
| 57 | + |
| 58 | + if (this._isRenderer) { |
| 59 | + this._amdPolicy = window.trustedTypes?.createPolicy('amdLoader', { |
| 60 | + createScriptURL(value) { |
| 61 | + if (value.startsWith(window.location.origin)) { |
| 62 | + return value; |
| 63 | + } |
| 64 | + if (value.startsWith('vscode-file://vscode-app')) { |
| 65 | + return value; |
| 66 | + } |
| 67 | + throw new Error(`[trusted_script_src] Invalid script url: ${value}`); |
| 68 | + } |
| 69 | + }); |
| 70 | + } else if (this._isWebWorker) { |
| 71 | + this._amdPolicy = (<any>globalThis).trustedTypes?.createPolicy('amdLoader', { |
| 72 | + createScriptURL(value: string) { |
| 73 | + return value; |
| 74 | + } |
| 75 | + }); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + public async load<T>(scriptSrc: string): Promise<T> { |
| 80 | + this._initialize(); |
| 81 | + const defineCall = await (this._isWebWorker ? this._workerLoadScript(scriptSrc) : this._isRenderer ? this._rendererLoadScript(scriptSrc) : this._nodeJSLoadScript(scriptSrc)); |
| 82 | + if (!defineCall) { |
| 83 | + throw new Error(`Did not receive a define call from script ${scriptSrc}`); |
| 84 | + } |
| 85 | + // TODO require, exports, module |
| 86 | + if (Array.isArray(defineCall.dependencies) && defineCall.dependencies.length > 0) { |
| 87 | + throw new Error(`Cannot resolve dependencies for script ${scriptSrc}. The dependencies are: ${defineCall.dependencies.join(', ')}`); |
| 88 | + } |
| 89 | + if (typeof defineCall.callback === 'function') { |
| 90 | + return defineCall.callback([]); |
| 91 | + } else { |
| 92 | + return defineCall.callback; |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + private _rendererLoadScript(scriptSrc: string): Promise<DefineCall | undefined> { |
| 97 | + return new Promise<DefineCall | undefined>((resolve, reject) => { |
| 98 | + const scriptElement = document.createElement('script'); |
| 99 | + scriptElement.setAttribute('async', 'async'); |
| 100 | + scriptElement.setAttribute('type', 'text/javascript'); |
| 101 | + |
| 102 | + const unbind = () => { |
| 103 | + scriptElement.removeEventListener('load', loadEventListener); |
| 104 | + scriptElement.removeEventListener('error', errorEventListener); |
| 105 | + }; |
| 106 | + |
| 107 | + const loadEventListener = (e: any) => { |
| 108 | + unbind(); |
| 109 | + resolve(this._defineCalls.pop()); |
| 110 | + }; |
| 111 | + |
| 112 | + const errorEventListener = (e: any) => { |
| 113 | + unbind(); |
| 114 | + reject(e); |
| 115 | + }; |
| 116 | + |
| 117 | + scriptElement.addEventListener('load', loadEventListener); |
| 118 | + scriptElement.addEventListener('error', errorEventListener); |
| 119 | + if (this._amdPolicy) { |
| 120 | + scriptSrc = this._amdPolicy.createScriptURL(scriptSrc) as any as string; |
| 121 | + } |
| 122 | + scriptElement.setAttribute('src', scriptSrc); |
| 123 | + document.getElementsByTagName('head')[0].appendChild(scriptElement); |
| 124 | + }); |
| 125 | + } |
| 126 | + |
| 127 | + private _workerLoadScript(scriptSrc: string): Promise<DefineCall | undefined> { |
| 128 | + return new Promise<DefineCall | undefined>((resolve, reject) => { |
| 129 | + try { |
| 130 | + if (this._amdPolicy) { |
| 131 | + scriptSrc = this._amdPolicy.createScriptURL(scriptSrc) as any as string; |
| 132 | + } |
| 133 | + importScripts(scriptSrc); |
| 134 | + resolve(this._defineCalls.pop()); |
| 135 | + } catch (err) { |
| 136 | + reject(err); |
| 137 | + } |
| 138 | + }); |
| 139 | + } |
| 140 | + |
| 141 | + private async _nodeJSLoadScript(scriptSrc: string): Promise<DefineCall | undefined> { |
| 142 | + try { |
| 143 | + const fs = <typeof import('fs')>globalThis._VSCODE_NODE_MODULES['fs']; |
| 144 | + const vm = <typeof import('vm')>globalThis._VSCODE_NODE_MODULES['vm']; |
| 145 | + const module = <typeof import('module')>globalThis._VSCODE_NODE_MODULES['module']; |
| 146 | + |
| 147 | + const filePath = URI.parse(scriptSrc).fsPath; |
| 148 | + const content = fs.readFileSync(filePath).toString(); |
| 149 | + const scriptSource = module.wrap(content.replace(/^#!.*/, '')); |
| 150 | + const script = new vm.Script(scriptSource); |
| 151 | + const compileWrapper = script.runInThisContext(); |
| 152 | + compileWrapper.apply(); |
| 153 | + return this._defineCalls.pop(); |
| 154 | + |
| 155 | + } catch (error) { |
| 156 | + throw error; |
| 157 | + } |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +const cache = new Map<string, Promise<any>>(); |
| 162 | + |
| 163 | +let _paths: Record<string, string> = {}; |
| 164 | +if (typeof globalThis.require === 'object') { |
| 165 | + _paths = (<Record<string, any>>globalThis.require).paths ?? {}; |
| 166 | +} |
| 167 | + |
| 168 | +/** |
| 169 | + * e.g. pass in `vscode-textmate/release/main.js` |
| 170 | + */ |
| 171 | +export async function importAMDNodeModule<T>(nodeModuleName: string, pathInsideNodeModule: string, isBuilt?: boolean): Promise<T> { |
| 172 | + if (isESM) { |
| 173 | + |
| 174 | + if (isBuilt === undefined) { |
| 175 | + const product = globalThis._VSCODE_PRODUCT_JSON as unknown as IProductConfiguration; |
| 176 | + isBuilt = !!product?.commit; |
| 177 | + } |
| 178 | + |
| 179 | + if (_paths[nodeModuleName]) { |
| 180 | + nodeModuleName = _paths[nodeModuleName]; |
| 181 | + } |
| 182 | + |
| 183 | + const nodeModulePath = `${nodeModuleName}/${pathInsideNodeModule}`; |
| 184 | + if (cache.has(nodeModulePath)) { |
| 185 | + return cache.get(nodeModulePath)!; |
| 186 | + } |
| 187 | + let scriptSrc: string; |
| 188 | + if (/^\w[\w\d+.-]*:\/\//.test(nodeModulePath)) { |
| 189 | + // looks like a URL |
| 190 | + // bit of a special case for: src/vs/workbench/services/languageDetection/browser/languageDetectionSimpleWorker.ts |
| 191 | + scriptSrc = nodeModulePath; |
| 192 | + } else { |
| 193 | + const useASAR = (isBuilt && !platform.isWeb); |
| 194 | + const actualNodeModulesPath = (useASAR ? nodeModulesAsarPath : nodeModulesPath); |
| 195 | + const resourcePath: AppResourcePath = `${actualNodeModulesPath}/${nodeModulePath}`; |
| 196 | + scriptSrc = FileAccess.asBrowserUri(resourcePath).toString(true); |
| 197 | + } |
| 198 | + const result = AMDModuleImporter.INSTANCE.load<T>(scriptSrc); |
| 199 | + cache.set(nodeModulePath, result); |
| 200 | + return result; |
| 201 | + } else { |
| 202 | + return await import(nodeModuleName); |
| 203 | + } |
| 204 | +} |
0 commit comments