@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 +14 -6
- package/dist/core/define-dialect.d.ts +44 -0
- package/dist/core/define-dialect.js +67 -0
- package/dist/core/jsx-name-validator.d.ts +1 -1
- package/dist/core/jsx-name-validator.js +3 -3
- package/dist/core/reject-tail.d.ts +4 -14
- package/dist/core/reject-tail.js +11 -22
- package/dist/dialects/react/ast.d.ts +2 -0
- package/dist/dialects/react/ast.js +11 -3
- package/dist/dialects/react/index.d.ts +24 -11
- package/dist/dialects/react/index.js +32 -31
- package/dist/dialects/react/ops.d.ts +58 -44
- package/dist/dialects/react/ops.js +301 -159
- package/dist/dialects/typescript/import-order.d.ts +38 -0
- package/dist/dialects/typescript/import-order.js +158 -0
- package/dist/dialects/typescript/index.d.ts +4 -1
- package/dist/dialects/typescript/ops.d.ts +18 -1
- package/dist/dialects/typescript/ops.js +39 -9
- package/dist/dialects/typescript/pack.d.ts +2 -0
- package/dist/dialects/typescript/pack.js +2 -0
- package/dist/runner-manifest.json +2 -2
- package/dist/scaffold/filename-pipeline.js +22 -4
- package/package.json +1 -1
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
|
|
609
|
-
|
|
610
|
-
|
|
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
|
-
| `
|
|
628
|
-
| `
|
|
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(
|
|
82
|
-
assertNotDenylisted(
|
|
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
|
-
/**
|
|
11
|
-
export declare function zeroMatchTail(elementName: string): string;
|
|
12
|
-
/**
|
|
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;
|
package/dist/core/reject-tail.js
CHANGED
|
@@ -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.
|
|
39
|
-
//
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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
|
-
/**
|
|
46
|
-
export function multiMatchTail(elementName, matchCount) {
|
|
47
|
-
return (`\`${elementNameEcho(elementName)}
|
|
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
|
|
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(
|
|
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
|
|
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
|
|
5
|
-
|
|
6
|
-
|
|
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
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
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
|
-
//
|
|
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 {
|
|
11
|
-
import {
|
|
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
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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 =
|
|
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
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
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
|
|
54
|
-
|
|
55
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
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. `
|
|
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,
|
|
26
|
+
export declare const setJsxProp: (ast: SourceFile, target: JsxTarget, propName: string, value?: string | undefined) => void;
|
|
17
27
|
/**
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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
|
|
70
|
+
export declare const renameJsxElement: (ast: SourceFile, target: JsxTarget, tag: string) => void;
|