@pbuilder/sdk 0.4.0 → 0.5.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 +42 -2
- package/dist/commons/index.js +5 -2
- package/dist/conformance/index.d.ts +2 -2
- package/dist/conformance/index.js +38 -19
- package/dist/core/define-dialect.js +15 -8
- package/dist/core/dialect-handle.js +1 -1
- package/dist/core/json-value.d.ts +14 -0
- package/dist/core/json-value.js +43 -0
- package/dist/dialects/json/ast.d.ts +24 -0
- package/dist/dialects/json/ast.js +21 -0
- package/dist/dialects/json/index.d.ts +55 -0
- package/dist/dialects/json/index.js +54 -0
- package/dist/dialects/json/ops.d.ts +46 -0
- package/dist/dialects/json/ops.js +561 -0
- package/dist/dialects/yaml/ast.d.ts +15 -0
- package/dist/dialects/yaml/ast.js +154 -0
- package/dist/dialects/yaml/documents.d.ts +8 -0
- package/dist/dialects/yaml/documents.js +24 -0
- package/dist/dialects/yaml/index.d.ts +69 -0
- package/dist/dialects/yaml/index.js +70 -0
- package/dist/dialects/yaml/paths.d.ts +55 -0
- package/dist/dialects/yaml/paths.js +208 -0
- package/dist/dialects/yaml/presentation.d.ts +24 -0
- package/dist/dialects/yaml/presentation.js +264 -0
- package/dist/dialects/yaml/structural.d.ts +39 -0
- package/dist/dialects/yaml/structural.js +307 -0
- package/dist/runner-manifest.json +3 -3
- package/dist/transport/error-text.d.ts +6 -1
- package/dist/transport/error-text.js +94 -31
- package/package.json +16 -3
- package/schemas/project-builder.schema.json +112 -0
package/README.md
CHANGED
|
@@ -559,8 +559,9 @@ conformance-tests a *dialect or op-pack* implementation — not the same audienc
|
|
|
559
559
|
|
|
560
560
|
When string-level mutation isn't enough — "add an import to this module", "set a prop on
|
|
561
561
|
this JSX element" — **dialects** provide structured, AST-aware operations for one file
|
|
562
|
-
type: see [authoring a dialect](./docs/authoring-a-dialect.md) for the full story.
|
|
563
|
-
ship today: `@pbuilder/sdk/typescript
|
|
562
|
+
type: see [authoring a dialect](./docs/authoring-a-dialect.md) for the full story. Four
|
|
563
|
+
ship today: `@pbuilder/sdk/typescript`, `@pbuilder/sdk/react`, `@pbuilder/sdk/json`, and
|
|
564
|
+
`@pbuilder/sdk/yaml`.
|
|
564
565
|
|
|
565
566
|
A dialect's entry point is its own `find(path)`: it opens a **coalescing, awaitable
|
|
566
567
|
handle**. Every op you chain mutates the same live AST, and the handle serializes to
|
|
@@ -620,6 +621,45 @@ await react
|
|
|
620
621
|
the TypeScript `source` strings. One React-specific subtlety: an inserted prop lands after
|
|
621
622
|
a trailing `{...spread}`, so it **wins** at runtime under React's later-position precedence.
|
|
622
623
|
|
|
624
|
+
### `@pbuilder/sdk/json`
|
|
625
|
+
|
|
626
|
+
Mutates `.json` and `.jsonc` files by path, editing only the bytes it changes: comments,
|
|
627
|
+
indentation, key order, and line endings survive. Paths are arrays (`["scripts", "build"]`,
|
|
628
|
+
`["plugins", 0]`).
|
|
629
|
+
|
|
630
|
+
```ts
|
|
631
|
+
import * as json from "@pbuilder/sdk/json";
|
|
632
|
+
|
|
633
|
+
await json
|
|
634
|
+
.find("package.json")
|
|
635
|
+
.setValue(["scripts", "build"], "tsc")
|
|
636
|
+
.appendItem(["keywords"], "schematics", { unique: true });
|
|
637
|
+
```
|
|
638
|
+
|
|
639
|
+
Named ops: `setValue`, `addKey`, `removeKey`, `renameKey`, `insertItem`, `appendItem`,
|
|
640
|
+
`removeItem`, `removeValue`, `replaceItem`, `moveItem`, `merge`, `updateValue`, `moveValue`,
|
|
641
|
+
`copyValue`, `sortKeys`. `.modify(fn)` exposes [jsonc-parser](https://github.com/microsoft/node-jsonc-parser).
|
|
642
|
+
See [the JSON dialect guide](./docs/json-dialect.md).
|
|
643
|
+
|
|
644
|
+
### `@pbuilder/sdk/yaml`
|
|
645
|
+
|
|
646
|
+
Mutates `.yaml` and `.yml` files with the same path-based ops as the JSON dialect, plus
|
|
647
|
+
comments, anchors and aliases, merge keys, styles, tags, and multi-document files. A
|
|
648
|
+
document no op touched prints byte-identical.
|
|
649
|
+
|
|
650
|
+
```ts
|
|
651
|
+
import * as yaml from "@pbuilder/sdk/yaml";
|
|
652
|
+
|
|
653
|
+
await yaml
|
|
654
|
+
.find("docker-compose.yml")
|
|
655
|
+
.setValue(["services", "web", "image"], "node:22")
|
|
656
|
+
.setComment(["services", "web"], "Public entrypoint");
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
Extra named ops: `setComment`, `removeComment`, `setAnchor`, `removeAnchor`, `setAlias`,
|
|
660
|
+
`addMergeKey`, `setStyle`, `setTag`, `addDocument`, `removeDocument`. `.modify(fn)` exposes
|
|
661
|
+
[yaml](https://eemeli.org/yaml/). See [the YAML dialect guide](./docs/yaml-dialect.md).
|
|
662
|
+
|
|
623
663
|
### `.modify()` — the universal escape hatch
|
|
624
664
|
|
|
625
665
|
Every dialect handle carries one universal op alongside its named ops: `.modify(ast => …)`.
|
package/dist/commons/index.js
CHANGED
|
@@ -98,11 +98,14 @@ export function find(path) {
|
|
|
98
98
|
}
|
|
99
99
|
export function create(path, opts) {
|
|
100
100
|
const { session, factory } = currentContext();
|
|
101
|
-
|
|
101
|
+
// The wire requires `options`, and an omitted bag (untyped callers) would vanish in JSON and
|
|
102
|
+
// fail the batch's round-trip check as unrepresentable content.
|
|
103
|
+
const options = opts.options === undefined ? {} : opts.options;
|
|
104
|
+
const template = "templateFile" in opts ? readTemplateFile(opts.templateFile, path, options, opts.force) : opts.template;
|
|
102
105
|
session.buffer(factory.create({
|
|
103
106
|
pathTemplate: path,
|
|
104
107
|
template,
|
|
105
|
-
options
|
|
108
|
+
options,
|
|
106
109
|
...forceEntry(opts.force),
|
|
107
110
|
}));
|
|
108
111
|
return buildWritableHandle(path);
|
|
@@ -120,7 +120,7 @@ export interface OpPackFixture {
|
|
|
120
120
|
/**
|
|
121
121
|
* Runs the conformance suite for a dialect: asserts parse/print no-op round-trip fidelity
|
|
122
122
|
* (REQ-DC-01) — `print(parse(sample)) === sample` BYTE-EXACT, never AST-equal, for every
|
|
123
|
-
* sample in `fixture.samples` PLUS the
|
|
123
|
+
* sample in `fixture.samples` PLUS the four mandatory adversarial samples the kit injects on
|
|
124
124
|
* every run (REQ-DC-06 — additive, not opt-out-able). Before each round-trip check, verifies
|
|
125
125
|
* `fixture.dialect.ast.parse` is a REAL parser, not an identity/stub function (REQ-DC-08): a
|
|
126
126
|
* `parse` returning `null`/`undefined`, or the input string unchanged, fails BEFORE the
|
|
@@ -137,7 +137,7 @@ export declare function testDialect<Library extends object>(fixture: DialectFixt
|
|
|
137
137
|
* no-read run, seam-serializability (REQ-DC-04) over every emitted directive, and — for
|
|
138
138
|
* every multi-op exercise — the read-boundary split (REQ-DC-05.2's live counterpart): a
|
|
139
139
|
* mid-chain `read()` must force exactly TWO cumulative modify directives, never one. Finally,
|
|
140
|
-
* asserts `fixture.baseDialect` survives the
|
|
140
|
+
* asserts `fixture.baseDialect` survives the four mandatory adversarial samples' round-trip +
|
|
141
141
|
* real-base probe (REQ-DC-06/REQ-DC-08 — additive, not opt-out-able, same mechanism
|
|
142
142
|
* `testDialect` runs), unconditionally on every call whose exercises pass.
|
|
143
143
|
*
|
|
@@ -68,20 +68,26 @@ async function runExercise(dialect, exercise, opts) {
|
|
|
68
68
|
.map((d) => d.modify);
|
|
69
69
|
return { modifies, directives };
|
|
70
70
|
}
|
|
71
|
-
// REQ-DC-06 (ADR-0012 amendment clause 1):
|
|
72
|
-
// ADDITIVELY into every `testDialect` run — `DialectFixture` carries no field
|
|
73
|
-
// disabling this (compile-level guarantee, REQ-DC-06.2, see test/conformance/planted/
|
|
74
|
-
// opt-out-attempt.test.ts).
|
|
75
|
-
//
|
|
76
|
-
//
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
71
|
+
// REQ-DC-06 (ADR-0012 amendment clause 1): four mandatory adversarial samples, injected
|
|
72
|
+
// ADDITIVELY into every `testDialect`/`testOpPack` run — `DialectFixture` carries no field
|
|
73
|
+
// capable of disabling this (compile-level guarantee, REQ-DC-06.2, see test/conformance/planted/
|
|
74
|
+
// opt-out-attempt.test.ts). No source text is valid in every language, so the samples derive
|
|
75
|
+
// from a source the dialect itself declares valid (the library-exercise seed, or the first
|
|
76
|
+
// op-exercise seed): only the empty file, line endings, the BOM, and size are format-neutral.
|
|
77
|
+
// Language-specific adversarial samples belong in each dialect's own `fixture.samples`.
|
|
78
|
+
const BOM = "\uFEFF";
|
|
79
|
+
const LARGE_SAMPLE_BYTES = 4 * 1024 * 1024;
|
|
80
|
+
function mandatoryAdversarialSamples(validSource) {
|
|
81
|
+
const lf = validSource.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
|
|
82
|
+
const terminated = lf.endsWith("\n") ? lf : `${lf}\n`;
|
|
83
|
+
return [
|
|
84
|
+
"", // empty file
|
|
85
|
+
terminated.replace(/\n/g, "\r\n"), // CRLF
|
|
86
|
+
BOM + terminated, // UTF-8 BOM
|
|
87
|
+
terminated + "\n".repeat(LARGE_SAMPLE_BYTES), // 4 MiB serialized-boundary sample (REQ-TSD-03.7 precedent)
|
|
88
|
+
];
|
|
89
|
+
}
|
|
90
|
+
const UNDECLARED_EXTENSION = ".pbuilder-undeclared";
|
|
85
91
|
// Shared by `testDialect` and `testOpPack` (verify-in-loop-4 Finding #1): the round-trip +
|
|
86
92
|
// real-base-probe loop is ONE mechanism, run against whichever dialect reference the caller
|
|
87
93
|
// holds (`fixture.dialect` for testDialect, `fixture.baseDialect` for testOpPack) — REQ-DC-06's
|
|
@@ -109,7 +115,7 @@ function runRoundTripProbe(dialectAst, samples, label) {
|
|
|
109
115
|
/**
|
|
110
116
|
* Runs the conformance suite for a dialect: asserts parse/print no-op round-trip fidelity
|
|
111
117
|
* (REQ-DC-01) — `print(parse(sample)) === sample` BYTE-EXACT, never AST-equal, for every
|
|
112
|
-
* sample in `fixture.samples` PLUS the
|
|
118
|
+
* sample in `fixture.samples` PLUS the four mandatory adversarial samples the kit injects on
|
|
113
119
|
* every run (REQ-DC-06 — additive, not opt-out-able). Before each round-trip check, verifies
|
|
114
120
|
* `fixture.dialect.ast.parse` is a REAL parser, not an identity/stub function (REQ-DC-08): a
|
|
115
121
|
* `parse` returning `null`/`undefined`, or the input string unchanged, fails BEFORE the
|
|
@@ -136,14 +142,27 @@ export async function testDialect(fixture) {
|
|
|
136
142
|
!Object.is(Reflect.get(module.astLibrary, key), Reflect.get(expected, key)))) {
|
|
137
143
|
throw new Error("testDialect: astLibrary runtime library mismatch with adapter evidence");
|
|
138
144
|
}
|
|
139
|
-
const samples = [...fixture.samples, ...
|
|
145
|
+
const samples = [...fixture.samples, ...mandatoryAdversarialSamples(fixture.libraryExercise.seed)];
|
|
140
146
|
runRoundTripProbe(fixture.dialect.ast, samples, "testDialect");
|
|
141
147
|
const exercise = fixture.libraryExercise;
|
|
142
148
|
const { client, emitted } = createRunVehicle({ [exercise.path]: exercise.seed });
|
|
149
|
+
// A-11: `find` must reject an extension the dialect does not declare. Probed inside the run,
|
|
150
|
+
// because outside a Session a conforming `find` would throw for the wrong reason.
|
|
151
|
+
const undeclaredPath = `conformance-probe${UNDECLARED_EXTENSION}`;
|
|
152
|
+
let acceptedUndeclared = !fixture.dialect.extensions.includes(UNDECLARED_EXTENSION);
|
|
143
153
|
const run = defineFactory(async () => {
|
|
154
|
+
try {
|
|
155
|
+
module.find(undeclaredPath);
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
acceptedUndeclared = false;
|
|
159
|
+
}
|
|
144
160
|
await module.find(exercise.path).modify((ast) => exercise.modify(ast, module.astLibrary));
|
|
145
161
|
});
|
|
146
162
|
await run(undefined, { client });
|
|
163
|
+
if (acceptedUndeclared) {
|
|
164
|
+
throw new Error(`testDialect: find accepted "${undeclaredPath}", an undeclared extension (A-11)`);
|
|
165
|
+
}
|
|
147
166
|
const directives = emitted.flatMap((batch) => batch.instructions);
|
|
148
167
|
if (!deepEqual(directives, [{ op: "modify", modify: { path: exercise.path, content: exercise.expect } }])) {
|
|
149
168
|
throw new Error("testDialect: library exercise did not emit the expected byte-exact modify");
|
|
@@ -156,7 +175,7 @@ export async function testDialect(fixture) {
|
|
|
156
175
|
* no-read run, seam-serializability (REQ-DC-04) over every emitted directive, and — for
|
|
157
176
|
* every multi-op exercise — the read-boundary split (REQ-DC-05.2's live counterpart): a
|
|
158
177
|
* mid-chain `read()` must force exactly TWO cumulative modify directives, never one. Finally,
|
|
159
|
-
* asserts `fixture.baseDialect` survives the
|
|
178
|
+
* asserts `fixture.baseDialect` survives the four mandatory adversarial samples' round-trip +
|
|
160
179
|
* real-base probe (REQ-DC-06/REQ-DC-08 — additive, not opt-out-able, same mechanism
|
|
161
180
|
* `testDialect` runs), unconditionally on every call whose exercises pass.
|
|
162
181
|
*
|
|
@@ -228,7 +247,7 @@ export async function testOpPack(fixture) {
|
|
|
228
247
|
}
|
|
229
248
|
}
|
|
230
249
|
}
|
|
231
|
-
// REQ-DC-06/REQ-DC-08 (verify-in-loop-4 Finding #1): the
|
|
250
|
+
// REQ-DC-06/REQ-DC-08 (verify-in-loop-4 Finding #1): the four mandatory adversarial
|
|
232
251
|
// samples' round-trip + real-base probe, run against `fixture.baseDialect` — same
|
|
233
252
|
// mechanism `testDialect` runs, independent of `fixture.exercises`. Deliberately LAST
|
|
234
253
|
// (not first, unlike testDialect): a fixture's own exercises target ONE specific
|
|
@@ -238,5 +257,5 @@ export async function testOpPack(fixture) {
|
|
|
238
257
|
// failure surface for its own reason first, while still running the probe unconditionally
|
|
239
258
|
// on every call whose exercises pass, exactly as REQ-DC-06's "regardless of what samples
|
|
240
259
|
// the contributor's own fixture supplies" demands.
|
|
241
|
-
runRoundTripProbe(fixture.baseDialect.ast,
|
|
260
|
+
runRoundTripProbe(fixture.baseDialect.ast, mandatoryAdversarialSamples(fixture.exercises[0].seed), "testOpPack");
|
|
242
261
|
}
|
|
@@ -11,7 +11,9 @@
|
|
|
11
11
|
// (target's param `unknown` must be assignable to source's param `ToyAst`, which it is not),
|
|
12
12
|
// but `any` short-circuits variance checking in both directions, which is exactly the
|
|
13
13
|
// "don't care about the concrete Ast" erasure this bare form needs.
|
|
14
|
+
import { basename } from "node:path";
|
|
14
15
|
import { createDialectHandle } from "./dialect-handle.js";
|
|
16
|
+
import { dialectError } from "./dialect-error.js";
|
|
15
17
|
/**
|
|
16
18
|
* Declares a named collection of ops over one AST type — usable standalone (REQ-DG-02.3),
|
|
17
19
|
* e.g. shareable across two dialects targeting the same AST type, before any `withOps`
|
|
@@ -25,6 +27,15 @@ import { createDialectHandle } from "./dialect-handle.js";
|
|
|
25
27
|
export function defineOpPack(ops) {
|
|
26
28
|
return ops;
|
|
27
29
|
}
|
|
30
|
+
// A basename that is only the extension (`.ts`) or whose stem ends in a dot (`a..ts`) names no
|
|
31
|
+
// file of that type, the same as a dotfile such as `.babelrc`.
|
|
32
|
+
function hasDeclaredExtension(path, extensions) {
|
|
33
|
+
const base = basename(path);
|
|
34
|
+
return extensions.some((extension) => {
|
|
35
|
+
const stem = base.slice(0, base.length - extension.length);
|
|
36
|
+
return base.endsWith(extension) && stem.length > 0 && !stem.endsWith(".");
|
|
37
|
+
});
|
|
38
|
+
}
|
|
28
39
|
/**
|
|
29
40
|
* Assembles a `Dialect` from its frozen descriptor (extensions, an AST parse/print pair,
|
|
30
41
|
* and an op-pack). `find` is the dialect's ONLY entry verb into a Session (REQ-DG-01.2) — it
|
|
@@ -43,6 +54,9 @@ export function defineDialect(d) {
|
|
|
43
54
|
ast: d.ast,
|
|
44
55
|
ops: d.ops,
|
|
45
56
|
find(path) {
|
|
57
|
+
if (!hasDeclaredExtension(path, d.extensions)) {
|
|
58
|
+
throw dialectError(`find(${JSON.stringify(path)}) — the file's extension is not one this dialect declares (${d.extensions.join(", ")}).`);
|
|
59
|
+
}
|
|
46
60
|
return createDialectHandle(d.ast, d.ops, path);
|
|
47
61
|
},
|
|
48
62
|
};
|
|
@@ -110,12 +124,5 @@ function assertNoCompositionCollision(baseOpNames, packs) {
|
|
|
110
124
|
export function withOps(base, ...packs) {
|
|
111
125
|
assertNoCompositionCollision(Object.keys(base.ops), packs);
|
|
112
126
|
const merged = Object.assign({}, base.ops, ...packs);
|
|
113
|
-
return {
|
|
114
|
-
extensions: base.extensions,
|
|
115
|
-
ast: base.ast,
|
|
116
|
-
ops: merged,
|
|
117
|
-
find(path) {
|
|
118
|
-
return createDialectHandle(base.ast, merged, path);
|
|
119
|
-
},
|
|
120
|
-
};
|
|
127
|
+
return defineDialect({ extensions: [...base.extensions], ast: base.ast, ops: merged });
|
|
121
128
|
}
|
|
@@ -155,7 +155,7 @@ class DialectHandleController {
|
|
|
155
155
|
this.#live = this.#dialectAst.parse(content);
|
|
156
156
|
}
|
|
157
157
|
catch {
|
|
158
|
-
throw dialectError(`could not parse "${this.#path}"
|
|
158
|
+
throw dialectError(`could not parse "${this.#path}"`);
|
|
159
159
|
}
|
|
160
160
|
astHandlePaths.set(this.#live, this.#path);
|
|
161
161
|
this.#lastEmittedText = content;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export type JsonValue = null | boolean | number | string | JsonValue[] | {
|
|
2
|
+
[key: string]: JsonValue;
|
|
3
|
+
};
|
|
4
|
+
export type JsonPath = readonly (string | number)[];
|
|
5
|
+
/**
|
|
6
|
+
* Renders a path for a rejection tail, e.g. `["scripts","build"]`. JSON encoding keeps a key
|
|
7
|
+
* containing quotes or newlines on one unambiguous line.
|
|
8
|
+
*/
|
|
9
|
+
export declare function formatPath(path: JsonPath): string;
|
|
10
|
+
/**
|
|
11
|
+
* Rejects anything a JSON document cannot hold, before an op touches the document. Types alone
|
|
12
|
+
* do not suffice: `as never`, `any`, and untyped JavaScript factories reach ops unchecked.
|
|
13
|
+
*/
|
|
14
|
+
export declare function assertJsonValue(value: unknown, where?: JsonPath, seen?: Set<object>): asserts value is JsonValue;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { dialectError } from "./dialect-error.js";
|
|
2
|
+
/**
|
|
3
|
+
* Renders a path for a rejection tail, e.g. `["scripts","build"]`. JSON encoding keeps a key
|
|
4
|
+
* containing quotes or newlines on one unambiguous line.
|
|
5
|
+
*/
|
|
6
|
+
export function formatPath(path) {
|
|
7
|
+
return JSON.stringify(path);
|
|
8
|
+
}
|
|
9
|
+
function isPlainObject(value) {
|
|
10
|
+
const proto = Object.getPrototypeOf(value);
|
|
11
|
+
return proto === Object.prototype || proto === null;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Rejects anything a JSON document cannot hold, before an op touches the document. Types alone
|
|
15
|
+
* do not suffice: `as never`, `any`, and untyped JavaScript factories reach ops unchecked.
|
|
16
|
+
*/
|
|
17
|
+
export function assertJsonValue(value, where = [], seen = new Set()) {
|
|
18
|
+
const fail = (what) => {
|
|
19
|
+
throw dialectError(`value at ${formatPath(where)} is ${what}, which JSON cannot represent.`);
|
|
20
|
+
};
|
|
21
|
+
if (value === null || typeof value === "boolean" || typeof value === "string")
|
|
22
|
+
return;
|
|
23
|
+
if (typeof value === "number") {
|
|
24
|
+
if (!Number.isFinite(value))
|
|
25
|
+
fail(String(value));
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (typeof value !== "object")
|
|
29
|
+
return fail(typeof value);
|
|
30
|
+
if (seen.has(value))
|
|
31
|
+
fail("a cyclic reference");
|
|
32
|
+
if (!Array.isArray(value) && !isPlainObject(value))
|
|
33
|
+
fail(`a ${value.constructor?.name ?? "non-plain"} instance`);
|
|
34
|
+
seen.add(value);
|
|
35
|
+
if (Array.isArray(value)) {
|
|
36
|
+
value.forEach((item, index) => assertJsonValue(item, [...where, index], seen));
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
for (const [key, item] of Object.entries(value))
|
|
40
|
+
assertJsonValue(item, [...where, key], seen);
|
|
41
|
+
}
|
|
42
|
+
seen.delete(value);
|
|
43
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The live document a JSON handle edits. `text` is the current source without its UTF-8 BOM
|
|
3
|
+
* (re-added on print). `jsonc-parser` edits text rather than a mutable tree, so named ops
|
|
4
|
+
* replace `text` with format-preserving edits; a `.modify(fn)` callback may do the same with
|
|
5
|
+
* any `jsonc-parser` edit.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* import * as json from "@pbuilder/sdk/json";
|
|
9
|
+
*
|
|
10
|
+
* await json.find("package.json").modify((doc) => {
|
|
11
|
+
* const edits = json.astLibrary.modify(doc.text, ["private"], true, {});
|
|
12
|
+
* doc.text = json.astLibrary.applyEdits(doc.text, edits);
|
|
13
|
+
* });
|
|
14
|
+
*/
|
|
15
|
+
export interface JsonDocument {
|
|
16
|
+
text: string;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Wraps `source` in a `JsonDocument`, throwing on any syntax error. Comments and trailing
|
|
20
|
+
* commas are JSONC and allowed; an empty or whitespace/comment-only source is a document with
|
|
21
|
+
* no value, which `setValue` fills.
|
|
22
|
+
*/
|
|
23
|
+
export declare function parse(source: string): JsonDocument;
|
|
24
|
+
export declare function print(doc: JsonDocument): string;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { parseTree } from "jsonc-parser";
|
|
2
|
+
const BOM = "";
|
|
3
|
+
const hadBom = new WeakSet();
|
|
4
|
+
/**
|
|
5
|
+
* Wraps `source` in a `JsonDocument`, throwing on any syntax error. Comments and trailing
|
|
6
|
+
* commas are JSONC and allowed; an empty or whitespace/comment-only source is a document with
|
|
7
|
+
* no value, which `setValue` fills.
|
|
8
|
+
*/
|
|
9
|
+
export function parse(source) {
|
|
10
|
+
const doc = { text: source.startsWith(BOM) ? source.slice(BOM.length) : source };
|
|
11
|
+
const errors = [];
|
|
12
|
+
parseTree(doc.text, errors, { allowTrailingComma: true, disallowComments: false, allowEmptyContent: true });
|
|
13
|
+
if (errors.length > 0)
|
|
14
|
+
throw new Error("invalid JSON");
|
|
15
|
+
if (source.startsWith(BOM))
|
|
16
|
+
hadBom.add(doc);
|
|
17
|
+
return doc;
|
|
18
|
+
}
|
|
19
|
+
export function print(doc) {
|
|
20
|
+
return hadBom.has(doc) ? BOM + doc.text : doc.text;
|
|
21
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { type Handle } from "../../core/define-dialect.ts";
|
|
2
|
+
import type { JsonPath, JsonValue } from "../../core/json-value.ts";
|
|
3
|
+
import { type JsonDocument } from "./ast.ts";
|
|
4
|
+
import { type AppendOptions, type KeyPosition, type SortOptions } from "./ops.ts";
|
|
5
|
+
export * as astLibrary from "jsonc-parser";
|
|
6
|
+
export type { JsonDocument, JsonPath, JsonValue, KeyPosition, AppendOptions, SortOptions };
|
|
7
|
+
type JsonOps = {
|
|
8
|
+
setValue: (ast: JsonDocument, path: JsonPath, value: JsonValue, options?: KeyPosition) => void;
|
|
9
|
+
addKey: (ast: JsonDocument, path: JsonPath, value: JsonValue, options?: KeyPosition) => void;
|
|
10
|
+
removeKey: (ast: JsonDocument, path: JsonPath) => void;
|
|
11
|
+
renameKey: (ast: JsonDocument, path: JsonPath, newKey: string) => void;
|
|
12
|
+
insertItem: (ast: JsonDocument, path: JsonPath, index: number, value: JsonValue) => void;
|
|
13
|
+
appendItem: (ast: JsonDocument, path: JsonPath, value: JsonValue, options?: AppendOptions) => void;
|
|
14
|
+
removeItem: (ast: JsonDocument, path: JsonPath, index: number) => void;
|
|
15
|
+
removeValue: (ast: JsonDocument, path: JsonPath, value: JsonValue) => void;
|
|
16
|
+
replaceItem: (ast: JsonDocument, path: JsonPath, index: number, value: JsonValue) => void;
|
|
17
|
+
moveItem: (ast: JsonDocument, path: JsonPath, from: number, to: number) => void;
|
|
18
|
+
merge: (ast: JsonDocument, path: JsonPath, value: {
|
|
19
|
+
[key: string]: JsonValue;
|
|
20
|
+
}) => void;
|
|
21
|
+
updateValue: <T extends JsonValue>(ast: JsonDocument, path: JsonPath, fn: (current: JsonValue | undefined) => T) => void;
|
|
22
|
+
moveValue: (ast: JsonDocument, from: JsonPath, to: JsonPath) => void;
|
|
23
|
+
copyValue: (ast: JsonDocument, from: JsonPath, to: JsonPath) => void;
|
|
24
|
+
sortKeys: (ast: JsonDocument, path: JsonPath, options?: SortOptions) => void;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Opens a `.json` or `.jsonc` file for structural editing. Every op addresses a value by a
|
|
28
|
+
* path array (`["scripts", "build"]`, `["files", 0]`) and edits only the bytes it must:
|
|
29
|
+
* comments, key order, indentation, line endings, a BOM, and the trailing newline survive.
|
|
30
|
+
* Any other extension, a basename with no stem (`.json`), or an extensionless path throws
|
|
31
|
+
* synchronously with the `dialect operation failed: ` prefix. `.modify(fn)` hands `fn` the
|
|
32
|
+
* live `JsonDocument`; edit its `text` with `astLibrary` (`jsonc-parser`) for anything the
|
|
33
|
+
* ops do not cover, such as comments.
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* import * as json from "@pbuilder/sdk/json";
|
|
37
|
+
*
|
|
38
|
+
* // package.json before: {\n "name": "app"\n}\n
|
|
39
|
+
* export const run = async () => {
|
|
40
|
+
* await json
|
|
41
|
+
* .find("package.json")
|
|
42
|
+
* .setValue(["scripts", "build"], "tsc")
|
|
43
|
+
* .appendItem(["files"], "dist", { unique: true });
|
|
44
|
+
* };
|
|
45
|
+
* // -> {
|
|
46
|
+
* // -> "name": "app",
|
|
47
|
+
* // -> "scripts": {
|
|
48
|
+
* // -> "build": "tsc"
|
|
49
|
+
* // -> },
|
|
50
|
+
* // -> "files": [
|
|
51
|
+
* // -> "dist"
|
|
52
|
+
* // -> ]
|
|
53
|
+
* // -> }
|
|
54
|
+
*/
|
|
55
|
+
export declare function find(path: string): Handle<"found", JsonDocument, JsonOps>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { defineDialect, defineOpPack, withOps } from "../../core/define-dialect.js";
|
|
2
|
+
import { parse, print } from "./ast.js";
|
|
3
|
+
import { addKey, appendItem, copyValue, insertItem, merge, moveItem, moveValue, removeItem, removeKey, removeValue, renameKey, replaceItem, setValue, sortKeys, updateValue, } from "./ops.js";
|
|
4
|
+
export * as astLibrary from "jsonc-parser";
|
|
5
|
+
const opsPack = defineOpPack({
|
|
6
|
+
setValue,
|
|
7
|
+
addKey,
|
|
8
|
+
removeKey,
|
|
9
|
+
renameKey,
|
|
10
|
+
insertItem,
|
|
11
|
+
appendItem,
|
|
12
|
+
removeItem,
|
|
13
|
+
removeValue,
|
|
14
|
+
replaceItem,
|
|
15
|
+
moveItem,
|
|
16
|
+
merge,
|
|
17
|
+
updateValue,
|
|
18
|
+
moveValue,
|
|
19
|
+
copyValue,
|
|
20
|
+
sortKeys,
|
|
21
|
+
});
|
|
22
|
+
const jsonDialect = withOps(defineDialect({ extensions: [".json", ".jsonc"], ast: { parse, print }, ops: {} }), opsPack);
|
|
23
|
+
/**
|
|
24
|
+
* Opens a `.json` or `.jsonc` file for structural editing. Every op addresses a value by a
|
|
25
|
+
* path array (`["scripts", "build"]`, `["files", 0]`) and edits only the bytes it must:
|
|
26
|
+
* comments, key order, indentation, line endings, a BOM, and the trailing newline survive.
|
|
27
|
+
* Any other extension, a basename with no stem (`.json`), or an extensionless path throws
|
|
28
|
+
* synchronously with the `dialect operation failed: ` prefix. `.modify(fn)` hands `fn` the
|
|
29
|
+
* live `JsonDocument`; edit its `text` with `astLibrary` (`jsonc-parser`) for anything the
|
|
30
|
+
* ops do not cover, such as comments.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* import * as json from "@pbuilder/sdk/json";
|
|
34
|
+
*
|
|
35
|
+
* // package.json before: {\n "name": "app"\n}\n
|
|
36
|
+
* export const run = async () => {
|
|
37
|
+
* await json
|
|
38
|
+
* .find("package.json")
|
|
39
|
+
* .setValue(["scripts", "build"], "tsc")
|
|
40
|
+
* .appendItem(["files"], "dist", { unique: true });
|
|
41
|
+
* };
|
|
42
|
+
* // -> {
|
|
43
|
+
* // -> "name": "app",
|
|
44
|
+
* // -> "scripts": {
|
|
45
|
+
* // -> "build": "tsc"
|
|
46
|
+
* // -> },
|
|
47
|
+
* // -> "files": [
|
|
48
|
+
* // -> "dist"
|
|
49
|
+
* // -> ]
|
|
50
|
+
* // -> }
|
|
51
|
+
*/
|
|
52
|
+
export function find(path) {
|
|
53
|
+
return jsonDialect.find(path);
|
|
54
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { type JsonPath, type JsonValue } from "../../core/json-value.ts";
|
|
2
|
+
import type { JsonDocument } from "./ast.ts";
|
|
3
|
+
export interface KeyPosition {
|
|
4
|
+
before?: string;
|
|
5
|
+
after?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface AppendOptions {
|
|
8
|
+
unique?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface SortOptions {
|
|
11
|
+
recursive?: boolean;
|
|
12
|
+
}
|
|
13
|
+
type JsonObject = {
|
|
14
|
+
[key: string]: JsonValue;
|
|
15
|
+
};
|
|
16
|
+
/** Sets the value at `path`, creating missing parent objects (upsert). */
|
|
17
|
+
export declare function setValue(doc: JsonDocument, path: JsonPath, value: JsonValue, options?: KeyPosition): void;
|
|
18
|
+
/** Adds an absent object key; a deep-equal existing value is a no-op, a different one rejects. */
|
|
19
|
+
export declare function addKey(doc: JsonDocument, path: JsonPath, value: JsonValue, options?: KeyPosition): void;
|
|
20
|
+
/** Removes an object key and its separator; an absent key is a no-op. */
|
|
21
|
+
export declare function removeKey(doc: JsonDocument, path: JsonPath): void;
|
|
22
|
+
/** Renames an object key in place, keeping its value, position, and comments. */
|
|
23
|
+
export declare function renameKey(doc: JsonDocument, path: JsonPath, newKey: string): void;
|
|
24
|
+
/** Inserts `value` before the item at `index`; `index === length` appends. */
|
|
25
|
+
export declare function insertItem(doc: JsonDocument, path: JsonPath, index: number, value: JsonValue): void;
|
|
26
|
+
/** Appends `value`, creating the array when absent; `{ unique: true }` skips a deep-equal duplicate. */
|
|
27
|
+
export declare function appendItem(doc: JsonDocument, path: JsonPath, value: JsonValue, options?: AppendOptions): void;
|
|
28
|
+
/** Removes the item at `index` and its separator. */
|
|
29
|
+
export declare function removeItem(doc: JsonDocument, path: JsonPath, index: number): void;
|
|
30
|
+
/** Removes every item deep-equal to `value`; no match (or no array) is a no-op. */
|
|
31
|
+
export declare function removeValue(doc: JsonDocument, path: JsonPath, value: JsonValue): void;
|
|
32
|
+
/** Replaces the item at `index` in place. */
|
|
33
|
+
export declare function replaceItem(doc: JsonDocument, path: JsonPath, index: number, value: JsonValue): void;
|
|
34
|
+
/** Moves the item at `from` so it ends up at `to`; the other items keep their relative order. */
|
|
35
|
+
export declare function moveItem(doc: JsonDocument, path: JsonPath, from: number, to: number): void;
|
|
36
|
+
/** Deep-merges a plain object into the object at `path`; arrays and scalars are replaced. */
|
|
37
|
+
export declare function merge(doc: JsonDocument, path: JsonPath, value: JsonObject): void;
|
|
38
|
+
/** Replaces the value at `path` with `fn(current)`; `current` is `undefined` when absent. */
|
|
39
|
+
export declare function updateValue<T extends JsonValue>(doc: JsonDocument, path: JsonPath, fn: (current: JsonValue | undefined) => T): void;
|
|
40
|
+
/** Moves the value at `from` to `to` (RFC 6902 `move`); a `number` last segment in `to` inserts. */
|
|
41
|
+
export declare function moveValue(doc: JsonDocument, from: JsonPath, to: JsonPath): void;
|
|
42
|
+
/** Copies the value at `from` to `to` with `setValue`'s rules (RFC 6902 `copy`). */
|
|
43
|
+
export declare function copyValue(doc: JsonDocument, from: JsonPath, to: JsonPath): void;
|
|
44
|
+
/** Orders the object's members by key (code-point order); `{ recursive: true }` sorts nested objects too. */
|
|
45
|
+
export declare function sortKeys(doc: JsonDocument, path: JsonPath, options?: SortOptions): void;
|
|
46
|
+
export {};
|