@pwfabric/compiler 0.0.0-stage → 1.0.0-rc.0

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.
@@ -0,0 +1,285 @@
1
+ /**
2
+ * compileAtom — the single atom compiler.
3
+ *
4
+ * Source files in, one ES module out: a block's `component.tsx` (or a
5
+ * capability's `handler.ts`, or a connector/provider engine) plus the
6
+ * companion files it imports, bundled with esbuild into one ESM module the
7
+ * runtime loads. The host-provided imports — the list in
8
+ * `@pwfabric/core` (`BLOCK_HOST_IMPORTS`) — stay external;
9
+ * the host's import map supplies them at load time.
10
+ *
11
+ * IN MEMORY ONLY. Every file comes from the caller's `files` map; an esbuild
12
+ * plugin resolves and loads from that map and nothing else. There are no disk
13
+ * writes, no disk reads of user paths and no network. A relative import that
14
+ * climbs out of the tree is a diagnostic, not a read of whatever sits there.
15
+ *
16
+ * THE SEAM. The compiler returns data — bytes, hash, diagnostics. Storing the
17
+ * bundle, recording it against an atom, licence checks and caching are the
18
+ * caller's job, never this package's.
19
+ *
20
+ * DETERMINISM. Same input + same compiler version + same esbuild version →
21
+ * identical `code` and `hash`. Both versions are returned so a caller can
22
+ * record them beside the hash.
23
+ *
24
+ * @module @pwfabric/compiler/compile
25
+ */
26
+ import { createHash } from 'node:crypto';
27
+ import { posix } from 'node:path';
28
+ import * as esbuild from 'esbuild';
29
+ import { atomKindMeta } from '@pwfabric/contracts';
30
+ import { blockBundleExternals } from '@pwfabric/core';
31
+ import { joinVirtual, normalizeVirtualPath, PathEscapeError, resolveCandidates } from './paths.js';
32
+ import { buildWrapperSource, isValidEngineName, isValidSourceBase } from './wrappers.js';
33
+ import { COMPILER_VERSION, ESBUILD_VERSION } from './version.js';
34
+ // ============================================================
35
+ // CONTRACT
36
+ // ============================================================
37
+ /** Default cap on one compiled bundle; the caller may raise or lower it. */
38
+ export const MAX_ATOM_BUNDLE_BYTES = 500 * 1024;
39
+ // ============================================================
40
+ // LOADERS
41
+ // ============================================================
42
+ const LOADERS = {
43
+ '.ts': 'ts',
44
+ '.mts': 'ts',
45
+ '.cts': 'ts',
46
+ '.tsx': 'tsx',
47
+ '.js': 'js',
48
+ '.mjs': 'js',
49
+ '.cjs': 'js',
50
+ '.jsx': 'jsx',
51
+ '.json': 'json',
52
+ };
53
+ const NAMESPACE = 'pwfabric-atom';
54
+ const OUTFILE = 'bundle.mjs';
55
+ // ============================================================
56
+ // COMPILER
57
+ // ============================================================
58
+ /** Compile one atom. Never throws for bad input — every problem is a diagnostic. */
59
+ export async function compileAtom(input) {
60
+ const diagnostics = [];
61
+ const fail = (extra) => {
62
+ if (extra)
63
+ diagnostics.push(extra);
64
+ return result({ ok: false, code: '', hash: '', size: 0, diagnostics, externals: [] });
65
+ };
66
+ // ── normalise the tree ─────────────────────────────────────────
67
+ const files = new Map();
68
+ for (const [rawKey, content] of Object.entries(input.files)) {
69
+ try {
70
+ files.set(normalizeVirtualPath(rawKey), content);
71
+ }
72
+ catch (e) {
73
+ if (e instanceof PathEscapeError)
74
+ return fail(error('PATH_ESCAPE', `file key '${rawKey}' resolves outside the source tree`));
75
+ throw e;
76
+ }
77
+ }
78
+ let entry;
79
+ let allowed = null;
80
+ try {
81
+ entry = normalizeVirtualPath(input.entry);
82
+ if (input.companions)
83
+ allowed = new Set(input.companions.map(normalizeVirtualPath));
84
+ }
85
+ catch (e) {
86
+ if (e instanceof PathEscapeError)
87
+ return fail(error('PATH_ESCAPE', `${e.message}`));
88
+ throw e;
89
+ }
90
+ // ── entry wrapper, by kind ─────────────────────────────────────
91
+ const kind = input.kind ?? 'block';
92
+ const meta = atomKindMeta(kind);
93
+ if (!meta.bundled)
94
+ return fail(error('INVALID_INPUT', `Atom kind "${kind}" is not a bundled kind`));
95
+ let esbuildEntry;
96
+ const ext = posix.extname(entry);
97
+ if (meta.entry === 'identity') {
98
+ const source = files.get(entry);
99
+ if (source === undefined)
100
+ return fail(error('INVALID_INPUT', `entry '${entry}' is not in the source tree`));
101
+ if (source.length === 0)
102
+ return fail(error('INVALID_INPUT', `Atom source for "${entry}" is empty`));
103
+ const sourceBase = posix.basename(entry, ext);
104
+ // The basename is written into the generated wrapper; it must be a plain name.
105
+ if (!isValidSourceBase(sourceBase)) {
106
+ return fail(error('INVALID_INPUT', `entry basename ${JSON.stringify(sourceBase)} may only contain letters, digits, '_', '-' and '.'`));
107
+ }
108
+ const wrapperPath = posix.join(posix.dirname(entry), `_bundle-entry${ext}`);
109
+ if (files.has(wrapperPath)) {
110
+ return fail(error('INVALID_INPUT', `'${wrapperPath}' is reserved for the generated entry wrapper`));
111
+ }
112
+ files.set(wrapperPath, buildWrapperSource(kind, { sourceBase }));
113
+ allowed?.add(entry);
114
+ esbuildEntry = wrapperPath;
115
+ }
116
+ else if (meta.entry === 'sibling-generated') {
117
+ if (!input.engineName)
118
+ return fail(error('INVALID_INPUT', `Atom "${entry}" (${kind}) needs engineName`));
119
+ // The engine name is written into the generated wrapper; it must be a plain name.
120
+ if (!isValidEngineName(input.engineName)) {
121
+ return fail(error('INVALID_INPUT', `engineName ${JSON.stringify(input.engineName)} may only contain letters, digits, '_' and '-'`));
122
+ }
123
+ if (files.has(entry)) {
124
+ return fail(error('INVALID_INPUT', `'${entry}' is generated by the compiler for ${kind} atoms; it must not be in the source tree`));
125
+ }
126
+ files.set(entry, buildWrapperSource(kind, { engineName: input.engineName }));
127
+ esbuildEntry = entry;
128
+ }
129
+ else {
130
+ return fail(error('INVALID_INPUT', `Atom kind "${kind}" has no bundleable entry`));
131
+ }
132
+ allowed?.add(esbuildEntry);
133
+ // ── bundle ─────────────────────────────────────────────────────
134
+ const hostImports = new Set(blockBundleExternals());
135
+ const plugin = virtualTreePlugin(files, allowed, hostImports);
136
+ let built;
137
+ try {
138
+ built = await esbuild.build({
139
+ entryPoints: [esbuildEntry],
140
+ outfile: OUTFILE,
141
+ write: false,
142
+ metafile: true,
143
+ bundle: true,
144
+ format: 'esm',
145
+ platform: 'browser',
146
+ target: input.target ?? 'es2022',
147
+ minify: input.minify ?? true,
148
+ treeShaking: true,
149
+ sourcemap: input.sourcemap ? 'external' : false,
150
+ jsx: 'automatic',
151
+ logLevel: 'silent',
152
+ plugins: [plugin],
153
+ });
154
+ }
155
+ catch (e) {
156
+ const failure = e;
157
+ if (!Array.isArray(failure.errors))
158
+ throw e;
159
+ diagnostics.push(...failure.errors.map((m) => fromMessage(m, 'error')));
160
+ diagnostics.push(...(failure.warnings ?? []).map((m) => fromMessage(m, 'warning')));
161
+ return fail();
162
+ }
163
+ diagnostics.push(...built.warnings.map((m) => fromMessage(m, 'warning')));
164
+ const out = built.outputFiles.find((f) => f.path.endsWith('.mjs'));
165
+ const mapFile = built.outputFiles.find((f) => f.path.endsWith('.mjs.map'));
166
+ /* c8 ignore next -- esbuild always emits the bundle when the build succeeds */
167
+ if (!out)
168
+ return fail(error('ESBUILD_FAILED', 'esbuild produced no output'));
169
+ const maxBytes = input.maxBytes ?? MAX_ATOM_BUNDLE_BYTES;
170
+ if (out.contents.length > maxBytes) {
171
+ return fail(error('BUNDLE_TOO_LARGE', `Atom "${entry}" bundle ${out.contents.length} bytes exceeds limit ${maxBytes}`));
172
+ }
173
+ const externals = new Set();
174
+ for (const output of Object.values(built.metafile.outputs)) {
175
+ for (const imp of output.imports)
176
+ if (imp.external)
177
+ externals.add(imp.path);
178
+ }
179
+ return result({
180
+ ok: true,
181
+ code: out.text,
182
+ ...(mapFile ? { map: mapFile.text } : {}),
183
+ hash: `sha256:${createHash('sha256').update(out.contents).digest('hex')}`,
184
+ size: out.contents.length,
185
+ diagnostics,
186
+ externals: [...externals].sort(),
187
+ });
188
+ }
189
+ // ============================================================
190
+ // THE VIRTUAL TREE
191
+ // ============================================================
192
+ /**
193
+ * Resolves every import against the in-memory tree. Bare host imports are
194
+ * external; every other bare import, every unresolvable or escaping relative
195
+ * import and every undeclared companion is an error carrying its code in
196
+ * `detail`, so all of them are reported in one pass.
197
+ */
198
+ function virtualTreePlugin(files, allowed, hostImports) {
199
+ const reject = (code, text) => ({
200
+ errors: [{ text, detail: code }],
201
+ });
202
+ return {
203
+ name: 'pwfabric-virtual-tree',
204
+ setup(build) {
205
+ build.onResolve({ filter: /.*/ }, (args) => {
206
+ const spec = args.path;
207
+ if (args.kind === 'entry-point')
208
+ return { path: spec, namespace: NAMESPACE };
209
+ if (spec.startsWith('/') || /^[A-Za-z]:[\\/]/.test(spec)) {
210
+ return reject('PATH_ESCAPE', `absolute import '${spec}' is not allowed; import relative to the file`);
211
+ }
212
+ if (spec.startsWith('.')) {
213
+ let joined;
214
+ try {
215
+ joined = joinVirtual(args.importer, spec);
216
+ }
217
+ catch {
218
+ return reject('PATH_ESCAPE', `relative import '${spec}' resolves outside the source tree`);
219
+ }
220
+ const hit = resolveCandidates(joined).find((c) => files.has(c));
221
+ if (!hit)
222
+ return reject('UNRESOLVED_IMPORT', `cannot resolve '${spec}' from '${args.importer}'`);
223
+ if (allowed && !allowed.has(hit)) {
224
+ return reject('NOT_A_COMPANION', `'${spec}' resolves to '${hit}', which is not a declared companion of this atom`);
225
+ }
226
+ return { path: hit, namespace: NAMESPACE };
227
+ }
228
+ if (hostImports.has(spec))
229
+ return { path: spec, external: true };
230
+ const hostRoot = [...hostImports].find((h) => spec.startsWith(`${h}/`));
231
+ if (hostRoot) {
232
+ return {
233
+ path: spec,
234
+ external: true,
235
+ warnings: [
236
+ {
237
+ text: `'${spec}' is a subpath of the host import '${hostRoot}'; it stays external, but a host import map resolves exact specifiers only, so the host must map it explicitly`,
238
+ detail: 'HOST_SUBPATH_IMPORT',
239
+ },
240
+ ],
241
+ };
242
+ }
243
+ return reject('NON_HOST_IMPORT', `'${spec}' is not a host import. A bare import must be one the host provides (${[...hostImports].sort().join(', ')}); bundle anything else as a companion file`);
244
+ });
245
+ build.onLoad({ filter: /.*/, namespace: NAMESPACE }, (args) => {
246
+ const loader = LOADERS[posix.extname(args.path)];
247
+ if (!loader) {
248
+ return { errors: [{ text: `no loader for '${args.path}' (supported: ${Object.keys(LOADERS).join(', ')})`, detail: 'UNSUPPORTED_FILE' }] };
249
+ }
250
+ return { contents: files.get(args.path), loader };
251
+ });
252
+ },
253
+ };
254
+ }
255
+ // ============================================================
256
+ // HELPERS
257
+ // ============================================================
258
+ function error(code, message) {
259
+ return { severity: 'error', code, message };
260
+ }
261
+ const KNOWN_CODES = new Set([
262
+ 'INVALID_INPUT',
263
+ 'PATH_ESCAPE',
264
+ 'NON_HOST_IMPORT',
265
+ 'HOST_SUBPATH_IMPORT',
266
+ 'UNRESOLVED_IMPORT',
267
+ 'NOT_A_COMPANION',
268
+ 'UNSUPPORTED_FILE',
269
+ 'ESBUILD_FAILED',
270
+ 'BUNDLE_TOO_LARGE',
271
+ ]);
272
+ function fromMessage(m, severity) {
273
+ const code = typeof m.detail === 'string' && KNOWN_CODES.has(m.detail) ? m.detail : 'ESBUILD_FAILED';
274
+ const loc = m.location;
275
+ return {
276
+ severity,
277
+ code,
278
+ message: m.text,
279
+ ...(loc ? { file: loc.file.replace(`${NAMESPACE}:`, ''), line: loc.line, column: loc.column } : {}),
280
+ };
281
+ }
282
+ function result(r) {
283
+ return { ...r, compilerVersion: COMPILER_VERSION, esbuildVersion: ESBUILD_VERSION };
284
+ }
285
+ //# sourceMappingURL=compile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile.js","sourceRoot":"","sources":["../src/compile.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AACjC,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAClC,OAAO,EAAE,YAAY,EAAiB,MAAM,qBAAqB,CAAA;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AACrD,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAClG,OA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,EAAE,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,SAAS,GAAG,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACpG,CAAA;AACH,CAAC;AAED,SAAS,MAAM,CACb,CAA4D;IAE5D,OAAO,EAAE,GAAG,CAAC,EAAE,eAAe,EAAE,gBAAgB,EAAE,cAAc,EAAE,eAAe,EAAE,CAAA;AACrF,CAAC"}
@@ -0,0 +1,6 @@
1
+ import { type CompileInput, type CompileResult } from './compile.js';
2
+ /** Read a directory into a `files` map keyed by POSIX path relative to `dir`. */
3
+ export declare function readSourceTree(dir: string): Promise<Record<string, Uint8Array>>;
4
+ /** Compile the atom whose entry is `entry` (relative to `dir`) from the tree under `dir`. */
5
+ export declare function compileFolder(dir: string, entry: string, options?: Omit<CompileInput, 'files' | 'entry'>): Promise<CompileResult>;
6
+ //# sourceMappingURL=folder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"folder.d.ts","sourceRoot":"","sources":["../src/folder.ts"],"names":[],"mappings":"AAYA,OAAO,EAAe,KAAK,YAAY,EAAE,KAAK,aAAa,EAAE,MAAM,cAAc,CAAA;AAIjF,iFAAiF;AACjF,wBAAsB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAiBrF;AAED,6FAA6F;AAC7F,wBAAsB,aAAa,CACjC,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,IAAI,CAAC,YAAY,EAAE,OAAO,GAAG,OAAO,CAAM,GAClD,OAAO,CAAC,aAAa,CAAC,CAExB"}
package/dist/folder.js ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * compileFolder — a convenience for a source tree that lives on disk.
3
+ *
4
+ * Reads every file under `dir` into memory (skipping `node_modules`, `dist`
5
+ * and dot-directories), then hands the map to {@link compileAtom}. Reading is
6
+ * the only disk access; compilation itself stays in memory. A pack reader that
7
+ * already holds the tree should call `compileAtom` directly.
8
+ *
9
+ * @module @pwfabric/compiler/folder
10
+ */
11
+ import { readdir, readFile } from 'node:fs/promises';
12
+ import { join, relative, sep } from 'node:path';
13
+ import { compileAtom } from './compile.js';
14
+ const SKIP_DIRS = new Set(['node_modules', 'dist']);
15
+ /** Read a directory into a `files` map keyed by POSIX path relative to `dir`. */
16
+ export async function readSourceTree(dir) {
17
+ const files = {};
18
+ const walk = async (current) => {
19
+ const entries = await readdir(current, { withFileTypes: true });
20
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
21
+ for (const e of entries) {
22
+ const full = join(current, e.name);
23
+ if (e.isDirectory()) {
24
+ if (SKIP_DIRS.has(e.name) || e.name.startsWith('.'))
25
+ continue;
26
+ await walk(full);
27
+ }
28
+ else if (e.isFile()) {
29
+ files[relative(dir, full).split(sep).join('/')] = await readFile(full);
30
+ }
31
+ }
32
+ };
33
+ await walk(dir);
34
+ return files;
35
+ }
36
+ /** Compile the atom whose entry is `entry` (relative to `dir`) from the tree under `dir`. */
37
+ export async function compileFolder(dir, entry, options = {}) {
38
+ return compileAtom({ ...options, files: await readSourceTree(dir), entry });
39
+ }
40
+ //# sourceMappingURL=folder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"folder.js","sourceRoot":"","sources":["../src/folder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AACpD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAA;AAC/C,OAAO,EAAE,WAAW,EAAyC,MAAM,cAAc,CAAA;AAEjF,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC,CAAA;AAEnD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AC7F,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,GAAW,EACX,KAAa,EACb,UAAiD,EAAE;IAEnD,OAAO,WAAW,CAAC,EAAE,GAAG,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,CAAA;AAC7E,CAAC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @pwfabric/compiler — the atom compiler.
3
+ *
4
+ * Block / capability / connector / provider source in, one ES module out, with
5
+ * the host-provided imports left external. Pure: the caller supplies the files
6
+ * and stores the result.
7
+ *
8
+ * @module @pwfabric/compiler
9
+ */
10
+ export { compileAtom, MAX_ATOM_BUNDLE_BYTES, type CompileInput, type CompileResult, type CompileTarget, type Diagnostic, type DiagnosticCode, } from './compile.js';
11
+ export { compileFolder, readSourceTree } from './folder.js';
12
+ export { screenSource, maskSource, SCREEN_IMPORT_ALLOWLIST, screenBlockSource, BLOCK_SOURCE_IMPORT_ALLOWLIST, type ScreenOptions, type ScreenResult, } from './screen.js';
13
+ export { collectCompanions, isCompanionTarget, resolveCompanion, type CompanionScan, type ScreenFn, } from './companions.js';
14
+ export { buildWrapperSource, isValidEngineName, isValidSourceBase, type WrapperContext } from './wrappers.js';
15
+ export { COMPILER_VERSION, ESBUILD_VERSION } from './version.js';
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EACL,WAAW,EACX,qBAAqB,EACrB,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,UAAU,EACf,KAAK,cAAc,GACpB,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAC3D,OAAO,EACL,YAAY,EACZ,UAAU,EACV,uBAAuB,EACvB,iBAAiB,EACjB,6BAA6B,EAC7B,KAAK,aAAa,EAClB,KAAK,YAAY,GAClB,MAAM,aAAa,CAAA;AACpB,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,aAAa,EAClB,KAAK,QAAQ,GACd,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAA;AAC7G,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @pwfabric/compiler — the atom compiler.
3
+ *
4
+ * Block / capability / connector / provider source in, one ES module out, with
5
+ * the host-provided imports left external. Pure: the caller supplies the files
6
+ * and stores the result.
7
+ *
8
+ * @module @pwfabric/compiler
9
+ */
10
+ export { compileAtom, MAX_ATOM_BUNDLE_BYTES, } from './compile.js';
11
+ export { compileFolder, readSourceTree } from './folder.js';
12
+ export { screenSource, maskSource, SCREEN_IMPORT_ALLOWLIST, screenBlockSource, BLOCK_SOURCE_IMPORT_ALLOWLIST, } from './screen.js';
13
+ export { collectCompanions, isCompanionTarget, resolveCompanion, } from './companions.js';
14
+ export { buildWrapperSource, isValidEngineName, isValidSourceBase } from './wrappers.js';
15
+ export { COMPILER_VERSION, ESBUILD_VERSION } from './version.js';
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EACL,WAAW,EACX,qBAAqB,GAMtB,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAC3D,OAAO,EACL,YAAY,EACZ,UAAU,EACV,uBAAuB,EACvB,iBAAiB,EACjB,6BAA6B,GAG9B,MAAM,aAAa,CAAA;AACpB,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,GAGjB,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,iBAAiB,EAAuB,MAAM,eAAe,CAAA;AAC7G,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA"}
@@ -0,0 +1,25 @@
1
+ /** Thrown for a path that resolves outside the virtual root. */
2
+ export declare class PathEscapeError extends Error {
3
+ readonly attempted: string;
4
+ constructor(attempted: string);
5
+ }
6
+ /**
7
+ * Normalise a caller-supplied key to the canonical virtual form: forward
8
+ * slashes, no leading `./`, no `.`/`..` segments. Throws {@link PathEscapeError}
9
+ * for an absolute path (POSIX or drive-letter), a NUL byte, an empty path, or a
10
+ * path whose `..` segments climb past the root.
11
+ */
12
+ export declare function normalizeVirtualPath(raw: string): string;
13
+ /**
14
+ * Join a relative specifier onto the directory of `fromPath` and normalise.
15
+ * Throws {@link PathEscapeError} when the result leaves the root.
16
+ */
17
+ export declare function joinVirtual(fromPath: string, spec: string): string;
18
+ /**
19
+ * The files a resolved-but-unextended path may name, in esbuild's own order:
20
+ * the exact path; for a `.js`/`.jsx`/`.mjs` spelling, the TypeScript file it
21
+ * stands for (esbuild rewrites `./x.js` to `./x.ts` the same way); the path
22
+ * plus each resolve extension; then `index.*` inside it.
23
+ */
24
+ export declare function resolveCandidates(joined: string): string[];
25
+ //# sourceMappingURL=paths.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paths.d.ts","sourceRoot":"","sources":["../src/paths.ts"],"names":[],"mappings":"AAYA,gEAAgE;AAChE,qBAAa,eAAgB,SAAQ,KAAK;IAC5B,QAAQ,CAAC,SAAS,EAAE,MAAM;gBAAjB,SAAS,EAAE,MAAM;CAIvC;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CASxD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAMlE;AAKD;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAY1D"}
package/dist/paths.js ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Virtual paths. The compiler never touches a disk: every file lives in the
3
+ * caller's `files` map under a POSIX path relative to a virtual root. This
4
+ * module is the one place that decides what such a path may look like.
5
+ *
6
+ * Containment is decided by where a path RESOLVES, not by whether it spells
7
+ * `..`: `lib/../lib/x.ts` is fine, `../x.ts` is not. A relative import that
8
+ * climbs within the tree is legitimate (a block in `blocks/a/b/` reaching
9
+ * `lib/` climbs three levels); one that climbs past the root is the escape.
10
+ */
11
+ import { posix } from 'node:path';
12
+ /** Thrown for a path that resolves outside the virtual root. */
13
+ export class PathEscapeError extends Error {
14
+ attempted;
15
+ constructor(attempted) {
16
+ super(`Path resolves outside the source tree: ${attempted}`);
17
+ this.attempted = attempted;
18
+ this.name = 'PathEscapeError';
19
+ }
20
+ }
21
+ /**
22
+ * Normalise a caller-supplied key to the canonical virtual form: forward
23
+ * slashes, no leading `./`, no `.`/`..` segments. Throws {@link PathEscapeError}
24
+ * for an absolute path (POSIX or drive-letter), a NUL byte, an empty path, or a
25
+ * path whose `..` segments climb past the root.
26
+ */
27
+ export function normalizeVirtualPath(raw) {
28
+ const slashed = raw.replace(/\\/g, '/');
29
+ if (slashed.length === 0 || slashed.includes('\0'))
30
+ throw new PathEscapeError(raw);
31
+ if (slashed.startsWith('/') || /^[A-Za-z]:/.test(slashed))
32
+ throw new PathEscapeError(raw);
33
+ const normalized = posix.normalize(slashed);
34
+ if (normalized === '..' || normalized.startsWith('../') || normalized === '.' || normalized.endsWith('/')) {
35
+ throw new PathEscapeError(raw);
36
+ }
37
+ return normalized;
38
+ }
39
+ /**
40
+ * Join a relative specifier onto the directory of `fromPath` and normalise.
41
+ * Throws {@link PathEscapeError} when the result leaves the root.
42
+ */
43
+ export function joinVirtual(fromPath, spec) {
44
+ const joined = posix.normalize(posix.join(posix.dirname(fromPath), spec));
45
+ if (joined === '..' || joined.startsWith('../') || joined.startsWith('/')) {
46
+ throw new PathEscapeError(spec);
47
+ }
48
+ return joined;
49
+ }
50
+ /** esbuild's default resolve order, which the on-disk compiler relied on. */
51
+ const RESOLVE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.json'];
52
+ /**
53
+ * The files a resolved-but-unextended path may name, in esbuild's own order:
54
+ * the exact path; for a `.js`/`.jsx`/`.mjs` spelling, the TypeScript file it
55
+ * stands for (esbuild rewrites `./x.js` to `./x.ts` the same way); the path
56
+ * plus each resolve extension; then `index.*` inside it.
57
+ */
58
+ export function resolveCandidates(joined) {
59
+ const out = [joined];
60
+ const ext = posix.extname(joined);
61
+ if (ext === '.js' || ext === '.jsx') {
62
+ const base = joined.slice(0, -ext.length);
63
+ out.push(`${base}.ts`, `${base}.tsx`);
64
+ }
65
+ else if (ext === '.mjs') {
66
+ out.push(`${joined.slice(0, -4)}.mts`);
67
+ }
68
+ for (const e of RESOLVE_EXTENSIONS)
69
+ out.push(`${joined}${e}`);
70
+ for (const e of RESOLVE_EXTENSIONS)
71
+ out.push(`${joined}/index${e}`);
72
+ return out;
73
+ }
74
+ //# sourceMappingURL=paths.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paths.js","sourceRoot":"","sources":["../src/paths.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AAEjC,gEAAgE;AAChE,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACnB;IAArB,YAAqB,SAAiB;QACpC,KAAK,CAAC,0CAA0C,SAAS,EAAE,CAAC,CAAA;QADzC,cAAS,GAAT,SAAS,CAAQ;QAEpC,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAA;IAC/B,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,GAAW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UAAU,iBAAiB,CAAC,MAAc;IAC9C,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAAA;IACpB,MAAM,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;IACjC,IAAI,GAAG,KAAK,KAAK,IAAI,GAAG,KAAK,MAAM,EAAE,CAAC;QACpC,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QACzC,GAAG,CAAC,IAAI,CAAC,GAAG,IAAI,KAAK,EAAE,GAAG,IAAI,MAAM,CAAC,CAAA;IACvC,CAAC;SAAM,IAAI,GAAG,KAAK,MAAM,EAAE,CAAC;QAC1B,GAAG,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAA;IACxC,CAAC;IACD,KAAK,MAAM,CAAC,IAAI,kBAAkB;QAAE,GAAG,CAAC,IAAI,CAAC,GAAG,MAAM,GAAG,CAAC,EAAE,CAAC,CAAA;IAC7D,KAAK,MAAM,CAAC,IAAI,kBAAkB;QAAE,GAAG,CAAC,IAAI,CAAC,GAAG,MAAM,SAAS,CAAC,EAAE,CAAC,CAAA;IACnE,OAAO,GAAG,CAAA;AACZ,CAAC"}
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Source screening — what a block or capability source may CONTAIN.
3
+ *
4
+ * ── THIS IS A HYGIENE CHECK, NOT A SECURITY BOUNDARY. ──
5
+ * It is a regex denylist over comment- and literal-masked text. Aliasing a global through a binding (`const g = globalThis;
6
+ * g['fe' + 'tch']`), `Reflect.get`, `top[...]` and similar spellings walk past
7
+ * it — the tests pin several as known gaps. Running untrusted block code safely
8
+ * is the HOST's job: an isolated origin or sandboxed iframe/worker for block
9
+ * bundles, plus a Content Security Policy. Do not treat a passing screen as
10
+ * permission to run a module with the host's privileges.
11
+ *
12
+ * Authorisation ("may this caller add a block") is the host's business. This
13
+ * answers the different question: once a source string reaches the compiler,
14
+ * may the module it becomes reach the ambient browser capabilities that turn
15
+ * "renders a component" into "reads your session and ships it somewhere"?
16
+ *
17
+ * A source that arrives as content — written by a model steered by text an
18
+ * attacker can influence, or posted directly by a caller — is compiled and then
19
+ * executed by every renderer that loads it, on the host's own origin, inside an
20
+ * authenticated session. So the module is constrained: it may render from its
21
+ * props; it may not reach network egress, credential stores or code
22
+ * construction.
23
+ *
24
+ * This narrows the blast radius. It does NOT stop prompt injection — see
25
+ * {@link screenSource}'s KNOWN GAPS for exactly what still gets through.
26
+ *
27
+ * The compiler does not call this for you: `compileAtom` compiles what it is
28
+ * given. A host that compiles untrusted source screens it first, and screens
29
+ * every companion the source reaches — `collectCompanions` does both.
30
+ *
31
+ * @module @pwfabric/compiler/screen
32
+ */
33
+ /**
34
+ * Module specifiers a screened source may import at VALUE level.
35
+ *
36
+ * DERIVED from the host import list (`blockBundleExternals()` over
37
+ * `BLOCK_HOST_IMPORTS` in `@pwfabric/core`), so the screen and
38
+ * the bundler can never disagree. A narrower hand-written list would refuse
39
+ * real packs, which import the runtime for the event bus, surface id and
40
+ * connection contexts. A specifier the bundler
41
+ * leaves external and every host maps for compiled blocks is a specifier the
42
+ * screen admits; one list says both.
43
+ *
44
+ * What still keeps a screened module from network egress, credential stores
45
+ * and code construction is layer 2 (the forbidden-capability scan) and the
46
+ * host's sandbox — not the narrowness of this list.
47
+ */
48
+ export declare const SCREEN_IMPORT_ALLOWLIST: readonly string[];
49
+ export type ScreenResult = {
50
+ readonly ok: true;
51
+ } | {
52
+ readonly ok: false;
53
+ readonly violations: readonly string[];
54
+ };
55
+ /**
56
+ * Blank out comments and (optionally) string/template/regex literal CONTENT,
57
+ * preserving byte offsets and newlines so reported line numbers stay true.
58
+ *
59
+ * Why this exists rather than a raw `source.includes('fetch(')`: a shipped
60
+ * first-party block's JSDoc says `same-origin fetch('/api/orders')`. A scan that
61
+ * did not strip comments would refuse a block for describing itself. Template
62
+ * SUBSTITUTIONS (`${...}`) are deliberately kept live — that is real code.
63
+ *
64
+ * The literal scanner must run even when `blankLiterals` is false, because a
65
+ * `//` or a `/` inside a string would otherwise be misread as a comment or a
66
+ * regex and swallow the rest of the file.
67
+ */
68
+ export declare function maskSource(src: string, blankLiterals: boolean): string;
69
+ /** Options for {@link screenSource}. */
70
+ export interface ScreenOptions {
71
+ /**
72
+ * The door for shared pack code. A value-level relative import is allowed
73
+ * only when this returns true for the specifier — i.e. the caller says it
74
+ * resolves to a file it will ship as a companion (`atoms/lib/*` or a
75
+ * `_shared-*` sibling) and will screen that file with this same function.
76
+ * Without the option every relative value import is rejected.
77
+ */
78
+ readonly allowRelativeImport?: (spec: string) => boolean;
79
+ }
80
+ /**
81
+ * Screen one source before it is allowed anywhere near the compiler. Returns
82
+ * every violation found (not just the first) so a repair loop gets a complete,
83
+ * actionable message.
84
+ *
85
+ * TWO LAYERS:
86
+ * 1. IMPORT ALLOWLIST — every value-level `import`/`export ... from` and bare
87
+ * `import '...'` specifier must be in {@link SCREEN_IMPORT_ALLOWLIST}.
88
+ * Relative specifiers are rejected at value level unless
89
+ * {@link ScreenOptions.allowRelativeImport} admits them, but permitted on
90
+ * `import type` / `export type` statements, which the compiler erases.
91
+ * 2. ESCAPE SCAN — the forbidden-capability patterns over the
92
+ * comment-and-literal-masked source.
93
+ *
94
+ * ── KNOWN GAPS. Read these before believing this closes anything. ──
95
+ *
96
+ * This is a DENYLIST over source text, not a sandbox, and it is deliberately
97
+ * incomplete. It does not stop:
98
+ *
99
+ * - **Prompt injection itself.** Attacker-controlled text still steers the
100
+ * model. All this changes is what the resulting module is allowed to do.
101
+ * - **`dangerouslySetInnerHTML` / `innerHTML`.** 30 of the 100 first-party
102
+ * blocks use `dangerouslySetInnerHTML` for inline SVG icon paths, so it is
103
+ * allowed — a screened block CAN inject arbitrary markup.
104
+ * - **Navigation-based exfiltration.** `window.location.href = ...` is used by
105
+ * first-party blocks for link handling, so it is allowed; a block can
106
+ * navigate the tab to an attacker URL with data in the query.
107
+ * - **Rendering hostile content into props/children**, phishing UI, and any
108
+ * purely-visual deception.
109
+ * - **Sufficiently indirect spellings.** The scan is textual: identifiers
110
+ * assembled at run time, property names built from arrays, aliasing a global
111
+ * through a permitted binding, or `top`/`parent` (excluded from the
112
+ * computed-access rule because they are common local names) can still reach
113
+ * a banned capability. Closing that class needs an execution sandbox (CSP +
114
+ * an isolated origin/worker for block bundles), not a string scan.
115
+ */
116
+ export declare function screenSource(source: string, opts?: ScreenOptions): ScreenResult;
117
+ /** Alternative name for `screenSource`. */
118
+ export declare const screenBlockSource: typeof screenSource;
119
+ /** Alternative name for `SCREEN_IMPORT_ALLOWLIST`. */
120
+ export declare const BLOCK_SOURCE_IMPORT_ALLOWLIST: readonly string[];
121
+ //# sourceMappingURL=screen.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"screen.d.ts","sourceRoot":"","sources":["../src/screen.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAIH;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,uBAAuB,EAAE,SAAS,MAAM,EAA+C,CAAA;AAEpG,MAAM,MAAM,YAAY,GACpB;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAA;CAAE,GACrB;IAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CAAA;AAyDlE;;;;;;;;;;;;GAYG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,GAAG,MAAM,CAuHtE;AAqBD,wCAAwC;AACxC,MAAM,WAAW,aAAa;IAC5B;;;;;;OAMG;IACH,QAAQ,CAAC,mBAAmB,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAA;CACzD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,aAAa,GAAG,YAAY,CAoD/E;AAED,2CAA2C;AAC3C,eAAO,MAAM,iBAAiB,qBAAe,CAAA;AAC7C,sDAAsD;AACtD,eAAO,MAAM,6BAA6B,mBAA0B,CAAA"}