@distilled.cloud/core 1.0.0-rc.16 → 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 (306) hide show
  1. package/lib/_bundle/aws.js +2 -0
  2. package/lib/_bundle/aws.js.map +1 -0
  3. package/lib/_bundle/base.js +5 -0
  4. package/lib/_bundle/base.js.map +1 -0
  5. package/lib/_bundle/graphql.js +3 -0
  6. package/lib/_bundle/graphql.js.map +1 -0
  7. package/lib/_bundle/rest.js +2 -0
  8. package/lib/_bundle/rest.js.map +1 -0
  9. package/lib/_bundle/xml.js +4 -0
  10. package/lib/_bundle/xml.js.map +1 -0
  11. package/lib/annotations.d.ts +15 -0
  12. package/lib/annotations.d.ts.map +1 -0
  13. package/lib/annotations.js +2 -0
  14. package/lib/annotations.js.map +1 -0
  15. package/lib/api.d.ts +15 -0
  16. package/lib/api.d.ts.map +1 -1
  17. package/lib/api.js +1 -796
  18. package/lib/category.d.ts.map +1 -1
  19. package/lib/category.js +1 -278
  20. package/lib/chunks.js +1 -11
  21. package/lib/config.d.ts +54 -13
  22. package/lib/config.d.ts.map +1 -1
  23. package/lib/config.js +1 -161
  24. package/lib/crypto.js +1 -130
  25. package/lib/debug.d.ts.map +1 -1
  26. package/lib/debug.js +1 -8
  27. package/lib/error-category.d.ts.map +1 -1
  28. package/lib/error-category.js +1 -47
  29. package/lib/errors.d.ts +2 -13
  30. package/lib/errors.d.ts.map +1 -1
  31. package/lib/errors.js +1 -198
  32. package/lib/graphql.d.ts +14 -0
  33. package/lib/graphql.d.ts.map +1 -1
  34. package/lib/graphql.js +1 -1058
  35. package/lib/graphql.types.js +1 -6
  36. package/lib/index.d.ts +3 -2
  37. package/lib/index.d.ts.map +1 -1
  38. package/lib/index.js +1 -15
  39. package/lib/pagination.d.ts +34 -2
  40. package/lib/pagination.d.ts.map +1 -1
  41. package/lib/pagination.js +1 -271
  42. package/lib/plain-values.js +1 -39
  43. package/lib/plain-values.js.map +1 -1
  44. package/lib/protocol-http.d.ts +30 -6
  45. package/lib/protocol-http.d.ts.map +1 -1
  46. package/lib/protocol-http.js +1 -812
  47. package/lib/protocol-rest.d.ts +53 -39
  48. package/lib/protocol-rest.d.ts.map +1 -1
  49. package/lib/protocol-rest.js +1 -375
  50. package/lib/query.js +1 -27
  51. package/lib/response-validation-strict.js +1 -284
  52. package/lib/response-validation.d.ts +4 -3
  53. package/lib/response-validation.d.ts.map +1 -1
  54. package/lib/response-validation.js +1 -118
  55. package/lib/retry-after.js +1 -112
  56. package/lib/retry.js +1 -197
  57. package/lib/schema-lite-impl.js +1 -341
  58. package/lib/schema-lite-typed.js +1 -27
  59. package/lib/schema-lite.js +1 -31
  60. package/lib/schema.js +1 -220
  61. package/lib/telemetry-debug.d.ts +14 -0
  62. package/lib/telemetry-debug.d.ts.map +1 -0
  63. package/lib/telemetry-debug.js +2 -0
  64. package/lib/telemetry-debug.js.map +1 -0
  65. package/lib/telemetry-hooks.d.ts +32 -0
  66. package/lib/telemetry-hooks.d.ts.map +1 -0
  67. package/lib/telemetry-hooks.js +2 -0
  68. package/lib/telemetry-hooks.js.map +1 -0
  69. package/lib/telemetry-host-rules.d.ts +23 -0
  70. package/lib/telemetry-host-rules.d.ts.map +1 -0
  71. package/lib/telemetry-host-rules.js +2 -0
  72. package/lib/telemetry-host-rules.js.map +1 -0
  73. package/lib/telemetry-lambda-context.d.ts +17 -0
  74. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  75. package/lib/telemetry-lambda-context.js +2 -0
  76. package/lib/telemetry-lambda-context.js.map +1 -0
  77. package/lib/telemetry-message-context.d.ts +52 -0
  78. package/lib/telemetry-message-context.d.ts.map +1 -0
  79. package/lib/telemetry-message-context.js +2 -0
  80. package/lib/telemetry-message-context.js.map +1 -0
  81. package/lib/telemetry-metrics.d.ts +6 -0
  82. package/lib/telemetry-metrics.d.ts.map +1 -0
  83. package/lib/telemetry-metrics.js +2 -0
  84. package/lib/telemetry-metrics.js.map +1 -0
  85. package/lib/telemetry-name-template.d.ts +13 -0
  86. package/lib/telemetry-name-template.d.ts.map +1 -0
  87. package/lib/telemetry-name-template.js +2 -0
  88. package/lib/telemetry-name-template.js.map +1 -0
  89. package/lib/telemetry-stream.d.ts +9 -0
  90. package/lib/telemetry-stream.d.ts.map +1 -0
  91. package/lib/telemetry-stream.js +2 -0
  92. package/lib/telemetry-stream.js.map +1 -0
  93. package/lib/telemetry-xray.d.ts +28 -0
  94. package/lib/telemetry-xray.d.ts.map +1 -0
  95. package/lib/telemetry-xray.js +2 -0
  96. package/lib/telemetry-xray.js.map +1 -0
  97. package/lib/telemetry.d.ts +269 -0
  98. package/lib/telemetry.d.ts.map +1 -0
  99. package/lib/telemetry.js +3 -0
  100. package/lib/telemetry.js.map +1 -0
  101. package/lib/trait.js +1 -131
  102. package/lib/xml.js +1 -323
  103. package/package.json +1 -3
  104. package/src/annotations.ts +37 -0
  105. package/src/api.ts +130 -30
  106. package/src/category.ts +21 -22
  107. package/src/config.ts +58 -29
  108. package/src/debug.ts +9 -6
  109. package/src/error-category.ts +12 -14
  110. package/src/errors.ts +7 -7
  111. package/src/graphql.ts +123 -18
  112. package/src/index.ts +3 -2
  113. package/src/pagination.ts +119 -6
  114. package/src/protocol-http.ts +63 -43
  115. package/src/protocol-rest.ts +201 -140
  116. package/src/response-validation.ts +4 -3
  117. package/src/telemetry-debug.ts +135 -0
  118. package/src/telemetry-hooks.ts +33 -0
  119. package/src/telemetry-host-rules.ts +39 -0
  120. package/src/telemetry-lambda-context.ts +46 -0
  121. package/src/telemetry-message-context.ts +170 -0
  122. package/src/telemetry-metrics.ts +69 -0
  123. package/src/telemetry-name-template.ts +26 -0
  124. package/src/telemetry-stream.ts +91 -0
  125. package/src/telemetry-xray.ts +66 -0
  126. package/src/telemetry.ts +768 -0
  127. package/lib/api.js.map +0 -1
  128. package/lib/category.js.map +0 -1
  129. package/lib/chunks.js.map +0 -1
  130. package/lib/codegen/boolean-string-enums.d.ts +0 -36
  131. package/lib/codegen/boolean-string-enums.d.ts.map +0 -1
  132. package/lib/codegen/boolean-string-enums.js +0 -147
  133. package/lib/codegen/boolean-string-enums.js.map +0 -1
  134. package/lib/codegen/chunk.d.ts +0 -7
  135. package/lib/codegen/chunk.d.ts.map +0 -1
  136. package/lib/codegen/chunk.js +0 -139
  137. package/lib/codegen/chunk.js.map +0 -1
  138. package/lib/codegen/cli.d.ts +0 -80
  139. package/lib/codegen/cli.d.ts.map +0 -1
  140. package/lib/codegen/cli.js +0 -166
  141. package/lib/codegen/cli.js.map +0 -1
  142. package/lib/codegen/datafy.d.ts +0 -14
  143. package/lib/codegen/datafy.d.ts.map +0 -1
  144. package/lib/codegen/datafy.js +0 -853
  145. package/lib/codegen/datafy.js.map +0 -1
  146. package/lib/codegen/dedupe.d.ts +0 -5
  147. package/lib/codegen/dedupe.d.ts.map +0 -1
  148. package/lib/codegen/dedupe.js +0 -153
  149. package/lib/codegen/dedupe.js.map +0 -1
  150. package/lib/codegen/emit.d.ts +0 -125
  151. package/lib/codegen/emit.d.ts.map +0 -1
  152. package/lib/codegen/emit.js +0 -99
  153. package/lib/codegen/emit.js.map +0 -1
  154. package/lib/codegen/format.d.ts +0 -11
  155. package/lib/codegen/format.d.ts.map +0 -1
  156. package/lib/codegen/format.js +0 -32
  157. package/lib/codegen/format.js.map +0 -1
  158. package/lib/codegen/generated-at.d.ts +0 -29
  159. package/lib/codegen/generated-at.d.ts.map +0 -1
  160. package/lib/codegen/generated-at.js +0 -78
  161. package/lib/codegen/generated-at.js.map +0 -1
  162. package/lib/codegen/generator.d.ts +0 -353
  163. package/lib/codegen/generator.d.ts.map +0 -1
  164. package/lib/codegen/generator.js +0 -810
  165. package/lib/codegen/generator.js.map +0 -1
  166. package/lib/codegen/graph.d.ts +0 -36
  167. package/lib/codegen/graph.d.ts.map +0 -1
  168. package/lib/codegen/graph.js +0 -136
  169. package/lib/codegen/graph.js.map +0 -1
  170. package/lib/codegen/graphql-client.d.ts +0 -70
  171. package/lib/codegen/graphql-client.d.ts.map +0 -1
  172. package/lib/codegen/graphql-client.js +0 -439
  173. package/lib/codegen/graphql-client.js.map +0 -1
  174. package/lib/codegen/graphql.d.ts +0 -207
  175. package/lib/codegen/graphql.d.ts.map +0 -1
  176. package/lib/codegen/graphql.js +0 -786
  177. package/lib/codegen/graphql.js.map +0 -1
  178. package/lib/codegen/latin1.d.ts +0 -3
  179. package/lib/codegen/latin1.d.ts.map +0 -1
  180. package/lib/codegen/latin1.js +0 -126
  181. package/lib/codegen/latin1.js.map +0 -1
  182. package/lib/codegen/members.d.ts +0 -32
  183. package/lib/codegen/members.d.ts.map +0 -1
  184. package/lib/codegen/members.js +0 -62
  185. package/lib/codegen/members.js.map +0 -1
  186. package/lib/codegen/model-diff.d.ts +0 -10
  187. package/lib/codegen/model-diff.d.ts.map +0 -1
  188. package/lib/codegen/model-diff.js +0 -67
  189. package/lib/codegen/model-diff.js.map +0 -1
  190. package/lib/codegen/naming.d.ts +0 -29
  191. package/lib/codegen/naming.d.ts.map +0 -1
  192. package/lib/codegen/naming.js +0 -74
  193. package/lib/codegen/naming.js.map +0 -1
  194. package/lib/codegen/openapi-cli.d.ts +0 -52
  195. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  196. package/lib/codegen/openapi-cli.js +0 -84
  197. package/lib/codegen/openapi-cli.js.map +0 -1
  198. package/lib/codegen/openapi.d.ts +0 -209
  199. package/lib/codegen/openapi.d.ts.map +0 -1
  200. package/lib/codegen/openapi.js +0 -1548
  201. package/lib/codegen/openapi.js.map +0 -1
  202. package/lib/codegen/operations.d.ts +0 -24
  203. package/lib/codegen/operations.d.ts.map +0 -1
  204. package/lib/codegen/operations.js +0 -56
  205. package/lib/codegen/operations.js.map +0 -1
  206. package/lib/codegen/pagination.d.ts +0 -39
  207. package/lib/codegen/pagination.d.ts.map +0 -1
  208. package/lib/codegen/pagination.js +0 -31
  209. package/lib/codegen/pagination.js.map +0 -1
  210. package/lib/codegen/patch-audit.d.ts +0 -84
  211. package/lib/codegen/patch-audit.d.ts.map +0 -1
  212. package/lib/codegen/patch-audit.js +0 -366
  213. package/lib/codegen/patch-audit.js.map +0 -1
  214. package/lib/codegen/patches.d.ts +0 -129
  215. package/lib/codegen/patches.d.ts.map +0 -1
  216. package/lib/codegen/patches.js +0 -472
  217. package/lib/codegen/patches.js.map +0 -1
  218. package/lib/codegen/prelude.d.ts +0 -15
  219. package/lib/codegen/prelude.d.ts.map +0 -1
  220. package/lib/codegen/prelude.js +0 -60
  221. package/lib/codegen/prelude.js.map +0 -1
  222. package/lib/codegen/privatize.d.ts +0 -21
  223. package/lib/codegen/privatize.d.ts.map +0 -1
  224. package/lib/codegen/privatize.js +0 -176
  225. package/lib/codegen/privatize.js.map +0 -1
  226. package/lib/codegen/proto.d.ts +0 -121
  227. package/lib/codegen/proto.d.ts.map +0 -1
  228. package/lib/codegen/proto.js +0 -960
  229. package/lib/codegen/proto.js.map +0 -1
  230. package/lib/codegen/pure.d.ts +0 -6
  231. package/lib/codegen/pure.d.ts.map +0 -1
  232. package/lib/codegen/pure.js +0 -91
  233. package/lib/codegen/pure.js.map +0 -1
  234. package/lib/codegen/rewrite-operation-ids.d.ts +0 -154
  235. package/lib/codegen/rewrite-operation-ids.d.ts.map +0 -1
  236. package/lib/codegen/rewrite-operation-ids.js +0 -1117
  237. package/lib/codegen/rewrite-operation-ids.js.map +0 -1
  238. package/lib/codegen/spec-path.d.ts +0 -16
  239. package/lib/codegen/spec-path.d.ts.map +0 -1
  240. package/lib/codegen/spec-path.js +0 -101
  241. package/lib/codegen/spec-path.js.map +0 -1
  242. package/lib/codegen/table.d.ts +0 -5
  243. package/lib/codegen/table.d.ts.map +0 -1
  244. package/lib/codegen/table.js +0 -249
  245. package/lib/codegen/table.js.map +0 -1
  246. package/lib/config.js.map +0 -1
  247. package/lib/crypto.js.map +0 -1
  248. package/lib/debug.js.map +0 -1
  249. package/lib/error-category.js.map +0 -1
  250. package/lib/errors.js.map +0 -1
  251. package/lib/graphql.js.map +0 -1
  252. package/lib/graphql.types.js.map +0 -1
  253. package/lib/index.js.map +0 -1
  254. package/lib/json-patch.d.ts +0 -58
  255. package/lib/json-patch.d.ts.map +0 -1
  256. package/lib/json-patch.js +0 -227
  257. package/lib/json-patch.js.map +0 -1
  258. package/lib/pagination.js.map +0 -1
  259. package/lib/protocol-http.js.map +0 -1
  260. package/lib/protocol-rest.js.map +0 -1
  261. package/lib/query.js.map +0 -1
  262. package/lib/response-validation-strict.js.map +0 -1
  263. package/lib/response-validation.js.map +0 -1
  264. package/lib/retry-after.js.map +0 -1
  265. package/lib/retry.js.map +0 -1
  266. package/lib/schema-lite-impl.js.map +0 -1
  267. package/lib/schema-lite-typed.js.map +0 -1
  268. package/lib/schema-lite.js.map +0 -1
  269. package/lib/schema.js.map +0 -1
  270. package/lib/testing.d.ts +0 -40
  271. package/lib/testing.d.ts.map +0 -1
  272. package/lib/testing.js +0 -42
  273. package/lib/testing.js.map +0 -1
  274. package/lib/trait.js.map +0 -1
  275. package/lib/xml.js.map +0 -1
  276. package/src/codegen/boolean-string-enums.ts +0 -155
  277. package/src/codegen/chunk.ts +0 -147
  278. package/src/codegen/cli.ts +0 -293
  279. package/src/codegen/datafy.ts +0 -874
  280. package/src/codegen/dedupe.ts +0 -173
  281. package/src/codegen/emit.ts +0 -200
  282. package/src/codegen/format.ts +0 -49
  283. package/src/codegen/generated-at.ts +0 -88
  284. package/src/codegen/generator.ts +0 -1229
  285. package/src/codegen/graph.ts +0 -151
  286. package/src/codegen/graphql-client.ts +0 -545
  287. package/src/codegen/graphql.ts +0 -1145
  288. package/src/codegen/latin1.ts +0 -131
  289. package/src/codegen/members.ts +0 -79
  290. package/src/codegen/model-diff.ts +0 -67
  291. package/src/codegen/naming.ts +0 -85
  292. package/src/codegen/openapi-cli.ts +0 -141
  293. package/src/codegen/openapi.ts +0 -1845
  294. package/src/codegen/operations.ts +0 -73
  295. package/src/codegen/pagination.ts +0 -64
  296. package/src/codegen/patch-audit.ts +0 -480
  297. package/src/codegen/patches.ts +0 -581
  298. package/src/codegen/prelude.ts +0 -70
  299. package/src/codegen/privatize.ts +0 -200
  300. package/src/codegen/proto.ts +0 -1092
  301. package/src/codegen/pure.ts +0 -94
  302. package/src/codegen/rewrite-operation-ids.ts +0 -1219
  303. package/src/codegen/spec-path.ts +0 -112
  304. package/src/codegen/table.ts +0 -254
  305. package/src/json-patch.ts +0 -273
  306. package/src/testing.ts +0 -74
@@ -1,1219 +0,0 @@
1
- /**
2
- * Operation naming (dev-time only).
3
- *
4
- * Distilled SDK operations are verbNoun (`listApps`, `getApp`,
5
- * `createMachine`). Upstream ids come in a handful of shapes and
6
- * {@link toVerbNoun} only reorders the ones it can recognise with confidence:
7
- *
8
- * - go-swagger `Resource_action` / `Resource_Sub_action` (`Apps_list`)
9
- * - REST `NounsAction` with a trailing CRUD verb (`ConfigsList`,
10
- * `ContainerCreate`, `ServiceMembers_getMetrics`)
11
- * - GraphQL `nounAction` (`projectCreate`)
12
- * - `show` → `get`, `index` → `list`, `retrieve` → `get`
13
- *
14
- * Anything else is left as-is (lowerFirst only). Reordering a verb out of
15
- * the middle of an id (`WatchCoreV1PodList` → `listWatch…`) produced worse
16
- * names than the input, so it is not attempted; per-package
17
- * {@link OperationIdRewrite} maps cover the tail.
18
- *
19
- * RFC-6902 patches that target `/paths/~1foo/get/operationId` break the
20
- * moment upstream prefixes paths. Naming is a convert policy, not a patch.
21
- */
22
- export interface OperationIdContext {
23
- readonly path: string;
24
- readonly method: string;
25
- }
26
-
27
- /**
28
- * Return the new operation name, or `undefined` to leave the current value.
29
- * A `Record` is looked up by `"METHOD path"` first, then the spec's
30
- * `operationId` — same id on PUT vs PATCH needs the path key.
31
- */
32
- export type OperationIdRewrite =
33
- | Readonly<Record<string, string>>
34
- | ((operationId: string, ctx: OperationIdContext) => string | undefined);
35
-
36
- /** Verb spellings normalised on the way out. */
37
- const VERB_ALIAS: Readonly<Record<string, string>> = {
38
- show: "get",
39
- index: "list",
40
- retrieve: "get",
41
- };
42
-
43
- /**
44
- * Rails `index` is a verb only when it is the whole id or a whole `_`
45
- * segment (`index`, `Apps_index`). Joined into a camel id it is the noun
46
- * (`InfoIndex`, `IndexCreate`, `IndexDocument`).
47
- */
48
- const isIndexVerb = (raw: string): boolean => raw.toLowerCase() === "index";
49
-
50
- /**
51
- * Unambiguous verbs. An id that STARTS with one is already verb-first and
52
- * is never reordered (`WatchPodList`, `InsertCalendarList`,
53
- * `BulkDeleteMessages`); one found in the middle of a resource name
54
- * (`Apps_getOrCreate`) marks the id as a compound we leave alone.
55
- */
56
- const STRONG_VERBS = new Set([
57
- "get",
58
- "list",
59
- "create",
60
- "delete",
61
- "update",
62
- "patch",
63
- "put",
64
- "post",
65
- "show",
66
- "index",
67
- "retrieve",
68
- "watch",
69
- "read",
70
- "replace",
71
- "connect",
72
- "disconnect",
73
- "insert",
74
- "mutate",
75
- "fetch",
76
- "remove",
77
- "add",
78
- "upload",
79
- "download",
80
- "send",
81
- "resend",
82
- "validate",
83
- "verify",
84
- "enable",
85
- "disable",
86
- "start",
87
- "stop",
88
- "restart",
89
- "cancel",
90
- "search",
91
- "purge",
92
- "revoke",
93
- "approve",
94
- "reject",
95
- "accept",
96
- "invoke",
97
- "trigger",
98
- "deploy",
99
- "redeploy",
100
- "describe",
101
- "generate",
102
- "regenerate",
103
- "rotate",
104
- "restore",
105
- "suspend",
106
- "resume",
107
- "activate",
108
- "deactivate",
109
- "archive",
110
- "unarchive",
111
- "publish",
112
- "unpublish",
113
- "subscribe",
114
- "unsubscribe",
115
- "register",
116
- "unregister",
117
- "authenticate",
118
- "authorize",
119
- "deauthorize",
120
- "attach",
121
- "detach",
122
- "assign",
123
- "unassign",
124
- "import",
125
- "export",
126
- "copy",
127
- "move",
128
- "rename",
129
- "retry",
130
- "reset",
131
- "refresh",
132
- "encrypt",
133
- "decrypt",
134
- "sign",
135
- "edit",
136
- "bulk",
137
- "execute",
138
- "submit",
139
- "apply",
140
- "undelete",
141
- "redeliver",
142
- "invalidate",
143
- "upsert",
144
- "cordon",
145
- "uncordon",
146
- "exec",
147
- "reclaim",
148
- "modify",
149
- "install",
150
- "uninstall",
151
- "migrate",
152
- "terminate",
153
- "reboot",
154
- "rebuild",
155
- "resize",
156
- "clone",
157
- "duplicate",
158
- "acknowledge",
159
- "unpause",
160
- "unblock",
161
- "unlink",
162
- "unpin",
163
- "unmute",
164
- "unhide",
165
- "unstar",
166
- "unfollow",
167
- "unshare",
168
- "unban",
169
- "unlock",
170
- "unflag",
171
- "unclaim",
172
- ]);
173
-
174
- /**
175
- * Words that act as the verb when they TRAIL a resource (`MachinesStart`,
176
- * `SecretkeysSet`, `JobsRun`) but are ordinary nouns when they lead
177
- * (`ReleaseGet`, `RequestGet`, `SetGet`, `CheckRunsList`). Includes every
178
- * strong verb.
179
- */
180
- const TRAILING_VERBS = new Set([
181
- ...STRONG_VERBS,
182
- "notify",
183
- "set",
184
- "check",
185
- "run",
186
- "wait",
187
- "signal",
188
- "fork",
189
- "extend",
190
- "test",
191
- "sync",
192
- "review",
193
- "invite",
194
- "join",
195
- "leave",
196
- "capture",
197
- "refund",
198
- "settle",
199
- "void",
200
- "preview",
201
- "complete",
202
- "confirm",
203
- "abort",
204
- "kill",
205
- "scale",
206
- "promote",
207
- "demote",
208
- "renew",
209
- "recover",
210
- "reveal",
211
- "presign",
212
- "provision",
213
- "trim",
214
- "vacuum",
215
- "compact",
216
- "flush",
217
- "merge",
218
- "dispatch",
219
- "poll",
220
- "redeem",
221
- "claim",
222
- "lint",
223
- "toggle",
224
- "pin",
225
- "mute",
226
- "hide",
227
- "ban",
228
- "block",
229
- "lock",
230
- "share",
231
- "follow",
232
- "star",
233
- "pause",
234
- "finalize",
235
- "transfer",
236
- "lookup",
237
- "clear",
238
- "convert",
239
- "dismiss",
240
- "reply",
241
- "squash",
242
- "commit",
243
- "swap",
244
- "recreate",
245
- "seal",
246
- "ping",
247
- "login",
248
- "logout",
249
- ]);
250
-
251
- /**
252
- * Leading tokens that are verbs often enough that an id starting with one
253
- * is left as-is unless a STRONG verb trails it (`QueryCreate` →
254
- * `createQuery`, but `QueryRun` stays).
255
- */
256
- const WEAK_LEADING_VERBS = new Set([
257
- ...TRAILING_VERBS,
258
- "request",
259
- "release",
260
- "report",
261
- "query",
262
- "stream",
263
- "open",
264
- "close",
265
- "head",
266
- "options",
267
- "compute",
268
- "batch",
269
- "count",
270
- "link",
271
- "mark",
272
- "grant",
273
- "aggregate",
274
- "skip",
275
- "filter",
276
- "change",
277
- "vote",
278
- "debug",
279
- "expire",
280
- "process",
281
- "redirect",
282
- "estimate",
283
- "calculate",
284
- "evaluate",
285
- "resolve",
286
- "load",
287
- "unload",
288
- "backup",
289
- "snapshot",
290
- "rollback",
291
- "flag",
292
- "certify",
293
- "checkout",
294
- "checkin",
295
- "suggest",
296
- "predict",
297
- "analyze",
298
- "annotate",
299
- "translate",
300
- "recognize",
301
- "detect",
302
- "classify",
303
- "simulate",
304
- "take",
305
- "end",
306
- "reassign",
307
- "consume",
308
- "prepare",
309
- "action",
310
- "act",
311
- "ask",
312
- "answer",
313
- "handle",
314
- "trace",
315
- "track",
316
- "log",
317
- ]);
318
-
319
- /** Compound tokens the naive split would leave as `Secretkeys`. */
320
- const TOKEN_ALIAS: Readonly<Record<string, string>> = {
321
- secretkeys: "SecretKeys",
322
- secretkey: "SecretKey",
323
- };
324
-
325
- const IRREGULAR_SINGULAR: Readonly<Record<string, string>> = {
326
- processes: "process",
327
- statuses: "status",
328
- addresses: "address",
329
- aliases: "alias",
330
- indexes: "index",
331
- indices: "index",
332
- matrices: "matrix",
333
- vertices: "vertex",
334
- analyses: "analysis",
335
- bases: "base",
336
- cases: "case",
337
- databases: "database",
338
- releases: "release",
339
- responses: "response",
340
- licenses: "license",
341
- courses: "course",
342
- purchases: "purchase",
343
- phases: "phase",
344
- leases: "lease",
345
- clauses: "clause",
346
- causes: "cause",
347
- pauses: "pause",
348
- houses: "house",
349
- children: "child",
350
- people: "person",
351
- media: "media",
352
- data: "data",
353
- metadata: "metadata",
354
- schemas: "schema",
355
- criteria: "criterion",
356
- feet: "foot",
357
- teeth: "tooth",
358
- mice: "mouse",
359
- geese: "goose",
360
- };
361
-
362
- /**
363
- * Nouns whose plural and singular coincide, or product names that end in
364
- * `s`. Never trimmed.
365
- */
366
- const UNCOUNTABLE = new Set([
367
- "postgres",
368
- "redis",
369
- "kubernetes",
370
- "ios",
371
- "macos",
372
- "windows",
373
- "dns",
374
- "tls",
375
- "https",
376
- "sms",
377
- "cors",
378
- "oidc",
379
- "sso",
380
- "saas",
381
- "aws",
382
- "gcs",
383
- "ecs",
384
- "eks",
385
- "rds",
386
- "sqs",
387
- "sns",
388
- "kms",
389
- "ses",
390
- "efs",
391
- "ebs",
392
- "status",
393
- "series",
394
- "timeseries",
395
- "analytics",
396
- "metrics",
397
- "settings",
398
- "credentials",
399
- "permissions",
400
- "news",
401
- "canvas",
402
- "lens",
403
- "bonus",
404
- "campus",
405
- "census",
406
- "focus",
407
- "virus",
408
- "corpus",
409
- "chorus",
410
- "genus",
411
- "radius",
412
- "consensus",
413
- "apparatus",
414
- "bus",
415
- "gas",
416
- "plus",
417
- "minus",
418
- "nexus",
419
- "prometheus",
420
- "chaos",
421
- "cosmos",
422
- "ethos",
423
- "pathos",
424
- "atlas",
425
- "bias",
426
- "gps",
427
- "cds",
428
- "css",
429
- "sass",
430
- "less",
431
- "js",
432
- "ts",
433
- "os",
434
- "fs",
435
- "vs",
436
- "as",
437
- "is",
438
- "has",
439
- "was",
440
- "this",
441
- "always",
442
- "sis",
443
- "axis",
444
- "basis",
445
- "crisis",
446
- "thesis",
447
- "diagnosis",
448
- "synthesis",
449
- "emphasis",
450
- "hypothesis",
451
- "oasis",
452
- "iris",
453
- "tennis",
454
- "chassis",
455
- "debris",
456
- "physics",
457
- "ethics",
458
- "economics",
459
- "logistics",
460
- "mathematics",
461
- "politics",
462
- "statistics",
463
- "dynamics",
464
- "graphics",
465
- "robotics",
466
- "genetics",
467
- "linguistics",
468
- "means",
469
- "species",
470
- "sheep",
471
- "fish",
472
- "deer",
473
- "aircraft",
474
- "software",
475
- "hardware",
476
- "firmware",
477
- "middleware",
478
- "access",
479
- "address",
480
- "progress",
481
- "success",
482
- "process",
483
- "business",
484
- "ingress",
485
- "egress",
486
- "express",
487
- "compress",
488
- "stress",
489
- "witness",
490
- "fitness",
491
- "wellness",
492
- "readiness",
493
- "liveness",
494
- "awareness",
495
- "class",
496
- "pass",
497
- "mass",
498
- "glass",
499
- "grass",
500
- "bypass",
501
- "compass",
502
- "kms",
503
- "eos",
504
- "nas",
505
- "ras",
506
- "sas",
507
- "das",
508
- "pas",
509
- "s3",
510
- "k8s",
511
- "kubeadm",
512
- ]);
513
-
514
- /** Certificate variants that sit in front of the resource noun. */
515
- const QUALIFIERS = new Set(["acme", "custom"]);
516
-
517
- export const operationNameKey = (ctx: OperationIdContext): string =>
518
- `${ctx.method.toUpperCase()} ${ctx.path}`;
519
-
520
- /** Resolve {@link OperationIdRewrite} against method+path, then operationId. */
521
- export const resolveOperationName = (
522
- rewrite: OperationIdRewrite,
523
- operationId: string,
524
- ctx: OperationIdContext,
525
- ): string | undefined => {
526
- if (typeof rewrite === "function") return rewrite(operationId, ctx);
527
- return rewrite[operationNameKey(ctx)] ?? rewrite[operationId];
528
- };
529
-
530
- /** `foo` → `Foo`; all-caps tokens (`CSI`, `API`) keep their casing. */
531
- const pascalToken = (raw: string): string => {
532
- const alias = TOKEN_ALIAS[raw.toLowerCase()];
533
- if (alias !== undefined) return alias;
534
- return raw.charAt(0).toUpperCase() + raw.slice(1);
535
- };
536
-
537
- /**
538
- * Conservative singular. Only strips a trailing `s` when the word is a
539
- * regular plural we are confident about; anything ambiguous is returned
540
- * unchanged, because `getAlia` is worse than `getAliases`.
541
- */
542
- export const singularize = (raw: string): string => {
543
- const lower = raw.toLowerCase();
544
- const keepCase = (s: string): string =>
545
- raw[0] === raw[0]?.toUpperCase() ? s.charAt(0).toUpperCase() + s.slice(1) : s;
546
- const alias = TOKEN_ALIAS[lower];
547
- if (alias !== undefined) {
548
- return alias.endsWith("s") ? alias.slice(0, -1) : alias;
549
- }
550
- const irregular = IRREGULAR_SINGULAR[lower];
551
- if (irregular !== undefined) return keepCase(irregular);
552
- if (UNCOUNTABLE.has(lower)) return raw;
553
- // All-caps acronyms (`IPs`, `CIDRs`, `DNS`) — only trim a lowercase `s`
554
- // after an acronym.
555
- if (/^[A-Z0-9]+s$/.test(raw)) return raw.slice(0, -1);
556
- if (raw !== lower && raw.toUpperCase() === raw) return raw;
557
- if (lower.length <= 3) return raw;
558
- if (!lower.endsWith("s")) return raw;
559
- // Vowel + `ys` is a regular plural (`keys`, `days`); consonant + `ys` is not.
560
- if (/(?:ss|us|is|os|as|[^aeiou]ys)$/.test(lower)) return raw;
561
- if (lower.endsWith("ies") && lower.length > 4) return `${raw.slice(0, -3)}y`;
562
- if (/(?:ches|shes|xes|zes|sses)$/.test(lower)) return raw.slice(0, -2);
563
- if (lower.endsWith("oes") && lower.length > 4) return raw.slice(0, -2);
564
- // `-ses` after a vowel is usually a regular `-se` noun (`Response`,
565
- // `Release`, `Database`), not an `-s` + `es` plural.
566
- if (/[aeiou]ses$/.test(lower)) return raw.slice(0, -1);
567
- if (lower.endsWith("ses")) return raw.slice(0, -2);
568
- return raw.slice(0, -1);
569
- };
570
-
571
- const lowerFirst = (s: string): string =>
572
- s.length === 0 ? s : s.charAt(0).toLowerCase() + s.slice(1);
573
-
574
- /**
575
- * Split on `_`, `-`, `/` and camel boundaries. Acronym runs stay together
576
- * (`CSIDriver` → `CSI`, `Driver`; `APIGroup` → `API`, `Group`).
577
- */
578
- const splitIdent = (s: string): string[] => {
579
- const parts: string[] = [];
580
- for (const chunk of s.split(/[_/\-.\s]+/).filter(Boolean)) {
581
- const split = chunk
582
- .replace(/([a-z0-9])([A-Z])/g, "$1\0$2")
583
- .replace(/([A-Z]+)([A-Z][a-z])/g, "$1\0$2");
584
- for (const p of split.split("\0")) {
585
- if (p) parts.push(p);
586
- }
587
- }
588
- return parts;
589
- };
590
-
591
- const isStrongVerb = (raw: string): boolean => STRONG_VERBS.has(raw.toLowerCase());
592
- const isTrailingVerb = (raw: string): boolean => TRAILING_VERBS.has(raw.toLowerCase());
593
- const isWeakLeadingVerb = (raw: string): boolean => WEAK_LEADING_VERBS.has(raw.toLowerCase());
594
-
595
- const alias = (raw: string): string => VERB_ALIAS[raw.toLowerCase()] ?? raw.toLowerCase();
596
-
597
- /** `version`-like tokens (`V1`, `v1beta1`, `V2`) are never nouns to singularise. */
598
- const isVersionToken = (raw: string): boolean => /^[vV]\d/.test(raw);
599
-
600
- /** Adverbs that sit between resource and verb: `HoldoutsPartialUpdate`. */
601
- const MODIFIERS = new Set(["partial", "bulk", "batch", "all", "many"]);
602
-
603
- /**
604
- * `verb + Resource + Object`. Only the resource (last noun before the verb)
605
- * is singularised, and only for non-list verbs (`getApp`, `listApps`,
606
- * `listMachineEvents`). Parent tokens keep their spelling.
607
- */
608
- const assemble = (verb: string, nouns: readonly string[], tail: readonly string[] = []): string => {
609
- // `App_Certificates_acme_create`: the qualifier trails the resource in
610
- // the id but reads better in front of it (`createAppAcmeCertificate`).
611
- let ordered = [...nouns];
612
- if (ordered.length >= 2 && QUALIFIERS.has(ordered.at(-1)!.toLowerCase())) {
613
- const q = ordered.pop()!;
614
- ordered.splice(ordered.length - 1, 0, q);
615
- }
616
- const shaped = ordered.map((p, i) => {
617
- const isLast = i === ordered.length - 1;
618
- if (!isLast || isVersionToken(p)) return pascalToken(p);
619
- if (verb === "list" && tail.length === 0) return pascalToken(p);
620
- return pascalToken(singularize(p));
621
- });
622
- return verb + shaped.join("") + tail.map(pascalToken).join("");
623
- };
624
-
625
- /**
626
- * Distilled SDK names are verbNoun (`listApps`, `getApp`, `createMachine`).
627
- *
628
- * - Already verb-first (`listSprites`, `GetObject`, `showContact`,
629
- * `WatchPodList`) stays, with `show`/`index`/`retrieve` aliased.
630
- * - Trailing action (`ConfigsList`, `PlansGet`, `ContainerCreate`,
631
- * `VirtualMachinesStart`, `ReleaseGet`) moves the verb first and
632
- * singularises the resource for non-list verbs.
633
- * - go-swagger / autorest `Apps_list`, `App_Certificates_show`,
634
- * `Machines_list_events`, `ServiceMembers_getMetrics`: the verb heads the
635
- * first `_` segment after the resource.
636
- * - Anything else (`AppGetOrCreate`, `VirtualMachines_createOrUpdate`,
637
- * `DnsRecordsBatch`, `accountById`) is returned unchanged apart from
638
- * lowerFirst. Use {@link OperationIdRewrite} for those.
639
- */
640
- export const toVerbNoun = (operationId: string): string => {
641
- const trimmed = operationId.trim();
642
- if (trimmed === "") return trimmed;
643
-
644
- const segments = trimmed.split(/[_/]+/).filter(Boolean);
645
- if (segments.length >= 2) {
646
- // snake_case verb-first (`get_apps`, `list_all_users`): join.
647
- const lead = splitIdent(segments[0]!);
648
- if (lead.length === 1 && isStrongVerb(lead[0]!)) {
649
- const rest = segments.slice(1).flatMap(splitIdent);
650
- return alias(lead[0]!) + rest.map(pascalToken).join("");
651
- }
652
- // Segments before the verb are the resource by construction, so a
653
- // verb-looking token inside them (`OpenIdConnectProvider_get`) is a
654
- // noun. Only the object after the verb can make this a compound.
655
- const verbSeg = segments.findIndex((seg, i) => {
656
- if (i === 0) return false;
657
- const tokens = splitIdent(seg);
658
- const head = tokens[0] ?? "";
659
- // `Apps_index` lists; `Apps_indexInfo` is about the index entity.
660
- if (isIndexVerb(head)) return tokens.length === 1;
661
- return isTrailingVerb(head);
662
- });
663
- if (verbSeg > 0) {
664
- const head = segments.slice(0, verbSeg).flatMap(splitIdent);
665
- const [verb, ...objectHere] = splitIdent(segments[verbSeg]!);
666
- const object = [...objectHere, ...segments.slice(verbSeg + 1).flatMap(splitIdent)];
667
- const compound = object.some((t) => isStrongVerb(t) || /^(or|and)$/i.test(t));
668
- if (!compound) return assemble(alias(verb!), head, object);
669
- }
670
- return lowerFirst(trimmed);
671
- }
672
-
673
- const parts = splitIdent(trimmed);
674
- // `Index1`, `Index2`: a converter's duplicate-route suffix on a bare id.
675
- if (parts.length <= 1 || parts.slice(1).every((p) => /^\d+$/.test(p))) {
676
- return parts.length >= 1 && isTrailingVerb(parts[0]!)
677
- ? alias(parts[0]!) + parts.slice(1).join("")
678
- : lowerFirst(trimmed);
679
- }
680
-
681
- const first = parts[0]!;
682
- const last = parts.at(-1)!;
683
-
684
- // A camel id never uses Rails `index` as its verb: `InfoIndex`,
685
- // `IndexCreate`, `IndexDocument` all name the index entity.
686
- const strong = (raw: string) => !isIndexVerb(raw) && isStrongVerb(raw);
687
- const trailing = (raw: string) => !isIndexVerb(raw) && isTrailingVerb(raw);
688
- const weakLeading = (raw: string) => !isIndexVerb(raw) && isWeakLeadingVerb(raw);
689
-
690
- if (strong(first)) {
691
- return alias(first) + parts.slice(1).map(pascalToken).join("");
692
- }
693
- if (parts.some((p) => /^(or|and)$/i.test(p))) return lowerFirst(trimmed);
694
-
695
- // Swagger tag-prefixed ids whose object repeats the tag (`issueListIssues`,
696
- // `repoGetRepo`): the tag is redundant, drop it. Other tag-prefixed shapes
697
- // (`userGetCurrent`, `notifyGetList`) are left for per-package
698
- // `operationNames`; a middle verb is too often a noun (`environmentPatchCommit`).
699
- if (
700
- parts.length >= 3 &&
701
- !weakLeading(first) &&
702
- !isVersionToken(first) &&
703
- strong(parts[1]!) &&
704
- singularize(parts[2]!).toLowerCase() === singularize(first).toLowerCase() &&
705
- !parts.slice(2).some(strong)
706
- ) {
707
- return alias(parts[1]!) + parts.slice(2).map(pascalToken).join("");
708
- }
709
-
710
- const reorder = weakLeading(first) ? strong(last) : trailing(last);
711
- if (!reorder) {
712
- return weakLeading(first)
713
- ? alias(first) + parts.slice(1).map(pascalToken).join("")
714
- : lowerFirst(trimmed);
715
- }
716
-
717
- const nouns = parts.slice(0, -1);
718
- if (nouns.slice(1).some(strong)) return lowerFirst(trimmed);
719
- const modifier = nouns.at(-1);
720
- if (nouns.length > 1 && modifier !== undefined && MODIFIERS.has(modifier.toLowerCase())) {
721
- return assemble(alias(last), nouns.slice(0, -1), [modifier]);
722
- }
723
- return assemble(alias(last), nouns);
724
- };
725
-
726
- const COMPANION_SUFFIXES = ["Request", "Response", "Input", "Output", "Error", "Result"] as const;
727
-
728
- const remapTargets = (node: unknown, mapping: ReadonlyMap<string, string>): unknown => {
729
- if (Array.isArray(node)) {
730
- return node.map((item) => remapTargets(item, mapping));
731
- }
732
- if (node === null || typeof node !== "object") return node;
733
- const out: Record<string, unknown> = {};
734
- for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
735
- if (key === "target" && typeof value === "string") {
736
- out[key] = mapping.get(value) ?? value;
737
- } else {
738
- out[key] = remapTargets(value, mapping);
739
- }
740
- }
741
- return out;
742
- };
743
-
744
- /**
745
- * `metadata` key of a model whose final names are deferred (the OpenAPI
746
- * converter's `deferNaming`): upstream shape id → final shape id.
747
- * `finalizeConvert` applies it after the Smithy patches and removes it.
748
- */
749
- export const RENAME_METADATA_KEY = "distilled.rename";
750
-
751
- /**
752
- * Apply and remove a model's deferred rename ({@link RENAME_METADATA_KEY}).
753
- * Returns how many shapes it renamed.
754
- */
755
- export const applyDeferredRename = (model: {
756
- metadata?: Record<string, any>;
757
- shapes?: Record<string, any>;
758
- }): number => {
759
- const rename = model.metadata?.[RENAME_METADATA_KEY] as Record<string, string> | undefined;
760
- if (rename === undefined) return 0;
761
- delete model.metadata![RENAME_METADATA_KEY];
762
- const shapes = model.shapes ?? {};
763
- // A patch may have moved or removed a shape; only rename what is there.
764
- const mapping = new Map(Object.entries(rename).filter(([from]) => from in shapes));
765
- if (mapping.size > 0) renameShapes(model, mapping);
766
- return mapping.size;
767
- };
768
-
769
- /**
770
- * Rename shapes by id and rewrite every `target` that points at a renamed
771
- * one, keeping the model's shape order. All renames happen at once, so a
772
- * mapping may swap names. Throws when a new id is already taken by a shape
773
- * that keeps its name, or two shapes would land on one id.
774
- */
775
- export const renameShapes = (
776
- model: { shapes?: Record<string, any> },
777
- mapping: ReadonlyMap<string, string>,
778
- ): void => {
779
- const shapes = model.shapes ?? {};
780
- const nextShapes: Record<string, any> = {};
781
- for (const [id, def] of Object.entries(shapes)) {
782
- const newId = mapping.get(id) ?? id;
783
- if (Object.prototype.hasOwnProperty.call(nextShapes, newId)) {
784
- throw new Error(`renaming ${id} → ${newId}: that shape id is already taken`);
785
- }
786
- nextShapes[newId] = remapTargets(def, mapping);
787
- }
788
- model.shapes = nextShapes;
789
- };
790
-
791
- /** Version prefixes and API roots that carry no meaning in a name. */
792
- const NOISE_SEGMENTS = new Set(["api", "rest", "v", "public"]);
793
- const isNoiseSegment = (seg: string): boolean => {
794
- const lower = seg.toLowerCase();
795
- return NOISE_SEGMENTS.has(lower) || /^v\d+(\.\d+)*$/.test(lower);
796
- };
797
-
798
- const HTTP_METHOD_ID = /^(get|post|put|patch|delete|head|options)(?=$|[-_./]|[A-Z0-9])/i;
799
-
800
- /**
801
- * Whether an OpenAPI `operationId` carries no information beyond the
802
- * method and path: absent, or a mechanical restatement of the route such
803
- * as `get-api-card`, `post_v1_users_id`, `getApiV1AnnotationLayer`. A
804
- * hand-chosen id that merely starts with the method (`delete-artifact` for
805
- * `/repos/{owner}/{repo}/actions/artifacts/{id}`) is NOT mechanical — it
806
- * names a subset of the route on purpose — so the id must cover every
807
- * literal path segment, and every id token must come from the route.
808
- */
809
- /**
810
- * A stricter subclass of mechanical ids: nothing in the id was chosen by
811
- * a person. Either there is no id, or the id is the route spelled out —
812
- * `postV1AppsByAppIdPromote`, `get_v1_users_id`, `get-api-card`,
813
- * `getCustomerById`. Such names are derived from the route alone.
814
- *
815
- * A `By…` clause counts as verbatim only when it names a whole parameter
816
- * (`ByAppId` for `{appId}`) or is a bare `ById`. `get_webhook_by_token`
817
- * for `/webhooks/{webhook_id}/{webhook_token}` is a chosen
818
- * disambiguation, so its nouns are kept; likewise `deleteScheduledJob`.
819
- */
820
- export const isVerbatimRouteId = (
821
- operationId: string | undefined,
822
- ctx: OperationIdContext,
823
- ): boolean => {
824
- if (!operationId) return true;
825
- if (!isMechanicalOperationId(operationId, ctx)) return false;
826
- const id = stripTag(operationId);
827
- const m = HTTP_METHOD_ID.exec(id);
828
- const norm = (t: string) => singularize(t.toLowerCase()).toLowerCase();
829
- const idTokens = splitIdent(id.slice(m ? m[0].length : 0)).map(norm);
830
- const literal = new Set<string>();
831
- const params: string[][] = [];
832
- for (const seg of ctx.path.split(/[?#]/)[0]!.split("/")) {
833
- for (const mm of seg.matchAll(/\{([^}]+)\}/g)) {
834
- params.push(splitIdent(mm[1]!).map(norm));
835
- }
836
- for (const t of splitIdent(seg.replace(/\{[^}]*\}/g, " ")).map(norm)) {
837
- literal.add(t);
838
- }
839
- }
840
- const paramTokens = new Set(params.flat());
841
- const clauses: string[][] = [[]];
842
- for (const t of idTokens) {
843
- if (t === "by") clauses.push([]);
844
- else clauses.at(-1)!.push(t);
845
- }
846
- const [head, ...byClauses] = clauses;
847
- if (!head!.every((t) => literal.has(t) || paramTokens.has(t))) return false;
848
- // `ByAppIdPromote`: a whole parameter, then route literals.
849
- return byClauses.every((c) => {
850
- const lengths = [
851
- ...params.filter((p) => p.every((t, i) => t === c[i])).map((p) => p.length),
852
- ...(c[0] === "id" ? [1] : []),
853
- ];
854
- return lengths.some((n) => n <= c.length && c.slice(n).every((t) => literal.has(t)));
855
- });
856
- };
857
-
858
- /** `activity/get-feeds` → `get-feeds`: a tag prefix is not part of the name. */
859
- const stripTag = (operationId: string): string =>
860
- operationId.includes("/") ? operationId.slice(operationId.lastIndexOf("/") + 1) : operationId;
861
-
862
- export const isMechanicalOperationId = (
863
- operationId: string | undefined,
864
- ctx: OperationIdContext,
865
- ): boolean => {
866
- if (!operationId) return true;
867
- const id = stripTag(operationId);
868
- const m = HTTP_METHOD_ID.exec(id);
869
- if (!m || m[1]!.toLowerCase() !== ctx.method.toLowerCase()) return false;
870
- const norm = (t: string) => singularize(t.toLowerCase()).toLowerCase();
871
- const joiners = new Set(["by", "for", "of", "in", "with", "and", "to"]);
872
- const idTokens = splitIdent(id.slice(m[0].length))
873
- .map(norm)
874
- .filter((t) => !joiners.has(t));
875
- const segments = ctx.path.split(/[?#]/)[0]!.split("/").filter(Boolean);
876
- // Route tokens in order; literals are required, params and `/api`,
877
- // `/v2` roots are optional (`getApiV1Foo` and `getFoo` both count).
878
- const route: Array<{ token: string; required: boolean }> = [];
879
- for (const seg of segments) {
880
- const param = /^\{(.*)\}$/.exec(seg);
881
- const required = param === null && !isNoiseSegment(seg);
882
- for (const t of splitIdent(param ? param[1]! : seg).map(norm)) {
883
- route.push({ token: t, required });
884
- }
885
- }
886
- if (idTokens.length === 0) return !route.some((r) => r.required);
887
- // The id must read the route left to right, skipping only optional
888
- // tokens. `delete-package-for-org` on /orgs/{org}/packages/… reads
889
- // `package, org` — out of order — and stays a hand-written name.
890
- let i = 0;
891
- for (const r of route) {
892
- if (i < idTokens.length && idTokens[i] === r.token) {
893
- i++;
894
- } else if (r.required) {
895
- return false;
896
- }
897
- }
898
- return i === idTokens.length;
899
- };
900
-
901
- /**
902
- * Derive `verbNoun` from `METHOD /path` for operations whose operationId
903
- * is missing or mechanical:
904
- *
905
- * GET /users → listUsers (when the 200 body is a
906
- * collection; else getUsers)
907
- * GET /users/{id} → getUser
908
- * POST /users → createUser
909
- * POST /users/{id} → updateUser (Stripe-style POST-to-update)
910
- * PUT /users/{id} → putUser (replace semantics kept)
911
- * PATCH /users/{id} → updateUser
912
- * DELETE /users/{id} → deleteUser
913
- * POST /users/{id}/reset → resetUser (trailing action segment)
914
- * GET /orgs/{o}/repos → listOrgRepos (parents, singular, keep order)
915
- *
916
- * `/api`, `/v1`-style roots are dropped. Path parameters contribute nothing
917
- * to the name; only literal segments do.
918
- */
919
- export interface PathNamingHints {
920
- /**
921
- * Whether the success response is a collection (array body, or an
922
- * object whose only/primary member is an array). Decides `list` vs
923
- * `get` for a GET on a route with no trailing parameter.
924
- */
925
- readonly returnsCollection?: boolean;
926
- /**
927
- * A mechanical operationId (`get-feeds`, `delete_v1_users_id`) whose
928
- * noun tokens, after the method, should be used verbatim instead of
929
- * being re-derived (and re-singularised) from the route.
930
- */
931
- readonly nouns?: string;
932
- /**
933
- * `nouns` is the route spelled out (`postV1AppsByAppIdPromote`), so
934
- * parameter tokens embedded without a `By` (`get_v1_users_id`) and
935
- * every `By…` clause are dropped, and the resource is singularised
936
- * when a parameter follows it.
937
- */
938
- readonly verbatim?: boolean;
939
- }
940
-
941
- export const pathToVerbNoun = (ctx: OperationIdContext, hints: PathNamingHints = {}): string => {
942
- const method = ctx.method.toLowerCase();
943
- const segments = ctx.path.split(/[?#]/)[0]!.split("/").filter(Boolean);
944
- const literal: string[] = [];
945
- // `{id}`, `:id`, and composite segments such as `{slug}-{id}`.
946
- const isParam = (seg: string) => /\{[^}]*\}/.test(seg) || seg.startsWith(":");
947
- let endsWithParam = false;
948
- for (let i = 0; i < segments.length; i++) {
949
- const seg = segments[i]!;
950
- if (isParam(seg)) {
951
- endsWithParam = i === segments.length - 1;
952
- continue;
953
- }
954
- endsWithParam = false;
955
- if (isNoiseSegment(seg)) continue;
956
- literal.push(seg);
957
- }
958
- if (literal.length === 0) return lowerFirst(method + "Root");
959
-
960
- if (hints.nouns !== undefined) {
961
- // `activity/get-feeds`: a tag prefix before the method is not a noun.
962
- const id = hints.nouns.includes("/")
963
- ? hints.nouns.slice(hints.nouns.lastIndexOf("/") + 1)
964
- : hints.nouns;
965
- const m = HTTP_METHOD_ID.exec(id);
966
- const rest = m ? id.slice(m[0].length) : id;
967
- // Route literals, both as written and singularised, so a parameter
968
- // that echoes a literal (`{team}` under `/teams/`) is not mistaken
969
- // for a parameter token.
970
- const literal = new Set(
971
- segments
972
- .filter((seg) => !isParam(seg))
973
- .flatMap((seg) => splitIdent(seg))
974
- .flatMap((t) => [t.toLowerCase(), singularize(t).toLowerCase()]),
975
- );
976
- const routeNoise = new Set(
977
- segments
978
- .filter((seg) => !isParam(seg) && isNoiseSegment(seg))
979
- .flatMap((seg) => splitIdent(seg).map((t) => t.toLowerCase())),
980
- );
981
- /** Whole parameter names as token lists (`{appId}` → ["app","id"]). */
982
- const params = segments
983
- .flatMap((seg) => [...seg.matchAll(/\{([^}]+)\}/g)])
984
- .map((mm) => splitIdent(mm[1]!).map((t) => t.toLowerCase()));
985
- const raw = splitIdent(rest);
986
- /** Longest whole parameter name starting at raw[at], else 0. */
987
- const matchParam = (at: number): number => {
988
- let best = 0;
989
- for (const prm of params) {
990
- if (prm.length > best && prm.every((t, k) => raw[at + k]?.toLowerCase() === t)) {
991
- best = prm.length;
992
- }
993
- }
994
- if (best === 0 && raw[at]?.toLowerCase() === "id") best = 1;
995
- return best;
996
- };
997
- const tokens: string[] = [];
998
- /** Index in `tokens` of a noun that a parameter immediately follows. */
999
- const followedByParam = new Set<number>();
1000
- for (let i = 0; i < raw.length; i++) {
1001
- const t = raw[i]!;
1002
- const lower = t.toLowerCase();
1003
- // `getApiV1Foo` → drop the api/version root the id copied from the
1004
- // route; a token the route does not have (`…DataAPI`) is kept.
1005
- if (isNoiseSegment(t) && routeNoise.has(lower)) continue;
1006
- let n = 0;
1007
- let skip = 0;
1008
- if (/^(by|for|of|in|with|and|to)$/.test(lower)) {
1009
- n = matchParam(i + 1);
1010
- skip = n + 1;
1011
- // Non-verbatim ids only drop a TRAILING `ById`; a `By` in the
1012
- // middle (`getBalanceByAsset`) is part of the chosen name.
1013
- if (n > 0 && !hints.verbatim && i + skip !== raw.length) n = 0;
1014
- } else if (hints.verbatim && i > 0) {
1015
- // `get_v1_users_id`, `GetAccountsAccount`: a whole parameter name
1016
- // with no `By`. When the parameter echoes the resource it follows
1017
- // (`/accounts/{account}`, `/teams/{team}`) the previous token has
1018
- // to be that resource; otherwise (`deleteProjectBranchCustomDomain`
1019
- // on `/custom-domains/{domain}`) it is the literal.
1020
- n = matchParam(i);
1021
- skip = n;
1022
- const echoes = raw.slice(i, i + n).some((x) => literal.has(x.toLowerCase()));
1023
- const prev = tokens.at(-1)?.toLowerCase();
1024
- const prevIsResource =
1025
- prev !== undefined &&
1026
- raw
1027
- .slice(i, i + n)
1028
- .some(
1029
- (x) => singularize(prev) === singularize(x.toLowerCase()) || prev === x.toLowerCase(),
1030
- );
1031
- if (echoes && !prevIsResource) n = 0;
1032
- }
1033
- if (n > 0) {
1034
- if (tokens.length) followedByParam.add(tokens.length - 1);
1035
- i += skip - 1;
1036
- continue;
1037
- }
1038
- tokens.push(t);
1039
- }
1040
- if (hints.verbatim) {
1041
- for (const i of followedByParam) tokens[i] = singularize(tokens[i]!);
1042
- // `PostAccounts` → createAccount: a create makes one member.
1043
- if (method === "post" && !endsWithParam && tokens.length > 0) {
1044
- tokens[tokens.length - 1] = singularize(tokens.at(-1)!);
1045
- }
1046
- }
1047
- if (tokens.length > 0) {
1048
- // A POST that addresses one member (`POST /accounts/{account}`,
1049
- // Stripe-style) updates it; a POST on a collection creates.
1050
- const verb =
1051
- method === "get"
1052
- ? !endsWithParam && hints.returnsCollection === true
1053
- ? "list"
1054
- : "get"
1055
- : method === "post"
1056
- ? endsWithParam
1057
- ? "update"
1058
- : "create"
1059
- : method === "patch"
1060
- ? "update"
1061
- : method;
1062
- return verb + tokens.map(pascalToken).join("");
1063
- }
1064
- }
1065
-
1066
- const tokens = literal.map((seg) => splitIdent(seg));
1067
- const lastTokens = tokens.at(-1)!;
1068
- // `/papers/index`, `/opensearch/index` address an index resource, not a
1069
- // Rails `index` action.
1070
- const lastIsVerb =
1071
- lastTokens.length > 0 &&
1072
- !isIndexVerb(lastTokens[0]!) &&
1073
- (isTrailingVerb(lastTokens[0]!) || isStrongVerb(lastTokens[0]!)) &&
1074
- !endsWithParam &&
1075
- method === "post";
1076
-
1077
- // POST /things/{id}/publish → publishThing; POST /login → login.
1078
- if (lastIsVerb) {
1079
- const [verb, ...rest] = lastTokens;
1080
- const parents = tokens.slice(0, -1);
1081
- const nouns = parents.map((t, i) =>
1082
- i === parents.length - 1 ? t.map((x, j) => (j === t.length - 1 ? singularize(x) : x)) : t,
1083
- );
1084
- return alias(verb!) + nouns.flat().map(pascalToken).join("") + rest.map(pascalToken).join("");
1085
- }
1086
-
1087
- // GET is `list` only when the body is known to be a collection; an
1088
- // unknown or non-JSON body (`/zen`, `/octocat`) is a plain `get`.
1089
- const verb =
1090
- method === "get"
1091
- ? !endsWithParam && hints.returnsCollection === true
1092
- ? "list"
1093
- : "get"
1094
- : method === "post"
1095
- ? endsWithParam
1096
- ? "update"
1097
- : "create"
1098
- : method === "patch"
1099
- ? "update"
1100
- : method === "put"
1101
- ? "put"
1102
- : method === "delete"
1103
- ? "delete"
1104
- : method;
1105
- // A GET/DELETE/PATCH/PUT on a collection route (no trailing parameter)
1106
- // addresses the collection itself — keep its plural. With a trailing
1107
- // parameter the route addresses one member, and `create` always makes
1108
- // one — singular.
1109
- const plural = !endsWithParam && verb !== "create";
1110
- const shaped = tokens.map((t, i) => {
1111
- const isResource = i === tokens.length - 1;
1112
- return t.map((x, j) => {
1113
- const last = j === t.length - 1;
1114
- if (!last) return pascalToken(x);
1115
- // Parents are singular (`Org` in listOrgRepos).
1116
- if (!isResource || !plural) return pascalToken(singularize(x));
1117
- return pascalToken(x);
1118
- });
1119
- });
1120
- return verb + shaped.flat().join("");
1121
- };
1122
-
1123
- /**
1124
- * Rename operations (and every shape whose name starts with the operation
1125
- * name — `FooRequest`, `FooResponse`, `FooRequestBody`, `FooResponseItemsList`)
1126
- * in a Smithy model to verbNoun PascalCase. Mutates `model.shapes`.
1127
- * Colliding names keep the original id and are reported.
1128
- */
1129
- export const verbNounSmithyModel = (model: {
1130
- shapes?: Record<string, any>;
1131
- }): { renamed: number; collisions: string[] } => {
1132
- const shapes = model.shapes ?? {};
1133
- const mapping = new Map<string, string>();
1134
- const mappedTo = new Set<string>();
1135
- const collisions: string[] = [];
1136
- const ids = Object.keys(shapes);
1137
- const taken = new Set(ids);
1138
- const order = new Map(ids.map((id, i) => [id, i]));
1139
-
1140
- const split = (id: string): [ns: string, local: string] => {
1141
- const hash = id.indexOf("#");
1142
- return hash >= 0 ? [id.slice(0, hash), id.slice(hash + 1)] : ["", id];
1143
- };
1144
- // Local names per namespace in code-unit order, so the shapes whose name
1145
- // starts with an operation's are one contiguous run (found by binary
1146
- // search) instead of a scan of every shape per operation.
1147
- const localsByNs = new Map<string, string[]>();
1148
- for (const id of ids) {
1149
- const [ns, local] = split(id);
1150
- const list = localsByNs.get(ns);
1151
- if (list) list.push(local);
1152
- else localsByNs.set(ns, [local]);
1153
- }
1154
- for (const list of localsByNs.values()) list.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
1155
- const withPrefix = (ns: string, prefix: string): string[] => {
1156
- const list = localsByNs.get(ns) ?? [];
1157
- let lo = 0;
1158
- let hi = list.length;
1159
- while (lo < hi) {
1160
- const mid = (lo + hi) >>> 1;
1161
- if (list[mid]! < prefix) lo = mid + 1;
1162
- else hi = mid;
1163
- }
1164
- const out: string[] = [];
1165
- for (let i = lo; i < list.length && list[i]!.startsWith(prefix); i++) {
1166
- out.push(ns ? `${ns}#${list[i]}` : list[i]!);
1167
- }
1168
- // Model order, as a scan of every shape would visit them.
1169
- return out.sort((a, b) => order.get(a)! - order.get(b)!);
1170
- };
1171
-
1172
- const ops = Object.entries(shapes).filter(([, def]) => def?.type === "operation");
1173
-
1174
- for (const [id] of ops) {
1175
- const [ns, local] = split(id);
1176
- const camel = toVerbNoun(local);
1177
- const nextLocal = camel.charAt(0).toUpperCase() + camel.slice(1);
1178
- if (nextLocal === local) continue;
1179
- const nextId = ns ? `${ns}#${nextLocal}` : nextLocal;
1180
- if (taken.has(nextId) && !mapping.has(nextId)) {
1181
- collisions.push(`${local} → ${nextLocal}`);
1182
- continue;
1183
- }
1184
- if (mappedTo.has(nextId)) {
1185
- collisions.push(`${local} → ${nextLocal}`);
1186
- continue;
1187
- }
1188
- mapping.set(id, nextId);
1189
- mappedTo.add(nextId);
1190
- taken.add(nextId);
1191
-
1192
- // Companions: `<Op>Request`, `<Op>Response…`, and anything derived
1193
- // from them by the converters' `${opName}Request${Member}` naming.
1194
- // Skip prefixes that are themselves another operation's name
1195
- // (`Get` vs `GetObject`) — only exact suffix matches count there.
1196
- for (const candidate of withPrefix(ns, local)) {
1197
- if (candidate === id || mapping.has(candidate)) continue;
1198
- const tail = split(candidate)[1].slice(local.length);
1199
- if (tail === "") continue;
1200
- const suffixed = COMPANION_SUFFIXES.some((s) => tail.startsWith(s));
1201
- if (!suffixed) continue;
1202
- // `ListAppsRequest` vs op `List` + `AppsRequest`: require the tail to
1203
- // start with a companion suffix immediately after the op name.
1204
- const to = ns ? `${ns}#${nextLocal}${tail}` : `${nextLocal}${tail}`;
1205
- if (taken.has(to)) continue;
1206
- mapping.set(candidate, to);
1207
- mappedTo.add(to);
1208
- taken.add(to);
1209
- }
1210
- }
1211
-
1212
- if (mapping.size === 0) return { renamed: 0, collisions };
1213
-
1214
- renameShapes(model, mapping);
1215
- return {
1216
- renamed: ops.filter(([opId]) => mapping.has(opId)).length,
1217
- collisions,
1218
- };
1219
- };