src/vs/amdX.ts

245 LOC · 151 covered · 94 uncovered · 27 ranges · 1976 concepts · 3 introducers · 932 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 > /*--------------------------------------------------------------------------------------------- amdX.ts ×8
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 { AppResourcePath, FileAccess, nodeModulesAsarPath, nodeModulesPath, Schemas, VSCODE_AUTHORITY } from './base/common/network.js';
7 > import * as platform from './base/common/platform.js';
8 > import { IProductConfiguration } from './base/common/product.js';
9 > import { URI } from './base/common/uri.js';
10 > import { generateUuid } from './base/common/uuid.js';
11 >
12 > declare const window: any;
13 > declare const document: any;
14 > declare const self: any;
15 > declare const globalThis: any;
16 >
17 > class DefineCall {
18 > constructor(
19 > public readonly id: string | null | undefined, amdX.ts ×18
20 > public readonly dependencies: string[] | null | undefined,
21 > public readonly callback: any
22 > ) { }
23 > } amdX.ts ×8
24 >
25 > enum AMDModuleImporterState {
26 > Uninitialized = 1,
27 > InitializedInternal,
28 > InitializedExternal
29 > }
30 >
31 > class AMDModuleImporter {
32 > public static INSTANCE = new AMDModuleImporter();
33 >
34 > private readonly _isWebWorker = (typeof self === 'object' && self.constructor && self.constructor.name === 'DedicatedWorkerGlobalScope');
35 > private readonly _isRenderer = typeof document === 'object';
36 >
37 > private readonly _defineCalls: DefineCall[] = [];
38 > private _state = AMDModuleImporterState.Uninitialized;
39 > private _amdPolicy: Pick<TrustedTypePolicy, 'name' | 'createScriptURL'> | undefined;
40 >
41 > constructor() { }
42 >
43 > private _initialize(): void {
44 > if (this._state === AMDModuleImporterState.Uninitialized) { amdX.ts ×18
45 > if (globalThis.define) {
46 this._state = AMDModuleImporterState.InitializedExternal;
47 return;
48 }
49 > } else { amdX.ts ×18
50 return;
51 }
53 > this._state = AMDModuleImporterState.InitializedInternal;
54 >
55 > globalThis.define = (id: any, dependencies: any, callback: any) => {
56 > if (typeof id !== 'string') {
57 > callback = dependencies;
58 > dependencies = id;
59 > id = null;
60 > }
61 > if (typeof dependencies !== 'object' || !Array.isArray(dependencies)) {
62 callback = dependencies;
63 dependencies = null;
64 }
65 > // if (!dependencies) { amdX.ts ×18
66 > // dependencies = ['require', 'exports', 'module'];
67 > // }
68 > this._defineCalls.push(new DefineCall(id, dependencies, callback));
69 > };
70 >
71 > globalThis.define.amd = true;
72 >
73 > if (this._isRenderer) {
74 this._amdPolicy = globalThis._VSCODE_WEB_PACKAGE_TTP ?? window.trustedTypes?.createPolicy('amdLoader', {
75 createScriptURL(value: any) {
76 if (value.startsWith(window.location.origin)) {
77 return value;
78 }
79 if (value.startsWith(`${Schemas.vscodeFileResource}://${VSCODE_AUTHORITY}`)) {
80 return value;
81 }
82 throw new Error(`[trusted_script_src] Invalid script url: ${value}`);
83 }
84 });
85 > } else if (this._isWebWorker) { amdX.ts ×18
86 this._amdPolicy = globalThis._VSCODE_WEB_PACKAGE_TTP ?? globalThis.trustedTypes?.createPolicy('amdLoader', {
87 createScriptURL(value: string) {
88 return value;
89 }
90 });
91 }
92 > } amdX.ts ×18
94 > public async load<T>(scriptSrc: string): Promise<T> {
95 > this._initialize(); amdX.ts ×18
96 >
97 > if (this._state === AMDModuleImporterState.InitializedExternal) {
98 return new Promise<T>(resolve => {
99 const tmpModuleId = generateUuid();
100 globalThis.define(tmpModuleId, [scriptSrc], function (moduleResult: T) {
101 resolve(moduleResult);
102 });
103 });
104 }
105 > amdX.ts ×18
106 > const defineCall = await (this._isWebWorker ? this._workerLoadScript(scriptSrc) : this._isRenderer ? this._rendererLoadScript(scriptSrc) : this._nodeJSLoadScript(scriptSrc));
107 > if (!defineCall) {
108 console.warn(`Did not receive a define call from script ${scriptSrc}`);
109 return <T>undefined;
110 }
111 > // TODO@esm require, module amdX.ts ×18
112 > const exports = {};
113 > const dependencyObjs: any[] = [];
114 > const dependencyModules: string[] = [];
115 >
116 > if (Array.isArray(defineCall.dependencies)) {
117 >
118 > for (const mod of defineCall.dependencies) {
119 if (mod === 'exports') {
120 dependencyObjs.push(exports);
121 } else {
122 dependencyModules.push(mod);
123 }
124 }
125 > } amdX.ts ×18
126 >
127 > if (dependencyModules.length > 0) {
128 throw new Error(`Cannot resolve dependencies for script ${scriptSrc}. The dependencies are: ${dependencyModules.join(', ')}`);
129 }
130 > if (typeof defineCall.callback === 'function') { amdX.ts ×18
131 > return defineCall.callback(...dependencyObjs) ?? exports;
132 > } else {
133 return defineCall.callback;
134 }
135 > } amdX.ts ×18
136 > amdX.ts ×8
137 > private _rendererLoadScript(scriptSrc: string): Promise<DefineCall | undefined> {
138 return new Promise<DefineCall | undefined>((resolve, reject) => {
139 const scriptElement = document.createElement('script');
140 scriptElement.setAttribute('async', 'async');
141 scriptElement.setAttribute('type', 'text/javascript');
142
143 const unbind = () => {
144 scriptElement.removeEventListener('load', loadEventListener);
145 scriptElement.removeEventListener('error', errorEventListener);
146 };
147
148 const loadEventListener = (e: any) => {
149 unbind();
150 resolve(this._defineCalls.pop());
151 };
152
153 const errorEventListener = (e: any) => {
154 unbind();
155 reject(e);
156 };
157
158 scriptElement.addEventListener('load', loadEventListener);
159 scriptElement.addEventListener('error', errorEventListener);
160 if (this._amdPolicy) {
161 scriptSrc = this._amdPolicy.createScriptURL(scriptSrc) as unknown as string;
162 }
163 scriptElement.setAttribute('src', scriptSrc);
164 window.document.getElementsByTagName('head')[0].appendChild(scriptElement);
165 });
166 }
167 > amdX.ts ×8
168 > private async _workerLoadScript(scriptSrc: string): Promise<DefineCall | undefined> {
169 if (this._amdPolicy) {
170 scriptSrc = this._amdPolicy.createScriptURL(scriptSrc) as unknown as string;
171 }
172 await import(/* webpackIgnore: true */ /* @vite-ignore */ scriptSrc);
173 return this._defineCalls.pop();
174 }
175 > amdX.ts ×8
176 > private async _nodeJSLoadScript(scriptSrc: string): Promise<DefineCall | undefined> {
177 > try { amdX.ts ×18
178 > // `import('module')` is not remapped (only `fs` is), so it yields the real
179 > // `module` builtin. We use its `createRequire` to obtain `fs`/`vm`: the ESM
180 > // resolution hook maps `import('fs')` to the ASAR-unaware `original-fs`, but
181 > // `scriptSrc` may point inside the `node_modules.asar` archive. The `fs`
182 > // returned by `require` stays ASAR-aware in Electron, so it can read module
183 > // files from within the archive.
184 > const module = (await import(/* webpackIgnore: true */ /* @vite-ignore */ `${'module'}`)).default;
185 > const nodeRequire = module.createRequire(import.meta.url);
186 > const fs = nodeRequire('fs');
187 > const vm = nodeRequire('vm');
188 >
189 > const filePath = URI.parse(scriptSrc).fsPath;
190 > const content = fs.readFileSync(filePath).toString();
191 > const scriptSource = module.wrap(content.replace(/^#!.*/, ''));
192 > const script = new vm.Script(scriptSource);
193 > const compileWrapper = script.runInThisContext();
194 > compileWrapper.apply();
195 > return this._defineCalls.pop();
196 > } catch (error) {
197 throw error;
198 }
199 > } amdX.ts ×18
200 > } amdX.ts ×8
201 >
202 > const cache = new Map<string, Promise<any>>();
203 >
204 > /**
205 > * Utility for importing an AMD node module. This util supports AMD and ESM contexts and should be used while the ESM adoption
206 > * is on its way.
207 > *
208 > * e.g. pass in `vscode-textmate/release/main.js`
209 > */
210 > export async function importAMDNodeModule<T>(nodeModuleName: string, pathInsideNodeModule: string, isBuilt?: boolean): Promise<T> { amdX.ts ×18
211 > if (isBuilt === undefined) {
212 > const product = globalThis._VSCODE_PRODUCT_JSON as unknown as IProductConfiguration;
213 > isBuilt = Boolean((product ?? globalThis.vscode?.context?.configuration()?.product)?.commit);
214 > }
215 >
216 > const nodeModulePath = pathInsideNodeModule ? `${nodeModuleName}/${pathInsideNodeModule}` : nodeModuleName;
217 > if (cache.has(nodeModulePath)) {
218 > return cache.get(nodeModulePath)!; amdX.ts ×1
219 > }
220 > let scriptSrc: string; amdX.ts ×18
221 > if (/^\w[\w\d+.-]*:\/\//.test(nodeModulePath)) {
222 // looks like a URL
223 // bit of a special case for: src/vs/workbench/services/languageDetection/browser/languageDetectionWebWorker.ts
224 scriptSrc = nodeModulePath;
225 > } else { amdX.ts ×18
226 > const useASAR = (isBuilt && (platform.isElectron || (platform.isWebWorker && platform.hasElectronUserAgent)));
227 > const actualNodeModulesPath = (useASAR ? nodeModulesAsarPath : nodeModulesPath);
228 > const resourcePath: AppResourcePath = `${actualNodeModulesPath}/${nodeModulePath}`;
229 > scriptSrc = FileAccess.asBrowserUri(resourcePath).toString(true);
230 > }
231 > const result = AMDModuleImporter.INSTANCE.load<T>(scriptSrc);
232 > cache.set(nodeModulePath, result);
233 > return result;
234 > }
235 > amdX.ts ×8
236 > export function resolveAmdNodeModulePath(nodeModuleName: string, pathInsideNodeModule: string): string {
237 const product = globalThis._VSCODE_PRODUCT_JSON as unknown as IProductConfiguration;
238 const isBuilt = Boolean((product ?? globalThis.vscode?.context?.configuration()?.product)?.commit);
239 const useASAR = (isBuilt && (platform.isElectron || (platform.isWebWorker && platform.hasElectronUserAgent)));
240
241 const nodeModulePath = `${nodeModuleName}/${pathInsideNodeModule}`;
242 const actualNodeModulesPath = (useASAR ? nodeModulesAsarPath : nodeModulesPath);
243 const resourcePath: AppResourcePath = `${actualNodeModulesPath}/${nodeModulePath}`;
244 return FileAccess.asBrowserUri(resourcePath).toString(true);
245 }