@pbuilder/sdk 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +67 -2
  2. package/dist/commons/index.js +5 -2
  3. package/dist/conformance/index.d.ts +2 -2
  4. package/dist/conformance/index.js +38 -19
  5. package/dist/core/define-dialect.js +15 -8
  6. package/dist/core/dialect-handle.js +1 -1
  7. package/dist/core/json-value.d.ts +14 -0
  8. package/dist/core/json-value.js +43 -0
  9. package/dist/dialects/json/ast.d.ts +24 -0
  10. package/dist/dialects/json/ast.js +21 -0
  11. package/dist/dialects/json/index.d.ts +55 -0
  12. package/dist/dialects/json/index.js +54 -0
  13. package/dist/dialects/json/ops.d.ts +46 -0
  14. package/dist/dialects/json/ops.js +561 -0
  15. package/dist/dialects/nestjs/index.d.ts +43 -0
  16. package/dist/dialects/nestjs/index.js +46 -0
  17. package/dist/dialects/nestjs/ops.d.ts +13 -0
  18. package/dist/dialects/nestjs/ops.js +100 -0
  19. package/dist/dialects/typescript/index.d.ts +15 -2
  20. package/dist/dialects/typescript/index.js +5 -10
  21. package/dist/dialects/typescript/ops.d.ts +65 -5
  22. package/dist/dialects/typescript/ops.js +272 -37
  23. package/dist/dialects/typescript/pack.d.ts +16 -0
  24. package/dist/dialects/typescript/pack.js +18 -0
  25. package/dist/dialects/yaml/ast.d.ts +15 -0
  26. package/dist/dialects/yaml/ast.js +154 -0
  27. package/dist/dialects/yaml/documents.d.ts +8 -0
  28. package/dist/dialects/yaml/documents.js +24 -0
  29. package/dist/dialects/yaml/index.d.ts +69 -0
  30. package/dist/dialects/yaml/index.js +70 -0
  31. package/dist/dialects/yaml/paths.d.ts +55 -0
  32. package/dist/dialects/yaml/paths.js +208 -0
  33. package/dist/dialects/yaml/presentation.d.ts +24 -0
  34. package/dist/dialects/yaml/presentation.js +264 -0
  35. package/dist/dialects/yaml/structural.d.ts +39 -0
  36. package/dist/dialects/yaml/structural.js +307 -0
  37. package/dist/runner-manifest.json +3 -3
  38. package/dist/transport/error-text.d.ts +6 -1
  39. package/dist/transport/error-text.js +94 -31
  40. package/package.json +21 -3
  41. package/schemas/project-builder.schema.json +112 -0
@@ -0,0 +1,561 @@
1
+ import { applyEdits, getNodeValue, modify, parseTree, } from "jsonc-parser";
2
+ import { deepEqual } from "../../core/deep-equal.js";
3
+ import { dialectError } from "../../core/dialect-error.js";
4
+ import { assertJsonValue, formatPath } from "../../core/json-value.js";
5
+ function fail(op, path, why) {
6
+ throw dialectError(`${op}(${formatPath(path)}) — ${why}`);
7
+ }
8
+ function assertPath(op, path) {
9
+ const valid = Array.isArray(path) &&
10
+ path.every((segment) => typeof segment === "string" || (Number.isInteger(segment) && segment >= 0));
11
+ if (!valid) {
12
+ throw dialectError(`${op} — a path must be an array of string keys and non-negative integer indices.`);
13
+ }
14
+ }
15
+ function assertKeyPath(op, path) {
16
+ assertPath(op, path);
17
+ if (typeof path.at(-1) !== "string")
18
+ fail(op, path, "the path must end in an object key.");
19
+ }
20
+ function assertIndex(op, path, index, max) {
21
+ if (!Number.isInteger(index) || index < 0 || index > max) {
22
+ fail(op, path, `index ${String(index)} is out of range 0..${max}.`);
23
+ }
24
+ }
25
+ function isPlainObject(value) {
26
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27
+ }
28
+ const PARSE_OPTIONS = { allowTrailingComma: true, disallowComments: false, allowEmptyContent: true };
29
+ // jsonc-parser is fault-tolerant and only reports syntax errors through `errors`, so every op
30
+ // checks them before trusting the tree. Comments and trailing commas are allowed (JSONC).
31
+ function readTree(op, text) {
32
+ const errors = [];
33
+ const root = parseTree(text, errors, PARSE_OPTIONS);
34
+ if (errors.length > 0)
35
+ throw dialectError(`${op} — the document is not valid JSON.`);
36
+ return root;
37
+ }
38
+ // Walks `path`, rejecting a segment whose kind does not fit its container (REQ-JSD-06).
39
+ function locate(op, text, path) {
40
+ const root = readTree(op, text);
41
+ const nodes = [root];
42
+ for (let depth = 0; depth < path.length; depth++) {
43
+ const current = nodes[depth];
44
+ if (current === undefined)
45
+ break;
46
+ const segment = path[depth];
47
+ const at = formatPath(path.slice(0, depth + 1));
48
+ if (current.type === "object") {
49
+ if (typeof segment === "number")
50
+ fail(op, path, `${at} indexes an object with a number.`);
51
+ const property = current.children?.find((child) => child.children?.[0]?.value === segment);
52
+ nodes.push(property?.children?.[1]);
53
+ }
54
+ else if (current.type === "array") {
55
+ if (typeof segment === "string")
56
+ fail(op, path, `${at} names a key on an array.`);
57
+ nodes.push(current.children?.[segment]);
58
+ }
59
+ else {
60
+ fail(op, path, `${at} crosses a ${current.type} value.`);
61
+ }
62
+ }
63
+ return {
64
+ root,
65
+ node: nodes[path.length],
66
+ parent: path.length > 0 ? nodes[path.length - 1] : undefined,
67
+ nodes,
68
+ missingDepth: nodes.findIndex((node) => node === undefined),
69
+ };
70
+ }
71
+ // Only setValue-style writes create parents, and only as objects (REQ-JSD-06).
72
+ function assertCreatable(op, path, missingDepth) {
73
+ if (missingDepth === -1)
74
+ return;
75
+ const keyedSegment = path[missingDepth - 1];
76
+ if (typeof keyedSegment === "number")
77
+ fail(op, path, `index ${keyedSegment} is out of range.`);
78
+ if (path.slice(missingDepth).some((segment) => typeof segment === "number")) {
79
+ fail(op, path, "a missing parent would have to be an array; only objects are created.");
80
+ }
81
+ }
82
+ function detectFormatting(text) {
83
+ const crlf = text.split("\r\n").length - 1;
84
+ const bareLf = text.split("\n").length - 1 - crlf;
85
+ const eol = crlf > bareLf ? "\r\n" : "\n";
86
+ const indent = /^([ \t]+)\S/m.exec(text)?.[1];
87
+ if (indent?.startsWith("\t"))
88
+ return { insertSpaces: false, tabSize: 1, eol };
89
+ return { insertSpaces: true, tabSize: indent?.length ?? 2, eol };
90
+ }
91
+ // jsonc-parser formats every line an edit touches, which would explode a one-line container
92
+ // into many lines; edits inside one-line containers therefore stay unformatted.
93
+ function formattingFor(text, located, path) {
94
+ const ancestors = located.nodes.slice(0, Math.max(path.length, 1));
95
+ const container = ancestors.findLast((node) => node !== undefined);
96
+ if (container === undefined)
97
+ return detectFormatting(text);
98
+ return text.slice(container.offset, container.offset + container.length).includes("\n")
99
+ ? detectFormatting(text)
100
+ : undefined;
101
+ }
102
+ function spaceSeparators(edit) {
103
+ let content = edit.content;
104
+ if (content.startsWith(",") && !content.startsWith(", "))
105
+ content = `, ${content.slice(1)}`;
106
+ if (content.endsWith(","))
107
+ content = `${content} `;
108
+ return { ...edit, content };
109
+ }
110
+ function write(op, doc, path, value, options = {}) {
111
+ const located = locate(op, doc.text, path);
112
+ const { position } = options;
113
+ if (value !== undefined && located.node === undefined && insertKeyLine(doc, located, path, value, position))
114
+ return;
115
+ const formattingOptions = formattingFor(doc.text, located, path);
116
+ const edits = modify(doc.text, [...path], value, {
117
+ formattingOptions,
118
+ getInsertionIndex: position === undefined
119
+ ? undefined
120
+ : (keys) => {
121
+ const sibling = position.before ?? position.after;
122
+ return keys.indexOf(sibling) + (position.after !== undefined ? 1 : 0);
123
+ },
124
+ });
125
+ doc.text = applyEdits(doc.text, formattingOptions === undefined ? edits.map(spaceSeparators) : edits);
126
+ }
127
+ const end = (node) => node.offset + node.length;
128
+ function splice(doc, start, stop, content) {
129
+ doc.text = doc.text.slice(0, start) + content + doc.text.slice(stop);
130
+ }
131
+ // Line-oriented layout of a container whose members each end their own line: a member owns
132
+ // the comment lines above it and the trailing comment on its last line, so edits move or drop
133
+ // those together with it. `undefined` for any other shape (one-line containers, two members on
134
+ // one line, a comma at the start of the next line).
135
+ function lineLayout(text, container) {
136
+ const children = container.children ?? [];
137
+ let leadStart = text.indexOf("\n", container.offset) + 1;
138
+ if (children.length === 0 || leadStart === 0 || leadStart > children[0].offset)
139
+ return undefined;
140
+ const lines = [];
141
+ for (const [index, member] of children.entries()) {
142
+ const newline = text.indexOf("\n", end(member));
143
+ const next = children[index + 1];
144
+ if (newline === -1 || newline >= (next?.offset ?? end(container) - 1))
145
+ return undefined;
146
+ const tailEnd = text[newline - 1] === "\r" ? newline - 1 : newline;
147
+ const commaEnd = afterComma(text, end(member), tailEnd);
148
+ const comma = commaEnd > end(member) ? commaEnd - 1 : -1;
149
+ if (comma === -1 && next !== undefined)
150
+ return undefined;
151
+ lines.push({ leadStart, comma, tailEnd, lineEnd: newline + 1 });
152
+ leadStart = newline + 1;
153
+ }
154
+ return lines;
155
+ }
156
+ // Removals and array insertions are computed against the existing separators rather than
157
+ // through jsonc-parser: its unformatted removal assumes the closing bracket sits on its own
158
+ // line, and its insertions put the new member between a member and its trailing comment.
159
+ function removeAt(op, doc, path) {
160
+ const node = locate(op, doc.text, path).node;
161
+ const member = typeof path.at(-1) === "number" ? node : node.parent;
162
+ const container = member.parent;
163
+ const children = container.children;
164
+ const index = children.indexOf(member);
165
+ const lines = lineLayout(doc.text, container);
166
+ if (children.length === 1) {
167
+ splice(doc, container.offset + 1, end(container) - 1, "");
168
+ }
169
+ else if (lines !== undefined) {
170
+ const line = lines[index];
171
+ const previousComma = index === children.length - 1 && line.comma === -1 ? lines[index - 1].comma : -1;
172
+ splice(doc, line.leadStart, line.lineEnd, "");
173
+ if (previousComma !== -1)
174
+ splice(doc, previousComma, previousComma + 1, "");
175
+ }
176
+ else if (index < children.length - 1) {
177
+ splice(doc, member.offset, children[index + 1].offset, "");
178
+ }
179
+ else {
180
+ splice(doc, end(children[index - 1]), end(member), "");
181
+ }
182
+ }
183
+ function indentUnit(text) {
184
+ const format = detectFormatting(text);
185
+ return format.insertSpaces ? " ".repeat(format.tabSize ?? 2) : "\t";
186
+ }
187
+ // Inserts `prefix + value` as its own line(s) before member `index`, or after the last member.
188
+ function insertLine(doc, container, lines, index, prefix, value) {
189
+ const text = doc.text;
190
+ const at = lines[Math.min(index, lines.length - 1)];
191
+ const member = container.children[Math.min(index, lines.length - 1)];
192
+ const indent = /[ \t]*$/.exec(text.slice(0, member.offset))[0];
193
+ const eol = text.slice(lines[0].tailEnd, lines[0].lineEnd);
194
+ const line = indent + prefix + JSON.stringify(value, null, indentUnit(text)).split("\n").join(eol + indent);
195
+ if (index < lines.length) {
196
+ splice(doc, at.leadStart, at.leadStart, `${line},${eol}`);
197
+ return;
198
+ }
199
+ splice(doc, at.lineEnd, at.lineEnd, `${line}${at.comma === -1 ? "" : ","}${eol}`);
200
+ const last = container.children.at(-1);
201
+ if (at.comma === -1)
202
+ splice(doc, end(last), end(last), ",");
203
+ }
204
+ function insertAt(op, doc, path, index, value) {
205
+ const array = requireArray(op, doc, path);
206
+ const items = array.children;
207
+ if (items.length === 0) {
208
+ splice(doc, array.offset + 1, end(array) - 1, JSON.stringify(value));
209
+ return;
210
+ }
211
+ const text = doc.text;
212
+ const lines = lineLayout(text, array);
213
+ if (lines !== undefined) {
214
+ insertLine(doc, array, lines, index, "", value);
215
+ return;
216
+ }
217
+ const anchor = items[Math.min(index, items.length - 1)];
218
+ const indent = text.slice(text.lastIndexOf("\n", anchor.offset - 1) + 1, anchor.offset);
219
+ const ownLine = text.slice(array.offset, end(array)).includes("\n") && /^[ \t]*$/.test(indent);
220
+ const eol = detectFormatting(text).eol ?? "\n";
221
+ const rendered = ownLine ? JSON.stringify(value, null, indentUnit(text)).split("\n").join(eol + indent) : JSON.stringify(value);
222
+ const gap = ownLine ? eol + indent : " ";
223
+ if (index < items.length)
224
+ splice(doc, anchor.offset, anchor.offset, `${rendered},${gap}`);
225
+ else
226
+ splice(doc, end(anchor), end(anchor), `,${gap}${rendered}`);
227
+ }
228
+ // A new key in an existing line-layout object is inserted here; everything else goes through
229
+ // jsonc-parser. Returns whether it handled the write.
230
+ function insertKeyLine(doc, located, path, value, position) {
231
+ const depth = located.missingDepth;
232
+ const container = depth > 0 ? located.nodes[depth - 1] : undefined;
233
+ if (container?.type !== "object")
234
+ return false;
235
+ const lines = lineLayout(doc.text, container);
236
+ if (lines === undefined)
237
+ return false;
238
+ const nested = path.slice(depth).reduceRight((inner, key) => ({ [key]: inner }), value);
239
+ const keys = container.children.map((property) => property.children[0].value);
240
+ const sibling = position?.before ?? position?.after;
241
+ const index = sibling === undefined ? keys.length : keys.indexOf(sibling) + (position?.after !== undefined ? 1 : 0);
242
+ insertLine(doc, container, lines, index, `${JSON.stringify(path[depth - 1])}: `, nested);
243
+ return true;
244
+ }
245
+ function assertPosition(op, path, position) {
246
+ if (position === undefined)
247
+ return;
248
+ if (position.before !== undefined && position.after !== undefined) {
249
+ fail(op, path, "give either `before` or `after`, not both.");
250
+ }
251
+ }
252
+ function assertSiblingExists(op, path, parent, position) {
253
+ const sibling = position?.before ?? position?.after;
254
+ if (sibling === undefined)
255
+ return;
256
+ const exists = parent?.type === "object" && parent.children.some((child) => child.children?.[0]?.value === sibling);
257
+ if (!exists)
258
+ fail(op, path, `the sibling key ${JSON.stringify(sibling)} does not exist.`);
259
+ }
260
+ // Shared upsert behind setValue, updateValue, copyValue, and merge's leaves.
261
+ function upsert(op, doc, path, value, position) {
262
+ const located = locate(op, doc.text, path);
263
+ if (located.node !== undefined) {
264
+ if (!deepEqual(getNodeValue(located.node), value))
265
+ write(op, doc, path, value);
266
+ return;
267
+ }
268
+ assertCreatable(op, path, located.missingDepth);
269
+ assertSiblingExists(op, path, located.parent, position);
270
+ write(op, doc, path, value, { position });
271
+ }
272
+ function arrayAt(op, doc, path) {
273
+ const { node } = locate(op, doc.text, path);
274
+ if (node !== undefined && node.type !== "array")
275
+ fail(op, path, `the value is ${node.type}, not an array.`);
276
+ return node;
277
+ }
278
+ function requireArray(op, doc, path) {
279
+ return arrayAt(op, doc, path) ?? fail(op, path, "no array exists at this path.");
280
+ }
281
+ /** Sets the value at `path`, creating missing parent objects (upsert). */
282
+ export function setValue(doc, path, value, options) {
283
+ assertPath("setValue", path);
284
+ assertJsonValue(value);
285
+ assertPosition("setValue", path, options);
286
+ if (options !== undefined && typeof path.at(-1) !== "string") {
287
+ fail("setValue", path, "`before`/`after` need a path that ends in an object key.");
288
+ }
289
+ upsert("setValue", doc, path, value, options);
290
+ }
291
+ /** Adds an absent object key; a deep-equal existing value is a no-op, a different one rejects. */
292
+ export function addKey(doc, path, value, options) {
293
+ assertKeyPath("addKey", path);
294
+ assertJsonValue(value);
295
+ assertPosition("addKey", path, options);
296
+ const { node, parent } = locate("addKey", doc.text, path);
297
+ if (node !== undefined) {
298
+ if (deepEqual(getNodeValue(node), value))
299
+ return;
300
+ fail("addKey", path, "the key already exists with a different value.");
301
+ }
302
+ if (parent === undefined)
303
+ fail("addKey", path, "the parent object does not exist.");
304
+ assertSiblingExists("addKey", path, parent, options);
305
+ write("addKey", doc, path, value, { position: options });
306
+ }
307
+ /** Removes an object key and its separator; an absent key is a no-op. */
308
+ export function removeKey(doc, path) {
309
+ assertKeyPath("removeKey", path);
310
+ if (locate("removeKey", doc.text, path).node !== undefined)
311
+ removeAt("removeKey", doc, path);
312
+ }
313
+ /** Renames an object key in place, keeping its value, position, and comments. */
314
+ export function renameKey(doc, path, newKey) {
315
+ assertKeyPath("renameKey", path);
316
+ if (typeof newKey !== "string")
317
+ fail("renameKey", path, "`newKey` must be a string.");
318
+ const { node, parent } = locate("renameKey", doc.text, path);
319
+ const target = [...path.slice(0, -1), newKey];
320
+ const renamed = parent === undefined ? undefined : locate("renameKey", doc.text, target).node;
321
+ if (node === undefined) {
322
+ if (renamed !== undefined)
323
+ return;
324
+ fail("renameKey", path, `neither the key nor ${formatPath(target)} exists.`);
325
+ }
326
+ if (path.at(-1) === newKey)
327
+ return;
328
+ if (renamed !== undefined)
329
+ fail("renameKey", path, `both the key and ${formatPath(target)} exist.`);
330
+ const keyNode = node.parent.children[0];
331
+ doc.text = doc.text.slice(0, keyNode.offset) + JSON.stringify(newKey) + doc.text.slice(keyNode.offset + keyNode.length);
332
+ }
333
+ /** Inserts `value` before the item at `index`; `index === length` appends. */
334
+ export function insertItem(doc, path, index, value) {
335
+ assertPath("insertItem", path);
336
+ assertJsonValue(value);
337
+ const length = requireArray("insertItem", doc, path).children.length;
338
+ assertIndex("insertItem", path, index, length);
339
+ insertAt("insertItem", doc, path, index, value);
340
+ }
341
+ /** Appends `value`, creating the array when absent; `{ unique: true }` skips a deep-equal duplicate. */
342
+ export function appendItem(doc, path, value, options) {
343
+ assertPath("appendItem", path);
344
+ assertJsonValue(value);
345
+ const array = arrayAt("appendItem", doc, path);
346
+ if (array === undefined) {
347
+ upsert("appendItem", doc, path, [value]);
348
+ return;
349
+ }
350
+ if (options?.unique === true && array.children.some((item) => deepEqual(getNodeValue(item), value)))
351
+ return;
352
+ insertAt("appendItem", doc, path, array.children.length, value);
353
+ }
354
+ /** Removes the item at `index` and its separator. */
355
+ export function removeItem(doc, path, index) {
356
+ assertPath("removeItem", path);
357
+ const length = requireArray("removeItem", doc, path).children.length;
358
+ assertIndex("removeItem", path, index, length - 1);
359
+ removeAt("removeItem", doc, [...path, index]);
360
+ }
361
+ /** Removes every item deep-equal to `value`; no match (or no array) is a no-op. */
362
+ export function removeValue(doc, path, value) {
363
+ assertPath("removeValue", path);
364
+ assertJsonValue(value);
365
+ const array = arrayAt("removeValue", doc, path);
366
+ if (array === undefined)
367
+ return;
368
+ const matches = array.children.flatMap((item, index) => (deepEqual(getNodeValue(item), value) ? [index] : []));
369
+ for (const index of matches.reverse())
370
+ removeAt("removeValue", doc, [...path, index]);
371
+ }
372
+ /** Replaces the item at `index` in place. */
373
+ export function replaceItem(doc, path, index, value) {
374
+ assertPath("replaceItem", path);
375
+ assertJsonValue(value);
376
+ const items = requireArray("replaceItem", doc, path).children;
377
+ assertIndex("replaceItem", path, index, items.length - 1);
378
+ if (!deepEqual(getNodeValue(items[index]), value))
379
+ write("replaceItem", doc, [...path, index], value);
380
+ }
381
+ /** Moves the item at `from` so it ends up at `to`; the other items keep their relative order. */
382
+ export function moveItem(doc, path, from, to) {
383
+ assertPath("moveItem", path);
384
+ const items = requireArray("moveItem", doc, path).children;
385
+ assertIndex("moveItem", path, from, items.length - 1);
386
+ assertIndex("moveItem", path, to, items.length - 1);
387
+ if (from === to)
388
+ return;
389
+ const value = getNodeValue(items[from]);
390
+ removeAt("moveItem", doc, [...path, from]);
391
+ insertAt("moveItem", doc, path, to, value);
392
+ }
393
+ function mergeInto(doc, path, value) {
394
+ for (const [key, incoming] of Object.entries(value)) {
395
+ const childPath = [...path, key];
396
+ const child = locate("merge", doc.text, childPath).node;
397
+ if (child?.type === "object" && isPlainObject(incoming)) {
398
+ mergeInto(doc, childPath, incoming);
399
+ }
400
+ else {
401
+ upsert("merge", doc, childPath, incoming);
402
+ }
403
+ }
404
+ }
405
+ /** Deep-merges a plain object into the object at `path`; arrays and scalars are replaced. */
406
+ export function merge(doc, path, value) {
407
+ assertPath("merge", path);
408
+ assertJsonValue(value);
409
+ if (!isPlainObject(value))
410
+ fail("merge", path, "the merged value must be a plain object.");
411
+ const { node, missingDepth } = locate("merge", doc.text, path);
412
+ if (node === undefined) {
413
+ assertCreatable("merge", path, missingDepth);
414
+ write("merge", doc, path, value);
415
+ return;
416
+ }
417
+ if (node.type !== "object")
418
+ fail("merge", path, `the target is ${node.type}, not an object.`);
419
+ mergeInto(doc, path, value);
420
+ }
421
+ /** Replaces the value at `path` with `fn(current)`; `current` is `undefined` when absent. */
422
+ export function updateValue(doc, path, fn) {
423
+ assertPath("updateValue", path);
424
+ if (typeof fn !== "function")
425
+ fail("updateValue", path, "`fn` must be a function.");
426
+ const { node, missingDepth } = locate("updateValue", doc.text, path);
427
+ if (node === undefined)
428
+ assertCreatable("updateValue", path, missingDepth);
429
+ const next = fn(node === undefined ? undefined : getNodeValue(node));
430
+ assertJsonValue(next);
431
+ upsert("updateValue", doc, path, next);
432
+ }
433
+ function isWithin(path, prefix) {
434
+ return path.length > prefix.length && prefix.every((segment, index) => path[index] === segment);
435
+ }
436
+ /** Moves the value at `from` to `to` (RFC 6902 `move`); a `number` last segment in `to` inserts. */
437
+ export function moveValue(doc, from, to) {
438
+ assertPath("moveValue", from);
439
+ assertPath("moveValue", to);
440
+ if (from.length === 0)
441
+ fail("moveValue", from, "the document root cannot be moved.");
442
+ if (isWithin(to, from))
443
+ fail("moveValue", from, `the destination ${formatPath(to)} lies inside the source.`);
444
+ const source = locate("moveValue", doc.text, from).node;
445
+ if (source === undefined) {
446
+ if (locate("moveValue", doc.text, to).node !== undefined)
447
+ return;
448
+ fail("moveValue", from, `neither the source nor ${formatPath(to)} exists.`);
449
+ }
450
+ if (deepEqual(from, to))
451
+ return;
452
+ const value = getNodeValue(source);
453
+ // Work on a scratch document so a rejected destination leaves the live text untouched.
454
+ const scratch = { text: doc.text };
455
+ removeAt("moveValue", scratch, from);
456
+ const last = to.at(-1);
457
+ if (typeof last === "number") {
458
+ const length = requireArray("moveValue", scratch, to.slice(0, -1)).children.length;
459
+ assertIndex("moveValue", to, last, length);
460
+ insertAt("moveValue", scratch, to.slice(0, -1), last, value);
461
+ }
462
+ else {
463
+ upsert("moveValue", scratch, to, value);
464
+ }
465
+ doc.text = scratch.text;
466
+ }
467
+ /** Copies the value at `from` to `to` with `setValue`'s rules (RFC 6902 `copy`). */
468
+ export function copyValue(doc, from, to) {
469
+ assertPath("copyValue", from);
470
+ assertPath("copyValue", to);
471
+ const source = locate("copyValue", doc.text, from).node ?? fail("copyValue", from, "the source does not exist.");
472
+ upsert("copyValue", doc, to, getNodeValue(source));
473
+ }
474
+ function compareCodePoints(a, b) {
475
+ const left = [...a];
476
+ const right = [...b];
477
+ for (let index = 0; index < Math.min(left.length, right.length); index++) {
478
+ const delta = left[index].codePointAt(0) - right[index].codePointAt(0);
479
+ if (delta !== 0)
480
+ return delta;
481
+ }
482
+ return left.length - right.length;
483
+ }
484
+ // Offset just past the separator comma in `text[start, end)`, which holds only whitespace,
485
+ // comments, and that comma.
486
+ function afterComma(text, start, end) {
487
+ for (let index = start; index < end; index++) {
488
+ if (text.startsWith("//", index))
489
+ index = text.indexOf("\n", index);
490
+ else if (text.startsWith("/*", index))
491
+ index = text.indexOf("*/", index) + 1;
492
+ else if (text[index] === ",")
493
+ return index + 1;
494
+ if (index < start)
495
+ break;
496
+ }
497
+ return start;
498
+ }
499
+ // Re-renders `node`, reordering object members; each member keeps the text that precedes it
500
+ // (its comments and indentation), and separators stay in place.
501
+ function sortedText(text, node, recursive) {
502
+ const slice = (from, to) => text.slice(from, to);
503
+ const render = (child) => (recursive ? sortedText(text, child, true) : slice(child.offset, child.offset + child.length));
504
+ const nodeEnd = end(node);
505
+ const children = node.children ?? [];
506
+ if (node.type === "array") {
507
+ let out = "";
508
+ let cursor = node.offset;
509
+ for (const child of children) {
510
+ out += slice(cursor, child.offset) + render(child);
511
+ cursor = child.offset + child.length;
512
+ }
513
+ return out + slice(cursor, nodeEnd);
514
+ }
515
+ if (node.type !== "object" || children.length === 0)
516
+ return slice(node.offset, nodeEnd);
517
+ const members = children.map((property, index) => {
518
+ const previous = children[index - 1];
519
+ const leadStart = previous === undefined ? node.offset + 1 : afterComma(text, previous.offset + previous.length, property.offset);
520
+ const [key, value] = property.children;
521
+ return {
522
+ key: key.value,
523
+ lead: slice(leadStart, property.offset),
524
+ body: slice(property.offset, value.offset) + render(value),
525
+ separator: previous === undefined ? "" : slice(previous.offset + previous.length, leadStart),
526
+ };
527
+ });
528
+ const sorted = [...members].sort((a, b) => compareCodePoints(a.key, b.key));
529
+ const last = children.at(-1);
530
+ const lines = lineLayout(text, node);
531
+ if (lines !== undefined) {
532
+ // Each member carries its trailing comment; commas are re-placed by position.
533
+ const trailingComma = lines.at(-1).comma !== -1;
534
+ const tails = children.map((property, index) => {
535
+ const { comma, tailEnd } = lines[index];
536
+ return comma === -1 ? slice(end(property), tailEnd) : slice(end(property), comma) + slice(comma + 1, tailEnd);
537
+ });
538
+ const order = sorted.map((member) => members.indexOf(member));
539
+ return (slice(node.offset, lines[0].leadStart) +
540
+ order
541
+ .map((from, position) => {
542
+ const lead = slice(lines[from].leadStart, children[from].offset);
543
+ const comma = position < children.length - 1 || trailingComma ? "," : "";
544
+ return lead + members[from].body + comma + tails[from] + slice(lines[position].tailEnd, lines[position].lineEnd);
545
+ })
546
+ .join("") +
547
+ slice(lines.at(-1).lineEnd, nodeEnd));
548
+ }
549
+ return ("{" +
550
+ sorted.map((member, index) => members[index].separator + member.lead + member.body).join("") +
551
+ slice(last.offset + last.length, nodeEnd));
552
+ }
553
+ /** Orders the object's members by key (code-point order); `{ recursive: true }` sorts nested objects too. */
554
+ export function sortKeys(doc, path, options) {
555
+ assertPath("sortKeys", path);
556
+ const { node } = locate("sortKeys", doc.text, path);
557
+ if (node?.type !== "object")
558
+ fail("sortKeys", path, `the value is ${node?.type ?? "absent"}, not an object.`);
559
+ const sorted = sortedText(doc.text, node, options?.recursive === true);
560
+ doc.text = doc.text.slice(0, node.offset) + sorted + doc.text.slice(node.offset + node.length);
561
+ }
@@ -0,0 +1,43 @@
1
+ import type { SourceFile } from "ts-morph";
2
+ import { type Handle } from "../../core/define-dialect.ts";
3
+ import { typescriptOps } from "../typescript/pack.ts";
4
+ export * as astLibrary from "ts-morph";
5
+ type ModuleOps = {
6
+ addProvider: (ast: SourceFile, name: string, from: string) => void;
7
+ addController: (ast: SourceFile, name: string, from: string) => void;
8
+ addModuleImport: (ast: SourceFile, name: string, from: string) => void;
9
+ addExport: (ast: SourceFile, name: string, from: string) => void;
10
+ };
11
+ type NestOps = typeof typescriptOps & ModuleOps;
12
+ /**
13
+ * Opens a `.ts` file of a NestJS project for editing. The handle carries every
14
+ * `@pbuilder/sdk/typescript` op plus the `@Module` ops below, chained on one handle and
15
+ * written once.
16
+ *
17
+ * `addProvider`, `addController`, `addModuleImport` and `addExport` each take
18
+ * `(name, from)`: they add `import { name } from "from"` with the same rules as `addImport`,
19
+ * then append `name` to the `providers`, `controllers`, `imports` or `exports` array of the
20
+ * file's only `@Module` class, creating the metadata object or the array when missing. They
21
+ * reject, leaving the file unchanged, when the file has no `@Module` class or more than one,
22
+ * or when the metadata or the array is not a literal. Use `.modify(fn)` for those files and
23
+ * for entries that are not a plain class name, such as `ConfigModule.forRoot()`.
24
+ *
25
+ * @example
26
+ * import * as nestjs from "@pbuilder/sdk/nestjs";
27
+ *
28
+ * // src/app.module.ts before:
29
+ * // @Module({ providers: [AppService] })
30
+ * // export class AppModule {}
31
+ * export const run = async () => {
32
+ * await nestjs
33
+ * .find("src/app.module.ts")
34
+ * .addModuleImport("UsersModule", "./users/users.module")
35
+ * .addProvider("UsersService", "./users/users.service");
36
+ * };
37
+ * // -> import { UsersModule } from "./users/users.module";
38
+ * // -> import { UsersService } from "./users/users.service";
39
+ * // ->
40
+ * // -> @Module({ providers: [AppService, UsersService], imports: [UsersModule] })
41
+ * // -> export class AppModule {}
42
+ */
43
+ export declare function find(path: string): Handle<"found", SourceFile, NestOps>;
@@ -0,0 +1,46 @@
1
+ import { defineDialect, defineOpPack, withOps } from "../../core/define-dialect.js";
2
+ import { parse, print } from "../typescript/ast.js";
3
+ import { typescriptOps } from "../typescript/pack.js";
4
+ import { addController, addExport, addModuleImport, addProvider } from "./ops.js";
5
+ export * as astLibrary from "ts-morph";
6
+ const moduleOps = defineOpPack({ addProvider, addController, addModuleImport, addExport });
7
+ const baseDialect = defineDialect({
8
+ extensions: [".ts"],
9
+ ast: { parse, print },
10
+ ops: {},
11
+ });
12
+ const nestjsDialect = withOps(baseDialect, typescriptOps, moduleOps);
13
+ /**
14
+ * Opens a `.ts` file of a NestJS project for editing. The handle carries every
15
+ * `@pbuilder/sdk/typescript` op plus the `@Module` ops below, chained on one handle and
16
+ * written once.
17
+ *
18
+ * `addProvider`, `addController`, `addModuleImport` and `addExport` each take
19
+ * `(name, from)`: they add `import { name } from "from"` with the same rules as `addImport`,
20
+ * then append `name` to the `providers`, `controllers`, `imports` or `exports` array of the
21
+ * file's only `@Module` class, creating the metadata object or the array when missing. They
22
+ * reject, leaving the file unchanged, when the file has no `@Module` class or more than one,
23
+ * or when the metadata or the array is not a literal. Use `.modify(fn)` for those files and
24
+ * for entries that are not a plain class name, such as `ConfigModule.forRoot()`.
25
+ *
26
+ * @example
27
+ * import * as nestjs from "@pbuilder/sdk/nestjs";
28
+ *
29
+ * // src/app.module.ts before:
30
+ * // @Module({ providers: [AppService] })
31
+ * // export class AppModule {}
32
+ * export const run = async () => {
33
+ * await nestjs
34
+ * .find("src/app.module.ts")
35
+ * .addModuleImport("UsersModule", "./users/users.module")
36
+ * .addProvider("UsersService", "./users/users.service");
37
+ * };
38
+ * // -> import { UsersModule } from "./users/users.module";
39
+ * // -> import { UsersService } from "./users/users.service";
40
+ * // ->
41
+ * // -> @Module({ providers: [AppService, UsersService], imports: [UsersModule] })
42
+ * // -> export class AppModule {}
43
+ */
44
+ export function find(path) {
45
+ return nestjsDialect.find(path);
46
+ }
@@ -0,0 +1,13 @@
1
+ import { type SourceFile } from "ts-morph";
2
+ /**
3
+ * Imports `name` from `from` and adds it to the `providers` array of the file's only
4
+ * `@Module` class, creating the metadata object or the array when missing. An entry already
5
+ * named `name` is left as it is.
6
+ */
7
+ export declare const addProvider: (ast: SourceFile, name: string, from: string) => void;
8
+ /** Same as `addProvider`, for the `controllers` array. */
9
+ export declare const addController: (ast: SourceFile, name: string, from: string) => void;
10
+ /** Same as `addProvider`, for the `imports` array (other Nest modules). */
11
+ export declare const addModuleImport: (ast: SourceFile, name: string, from: string) => void;
12
+ /** Same as `addProvider`, for the `exports` array. */
13
+ export declare const addExport: (ast: SourceFile, name: string, from: string) => void;