@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.
@@ -2,37 +2,35 @@ import { path } from '../nodeApi.mjs';
2
2
  import { CLIENT_CONDITIONS } from '../conditions.mjs';
3
3
 
4
4
  /**
5
- * Rollup plugin: keep `*.css` imports OUT of the module JS (System artifact carries no CSS),
6
- * but record their resolved paths so the CSS pipeline can emit a co-located stylesheet artifact.
7
- * Relative imports resolve against the importer; BARE imports ('@mosetta/ui/ui.css')
8
- * resolve through the fileSystem FROM the importer's directory — library css lands in the consuming
9
- * MODULE's scoped artifact (dependency artifacts carry no css; duplication accepted).
10
- * `baseDir` — resolution context for the entry (it has no importer).
5
+ * Esbuild plugin: keep `*.css` imports OUT of the module JS (factory artifact carries no CSS),
6
+ * while recording their resolved paths so the CSS pipeline can emit co-located or shared
7
+ * stylesheet artifacts.
8
+ *
9
+ * Uses a relative virtual path so dev comments and sourcemaps never leak host-specific paths.
11
10
  */
12
- export function cssIntercept(collected, resolver, baseDir) {
11
+ export function cssIntercept(collected, resolver, baseDir, watched) {
13
12
  return {
14
13
  name: 'mosetta-css-intercept',
15
- resolveId(source, importer) {
16
- if (!source.endsWith('.css')) return null;
17
- const isPathLike = source.startsWith('.') || path.isAbsolute(source);
18
- let resolved;
19
- if (isPathLike) {
20
- resolved = importer
21
- ? path.resolve(path.dirname(importer), source)
22
- : path.resolve(source);
23
- } else {
24
- // resolve from the importing file's package first (pnpm: deps live per-package)
25
- resolved = resolver.resolve(source, importer ? path.dirname(importer) : baseDir, CLIENT_CONDITIONS);
26
- }
27
- collected.push(resolved);
28
- // css is read by `processCss`, not rollup (a stub is served below) — so we add it to the
29
- // watch list here, otherwise a style edit would not invalidate the module artifact
30
- this.addWatchFile(resolved);
31
- return { id: resolved, external: false };
32
- },
33
- load(id) {
34
- if (id.endsWith('.css')) return 'export default undefined;';
35
- return null;
14
+ setup(build) {
15
+ build.onResolve({ filter: /\.css$/ }, (args) => {
16
+ const fromDir = args.resolveDir || baseDir;
17
+ const isPathLike = args.path.startsWith('.') || path.isAbsolute(args.path);
18
+ let resolved;
19
+ if (isPathLike) {
20
+ resolved = path.isAbsolute(args.path) ? args.path : path.resolve(fromDir, args.path);
21
+ } else {
22
+ resolved = resolver.resolve(args.path, fromDir, CLIENT_CONDITIONS);
23
+ }
24
+ collected.push(resolved);
25
+ watched?.add(resolved);
26
+ const rel = isPathLike ? path.relative(baseDir, resolved).split(path.sep).join('/') : args.path;
27
+ return { path: rel, namespace: 'mosetta-css' };
28
+ });
29
+
30
+ build.onLoad({ filter: /.*/, namespace: 'mosetta-css' }, () => ({
31
+ contents: 'export default undefined;',
32
+ loader: 'js',
33
+ }));
36
34
  },
37
35
  };
38
36
  }
@@ -0,0 +1,52 @@
1
+ import { parse } from 'acorn';
2
+
3
+ /**
4
+ * Rewrite every JS `ImportExpression` (`import(spec)`) in a bundled factory chunk to
5
+ * `__meta.import(spec)` using a real JS AST (`acorn`).
6
+ *
7
+ * 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).
11
+ */
12
+ export function rewriteDynamicImports(code) {
13
+ if (!code.includes('import(') && !/\bimport\s*\(/.test(code)) return code;
14
+
15
+ let ast;
16
+ try {
17
+ ast = parse(code, { ecmaVersion: 2022, sourceType: 'script', allowReturnOutsideFunction: true });
18
+ } catch {
19
+ // Fallback if a custom plugin emitted non-standard syntax; return untouched rather than corrupting.
20
+ return code;
21
+ }
22
+
23
+ const starts = [];
24
+ const walk = (node) => {
25
+ if (!node || typeof node !== 'object') return;
26
+ if (node.type === 'ImportExpression') {
27
+ starts.push(node.start);
28
+ }
29
+ for (const key of Object.keys(node)) {
30
+ if (key === 'start' || key === 'end' || key === 'type') continue;
31
+ const value = node[key];
32
+ if (Array.isArray(value)) {
33
+ for (const item of value) walk(item);
34
+ } else if (value && typeof value === 'object' && typeof value.type === 'string') {
35
+ walk(value);
36
+ }
37
+ }
38
+ };
39
+ walk(ast);
40
+
41
+ if (!starts.length) return code;
42
+
43
+ // Replace from back to front so earlier offsets stay valid.
44
+ starts.sort((a, b) => b - a);
45
+ 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
+ }
50
+ }
51
+ return out;
52
+ }
@@ -1,4 +1,4 @@
1
- import { builtinModules, path } from '../nodeApi.mjs';
1
+ import { builtinModules } from '../nodeApi.mjs';
2
2
 
3
3
  /**
4
4
  * Monolith compatibility with workerd — the FRAMEWORK DEFAULTS of packing: everything that used
@@ -11,28 +11,16 @@ import { builtinModules, path } from '../nodeApi.mjs';
11
11
  * substitute a virtual shim that STATICALLY re-exports `node:*` (while `node:*` stays
12
12
  * external — workerd provides it under nodejs_compat, the runner enables the flags at
13
13
  * composition);
14
- * - `cjs-module-lexer`: its `import` entry compiles wasm at runtime (forbidden in workerd).
15
- * We resolve WITHOUT conditions (require semantics) — the package's exports map itself
16
- * yields the pure-JS entry `lexer.js` via the `default` branch. This picks an entry the
17
- * author declared, it is not a patch;
18
14
  * - `graceful-fs`: monkey-patches fs at top level, and workerd's fs is frozen — we substitute
19
- * the fs shim (nobody calls this package's file functions inside the isolate);
20
- * - `@rollup/browser`: fetches its wasm via `fetch(new URL(..., import.meta.url))` and cannot
21
- * accept a precompiled WebAssembly.Module (esbuild-wasm can: `initialize({wasmModule})`).
22
- * The only real patch: the default URL is replaced with `globalThis.__ROLLUP_WASM__`, where
23
- * the action puts the DECLARED wasm module. Goes away once upstream adds a parameter.
15
+ * the fs shim (nobody calls this package's file functions inside the isolate).
24
16
  */
25
17
 
26
18
  const SHIM_NAMESPACE = 'mosetta-node-shim';
27
- // there is nothing esbuild can turn a `require()` of an external module into ("Dynamic require
28
- // is not supported"), so `node:*` require calls also go to the shim — it gives a STATIC binding;
29
- // `node:*` import declarations stay external (workerd provides them)
30
19
  const REQUIRE_KINDS = new Set(['require-call', 'require-resolve']);
31
20
  const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
32
21
  const BARE_BUILTINS_RE = new RegExp(`^(${builtinModules.map(escape).join('|')})$`);
33
- const ROLLUP_WASM_URL_RE = /void 0===(\w+)&&\(\1=new URL\("bindings_wasm_bg\.wasm",[^)]*\)\)/;
34
22
 
35
- export function monolithCompat(fileSystem, resolver) {
23
+ export function monolithCompat() {
36
24
  return {
37
25
  name: 'mosetta-monolith-compat',
38
26
  setup(build) {
@@ -50,16 +38,6 @@ export function monolithCompat(fileSystem, resolver) {
50
38
  + `export * from 'node:${args.path}';\n`,
51
39
  loader: 'js',
52
40
  }));
53
-
54
- build.onResolve({ filter: /^cjs-module-lexer$/ }, (args) => ({
55
- path: resolver.resolve('cjs-module-lexer', args.resolveDir || path.dirname(args.importer), null),
56
- }));
57
-
58
- build.onLoad({ filter: /rollup\.browser\.js$/ }, (args) => ({
59
- contents: fileSystem.readFile(args.path, 'utf8')
60
- .replace(ROLLUP_WASM_URL_RE, 'void 0===$1&&($1=globalThis.__ROLLUP_WASM__)'),
61
- loader: 'js',
62
- }));
63
41
  },
64
42
  };
65
43
  }
@@ -69,13 +47,6 @@ export function monolithCompatOptions() {
69
47
  return {
70
48
  external: ['node:*'],
71
49
  define: { 'import.meta.url': JSON.stringify('file:///bundle/module.js') },
72
- // Small runtime divergences that must be closed before the first line of foreign code:
73
- // - workerd's process has no cwd(), and engines/postcss call it when normalizing paths
74
- // (in the monolith's world all paths are absolute, any root will do);
75
- // - workerd DELIBERATELY withholds FinalizationRegistry (GC observability), while the napi
76
- // bridges of wasm packages (napi-wasm in lightningcss-wasm) register handle disposal in
77
- // it. A no-op means handles are not freed on GC — for a short-lived build isolate that is
78
- // bounded memory, not a production leak.
79
50
  banner: {
80
51
  js: 'globalThis.process&&typeof globalThis.process.cwd!=="function"&&(globalThis.process.cwd=()=>"/");'
81
52
  + 'globalThis.FinalizationRegistry||(globalThis.FinalizationRegistry=class{register(){}unregister(){}});',
@@ -0,0 +1,107 @@
1
+ import { path } from '../nodeApi.mjs';
2
+ import { CLIENT_CONDITIONS } from '../conditions.mjs';
3
+ import { applyBrowserField, applyBrowserEntry, applyBrowserBareMap, BROWSER_EMPTY } from '../browserField.mjs';
4
+ import { probeFile, isDirectoryRequest } from '../probeFile.mjs';
5
+ import { inlineInputSourcemap } from './portResolveEsbuild.mjs';
6
+
7
+ const LOADER = { '.ts': 'ts', '.tsx': 'tsx', '.js': 'js', '.mjs': 'js', '.cjs': 'js', '.json': 'json' };
8
+
9
+ /**
10
+ * Client-side esbuild resolver & loader ON TOP OF THE PORT.
11
+ *
12
+ * Handles both:
13
+ * - `externalizeBare: true` (tiles and external dependency artifacts): relative/absolute imports
14
+ * resolve through `fileSystem` with `browser` field support; bare imports are externalized and
15
+ * rewritten to version-qualified full-ids, split into `eagerExternalMap` vs `lazyExternalMap`
16
+ * (`args.kind === 'dynamic-import'`).
17
+ * - `externalizeBare: false` (self-contained IIFE such as `loader.js`): bare imports are resolved
18
+ * and bundled in via `resolver` + `CLIENT_CONDITIONS` + `browser` field.
19
+ */
20
+ export function portResolveClient(fileSystem, resolver, baseDir, {
21
+ externalizeBare = true,
22
+ resolveExternal = null,
23
+ eagerExternalMap = null,
24
+ lazyExternalMap = null,
25
+ watched = null,
26
+ } = {}) {
27
+ const canonical = (file) => {
28
+ try {
29
+ return fileSystem.realPath(file);
30
+ } catch {
31
+ return file;
32
+ }
33
+ };
34
+
35
+ return {
36
+ name: 'mosetta-port-resolve-client',
37
+ setup(build) {
38
+ build.onResolve({ filter: /.*/ }, (args) => {
39
+ if (args.kind === 'entry-point') {
40
+ const p = canonical(args.path);
41
+ watched?.add(p);
42
+ return { path: p };
43
+ }
44
+
45
+ const fromDir = args.resolveDir
46
+ || (args.importer && path.isAbsolute(args.importer) ? path.dirname(args.importer) : baseDir);
47
+
48
+ if (args.path.startsWith('.') || path.isAbsolute(args.path)) {
49
+ const target = path.isAbsolute(args.path) ? args.path : path.resolve(fromDir, args.path);
50
+ const found = probeFile(fileSystem, target, { directoryOnly: isDirectoryRequest(args.path) });
51
+ if (!found) return null;
52
+ const mapped = applyBrowserField(fileSystem, canonical(found), CLIENT_CONDITIONS);
53
+ if (mapped === BROWSER_EMPTY) return { path: BROWSER_EMPTY, namespace: 'mosetta-browser-empty' };
54
+ watched?.add(mapped);
55
+ return { path: mapped };
56
+ }
57
+
58
+ if (externalizeBare) {
59
+ // Check package-level `browser` map first (e.g. `"crypto": false` inside a package).
60
+ const browserMapped = applyBrowserBareMap(fileSystem, args.path, fromDir, CLIENT_CONDITIONS);
61
+ if (browserMapped === BROWSER_EMPTY) {
62
+ return { path: BROWSER_EMPTY, namespace: 'mosetta-browser-empty' };
63
+ }
64
+ if (typeof browserMapped === 'string') {
65
+ watched?.add(browserMapped);
66
+ return { path: browserMapped };
67
+ }
68
+ // Bare specifier: external! Rewrite to version-qualified full-id.
69
+ const full = (resolveExternal && resolveExternal(args.path)) || args.path;
70
+ if (args.kind === 'dynamic-import') {
71
+ lazyExternalMap?.set(args.path, full);
72
+ } else {
73
+ eagerExternalMap?.set(args.path, full);
74
+ }
75
+ return { path: full, external: true };
76
+ }
77
+
78
+ // Self-contained bundle (e.g. loader.js): resolve bare imports through the catalog.
79
+ try {
80
+ const resolved = canonical(resolver.resolve(args.path, fromDir, CLIENT_CONDITIONS));
81
+ const entry = applyBrowserEntry(fileSystem, args.path, resolved, CLIENT_CONDITIONS);
82
+ const mapped = applyBrowserField(fileSystem, entry, CLIENT_CONDITIONS);
83
+ if (mapped === BROWSER_EMPTY) return { path: BROWSER_EMPTY, namespace: 'mosetta-browser-empty' };
84
+ watched?.add(mapped);
85
+ return { path: mapped };
86
+ } catch {
87
+ return null;
88
+ }
89
+ });
90
+
91
+ build.onLoad({ filter: /.*/, namespace: 'mosetta-browser-empty' }, () => ({
92
+ contents: 'export default {};\n',
93
+ loader: 'js',
94
+ }));
95
+
96
+ build.onLoad({ filter: /.*/ }, (args) => {
97
+ watched?.add(args.path);
98
+ const raw = fileSystem.readFile(args.path, 'utf8');
99
+ return {
100
+ contents: inlineInputSourcemap(fileSystem, args.path, raw),
101
+ loader: LOADER[path.extname(args.path)] ?? 'js',
102
+ resolveDir: path.dirname(args.path),
103
+ };
104
+ });
105
+ },
106
+ };
107
+ }
@@ -20,7 +20,7 @@ const toBase64 = (bytes) => {
20
20
  return btoa(binary);
21
21
  };
22
22
 
23
- function inlineInputSourcemap(fileSystem, file, contents) {
23
+ export function inlineInputSourcemap(fileSystem, file, contents) {
24
24
  const hit = MAP_URL_RE.exec(contents);
25
25
  if (!hit) return contents;
26
26
  const url = hit[1];
package/src/sourcemap.mjs CHANGED
@@ -1,26 +1,25 @@
1
1
  import { path } from './nodeApi.mjs';
2
2
 
3
3
  /**
4
- * Unified `sources` form in sourcemaps.
5
- *
6
- * The engines relativize paths differently and both badly: native rollup — against
7
- * `process.cwd()` (the form depends on which directory the build runs from), `@rollup/browser` —
8
- * against `/`, because it has no `cwd` at all. We normalize to a path RELATIVE TO THE ROOT of
9
- * the distributive: the engines start to agree, and the form stops depending on the machine and
10
- * the launch directory.
11
- *
12
- * The engines can be told apart by what they put in `sourcemapPath`: the native one gives an
13
- * absolute path (and `rel` relative to it), the wasm one — a bare file name (and `rel` = an
14
- * absolute path without the leading slash). This contract is pinned by `sourcemapForm`.
15
- *
16
- * Changing the form is safe: `sourcesContent` is inlined into the maps, so `sources` acts as a
17
- * label in devtools, not as a load address.
4
+ * Normalize `sources` entries in an esbuild-emitted sourcemap so every path is relative to
5
+ * `sourceBase` with forward slashes, independent of `process.cwd()`, OS path separators, or
6
+ * virtual outdir. `sourcesContent` is inlined into the map, so `sources` serves as a stable
7
+ * devtools label and matches identically between native esbuild and esbuild-wasm.
18
8
  */
19
- export function sourcemapPathTransformFor(sourceBase) {
20
- return (relativeSourcePath, sourcemapPath) => {
21
- const absolute = sourcemapPath && path.isAbsolute(sourcemapPath)
22
- ? path.resolve(path.dirname(sourcemapPath), relativeSourcePath)
23
- : path.resolve('/', relativeSourcePath);
24
- return path.relative(sourceBase, absolute).split(path.sep).join('/');
25
- };
9
+ export function normalizeSourcemap(mapText, sourceBase) {
10
+ if (!mapText || !sourceBase) return mapText;
11
+ try {
12
+ const parsed = JSON.parse(mapText);
13
+ if (!Array.isArray(parsed.sources)) return mapText;
14
+ parsed.sources = parsed.sources.map((src) => {
15
+ if (typeof src !== 'string' || !src) return src;
16
+ // Preserve virtual plugin namespaces (`mosetta-asset:...`, `<stdin>`)
17
+ if (src.startsWith('<') || /^[a-z][a-z0-9+.-]*:/i.test(src)) return src;
18
+ const abs = path.isAbsolute(src) ? src : path.resolve(sourceBase, src);
19
+ return path.relative(sourceBase, abs).split(path.sep).join('/');
20
+ });
21
+ return JSON.stringify(parsed);
22
+ } catch {
23
+ return mapText;
24
+ }
26
25
  }
@@ -1,81 +0,0 @@
1
- import { path } from './nodeApi.mjs';
2
- import { parse, init } from 'cjs-module-lexer';
3
-
4
- // the lexer's wasm is embedded in the package as base64 (no fetch, no file) — init is one-shot and lazy
5
- let ready = null;
6
- function ensureLexer() {
7
- if (!ready) ready = init();
8
- return ready;
9
- }
10
-
11
- const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
12
- // `default` — arrives separately via the facade; `__esModule` is an interop MARKER, not an
13
- // export: it is set non-enumerable (`Object.defineProperty`), so the old runtime walk never saw it.
14
- const NOT_AN_EXPORT = new Set(['default', '__esModule']);
15
- const LEXABLE_EXT = new Set(['.js', '.cjs']);
16
- const MAX_REEXPORT_DEPTH = 16;
17
-
18
- /**
19
- * Named exports of a CJS module — by STATIC parsing.
20
- *
21
- * Needed by the dependency artifact's facade: a cross-artifact
22
- * `import { createContext } from 'react'` requires the artifact to serve REAL named exports —
23
- * default-based CJS interop loses them at artifact boundaries.
24
- *
25
- * The list used to be obtained by executing the module (`require(file)` + `Object.keys`).
26
- * Parsing the string instead of executing removes three things at once: running foreign code on
27
- * the build machine, depending on the node loader, and the last reason to keep `cjsNamedExports`
28
- * in the port — the function only needs `readFile` and `resolve`, so it lives OUTSIDE the port
29
- * and works with any implementation of it. The lexer is the same `cjs-module-lexer` node itself
30
- * uses to determine CJS named exports.
31
- *
32
- * Returns string[], or null when this is not parseable CJS (ESM, another extension, a syntax
33
- * error) — then rollup handles the module natively, as before.
34
- */
35
- export async function cjsNamedExports(fileSystem, resolver, file, fromDir) {
36
- if (!LEXABLE_EXT.has(path.extname(file))) return null;
37
- await ensureLexer();
38
-
39
- const collected = new Set();
40
- const visited = new Set();
41
-
42
- // `module.exports = require('./cjs/react.production.js')` — the form half of real-world npm
43
- // lives in: the entry itself exports NOTHING, everything is in the re-export target.
44
- const walk = (target, dir, depth) => {
45
- if (depth > MAX_REEXPORT_DEPTH || visited.has(target)) return true;
46
- visited.add(target);
47
-
48
- let source;
49
- try {
50
- source = fileSystem.readFile(target, 'utf8');
51
- } catch {
52
- return false; // file missing / unreadable — treat the parse as failed
53
- }
54
-
55
- let parsed;
56
- try {
57
- parsed = parse(source, target);
58
- } catch {
59
- return false; // ESM syntax or broken CJS — let rollup decide on its own
60
- }
61
-
62
- for (const name of parsed.exports) {
63
- if (!NOT_AN_EXPORT.has(name) && IDENTIFIER.test(name)) collected.add(name);
64
- }
65
-
66
- const nextDir = path.dirname(target);
67
- for (const specifier of parsed.reexports) {
68
- let resolved;
69
- try {
70
- resolved = resolver.resolve(specifier, nextDir);
71
- } catch {
72
- continue; // unresolvable re-export (conditional/optional) — simply adds no names
73
- }
74
- if (!LEXABLE_EXT.has(path.extname(resolved))) continue;
75
- if (!walk(resolved, nextDir, depth + 1)) return false;
76
- }
77
- return true;
78
- };
79
-
80
- return walk(file, fromDir, 0) ? [...collected] : null;
81
- }
@@ -1,14 +0,0 @@
1
- import replace from '@rollup/plugin-replace';
2
-
3
- // Replace `process.env.NODE_ENV` with a string literal at build time.
4
- // Browsers have no `process`; CJS deps (react, react-dom, scheduler) branch on this, so without
5
- // it they throw `process is not defined`. The literal also lets dead branches tree-shake out.
6
- export function defineEnv(mode) {
7
- const nodeEnv = mode === 'production' ? 'production' : 'development';
8
- return replace({
9
- preventAssignment: true,
10
- values: {
11
- 'process.env.NODE_ENV': JSON.stringify(nodeEnv),
12
- },
13
- });
14
- }
@@ -1,80 +0,0 @@
1
- import { path } from '../nodeApi.mjs';
2
- import { CLIENT_CONDITIONS } from '../conditions.mjs';
3
- import { applyBrowserField, applyBrowserEntry, BROWSER_EMPTY } from '../browserField.mjs';
4
- import { probeFile, isDirectoryRequest } from '../probeFile.mjs';
5
-
6
- const isOwnedByAnotherPlugin = (id) => id.includes('\0') || id.includes('?');
7
-
8
- /**
9
- * Resolver and loader of the module graph ON TOP OF THE PORT.
10
- *
11
- * Replaces two at once: `@rollup/plugin-node-resolve` and rollup's BUILT-IN resolver — both hit
12
- * the disk past the port, so "a builder without node" held only at the outer layer. Now all
13
- * module-graph I/O goes through `fileSystem`, and a second port implementation gets the graph
14
- * for free.
15
- *
16
- * The position in the plugin list is SIGNIFICANT and mirrors the old one: where `nodeResolve`
17
- * stood — in its place; where there was no resolver and the built-in worked — last. Otherwise
18
- * we would intercept what used to reach `cssIntercept`, `assets`, `commonjs` or the transpiler.
19
- */
20
- export function portResolve(fileSystem, resolver, baseDir) {
21
- // Symlinks are dereferenced DELIBERATELY: rollup and node-resolve do this by default
22
- // (`preserveSymlinks: false`), and the whole graph currently lives in realpath form — a
23
- // workspace package is seen as `packages/react/src/...`, not as a path inside node_modules.
24
- // Without this, ids would fork and the same file would enter the bundle twice.
25
- const canonical = (file) => {
26
- try {
27
- return fileSystem.realPath(file);
28
- } catch {
29
- return file;
30
- }
31
- };
32
-
33
- return {
34
- name: 'mosetta-port-resolve',
35
-
36
- resolveId(source, importer) {
37
- if (isOwnedByAnotherPlugin(source)) return null;
38
-
39
- const fromDir = importer && !isOwnedByAnotherPlugin(importer)
40
- ? path.dirname(importer)
41
- : baseDir;
42
-
43
- if (path.isAbsolute(source) || source.startsWith('.')) {
44
- const target = path.isAbsolute(source) ? source : path.resolve(fromDir, source);
45
- // a trailing slash disables node's file branch — decide by the ORIGINAL specifier
46
- const found = probeFile(fileSystem, target, { directoryOnly: isDirectoryRequest(source) });
47
- // the owning package's legacy `browser` map also hits the package's INTERNAL paths
48
- return found ? applyBrowserField(fileSystem, canonical(found), CLIENT_CONDITIONS) : null;
49
- }
50
-
51
- // bare: exports maps and conditions are policy over the package catalog — the resolver's job
52
- try {
53
- const resolved = canonical(resolver.resolve(source, fromDir, CLIENT_CONDITIONS));
54
- const entry = applyBrowserEntry(fileSystem, source, resolved, CLIENT_CONDITIONS);
55
- return applyBrowserField(fileSystem, entry, CLIENT_CONDITIONS);
56
- } catch {
57
- return null; // let rollup decide: an external import or an honest error
58
- }
59
- },
60
-
61
- load(id) {
62
- // `"…": false` in the browser map — the module does not exist in the browser, serve a stub
63
- if (id === BROWSER_EMPTY) return 'export default {};\n';
64
- if (isOwnedByAnotherPlugin(id)) return null;
65
- try {
66
- const code = fileSystem.readFile(id, 'utf8');
67
- // The file was read by US, not by rollup — so WE must also put it into the watch list:
68
- // rollup fills `bundle.watchFiles` only from its own loader, which never runs with the
69
- // port. Without this line the list is empty, and everything resting on it silently
70
- // breaks: mtime cache invalidation and the dev server's watching of sources OUTSIDE
71
- // `modules/` (in the monorepo that is every workspace library). The path here is already
72
- // dereferenced (`canonical`), so a workspace symlink points at the real file.
73
- this.addWatchFile(id);
74
- return code;
75
- } catch {
76
- return null;
77
- }
78
- },
79
- };
80
- }
@@ -1,56 +0,0 @@
1
- import { path } from '../nodeApi.mjs';
2
-
3
- const TS_RE = /\.(ts|tsx)$/;
4
- const LOADER = { '.ts': 'ts', '.tsx': 'tsx' };
5
-
6
- // Transpile policy belongs to the BUILD, not the engine: the engine only knows "string in, string out".
7
- const TRANSFORM = {
8
- jsx: 'automatic',
9
- target: 'es2020',
10
- tsconfigRaw: { compilerOptions: { experimentalDecorators: true } },
11
- };
12
-
13
- /**
14
- * TS/TSX transpilation as an ENGINE CAPABILITY, not a binding to a native binary.
15
- *
16
- * This used to be `rollup-plugin-esbuild`, pulling the platform esbuild binary — the last
17
- * engine-bound node of the client path, not portable into an isolate. Now the plugin asks the
18
- * engine for `transform(code, opts)`; which esbuild stands behind it — native or wasm — is
19
- * decided by whoever injected the engine. Resolution is not part of this: `portResolve`
20
- * covers it entirely.
21
- */
22
- export function transformTs(engine) {
23
- return {
24
- name: 'mosetta-transform',
25
- async transform(code, id) {
26
- if (!TS_RE.test(id)) return null;
27
- const r = await engine.transform(code, {
28
- ...TRANSFORM,
29
- loader: LOADER[path.extname(id)],
30
- sourcefile: id,
31
- sourcemap: true,
32
- });
33
- return { code: r.code, map: r.map || null };
34
- },
35
- };
36
- }
37
-
38
- /**
39
- * Minification — a post-pass over the finished chunk (prod). Mangling touches only the
40
- * artifact's internal scope: the `System.register` name, dependency specifiers and export names
41
- * are string literals, so cross-artifact linkage survives it unchanged.
42
- */
43
- export function minifyChunk(engine) {
44
- return {
45
- name: 'mosetta-minify',
46
- async renderChunk(code) {
47
- const r = await engine.transform(code, {
48
- loader: 'js',
49
- minify: true,
50
- target: TRANSFORM.target,
51
- sourcemap: true,
52
- });
53
- return { code: r.code, map: r.map || null };
54
- },
55
- };
56
- }