@distilled.cloud/core 1.0.0-rc.17 → 1.0.0-rc.18

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 (259) hide show
  1. package/lib/_bundle/base.js +2 -2
  2. package/lib/_bundle/base.js.map +1 -1
  3. package/lib/_bundle/graphql.js +2 -2
  4. package/lib/_bundle/graphql.js.map +1 -1
  5. package/lib/_bundle/rest.js +1 -1
  6. package/lib/_bundle/rest.js.map +1 -1
  7. package/lib/annotations.d.ts +15 -0
  8. package/lib/annotations.d.ts.map +1 -0
  9. package/lib/annotations.js +2 -0
  10. package/lib/annotations.js.map +1 -0
  11. package/lib/api.d.ts +15 -0
  12. package/lib/api.d.ts.map +1 -1
  13. package/lib/api.js +1 -1
  14. package/lib/category.d.ts.map +1 -1
  15. package/lib/config.d.ts +54 -13
  16. package/lib/config.d.ts.map +1 -1
  17. package/lib/config.js +1 -1
  18. package/lib/debug.d.ts.map +1 -1
  19. package/lib/error-category.d.ts.map +1 -1
  20. package/lib/errors.d.ts +2 -13
  21. package/lib/errors.d.ts.map +1 -1
  22. package/lib/errors.js +1 -1
  23. package/lib/graphql.d.ts +14 -0
  24. package/lib/graphql.d.ts.map +1 -1
  25. package/lib/index.d.ts +3 -2
  26. package/lib/index.d.ts.map +1 -1
  27. package/lib/index.js +1 -0
  28. package/lib/pagination.d.ts +34 -2
  29. package/lib/pagination.d.ts.map +1 -1
  30. package/lib/pagination.js +1 -1
  31. package/lib/protocol-http.d.ts +30 -6
  32. package/lib/protocol-http.d.ts.map +1 -1
  33. package/lib/protocol-http.js +1 -1
  34. package/lib/protocol-rest.d.ts +53 -39
  35. package/lib/protocol-rest.d.ts.map +1 -1
  36. package/lib/protocol-rest.js +1 -1
  37. package/lib/response-validation.d.ts +4 -3
  38. package/lib/response-validation.d.ts.map +1 -1
  39. package/lib/schema-lite-typed.js +1 -2
  40. package/lib/telemetry-debug.d.ts +14 -0
  41. package/lib/telemetry-debug.d.ts.map +1 -0
  42. package/lib/telemetry-debug.js +2 -0
  43. package/lib/telemetry-debug.js.map +1 -0
  44. package/lib/telemetry-hooks.d.ts +32 -0
  45. package/lib/telemetry-hooks.d.ts.map +1 -0
  46. package/lib/telemetry-hooks.js +2 -0
  47. package/lib/telemetry-hooks.js.map +1 -0
  48. package/lib/telemetry-host-rules.d.ts +23 -0
  49. package/lib/telemetry-host-rules.d.ts.map +1 -0
  50. package/lib/telemetry-host-rules.js +2 -0
  51. package/lib/telemetry-host-rules.js.map +1 -0
  52. package/lib/telemetry-lambda-context.d.ts +17 -0
  53. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  54. package/lib/telemetry-lambda-context.js +2 -0
  55. package/lib/telemetry-lambda-context.js.map +1 -0
  56. package/lib/telemetry-message-context.d.ts +52 -0
  57. package/lib/telemetry-message-context.d.ts.map +1 -0
  58. package/lib/telemetry-message-context.js +2 -0
  59. package/lib/telemetry-message-context.js.map +1 -0
  60. package/lib/telemetry-metrics.d.ts +6 -0
  61. package/lib/telemetry-metrics.d.ts.map +1 -0
  62. package/lib/telemetry-metrics.js +2 -0
  63. package/lib/telemetry-metrics.js.map +1 -0
  64. package/lib/telemetry-name-template.d.ts +13 -0
  65. package/lib/telemetry-name-template.d.ts.map +1 -0
  66. package/lib/telemetry-name-template.js +2 -0
  67. package/lib/telemetry-name-template.js.map +1 -0
  68. package/lib/telemetry-stream.d.ts +9 -0
  69. package/lib/telemetry-stream.d.ts.map +1 -0
  70. package/lib/telemetry-stream.js +2 -0
  71. package/lib/telemetry-stream.js.map +1 -0
  72. package/lib/telemetry-xray.d.ts +28 -0
  73. package/lib/telemetry-xray.d.ts.map +1 -0
  74. package/lib/telemetry-xray.js +2 -0
  75. package/lib/telemetry-xray.js.map +1 -0
  76. package/lib/telemetry.d.ts +269 -0
  77. package/lib/telemetry.d.ts.map +1 -0
  78. package/lib/telemetry.js +3 -0
  79. package/lib/telemetry.js.map +1 -0
  80. package/package.json +1 -3
  81. package/src/annotations.ts +37 -0
  82. package/src/api.ts +123 -24
  83. package/src/category.ts +21 -22
  84. package/src/config.ts +58 -29
  85. package/src/debug.ts +9 -6
  86. package/src/error-category.ts +12 -14
  87. package/src/errors.ts +7 -7
  88. package/src/graphql.ts +123 -18
  89. package/src/index.ts +3 -2
  90. package/src/pagination.ts +119 -6
  91. package/src/protocol-http.ts +63 -43
  92. package/src/protocol-rest.ts +201 -140
  93. package/src/response-validation.ts +4 -3
  94. package/src/telemetry-debug.ts +135 -0
  95. package/src/telemetry-hooks.ts +33 -0
  96. package/src/telemetry-host-rules.ts +39 -0
  97. package/src/telemetry-lambda-context.ts +46 -0
  98. package/src/telemetry-message-context.ts +170 -0
  99. package/src/telemetry-metrics.ts +69 -0
  100. package/src/telemetry-name-template.ts +26 -0
  101. package/src/telemetry-stream.ts +91 -0
  102. package/src/telemetry-xray.ts +66 -0
  103. package/src/telemetry.ts +768 -0
  104. package/lib/codegen/boolean-string-enums.d.ts +0 -36
  105. package/lib/codegen/boolean-string-enums.d.ts.map +0 -1
  106. package/lib/codegen/boolean-string-enums.js +0 -147
  107. package/lib/codegen/boolean-string-enums.js.map +0 -1
  108. package/lib/codegen/chunk.d.ts +0 -7
  109. package/lib/codegen/chunk.d.ts.map +0 -1
  110. package/lib/codegen/chunk.js +0 -139
  111. package/lib/codegen/chunk.js.map +0 -1
  112. package/lib/codegen/cli.d.ts +0 -80
  113. package/lib/codegen/cli.d.ts.map +0 -1
  114. package/lib/codegen/cli.js +0 -166
  115. package/lib/codegen/cli.js.map +0 -1
  116. package/lib/codegen/datafy.d.ts +0 -14
  117. package/lib/codegen/datafy.d.ts.map +0 -1
  118. package/lib/codegen/datafy.js +0 -853
  119. package/lib/codegen/datafy.js.map +0 -1
  120. package/lib/codegen/dedupe.d.ts +0 -5
  121. package/lib/codegen/dedupe.d.ts.map +0 -1
  122. package/lib/codegen/dedupe.js +0 -153
  123. package/lib/codegen/dedupe.js.map +0 -1
  124. package/lib/codegen/emit.d.ts +0 -125
  125. package/lib/codegen/emit.d.ts.map +0 -1
  126. package/lib/codegen/emit.js +0 -99
  127. package/lib/codegen/emit.js.map +0 -1
  128. package/lib/codegen/format.d.ts +0 -11
  129. package/lib/codegen/format.d.ts.map +0 -1
  130. package/lib/codegen/format.js +0 -32
  131. package/lib/codegen/format.js.map +0 -1
  132. package/lib/codegen/generated-at.d.ts +0 -29
  133. package/lib/codegen/generated-at.d.ts.map +0 -1
  134. package/lib/codegen/generated-at.js +0 -78
  135. package/lib/codegen/generated-at.js.map +0 -1
  136. package/lib/codegen/generator.d.ts +0 -353
  137. package/lib/codegen/generator.d.ts.map +0 -1
  138. package/lib/codegen/generator.js +0 -810
  139. package/lib/codegen/generator.js.map +0 -1
  140. package/lib/codegen/graph.d.ts +0 -36
  141. package/lib/codegen/graph.d.ts.map +0 -1
  142. package/lib/codegen/graph.js +0 -136
  143. package/lib/codegen/graph.js.map +0 -1
  144. package/lib/codegen/graphql-client.d.ts +0 -70
  145. package/lib/codegen/graphql-client.d.ts.map +0 -1
  146. package/lib/codegen/graphql-client.js +0 -439
  147. package/lib/codegen/graphql-client.js.map +0 -1
  148. package/lib/codegen/graphql.d.ts +0 -207
  149. package/lib/codegen/graphql.d.ts.map +0 -1
  150. package/lib/codegen/graphql.js +0 -786
  151. package/lib/codegen/graphql.js.map +0 -1
  152. package/lib/codegen/latin1.d.ts +0 -3
  153. package/lib/codegen/latin1.d.ts.map +0 -1
  154. package/lib/codegen/latin1.js +0 -126
  155. package/lib/codegen/latin1.js.map +0 -1
  156. package/lib/codegen/members.d.ts +0 -32
  157. package/lib/codegen/members.d.ts.map +0 -1
  158. package/lib/codegen/members.js +0 -62
  159. package/lib/codegen/members.js.map +0 -1
  160. package/lib/codegen/model-diff.d.ts +0 -10
  161. package/lib/codegen/model-diff.d.ts.map +0 -1
  162. package/lib/codegen/model-diff.js +0 -67
  163. package/lib/codegen/model-diff.js.map +0 -1
  164. package/lib/codegen/naming.d.ts +0 -29
  165. package/lib/codegen/naming.d.ts.map +0 -1
  166. package/lib/codegen/naming.js +0 -74
  167. package/lib/codegen/naming.js.map +0 -1
  168. package/lib/codegen/openapi-cli.d.ts +0 -52
  169. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  170. package/lib/codegen/openapi-cli.js +0 -84
  171. package/lib/codegen/openapi-cli.js.map +0 -1
  172. package/lib/codegen/openapi.d.ts +0 -209
  173. package/lib/codegen/openapi.d.ts.map +0 -1
  174. package/lib/codegen/openapi.js +0 -1548
  175. package/lib/codegen/openapi.js.map +0 -1
  176. package/lib/codegen/operations.d.ts +0 -24
  177. package/lib/codegen/operations.d.ts.map +0 -1
  178. package/lib/codegen/operations.js +0 -56
  179. package/lib/codegen/operations.js.map +0 -1
  180. package/lib/codegen/pagination.d.ts +0 -39
  181. package/lib/codegen/pagination.d.ts.map +0 -1
  182. package/lib/codegen/pagination.js +0 -31
  183. package/lib/codegen/pagination.js.map +0 -1
  184. package/lib/codegen/patch-audit.d.ts +0 -84
  185. package/lib/codegen/patch-audit.d.ts.map +0 -1
  186. package/lib/codegen/patch-audit.js +0 -366
  187. package/lib/codegen/patch-audit.js.map +0 -1
  188. package/lib/codegen/patches.d.ts +0 -129
  189. package/lib/codegen/patches.d.ts.map +0 -1
  190. package/lib/codegen/patches.js +0 -472
  191. package/lib/codegen/patches.js.map +0 -1
  192. package/lib/codegen/prelude.d.ts +0 -15
  193. package/lib/codegen/prelude.d.ts.map +0 -1
  194. package/lib/codegen/prelude.js +0 -60
  195. package/lib/codegen/prelude.js.map +0 -1
  196. package/lib/codegen/privatize.d.ts +0 -21
  197. package/lib/codegen/privatize.d.ts.map +0 -1
  198. package/lib/codegen/privatize.js +0 -176
  199. package/lib/codegen/privatize.js.map +0 -1
  200. package/lib/codegen/proto.d.ts +0 -121
  201. package/lib/codegen/proto.d.ts.map +0 -1
  202. package/lib/codegen/proto.js +0 -960
  203. package/lib/codegen/proto.js.map +0 -1
  204. package/lib/codegen/pure.d.ts +0 -6
  205. package/lib/codegen/pure.d.ts.map +0 -1
  206. package/lib/codegen/pure.js +0 -91
  207. package/lib/codegen/pure.js.map +0 -1
  208. package/lib/codegen/rewrite-operation-ids.d.ts +0 -154
  209. package/lib/codegen/rewrite-operation-ids.d.ts.map +0 -1
  210. package/lib/codegen/rewrite-operation-ids.js +0 -1117
  211. package/lib/codegen/rewrite-operation-ids.js.map +0 -1
  212. package/lib/codegen/spec-path.d.ts +0 -16
  213. package/lib/codegen/spec-path.d.ts.map +0 -1
  214. package/lib/codegen/spec-path.js +0 -101
  215. package/lib/codegen/spec-path.js.map +0 -1
  216. package/lib/codegen/table.d.ts +0 -5
  217. package/lib/codegen/table.d.ts.map +0 -1
  218. package/lib/codegen/table.js +0 -249
  219. package/lib/codegen/table.js.map +0 -1
  220. package/lib/json-patch.d.ts +0 -58
  221. package/lib/json-patch.d.ts.map +0 -1
  222. package/lib/json-patch.js +0 -2
  223. package/lib/json-patch.js.map +0 -1
  224. package/lib/schema-lite-typed.js.map +0 -1
  225. package/lib/testing.d.ts +0 -40
  226. package/lib/testing.d.ts.map +0 -1
  227. package/lib/testing.js +0 -2
  228. package/lib/testing.js.map +0 -1
  229. package/src/codegen/boolean-string-enums.ts +0 -155
  230. package/src/codegen/chunk.ts +0 -147
  231. package/src/codegen/cli.ts +0 -293
  232. package/src/codegen/datafy.ts +0 -874
  233. package/src/codegen/dedupe.ts +0 -173
  234. package/src/codegen/emit.ts +0 -200
  235. package/src/codegen/format.ts +0 -49
  236. package/src/codegen/generated-at.ts +0 -88
  237. package/src/codegen/generator.ts +0 -1229
  238. package/src/codegen/graph.ts +0 -151
  239. package/src/codegen/graphql-client.ts +0 -545
  240. package/src/codegen/graphql.ts +0 -1145
  241. package/src/codegen/latin1.ts +0 -131
  242. package/src/codegen/members.ts +0 -79
  243. package/src/codegen/model-diff.ts +0 -67
  244. package/src/codegen/naming.ts +0 -85
  245. package/src/codegen/openapi-cli.ts +0 -141
  246. package/src/codegen/openapi.ts +0 -1845
  247. package/src/codegen/operations.ts +0 -73
  248. package/src/codegen/pagination.ts +0 -64
  249. package/src/codegen/patch-audit.ts +0 -480
  250. package/src/codegen/patches.ts +0 -581
  251. package/src/codegen/prelude.ts +0 -70
  252. package/src/codegen/privatize.ts +0 -200
  253. package/src/codegen/proto.ts +0 -1092
  254. package/src/codegen/pure.ts +0 -94
  255. package/src/codegen/rewrite-operation-ids.ts +0 -1219
  256. package/src/codegen/spec-path.ts +0 -112
  257. package/src/codegen/table.ts +0 -254
  258. package/src/json-patch.ts +0 -273
  259. package/src/testing.ts +0 -74
@@ -1,173 +0,0 @@
1
- /**
2
- * Merge structurally identical schema consts in a generated module
3
- * (dev-time only).
4
- *
5
- * Specs repeat shapes under different names: Stripe has hundreds of
6
- * `{ object: string; url: string }`-style structs, AWS has dozens of empty
7
- * `*Response` shapes and identical lists. Each copy is its own schema at
8
- * runtime. This pass keeps the first schema of every structural class and
9
- * turns the others into aliases (`export const B = A as any as S.Schema<B>;`),
10
- * so the exports and types are unchanged and only one schema is built.
11
- *
12
- * Two consts are equal when their initializers are the same text after
13
- * (1) dropping their own name from `identifier: "<name>"` annotations and
14
- * casts, and (2) replacing every reference to another schema const, and every
15
- * `identifier: "<other>"` string, with that const's current class. This is
16
- * repeated until the classes stop changing (bottom-up merging; members of a
17
- * reference cycle merge only when they were already textually identical).
18
- *
19
- * Schemas passed directly as an operation's `input:` keep their own object:
20
- * AWS query protocols derive the action name from the input identifier.
21
- * Modules on AWS XML / query protocols are left alone entirely: those
22
- * protocols use a shape's identifier as its XML element name, so a merged
23
- * shape would change the wire format.
24
- */
25
- const IDENTIFIER_ON_WIRE =
26
- /^const proto = (?:\/\*[@#]__PURE__\*\/ )?T\.AwsProtocols(?:RestXml|AwsQuery|Ec2Query)\(/m;
27
- import { parseAst } from "rolldown/parseAst";
28
-
29
- type Node = { readonly type: string; readonly start: number; readonly end: number } & Record<
30
- string,
31
- unknown
32
- >;
33
-
34
- const isNode = (value: unknown): value is Node =>
35
- value !== null && typeof value === "object" && typeof (value as Node).type === "string";
36
-
37
- interface Candidate {
38
- readonly name: string;
39
- /** Initializer span. */
40
- readonly start: number;
41
- readonly end: number;
42
- /** Positions [start, end, name] of identifier references to other consts, in the initializer. */
43
- readonly refs: Array<readonly [number, number, string]>;
44
- /** Positions of `"<name>"` string literals under an `identifier` key. */
45
- readonly idStrings: Array<readonly [number, number, string]>;
46
- }
47
-
48
- const SCHEMA_CALL = /\bS\.(suspend|Struct|Array|Record|Union|Tuple|Literals|NullOr|optional)\(/;
49
-
50
- export const dedupeSchemas = (
51
- code: string,
52
- filename = "generated.ts",
53
- ): { code: string; merged: number } => {
54
- if (IDENTIFIER_ON_WIRE.test(code)) return { code, merged: 0 };
55
- const program = parseAst(code, { sourceType: "module", lang: "ts" }, filename);
56
- const decls: Array<{ name: string; init: Node }> = [];
57
- // `export const Status = S.String;`: enum aliases and other plain leaf
58
- // schemas. References to them compare by what they alias, so two structs
59
- // that differ only in which string enum a field names still merge.
60
- const leafAliases = new Map<string, string>();
61
- const operationSchemas = new Set<string>();
62
-
63
- for (let statement of program.body as unknown as Node[]) {
64
- if (statement.type !== "ExportNamedDeclaration" || !isNode(statement.declaration)) continue;
65
- statement = statement.declaration;
66
- if (statement.type !== "VariableDeclaration") continue;
67
- for (const d of statement.declarations as Node[]) {
68
- const id = d.id as Node;
69
- if (id.type !== "Identifier" || !isNode(d.init)) continue;
70
- const text = code.slice(d.init.start, d.init.end);
71
- if (/\bAPI\.make(Paginated)?\(/.test(text)) {
72
- for (const m of text.matchAll(/\binput: (\w+)\b/g)) operationSchemas.add(m[1]!);
73
- continue;
74
- }
75
- if (SCHEMA_CALL.test(text)) decls.push({ name: id.name as string, init: d.init });
76
- else if (/^S\.[A-Z]\w*$/.test(text)) leafAliases.set(id.name as string, text);
77
- }
78
- }
79
-
80
- const names = new Set([...decls.map((d) => d.name), ...leafAliases.keys()]);
81
- const candidates: Candidate[] = decls
82
- .filter((d) => !operationSchemas.has(d.name))
83
- .map(({ name, init }) => {
84
- const refs: Array<readonly [number, number, string]> = [];
85
- const idStrings: Array<readonly [number, number, string]> = [];
86
- const visit = (node: unknown, parentKey?: string, parent?: Node): void => {
87
- if (Array.isArray(node)) {
88
- for (const child of node) visit(child, parentKey, parent);
89
- return;
90
- }
91
- if (!isNode(node)) return;
92
- if (node.type === "Identifier" && names.has(node.name as string)) {
93
- // Skip object keys and member property names: they are not references.
94
- const isKey =
95
- (parent?.type === "Property" && parentKey === "key" && !parent.computed) ||
96
- (parent?.type === "MemberExpression" && parentKey === "property" && !parent.computed);
97
- if (!isKey) refs.push([node.start, node.end, node.name as string]);
98
- }
99
- if (
100
- node.type === "Property" &&
101
- isNode(node.key) &&
102
- ((node.key.type === "Identifier" && node.key.name === "identifier") ||
103
- (node.key.type === "Literal" && node.key.value === "identifier")) &&
104
- isNode(node.value) &&
105
- node.value.type === "Literal" &&
106
- typeof node.value.value === "string"
107
- ) {
108
- idStrings.push([node.value.start, node.value.end, node.value.value]);
109
- }
110
- for (const [key, value] of Object.entries(node)) {
111
- if (key === "type" || key === "start" || key === "end") continue;
112
- if (value !== null && typeof value === "object") visit(value, key, node);
113
- }
114
- };
115
- visit(init);
116
- return { name, start: init.start, end: init.end, refs, idStrings };
117
- });
118
-
119
- // Class of every schema const; operation schemas are their own class.
120
- const cls = new Map<string, string>([...names].map((n) => [n, leafAliases.get(n) ?? n]));
121
- const keyOf = (c: Candidate): string => {
122
- const edits = [
123
- ...c.refs.map(([s, e, n]) => [s, e, n === c.name ? "@self" : `@${cls.get(n) ?? n}`] as const),
124
- ...c.idStrings.map(
125
- ([s, e, n]) => [s, e, n === c.name ? `"@self"` : `"@${cls.get(n) ?? n}"`] as const,
126
- ),
127
- ].sort((a, b) => a[0] - b[0]);
128
- let out = "";
129
- let pos = c.start;
130
- for (const [s, e, text] of edits) {
131
- if (s < pos) continue;
132
- out += code.slice(pos, s) + text;
133
- pos = e;
134
- }
135
- return out + code.slice(pos, c.end);
136
- };
137
-
138
- for (let round = 0; round < 50; round++) {
139
- const first = new Map<string, string>();
140
- let changed = false;
141
- for (const c of candidates) {
142
- const key = keyOf(c);
143
- const canon = first.get(key);
144
- if (canon === undefined) first.set(key, c.name);
145
- const next = canon ?? c.name;
146
- if (cls.get(c.name) !== next) {
147
- cls.set(c.name, next);
148
- changed = true;
149
- }
150
- }
151
- if (!changed) break;
152
- }
153
-
154
- // Rewrite duplicates as aliases (back to front so offsets stay valid).
155
- const aliases = candidates
156
- .filter((c) => cls.get(c.name) !== c.name)
157
- .sort((a, b) => b.start - a.start);
158
- let out = code;
159
- for (const c of aliases) {
160
- // Follow the class to a const that is still a real schema.
161
- let target = cls.get(c.name)!;
162
- while (cls.get(target) !== target) target = cls.get(target)!;
163
- out = `${out.slice(0, c.start)}${target} as any as S.Schema<${c.name}>${out.slice(c.end)}`;
164
- }
165
- // `X as any as S.Schema<X>` with a leftover trailing cast: `A as any as S.Schema<B> as any as S.Schema<B>`.
166
- out = out.replace(
167
- / as any as S\.Schema<(\w+)> as any as S\.Schema<\1>/g,
168
- " as any as S.Schema<$1>",
169
- );
170
- // An alias is not a call; a PURE marker before it would only draw bundler warnings.
171
- out = out.replace(/\/\*[@#]__PURE__\*\/\s*(\w+ as any as S\.Schema<)/g, "$1");
172
- return { code: out, merged: aliases.length };
173
- };
@@ -1,200 +0,0 @@
1
- /**
2
- * Shared emission idioms for the SDK generators (dev-time only).
3
- *
4
- * Both SDK generators emit the same compile-time-performance pattern
5
- * (ported from distilled PR #360):
6
- *
7
- * export interface X { … } // hand-emitted type
8
- * export const X = S.suspend(() => S.Struct({…}))
9
- * .annotate({ identifier: "X" })
10
- * as any as S.Schema<X>; // no inference needed
11
- *
12
- * plus closed-alias string-union enums, `S.TaggedError` error classes, and
13
- * `API.make(() => ({ … }))` operation consts. The helpers here own those
14
- * shared skeletons; providers own the content strings (member pipes, trait
15
- * calls, config fields). Emitted output is normalized by oxfmt afterwards,
16
- * so helpers emit canonical token streams rather than matching historical
17
- * whitespace.
18
- */
19
- import { q } from "./naming.ts";
20
-
21
- /** PURE annotates calls, never property reads. Both @ and # forms are supported. */
22
- export const PURE = "/*@__PURE__*/ ";
23
-
24
- /** `export interface X { … }` (or the empty-body form). */
25
- export const interfaceDecl = (name: string, fields: string[]): string =>
26
- fields.length
27
- ? `export interface ${name} {\n${fields.join("\n")}\n}`
28
- : `export interface ${name} {}`;
29
-
30
- export interface SuspendConstOptions {
31
- readonly name: string;
32
- /** The schema expression inside the suspend thunk. */
33
- readonly expr: string;
34
- /** PURE marker(s), e.g. `"/*@__PURE__*​/ "`. Emitted verbatim before the expression. */
35
- readonly pure?: string;
36
- /** When set, `.annotate({ identifier: <name> })` is appended after the suspend. */
37
- readonly annotateIdentifier?: boolean;
38
- /** Extra annotation object source to use instead of the identifier default. */
39
- readonly annotation?: string;
40
- /**
41
- * Explicit thunk return type (`(): S.Schema<X> =>`) — used for shapes in
42
- * dependency cycles to stop circular type inference.
43
- */
44
- readonly thunkType?: string;
45
- /** CF-style multiline body (`S.suspend(() =>\n<expr>,\n)`). */
46
- readonly multiline?: boolean;
47
- /** The cast target; defaults to `S.Schema<name>`. */
48
- readonly castTo?: string;
49
- }
50
-
51
- /**
52
- * The `export const X = S.suspend(…) … as any as S.Schema<X>;` skeleton
53
- * shared by both generators.
54
- */
55
- export const suspendConst = (o: SuspendConstOptions): string => {
56
- const cast = o.castTo ?? `S.Schema<${o.name}>`;
57
- const thunk = o.thunkType ? `(): ${o.thunkType} =>` : `() =>`;
58
- const suspend = o.multiline
59
- ? `S.suspend(${thunk}\n${o.expr},\n)`
60
- : `S.suspend(${thunk} ${o.expr})`;
61
- const annotate = o.annotation
62
- ? `.annotate(${o.annotation})`
63
- : o.annotateIdentifier
64
- ? `.annotate({ identifier: ${q(o.name)} })`
65
- : "";
66
- return `export const ${o.name} = ${o.pure ?? ""}${suspend}${annotate} as any as ${cast};\n`;
67
- };
68
-
69
- /**
70
- * Member-level lazy reference: `S.suspend(() => X).annotate({ identifier })`.
71
- * The `typed` form adds an explicit `S.Schema<X>` thunk return type — used
72
- * for references into dependency cycles to stop circular type inference.
73
- */
74
- export const suspendRef = (name: string, typed = false): string =>
75
- typed
76
- ? `S.suspend((): S.Schema<${name}> => ${name}).annotate({ identifier: ${q(name)} })`
77
- : `S.suspend(() => ${name}).annotate({ identifier: ${q(name)} })`;
78
-
79
- export interface EnumDeclOptions {
80
- readonly name: string;
81
- readonly values: readonly string[];
82
- readonly pure?: string;
83
- /** The schema const expression; both SDKs use `S.String` (open enums). */
84
- readonly schemaExpr?: string;
85
- }
86
-
87
- /**
88
- * String-union enum ALIAS: the spec's documented values as a CLOSED literal
89
- * union (`type X = "a" | "b"`) — response readers match documented values
90
- * exhaustively. INPUT references re-open the alias inline
91
- * (`X | (string & {})`) so consumers can send tomorrow's values without an
92
- * SDK update. The schema stays `S.String` in both directions (the
93
- * protocols never validate enum membership, so undocumented wire values
94
- * always pass through at runtime).
95
- */
96
- export const enumDecl = (o: EnumDeclOptions): string[] => {
97
- const union = o.values.length ? o.values.map(q).join(" | ") : "string";
98
- return [
99
- `export type ${o.name} = ${union};`,
100
- `export const ${o.name} = ${o.schemaExpr ? `${o.pure ?? ""}${o.schemaExpr}` : "S.String"};\n`,
101
- ];
102
- };
103
-
104
- export interface ErrorClassOptions {
105
- readonly name: string;
106
- /** The error tag; defaults to `name`. */
107
- readonly tag?: string;
108
- /** Field lines (` key: S.String,`). */
109
- readonly fields: readonly string[];
110
- /** Optional extra argument(s) after the fields object (annotations). */
111
- readonly annotations?: string;
112
- /** `.pipe(…)` suffix (e.g. category decorators). */
113
- readonly pipes?: string;
114
- /** Wrap the class expression (e.g. `T.applyErrorMatchers(<cls>, …)`). */
115
- readonly wrap?: (cls: string) => string;
116
- }
117
-
118
- /**
119
- * `export class X extends /*@__PURE__*​/ S.TaggedError<X>()("X", { … }) {}`
120
- *
121
- * The PURE markers are what make an unused error class droppable. A class
122
- * whose heritage clause is an unannotated call can never be tree-shaken —
123
- * the bundler has to assume the call has side effects — so a consumer
124
- * importing one operation would retain every error class in the module
125
- * (distilled #191).
126
- *
127
- * `wrap` needs its own marker as well as the inner one: a pure call's
128
- * ARGUMENTS are still evaluated, so annotating only
129
- * `T.applyErrorMatchers(S.TaggedError…(…), […])` leaves the inner call
130
- * holding the class alive. Verified against esbuild in both directions.
131
- */
132
- export const errorClass = (o: ErrorClassOptions): string => {
133
- const annotations = o.annotations ? `,\n${o.annotations}` : "";
134
- const cls = `${PURE}S.TaggedError<${o.name}>()(${q(o.tag ?? o.name)}, {\n${o.fields.join("\n")}\n}${annotations})${o.pipes ?? ""}`;
135
- const body = o.wrap ? `${PURE}${o.wrap(cls)}` : cls;
136
- return `export class ${o.name} extends ${body} {}\n`;
137
- };
138
-
139
- export interface OperationConstOptions {
140
- /** The exported (usually lowerFirst) operation name. */
141
- readonly exportName: string;
142
- /** Full type annotation (e.g. `API.OperationMethod<A, B, E, R>`). */
143
- readonly typeAnnotation: string;
144
- /** `API.make` or `API.makePaginated` (with namespace prefix). */
145
- readonly factory: string;
146
- /** The config object source (including braces). */
147
- readonly config: string;
148
- /** Optional extra factory argument (e.g. a pagination strategy). */
149
- readonly extraArg?: string;
150
- readonly pure?: string;
151
- /**
152
- * Widen the factory result to `any`, for annotations the factory's
153
- * generic signature can't prove. The one case today: a paginated
154
- * operation's `items` element type comes from the pagination trait's
155
- * `items` PATH — a runtime string — so the factory can only infer the
156
- * structural fallback while the annotation names the real element type.
157
- *
158
- * Unlike the schema consts' `as any as S.Schema<X>`, the target doesn't
159
- * need restating here: the const carries its own annotation, which IS
160
- * the assignment target, so a bare `as any` lands in the same place.
161
- * Restating it would double every paginated operation's declaration —
162
- * ~40k lines across the SDKs — for no added checking.
163
- */
164
- readonly castToAnnotation?: boolean;
165
- }
166
-
167
- /** `export const op: T = API.make(() => ({ … }));` */
168
- export const operationConst = (o: OperationConstOptions): string =>
169
- `export const ${o.exportName}: ${o.typeAnnotation} = ${o.pure ?? ""}${o.factory}(() => (${o.config})${
170
- o.extraArg ? `, ${o.extraArg}` : ""
171
- })${o.castToAnnotation ? ` as any` : ""};\n`;
172
-
173
- import { tsKey } from "./naming.ts";
174
-
175
- export interface InterfaceFieldOptions {
176
- readonly name: string;
177
- readonly type: string;
178
- readonly optional: boolean;
179
- readonly doc?: string;
180
- }
181
-
182
- /** Interface field line(s): optional doc comment + ` name?: Type;`. */
183
- export const interfaceField = (o: InterfaceFieldOptions): string[] => [
184
- ...(o.doc ? [` /** ${o.doc} */`] : []),
185
- ` ${tsKey(o.name)}${o.optional ? "?" : ""}: ${o.type};`,
186
- ];
187
-
188
- /** `export type <Op>Error = A | B | <CommonErrors>;` */
189
- export const errorUnionAlias = (
190
- opName: string,
191
- errorNames: readonly string[],
192
- commonRef: string,
193
- ): string => `export type ${opName}Error = ${[...errorNames, commonRef].join(" | ")};`;
194
-
195
- /** Namespaced barrel: `export * as name from "./file.ts";` per entry. */
196
- export const barrel = (
197
- header: string,
198
- entries: ReadonlyArray<{ name: string; path: string }>,
199
- ): string =>
200
- header + entries.map((e) => `export * as ${e.name} from ${q(e.path)};`).join("\n") + "\n";
@@ -1,49 +0,0 @@
1
- /**
2
- * Post-generation formatting (dev-time only).
3
- *
4
- * The emitters produce a canonical token stream, not formatted source, so
5
- * every generator formats what it wrote before finishing. Without it a
6
- * generate run leaves the whole output directory dirty against the committed
7
- * (formatted) files, and a real regression is indistinguishable from
8
- * whitespace in the diff.
9
- *
10
- * Lives here so the shared {@link runGeneratorCli} and the providers with
11
- * their own pipelines run the identical step.
12
- */
13
- import { spawn } from "node:child_process";
14
- import { Console, Effect } from "effect";
15
-
16
- /** Run a dev-time tool, failing the generate run if it does. */
17
- export const runTool = (argv: readonly string[]): Effect.Effect<void, never, never> =>
18
- Effect.tryPromise({
19
- try: () =>
20
- new Promise<number | null>((resolve, reject) => {
21
- const [command, ...args] = argv;
22
- spawn(command!, args, { stdio: ["ignore", "inherit", "inherit"] })
23
- .on("error", reject)
24
- .on("exit", resolve);
25
- }),
26
- catch: (cause) => new Error(`${argv[0]} failed to start: ${cause}`),
27
- }).pipe(
28
- Effect.flatMap((code) =>
29
- code === 0 ? Effect.void : Effect.die(new Error(`${argv.join(" ")} exited with ${code}`)),
30
- ),
31
- Effect.catchCause((cause) => Effect.die(cause)),
32
- );
33
-
34
- /** Format a generated directory in place. */
35
- export const formatGenerated = (dir: string) =>
36
- Effect.flatMap(Console.log(`\n🧹 Formatting ${dir}`), () =>
37
- runTool(["pnpm", "exec", "oxfmt", dir]),
38
- );
39
-
40
- /**
41
- * Lint-fix then format. `oxlint --fix` can leave its rewrites unformatted,
42
- * so the formatter has to run after it, not before.
43
- */
44
- export const lintAndFormatGenerated = (dir: string) =>
45
- Effect.flatMap(Console.log(`\n🧹 Linting and formatting ${dir}`), () =>
46
- Effect.flatMap(runTool(["pnpm", "exec", "oxlint", "--fix", dir]), () =>
47
- runTool(["pnpm", "exec", "oxfmt", dir]),
48
- ),
49
- );
@@ -1,88 +0,0 @@
1
- /**
2
- * Records, in the package's `package.json`, two UTC `YYYY-MM-DD` dates:
3
- *
4
- * - `distilled.generatedAt` — when the SDK was last generated.
5
- * - `distilled.specUpdatedAt` — when the spec it was generated from last
6
- * changed: the newest commit at or before the pinned mirror commit that
7
- * touched the mirror's `specs/` directory.
8
- *
9
- * Every successful generator run calls this, so both dates land in the same
10
- * commit as the regenerated code and ship to npm with the package. Dates (not
11
- * timestamps) keep repeat runs on the same day from churning the manifest.
12
- */
13
- import { execFileSync } from "node:child_process";
14
- import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
15
- import { join } from "node:path";
16
- import { isLocalSpecs } from "./spec-path.ts";
17
-
18
- /** A date in UTC, `YYYY-MM-DD`. */
19
- export const generatedAtDate = (now: Date = new Date()): string => now.toISOString().slice(0, 10);
20
-
21
- const git = (cwd: string, ...args: string[]): string =>
22
- execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
23
-
24
- /** Commits at a shallow boundary; git shows them as adding every file. */
25
- const shallowCommits = (cwd: string): Set<string> => {
26
- const file = git(cwd, "rev-parse", "--path-format=absolute", "--git-path", "shallow");
27
- return new Set(existsSync(file) ? readFileSync(file, "utf8").split("\n").filter(Boolean) : []);
28
- };
29
-
30
- /**
31
- * Date of the newest commit at or before `HEAD` of the repository at `cwd`
32
- * that changed `pathspec`. Mirrors are checked out `--depth=1`, so this
33
- * deepens the history (commits and trees only, no file content) until the
34
- * answer is a real commit and not the shallow boundary.
35
- */
36
- export const lastChangeDate = (cwd: string, pathspec: string): string => {
37
- for (let round = 0; round < 20; round++) {
38
- const [sha, date] = git(cwd, "log", "-1", "--format=%H %cI", "HEAD", "--", pathspec).split(" ");
39
- if (!sha) throw new Error(`no commit in ${cwd} touches ${pathspec}`);
40
- if (!shallowCommits(cwd).has(sha)) return generatedAtDate(new Date(date!));
41
- git(cwd, "fetch", "--quiet", "--deepen=50", "--filter=blob:none", "origin");
42
- }
43
- throw new Error(`gave up deepening ${cwd} to find the last change to ${pathspec}`);
44
- };
45
-
46
- /**
47
- * When the package's spec last changed, or `undefined` if that cannot be
48
- * known here: no `specs/` directory (a hand-written SDK), the mirror is not
49
- * checked out, or specs come from the untracked `specs/.local` copy.
50
- */
51
- export const specUpdatedAt = (root: string): string | undefined => {
52
- const specs = join(root, "specs");
53
- if (isLocalSpecs() || !existsSync(specs)) return undefined;
54
- const mirror = readdirSync(specs).find((d) => d.startsWith("spec-mirror-"));
55
- if (mirror === undefined) return lastChangeDate(root, "specs");
56
- const dir = join(specs, mirror);
57
- // An uninitialised submodule is an empty directory with no `.git`.
58
- return existsSync(join(dir, ".git")) ? lastChangeDate(dir, "specs") : undefined;
59
- };
60
-
61
- export interface GeneratedAtStamp {
62
- readonly generatedAt: string;
63
- /** `undefined` when unknown; the existing value in `package.json` is kept. */
64
- readonly specUpdatedAt: string | undefined;
65
- }
66
-
67
- /**
68
- * Set `distilled.generatedAt` and `distilled.specUpdatedAt` in
69
- * `<root>/package.json`; returns the dates written.
70
- */
71
- export const stampGeneratedAt = (
72
- root: string,
73
- options: { readonly now?: Date; readonly specUpdatedAt?: string | undefined } = {},
74
- ): GeneratedAtStamp => {
75
- const generatedAt = generatedAtDate(options.now);
76
- const spec = "specUpdatedAt" in options ? options.specUpdatedAt : specUpdatedAt(root);
77
- const file = join(root, "package.json");
78
- const text = readFileSync(file, "utf8");
79
- const pkg = JSON.parse(text);
80
- pkg.distilled = {
81
- ...pkg.distilled,
82
- generatedAt,
83
- ...(spec === undefined ? {} : { specUpdatedAt: spec }),
84
- };
85
- const next = `${JSON.stringify(pkg, null, 2)}\n`;
86
- if (next !== text) writeFileSync(file, next);
87
- return { generatedAt, specUpdatedAt: spec };
88
- };