@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.
@@ -1,29 +1,52 @@
1
1
  // S-001: `setJsxProp` (REQ-RXD-04 targeting/upsert, REQ-RXD-10 placement, REQ-RXD-11 value
2
2
  // forms, REQ-RXD-12 trust boundary, design §4.4/ADR-02/ADR-03). Wrapped in `validatedOp` —
3
- // `elementName`/`propName` validate BEFORE `body` runs; `value` is NOT validated (trust
3
+ // the target and `propName` validate BEFORE `body` runs; `value` is NOT validated (trust
4
4
  // contract, REQ-RXD-11/12 verbatim: it is emitted AS-IS, malformed or not, and becomes
5
5
  // executable code the author is solely responsible for).
6
- //
7
- // S-002: `addImport` (REQ-RXD-05 merge/create/idempotent/named-only, REQ-RXD-06 `name`
8
- // validation + `from`'s pinned-escaping trust, design §4.4/ADR-05). Written FRESH — NOT
9
- // copied from the TypeScript dialect's `addImport` (src/dialects/typescript/ops.ts), which
10
- // validates nothing; that laxity is a confirmed vulnerability class this op does not repeat.
11
6
  import { Node, SyntaxKind, } from "ts-morph";
12
7
  import { dialectError } from "../../core/dialect-error.js";
13
8
  import { assertValidAttributeName, assertValidElementName, assertValidImportBinding, validatedOp, } from "../../core/jsx-name-validator.js";
14
- import { claimedNameTail, multiMatchTail, zeroMatchTail } from "../../core/reject-tail.js";
9
+ import { elementNameEcho, multiMatchTail, zeroMatchTail } from "../../core/reject-tail.js";
10
+ import { parse } from "./ast.js";
11
+ function targetParts(target) {
12
+ if (typeof target === "string")
13
+ return { tag: target, props: [] };
14
+ return { tag: target.tag, props: Object.entries(target.props ?? {}) };
15
+ }
16
+ export function assertValidTarget(target) {
17
+ const { tag, props } = targetParts(target);
18
+ assertValidElementName(tag);
19
+ for (const [name, value] of props) {
20
+ assertValidAttributeName(name);
21
+ if (typeof value !== "string" && value !== true) {
22
+ throw dialectError("`target.props` values must be a string or `true` — fix the target, or use `.modify()` to make this edit directly.");
23
+ }
24
+ }
25
+ }
26
+ function hasProp(element, name, value) {
27
+ const attr = element.getAttribute(name);
28
+ if (attr === undefined || !Node.isJsxAttribute(attr))
29
+ return false;
30
+ return value === true || attr.getInitializer()?.getText() === value;
31
+ }
15
32
  // Text-equality targeting against each element's tag-name text (design §4.4) — Set-key-safety
16
- // clause: `elementName` is compared with `===`, NEVER used as an object/array index.
17
- function matchingElements(ast, elementName) {
33
+ // clause: the tag and prop names are compared with `===`, NEVER used as an object/array index.
34
+ // Zero or several matches reject — never a silent first-match.
35
+ function targetElement(ast, target, opName) {
36
+ const { tag, props } = targetParts(target);
18
37
  const openings = ast.getDescendantsOfKind(SyntaxKind.JsxOpeningElement);
19
38
  const selfClosing = ast.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement);
20
- const all = [...openings, ...selfClosing];
21
- return all.filter((element) => element.getTagNameNode().getText() === elementName);
39
+ const matches = [...openings, ...selfClosing].filter((element) => element.getTagNameNode().getText() === tag && props.every(([name, value]) => hasProp(element, name, value)));
40
+ const propNames = props.map(([name]) => name);
41
+ if (matches.length === 0)
42
+ throw dialectError(zeroMatchTail(tag, propNames));
43
+ if (matches.length > 1)
44
+ throw dialectError(multiMatchTail(opName, tag, matches.length, propNames));
45
+ return matches[0];
22
46
  }
23
47
  /**
24
- * Sets (inserts or updates) a JSX attribute on the ONE element whose tag-name text equals
25
- * `elementName` (REQ-RXD-04). Zero matches or more than one match both reject — never a
26
- * silent first-match. `value`'s three forms (REQ-RXD-11): a quoted string (`'"hi"'`), an
48
+ * Sets (inserts or updates) a JSX attribute on the ONE element `target` names (REQ-RXD-04).
49
+ * 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
27
50
  * expression container (`'{count}'`), or omitted (boolean shorthand, no `=`). An insert lands
28
51
  * immediately after the element's last existing attribute — including after a trailing
29
52
  * `{...spread}`, which is deliberate: the explicit prop wins at React runtime (REQ-RXD-10). An
@@ -31,21 +54,15 @@ function matchingElements(ast, elementName) {
31
54
  *
32
55
  * Trust boundary (REQ-RXD-12): `value` is emitted VERBATIM and becomes executable code — the
33
56
  * SDK performs no validation, escaping, or sanitisation on it; the author is solely
34
- * responsible for any untrusted input reaching this channel. `elementName`/`propName` ARE
35
- * validated and are not a trusted-code channel.
57
+ * responsible for any untrusted input reaching this channel. The target and `propName` ARE
58
+ * validated and are not a trusted-code channel; `target`'s prop values are compared, never
59
+ * emitted or echoed.
36
60
  */
37
- export const setJsxProp = validatedOp(([elementName, propName]) => {
38
- assertValidElementName(elementName);
61
+ export const setJsxProp = validatedOp(([target, propName]) => {
62
+ assertValidTarget(target);
39
63
  assertValidAttributeName(propName);
40
- }, (ast, elementName, propName, value) => {
41
- const matches = matchingElements(ast, elementName);
42
- if (matches.length === 0) {
43
- throw dialectError(zeroMatchTail(elementName));
44
- }
45
- if (matches.length > 1) {
46
- throw dialectError(multiMatchTail(elementName, matches.length));
47
- }
48
- const element = matches[0];
64
+ }, (ast, target, propName, value) => {
65
+ const element = targetElement(ast, target, "setJsxProp");
49
66
  const existingAttr = element.getAttribute(propName);
50
67
  if (existingAttr !== undefined && existingAttr.getKind() === SyntaxKind.JsxAttribute) {
51
68
  const attr = existingAttr.asKindOrThrow(SyntaxKind.JsxAttribute);
@@ -59,146 +76,271 @@ export const setJsxProp = validatedOp(([elementName, propName]) => {
59
76
  }
60
77
  element.addAttribute({ name: propName, initializer: value });
61
78
  });
62
- // Collects every local name a single declaration binds, across all three clause shapes at once
63
- // (a declaration can carry a default AND a named clause simultaneously, e.g. `import React, {
64
- // useState } from "react"`). Set-key-safety clause: names are compared via `.includes()`/`===`
65
- // on plain arrays, NEVER used as an object/Map key.
66
- function boundNamesIn(decl) {
67
- const declTypeOnly = decl.isTypeOnly();
68
- const names = [];
69
- const defaultImport = decl.getDefaultImport();
70
- if (defaultImport !== undefined) {
71
- names.push({ localName: defaultImport.getText(), kind: "default", aliased: false, valueBound: !declTypeOnly });
72
- }
73
- const namespaceImport = decl.getNamespaceImport();
74
- if (namespaceImport !== undefined) {
75
- names.push({
76
- localName: namespaceImport.getText(),
77
- kind: "namespace",
78
- aliased: false,
79
- valueBound: !declTypeOnly,
80
- });
81
- }
82
- for (const specifier of decl.getNamedImports()) {
83
- const alias = specifier.getAliasNode();
84
- names.push({
85
- localName: alias !== undefined ? alias.getText() : specifier.getName(),
86
- kind: "named",
87
- aliased: alias !== undefined,
88
- valueBound: !declTypeOnly && !specifier.isTypeOnly(),
89
- });
90
- }
91
- return names;
79
+ /**
80
+ * Removes the attribute named `propName` from the ONE element `target` names. An absent
81
+ * attribute is a no-op; a `{...spread}` is never touched, even when it may carry the prop.
82
+ */
83
+ export const removeJsxProp = validatedOp(([target, propName]) => {
84
+ assertValidTarget(target);
85
+ assertValidAttributeName(propName);
86
+ }, (ast, target, propName) => {
87
+ const attr = targetElement(ast, target, "removeJsxProp").getAttribute(propName);
88
+ if (attr !== undefined && Node.isJsxAttribute(attr))
89
+ attr.remove();
90
+ });
91
+ // One JSX node of an accepted kind and nothing around it. Parsed as `(jsx);`, so trailing code
92
+ // such as `<a />); evil(<b />` yields a second statement and rejects. The text is never echoed.
93
+ function assertJsxNode(jsx, argName, accepts, ruleLabel) {
94
+ let valid = false;
95
+ try {
96
+ const statements = parse(`(${jsx});\n`).getStatements();
97
+ const statement = statements[0];
98
+ if (statements.length === 1 && Node.isExpressionStatement(statement)) {
99
+ const expression = statement.getExpression();
100
+ if (Node.isParenthesizedExpression(expression)) {
101
+ const inner = expression.getExpression();
102
+ valid = accepts(inner) && inner.getText() === jsx.trim();
103
+ }
104
+ }
105
+ }
106
+ catch {
107
+ valid = false;
108
+ }
109
+ if (!valid) {
110
+ throw dialectError(`\`${argName}\` must be ${ruleLabel} — fix it, or use \`.modify()\` to make this edit directly.`);
111
+ }
92
112
  }
93
- // Step 1's idempotency-satisfying shape (REQ-RXD-05, V7-narrowed): a value-bound default
94
- // specifier, a value-bound namespace specifier, or a value-bound UNALIASED named specifier.
95
- // An aliased named specifier's local name identifies a DIFFERENT export (Defect 3) and a
96
- // type-only binding at either granularity does not satisfy the value-binding promise (Defect
97
- // 1) — neither counts here, even though both still CLAIM the name for Step 2's purposes.
98
- function satisfiesIdempotency(bound) {
99
- if (!bound.valueBound)
100
- return false;
101
- return bound.kind !== "named" || !bound.aliased;
113
+ function lineIndent(ast, pos) {
114
+ const text = ast.getFullText();
115
+ const lineStart = text.lastIndexOf("\n", pos - 1) + 1;
116
+ return /^[ \t]*/.exec(text.slice(lineStart))[0];
117
+ }
118
+ function indentUnit(indent) {
119
+ return indent.includes("\t") ? "\t" : " ";
102
120
  }
103
- // V5 (REQ-RXD-05, step 2): a valid MERGE target is a declaration that (a) is NOT type-only and
104
- // (b) has a `NamedImports` clause node — whether or not it already carries specifiers. A
105
- // default-only or namespace-only declaration has no `NamedImports` node at all: TS/JS syntax
106
- // forbids grafting a named clause onto a namespace import, and grafting one onto a default-only
107
- // declaration would silently widen an existing statement the author did not ask this op to
108
- // touch — so neither is a merge target, matching a FRESH separate declaration instead.
109
- function isNonTypeOnlyNamedImportClause(decl) {
110
- if (decl.isTypeOnly())
121
+ /**
122
+ * Appends `jsx` as the last child of the ONE element `target` names. A self-closing target
123
+ * becomes an open/close pair holding the child; otherwise the child goes on its own line at
124
+ * the siblings' indentation, or inline when the element's content is inline. A child with the
125
+ * same text already present is a no-op. `jsx` must be exactly one JSX element or fragment and
126
+ * is emitted verbatim, the same trust boundary as `setJsxProp`'s `value`.
127
+ */
128
+ export const addJsxChild = validatedOp(([target, jsx]) => {
129
+ assertValidTarget(target);
130
+ assertJsxNode(jsx, "jsx", (node) => Node.isJsxElement(node) || Node.isJsxSelfClosingElement(node) || Node.isJsxFragment(node), "exactly one JSX element or fragment");
131
+ }, (ast, target, jsx) => {
132
+ const child = jsx.trim();
133
+ const tag = targetElement(ast, target, "addJsxChild");
134
+ const eol = ast.getProject().manipulationSettings.getNewLineKindAsString();
135
+ if (Node.isJsxSelfClosingElement(tag)) {
136
+ const indent = lineIndent(ast, tag.getStart());
137
+ const open = tag.getText().replace(/\s*\/>$/, ">");
138
+ const close = `</${tag.getTagNameNode().getText()}>`;
139
+ ast.replaceText([tag.getStart(), tag.getEnd()], `${open}${eol}${indent}${indentUnit(indent)}${child}${eol}${indent}${close}`);
140
+ return;
141
+ }
142
+ const element = tag.getParentIfKindOrThrow(SyntaxKind.JsxElement);
143
+ const children = element.getJsxChildren();
144
+ if (children.some((existing) => existing.getText() === child))
145
+ return;
146
+ const content = children.filter((node) => !(Node.isJsxText(node) && node.containsOnlyTriviaWhiteSpaces()));
147
+ const last = content.at(-1);
148
+ const closingStart = element.getClosingElement().getStart();
149
+ const anchor = last?.getEnd() ?? tag.getEnd();
150
+ if (!ast.getFullText().slice(anchor, closingStart).includes("\n")) {
151
+ ast.insertText(closingStart, child);
152
+ return;
153
+ }
154
+ const closingIndent = lineIndent(ast, closingStart);
155
+ const indent = last === undefined ? closingIndent + indentUnit(closingIndent) : lineIndent(ast, last.getStart());
156
+ ast.insertText(anchor, `${eol}${indent}${child}`);
157
+ });
158
+ /**
159
+ * Wraps the ONE element `target` names in `wrapper`, a self-closing JSX element whose props are
160
+ * kept: `'<QueryProvider client={qc} />'` turns `<App />` into
161
+ * `<QueryProvider client={qc}><App /></QueryProvider>`. A target whose direct parent already
162
+ * has the wrapper's tag is a no-op. `wrapper` is emitted verbatim, the same trust boundary as
163
+ * `setJsxProp`'s `value`.
164
+ */
165
+ export const wrapJsxElement = validatedOp(([target, wrapper]) => {
166
+ assertValidTarget(target);
167
+ assertJsxNode(wrapper, "wrapper", (node) => Node.isJsxSelfClosingElement(node), "exactly one self-closing JSX element");
168
+ }, (ast, target, wrapper) => {
169
+ const tag = targetElement(ast, target, "wrapJsxElement");
170
+ const node = Node.isJsxSelfClosingElement(tag) ? tag : tag.getParentIfKindOrThrow(SyntaxKind.JsxElement);
171
+ const open = wrapper.trim().replace(/\s*\/>$/, ">");
172
+ const wrapperTag = /^<([^\s/>]+)/.exec(open)[1];
173
+ const parent = node.getParent();
174
+ if (Node.isJsxElement(parent) && parent.getOpeningElement().getTagNameNode().getText() === wrapperTag)
175
+ return;
176
+ ast.replaceText([node.getStart(), node.getEnd()], `${open}${node.getText()}</${wrapperTag}>`);
177
+ });
178
+ // A top-level `function Name` or `const Name =` arrow/function expression. Wrapped components
179
+ // (`memo(...)`, `forwardRef(...)`) are deliberately not unwrapped.
180
+ function componentFunction(ast, name) {
181
+ const declared = ast.getFunctions().filter((fn) => fn.getName() === name);
182
+ const assigned = ast
183
+ .getVariableDeclarations()
184
+ .filter((decl) => decl.getName() === name)
185
+ .map((decl) => decl.getInitializer())
186
+ .filter((init) => Node.isArrowFunction(init) || Node.isFunctionExpression(init));
187
+ const matches = [...declared, ...assigned];
188
+ if (matches.length !== 1) {
189
+ const found = matches.length === 0 ? "no component named" : `${matches.length} components named`;
190
+ throw dialectError(`${found} \`${elementNameEcho(name)}\` (a top-level function, or a const holding an arrow or function expression) — ` +
191
+ "use `.modify()` to edit it directly.");
192
+ }
193
+ return matches[0];
194
+ }
195
+ function assertSingleStatement(statement) {
196
+ let valid = false;
197
+ try {
198
+ const statements = parse(statement).getStatements();
199
+ valid = statements.length === 1 && statements[0].getText() === statement.trim();
200
+ }
201
+ catch {
202
+ valid = false;
203
+ }
204
+ if (!valid) {
205
+ throw dialectError("`statement` must be exactly one statement — fix it, or use `.modify()` to make this edit directly.");
206
+ }
207
+ }
208
+ // `useX(...)`, `React.useX(...)`, or a declaration initialized by one.
209
+ function isHookCall(statement) {
210
+ const call = Node.isExpressionStatement(statement)
211
+ ? statement.getExpression()
212
+ : Node.isVariableStatement(statement)
213
+ ? statement.getDeclarations()[0]?.getInitializer()
214
+ : undefined;
215
+ if (!Node.isCallExpression(call))
111
216
  return false;
112
- const namedBindings = decl.getImportClause()?.getNamedBindings();
113
- return namedBindings !== undefined && namedBindings.getKind() === SyntaxKind.NamedImports;
217
+ const callee = call.getExpression();
218
+ const name = Node.isPropertyAccessExpression(callee) ? callee.getName() : callee.getText();
219
+ return /^use[A-Z0-9]/.test(name);
220
+ }
221
+ /**
222
+ * Inserts `statement` into the body of the component named `component`, after its leading
223
+ * hook calls, or first when it has none. An identical statement already in the body is a
224
+ * no-op; an expression-bodied arrow component rejects. `statement` must be exactly one
225
+ * statement and is emitted verbatim, the same trust boundary as `setJsxProp`'s `value`.
226
+ */
227
+ export const addHookCall = validatedOp(([component, statement]) => {
228
+ assertValidImportBinding(component, "component");
229
+ assertSingleStatement(statement);
230
+ }, (ast, component, statement) => {
231
+ const body = componentFunction(ast, component).getBody();
232
+ if (!Node.isBlock(body)) {
233
+ throw dialectError(`component \`${elementNameEcho(component)}\` has an expression body, so there is no statement list to add to — ` +
234
+ "give it a block body, or use `.modify()` to make this edit directly.");
235
+ }
236
+ const statements = body.getStatements();
237
+ const text = statement.trim();
238
+ if (statements.some((existing) => existing.getText() === text))
239
+ return;
240
+ const leadingHooks = statements.findIndex((existing) => !isHookCall(existing));
241
+ body.insertStatements(leadingHooks === -1 ? statements.length : leadingHooks, text);
242
+ });
243
+ function assertSingleType(type) {
244
+ let valid = false;
245
+ try {
246
+ const statements = parse(`type T = ${type};\n`).getStatements();
247
+ const alias = statements[0];
248
+ valid = statements.length === 1 && Node.isTypeAliasDeclaration(alias) && alias.getTypeNode()?.getText() === type.trim();
249
+ }
250
+ catch {
251
+ valid = false;
252
+ }
253
+ if (!valid) {
254
+ throw dialectError("`type` must be exactly one type — fix it, or use `.modify()` to make this edit directly.");
255
+ }
256
+ }
257
+ // The first parameter's inline type literal, or the same-file interface or type-alias literal it
258
+ // names. Anything else (imported, generic utility, untyped) is left to `.modify()`.
259
+ function propsType(ast, fn, component) {
260
+ const typeNode = fn.getParameters()[0]?.getTypeNode();
261
+ if (Node.isTypeLiteral(typeNode))
262
+ return typeNode;
263
+ if (Node.isTypeReference(typeNode)) {
264
+ const name = typeNode.getTypeName().getText();
265
+ const declared = ast.getInterface(name) ?? ast.getTypeAlias(name)?.getTypeNode();
266
+ if (Node.isInterfaceDeclaration(declared) || Node.isTypeLiteral(declared))
267
+ return declared;
268
+ }
269
+ throw dialectError(`component \`${elementNameEcho(component)}\` has no props type this op can edit — its first parameter needs an inline ` +
270
+ "type literal, or an interface or type literal declared in this file; use `.modify()` to make this edit directly.");
271
+ }
272
+ function addPropsMember(ast, props, name, type, optional) {
273
+ const last = props.getMembers().at(-1);
274
+ if (last === undefined || props.getText().includes("\n")) {
275
+ props.addProperty({ name, type, hasQuestionToken: optional });
276
+ return;
277
+ }
278
+ // ts-morph's addProperty breaks a single-line literal across lines; keep it on one line,
279
+ // reusing the last member's separator when it has one.
280
+ const signature = `${name}${optional ? "?" : ""}: ${type}`;
281
+ const separator = /[;,]$/.exec(last.getText())?.[0];
282
+ ast.insertText(last.getEnd(), separator === undefined ? `; ${signature}` : ` ${signature}${separator}`);
114
283
  }
115
- // V8 (judgment-day Round 2, REQ-RXD-05 step 2, second half of CLAIMED): a top-level
116
- // VALUE-NAMESPACE declaration under `name` collides the same way a same-name import specifier
117
- // does — ADOPTED verbatim from ADR-0039's ratified `assertNoCollision` predicate
118
- // (typescript/ops.ts:54-75), not reinvented. `type`/`interface` are exempt (legal TS
119
- // coexistence, the same ADR-0039 carve-out).
120
- function isValueNamespaceClaimed(ast, name) {
121
- return (ast.getFunction(name) !== undefined ||
122
- ast.getVariableDeclaration(name) !== undefined ||
123
- ast.getClass(name) !== undefined ||
124
- ast.getEnum(name) !== undefined ||
125
- ast.getModule(name) !== undefined);
284
+ function addDestructuredName(fn, name) {
285
+ const pattern = fn.getParameters()[0]?.getNameNode();
286
+ if (!Node.isObjectBindingPattern(pattern))
287
+ return;
288
+ const elements = pattern.getElements();
289
+ if (elements.some((element) => element.getName() === name))
290
+ return;
291
+ const rest = elements.find((element) => element.getDotDotDotToken() !== undefined);
292
+ const last = elements.at(-1);
293
+ if (rest !== undefined)
294
+ fn.getSourceFile().insertText(rest.getStart(), `${name}, `);
295
+ else if (last !== undefined)
296
+ fn.getSourceFile().insertText(last.getEnd(), `, ${name}`);
297
+ else
298
+ fn.getSourceFile().replaceText([pattern.getStart(), pattern.getEnd()], `{ ${name} }`);
126
299
  }
127
300
  /**
128
- * Adds `import { name } from "from";`, or merges `name` into an EXISTING NAMED-import clause
129
- * from the SAME module `from` if one already exists (REQ-RXD-05, V8 unified algorithm):
130
- *
131
- * 1. Already-bound (idempotency, SAME module only): if an EXISTING declaration for `from` has
132
- * a VALUE-BOUND specifier whose local name equals `name`, AND that specifier is a default
133
- * specifier, a namespace specifier, or an UNALIASED named specifier — this is a no-op. An
134
- * aliased named specifier's local name identifies a DIFFERENT export, so it does NOT satisfy
135
- * idempotency (Defect 3); neither does a type-only specifier at either granularity (Defect
136
- * 1), because it does not satisfy the value-binding promise.
137
- * 2. Collision (file-wide, V7; widened V8): otherwise, if `name` is CLAIMED anywhere in the
138
- * file — EITHER the local name of ANY import specifier, in ANY module, value-bound or
139
- * type-only alike (V7 half), OR a top-level VALUE-NAMESPACE declaration (`function`/`const`/
140
- * `let`/`var`/`class`/`enum`/`namespace`) sharing `name` (V8 half, `isValueNamespaceClaimed`
141
- * above, adopting ADR-0039's `assertNoCollision` predicate verbatim) — REJECT via
142
- * `dialectError`. TypeScript treats a same-name type-only/value collision as the identical
143
- * `TS2300: Duplicate identifier` error as two value bindings, so a type-only specifier claims
144
- * its name exactly as a value specifier does (Defect 1); the claiming declaration may be FROM
145
- * `from` (a same-module alias or type-only collision, Defect 1/3), from a DIFFERENT module
146
- * entirely (a cross-module collision, Defect 2), or a same-file value-namespace declaration
147
- * (V8) — all reject. `type`/`interface` declarations are exempt (legal TS coexistence).
148
- * 3. Merge: otherwise, if an EXISTING declaration for `from` has a non-type-only named-import
149
- * clause, add a NEW, UNALIASED named specifier to it. (Reaching this step guarantees `name`
150
- * is claimed nowhere in the file, so the merge is always safe.)
151
- * 4. Create: otherwise (no declaration for `from`; every one is type-only, default-only, or
152
- * namespace-only), INSERT a FRESH, SEPARATE `import { name } from "from";` — a type-only,
153
- * default-only, or namespace-only declaration's clause structure is NEVER mutated to graft
154
- * a named binding onto it. (Reaching this step also guarantees `name` is claimed nowhere in
155
- * the file, so the fresh declaration never collides.)
156
- *
157
- * NAMED-ONLY, pinned as contract: always the `import { name } from "from"` form — v1 never
158
- * synthesizes default or namespace imports (REQ-RXD-05.4).
159
- *
160
- * `name` is validated (`assertValidImportBinding`, REQ-RXD-06) — a plain JS identifier, not a
161
- * reserved word, checked against the reserved-name denylist — BEFORE any AST mutation. `from`
162
- * has NO allow-list: legitimate module specifiers contain `@ / . :` and more; its safety rests
163
- * on ts-morph escaping `moduleSpecifier` as a single string literal (REQ-RXD-06.4 pins this
164
- * assumption as a regression test, never assumes it silently).
301
+ * Adds `name: type` (`name?: type` with `{ optional: true }`) to the props of the component
302
+ * named `component` and, when its props parameter is destructured, `name` to the destructuring.
303
+ * The props type is an inline type literal, or an interface or type literal declared in the
304
+ * same file; a component without parameters gets `({ name }: { name: type })`. The same name
305
+ * with the same type text is a no-op; a different type rejects. `type` is emitted verbatim.
165
306
  */
166
- export const addImport = validatedOp(([name]) => {
167
- assertValidImportBinding(name);
168
- }, (ast, name, from) => {
169
- const declarationsForModule = ast
170
- .getImportDeclarations()
171
- .filter((decl) => decl.getModuleSpecifierValue() === from);
172
- const alreadyBound = declarationsForModule.some((decl) => boundNamesIn(decl).some((bound) => bound.localName === name && satisfiesIdempotency(bound)));
173
- if (alreadyBound)
307
+ export const addComponentProp = validatedOp(([component, name, type]) => {
308
+ assertValidImportBinding(component, "component");
309
+ assertValidImportBinding(name, "name");
310
+ assertSingleType(type);
311
+ }, (ast, component, name, type, options) => {
312
+ const text = type.trim();
313
+ const optional = options?.optional === true;
314
+ const fn = componentFunction(ast, component);
315
+ if (fn.getParameters().length === 0) {
316
+ fn.insertParameter(0, { name: `{ ${name} }`, type: `{ ${name}${optional ? "?" : ""}: ${text} }` });
174
317
  return;
175
- const claimed = ast.getImportDeclarations().some((decl) => boundNamesIn(decl).some((bound) => bound.localName === name)) ||
176
- isValueNamespaceClaimed(ast, name);
177
- if (claimed) {
178
- throw dialectError(claimedNameTail(name));
179
- }
180
- const mergeTarget = declarationsForModule.find(isNonTypeOnlyNamedImportClause);
181
- if (mergeTarget !== undefined) {
182
- mergeTarget.addNamedImport(name);
318
+ }
319
+ const props = propsType(ast, fn, component);
320
+ const existing = props.getProperty(name);
321
+ if (existing !== undefined) {
322
+ if (existing.getTypeNode()?.getText() === text)
323
+ return;
324
+ throw dialectError(`prop \`${elementNameEcho(name)}\` already exists on \`${elementNameEcho(component)}\` with a different type — ` +
325
+ "change it with `.modify()`.");
326
+ }
327
+ addPropsMember(ast, props, name, text, optional);
328
+ addDestructuredName(componentFunction(ast, component), name);
329
+ });
330
+ /**
331
+ * Renames the ONE element `target` names to `tag`, opening and closing tag together; nested
332
+ * elements are left alone. Renaming to the same tag is a no-op. Imports are not touched —
333
+ * chain `addImport` for the new component.
334
+ */
335
+ export const renameJsxElement = validatedOp(([target, tag]) => {
336
+ assertValidTarget(target);
337
+ assertValidElementName(tag, "tag");
338
+ }, (ast, target, tag) => {
339
+ const opening = targetElement(ast, target, "renameJsxElement");
340
+ if (opening.getTagNameNode().getText() === tag)
183
341
  return;
342
+ if (Node.isJsxOpeningElement(opening)) {
343
+ opening.getParentIfKindOrThrow(SyntaxKind.JsxElement).getClosingElement().getTagNameNode().replaceWithText(tag);
184
344
  }
185
- const dropSemicolon = omitsSemicolons(ast);
186
- const inserted = ast.addImportDeclaration({ moduleSpecifier: from, namedImports: [name] });
187
- if (dropSemicolon)
188
- inserted.replaceWithText(inserted.getText().slice(0, -1));
345
+ opening.getTagNameNode().replaceWithText(tag);
189
346
  });
190
- // Duplicated from typescript/ops.ts per ADR-01. A fresh import keeps the file's statement-terminating semicolon style: ts-morph always
191
- // prints one, so it is dropped only when the file's terminable top-level statements mostly
192
- // omit it (a file with no such statements, or a tie, keeps it).
193
- function omitsSemicolons(ast) {
194
- const terminable = ast
195
- .getStatements()
196
- .filter((statement) => Node.isImportDeclaration(statement) ||
197
- Node.isExportDeclaration(statement) ||
198
- Node.isExportAssignment(statement) ||
199
- Node.isVariableStatement(statement) ||
200
- Node.isExpressionStatement(statement) ||
201
- Node.isTypeAliasDeclaration(statement));
202
- const terminated = terminable.filter((statement) => statement.getText().endsWith(";")).length;
203
- return terminable.length - terminated > terminated;
204
- }
@@ -0,0 +1,38 @@
1
+ import { type ImportDeclaration, type SourceFile } from "ts-morph";
2
+ /** Index at which `name` keeps `decl`'s named specifiers in order. */
3
+ export declare function sortedSpecifierIndex(decl: ImportDeclaration, name: string): number;
4
+ /**
5
+ * Where a new declaration of `from` goes: among the existing declarations most related to it
6
+ * (its folder siblings), before the first that sorts after it, or after the last. `index` is a
7
+ * `getStatementsWithComments()` index; inserting before a declaration also goes above the
8
+ * comments directly over it, so an `eslint-disable-next-line` keeps covering the import it was
9
+ * written for. `joinsComment` is true when that comment had no blank line above it, which
10
+ * `closeGapAfter` must restore. Undefined when the file has no import declarations.
11
+ */
12
+ export declare function sortedPlacement(ast: SourceFile, from: string): {
13
+ index: number;
14
+ joinsComment: boolean;
15
+ } | undefined;
16
+ export declare function closeGapAfter(decl: ImportDeclaration): void;
17
+ /**
18
+ * Sorts the file's import declarations by module specifier (packages first, then relative
19
+ * paths, case-insensitively) and the named specifiers inside each declaration's braces.
20
+ *
21
+ * It only reorders; it never combines, removes, or reformats a declaration. Declarations move
22
+ * only within a run of consecutive imports: a blank line, a comment, a side-effect import
23
+ * (`import "./polyfills";`, whose position is behaviour), or a declaration with a comment
24
+ * attached to it ends the run, and nothing moves across it. Calling it on a sorted file
25
+ * changes nothing.
26
+ *
27
+ * @example
28
+ * // import { useState, type FC } from "react";
29
+ * // import { b } from "./b";
30
+ * // import { a } from "./a";
31
+ * // import { Users, BookOpen } from "lucide-react";
32
+ * ts.find(path).sortImports();
33
+ * // import { BookOpen, Users } from "lucide-react";
34
+ * // import { type FC, useState } from "react";
35
+ * // import { a } from "./a";
36
+ * // import { b } from "./b";
37
+ */
38
+ export declare function sortImports(ast: SourceFile): void;