@pbuilder/sdk 0.10.1 → 0.12.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,158 @@
1
+ import { Node } from "ts-morph";
2
+ const BLANK_LINE = /\n[ \t]*\r?\n/;
3
+ // Case-insensitive with an ordinal tie-break, never `localeCompare`: the order must not
4
+ // depend on the host locale.
5
+ function compareText(a, b) {
6
+ const foldedA = a.toLowerCase();
7
+ const foldedB = b.toLowerCase();
8
+ if (foldedA !== foldedB)
9
+ return foldedA < foldedB ? -1 : 1;
10
+ return a < b ? -1 : a > b ? 1 : 0;
11
+ }
12
+ function isRelative(specifier) {
13
+ return specifier.startsWith(".");
14
+ }
15
+ // Package specifiers (including `node:` builtins and path aliases) sort ahead of relative ones.
16
+ function compareModules(a, b) {
17
+ return Number(isRelative(a)) - Number(isRelative(b)) || compareText(a, b);
18
+ }
19
+ function byModule(a, b) {
20
+ return compareModules(a.getModuleSpecifierValue(), b.getModuleSpecifierValue());
21
+ }
22
+ // How closely two specifiers are related: 0 across the package/relative divide, otherwise
23
+ // 1 plus the number of leading path segments they share.
24
+ function kinship(a, b) {
25
+ if (isRelative(a) !== isRelative(b))
26
+ return 0;
27
+ const left = a.split("/");
28
+ const right = b.split("/");
29
+ let shared = 0;
30
+ while (shared < Math.min(left.length, right.length) && left[shared] === right[shared])
31
+ shared++;
32
+ return 1 + shared;
33
+ }
34
+ /** Index at which `name` keeps `decl`'s named specifiers in order. */
35
+ export function sortedSpecifierIndex(decl, name) {
36
+ const specifiers = decl.getNamedImports();
37
+ const index = specifiers.findIndex((specifier) => compareText(specifier.getName(), name) > 0);
38
+ return index === -1 ? specifiers.length : index;
39
+ }
40
+ /**
41
+ * Where a new declaration of `from` goes: among the existing declarations most related to it
42
+ * (its folder siblings), before the first that sorts after it, or after the last. `index` is a
43
+ * `getStatementsWithComments()` index; inserting before a declaration also goes above the
44
+ * comments directly over it, so an `eslint-disable-next-line` keeps covering the import it was
45
+ * written for. `joinsComment` is true when that comment had no blank line above it, which
46
+ * `closeGapAfter` must restore. Undefined when the file has no import declarations.
47
+ */
48
+ export function sortedPlacement(ast, from) {
49
+ const declarations = ast.getImportDeclarations();
50
+ if (declarations.length === 0)
51
+ return undefined;
52
+ const closest = Math.max(...declarations.map((decl) => kinship(decl.getModuleSpecifierValue(), from)));
53
+ const siblings = declarations.filter((decl) => kinship(decl.getModuleSpecifierValue(), from) === closest);
54
+ const next = siblings.find((decl) => compareModules(decl.getModuleSpecifierValue(), from) > 0);
55
+ const statements = ast.getStatementsWithComments();
56
+ if (next === undefined)
57
+ return { index: statements.indexOf(siblings[siblings.length - 1]) + 1, joinsComment: false };
58
+ let index = statements.indexOf(next);
59
+ while (index > 0 && Node.isCommentStatement(statements[index - 1]) && !BLANK_LINE.test(gapBefore(statements, index))) {
60
+ index--;
61
+ }
62
+ const joinsComment = Node.isCommentStatement(statements[index]) && (index === 0 || !BLANK_LINE.test(gapBefore(statements, index)));
63
+ return { index, joinsComment };
64
+ }
65
+ // ts-morph always leaves a blank line between a declaration it inserts and a comment right
66
+ // below it; that blank line would split one group of imports in two.
67
+ export function closeGapAfter(decl) {
68
+ const end = decl.getEnd();
69
+ const blank = /^[ \t]*\r?\n([ \t]*\r?\n)/.exec(decl.getSourceFile().getFullText().slice(end));
70
+ if (blank !== null)
71
+ decl.getSourceFile().removeText(end + blank[0].length - blank[1].length, end + blank[0].length);
72
+ }
73
+ function gapBefore(statements, index) {
74
+ return statements[index].getSourceFile().getFullText().slice(statements[index - 1].getEnd(), statements[index].getStart());
75
+ }
76
+ // A comment on the same line, or directly above with no blank line, belongs to the declaration.
77
+ function hasAttachedComment(decl) {
78
+ const text = decl.getSourceFile().getFullText();
79
+ return (decl.getTrailingCommentRanges().length > 0 ||
80
+ decl.getLeadingCommentRanges().some((range) => !BLANK_LINE.test(text.slice(range.getEnd(), decl.getStart()))));
81
+ }
82
+ // Runs of declarations that may be reordered among themselves: consecutive, with no blank
83
+ // line between them. A side-effect import (its evaluation order is behaviour) and a
84
+ // declaration with an attached comment never move, and every other statement or comment ends
85
+ // the run, so nothing crosses them.
86
+ function reorderableRuns(ast) {
87
+ const runs = [];
88
+ const statements = ast.getStatementsWithComments();
89
+ statements.forEach((statement, index) => {
90
+ if (!Node.isImportDeclaration(statement))
91
+ return;
92
+ if (statement.getImportClause() === undefined || hasAttachedComment(statement))
93
+ return;
94
+ const run = runs[runs.length - 1];
95
+ const continuesRun = run !== undefined && statements[index - 1] === run[run.length - 1] && !BLANK_LINE.test(gapBefore(statements, index));
96
+ if (continuesRun)
97
+ run.push(statement);
98
+ else
99
+ runs.push([statement]);
100
+ });
101
+ return runs;
102
+ }
103
+ // `decl`'s text with its named specifiers in order, each swapped into an existing specifier's
104
+ // slot so the braces keep their layout. Braces holding a comment are left as they are: the
105
+ // comment would end up beside a different name.
106
+ function withSortedSpecifiers(decl) {
107
+ const text = decl.getText();
108
+ const bindings = decl.getImportClause()?.getNamedBindings();
109
+ if (bindings === undefined || !Node.isNamedImports(bindings) || /\/[/*]/.test(bindings.getText()))
110
+ return text;
111
+ const specifiers = bindings.getElements();
112
+ const sorted = [...specifiers].sort((a, b) => compareText(a.getName(), b.getName()));
113
+ const offset = decl.getStart();
114
+ let result = text;
115
+ for (let i = specifiers.length - 1; i >= 0; i--) {
116
+ const slot = specifiers[i];
117
+ result = result.slice(0, slot.getStart() - offset) + sorted[i].getText() + result.slice(slot.getEnd() - offset);
118
+ }
119
+ return result;
120
+ }
121
+ /**
122
+ * Sorts the file's import declarations by module specifier (packages first, then relative
123
+ * paths, case-insensitively) and the named specifiers inside each declaration's braces.
124
+ *
125
+ * It only reorders; it never combines, removes, or reformats a declaration. Declarations move
126
+ * only within a run of consecutive imports: a blank line, a comment, a side-effect import
127
+ * (`import "./polyfills";`, whose position is behaviour), or a declaration with a comment
128
+ * attached to it ends the run, and nothing moves across it. Calling it on a sorted file
129
+ * changes nothing.
130
+ *
131
+ * @example
132
+ * // import { useState, type FC } from "react";
133
+ * // import { b } from "./b";
134
+ * // import { a } from "./a";
135
+ * // import { Users, BookOpen } from "lucide-react";
136
+ * ts.find(path).sortImports();
137
+ * // import { BookOpen, Users } from "lucide-react";
138
+ * // import { type FC, useState } from "react";
139
+ * // import { a } from "./a";
140
+ * // import { b } from "./b";
141
+ */
142
+ export function sortImports(ast) {
143
+ const placement = new Map();
144
+ for (const run of reorderableRuns(ast)) {
145
+ const sorted = [...run].sort(byModule);
146
+ run.forEach((decl, i) => placement.set(decl, sorted[i]));
147
+ }
148
+ const edits = ast.getImportDeclarations().map((decl) => ({
149
+ start: decl.getStart(),
150
+ end: decl.getEnd(),
151
+ text: withSortedSpecifiers(placement.get(decl) ?? decl),
152
+ }));
153
+ const original = ast.getFullText();
154
+ // Applied last to first so every earlier edit's offsets stay valid.
155
+ const result = edits.reduceRight((text, edit) => text.slice(0, edit.start) + edit.text + text.slice(edit.end), original);
156
+ if (result !== original)
157
+ ast.replaceWithText(result);
158
+ }
@@ -4,7 +4,9 @@ import type { ArrayElement, ArrayLocator } from "./array-element.ts";
4
4
  import type { ClassPropertyOptions } from "./class-property.ts";
5
5
  export * as astLibrary from "ts-morph";
6
6
  type TypeScriptOps = {
7
- addImport: (ast: SourceFile, name: string, from: string) => void;
7
+ addImport: (ast: SourceFile, name: string, from: string, options?: {
8
+ position?: "sorted";
9
+ }) => void;
8
10
  addDefaultImport: (ast: SourceFile, name: string, from: string) => void;
9
11
  addNamespaceImport: (ast: SourceFile, name: string, from: string) => void;
10
12
  addTypeImport: (ast: SourceFile, name: string, from: string) => void;
@@ -30,6 +32,7 @@ type TypeScriptOps = {
30
32
  }) => void;
31
33
  addArrayElement: (ast: SourceFile, locator: ArrayLocator, element: ArrayElement) => void;
32
34
  addClassProperty: (ast: SourceFile, className: string, name: string, initializer: string, options?: ClassPropertyOptions) => void;
35
+ sortImports: (ast: SourceFile) => void;
33
36
  };
34
37
  /**
35
38
  * Opens a TypeScript file for dialect-aware editing — the dialect's entry verb into a Session
@@ -47,12 +47,29 @@ import { type SourceFile } from "ts-morph";
47
47
  * Idempotent: calling this twice with the same `name`+`from` produces a single import line,
48
48
  * never a duplicate (REQ-TSD-03.10).
49
49
  *
50
+ * `{ position: "sorted" }` changes only where Steps 3 and 4 put the new code: the merged name
51
+ * goes into its alphabetical place inside the braces (case-insensitive), and a fresh
52
+ * declaration goes next to its folder siblings (the existing imports sharing the most leading
53
+ * path segments with `from`, packages and relative paths kept apart), before the first of them
54
+ * that sorts after it. Existing imports never move; `sortImports` reorders a whole file.
55
+ *
56
+ * @example
57
+ * // import { BookOpen, Users } from "lucide-react";
58
+ * // import { authorHandlers } from "./domains/authors.mock";
59
+ * ts.find(path).addImport("LayoutDashboard", "lucide-react", { position: "sorted" });
60
+ * ts.find(path).addImport("bookHandlers", "./domains/books.mock", { position: "sorted" });
61
+ * // import { BookOpen, LayoutDashboard, Users } from "lucide-react";
62
+ * // import { authorHandlers } from "./domains/authors.mock";
63
+ * // import { bookHandlers } from "./domains/books.mock";
64
+ *
50
65
  * Trust boundary (REQ-TSD-13.5): every op in this dialect validates its `name` the same way
51
66
  * (and `addVariable` its `kind`), but `addFunction`'s `source`, `addVariable`'s `initializer`
52
67
  * and `addClass`'s `source` are code bodies, not identifiers — they remain RAW-SPLICED,
53
68
  * author-trusted input that no op validates or escapes.
54
69
  */
55
- export declare function addImport(ast: SourceFile, name: string, from: string): void;
70
+ export declare function addImport(ast: SourceFile, name: string, from: string, options?: {
71
+ position?: "sorted";
72
+ }): void;
56
73
  /**
57
74
  * Adds `import name from "from";` (V2 REQ-TSD-13). `name` is validated first, as in
58
75
  * `addImport`. A no-op when `from` already has the default import `name`. Rejects when `from`
@@ -33,6 +33,7 @@ import { elementNameEcho } from "../../core/reject-tail.js";
33
33
  // A misnomer surviving from its JSX-only origin (`jsx-name-validator.ts`) — this dialect is
34
34
  // its first non-JSX consumer, sharpening ARCH-2's now-realised "one consumer" debt (ADR-02).
35
35
  import { assertValidImportBinding } from "../../core/jsx-name-validator.js";
36
+ import { closeGapAfter, sortedPlacement, sortedSpecifierIndex } from "./import-order.js";
36
37
  // Collects every local name a single declaration binds, across all three clause shapes at
37
38
  // once (a declaration can carry a default AND a named clause simultaneously, e.g.
38
39
  // `import Def, { B } from "m"`). Set-key-safety clause: names are compared via
@@ -193,16 +194,36 @@ function directiveInsertIndex(ast, directiveCount) {
193
194
  * Idempotent: calling this twice with the same `name`+`from` produces a single import line,
194
195
  * never a duplicate (REQ-TSD-03.10).
195
196
  *
197
+ * `{ position: "sorted" }` changes only where Steps 3 and 4 put the new code: the merged name
198
+ * goes into its alphabetical place inside the braces (case-insensitive), and a fresh
199
+ * declaration goes next to its folder siblings (the existing imports sharing the most leading
200
+ * path segments with `from`, packages and relative paths kept apart), before the first of them
201
+ * that sorts after it. Existing imports never move; `sortImports` reorders a whole file.
202
+ *
203
+ * @example
204
+ * // import { BookOpen, Users } from "lucide-react";
205
+ * // import { authorHandlers } from "./domains/authors.mock";
206
+ * ts.find(path).addImport("LayoutDashboard", "lucide-react", { position: "sorted" });
207
+ * ts.find(path).addImport("bookHandlers", "./domains/books.mock", { position: "sorted" });
208
+ * // import { BookOpen, LayoutDashboard, Users } from "lucide-react";
209
+ * // import { authorHandlers } from "./domains/authors.mock";
210
+ * // import { bookHandlers } from "./domains/books.mock";
211
+ *
196
212
  * Trust boundary (REQ-TSD-13.5): every op in this dialect validates its `name` the same way
197
213
  * (and `addVariable` its `kind`), but `addFunction`'s `source`, `addVariable`'s `initializer`
198
214
  * and `addClass`'s `source` are code bodies, not identifiers — they remain RAW-SPLICED,
199
215
  * author-trusted input that no op validates or escapes.
200
216
  */
201
- export function addImport(ast, name, from) {
217
+ export function addImport(ast, name, from, options) {
202
218
  // REQ-TSD-13 validation gate: a deliberately PATH-LESS reject (contrast Step 2's path-ful
203
219
  // `dialectError` below) — runs first, so a `name` that is BOTH invalid AND claimed rejects
204
220
  // via validation, never collision (REQ-TSD-13.6).
205
221
  assertValidImportBinding(name);
222
+ const sorted = options?.position === "sorted";
223
+ if (options?.position !== undefined && !sorted) {
224
+ throw dialectError(`addImport("${name}") on "${handlePathFor(ast)}" — \`position\` must be "sorted" or omitted. ` +
225
+ "Fix the option, or edit the file with .modify().");
226
+ }
206
227
  // Single pass: one `getImportDeclarations()` call, one `boundNamesIn` per declaration —
207
228
  // Step 1 and Step 2 below both read from `declarationBoundNames` instead of each re-walking
208
229
  // the AST. Step 1 still fully evaluates (and early-returns) before Step 2 ever runs
@@ -223,10 +244,16 @@ export function addImport(ast, name, from) {
223
244
  throw claimedBindingError(ast, "addImport", name);
224
245
  const mergeTarget = declarationsForModule.find(isNonTypeOnlyNamedImportClause);
225
246
  if (mergeTarget !== undefined) {
226
- mergeTarget.addNamedImport(name);
247
+ if (sorted)
248
+ mergeTarget.insertNamedImport(sortedSpecifierIndex(mergeTarget, name), name);
249
+ else
250
+ mergeTarget.addNamedImport(name);
227
251
  return;
228
252
  }
229
- insertImport(ast, { moduleSpecifier: from, namedImports: [name] });
253
+ const placement = sorted ? sortedPlacement(ast, from) : undefined;
254
+ const inserted = insertImport(ast, { moduleSpecifier: from, namedImports: [name] }, placement?.index);
255
+ if (placement?.joinsComment)
256
+ closeGapAfter(inserted);
230
257
  }
231
258
  // True when `name` is already bound anywhere in the file: any import binding (default,
232
259
  // namespace, or named, type-only included) or a top-level value-namespace declaration.
@@ -244,14 +271,17 @@ function claimedBindingError(ast, opName, name) {
244
271
  }
245
272
  // A fresh import declaration goes after a leading directive prologue, never above it
246
273
  // (REQ-TSD-01.21).
247
- function insertImport(ast, structure) {
274
+ // `index`, when given, is a `getStatementsWithComments()` index that already sits after any
275
+ // directive prologue (it comes from an existing import's position).
276
+ function insertImport(ast, structure, index) {
248
277
  const dropSemicolon = omitsSemicolons(ast);
249
278
  const directiveCount = leadingDirectiveCount(ast);
250
- const inserted = directiveCount === 0
251
- ? ast.addImportDeclaration(structure)
252
- : ast.insertImportDeclaration(directiveInsertIndex(ast, directiveCount), structure);
253
- if (dropSemicolon)
254
- inserted.replaceWithText(inserted.getText().slice(0, -1));
279
+ const inserted = index !== undefined
280
+ ? ast.insertImportDeclaration(index, structure)
281
+ : directiveCount === 0
282
+ ? ast.addImportDeclaration(structure)
283
+ : ast.insertImportDeclaration(directiveInsertIndex(ast, directiveCount), structure);
284
+ return dropSemicolon ? inserted.replaceWithText(inserted.getText().slice(0, -1)) : inserted;
255
285
  }
256
286
  // A fresh import keeps the file's statement-terminating semicolon style: ts-morph always
257
287
  // prints one, so it is dropped only when the file's terminable top-level statements mostly
@@ -1,5 +1,6 @@
1
1
  import { addImport, addDefaultImport, addNamespaceImport, addTypeImport, addSideEffectImport, addReExport, addExportAll, addFunction, addVariable, addClass, removeImport, removeExport, removeExportAll } from "./ops.ts";
2
2
  import { addArrayElement } from "./array-element.ts";
3
+ import { sortImports } from "./import-order.ts";
3
4
  import { addClassProperty } from "./class-property.ts";
4
5
  export declare const typescriptOps: {
5
6
  addImport: typeof addImport;
@@ -17,4 +18,5 @@ export declare const typescriptOps: {
17
18
  removeExportAll: typeof removeExportAll;
18
19
  addArrayElement: typeof addArrayElement;
19
20
  addClassProperty: typeof addClassProperty;
21
+ sortImports: typeof sortImports;
20
22
  };
@@ -2,6 +2,7 @@
2
2
  // (src/dialects/nestjs) composes the same ops without importing the `find` entry point.
3
3
  import { addImport, addDefaultImport, addNamespaceImport, addTypeImport, addSideEffectImport, addReExport, addExportAll, addFunction, addVariable, addClass, removeImport, removeExport, removeExportAll, } from "./ops.js";
4
4
  import { addArrayElement } from "./array-element.js";
5
+ import { sortImports } from "./import-order.js";
5
6
  import { addClassProperty } from "./class-property.js";
6
7
  export const typescriptOps = {
7
8
  addImport,
@@ -19,4 +20,5 @@ export const typescriptOps = {
19
20
  removeExportAll,
20
21
  addArrayElement,
21
22
  addClassProperty,
23
+ sortImports,
22
24
  };
@@ -2,7 +2,7 @@
2
2
  "manifestVersion": 1,
3
3
  "algorithm": "sha256",
4
4
  "entry": "dist/bin/pbuilder-runner.js",
5
- "packageVersion": "0.10.1",
5
+ "packageVersion": "0.12.0",
6
6
  "files": [
7
7
  {
8
8
  "path": "dist/bin/pbuilder-runner.js",
@@ -98,7 +98,7 @@
98
98
  },
99
99
  {
100
100
  "path": "package.json",
101
- "sha256": "a1394881932ffe36d70d2e8e942ae21056a7bd69c5a6a868b825b181d966deda"
101
+ "sha256": "dd84ad976cc9ec3ae2fba6d4adc7c2d5a7ce3eceeac47212a62727e7a2e96a9c"
102
102
  }
103
103
  ]
104
104
  }
@@ -8,7 +8,8 @@
8
8
  import { posix } from "node:path";
9
9
  import { invalidInput } from "../core/authoring-error.js";
10
10
  const TEMPLATE_SUFFIX = ".template";
11
- const TOKEN_PATTERN = /__([A-Za-z_][A-Za-z0-9_]*(?:@[A-Za-z_][A-Za-z0-9_]*)*)__/g;
11
+ const TOKEN_MARKER = "__";
12
+ const TOKEN_INNER = /^[A-Za-z_][A-Za-z0-9_]*(?:@[A-Za-z_][A-Za-z0-9_]*)*$/;
12
13
  /**
13
14
  * Translates on-disk filename tokens to the wire `pathTemplate` syntax the ENGINE
14
15
  * substitutes (obs #915 ruling 4) — the SDK never renders these itself, only rewrites the
@@ -19,10 +20,27 @@ const TOKEN_PATTERN = /__([A-Za-z_][A-Za-z0-9_]*(?:@[A-Za-z_][A-Za-z0-9_]*)*)__/
19
20
  * path-render at ingest (`path-render-failed`, exit 2).
20
21
  */
21
22
  export function translateTokens(path) {
22
- return path.replace(TOKEN_PATTERN, (_match, inner) => {
23
+ // A scan pairing each marker with the NEXT one, never a single unanchored regex: an
24
+ // identifier may contain `_`, so a regex whose closing `__` overlaps it backtracks from
25
+ // every start and goes quadratic on long runs of near-tokens (CodeQL js/polynomial-redos).
26
+ let translated = "";
27
+ let cursor = 0;
28
+ for (let open = path.indexOf(TOKEN_MARKER); open !== -1; open = path.indexOf(TOKEN_MARKER, cursor)) {
29
+ const close = path.indexOf(TOKEN_MARKER, open + TOKEN_MARKER.length);
30
+ if (close === -1)
31
+ break;
32
+ const inner = path.slice(open + TOKEN_MARKER.length, close);
33
+ if (!TOKEN_INNER.test(inner)) {
34
+ translated += path.slice(cursor, open + 1);
35
+ cursor = open + 1;
36
+ continue;
37
+ }
23
38
  const [field, ...pipes] = inner.split("@");
24
- return pipes.length > 0 ? `{= .${field} | ${pipes.join(" | ")} =}` : `{= .${field} =}`;
25
- });
39
+ translated += path.slice(cursor, open);
40
+ translated += pipes.length > 0 ? `{= .${field} | ${pipes.join(" | ")} =}` : `{= .${field} =}`;
41
+ cursor = close + TOKEN_MARKER.length;
42
+ }
43
+ return translated + path.slice(cursor);
26
44
  }
27
45
  /** REQ-FSC-05 step (3): strips a `.template` suffix from the (post-translation) path. */
28
46
  export function stripTemplateSuffix(path) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pbuilder/sdk",
3
- "version": "0.10.1",
3
+ "version": "0.12.0",
4
4
  "description": "The public TypeScript/Bun authoring layer for Project Builder schematics. Authors file mutations (create, replaceContent, remove, rename, move, copy, copyIn), lowers them to IR, and talks to the Project Builder engine over framed stdio (see docs/engine-sdk-wire-spec.md).",
5
5
  "license": "MIT",
6
6
  "type": "module",