@mosetta/build 0.0.38 → 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.
@@ -1,117 +1,152 @@
1
- import commonjs from '@rollup/plugin-commonjs';
2
1
  import { path } from './nodeApi.mjs';
3
2
  import { packageDirOf } from './packageMeta.mjs';
4
3
  import { fullTileName } from './moduleName.mjs';
5
4
  import { cssIntercept } from './plugins/cssIntercept.mjs';
6
5
  import { assets } from './plugins/assets.mjs';
7
- import { defineEnv } from './plugins/defineEnv.mjs';
8
- import { portResolve } from './plugins/portResolve.mjs';
6
+ import { portResolveClient } from './plugins/portResolveClient.mjs';
7
+ import { rewriteDynamicImportsWithMap } from './plugins/dynamicImport.mjs';
9
8
  import { processCss } from './css.mjs';
10
9
  import { resolveSpecifier } from './specifiers.mjs';
11
- import { assertNamedRegister } from './buildConfig.mjs';
12
- import { sourcemapPathTransformFor } from './sourcemap.mjs';
13
- import { transformTs, minifyChunk } from './plugins/transform.mjs';
10
+ import { applyEsbuildOptions, assertFactoryArtifact, userPluginsFor } from './buildConfig.mjs';
11
+ import { normalizeSourcemap } from './sourcemap.mjs';
14
12
  import { mtimeStamp } from './artifactCache.mjs';
15
13
 
16
- // Every bare specifier (npm AND framework packages) is external — they become
17
- // import-map-resolved System deps. Relative/absolute imports are bundled into the module.
18
- // css is NEVER external: rollup consults `external` BEFORE plugin resolveId hooks, and a bare
19
- // css import ('@mosetta/ui/ui.css') must reach cssIntercept, not the dep closure.
20
- const isExternal = (id) =>
21
- !id.endsWith('.css') && !id.startsWith('.') && !path.isAbsolute(id) && !id.startsWith('\0');
14
+ const CLIENT_TARGET = 'es2020';
15
+ const CLIENT_TSCONFIG = { compilerOptions: { experimentalDecorators: true } };
22
16
 
23
- // external maps in EVERY mode: the map is a separate artifact the build places into
24
- // the store's private counterpart; dev DX comes from the dev server's SourceMap response header
25
- export const sourcemapFor = () => true;
26
-
27
- // user hooks: plugins from mosetta.build.mjs land BEFORE the framework ones (React
28
- // Compiler wants original JSX, an scss plugin must run before cssIntercept), the rollupOptions
29
- // escape hatch transforms the composed INPUT options (output shape is protocol — not exposed)
30
- export function userPluginsFor(buildConfig, target, mode) {
31
- return buildConfig?.clientPlugins?.({ target, mode }) ?? [];
32
- }
33
- function applyOptionsHook(buildConfig, options, target, mode) {
34
- return buildConfig?.rollupOptions?.(options, { target, mode }) ?? options;
35
- }
17
+ /**
18
+ * Bundle one client entry (tile side or external dependency) into a passive factory artifact:
19
+ *
20
+ * (globalThis.__mosetta__=globalThis.__mosetta__||{})["<full-id>"]=[function(require,exports,module,__meta){
21
+ * ...cjs output...
22
+ * },["<eager-dep-1>",...]];
23
+ *
24
+ * - `banner` shifts sourcemap line numbers automatically; the trailing `},[deps]];` sits after
25
+ * the body so sourcemap mappings remain intact.
26
+ * - Eager dependencies are sorted for byte-for-byte determinism between native esbuild and
27
+ * esbuild-wasm.
28
+ * - Dynamic `import(...)` expressions are rewritten via AST (`acorn`) to `__meta.import(...)`,
29
+ * keeping lazy external packages out of the eager `deps` array while still returning them in
30
+ * `lazyImports` and `rawImports` so the build includes them in the distributive closure.
31
+ */
32
+ export async function generateFactory({
33
+ engine,
34
+ fileSystem,
35
+ resolver,
36
+ sourceBase,
37
+ baseDir,
38
+ input,
39
+ name,
40
+ extraPlugins = [],
41
+ wantSourcemap = true,
42
+ resolveExternal,
43
+ minified = false,
44
+ buildConfig = null,
45
+ target = 'module',
46
+ mode = 'development',
47
+ watched = new Set(),
48
+ }) {
49
+ const eagerExternalMap = new Map(); // rawSpecifier -> fullId
50
+ const lazyExternalMap = new Map(); // rawSpecifier -> fullId (from dynamic import())
51
+ const nodeEnv = mode === 'production' ? 'production' : 'development';
52
+ const banner = `(globalThis.__mosetta__=globalThis.__mosetta__||{})[${JSON.stringify(name)}]=[function(require,exports,module,__meta){`;
36
53
 
37
- // production minify is a render-chunk post-pass — mangling touches only artifact-internal scope:
38
- // the System.register name, dep specifiers and export names are string literals, so the
39
- // cross-artifact runtime linkage survives untouched
40
- async function generateSystem({ engine, sourceBase, input, name, plugins, sourcemap = 'inline', resolveExternal, minified = false, buildConfig = null, target = 'module', mode = 'development' }) {
41
- const bundle = await engine.rollup(applyOptionsHook(buildConfig, {
42
- input,
43
- external: isExternal,
44
- plugins,
45
- onwarn(w, warn) {
46
- if (w.code === 'UNRESOLVED_IMPORT' || w.code === 'CIRCULAR_DEPENDENCY') return;
47
- warn(w);
54
+ const options = await applyEsbuildOptions(buildConfig, {
55
+ entryPoints: [input],
56
+ bundle: true,
57
+ write: false,
58
+ format: 'cjs',
59
+ platform: 'browser',
60
+ target: CLIENT_TARGET,
61
+ jsx: 'automatic',
62
+ tsconfigRaw: CLIENT_TSCONFIG,
63
+ minify: minified,
64
+ sourcemap: wantSourcemap ? 'external' : false,
65
+ sourcesContent: wantSourcemap,
66
+ outdir: '.',
67
+ ...(sourceBase ? { absWorkingDir: sourceBase } : {}),
68
+ define: {
69
+ 'process.env.NODE_ENV': JSON.stringify(nodeEnv),
70
+ 'import.meta.url': '__meta.url',
48
71
  },
49
- }, target, mode));
50
- // output.paths rewrites every emitted external `bare` → version-qualified full-id,
51
- // and records the (bare → full) of externals actually rendered into this artifact.
52
- const externalMap = new Map();
53
- const paths = (id) => {
54
- const full = (resolveExternal && resolveExternal(id)) || id;
55
- externalMap.set(id, full);
56
- return full;
57
- };
58
- // NAMED register (SSR epic stage 1): `System.register('<full-id>', …)` — the artifact is
59
- // self-identified, executable by the server mini-System AND concatenable into bundles later.
60
- // The client keeps loading by URL: the named-register extra links the URL load to the name
61
- // (one instance), so the browser path needs no changes.
62
- const { output } = await bundle.generate({
63
- format: 'system', name, exports: 'named', sourcemap, paths,
64
- sourcemapPathTransform: sourcemapPathTransformFor(sourceBase),
65
- plugins: minified ? [minifyChunk(engine)] : [],
66
- });
67
- const watchFiles = bundle.watchFiles.slice();
68
- await bundle.close();
69
- const chunk = output.find((o) => o.type === 'chunk');
70
- assertNamedRegister(chunk.code, name, buildConfig); // protocol invariant
71
- // sourcemap:'inline' embeds the map in chunk.code; true → external map returned separately
72
- const map = sourcemap === true && chunk.map ? chunk.map.toString() : null;
72
+ banner: { js: banner },
73
+ plugins: [
74
+ ...userPluginsFor(buildConfig, target, mode),
75
+ ...extraPlugins,
76
+ portResolveClient(fileSystem, resolver, baseDir, {
77
+ externalizeBare: true,
78
+ resolveExternal,
79
+ eagerExternalMap,
80
+ lazyExternalMap,
81
+ watched,
82
+ }),
83
+ ],
84
+ logLevel: 'silent',
85
+ }, target, mode);
86
+
87
+ const result = await engine.bundle(options);
88
+ const jsFile = result.outputFiles.find((f) => !f.path.endsWith('.map'));
89
+ const mapFile = result.outputFiles.find((f) => f.path.endsWith('.map'));
90
+
91
+ // Any dependency imported both statically and dynamically is eager, not lazy.
92
+ const eagerSet = new Set(eagerExternalMap.values());
93
+ const eagerDeps = [...eagerSet].sort();
94
+ const lazyDeps = [...new Set(lazyExternalMap.values())].filter((id) => !eagerSet.has(id)).sort();
95
+ const rawImports = [...new Set([...eagerExternalMap.keys(), ...lazyExternalMap.keys()])].sort();
96
+
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.
99
+ const wrapped = `${jsFile.text}\n},${JSON.stringify(eagerDeps)}];\n`;
100
+ const rawMap = wantSourcemap && mapFile ? mapFile.text : null;
101
+ const { code, map: shiftedMap } = rewriteDynamicImportsWithMap(wrapped, rawMap);
102
+
103
+ assertFactoryArtifact(code, name, buildConfig);
104
+
105
+ const map = shiftedMap ? normalizeSourcemap(shiftedMap, sourceBase) : null;
73
106
  return {
74
- code: chunk.code,
107
+ code,
75
108
  map,
76
- imports: [...externalMap.values()], // full-ids (the artifact's resolved dependencies)
77
- rawImports: [...externalMap.keys()], // bare specifiers (for closure traversal)
78
- watchFiles,
109
+ imports: eagerDeps,
110
+ lazyImports: lazyDeps,
111
+ rawImports,
112
+ watchFiles: [...watched],
79
113
  };
80
114
  }
81
115
 
82
116
  /**
83
- * Build one module to a System artifact. Returns code + descriptor (no disk write).
117
+ * Build one client tile side to a factory artifact. Returns code + descriptor (no disk write).
84
118
  */
85
119
  export async function buildModule(fileSystem, mod, { resolver, mode = 'development', buildConfig = null, engine, sourceBase, assetExtensions = [] } = {}) {
86
120
  const full = fullTileName(mod);
87
- // externals resolve from the MODULE's own package — the full-id rewritten into the
88
- // artifact must match what the closure walk resolves and builds from the same context
89
121
  const baseDir = path.dirname(mod.file);
90
122
  const cssRefs = [];
91
123
  const jsAssets = new Map(); // out -> srcAbs (assets imported from JS)
92
- const { code, map, imports, rawImports, watchFiles } = await generateSystem({
124
+ const watched = new Set();
125
+
126
+ const { code, map, imports, lazyImports, rawImports, watchFiles } = await generateFactory({
93
127
  engine,
128
+ fileSystem,
129
+ resolver,
94
130
  sourceBase,
131
+ baseDir,
95
132
  input: mod.file,
96
133
  name: full,
97
- plugins: [
98
- ...userPluginsFor(buildConfig, 'module', mode),
99
- defineEnv(mode), assets(jsAssets, assetExtensions, fileSystem), cssIntercept(cssRefs, resolver, baseDir), transformTs(engine),
100
- // LAST: rollup's built-in resolver used to work here, and it runs after all plugins —
101
- // placing it earlier would intercept css, assets and the transpiler
102
- portResolve(fileSystem, resolver, baseDir),
134
+ extraPlugins: [
135
+ assets(jsAssets, assetExtensions, fileSystem, baseDir, watched),
136
+ cssIntercept(cssRefs, resolver, baseDir, watched),
103
137
  ],
104
- sourcemap: sourcemapFor(mode),
138
+ wantSourcemap: true,
105
139
  resolveExternal: (id) => resolveSpecifier(fileSystem, resolver, id, baseDir)?.full,
106
140
  minified: mode === 'production',
107
141
  buildConfig,
108
142
  target: 'module',
109
143
  mode,
144
+ watched,
110
145
  });
111
146
 
112
147
  // css partition: a file from the module's own package is authored styles (a scoped per-module
113
- // artifact, as before); a file from a FOREIGN package is dependency css and leaves as one
114
- // shared artifact per closure (emitted by build()). realpath — because of workspace symlinks.
148
+ // artifact); a file from a FOREIGN package is dependency css and leaves as one shared artifact
149
+ // per closure (emitted by build()). realpath — because of workspace symlinks.
115
150
  const ownPkg = packageDirOf(fileSystem, fileSystem.realPath(mod.file));
116
151
  const ownCss = [];
117
152
  const sharedCss = []; // {file, specifier: '<pkg>/<rel>', version}
@@ -149,17 +184,9 @@ export async function buildModule(fileSystem, mod, { resolver, mode = 'developme
149
184
  version: mod.version,
150
185
  },
151
186
  assets: [...(css ? [`${full}.css`] : []), ...allAssets.keys()],
152
- dependencies: imports, // version-qualified full-ids (declared intent)
153
- // A PAGE ROOT is a component facet only by file type: it takes the page's tree as a prop,
154
- // it is what `page.reference` names, and it can never be someone's child — so the editor
155
- // must not offer it as a block to place. Read off the import the facet actually made:
156
- // the binding is emitted as a property access on the imported namespace, which survives
157
- // minification (property names are not renamed), and merely importing the definer IS the
158
- // declaration. Absent rather than false — descriptors stay free of noise.
187
+ dependencies: imports, // version-qualified full-ids (eager dependencies)
188
+ ...(lazyImports.length ? { lazyDependencies: lazyImports } : {}),
159
189
  ...(ROOT_DEFINER_RE.test(code) ? { isRoot: true } : {}),
160
- // an INTERNAL block (a tool's own — an editor panel, the editor's fallback): placed by the
161
- // platform's pages, never offered to an author. The same reading, off the marker the facet
162
- // imported — a wrapper over any definer, so a fallback is marked the way a component is
163
190
  ...(INTERNAL_MARK_RE.test(code) ? { internal: true } : {}),
164
191
  };
165
192
 
@@ -171,38 +198,20 @@ const ROOT_DEFINER_RE = /\.defineRootComponentSide\b/;
171
198
  /** …and `markInternalTile(...)` — a block the picker leaves out */
172
199
  const INTERNAL_MARK_RE = /\.markInternalTile\b/;
173
200
 
174
- const VIRTUAL_PROLOG = '\0mosetta-loader-prolog-entry';
175
-
176
- // identical across modules, roots and rebuilds — built once per mode, but VALIDATED by the
177
- // mtimes of its own source graph: the dev server process is long-lived, and a checkout (or
178
- // framework-source edit in this repo) must not keep serving a stale prolog until restart
179
- let prologCache = null; // { mode, jsCode, watchFiles, stamp }
201
+ // identical across modules, roots and rebuilds — built once per mode, validated by source mtimes
202
+ let loaderCache = null; // { mode, configStamp, jsCode, watchFiles, stamp }
180
203
 
181
204
  /**
182
- * The loader PROLOG: the idempotent resolver installation
183
- * (`installResolverFromPage()`) bundled as a self-contained IIFE. build() concatenates it after
184
- * `systemjs + named-register` into the `system.js` co-located with every script facet — the
185
- * prolog runs before any `systemjs-module` entry is processed, so the resolve hook is always
186
- * installed first.
205
+ * The self-contained page LOADER (`loader.js`) co-located with every script facet: installs the
206
+ * factory module loader (`@mosetta/runtime/loader`) from `#pageContent`, boots all
207
+ * `<script type="mosetta-module">` entries with native SRI, and in dev attaches the SSE livereload
208
+ * + error overlay companion. Replaces `system.js + named-register.js + prolog`.
187
209
  */
188
- export async function buildLoaderProlog(fileSystem, { resolver, mode = 'development', buildConfig = null, engine } = {}) {
189
- if (prologCache && prologCache.mode === mode
190
- && prologCache.configStamp === (buildConfig?.stamp ?? 'none')
191
- && mtimeStamp(fileSystem, prologCache.watchFiles) === prologCache.stamp) return prologCache;
192
- // livereload is BUILD knowledge: the dev prolog itself listens to the provider's SSE
193
- // (the dev provider's /__mosetta__/reload endpoint, base — from the envelope), prod is clean
194
- // by construction; the cross-cutting machinery (runner/env/shells) knows nothing about dev
195
- // mode. The guard — one subscription per realm (as many prologs as script facets).
196
- // The page's dev companions: SSE reload and the ERROR OVERLAY. The overlay lives here rather
197
- // than as a distributive module precisely because it is needed when the build is BROKEN: there
198
- // are no new artifacts, yet the prolog arrived with the last successful build and keeps
199
- // working. The status sits next to the artifact tree and survives a build failure.
200
- // ONE connection per ORIGIN, not per realm. A browser gives an origin about six sockets and
201
- // SHARES them across tabs; an EventSource holds one of them for its whole life. The editor
202
- // alone is three realms (the page plus a preview frame per canvas), so two open tabs used to
203
- // pin six permanent subscriptions and the origin ran dry — a sibling frame's document could
204
- // then never load (a gray canvas, an eternal spinner). So: whoever wins the web lock talks to
205
- // the server and fans the news out over a BroadcastChannel; every other realm only listens.
210
+ export async function buildLoader(fileSystem, { resolver, mode = 'development', buildConfig = null, engine, sourceBase } = {}) {
211
+ if (loaderCache && loaderCache.mode === mode
212
+ && loaderCache.configStamp === (buildConfig?.stamp ?? 'none')
213
+ && mtimeStamp(fileSystem, loaderCache.watchFiles) === loaderCache.stamp) return loaderCache;
214
+
206
215
  const livereloadSnippet = mode === 'development'
207
216
  ? 'try {\n'
208
217
  + ' if (!globalThis.__mosettaReload) {\n'
@@ -227,9 +236,6 @@ export async function buildLoaderProlog(fileSystem, { resolver, mode = 'developm
227
236
  + ' };\n'
228
237
  + ' };\n'
229
238
  + " var esc = function (s) { return String(s).replace(/[&<>]/g, function (c) { return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]; }); };\n"
230
- // the fan-out: news reaches every realm of the origin over the channel, so only the realm
231
- // holding the lock ever opens a socket. A late-arriving realm asks for the last status
232
- // instead of fetching it (`ask`), and the leader answers off its own memory
233
239
  + " var chan = typeof BroadcastChannel === 'function' ? new BroadcastChannel('mosetta-dev') : null;\n"
234
240
  + ' var leading = false;\n'
235
241
  + ' var last = null;\n'
@@ -250,9 +256,6 @@ export async function buildLoaderProlog(fileSystem, { resolver, mode = 'developm
250
256
  + ' }\n'
251
257
  + ' apply(msg);\n'
252
258
  + ' };\n'
253
- // ONE stream, no polling: the build status rides the same SSE (`event: status`, sent on
254
- // connect and then on every change), so the browser never spends a second socket — and
255
- // never learns about a broken build a whole second late either
256
259
  + ' var lead = function () {\n'
257
260
  + ' leading = true;\n'
258
261
  + " var src = new EventSource(new URL('__mosetta__/reload', base).href);\n"
@@ -266,10 +269,6 @@ export async function buildLoaderProlog(fileSystem, { resolver, mode = 'developm
266
269
  + ' tell({ status: status });\n'
267
270
  + ' });\n'
268
271
  + ' };\n'
269
- // the lock is held for the life of the realm and released by the browser when the realm
270
- // dies, so a closed (or reloaded) leader hands the connection to the next realm by itself.
271
- // Without a channel there is nobody to fan out to, and without locks nobody to elect —
272
- // then every realm speaks for itself, as it did before
273
272
  + " var locks = typeof navigator === 'object' && navigator ? navigator.locks : null;\n"
274
273
  + ' if (chan && locks && typeof locks.request === "function") {\n'
275
274
  + " locks.request('mosetta-dev-channel', function () {\n"
@@ -283,46 +282,49 @@ export async function buildLoaderProlog(fileSystem, { resolver, mode = 'developm
283
282
  + ' }\n'
284
283
  + '} catch (e) { /* dev-only, optional */ }\n'
285
284
  : '';
285
+
286
286
  const bootstrapEntry = resolver.resolveFramework('@mosetta/runtime/bootstrap');
287
287
  const source =
288
- `import { installResolverFromPage } from ${JSON.stringify(bootstrapEntry)};\n`
289
- + `const { base } = installResolverFromPage();\n${livereloadSnippet}`;
290
- const bundle = await engine.rollup({
291
- input: VIRTUAL_PROLOG,
288
+ `import { bootPageLoader } from ${JSON.stringify(bootstrapEntry)};\n`
289
+ + `const { base } = bootPageLoader();\n${livereloadSnippet}`;
290
+ const watched = new Set();
291
+ const baseDir = path.dirname(bootstrapEntry);
292
+ const nodeEnv = mode === 'production' ? 'production' : 'development';
293
+
294
+ const result = await engine.bundle(await applyEsbuildOptions(buildConfig, {
295
+ stdin: {
296
+ contents: source,
297
+ resolveDir: baseDir,
298
+ sourcefile: 'mosetta-loader.entry.ts',
299
+ loader: 'ts',
300
+ },
301
+ bundle: true,
302
+ write: false,
303
+ format: 'iife',
304
+ platform: 'browser',
305
+ target: CLIENT_TARGET,
306
+ tsconfigRaw: CLIENT_TSCONFIG,
307
+ minify: mode === 'production',
308
+ ...(sourceBase ? { absWorkingDir: sourceBase } : {}),
309
+ define: { 'process.env.NODE_ENV': JSON.stringify(nodeEnv) },
292
310
  plugins: [
293
- {
294
- name: 'mosetta-loader-prolog',
295
- resolveId: (id) => (id === VIRTUAL_PROLOG ? id : null),
296
- load: (id) => (id === VIRTUAL_PROLOG ? source : null),
297
- },
298
- ...userPluginsFor(buildConfig, 'prolog', mode),
299
- defineEnv(mode),
300
- portResolve(fileSystem, resolver, path.dirname(bootstrapEntry)),
301
- commonjs(),
302
- transformTs(engine),
311
+ ...userPluginsFor(buildConfig, 'loader', mode),
312
+ portResolveClient(fileSystem, resolver, baseDir, {
313
+ externalizeBare: false,
314
+ watched,
315
+ }),
303
316
  ],
304
- onwarn(w, warn) {
305
- if (w.code === 'CIRCULAR_DEPENDENCY') return;
306
- warn(w);
307
- },
308
- });
309
- const { output } = await bundle.generate({
310
- format: 'iife', name: 'mosettaLoaderProlog', plugins: mode === 'production' ? [minifyChunk(engine)] : [],
311
- });
312
- const watchFiles = bundle.watchFiles.slice();
313
- // the GENERATOR is part of the prolog's graph: the livereload/overlay snippet is authored
314
- // right here as a string, invisible to rollup — without this line an edit to it would keep
315
- // serving stale cached prologs (in-memory AND on-disk) until the cache is wiped by hand.
316
- // Non-file realms (an in-browser build) skip it: a missing path stamps as a constant.
317
+ logLevel: 'silent',
318
+ }, 'loader', mode));
319
+
320
+ const watchFiles = [...watched];
317
321
  if (import.meta.url.startsWith('file:')) watchFiles.push(new URL(import.meta.url).pathname);
318
- await bundle.close();
319
- prologCache = {
322
+ loaderCache = {
320
323
  mode,
321
- jsCode: output.find((o) => o.type === 'chunk').code,
324
+ configStamp: buildConfig?.stamp ?? 'none',
325
+ jsCode: result.outputFiles[0].text,
322
326
  watchFiles,
323
327
  stamp: mtimeStamp(fileSystem, watchFiles),
324
- configStamp: buildConfig?.stamp ?? 'none',
325
328
  };
326
- return prologCache;
329
+ return loaderCache;
327
330
  }
328
-
@@ -4,6 +4,7 @@ import { portResolveEsbuild } from './plugins/portResolveEsbuild.mjs';
4
4
  import { monolithCompat, monolithCompatOptions } from './plugins/monolithCompat.mjs';
5
5
  import { MONOLITH_CONDITIONS } from './conditions.mjs';
6
6
  import { mtimeStamp } from './artifactCache.mjs';
7
+ import { applyEsbuildOptions, userPluginsFor } from './buildConfig.mjs';
7
8
 
8
9
  // Private monoliths are built by esbuild (self-contained ESM, everything inside), but it no
9
10
  // longer resolves BY ITSELF — all I/O goes through the port via `portResolveEsbuild`, and the
@@ -16,12 +17,13 @@ import { mtimeStamp } from './artifactCache.mjs';
16
17
  // `@mosetta/server` and react). It used to be derived from `import.meta.url` — and that broke
17
18
  // exactly like the `fileSystem`/`engine` defaults did: the binding came from the CODE's location
18
19
  // instead of being supplied from outside, and did not survive bundling into an isolate.
19
- const portOptions = (fileSystem, resolver, sourceBase, frameworkDir, wasmAssets = null, watched = null) => ({
20
+ const portOptions = (fileSystem, resolver, sourceBase, frameworkDir, wasmAssets = null, watched = null, userPlugins = []) => ({
20
21
  plugins: [
22
+ ...userPlugins,
21
23
  ...(wasmAssets ? [wasmAssetsPlugin(resolver, frameworkDir, wasmAssets)] : []),
22
24
  // workerd compatibility — BEFORE the port resolver: package substitutions and onLoad patches
23
25
  // must fire before the port resolves/reads the files itself
24
- monolithCompat(fileSystem, resolver),
26
+ monolithCompat(),
25
27
  portResolveEsbuild(fileSystem, resolver, frameworkDir, MONOLITH_CONDITIONS, watched),
26
28
  ],
27
29
  ...monolithCompatOptions(),
@@ -71,15 +73,15 @@ const pickOutputs = (result) => ({
71
73
  // which the static Worker-Loader glue imports.
72
74
  // user hook: transforms the composed esbuild options of a server-side monolith build
73
75
  function applyServerHook(buildConfig, options, target, mode) {
74
- return buildConfig?.serverEsbuild?.(options, { target, mode }) ?? options;
76
+ return applyEsbuildOptions(buildConfig, options, target, mode);
75
77
  }
76
78
 
77
79
  export async function buildServerModule(fileSystem, { file, name, type, namespace, version }, { resolver, mode = 'development', buildConfig = null, engine, sourceBase, frameworkDir } = {}) {
78
80
  const full = fullTileName({ namespace, type, name, version });
79
81
  const wasmAssets = new Map(); // asset name -> absolute source file
80
82
  const watched = new Set(); // the monolith's source graph — for invalidation and watching
81
- const result = await engine.bundle(applyServerHook(buildConfig, {
82
- ...portOptions(fileSystem, resolver, sourceBase, frameworkDir, wasmAssets, watched),
83
+ const result = await engine.bundle(await applyServerHook(buildConfig, {
84
+ ...portOptions(fileSystem, resolver, sourceBase, frameworkDir, wasmAssets, watched, userPluginsFor(buildConfig, 'server', mode)),
83
85
  entryPoints: [file],
84
86
  bundle: true,
85
87
  format: 'esm',
@@ -129,11 +131,11 @@ export async function buildSsrModule(fileSystem, { file, name, namespace, versio
129
131
  };
130
132
  }
131
133
  const watched = new Set();
132
- const result = await engine.bundle(applyServerHook(buildConfig, {
133
- ...portOptions(fileSystem, resolver, sourceBase, frameworkDir, null, watched),
134
+ const result = await engine.bundle(await applyServerHook(buildConfig, {
135
+ ...portOptions(fileSystem, resolver, sourceBase, frameworkDir, null, watched, userPluginsFor(buildConfig, 'ssr', mode)),
134
136
  ...(custom
135
137
  ? { entryPoints: [grain] }
136
- : { 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' } }),
137
139
  bundle: true,
138
140
  format: 'esm',
139
141
  platform: 'neutral',
@@ -10,7 +10,7 @@
10
10
  * That is why the policy lives here, apart from the mechanics, and is visible as a whole.
11
11
  */
12
12
 
13
- // Client artifacts execute in the browser (SystemJS) AND in ssr isolates (MiniSystem, workerd) —
13
+ // Client artifacts execute in the browser AND in ssr isolates (`@mosetta/runtime/loader`, workerd) —
14
14
  // it is the same artifact set. The browser ESM branch suits both environments: it contains no
15
15
  // node specifics by construction.
16
16
  export const CLIENT_CONDITIONS = ['browser', 'import'];
@@ -52,8 +52,7 @@ export function buildConfigFrom(ns) {
52
52
  return {
53
53
  file: 'mosetta.build.mjs',
54
54
  stamp: 'recomposed', // the composition's identity already includes the config module's hash
55
- clientPlugins: asFn(cfg.clientPlugins, 'clientPlugins'),
56
- serverEsbuild: asFn(cfg.serverEsbuild, 'serverEsbuild'),
57
- rollupOptions: asFn(cfg.rollupOptions, 'rollupOptions'),
55
+ plugins: asFn(cfg.plugins, 'plugins'),
56
+ esbuildOptions: asFn(cfg.esbuildOptions, 'esbuildOptions'),
58
57
  };
59
58
  }
package/src/node.mjs CHANGED
@@ -61,7 +61,7 @@ export class NodeFileSystem extends FileSystem {
61
61
 
62
62
  const buildRequire = createRequire(import.meta.url);
63
63
 
64
- /** a framework file (`systemjs/dist/system.js`, `@mosetta/runtime/bootstrap`) as this installation of the build resolves it */
64
+ /** a framework file (`@mosetta/build`, `@mosetta/runtime/bootstrap`) as this installation of the build resolves it */
65
65
  export function frameworkFileOf(specifier) {
66
66
  return buildRequire.resolve(specifier);
67
67
  }
@@ -29,8 +29,6 @@ export const FRAMEWORK_RESOLUTIONS = [
29
29
  '@mosetta/build',
30
30
  '@mosetta/runtime',
31
31
  '@mosetta/runtime/bootstrap',
32
- 'systemjs/dist/system.js',
33
- 'systemjs/dist/extras/named-register.js',
34
32
  ];
35
33
 
36
34
  const MAX_WALK_UP = 50;
@@ -4,38 +4,45 @@ import { hashedAssetName } from '../hash.mjs';
4
4
  export const ASSET_RE = /\.(png|jpe?g|gif|svg|webp|avif|ico|bmp|woff2?|ttf|eot|otf|mp4|webm|mp3|wav|ogg|pdf)$/i;
5
5
 
6
6
  /**
7
- * Rollup plugin: turn `import x from './img.png'` into a value resolved at runtime by
8
- * @mosetta/runtime's __asset(rel, import.meta.url). Records {src,out} so the asset file can be
9
- * copied co-located with the module. `collected` is a Map(out -> srcAbsPath) (dedup by out name).
7
+ * Esbuild plugin: turn `import x from './img.png'` into a value resolved at runtime by
8
+ * `@mosetta/runtime`'s `__asset(rel, import.meta.url)`. Records `{ out -> srcAbs }` so the asset
9
+ * file is copied co-located with the module.
10
+ *
11
+ * Uses a relative virtual path (via `pluginData.abs` for reading) so dev comments and sourcemaps
12
+ * in non-file namespaces never leak host-specific absolute paths.
10
13
  */
11
- export function assets(collected, extraExtensions, fileSystem) {
12
- // data-level extensibility: `assetExtensions` from mosetta.json widens the built-in
13
- // list — a custom asset type in the simple case needs no rollup plugin at all
14
+ export function assets(collected, extraExtensions, fileSystem, baseDir, watched) {
14
15
  const extraRe = extraExtensions?.length
15
16
  ? new RegExp(`\\.(${extraExtensions.map((e) => e.replace(/^\./, '')).join('|')})$`, 'i')
16
17
  : null;
17
- const isAsset = (source) => ASSET_RE.test(source) || (extraRe && extraRe.test(source));
18
+ const filter = extraRe
19
+ ? new RegExp(`(?:${ASSET_RE.source}|${extraRe.source})`, 'i')
20
+ : ASSET_RE;
21
+
18
22
  return {
19
23
  name: 'mosetta-assets',
20
- async resolveId(source, importer) {
21
- if (!isAsset(source)) return null;
22
- const abs = importer ? path.resolve(path.dirname(importer), source) : path.resolve(source);
23
- return { id: `${abs}?mosetta-asset`, external: false };
24
- },
25
- load(id) {
26
- if (!id.endsWith('?mosetta-asset')) return null;
27
- const abs = id.slice(0, -'?mosetta-asset'.length);
28
- const buf = fileSystem.readFile(abs);
29
- // the asset's name derives from its CONTENT: editing an image changes the name inside the
30
- // artifact, so the file itself must be watched (the id carries a marker suffix, we watch
31
- // the clean path)
32
- this.addWatchFile(abs);
33
- const out = hashedAssetName(abs, buf);
34
- collected.set(out, abs);
35
- return (
36
- `import { __asset } from '@mosetta/runtime';\n` +
37
- `export default __asset(${JSON.stringify('./' + out)}, import.meta.url);\n`
38
- );
24
+ setup(build) {
25
+ build.onResolve({ filter }, (args) => {
26
+ const fromDir = args.resolveDir || baseDir;
27
+ const abs = path.isAbsolute(args.path) ? args.path : path.resolve(fromDir, args.path);
28
+ const rel = path.relative(baseDir, abs).split(path.sep).join('/');
29
+ return { path: rel, namespace: 'mosetta-asset', pluginData: { abs } };
30
+ });
31
+
32
+ build.onLoad({ filter: /.*/, namespace: 'mosetta-asset' }, (args) => {
33
+ const abs = args.pluginData?.abs ?? path.resolve(baseDir, args.path);
34
+ const buf = fileSystem.readFile(abs);
35
+ watched?.add(abs);
36
+ const out = hashedAssetName(abs, buf);
37
+ collected.set(out, abs);
38
+ return {
39
+ contents:
40
+ `import { __asset } from '@mosetta/runtime';\n` +
41
+ `export default __asset(${JSON.stringify('./' + out)}, import.meta.url);\n`,
42
+ loader: 'js',
43
+ resolveDir: baseDir,
44
+ };
45
+ });
39
46
  },
40
47
  };
41
48
  }