@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.
package/README.md CHANGED
@@ -580,7 +580,7 @@ await ts.find("src/index.ts")
580
580
 
581
581
  | Op | What it does |
582
582
  |---|---|
583
- | `addImport(name, from)` | Adds `import { name } from "from"`, merging into an existing clause from the same module. Idempotent — calling it twice never duplicates the import. |
583
+ | `addImport(name, from, opts?)` | Adds `import { name } from "from"`, merging into an existing clause from the same module. Idempotent — calling it twice never duplicates the import. With `{ position: "sorted" }` the name goes into its alphabetical place inside the braces and a new declaration goes next to its folder siblings; existing imports never move. |
584
584
  | `addDefaultImport(name, from)` | Adds `import name from "from"`, merging into a declaration of that module with no default yet. Rejects a second default under another name. |
585
585
  | `addNamespaceImport(name, from)` | Adds `import * as name from "from"`, merging into a default-only declaration; beside named imports it opens its own. |
586
586
  | `addTypeImport(name, from)` | Adds `import type { name } from "from"` as its own statement. A no-op when the module already imports `name`, by value or as a type. |
@@ -590,6 +590,7 @@ await ts.find("src/index.ts")
590
590
  | `removeImport(name, from)` | Removes the named binding; deletes the whole statement when it was the last one. Idempotent on an absent binding. |
591
591
  | `removeExport(name, from)` | Removes a named re-export; deletes the statement when it was the last one. Idempotent on an absent one. |
592
592
  | `removeExportAll(from, { as? })` | Removes `export * from "from"` (or the `as` form). Idempotent on an absent one. |
593
+ | `sortImports()` | Sorts import declarations by module (packages first, then relative paths) and the names inside each one's braces. Only reorders, never combines or removes; nothing moves across a blank line, a comment, or a side-effect import. A no-op on a sorted file. |
593
594
  | `addArrayElement(locator, element)` | Appends to the array literal `locator` points at (a variable, a call argument, or a decorator argument, then a `path` of keys and `{ key: "value" }` matches), keeping its layout. Creates missing keys; a no-op when the element is already listed. `element` is an identifier, or `{ expression }` for code. |
594
595
  | `addClassProperty(className, name, initializer, opts?)` | Adds `{scope }{readonly }name = initializer;` to the only class named `className`, after its last property. A no-op when the same property exists; any other member named `name` rejects. |
595
596
  | `addFunction(name, source, opts?)` | Appends a top-level function. `source` **includes** the braces (`"(): void {}"`). |
@@ -605,9 +606,11 @@ untrusted input is the author's responsibility to sanitize.
605
606
 
606
607
  ### `@pbuilder/sdk/react`
607
608
 
608
- Mutates `.tsx` files — `find()` requires the explicit `.tsx` extension (extensionless and
609
- `.jsx` paths are rejected, never normalized). The v1 op-pack — a dialect's bundle of named
610
- ops — is deliberately minimal: two named ops, with `.modify(fn)` as the escape hatch
609
+ Mutates `.tsx` and `.jsx` files — `find()` requires one of those extensions explicitly
610
+ (extensionless paths are rejected, never normalized). On `.jsx`, the ops that write TypeScript
611
+ syntax (`addTypeImport`, `addComponentProp`, `addClassProperty`'s `scope`/`readonly`) reject,
612
+ leaving the file unchanged. The handle carries every
613
+ `@pbuilder/sdk/typescript` op plus the JSX ops below, with `.modify(fn)` as the escape hatch
611
614
  for everything else:
612
615
 
613
616
  ```ts
@@ -624,8 +627,13 @@ await react
624
627
 
625
628
  | Op | What it does |
626
629
  |---|---|
627
- | `addImport(name, from)` | Same contract as the TypeScript dialect's — idempotent, named-binding-only (no default/namespace imports in v1). |
628
- | `setJsxProp(element, prop, value?)` | Sets a prop on **the one** element with that tag name — zero or multiple matches reject loudly. `value` takes three forms: `'"hi"'` (string), `'{count}'` (expression), or omitted (boolean shorthand). |
630
+ | `setJsxProp(target, prop, value?)` | Sets a prop on **the one** element `target` names: a tag (`"Button"`) or a tag plus props that narrow it (`{ tag: "Route", props: { path: '"/users"' } }`) — zero or multiple matches reject loudly. `value` takes three forms: `'"hi"'` (string), `'{count}'` (expression), or omitted (boolean shorthand). |
631
+ | `removeJsxProp(target, prop)` | Removes a prop from **the one** element `target` names. An absent prop is a no-op; a `{...spread}` is never touched. |
632
+ | `addJsxChild(target, jsx)` | Appends `jsx` (one JSX element or fragment, emitted verbatim) as the last child of **the one** element `target` names, at the siblings' indentation; a self-closing target becomes an open/close pair. A child with the same text already there is a no-op. |
633
+ | `wrapJsxElement(target, wrapper)` | Wraps **the one** element `target` names in `wrapper`, a self-closing JSX element whose props are kept (`'<QueryProvider client={qc} />'`). A target already directly inside that tag is a no-op. |
634
+ | `addHookCall(component, statement)` | Inserts one statement (emitted verbatim) into the body of the component named `component` — a top-level `function` or a `const` arrow/function expression — after its leading hook calls. An identical statement already there is a no-op. |
635
+ | `addComponentProp(component, name, type, options?)` | Adds `name: type` (`name?:` with `{ optional: true }`) to the component's props type — inline, or an `interface`/`type` literal in the same file — and to its destructured parameter. Same name and type is a no-op; a different type rejects. |
636
+ | `renameJsxElement(target, tag)` | Renames **the one** element `target` names, opening and closing tag together. Imports are not touched. |
629
637
 
630
638
  `setJsxProp`'s `value` is emitted verbatim into executable code — same trust boundary as
631
639
  the TypeScript `source` strings. One React-specific subtlety: an inserted prop lands after
@@ -96,3 +96,47 @@ export declare const RESERVED_HANDLE_NAMES: readonly ["then", "read", "raw", "mo
96
96
  * const tsDialect = withOps(baseTsDialect, addImportPack);
97
97
  */
98
98
  export declare function withOps<Ast, B extends OpPack<Ast>, P extends OpPack<Ast>[]>(base: Dialect<Ast, B>, ...packs: P): Dialect<Ast, B & UnionToIntersection<P[number]>>;
99
+ /**
100
+ * Derives a dialect whose named ops reject at call time, leaving the file unchanged, with a
101
+ * message naming the op, the dialect's extensions and `reason`. The ops stay on the handle and
102
+ * in its type, so one handle shape can serve every extension of a routed dialect
103
+ * (`byExtension`). Throws at composition on an op name the dialect does not have.
104
+ *
105
+ * @example
106
+ * const jsx = withoutOps(defineDialect({ extensions: [".jsx"], ast: jsxAst, ops: tsx.ops }), ["addTypeImport"], ".jsx files have no type syntax");
107
+ */
108
+ export declare function withoutOps<Ast, Ops extends OpPack<Ast>>(dialect: Dialect<Ast, Ops>, names: readonly (keyof Ops & string)[], reason: string): Dialect<Ast, Ops>;
109
+ /**
110
+ * Derives a dialect whose named ops run `overrides` instead, with the same signatures. Throws at
111
+ * composition on an op name the dialect does not have; adding new ops is `withOps`'s job.
112
+ *
113
+ * @example
114
+ * const jsx = overrideOps(tsx, { addClassProperty: jsxClassProperty });
115
+ */
116
+ export declare function overrideOps<Ast, Ops extends OpPack<Ast>>(dialect: Dialect<Ast, Ops>, overrides: Partial<Ops>): Dialect<Ast, Ops>;
117
+ type DialectsByExtension = {
118
+ readonly [extension: string]: Dialect;
119
+ };
120
+ type HandleOf<D> = D extends Dialect<infer A, infer O> ? Handle<"found", A, O> : never;
121
+ type MatchingKey<M, P extends string> = {
122
+ [K in keyof M & string]: P extends `${string}${K}` ? K : never;
123
+ }[keyof M & string];
124
+ type LongestKey<Ks extends string> = {
125
+ [K in Ks]: [Extract<Exclude<Ks, K>, `${string}${K}`>] extends [never] ? K : never;
126
+ }[Ks];
127
+ type RoutedHandle<M extends DialectsByExtension, P extends string> = string extends P ? HandleOf<M[keyof M]> : HandleOf<M[LongestKey<MatchingKey<M, P>>]>;
128
+ export interface ExtensionRouter<M extends DialectsByExtension> {
129
+ readonly extensions: readonly (keyof M & string)[];
130
+ find<P extends string>(path: P): RoutedHandle<M, P>;
131
+ }
132
+ /**
133
+ * Routes `find` by file extension to one dialect per extension, each with its own AST and ops —
134
+ * a `.ts` dialect and an `.html` dialect may parse to different AST types. The longest matching
135
+ * extension wins (`.component.html` over `.html`); a path matching none rejects synchronously,
136
+ * naming every routed extension. Throws at composition on a key its dialect does not declare.
137
+ *
138
+ * @example
139
+ * export const react = byExtension({ ".tsx": tsxDialect, ".jsx": jsxDialect });
140
+ * react.find("src/App.jsx").setJsxProp("div", "hidden");
141
+ */
142
+ export declare function byExtension<M extends DialectsByExtension>(dialects: M): ExtensionRouter<M>;
@@ -127,3 +127,70 @@ export function withOps(base, ...packs) {
127
127
  const merged = Object.assign({}, base.ops, ...packs);
128
128
  return defineDialect({ extensions: [...base.extensions], ast: base.ast, ops: merged });
129
129
  }
130
+ function assertKnownOps(ops, names, composer) {
131
+ for (const name of names) {
132
+ if (!Object.hasOwn(ops, name))
133
+ throw new Error(`${composer} failed: the dialect has no op "${name}".`);
134
+ }
135
+ }
136
+ /**
137
+ * Derives a dialect whose named ops reject at call time, leaving the file unchanged, with a
138
+ * message naming the op, the dialect's extensions and `reason`. The ops stay on the handle and
139
+ * in its type, so one handle shape can serve every extension of a routed dialect
140
+ * (`byExtension`). Throws at composition on an op name the dialect does not have.
141
+ *
142
+ * @example
143
+ * const jsx = withoutOps(defineDialect({ extensions: [".jsx"], ast: jsxAst, ops: tsx.ops }), ["addTypeImport"], ".jsx files have no type syntax");
144
+ */
145
+ export function withoutOps(dialect, names, reason) {
146
+ assertKnownOps(dialect.ops, names, "withoutOps");
147
+ const files = dialect.extensions.join(", ");
148
+ const blocked = Object.fromEntries(names.map((name) => [
149
+ name,
150
+ () => {
151
+ throw dialectError(`${name} is not available for ${files} files — ${reason}. Use .modify() to make this edit directly.`);
152
+ },
153
+ ]));
154
+ return defineDialect({ extensions: [...dialect.extensions], ast: dialect.ast, ops: { ...dialect.ops, ...blocked } });
155
+ }
156
+ /**
157
+ * Derives a dialect whose named ops run `overrides` instead, with the same signatures. Throws at
158
+ * composition on an op name the dialect does not have; adding new ops is `withOps`'s job.
159
+ *
160
+ * @example
161
+ * const jsx = overrideOps(tsx, { addClassProperty: jsxClassProperty });
162
+ */
163
+ export function overrideOps(dialect, overrides) {
164
+ assertKnownOps(dialect.ops, Object.keys(overrides), "overrideOps");
165
+ return defineDialect({ extensions: [...dialect.extensions], ast: dialect.ast, ops: { ...dialect.ops, ...overrides } });
166
+ }
167
+ /**
168
+ * Routes `find` by file extension to one dialect per extension, each with its own AST and ops —
169
+ * a `.ts` dialect and an `.html` dialect may parse to different AST types. The longest matching
170
+ * extension wins (`.component.html` over `.html`); a path matching none rejects synchronously,
171
+ * naming every routed extension. Throws at composition on a key its dialect does not declare.
172
+ *
173
+ * @example
174
+ * export const react = byExtension({ ".tsx": tsxDialect, ".jsx": jsxDialect });
175
+ * react.find("src/App.jsx").setJsxProp("div", "hidden");
176
+ */
177
+ export function byExtension(dialects) {
178
+ const extensions = Object.keys(dialects);
179
+ for (const extension of extensions) {
180
+ const declared = dialects[extension].extensions;
181
+ if (!declared.includes(extension)) {
182
+ throw new Error(`dialect routing failed: "${extension}" is not an extension its dialect declares (${declared.join(", ")}).`);
183
+ }
184
+ }
185
+ const longestFirst = [...extensions].sort((a, b) => b.length - a.length);
186
+ return {
187
+ extensions,
188
+ find(path) {
189
+ const extension = longestFirst.find((candidate) => hasDeclaredExtension(path, [candidate]));
190
+ if (extension === undefined) {
191
+ throw dialectError(`find(${JSON.stringify(path)}) — the file's extension is not one this dialect declares (${extensions.join(", ")}).`);
192
+ }
193
+ return dialects[extension].find(path);
194
+ },
195
+ };
196
+ }
@@ -4,7 +4,7 @@ export declare const IMPORT_RESERVED_WORDS: ReadonlySet<string>;
4
4
  /** `assertValidAttributeName`'s propName grammar — hyphens + one optional `:namespace` segment. */
5
5
  export declare function assertValidAttributeName(propName: string): void;
6
6
  /** `assertValidElementName`'s lookup-only JSX-name grammar — identifier/hyphenated, dot-joined. */
7
- export declare function assertValidElementName(elementName: string): void;
7
+ export declare function assertValidElementName(elementName: string, argName?: string): void;
8
8
  /**
9
9
  * `assertValidImportBinding`'s plain-JS-identifier grammar. The regex alone admits any
10
10
  * `IdentifierName` (including reserved words) — `import { name }` requires a `BindingIdentifier`,
@@ -77,9 +77,9 @@ export function assertValidAttributeName(propName) {
77
77
  assertNotDenylisted("propName", propName);
78
78
  }
79
79
  /** `assertValidElementName`'s lookup-only JSX-name grammar — identifier/hyphenated, dot-joined. */
80
- export function assertValidElementName(elementName) {
81
- assertGrammar("elementName", elementName, ELEMENT_NAME_GRAMMAR, "match the JSX element-name grammar (identifier or hyphenated segments, optionally joined by `.`)");
82
- assertNotDenylisted("elementName", elementName);
80
+ export function assertValidElementName(elementName, argName = "elementName") {
81
+ assertGrammar(argName, elementName, ELEMENT_NAME_GRAMMAR, "match the JSX element-name grammar (identifier or hyphenated segments, optionally joined by `.`)");
82
+ assertNotDenylisted(argName, elementName);
83
83
  }
84
84
  /**
85
85
  * `assertValidImportBinding`'s plain-JS-identifier grammar. The regex alone admits any
@@ -7,17 +7,7 @@ export declare function elementNameEcho(s: string): string;
7
7
  * the name / use `.modify()`) — never the rejected VALUE (REQ-RXD-13.3's zero-echo contract).
8
8
  */
9
9
  export declare function nameRuleTail(argName: string, ruleLabel: string): string;
10
- /** `setJsxProp`'s zero-match reject tail (REQ-RXD-04.4) — names the missing element, bounded. */
11
- export declare function zeroMatchTail(elementName: string): string;
12
- /** `setJsxProp`'s multi-match reject tail (REQ-RXD-04.5) — names the element + count, bounded. */
13
- export declare function multiMatchTail(elementName: string, matchCount: number): string;
14
- /**
15
- * `addImport`'s file-wide collision reject tail (REQ-RXD-05, V7 Step 2; echo bound fixed V8,
16
- * REQ-RXD-05.18) — names `name` and the rule. `name` is POST-VALIDATION at this point
17
- * (REQ-RXD-06 already ran), so — the same class as `zeroMatchTail`/`multiMatchTail`'s
18
- * `elementName` echo — it routes through the wider, marked `elementNameEcho` bound, NEVER
19
- * REQ-RXD-13's 16-char hostile-value `boundedFragment` cap (that cap silently mangled
20
- * realistic names, e.g. `useDebouncedCallback` -> `useDebouncedCall`, with no signal anything
21
- * was cut).
22
- */
23
- export declare function claimedNameTail(name: string): string;
10
+ /** A JSX op's zero-match reject tail (REQ-RXD-04.4) — names the missing element, bounded. */
11
+ export declare function zeroMatchTail(elementName: string, propNames?: readonly string[]): string;
12
+ /** A JSX op's multi-match reject tail (REQ-RXD-04.5) — names the element + count, bounded. */
13
+ export declare function multiMatchTail(opName: string, elementName: string, matchCount: number, propNames?: readonly string[]): string;
@@ -35,29 +35,18 @@ export function nameRuleTail(argName, ruleLabel) {
35
35
  // injection vector), but the grammar has no LENGTH ceiling, so the echo routes through
36
36
  // `elementNameEcho` (the wide, marked 100-char bound above) — NOT `boundedFragment`'s 16-char
37
37
  // hostile-value cap — keeping every react reject message bounded without mangling ordinary
38
- // names. `addImport`'s collision-reject tail (`claimedNameTail`, below) echoes `name` the same
39
- // way, for the same reason (V8).
40
- /** `setJsxProp`'s zero-match reject tail (REQ-RXD-04.4) — names the missing element, bounded. */
41
- export function zeroMatchTail(elementName) {
42
- return (`no element named \`${elementNameEcho(elementName)}\` was found — use \`.modify()\` to inspect ` +
38
+ // names.
39
+ // Target prop NAMES are grammar-validated like `elementName`; their values are never echoed.
40
+ function withProps(propNames) {
41
+ return propNames.length === 0 ? "" : ` with props ${propNames.map((name) => `\`${elementNameEcho(name)}\``).join(", ")}`;
42
+ }
43
+ /** A JSX op's zero-match reject tail (REQ-RXD-04.4) — names the missing element, bounded. */
44
+ export function zeroMatchTail(elementName, propNames = []) {
45
+ return (`no element named \`${elementNameEcho(elementName)}\`${withProps(propNames)} was found — use \`.modify()\` to inspect ` +
43
46
  "the file and edit it directly.");
44
47
  }
45
- /** `setJsxProp`'s multi-match reject tail (REQ-RXD-04.5) — names the element + count, bounded. */
46
- export function multiMatchTail(elementName, matchCount) {
47
- return (`\`${elementNameEcho(elementName)}\` matched ${matchCount} elements — setJsxProp requires ` +
48
+ /** A JSX op's multi-match reject tail (REQ-RXD-04.5) — names the element + count, bounded. */
49
+ export function multiMatchTail(opName, elementName, matchCount, propNames = []) {
50
+ return (`\`${elementNameEcho(elementName)}\`${withProps(propNames)} matched ${matchCount} elements — ${opName} requires ` +
48
51
  "exactly one match; use `.modify()` to disambiguate.");
49
52
  }
50
- /**
51
- * `addImport`'s file-wide collision reject tail (REQ-RXD-05, V7 Step 2; echo bound fixed V8,
52
- * REQ-RXD-05.18) — names `name` and the rule. `name` is POST-VALIDATION at this point
53
- * (REQ-RXD-06 already ran), so — the same class as `zeroMatchTail`/`multiMatchTail`'s
54
- * `elementName` echo — it routes through the wider, marked `elementNameEcho` bound, NEVER
55
- * REQ-RXD-13's 16-char hostile-value `boundedFragment` cap (that cap silently mangled
56
- * realistic names, e.g. `useDebouncedCallback` -> `useDebouncedCall`, with no signal anything
57
- * was cut).
58
- */
59
- export function claimedNameTail(name) {
60
- return (`\`name\` "${elementNameEcho(name)}" is already bound elsewhere in the file — addImport ` +
61
- "cannot create a second local binding under an already-claimed name; rename the existing " +
62
- "binding or choose a different `name`, or use `.modify()` to make this edit directly.");
63
- }
@@ -18,6 +18,8 @@ import { type SourceFile } from "ts-morph";
18
18
  * never surfaced directly to the author.
19
19
  */
20
20
  export declare function parse(source: string): SourceFile;
21
+ /** `parse` for `.jsx` files: `ScriptKind.JSX`, so `<div>` is always JSX, never a cast. */
22
+ export declare function parseJsx(source: string): SourceFile;
21
23
  /**
22
24
  * Prints the live AST back to a string — the ONLY serialization point for a React handle's
23
25
  * flush. Re-prepends a BOM if the original parse observed one (see `hadBom` above) — ts-morph's
@@ -10,7 +10,8 @@ import { Project, NewLineKind, QuoteKind, IndentationText } from "ts-morph";
10
10
  // `.tsx` extension is what engages `ScriptKind.Tsx` (ts-morph infers script kind from the
11
11
  // extension, verified empirically against ts-morph@28.0.0 — no explicit scriptKind option
12
12
  // needed, mirroring typescript/ast.ts's "the extension drives it" shape).
13
- const VIRTUAL_PATH = "dialect-source.tsx";
13
+ const TSX_PATH = "dialect-source.tsx";
14
+ const JSX_PATH = "dialect-source.jsx";
14
15
  const BOM = "";
15
16
  // ts-morph@28's `getFullText()` does not round-trip a leading UTF-8 BOM (same finding as
16
17
  // typescript/ast.ts, same pinned ts-morph version) — a private per-SourceFile flag remembers
@@ -60,6 +61,13 @@ function detectQuoteKind(sourceFile) {
60
61
  * never surfaced directly to the author.
61
62
  */
62
63
  export function parse(source) {
64
+ return parseAs(source, TSX_PATH);
65
+ }
66
+ /** `parse` for `.jsx` files: `ScriptKind.JSX`, so `<div>` is always JSX, never a cast. */
67
+ export function parseJsx(source) {
68
+ return parseAs(source, JSX_PATH);
69
+ }
70
+ function parseAs(source, virtualPath) {
63
71
  const startsWithBom = source.startsWith(BOM);
64
72
  const body = startsWithBom ? source.slice(BOM.length) : source;
65
73
  const project = new Project({
@@ -71,13 +79,13 @@ export function parse(source) {
71
79
  usePrefixAndSuffixTextForRename: false,
72
80
  },
73
81
  });
74
- const sourceFile = project.createSourceFile(VIRTUAL_PATH, body);
82
+ const sourceFile = project.createSourceFile(virtualPath, body);
75
83
  project.manipulationSettings.set({ quoteKind: detectQuoteKind(sourceFile) });
76
84
  if (startsWithBom)
77
85
  hadBom.set(sourceFile, true);
78
86
  const syntacticErrors = project.getProgram().getSyntacticDiagnostics(sourceFile);
79
87
  if (syntacticErrors.length > 0) {
80
- throw new Error("syntactically invalid TSX source");
88
+ throw new Error("syntactically invalid JSX source");
81
89
  }
82
90
  return sourceFile;
83
91
  }
@@ -1,19 +1,32 @@
1
1
  import type { SourceFile } from "ts-morph";
2
2
  import { type Handle } from "../../core/define-dialect.ts";
3
+ import { typescriptOps } from "../typescript/pack.ts";
4
+ import { type JsxTarget } from "./ops.ts";
3
5
  export * as astLibrary from "ts-morph";
4
- type ReactOps = {
5
- setJsxProp: (ast: SourceFile, elementName: string, propName: string, value?: string) => void;
6
- addImport: (ast: SourceFile, name: string, from: string) => void;
6
+ export type { JsxTarget };
7
+ type JsxOps = {
8
+ setJsxProp: (ast: SourceFile, target: JsxTarget, propName: string, value?: string) => void;
9
+ removeJsxProp: (ast: SourceFile, target: JsxTarget, propName: string) => void;
10
+ addJsxChild: (ast: SourceFile, target: JsxTarget, jsx: string) => void;
11
+ wrapJsxElement: (ast: SourceFile, target: JsxTarget, wrapper: string) => void;
12
+ addHookCall: (ast: SourceFile, component: string, statement: string) => void;
13
+ addComponentProp: (ast: SourceFile, component: string, name: string, type: string, options?: {
14
+ optional?: boolean;
15
+ }) => void;
16
+ renameJsxElement: (ast: SourceFile, target: JsxTarget, tag: string) => void;
7
17
  };
18
+ type ReactOps = typeof typescriptOps & JsxOps;
8
19
  /**
9
- * Opens a `.tsx` file for React-dialect-aware editing — the dialect's entry verb into a Session
10
- * (REQ-DG-01.2). `path` MUST end in `.tsx`: the gate below runs SYNCHRONOUSLY, before any op
11
- * is chained and before any run flush, so a rejected path throws on the bare `find()` call
12
- * itself. `.ts` files are TypeScript, not this dialect — use `@pbuilder/sdk/typescript`.
13
- * `.jsx` is not supported in v1: the extension must stay explicit so a future `.jsx` dialect
14
- * addition never has to disambiguate an assumed `.tsx` default (tracked as a React op-catalog
15
- * follow-up). Every other extension, dotfile basename, trailing-dot basename, and
16
- * extensionless path is rejected the same way — no normalization, always an explicit `.tsx`.
20
+ * Opens a `.tsx` or `.jsx` file for React-dialect-aware editing — the dialect's entry verb into
21
+ * a Session that carries every `@pbuilder/sdk/typescript` op plus the JSX ops, chained on one
22
+ * handle (REQ-DG-01.2). Both extensions get the same handle: on `.jsx`, which parses as plain
23
+ * JavaScript with JSX, `addTypeImport`, `addComponentProp` and `addClassProperty`'s `scope`/
24
+ * `readonly` reject at call time because they write TypeScript syntax, leaving the file
25
+ * unchanged. The gate below runs SYNCHRONOUSLY, before any op is chained and before any run
26
+ * flush, so a rejected path throws on the bare `find()` call itself. `.ts` files are TypeScript,
27
+ * not this dialect — use `@pbuilder/sdk/typescript`. Every other extension, dotfile basename,
28
+ * trailing-dot basename, and extensionless path is rejected the same way —
29
+ * no normalization, always an explicit `.tsx` or `.jsx`, so neither extension is ever assumed.
17
30
  * Every gate rejection throws via `dialectError`, so its message carries the standard
18
31
  * `dialect operation failed: ` prefix.
19
32
  *
@@ -2,30 +2,38 @@
2
2
  // Composes the sanctioned kit surface ONLY (`defineDialect`/`defineOpPack`/`withOps` from
3
3
  // ../../core/define-dialect.ts) — mirrors src/dialects/typescript/index.ts's shape exactly,
4
4
  // no port-internal machinery imported anywhere in this tree (REQ-DG-04.1, fit-08/fit-10).
5
- // S-002 closes the op-pack at its final, exact two-op shape: `setJsxProp` (S-001) +
6
- // `addImport` (S-002) — no third op ships in v1 (REQ-RXD-01.1).
5
+ // The parser stays local: typescript/ast.ts parses as `.ts`, which rejects JSX syntax.
7
6
  import { basename } from "node:path";
8
- import { defineDialect, defineOpPack, withOps } from "../../core/define-dialect.js";
7
+ import { byExtension, defineDialect, defineOpPack, overrideOps, withOps, withoutOps } from "../../core/define-dialect.js";
9
8
  import { dialectError } from "../../core/dialect-error.js";
10
- import { parse, print } from "./ast.js";
11
- import { addImport, setJsxProp } from "./ops.js";
9
+ import { addClassProperty } from "../typescript/class-property.js";
10
+ import { typescriptOps } from "../typescript/pack.js";
11
+ import { parse, parseJsx, print } from "./ast.js";
12
+ import { addComponentProp, addHookCall, addJsxChild, removeJsxProp, renameJsxElement, setJsxProp, wrapJsxElement, } from "./ops.js";
12
13
  export * as astLibrary from "ts-morph";
13
- const opsPack = defineOpPack({ setJsxProp, addImport });
14
- const baseDialect = defineDialect({
15
- extensions: [".tsx"],
16
- ast: { parse, print },
17
- ops: {},
14
+ const jsxOps = defineOpPack({ setJsxProp, removeJsxProp, addJsxChild, wrapJsxElement, addHookCall, addComponentProp, renameJsxElement });
15
+ const tsxDialect = withOps(defineDialect({ extensions: [".tsx"], ast: { parse, print }, ops: {} }), typescriptOps, jsxOps);
16
+ const jsxDialect = overrideOps(withoutOps(defineDialect({ extensions: [".jsx"], ast: { parse: parseJsx, print }, ops: tsxDialect.ops }), ["addTypeImport", "addComponentProp"], "they write TypeScript type syntax, which a .jsx file cannot hold"), {
17
+ addClassProperty: (ast, className, name, initializer, options) => {
18
+ if (options?.scope !== undefined || options?.readonly !== undefined) {
19
+ throw dialectError("addClassProperty's `scope` and `readonly` are TypeScript modifiers, which a .jsx file cannot hold — " +
20
+ "omit them, or use .modify() to make this edit directly.");
21
+ }
22
+ addClassProperty(ast, className, name, initializer);
23
+ },
18
24
  });
19
- const reactDialect = withOps(baseDialect, opsPack);
25
+ const reactDialect = byExtension({ ".tsx": tsxDialect, ".jsx": jsxDialect });
20
26
  /**
21
- * Opens a `.tsx` file for React-dialect-aware editing — the dialect's entry verb into a Session
22
- * (REQ-DG-01.2). `path` MUST end in `.tsx`: the gate below runs SYNCHRONOUSLY, before any op
23
- * is chained and before any run flush, so a rejected path throws on the bare `find()` call
24
- * itself. `.ts` files are TypeScript, not this dialect — use `@pbuilder/sdk/typescript`.
25
- * `.jsx` is not supported in v1: the extension must stay explicit so a future `.jsx` dialect
26
- * addition never has to disambiguate an assumed `.tsx` default (tracked as a React op-catalog
27
- * follow-up). Every other extension, dotfile basename, trailing-dot basename, and
28
- * extensionless path is rejected the same way — no normalization, always an explicit `.tsx`.
27
+ * Opens a `.tsx` or `.jsx` file for React-dialect-aware editing — the dialect's entry verb into
28
+ * a Session that carries every `@pbuilder/sdk/typescript` op plus the JSX ops, chained on one
29
+ * handle (REQ-DG-01.2). Both extensions get the same handle: on `.jsx`, which parses as plain
30
+ * JavaScript with JSX, `addTypeImport`, `addComponentProp` and `addClassProperty`'s `scope`/
31
+ * `readonly` reject at call time because they write TypeScript syntax, leaving the file
32
+ * unchanged. The gate below runs SYNCHRONOUSLY, before any op is chained and before any run
33
+ * flush, so a rejected path throws on the bare `find()` call itself. `.ts` files are TypeScript,
34
+ * not this dialect — use `@pbuilder/sdk/typescript`. Every other extension, dotfile basename,
35
+ * trailing-dot basename, and extensionless path is rejected the same way —
36
+ * no normalization, always an explicit `.tsx` or `.jsx`, so neither extension is ever assumed.
29
37
  * Every gate rejection throws via `dialectError`, so its message carries the standard
30
38
  * `dialect operation failed: ` prefix.
31
39
  *
@@ -50,23 +58,16 @@ const reactDialect = withOps(baseDialect, opsPack);
50
58
  */
51
59
  export function find(path) {
52
60
  const base = basename(path);
53
- // A non-empty STEM before `.tsx` is required — `base.endsWith(".tsx")` alone is true for
54
- // `base === ".tsx"` itself (and for a degenerate `..tsx`, whose stem is a lone dot), which
55
- // would pass a basename with no real name before the extension. That is the SAME "dotfile
56
- // with no usable name" shape as `.babelrc` (suffix `babelrc`, not `.tsx`) — by the suffix
57
- // rule REQ-RXD-02 already applies to dotfiles, `.tsx`'s suffix is `tsx`, not `.tsx`.
58
- const stem = base.substring(0, base.length - ".tsx".length);
59
- if (base.endsWith(".tsx") && stem.length > 0 && !stem.endsWith(".")) {
61
+ // A non-empty stem that does not end in a dot: `.tsx` and `a..tsx` name no file of that type.
62
+ const routed = reactDialect.extensions.some((extension) => base.endsWith(extension) && base.length > extension.length && !base.endsWith(`.${extension}`));
63
+ if (routed) {
60
64
  return reactDialect.find(path);
61
65
  }
62
66
  if (!base.includes(".")) {
63
- throw dialectError("find(path) — the React dialect requires an explicit .tsx extension; received a path with no extension. Append .tsx to the path.");
67
+ throw dialectError("find(path) — the React dialect requires an explicit .tsx or .jsx extension; received a path with no extension. Append .tsx or .jsx to the path.");
64
68
  }
65
69
  if (base.endsWith(".ts")) {
66
70
  throw dialectError("find(path) — .ts is not a React file; use @pbuilder/sdk/typescript for TypeScript sources.");
67
71
  }
68
- if (base.endsWith(".jsx")) {
69
- throw dialectError("find(path) — .jsx is not supported in v1; tracked as a follow-up in the React dialect's op catalog.");
70
- }
71
- throw dialectError("find(path) — .tsx is the only extension the React dialect supports.");
72
+ throw dialectError("find(path) — .tsx and .jsx are the only extensions the React dialect supports.");
72
73
  }
@@ -1,8 +1,17 @@
1
1
  import { type SourceFile } from "ts-morph";
2
2
  /**
3
- * Sets (inserts or updates) a JSX attribute on the ONE element whose tag-name text equals
4
- * `elementName` (REQ-RXD-04). Zero matches or more than one match both reject — never a
5
- * silent first-match. `value`'s three forms (REQ-RXD-11): a quoted string (`'"hi"'`), an
3
+ * The element a JSX op edits: a tag name, or a tag plus props that narrow same-tag elements. A
4
+ * string prop value must equal the attribute's initializer text (`'"/users"'`, `'{id}'`);
5
+ * `true` matches the prop with any value, shorthand included.
6
+ */
7
+ export type JsxTarget = string | {
8
+ tag: string;
9
+ props?: Readonly<Record<string, string | true>>;
10
+ };
11
+ export declare function assertValidTarget(target: JsxTarget): void;
12
+ /**
13
+ * Sets (inserts or updates) a JSX attribute on the ONE element `target` names (REQ-RXD-04).
14
+ * Zero matches or more than one match both reject — never a silent first-match. `value`'s three forms (REQ-RXD-11): a quoted string (`'"hi"'`), an
6
15
  * expression container (`'{count}'`), or omitted (boolean shorthand, no `=`). An insert lands
7
16
  * immediately after the element's last existing attribute — including after a trailing
8
17
  * `{...spread}`, which is deliberate: the explicit prop wins at React runtime (REQ-RXD-10). An
@@ -10,47 +19,52 @@ import { type SourceFile } from "ts-morph";
10
19
  *
11
20
  * Trust boundary (REQ-RXD-12): `value` is emitted VERBATIM and becomes executable code — the
12
21
  * SDK performs no validation, escaping, or sanitisation on it; the author is solely
13
- * responsible for any untrusted input reaching this channel. `elementName`/`propName` ARE
14
- * validated and are not a trusted-code channel.
22
+ * responsible for any untrusted input reaching this channel. The target and `propName` ARE
23
+ * validated and are not a trusted-code channel; `target`'s prop values are compared, never
24
+ * emitted or echoed.
15
25
  */
16
- export declare const setJsxProp: (ast: SourceFile, elementName: string, propName: string, value?: string | undefined) => void;
26
+ export declare const setJsxProp: (ast: SourceFile, target: JsxTarget, propName: string, value?: string | undefined) => void;
17
27
  /**
18
- * Adds `import { name } from "from";`, or merges `name` into an EXISTING NAMED-import clause
19
- * from the SAME module `from` if one already exists (REQ-RXD-05, V8 unified algorithm):
20
- *
21
- * 1. Already-bound (idempotency, SAME module only): if an EXISTING declaration for `from` has
22
- * a VALUE-BOUND specifier whose local name equals `name`, AND that specifier is a default
23
- * specifier, a namespace specifier, or an UNALIASED named specifier — this is a no-op. An
24
- * aliased named specifier's local name identifies a DIFFERENT export, so it does NOT satisfy
25
- * idempotency (Defect 3); neither does a type-only specifier at either granularity (Defect
26
- * 1), because it does not satisfy the value-binding promise.
27
- * 2. Collision (file-wide, V7; widened V8): otherwise, if `name` is CLAIMED anywhere in the
28
- * file — EITHER the local name of ANY import specifier, in ANY module, value-bound or
29
- * type-only alike (V7 half), OR a top-level VALUE-NAMESPACE declaration (`function`/`const`/
30
- * `let`/`var`/`class`/`enum`/`namespace`) sharing `name` (V8 half, `isValueNamespaceClaimed`
31
- * above, adopting ADR-0039's `assertNoCollision` predicate verbatim) — REJECT via
32
- * `dialectError`. TypeScript treats a same-name type-only/value collision as the identical
33
- * `TS2300: Duplicate identifier` error as two value bindings, so a type-only specifier claims
34
- * its name exactly as a value specifier does (Defect 1); the claiming declaration may be FROM
35
- * `from` (a same-module alias or type-only collision, Defect 1/3), from a DIFFERENT module
36
- * entirely (a cross-module collision, Defect 2), or a same-file value-namespace declaration
37
- * (V8) — all reject. `type`/`interface` declarations are exempt (legal TS coexistence).
38
- * 3. Merge: otherwise, if an EXISTING declaration for `from` has a non-type-only named-import
39
- * clause, add a NEW, UNALIASED named specifier to it. (Reaching this step guarantees `name`
40
- * is claimed nowhere in the file, so the merge is always safe.)
41
- * 4. Create: otherwise (no declaration for `from`; every one is type-only, default-only, or
42
- * namespace-only), INSERT a FRESH, SEPARATE `import { name } from "from";` — a type-only,
43
- * default-only, or namespace-only declaration's clause structure is NEVER mutated to graft
44
- * a named binding onto it. (Reaching this step also guarantees `name` is claimed nowhere in
45
- * the file, so the fresh declaration never collides.)
46
- *
47
- * NAMED-ONLY, pinned as contract: always the `import { name } from "from"` form — v1 never
48
- * synthesizes default or namespace imports (REQ-RXD-05.4).
49
- *
50
- * `name` is validated (`assertValidImportBinding`, REQ-RXD-06) — a plain JS identifier, not a
51
- * reserved word, checked against the reserved-name denylist — BEFORE any AST mutation. `from`
52
- * has NO allow-list: legitimate module specifiers contain `@ / . :` and more; its safety rests
53
- * on ts-morph escaping `moduleSpecifier` as a single string literal (REQ-RXD-06.4 pins this
54
- * assumption as a regression test, never assumes it silently).
28
+ * Removes the attribute named `propName` from the ONE element `target` names. An absent
29
+ * attribute is a no-op; a `{...spread}` is never touched, even when it may carry the prop.
30
+ */
31
+ export declare const removeJsxProp: (ast: SourceFile, target: JsxTarget, propName: string) => void;
32
+ /**
33
+ * Appends `jsx` as the last child of the ONE element `target` names. A self-closing target
34
+ * becomes an open/close pair holding the child; otherwise the child goes on its own line at
35
+ * the siblings' indentation, or inline when the element's content is inline. A child with the
36
+ * same text already present is a no-op. `jsx` must be exactly one JSX element or fragment and
37
+ * is emitted verbatim, the same trust boundary as `setJsxProp`'s `value`.
38
+ */
39
+ export declare const addJsxChild: (ast: SourceFile, target: JsxTarget, jsx: string) => void;
40
+ /**
41
+ * Wraps the ONE element `target` names in `wrapper`, a self-closing JSX element whose props are
42
+ * kept: `'<QueryProvider client={qc} />'` turns `<App />` into
43
+ * `<QueryProvider client={qc}><App /></QueryProvider>`. A target whose direct parent already
44
+ * has the wrapper's tag is a no-op. `wrapper` is emitted verbatim, the same trust boundary as
45
+ * `setJsxProp`'s `value`.
46
+ */
47
+ export declare const wrapJsxElement: (ast: SourceFile, target: JsxTarget, wrapper: string) => void;
48
+ /**
49
+ * Inserts `statement` into the body of the component named `component`, after its leading
50
+ * hook calls, or first when it has none. An identical statement already in the body is a
51
+ * no-op; an expression-bodied arrow component rejects. `statement` must be exactly one
52
+ * statement and is emitted verbatim, the same trust boundary as `setJsxProp`'s `value`.
53
+ */
54
+ export declare const addHookCall: (ast: SourceFile, component: string, statement: string) => void;
55
+ /**
56
+ * Adds `name: type` (`name?: type` with `{ optional: true }`) to the props of the component
57
+ * named `component` and, when its props parameter is destructured, `name` to the destructuring.
58
+ * The props type is an inline type literal, or an interface or type literal declared in the
59
+ * same file; a component without parameters gets `({ name }: { name: type })`. The same name
60
+ * with the same type text is a no-op; a different type rejects. `type` is emitted verbatim.
61
+ */
62
+ export declare const addComponentProp: (ast: SourceFile, component: string, name: string, type: string, options?: {
63
+ optional?: boolean;
64
+ } | undefined) => void;
65
+ /**
66
+ * Renames the ONE element `target` names to `tag`, opening and closing tag together; nested
67
+ * elements are left alone. Renaming to the same tag is a no-op. Imports are not touched —
68
+ * chain `addImport` for the new component.
55
69
  */
56
- export declare const addImport: (ast: SourceFile, name: string, from: string) => void;
70
+ export declare const renameJsxElement: (ast: SourceFile, target: JsxTarget, tag: string) => void;