@mosetta/build 0.0.39 → 0.0.41
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 +22 -0
- package/package.json +6 -6
- package/src/build.mjs +143 -82
- package/src/buildModules.mjs +6 -4
- package/src/buildServer.mjs +1 -1
- package/src/fileSystem.mjs +91 -0
- package/src/plugins/dynamicImport.mjs +127 -14
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# @mosetta/build
|
|
2
2
|
|
|
3
|
+
## 0.0.41
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Add per-build `SnapshotFileSystem` memoization over the `FileSystem` port (~2x faster cold builds on large multi-tile palettes with shared barrels, zero stale cache across `dev` rebuilds).
|
|
8
|
+
- @mosetta/router@0.0.41
|
|
9
|
+
- @mosetta/runtime@0.0.41
|
|
10
|
+
- @mosetta/server@0.0.41
|
|
11
|
+
- @mosetta/server-action@0.0.41
|
|
12
|
+
- @mosetta/tar@0.0.41
|
|
13
|
+
|
|
14
|
+
## 0.0.40
|
|
15
|
+
|
|
16
|
+
### Patch Changes
|
|
17
|
+
|
|
18
|
+
- 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.
|
|
19
|
+
- @mosetta/router@0.0.40
|
|
20
|
+
- @mosetta/runtime@0.0.40
|
|
21
|
+
- @mosetta/server@0.0.40
|
|
22
|
+
- @mosetta/server-action@0.0.40
|
|
23
|
+
- @mosetta/tar@0.0.40
|
|
24
|
+
|
|
3
25
|
## 0.0.39
|
|
4
26
|
|
|
5
27
|
### Patch Changes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mosetta/build",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.41",
|
|
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.
|
|
29
|
-
"@mosetta/runtime": "0.0.
|
|
30
|
-
"@mosetta/
|
|
31
|
-
"@mosetta/server
|
|
32
|
-
"@mosetta/
|
|
28
|
+
"@mosetta/router": "0.0.41",
|
|
29
|
+
"@mosetta/runtime": "0.0.41",
|
|
30
|
+
"@mosetta/tar": "0.0.41",
|
|
31
|
+
"@mosetta/server": "0.0.41",
|
|
32
|
+
"@mosetta/server-action": "0.0.41"
|
|
33
33
|
},
|
|
34
34
|
"publishConfig": {
|
|
35
35
|
"access": "public"
|
package/src/build.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { processCss } from './css.mjs';
|
|
|
10
10
|
import { INERT_BUILD_CONFIG } from './buildConfig.mjs';
|
|
11
11
|
import { formatBytes } from './format.mjs';
|
|
12
12
|
import { mtimeStamp } from './artifactCache.mjs';
|
|
13
|
+
import { snapshotFileSystem } from './fileSystem.mjs';
|
|
13
14
|
import { describeSettings, SETTINGS_SUFFIX } from './settings.mjs';
|
|
14
15
|
import { DocIndex, renderPaletteDocs, renderTileDocs, tileDocHref, tileDocModule } from './docs.mjs';
|
|
15
16
|
|
|
@@ -81,7 +82,28 @@ async function offersOf(jsCode, evaluate) {
|
|
|
81
82
|
}
|
|
82
83
|
}
|
|
83
84
|
|
|
84
|
-
|
|
85
|
+
/** Run `fn` over `items` with at most `limit` concurrent promises, preserving input order. */
|
|
86
|
+
async function mapLimit(items, limit, fn) {
|
|
87
|
+
if (items.length <= 1 || limit <= 1) {
|
|
88
|
+
const results = [];
|
|
89
|
+
for (let i = 0; i < items.length; i++) results.push(await fn(items[i], i));
|
|
90
|
+
return results;
|
|
91
|
+
}
|
|
92
|
+
const results = new Array(items.length);
|
|
93
|
+
let next = 0;
|
|
94
|
+
const worker = async () => {
|
|
95
|
+
while (next < items.length) {
|
|
96
|
+
const i = next++;
|
|
97
|
+
results[i] = await fn(items[i], i);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
101
|
+
return results;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function build(root, { mode = 'development', log, fileSystem: rawFileSystem, resolver, engine, frameworkDir, buildConfig = INERT_BUILD_CONFIG, cache = null, evaluate = null, released = null }) {
|
|
105
|
+
const fileSystem = snapshotFileSystem(rawFileSystem);
|
|
106
|
+
const concurrency = Math.max(1, Number(engine?.concurrency) || 1);
|
|
85
107
|
const out = new OutputFS();
|
|
86
108
|
const watchFiles = new Set();
|
|
87
109
|
const addWatch = (arr) => arr.forEach((f) => watchFiles.add(f));
|
|
@@ -195,11 +217,33 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
|
|
|
195
217
|
const docFileOf = (full) => `${full}.doc.md`;
|
|
196
218
|
const docHref = tileDocHref(docIndex, (module) => `${fullOfDoc.get(module.address)}/${docFileOf(fullOfDoc.get(module.address))}`);
|
|
197
219
|
|
|
220
|
+
// Bundle client tile sides (and their settings schemas, when present) in parallel up to
|
|
221
|
+
// `concurrency`, then emit artifacts in deterministic `mods` order so `modules.json` is
|
|
222
|
+
// byte-for-byte identical between native Node and single-threaded WASM builds.
|
|
223
|
+
const builtModules = await mapLimit(mods, concurrency, async (m) => {
|
|
224
|
+
const full = fullTileName(m);
|
|
225
|
+
const cached = await memo(`module:${full}`,
|
|
226
|
+
() => buildModule(fileSystem, m, { resolver, mode, buildConfig, engine, sourceBase: root, assetExtensions }));
|
|
227
|
+
let settingsFile = null;
|
|
228
|
+
let described = null;
|
|
229
|
+
let settingsSkipped = false;
|
|
230
|
+
if (m.type === 'component') {
|
|
231
|
+
settingsFile = path.join(path.dirname(m.file), `${m.name}${SETTINGS_SUFFIX}`);
|
|
232
|
+
if (fileSystem.exists(settingsFile)) {
|
|
233
|
+
if (evaluate) {
|
|
234
|
+
described = await memo(`settings:${full}`,
|
|
235
|
+
() => describeSettings(fileSystem, settingsFile, { resolver, engine, evaluate, frameworkDir, sourceBase: root }));
|
|
236
|
+
} else {
|
|
237
|
+
settingsSkipped = true;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return { m, cached, settingsFile, described, settingsSkipped };
|
|
242
|
+
});
|
|
243
|
+
|
|
198
244
|
const moduleResults = [];
|
|
199
245
|
let skippedSettings = 0;
|
|
200
|
-
for (const m of
|
|
201
|
-
const cached = await memo(`module:${fullTileName(m)}`,
|
|
202
|
-
() => buildModule(fileSystem, m, { resolver, mode, buildConfig, engine, sourceBase: root, assetExtensions }));
|
|
246
|
+
for (const { m, cached, settingsFile, described, settingsSkipped } of builtModules) {
|
|
203
247
|
// the descriptor below gets AUGMENTED (edges to css entities, integrity) — the cached object
|
|
204
248
|
// must stay untouched, otherwise edits would accumulate from iteration to iteration
|
|
205
249
|
const r = { ...cached, descriptor: { ...cached.descriptor, dependencies: [...cached.descriptor.dependencies] } };
|
|
@@ -226,17 +270,12 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
|
|
|
226
270
|
}
|
|
227
271
|
// its SETTINGS: `<name>.settings.ts` beside it — what the block's node keeps, as JSON Schema
|
|
228
272
|
// 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
273
|
watchFiles.add(settingsFile);
|
|
231
|
-
if (
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
r.descriptor.settings = described.schema;
|
|
237
|
-
} else {
|
|
238
|
-
skippedSettings++;
|
|
239
|
-
}
|
|
274
|
+
if (described) {
|
|
275
|
+
addWatch(described.watchFiles);
|
|
276
|
+
r.descriptor.settings = described.schema;
|
|
277
|
+
} else if (settingsSkipped) {
|
|
278
|
+
skippedSettings++;
|
|
240
279
|
}
|
|
241
280
|
// its PAGE: what its sides say of it in doc comments, as Markdown beside it — `<id>.doc.md`,
|
|
242
281
|
// named by the descriptor's `doc`; the settings schema, when read, closes it as a table
|
|
@@ -286,59 +325,70 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
|
|
|
286
325
|
let depCount = 0;
|
|
287
326
|
let releasedDeps = 0;
|
|
288
327
|
const depRows = []; // {specifier, version, bytes} — for the dependency-artifact report
|
|
328
|
+
// Process BFS dependency closure wave-by-wave: each wave resolves/dedups deterministically,
|
|
329
|
+
// bundles in parallel up to `concurrency`, and emits descriptors in exact BFS order.
|
|
289
330
|
while (queue.length) {
|
|
290
|
-
const
|
|
291
|
-
const
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
331
|
+
const rawWave = queue.splice(0);
|
|
332
|
+
const wave = [];
|
|
333
|
+
for (const [specifier, importerDir] of rawWave) {
|
|
334
|
+
const resolved = resolveSpecifier(fileSystem, resolver, specifier, importerDir, log);
|
|
335
|
+
if (!resolved) continue;
|
|
336
|
+
const { full, resolvedFile, version } = resolved;
|
|
337
|
+
if (seen.has(full)) continue;
|
|
338
|
+
seen.add(full);
|
|
339
|
+
// a PUBLISHED package already released where this build goes is there with everything it
|
|
340
|
+
// imports (released together with it): neither it nor its closure is built again. A package of
|
|
341
|
+
// the distribution's own sources always is — new bytes under its version must be seen
|
|
342
|
+
const inNodeModules = fileSystem.realPath(resolvedFile).split(/[\\/]/).includes('node_modules');
|
|
343
|
+
if (released?.has(full) && inNodeModules) {
|
|
344
|
+
releasedDeps++;
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
wave.push({ specifier, full, resolvedFile, version, inNodeModules });
|
|
302
348
|
}
|
|
349
|
+
if (!wave.length) continue;
|
|
303
350
|
|
|
304
|
-
const
|
|
351
|
+
const builtWave = await mapLimit(wave, concurrency, ({ full, resolvedFile }) => memo(`dep:${full}`, () => buildDependency(fileSystem, {
|
|
305
352
|
resolver, resolvedFile, full, mode, buildConfig, engine, sourceBase: root,
|
|
306
|
-
}));
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
353
|
+
})));
|
|
354
|
+
|
|
355
|
+
for (let i = 0; i < wave.length; i++) {
|
|
356
|
+
const { specifier, full, resolvedFile, version: depVersion, inNodeModules } = wave[i];
|
|
357
|
+
const res = builtWave[i];
|
|
358
|
+
addWatch(res.watchFiles);
|
|
359
|
+
writeJs(`${PUB}/modules/${full}/${full}.js`, res.jsCode, res.map);
|
|
360
|
+
const depDescriptor = {
|
|
361
|
+
id: full,
|
|
362
|
+
reference: { type: 'package', specifier, version: depVersion },
|
|
363
|
+
assets: [],
|
|
364
|
+
dependencies: res.imports,
|
|
365
|
+
...(res.lazyImports?.length ? { lazyDependencies: res.lazyImports } : {}),
|
|
366
|
+
integrity: sriOf(`${PUB}/modules/${full}/${full}.js`),
|
|
367
|
+
// built from the distribution's OWN sources (a workspace package), not a published one: new
|
|
368
|
+
// bytes under its version are a change that needs a new version — a published package's
|
|
369
|
+
// bytes may differ by build tooling alone, and its first deployed copy stands (deploy.mjs)
|
|
370
|
+
...(inNodeModules ? {} : { local: true }),
|
|
371
|
+
};
|
|
372
|
+
out.set(`${PUB}/modules/${full}/${full}.json`, JSON.stringify(depDescriptor, null, 2));
|
|
373
|
+
entityDescriptors.push(depDescriptor);
|
|
374
|
+
depRows.push({ specifier, version: depVersion, bytes: res.jsCode.length });
|
|
375
|
+
// this artifact's own imports resolve from ITS package next
|
|
376
|
+
enqueue(res.rawImports, packageDirOf(fileSystem, resolvedFile) ?? path.dirname(resolvedFile));
|
|
377
|
+
depCount++;
|
|
378
|
+
}
|
|
328
379
|
}
|
|
329
380
|
|
|
330
381
|
// 3b) css entities: a shared UNscoped css artifact is a full catalog entity
|
|
331
382
|
// (folder: css + url() assets + descriptor, no JS facet)
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
});
|
|
383
|
+
const sharedCssEntries = [...sharedCssArtifacts.entries()].filter(([cssFull]) => !released?.has(cssFull));
|
|
384
|
+
const builtSharedCss = await mapLimit(sharedCssEntries, concurrency, ([cssFull, s]) => memo(`css:${cssFull}`,
|
|
385
|
+
async () => {
|
|
386
|
+
const r = await processCss({ fileSystem, cssFiles: [s.file], scopeClass: null, engine, mode });
|
|
387
|
+
return { ...r, watchFiles: [s.file, ...r.assets.values()] };
|
|
388
|
+
}));
|
|
389
|
+
for (let i = 0; i < sharedCssEntries.length; i++) {
|
|
390
|
+
const [cssFull, s] = sharedCssEntries[i];
|
|
391
|
+
const { css, assets: cssAssets } = builtSharedCss[i];
|
|
342
392
|
out.set(`${PUB}/modules/${cssFull}/${cssFull}.css`, css);
|
|
343
393
|
for (const [outName, srcAbs] of cssAssets) {
|
|
344
394
|
out.set(`${PUB}/modules/${cssFull}/${outName}`, fileSystem.readFile(srcAbs));
|
|
@@ -457,8 +507,7 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
|
|
|
457
507
|
};
|
|
458
508
|
const serverMods = builtRoots.flatMap((r) => discoverServerModulesIn(fileSystem, r));
|
|
459
509
|
const actionPermissionsByNamespace = new Map();
|
|
460
|
-
|
|
461
|
-
for (const sm of serverMods) {
|
|
510
|
+
const builtServerMods = await mapLimit(serverMods, concurrency, async (sm) => {
|
|
462
511
|
try {
|
|
463
512
|
// what the module OFFERS — its actions that offer themselves as tools, its handlers, their
|
|
464
513
|
// input and settings as JSON Schema — asked of the built module itself, kept with the build
|
|
@@ -467,27 +516,37 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
|
|
|
467
516
|
const built = await buildServerModule(fileSystem, sm, { resolver, mode, buildConfig, engine, sourceBase: root, frameworkDir });
|
|
468
517
|
return { ...built, offers: evaluate ? await offersOf(built.jsCode, evaluate) : null };
|
|
469
518
|
});
|
|
470
|
-
|
|
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++;
|
|
519
|
+
return { sm, ok: true, s };
|
|
487
520
|
} catch (e) {
|
|
488
|
-
|
|
521
|
+
return { sm, ok: false, e };
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
let serverCount = 0;
|
|
525
|
+
for (const item of builtServerMods) {
|
|
526
|
+
const { sm } = item;
|
|
527
|
+
if (!item.ok) {
|
|
528
|
+
log(` ! server side ${sm.name}@${sm.namespace} not bundled (${String(item.e.message || item.e)})`
|
|
489
529
|
+ ` — skipped; needs @mosetta/server-action Web-API port`);
|
|
530
|
+
continue;
|
|
531
|
+
}
|
|
532
|
+
const { s } = item;
|
|
533
|
+
addWatch(s.watchFiles);
|
|
534
|
+
writeJs(`private/modules/${s.full}/${s.full}.js`, s.jsCode, s.map);
|
|
535
|
+
// the facet's wasm imports travel as assets next to the monolith: the runner will declare
|
|
536
|
+
// them as bundle modules under the same relative names
|
|
537
|
+
for (const [assetName, srcFile] of s.wasmAssets) {
|
|
538
|
+
out.set(`private/modules/${s.full}/${assetName}`, fileSystem.readFile(srcFile));
|
|
539
|
+
}
|
|
540
|
+
if (s.offers?.permissions?.length) {
|
|
541
|
+
const list = actionPermissionsByNamespace.get(sm.namespace) ?? [];
|
|
542
|
+
list.push(...s.offers.permissions);
|
|
543
|
+
actionPermissionsByNamespace.set(sm.namespace, list);
|
|
490
544
|
}
|
|
545
|
+
recordPrivate(s.full, { namespace: sm.namespace, name: sm.name, type: 'server', version: sm.version },
|
|
546
|
+
s.offers ? { offers: s.offers } : {}, [...s.wasmAssets.keys()]);
|
|
547
|
+
record(sm, 'server', s.jsCode.length, 'private'
|
|
548
|
+
+ (s.wasmAssets.size ? `, ${s.wasmAssets.size} wasm asset(s)` : ''));
|
|
549
|
+
serverCount++;
|
|
491
550
|
}
|
|
492
551
|
for (const [namespace, declared] of actionPermissionsByNamespace) {
|
|
493
552
|
let entry = distributionByNamespace.get(namespace);
|
|
@@ -523,9 +582,11 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
|
|
|
523
582
|
let ssrCount = 0;
|
|
524
583
|
const scriptDirs = new Set(mods.filter((m) => m.type === 'script').map((m) => path.dirname(m.file)));
|
|
525
584
|
const ssrRoots = mods.filter((m) => m.type === 'component' && scriptDirs.has(path.dirname(m.file)));
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
585
|
+
const builtSsrRoots = await mapLimit(ssrRoots, concurrency, (am) => memo(`ssr:${fullTileName(am)}`,
|
|
586
|
+
() => buildSsrModule(fileSystem, am, { resolver, mode, buildConfig, engine, sourceBase: root, frameworkDir })));
|
|
587
|
+
for (let i = 0; i < ssrRoots.length; i++) {
|
|
588
|
+
const am = ssrRoots[i];
|
|
589
|
+
const s = builtSsrRoots[i];
|
|
529
590
|
if (s.watchFile) watchFiles.add(s.watchFile);
|
|
530
591
|
addWatch(s.watchFiles);
|
|
531
592
|
writeJs(`private/modules/${s.full}/${s.full}.js`, s.jsCode, s.map);
|
package/src/buildModules.mjs
CHANGED
|
@@ -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 {
|
|
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
|
|
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 =
|
|
105
|
+
const map = shiftedMap ? normalizeSourcemap(shiftedMap, sourceBase) : null;
|
|
104
106
|
return {
|
|
105
107
|
code,
|
|
106
108
|
map,
|
package/src/buildServer.mjs
CHANGED
|
@@ -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:
|
|
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',
|
package/src/fileSystem.mjs
CHANGED
|
@@ -67,3 +67,94 @@ export class FileSystem {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
}
|
|
70
|
+
|
|
71
|
+
function memoResult(map, key, compute) {
|
|
72
|
+
let entry = map.get(key);
|
|
73
|
+
if (!entry) {
|
|
74
|
+
try {
|
|
75
|
+
entry = { ok: true, value: compute() };
|
|
76
|
+
} catch (error) {
|
|
77
|
+
entry = { ok: false, error };
|
|
78
|
+
}
|
|
79
|
+
map.set(key, entry);
|
|
80
|
+
}
|
|
81
|
+
if (!entry.ok) throw entry.error;
|
|
82
|
+
return entry.value;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Per-build read-only snapshot over any `FileSystem` port.
|
|
87
|
+
*
|
|
88
|
+
* A multi-tile palette frequently probes and reads the same shared files, symlinks, and
|
|
89
|
+
* `package.json` manifests hundreds of thousands of times during one `build()`. Wrapping the port
|
|
90
|
+
* for the duration of a single `build()` eliminates redundant OS syscalls and repeated `JSON.parse`
|
|
91
|
+
* calls while staying completely fresh across subsequent `dev` rebuilds (discarded on return).
|
|
92
|
+
*/
|
|
93
|
+
export class SnapshotFileSystem extends FileSystem {
|
|
94
|
+
#inner;
|
|
95
|
+
#exists = new Map();
|
|
96
|
+
#isDir = new Map();
|
|
97
|
+
#realPath = new Map();
|
|
98
|
+
#readDir = new Map();
|
|
99
|
+
#readFile = new Map();
|
|
100
|
+
#readJson = new Map();
|
|
101
|
+
#mtimeMs = new Map();
|
|
102
|
+
|
|
103
|
+
constructor(inner) {
|
|
104
|
+
super();
|
|
105
|
+
this.#inner = inner instanceof SnapshotFileSystem ? inner.#inner : inner;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
exists(file) {
|
|
109
|
+
if (this.#exists.has(file)) return this.#exists.get(file);
|
|
110
|
+
const value = this.#inner.exists(file);
|
|
111
|
+
this.#exists.set(file, value);
|
|
112
|
+
return value;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
isDirectory(dir) {
|
|
116
|
+
if (this.#isDir.has(dir)) return this.#isDir.get(dir);
|
|
117
|
+
const value = this.#inner.isDirectory(dir);
|
|
118
|
+
this.#isDir.set(dir, value);
|
|
119
|
+
return value;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
realPath(file) {
|
|
123
|
+
return memoResult(this.#realPath, file, () => this.#inner.realPath(file));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
readDir(dir) {
|
|
127
|
+
return memoResult(this.#readDir, dir, () => this.#inner.readDir(dir));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* @param {string} file
|
|
132
|
+
* @param {string | null} [encoding]
|
|
133
|
+
*/
|
|
134
|
+
readFile(file, encoding = null) {
|
|
135
|
+
const key = `${encoding ?? ''}\0${file}`;
|
|
136
|
+
return memoResult(this.#readFile, key, () => this.#inner.readFile(file, encoding));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
readJson(file) {
|
|
140
|
+
return memoResult(this.#readJson, file, () => JSON.parse(this.readFile(file, 'utf8')));
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
mtimeMs(file) {
|
|
144
|
+
if (this.#mtimeMs.has(file)) return this.#mtimeMs.get(file);
|
|
145
|
+
const value = this.#inner.mtimeMs(file);
|
|
146
|
+
this.#mtimeMs.set(file, value);
|
|
147
|
+
return value;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Create a fresh per-build snapshot wrapping `fileSystem`.
|
|
153
|
+
*
|
|
154
|
+
* @template T
|
|
155
|
+
* @param {T} fileSystem
|
|
156
|
+
* @returns {SnapshotFileSystem}
|
|
157
|
+
*/
|
|
158
|
+
export function snapshotFileSystem(fileSystem) {
|
|
159
|
+
return new SnapshotFileSystem(fileSystem);
|
|
160
|
+
}
|
|
@@ -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
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
111
|
+
*
|
|
112
|
+
* @param {string} code
|
|
113
|
+
* @param {string | null} [mapText]
|
|
114
|
+
* @returns {{ code: string; map: string | null }}
|
|
11
115
|
*/
|
|
12
|
-
export function
|
|
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
|
-
|
|
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 (
|
|
47
|
-
|
|
48
|
-
|
|
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
|
-
|
|
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
|
}
|