@mosetta/build 0.0.39 → 0.0.40

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @mosetta/build
2
2
 
3
+ ## 0.0.40
4
+
5
+ ### Patch Changes
6
+
7
+ - Shift SourceMap v3 VLQ columns after dynamic `import()` AST rewrites for exact minified column accuracy, parallelize native esbuild compilation phases deterministically (tiles, BFS dependency waves, shared CSS, server monoliths, SSR), and stabilize default SSR sourcemap virtual paths.
8
+ - @mosetta/router@0.0.40
9
+ - @mosetta/runtime@0.0.40
10
+ - @mosetta/server@0.0.40
11
+ - @mosetta/server-action@0.0.40
12
+ - @mosetta/tar@0.0.40
13
+
3
14
  ## 0.0.39
4
15
 
5
16
  ### Patch Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mosetta/build",
3
- "version": "0.0.39",
3
+ "version": "0.0.40",
4
4
  "license": "MIT",
5
5
  "description": "The core of the tile forge: builds a tile palette — its tile side artifacts, their dependency closure, the tile host descriptor. Environment-agnostic — the file system and the bundling engine are supplied from outside.",
6
6
  "type": "module",
@@ -25,11 +25,11 @@
25
25
  "resolve.exports": "^2.0.3",
26
26
  "scheduler": "*",
27
27
  "yaml": "^2.9.0",
28
- "@mosetta/router": "0.0.39",
29
- "@mosetta/runtime": "0.0.39",
30
- "@mosetta/server": "0.0.39",
31
- "@mosetta/server-action": "0.0.39",
32
- "@mosetta/tar": "0.0.39"
28
+ "@mosetta/router": "0.0.40",
29
+ "@mosetta/runtime": "0.0.40",
30
+ "@mosetta/tar": "0.0.40",
31
+ "@mosetta/server-action": "0.0.40",
32
+ "@mosetta/server": "0.0.40"
33
33
  },
34
34
  "publishConfig": {
35
35
  "access": "public"
package/src/build.mjs CHANGED
@@ -81,7 +81,27 @@ async function offersOf(jsCode, evaluate) {
81
81
  }
82
82
  }
83
83
 
84
+ /** Run `fn` over `items` with at most `limit` concurrent promises, preserving input order. */
85
+ async function mapLimit(items, limit, fn) {
86
+ if (items.length <= 1 || limit <= 1) {
87
+ const results = [];
88
+ for (let i = 0; i < items.length; i++) results.push(await fn(items[i], i));
89
+ return results;
90
+ }
91
+ const results = new Array(items.length);
92
+ let next = 0;
93
+ const worker = async () => {
94
+ while (next < items.length) {
95
+ const i = next++;
96
+ results[i] = await fn(items[i], i);
97
+ }
98
+ };
99
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
100
+ return results;
101
+ }
102
+
84
103
  export async function build(root, { mode = 'development', log, fileSystem, resolver, engine, frameworkDir, buildConfig = INERT_BUILD_CONFIG, cache = null, evaluate = null, released = null }) {
104
+ const concurrency = Math.max(1, Number(engine?.concurrency) || 1);
85
105
  const out = new OutputFS();
86
106
  const watchFiles = new Set();
87
107
  const addWatch = (arr) => arr.forEach((f) => watchFiles.add(f));
@@ -195,11 +215,33 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
195
215
  const docFileOf = (full) => `${full}.doc.md`;
196
216
  const docHref = tileDocHref(docIndex, (module) => `${fullOfDoc.get(module.address)}/${docFileOf(fullOfDoc.get(module.address))}`);
197
217
 
218
+ // Bundle client tile sides (and their settings schemas, when present) in parallel up to
219
+ // `concurrency`, then emit artifacts in deterministic `mods` order so `modules.json` is
220
+ // byte-for-byte identical between native Node and single-threaded WASM builds.
221
+ const builtModules = await mapLimit(mods, concurrency, async (m) => {
222
+ const full = fullTileName(m);
223
+ const cached = await memo(`module:${full}`,
224
+ () => buildModule(fileSystem, m, { resolver, mode, buildConfig, engine, sourceBase: root, assetExtensions }));
225
+ let settingsFile = null;
226
+ let described = null;
227
+ let settingsSkipped = false;
228
+ if (m.type === 'component') {
229
+ settingsFile = path.join(path.dirname(m.file), `${m.name}${SETTINGS_SUFFIX}`);
230
+ if (fileSystem.exists(settingsFile)) {
231
+ if (evaluate) {
232
+ described = await memo(`settings:${full}`,
233
+ () => describeSettings(fileSystem, settingsFile, { resolver, engine, evaluate, frameworkDir, sourceBase: root }));
234
+ } else {
235
+ settingsSkipped = true;
236
+ }
237
+ }
238
+ }
239
+ return { m, cached, settingsFile, described, settingsSkipped };
240
+ });
241
+
198
242
  const moduleResults = [];
199
243
  let skippedSettings = 0;
200
- for (const m of mods) {
201
- const cached = await memo(`module:${fullTileName(m)}`,
202
- () => buildModule(fileSystem, m, { resolver, mode, buildConfig, engine, sourceBase: root, assetExtensions }));
244
+ for (const { m, cached, settingsFile, described, settingsSkipped } of builtModules) {
203
245
  // the descriptor below gets AUGMENTED (edges to css entities, integrity) — the cached object
204
246
  // must stay untouched, otherwise edits would accumulate from iteration to iteration
205
247
  const r = { ...cached, descriptor: { ...cached.descriptor, dependencies: [...cached.descriptor.dependencies] } };
@@ -226,17 +268,12 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
226
268
  }
227
269
  // its SETTINGS: `<name>.settings.ts` beside it — what the block's node keeps, as JSON Schema
228
270
  // in the descriptor (settings.mjs); run by the host, skipped where the host runs nothing
229
- const settingsFile = path.join(path.dirname(m.file), `${m.name}${SETTINGS_SUFFIX}`);
230
271
  watchFiles.add(settingsFile);
231
- if (fileSystem.exists(settingsFile)) {
232
- if (evaluate) {
233
- const described = await memo(`settings:${r.full}`,
234
- () => describeSettings(fileSystem, settingsFile, { resolver, engine, evaluate, frameworkDir, sourceBase: root }));
235
- addWatch(described.watchFiles);
236
- r.descriptor.settings = described.schema;
237
- } else {
238
- skippedSettings++;
239
- }
272
+ if (described) {
273
+ addWatch(described.watchFiles);
274
+ r.descriptor.settings = described.schema;
275
+ } else if (settingsSkipped) {
276
+ skippedSettings++;
240
277
  }
241
278
  // its PAGE: what its sides say of it in doc comments, as Markdown beside it — `<id>.doc.md`,
242
279
  // named by the descriptor's `doc`; the settings schema, when read, closes it as a table
@@ -286,59 +323,70 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
286
323
  let depCount = 0;
287
324
  let releasedDeps = 0;
288
325
  const depRows = []; // {specifier, version, bytes} — for the dependency-artifact report
326
+ // Process BFS dependency closure wave-by-wave: each wave resolves/dedups deterministically,
327
+ // bundles in parallel up to `concurrency`, and emits descriptors in exact BFS order.
289
328
  while (queue.length) {
290
- const [specifier, importerDir] = queue.shift();
291
- const resolved = resolveSpecifier(fileSystem, resolver, specifier, importerDir, log);
292
- if (!resolved) continue;
293
- const { full, resolvedFile, kind, version } = resolved;
294
- if (seen.has(full)) continue;
295
- seen.add(full);
296
- // a PUBLISHED package already released where this build goes is there with everything it
297
- // imports (released together with it): neither it nor its closure is built again. A package of
298
- // the distribution's own sources always is — new bytes under its version must be seen
299
- if (released?.has(full) && fileSystem.realPath(resolvedFile).split(/[\\/]/).includes('node_modules')) {
300
- releasedDeps++;
301
- continue;
329
+ const rawWave = queue.splice(0);
330
+ const wave = [];
331
+ for (const [specifier, importerDir] of rawWave) {
332
+ const resolved = resolveSpecifier(fileSystem, resolver, specifier, importerDir, log);
333
+ if (!resolved) continue;
334
+ const { full, resolvedFile, version } = resolved;
335
+ if (seen.has(full)) continue;
336
+ seen.add(full);
337
+ // a PUBLISHED package already released where this build goes is there with everything it
338
+ // imports (released together with it): neither it nor its closure is built again. A package of
339
+ // the distribution's own sources always is — new bytes under its version must be seen
340
+ const inNodeModules = fileSystem.realPath(resolvedFile).split(/[\\/]/).includes('node_modules');
341
+ if (released?.has(full) && inNodeModules) {
342
+ releasedDeps++;
343
+ continue;
344
+ }
345
+ wave.push({ specifier, full, resolvedFile, version, inNodeModules });
302
346
  }
347
+ if (!wave.length) continue;
303
348
 
304
- const res = await memo(`dep:${full}`, () => buildDependency(fileSystem, {
349
+ const builtWave = await mapLimit(wave, concurrency, ({ full, resolvedFile }) => memo(`dep:${full}`, () => buildDependency(fileSystem, {
305
350
  resolver, resolvedFile, full, mode, buildConfig, engine, sourceBase: root,
306
- }));
307
- addWatch(res.watchFiles);
308
- writeJs(`${PUB}/modules/${full}/${full}.js`, res.jsCode, res.map);
309
- const depVersion = version;
310
- const depDescriptor = {
311
- id: full,
312
- reference: { type: 'package', specifier, version: depVersion },
313
- assets: [],
314
- dependencies: res.imports,
315
- ...(res.lazyImports?.length ? { lazyDependencies: res.lazyImports } : {}),
316
- integrity: sriOf(`${PUB}/modules/${full}/${full}.js`),
317
- // built from the distribution's OWN sources (a workspace package), not a published one: new
318
- // bytes under its version are a change that needs a new version — a published package's
319
- // bytes may differ by build tooling alone, and its first deployed copy stands (deploy.mjs)
320
- ...(fileSystem.realPath(resolvedFile).split(/[\\/]/).includes('node_modules') ? {} : { local: true }),
321
- };
322
- out.set(`${PUB}/modules/${full}/${full}.json`, JSON.stringify(depDescriptor, null, 2));
323
- entityDescriptors.push(depDescriptor);
324
- depRows.push({ specifier, version: depVersion, bytes: res.jsCode.length });
325
- // this artifact's own imports resolve from ITS package next
326
- enqueue(res.rawImports, packageDirOf(fileSystem, resolvedFile) ?? path.dirname(resolvedFile));
327
- depCount++;
351
+ })));
352
+
353
+ for (let i = 0; i < wave.length; i++) {
354
+ const { specifier, full, resolvedFile, version: depVersion, inNodeModules } = wave[i];
355
+ const res = builtWave[i];
356
+ addWatch(res.watchFiles);
357
+ writeJs(`${PUB}/modules/${full}/${full}.js`, res.jsCode, res.map);
358
+ const depDescriptor = {
359
+ id: full,
360
+ reference: { type: 'package', specifier, version: depVersion },
361
+ assets: [],
362
+ dependencies: res.imports,
363
+ ...(res.lazyImports?.length ? { lazyDependencies: res.lazyImports } : {}),
364
+ integrity: sriOf(`${PUB}/modules/${full}/${full}.js`),
365
+ // built from the distribution's OWN sources (a workspace package), not a published one: new
366
+ // bytes under its version are a change that needs a new version — a published package's
367
+ // bytes may differ by build tooling alone, and its first deployed copy stands (deploy.mjs)
368
+ ...(inNodeModules ? {} : { local: true }),
369
+ };
370
+ out.set(`${PUB}/modules/${full}/${full}.json`, JSON.stringify(depDescriptor, null, 2));
371
+ entityDescriptors.push(depDescriptor);
372
+ depRows.push({ specifier, version: depVersion, bytes: res.jsCode.length });
373
+ // this artifact's own imports resolve from ITS package next
374
+ enqueue(res.rawImports, packageDirOf(fileSystem, resolvedFile) ?? path.dirname(resolvedFile));
375
+ depCount++;
376
+ }
328
377
  }
329
378
 
330
379
  // 3b) css entities: a shared UNscoped css artifact is a full catalog entity
331
380
  // (folder: css + url() assets + descriptor, no JS facet)
332
- for (const [cssFull, s] of sharedCssArtifacts) {
333
- if (released?.has(cssFull)) continue; // released with the package it comes from
334
- // a dependency's css entity is the file itself plus its url() assets; there is no graph here,
335
- // so we assemble the watched set ourselves (otherwise editing an image would not change its
336
- // hash-based name)
337
- const { css, assets: cssAssets } = await memo(`css:${cssFull}`,
338
- async () => {
339
- const r = await processCss({ fileSystem, cssFiles: [s.file], scopeClass: null, engine, mode });
340
- return { ...r, watchFiles: [s.file, ...r.assets.values()] };
341
- });
381
+ const sharedCssEntries = [...sharedCssArtifacts.entries()].filter(([cssFull]) => !released?.has(cssFull));
382
+ const builtSharedCss = await mapLimit(sharedCssEntries, concurrency, ([cssFull, s]) => memo(`css:${cssFull}`,
383
+ async () => {
384
+ const r = await processCss({ fileSystem, cssFiles: [s.file], scopeClass: null, engine, mode });
385
+ return { ...r, watchFiles: [s.file, ...r.assets.values()] };
386
+ }));
387
+ for (let i = 0; i < sharedCssEntries.length; i++) {
388
+ const [cssFull, s] = sharedCssEntries[i];
389
+ const { css, assets: cssAssets } = builtSharedCss[i];
342
390
  out.set(`${PUB}/modules/${cssFull}/${cssFull}.css`, css);
343
391
  for (const [outName, srcAbs] of cssAssets) {
344
392
  out.set(`${PUB}/modules/${cssFull}/${outName}`, fileSystem.readFile(srcAbs));
@@ -457,8 +505,7 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
457
505
  };
458
506
  const serverMods = builtRoots.flatMap((r) => discoverServerModulesIn(fileSystem, r));
459
507
  const actionPermissionsByNamespace = new Map();
460
- let serverCount = 0;
461
- for (const sm of serverMods) {
508
+ const builtServerMods = await mapLimit(serverMods, concurrency, async (sm) => {
462
509
  try {
463
510
  // what the module OFFERS — its actions that offer themselves as tools, its handlers, their
464
511
  // input and settings as JSON Schema — asked of the built module itself, kept with the build
@@ -467,27 +514,37 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
467
514
  const built = await buildServerModule(fileSystem, sm, { resolver, mode, buildConfig, engine, sourceBase: root, frameworkDir });
468
515
  return { ...built, offers: evaluate ? await offersOf(built.jsCode, evaluate) : null };
469
516
  });
470
- addWatch(s.watchFiles);
471
- writeJs(`private/modules/${s.full}/${s.full}.js`, s.jsCode, s.map);
472
- // the facet's wasm imports travel as assets next to the monolith: the runner will declare
473
- // them as bundle modules under the same relative names
474
- for (const [assetName, srcFile] of s.wasmAssets) {
475
- out.set(`private/modules/${s.full}/${assetName}`, fileSystem.readFile(srcFile));
476
- }
477
- if (s.offers?.permissions?.length) {
478
- const list = actionPermissionsByNamespace.get(sm.namespace) ?? [];
479
- list.push(...s.offers.permissions);
480
- actionPermissionsByNamespace.set(sm.namespace, list);
481
- }
482
- recordPrivate(s.full, { namespace: sm.namespace, name: sm.name, type: 'server', version: sm.version },
483
- s.offers ? { offers: s.offers } : {}, [...s.wasmAssets.keys()]);
484
- record(sm, 'server', s.jsCode.length, 'private'
485
- + (s.wasmAssets.size ? `, ${s.wasmAssets.size} wasm asset(s)` : ''));
486
- serverCount++;
517
+ return { sm, ok: true, s };
487
518
  } catch (e) {
488
- log(` ! server side ${sm.name}@${sm.namespace} not bundled (${String(e.message || e)})`
519
+ return { sm, ok: false, e };
520
+ }
521
+ });
522
+ let serverCount = 0;
523
+ for (const item of builtServerMods) {
524
+ const { sm } = item;
525
+ if (!item.ok) {
526
+ log(` ! server side ${sm.name}@${sm.namespace} not bundled (${String(item.e.message || item.e)})`
489
527
  + ` — skipped; needs @mosetta/server-action Web-API port`);
528
+ continue;
529
+ }
530
+ const { s } = item;
531
+ addWatch(s.watchFiles);
532
+ writeJs(`private/modules/${s.full}/${s.full}.js`, s.jsCode, s.map);
533
+ // the facet's wasm imports travel as assets next to the monolith: the runner will declare
534
+ // them as bundle modules under the same relative names
535
+ for (const [assetName, srcFile] of s.wasmAssets) {
536
+ out.set(`private/modules/${s.full}/${assetName}`, fileSystem.readFile(srcFile));
537
+ }
538
+ if (s.offers?.permissions?.length) {
539
+ const list = actionPermissionsByNamespace.get(sm.namespace) ?? [];
540
+ list.push(...s.offers.permissions);
541
+ actionPermissionsByNamespace.set(sm.namespace, list);
490
542
  }
543
+ recordPrivate(s.full, { namespace: sm.namespace, name: sm.name, type: 'server', version: sm.version },
544
+ s.offers ? { offers: s.offers } : {}, [...s.wasmAssets.keys()]);
545
+ record(sm, 'server', s.jsCode.length, 'private'
546
+ + (s.wasmAssets.size ? `, ${s.wasmAssets.size} wasm asset(s)` : ''));
547
+ serverCount++;
491
548
  }
492
549
  for (const [namespace, declared] of actionPermissionsByNamespace) {
493
550
  let entry = distributionByNamespace.get(namespace);
@@ -523,9 +580,11 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
523
580
  let ssrCount = 0;
524
581
  const scriptDirs = new Set(mods.filter((m) => m.type === 'script').map((m) => path.dirname(m.file)));
525
582
  const ssrRoots = mods.filter((m) => m.type === 'component' && scriptDirs.has(path.dirname(m.file)));
526
- for (const am of ssrRoots) {
527
- const s = await memo(`ssr:${fullTileName(am)}`,
528
- () => buildSsrModule(fileSystem, am, { resolver, mode, buildConfig, engine, sourceBase: root, frameworkDir }));
583
+ const builtSsrRoots = await mapLimit(ssrRoots, concurrency, (am) => memo(`ssr:${fullTileName(am)}`,
584
+ () => buildSsrModule(fileSystem, am, { resolver, mode, buildConfig, engine, sourceBase: root, frameworkDir })));
585
+ for (let i = 0; i < ssrRoots.length; i++) {
586
+ const am = ssrRoots[i];
587
+ const s = builtSsrRoots[i];
529
588
  if (s.watchFile) watchFiles.add(s.watchFile);
530
589
  addWatch(s.watchFiles);
531
590
  writeJs(`private/modules/${s.full}/${s.full}.js`, s.jsCode, s.map);
@@ -4,7 +4,7 @@ import { fullTileName } from './moduleName.mjs';
4
4
  import { cssIntercept } from './plugins/cssIntercept.mjs';
5
5
  import { assets } from './plugins/assets.mjs';
6
6
  import { portResolveClient } from './plugins/portResolveClient.mjs';
7
- import { rewriteDynamicImports } from './plugins/dynamicImport.mjs';
7
+ import { rewriteDynamicImportsWithMap } from './plugins/dynamicImport.mjs';
8
8
  import { processCss } from './css.mjs';
9
9
  import { resolveSpecifier } from './specifiers.mjs';
10
10
  import { applyEsbuildOptions, assertFactoryArtifact, userPluginsFor } from './buildConfig.mjs';
@@ -94,13 +94,15 @@ export async function generateFactory({
94
94
  const lazyDeps = [...new Set(lazyExternalMap.values())].filter((id) => !eagerSet.has(id)).sort();
95
95
  const rawImports = [...new Set([...eagerExternalMap.keys(), ...lazyExternalMap.keys()])].sort();
96
96
 
97
- // Rewrite `import(...)` -> `__meta.import(...)` on the complete syntactically-valid script.
97
+ // Rewrite `import(...)` -> `__meta.import(...)` on the complete syntactically-valid script,
98
+ // shifting generated columns in the sourcemap so minified stack traces stay column-accurate.
98
99
  const wrapped = `${jsFile.text}\n},${JSON.stringify(eagerDeps)}];\n`;
99
- const code = rewriteDynamicImports(wrapped);
100
+ const rawMap = wantSourcemap && mapFile ? mapFile.text : null;
101
+ const { code, map: shiftedMap } = rewriteDynamicImportsWithMap(wrapped, rawMap);
100
102
 
101
103
  assertFactoryArtifact(code, name, buildConfig);
102
104
 
103
- const map = wantSourcemap && mapFile ? normalizeSourcemap(mapFile.text, sourceBase) : null;
105
+ const map = shiftedMap ? normalizeSourcemap(shiftedMap, sourceBase) : null;
104
106
  return {
105
107
  code,
106
108
  map,
@@ -135,7 +135,7 @@ export async function buildSsrModule(fileSystem, { file, name, namespace, versio
135
135
  ...portOptions(fileSystem, resolver, sourceBase, frameworkDir, null, watched, userPluginsFor(buildConfig, 'ssr', mode)),
136
136
  ...(custom
137
137
  ? { entryPoints: [grain] }
138
- : { stdin: { contents: DEFAULT_SSR_SOURCE, resolveDir: sourceBase ?? frameworkDir, sourcefile: `${name}.ssr.default.ts`, loader: 'ts' } }),
138
+ : { stdin: { contents: DEFAULT_SSR_SOURCE, resolveDir: sourceBase ?? frameworkDir, sourcefile: 'default.ssr.ts', loader: 'ts' } }),
139
139
  bundle: true,
140
140
  format: 'esm',
141
141
  platform: 'neutral',
@@ -1,23 +1,127 @@
1
1
  import { parse } from 'acorn';
2
2
 
3
+ const PREFIX = '__meta.';
4
+ const VLQ_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
5
+ const VLQ_LOOKUP = new Int8Array(128).fill(-1);
6
+ for (let i = 0; i < VLQ_CHARS.length; i++) VLQ_LOOKUP[VLQ_CHARS.charCodeAt(i)] = i;
7
+
8
+ /** Decode one signed base64-VLQ integer starting at `index` in `str`. */
9
+ function decodeVlq(str, index) {
10
+ let result = 0;
11
+ let shift = 0;
12
+ let i = index;
13
+ while (i < str.length) {
14
+ const digit = VLQ_LOOKUP[str.charCodeAt(i++)];
15
+ if (digit < 0) break;
16
+ result += (digit & 31) << shift;
17
+ shift += 5;
18
+ if ((digit & 32) === 0) break;
19
+ }
20
+ const neg = (result & 1) === 1;
21
+ const value = result >> 1;
22
+ return [neg ? -value : value, i];
23
+ }
24
+
25
+ /** Encode one signed integer as base64-VLQ. */
26
+ function encodeVlq(value) {
27
+ let vlq = value < 0 ? ((-value) << 1) | 1 : value << 1;
28
+ let out = '';
29
+ do {
30
+ let digit = vlq & 31;
31
+ vlq >>>= 5;
32
+ if (vlq > 0) digit |= 32;
33
+ out += VLQ_CHARS[digit];
34
+ } while (vlq > 0);
35
+ return out;
36
+ }
37
+
38
+ /**
39
+ * Shift generated columns in a SourceMap v3 JSON string to account for fixed-length inline
40
+ * insertions (`delta` UTF-16 code units) recorded in `editsByLine` (Map<0-based line, sorted 0-based cols>).
41
+ * Only affected lines are decoded/re-encoded; all other lines and non-column segment fields pass through verbatim.
42
+ *
43
+ * @param {string | null} mapText
44
+ * @param {Map<number, number[]>} editsByLine
45
+ * @param {number} delta
46
+ * @returns {string | null}
47
+ */
48
+ export function shiftSourcemapColumns(mapText, editsByLine, delta) {
49
+ if (!mapText || !editsByLine.size || !delta) return mapText;
50
+ let parsed;
51
+ try {
52
+ parsed = JSON.parse(mapText);
53
+ } catch {
54
+ return mapText;
55
+ }
56
+ if (typeof parsed.mappings !== 'string' || !parsed.mappings) return mapText;
57
+
58
+ const lines = parsed.mappings.split(';');
59
+ for (const [line, cols] of editsByLine) {
60
+ if (line >= lines.length || !lines[line]) continue;
61
+ const segments = lines[line].split(',');
62
+ let origCol = 0;
63
+ let prevNewCol = 0;
64
+ let editIdx = 0;
65
+ for (let s = 0; s < segments.length; s++) {
66
+ const seg = segments[s];
67
+ if (!seg) continue;
68
+ const [colDelta, restStart] = decodeVlq(seg, 0);
69
+ origCol += colDelta;
70
+ while (editIdx < cols.length && cols[editIdx] < origCol) editIdx++;
71
+ const newCol = origCol + editIdx * delta;
72
+ segments[s] = encodeVlq(newCol - prevNewCol) + seg.slice(restStart);
73
+ prevNewCol = newCol;
74
+ }
75
+ lines[line] = segments.join(',');
76
+ }
77
+ parsed.mappings = lines.join(';');
78
+ return JSON.stringify(parsed);
79
+ }
80
+
81
+ /** Map sorted ascending UTF-16 offsets in `code` to `Map<0-based line, 0-based cols[]>`. */
82
+ function offsetsToLineCols(code, sortedAsc) {
83
+ const editsByLine = new Map();
84
+ let line = 0;
85
+ let lineStart = 0;
86
+ let cursor = 0;
87
+ for (const pos of sortedAsc) {
88
+ while (cursor < pos) {
89
+ if (code.charCodeAt(cursor) === 10) {
90
+ line += 1;
91
+ lineStart = cursor + 1;
92
+ }
93
+ cursor += 1;
94
+ }
95
+ let cols = editsByLine.get(line);
96
+ if (!cols) {
97
+ cols = [];
98
+ editsByLine.set(line, cols);
99
+ }
100
+ cols.push(pos - lineStart);
101
+ }
102
+ return editsByLine;
103
+ }
104
+
3
105
  /**
4
106
  * Rewrite every JS `ImportExpression` (`import(spec)`) in a bundled factory chunk to
5
- * `__meta.import(spec)` using a real JS AST (`acorn`).
107
+ * `__meta.import(spec)` using a real JS AST (`acorn`), and shift generated columns in `mapText`
108
+ * (when provided) so minified and non-minified sourcemaps remain column-accurate.
6
109
  *
7
110
  * Fast-path: 99% of artifacts contain no `import(` substring and skip parsing completely (0 ms).
8
- * When present, only genuine `ImportExpression` AST nodes are rewritten — strings, comments and
9
- * property names are untouched, and every replacement stays on the same line (sourcemap line
10
- * numbers remain intact).
111
+ *
112
+ * @param {string} code
113
+ * @param {string | null} [mapText]
114
+ * @returns {{ code: string; map: string | null }}
11
115
  */
12
- export function rewriteDynamicImports(code) {
13
- if (!code.includes('import(') && !/\bimport\s*\(/.test(code)) return code;
116
+ export function rewriteDynamicImportsWithMap(code, mapText = null) {
117
+ if (!code.includes('import(') && !/\bimport\s*\(/.test(code)) return { code, map: mapText };
14
118
 
15
119
  let ast;
16
120
  try {
17
121
  ast = parse(code, { ecmaVersion: 2022, sourceType: 'script', allowReturnOutsideFunction: true });
18
122
  } catch {
19
123
  // Fallback if a custom plugin emitted non-standard syntax; return untouched rather than corrupting.
20
- return code;
124
+ return { code, map: mapText };
21
125
  }
22
126
 
23
127
  const starts = [];
@@ -38,15 +142,24 @@ export function rewriteDynamicImports(code) {
38
142
  };
39
143
  walk(ast);
40
144
 
41
- if (!starts.length) return code;
145
+ const validStarts = starts.filter((pos) => code.slice(pos, pos + 6) === 'import');
146
+ if (!validStarts.length) return { code, map: mapText };
147
+
148
+ validStarts.sort((a, b) => a - b);
149
+ const editsByLine = mapText ? offsetsToLineCols(code, validStarts) : null;
42
150
 
43
151
  // Replace from back to front so earlier offsets stay valid.
44
- starts.sort((a, b) => b - a);
45
152
  let out = code;
46
- for (const pos of starts) {
47
- if (out.slice(pos, pos + 6) === 'import') {
48
- out = `${out.slice(0, pos)}__meta.import${out.slice(pos + 6)}`;
49
- }
153
+ for (let i = validStarts.length - 1; i >= 0; i--) {
154
+ const pos = validStarts[i];
155
+ out = `${out.slice(0, pos)}${PREFIX}${out.slice(pos)}`;
50
156
  }
51
- return out;
157
+
158
+ const map = editsByLine ? shiftSourcemapColumns(mapText, editsByLine, PREFIX.length) : mapText;
159
+ return { code: out, map };
160
+ }
161
+
162
+ /** Convenience wrapper when no sourcemap needs adjustment. */
163
+ export function rewriteDynamicImports(code) {
164
+ return rewriteDynamicImportsWithMap(code, null).code;
52
165
  }