@apifuse/provider-sdk 2.2.0-beta.3 → 2.2.0-beta.30

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 (342) hide show
  1. package/AUTHORING.md +493 -5
  2. package/CHANGELOG.md +127 -1
  3. package/README.md +52 -6
  4. package/SUBMISSION.md +1 -1
  5. package/bin/apifuse-check.ts +106 -62
  6. package/bin/apifuse-create.ts +1 -1
  7. package/bin/apifuse-dev.ts +63 -55
  8. package/bin/apifuse-pack-check.ts +22 -2
  9. package/bin/apifuse-pack-smoke.ts +78 -82
  10. package/bin/apifuse-pack-types.ts +583 -0
  11. package/bin/apifuse-perf.ts +59 -140
  12. package/bin/apifuse-record.ts +698 -113
  13. package/bin/apifuse-submit-check.ts +517 -44
  14. package/bin/apifuse-sync-assets.ts +117 -0
  15. package/bin/apifuse.ts +1 -1
  16. package/bin/submit-check-delimited-text.ts +50 -0
  17. package/bin/submit-check-xml.ts +1 -1
  18. package/dist/auth-turn/index.d.ts +4 -4
  19. package/dist/auth-turn/index.js +1 -1
  20. package/dist/auth.d.ts +16 -2
  21. package/dist/auth.js +76 -18
  22. package/dist/ceremonies/index.d.ts +9 -1
  23. package/dist/ceremonies/index.js +117 -29
  24. package/dist/cli/commands.d.ts +1 -1
  25. package/dist/cli/commands.js +8 -0
  26. package/dist/cli/create.d.ts +3 -0
  27. package/dist/cli/create.js +34 -35
  28. package/dist/cli/prompt-assets.d.ts +80 -0
  29. package/dist/cli/prompt-assets.js +743 -0
  30. package/dist/cli/templates/provider/AGENTS.md.tpl +17 -8
  31. package/dist/cli/templates/provider/README.md.tpl +4 -4
  32. package/dist/config/loader.d.ts +176 -17
  33. package/dist/config/loader.js +434 -161
  34. package/dist/contract-serialization.d.ts +2 -2
  35. package/dist/contract-serialization.js +7 -14
  36. package/dist/contract-types.d.ts +3 -2
  37. package/dist/contract.d.ts +3 -3
  38. package/dist/contract.js +6 -6
  39. package/dist/declaration-validation.d.ts +23 -0
  40. package/dist/declaration-validation.js +159 -0
  41. package/dist/define.d.ts +13 -1
  42. package/dist/define.js +391 -122
  43. package/dist/dev.d.ts +1 -1
  44. package/dist/dev.js +1 -1
  45. package/dist/error-resolution.d.ts +4 -0
  46. package/dist/error-resolution.js +122 -0
  47. package/dist/errors.d.ts +19 -1
  48. package/dist/errors.js +41 -3
  49. package/dist/fixture-sanitization.d.ts +26 -0
  50. package/dist/fixture-sanitization.js +216 -0
  51. package/dist/i18n/catalog.d.ts +2 -2
  52. package/dist/i18n/catalog.js +4 -10
  53. package/dist/i18n/index.d.ts +2 -2
  54. package/dist/i18n/index.js +2 -2
  55. package/dist/i18n/keys.d.ts +2 -2
  56. package/dist/index.d.ts +50 -42
  57. package/dist/index.js +41 -37
  58. package/dist/lint.d.ts +6 -1
  59. package/dist/lint.js +370 -18
  60. package/dist/native-address.d.ts +43 -0
  61. package/dist/native-address.js +281 -0
  62. package/dist/native-egress-policy.d.ts +31 -0
  63. package/dist/native-egress-policy.js +288 -0
  64. package/dist/observability.d.ts +5 -2
  65. package/dist/observability.js +48 -1
  66. package/dist/provider.d.ts +13 -11
  67. package/dist/provider.js +10 -9
  68. package/dist/public-schema-field-lint.d.ts +1 -1
  69. package/dist/recipes/gov-api.js +1 -1
  70. package/dist/runtime/auth-flow.d.ts +3 -1
  71. package/dist/runtime/auth-flow.js +8 -3
  72. package/dist/runtime/browser.d.ts +1 -1
  73. package/dist/runtime/browser.js +138 -40
  74. package/dist/runtime/cache.d.ts +2 -1
  75. package/dist/runtime/cache.js +173 -23
  76. package/dist/runtime/choice-wordlist.d.ts +9 -0
  77. package/dist/runtime/choice-wordlist.js +138 -0
  78. package/dist/runtime/choice.d.ts +13 -1
  79. package/dist/runtime/choice.js +514 -124
  80. package/dist/runtime/credential.d.ts +1 -1
  81. package/dist/runtime/credential.js +1 -1
  82. package/dist/runtime/env.d.ts +1 -1
  83. package/dist/runtime/executor.d.ts +1 -1
  84. package/dist/runtime/executor.js +25 -3
  85. package/dist/runtime/http.d.ts +3 -2
  86. package/dist/runtime/http.js +517 -55
  87. package/dist/runtime/insights.d.ts +1 -1
  88. package/dist/runtime/insights.js +6 -13
  89. package/dist/runtime/instrumentation.d.ts +2 -2
  90. package/dist/runtime/instrumentation.js +371 -23
  91. package/dist/runtime/keyring.js +1 -1
  92. package/dist/runtime/namespace.js +1 -1
  93. package/dist/runtime/native-network-errors.d.ts +33 -0
  94. package/dist/runtime/native-network-errors.js +69 -0
  95. package/dist/runtime/native-network.d.ts +96 -0
  96. package/dist/runtime/native-network.js +1232 -0
  97. package/dist/runtime/ocr.d.ts +29 -0
  98. package/dist/runtime/ocr.js +440 -0
  99. package/dist/runtime/otlp.d.ts +1 -1
  100. package/dist/runtime/perf.d.ts +1 -1
  101. package/dist/runtime/provider.d.ts +1 -1
  102. package/dist/runtime/provider.js +1 -2
  103. package/dist/runtime/proxy-errors.d.ts +1 -1
  104. package/dist/runtime/proxy-errors.js +9 -7
  105. package/dist/runtime/proxy-nodemaven.d.ts +56 -0
  106. package/dist/runtime/proxy-nodemaven.js +146 -0
  107. package/dist/runtime/proxy-retry-policy.d.ts +2 -2
  108. package/dist/runtime/proxy-retry-policy.js +2 -2
  109. package/dist/runtime/proxy-telemetry.d.ts +2 -1
  110. package/dist/runtime/proxy-telemetry.js +58 -52
  111. package/dist/runtime/redirects.d.ts +29 -0
  112. package/dist/runtime/redirects.js +36 -0
  113. package/dist/runtime/redis.d.ts +1 -1
  114. package/dist/runtime/redis.js +5 -5
  115. package/dist/runtime/request-options.d.ts +68 -1
  116. package/dist/runtime/request-options.js +548 -0
  117. package/dist/runtime/resolver-config.d.ts +6 -0
  118. package/dist/runtime/resolver-config.js +6 -0
  119. package/dist/runtime/resolver-public.d.ts +1 -0
  120. package/dist/runtime/resolver-public.js +1 -0
  121. package/dist/runtime/resolver-shared.d.ts +3 -0
  122. package/dist/runtime/resolver-shared.js +12 -0
  123. package/dist/runtime/resolver-vendors/bindings.d.ts +48 -0
  124. package/dist/runtime/resolver-vendors/bindings.js +40 -0
  125. package/dist/runtime/resolver-vendors/browser.d.ts +20 -0
  126. package/dist/runtime/resolver-vendors/browser.js +282 -0
  127. package/dist/runtime/resolver-vendors/hosts.d.ts +2 -0
  128. package/dist/runtime/resolver-vendors/hosts.js +33 -0
  129. package/dist/runtime/resolver-vendors/twocaptcha.d.ts +24 -0
  130. package/dist/runtime/resolver-vendors/twocaptcha.js +368 -0
  131. package/dist/runtime/resolver-vendors/types.d.ts +83 -0
  132. package/dist/runtime/resolver-vendors/types.js +69 -0
  133. package/dist/runtime/resolver.d.ts +59 -0
  134. package/dist/runtime/resolver.js +705 -0
  135. package/dist/runtime/secrets.d.ts +27 -0
  136. package/dist/runtime/secrets.js +51 -0
  137. package/dist/runtime/state.d.ts +5 -2
  138. package/dist/runtime/state.js +280 -74
  139. package/dist/runtime/stealth-cookies.d.ts +20 -0
  140. package/dist/runtime/stealth-cookies.js +111 -0
  141. package/dist/runtime/stealth.d.ts +30 -5
  142. package/dist/runtime/stealth.js +523 -259
  143. package/dist/runtime/stt.d.ts +1 -1
  144. package/dist/runtime/stt.js +12 -27
  145. package/dist/runtime/timeout.d.ts +5 -0
  146. package/dist/runtime/timeout.js +12 -0
  147. package/dist/runtime/trace.d.ts +2 -2
  148. package/dist/runtime/trace.js +2 -4
  149. package/dist/runtime/waterfall.d.ts +1 -1
  150. package/dist/schema.d.ts +1 -1
  151. package/dist/schema.js +7 -15
  152. package/dist/serve.d.ts +1 -1
  153. package/dist/serve.js +1 -1
  154. package/dist/server/index.d.ts +7 -7
  155. package/dist/server/index.js +6 -6
  156. package/dist/server/self-test-input-tokens.d.ts +2 -1
  157. package/dist/server/self-test-input-tokens.js +18 -14
  158. package/dist/server/self-test-redaction.d.ts +1 -1
  159. package/dist/server/self-test-redaction.js +1 -1
  160. package/dist/server/self-test.d.ts +117 -3
  161. package/dist/server/self-test.js +787 -151
  162. package/dist/server/serve-implementation.d.ts +210 -0
  163. package/dist/server/serve-implementation.js +2077 -0
  164. package/dist/server/serve.d.ts +1 -70
  165. package/dist/server/serve.js +1 -1143
  166. package/dist/server/types.d.ts +34 -9
  167. package/dist/server/types.js +8 -1
  168. package/dist/stateful/errors.d.ts +19 -0
  169. package/dist/stateful/errors.js +24 -0
  170. package/dist/stateful/http-provider-event-emitter.d.ts +40 -0
  171. package/dist/stateful/http-provider-event-emitter.js +237 -0
  172. package/dist/stateful/http-session-owner-registry.d.ts +44 -0
  173. package/dist/stateful/http-session-owner-registry.js +210 -0
  174. package/dist/stateful/index.d.ts +18 -0
  175. package/dist/stateful/index.js +18 -0
  176. package/dist/stateful/provider-event-delivery-failures.d.ts +32 -0
  177. package/dist/stateful/provider-event-delivery-failures.js +43 -0
  178. package/dist/stateful/provider-event-pipeline-metrics.d.ts +46 -0
  179. package/dist/stateful/provider-event-pipeline-metrics.js +48 -0
  180. package/dist/stateful/provider-event-pipeline.d.ts +50 -0
  181. package/dist/stateful/provider-event-pipeline.js +1 -0
  182. package/dist/stateful/provider-events.d.ts +101 -0
  183. package/dist/stateful/provider-events.js +289 -0
  184. package/dist/stateful/session-key.d.ts +15 -0
  185. package/dist/stateful/session-key.js +86 -0
  186. package/dist/stateful/stateful-provider-adapter-context.d.ts +5 -0
  187. package/dist/stateful/stateful-provider-adapter-context.js +42 -0
  188. package/dist/stateful/stateful-provider-adapter-metrics.d.ts +15 -0
  189. package/dist/stateful/stateful-provider-adapter-metrics.js +21 -0
  190. package/dist/stateful/stateful-provider-adapter.d.ts +98 -0
  191. package/dist/stateful/stateful-provider-adapter.js +287 -0
  192. package/dist/stateful/stateful-provider-observability.d.ts +62 -0
  193. package/dist/stateful/stateful-provider-observability.js +161 -0
  194. package/dist/stateful/stateful-provider-owner-forwarder.d.ts +41 -0
  195. package/dist/stateful/stateful-provider-owner-forwarder.js +215 -0
  196. package/dist/stateful/stateful-provider-runtime-context.d.ts +32 -0
  197. package/dist/stateful/stateful-provider-runtime-context.js +60 -0
  198. package/dist/stateful/stateful-provider-runtime-executor.d.ts +34 -0
  199. package/dist/stateful/stateful-provider-runtime-executor.js +52 -0
  200. package/dist/stateful/stateful-provider-session-routing.d.ts +67 -0
  201. package/dist/stateful/stateful-provider-session-routing.js +345 -0
  202. package/dist/stateful/stateful-provider-session-runtime.d.ts +98 -0
  203. package/dist/stateful/stateful-provider-session-runtime.js +245 -0
  204. package/dist/stateful-signing.d.ts +18 -0
  205. package/dist/stateful-signing.js +27 -0
  206. package/dist/stealth/profiles.d.ts +1 -1
  207. package/dist/stealth/profiles.js +21 -21
  208. package/dist/stream-evidence.d.ts +74 -0
  209. package/dist/stream-evidence.js +785 -0
  210. package/dist/stream.d.ts +1 -1
  211. package/dist/stream.js +7 -1
  212. package/dist/testing/index.d.ts +3 -2
  213. package/dist/testing/index.js +3 -2
  214. package/dist/testing/run.d.ts +32 -2
  215. package/dist/testing/run.js +488 -28
  216. package/dist/types.d.ts +566 -19
  217. package/dist/types.js +1 -0
  218. package/dist/user-input.d.ts +30 -0
  219. package/dist/user-input.js +66 -0
  220. package/package.json +42 -7
  221. package/src/auth-turn/index.ts +2 -2
  222. package/src/auth.ts +146 -86
  223. package/src/ceremonies/index.ts +167 -92
  224. package/src/cli/commands.ts +10 -0
  225. package/src/cli/create.ts +42 -35
  226. package/src/cli/prompt-assets.ts +865 -0
  227. package/src/cli/templates/provider/AGENTS.md.tpl +17 -8
  228. package/src/cli/templates/provider/README.md.tpl +4 -4
  229. package/src/config/loader.ts +667 -289
  230. package/src/contract-serialization.ts +10 -18
  231. package/src/contract-types.ts +3 -2
  232. package/src/contract.ts +14 -28
  233. package/src/declaration-validation.ts +202 -0
  234. package/src/define.ts +631 -495
  235. package/src/dev.ts +4 -9
  236. package/src/error-resolution.ts +127 -0
  237. package/src/errors.ts +56 -11
  238. package/src/fixture-sanitization.ts +247 -0
  239. package/src/i18n/catalog.ts +10 -32
  240. package/src/i18n/index.ts +2 -2
  241. package/src/i18n/keys.ts +5 -11
  242. package/src/index.ts +157 -44
  243. package/src/lint.ts +488 -154
  244. package/src/native-address.ts +340 -0
  245. package/src/native-egress-policy.ts +358 -0
  246. package/src/observability.ts +51 -1
  247. package/src/provider.ts +65 -11
  248. package/src/public-schema-field-lint.ts +7 -33
  249. package/src/recipes/gov-api.ts +2 -5
  250. package/src/runtime/auth-flow.ts +13 -7
  251. package/src/runtime/browser.ts +252 -207
  252. package/src/runtime/cache.ts +209 -81
  253. package/src/runtime/choice-wordlist.ts +145 -0
  254. package/src/runtime/choice.ts +685 -216
  255. package/src/runtime/credential.ts +2 -2
  256. package/src/runtime/env.ts +1 -1
  257. package/src/runtime/executor.ts +37 -19
  258. package/src/runtime/http.ts +645 -65
  259. package/src/runtime/insights.ts +15 -53
  260. package/src/runtime/instrumentation.ts +530 -67
  261. package/src/runtime/keyring.ts +7 -19
  262. package/src/runtime/namespace.ts +2 -7
  263. package/src/runtime/native-network-errors.ts +99 -0
  264. package/src/runtime/native-network.ts +1605 -0
  265. package/src/runtime/ocr.ts +523 -0
  266. package/src/runtime/otlp.ts +12 -23
  267. package/src/runtime/perf.ts +1 -1
  268. package/src/runtime/provider.ts +4 -9
  269. package/src/runtime/proxy-errors.ts +29 -42
  270. package/src/runtime/proxy-nodemaven.ts +221 -0
  271. package/src/runtime/proxy-retry-policy.ts +3 -3
  272. package/src/runtime/proxy-telemetry.ts +84 -77
  273. package/src/runtime/redirects.ts +66 -0
  274. package/src/runtime/redis.ts +10 -13
  275. package/src/runtime/request-options.ts +679 -9
  276. package/src/runtime/resolver-config.ts +6 -0
  277. package/src/runtime/resolver-public.ts +18 -0
  278. package/src/runtime/resolver-shared.ts +17 -0
  279. package/src/runtime/resolver-vendors/bindings.ts +56 -0
  280. package/src/runtime/resolver-vendors/browser.ts +408 -0
  281. package/src/runtime/resolver-vendors/hosts.ts +38 -0
  282. package/src/runtime/resolver-vendors/twocaptcha.ts +500 -0
  283. package/src/runtime/resolver-vendors/types.ts +173 -0
  284. package/src/runtime/resolver.ts +1060 -0
  285. package/src/runtime/secrets.ts +64 -0
  286. package/src/runtime/state.ts +399 -161
  287. package/src/runtime/stealth-cookies.ts +132 -0
  288. package/src/runtime/stealth.ts +681 -295
  289. package/src/runtime/stt.ts +39 -113
  290. package/src/runtime/timeout.ts +18 -0
  291. package/src/runtime/trace.ts +14 -44
  292. package/src/runtime/waterfall.ts +5 -18
  293. package/src/schema.ts +23 -84
  294. package/src/serve.ts +6 -1
  295. package/src/server/index.ts +30 -7
  296. package/src/server/self-test-input-tokens.ts +29 -14
  297. package/src/server/self-test-redaction.ts +2 -2
  298. package/src/server/self-test.ts +1030 -180
  299. package/src/server/serve-implementation.ts +3060 -0
  300. package/src/server/serve.ts +1 -1781
  301. package/src/server/types.ts +12 -13
  302. package/src/stateful/README.md +146 -0
  303. package/src/stateful/errors.ts +35 -0
  304. package/src/stateful/http-provider-event-emitter.ts +314 -0
  305. package/src/stateful/http-session-owner-registry.ts +306 -0
  306. package/src/stateful/index.ts +18 -0
  307. package/src/stateful/provider-event-delivery-failures.ts +80 -0
  308. package/src/stateful/provider-event-pipeline-metrics.ts +95 -0
  309. package/src/stateful/provider-event-pipeline.ts +61 -0
  310. package/src/stateful/provider-events.ts +462 -0
  311. package/src/stateful/session-key.ts +111 -0
  312. package/src/stateful/stateful-provider-adapter-context.ts +59 -0
  313. package/src/stateful/stateful-provider-adapter-metrics.ts +48 -0
  314. package/src/stateful/stateful-provider-adapter.ts +562 -0
  315. package/src/stateful/stateful-provider-observability.ts +261 -0
  316. package/src/stateful/stateful-provider-owner-forwarder.ts +287 -0
  317. package/src/stateful/stateful-provider-runtime-context.ts +92 -0
  318. package/src/stateful/stateful-provider-runtime-executor.ts +96 -0
  319. package/src/stateful/stateful-provider-session-routing.ts +546 -0
  320. package/src/stateful/stateful-provider-session-runtime.ts +403 -0
  321. package/src/stateful-signing.ts +46 -0
  322. package/src/stealth/profiles.ts +27 -33
  323. package/src/stream-evidence.ts +988 -0
  324. package/src/stream.ts +16 -20
  325. package/src/testing/index.ts +11 -2
  326. package/src/testing/run.ts +668 -74
  327. package/src/types.ts +665 -35
  328. package/src/user-input.ts +118 -0
  329. package/dist/cli/templates/provider/CLAUDE.md.tpl +0 -1
  330. package/src/cli/templates/provider/CLAUDE.md.tpl +0 -1
  331. /package/dist/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
  332. /package/dist/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
  333. /package/dist/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
  334. /package/dist/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
  335. /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
  336. /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
  337. /package/src/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
  338. /package/src/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
  339. /package/src/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
  340. /package/src/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
  341. /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
  342. /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
@@ -1,4 +1,4 @@
1
- import { ProviderError, TransportError, ValidationError } from "../errors";
1
+ import { ProviderError, TransportError, ValidationError } from "../errors.js";
2
2
  import type {
3
3
  Bcp47Locale,
4
4
  ProviderSttConfig,
@@ -13,16 +13,15 @@ import type {
13
13
  VerificationCodeCandidate,
14
14
  VerificationCodeCandidateSource,
15
15
  VerificationCodeExtractionResult,
16
- } from "../types";
16
+ } from "../types.js";
17
+ import { createTimeoutController, isTimeoutLikeError } from "./timeout.js";
17
18
 
18
19
  export const APIFUSE__STT__BACKEND_ENV = "APIFUSE__STT__BACKEND";
19
20
  export const APIFUSE__STT__MODEL_ENV = "APIFUSE__STT__MODEL";
20
21
  export const CLOUDFLARE_ACCOUNT_ID_ENV = "APIFUSE__CLOUDFLARE__ACCOUNT_ID";
21
- export const APIFUSE__STT__CLOUDFLARE_API_TOKEN_ENV =
22
- "APIFUSE__STT__CLOUDFLARE_API_TOKEN";
22
+ export const APIFUSE__STT__CLOUDFLARE_API_TOKEN_ENV = "APIFUSE__STT__CLOUDFLARE_API_TOKEN";
23
23
  export const CLOUDFLARE_WORKERS_AI_STT_BACKEND = "cloudflare-workers-ai";
24
- export const DEFAULT_CLOUDFLARE_WORKERS_AI_STT_MODEL =
25
- "@cf/openai/whisper-large-v3-turbo";
24
+ export const DEFAULT_CLOUDFLARE_WORKERS_AI_STT_MODEL = "@cf/openai/whisper-large-v3-turbo";
26
25
  export const DEFAULT_STT_MAX_AUDIO_BYTES = 10 * 1024 * 1024;
27
26
  export const DEFAULT_STT_TIMEOUT_MS = 30_000;
28
27
 
@@ -45,10 +44,7 @@ type ErrorSttClientOptions = {
45
44
  fix?: string;
46
45
  };
47
46
 
48
- function providerError(
49
- message: string,
50
- options: { code: string; fix?: string },
51
- ): ProviderError {
47
+ function providerError(message: string, options: { code: string; fix?: string }): ProviderError {
52
48
  return new ProviderError(message, options);
53
49
  }
54
50
 
@@ -82,9 +78,7 @@ export function createSttClientFromEnv(
82
78
  env: EnvLike = process.env,
83
79
  ): SttContext {
84
80
  if (!config) {
85
- return createUnsupportedSttClient(
86
- "Provider does not declare STT capability",
87
- );
81
+ return createUnsupportedSttClient("Provider does not declare STT capability");
88
82
  }
89
83
 
90
84
  const backend = normalizedEnvValue(env, APIFUSE__STT__BACKEND_ENV);
@@ -116,25 +110,17 @@ export function createSttClientFromEnv(
116
110
  accountId,
117
111
  apiToken,
118
112
  model:
119
- normalizedEnvValue(env, APIFUSE__STT__MODEL_ENV) ??
120
- DEFAULT_CLOUDFLARE_WORKERS_AI_STT_MODEL,
113
+ normalizedEnvValue(env, APIFUSE__STT__MODEL_ENV) ?? DEFAULT_CLOUDFLARE_WORKERS_AI_STT_MODEL,
121
114
  });
122
115
  }
123
116
 
124
117
  function base64ByteLength(data: string): number {
125
118
  const normalized = data.trim();
126
- const padding = normalized.endsWith("==")
127
- ? 2
128
- : normalized.endsWith("=")
129
- ? 1
130
- : 0;
119
+ const padding = normalized.endsWith("==") ? 2 : normalized.endsWith("=") ? 1 : 0;
131
120
  return Math.floor((normalized.length * 3) / 4) - padding;
132
121
  }
133
122
 
134
- function assertBase64Audio(
135
- audio: SttAudioInput,
136
- maxAudioBytes: number | undefined,
137
- ): number {
123
+ function assertBase64Audio(audio: SttAudioInput, maxAudioBytes: number | undefined): number {
138
124
  if (audio.kind !== "base64") {
139
125
  throw new ValidationError("Unsupported STT audio input kind", {
140
126
  code: "UNSUPPORTED_STT_OPTION",
@@ -142,32 +128,22 @@ function assertBase64Audio(
142
128
  });
143
129
  }
144
130
  const data = audio.data.trim();
145
- if (
146
- data.length === 0 ||
147
- data.length % 4 !== 0 ||
148
- !BASE64_AUDIO_PATTERN.test(data)
149
- ) {
150
- throw new ValidationError(
151
- "STT audio.data must be a base64-encoded string",
152
- {
153
- code: "INVALID_STT_AUDIO",
154
- },
155
- );
131
+ if (data.length === 0 || data.length % 4 !== 0 || !BASE64_AUDIO_PATTERN.test(data)) {
132
+ throw new ValidationError("STT audio.data must be a base64-encoded string", {
133
+ code: "INVALID_STT_AUDIO",
134
+ });
156
135
  }
157
136
  const bytes = base64ByteLength(data);
158
137
  const maxBytes = maxAudioBytes ?? DEFAULT_STT_MAX_AUDIO_BYTES;
159
138
  if (bytes > maxBytes) {
160
- throw new ValidationError(
161
- `STT audio exceeds maxAudioBytes (${bytes} > ${maxBytes})`,
162
- { code: "STT_AUDIO_TOO_LARGE" },
163
- );
139
+ throw new ValidationError(`STT audio exceeds maxAudioBytes (${bytes} > ${maxBytes})`, {
140
+ code: "STT_AUDIO_TOO_LARGE",
141
+ });
164
142
  }
165
143
  return bytes;
166
144
  }
167
145
 
168
- export function resolveSttPrompt(
169
- request: SttTranscribeRequest,
170
- ): string | undefined {
146
+ export function resolveSttPrompt(request: SttTranscribeRequest): string | undefined {
171
147
  const policy = effectivePromptPolicy(request);
172
148
  if (policy === "none") return undefined;
173
149
  if (policy === "default-hint") return DEFAULT_OTP_HINT;
@@ -183,29 +159,17 @@ function warnOrThrowUnsupportedOption(
183
159
  request: SttTranscribeRequest,
184
160
  message: string,
185
161
  ): { code: "UNSUPPORTED_STT_OPTION"; message: string } | undefined {
186
- const policy: SttUnsupportedOptionPolicy =
187
- request.unsupportedOptionPolicy ?? "warn";
162
+ const policy: SttUnsupportedOptionPolicy = request.unsupportedOptionPolicy ?? "warn";
188
163
  if (policy === "error") {
189
164
  throw new ProviderError(message, { code: "UNSUPPORTED_STT_OPTION" });
190
165
  }
191
166
  return { code: "UNSUPPORTED_STT_OPTION", message };
192
167
  }
193
168
 
194
- function normalizeCloudflareLanguage(
195
- language: Bcp47Locale | undefined,
196
- ): string | undefined {
169
+ function normalizeCloudflareLanguage(language: Bcp47Locale | undefined): string | undefined {
197
170
  return language?.split("-")[0]?.toLowerCase();
198
171
  }
199
172
 
200
- function isTimeoutLikeError(error: unknown): error is Error {
201
- return (
202
- error instanceof Error &&
203
- (error.name === "AbortError" ||
204
- error.name === "TimeoutError" ||
205
- /\b(timed out|timeout|deadline exceeded)\b/i.test(error.message))
206
- );
207
- }
208
-
209
173
  function toSttTransportError(error: unknown): TransportError {
210
174
  if (error instanceof TransportError) return error;
211
175
  if (isTimeoutLikeError(error)) {
@@ -222,19 +186,7 @@ function toSttTransportError(error: unknown): TransportError {
222
186
  });
223
187
  }
224
188
 
225
- function createTimeoutController(signalTimeoutMs: number): {
226
- controller: AbortController;
227
- clear: () => void;
228
- } {
229
- const controller = new AbortController();
230
- const timeout = setTimeout(() => controller.abort(), signalTimeoutMs);
231
- timeout.unref?.();
232
- return { controller, clear: () => clearTimeout(timeout) };
233
- }
234
-
235
- function toCloudflareInput(
236
- request: SttTranscribeRequest,
237
- ): Record<string, unknown> {
189
+ function toCloudflareInput(request: SttTranscribeRequest): Record<string, unknown> {
238
190
  const prompt = resolveSttPrompt(request);
239
191
  const input: Record<string, unknown> = {
240
192
  audio: request.audio.data.trim(),
@@ -273,8 +225,7 @@ function parseSegments(value: unknown): SttSegment[] | undefined {
273
225
  : typeof segment.endMs === "number"
274
226
  ? segment.endMs
275
227
  : undefined,
276
- confidence:
277
- typeof segment.confidence === "number" ? segment.confidence : undefined,
228
+ confidence: typeof segment.confidence === "number" ? segment.confidence : undefined,
278
229
  });
279
230
  }
280
231
  return segments.length > 0 ? segments : undefined;
@@ -288,13 +239,10 @@ function toSttTranscript(payload: unknown, audioBytes: number): SttTranscript {
288
239
  (typeof result?.text === "string" ? result.text : undefined) ??
289
240
  (typeof info?.text === "string" ? info.text : undefined);
290
241
  if (!text) {
291
- throw new TransportError(
292
- "STT upstream response did not include transcript text",
293
- {
294
- code: "STT_UPSTREAM_FAILED",
295
- status: 502,
296
- },
297
- );
242
+ throw new TransportError("STT upstream response did not include transcript text", {
243
+ code: "STT_UPSTREAM_FAILED",
244
+ status: 502,
245
+ });
298
246
  }
299
247
  const durationMs =
300
248
  typeof result?.durationMs === "number"
@@ -327,23 +275,15 @@ export function createCloudflareWorkersAiSttClient(
327
275
  return {
328
276
  async transcribe(request) {
329
277
  const warnings = [];
330
- if (
331
- request.initialPrompt &&
332
- effectivePromptPolicy(request) !== "custom-hint"
333
- ) {
278
+ if (request.initialPrompt && effectivePromptPolicy(request) !== "custom-hint") {
334
279
  const warning = warnOrThrowUnsupportedOption(
335
280
  request,
336
281
  "initialPrompt is honored only when promptPolicy is custom-hint",
337
282
  );
338
283
  if (warning) warnings.push(warning);
339
284
  }
340
- const audioBytes = assertBase64Audio(
341
- request.audio,
342
- request.maxAudioBytes,
343
- );
344
- const timeout = createTimeoutController(
345
- request.timeoutMs ?? DEFAULT_STT_TIMEOUT_MS,
346
- );
285
+ const audioBytes = assertBase64Audio(request.audio, request.maxAudioBytes);
286
+ const timeout = createTimeoutController(request.timeoutMs ?? DEFAULT_STT_TIMEOUT_MS);
347
287
  try {
348
288
  let response: Response;
349
289
  try {
@@ -388,10 +328,7 @@ export function createCloudflareWorkersAiSttClient(
388
328
  if (request.mode === "otp" || request.verificationCode) {
389
329
  return {
390
330
  ...withWarnings,
391
- verificationCode: extractVerificationCode(
392
- withWarnings.text,
393
- request.verificationCode,
394
- ),
331
+ verificationCode: extractVerificationCode(withWarnings.text, request.verificationCode),
395
332
  };
396
333
  }
397
334
  return withWarnings;
@@ -433,12 +370,9 @@ const KO_DIGITS: Record<string, string> = {
433
370
  구: "9",
434
371
  };
435
372
 
436
- function lengthSet(
437
- codeLengths: SttVerificationCodeOptions["codeLengths"],
438
- ): Set<number> {
373
+ function lengthSet(codeLengths: SttVerificationCodeOptions["codeLengths"]): Set<number> {
439
374
  if (codeLengths === undefined) return new Set([4, 5, 6, 7, 8]);
440
- if (typeof codeLengths === "number")
441
- return new Set([validCodeLength(codeLengths)]);
375
+ if (typeof codeLengths === "number") return new Set([validCodeLength(codeLengths)]);
442
376
  if (Array.isArray(codeLengths)) {
443
377
  const values = codeLengths.map((length) => validCodeLength(length));
444
378
  return new Set(values);
@@ -469,10 +403,9 @@ function lengthSet(
469
403
 
470
404
  function validCodeLength(value: number): number {
471
405
  if (!Number.isInteger(value) || value < 1 || value > 32) {
472
- throw new ValidationError(
473
- "STT verification code length must be an integer between 1 and 32",
474
- { code: "INVALID_STT_VERIFICATION_CODE_OPTIONS" },
475
- );
406
+ throw new ValidationError("STT verification code length must be an integer between 1 and 32", {
407
+ code: "INVALID_STT_VERIFICATION_CODE_OPTIONS",
408
+ });
476
409
  }
477
410
  return value;
478
411
  }
@@ -554,11 +487,7 @@ function tokenizeDigits(text: string): DigitToken[] {
554
487
  return tokens.sort((a, b) => a.startIndex - b.startIndex);
555
488
  }
556
489
 
557
- function isAdjacent(
558
- left: DigitToken,
559
- right: DigitToken,
560
- text: string,
561
- ): boolean {
490
+ function isAdjacent(left: DigitToken, right: DigitToken, text: string): boolean {
562
491
  const between = text.slice(left.endIndex, right.startIndex);
563
492
  return /^[\s,.:;\-_/]*$/u.test(between);
564
493
  }
@@ -608,12 +537,9 @@ export function extractVerificationCode(
608
537
  }
609
538
  const candidates = [...candidatesByCode.values()];
610
539
  if (candidates.length === 0) {
611
- throw new ProviderError(
612
- "No verification code candidate found in transcript",
613
- {
614
- code: "NO_CODE_FOUND",
615
- },
616
- );
540
+ throw new ProviderError("No verification code candidate found in transcript", {
541
+ code: "NO_CODE_FOUND",
542
+ });
617
543
  }
618
544
  if (candidates.length > 1) {
619
545
  throw new ProviderError("Multiple verification code candidates found", {
@@ -0,0 +1,18 @@
1
+ export function isTimeoutLikeError(error: unknown): error is Error {
2
+ return (
3
+ error instanceof Error &&
4
+ (error.name === "AbortError" ||
5
+ error.name === "TimeoutError" ||
6
+ /\b(timed out|timeout|deadline exceeded)\b/i.test(error.message))
7
+ );
8
+ }
9
+
10
+ export function createTimeoutController(signalTimeoutMs: number): {
11
+ controller: AbortController;
12
+ clear: () => void;
13
+ } {
14
+ const controller = new AbortController();
15
+ const timeout = setTimeout(() => controller.abort(), signalTimeoutMs);
16
+ timeout.unref?.();
17
+ return { controller, clear: () => clearTimeout(timeout) };
18
+ }
@@ -5,8 +5,8 @@ import type {
5
5
  TraceAttributeValue,
6
6
  TraceConfig,
7
7
  TraceSpan,
8
- } from "../types";
9
- import { exportSpansOTLP, type OTLPExportOptions } from "./otlp";
8
+ } from "../types.js";
9
+ import { exportSpansOTLP, type OTLPExportOptions } from "./otlp.js";
10
10
 
11
11
  export type SpanAttributeValue = TraceAttributeValue;
12
12
 
@@ -44,16 +44,10 @@ type CompletedSpanEntry = {
44
44
  };
45
45
 
46
46
  export interface TraceRecorder {
47
- runSpan<T>(
48
- name: string,
49
- fn: () => Promise<T> | T,
50
- options?: SpanHookOptions<T>,
51
- ): Promise<T>;
47
+ runSpan<T>(name: string, fn: () => Promise<T> | T, options?: SpanHookOptions<T>): Promise<T>;
52
48
  }
53
49
 
54
- export const TRACE_RECORDER = Symbol.for(
55
- "@apifuse/provider-sdk/runtime/trace-recorder",
56
- );
50
+ export const TRACE_RECORDER = Symbol.for("@apifuse/provider-sdk/runtime/trace-recorder");
57
51
 
58
52
  type InternalTraceContext = TraceContext & {
59
53
  [TRACE_RECORDER]: TraceRecorder;
@@ -61,9 +55,7 @@ type InternalTraceContext = TraceContext & {
61
55
  _resourceAttributes?: Record<string, string>;
62
56
  };
63
57
 
64
- function buildOTLPExportOptions(
65
- config?: TraceConfig,
66
- ): OTLPExportOptions | undefined {
58
+ function buildOTLPExportOptions(config?: TraceConfig): OTLPExportOptions | undefined {
67
59
  if (config?.exporter !== "otlp") {
68
60
  return undefined;
69
61
  }
@@ -80,9 +72,7 @@ function buildOTLPExportOptions(
80
72
  };
81
73
  }
82
74
 
83
- export function resolveTraceContextOptions(
84
- config?: TraceConfig,
85
- ): CreateTraceContextOptions {
75
+ export function resolveTraceContextOptions(config?: TraceConfig): CreateTraceContextOptions {
86
76
  return {
87
77
  maxSpans: config?.maxSpans,
88
78
  onSpan: config?.onSpan,
@@ -90,14 +80,8 @@ export function resolveTraceContextOptions(
90
80
  };
91
81
  }
92
82
 
93
- function normalizeAttributeValue(
94
- value: unknown,
95
- ): SpanAttributeValue | undefined {
96
- if (
97
- typeof value === "string" ||
98
- typeof value === "number" ||
99
- typeof value === "boolean"
100
- ) {
83
+ function normalizeAttributeValue(value: unknown): SpanAttributeValue | undefined {
84
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
101
85
  return value;
102
86
  }
103
87
 
@@ -117,10 +101,7 @@ function normalizeAttributes(
117
101
 
118
102
  const normalizedEntries = Object.entries(attributes)
119
103
  .map(([key, value]) => [key, normalizeAttributeValue(value)] as const)
120
- .filter(
121
- (entry): entry is readonly [string, SpanAttributeValue] =>
122
- entry[1] !== undefined,
123
- );
104
+ .filter((entry): entry is readonly [string, SpanAttributeValue] => entry[1] !== undefined);
124
105
 
125
106
  return Object.fromEntries(normalizedEntries);
126
107
  }
@@ -130,9 +111,7 @@ function insertCompletedSpan(
130
111
  entry: CompletedSpanEntry,
131
112
  maxSpans: number,
132
113
  ): void {
133
- const insertAt = completed.findIndex(
134
- (existingEntry) => existingEntry.sequence > entry.sequence,
135
- );
114
+ const insertAt = completed.findIndex((existingEntry) => existingEntry.sequence > entry.sequence);
136
115
 
137
116
  if (insertAt === -1) {
138
117
  completed.push(entry);
@@ -145,15 +124,11 @@ function insertCompletedSpan(
145
124
  }
146
125
  }
147
126
 
148
- export function getTraceRecorder(
149
- trace: BaseTraceContext,
150
- ): TraceRecorder | null {
127
+ export function getTraceRecorder(trace: BaseTraceContext): TraceRecorder | null {
151
128
  return (trace as Partial<InternalTraceContext>)[TRACE_RECORDER] ?? null;
152
129
  }
153
130
 
154
- export function createTraceContext(
155
- options: CreateTraceContextOptions = {},
156
- ): TraceContext {
131
+ export function createTraceContext(options: CreateTraceContextOptions = {}): TraceContext {
157
132
  const maxSpans = options.maxSpans ?? 1000;
158
133
  const completed: CompletedSpanEntry[] = [];
159
134
  const activeSpanStorage = new AsyncLocalStorage<PendingSpan | undefined>();
@@ -214,11 +189,7 @@ export function createTraceContext(
214
189
  ...(pendingSpan.parentId ? { parentId: pendingSpan.parentId } : {}),
215
190
  };
216
191
 
217
- insertCompletedSpan(
218
- completed,
219
- { sequence: pendingSpan.sequence, span },
220
- maxSpans,
221
- );
192
+ insertCompletedSpan(completed, { sequence: pendingSpan.sequence, span }, maxSpans);
222
193
  options.onSpan?.(span);
223
194
 
224
195
  if (!pendingSpan.parentId) {
@@ -233,8 +204,7 @@ export function createTraceContext(
233
204
  finalize("ok", successAttributes ?? undefined);
234
205
  return value;
235
206
  } catch (error) {
236
- const errorMessage =
237
- error instanceof Error ? error.message : String(error);
207
+ const errorMessage = error instanceof Error ? error.message : String(error);
238
208
  const errorAttributes = spanOptions.onError?.(error);
239
209
  finalize("error", errorAttributes ?? undefined, errorMessage);
240
210
  throw error;
@@ -1,4 +1,4 @@
1
- import type { Span } from "./trace";
1
+ import type { Span } from "./trace.js";
2
2
 
3
3
  export type WaterfallRequest = {
4
4
  method: string;
@@ -52,11 +52,7 @@ export function renderWaterfall(
52
52
 
53
53
  for (const node of tree) {
54
54
  const operationDuration = formatDuration(node.span.duration_ms);
55
- const operationBar = renderBar(
56
- node.span.duration_ms,
57
- totalDuration,
58
- maxBarWidth,
59
- );
55
+ const operationBar = renderBar(node.span.duration_ms, totalDuration, maxBarWidth);
60
56
  const operationColor = spanColor(node.span, slowThresholdMs);
61
57
 
62
58
  lines.push(
@@ -104,14 +100,9 @@ function renderChildren(
104
100
  const provider = isLast ? "└─" : "├─";
105
101
 
106
102
  const duration = formatDuration(node.span.duration_ms);
107
- const bar = renderBar(
108
- node.span.duration_ms,
109
- ctx.totalDuration,
110
- ctx.maxBarWidth,
111
- );
103
+ const bar = renderBar(node.span.duration_ms, ctx.totalDuration, ctx.maxBarWidth);
112
104
  const color = spanColor(node.span, ctx.slowThresholdMs);
113
- const star =
114
- node.span.id === ctx.bottleneckId ? ` ${ANSI.yellow}★${ANSI.reset}` : "";
105
+ const star = node.span.id === ctx.bottleneckId ? ` ${ANSI.yellow}★${ANSI.reset}` : "";
115
106
  const barSuffix = bar ? ` ${bar}` : "";
116
107
 
117
108
  const nameWidth = 20;
@@ -190,11 +181,7 @@ function findBottleneck(roots: SpanNode[]): string | null {
190
181
  return longest.id;
191
182
  }
192
183
 
193
- function renderBar(
194
- durationMs: number,
195
- totalMs: number,
196
- maxWidth: number,
197
- ): string {
184
+ function renderBar(durationMs: number, totalMs: number, maxWidth: number): string {
198
185
  if (totalMs <= 0 || durationMs <= 0) {
199
186
  return "";
200
187
  }