@pbuilder/sdk 0.1.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.
Files changed (121) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +202 -0
  3. package/dist/bin/pbuilder-codegen.js +506 -0
  4. package/dist/bin/pbuilder-runner.d.ts +1 -0
  5. package/dist/bin/pbuilder-runner.js +47 -0
  6. package/dist/commons/classify-content.d.ts +40 -0
  7. package/dist/commons/classify-content.js +32 -0
  8. package/dist/commons/index.d.ts +271 -0
  9. package/dist/commons/index.js +276 -0
  10. package/dist/conformance/index.d.ts +115 -0
  11. package/dist/conformance/index.js +218 -0
  12. package/dist/conformance/run-vehicle.d.ts +19 -0
  13. package/dist/conformance/run-vehicle.js +104 -0
  14. package/dist/core/authoring-error.d.ts +116 -0
  15. package/dist/core/authoring-error.js +205 -0
  16. package/dist/core/base-handle.d.ts +17 -0
  17. package/dist/core/base-handle.js +4 -0
  18. package/dist/core/context.d.ts +85 -0
  19. package/dist/core/context.js +356 -0
  20. package/dist/core/deep-equal.d.ts +1 -0
  21. package/dist/core/deep-equal.js +29 -0
  22. package/dist/core/define-dialect.d.ts +94 -0
  23. package/dist/core/define-dialect.js +121 -0
  24. package/dist/core/dialect-error.d.ts +8 -0
  25. package/dist/core/dialect-error.js +26 -0
  26. package/dist/core/dialect-handle.d.ts +21 -0
  27. package/dist/core/dialect-handle.js +382 -0
  28. package/dist/core/directive-factory.d.ts +47 -0
  29. package/dist/core/directive-factory.js +154 -0
  30. package/dist/core/emit-rejection.d.ts +19 -0
  31. package/dist/core/emit-rejection.js +31 -0
  32. package/dist/core/engine-client.d.ts +7 -0
  33. package/dist/core/engine-client.js +5 -0
  34. package/dist/core/fs-errors.d.ts +1 -0
  35. package/dist/core/fs-errors.js +5 -0
  36. package/dist/core/handle-state.d.ts +24 -0
  37. package/dist/core/handle-state.js +4 -0
  38. package/dist/core/index.d.ts +10 -0
  39. package/dist/core/index.js +6 -0
  40. package/dist/core/jsx-name-validator.d.ts +19 -0
  41. package/dist/core/jsx-name-validator.js +104 -0
  42. package/dist/core/reject-tail.d.ts +23 -0
  43. package/dist/core/reject-tail.js +63 -0
  44. package/dist/core/schema/input-rejection.d.ts +4 -0
  45. package/dist/core/schema/input-rejection.js +32 -0
  46. package/dist/core/schema/schema-digest.d.ts +1 -0
  47. package/dist/core/schema/schema-digest.js +7 -0
  48. package/dist/core/schema/schema-discovery.d.ts +13 -0
  49. package/dist/core/schema/schema-discovery.js +51 -0
  50. package/dist/core/schema/schema-locate.d.ts +10 -0
  51. package/dist/core/schema/schema-locate.js +192 -0
  52. package/dist/core/schema/schema-model.d.ts +18 -0
  53. package/dist/core/schema/schema-model.js +15 -0
  54. package/dist/core/schema/schema-parse.d.ts +20 -0
  55. package/dist/core/schema/schema-parse.js +80 -0
  56. package/dist/core/schema/schema-sufficiency.d.ts +17 -0
  57. package/dist/core/schema/schema-sufficiency.js +54 -0
  58. package/dist/core/schema/schema-validate.d.ts +14 -0
  59. package/dist/core/schema/schema-validate.js +64 -0
  60. package/dist/core/session.d.ts +13 -0
  61. package/dist/core/session.js +72 -0
  62. package/dist/core/wire.d.ts +87 -0
  63. package/dist/core/wire.js +49 -0
  64. package/dist/dialects/react/ast.d.ts +25 -0
  65. package/dist/dialects/react/ast.js +80 -0
  66. package/dist/dialects/react/index.d.ts +39 -0
  67. package/dist/dialects/react/index.js +71 -0
  68. package/dist/dialects/react/ops.d.ts +56 -0
  69. package/dist/dialects/react/ops.js +186 -0
  70. package/dist/dialects/typescript/ast.d.ts +42 -0
  71. package/dist/dialects/typescript/ast.js +93 -0
  72. package/dist/dialects/typescript/index.d.ts +32 -0
  73. package/dist/dialects/typescript/index.js +40 -0
  74. package/dist/dialects/typescript/ops.d.ts +123 -0
  75. package/dist/dialects/typescript/ops.js +365 -0
  76. package/dist/dry-run/index.d.ts +2 -0
  77. package/dist/dry-run/index.js +1 -0
  78. package/dist/dry-run/plan.d.ts +69 -0
  79. package/dist/dry-run/plan.js +44 -0
  80. package/dist/index.d.ts +1 -0
  81. package/dist/index.js +3 -0
  82. package/dist/runner-manifest.json +104 -0
  83. package/dist/scaffold/classify-transport.d.ts +57 -0
  84. package/dist/scaffold/classify-transport.js +123 -0
  85. package/dist/scaffold/containment.d.ts +54 -0
  86. package/dist/scaffold/containment.js +242 -0
  87. package/dist/scaffold/expander.d.ts +30 -0
  88. package/dist/scaffold/expander.js +161 -0
  89. package/dist/scaffold/filename-pipeline.d.ts +39 -0
  90. package/dist/scaffold/filename-pipeline.js +125 -0
  91. package/dist/scaffold/index.d.ts +45 -0
  92. package/dist/scaffold/index.js +99 -0
  93. package/dist/scaffold/walk.d.ts +25 -0
  94. package/dist/scaffold/walk.js +124 -0
  95. package/dist/testing/contract-fake.d.ts +17 -0
  96. package/dist/testing/contract-fake.js +221 -0
  97. package/dist/testing/index.d.ts +84 -0
  98. package/dist/testing/index.js +82 -0
  99. package/dist/testing/rejection-messages.d.ts +7 -0
  100. package/dist/testing/rejection-messages.js +12 -0
  101. package/dist/transport/bootstrap-bridge.d.ts +33 -0
  102. package/dist/transport/bootstrap-bridge.js +65 -0
  103. package/dist/transport/error-text.d.ts +8 -0
  104. package/dist/transport/error-text.js +44 -0
  105. package/dist/transport/exit-codes.d.ts +2 -0
  106. package/dist/transport/exit-codes.js +35 -0
  107. package/dist/transport/factory-pointer.d.ts +32 -0
  108. package/dist/transport/factory-pointer.js +63 -0
  109. package/dist/transport/frame-reader.d.ts +10 -0
  110. package/dist/transport/frame-reader.js +81 -0
  111. package/dist/transport/framing.d.ts +20 -0
  112. package/dist/transport/framing.js +98 -0
  113. package/dist/transport/runner.d.ts +25 -0
  114. package/dist/transport/runner.js +308 -0
  115. package/dist/transport/single-instance-probe.d.ts +23 -0
  116. package/dist/transport/single-instance-probe.js +119 -0
  117. package/dist/transport/stdio-engine-client.d.ts +27 -0
  118. package/dist/transport/stdio-engine-client.js +243 -0
  119. package/dist/transport/wire-protocol.d.ts +33 -0
  120. package/dist/transport/wire-protocol.js +22 -0
  121. package/package.json +93 -0
@@ -0,0 +1,271 @@
1
+ import type { JsonValue } from "../core/wire.ts";
2
+ import type { FoundHandle, WritableHandle } from "../core/handle-state.ts";
3
+ import { AuthoringError } from "../core/authoring-error.ts";
4
+ import type { AuthoringVerb, AuthoringReason, AuthoringOrigin } from "../core/authoring-error.ts";
5
+ import type { ScaffoldArgs } from "../scaffold/index.ts";
6
+ export type { FoundHandle, WritableHandle };
7
+ export { AuthoringError };
8
+ export type { AuthoringVerb, AuthoringReason, AuthoringOrigin };
9
+ export { classifyContent } from "./classify-content.ts";
10
+ export type { ContentState } from "./classify-content.ts";
11
+ /**
12
+ * Options for the `create` author verb.
13
+ *
14
+ * @example
15
+ * const opts: CreateOptions = {
16
+ * template: "export const {{name}} = '{{value}}';",
17
+ * options: { name: "greeting", value: "hello" },
18
+ * };
19
+ */
20
+ export interface CreateOptions {
21
+ template: string;
22
+ options: JsonValue;
23
+ force?: boolean;
24
+ }
25
+ /**
26
+ * Options for the `create({ templateFile })` render request — an explicit, package-local
27
+ * alternative to an inline `template` string (REQ-FEH-01). `templateFile` is a
28
+ * package-relative path (resolved against the active run's `packageDir`), read at
29
+ * emission time; its content becomes the `create` directive's `template` field —
30
+ * the existing `create` IR, zero wire change. `templateFile` REQUESTS a render: a binary
31
+ * or oversized source fails loud (`invalid-input`), it never silently falls back to a
32
+ * by-reference copy (REQ-FEH-02).
33
+ *
34
+ * @example
35
+ * const opts: CreateFromTemplateFileOptions = {
36
+ * templateFile: "tpl.ts.template",
37
+ * options: { name: "greeting" },
38
+ * };
39
+ */
40
+ export interface CreateFromTemplateFileOptions {
41
+ templateFile: string;
42
+ options: JsonValue;
43
+ force?: boolean;
44
+ }
45
+ /**
46
+ * Locates an existing file and returns a `FoundHandle` for reading or removing it.
47
+ *
48
+ * `read()` resolves `string | undefined`: the content, `undefined` when the path does not
49
+ * exist, or `""` when the file exists but is empty. Branch on the three outcomes with strict
50
+ * `=== undefined` / `=== ""` — NEVER `if (!content)`, which would merge `undefined`, `""`,
51
+ * `"0"` and `"false"` and reintroduce the absent-vs-empty bug. Prefer `classifyContent()`
52
+ * over manual comparisons — it names the trichotomy and gives exhaustive-switch parity.
53
+ *
54
+ * @example
55
+ * const c = await find("src/config.ts").read();
56
+ * if (c === undefined) create("src/config.ts", { template, options });
57
+ * else if (c === "") replaceContent("src/config.ts", seedContent);
58
+ * else replaceContent("src/config.ts", patch(c));
59
+ */
60
+ export declare function find(path: string): FoundHandle;
61
+ /**
62
+ * Schedules a file-creation directive and returns a `WritableHandle` for chaining.
63
+ * The file is written when the session flushes — on the next `read()` call (REQ-KIT-02)
64
+ * or at run end (REQ-KIT-05). A factory that never calls `read()` still emits all
65
+ * buffered directives when the runner resolves.
66
+ *
67
+ * SEAM-01 (REQ-01): a generic type parameter `S` narrows `options` from the bare
68
+ * `JsonValue` to the schema's keys at the type level only — the runtime body is unchanged.
69
+ *
70
+ * Creating over an existing file is rejected at the engine seam unless
71
+ * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
72
+ * rejected run throws `AuthoringError`.
73
+ *
74
+ * `templateFile` is a THIRD overload (REQ-FEH-01): pass a package-local path instead of an
75
+ * inline `template` string — its content is read at emission time and becomes the
76
+ * directive's `template` field. `template` and `templateFile` are mutually exclusive forms;
77
+ * only usable inside a factory run started with packageDir (there is no resolution anchor
78
+ * to read a package-local file against otherwise — `invalid-input`, never a cwd fallback).
79
+ * `templateFile`'s VALUE is a literal package-relative path, read verbatim by CONTENT —
80
+ * it is NOT run through `scaffold`'s filename pipeline (no rename remap, no `__x__` token
81
+ * translation, no `.template`-suffix strip applied to the path itself); this is an
82
+ * explicit REQUEST to render one named file, unlike `scaffold`'s per-entry filename
83
+ * processing. Because `templateFile` REQUESTS a render, it has no silent by-reference
84
+ * fallback (REQ-FEH-02): a binary file (a null byte or invalid UTF-8 anywhere in the
85
+ * whole file) or a file too large to render inline (over the 4 MiB limit) both reject
86
+ * fail-loud with reason `invalid-input` — never a silent copy.
87
+ *
88
+ * @example
89
+ * create("src/index.ts", {
90
+ * template: "export const version = '{{version}}';",
91
+ * options: { version: "1.0.0" },
92
+ * });
93
+ * @example
94
+ * create("src/index.ts", {
95
+ * templateFile: "index.ts.template",
96
+ * options: { version: "1.0.0" },
97
+ * });
98
+ */
99
+ export declare function create<S>(path: string, opts: {
100
+ template: string;
101
+ options: {
102
+ [K in keyof S]: S[K];
103
+ };
104
+ force?: boolean;
105
+ }): WritableHandle;
106
+ export declare function create(path: string, opts: CreateOptions): WritableHandle;
107
+ export declare function create(path: string, opts: CreateFromTemplateFileOptions): WritableHandle;
108
+ /**
109
+ * Author-facing options for the `scaffold` verb — walks a package-local folder and mirrors
110
+ * it into the target tree. `from`/`to` are mandatory. `options` defaults `{}`, `include`
111
+ * defaults to matching everything, `exclude` defaults to matching nothing (`exclude` wins
112
+ * on overlap), `rename` defaults to no remap, `force` defaults `false`.
113
+ *
114
+ * @example
115
+ * const opts: ScaffoldOptions = {
116
+ * from: "files",
117
+ * to: "src/generated",
118
+ * options: { name: "Widget" },
119
+ * exclude: ["*.spec.ts"],
120
+ * };
121
+ */
122
+ export type ScaffoldOptions = ScaffoldArgs;
123
+ /**
124
+ * Walks a package-local folder (`from`, resolved against the active run's `packageDir`)
125
+ * and mirrors every entry into `to`, applying the rename → filename-token-translation →
126
+ * `.template`-strip pipeline (REQ-FSC-05) and include/exclude glob filtering (REQ-FSC-03,
127
+ * `exclude` wins on overlap). Each source classifies by-value or by-reference
128
+ * (`content-classification`, entirely sniffed — never author-declared); by-value sources
129
+ * emit a `create` directive through the existing IR. A `from` folder with zero entries
130
+ * no-ops silently; `include`/`exclude` eliminating every entry rejects fail-loud, naming
131
+ * the filters (REQ-FSC-04 — two distinct outcomes, never collapsed). `force` (default
132
+ * `false`) passes through unchanged to every emitted directive, no per-file override
133
+ * (REQ-FSC-06). Two or more sources collapsing to the same destination reject fail-loud,
134
+ * naming every offending source (REQ-FSC-08). Only usable inside a
135
+ * factory run started with packageDir — there is no resolution anchor to walk a
136
+ * package-local folder against otherwise (`invalid-input`, never a cwd fallback).
137
+ *
138
+ * `rename` is a static REMAP TABLE (`Record<originalSourceRelativePath,
139
+ * newDestinationRelativePath>`), matched against the ORIGINAL (pre-token-translation)
140
+ * source path — distinct from the `rename()` verb, which renames one already-targeted
141
+ * file's basename at emit time, not a folder-walk's per-entry destination.
142
+ *
143
+ * The walk never descends into a symlinked directory, even when its target resolves
144
+ * INSIDE the package boundary (skipped silently, no error — uniform with
145
+ * `package-root-containment`'s no-descent rule) and is capped at 10,000 enumerated
146
+ * entries per call, failing loud and naming the bound past that (REQ-FSC-09) — a
147
+ * resource guard no real schematic collection should approach.
148
+ *
149
+ * **Packaging caveat**: the empty-folder no-op (above) depends on `from` existing ON
150
+ * DISK at run time — npm tarball packaging commonly DROPS empty directories, so an
151
+ * empty `from` folder that relies on this no-op may not survive `npm publish` at all
152
+ * (REQ-FSC-04). Ship at least a placeholder file if the folder's presence matters.
153
+ *
154
+ * Returns `void` (REQ-FSC-07) — fire-and-forget, no chainable handle group.
155
+ *
156
+ * @example
157
+ * scaffold({ from: "files", to: "src/generated", options: { name: "Widget" } });
158
+ */
159
+ export declare function scaffold(args: ScaffoldOptions): void;
160
+ /**
161
+ * Emits a by-reference copy of ONE package-local file (`from`, resolved against the active
162
+ * run's `packageDir`) to `to` — ALWAYS by-reference, NEVER classified or rendered
163
+ * (REQ-FEH-03), regardless of the source's own text-vs-binary shape: a text asset
164
+ * containing `{= =}`-like sequences (that `scaffold` would otherwise render as tokens)
165
+ * travels verbatim — the documented escape from `scaffold`'s by-value classification
166
+ * (`content-classification` REQ-CCL-04). Contrast with tree→tree `copy`: `copyIn`'s source
167
+ * is a PACKAGE-LOCAL path read at emission time, not an existing tree entry.
168
+ *
169
+ * `from`/`to` are mandatory; `force` defaults `false`. A missing `from`/`to` rejects
170
+ * fail-loud before any emission (REQ-FEH-04.1/.2). Collision without `force` rejects;
171
+ * `force: true` overwrites (`by-reference-copy-wire` REQ-BRC-05). Only usable inside a
172
+ * factory run started with packageDir — there is no resolution anchor to read a
173
+ * package-local file against otherwise (`invalid-input`, never a cwd fallback).
174
+ *
175
+ * Returns `void` (REQ-FEH-04.3) — NOT a `WritableHandle`, unlike `copy`: a by-reference
176
+ * destination's bytes exist only after the ENGINE applies the directive (the fake never
177
+ * materializes them, `author-test-harness` REQ-ATH-15) — a handle chaining over tree
178
+ * CONTENT would lie about content that was never staged. This asymmetry with `copy`
179
+ * (which DOES stage tree→tree content the fake can chain over) is deliberate.
180
+ *
181
+ * @example
182
+ * copyIn("assets/logo.svg", "src/generated/logo.svg");
183
+ */
184
+ export declare function copyIn(from: string, to: string, opts?: {
185
+ force?: boolean;
186
+ }): void;
187
+ /**
188
+ * Schedules an in-place content replacement for an existing file and returns a `WritableHandle`.
189
+ * A rejected run (e.g. the target does not exist) throws `AuthoringError`.
190
+ *
191
+ * @example
192
+ * replaceContent("src/config.json", '{ "version": "2.0.0" }');
193
+ */
194
+ export declare function replaceContent(path: string, content: string): WritableHandle;
195
+ /**
196
+ * Schedules a file deletion. Idempotent — deleting an absent file is not an error.
197
+ *
198
+ * @example
199
+ * remove("src/legacy.ts");
200
+ */
201
+ export declare function remove(path: string): void;
202
+ /**
203
+ * Schedules a file rename (basename only) and returns a `WritableHandle` for the new path.
204
+ * Renaming onto an existing path is rejected at the engine seam unless
205
+ * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
206
+ * rejected run throws `AuthoringError`.
207
+ *
208
+ * @example
209
+ * rename("src/foo.ts", "bar.ts");
210
+ */
211
+ export declare function rename(path: string, newName: string, opts?: {
212
+ force?: boolean;
213
+ }): WritableHandle;
214
+ /**
215
+ * Schedules a file move to a different directory and returns a `WritableHandle`.
216
+ * Moving onto an existing destination is rejected at the engine seam unless
217
+ * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
218
+ * rejected run throws `AuthoringError`.
219
+ * A move whose destination equals its source is a no-op, never a collision
220
+ * (ADR-0017 self-move amendment).
221
+ *
222
+ * @example
223
+ * move("src/utils/helper.ts", "src/shared");
224
+ */
225
+ export declare function move(path: string, toDir: string, opts?: {
226
+ force?: boolean;
227
+ }): WritableHandle;
228
+ /**
229
+ * Schedules a file copy to a new path and returns a `WritableHandle` for the destination.
230
+ * Copying onto an existing destination is rejected at the engine seam unless
231
+ * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
232
+ * rejected run throws `AuthoringError`.
233
+ *
234
+ * @example
235
+ * copy("src/template.ts", "src/generated/output.ts");
236
+ */
237
+ export declare function copy(from: string, to: string, opts?: {
238
+ force?: boolean;
239
+ }): WritableHandle;
240
+ import type { DryRunEntry, DryRunVerb } from "../dry-run/plan.ts";
241
+ export type { DryRunEntry, DryRunVerb };
242
+ /**
243
+ * Returns the plan of directives still pending in the active run's buffer, rendered
244
+ * in author vocabulary.
245
+ *
246
+ * The plan reflects only what is still pending — the honest answer to "what will this
247
+ * run still emit", not "what has this run emitted in total." A `read()` (or any flush)
248
+ * empties the pending buffer, so directives already flushed no longer appear.
249
+ *
250
+ * Entries carry verb and path — no content or byte preview — plus an optional `kind`
251
+ * (`"rendered" | "copied"`) present only on the package-local-read verbs whose transport
252
+ * is classified: `create` (inline or `templateFile`, `kind: "rendered"`) and `copyIn`
253
+ * (`kind: "copied"`). The tree→tree `copy` verb also materializes content but predates
254
+ * this axis and is never package-local-read/classified, so it carries no `kind`.
255
+ *
256
+ * Call it inside an active factory run, like every other `./commons` verb.
257
+ *
258
+ * @example
259
+ * const run = () => {
260
+ * create("src/index.ts", { template: "export const version = '1.0.0';", options: {} });
261
+ * find("src/legacy.ts").remove();
262
+ * for (const entry of dryRun()) {
263
+ * console.log(entry.verb, entry.path); // "create src/index.ts", then "remove src/legacy.ts"
264
+ * }
265
+ * };
266
+ *
267
+ * @throws When called outside an active factory run, propagates the standard
268
+ * error — authoring verbs "can only be used while a schematic is running" (ADR-0026: the
269
+ * message no longer enumerates individual verbs, so it covers `dryRun` too).
270
+ */
271
+ export declare function dryRun(): DryRunEntry[];
@@ -0,0 +1,276 @@
1
+ // Author surface: positional + trailing options, frozen public API (KIT-03/SKEL-01/KIT-04).
2
+ // No AST imports. All handle write-ops wired (S-003).
3
+ import { posix } from "node:path";
4
+ import { currentContext } from "../core/context.js";
5
+ import { forceEntry } from "../core/directive-factory.js";
6
+ import { AuthoringError } from "../core/authoring-error.js";
7
+ import { readTemplateFile, runScaffold, runCopyIn } from "../scaffold/index.js";
8
+ // ADR-0023: AuthoringError (+ its supporting types) is an author-facing DATA type, not
9
+ // kit MACHINERY (the port, the session, the directive factory stay unexported) — it
10
+ // legitimately crosses the ADR-0009 boundary via the same two-step pattern
11
+ // FoundHandle/WritableHandle already use.
12
+ export { AuthoringError };
13
+ // 2.3 (CQ-1, droppable): classifyContent + ContentState give authors a named,
14
+ // branchable read-result classification (see find()'s JSDoc pointer below). Severable
15
+ // from the AuthoringError cluster above — no other component references it.
16
+ export { classifyContent } from "./classify-content.js";
17
+ // Pure factory for WritableHandle. Returned by every write verb.
18
+ function buildWritableHandle(path) {
19
+ return {
20
+ read() {
21
+ const { session } = currentContext();
22
+ return session.read(path);
23
+ },
24
+ replaceContent(content) {
25
+ const { session, factory } = currentContext();
26
+ session.buffer(factory.modify({ path, content }));
27
+ return buildWritableHandle(path);
28
+ },
29
+ rename(newName, opts) {
30
+ const { session, factory } = currentContext();
31
+ session.buffer(factory.rename({ path, newName, ...forceEntry(opts?.force) }));
32
+ const dir = posix.dirname(path);
33
+ return buildWritableHandle(dir === "." ? newName : posix.join(dir, newName));
34
+ },
35
+ move(toDir, opts) {
36
+ const { session, factory } = currentContext();
37
+ session.buffer(factory.move({ path, toDir, ...forceEntry(opts?.force) }));
38
+ return buildWritableHandle(posix.join(toDir, posix.basename(path)));
39
+ },
40
+ copy(to, opts) {
41
+ const { session, factory } = currentContext();
42
+ session.buffer(factory.copy({ from: path, to, ...forceEntry(opts?.force) }));
43
+ return buildWritableHandle(to);
44
+ },
45
+ };
46
+ }
47
+ // FoundHandle factory. Returned exclusively by find(). Has remove().
48
+ function buildFoundHandle(path) {
49
+ return {
50
+ read() {
51
+ const { session } = currentContext();
52
+ return session.read(path);
53
+ },
54
+ replaceContent(content) {
55
+ const { session, factory } = currentContext();
56
+ session.buffer(factory.modify({ path, content }));
57
+ return buildWritableHandle(path);
58
+ },
59
+ rename(newName, opts) {
60
+ const { session, factory } = currentContext();
61
+ session.buffer(factory.rename({ path, newName, ...forceEntry(opts?.force) }));
62
+ const dir = posix.dirname(path);
63
+ return buildWritableHandle(dir === "." ? newName : posix.join(dir, newName));
64
+ },
65
+ move(toDir, opts) {
66
+ const { session, factory } = currentContext();
67
+ session.buffer(factory.move({ path, toDir, ...forceEntry(opts?.force) }));
68
+ return buildWritableHandle(posix.join(toDir, posix.basename(path)));
69
+ },
70
+ copy(to, opts) {
71
+ const { session, factory } = currentContext();
72
+ session.buffer(factory.copy({ from: path, to, ...forceEntry(opts?.force) }));
73
+ return buildWritableHandle(to);
74
+ },
75
+ remove() {
76
+ const { session, factory } = currentContext();
77
+ session.buffer(factory.remove({ path }));
78
+ },
79
+ };
80
+ }
81
+ /**
82
+ * Locates an existing file and returns a `FoundHandle` for reading or removing it.
83
+ *
84
+ * `read()` resolves `string | undefined`: the content, `undefined` when the path does not
85
+ * exist, or `""` when the file exists but is empty. Branch on the three outcomes with strict
86
+ * `=== undefined` / `=== ""` — NEVER `if (!content)`, which would merge `undefined`, `""`,
87
+ * `"0"` and `"false"` and reintroduce the absent-vs-empty bug. Prefer `classifyContent()`
88
+ * over manual comparisons — it names the trichotomy and gives exhaustive-switch parity.
89
+ *
90
+ * @example
91
+ * const c = await find("src/config.ts").read();
92
+ * if (c === undefined) create("src/config.ts", { template, options });
93
+ * else if (c === "") replaceContent("src/config.ts", seedContent);
94
+ * else replaceContent("src/config.ts", patch(c));
95
+ */
96
+ export function find(path) {
97
+ return buildFoundHandle(path);
98
+ }
99
+ export function create(path, opts) {
100
+ const { session, factory } = currentContext();
101
+ const template = "templateFile" in opts ? readTemplateFile(opts.templateFile, path, opts.options, opts.force) : opts.template;
102
+ session.buffer(factory.create({
103
+ pathTemplate: path,
104
+ template,
105
+ options: opts.options,
106
+ ...forceEntry(opts.force),
107
+ }));
108
+ return buildWritableHandle(path);
109
+ }
110
+ /**
111
+ * Walks a package-local folder (`from`, resolved against the active run's `packageDir`)
112
+ * and mirrors every entry into `to`, applying the rename → filename-token-translation →
113
+ * `.template`-strip pipeline (REQ-FSC-05) and include/exclude glob filtering (REQ-FSC-03,
114
+ * `exclude` wins on overlap). Each source classifies by-value or by-reference
115
+ * (`content-classification`, entirely sniffed — never author-declared); by-value sources
116
+ * emit a `create` directive through the existing IR. A `from` folder with zero entries
117
+ * no-ops silently; `include`/`exclude` eliminating every entry rejects fail-loud, naming
118
+ * the filters (REQ-FSC-04 — two distinct outcomes, never collapsed). `force` (default
119
+ * `false`) passes through unchanged to every emitted directive, no per-file override
120
+ * (REQ-FSC-06). Two or more sources collapsing to the same destination reject fail-loud,
121
+ * naming every offending source (REQ-FSC-08). Only usable inside a
122
+ * factory run started with packageDir — there is no resolution anchor to walk a
123
+ * package-local folder against otherwise (`invalid-input`, never a cwd fallback).
124
+ *
125
+ * `rename` is a static REMAP TABLE (`Record<originalSourceRelativePath,
126
+ * newDestinationRelativePath>`), matched against the ORIGINAL (pre-token-translation)
127
+ * source path — distinct from the `rename()` verb, which renames one already-targeted
128
+ * file's basename at emit time, not a folder-walk's per-entry destination.
129
+ *
130
+ * The walk never descends into a symlinked directory, even when its target resolves
131
+ * INSIDE the package boundary (skipped silently, no error — uniform with
132
+ * `package-root-containment`'s no-descent rule) and is capped at 10,000 enumerated
133
+ * entries per call, failing loud and naming the bound past that (REQ-FSC-09) — a
134
+ * resource guard no real schematic collection should approach.
135
+ *
136
+ * **Packaging caveat**: the empty-folder no-op (above) depends on `from` existing ON
137
+ * DISK at run time — npm tarball packaging commonly DROPS empty directories, so an
138
+ * empty `from` folder that relies on this no-op may not survive `npm publish` at all
139
+ * (REQ-FSC-04). Ship at least a placeholder file if the folder's presence matters.
140
+ *
141
+ * Returns `void` (REQ-FSC-07) — fire-and-forget, no chainable handle group.
142
+ *
143
+ * @example
144
+ * scaffold({ from: "files", to: "src/generated", options: { name: "Widget" } });
145
+ */
146
+ export function scaffold(args) {
147
+ runScaffold(args);
148
+ }
149
+ /**
150
+ * Emits a by-reference copy of ONE package-local file (`from`, resolved against the active
151
+ * run's `packageDir`) to `to` — ALWAYS by-reference, NEVER classified or rendered
152
+ * (REQ-FEH-03), regardless of the source's own text-vs-binary shape: a text asset
153
+ * containing `{= =}`-like sequences (that `scaffold` would otherwise render as tokens)
154
+ * travels verbatim — the documented escape from `scaffold`'s by-value classification
155
+ * (`content-classification` REQ-CCL-04). Contrast with tree→tree `copy`: `copyIn`'s source
156
+ * is a PACKAGE-LOCAL path read at emission time, not an existing tree entry.
157
+ *
158
+ * `from`/`to` are mandatory; `force` defaults `false`. A missing `from`/`to` rejects
159
+ * fail-loud before any emission (REQ-FEH-04.1/.2). Collision without `force` rejects;
160
+ * `force: true` overwrites (`by-reference-copy-wire` REQ-BRC-05). Only usable inside a
161
+ * factory run started with packageDir — there is no resolution anchor to read a
162
+ * package-local file against otherwise (`invalid-input`, never a cwd fallback).
163
+ *
164
+ * Returns `void` (REQ-FEH-04.3) — NOT a `WritableHandle`, unlike `copy`: a by-reference
165
+ * destination's bytes exist only after the ENGINE applies the directive (the fake never
166
+ * materializes them, `author-test-harness` REQ-ATH-15) — a handle chaining over tree
167
+ * CONTENT would lie about content that was never staged. This asymmetry with `copy`
168
+ * (which DOES stage tree→tree content the fake can chain over) is deliberate.
169
+ *
170
+ * @example
171
+ * copyIn("assets/logo.svg", "src/generated/logo.svg");
172
+ */
173
+ export function copyIn(from, to, opts) {
174
+ runCopyIn({ from, to, force: opts?.force });
175
+ }
176
+ /**
177
+ * Schedules an in-place content replacement for an existing file and returns a `WritableHandle`.
178
+ * A rejected run (e.g. the target does not exist) throws `AuthoringError`.
179
+ *
180
+ * @example
181
+ * replaceContent("src/config.json", '{ "version": "2.0.0" }');
182
+ */
183
+ export function replaceContent(path, content) {
184
+ const { session, factory } = currentContext();
185
+ session.buffer(factory.modify({ path, content }));
186
+ return buildWritableHandle(path);
187
+ }
188
+ /**
189
+ * Schedules a file deletion. Idempotent — deleting an absent file is not an error.
190
+ *
191
+ * @example
192
+ * remove("src/legacy.ts");
193
+ */
194
+ export function remove(path) {
195
+ const { session, factory } = currentContext();
196
+ session.buffer(factory.remove({ path }));
197
+ }
198
+ /**
199
+ * Schedules a file rename (basename only) and returns a `WritableHandle` for the new path.
200
+ * Renaming onto an existing path is rejected at the engine seam unless
201
+ * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
202
+ * rejected run throws `AuthoringError`.
203
+ *
204
+ * @example
205
+ * rename("src/foo.ts", "bar.ts");
206
+ */
207
+ export function rename(path, newName, opts) {
208
+ const { session, factory } = currentContext();
209
+ session.buffer(factory.rename({ path, newName, ...forceEntry(opts?.force) }));
210
+ const dir = posix.dirname(path);
211
+ return buildWritableHandle(dir === "." ? newName : posix.join(dir, newName));
212
+ }
213
+ /**
214
+ * Schedules a file move to a different directory and returns a `WritableHandle`.
215
+ * Moving onto an existing destination is rejected at the engine seam unless
216
+ * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
217
+ * rejected run throws `AuthoringError`.
218
+ * A move whose destination equals its source is a no-op, never a collision
219
+ * (ADR-0017 self-move amendment).
220
+ *
221
+ * @example
222
+ * move("src/utils/helper.ts", "src/shared");
223
+ */
224
+ export function move(path, toDir, opts) {
225
+ const { session, factory } = currentContext();
226
+ session.buffer(factory.move({ path, toDir, ...forceEntry(opts?.force) }));
227
+ return buildWritableHandle(posix.join(toDir, posix.basename(path)));
228
+ }
229
+ /**
230
+ * Schedules a file copy to a new path and returns a `WritableHandle` for the destination.
231
+ * Copying onto an existing destination is rejected at the engine seam unless
232
+ * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
233
+ * rejected run throws `AuthoringError`.
234
+ *
235
+ * @example
236
+ * copy("src/template.ts", "src/generated/output.ts");
237
+ */
238
+ export function copy(from, to, opts) {
239
+ const { session, factory } = currentContext();
240
+ session.buffer(factory.copy({ from, to, ...forceEntry(opts?.force) }));
241
+ return buildWritableHandle(to);
242
+ }
243
+ // --- Stage 3: dry-run plan exposure (REQ-DRE-01..04) ---
244
+ import { dryRunPlan } from "../dry-run/index.js";
245
+ /**
246
+ * Returns the plan of directives still pending in the active run's buffer, rendered
247
+ * in author vocabulary.
248
+ *
249
+ * The plan reflects only what is still pending — the honest answer to "what will this
250
+ * run still emit", not "what has this run emitted in total." A `read()` (or any flush)
251
+ * empties the pending buffer, so directives already flushed no longer appear.
252
+ *
253
+ * Entries carry verb and path — no content or byte preview — plus an optional `kind`
254
+ * (`"rendered" | "copied"`) present only on the package-local-read verbs whose transport
255
+ * is classified: `create` (inline or `templateFile`, `kind: "rendered"`) and `copyIn`
256
+ * (`kind: "copied"`). The tree→tree `copy` verb also materializes content but predates
257
+ * this axis and is never package-local-read/classified, so it carries no `kind`.
258
+ *
259
+ * Call it inside an active factory run, like every other `./commons` verb.
260
+ *
261
+ * @example
262
+ * const run = () => {
263
+ * create("src/index.ts", { template: "export const version = '1.0.0';", options: {} });
264
+ * find("src/legacy.ts").remove();
265
+ * for (const entry of dryRun()) {
266
+ * console.log(entry.verb, entry.path); // "create src/index.ts", then "remove src/legacy.ts"
267
+ * }
268
+ * };
269
+ *
270
+ * @throws When called outside an active factory run, propagates the standard
271
+ * error — authoring verbs "can only be used while a schematic is running" (ADR-0026: the
272
+ * message no longer enumerates individual verbs, so it covers `dryRun` too).
273
+ */
274
+ export function dryRun() {
275
+ return dryRunPlan(currentContext().session.pendingSnapshot());
276
+ }
@@ -0,0 +1,115 @@
1
+ import type { Dialect, OpPack } from "../core/define-dialect.ts";
2
+ /**
3
+ * Fixture passed to `testDialect` to drive the conformance suite.
4
+ * The fixture supplies the dialect under test plus representative source samples.
5
+ *
6
+ * @example
7
+ * const fixture: DialectFixture = {
8
+ * dialect: myTypeScriptDialect,
9
+ * samples: ["const x = 1;", "export default {};"],
10
+ * };
11
+ */
12
+ export interface DialectFixture {
13
+ /** The dialect instance to exercise. */
14
+ dialect: Dialect;
15
+ /** Representative source strings the dialect's parse/print round-trip must survive byte-exact. */
16
+ samples: string[];
17
+ }
18
+ /**
19
+ * One op-invocation recipe `testOpPack` applies to a seeded target: seed the file, run the
20
+ * op `chain` (named pack ops and/or the universal `.modify`), and assert the coalesced
21
+ * `modify`'s content is BYTE-EXACT `expect` — a full-output comparison, never a substring,
22
+ * so one assertion proves both the op's intended effect AND that every other region is
23
+ * byte-stable (REQ-DC-02's unchanged-elsewhere).
24
+ *
25
+ * @example
26
+ * const exercise: OpExercise = {
27
+ * seed: "export const x = 1;",
28
+ * chain: [{ op: "addImport", args: ["readFileSync", "node:fs"] }],
29
+ * expect: 'import { readFileSync } from "node:fs";\nexport const x = 1;',
30
+ * };
31
+ */
32
+ export interface OpExercise {
33
+ /** Initial content seeded at `path` (flush-seed-rule, REQ-MC-04) — never a `create()` target. */
34
+ seed: string;
35
+ /** Optional target path; the kit defaults to a stable name using `baseDialect.extensions[0]`. */
36
+ path?: string;
37
+ /** Ops applied in order: a named pack op (`op` + `args`), or the universal `.modify`. */
38
+ chain: ReadonlyArray<{
39
+ readonly op: string;
40
+ readonly args: readonly unknown[];
41
+ } | {
42
+ readonly modify: (ast: unknown) => void;
43
+ }>;
44
+ /** BYTE-EXACT printed content of the coalesced `modify` directive after the chain runs. */
45
+ expect: string;
46
+ }
47
+ /**
48
+ * Fixture passed to `testOpPack` to drive the conformance suite.
49
+ * The fixture supplies the op-pack under test, the base dialect it augments, and the
50
+ * op-invocation recipes (`exercises`) the kit needs to actually apply each op and assert
51
+ * byte-exact effects — REQUIRED at the type level so an exercise-less fixture cannot
52
+ * silently skip `testOpPack`'s load-bearing per-op assertions (REQ-DC-02..04).
53
+ *
54
+ * @example
55
+ * const fixture: OpPackFixture = {
56
+ * opPack: myInsertImportOps,
57
+ * baseDialect: myTypeScriptDialect,
58
+ * exercises: [
59
+ * {
60
+ * seed: "export const x = 1;",
61
+ * chain: [{ op: "addImport", args: ["readFileSync", "node:fs"] }],
62
+ * expect: 'import { readFileSync } from "node:fs";\nexport const x = 1;',
63
+ * },
64
+ * ],
65
+ * };
66
+ */
67
+ export interface OpPackFixture {
68
+ /** The op-pack to exercise against a real base dialect (not a mock). */
69
+ opPack: OpPack;
70
+ /** The base dialect that holds the live AST — required by ADR-0012 (op-packs tested against real dialects). */
71
+ baseDialect: Dialect;
72
+ /** The op-invocation recipes `testOpPack` applies — REQUIRED (rev 5, ADR-0012 amendment). */
73
+ exercises: readonly OpExercise[];
74
+ }
75
+ /**
76
+ * Runs the conformance suite for a dialect: asserts parse/print no-op round-trip fidelity
77
+ * (REQ-DC-01) — `print(parse(sample)) === sample` BYTE-EXACT, never AST-equal, for every
78
+ * sample in `fixture.samples` PLUS the six mandatory adversarial samples the kit injects on
79
+ * every run (REQ-DC-06 — additive, not opt-out-able). Before each round-trip check, verifies
80
+ * `fixture.dialect.ast.parse` is a REAL parser, not an identity/stub function (REQ-DC-08): a
81
+ * `parse` returning `null`/`undefined`, or the input string unchanged, fails BEFORE the
82
+ * round-trip assertion could vacuously pass.
83
+ *
84
+ * @example
85
+ * await testDialect({
86
+ * dialect: myTypeScriptDialect,
87
+ * samples: ["const x = 1;"],
88
+ * });
89
+ */
90
+ export declare function testDialect(fixture: DialectFixture): Promise<void>;
91
+ /**
92
+ * Runs the conformance suite for an op-pack against a REAL base dialect (never a mock,
93
+ * ADR-0012): for each of `fixture.exercises`, asserts single-op fidelity +
94
+ * unchanged-elsewhere (REQ-DC-02) / coalescing-to-one content-verified (REQ-DC-03) via a
95
+ * no-read run, seam-serializability (REQ-DC-04) over every emitted directive, and — for
96
+ * every multi-op exercise — the read-boundary split (REQ-DC-05.2's live counterpart): a
97
+ * mid-chain `read()` must force exactly TWO cumulative modify directives, never one. Finally,
98
+ * asserts `fixture.baseDialect` survives the six mandatory adversarial samples' round-trip +
99
+ * real-base probe (REQ-DC-06/REQ-DC-08 — additive, not opt-out-able, same mechanism
100
+ * `testDialect` runs), unconditionally on every call whose exercises pass.
101
+ *
102
+ * @example
103
+ * await testOpPack({
104
+ * opPack: myInsertImportOps,
105
+ * baseDialect: myTypeScriptDialect,
106
+ * exercises: [
107
+ * {
108
+ * seed: "export const x = 1;",
109
+ * chain: [{ op: "addImport", args: ["readFileSync", "node:fs"] }],
110
+ * expect: 'import { readFileSync } from "node:fs";\nexport const x = 1;',
111
+ * },
112
+ * ],
113
+ * });
114
+ */
115
+ export declare function testOpPack(fixture: OpPackFixture): Promise<void>;