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

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/LICENSE ADDED
@@ -0,0 +1,90 @@
1
+ Business Source License 1.1
2
+
3
+ Parameters
4
+
5
+ Licensor: PhiMajor Solutions
6
+ Licensed Work: @pwfabric/compiler 1.0.0
7
+ The Licensed Work is (c) 2026 PhiMajor Solutions.
8
+ Additional Use Grant: You may make production use of the Licensed Work,
9
+ including building applications with it and hosting
10
+ those applications for yourself or for your own
11
+ customers, provided you do not offer the Licensed Work
12
+ to third parties as a hosted or managed service where
13
+ the service gives them substantially the functionality
14
+ of the Licensed Work.
15
+ Change Date: 2030-10-06
16
+ Change License: Apache License, Version 2.0
17
+
18
+ For information about alternative licensing arrangements for the Licensed
19
+ Work, please contact licensing@phimajor.com.
20
+
21
+ Notice
22
+
23
+ Business Source License 1.1
24
+
25
+ Terms
26
+
27
+ The Licensor hereby grants you the right to copy, modify, create derivative
28
+ works, redistribute, and make non-production use of the Licensed Work. The
29
+ Licensor may make an Additional Use Grant, above, permitting limited
30
+ production use.
31
+
32
+ Effective on the Change Date, or the fourth anniversary of the first publicly
33
+ available distribution of a specific version of the Licensed Work under this
34
+ License, whichever comes first, the Licensor hereby grants you rights under
35
+ the terms of the Change License, and the rights granted in the paragraph
36
+ above terminate.
37
+
38
+ If your use of the Licensed Work does not comply with the requirements
39
+ currently in effect as described in this License, you must purchase a
40
+ commercial license from the Licensor, its affiliated entities, or authorized
41
+ resellers, or you must refrain from using the Licensed Work.
42
+
43
+ All copies of the original and modified Licensed Work, and derivative works
44
+ of the Licensed Work, are subject to this License. This License applies
45
+ separately for each version of the Licensed Work and the Change Date may vary
46
+ for each version of the Licensed Work released by Licensor.
47
+
48
+ You must conspicuously display this License on each original or modified copy
49
+ of the Licensed Work. If you receive the Licensed Work in original or
50
+ modified form from a third party, the terms and conditions set forth in this
51
+ License apply to your use of that work.
52
+
53
+ Any use of the Licensed Work in violation of this License will automatically
54
+ terminate your rights under this License for the current and all other
55
+ versions of the Licensed Work.
56
+
57
+ This License does not grant you any right in any trademark or logo of
58
+ Licensor or its affiliates (provided that you may use a trademark or logo of
59
+ Licensor as expressly required by this License).
60
+
61
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
62
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
63
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
64
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
65
+ TITLE.
66
+
67
+ MariaDB hereby grants you permission to use this License's text to license
68
+ your works, and to refer to it using the trademark "Business Source License",
69
+ as long as you comply with the Covenants of Licensor below.
70
+
71
+ Covenants of Licensor
72
+
73
+ In consideration of the right to use this License's text and the "Business
74
+ Source License" name and trademark, Licensor covenants to MariaDB, and to all
75
+ other recipients of the licensed work to be provided by Licensor:
76
+
77
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
78
+ or a license that is compatible with GPL Version 2.0 or a later version,
79
+ where "compatible" means that software provided under the Change License
80
+ can be included in a program with software provided under GPL Version 2.0
81
+ or a later version. Licensor may specify additional Change Licenses
82
+ without limitation.
83
+
84
+ 2. To either: (a) specify an additional grant of rights to use that does not
85
+ impose any additional restriction on the right granted in this License, as
86
+ the Additional Use Grant; or (b) insert the text "None".
87
+
88
+ 3. To specify a Change Date.
89
+
90
+ 4. Not to modify this License in any other way.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # @pwfabric/compiler
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The PWFabric atom compiler. A block's `component.tsx` (or a capability's
4
+ `handler.ts`, or a connector/provider engine) plus the companion files it
5
+ imports go in; one ES module the runtime can load comes out. The imports the
6
+ host provides — `react`, `zod`, the PWFabric packages; the list lives in
7
+ `@pwfabric/core` (`BLOCK_HOST_IMPORTS`) — stay external.
8
+
9
+ The compiler is pure: it works on an in-memory file map, writes nothing and
10
+ fetches nothing. Storing the bundle is the caller's job.
11
+
12
+ ```ts
13
+ import { collectCompanions, compileAtom, screenSource } from '@pwfabric/compiler'
14
+
15
+ const files = {
16
+ 'atoms/blocks/content/greeting/component.tsx': source,
17
+ 'atoms/lib/format.ts': libSource,
18
+ }
19
+ const entry = 'atoms/blocks/content/greeting/component.tsx'
20
+
21
+ // Untrusted source? Screen the entry and every companion it reaches first.
22
+ const scan = collectCompanions(files, entry)
23
+ if (!scan.ok) throw new Error(scan.violations.join('\n'))
24
+
25
+ const result = await compileAtom({ files, entry, companions: scan.companions })
26
+ if (result.ok) {
27
+ // result.code — the ES module
28
+ // result.hash — 'sha256:…' of the code
29
+ // result.externals — the host imports it needs
30
+ // result.compilerVersion / result.esbuildVersion — record them with the hash
31
+ } else {
32
+ console.error(result.diagnostics)
33
+ }
34
+ ```
35
+
36
+ Same input and the same compiler and esbuild versions give the same bytes.
37
+
38
+ `compileFolder(dir, entry)` reads a tree from disk and calls `compileAtom`.
39
+
40
+ ## What the compiler checks
41
+
42
+ - **Resolution is in memory.** Imports are resolved against the `files` map
43
+ only, never the disk: a climb past the tree root is `PATH_ESCAPE` (a path is
44
+ judged by where it resolves, not by whether it spells `..`), a missing file
45
+ is `UNRESOLVED_IMPORT`.
46
+ - **Bare imports must be host imports.** A bare import outside the host import
47
+ list is `NON_HOST_IMPORT`, listing the host imports. A subpath of a host
48
+ import (`@pwfabric/runtime/auth`) compiles but carries a
49
+ `HOST_SUBPATH_IMPORT` warning, because a host import map resolves exact
50
+ specifiers only; subpaths that are on the list in their own right (`/data`,
51
+ `/capability`, `/adapters`) compile without it.
52
+ - **Declared companions are enforced when given.** `companions` is optional;
53
+ when it is passed, a relative import of any other file is `NOT_A_COMPANION`.
54
+ Every file is keyed by its path from the tree root; `lib/` and `atoms/lib/`
55
+ are both accepted.
56
+ - **The generated wrapper never overwrites a file.** A tree that already holds
57
+ the wrapper's path is `INVALID_INPUT`.
58
+ - **Only script and JSON files load.** `.ts .mts .cts .tsx .js .mjs .cjs .jsx
59
+ .json`; anything else (CSS, for instance) is `UNSUPPORTED_FILE`.
60
+ - **Source maps are opt-in and external.** `sourcemap: true` returns `map` and
61
+ leaves `code` (and its hash) untouched — no `sourceMappingURL` comment.
62
+ - **Size is capped.** `MAX_ATOM_BUNDLE_BYTES` (500 KiB) unless `maxBytes` says
63
+ otherwise; over it is `BUNDLE_TOO_LARGE`.
64
+ - **The screen's import allowlist is the host import list**, derived from
65
+ `blockBundleExternals()`. The runtime hands a module classes that perform
66
+ network requests, so the import layer does not narrow egress by itself; the
67
+ escape scan and the host's sandbox do.
68
+
69
+ Storing the bundle, recording it, licence or permission checks, and deciding
70
+ which files of a pack are atoms are the caller's job.
71
+
72
+ ## Security notes
73
+
74
+ **Screening is a hygiene check, not a security boundary.** `screenSource` is a
75
+ regex denylist over masked text. It catches the obvious spellings a model
76
+ emits; it does not stop aliasing a global through a binding
77
+ (`const g = globalThis; g['fe' + 'tch']`), `Reflect.get(globalThis, …)`,
78
+ `top[…]`/`parent[…]`, or an aliased `document` read by computed key. Four of
79
+ these are pinned as `it.fails` tests in `src/__tests__/screen.test.ts` so an
80
+ AST-based screener can flip them. Isolating untrusted block code (a separate
81
+ origin or sandboxed iframe/worker for block bundles, plus a Content Security
82
+ Policy) is the host's responsibility.
83
+
84
+ **Names written into generated source are validated and quoted.** The entry
85
+ wrappers embed the entry basename (block/capability) and the engine name
86
+ (connector/provider) in generated source, and both come from pack file and
87
+ folder names. So:
88
+
89
+ - `compileAtom` refuses an entry basename outside `[A-Za-z0-9_.-]` (or
90
+ containing `..`) and an engine name outside `[A-Za-z0-9_-]` with
91
+ `INVALID_INPUT`;
92
+ - `buildWrapperSource` re-checks and throws;
93
+ - every specifier, property key and message built from a name is emitted via
94
+ `JSON.stringify`.
95
+
96
+ ## Determinism
97
+
98
+ The compile is a pure function of the `files` contents, `entry`, options, this
99
+ package's version and esbuild's version. The `files` map order, the working
100
+ directory and the operating system do not enter the output. esbuild is pinned
101
+ to an exact version for that reason; `compilerVersion` and `esbuildVersion`
102
+ are returned with every result so a caller can record them beside the hash.
103
+
104
+ Licensed under the Business Source License 1.1 — see [LICENSE](./LICENSE).
@@ -0,0 +1,29 @@
1
+ import { type ScreenOptions, type ScreenResult } from './screen.js';
2
+ /** A screening function with {@link screenSource}'s shape — injectable for tests or stricter hosts. */
3
+ export type ScreenFn = (source: string, opts?: ScreenOptions) => ScreenResult;
4
+ /**
5
+ * Whether a tree path may be reached by a value-level relative import:
6
+ * shared lib code (`lib/…`, `atoms/lib/…`) or a `_shared-*` file anywhere.
7
+ */
8
+ export declare function isCompanionTarget(path: string): boolean;
9
+ /**
10
+ * Resolve `spec`, imported from `fromPath`, to a companion file in `files`, or
11
+ * `null` when it does not name one (missing, outside the tree, or not a
12
+ * companion target).
13
+ */
14
+ export declare function resolveCompanion(fromPath: string, spec: string, files: ReadonlySet<string> | ReadonlyMap<string, unknown>): string | null;
15
+ /** Result of {@link collectCompanions}. */
16
+ export interface CompanionScan {
17
+ readonly ok: boolean;
18
+ /** Every screening violation; a companion's are prefixed with its path. */
19
+ readonly violations: readonly string[];
20
+ /** Companion paths the entry reaches, in discovery order. Pass to `compileAtom`. */
21
+ readonly companions: readonly string[];
22
+ }
23
+ /**
24
+ * Screen `entry` and every companion it reaches, transitively. A relative value
25
+ * import passes only when it resolves to a companion target, and that target is
26
+ * screened in turn. JSON companions are data: collected, not screened or
27
+ * followed.
28
+ */
29
+ export declare function collectCompanions(files: Readonly<Record<string, string | Uint8Array>>, entry: string, screen?: ScreenFn): CompanionScan;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Companions — the shared pack code an atom's entry may import at value level.
3
+ *
4
+ * A pack keeps code that several atoms share in `atoms/lib/` (or `lib/` in the
5
+ * rootless layout) and in `_shared-*` files next to the atoms. Those are the
6
+ * only files a value-level relative import may reach; anything else in the tree
7
+ * belongs to another atom and is not shipped with this one.
8
+ *
9
+ * {@link collectCompanions} walks an entry's relative imports transitively,
10
+ * screening the entry and every companion it reaches with the same
11
+ * {@link screenSource} rules, and returns the companion paths `compileAtom`
12
+ * should be given. It is pure: the tree comes in as a map, nothing is read.
13
+ *
14
+ * @module @pwfabric/compiler/companions
15
+ */
16
+ import { posix } from 'node:path';
17
+ import { screenSource } from './screen.js';
18
+ /**
19
+ * Whether a tree path may be reached by a value-level relative import:
20
+ * shared lib code (`lib/…`, `atoms/lib/…`) or a `_shared-*` file anywhere.
21
+ */
22
+ export function isCompanionTarget(path) {
23
+ if (path.startsWith('lib/') || path.startsWith('atoms/lib/'))
24
+ return true;
25
+ const base = path.slice(path.lastIndexOf('/') + 1);
26
+ return base.startsWith('_shared-');
27
+ }
28
+ /**
29
+ * Resolve `spec`, imported from `fromPath`, to a companion file in `files`, or
30
+ * `null` when it does not name one (missing, outside the tree, or not a
31
+ * companion target).
32
+ */
33
+ export function resolveCompanion(fromPath, spec, files) {
34
+ const joined = posix.normalize(posix.join(posix.dirname(fromPath), spec));
35
+ if (joined.startsWith('..') || joined.startsWith('/'))
36
+ return null;
37
+ const noJs = joined.replace(/\.(m?js|jsx)$/, '');
38
+ const candidates = [
39
+ joined,
40
+ `${noJs}.ts`,
41
+ `${noJs}.tsx`,
42
+ `${joined}.ts`,
43
+ `${joined}.tsx`,
44
+ `${joined}.json`,
45
+ `${joined}/index.ts`,
46
+ `${joined}/index.tsx`,
47
+ ];
48
+ for (const c of candidates) {
49
+ if (files.has(c) && isCompanionTarget(c))
50
+ return c;
51
+ }
52
+ return null;
53
+ }
54
+ function textOf(value) {
55
+ return typeof value === 'string' ? value : new TextDecoder().decode(value);
56
+ }
57
+ /**
58
+ * Screen `entry` and every companion it reaches, transitively. A relative value
59
+ * import passes only when it resolves to a companion target, and that target is
60
+ * screened in turn. JSON companions are data: collected, not screened or
61
+ * followed.
62
+ */
63
+ export function collectCompanions(files, entry, screen = screenSource) {
64
+ const index = new Map(Object.entries(files));
65
+ const source = index.get(entry);
66
+ if (source === undefined) {
67
+ return { ok: false, violations: [`entry '${entry}' is not in the source tree`], companions: [] };
68
+ }
69
+ const violations = [];
70
+ const companions = [];
71
+ const queue = [[entry, textOf(source)]];
72
+ const seen = new Set([entry]);
73
+ while (queue.length > 0) {
74
+ const [path, text] = queue.shift();
75
+ const reached = [];
76
+ const result = screen(text, {
77
+ allowRelativeImport: (spec) => {
78
+ const target = resolveCompanion(path, spec, index);
79
+ if (target)
80
+ reached.push(target);
81
+ return target !== null;
82
+ },
83
+ });
84
+ if (!result.ok) {
85
+ const prefix = path === entry ? '' : `${path}: `;
86
+ violations.push(...result.violations.map((v) => `${prefix}${v}`));
87
+ }
88
+ for (const target of reached) {
89
+ if (seen.has(target))
90
+ continue;
91
+ seen.add(target);
92
+ companions.push(target);
93
+ if (!target.endsWith('.json'))
94
+ queue.push([target, textOf(index.get(target))]);
95
+ }
96
+ }
97
+ return { ok: violations.length === 0, violations, companions };
98
+ }
99
+ //# sourceMappingURL=companions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"companions.js","sourceRoot":"","sources":["../src/companions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AACjC,OAAO,EAAE,YAAY,EAAyC,MAAM,aAAa,CAAA;AAKjF;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,IAAY;IAC5C,IAAI,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC;QAAE,OAAO,IAAI,CAAA;IACzE,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAA;IAClD,OAAO,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,CAAA;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,CAAC;QACD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,IAAI,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC;gBAAE,SAAQ;YAC9B,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;YAChB,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;YACvB,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;gBAAE,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAwB,CAAC,CAAC,CAAC,CAAA;QACvG,CAAC;IACH,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,UAAU,EAAE,UAAU,EAAE,CAAA;AAChE,CAAC","sourcesContent":["/**\n * Companions — the shared pack code an atom's entry may import at value level.\n *\n * A pack keeps code that several atoms share in `atoms/lib/` (or `lib/` in the\n * rootless layout) and in `_shared-*` files next to the atoms. Those are the\n * only files a value-level relative import may reach; anything else in the tree\n * belongs to another atom and is not shipped with this one.\n *\n * {@link collectCompanions} walks an entry's relative imports transitively,\n * screening the entry and every companion it reaches with the same\n * {@link screenSource} rules, and returns the companion paths `compileAtom`\n * should be given. It is pure: the tree comes in as a map, nothing is read.\n *\n * @module @pwfabric/compiler/companions\n */\nimport { posix } from 'node:path'\nimport { screenSource, type ScreenOptions, type ScreenResult } from './screen.js'\n\n/** A screening function with {@link screenSource}'s shape — injectable for tests or stricter hosts. */\nexport type ScreenFn = (source: string, opts?: ScreenOptions) => ScreenResult\n\n/**\n * Whether a tree path may be reached by a value-level relative import:\n * shared lib code (`lib/…`, `atoms/lib/…`) or a `_shared-*` file anywhere.\n */\nexport function isCompanionTarget(path: string): boolean {\n if (path.startsWith('lib/') || path.startsWith('atoms/lib/')) return true\n const base = path.slice(path.lastIndexOf('/') + 1)\n return base.startsWith('_shared-')\n}\n\n/**\n * Resolve `spec`, imported from `fromPath`, to a companion file in `files`, or\n * `null` when it does not name one (missing, outside the tree, or not a\n * companion target).\n */\nexport function resolveCompanion(\n fromPath: string,\n spec: string,\n files: ReadonlySet<string> | ReadonlyMap<string, unknown>\n): string | null {\n const joined = posix.normalize(posix.join(posix.dirname(fromPath), spec))\n if (joined.startsWith('..') || joined.startsWith('/')) return null\n const noJs = joined.replace(/\\.(m?js|jsx)$/, '')\n const candidates = [\n joined,\n `${noJs}.ts`,\n `${noJs}.tsx`,\n `${joined}.ts`,\n `${joined}.tsx`,\n `${joined}.json`,\n `${joined}/index.ts`,\n `${joined}/index.tsx`,\n ]\n for (const c of candidates) {\n if (files.has(c) && isCompanionTarget(c)) return c\n }\n return null\n}\n\n/** Result of {@link collectCompanions}. */\nexport interface CompanionScan {\n readonly ok: boolean\n /** Every screening violation; a companion's are prefixed with its path. */\n readonly violations: readonly string[]\n /** Companion paths the entry reaches, in discovery order. Pass to `compileAtom`. */\n readonly companions: readonly string[]\n}\n\nfunction textOf(value: string | Uint8Array): string {\n return typeof value === 'string' ? value : new TextDecoder().decode(value)\n}\n\n/**\n * Screen `entry` and every companion it reaches, transitively. A relative value\n * import passes only when it resolves to a companion target, and that target is\n * screened in turn. JSON companions are data: collected, not screened or\n * followed.\n */\nexport function collectCompanions(\n files: Readonly<Record<string, string | Uint8Array>>,\n entry: string,\n screen: ScreenFn = screenSource\n): CompanionScan {\n const index = new Map(Object.entries(files))\n const source = index.get(entry)\n if (source === undefined) {\n return { ok: false, violations: [`entry '${entry}' is not in the source tree`], companions: [] }\n }\n const violations: string[] = []\n const companions: string[] = []\n const queue: Array<[string, string]> = [[entry, textOf(source)]]\n const seen = new Set<string>([entry])\n while (queue.length > 0) {\n const [path, text] = queue.shift() as [string, string]\n const reached: string[] = []\n const result = screen(text, {\n allowRelativeImport: (spec) => {\n const target = resolveCompanion(path, spec, index)\n if (target) reached.push(target)\n return target !== null\n },\n })\n if (!result.ok) {\n const prefix = path === entry ? '' : `${path}: `\n violations.push(...result.violations.map((v) => `${prefix}${v}`))\n }\n for (const target of reached) {\n if (seen.has(target)) continue\n seen.add(target)\n companions.push(target)\n if (!target.endsWith('.json')) queue.push([target, textOf(index.get(target) as string | Uint8Array)])\n }\n }\n return { ok: violations.length === 0, violations, companions }\n}\n"]}
@@ -0,0 +1,86 @@
1
+ import { type AtomKind } from '@pwfabric/contracts';
2
+ /** Default cap on one compiled bundle; the caller may raise or lower it. */
3
+ export declare const MAX_ATOM_BUNDLE_BYTES: number;
4
+ /** esbuild language targets the compiler accepts. */
5
+ export type CompileTarget = 'es2018' | 'es2019' | 'es2020' | 'es2021' | 'es2022' | 'es2023' | 'es2024' | 'esnext';
6
+ /** Machine-readable reason for a diagnostic. */
7
+ export type DiagnosticCode =
8
+ /** Bad call shape: missing entry, empty source, a kind that is not bundled. */
9
+ 'INVALID_INPUT'
10
+ /** A file key or a relative import resolves outside the source tree. */
11
+ | 'PATH_ESCAPE'
12
+ /** A bare import that is not a host import. */
13
+ | 'NON_HOST_IMPORT'
14
+ /** A subpath of a host import — compiled external, but the host import map only resolves exact specifiers. */
15
+ | 'HOST_SUBPATH_IMPORT'
16
+ /** A relative import that names no file in the tree. */
17
+ | 'UNRESOLVED_IMPORT'
18
+ /** A relative import that names a file the caller did not declare as a companion. */
19
+ | 'NOT_A_COMPANION'
20
+ /** A file type the compiler has no loader for. */
21
+ | 'UNSUPPORTED_FILE'
22
+ /** A syntax or type-strip error reported by esbuild itself. */
23
+ | 'ESBUILD_FAILED'
24
+ /** The bundle is larger than `maxBytes`. */
25
+ | 'BUNDLE_TOO_LARGE';
26
+ export interface Diagnostic {
27
+ readonly severity: 'error' | 'warning';
28
+ readonly code: DiagnosticCode;
29
+ readonly message: string;
30
+ /** Virtual path of the file the diagnostic points at, when esbuild knows it. */
31
+ readonly file?: string;
32
+ readonly line?: number;
33
+ readonly column?: number;
34
+ }
35
+ export interface CompileInput {
36
+ /**
37
+ * The source tree: POSIX path relative to a virtual root → file content.
38
+ * Backslashes are normalised; absolute or root-escaping keys are refused.
39
+ */
40
+ readonly files: Readonly<Record<string, string | Uint8Array>>;
41
+ /**
42
+ * The entry's path in `files`. For `identity` kinds (block, capability) it is
43
+ * the atom's own source (`blocks/<cat>/<name>/component.tsx`). For
44
+ * `sibling-generated` kinds (connector, provider) it is the wrapper path the
45
+ * contract derives (`resolveSiblingEntry(...).wrapperPath`); the compiler
46
+ * generates that file, and the engine source must be in `files`.
47
+ */
48
+ readonly entry: string;
49
+ /**
50
+ * Paths in `files` the entry may reach through relative imports (shared lib
51
+ * code, `_shared-*` siblings, an engine source). Omitted → every file in
52
+ * `files` may be reached. Given → importing any other file is a
53
+ * `NOT_A_COMPANION` error. `collectCompanions()` computes this list.
54
+ */
55
+ readonly companions?: readonly string[];
56
+ /** Atom kind; drives the entry wrapper. Default `'block'`. */
57
+ readonly kind?: AtomKind;
58
+ /** `sibling-generated` kinds only: the engine's base name (connector `<Name>`, provider `<domain>`). */
59
+ readonly engineName?: string;
60
+ /** Default `'es2022'`. */
61
+ readonly target?: CompileTarget;
62
+ /** Default `true`. */
63
+ readonly minify?: boolean;
64
+ /** Produce a source map in `map`. Default `false`. */
65
+ readonly sourcemap?: boolean;
66
+ /** Bundle size cap in bytes. Default {@link MAX_ATOM_BUNDLE_BYTES}. */
67
+ readonly maxBytes?: number;
68
+ }
69
+ export interface CompileResult {
70
+ readonly ok: boolean;
71
+ /** The ES module. Empty when `ok` is false. */
72
+ readonly code: string;
73
+ /** Source map JSON, when `sourcemap` was requested and the compile succeeded. */
74
+ readonly map?: string;
75
+ /** `sha256:<hex>` of the UTF-8 bytes of `code`. Empty when `ok` is false. */
76
+ readonly hash: string;
77
+ /** Byte length of `code`. */
78
+ readonly size: number;
79
+ readonly diagnostics: readonly Diagnostic[];
80
+ /** Host imports the module imports, sorted. These are what the host must provide to load it. */
81
+ readonly externals: readonly string[];
82
+ readonly compilerVersion: string;
83
+ readonly esbuildVersion: string;
84
+ }
85
+ /** Compile one atom. Never throws for bad input — every problem is a diagnostic. */
86
+ export declare function compileAtom(input: CompileInput): Promise<CompileResult>;