@unframework.dev/compiler 0.0.0-stage → 0.2.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.
package/README.md CHANGED
@@ -1,3 +1,196 @@
1
- # Temporary Holding Version
1
+ # @unframework.dev/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 Unframework compiler (plan §5.1):
4
+
5
+ ```ts
6
+ import { compile } from "@unframework.dev/compiler";
7
+
8
+ const result = await compile(source, {
9
+ filename: "src/Hello.uf.tsx",
10
+ targets: ["react", "vue", "svelte", "solid", "angular", "qwik", "astro"],
11
+ });
12
+ result.outputs.vue; // [{ path: "Hello.vue", contents: "<template>…</template>\n" }]
13
+ result.diagnostics; // sorted, with stable UF codes
14
+ ```
15
+
16
+ `compile()` runs the passes in order: parse (oxc), analyse and lower into IR, the `ir` plugin hook,
17
+ the capability check for each target, each target's `emit`, the `output` plugin hook, and
18
+ formatting (oxfmt). It is a pure function of the source and the options, and it throws only for
19
+ invalid options (an unknown target name, two targets with one name): every other problem is a
20
+ diagnostic, including a plugin or a target that throws, or returns or reports something malformed. Hooks and
21
+ targets receive the IR frozen, a target's missing capability cell counts as unsupported, and two
22
+ output files whose paths differ only in case are reported, since they collide on macOS and Windows.
23
+ The `resolve` option gives each imported `.uf.tsx` module's public API (ADR-0053), which the
24
+ analyser lowers a parent's components by; `createFileResolver({ root, readFile, typeOracle })`
25
+ reads the file, analyses its declarations (never its children's), their types read through the
26
+ type oracle over the same root (ADR-0067), and caches that by its contents and its shapes. Without
27
+ `typeOracle`, a child's types are read from its own module alone. An import it
28
+ cannot resolve is UF1202, and a resolver that throws UF9001. The resolver's `stylesheet` reads each
29
+ stylesheet the source imports (ADR-0063), and `createFileResolver` also reads a child's sheets, for
30
+ the scope id its API carries, and caches by their text too: a sheet it cannot read is UF5005.
31
+ The resolver's `module` reads each shared `.ts` module the source imports or re-exports from, a
32
+ type re-export alone included (ADR-0070), a specifier without an extension naming its `.ts`, and
33
+ `createFileResolver` follows its relative imports through every `.ts` module they reach, each
34
+ once, noting the first framework or `@uxfront/unframework` import (UF1204) and the first relative import it
35
+ cannot read (UF1202). A value import of a module it
36
+ cannot read, or without a resolver, is UF1202. Each output tree beside a component's files holds a
37
+ copy of every module the source reaches, unchanged, at its path relative to the source: neither
38
+ the hooks nor formatting see it, and `owners` leaves it out. A copy named like a component's output
39
+ file, without the extensions (an output imports `./CardIcon`, and `./card-icon` on Angular), is
40
+ UF1104 at the import that reaches it, for the module's own components and every child it
41
+ imports, and withholds the module from every target.
42
+ After the `ir` hooks, `compile()` runs the codegen scoper once per sheet of the module the targets
43
+ emit from; a selector it rejects (UF5004, in the sheet's file) withholds the module from every
44
+ target, as an analyser error does. A styled component's files end, on every target, with its
45
+ scoped sheet, `<source>.css` (`Button.uf.tsx.css`): its sheets scoped and joined in import order,
46
+ which the `output` hooks see and formatting keeps as printed. `CompileResult.owners` names the
47
+ component each output file is written for, by target, which the unplugin loads files by; the
48
+ sheet is no component's module, and is left out.
49
+ The `typeOracle` option is the type oracle (plan §5.5, ADR-0067): before it analyses, `compile()`
50
+ asks it for the shape of each type the analyser reads (`shapeQueries`), and the analyser lowers
51
+ props from those shapes, so a props type may come from another file or a package. Its queries name
52
+ files relative to its root, as `filename` is. Without it, `compile()` uses an in-process syntactic
53
+ oracle over the one source, which reads no file, so an imported type is UF6001; an oracle that
54
+ throws is UF9001. `createSyntacticOracle({ root, readFile })` is the type oracle's syntactic
55
+ adapter, re-exported so a caller builds a file-backed one without another dependency; the caller
56
+ disposes of its oracle. The oracle reads the source's own file too, so it must hold the text
57
+ `compile()` is given: a caller that compiles an unsaved edit updates its oracle first.
58
+ `CompileResult.dependencies` lists what the compile read or looked for through the oracle: files
59
+ relative to its root, and packages as `pkg:<name>`, a package that is not installed included,
60
+ sorted (ADR-0071). It also lists each shared `.ts` module the resolver read, and each `.uf.ts`
61
+ module whose composables the source imports, one that is missing included, named as `filename` is.
62
+
63
+ **Source maps** (ADR-0074). With `sourceMap: true`, each output file has a `map`: version 3, whose
64
+ `sources` name the source relative to the file and whose `sourcesContent` holds it. `compile()`
65
+ anchors each file after the `output` hooks, from its own component's code, and carries the map
66
+ through formatting. The hooks never see a map, and a `map` a hook or a target returns is dropped.
67
+
68
+ A copy of a shared `.ts` module gets an identity map, whose source is the copy itself. A scoped
69
+ sheet's map has no segments, since its text isn't this source's. Most of what the targets copy from
70
+ the source is mapped token by token, and each mapped token reads the same in both files. A run of
71
+ punctuation alone, a short run the output holds in several places and a target's own code stay
72
+ unmapped, so a frame there resolves to the nearest segment on its line, if there is one.
73
+
74
+ A map that can't follow formatting is UF9002, and the file comes without one: the formatter broke,
75
+ or a target or a plugin printed what oxfmt rewrites, like `title="don&apos;t"`. A diff
76
+ whose trace passes 256 MB, as a large table of numbers oxfmt rewrites makes it, is the warning
77
+ UF9003, and the file comes without one too. A file that doesn't
78
+ parse stays as printed, with the map of what was printed, and `format: false` keeps the anchored
79
+ map as it is. Maps don't change the files' text, and they never enter the golden files.
80
+
81
+ **The project graph** (ADR-0071). `createProject({ root, readFile, targets, typeOracle })` takes
82
+ the files `createFileResolver` does and the options each compile takes, but `filename` and
83
+ `resolve`. Its `compile(file)` compiles a module, named relative to `root`, through its own
84
+ resolver and the caller's oracle, and keeps the result. The result leaves out the copies of shared
85
+ `.ts` modules: each copy is its module's own node, which `copy(file)` gives. `copies(file)` gives
86
+ a compiled module's copies at their paths relative to it, each with its module's current text: with
87
+ the result's outputs, they are what `compile()` emits (the unplugin's golden guard reads them), but
88
+ for a copy named like a component's output, which `compile()` leaves out with UF1104.
89
+
90
+ Its `update(files)` tells the oracle which files changed, and reads again the copies among them.
91
+ Then it checks every compiled module that reaches a changed file, directly or not, along the
92
+ graph's reverse edges. It compiles a module again only where a hash of its source and of every
93
+ answer it was given changed: its children's APIs and the shapes they were read with, its
94
+ stylesheets, the files of its shared modules with the first import they cannot read, its cycles
95
+ and its own types' shapes. So an edit that leaves a shape alone stops there. A module's edges are
96
+ every file those answers read, each missing `.ts` file a shared module imports included, and an
97
+ update renews them even when the key holds. It returns the modules it compiled and the copies
98
+ that were added, changed or went.
99
+
100
+ `dependencies(file)` lists what a module read. A caller that changes a file without `update` gets
101
+ the last result. `createFileResolver` is a project's `resolve`.
102
+
103
+ **Cycles.** The resolver's `cycle` gives the files of the cycle of component edges an import
104
+ closes, from the importer back to it: a component edge is a value import of a component from
105
+ another `.uf.tsx` module. `compile()` asks it for each of the source's own component edges and
106
+ reports UF1205 at the import that closes a cycle, which withholds the module from every target, as
107
+ an analyser error does. An injection key, a type or a shared module imported back closes no cycle
108
+ (UF2033's context pattern), and a component that imports itself is UF1203's.
109
+
110
+ **Composables** (ADR-0069). The resolver gives a `.uf.ts` module's API too: its `composables`,
111
+ each with its parameters' kinds and its members' kinds and flags, which a caller's `Use` item is
112
+ lowered by, so a caller's output never depends on a composable's body. `compile()` also takes a
113
+ `.uf.ts` source: its IR holds the module's composables and no component, and each target emits
114
+ each composable with its `emitComposable`, formatted as a component's files are, with `owners`
115
+ naming the composable. The `output` hooks see none of it. Every built-in target has
116
+ `emitComposable`. It is optional for a third-party target: one without it reports UF1002 at the
117
+ composable, for that target, and emits nothing for it.
118
+ A capability that refines one the target cannot support (a listener's options and semantics, and
119
+ `nextTick`, refine `interactivity`: codegen's `CAPABILITY_PREREQUISITES`) is not reported again, so
120
+ Astro reports one inert listener once.
121
+
122
+ An `ir` hook's module must be valid IR (its schema and `checkInvariants`), keep the analysed file
123
+ and every span inside the source, and hold only the expressions, setup code, functions (their
124
+ parameters, types, defaults, bodies, event controls and flags), type annotations, declared events,
125
+ type declarations and stylesheets with their scope id the analyser produced for that source, each
126
+ whole (span, code and every reference with all its fields: a write stays a write, a call a call):
127
+ a plugin may move, copy or drop analysed code, never write its own, because every target copies
128
+ that code into its output and the IR cannot parse it (ADR-0032). Each function stays in a place of its context and role,
129
+ and each piece of code in a place of its context and kind (statements or an expression): the
130
+ analyser judges client code by looser rules than a getter or an initial value (ADR-0045), so a
131
+ local function moved into a `computed` is refused. A module that breaks any of this is UF8001,
132
+ and the hook's result is dropped.
133
+
134
+ ## Configuration
135
+
136
+ `loadConfig` and `resolveConfig` read a project's `unframework.config.ts` (plan §8.1, ADR-0076). The
137
+ bundler plugin doesn't call them: it takes explicit options.
138
+
139
+ ```ts
140
+ import { loadConfig, resolveConfig } from "@unframework.dev/compiler";
141
+
142
+ async function readConfig(root: string) {
143
+ const loaded = await loadConfig(root);
144
+ // A file that failed to load leaves nothing to check.
145
+ if (loaded.diagnostics.length > 0) return { config: undefined, diagnostics: loaded.diagnostics };
146
+ return resolveConfig(loaded.raw, loaded);
147
+ }
148
+ ```
149
+
150
+ `loadConfig(root, file?)` imports `file`, relative to `root`, or the first of
151
+ `unframework.config.ts`, `.mts`, `.js` and `.mjs` it finds in `root`. Node's type stripping loads a
152
+ TypeScript config, so a loader isn't needed. A project with no config file gets `raw: {}` and no
153
+ diagnostic, so it takes the defaults.
154
+
155
+ A file it can't import, or one with no default export, is UF7001. `loadConfig` reports it in its own
156
+ `diagnostics` and leaves `raw` as `undefined`, so read those first: `resolveConfig` would only say
157
+ that `undefined` isn't an object.
158
+
159
+ A `.ts` or `.js` file with no ES module syntax left once its types are stripped loads as CommonJS
160
+ unless its package sets `"type": "module"`. Node gives such a file an empty `default` only when it
161
+ exports nothing, and that counts as no default export. So does an explicit `module.exports = {}`,
162
+ which reads the same. A CommonJS file that does export something keeps what it exports.
163
+
164
+ `resolveConfig(raw, origin?)` checks the config and applies the defaults. It's asynchronous, because
165
+ a Standard Schema may be. `origin` is what `loadConfig` returned: `directory`, which relative paths
166
+ resolve against, and `file`, which diagnostics name. Each one has a default: the working directory,
167
+ and `unframework.config.ts`.
168
+
169
+ | Field | Default | Checked |
170
+ | --------------------- | ----------- | ---------------------------------------------------------------- |
171
+ | `targets` | all seven | a list of at least one built-in name, none repeated |
172
+ | `srcDir` | `src` | a path that isn't empty, made absolute |
173
+ | `outDir` | `dist` | a path that isn't empty, made absolute |
174
+ | `targetOptions` | `{}` | each key a built-in name, each value through its target's schema |
175
+ | `typeOracle` | `syntactic` | `syntactic` or `tsgo` |
176
+ | `strict` | `false` | a boolean |
177
+ | `package.targets` | left out | as `targets`, and each name also in `targets` |
178
+ | `package.resolveFrom` | left out | a path, or a path per built-in name, each made absolute |
179
+ | `vite` | left out | a function, kept as it is (ADR-0104) |
180
+ | `liveFonts` | `[]` | a list of font family names that aren't empty (ADR-0105) |
181
+
182
+ A field of the wrong shape, or one the config doesn't have, is UF7002. A name that isn't a built-in
183
+ target is UF7003, with a did-you-mean where one is close. Options a target's schema rejects are
184
+ UF7004, and options a schema returns replace the ones written.
185
+
186
+ A target without a schema takes no options, so any key under it is UF7004 too. No built-in target
187
+ declares a schema yet, so `react: { compiler: true }` reports "`react` declares no options" until
188
+ React declares that option.
189
+
190
+ `vite` and `liveFonts` are for `unframework test`, `visual` and `preview`, which
191
+ `@unframework.dev/testing` and `@unframework.dev/visual` read. `compile()`, `build` and `check`
192
+ ignore them. `DEFAULT_PASS_THROUGH`, the analyser's default prefixes, is exported for the harness,
193
+ which declares the modules under them for Angular's compile.
194
+
195
+ Each message gives the field's JSON pointer, and `config` is `undefined` when there is any
196
+ diagnostic. A known field set to `undefined` counts as left out.
@@ -0,0 +1,15 @@
1
+ import { Target } from "@unframework.dev/codegen";
2
+ import { Diagnostic } from "@unframework.dev/diagnostics";
3
+ import { UfModule } from "@unframework.dev/ir";
4
+ //#region src/capabilities.d.ts
5
+ /**
6
+ * Pass P4: checks the capabilities a module uses against a target's matrix and reports a
7
+ * portability diagnostic for each one the target cannot support, where the module first uses
8
+ * it. A capability the matrix does not declare (a third-party target written before the
9
+ * capability existed) is unsupported: nothing says the target can lower it. A capability that
10
+ * refines another the target cannot support either (a listener's options and semantics, and
11
+ * `nextTick`, refine `interactivity`: `CAPABILITY_PREREQUISITES`) is not reported again: the
12
+ * one report says the listener is inert, where three would say it at the same span.
13
+ */
14
+ export declare function checkCapabilities(module: UfModule, target: Target): Diagnostic[];
15
+ //#endregion
@@ -0,0 +1,44 @@
1
+ import { CAPABILITY_PREREQUISITES, requiredCapabilities } from "@unframework.dev/codegen";
2
+ import { createDiagnostic } from "@unframework.dev/diagnostics";
3
+ //#region src/capabilities.ts
4
+ /**
5
+ * Pass P4: checks the capabilities a module uses against a target's matrix and reports a
6
+ * portability diagnostic for each one the target cannot support, where the module first uses
7
+ * it. A capability the matrix does not declare (a third-party target written before the
8
+ * capability existed) is unsupported: nothing says the target can lower it. A capability that
9
+ * refines another the target cannot support either (a listener's options and semantics, and
10
+ * `nextTick`, refine `interactivity`: `CAPABILITY_PREREQUISITES`) is not reported again: the
11
+ * one report says the listener is inert, where three would say it at the same span.
12
+ */
13
+ function checkCapabilities(module, target) {
14
+ const diagnostics = [];
15
+ const required = requiredCapabilities(module);
16
+ const cellOf = (capability) => target.capabilities?.[capability];
17
+ const supports = (capability) => {
18
+ const support = cellOf(capability)?.support;
19
+ return support === "native" || support === "emulated";
20
+ };
21
+ for (const [capability, span] of required) {
22
+ if (supports(capability)) continue;
23
+ const prerequisite = CAPABILITY_PREREQUISITES[capability];
24
+ if (prerequisite && required.has(prerequisite) && !supports(prerequisite)) continue;
25
+ const cell = cellOf(capability);
26
+ const at = {
27
+ file: module.file,
28
+ span,
29
+ target: target.name
30
+ };
31
+ diagnostics.push(cell?.support === "unsupported" ? createDiagnostic(cell.code, {
32
+ ...at,
33
+ severity: cell.severity,
34
+ message: `The ${target.name} target does not support ${capability}: ${cell.reason}`
35
+ }) : createDiagnostic("UF4001", {
36
+ ...at,
37
+ severity: "error",
38
+ message: `The ${target.name} target does not declare whether it supports ${capability}, so the compiler treats it as unsupported.`
39
+ }));
40
+ }
41
+ return diagnostics;
42
+ }
43
+ //#endregion
44
+ export { checkCapabilities };
@@ -0,0 +1,128 @@
1
+ import { TargetName } from "./config-types.js";
2
+ import { Resolver } from "./resolver.js";
3
+ import "./targets.js";
4
+ import { OutputFile, Target } from "@unframework.dev/codegen";
5
+ import { Diagnostic } from "@unframework.dev/diagnostics";
6
+ import { UfComponent, UfModule } from "@unframework.dev/ir";
7
+ import { TypeOracle } from "@unframework.dev/type-oracle";
8
+ //#region src/compile.d.ts
9
+ /** What an `output` plugin hook receives besides the files. */
10
+ export interface OutputHookContext {
11
+ target: string;
12
+ component: UfComponent;
13
+ module: UfModule;
14
+ }
15
+ /**
16
+ * A compiler plugin (plan §5.10). Hooks are pure: the module and the files they receive are
17
+ * frozen, so a hook returns a new value to change them. A hook that throws, or returns a value
18
+ * that is not valid IR (by its schema and its invariants, `checkInvariants`) or a list of
19
+ * files, becomes a UF8001 diagnostic and its step is left out. An `ir` hook's module also keeps
20
+ * the analysed file and every span in the source, and holds only expressions, type annotations
21
+ * and type declarations the analyser produced: it may move, copy or drop analysed code, never
22
+ * write its own.
23
+ */
24
+ export interface CompilerPlugin {
25
+ name: string;
26
+ /** Transforms the IR after analysis. Return a new module, or nothing to keep it. */
27
+ ir?(module: UfModule): UfModule | void;
28
+ /** Transforms one component's files for one target, before formatting. */
29
+ output?(files: readonly OutputFile[], context: OutputHookContext): OutputFile[] | void;
30
+ }
31
+ /** Options for {@link compile}. */
32
+ export interface CompileOptions {
33
+ /**
34
+ * The file name as it appears in the IR and in diagnostics. Pass a project-relative path
35
+ * with forward slashes for output that does not depend on the machine.
36
+ */
37
+ filename: string;
38
+ /** The targets to emit, by name or as target objects. */
39
+ targets: readonly (TargetName | Target)[];
40
+ /** Formats the output with oxfmt. Defaults to `true`; the dev server may skip it. */
41
+ format?: boolean;
42
+ /**
43
+ * Gives each output file a `map` back to the source (ADR-0074): anchored after the `output`
44
+ * hooks, then carried through formatting. Defaults to `false`. A map that can't follow formatting
45
+ * is UF9002, and one whose diff passes its cap is UF9003, a warning: either way the file comes
46
+ * without one.
47
+ */
48
+ sourceMap?: boolean;
49
+ plugins?: readonly CompilerPlugin[];
50
+ /** Each target's options, by target name. */
51
+ targetOptions?: Readonly<Record<string, unknown>>;
52
+ /**
53
+ * Resolves an imported `.uf.tsx` module to its public API (ADR-0053): `createFileResolver`
54
+ * reads files. `importer` is `filename`. It is pure and deterministic (P8): it analyses the
55
+ * child's declarations, never compiles it, so the output depends only on the source, the
56
+ * options and what it returns. Without it, or when it returns nothing, the import is UF1202;
57
+ * a resolver that throws is UF9001 as well. Its `stylesheet` reads each stylesheet the source
58
+ * imports (ADR-0063): without it, or when it returns nothing, the import is UF5005. Its `module`
59
+ * reads each shared `.ts` module the source imports (ADR-0070): without it, or when it returns
60
+ * nothing, a value import of one is UF1202.
61
+ */
62
+ resolve?: Resolver;
63
+ /**
64
+ * The specifier prefixes whose imports pass through to every output as written (plan §4.4,
65
+ * ADR-0064): a styling engine's virtual modules, which its own bundler plugin resolves. It
66
+ * defaults to `["virtual:"]`, Vite's convention for a module a plugin registers, and a list
67
+ * replaces the default (`["virtual:", "styled-system/"]`). A prefix that is empty, relative or
68
+ * absolute throws (`checkPassThrough`). An import the analyser classifies itself (the
69
+ * authoring API, a framework, a `.uf.tsx` or relative module) never passes through.
70
+ */
71
+ passThrough?: readonly string[];
72
+ /**
73
+ * The type oracle the props, events, models, slots and injection keys' types are resolved
74
+ * through (plan §5.5, ADR-0067): `compile()` asks it for each type the analyser reads before it
75
+ * analyses, as it asks the resolver for each child's API. Its queries name files relative to its
76
+ * root, so `filename` is relative to that root too. Without it, `compile()` uses an in-process
77
+ * syntactic oracle over the one source, which reads no file: a type imported from another
78
+ * module is UF6001. An oracle that throws is UF9001 as well. It reads the source's own file
79
+ * too, so it must hold the text given here. The caller owns it, and disposes of it.
80
+ */
81
+ typeOracle?: TypeOracle;
82
+ }
83
+ /**
84
+ * Checks the `passThrough` option (ADR-0064): throws when a prefix is empty, or starts with `.`,
85
+ * `/`, `\\` or a drive letter, since such a specifier names a file of the project, a component's
86
+ * own sheet or a child, never a module a plugin registers.
87
+ */
88
+ export declare function checkPassThrough(prefixes: readonly string[]): void;
89
+ /** The result of {@link compile}. */
90
+ export interface CompileResult {
91
+ filename: string;
92
+ /** The module's IR (frozen), or `undefined` when module-level errors stop compilation. */
93
+ ir: UfModule | undefined;
94
+ /** Every diagnostic, sorted. Portability diagnostics carry their target. */
95
+ diagnostics: Diagnostic[];
96
+ /**
97
+ * Each target's files, by target name, in the order of `targets`: each component's, then a copy
98
+ * of each shared `.ts` module the source reaches, unchanged, at its path relative to the source
99
+ * (ADR-0070).
100
+ */
101
+ outputs: Record<string, OutputFile[]>;
102
+ /**
103
+ * The component each output file is written for, by target name, then by the file's path, or
104
+ * the composable for a `.uf.ts` source's: the unplugin loads a file's components under ids of
105
+ * their own (ADR-0053). The scoped sheet, `<source>.css`, is no component's module, and is left
106
+ * out (ADR-0063).
107
+ */
108
+ owners: Record<string, Record<string, string>>;
109
+ /**
110
+ * What the compile read besides the source, sorted, each once (ADR-0071): the files the type
111
+ * oracle read or looked for, relative to its root, the shared `.ts` modules the resolver read,
112
+ * named as `filename` is, the `.uf.ts` modules whose composables the source imports, named so
113
+ * too, one that is missing included (ADR-0069), and the packages, as `pkg:<name>`, one that is
114
+ * not installed included. Never an absolute path (P8).
115
+ */
116
+ dependencies: string[];
117
+ }
118
+ /**
119
+ * Compiles one `.uf.tsx` source, or a `.uf.ts` module of composables (ADR-0069), to every
120
+ * selected target. A pure function of the source and
121
+ * the options: the same input and versions give byte-identical output (P8). It throws only
122
+ * for invalid options (an unknown target name, two targets with one name, an invalid
123
+ * `passThrough` prefix); every other
124
+ * problem, a misbehaving plugin or target included, is a diagnostic, and an error in one
125
+ * component or target never stops the others.
126
+ */
127
+ export declare function compile(source: string, options: CompileOptions): Promise<CompileResult>;
128
+ //#endregion