@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.
@@ -0,0 +1,154 @@
1
+ // `yaml` parse/print pair for the YAML dialect. The library re-serializes a whole document from
2
+ // its node tree, which normalizes spacing, folds, and number spelling, so fidelity is kept per
3
+ // document: a document whose serialization still equals the one taken right after parse is
4
+ // printed from its original source slice; only touched documents are re-serialized.
5
+ import { stringifyString } from "yaml/util";
6
+ import { Document, isAlias, isMap, isNode, isScalar, isSeq, parseAllDocuments, visit } from "yaml";
7
+ export const DOCUMENT_OPTIONS = { merge: true };
8
+ const BOM = "";
9
+ const streamStates = new WeakMap();
10
+ const documentStates = new WeakMap();
11
+ function detectEol(source) {
12
+ const crlf = source.split("\r\n").length - 1;
13
+ const lf = source.split("\n").length - 1 - crlf;
14
+ return crlf > lf ? "\r\n" : "\n";
15
+ }
16
+ const leadingSpaces = (line) => line.length - line.trimStart().length;
17
+ function inferOptions(source) {
18
+ const lines = source.split(/\r?\n/).filter((line) => line.trim() !== "" && !line.trimStart().startsWith("#"));
19
+ const indents = lines.map(leadingSpaces).filter((width) => width > 0);
20
+ const indent = indents.length > 0 ? Math.min(...indents) : 2;
21
+ let indentSeq = true;
22
+ for (let i = 0; i + 1 < lines.length; i++) {
23
+ const parent = lines[i];
24
+ const child = lines[i + 1];
25
+ if (/:\s*(#.*)?$/.test(parent) && child.trimStart().startsWith("- ")) {
26
+ indentSeq = leadingSpaces(child) > leadingSpaces(parent);
27
+ break;
28
+ }
29
+ }
30
+ const flow = /[[{](\s?)[^\s\]}]/.exec(source);
31
+ return { indent, indentSeq, flowCollectionPadding: flow === null || flow[1] !== "", lineWidth: 0 };
32
+ }
33
+ // The library accepts an alias to an undefined anchor at parse time and only fails later.
34
+ function assertAliasesDefined(document) {
35
+ const anchors = new Set();
36
+ visit(document, (_, node) => {
37
+ if (isAlias(node)) {
38
+ if (!anchors.has(node.source))
39
+ throw new Error(`invalid YAML: alias *${node.source} has no preceding anchor`);
40
+ }
41
+ else if (isNode(node) && node.anchor) {
42
+ anchors.add(node.anchor);
43
+ }
44
+ });
45
+ }
46
+ // The library keeps a comment above the first entry of a block collection on the collection
47
+ // itself; moving it onto that entry lets ops read, replace, remove, sort, and move it with the
48
+ // entry. Both spellings print the same.
49
+ function attachLeadingComments(document) {
50
+ visit(document, (_, node) => {
51
+ if (!(isMap(node) || isSeq(node)) || node.flow === true || !node.commentBefore || node.items.length === 0)
52
+ return;
53
+ const first = node.items[0];
54
+ const holder = isMap(node) ? first.key : first;
55
+ if (!isNode(holder))
56
+ return;
57
+ holder.commentBefore = holder.commentBefore ? `${node.commentBefore}\n${holder.commentBefore}` : node.commentBefore;
58
+ node.commentBefore = undefined;
59
+ });
60
+ }
61
+ // A tag the schema does not know falls back to the string stringifier, which quotes a value
62
+ // such as `8080` to keep it a string. The explicit tag already decides how the value resolves,
63
+ // so each unknown tag gets a pass-through entry that leaves the scalar's own style alone.
64
+ function registerUnknownTags(document) {
65
+ const known = new Set(document.schema.tags.map((tag) => tag.tag));
66
+ const extra = [];
67
+ visit(document, {
68
+ Scalar(_, scalar) {
69
+ if (scalar.tag === undefined || known.has(scalar.tag))
70
+ return;
71
+ known.add(scalar.tag);
72
+ extra.push({
73
+ tag: scalar.tag,
74
+ default: false,
75
+ resolve: (source) => source,
76
+ stringify: (item, ctx, onComment, onChompKeep) => isScalar(item) && typeof item.value === "string"
77
+ ? stringifyString(item, ctx, onComment, onChompKeep)
78
+ : String(item.value),
79
+ });
80
+ },
81
+ });
82
+ if (extra.length > 0)
83
+ document.schema.tags = [...document.schema.tags, ...extra];
84
+ }
85
+ /** A document created by an op, sharing the parse options so merge keys resolve alike. */
86
+ export function newDocument(value) {
87
+ if (value === undefined) {
88
+ const document = new Document(null, DOCUMENT_OPTIONS);
89
+ document.contents = null;
90
+ return document;
91
+ }
92
+ return new Document(value, { ...DOCUMENT_OPTIONS, aliasDuplicateObjects: false });
93
+ }
94
+ /**
95
+ * Parses YAML source into a `YamlStream`. Throws on the first syntax error of any document; the
96
+ * dialect handle contains it.
97
+ */
98
+ export function parse(source) {
99
+ const bom = source.startsWith(BOM);
100
+ const body = bom ? source.slice(BOM.length) : source;
101
+ const parsed = parseAllDocuments(body, DOCUMENT_OPTIONS);
102
+ const documents = [...parsed];
103
+ for (const document of documents) {
104
+ if (document.errors.length > 0)
105
+ throw new Error(`invalid YAML: ${document.errors[0].message}`);
106
+ assertAliasesDefined(document);
107
+ attachLeadingComments(document);
108
+ }
109
+ const stream = { documents };
110
+ streamStates.set(stream, {
111
+ bom,
112
+ eol: detectEol(body),
113
+ preamble: documents.length === 0 ? body : "",
114
+ finalNewline: body === "" || body.endsWith("\n"),
115
+ options: inferOptions(body),
116
+ });
117
+ let start = 0;
118
+ documents.forEach((document, index) => {
119
+ const end = index === documents.length - 1 ? body.length : document.range[2];
120
+ const slice = body.slice(start, end);
121
+ const options = inferOptions(slice);
122
+ documentStates.set(document, {
123
+ slice,
124
+ fresh: (registerUnknownTags(document), document.toString(options)),
125
+ marker: document.directives.docStart === true,
126
+ options,
127
+ });
128
+ start = end;
129
+ });
130
+ return stream;
131
+ }
132
+ function printDocument(document, position, stream) {
133
+ registerUnknownTags(document);
134
+ const state = documentStates.get(document);
135
+ if (state !== undefined && document.toString(state.options) === state.fresh) {
136
+ return position > 0 && !state.marker ? `---${stream.eol}${state.slice}` : state.slice;
137
+ }
138
+ const options = state?.options ?? stream.options;
139
+ const text = document.toString(position > 0 ? { ...options, directives: true } : options);
140
+ return stream.eol === "\n" ? text : text.replace(/\n/g, stream.eol);
141
+ }
142
+ /** Prints the stream: untouched documents byte-identical, touched ones re-serialized. */
143
+ export function print(ast) {
144
+ const stream = streamStates.get(ast) ?? { bom: false, eol: "\n", preamble: "", finalNewline: true, options: inferOptions("") };
145
+ let out = stream.preamble;
146
+ ast.documents.forEach((document, position) => {
147
+ if (out !== "" && !out.endsWith("\n"))
148
+ out += stream.eol;
149
+ out += printDocument(document, position, stream);
150
+ });
151
+ if (!stream.finalNewline && out.endsWith(stream.eol))
152
+ out = out.slice(0, -stream.eol.length);
153
+ return stream.bom ? BOM + out : out;
154
+ }
@@ -0,0 +1,8 @@
1
+ import { type YamlStream } from "./ast.ts";
2
+ import { type YamlValue } from "./paths.ts";
3
+ /** Inserts a document holding `value` at `options.index`, by default at the end. */
4
+ export declare function addDocument(ast: YamlStream, value: YamlValue, options?: {
5
+ index?: number;
6
+ }): void;
7
+ /** Removes the document at `index`. */
8
+ export declare function removeDocument(ast: YamlStream, index: number): void;
@@ -0,0 +1,24 @@
1
+ // Document-level ops for multi-document files.
2
+ import { newDocument } from "./ast.js";
3
+ import { assertValue, fail, isPlainObject } from "./paths.js";
4
+ function assertIndex(op, index, max) {
5
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index > max) {
6
+ fail(op, null, `index ${String(index)} is out of range (0..${max}).`);
7
+ }
8
+ }
9
+ /** Inserts a document holding `value` at `options.index`, by default at the end. */
10
+ export function addDocument(ast, value, options) {
11
+ assertValue("addDocument", [], value);
12
+ if (options !== undefined && !isPlainObject(options))
13
+ fail("addDocument", null, "options must be a plain object.");
14
+ const index = options?.index ?? ast.documents.length;
15
+ assertIndex("addDocument", index, ast.documents.length);
16
+ ast.documents.splice(index, 0, newDocument(value));
17
+ }
18
+ /** Removes the document at `index`. */
19
+ export function removeDocument(ast, index) {
20
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= ast.documents.length) {
21
+ fail("removeDocument", null, `document ${String(index)} is out of range; the file has ${ast.documents.length} document(s).`);
22
+ }
23
+ ast.documents.splice(index, 1);
24
+ }
@@ -0,0 +1,69 @@
1
+ import { type Handle } from "../../core/define-dialect.ts";
2
+ import { type YamlStream } from "./ast.ts";
3
+ import type { DocumentOption, YamlPath, YamlValue } from "./paths.ts";
4
+ import { type CollectionStyle, type CommentOptions, type ScalarStyle } from "./presentation.ts";
5
+ import { type KeyOptions } from "./structural.ts";
6
+ export * as astLibrary from "yaml";
7
+ export type { YamlStream, YamlPath, YamlValue };
8
+ type YamlOps = {
9
+ setValue: (ast: YamlStream, path: YamlPath, value: YamlValue, options?: KeyOptions) => void;
10
+ addKey: (ast: YamlStream, path: YamlPath, value: YamlValue, options?: KeyOptions) => void;
11
+ removeKey: (ast: YamlStream, path: YamlPath, options?: DocumentOption) => void;
12
+ renameKey: (ast: YamlStream, path: YamlPath, newKey: string, options?: DocumentOption) => void;
13
+ insertItem: (ast: YamlStream, path: YamlPath, index: number, value: YamlValue, options?: DocumentOption) => void;
14
+ appendItem: (ast: YamlStream, path: YamlPath, value: YamlValue, options?: DocumentOption & {
15
+ unique?: boolean;
16
+ }) => void;
17
+ removeItem: (ast: YamlStream, path: YamlPath, index: number, options?: DocumentOption) => void;
18
+ removeValue: (ast: YamlStream, path: YamlPath, value: YamlValue, options?: DocumentOption) => void;
19
+ replaceItem: (ast: YamlStream, path: YamlPath, index: number, value: YamlValue, options?: DocumentOption) => void;
20
+ moveItem: (ast: YamlStream, path: YamlPath, from: number, to: number, options?: DocumentOption) => void;
21
+ merge: (ast: YamlStream, path: YamlPath, value: {
22
+ [key: string]: YamlValue;
23
+ }, options?: DocumentOption) => void;
24
+ updateValue: (ast: YamlStream, path: YamlPath, fn: (current: YamlValue | undefined) => YamlValue, options?: DocumentOption) => void;
25
+ setComment: (ast: YamlStream, path: YamlPath, comment: string, options?: CommentOptions) => void;
26
+ removeComment: (ast: YamlStream, path: YamlPath, options?: CommentOptions) => void;
27
+ setAnchor: (ast: YamlStream, path: YamlPath, name: string, options?: DocumentOption) => void;
28
+ removeAnchor: (ast: YamlStream, path: YamlPath, options?: DocumentOption) => void;
29
+ setAlias: (ast: YamlStream, path: YamlPath, anchor: string, options?: DocumentOption) => void;
30
+ addMergeKey: (ast: YamlStream, path: YamlPath, anchor: string, options?: DocumentOption) => void;
31
+ setStyle: (ast: YamlStream, path: YamlPath, style: CollectionStyle | ScalarStyle, options?: DocumentOption) => void;
32
+ addDocument: (ast: YamlStream, value: YamlValue, options?: {
33
+ index?: number;
34
+ }) => void;
35
+ removeDocument: (ast: YamlStream, index: number) => void;
36
+ moveValue: (ast: YamlStream, from: YamlPath, to: YamlPath, options?: DocumentOption) => void;
37
+ copyValue: (ast: YamlStream, from: YamlPath, to: YamlPath, options?: DocumentOption) => void;
38
+ sortKeys: (ast: YamlStream, path: YamlPath, options?: DocumentOption & {
39
+ recursive?: boolean;
40
+ }) => void;
41
+ setTag: (ast: YamlStream, path: YamlPath, tag: string | null, options?: DocumentOption) => void;
42
+ };
43
+ /**
44
+ * Opens a `.yaml` or `.yml` file for YAML-dialect editing. The basename must end in one of those
45
+ * extensions after a non-empty stem; every other path throws synchronously, before any op runs,
46
+ * with the `dialect operation failed: ` prefix.
47
+ *
48
+ * Every named op addresses a node by a path array (`["services", "web", "ports", 0]`) and takes
49
+ * an optional last `{ document }` option selecting a document of a multi-document file.
50
+ * Documents no op touched print byte-identical to their source.
51
+ *
52
+ * @example
53
+ * import * as yaml from "@pbuilder/sdk/yaml";
54
+ *
55
+ * // compose.yaml before: services:\n web:\n image: node\n
56
+ * export const run = async () => {
57
+ * await yaml
58
+ * .find("compose.yaml")
59
+ * .setValue(["services", "web", "ports"], ["3000:3000"])
60
+ * .setComment(["services", "web"], "Frontend");
61
+ * };
62
+ * // -> services:
63
+ * // -> # Frontend
64
+ * // -> web:
65
+ * // -> image: node
66
+ * // -> ports:
67
+ * // -> - 3000:3000
68
+ */
69
+ export declare function find(path: string): Handle<"found", YamlStream, YamlOps>;
@@ -0,0 +1,70 @@
1
+ // The YAML dialect module, `@pbuilder/sdk/yaml`. Composes the sanctioned kit surface only
2
+ // (`defineDialect`/`defineOpPack`/`withOps`), mirroring the other dialect modules.
3
+ import { defineDialect, defineOpPack, withOps } from "../../core/define-dialect.js";
4
+ import { parse, print } from "./ast.js";
5
+ import { addDocument, removeDocument } from "./documents.js";
6
+ import { addMergeKey, removeAnchor, removeComment, setAlias, setAnchor, setComment, setStyle, setTag, } from "./presentation.js";
7
+ import { addKey, appendItem, copyValue, insertItem, merge, moveItem, moveValue, removeItem, removeKey, removeValue, renameKey, replaceItem, setValue, sortKeys, updateValue, } from "./structural.js";
8
+ export * as astLibrary from "yaml";
9
+ const opsPack = defineOpPack({
10
+ setValue,
11
+ addKey,
12
+ removeKey,
13
+ renameKey,
14
+ insertItem,
15
+ appendItem,
16
+ removeItem,
17
+ removeValue,
18
+ replaceItem,
19
+ moveItem,
20
+ merge,
21
+ updateValue,
22
+ setComment,
23
+ removeComment,
24
+ setAnchor,
25
+ removeAnchor,
26
+ setAlias,
27
+ addMergeKey,
28
+ setStyle,
29
+ addDocument,
30
+ removeDocument,
31
+ moveValue,
32
+ copyValue,
33
+ sortKeys,
34
+ setTag,
35
+ });
36
+ const baseDialect = defineDialect({
37
+ extensions: [".yaml", ".yml"],
38
+ ast: { parse, print },
39
+ ops: {},
40
+ });
41
+ const yamlDialect = withOps(baseDialect, opsPack);
42
+ /**
43
+ * Opens a `.yaml` or `.yml` file for YAML-dialect editing. The basename must end in one of those
44
+ * extensions after a non-empty stem; every other path throws synchronously, before any op runs,
45
+ * with the `dialect operation failed: ` prefix.
46
+ *
47
+ * Every named op addresses a node by a path array (`["services", "web", "ports", 0]`) and takes
48
+ * an optional last `{ document }` option selecting a document of a multi-document file.
49
+ * Documents no op touched print byte-identical to their source.
50
+ *
51
+ * @example
52
+ * import * as yaml from "@pbuilder/sdk/yaml";
53
+ *
54
+ * // compose.yaml before: services:\n web:\n image: node\n
55
+ * export const run = async () => {
56
+ * await yaml
57
+ * .find("compose.yaml")
58
+ * .setValue(["services", "web", "ports"], ["3000:3000"])
59
+ * .setComment(["services", "web"], "Frontend");
60
+ * };
61
+ * // -> services:
62
+ * // -> # Frontend
63
+ * // -> web:
64
+ * // -> image: node
65
+ * // -> ports:
66
+ * // -> - 3000:3000
67
+ */
68
+ export function find(path) {
69
+ return yamlDialect.find(path);
70
+ }
@@ -0,0 +1,55 @@
1
+ import { Pair, type Document, type Node, type YAMLMap, type YAMLSeq } from "yaml";
2
+ import { type JsonPath, type JsonValue } from "../../core/json-value.ts";
3
+ import { type YamlStream } from "./ast.ts";
4
+ export type YamlValue = JsonValue;
5
+ export type YamlPath = JsonPath;
6
+ /** The `{ document }` option every op accepts as its last argument. */
7
+ export interface DocumentOption {
8
+ document?: number;
9
+ }
10
+ /** Key placement for a newly created mapping key. */
11
+ export interface PositionOption {
12
+ before?: string;
13
+ after?: string;
14
+ }
15
+ export type Container = YAMLMap | YAMLSeq;
16
+ /** A resolved location: the node at `path` (null when absent) and where it lives. */
17
+ export interface Slot {
18
+ parent: Container | null;
19
+ segment: string | number | null;
20
+ node: Node | null;
21
+ }
22
+ export declare function fail(op: string, path: YamlPath | null, tail: string): never;
23
+ export declare function isPlainObject(value: unknown): value is {
24
+ [key: string]: JsonValue;
25
+ };
26
+ export declare function assertPath(op: string, path: unknown): asserts path is YamlPath;
27
+ export declare function assertValue(op: string, path: YamlPath, value: unknown): asserts value is YamlValue;
28
+ /**
29
+ * Picks the document an op edits. An empty stream gets document 0 created on demand by the ops
30
+ * that create missing parents; every other out-of-range index rejects.
31
+ */
32
+ export declare function selectDocument(op: string, stream: YamlStream, options: DocumentOption | undefined, create?: boolean): Document;
33
+ export declare function keyLabel(key: unknown): string | undefined;
34
+ export declare function findPair(map: YAMLMap, key: string): Pair | undefined;
35
+ export declare function resolveAlias(document: Document, node: Node | null): Node | null;
36
+ /**
37
+ * Walks `path`. `mode` decides how containers along the way behave: `read` follows aliases,
38
+ * `write` rejects descending into an alias, and `create` also adds missing parents as mappings.
39
+ */
40
+ export declare function resolve(op: string, document: Document, path: YamlPath, mode: "read" | "write" | "create"): Slot;
41
+ /** Writes `node` into the slot's position, creating the mapping key when absent. */
42
+ export declare function writeSlot(document: Document, slot: Slot, node: Node, position?: PositionOption): void;
43
+ /** Rejects a malformed `before`/`after` before anything changes. */
44
+ export declare function assertPosition(op: string, path: YamlPath, document: Document, options: PositionOption | undefined): void;
45
+ /** Builds a node from plain data; a value referenced twice is written out twice, never aliased. */
46
+ export declare function createNode(document: Document, value: unknown): Node;
47
+ export declare function toValue(document: Document, node: Node | null): unknown;
48
+ /**
49
+ * Builds the node that replaces `old` with `value`, keeping its comments, blank line, anchor,
50
+ * and collection style. A scalar of the same type is edited in place so its quoting survives.
51
+ */
52
+ export declare function replacement(document: Document, old: Node | null, value: YamlValue): Node;
53
+ /** Every alias must follow a node carrying its anchor in document order. */
54
+ export declare function assertAliasesResolve(op: string, document: Document): void;
55
+ export declare function findAnchored(document: Document, name: string): Node | undefined;
@@ -0,0 +1,208 @@
1
+ // Shared plumbing for the YAML ops: document selection, path resolution over `yaml` nodes,
2
+ // node replacement that keeps comments and anchors, and the alias-order invariant.
3
+ import { Pair, Scalar, isAlias, isMap, isNode, isScalar, isSeq, visit } from "yaml";
4
+ import { dialectError } from "../../core/dialect-error.js";
5
+ import { assertJsonValue, formatPath } from "../../core/json-value.js";
6
+ import { newDocument } from "./ast.js";
7
+ export function fail(op, path, tail) {
8
+ throw dialectError(path === null ? `${op}: ${tail}` : `${op} ${formatPath(path)}: ${tail}`);
9
+ }
10
+ export function isPlainObject(value) {
11
+ if (value === null || typeof value !== "object" || Array.isArray(value))
12
+ return false;
13
+ const proto = Object.getPrototypeOf(value);
14
+ return proto === Object.prototype || proto === null;
15
+ }
16
+ export function assertPath(op, path) {
17
+ if (!Array.isArray(path))
18
+ fail(op, null, "path must be an array of keys and indices.");
19
+ for (const segment of path) {
20
+ if (typeof segment === "string")
21
+ continue;
22
+ if (typeof segment !== "number" || !Number.isInteger(segment) || segment < 0) {
23
+ fail(op, path, `segment ${String(segment)} is neither a key nor a non-negative integer index.`);
24
+ }
25
+ }
26
+ }
27
+ export function assertValue(op, path, value) {
28
+ try {
29
+ assertJsonValue(value);
30
+ }
31
+ catch (error) {
32
+ const message = error instanceof Error ? error.message.replace(/^dialect operation failed: /, "") : String(error);
33
+ fail(op, path, message);
34
+ }
35
+ }
36
+ function assertOptions(op, options) {
37
+ if (options !== undefined && !isPlainObject(options))
38
+ fail(op, null, "options must be a plain object.");
39
+ }
40
+ /**
41
+ * Picks the document an op edits. An empty stream gets document 0 created on demand by the ops
42
+ * that create missing parents; every other out-of-range index rejects.
43
+ */
44
+ export function selectDocument(op, stream, options, create = false) {
45
+ assertOptions(op, options);
46
+ const index = options?.document ?? 0;
47
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= stream.documents.length) {
48
+ if (create && index === 0 && stream.documents.length === 0) {
49
+ const document = newDocument();
50
+ stream.documents.push(document);
51
+ return document;
52
+ }
53
+ fail(op, null, `document ${String(index)} is out of range; the file has ${stream.documents.length} document(s).`);
54
+ }
55
+ return stream.documents[index];
56
+ }
57
+ export function keyLabel(key) {
58
+ if (!isScalar(key))
59
+ return undefined;
60
+ return typeof key.value === "symbol" ? "<<" : String(key.value);
61
+ }
62
+ export function findPair(map, key) {
63
+ return map.items.find((pair) => keyLabel(pair.key) === key);
64
+ }
65
+ function childOf(container, segment) {
66
+ if (isMap(container)) {
67
+ const pair = findPair(container, segment);
68
+ return pair === undefined ? null : (pair.value ?? new Scalar(null));
69
+ }
70
+ return container.items[segment] ?? null;
71
+ }
72
+ export function resolveAlias(document, node) {
73
+ return isAlias(node) ? (node.resolve(document) ?? null) : node;
74
+ }
75
+ function describe(node) {
76
+ if (isMap(node))
77
+ return "a mapping";
78
+ if (isSeq(node))
79
+ return "a sequence";
80
+ if (isAlias(node))
81
+ return `the alias *${node.source}`;
82
+ return "a scalar";
83
+ }
84
+ /**
85
+ * Walks `path`. `mode` decides how containers along the way behave: `read` follows aliases,
86
+ * `write` rejects descending into an alias, and `create` also adds missing parents as mappings.
87
+ */
88
+ export function resolve(op, document, path, mode) {
89
+ let slot = { parent: null, segment: null, node: document.contents ?? null };
90
+ for (let i = 0; i < path.length; i++) {
91
+ const segment = path[i];
92
+ let current = slot.node;
93
+ if (isAlias(current)) {
94
+ if (mode !== "read")
95
+ fail(op, path, `${formatPath(path.slice(0, i))} is the alias *${current.source}; edit the anchored node instead.`);
96
+ current = resolveAlias(document, current);
97
+ }
98
+ if (current === null) {
99
+ if (mode !== "create")
100
+ return { parent: null, segment, node: null };
101
+ if (typeof segment === "number")
102
+ fail(op, path, `${formatPath(path.slice(0, i))} is absent; only mappings are created for missing parents.`);
103
+ current = createNode(document, {});
104
+ writeSlot(document, slot, current);
105
+ }
106
+ if (typeof segment === "number" && !isSeq(current)) {
107
+ fail(op, path, `index ${segment} addresses ${describe(current)}, not a sequence.`);
108
+ }
109
+ if (typeof segment === "string" && !isMap(current)) {
110
+ fail(op, path, `key "${segment}" addresses ${describe(current)}, not a mapping.`);
111
+ }
112
+ const container = current;
113
+ slot = { parent: container, segment, node: childOf(container, segment) };
114
+ }
115
+ return slot;
116
+ }
117
+ /** Writes `node` into the slot's position, creating the mapping key when absent. */
118
+ export function writeSlot(document, slot, node, position) {
119
+ if (slot.parent === null) {
120
+ document.contents = node;
121
+ return;
122
+ }
123
+ if (isMap(slot.parent)) {
124
+ const existing = findPair(slot.parent, slot.segment);
125
+ if (existing !== undefined) {
126
+ existing.value = node;
127
+ return;
128
+ }
129
+ const pair = new Pair(new Scalar(slot.segment), node);
130
+ slot.parent.items.splice(insertionIndex(slot.parent, position), 0, pair);
131
+ return;
132
+ }
133
+ slot.parent.items[slot.segment] = node;
134
+ }
135
+ function insertionIndex(map, position) {
136
+ const sibling = position?.before ?? position?.after;
137
+ if (sibling === undefined)
138
+ return map.items.length;
139
+ const index = map.items.findIndex((pair) => keyLabel(pair.key) === sibling);
140
+ return position?.before !== undefined ? index : index + 1;
141
+ }
142
+ /** Rejects a malformed `before`/`after` before anything changes. */
143
+ export function assertPosition(op, path, document, options) {
144
+ if (options?.before !== undefined && options.after !== undefined)
145
+ fail(op, path, "give either before or after, not both.");
146
+ const sibling = options?.before ?? options?.after;
147
+ if (sibling === undefined)
148
+ return;
149
+ if (path.length === 0 || typeof path[path.length - 1] !== "string")
150
+ fail(op, path, "before/after only place mapping keys.");
151
+ const parent = resolve(op, document, path.slice(0, -1), "read").node;
152
+ const resolved = resolveAlias(document, parent);
153
+ const exists = isMap(resolved) && findPair(resolved, path[path.length - 1]) !== undefined;
154
+ if (!exists && !(isMap(resolved) && findPair(resolved, sibling) !== undefined)) {
155
+ fail(op, path, `sibling key "${sibling}" does not exist.`);
156
+ }
157
+ }
158
+ /** Builds a node from plain data; a value referenced twice is written out twice, never aliased. */
159
+ export function createNode(document, value) {
160
+ return document.createNode(value, { aliasDuplicateObjects: false });
161
+ }
162
+ export function toValue(document, node) {
163
+ if (node === null)
164
+ return undefined;
165
+ return node.toJS(document, { maxAliasCount: -1 });
166
+ }
167
+ /**
168
+ * Builds the node that replaces `old` with `value`, keeping its comments, blank line, anchor,
169
+ * and collection style. A scalar of the same type is edited in place so its quoting survives.
170
+ */
171
+ export function replacement(document, old, value) {
172
+ if (isScalar(old) && value !== null && typeof value !== "object" && typeof old.value === typeof value && old.tag === undefined) {
173
+ old.value = value;
174
+ return old;
175
+ }
176
+ const node = createNode(document, value);
177
+ if (old !== null) {
178
+ node.commentBefore = old.commentBefore;
179
+ node.comment = old.comment;
180
+ node.spaceBefore = old.spaceBefore;
181
+ if (!isAlias(old))
182
+ node.anchor = old.anchor;
183
+ if ((isMap(old) || isSeq(old)) && (isMap(node) || isSeq(node)))
184
+ node.flow = old.flow;
185
+ }
186
+ return node;
187
+ }
188
+ /** Every alias must follow a node carrying its anchor in document order. */
189
+ export function assertAliasesResolve(op, document) {
190
+ const seen = new Set();
191
+ visit(document, (_, node) => {
192
+ if (isAlias(node)) {
193
+ if (!seen.has(node.source))
194
+ fail(op, null, `the edit leaves the alias *${node.source} without a preceding anchor &${node.source}.`);
195
+ return;
196
+ }
197
+ if (isNode(node) && node.anchor)
198
+ seen.add(node.anchor);
199
+ });
200
+ }
201
+ export function findAnchored(document, name) {
202
+ let found;
203
+ visit(document, (_, node) => {
204
+ if (isNode(node) && !isAlias(node) && node.anchor === name)
205
+ found = node;
206
+ });
207
+ return found;
208
+ }
@@ -0,0 +1,24 @@
1
+ import type { YamlStream } from "./ast.ts";
2
+ import { type DocumentOption, type YamlPath } from "./paths.ts";
3
+ export type CommentPosition = "before" | "inline";
4
+ export type CommentOptions = DocumentOption & {
5
+ position?: CommentPosition;
6
+ };
7
+ export type CollectionStyle = "block" | "flow";
8
+ export type ScalarStyle = "plain" | "single" | "double" | "literal" | "folded";
9
+ /** Sets the comment before a node, or after it on the same line; multi-line text gives one `#` line each. */
10
+ export declare function setComment(ast: YamlStream, path: YamlPath, comment: string, options?: CommentOptions): void;
11
+ /** Removes the comment at the given position; no comment is a no-op. */
12
+ export declare function removeComment(ast: YamlStream, path: YamlPath, options?: CommentOptions): void;
13
+ /** Puts `&name` on the node at `path`; renaming an anchor re-points its aliases. */
14
+ export declare function setAnchor(ast: YamlStream, path: YamlPath, name: string, options?: DocumentOption): void;
15
+ /** Removes the anchor, replacing every alias to it with a copy so the data is unchanged. */
16
+ export declare function removeAnchor(ast: YamlStream, path: YamlPath, options?: DocumentOption): void;
17
+ /** Sets the value at `path` to `*anchor`, creating missing parents like `setValue`. */
18
+ export declare function setAlias(ast: YamlStream, path: YamlPath, anchor: string, options?: DocumentOption): void;
19
+ /** Adds `<<: *anchor` as the first entry of the mapping at `path`. */
20
+ export declare function addMergeKey(ast: YamlStream, path: YamlPath, anchor: string, options?: DocumentOption): void;
21
+ /** Sets a collection to block or flow, or a scalar to a quoting or block style. */
22
+ export declare function setStyle(ast: YamlStream, path: YamlPath, style: CollectionStyle | ScalarStyle, options?: DocumentOption): void;
23
+ /** Sets the node's tag, keeping its value and style; `null` removes it. */
24
+ export declare function setTag(ast: YamlStream, path: YamlPath, tag: string | null, options?: DocumentOption): void;