@oseo/compiler 0.0.0-stage → 0.1.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +172 -2
  3. package/dist/agent-programs.d.ts +28 -0
  4. package/dist/agent-programs.d.ts.map +1 -0
  5. package/dist/agent-programs.js +134 -0
  6. package/dist/agent-programs.js.map +1 -0
  7. package/dist/agent-templates.d.ts +33 -0
  8. package/dist/agent-templates.d.ts.map +1 -0
  9. package/dist/agent-templates.js +45 -0
  10. package/dist/agent-templates.js.map +1 -0
  11. package/dist/compile.d.ts +20 -0
  12. package/dist/compile.d.ts.map +1 -0
  13. package/dist/compile.js +75 -0
  14. package/dist/compile.js.map +1 -0
  15. package/dist/fragments.d.ts +72 -0
  16. package/dist/fragments.d.ts.map +1 -0
  17. package/dist/fragments.js +158 -0
  18. package/dist/fragments.js.map +1 -0
  19. package/dist/hir-build.d.ts +80 -0
  20. package/dist/hir-build.d.ts.map +1 -0
  21. package/dist/hir-build.js +3077 -0
  22. package/dist/hir-build.js.map +1 -0
  23. package/dist/hir-print.d.ts +10 -0
  24. package/dist/hir-print.d.ts.map +1 -0
  25. package/dist/hir-print.js +271 -0
  26. package/dist/hir-print.js.map +1 -0
  27. package/dist/hir.d.ts +1246 -0
  28. package/dist/hir.d.ts.map +1 -0
  29. package/dist/hir.js +147 -0
  30. package/dist/hir.js.map +1 -0
  31. package/dist/host-scripts.d.ts +14 -0
  32. package/dist/host-scripts.d.ts.map +1 -0
  33. package/dist/host-scripts.js +204 -0
  34. package/dist/host-scripts.js.map +1 -0
  35. package/dist/index.d.ts +26 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +27 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/mir-build.d.ts +8 -0
  40. package/dist/mir-build.d.ts.map +1 -0
  41. package/dist/mir-build.js +5113 -0
  42. package/dist/mir-build.js.map +1 -0
  43. package/dist/mir-print.d.ts +7 -0
  44. package/dist/mir-print.d.ts.map +1 -0
  45. package/dist/mir-print.js +65 -0
  46. package/dist/mir-print.js.map +1 -0
  47. package/dist/mir-specialize.d.ts +7 -0
  48. package/dist/mir-specialize.d.ts.map +1 -0
  49. package/dist/mir-specialize.js +182 -0
  50. package/dist/mir-specialize.js.map +1 -0
  51. package/dist/mir.d.ts +571 -0
  52. package/dist/mir.d.ts.map +1 -0
  53. package/dist/mir.js +1 -0
  54. package/dist/module-builtin.d.ts +20 -0
  55. package/dist/module-builtin.d.ts.map +1 -0
  56. package/dist/module-builtin.js +57 -0
  57. package/dist/module-builtin.js.map +1 -0
  58. package/dist/module-compile.d.ts +64 -0
  59. package/dist/module-compile.d.ts.map +1 -0
  60. package/dist/module-compile.js +690 -0
  61. package/dist/module-compile.js.map +1 -0
  62. package/dist/module-json.d.ts +7 -0
  63. package/dist/module-json.d.ts.map +1 -0
  64. package/dist/module-json.js +88 -0
  65. package/dist/module-json.js.map +1 -0
  66. package/dist/modules.d.ts +87 -0
  67. package/dist/modules.d.ts.map +1 -0
  68. package/dist/modules.js +734 -0
  69. package/dist/modules.js.map +1 -0
  70. package/dist/native-fragments.d.ts +36 -0
  71. package/dist/native-fragments.d.ts.map +1 -0
  72. package/dist/native-fragments.js +110 -0
  73. package/dist/native-fragments.js.map +1 -0
  74. package/dist/native.d.ts +282 -0
  75. package/dist/native.d.ts.map +1 -0
  76. package/dist/native.js +47 -0
  77. package/dist/native.js.map +1 -0
  78. package/dist/regexp-execute.d.ts +74 -0
  79. package/dist/regexp-execute.d.ts.map +1 -0
  80. package/dist/regexp-execute.js +480 -0
  81. package/dist/regexp-execute.js.map +1 -0
  82. package/dist/regexp-matcher.d.ts +279 -0
  83. package/dist/regexp-matcher.d.ts.map +1 -0
  84. package/dist/regexp-matcher.js +1098 -0
  85. package/dist/regexp-matcher.js.map +1 -0
  86. package/dist/regexp-parse.d.ts +22 -0
  87. package/dist/regexp-parse.d.ts.map +1 -0
  88. package/dist/regexp-parse.js +1440 -0
  89. package/dist/regexp-parse.js.map +1 -0
  90. package/dist/regexp-print.d.ts +24 -0
  91. package/dist/regexp-print.d.ts.map +1 -0
  92. package/dist/regexp-print.js +147 -0
  93. package/dist/regexp-print.js.map +1 -0
  94. package/dist/regexp.d.ts +324 -0
  95. package/dist/regexp.d.ts.map +1 -0
  96. package/dist/regexp.js +22 -0
  97. package/dist/regexp.js.map +1 -0
  98. package/dist/source.d.ts +38 -0
  99. package/dist/source.d.ts.map +1 -0
  100. package/dist/source.js +10 -0
  101. package/dist/source.js.map +1 -0
  102. package/dist/syntax.d.ts +1232 -0
  103. package/dist/syntax.d.ts.map +1 -0
  104. package/dist/syntax.js +1 -0
  105. package/package.json +32 -3
@@ -0,0 +1,734 @@
1
+ import { moduleNodeSyntax } from "./module-builtin.js";
2
+ import { jsonModuleSyntax } from "./module-json.js";
3
+
4
+ //#region src/modules.ts
5
+ function includePropertiesWhen(properties) {
6
+ return properties() ?? {};
7
+ }
8
+ /** Retain each syntactic request once without merging distinct source sites. */
9
+ function moduleSpecifiers(module) {
10
+ const specifiers = [];
11
+ for (const entry of module.imports) specifiers.push(entry.specifier);
12
+ for (const entry of module.exports) if (entry.kind === "indirect" || entry.kind === "namespace" || entry.kind === "star") specifiers.push(entry.specifier);
13
+ const requests = /* @__PURE__ */ new Set();
14
+ return specifiers.toSorted((left, right) => left.byteRange.start - right.byteRange.start).filter((specifier) => {
15
+ const key = `${specifier.byteRange.start}:${specifier.byteRange.end}:` + specifier.value;
16
+ if (requests.has(key)) return false;
17
+ requests.add(key);
18
+ return true;
19
+ });
20
+ }
21
+ function requestSites(module, importCalls) {
22
+ const sites = [];
23
+ if (module != null) for (const specifier of moduleSpecifiers(module)) sites.push({
24
+ edgeKind: "evaluation",
25
+ location: specifier,
26
+ specifier
27
+ });
28
+ for (const call of importCalls ?? []) sites.push({
29
+ edgeKind: "discovery",
30
+ location: {
31
+ byteRange: call.byteRange ?? call.specifier.byteRange,
32
+ range: call.range
33
+ },
34
+ specifier: call.specifier
35
+ });
36
+ return sites.toSorted((left, right) => left.location.byteRange.start - right.location.byteRange.start);
37
+ }
38
+ /** A Script and a module may share an identity, so the key keeps both. */
39
+ function referrerKey(referrer) {
40
+ return `${referrer.kind}:${referrer.id}`;
41
+ }
42
+ function positionText(sourceId, location) {
43
+ const start = location.range.start;
44
+ return `${sourceId}:${start.line}:${start.column}`;
45
+ }
46
+ /**
47
+ * The importer chain of a module as diagnostic notes, nearest request
48
+ * first. The chain is reported only when it, or the failing request,
49
+ * crosses a discovery edge, so a static-only graph keeps the diagnostics
50
+ * it reported before `import()` discovery existed.
51
+ */
52
+ function importerChainNotes(origins, referrer, failing) {
53
+ const notes = [];
54
+ let crossesDiscovery = failing === "discovery";
55
+ const seen = /* @__PURE__ */ new Set();
56
+ let origin = referrer.kind === "module" ? origins.get(referrer.id) : void 0;
57
+ while (origin != null && !seen.has(referrerKey(origin.referrer))) {
58
+ seen.add(referrerKey(origin.referrer));
59
+ if (origin.edgeKind === "discovery") crossesDiscovery = true;
60
+ const where = positionText(origin.referrer.id, origin.location);
61
+ const script = origin.referrer.kind === "script" ? " (Script)" : "";
62
+ notes.push(origin.edgeKind === "discovery" ? `requested by import() at ${where}${script}` : `imported by a static request at ${where}${script}`);
63
+ origin = origin.referrer.kind === "module" ? origins.get(origin.referrer.id) : void 0;
64
+ }
65
+ return crossesDiscovery && notes.length > 0 ? notes : void 0;
66
+ }
67
+ function withNotes(diagnostic, notes) {
68
+ return notes == null ? diagnostic : {
69
+ ...diagnostic,
70
+ notes: [...diagnostic.notes ?? [], ...notes]
71
+ };
72
+ }
73
+ /** The origin of each module, recovered from a discovered graph. */
74
+ function graphOrigins(graph) {
75
+ const origins = /* @__PURE__ */ new Map();
76
+ const requests = graph.requests ?? [];
77
+ for (const module of graph.modules) {
78
+ const request = module.discoveredBy == null ? void 0 : requests[module.discoveredBy];
79
+ if (request == null) continue;
80
+ origins.set(module.canonicalId, {
81
+ edgeKind: request.edgeKind,
82
+ location: request,
83
+ referrer: request.referrer
84
+ });
85
+ }
86
+ return origins;
87
+ }
88
+ /**
89
+ * Add the importer chain of each referrer to the diagnostic located in
90
+ * it, when that chain crosses an `import()` edge. Other diagnostics are
91
+ * returned unchanged.
92
+ */
93
+ function withReferrerChains(graph, located) {
94
+ if (!(graph.requests ?? []).some((request) => request.edgeKind === "discovery")) return located.map(({ diagnostic }) => diagnostic);
95
+ const origins = graphOrigins(graph);
96
+ return located.map(({ diagnostic, referrer }) => withNotes(diagnostic, importerChainNotes(origins, referrer)));
97
+ }
98
+ /** {@link withReferrerChains} for diagnostics located in modules. */
99
+ function withImporterChains(graph, diagnostics) {
100
+ return withReferrerChains(graph, diagnostics.map((diagnostic) => ({
101
+ diagnostic,
102
+ referrer: {
103
+ id: diagnostic.sourceId,
104
+ kind: "module"
105
+ }
106
+ })));
107
+ }
108
+ /**
109
+ * Discover, load, and parse every module the entry's static closure and
110
+ * the literal `import()` requests reach, without evaluating anything.
111
+ *
112
+ * The entry's static closure is visited first, depth first in source
113
+ * order, exactly as a graph without `import()` is. Script referrers'
114
+ * requests and every `import()` request found along the way join one
115
+ * first-in, first-out queue, and each dequeued target contributes its own
116
+ * static closure the same way. A module is parsed once however many
117
+ * requests reach it.
118
+ */
119
+ function pendingRequest(referrer, site) {
120
+ return {
121
+ origin: {
122
+ edgeKind: site.edgeKind,
123
+ location: site.location,
124
+ referrer
125
+ },
126
+ site
127
+ };
128
+ }
129
+ async function discoverModules(frontend, loader, resolver, entryId, scripts) {
130
+ const diagnostics = [];
131
+ const modules = [];
132
+ const discovered = /* @__PURE__ */ new Set();
133
+ const loadedSources = /* @__PURE__ */ new Map();
134
+ const origins = /* @__PURE__ */ new Map();
135
+ const originSites = /* @__PURE__ */ new Map();
136
+ const moduleSites = /* @__PURE__ */ new Map();
137
+ const queue = [];
138
+ /** Resolve a referrer's sites in source order, reporting failures. */
139
+ const resolveSites = (referrer, sites) => {
140
+ const resolved = [];
141
+ for (const site of sites) {
142
+ const notes = importerChainNotes(origins, referrer, site.edgeKind);
143
+ const unsupportedAttribute = site.specifier.attributes?.find((attribute) => attribute.key !== "type" || attribute.value !== "json");
144
+ if (unsupportedAttribute != null) {
145
+ diagnostics.push(withNotes(linkDiagnostic(referrer.id, unsupportedAttribute, "Unsupported static import attribute."), notes));
146
+ continue;
147
+ }
148
+ const result = resolver.resolve(referrer.id, site.specifier);
149
+ diagnostics.push(...result.diagnostics.map((diagnostic) => withNotes(diagnostic, notes)));
150
+ if (result.canonicalId == null || result.diagnostics.length > 0) continue;
151
+ resolved.push({
152
+ ...site,
153
+ canonicalId: result.canonicalId
154
+ });
155
+ }
156
+ return resolved;
157
+ };
158
+ const visit = async (canonicalId, request) => {
159
+ const referrer = request == null ? void 0 : {
160
+ importerId: request.origin.referrer.id,
161
+ specifier: request.site.specifier
162
+ };
163
+ const failingNotes = request == null ? void 0 : importerChainNotes(origins, request.origin.referrer, request.origin.edgeKind);
164
+ let loaded = loadedSources.get(canonicalId);
165
+ if (loaded == null) {
166
+ loaded = await loader.load(canonicalId, referrer);
167
+ loadedSources.set(canonicalId, loaded);
168
+ diagnostics.push(...loaded.diagnostics.map((diagnostic) => withNotes(diagnostic, failingNotes)));
169
+ }
170
+ if (loaded.diagnostics.length > 0) return;
171
+ if (loaded.builtin != null) {
172
+ if (canonicalId !== loaded.builtin.specifier) {
173
+ diagnostics.push(linkDiagnostic(canonicalId, { range: {
174
+ start: {
175
+ line: 1,
176
+ column: 1
177
+ },
178
+ end: {
179
+ line: 1,
180
+ column: 1
181
+ }
182
+ } }, "A builtin module must use its canonical specifier identity."));
183
+ return;
184
+ }
185
+ if (referrer?.specifier.attributes?.length) {
186
+ diagnostics.push(linkDiagnostic(referrer.importerId, referrer.specifier, "A builtin module does not accept import attributes."));
187
+ return;
188
+ }
189
+ if (discovered.has(canonicalId)) return;
190
+ discovered.add(canonicalId);
191
+ if (request != null) {
192
+ origins.set(canonicalId, request.origin);
193
+ originSites.set(canonicalId, request.site);
194
+ }
195
+ modules.push({
196
+ canonicalId,
197
+ moduleKind: "builtin",
198
+ builtin: loaded.builtin.specifier,
199
+ sourceHash: loaded.builtin.sourceHash,
200
+ dependencies: [],
201
+ resolutions: []
202
+ });
203
+ return;
204
+ }
205
+ if (loaded.source == null) return;
206
+ if (referrer == null && loaded.source.kind === "json") {
207
+ diagnostics.push(linkDiagnostic(canonicalId, { range: {
208
+ start: {
209
+ line: 1,
210
+ column: 1
211
+ },
212
+ end: {
213
+ line: 1,
214
+ column: 1
215
+ }
216
+ } }, "A JSON module cannot be the entry module."));
217
+ return;
218
+ }
219
+ if ((referrer?.specifier.attributes?.some((attribute) => attribute.key === "type" && attribute.value === "json") ?? false) !== (loaded.source.kind === "json")) {
220
+ diagnostics.push(withNotes(linkDiagnostic(referrer?.importerId ?? canonicalId, referrer?.specifier ?? { range: {
221
+ start: {
222
+ line: 1,
223
+ column: 1
224
+ },
225
+ end: {
226
+ line: 1,
227
+ column: 1
228
+ }
229
+ } }, "The module kind does not match its import attributes."), failingNotes));
230
+ return;
231
+ }
232
+ if (discovered.has(canonicalId)) return;
233
+ discovered.add(canonicalId);
234
+ if (request != null) {
235
+ origins.set(canonicalId, request.origin);
236
+ originSites.set(canonicalId, request.site);
237
+ }
238
+ const moduleNotes = importerChainNotes(origins, {
239
+ id: canonicalId,
240
+ kind: "module"
241
+ });
242
+ let parsed;
243
+ if (loaded.source.kind === "json") try {
244
+ parsed = {
245
+ diagnostics: [],
246
+ module: jsonModuleSyntax(loaded.source)
247
+ };
248
+ } catch (error) {
249
+ const diagnostic = withNotes(linkDiagnostic(referrer?.importerId ?? canonicalId, referrer?.specifier ?? { range: {
250
+ start: {
251
+ line: 1,
252
+ column: 1
253
+ },
254
+ end: {
255
+ line: 1,
256
+ column: 1
257
+ }
258
+ } }, error instanceof SyntaxError ? "Invalid JSON module source." : "JSON module construction exceeds compiler limits."), failingNotes);
259
+ diagnostics.push(error instanceof SyntaxError ? diagnostic : {
260
+ ...diagnostic,
261
+ code: "OSEO1001"
262
+ });
263
+ return;
264
+ }
265
+ else parsed = frontend.parseModule({
266
+ source: loaded.source.source,
267
+ sourceId: canonicalId
268
+ });
269
+ diagnostics.push(...parsed.diagnostics.map((diagnostic) => withNotes(diagnostic, moduleNotes)));
270
+ if (parsed.module == null || parsed.diagnostics.length > 0) return;
271
+ const moduleReferrer = {
272
+ id: canonicalId,
273
+ kind: "module"
274
+ };
275
+ const sites = resolveSites(moduleReferrer, requestSites(parsed.module, parsed.module.importCalls));
276
+ moduleSites.set(canonicalId, sites);
277
+ const dependencies = [];
278
+ const resolutions = [];
279
+ const dependencyIds = /* @__PURE__ */ new Set();
280
+ for (const site of sites) {
281
+ if (site.edgeKind !== "evaluation") continue;
282
+ resolutions.push({
283
+ canonicalId: site.canonicalId,
284
+ specifier: site.specifier
285
+ });
286
+ if (!dependencyIds.has(site.canonicalId)) {
287
+ dependencyIds.add(site.canonicalId);
288
+ dependencies.push({
289
+ canonicalId: site.canonicalId,
290
+ specifier: site.specifier
291
+ });
292
+ }
293
+ }
294
+ modules.push({
295
+ canonicalId,
296
+ dependencies,
297
+ resolutions,
298
+ sourceHash: loaded.source.sourceHash,
299
+ syntax: parsed.module,
300
+ moduleKind: loaded.source.kind ?? "javascript"
301
+ });
302
+ for (const site of sites) {
303
+ const pending = pendingRequest(moduleReferrer, site);
304
+ if (site.edgeKind === "discovery") {
305
+ queue.push(pending);
306
+ continue;
307
+ }
308
+ await visit(site.canonicalId, pending);
309
+ }
310
+ };
311
+ const scriptSites = scripts.map((script) => {
312
+ const referrer = {
313
+ id: script.canonicalId,
314
+ kind: "script"
315
+ };
316
+ return {
317
+ referrer,
318
+ sites: resolveSites(referrer, requestSites(void 0, script.program.importCalls))
319
+ };
320
+ });
321
+ if (entryId != null) await visit(entryId);
322
+ queue.unshift(...scriptSites.flatMap(({ referrer, sites }) => sites.map((site) => pendingRequest(referrer, site))));
323
+ for (let index = 0; index < queue.length; index += 1) {
324
+ const pending = queue[index];
325
+ await visit(pending.site.canonicalId, pending);
326
+ }
327
+ const requests = [];
328
+ const siteIndices = /* @__PURE__ */ new Map();
329
+ const record = (referrer, sites) => {
330
+ for (const site of sites) {
331
+ siteIndices.set(site, requests.length);
332
+ requests.push({
333
+ byteRange: site.location.byteRange,
334
+ edgeKind: site.edgeKind,
335
+ index: requests.length,
336
+ range: site.location.range,
337
+ referrer,
338
+ specifier: site.specifier,
339
+ targetId: site.canonicalId
340
+ });
341
+ }
342
+ };
343
+ for (const { referrer, sites } of scriptSites) record(referrer, sites);
344
+ for (const module of modules) record({
345
+ id: module.canonicalId,
346
+ kind: "module"
347
+ }, moduleSites.get(module.canonicalId) ?? []);
348
+ const discoveredModules = [];
349
+ for (const module of modules) {
350
+ const site = originSites.get(module.canonicalId);
351
+ const discoveredBy = site == null ? void 0 : siteIndices.get(site);
352
+ discoveredModules.push(discoveredBy == null ? module : {
353
+ ...module,
354
+ discoveredBy
355
+ });
356
+ }
357
+ return {
358
+ diagnostics,
359
+ modules: discoveredModules,
360
+ requests
361
+ };
362
+ }
363
+ /**
364
+ * Discover and parse one closed module graph without evaluating its modules.
365
+ *
366
+ * Literal `import()` sites, which a module frontend produces only when
367
+ * static-specifier imports are enabled, add discovery edges: their
368
+ * targets and those targets' closures join {@link ModuleGraph.modules},
369
+ * but never a module's `dependencies`. A target that cannot be resolved,
370
+ * loaded, or parsed fails discovery with its source location and its
371
+ * importer chain in the diagnostic notes.
372
+ */
373
+ async function buildModuleGraph(frontend, loader, resolver, entryId, options = {}) {
374
+ const result = await discoverModules(frontend, loader, resolver, entryId, options.scripts ?? []);
375
+ return result.diagnostics.length > 0 ? { diagnostics: result.diagnostics } : {
376
+ diagnostics: result.diagnostics,
377
+ graph: {
378
+ entryId,
379
+ kind: "module-graph",
380
+ modules: result.modules,
381
+ requests: result.requests
382
+ }
383
+ };
384
+ }
385
+ /**
386
+ * Discover the modules that Script referrers reach through `import()`,
387
+ * for a Script program with no module entry. Each Script resolves its
388
+ * requests against its own canonical identity, and a module with the same
389
+ * identity is a separate record.
390
+ */
391
+ async function buildScriptRequests(frontend, loader, resolver, scripts) {
392
+ const result = await discoverModules(frontend, loader, resolver, void 0, scripts);
393
+ return result.diagnostics.length > 0 ? { diagnostics: result.diagnostics } : {
394
+ closure: {
395
+ kind: "script-request-closure",
396
+ modules: result.modules,
397
+ requests: result.requests
398
+ },
399
+ diagnostics: result.diagnostics
400
+ };
401
+ }
402
+ function linkDiagnostic(sourceId, locationValue, message) {
403
+ return {
404
+ byteRange: locationValue.byteRange ?? {
405
+ end: 0,
406
+ start: 0
407
+ },
408
+ code: "OSEO2001",
409
+ message,
410
+ range: locationValue.range,
411
+ sourceId
412
+ };
413
+ }
414
+ function resolvedModuleId(module, specifier) {
415
+ return module.resolutions.find((resolution) => resolution.specifier === specifier || resolution.specifier.value === specifier.value && resolution.specifier.byteRange.start === specifier.byteRange.start && resolution.specifier.byteRange.end === specifier.byteRange.end)?.canonicalId;
416
+ }
417
+ function importedBinding(module, localName) {
418
+ return moduleNodeSyntax(module).imports.find((entry) => entry.localName === localName && entry.importedName != null);
419
+ }
420
+ function sameExport(left, right) {
421
+ return left.cellId === right.cellId;
422
+ }
423
+ function compareCodeUnits(left, right) {
424
+ return left < right ? -1 : left > right ? 1 : 0;
425
+ }
426
+ function moduleDepthFirstOrder(graph) {
427
+ const nodes = new Map(graph.modules.map((module) => [module.canonicalId, module]));
428
+ const visited = /* @__PURE__ */ new Set();
429
+ const order = [];
430
+ const visit = (rootId) => {
431
+ if (visited.has(rootId)) return;
432
+ visited.add(rootId);
433
+ const frames = [{
434
+ dependencyIndex: 0,
435
+ moduleId: rootId
436
+ }];
437
+ while (frames.length > 0) {
438
+ const frame = frames.at(-1);
439
+ const dependency = (nodes.get(frame.moduleId)?.dependencies ?? [])[frame.dependencyIndex];
440
+ if (dependency != null) {
441
+ frame.dependencyIndex += 1;
442
+ if (visited.has(dependency.canonicalId)) continue;
443
+ visited.add(dependency.canonicalId);
444
+ frames.push({
445
+ dependencyIndex: 0,
446
+ moduleId: dependency.canonicalId
447
+ });
448
+ continue;
449
+ }
450
+ order.push(frame.moduleId);
451
+ frames.pop();
452
+ }
453
+ };
454
+ if (nodes.has(graph.entryId)) visit(graph.entryId);
455
+ if (graph.requests != null) return order;
456
+ for (const moduleId of [...nodes.keys()].toSorted(compareCodeUnits)) visit(moduleId);
457
+ return order;
458
+ }
459
+ function moduleComponents(graph) {
460
+ const nodes = new Map(graph.modules.map((module) => [module.canonicalId, module]));
461
+ const indices = /* @__PURE__ */ new Map();
462
+ const lowLinks = /* @__PURE__ */ new Map();
463
+ const stack = [];
464
+ const stacked = /* @__PURE__ */ new Set();
465
+ const found = [];
466
+ let nextIndex = 0;
467
+ const begin = (moduleId) => {
468
+ const index = nextIndex;
469
+ nextIndex += 1;
470
+ indices.set(moduleId, index);
471
+ lowLinks.set(moduleId, index);
472
+ stack.push(moduleId);
473
+ stacked.add(moduleId);
474
+ };
475
+ const strongConnect = (root) => {
476
+ begin(root);
477
+ const frames = [{
478
+ dependencyIndex: 0,
479
+ moduleId: root
480
+ }];
481
+ while (frames.length > 0) {
482
+ const frame = frames.at(-1);
483
+ const index = indices.get(frame.moduleId);
484
+ const dependency = (nodes.get(frame.moduleId)?.dependencies ?? [])[frame.dependencyIndex];
485
+ if (dependency != null) {
486
+ frame.dependencyIndex += 1;
487
+ if (!indices.has(dependency.canonicalId)) {
488
+ begin(dependency.canonicalId);
489
+ frames.push({
490
+ dependencyIndex: 0,
491
+ moduleId: dependency.canonicalId
492
+ });
493
+ } else if (stacked.has(dependency.canonicalId)) lowLinks.set(frame.moduleId, Math.min(lowLinks.get(frame.moduleId) ?? index, indices.get(dependency.canonicalId) ?? index));
494
+ continue;
495
+ }
496
+ if (lowLinks.get(frame.moduleId) === index) {
497
+ const component = [];
498
+ for (;;) {
499
+ const member = stack.pop();
500
+ if (member == null) throw new Error("Module component stack underflow.");
501
+ stacked.delete(member);
502
+ component.push(member);
503
+ if (member === frame.moduleId) break;
504
+ }
505
+ found.push(component);
506
+ }
507
+ frames.pop();
508
+ const parent = frames.at(-1);
509
+ if (parent != null) lowLinks.set(parent.moduleId, Math.min(lowLinks.get(parent.moduleId) ?? index, lowLinks.get(frame.moduleId) ?? index));
510
+ }
511
+ };
512
+ const roots = [graph.entryId, ...graph.modules.map((module) => module.canonicalId)];
513
+ for (const root of roots) {
514
+ if (indices.has(root)) continue;
515
+ strongConnect(root);
516
+ }
517
+ const evaluationOrder = moduleDepthFirstOrder(graph);
518
+ const evaluationIndex = new Map(evaluationOrder.map((moduleId, index) => [moduleId, index]));
519
+ return found.map((moduleIds) => moduleIds.toSorted((left, right) => (evaluationIndex.get(left) ?? Number.MAX_SAFE_INTEGER) - (evaluationIndex.get(right) ?? Number.MAX_SAFE_INTEGER))).toSorted((left, right) => (evaluationIndex.get(left[0] ?? "") ?? Number.MAX_SAFE_INTEGER) - (evaluationIndex.get(right[0] ?? "") ?? Number.MAX_SAFE_INTEGER)).map((moduleIds, id) => {
520
+ const first = nodes.get(moduleIds[0] ?? "");
521
+ const selfCycle = first?.dependencies.some((dependency) => dependency.canonicalId === first.canonicalId);
522
+ return {
523
+ cyclic: moduleIds.length > 1 || selfCycle === true,
524
+ id,
525
+ moduleIds
526
+ };
527
+ });
528
+ }
529
+ /** Resolve live imports, exports, namespace keys, and cyclic graph order. */
530
+ function linkModuleGraph(graph) {
531
+ const diagnostics = [];
532
+ const nodes = new Map(graph.modules.map((module) => [module.canonicalId, module]));
533
+ const cells = [];
534
+ const cellIds = /* @__PURE__ */ new Map();
535
+ const exportsByModule = /* @__PURE__ */ new Map();
536
+ const explicitNames = /* @__PURE__ */ new Map();
537
+ const ambiguousNames = /* @__PURE__ */ new Map();
538
+ const namespaceCells = /* @__PURE__ */ new Map();
539
+ const cellFor = (moduleId, localName) => {
540
+ const key = `${moduleId}\0${localName}`;
541
+ const existing = cellIds.get(key);
542
+ if (existing != null) return existing;
543
+ const id = cells.length;
544
+ cells.push({
545
+ id,
546
+ localName,
547
+ moduleId
548
+ });
549
+ cellIds.set(key, id);
550
+ return id;
551
+ };
552
+ const namespaceCellFor = (moduleId) => {
553
+ const existing = namespaceCells.get(moduleId);
554
+ if (existing != null) return existing;
555
+ const cellId = cellFor(moduleId, `*namespace:${moduleId}*`);
556
+ namespaceCells.set(moduleId, cellId);
557
+ return cellId;
558
+ };
559
+ for (const module of graph.modules) {
560
+ const moduleExports = /* @__PURE__ */ new Map();
561
+ const names = /* @__PURE__ */ new Set();
562
+ exportsByModule.set(module.canonicalId, moduleExports);
563
+ explicitNames.set(module.canonicalId, names);
564
+ ambiguousNames.set(module.canonicalId, /* @__PURE__ */ new Set());
565
+ for (const [index, entry] of moduleNodeSyntax(module).exports.entries()) {
566
+ if (entry.kind === "star") continue;
567
+ if (names.has(entry.exportedName)) {
568
+ diagnostics.push(linkDiagnostic(module.canonicalId, entry, `Duplicate export '${entry.exportedName}'.`));
569
+ continue;
570
+ }
571
+ names.add(entry.exportedName);
572
+ if (entry.kind === "local") {
573
+ if (importedBinding(module, entry.localName) == null) moduleExports.set(entry.exportedName, {
574
+ cellId: cellFor(module.canonicalId, entry.localName),
575
+ sourceModuleId: module.canonicalId
576
+ });
577
+ } else if (entry.kind === "default") moduleExports.set("default", {
578
+ cellId: cellFor(module.canonicalId, `*default:${index}*`),
579
+ sourceModuleId: module.canonicalId
580
+ });
581
+ else if (entry.kind === "namespace") {
582
+ const targetId = resolvedModuleId(module, entry.specifier);
583
+ if (targetId == null || !nodes.has(targetId)) {
584
+ diagnostics.push(linkDiagnostic(module.canonicalId, entry, `Module '${entry.specifier.value}' was not resolved.`));
585
+ continue;
586
+ }
587
+ moduleExports.set(entry.exportedName, {
588
+ cellId: namespaceCellFor(targetId),
589
+ sourceModuleId: targetId
590
+ });
591
+ }
592
+ }
593
+ }
594
+ let changed = true;
595
+ while (changed) {
596
+ changed = false;
597
+ for (const module of graph.modules) {
598
+ const moduleExports = exportsByModule.get(module.canonicalId);
599
+ const moduleAmbiguous = ambiguousNames.get(module.canonicalId);
600
+ const moduleExplicit = explicitNames.get(module.canonicalId);
601
+ if (moduleExports == null || moduleAmbiguous == null || moduleExplicit == null) throw new Error("Module link state is incomplete.");
602
+ for (const entry of moduleNodeSyntax(module).exports) {
603
+ if (entry.kind === "local") {
604
+ const imported = importedBinding(module, entry.localName);
605
+ if (imported == null) continue;
606
+ const targetId = resolvedModuleId(module, imported.specifier);
607
+ const candidate = targetId == null || imported.importedName == null ? void 0 : imported.namespace === true ? {
608
+ cellId: namespaceCellFor(targetId),
609
+ sourceModuleId: targetId
610
+ } : exportsByModule.get(targetId)?.get(imported.importedName);
611
+ const existing = moduleExports.get(entry.exportedName);
612
+ if (candidate != null && (existing == null || !sameExport(existing, candidate))) {
613
+ moduleExports.set(entry.exportedName, candidate);
614
+ changed = true;
615
+ }
616
+ continue;
617
+ }
618
+ if (entry.kind === "indirect") {
619
+ const targetId = resolvedModuleId(module, entry.specifier);
620
+ const candidate = targetId == null ? void 0 : exportsByModule.get(targetId)?.get(entry.importedName);
621
+ if (candidate != null && !moduleExports.has(entry.exportedName) && !moduleAmbiguous.has(entry.exportedName)) {
622
+ moduleExports.set(entry.exportedName, candidate);
623
+ changed = true;
624
+ }
625
+ continue;
626
+ }
627
+ if (entry.kind !== "star") continue;
628
+ const targetId = resolvedModuleId(module, entry.specifier);
629
+ if (targetId == null) continue;
630
+ const targetExports = exportsByModule.get(targetId);
631
+ const targetAmbiguous = ambiguousNames.get(targetId);
632
+ if (targetExports == null || targetAmbiguous == null) continue;
633
+ for (const name of targetAmbiguous) if (name !== "default" && !moduleExplicit.has(name)) {
634
+ if (!moduleAmbiguous.has(name)) changed = true;
635
+ moduleAmbiguous.add(name);
636
+ moduleExports.delete(name);
637
+ }
638
+ for (const [name, candidate] of targetExports) {
639
+ if (name === "default" || moduleExplicit.has(name) || moduleAmbiguous.has(name)) continue;
640
+ const existing = moduleExports.get(name);
641
+ if (existing == null) {
642
+ moduleExports.set(name, candidate);
643
+ changed = true;
644
+ } else if (!sameExport(existing, candidate)) {
645
+ moduleExports.delete(name);
646
+ moduleAmbiguous.add(name);
647
+ changed = true;
648
+ }
649
+ }
650
+ }
651
+ }
652
+ }
653
+ const linkedImports = /* @__PURE__ */ new Map();
654
+ for (const module of graph.modules) {
655
+ const imports = [];
656
+ linkedImports.set(module.canonicalId, imports);
657
+ for (const entry of moduleNodeSyntax(module).exports) {
658
+ if (entry.kind !== "indirect") continue;
659
+ const targetId = resolvedModuleId(module, entry.specifier);
660
+ const targetAmbiguous = targetId == null ? void 0 : ambiguousNames.get(targetId);
661
+ const candidate = targetId == null ? void 0 : exportsByModule.get(targetId)?.get(entry.importedName);
662
+ if (targetAmbiguous?.has(entry.importedName) === true) diagnostics.push(linkDiagnostic(module.canonicalId, entry, `Export '${entry.importedName}' is ambiguous.`));
663
+ else if (candidate == null) diagnostics.push(linkDiagnostic(module.canonicalId, entry, `Module has no export '${entry.importedName}'.`));
664
+ }
665
+ for (const entry of moduleNodeSyntax(module).imports) {
666
+ if (entry.localName == null || entry.importedName == null) continue;
667
+ const targetId = resolvedModuleId(module, entry.specifier);
668
+ if (targetId == null || !nodes.has(targetId)) {
669
+ diagnostics.push(linkDiagnostic(module.canonicalId, entry, `Module '${entry.specifier.value}' was not resolved.`));
670
+ continue;
671
+ }
672
+ if (entry.namespace === true) {
673
+ imports.push({
674
+ cellId: namespaceCellFor(targetId),
675
+ importedName: "*",
676
+ localName: entry.localName,
677
+ namespaceModuleId: targetId
678
+ });
679
+ continue;
680
+ }
681
+ const targetAmbiguous = ambiguousNames.get(targetId);
682
+ const candidate = exportsByModule.get(targetId)?.get(entry.importedName);
683
+ if (targetAmbiguous?.has(entry.importedName) === true) diagnostics.push(linkDiagnostic(module.canonicalId, entry, `Import '${entry.importedName}' is ambiguous.`));
684
+ else if (candidate == null) diagnostics.push(linkDiagnostic(module.canonicalId, entry, `Module has no export '${entry.importedName}'.`));
685
+ else imports.push({
686
+ cellId: candidate.cellId,
687
+ importedName: entry.importedName,
688
+ localName: entry.localName
689
+ });
690
+ }
691
+ }
692
+ if (diagnostics.length > 0) return { diagnostics: withImporterChains(graph, diagnostics) };
693
+ for (const request of graph.requests ?? []) if (request.edgeKind === "discovery") namespaceCellFor(request.targetId);
694
+ const components = moduleComponents(graph);
695
+ const componentByModule = /* @__PURE__ */ new Map();
696
+ for (const component of components) for (const moduleId of component.moduleIds) componentByModule.set(moduleId, component.id);
697
+ const linkedModules = graph.modules.map((module) => {
698
+ const moduleExports = exportsByModule.get(module.canonicalId);
699
+ const componentId = componentByModule.get(module.canonicalId);
700
+ if (moduleExports == null || componentId == null) throw new Error("Linked module state is incomplete.");
701
+ const exports = [...moduleExports].toSorted(([left], [right]) => compareCodeUnits(left, right)).map(([exportedName, candidate]) => ({
702
+ cellId: candidate.cellId,
703
+ exportedName,
704
+ sourceModuleId: candidate.sourceModuleId
705
+ }));
706
+ return {
707
+ canonicalId: module.canonicalId,
708
+ cellIds: cells.filter((cell) => cell.moduleId === module.canonicalId).map((cell) => cell.id),
709
+ componentId,
710
+ exports,
711
+ imports: linkedImports.get(module.canonicalId) ?? [],
712
+ ...includePropertiesWhen(() => {
713
+ const cellId = namespaceCells.get(module.canonicalId);
714
+ return cellId == null ? void 0 : { namespaceCellId: cellId };
715
+ }),
716
+ namespaceNames: exports.map((entry) => entry.exportedName)
717
+ };
718
+ });
719
+ return {
720
+ diagnostics,
721
+ graph: {
722
+ cells,
723
+ components,
724
+ entryId: graph.entryId,
725
+ evaluationOrder: moduleDepthFirstOrder(graph),
726
+ kind: "linked-module-graph",
727
+ modules: linkedModules
728
+ }
729
+ };
730
+ }
731
+
732
+ //#endregion
733
+ export { buildModuleGraph, buildScriptRequests, importedBinding, linkModuleGraph };
734
+ //# sourceMappingURL=modules.js.map