@pbuilder/sdk 0.14.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/README.md +57 -42
  2. package/dist/{transport → acl/irwire}/frame-reader.d.ts +2 -0
  3. package/dist/{transport → acl/irwire}/frame-reader.js +57 -5
  4. package/dist/{transport → acl/irwire}/stdio-engine-client.d.ts +2 -2
  5. package/dist/{transport → acl/irwire}/stdio-engine-client.js +4 -4
  6. package/dist/bin/pbuilder-codegen.js +30 -35
  7. package/dist/bin/pbuilder-runner.js +6 -6
  8. package/dist/bounded-contexts/authoring/application/usecases/authoring-verbs/index.d.ts +106 -0
  9. package/dist/bounded-contexts/authoring/application/usecases/authoring-verbs/index.js +202 -0
  10. package/dist/{pending-directives → bounded-contexts/authoring/application/usecases/pending-directives}/render.d.ts +2 -2
  11. package/dist/{core → bounded-contexts/authoring/application/usecases/run-factory}/context.d.ts +12 -9
  12. package/dist/{core → bounded-contexts/authoring/application/usecases/run-factory}/context.js +59 -120
  13. package/dist/bounded-contexts/authoring/application/usecases/run-factory/driving.d.ts +5 -0
  14. package/dist/bounded-contexts/authoring/application/usecases/run-factory/driving.js +15 -0
  15. package/dist/bounded-contexts/authoring/application/usecases/scaffold/classify-transport.d.ts +51 -0
  16. package/dist/bounded-contexts/authoring/application/usecases/scaffold/classify-transport.js +105 -0
  17. package/dist/{scaffold → bounded-contexts/authoring/application/usecases/scaffold}/expander.d.ts +2 -1
  18. package/dist/{scaffold → bounded-contexts/authoring/application/usecases/scaffold}/expander.js +13 -7
  19. package/dist/{scaffold → bounded-contexts/authoring/application/usecases/scaffold}/index.d.ts +1 -1
  20. package/dist/{scaffold → bounded-contexts/authoring/application/usecases/scaffold}/index.js +7 -6
  21. package/dist/{scaffold → bounded-contexts/authoring/application/usecases/scaffold}/path-guards.d.ts +11 -10
  22. package/dist/{scaffold → bounded-contexts/authoring/application/usecases/scaffold}/path-guards.js +21 -48
  23. package/dist/{scaffold → bounded-contexts/authoring/application/usecases/scaffold}/walk.d.ts +2 -3
  24. package/dist/{scaffold → bounded-contexts/authoring/application/usecases/scaffold}/walk.js +37 -56
  25. package/dist/{core → bounded-contexts/authoring/domain/aggregates/session}/session.d.ts +2 -2
  26. package/dist/{core → bounded-contexts/authoring/domain/aggregates/session}/session.js +1 -1
  27. package/dist/{core → bounded-contexts/authoring/domain/entities}/dialect-handle.d.ts +1 -1
  28. package/dist/{core → bounded-contexts/authoring/domain/entities}/dialect-handle.js +10 -10
  29. package/dist/{core → bounded-contexts/authoring/domain/ports}/engine-client.d.ts +1 -1
  30. package/dist/bounded-contexts/authoring/domain/ports/package-files.d.ts +53 -0
  31. package/dist/bounded-contexts/authoring/domain/ports/package-files.js +11 -0
  32. package/dist/{core → bounded-contexts/authoring/domain/services}/define-dialect.d.ts +2 -2
  33. package/dist/{core → bounded-contexts/authoring/domain/services}/define-dialect.js +3 -3
  34. package/dist/{core → bounded-contexts/authoring/domain/services}/directive-factory.d.ts +2 -2
  35. package/dist/{core → bounded-contexts/authoring/domain/services}/directive-factory.js +37 -12
  36. package/dist/{scaffold → bounded-contexts/authoring/domain/services}/filename-pipeline.d.ts +7 -5
  37. package/dist/{scaffold → bounded-contexts/authoring/domain/services}/filename-pipeline.js +28 -8
  38. package/dist/{core/jsx-name-validator.d.ts → bounded-contexts/authoring/domain/services/identifier-names.d.ts} +8 -4
  39. package/dist/{core/jsx-name-validator.js → bounded-contexts/authoring/domain/services/identifier-names.js} +21 -28
  40. package/dist/bounded-contexts/authoring/domain/services/reject-tail.d.ts +9 -0
  41. package/dist/bounded-contexts/authoring/domain/services/reject-tail.js +30 -0
  42. package/dist/bounded-contexts/authoring/domain/services/run-context.d.ts +5 -0
  43. package/dist/bounded-contexts/authoring/domain/services/run-context.js +70 -0
  44. package/dist/{core → bounded-contexts/authoring/domain/services}/schema/input-rejection.d.ts +1 -1
  45. package/dist/{core → bounded-contexts/authoring/domain/services}/schema/input-rejection.js +1 -1
  46. package/dist/bounded-contexts/authoring/domain/services/schema/schema-files.d.ts +2 -0
  47. package/dist/bounded-contexts/authoring/domain/services/schema/schema-files.js +6 -0
  48. package/dist/{core → bounded-contexts/authoring/domain/services}/schema/schema-locate.d.ts +2 -1
  49. package/dist/{core → bounded-contexts/authoring/domain/services}/schema/schema-locate.js +13 -2
  50. package/dist/{core → bounded-contexts/authoring/domain/services}/schema/schema-parse.d.ts +1 -1
  51. package/dist/{core → bounded-contexts/authoring/domain/services}/schema/schema-parse.js +2 -14
  52. package/dist/{core → bounded-contexts/authoring/domain/services}/schema/schema-sufficiency.d.ts +4 -3
  53. package/dist/{core → bounded-contexts/authoring/domain/services}/schema/schema-sufficiency.js +8 -4
  54. package/dist/{core → bounded-contexts/authoring/domain/services}/schema/schema-validate.d.ts +1 -1
  55. package/dist/{core → bounded-contexts/authoring/domain/services}/schema/schema-validate.js +1 -1
  56. package/dist/{core → bounded-contexts/authoring/domain/valueobjects}/authoring-error.js +1 -1
  57. package/dist/{core → bounded-contexts/authoring/domain/valueobjects}/wire.d.ts +0 -3
  58. package/dist/bounded-contexts/authoring/domain/valueobjects/wire.js +28 -0
  59. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/cli.d.ts +27 -0
  60. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/cli.js +306 -0
  61. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.d.ts +7 -0
  62. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.js +68 -0
  63. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/project-codegen.d.ts +19 -0
  64. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/project-codegen.js +131 -0
  65. package/dist/bounded-contexts/authoring/infrastructure/in/commons/index.d.ts +182 -0
  66. package/dist/bounded-contexts/authoring/infrastructure/in/commons/index.js +94 -0
  67. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/angular/index.d.ts +63 -0
  68. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/angular/index.js +68 -0
  69. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/angular/ops.js +9 -9
  70. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/css/index.d.ts +40 -0
  71. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/css/index.js +38 -0
  72. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/css/ops.js +2 -2
  73. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/json/index.d.ts +55 -0
  74. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/json/index.js +54 -0
  75. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/json/ops.d.ts +1 -1
  76. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/json/ops.js +35 -8
  77. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.d.ts +43 -0
  78. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.js +46 -0
  79. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/nestjs/ops.js +7 -7
  80. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.d.ts +52 -0
  81. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.js +73 -0
  82. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/jsx-names.d.ts +4 -0
  83. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/jsx-names.js +18 -0
  84. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/match-tails.d.ts +4 -0
  85. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/match-tails.js +25 -0
  86. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/react/ops.js +5 -3
  87. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/typescript/array-element.d.ts +7 -2
  88. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/typescript/array-element.js +29 -15
  89. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/typescript/ast.d.ts +5 -1
  90. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/typescript/ast.js +22 -4
  91. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/typescript/class-property.js +14 -19
  92. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.d.ts +53 -0
  93. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.js +37 -0
  94. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/typescript/ops.d.ts +6 -1
  95. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/typescript/ops.js +90 -54
  96. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/yaml/index.d.ts +69 -0
  97. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/yaml/index.js +70 -0
  98. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/yaml/paths.d.ts +1 -1
  99. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/yaml/paths.js +2 -2
  100. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/yaml/presentation.js +1 -1
  101. package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/yaml/structural.js +2 -2
  102. package/dist/bounded-contexts/authoring/infrastructure/out/fs/package-files.d.ts +8 -0
  103. package/dist/bounded-contexts/authoring/infrastructure/out/fs/package-files.js +133 -0
  104. package/dist/bounded-contexts/authoring/testing/conformance/index.d.ts +157 -0
  105. package/dist/bounded-contexts/authoring/testing/conformance/index.js +261 -0
  106. package/dist/{testing → bounded-contexts/authoring/testing}/contract-fake.d.ts +2 -2
  107. package/dist/{testing → bounded-contexts/authoring/testing}/contract-fake.js +4 -3
  108. package/dist/bounded-contexts/authoring/testing/harness/index.d.ts +89 -0
  109. package/dist/bounded-contexts/authoring/testing/harness/index.js +85 -0
  110. package/dist/{conformance → bounded-contexts/authoring/testing}/run-vehicle.d.ts +1 -1
  111. package/dist/{transport → bounded-contexts/runner-hosting/infrastructure/in}/bootstrap-bridge.js +2 -2
  112. package/dist/{transport → bounded-contexts/runner-hosting/infrastructure/in}/exit-codes.js +5 -4
  113. package/dist/{transport → bounded-contexts/runner-hosting/infrastructure/in}/factory-pointer.js +1 -1
  114. package/dist/{transport → bounded-contexts/runner-hosting/infrastructure/in}/runner.d.ts +4 -0
  115. package/dist/{transport → bounded-contexts/runner-hosting/infrastructure/in}/runner.js +49 -23
  116. package/dist/{transport → bounded-contexts/runner-hosting/infrastructure/in}/single-instance-probe.js +1 -1
  117. package/dist/commons/index.d.ts +1 -278
  118. package/dist/commons/index.js +1 -286
  119. package/dist/conformance/index.d.ts +1 -157
  120. package/dist/conformance/index.js +1 -261
  121. package/dist/dialects/angular/index.d.ts +1 -63
  122. package/dist/dialects/angular/index.js +1 -68
  123. package/dist/dialects/css/index.d.ts +1 -40
  124. package/dist/dialects/css/index.js +1 -38
  125. package/dist/dialects/json/index.d.ts +1 -55
  126. package/dist/dialects/json/index.js +1 -54
  127. package/dist/dialects/nestjs/index.d.ts +1 -43
  128. package/dist/dialects/nestjs/index.js +1 -46
  129. package/dist/dialects/react/index.d.ts +1 -52
  130. package/dist/dialects/react/index.js +1 -73
  131. package/dist/dialects/typescript/index.d.ts +1 -53
  132. package/dist/dialects/typescript/index.js +1 -37
  133. package/dist/dialects/yaml/index.d.ts +1 -69
  134. package/dist/dialects/yaml/index.js +1 -70
  135. package/dist/{core → platform}/deep-equal.js +2 -2
  136. package/dist/{transport → platform}/error-text.js +2 -2
  137. package/dist/runner-manifest.json +66 -46
  138. package/dist/shared-kernel/batch-cap.d.ts +4 -0
  139. package/dist/{core/wire.js → shared-kernel/batch-cap.js} +9 -26
  140. package/dist/{transport → shared-kernel}/framing.js +2 -2
  141. package/dist/{transport → shared-kernel}/wire-protocol.js +1 -1
  142. package/dist/testing/index.d.ts +1 -84
  143. package/dist/testing/index.js +1 -82
  144. package/package.json +9 -3
  145. package/dist/core/index.d.ts +0 -10
  146. package/dist/core/index.js +0 -6
  147. package/dist/core/reject-tail.d.ts +0 -13
  148. package/dist/core/reject-tail.js +0 -52
  149. package/dist/core/schema/schema-discovery.d.ts +0 -13
  150. package/dist/core/schema/schema-discovery.js +0 -51
  151. package/dist/scaffold/classify-transport.d.ts +0 -54
  152. package/dist/scaffold/classify-transport.js +0 -119
  153. /package/dist/{pending-directives → bounded-contexts/authoring/application/usecases/pending-directives}/index.d.ts +0 -0
  154. /package/dist/{pending-directives → bounded-contexts/authoring/application/usecases/pending-directives}/index.js +0 -0
  155. /package/dist/{pending-directives → bounded-contexts/authoring/application/usecases/pending-directives}/render.js +0 -0
  156. /package/dist/{core → bounded-contexts/authoring/domain/entities}/base-handle.d.ts +0 -0
  157. /package/dist/{core → bounded-contexts/authoring/domain/entities}/base-handle.js +0 -0
  158. /package/dist/{core → bounded-contexts/authoring/domain/entities}/handle-state.d.ts +0 -0
  159. /package/dist/{core → bounded-contexts/authoring/domain/entities}/handle-state.js +0 -0
  160. /package/dist/{core → bounded-contexts/authoring/domain/ports}/emit-rejection.d.ts +0 -0
  161. /package/dist/{core → bounded-contexts/authoring/domain/ports}/emit-rejection.js +0 -0
  162. /package/dist/{core → bounded-contexts/authoring/domain/ports}/engine-client.js +0 -0
  163. /package/dist/{commons → bounded-contexts/authoring/domain/services}/classify-content.d.ts +0 -0
  164. /package/dist/{commons → bounded-contexts/authoring/domain/services}/classify-content.js +0 -0
  165. /package/dist/{core → bounded-contexts/authoring/domain/services}/schema/schema-digest.d.ts +0 -0
  166. /package/dist/{core → bounded-contexts/authoring/domain/services}/schema/schema-digest.js +0 -0
  167. /package/dist/{core → bounded-contexts/authoring/domain/valueobjects}/authoring-error.d.ts +0 -0
  168. /package/dist/{core → bounded-contexts/authoring/domain/valueobjects}/dialect-error.d.ts +0 -0
  169. /package/dist/{core → bounded-contexts/authoring/domain/valueobjects}/dialect-error.js +0 -0
  170. /package/dist/{core → bounded-contexts/authoring/domain/valueobjects}/json-value.d.ts +0 -0
  171. /package/dist/{core → bounded-contexts/authoring/domain/valueobjects}/json-value.js +0 -0
  172. /package/dist/{core/schema → bounded-contexts/authoring/domain/valueobjects}/schema-model.d.ts +0 -0
  173. /package/dist/{core/schema → bounded-contexts/authoring/domain/valueobjects}/schema-model.js +0 -0
  174. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/angular/ops.d.ts +0 -0
  175. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/css/ast.d.ts +0 -0
  176. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/css/ast.js +0 -0
  177. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/css/ops.d.ts +0 -0
  178. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/json/ast.d.ts +0 -0
  179. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/json/ast.js +0 -0
  180. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/nestjs/ops.d.ts +0 -0
  181. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/react/ast.d.ts +0 -0
  182. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/react/ast.js +0 -0
  183. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/react/ops.d.ts +0 -0
  184. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/typescript/class-property.d.ts +0 -0
  185. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/typescript/import-order.d.ts +0 -0
  186. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/typescript/import-order.js +0 -0
  187. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/typescript/pack.d.ts +0 -0
  188. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/typescript/pack.js +0 -0
  189. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/yaml/ast.d.ts +0 -0
  190. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/yaml/ast.js +0 -0
  191. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/yaml/documents.d.ts +0 -0
  192. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/yaml/documents.js +0 -0
  193. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/yaml/presentation.d.ts +0 -0
  194. /package/dist/{dialects → bounded-contexts/authoring/infrastructure/out/dialects}/yaml/structural.d.ts +0 -0
  195. /package/dist/{testing → bounded-contexts/authoring/testing}/rejection-messages.d.ts +0 -0
  196. /package/dist/{testing → bounded-contexts/authoring/testing}/rejection-messages.js +0 -0
  197. /package/dist/{conformance → bounded-contexts/authoring/testing}/run-vehicle.js +0 -0
  198. /package/dist/{transport → bounded-contexts/runner-hosting/infrastructure/in}/bootstrap-bridge.d.ts +0 -0
  199. /package/dist/{transport → bounded-contexts/runner-hosting/infrastructure/in}/exit-codes.d.ts +0 -0
  200. /package/dist/{transport → bounded-contexts/runner-hosting/infrastructure/in}/factory-pointer.d.ts +0 -0
  201. /package/dist/{transport → bounded-contexts/runner-hosting/infrastructure/in}/single-instance-probe.d.ts +0 -0
  202. /package/dist/{core → platform}/deep-equal.d.ts +0 -0
  203. /package/dist/{transport → platform}/error-text.d.ts +0 -0
  204. /package/dist/{core → platform}/fs-errors.d.ts +0 -0
  205. /package/dist/{core → platform}/fs-errors.js +0 -0
  206. /package/dist/{transport → shared-kernel}/framing.d.ts +0 -0
  207. /package/dist/{transport → shared-kernel}/wire-protocol.d.ts +0 -0
@@ -1,8 +1,8 @@
1
1
  import { Node, SyntaxKind, ts, } from "ts-morph";
2
- import { dialectError } from "../../core/dialect-error.js";
3
- import { handlePathFor } from "../../core/dialect-handle.js";
4
- import { elementNameEcho } from "../../core/reject-tail.js";
5
- import { assertValidImportBinding, assertValidPropertyKey } from "../../core/jsx-name-validator.js";
2
+ import { dialectError } from "../../../../domain/valueobjects/dialect-error.js";
3
+ import { handlePathFor } from "../../../../domain/entities/dialect-handle.js";
4
+ import { elementNameEcho } from "../../../../domain/services/reject-tail.js";
5
+ import { assertValidImportBinding, assertValidPropertyKey } from "../../../../domain/services/identifier-names.js";
6
6
  import { parse } from "./ast.js";
7
7
  // Appends `item` after the last entry of an array or object literal, keeping its layout: one
8
8
  // line stays one line, a multi-line list gets a new line at the last entry's indentation, and
@@ -71,11 +71,17 @@ function assertLocator(locator) {
71
71
  assertValidPropertyKey(entries[0][0], "path");
72
72
  }
73
73
  }
74
+ // The extension the author's code is parsed as: that of the file it goes into, so JSX is
75
+ // accepted in `.tsx` and `.jsx`, and type syntax is not in `.jsx`.
76
+ function scriptExtension(node) {
77
+ const extension = node.getSourceFile().getExtension();
78
+ return extension === ".tsx" || extension === ".jsx" ? extension : ".ts";
79
+ }
74
80
  // The only element of `[text]`, or undefined when `text` is not exactly one plain element.
75
- function parseElement(text) {
81
+ function parseElement(text, extension) {
76
82
  let parsed;
77
83
  try {
78
- parsed = parse(`[${text}]`);
84
+ parsed = parse(`[${text}]`, extension);
79
85
  }
80
86
  catch {
81
87
  return undefined;
@@ -89,17 +95,17 @@ function parseElement(text) {
89
95
  return elements[0];
90
96
  }
91
97
  // Returns the element's parsed node once it is proven to be a single array element.
92
- function elementNode(element) {
98
+ function elementNode(element, extension) {
93
99
  if (typeof element === "string") {
94
100
  assertValidImportBinding(element, "element");
95
- return parseElement(element);
101
+ return parseElement(element, extension);
96
102
  }
97
103
  if (!isPlainObject(element) || !hasExactKeys(element, ["expression"]) || typeof element.expression !== "string") {
98
104
  throw dialectError(ELEMENT_SHAPE);
99
105
  }
100
106
  // Wrapping in brackets and requiring exactly one plain element blocks every breakout: a
101
107
  // closed bracket, a comma, or a comment that swallows `]` yields a different parse.
102
- const node = parseElement(element.expression.trim());
108
+ const node = parseElement(element.expression.trim(), extension);
103
109
  if (node === undefined)
104
110
  throw dialectError(EXPRESSION_RULE);
105
111
  return node;
@@ -124,12 +130,17 @@ export function tokensOf(node) {
124
130
  visit(node.compilerNode);
125
131
  return tokens.filter((token, index) => token !== "," || ![")", "]", "}"].includes(tokens[index + 1] ?? ""));
126
132
  }
127
- function sameTokens(a, b) {
133
+ export function sameTokens(a, b) {
128
134
  return a.length === b.length && a.every((token, index) => token === b[index]);
129
135
  }
136
+ // Tokens without a trailing `;`, so `b = 1` and `b = 1;` are the same declaration.
137
+ export function declarationTokens(node) {
138
+ const tokens = tokensOf(node);
139
+ return tokens.at(-1) === ";" ? tokens.slice(0, -1) : tokens;
140
+ }
130
141
  /** True when `node` and the validated `element` are the same code, compared token by token. */
131
142
  export function isSameElement(node, element) {
132
- return sameTokens(tokensOf(node), tokensOf(elementNode(element)));
143
+ return sameTokens(tokensOf(node), tokensOf(elementNode(element, scriptExtension(node))));
133
144
  }
134
145
  export function unwrap(node) {
135
146
  let current = node;
@@ -290,16 +301,19 @@ export function addArrayElement(ast, locator, element) {
290
301
  assertLocator(locator);
291
302
  appendArrayElement(ast, locator, element, `addArrayElement(${locatorEcho(locator)})`);
292
303
  }
293
- /** The validated source text of `element`; rejects like `addArrayElement` does. */
294
- export function elementText(element) {
295
- return elementNode(element).getText();
304
+ /**
305
+ * The validated source text of `element`, parsed as code of the file `ast` belongs to; rejects
306
+ * like `addArrayElement` does.
307
+ */
308
+ export function elementText(element, ast) {
309
+ return elementNode(element, ast === undefined ? ".ts" : scriptExtension(ast)).getText();
296
310
  }
297
311
  /**
298
312
  * `addArrayElement` for a dialect that builds `locator` itself: `label` heads the reject
299
313
  * tail in place of `addArrayElement(<locator>)`.
300
314
  */
301
315
  export function appendArrayElement(ast, locator, element, label) {
302
- const node = elementNode(element);
316
+ const node = elementNode(element, scriptExtension(ast));
303
317
  const item = node.getText();
304
318
  const fail = (reason) => {
305
319
  throw dialectError(`${label} on "${handlePathFor(ast)}" — ${reason}. Edit it with .modify().`);
@@ -28,12 +28,15 @@ export declare function detectNewLineKind(source: string): NewLineKind;
28
28
  * frozen contained-error prefix; this function's own thrown message is never surfaced
29
29
  * directly to the author.
30
30
  *
31
+ * `extension` sets the script kind, for author code parsed as the file it goes into would be; the
32
+ * dialect itself parses with the default.
33
+ *
31
34
  * Row-139 (stage-5b, executor-latitude, no REQ of its own): classification below reads off
32
35
  * `getSyntacticDiagnostics()`'s own diagnostic objects — never an assumption about a caught
33
36
  * error's own-enumerable-properties or call-stack shape. Verified already in this shape; no
34
37
  * heuristic-based classification exists in this function to sweep out.
35
38
  */
36
- export declare function parse(source: string): SourceFile;
39
+ export declare function parse(source: string, extension?: ".ts" | ".tsx" | ".jsx"): SourceFile;
37
40
  /**
38
41
  * Prints the live AST back to a string — the ONLY serialization point (ADR-0006's "serialize
39
42
  * once at flush", realised by the dialect handle's memoized lazy getter). Re-prepends a BOM
@@ -41,3 +44,4 @@ export declare function parse(source: string): SourceFile;
41
44
  * does not carry it.
42
45
  */
43
46
  export declare function print(ast: SourceFile): string;
47
+ export declare function omitsSemicolons(ast: SourceFile): boolean;
@@ -3,11 +3,11 @@
3
3
  // a fresh `Project` per parse so the setting can vary per source, never a module-level
4
4
  // singleton. No language-service formatter is ever invoked (REQ-TSD-02.3): this module calls
5
5
  // no `.formatText()`/language-service API anywhere.
6
- import { Project, NewLineKind, QuoteKind, IndentationText } from "ts-morph";
6
+ import { Node, Project, NewLineKind, QuoteKind, IndentationText } from "ts-morph";
7
7
  // In-memory-only path fed to ts-morph's virtual file system — never a real disk path; the
8
8
  // dialect handle (src/core/dialect-handle.ts) owns the AUTHOR-FACING path, this is purely an
9
9
  // internal identifier ts-morph's Project API requires.
10
- const VIRTUAL_PATH = "dialect-source.ts";
10
+ const VIRTUAL_STEM = "dialect-source";
11
11
  const BOM = "";
12
12
  // ts-morph's `SourceFile#getFullText()` does NOT round-trip a leading UTF-8 BOM (verified
13
13
  // empirically against the pinned ts-morph@28.0.0 — the design's "preserved by ts-morph
@@ -66,12 +66,15 @@ function detectQuoteKind(sourceFile) {
66
66
  * frozen contained-error prefix; this function's own thrown message is never surfaced
67
67
  * directly to the author.
68
68
  *
69
+ * `extension` sets the script kind, for author code parsed as the file it goes into would be; the
70
+ * dialect itself parses with the default.
71
+ *
69
72
  * Row-139 (stage-5b, executor-latitude, no REQ of its own): classification below reads off
70
73
  * `getSyntacticDiagnostics()`'s own diagnostic objects — never an assumption about a caught
71
74
  * error's own-enumerable-properties or call-stack shape. Verified already in this shape; no
72
75
  * heuristic-based classification exists in this function to sweep out.
73
76
  */
74
- export function parse(source) {
77
+ export function parse(source, extension = ".ts") {
75
78
  const startsWithBom = source.startsWith(BOM);
76
79
  const body = startsWithBom ? source.slice(BOM.length) : source;
77
80
  const project = new Project({
@@ -83,7 +86,7 @@ export function parse(source) {
83
86
  usePrefixAndSuffixTextForRename: false,
84
87
  },
85
88
  });
86
- const sourceFile = project.createSourceFile(VIRTUAL_PATH, body);
89
+ const sourceFile = project.createSourceFile(`${VIRTUAL_STEM}${extension}`, body);
87
90
  project.manipulationSettings.set({ quoteKind: detectQuoteKind(sourceFile) });
88
91
  if (startsWithBom)
89
92
  hadBom.set(sourceFile, true);
@@ -103,3 +106,18 @@ export function print(ast) {
103
106
  const text = ast.getFullText();
104
107
  return hadBom.get(ast) === true ? BOM + text : text;
105
108
  }
109
+ // Inserted statements keep the file's statement-terminating semicolon style: ts-morph always
110
+ // prints one, so it is dropped only when the file's terminable top-level statements mostly
111
+ // omit it (a file with no such statements, or a tie, keeps it).
112
+ export function omitsSemicolons(ast) {
113
+ const terminable = ast
114
+ .getStatements()
115
+ .filter((statement) => Node.isImportDeclaration(statement) ||
116
+ Node.isExportDeclaration(statement) ||
117
+ Node.isExportAssignment(statement) ||
118
+ Node.isVariableStatement(statement) ||
119
+ Node.isExpressionStatement(statement) ||
120
+ Node.isTypeAliasDeclaration(statement));
121
+ const terminated = terminable.filter((statement) => statement.getText().endsWith(";")).length;
122
+ return terminable.length - terminated > terminated;
123
+ }
@@ -1,10 +1,10 @@
1
1
  import { Node, SyntaxKind } from "ts-morph";
2
- import { dialectError } from "../../core/dialect-error.js";
3
- import { handlePathFor } from "../../core/dialect-handle.js";
4
- import { assertValidImportBinding } from "../../core/jsx-name-validator.js";
5
- import { elementNameEcho } from "../../core/reject-tail.js";
6
- import { elementText, tokensOf } from "./array-element.js";
7
- import { parse } from "./ast.js";
2
+ import { dialectError } from "../../../../domain/valueobjects/dialect-error.js";
3
+ import { handlePathFor } from "../../../../domain/entities/dialect-handle.js";
4
+ import { assertGrammar, assertNotDenylisted, assertValidImportBinding, IMPORT_BINDING_GRAMMAR } from "../../../../domain/services/identifier-names.js";
5
+ import { elementNameEcho } from "../../../../domain/services/reject-tail.js";
6
+ import { declarationTokens, elementText, sameTokens } from "./array-element.js";
7
+ import { omitsSemicolons, parse } from "./ast.js";
8
8
  const OPTIONS_SHAPE = '`options` must be { scope?, readonly? } with scope "public", "protected" or "private" — fix the options, or use ' +
9
9
  "`.modify()` to make this edit directly.";
10
10
  export function assertClassPropertyOptions(options) {
@@ -18,20 +18,13 @@ export function assertClassPropertyOptions(options) {
18
18
  if (!valid)
19
19
  throw dialectError(OPTIONS_SHAPE);
20
20
  }
21
- function declarationOf(property) {
21
+ function declarationOf(property, semicolon) {
22
22
  const modifiers = [property.scope, property.readonly ? "readonly" : undefined].filter((m) => m !== undefined);
23
- return [...modifiers, `${property.name} = ${property.initializer};`].join(" ");
24
- }
25
- // Tokens without a trailing `;`, so `b = 1` and `b = 1;` are the same declaration.
26
- function declarationTokens(node) {
27
- const tokens = tokensOf(node);
28
- return tokens.at(-1) === ";" ? tokens.slice(0, -1) : tokens;
23
+ return [...modifiers, `${property.name} = ${property.initializer}${semicolon ? ";" : ""}`].join(" ");
29
24
  }
30
25
  function sameDeclaration(member, text) {
31
26
  const parsed = parse(`class X {\n${text}\n}`).getClassOrThrow("X").getMembers()[0];
32
- const a = declarationTokens(member);
33
- const b = declarationTokens(parsed);
34
- return a.length === b.length && a.every((token, index) => token === b[index]);
27
+ return sameTokens(declarationTokens(member), declarationTokens(parsed));
35
28
  }
36
29
  /**
37
30
  * Inserts `property` into `cls`: after its last property, else before its first member, else
@@ -39,7 +32,7 @@ function sameDeclaration(member, text) {
39
32
  * any other member with that name rejects through `fail`.
40
33
  */
41
34
  export function insertClassProperty(ast, cls, property, fail) {
42
- const text = declarationOf(property);
35
+ const text = declarationOf(property, !omitsSemicolons(ast));
43
36
  const members = cls.getMembers();
44
37
  const named = members.filter((member) => Node.hasName(member) && member.getName() === property.name);
45
38
  if (named.length > 0) {
@@ -83,9 +76,11 @@ export function insertClassProperty(ast, cls, property, fail) {
83
76
  */
84
77
  export function addClassProperty(ast, className, name, initializer, options) {
85
78
  assertValidImportBinding(className, "className");
86
- assertValidImportBinding(name, "name");
79
+ // A reserved word is a valid property name (`default = 2`), so only the grammar and the denylist apply.
80
+ assertGrammar("name", name, IMPORT_BINDING_GRAMMAR, "be a valid JavaScript identifier");
81
+ assertNotDenylisted("name", name);
87
82
  assertClassPropertyOptions(options);
88
- const value = elementText({ expression: initializer });
83
+ const value = elementText({ expression: initializer }, ast);
89
84
  const fail = (reason) => {
90
85
  throw dialectError(`addClassProperty("${elementNameEcho(className)}", "${elementNameEcho(name)}") on "${handlePathFor(ast)}" — ${reason}. Edit it with .modify().`);
91
86
  };
@@ -0,0 +1,53 @@
1
+ import type { SourceFile } from "ts-morph";
2
+ import { type Handle } from "../../../../domain/services/define-dialect.ts";
3
+ import type { ArrayElement, ArrayLocator } from "./array-element.ts";
4
+ import type { ClassPropertyOptions } from "./class-property.ts";
5
+ export * as astLibrary from "ts-morph";
6
+ type TypeScriptOps = {
7
+ addImport: (ast: SourceFile, name: string, from: string, options?: {
8
+ position?: "sorted";
9
+ }) => void;
10
+ addDefaultImport: (ast: SourceFile, name: string, from: string) => void;
11
+ addNamespaceImport: (ast: SourceFile, name: string, from: string) => void;
12
+ addTypeImport: (ast: SourceFile, name: string, from: string) => void;
13
+ addSideEffectImport: (ast: SourceFile, from: string) => void;
14
+ addReExport: (ast: SourceFile, name: string, from: string) => void;
15
+ addExportAll: (ast: SourceFile, from: string, options?: {
16
+ as?: string;
17
+ }) => void;
18
+ addFunction: (ast: SourceFile, name: string, source: string, options?: {
19
+ export?: boolean;
20
+ }) => void;
21
+ addVariable: (ast: SourceFile, name: string, initializer: string, options?: {
22
+ export?: boolean;
23
+ kind?: "const" | "let" | "var";
24
+ }) => void;
25
+ addClass: (ast: SourceFile, name: string, source: string, options?: {
26
+ export?: boolean;
27
+ }) => void;
28
+ removeImport: (ast: SourceFile, name: string, from: string) => void;
29
+ removeExport: (ast: SourceFile, name: string, from: string) => void;
30
+ removeExportAll: (ast: SourceFile, from: string, options?: {
31
+ as?: string;
32
+ }) => void;
33
+ addArrayElement: (ast: SourceFile, locator: ArrayLocator, element: ArrayElement) => void;
34
+ addClassProperty: (ast: SourceFile, className: string, name: string, initializer: string, options?: ClassPropertyOptions) => void;
35
+ sortImports: (ast: SourceFile) => void;
36
+ };
37
+ /**
38
+ * Opens a TypeScript file for dialect-aware editing — the dialect's entry verb into a Session
39
+ * (REQ-DG-01.2). Returns an awaitable, chainable `Handle` exposing the universal `.modify()`
40
+ * escape hatch plus the dialect's named ops (`addImport`, `addDefaultImport`,
41
+ * `addNamespaceImport`, `addTypeImport`, `addSideEffectImport`, `addReExport`, `addExportAll`,
42
+ * `addFunction`, `addVariable`, `addClass`, `removeImport`, `removeExport`, `removeExportAll`,
43
+ * `addArrayElement`, `addClassProperty`). Reads route through `Session.read` only (REQ-MC-03); edits
44
+ * coalesce into a single `modify` at flush (REQ-MC-01/02).
45
+ *
46
+ * @example
47
+ * import * as ts from "@pbuilder/sdk/typescript";
48
+ *
49
+ * export const run = async () => {
50
+ * await ts.find("src/index.ts").addImport("readFileSync", "node:fs");
51
+ * };
52
+ */
53
+ export declare function find(path: string): Handle<"found", SourceFile, TypeScriptOps>;
@@ -0,0 +1,37 @@
1
+ // S-002: the TypeScript dialect module — `@pbuilder/sdk/typescript` (REQ-TSD-01, frozen
2
+ // subpath, ADR-0014 amendment). Composes the sanctioned kit surface ONLY
3
+ // (`defineDialect`/`defineOpPack`/`withOps` from `../../core/define-dialect.ts`) — no
4
+ // port-internal machinery is imported anywhere in this tree (REQ-DG-04.1, see
5
+ // test/fitness/fit-08-no-kit-bleed.test.ts and fit-10-engine-client-port-guard.test.ts).
6
+ // Namespace import surface (ADR-0003): `import * as ts from "@pbuilder/sdk/typescript"`,
7
+ // then `ts.find(path)`.
8
+ import { defineDialect, defineOpPack, withOps } from "../../../../domain/services/define-dialect.js";
9
+ import { parse, print } from "./ast.js";
10
+ import { typescriptOps } from "./pack.js";
11
+ export * as astLibrary from "ts-morph";
12
+ const opsPack = defineOpPack(typescriptOps);
13
+ const baseDialect = defineDialect({
14
+ extensions: [".ts"],
15
+ ast: { parse, print },
16
+ ops: {},
17
+ });
18
+ const typescriptDialect = withOps(baseDialect, opsPack);
19
+ /**
20
+ * Opens a TypeScript file for dialect-aware editing — the dialect's entry verb into a Session
21
+ * (REQ-DG-01.2). Returns an awaitable, chainable `Handle` exposing the universal `.modify()`
22
+ * escape hatch plus the dialect's named ops (`addImport`, `addDefaultImport`,
23
+ * `addNamespaceImport`, `addTypeImport`, `addSideEffectImport`, `addReExport`, `addExportAll`,
24
+ * `addFunction`, `addVariable`, `addClass`, `removeImport`, `removeExport`, `removeExportAll`,
25
+ * `addArrayElement`, `addClassProperty`). Reads route through `Session.read` only (REQ-MC-03); edits
26
+ * coalesce into a single `modify` at flush (REQ-MC-01/02).
27
+ *
28
+ * @example
29
+ * import * as ts from "@pbuilder/sdk/typescript";
30
+ *
31
+ * export const run = async () => {
32
+ * await ts.find("src/index.ts").addImport("readFileSync", "node:fs");
33
+ * };
34
+ */
35
+ export function find(path) {
36
+ return typescriptDialect.find(path);
37
+ }
@@ -8,7 +8,7 @@ import { type SourceFile } from "ts-morph";
8
8
  * 0. Validation (REQ-TSD-13, runs FIRST, strictly before Step 1): `name` MUST be a valid
9
9
  * plain-JS identifier, MUST NOT be a reserved or strict-mode-restricted word, and MUST
10
10
  * NOT be a denylisted name (`assertValidImportBinding`, reused verbatim from
11
- * `src/core/jsx-name-validator.ts`) — REJECTS via a PATH-LESS `dialectError` before Step
11
+ * `domain/services/identifier-names.ts`) — REJECTS via a PATH-LESS `dialectError` before Step
12
12
  * 1/2/3/4 ever evaluate `name`, even when `name` would ALSO collide under Step 2
13
13
  * (REQ-TSD-13.6, precedence pinned: validation wins, never the collision message).
14
14
  * 1. Already-bound (idempotency, SAME module only): if an EXISTING declaration for `from`
@@ -70,6 +70,11 @@ import { type SourceFile } from "ts-morph";
70
70
  export declare function addImport(ast: SourceFile, name: string, from: string, options?: {
71
71
  position?: "sorted";
72
72
  }): void;
73
+ /**
74
+ * `addImport`'s steps 1-4 for a `name` already validated, rejecting a taken name under `opName`:
75
+ * the op the author called, which may add the import on the author's behalf.
76
+ */
77
+ export declare function importBinding(ast: SourceFile, opName: string, name: string, from: string, sorted?: boolean): void;
73
78
  /**
74
79
  * Adds `import name from "from";` (V2 REQ-TSD-13). `name` is validated first, as in
75
80
  * `addImport`. A no-op when `from` already has the default import `name`. Rejects when `from`
@@ -1,7 +1,7 @@
1
1
  // S-002: the `addImport` named op (REQ-TSD-01, frozen call signature
2
2
  // `addImport(name: string, from: string)`, design §4.4).
3
3
  //
4
- // S-001: `addFunction` (REQ-TSD-09) + the shared `assertNoCollision` predicate it (and
4
+ // S-001: `addFunction` (REQ-TSD-09) + the shared `addDeclaration` predicate it (and
5
5
  // S-003's addVariable/addClass) reuse (design §4.5 ADR-0039).
6
6
  //
7
7
  // S-003: `addVariable` (REQ-TSD-10) + `addClass` (REQ-TSD-11) — same insert-mechanism and
@@ -14,26 +14,28 @@
14
14
  //
15
15
  // ts-addimport-collision/S-001: Step 2 (file-wide collision reject) lands here, strictly
16
16
  // AFTER Step 1 (REQ-TSD-01.24, mutant-kill ordering invariant) and before Step 3/4.
17
- // `isValueNamespaceClaimed` is EXTRACTED from `assertNoCollision` below (design §4.5 ADR-01)
18
- // and consumed by BOTH `assertNoCollision` (behaviour-preserving, siblings' own import-scan
17
+ // `isValueNamespaceClaimed` is EXTRACTED from `addDeclaration` below (design §4.5 ADR-01)
18
+ // and consumed by BOTH `addDeclaration` (behaviour-preserving, siblings' own import-scan
19
19
  // posture UNCHANGED) and `addImport`'s new Step 2 (design §4.4 — TS house-style tail, built
20
- // inline, NOT reusing `assertNoCollision`'s own message: "two bindings sharing a name" here,
20
+ // inline, NOT reusing `addDeclaration`'s own message: "two bindings sharing a name" here,
21
21
  // vs "two value declarations sharing a name" there — `addImport`'s collision surface also
22
22
  // fires on import-vs-import and type-only claims, which are not value declarations, F10).
23
23
  //
24
24
  // ts-addimport-collision/S-002: REQ-TSD-13's injection-safety validation gate lands here —
25
- // `assertValidImportBinding` (reused verbatim from `src/core/jsx-name-validator.ts`, ADR-02)
25
+ // `assertValidImportBinding` (reused verbatim from `domain/services/identifier-names.ts`, ADR-02)
26
26
  // runs INLINE as `addImport`'s first statement, strictly BEFORE Step 1/2/3/4 ever evaluate
27
27
  // `name` (REQ-TSD-13.6 precedence pin). Its PATH-LESS reject shape is deliberately distinct
28
28
  // from Step 2's path-ful `dialectError` tail below — see `addImport`'s own JSDoc.
29
- import { Node, SyntaxKind, } from "ts-morph";
30
- import { dialectError } from "../../core/dialect-error.js";
31
- import { handlePathFor } from "../../core/dialect-handle.js";
32
- import { elementNameEcho } from "../../core/reject-tail.js";
33
- // A misnomer surviving from its JSX-only origin (`jsx-name-validator.ts`) — this dialect is
34
- // its first non-JSX consumer, sharpening ARCH-2's now-realised "one consumer" debt (ADR-02).
35
- import { assertValidImportBinding } from "../../core/jsx-name-validator.js";
29
+ import { SyntaxKind, } from "ts-morph";
30
+ import { dialectError } from "../../../../domain/valueobjects/dialect-error.js";
31
+ import { handlePathFor } from "../../../../domain/entities/dialect-handle.js";
32
+ import { elementNameEcho, nameRuleTail } from "../../../../domain/services/reject-tail.js";
33
+ // The identifier rules every dialect shares; the JSX-only grammars live in the React adapter
34
+ // (ARCH-2, ADR-0071).
35
+ import { assertValidImportBinding, assertValidLookupName } from "../../../../domain/services/identifier-names.js";
36
36
  import { closeGapAfter, sortedPlacement, sortedSpecifierIndex } from "./import-order.js";
37
+ import { omitsSemicolons, parse } from "./ast.js";
38
+ import { declarationTokens, sameTokens } from "./array-element.js";
37
39
  // Collects every local name a single declaration binds, across all three clause shapes at
38
40
  // once (a declaration can carry a default AND a named clause simultaneously, e.g.
39
41
  // `import Def, { B } from "m"`). Set-key-safety clause: names are compared via
@@ -101,7 +103,7 @@ function isNonTypeOnlyNamedImportClause(decl) {
101
103
  return namedBindings !== undefined && namedBindings.getKind() === SyntaxKind.NamedImports;
102
104
  }
103
105
  // ADR-0039 collision-namespace pin (owner ruling #4), EXTRACTED (S-001, design §4.5 ADR-01)
104
- // from `assertNoCollision` below so both it and `addImport`'s Step 2 share ONE predicate: a
106
+ // from `addDeclaration` below so both it and `addImport`'s Step 2 share ONE predicate: a
105
107
  // top-level VALUE-NAMESPACE declaration (function/const/let/var/class/enum/namespace) under
106
108
  // `name` collides; `type`/`interface` are exempt (legal TS coexistence). Syntactic search
107
109
  // only (no language service, REQ-TSD-02.3) — SourceFile-wide, not scope-aware.
@@ -116,9 +118,7 @@ function isValueNamespaceClaimed(ast, name) {
116
118
  // `ExpressionStatement`s starting at statement 0, stopping at the first non-directive
117
119
  // statement (a directive is only live when first-in-scope; a string literal appearing
118
120
  // later in the file is an ordinary expression statement, not a directive). A shebang is
119
- // SourceFile leading trivia, never a statement, so it never contributes here — the Create
120
- // branch below falls through to its pre-existing `addImportDeclaration` path for a shebang
121
- // file, leaving REQ-TSD-01.33's fail-closed containment untouched (ADR-03).
121
+ // SourceFile leading trivia, never a statement, so it never contributes here.
122
122
  function leadingDirectiveCount(ast) {
123
123
  let count = 0;
124
124
  for (const statement of ast.getStatements()) {
@@ -155,7 +155,7 @@ function directiveInsertIndex(ast, directiveCount) {
155
155
  * 0. Validation (REQ-TSD-13, runs FIRST, strictly before Step 1): `name` MUST be a valid
156
156
  * plain-JS identifier, MUST NOT be a reserved or strict-mode-restricted word, and MUST
157
157
  * NOT be a denylisted name (`assertValidImportBinding`, reused verbatim from
158
- * `src/core/jsx-name-validator.ts`) — REJECTS via a PATH-LESS `dialectError` before Step
158
+ * `domain/services/identifier-names.ts`) — REJECTS via a PATH-LESS `dialectError` before Step
159
159
  * 1/2/3/4 ever evaluate `name`, even when `name` would ALSO collide under Step 2
160
160
  * (REQ-TSD-13.6, precedence pinned: validation wins, never the collision message).
161
161
  * 1. Already-bound (idempotency, SAME module only): if an EXISTING declaration for `from`
@@ -224,6 +224,13 @@ export function addImport(ast, name, from, options) {
224
224
  throw dialectError(`addImport("${name}") on "${handlePathFor(ast)}" — \`position\` must be "sorted" or omitted. ` +
225
225
  "Fix the option, or edit the file with .modify().");
226
226
  }
227
+ importBinding(ast, "addImport", name, from, sorted);
228
+ }
229
+ /**
230
+ * `addImport`'s steps 1-4 for a `name` already validated, rejecting a taken name under `opName`:
231
+ * the op the author called, which may add the import on the author's behalf.
232
+ */
233
+ export function importBinding(ast, opName, name, from, sorted = false) {
227
234
  // Single pass: one `getImportDeclarations()` call, one `boundNamesIn` per declaration —
228
235
  // Step 1 and Step 2 below both read from `declarationBoundNames` instead of each re-walking
229
236
  // the AST. Step 1 still fully evaluates (and early-returns) before Step 2 ever runs
@@ -241,7 +248,7 @@ export function addImport(ast, name, from, options) {
241
248
  const claimed = declarationBoundNames.some(([, bound]) => bound.some((b) => b.localName === name)) ||
242
249
  isValueNamespaceClaimed(ast, name);
243
250
  if (claimed)
244
- throw claimedBindingError(ast, "addImport", name);
251
+ throw claimedBindingError(ast, opName, name);
245
252
  const mergeTarget = declarationsForModule.find(isNonTypeOnlyNamedImportClause);
246
253
  if (mergeTarget !== undefined) {
247
254
  if (sorted)
@@ -279,24 +286,24 @@ function insertImport(ast, structure, index) {
279
286
  const inserted = index !== undefined
280
287
  ? ast.insertImportDeclaration(index, structure)
281
288
  : directiveCount === 0
282
- ? ast.addImportDeclaration(structure)
289
+ ? addFirstImport(ast, structure)
283
290
  : ast.insertImportDeclaration(directiveInsertIndex(ast, directiveCount), structure);
284
- return dropSemicolon ? inserted.replaceWithText(inserted.getText().slice(0, -1)) : inserted;
285
- }
286
- // A fresh import keeps the file's statement-terminating semicolon style: ts-morph always
287
- // prints one, so it is dropped only when the file's terminable top-level statements mostly
288
- // omit it (a file with no such statements, or a tie, keeps it).
289
- function omitsSemicolons(ast) {
290
- const terminable = ast
291
- .getStatements()
292
- .filter((statement) => Node.isImportDeclaration(statement) ||
293
- Node.isExportDeclaration(statement) ||
294
- Node.isExportAssignment(statement) ||
295
- Node.isVariableStatement(statement) ||
296
- Node.isExpressionStatement(statement) ||
297
- Node.isTypeAliasDeclaration(statement));
298
- const terminated = terminable.filter((statement) => statement.getText().endsWith(";")).length;
299
- return terminable.length - terminated > terminated;
291
+ return dropSemicolon ? withoutSemicolon(inserted) : inserted;
292
+ }
293
+ function withoutSemicolon(statement) {
294
+ return statement.replaceWithText(statement.getText().slice(0, -1));
295
+ }
296
+ // ts-morph cannot put the first import of a file below a shebang: it throws when code follows the
297
+ // shebang and drops the shebang when nothing does. The shebang is lifted out, the import added to
298
+ // the rest, and the shebang put back above it.
299
+ function addFirstImport(ast, structure) {
300
+ const shebang = /^#![^\n]*\n?/.exec(ast.getFullText())?.[0];
301
+ if (shebang === undefined || ast.getImportDeclarations().length > 0)
302
+ return ast.addImportDeclaration(structure);
303
+ ast.removeText(0, shebang.length);
304
+ ast.addImportDeclaration(structure);
305
+ ast.insertText(0, shebang.endsWith("\n") ? shebang : `${shebang}\n`);
306
+ return ast.getImportDeclarations()[0];
300
307
  }
301
308
  // The value-bound (not whole-declaration type-only) declarations importing `from`.
302
309
  function valueImportsOf(ast, from) {
@@ -406,9 +413,28 @@ function exportPrefixFor(options) {
406
413
  // message (design §4.4's pinned "on {path}" clause) — position-independent (keyed by the
407
414
  // live AST instance, not a runtime argument position), so it can never collide with `name`/
408
415
  // `options` regardless of which trailing args the author omitted.
409
- function assertNoCollision(ast, name, opName) {
410
- if (!isBindingClaimed(ast, name))
411
- return;
416
+ // Appends the declaration `text` of `name`. When `name` is taken, a top-level statement that is
417
+ // `text` token for token (trivia and a trailing `;` aside) leaves the file as it is, so running
418
+ // the op again is a no-op; any other binding of `name` rejects.
419
+ function addDeclaration(ast, name, opName, text) {
420
+ if (isBindingClaimed(ast, name)) {
421
+ if (declaresIdentically(ast, text))
422
+ return;
423
+ throwCollision(ast, name, opName);
424
+ }
425
+ ast.addStatements(text);
426
+ }
427
+ function declaresIdentically(ast, text) {
428
+ let written;
429
+ try {
430
+ written = declarationTokens(parse(text).getStatements()[0]);
431
+ }
432
+ catch {
433
+ return false;
434
+ }
435
+ return ast.getStatements().some((statement) => sameTokens(declarationTokens(statement), written));
436
+ }
437
+ function throwCollision(ast, name, opName) {
412
438
  throw dialectError(`${opName}("${name}") on "${handlePathFor(ast)}" — a value or import binding named "${name}" already exists; ` +
413
439
  `TypeScript forbids two value declarations sharing a name. Rename or remove the existing one, or edit it with .modify().`);
414
440
  }
@@ -428,8 +454,7 @@ function assertNoCollision(ast, name, opName) {
428
454
  */
429
455
  export function addFunction(ast, name, source, options) {
430
456
  assertValidImportBinding(name);
431
- assertNoCollision(ast, name, "addFunction");
432
- ast.addStatements(`${exportPrefixFor(options)}function ${name}${source}`);
457
+ addDeclaration(ast, name, "addFunction", `${exportPrefixFor(options)}function ${name}${source}`);
433
458
  }
434
459
  /**
435
460
  * Inserts a new top-level variable declaration `{export }{kind} {name} = {initializer};` at
@@ -450,8 +475,7 @@ export function addVariable(ast, name, initializer, options) {
450
475
  throw dialectError(`addVariable("${name}") on "${handlePathFor(ast)}" — \`kind\` must be "const", "let", or "var". ` +
451
476
  "Fix the option, or edit the file with .modify().");
452
477
  }
453
- assertNoCollision(ast, name, "addVariable");
454
- ast.addStatements(`${exportPrefixFor(options)}${kind} ${name} = ${initializer};`);
478
+ addDeclaration(ast, name, "addVariable", `${exportPrefixFor(options)}${kind} ${name} = ${initializer}${omitsSemicolons(ast) ? "" : ";"}`);
455
479
  }
456
480
  /**
457
481
  * Inserts a new top-level class declaration `{export }class {name} {\n{source}\n}` at the
@@ -469,8 +493,7 @@ export function addVariable(ast, name, initializer, options) {
469
493
  */
470
494
  export function addClass(ast, name, source, options) {
471
495
  assertValidImportBinding(name);
472
- assertNoCollision(ast, name, "addClass");
473
- ast.addStatements(`${exportPrefixFor(options)}class ${name} {\n${source}\n}`);
496
+ addDeclaration(ast, name, "addClass", `${exportPrefixFor(options)}class ${name} {\n${source}\n}`);
474
497
  }
475
498
  /**
476
499
  * Removes the named binding from `from`'s import clause (REQ-TSD-08). Idempotent: an
@@ -492,7 +515,7 @@ export function addClass(ast, name, source, options) {
492
515
  * is first-match-only. Sibling declarations from the same module are never touched.
493
516
  */
494
517
  export function removeImport(ast, name, from) {
495
- assertValidImportBinding(name);
518
+ assertValidLookupName(name);
496
519
  const decls = ast.getImportDeclarations().filter((d) => d.getModuleSpecifierValue() === from);
497
520
  for (const decl of decls) {
498
521
  const namedImports = decl.getNamedImports();
@@ -561,10 +584,27 @@ function assertNotExported(ast, name, opName) {
561
584
  throw dialectError(`${opName}("${echoedName}") on "${handlePathFor(ast)}" — the file already exports a binding named "${echoedName}"; ` +
562
585
  "TypeScript forbids two exports sharing a name. Rename or remove the existing one, or edit it with .modify().");
563
586
  }
587
+ function addExport(ast, structure) {
588
+ const dropSemicolon = omitsSemicolons(ast);
589
+ const added = ast.addExportDeclaration(structure);
590
+ if (dropSemicolon)
591
+ withoutSemicolon(added);
592
+ }
564
593
  function exportsOf(ast, from) {
565
594
  return ast.getExportDeclarations().filter((decl) => decl.getModuleSpecifierValue() === from);
566
595
  }
567
596
  // `export * from "m"` when `as` is undefined, `export * as ns from "m"` when it is "ns".
597
+ // An `as` that is present is a name like any other: `null` or another non-string rejects instead of
598
+ // reading as the bare `export *` form.
599
+ function namespaceExportName(options, assertName) {
600
+ const as = options?.as;
601
+ if (as === undefined)
602
+ return undefined;
603
+ if (typeof as !== "string")
604
+ throw dialectError(nameRuleTail("as", "be a valid JavaScript identifier"));
605
+ assertName(as, "as");
606
+ return as;
607
+ }
568
608
  function isExportAll(decl, as) {
569
609
  if (decl.isTypeOnly())
570
610
  return false;
@@ -591,7 +631,7 @@ export function addReExport(ast, name, from) {
591
631
  mergeTarget.addNamedExport(name);
592
632
  return;
593
633
  }
594
- ast.addExportDeclaration({ moduleSpecifier: from, namedExports: [name] });
634
+ addExport(ast, { moduleSpecifier: from, namedExports: [name] });
595
635
  }
596
636
  /**
597
637
  * Adds `export * from "from";`, or `export * as ns from "from";` with `{ as: "ns" }` (V2
@@ -600,14 +640,12 @@ export function addReExport(ast, name, from) {
600
640
  * exports it.
601
641
  */
602
642
  export function addExportAll(ast, from, options) {
603
- const as = options?.as;
604
- if (as !== undefined)
605
- assertValidImportBinding(as);
643
+ const as = namespaceExportName(options, assertValidImportBinding);
606
644
  if (exportsOf(ast, from).some((decl) => isExportAll(decl, as)))
607
645
  return;
608
646
  if (as !== undefined)
609
647
  assertNotExported(ast, as, "addExportAll");
610
- ast.addExportDeclaration(as === undefined ? { moduleSpecifier: from } : { moduleSpecifier: from, namespaceExport: as });
648
+ addExport(ast, as === undefined ? { moduleSpecifier: from } : { moduleSpecifier: from, namespaceExport: as });
611
649
  }
612
650
  /**
613
651
  * Removes the re-export of `name` from `export { … } from "from"` (V2 REQ-TSD-19), deleting
@@ -616,7 +654,7 @@ export function addExportAll(ast, from, options) {
616
654
  * `export *` statements are never touched — see `removeExportAll`.
617
655
  */
618
656
  export function removeExport(ast, name, from) {
619
- assertValidImportBinding(name);
657
+ assertValidLookupName(name);
620
658
  for (const decl of exportsOf(ast, from)) {
621
659
  const namedExports = decl.getNamedExports();
622
660
  const specifier = namedExports.find((named) => named.getName() === name);
@@ -636,9 +674,7 @@ export function removeExport(ast, name, from) {
636
674
  * form only removes itself; an absent statement is a no-op.
637
675
  */
638
676
  export function removeExportAll(ast, from, options) {
639
- const as = options?.as;
640
- if (as !== undefined)
641
- assertValidImportBinding(as);
677
+ const as = namespaceExportName(options, assertValidLookupName);
642
678
  exportsOf(ast, from)
643
679
  .find((decl) => isExportAll(decl, as))
644
680
  ?.remove();