@mosetta/build 0.0.37 → 0.0.39

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,28 @@
1
1
  # @mosetta/build
2
2
 
3
+ ## 0.0.39
4
+
5
+ ### Patch Changes
6
+
7
+ - Replace Rollup and SystemJS with a unified esbuild build pipeline, passive factory artifacts (`globalThis.__mosetta__`), unified `@mosetta/runtime/loader` with native browser SRI, and AST-rewritten lazy dynamic `import()` (`__meta.import()` and `lazyDependencies`).
8
+ - Updated dependencies
9
+ - @mosetta/runtime@0.0.39
10
+ - @mosetta/server@0.0.39
11
+ - @mosetta/server-action@0.0.39
12
+ - @mosetta/router@0.0.39
13
+ - @mosetta/tar@0.0.39
14
+
15
+ ## 0.0.38
16
+
17
+ ### Patch Changes
18
+
19
+ - Updated dependencies
20
+ - @mosetta/server@0.0.38
21
+ - @mosetta/router@0.0.38
22
+ - @mosetta/runtime@0.0.38
23
+ - @mosetta/server-action@0.0.38
24
+ - @mosetta/tar@0.0.38
25
+
3
26
  ## 0.0.37
4
27
 
5
28
  ### Patch Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mosetta/build",
3
- "version": "0.0.37",
3
+ "version": "0.0.39",
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",
@@ -17,22 +17,19 @@
17
17
  },
18
18
  "dependencies": {
19
19
  "@pnpm/dependency-path": "^1000.0.9",
20
- "@rollup/plugin-commonjs": "^28.0.9",
21
- "@rollup/plugin-replace": "^6.0.3",
22
- "cjs-module-lexer": "^2.2.0",
20
+ "acorn": "^8.17.0",
23
21
  "postcss": "^8.5.15",
24
22
  "postcss-value-parser": "^4.2.0",
25
23
  "react": "*",
26
24
  "react-dom": "*",
27
25
  "resolve.exports": "^2.0.3",
28
26
  "scheduler": "*",
29
- "systemjs": "^6.15.1",
30
27
  "yaml": "^2.9.0",
31
- "@mosetta/router": "0.0.37",
32
- "@mosetta/runtime": "0.0.37",
33
- "@mosetta/server": "0.0.37",
34
- "@mosetta/server-action": "0.0.37",
35
- "@mosetta/tar": "0.0.37"
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"
36
33
  },
37
34
  "publishConfig": {
38
35
  "access": "public"
@@ -88,3 +88,21 @@ export function applyBrowserEntry(fileSystem, specifier, file, conditions) {
88
88
  if (pkg.name && specifier !== pkg.name) return file; // subpath — the root entry does not apply
89
89
  return path.resolve(dir, pkg.browser);
90
90
  }
91
+
92
+ /**
93
+ * Bare-specifier substitution inside a package's own `browser` map (e.g. `"crypto": false`).
94
+ * Returns `BROWSER_EMPTY`, a substituted absolute path, or `null` when untouched.
95
+ */
96
+ export function applyBrowserBareMap(fileSystem, specifier, fromDir, conditions) {
97
+ if (!conditions?.includes('browser')) return null;
98
+ if (specifier.startsWith('.') || path.isAbsolute(specifier)) return null;
99
+ const dir = packageDirOf(fileSystem, path.join(fromDir, '_'));
100
+ if (!dir) return null;
101
+ const pkg = readPackage(fileSystem, dir);
102
+ const map = pkg?.browser;
103
+ if (!map || typeof map !== 'object' || !Object.hasOwn(map, specifier)) return null;
104
+ const hit = map[specifier];
105
+ if (hit === false) return BROWSER_EMPTY;
106
+ if (typeof hit === 'string' && hit.startsWith('.')) return path.resolve(dir, hit);
107
+ return null;
108
+ }
package/src/build.mjs CHANGED
@@ -1,12 +1,11 @@
1
1
  import { crypto, path } from './nodeApi.mjs';
2
2
  import { packageDirOf } from './packageMeta.mjs';
3
3
  import { discoverRoots, discoverModulesIn, discoverServerModulesIn, discoverRouterModulesIn, discoverPrefabsIn, discoverPagesIn, readConfig } from './discovery.mjs';
4
- import { buildModule, buildLoaderProlog } from './buildModules.mjs';
4
+ import { buildModule, buildLoader } from './buildModules.mjs';
5
5
  import { fullTileName } from './moduleName.mjs';
6
6
  import { buildServerModule, buildSsrModule } from './buildServer.mjs';
7
7
  import { buildDependency } from './buildDependencies.mjs';
8
8
  import { resolveSpecifier, dependencyFullId } from './specifiers.mjs';
9
- import { cjsNamedExports } from './cjsExports.mjs';
10
9
  import { processCss } from './css.mjs';
11
10
  import { INERT_BUILD_CONFIG } from './buildConfig.mjs';
12
11
  import { formatBytes } from './format.mjs';
@@ -18,18 +17,6 @@ import { DocIndex, renderPaletteDocs, renderTileDocs, tileDocHref, tileDocModule
18
17
  export { formatBytes };
19
18
  export { INERT_BUILD_CONFIG } from './buildConfig.mjs';
20
19
 
21
- // core + the named-register extra: artifacts are NAMED System.register('<full-id>', …) bundles
22
- // (SSR epic stage 1) — the extra links a URL load to its name (one instance both ways).
23
- // Read THROUGH THE PORT and lazily: importing the build module must not touch the disk by itself.
24
- let systemjsCache = null;
25
- function readSystemjs(fileSystem, resolver) {
26
- if (!systemjsCache) {
27
- systemjsCache = `${fileSystem.readFile(resolver.resolveFramework('systemjs/dist/system.js'), 'utf8')}\n${
28
- fileSystem.readFile(resolver.resolveFramework('systemjs/dist/extras/named-register.js'), 'utf8')}`;
29
- }
30
- return systemjsCache;
31
- }
32
-
33
20
  // Distributive layout: the in-memory FS (and any disk mirror) is split into two top-level
34
21
  // namespaces so nothing leaks across the trust boundary on deploy:
35
22
  // public/ — client-facing static (modules + co-located loaders, deps, prefabs, pages, manifests).
@@ -165,14 +152,15 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
165
152
  // within an epoch artifacts live by the mtime of their graphs.
166
153
  cache?.epoch([mode, buildConfig?.stamp ?? 'none', resolver.stamp, mtimeStamp(fileSystem, [...watchFiles])].join('|'));
167
154
 
168
- // the loader for script facets: systemjs + named-register + resolver prolog,
169
- // co-located into EVERY script facet's folder — a System.register entry is not executable
170
- // without the loader, and the module folder gives it a version-qualified (immutable) URL.
155
+ // the self-contained loader for script facets (`loader.js`), co-located into EVERY script
156
+ // facet's folder — installs the factory module loader (`@mosetta/runtime/loader`) from
157
+ // `#pageContent`, boots `<script type="mosetta-module">` entries with native SRI, and in dev
158
+ // attaches SSE livereload + error overlay.
171
159
  let loaderJs = null;
172
160
  if (mods.some((m) => m.type === 'script')) {
173
- const prolog = await buildLoaderProlog(fileSystem, { resolver, mode, buildConfig, engine, sourceBase: root });
174
- addWatch(prolog.watchFiles);
175
- loaderJs = `${readSystemjs(fileSystem, resolver)}\n${prolog.jsCode}`;
161
+ const builtLoader = await buildLoader(fileSystem, { resolver, mode, buildConfig, engine, sourceBase: root });
162
+ addWatch(builtLoader.watchFiles);
163
+ loaderJs = builtLoader.jsCode;
176
164
  }
177
165
 
178
166
  // catalog of LOGICAL artifacts for the report (renderBuildReport): distributive → module → facets
@@ -260,7 +248,7 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
260
248
  }
261
249
  out.set(`${PUB}/modules/${r.full}/${r.full}.json`, JSON.stringify(r.descriptor, null, 2));
262
250
  if (r.css) out.set(`${PUB}/modules/${r.full}/${r.full}.css`, r.css);
263
- if (m.type === 'script') out.set(`${PUB}/modules/${r.full}/system.js`, loaderJs);
251
+ if (m.type === 'script') out.set(`${PUB}/modules/${r.full}/loader.js`, loaderJs);
264
252
  let assetBytes = 0;
265
253
  for (const [outName, srcAbs] of r.assets) {
266
254
  const content = fileSystem.readFile(srcAbs);
@@ -313,12 +301,9 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
313
301
  continue;
314
302
  }
315
303
 
316
- // a dependency artifact is cached together with its cjs-export scan: both read the same
317
- // package files and only change together with them
318
- const res = await memo(`dep:${full}`, async () => {
319
- const namedExports = kind === 'builtin' ? null : await cjsNamedExports(fileSystem, resolver, resolvedFile, importerDir);
320
- return buildDependency(fileSystem, { resolver, specifier, resolvedFile, full, namedExports, mode, buildConfig, engine, sourceBase: root });
321
- });
304
+ const res = await memo(`dep:${full}`, () => buildDependency(fileSystem, {
305
+ resolver, resolvedFile, full, mode, buildConfig, engine, sourceBase: root,
306
+ }));
322
307
  addWatch(res.watchFiles);
323
308
  writeJs(`${PUB}/modules/${full}/${full}.js`, res.jsCode, res.map);
324
309
  const depVersion = version;
@@ -327,6 +312,7 @@ export async function build(root, { mode = 'development', log, fileSystem, resol
327
312
  reference: { type: 'package', specifier, version: depVersion },
328
313
  assets: [],
329
314
  dependencies: res.imports,
315
+ ...(res.lazyImports?.length ? { lazyDependencies: res.lazyImports } : {}),
330
316
  integrity: sriOf(`${PUB}/modules/${full}/${full}.js`),
331
317
  // built from the distribution's OWN sources (a workspace package), not a published one: new
332
318
  // bytes under its version are a change that needs a new version — a published package's
@@ -5,18 +5,27 @@
5
5
 
6
6
  /** Inert form: `mosetta.build.mjs` is absent or the caller did not load it. */
7
7
  export const INERT_BUILD_CONFIG = Object.freeze({
8
- file: null, stamp: 'none', clientPlugins: null, serverEsbuild: null, rollupOptions: null,
8
+ file: null, stamp: 'none', plugins: null, esbuildOptions: null,
9
9
  });
10
10
 
11
+ /** User esbuild plugins from `mosetta.build.mjs`, placed BEFORE framework plugins. */
12
+ export function userPluginsFor(buildConfig, target, mode) {
13
+ return buildConfig?.plugins?.({ target, mode }) ?? [];
14
+ }
15
+
16
+ /** User esbuild options escape hatch from `mosetta.build.mjs` (sync or async). */
17
+ export async function applyEsbuildOptions(buildConfig, options, target, mode) {
18
+ return (await buildConfig?.esbuildOptions?.(options, { target, mode })) ?? options;
19
+ }
11
20
 
12
- // The protocol invariant a user plugin must not break: a client artifact is a
13
- // NAMED System.register — the runtime links artifacts by these string names. Checked after every
14
- // generate; quote-agnostic (production minify normalizes quotes).
15
- export function assertNamedRegister(code, full, buildConfig) {
16
- const re = new RegExp(`System\\.register\\(\\s*["']${full.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["']`);
21
+ // The protocol invariant a user plugin must not break: a client artifact is a passive
22
+ // factory registration on `globalThis.__mosetta__["<full-id>"] = [function(...), [...]]`.
23
+ export function assertFactoryArtifact(code, full, buildConfig) {
24
+ const escaped = full.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
25
+ const re = new RegExp(`__mosetta__\\s*\\|\\|\\s*\\{\\}\\s*\\)\\s*\\[\\s*["']${escaped}["']\\s*\\]\\s*=\\s*\\[\\s*function`);
17
26
  if (re.test(code)) return;
18
27
  const hint = buildConfig?.file && buildConfig.stamp !== 'none'
19
28
  ? ` — check your plugins in ${buildConfig.file} (reproduce without them first)`
20
29
  : '';
21
- throw new Error(`artifact ${full} lost its named System.register form${hint}`);
30
+ throw new Error(`artifact ${full} lost its passive factory registration form${hint}`);
22
31
  }
@@ -1,97 +1,46 @@
1
- import commonjs from '@rollup/plugin-commonjs';
2
1
  import { path } from './nodeApi.mjs';
3
2
  import { packageDirOf } from './packageMeta.mjs';
4
- import { defineEnv } from './plugins/defineEnv.mjs';
5
- import { portResolve } from './plugins/portResolve.mjs';
6
3
  import { resolveSpecifier } from './specifiers.mjs';
7
- import { assertNamedRegister } from './buildConfig.mjs';
8
- import { userPluginsFor } from './buildModules.mjs';
9
- import { sourcemapPathTransformFor } from './sourcemap.mjs';
10
- import { transformTs, minifyChunk } from './plugins/transform.mjs';
11
-
12
- const isBareExternal = (id) =>
13
- !id.startsWith('.') && !path.isAbsolute(id) && !id.startsWith('\0');
14
-
15
- const FACADE_ID = '\0mosetta-facade';
4
+ import { generateFactory } from './buildModules.mjs';
16
5
 
17
6
  /**
18
- * Build one external dependency (npm or framework package) into a System artifact.
19
- * Internal/relative imports are bundled; cross-package bare imports stay external
20
- * (→ their own artifacts, resolved by the import map).
21
- * For CJS deps, `namedExports` (enumerated via Node) generates a facade so the artifact
22
- * exposes real named exports (needed for cross-artifact `import { x } from 'pkg'`).
23
- * Returns { full, code, imports } where imports = bare deps of this artifact.
7
+ * Build one external dependency (npm or framework package) into a passive factory artifact.
8
+ * Internal/relative imports are bundled; cross-package bare imports stay external (rewritten to
9
+ * version-qualified full-ids). CJS dependencies (react, react-dom, scheduler) are handled
10
+ * natively by esbuild with no `cjs-module-lexer` facade needed.
24
11
  */
25
- export async function buildDependency(fileSystem, { resolver, specifier, resolvedFile, full, namedExports, mode = 'development', buildConfig = null, engine, sourceBase }) {
12
+ export async function buildDependency(fileSystem, { resolver, resolvedFile, full, mode = 'development', buildConfig = null, engine, sourceBase }) {
26
13
  // this dependency's OWN transitives resolve from ITS package — dockview finds
27
14
  // dockview-core in its .pnpm neighbourhood, no app-level declarations
28
15
  const baseDir = packageDirOf(fileSystem, resolvedFile) ?? path.dirname(resolvedFile);
29
16
  // maps are always EXTERNAL (placed into the private counterpart by writeJs); in dev,
30
17
  // heavy vendor deps (react) skip map generation entirely — nobody debugs their internals
31
18
  const isTS = /\.tsx?$/.test(resolvedFile);
32
- const sourcemap = mode === 'production' || isTS;
33
- const useFacade = Array.isArray(namedExports) && namedExports.length > 0;
34
- const facadeCode = useFacade
35
- ? `import __cjs from ${JSON.stringify(resolvedFile)};\n`
36
- + `export default __cjs;\n`
37
- + `export const { ${namedExports.join(', ')} } = __cjs;\n`
38
- : null;
19
+ const wantSourcemap = mode === 'production' || isTS;
39
20
 
40
- // the rollupOptions escape hatch transforms the composed INPUT options; user
41
- // plugins land after the facade virtual entry (it must keep resolving first) and before the
42
- // framework chain
43
- const optionsHook = (o) => buildConfig?.rollupOptions?.(o, { target: 'dependency', mode }) ?? o;
44
- const bundle = await engine.rollup(optionsHook({
45
- input: useFacade ? FACADE_ID : resolvedFile,
46
- external: isBareExternal,
47
- plugins: [
48
- {
49
- name: 'mosetta-facade',
50
- resolveId(id) {
51
- return id === FACADE_ID ? id : null;
52
- },
53
- load(id) {
54
- return id === FACADE_ID ? facadeCode : null;
55
- },
56
- },
57
- ...userPluginsFor(buildConfig, 'dependency', mode),
58
- defineEnv(mode),
59
- portResolve(fileSystem, resolver, baseDir),
60
- commonjs(),
61
- transformTs(engine), // .js (CJS deps like react) is handled by @rollup/plugin-commonjs
62
- ],
63
- onwarn(w, warn) {
64
- if (w.code === 'UNRESOLVED_IMPORT' || w.code === 'CIRCULAR_DEPENDENCY') return;
65
- warn(w);
66
- },
67
- }));
68
-
69
- // rewrite cross-package externals `bare` → version-qualified full-id
70
- const externalMap = new Map();
71
- const paths = (id) => {
72
- const f = resolveSpecifier(fileSystem, resolver, id, baseDir)?.full || id;
73
- externalMap.set(id, f);
74
- return f;
75
- };
76
- // named register (SSR epic stage 1) — same rationale as buildModules.generateSystem; production
77
- // minify mangles only artifact-internal scope (linkage names are string literals)
78
- const { output } = await bundle.generate({
79
- format: 'system', name: full, exports: 'named', sourcemap, paths,
80
- sourcemapPathTransform: sourcemapPathTransformFor(sourceBase),
81
- plugins: mode === 'production' ? [minifyChunk(engine)] : [],
21
+ const { code, map, imports, lazyImports, rawImports, watchFiles } = await generateFactory({
22
+ engine,
23
+ fileSystem,
24
+ resolver,
25
+ sourceBase,
26
+ baseDir,
27
+ input: resolvedFile,
28
+ name: full,
29
+ wantSourcemap,
30
+ resolveExternal: (id) => resolveSpecifier(fileSystem, resolver, id, baseDir)?.full,
31
+ minified: mode === 'production',
32
+ buildConfig,
33
+ target: 'dependency',
34
+ mode,
82
35
  });
83
- const watchFiles = bundle.watchFiles.slice();
84
- await bundle.close();
85
36
 
86
- const chunk = output.find((o) => o.type === 'chunk');
87
- assertNamedRegister(chunk.code, full, buildConfig); // protocol invariant
88
- const map = sourcemap === true && chunk.map ? chunk.map.toString() : null;
89
37
  return {
90
38
  full,
91
- jsCode: chunk.code,
39
+ jsCode: code,
92
40
  map,
93
- imports: [...externalMap.values()], // full-ids
94
- rawImports: [...externalMap.keys()], // bare specifiers (for closure traversal)
41
+ imports,
42
+ lazyImports,
43
+ rawImports,
95
44
  watchFiles,
96
45
  };
97
46
  }