@apifuse/provider-sdk 2.2.0-beta.4 → 2.2.0-beta.41

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 (315) hide show
  1. package/AUTHORING.md +501 -13
  2. package/CHANGELOG.md +169 -1
  3. package/README.md +72 -14
  4. package/SUBMISSION.md +1 -1
  5. package/bin/apifuse-check.ts +150 -5
  6. package/bin/apifuse-dev.ts +38 -5
  7. package/bin/apifuse-migrate-shape.ts +84 -0
  8. package/bin/apifuse-pack-check.ts +22 -2
  9. package/bin/apifuse-pack-smoke.ts +57 -2
  10. package/bin/apifuse-pack-types.ts +356 -38
  11. package/bin/apifuse-perf.ts +14 -13
  12. package/bin/apifuse-record.ts +691 -68
  13. package/bin/apifuse-submit-check.ts +2301 -282
  14. package/bin/apifuse-sync-assets.ts +117 -0
  15. package/bin/submit-check-delimited-text.ts +50 -0
  16. package/dist/auth-turn/index.d.ts +3 -3
  17. package/dist/auth-turn/index.js +1 -1
  18. package/dist/auth.d.ts +14 -0
  19. package/dist/auth.js +67 -0
  20. package/dist/ceremonies/index.d.ts +16 -0
  21. package/dist/ceremonies/index.js +141 -36
  22. package/dist/cli/commands.d.ts +1 -1
  23. package/dist/cli/commands.js +16 -0
  24. package/dist/cli/create.d.ts +3 -0
  25. package/dist/cli/create.js +40 -35
  26. package/dist/cli/migrate-provider-shape.d.ts +52 -0
  27. package/dist/cli/migrate-provider-shape.js +515 -0
  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/Dockerfile.tpl +1 -1
  32. package/dist/cli/templates/provider/README.md.tpl +4 -4
  33. package/dist/cli/templates/provider/index.ts.tpl +6 -3
  34. package/dist/cli/templates/provider/operations/ping.ts.tpl +2 -1
  35. package/dist/cli/templates/provider/provider.json.tpl +6 -0
  36. package/dist/config/loader.d.ts +177 -16
  37. package/dist/config/loader.js +424 -127
  38. package/dist/contract-serialization.js +4 -8
  39. package/dist/contract-types.d.ts +1 -0
  40. package/dist/contract.js +3 -0
  41. package/dist/declaration-validation.d.ts +32 -0
  42. package/dist/declaration-validation.js +207 -0
  43. package/dist/define.d.ts +51 -25
  44. package/dist/define.js +774 -39
  45. package/dist/error-observability.d.ts +7 -0
  46. package/dist/error-observability.js +61 -0
  47. package/dist/error-resolution.d.ts +4 -0
  48. package/dist/error-resolution.js +122 -0
  49. package/dist/errors.d.ts +33 -0
  50. package/dist/errors.js +40 -0
  51. package/dist/fixture-sanitization.d.ts +28 -0
  52. package/dist/fixture-sanitization.js +227 -0
  53. package/dist/health-scenario.d.ts +1842 -0
  54. package/dist/health-scenario.js +624 -0
  55. package/dist/index.d.ts +19 -9
  56. package/dist/index.js +10 -6
  57. package/dist/lint.d.ts +6 -1
  58. package/dist/lint.js +362 -3
  59. package/dist/native-address.d.ts +43 -0
  60. package/dist/native-address.js +281 -0
  61. package/dist/native-egress-policy.d.ts +31 -0
  62. package/dist/native-egress-policy.js +288 -0
  63. package/dist/observability.d.ts +5 -2
  64. package/dist/observability.js +48 -1
  65. package/dist/provider.d.ts +8 -2
  66. package/dist/provider.js +3 -1
  67. package/dist/runtime/auth-flow.d.ts +5 -1
  68. package/dist/runtime/auth-flow.js +6 -0
  69. package/dist/runtime/browser.d.ts +1 -0
  70. package/dist/runtime/browser.js +492 -49
  71. package/dist/runtime/cache.d.ts +1 -0
  72. package/dist/runtime/cache.js +169 -15
  73. package/dist/runtime/choice-wordlist.d.ts +9 -0
  74. package/dist/runtime/choice-wordlist.js +138 -0
  75. package/dist/runtime/choice.d.ts +13 -1
  76. package/dist/runtime/choice.js +490 -102
  77. package/dist/runtime/executor.d.ts +2 -2
  78. package/dist/runtime/executor.js +37 -3
  79. package/dist/runtime/http.d.ts +1 -0
  80. package/dist/runtime/http.js +515 -53
  81. package/dist/runtime/instrumentation.d.ts +2 -2
  82. package/dist/runtime/instrumentation.js +366 -8
  83. package/dist/runtime/native-network-errors.d.ts +33 -0
  84. package/dist/runtime/native-network-errors.js +69 -0
  85. package/dist/runtime/native-network.d.ts +96 -0
  86. package/dist/runtime/native-network.js +1232 -0
  87. package/dist/runtime/ocr.d.ts +29 -0
  88. package/dist/runtime/ocr.js +440 -0
  89. package/dist/runtime/proxy-errors.js +6 -2
  90. package/dist/runtime/proxy-nodemaven.d.ts +56 -0
  91. package/dist/runtime/proxy-nodemaven.js +146 -0
  92. package/dist/runtime/proxy-telemetry.d.ts +80 -1
  93. package/dist/runtime/proxy-telemetry.js +154 -47
  94. package/dist/runtime/redirects.d.ts +29 -0
  95. package/dist/runtime/redirects.js +36 -0
  96. package/dist/runtime/redis.d.ts +1 -1
  97. package/dist/runtime/redis.js +4 -2
  98. package/dist/runtime/request-options.d.ts +68 -1
  99. package/dist/runtime/request-options.js +548 -0
  100. package/dist/runtime/resolver-config.d.ts +6 -0
  101. package/dist/runtime/resolver-config.js +6 -0
  102. package/dist/runtime/resolver-public.d.ts +1 -0
  103. package/dist/runtime/resolver-public.js +1 -0
  104. package/dist/runtime/resolver-shared.d.ts +3 -0
  105. package/dist/runtime/resolver-shared.js +12 -0
  106. package/dist/runtime/resolver-vendors/bindings.d.ts +48 -0
  107. package/dist/runtime/resolver-vendors/bindings.js +40 -0
  108. package/dist/runtime/resolver-vendors/browser.d.ts +22 -0
  109. package/dist/runtime/resolver-vendors/browser.js +377 -0
  110. package/dist/runtime/resolver-vendors/capsolver.d.ts +22 -0
  111. package/dist/runtime/resolver-vendors/capsolver.js +526 -0
  112. package/dist/runtime/resolver-vendors/hosts.d.ts +2 -0
  113. package/dist/runtime/resolver-vendors/hosts.js +33 -0
  114. package/dist/runtime/resolver-vendors/twocaptcha.d.ts +24 -0
  115. package/dist/runtime/resolver-vendors/twocaptcha.js +407 -0
  116. package/dist/runtime/resolver-vendors/types.d.ts +94 -0
  117. package/dist/runtime/resolver-vendors/types.js +96 -0
  118. package/dist/runtime/resolver.d.ts +60 -0
  119. package/dist/runtime/resolver.js +737 -0
  120. package/dist/runtime/secrets.d.ts +27 -0
  121. package/dist/runtime/secrets.js +51 -0
  122. package/dist/runtime/state.d.ts +3 -0
  123. package/dist/runtime/state.js +277 -71
  124. package/dist/runtime/stealth-cookies.d.ts +20 -0
  125. package/dist/runtime/stealth-cookies.js +111 -0
  126. package/dist/runtime/stealth.d.ts +28 -3
  127. package/dist/runtime/stealth.js +519 -255
  128. package/dist/runtime/stt.js +1 -12
  129. package/dist/runtime/timeout.d.ts +5 -0
  130. package/dist/runtime/timeout.js +12 -0
  131. package/dist/runtime/trace-config.d.ts +12 -0
  132. package/dist/runtime/trace-config.js +61 -0
  133. package/dist/serve.d.ts +1 -1
  134. package/dist/serve.js +1 -1
  135. package/dist/server/error-observability.d.ts +1 -0
  136. package/dist/server/error-observability.js +1 -0
  137. package/dist/server/index.d.ts +6 -3
  138. package/dist/server/index.js +3 -3
  139. package/dist/server/self-test-input-tokens.d.ts +2 -1
  140. package/dist/server/self-test-input-tokens.js +18 -14
  141. package/dist/server/self-test.d.ts +114 -0
  142. package/dist/server/self-test.js +787 -148
  143. package/dist/server/serve-implementation.d.ts +225 -0
  144. package/dist/server/serve-implementation.js +2242 -0
  145. package/dist/server/serve.d.ts +1 -70
  146. package/dist/server/serve.js +1 -1130
  147. package/dist/server/trace-output.d.ts +4 -0
  148. package/dist/server/trace-output.js +20 -0
  149. package/dist/server/types.d.ts +30 -5
  150. package/dist/server/types.js +13 -1
  151. package/dist/stateful/errors.d.ts +19 -0
  152. package/dist/stateful/errors.js +24 -0
  153. package/dist/stateful/http-provider-event-emitter.d.ts +40 -0
  154. package/dist/stateful/http-provider-event-emitter.js +237 -0
  155. package/dist/stateful/http-session-owner-registry.d.ts +44 -0
  156. package/dist/stateful/http-session-owner-registry.js +210 -0
  157. package/dist/stateful/index.d.ts +18 -0
  158. package/dist/stateful/index.js +18 -0
  159. package/dist/stateful/provider-event-delivery-failures.d.ts +32 -0
  160. package/dist/stateful/provider-event-delivery-failures.js +43 -0
  161. package/dist/stateful/provider-event-pipeline-metrics.d.ts +46 -0
  162. package/dist/stateful/provider-event-pipeline-metrics.js +48 -0
  163. package/dist/stateful/provider-event-pipeline.d.ts +50 -0
  164. package/dist/stateful/provider-event-pipeline.js +1 -0
  165. package/dist/stateful/provider-events.d.ts +101 -0
  166. package/dist/stateful/provider-events.js +289 -0
  167. package/dist/stateful/session-key.d.ts +15 -0
  168. package/dist/stateful/session-key.js +86 -0
  169. package/dist/stateful/stateful-provider-adapter-context.d.ts +5 -0
  170. package/dist/stateful/stateful-provider-adapter-context.js +42 -0
  171. package/dist/stateful/stateful-provider-adapter-metrics.d.ts +15 -0
  172. package/dist/stateful/stateful-provider-adapter-metrics.js +21 -0
  173. package/dist/stateful/stateful-provider-adapter.d.ts +98 -0
  174. package/dist/stateful/stateful-provider-adapter.js +287 -0
  175. package/dist/stateful/stateful-provider-observability.d.ts +62 -0
  176. package/dist/stateful/stateful-provider-observability.js +161 -0
  177. package/dist/stateful/stateful-provider-owner-forwarder.d.ts +41 -0
  178. package/dist/stateful/stateful-provider-owner-forwarder.js +215 -0
  179. package/dist/stateful/stateful-provider-runtime-context.d.ts +32 -0
  180. package/dist/stateful/stateful-provider-runtime-context.js +60 -0
  181. package/dist/stateful/stateful-provider-runtime-executor.d.ts +34 -0
  182. package/dist/stateful/stateful-provider-runtime-executor.js +52 -0
  183. package/dist/stateful/stateful-provider-session-routing.d.ts +67 -0
  184. package/dist/stateful/stateful-provider-session-routing.js +345 -0
  185. package/dist/stateful/stateful-provider-session-runtime.d.ts +98 -0
  186. package/dist/stateful/stateful-provider-session-runtime.js +245 -0
  187. package/dist/stateful-signing.d.ts +18 -0
  188. package/dist/stateful-signing.js +27 -0
  189. package/dist/stealth/profiles.js +16 -7
  190. package/dist/stream-evidence.d.ts +74 -0
  191. package/dist/stream-evidence.js +785 -0
  192. package/dist/stream.js +7 -1
  193. package/dist/testing/index.d.ts +2 -1
  194. package/dist/testing/index.js +2 -1
  195. package/dist/testing/run.d.ts +32 -2
  196. package/dist/testing/run.js +489 -21
  197. package/dist/trace-sanitization.d.ts +5 -0
  198. package/dist/trace-sanitization.js +45 -0
  199. package/dist/types.d.ts +563 -33
  200. package/dist/types.js +1 -0
  201. package/package.json +44 -5
  202. package/src/auth-turn/index.ts +1 -1
  203. package/src/auth.ts +118 -0
  204. package/src/ceremonies/index.ts +189 -46
  205. package/src/cli/commands.ts +20 -0
  206. package/src/cli/create.ts +48 -35
  207. package/src/cli/migrate-provider-shape.ts +701 -0
  208. package/src/cli/prompt-assets.ts +865 -0
  209. package/src/cli/templates/provider/AGENTS.md.tpl +17 -8
  210. package/src/cli/templates/provider/Dockerfile.tpl +1 -1
  211. package/src/cli/templates/provider/README.md.tpl +4 -4
  212. package/src/cli/templates/provider/index.ts.tpl +6 -3
  213. package/src/cli/templates/provider/operations/ping.ts.tpl +2 -1
  214. package/src/cli/templates/provider/provider.json.tpl +6 -0
  215. package/src/config/loader.ts +665 -163
  216. package/src/contract-serialization.ts +5 -7
  217. package/src/contract-types.ts +1 -0
  218. package/src/contract.ts +3 -0
  219. package/src/declaration-validation.ts +266 -0
  220. package/src/define.ts +1003 -88
  221. package/src/error-observability.ts +64 -0
  222. package/src/error-resolution.ts +127 -0
  223. package/src/errors.ts +68 -0
  224. package/src/fixture-sanitization.ts +264 -0
  225. package/src/health-scenario.ts +875 -0
  226. package/src/index.ts +205 -8
  227. package/src/lint.ts +408 -4
  228. package/src/native-address.ts +340 -0
  229. package/src/native-egress-policy.ts +358 -0
  230. package/src/observability.ts +51 -1
  231. package/src/provider.ts +134 -0
  232. package/src/runtime/auth-flow.ts +12 -0
  233. package/src/runtime/browser.ts +661 -63
  234. package/src/runtime/cache.ts +189 -14
  235. package/src/runtime/choice-wordlist.ts +145 -0
  236. package/src/runtime/choice.ts +631 -120
  237. package/src/runtime/executor.ts +53 -8
  238. package/src/runtime/http.ts +641 -61
  239. package/src/runtime/instrumentation.ts +520 -15
  240. package/src/runtime/native-network-errors.ts +99 -0
  241. package/src/runtime/native-network.ts +1605 -0
  242. package/src/runtime/ocr.ts +523 -0
  243. package/src/runtime/proxy-errors.ts +12 -4
  244. package/src/runtime/proxy-nodemaven.ts +221 -0
  245. package/src/runtime/proxy-telemetry.ts +244 -75
  246. package/src/runtime/redirects.ts +66 -0
  247. package/src/runtime/redis.ts +7 -2
  248. package/src/runtime/request-options.ts +680 -1
  249. package/src/runtime/resolver-config.ts +6 -0
  250. package/src/runtime/resolver-public.ts +20 -0
  251. package/src/runtime/resolver-shared.ts +17 -0
  252. package/src/runtime/resolver-vendors/bindings.ts +56 -0
  253. package/src/runtime/resolver-vendors/browser.ts +533 -0
  254. package/src/runtime/resolver-vendors/capsolver.ts +700 -0
  255. package/src/runtime/resolver-vendors/hosts.ts +38 -0
  256. package/src/runtime/resolver-vendors/twocaptcha.ts +539 -0
  257. package/src/runtime/resolver-vendors/types.ts +212 -0
  258. package/src/runtime/resolver.ts +1103 -0
  259. package/src/runtime/secrets.ts +64 -0
  260. package/src/runtime/state.ts +394 -77
  261. package/src/runtime/stealth-cookies.ts +132 -0
  262. package/src/runtime/stealth.ts +675 -289
  263. package/src/runtime/stt.ts +1 -19
  264. package/src/runtime/timeout.ts +18 -0
  265. package/src/runtime/trace-config.ts +77 -0
  266. package/src/serve.ts +6 -1
  267. package/src/server/error-observability.ts +1 -0
  268. package/src/server/index.ts +39 -2
  269. package/src/server/self-test-input-tokens.ts +29 -14
  270. package/src/server/self-test.ts +1030 -175
  271. package/src/server/serve-implementation.ts +3338 -0
  272. package/src/server/serve.ts +1 -1626
  273. package/src/server/trace-output.ts +32 -0
  274. package/src/server/types.ts +13 -1
  275. package/src/stateful/README.md +146 -0
  276. package/src/stateful/errors.ts +35 -0
  277. package/src/stateful/http-provider-event-emitter.ts +314 -0
  278. package/src/stateful/http-session-owner-registry.ts +306 -0
  279. package/src/stateful/index.ts +18 -0
  280. package/src/stateful/provider-event-delivery-failures.ts +80 -0
  281. package/src/stateful/provider-event-pipeline-metrics.ts +95 -0
  282. package/src/stateful/provider-event-pipeline.ts +61 -0
  283. package/src/stateful/provider-events.ts +462 -0
  284. package/src/stateful/session-key.ts +111 -0
  285. package/src/stateful/stateful-provider-adapter-context.ts +59 -0
  286. package/src/stateful/stateful-provider-adapter-metrics.ts +48 -0
  287. package/src/stateful/stateful-provider-adapter.ts +562 -0
  288. package/src/stateful/stateful-provider-observability.ts +261 -0
  289. package/src/stateful/stateful-provider-owner-forwarder.ts +287 -0
  290. package/src/stateful/stateful-provider-runtime-context.ts +92 -0
  291. package/src/stateful/stateful-provider-runtime-executor.ts +96 -0
  292. package/src/stateful/stateful-provider-session-routing.ts +546 -0
  293. package/src/stateful/stateful-provider-session-runtime.ts +403 -0
  294. package/src/stateful-signing.ts +46 -0
  295. package/src/stealth/profiles.ts +17 -7
  296. package/src/stream-evidence.ts +988 -0
  297. package/src/stream.ts +8 -1
  298. package/src/testing/index.ts +10 -1
  299. package/src/testing/run.ts +658 -15
  300. package/src/trace-sanitization.ts +63 -0
  301. package/src/types.ts +698 -65
  302. package/dist/cli/templates/provider/CLAUDE.md.tpl +0 -1
  303. package/src/cli/templates/provider/CLAUDE.md.tpl +0 -1
  304. /package/dist/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
  305. /package/dist/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
  306. /package/dist/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
  307. /package/dist/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
  308. /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
  309. /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
  310. /package/src/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
  311. /package/src/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
  312. /package/src/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
  313. /package/src/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
  314. /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
  315. /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
package/dist/define.js CHANGED
@@ -1,22 +1,90 @@
1
1
  import ms from "ms";
2
+ import { validateFailClosedOperationDeclaration, validateFailClosedProviderDeclaration, } from "./declaration-validation.js";
3
+ import { SDK_RUNTIME_OWNED_ERROR_CODES } from "./error-resolution.js";
2
4
  import { ProviderError, ValidationError } from "./errors.js";
5
+ import { HealthScenarioSchema } from "./health-scenario.js";
6
+ import { NativeEgressPolicyValidationError, validateNativeProviderConfig, } from "./native-egress-policy.js";
3
7
  import { safeParseSchemaSync } from "./schema.js";
4
- import { HEALTH_CHECK_DEGRADED_THRESHOLD_MS_MAX, HEALTH_CHECK_DEGRADED_THRESHOLD_MS_MIN, HEALTH_CHECK_TIMEOUT_MS_MAX, HEALTH_CHECK_TIMEOUT_MS_MIN, OPERATION_TIMEOUT_MS_MAX, OPERATION_TIMEOUT_MS_MIN, STREAM_CHUNK_BYTES_MAX, STREAM_CHUNK_BYTES_MIN, STREAM_HEARTBEAT_MS_MAX, STREAM_HEARTBEAT_MS_MIN, STREAM_IDLE_TIMEOUT_MS_MAX, STREAM_IDLE_TIMEOUT_MS_MIN, STREAM_MAX_DURATION_MS_MAX, STREAM_MAX_DURATION_MS_MIN, } from "./types.js";
8
+ import { resolveHealthCheckInputDateTokens } from "./server/self-test-input-tokens.js";
9
+ import { HEALTH_CHECK_DEGRADED_THRESHOLD_MS_MAX, HEALTH_CHECK_DEGRADED_THRESHOLD_MS_MIN, HEALTH_CHECK_TIMEOUT_MS_MAX, HEALTH_CHECK_TIMEOUT_MS_MIN, OPERATION_TIMEOUT_MS_MAX, OPERATION_TIMEOUT_MS_MIN, STREAM_CHUNK_BYTES_MAX, STREAM_CHUNK_BYTES_MIN, STREAM_HEARTBEAT_MS_MAX, STREAM_HEARTBEAT_MS_MIN, STREAM_IDLE_TIMEOUT_MS_MAX, STREAM_IDLE_TIMEOUT_MS_MIN, STREAM_MAX_DURATION_MS_MAX, STREAM_MAX_DURATION_MS_MIN, VALID_OPERATION_ERROR_STATUSES, } from "./types.js";
5
10
  const CONNECTOR_ID_REGEX = /^[a-z][a-z0-9]*(-[a-z][a-z0-9]*)*$/;
6
11
  const OPERATION_ID_REGEX = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/;
7
12
  const VALID_RUNTIMES = ["standard", "shared", "browser"];
8
- const VALID_AUTH_MODES = ["none", "platform-managed", "credentials", "oauth2"];
13
+ const VALID_AUTH_MODES = [
14
+ "none",
15
+ "platform-managed",
16
+ "credentials",
17
+ "oauth2",
18
+ "oauth2_proxied",
19
+ ];
20
+ const PROXIED_OAUTH_REQUIRED_FIELDS = [
21
+ "authorizeUrl",
22
+ "tokenUrl",
23
+ "customScheme",
24
+ "rewriteProfile",
25
+ "clientIdEnvKey",
26
+ ];
27
+ const PROXIED_OAUTH_ALLOWED_FIELDS = new Set([
28
+ ...PROXIED_OAUTH_REQUIRED_FIELDS,
29
+ "pkce",
30
+ "authorizeParams",
31
+ "tokenParams",
32
+ ]);
33
+ const PROXIED_OAUTH_RESERVED_AUTHORIZE_PARAMS = new Set([
34
+ "client_id",
35
+ "response_type",
36
+ "state",
37
+ "code_challenge",
38
+ "code_challenge_method",
39
+ ]);
40
+ const PROXIED_OAUTH_PROFILE_REGEX = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
41
+ const PROXIED_OAUTH_ENV_KEY_REGEX = /^[A-Z][A-Z0-9_]*__[A-Z0-9_]+$/;
42
+ const CUSTOM_SCHEME_REGEX = /^[A-Za-z][A-Za-z0-9+.-]*:\/\/\S+$/;
9
43
  const VALID_PROVIDER_ACCESS_VISIBILITIES = ["public", "early_access"];
10
44
  const VALID_PROVIDER_PROXY_MODES = ["disabled", "optional", "required"];
11
- const VALID_PROVIDER_PROXY_PROVIDERS = ["smartproxy", "decodo", "custom"];
45
+ const VALID_PROVIDER_PROXY_PROVIDERS = ["smartproxy", "nodemaven", "decodo", "custom"];
12
46
  const VALID_PROVIDER_PROXY_AFFINITIES = [
13
47
  "request",
14
48
  "operation",
15
49
  "auth-flow",
16
50
  "connection",
17
51
  ];
52
+ const VALID_PROVIDER_OCR_MODES = ["optional", "required"];
18
53
  const VALID_PROVIDER_STT_MODES = ["optional", "required"];
54
+ function exhaustiveLiteralArray() {
55
+ return (values, ..._missing) => values;
56
+ }
57
+ export const VALID_PROVIDER_RESOLVER_VENDORS = exhaustiveLiteralArray()([
58
+ "browser",
59
+ "capsolver",
60
+ "capmonster",
61
+ "2captcha",
62
+ "custom",
63
+ ]);
64
+ export const VALID_PROVIDER_CHALLENGE_KINDS = exhaustiveLiteralArray()([
65
+ "turnstile",
66
+ "recaptcha_v2",
67
+ "recaptcha_v3",
68
+ "hcaptcha",
69
+ "cloudflare_interstitial",
70
+ "aws_waf",
71
+ "akamai_sec_cpt",
72
+ "akamai_sensor",
73
+ ]);
19
74
  const SMARTPROXY_APP_KEY_SECRET = "APIFUSE__PROXY__SMARTPROXY_APP_KEY";
75
+ const NODEMAVEN_USERNAME_SECRET = "APIFUSE__PROXY__NODEMAVEN_USERNAME";
76
+ const NODEMAVEN_PASSWORD_SECRET = "APIFUSE__PROXY__NODEMAVEN_PASSWORD";
77
+ // Per-vendor provider-declared credential secrets. A required-mode chain must
78
+ // declare every secret of every credentialed vendor it names, so a missing
79
+ // credential fails at build/validation time rather than during a live outage: a
80
+ // declared-but-uncredentialed fallback leg is a silently dead SPOF, which is
81
+ // exactly the failure class the multi-vendor chain exists to remove. Vendors
82
+ // absent from this map (the deprecated `custom`/`decodo` values have no managed
83
+ // adapter) impose no declaration requirement.
84
+ const VENDOR_REQUIRED_SECRETS = {
85
+ smartproxy: [SMARTPROXY_APP_KEY_SECRET],
86
+ nodemaven: [NODEMAVEN_USERNAME_SECRET, NODEMAVEN_PASSWORD_SECRET],
87
+ };
20
88
  const RESERVED_OPERATION_IDS = new Set(["auth", "health"]);
21
89
  const MCP_TOOL_NAME_REGEX = /^[A-Za-z][A-Za-z0-9_]{0,127}$/;
22
90
  const VALID_OPERATION_RISK_CLASSES = ["read", "write", "destructive", "external-send"];
@@ -42,13 +110,357 @@ function parsePositiveMsDuration(value) {
42
110
  return undefined;
43
111
  return parsed;
44
112
  }
45
- /** Define one provider operation with schema-driven handler inference. */
46
- export function defineOperation(operation) {
47
- return operation;
113
+ function splitAuthStartParameters(parameters) {
114
+ const parts = [];
115
+ let start = 0;
116
+ let round = 0;
117
+ let square = 0;
118
+ let curly = 0;
119
+ let quote;
120
+ let escaped = false;
121
+ let lineComment = false;
122
+ let blockComment = false;
123
+ const templateDepths = [0];
124
+ templateDepths.length = 0;
125
+ for (let index = 0; index < parameters.length; index++) {
126
+ const character = parameters[index];
127
+ const nextCharacter = parameters[index + 1];
128
+ if (lineComment) {
129
+ if (character === "\n" || character === "\r")
130
+ lineComment = false;
131
+ else
132
+ continue;
133
+ }
134
+ if (blockComment) {
135
+ if (character === "*" && nextCharacter === "/") {
136
+ blockComment = false;
137
+ index++;
138
+ }
139
+ continue;
140
+ }
141
+ if (quote) {
142
+ if (escaped) {
143
+ escaped = false;
144
+ }
145
+ else if (character === "\\") {
146
+ escaped = true;
147
+ }
148
+ else if (quote === "`" && character === "$" && nextCharacter === "{") {
149
+ curly++;
150
+ templateDepths.push(curly);
151
+ quote = undefined;
152
+ index++;
153
+ }
154
+ else if (character === quote) {
155
+ quote = undefined;
156
+ }
157
+ continue;
158
+ }
159
+ if (character === "'" || character === '"' || character === "`") {
160
+ quote = character;
161
+ continue;
162
+ }
163
+ if (character === "/" && nextCharacter === "/") {
164
+ lineComment = true;
165
+ index++;
166
+ continue;
167
+ }
168
+ if (character === "/" && nextCharacter === "*") {
169
+ blockComment = true;
170
+ index++;
171
+ continue;
172
+ }
173
+ if (character === "/")
174
+ return undefined;
175
+ // Annex B HTML-like comments are not lexed here; give up rather than
176
+ // risk misreading the parameter list.
177
+ if (character === "<" && parameters.startsWith("!--", index + 1))
178
+ return undefined;
179
+ if (character === "-" && parameters.startsWith("->", index + 1))
180
+ return undefined;
181
+ if (character === "(")
182
+ round++;
183
+ else if (character === ")")
184
+ round--;
185
+ else if (character === "[")
186
+ square++;
187
+ else if (character === "]")
188
+ square--;
189
+ else if (character === "{")
190
+ curly++;
191
+ else if (character === "}") {
192
+ if (templateDepths.at(-1) === curly) {
193
+ templateDepths.pop();
194
+ curly--;
195
+ quote = "`";
196
+ }
197
+ else
198
+ curly--;
199
+ }
200
+ else if (character === "," && round === 0 && square === 0 && curly === 0) {
201
+ parts.push(parameters.slice(start, index));
202
+ start = index + 1;
203
+ }
204
+ if (round < 0 || square < 0 || curly < 0)
205
+ return undefined;
206
+ }
207
+ if (quote ||
208
+ blockComment ||
209
+ templateDepths.length > 0 ||
210
+ round !== 0 ||
211
+ square !== 0 ||
212
+ curly !== 0)
213
+ return undefined;
214
+ parts.push(parameters.slice(start));
215
+ return parts;
48
216
  }
49
- /** Define a non-JSON provider operation with explicit transport metadata. */
50
- export function defineStreamOperation(operation) {
51
- return operation;
217
+ function authStartParameterList(source) {
218
+ let index = 0;
219
+ while (index < source.length && /\s/.test(source[index] ?? ""))
220
+ index++;
221
+ if (index >= source.length)
222
+ return undefined;
223
+ let openIndex = -1;
224
+ let parenthesizedArrow = false;
225
+ let asyncMethodOrArrow = false;
226
+ const skipTrivia = () => {
227
+ while (index < source.length) {
228
+ if (/\s/.test(source[index] ?? "")) {
229
+ index++;
230
+ continue;
231
+ }
232
+ if (source[index] === "/" && source[index + 1] === "/") {
233
+ index += 2;
234
+ while (index < source.length && source[index] !== "\n" && source[index] !== "\r")
235
+ index++;
236
+ continue;
237
+ }
238
+ if (source[index] === "/" && source[index + 1] === "*") {
239
+ const end = source.indexOf("*/", index + 2);
240
+ if (end < 0) {
241
+ index = source.length;
242
+ return;
243
+ }
244
+ index = end + 2;
245
+ continue;
246
+ }
247
+ return;
248
+ }
249
+ };
250
+ const initial = source.slice(index);
251
+ const isAsync = initial.startsWith("async") && !/[\w$]/.test(initial[5] ?? "");
252
+ if (isAsync) {
253
+ index += 5;
254
+ skipTrivia();
255
+ }
256
+ const afterAsync = source.slice(index);
257
+ const isFunction = afterAsync.startsWith("function") && !/[\w$]/.test(afterAsync[8] ?? "");
258
+ if (isFunction) {
259
+ index += 8;
260
+ skipTrivia();
261
+ if (source[index] === "*") {
262
+ index++;
263
+ skipTrivia();
264
+ }
265
+ }
266
+ else if (source[index] === "*") {
267
+ index++;
268
+ skipTrivia();
269
+ }
270
+ if (source[index] === "(") {
271
+ openIndex = index;
272
+ parenthesizedArrow = !isFunction;
273
+ asyncMethodOrArrow = isAsync && !isFunction;
274
+ }
275
+ else if (isFunction) {
276
+ if (!/[A-Za-z_$]/.test(source[index] ?? ""))
277
+ return undefined;
278
+ index++;
279
+ while (index < source.length && /[A-Za-z0-9_$]/.test(source[index] ?? ""))
280
+ index++;
281
+ skipTrivia();
282
+ if (source[index] !== "(")
283
+ return undefined;
284
+ openIndex = index;
285
+ }
286
+ else {
287
+ const identifierStart = index;
288
+ if (!/[A-Za-z_$]/.test(source[index] ?? ""))
289
+ return undefined;
290
+ index++;
291
+ while (index < source.length && /[A-Za-z0-9_$]/.test(source[index] ?? ""))
292
+ index++;
293
+ const firstIdentifier = source.slice(identifierStart, index);
294
+ skipTrivia();
295
+ if (source[index] === "=" && source[index + 1] === ">")
296
+ return undefined;
297
+ if (source[index] !== "(") {
298
+ if (firstIdentifier !== "get" && firstIdentifier !== "set")
299
+ return undefined;
300
+ if (!/[A-Za-z_$]/.test(source[index] ?? ""))
301
+ return undefined;
302
+ index++;
303
+ while (index < source.length && /[A-Za-z0-9_$]/.test(source[index] ?? ""))
304
+ index++;
305
+ skipTrivia();
306
+ }
307
+ if (source[index] !== "(")
308
+ return undefined;
309
+ openIndex = index;
310
+ }
311
+ if (openIndex < 0)
312
+ return undefined;
313
+ let depth = 1;
314
+ let square = 0;
315
+ let curly = 0;
316
+ let quote;
317
+ let escaped = false;
318
+ let lineComment = false;
319
+ let blockComment = false;
320
+ const templateDepths = [0];
321
+ templateDepths.length = 0;
322
+ for (index = openIndex + 1; index < source.length; index++) {
323
+ const character = source[index];
324
+ const nextCharacter = source[index + 1];
325
+ if (lineComment) {
326
+ if (character === "\n" || character === "\r")
327
+ lineComment = false;
328
+ else
329
+ continue;
330
+ }
331
+ if (blockComment) {
332
+ if (character === "*" && nextCharacter === "/") {
333
+ blockComment = false;
334
+ index++;
335
+ }
336
+ continue;
337
+ }
338
+ if (quote) {
339
+ if (escaped)
340
+ escaped = false;
341
+ else if (character === "\\")
342
+ escaped = true;
343
+ else if (quote === "`" && character === "$" && nextCharacter === "{") {
344
+ curly++;
345
+ templateDepths.push(curly);
346
+ quote = undefined;
347
+ index++;
348
+ }
349
+ else if (character === quote)
350
+ quote = undefined;
351
+ continue;
352
+ }
353
+ if (character === "'" || character === '"' || character === "`") {
354
+ quote = character;
355
+ continue;
356
+ }
357
+ if (character === "/" && nextCharacter === "/") {
358
+ lineComment = true;
359
+ index++;
360
+ continue;
361
+ }
362
+ if (character === "/" && nextCharacter === "*") {
363
+ blockComment = true;
364
+ index++;
365
+ continue;
366
+ }
367
+ if (character === "/")
368
+ return undefined;
369
+ // Annex B HTML-like comments are not lexed here; give up rather than
370
+ // risk misreading the parameter list.
371
+ if (character === "<" && source.startsWith("!--", index + 1))
372
+ return undefined;
373
+ if (character === "-" && source.startsWith("->", index + 1))
374
+ return undefined;
375
+ if (character === "(")
376
+ depth++;
377
+ else if (character === ")") {
378
+ depth--;
379
+ if (depth === 0 && square === 0 && curly === 0) {
380
+ const closeIndex = index;
381
+ if (parenthesizedArrow) {
382
+ index++;
383
+ skipTrivia();
384
+ const hasArrow = source[index] === "=" && source[index + 1] === ">";
385
+ if (!hasArrow && (!asyncMethodOrArrow || source[index] !== "{"))
386
+ return undefined;
387
+ }
388
+ return source.slice(openIndex + 1, closeIndex);
389
+ }
390
+ if (depth < 0)
391
+ return undefined;
392
+ }
393
+ else if (character === "[")
394
+ square++;
395
+ else if (character === "]") {
396
+ square--;
397
+ if (square < 0)
398
+ return undefined;
399
+ }
400
+ else if (character === "{")
401
+ curly++;
402
+ else if (character === "}") {
403
+ if (templateDepths.at(-1) === curly) {
404
+ templateDepths.pop();
405
+ curly--;
406
+ quote = "`";
407
+ }
408
+ else
409
+ curly--;
410
+ if (curly < 0)
411
+ return undefined;
412
+ }
413
+ }
414
+ return undefined;
415
+ }
416
+ /**
417
+ * Conservative defense in depth for defaulted second parameters, which
418
+ * JavaScript intentionally omits from Function.length. Ambiguous source is
419
+ * ignored so this check can never reject a valid provider on weak evidence.
420
+ */
421
+ function authStartHasHiddenInput(start) {
422
+ let source;
423
+ try {
424
+ source = Function.prototype.toString.call(start);
425
+ }
426
+ catch {
427
+ return false;
428
+ }
429
+ if (!source ||
430
+ source.includes("[native code]") ||
431
+ /^\s*(?:async\s+)?function\s+bound\b/.test(source))
432
+ return false;
433
+ const parameters = authStartParameterList(source);
434
+ if (!parameters)
435
+ return false;
436
+ const parts = splitAuthStartParameters(parameters);
437
+ if (!parts || parts.length < 2)
438
+ return false;
439
+ // Require ordinary, readable source formatting. This intentionally fails
440
+ // open for minified output and for transpilers that rewrite defaults.
441
+ const commaIndex = parameters.indexOf(",");
442
+ if (commaIndex < 0 || !/\s/.test(parameters[commaIndex + 1] ?? ""))
443
+ return false;
444
+ const first = parts[0].trim();
445
+ const second = parts[1].trim();
446
+ const identifier = /^[_$A-Za-z][_$A-Za-z0-9]*/;
447
+ const firstName = first.match(identifier)?.[0];
448
+ const secondName = second.match(identifier)?.[0];
449
+ if (!firstName || !secondName || firstName.length < 3 || secondName.length < 3)
450
+ return false;
451
+ return /\s=\s/.test(second);
452
+ }
453
+ /** Define one factored provider operation with schema-driven handler inference. */
454
+ export function defineOperation() {
455
+ return function operation(config) {
456
+ return config;
457
+ };
458
+ }
459
+ /** Define a factored non-JSON operation with explicit transport metadata. */
460
+ export function defineStreamOperation() {
461
+ return function streamOperation(config) {
462
+ return config;
463
+ };
52
464
  }
53
465
  function assertObjectConfig(value) {
54
466
  if (!value || typeof value !== "object") {
@@ -72,18 +484,95 @@ function assertLiteralField(value, field, validValues, providerId) {
72
484
  });
73
485
  }
74
486
  }
75
- function validateProviderShape(config) {
487
+ function validateProxiedOAuthParams(value, field, providerId) {
488
+ if (value === undefined)
489
+ return;
490
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
491
+ throw new ValidationError(`Provider "${providerId}" auth.proxied.${field} must be an object of string values.`);
492
+ }
493
+ for (const [key, paramValue] of Object.entries(value)) {
494
+ if (!key.trim() || typeof paramValue !== "string") {
495
+ throw new ValidationError(`Provider "${providerId}" auth.proxied.${field} must contain non-empty keys and string values.`);
496
+ }
497
+ if (field === "authorizeParams" &&
498
+ PROXIED_OAUTH_RESERVED_AUTHORIZE_PARAMS.has(key.toLowerCase())) {
499
+ throw new ValidationError(`Provider "${providerId}" auth.proxied.authorizeParams cannot override reserved parameter "${key}".`);
500
+ }
501
+ }
502
+ }
503
+ function validateProxiedOAuthAuth(auth, providerId) {
504
+ const proxied = auth.proxied;
505
+ if (auth.mode !== "oauth2_proxied") {
506
+ if (proxied !== undefined) {
507
+ throw new ValidationError(`Provider "${providerId}" auth.proxied is only valid when auth.mode is "oauth2_proxied".`);
508
+ }
509
+ return;
510
+ }
511
+ if (!proxied || typeof proxied !== "object" || Array.isArray(proxied)) {
512
+ throw new ValidationError(`Provider "${providerId}" with auth.mode "oauth2_proxied" must declare auth.proxied.`);
513
+ }
514
+ const config = Object.fromEntries(Object.entries(proxied));
515
+ for (const key of Object.keys(config)) {
516
+ if (!PROXIED_OAUTH_ALLOWED_FIELDS.has(key)) {
517
+ throw new ValidationError(`Provider "${providerId}" has unknown auth.proxied field "${key}".`);
518
+ }
519
+ }
520
+ for (const field of PROXIED_OAUTH_REQUIRED_FIELDS) {
521
+ if (typeof config[field] !== "string" || !config[field].trim()) {
522
+ throw new ValidationError(`Provider "${providerId}" auth.proxied.${field} must be a non-empty string.`);
523
+ }
524
+ }
525
+ for (const field of ["authorizeUrl", "tokenUrl"]) {
526
+ try {
527
+ const endpoint = new URL(String(config[field]));
528
+ if (endpoint.protocol !== "https:" ||
529
+ endpoint.username ||
530
+ endpoint.password ||
531
+ endpoint.hash) {
532
+ throw new Error("invalid endpoint");
533
+ }
534
+ }
535
+ catch {
536
+ throw new ValidationError(`Provider "${providerId}" auth.proxied.${field} must be an absolute HTTPS URL without credentials or a fragment.`);
537
+ }
538
+ }
539
+ const customScheme = String(config.customScheme);
540
+ if (!CUSTOM_SCHEME_REGEX.test(customScheme) ||
541
+ customScheme.toLowerCase().startsWith("http://") ||
542
+ customScheme.toLowerCase().startsWith("https://")) {
543
+ throw new ValidationError(`Provider "${providerId}" auth.proxied.customScheme must be a non-HTTP custom-scheme URL prefix.`);
544
+ }
545
+ if (!PROXIED_OAUTH_PROFILE_REGEX.test(String(config.rewriteProfile))) {
546
+ throw new ValidationError(`Provider "${providerId}" auth.proxied.rewriteProfile must be a kebab-case profile name.`);
547
+ }
548
+ if (!PROXIED_OAUTH_ENV_KEY_REGEX.test(String(config.clientIdEnvKey))) {
549
+ throw new ValidationError(`Provider "${providerId}" auth.proxied.clientIdEnvKey must be an APIFuse-style uppercase environment key.`);
550
+ }
551
+ if (config.pkce !== undefined && config.pkce !== "S256" && config.pkce !== "none") {
552
+ throw new ValidationError(`Provider "${providerId}" auth.proxied.pkce must be "S256" or "none".`);
553
+ }
554
+ validateProxiedOAuthParams(config.authorizeParams, "authorizeParams", providerId);
555
+ validateProxiedOAuthParams(config.tokenParams, "tokenParams", providerId);
556
+ }
557
+ function validateProviderDeclarationShape(config) {
76
558
  assertObjectConfig(config);
77
559
  assertRequiredField(config, "id");
78
560
  assertRequiredField(config, "version", String(config.id));
79
561
  assertRequiredField(config, "runtime", String(config.id));
80
562
  assertRequiredField(config, "meta", String(config.id));
81
- assertRequiredField(config, "operations", String(config.id));
82
563
  if (typeof config.runtime === "string")
83
564
  assertLiteralField(config.runtime, "runtime", VALID_RUNTIMES, String(config.id));
565
+ if (config.native !== undefined && config.runtime === "browser") {
566
+ throw new ValidationError(`Provider "${String(config.id)}" cannot declare capability "native" with runtime "browser"`, {
567
+ fix: 'Use runtime: "standard" or runtime: "shared", or remove the native declaration.',
568
+ });
569
+ }
84
570
  const auth = config.auth;
85
571
  if (auth && typeof auth === "object" && "mode" in auth && typeof auth.mode === "string")
86
572
  assertLiteralField(auth.mode, "auth.mode", VALID_AUTH_MODES, String(config.id));
573
+ if (auth && typeof auth === "object" && !Array.isArray(auth)) {
574
+ validateProxiedOAuthAuth(Object.fromEntries(Object.entries(auth)), String(config.id));
575
+ }
87
576
  if (auth && typeof auth === "object" && "exchange" in auth) {
88
577
  throw new ProviderError(`Provider "${String(config.id)}" auth.exchange is not part of the Provider SDK auth contract`, {
89
578
  fix: "Use the single canonical auth interface: auth.flow. Gateway calls auth.flow.start/continue/poll/abort/refresh only and persists complete turn data.credential as-is, so put login/token/session exchange inside auth.flow.continue.",
@@ -101,6 +590,19 @@ function validateProviderShape(config) {
101
590
  fix: "Return a form turn from start(ctx), then receive user input in continue(ctx, input).",
102
591
  });
103
592
  }
593
+ if (auth &&
594
+ typeof auth === "object" &&
595
+ "flow" in auth &&
596
+ auth.flow &&
597
+ typeof auth.flow === "object" &&
598
+ "start" in auth.flow &&
599
+ typeof auth.flow.start === "function" &&
600
+ auth.flow.start.length <= 1 &&
601
+ authStartHasHiddenInput(auth.flow.start)) {
602
+ throw new ProviderError(`Provider "${String(config.id)}" auth.flow.start must not declare an input parameter`, {
603
+ fix: "Return a form turn from start(ctx), then receive user input in continue(ctx, input).",
604
+ });
605
+ }
104
606
  const access = config.access;
105
607
  if (access !== undefined) {
106
608
  if (!access || typeof access !== "object" || Array.isArray(access)) {
@@ -127,6 +629,10 @@ function validateProviderShape(config) {
127
629
  }
128
630
  }
129
631
  }
632
+ function validateProviderImplementationShape(config) {
633
+ const configRecord = config;
634
+ assertRequiredField(configRecord, "operations", String(config.id));
635
+ }
130
636
  function validateProviderProxy(config) {
131
637
  const proxy = config.proxy;
132
638
  if (proxy === undefined || typeof proxy === "boolean") {
@@ -137,11 +643,21 @@ function validateProviderProxy(config) {
137
643
  fix: `Use proxy: { mode: "required", provider: "smartproxy", geo: { country: "KR" }, session: { affinity: "connection", lifetimeMinutes: 30 } }`,
138
644
  });
139
645
  }
140
- rejectUnknownFields(proxy, new Set(["mode", "provider", "geo", "session"]), "proxy");
646
+ rejectUnknownFields(proxy, new Set(["mode", "provider", "providers", "geo", "session"]), "proxy");
141
647
  assertLiteralField(proxy.mode, "proxy.mode", VALID_PROVIDER_PROXY_MODES, config.id);
142
648
  if (proxy.provider !== undefined) {
143
649
  assertLiteralField(proxy.provider, "proxy.provider", VALID_PROVIDER_PROXY_PROVIDERS, config.id);
144
650
  }
651
+ if (proxy.providers !== undefined) {
652
+ if (!Array.isArray(proxy.providers) || proxy.providers.length === 0) {
653
+ throw new ValidationError(`Provider "${config.id}" has invalid proxy.providers: must be a non-empty array of proxy vendors.`, {
654
+ fix: `Use proxy.providers: ["smartproxy", "nodemaven"] to declare an ordered fallback chain.`,
655
+ });
656
+ }
657
+ for (const vendor of proxy.providers) {
658
+ assertLiteralField(vendor, "proxy.providers[]", VALID_PROVIDER_PROXY_PROVIDERS, config.id);
659
+ }
660
+ }
145
661
  if (proxy.geo !== undefined) {
146
662
  if (!proxy.geo || typeof proxy.geo !== "object" || Array.isArray(proxy.geo)) {
147
663
  throw new ValidationError(`Provider "${config.id}" has invalid proxy.geo: must be an object.`, {
@@ -165,7 +681,7 @@ function validateProviderProxy(config) {
165
681
  fix: `Use proxy.session: { affinity: "connection", lifetimeMinutes: 30 }.`,
166
682
  });
167
683
  }
168
- rejectUnknownFields(proxy.session, new Set(["affinity", "lifetimeMinutes", "poolSize"]), "proxy.session");
684
+ rejectUnknownFields(proxy.session, new Set(["affinity", "lifetimeMinutes", "poolSize", "drainLeadSeconds"]), "proxy.session");
169
685
  if (proxy.session.affinity !== undefined) {
170
686
  assertLiteralField(proxy.session.affinity, "proxy.session.affinity", VALID_PROVIDER_PROXY_AFFINITIES, config.id);
171
687
  }
@@ -177,14 +693,70 @@ function validateProviderProxy(config) {
177
693
  if (poolSize !== undefined && (!Number.isInteger(poolSize) || poolSize <= 0)) {
178
694
  throw new ValidationError(`Provider "${config.id}" has invalid proxy.session.poolSize: must be a positive integer.`);
179
695
  }
180
- }
181
- if (proxy.mode === "required" && proxy.provider === "smartproxy") {
182
- const hasSmartproxySecret = config.secrets?.some((secret) => secret.name === SMARTPROXY_APP_KEY_SECRET && secret.required !== false);
183
- if (!hasSmartproxySecret) {
184
- throw new ValidationError(`Provider "${config.id}" requires Smartproxy egress but does not declare ${SMARTPROXY_APP_KEY_SECRET}.`, {
185
- fix: `Add secrets: [{ name: "${SMARTPROXY_APP_KEY_SECRET}", required: true }] to the provider.`,
696
+ const drainLeadSeconds = proxy.session.drainLeadSeconds;
697
+ if (drainLeadSeconds !== undefined &&
698
+ (!Number.isFinite(drainLeadSeconds) || drainLeadSeconds <= 0)) {
699
+ throw new ValidationError(`Provider "${config.id}" has invalid proxy.session.drainLeadSeconds: must be a positive number of seconds.`, {
700
+ fix: `Use proxy.session.drainLeadSeconds: 120 to receive the sticky-expiry drain event 120s before hard expiry.`,
186
701
  });
187
702
  }
703
+ // A drain lead longer than the sticky lifetime would fire the expiring
704
+ // event before the session is even established, so the provider would
705
+ // never get a usable window. Reject the contradiction at build time.
706
+ if (drainLeadSeconds !== undefined &&
707
+ lifetime !== undefined &&
708
+ Number.isFinite(lifetime) &&
709
+ drainLeadSeconds >= lifetime * 60) {
710
+ throw new ValidationError(`Provider "${config.id}" has proxy.session.drainLeadSeconds (${drainLeadSeconds}s) greater than or equal to proxy.session.lifetimeMinutes (${lifetime}m).`, {
711
+ fix: `Lower drainLeadSeconds below the sticky lifetime so the drain event leaves a usable session window.`,
712
+ });
713
+ }
714
+ }
715
+ // Every credentialed vendor in a required-mode chain must declare its
716
+ // provider secret(s) so a missing credential fails at build/validation time,
717
+ // not during a live outage. This covers the fallback legs too (not just the
718
+ // first vendor): a declared-but-uncredentialed nodemaven fallback would leave
719
+ // the chain silently down to a single vendor, reintroducing the SPOF the chain
720
+ // removes.
721
+ const vendorChain = proxy.providers && proxy.providers.length > 0
722
+ ? proxy.providers
723
+ : proxy.provider
724
+ ? [proxy.provider]
725
+ : [];
726
+ if (proxy.mode === "required") {
727
+ for (const vendor of vendorChain) {
728
+ const requiredSecrets = VENDOR_REQUIRED_SECRETS[vendor];
729
+ if (!requiredSecrets)
730
+ continue;
731
+ for (const secretName of requiredSecrets) {
732
+ // Match the canonical runtime gate (assertRequiredSecretsPresent /
733
+ // listMissingRequiredSecrets), which enforces only `required === true`
734
+ // declarations. A declaration that omits `required` (defaulting to
735
+ // optional) is skipped at runtime, so accepting it here would pass
736
+ // validation while leaving the credential unenforced until proxy
737
+ // resolution during a live request — the fail-open gap this check exists
738
+ // to close.
739
+ const declared = config.secrets?.some((secret) => secret.name === secretName && secret.required === true);
740
+ if (!declared) {
741
+ throw new ValidationError(`Provider "${config.id}" requires ${vendor} egress but does not declare ${secretName}.`, {
742
+ fix: `Add secrets: [{ name: "${secretName}", required: true }] to the provider (every vendor in a required proxy chain must declare its credential secrets).`,
743
+ });
744
+ }
745
+ }
746
+ }
747
+ }
748
+ // `decodo`/`custom` are deprecated vendor values (string-union members, so the
749
+ // @deprecated symbol gate can't catch them — warn at validation time instead).
750
+ const deprecatedVendors = vendorChain.filter((vendor) => vendor === "decodo" || vendor === "custom");
751
+ if (proxy.mode === "required" &&
752
+ vendorChain.length > 0 &&
753
+ deprecatedVendors.length === vendorChain.length) {
754
+ throw new ValidationError(`Provider "${config.id}" requires proxy egress but declares only deprecated proxy vendor(s): ${deprecatedVendors.join(", ")}.`, {
755
+ fix: `Use proxy.provider or proxy.providers with "smartproxy" and/or "nodemaven".`,
756
+ });
757
+ }
758
+ if (deprecatedVendors.length > 0) {
759
+ console.warn(`[provider-sdk] Provider "${config.id}" uses deprecated proxy vendor(s): ${deprecatedVendors.join(", ")}. Use "smartproxy"/"nodemaven".`);
188
760
  }
189
761
  }
190
762
  function validateProviderStt(config) {
@@ -199,6 +771,54 @@ function validateProviderStt(config) {
199
771
  rejectUnknownFields(stt, new Set(["mode"]), "stt");
200
772
  assertLiteralField(stt.mode, "stt.mode", VALID_PROVIDER_STT_MODES, config.id);
201
773
  }
774
+ function validateProviderOcr(config) {
775
+ const ocr = config.ocr;
776
+ if (ocr === undefined)
777
+ return;
778
+ if (!ocr || typeof ocr !== "object" || Array.isArray(ocr)) {
779
+ throw new ValidationError(`Provider "${config.id}" has invalid ocr: must be an object.`, {
780
+ fix: `Use ocr: { mode: "required" } or ocr: { mode: "optional" }.`,
781
+ });
782
+ }
783
+ rejectUnknownFields(ocr, new Set(["mode"]), "ocr");
784
+ assertLiteralField(ocr.mode, "ocr.mode", VALID_PROVIDER_OCR_MODES, config.id);
785
+ }
786
+ function validateProviderResolver(config) {
787
+ const resolver = config.resolver;
788
+ if (resolver === undefined)
789
+ return;
790
+ if (!resolver || typeof resolver !== "object" || Array.isArray(resolver)) {
791
+ throw new ValidationError(`Provider "${config.id}" has invalid resolver: must be an object.`, {
792
+ fix: `Set resolver for provider "${config.id}" to { vendors: ["2captcha"], kinds: ["turnstile"] }.`,
793
+ });
794
+ }
795
+ rejectUnknownFields(resolver, new Set(["vendors", "kinds", "clientProfile"]), "resolver", config.id);
796
+ if (resolver.vendors !== undefined) {
797
+ validateResolverLiteralArray(resolver.vendors, "resolver.vendors", VALID_PROVIDER_RESOLVER_VENDORS, config.id);
798
+ }
799
+ validateResolverLiteralArray(resolver.kinds, "resolver.kinds", VALID_PROVIDER_CHALLENGE_KINDS, config.id);
800
+ if (resolver.clientProfile !== undefined &&
801
+ (typeof resolver.clientProfile !== "string" || !resolver.clientProfile.trim())) {
802
+ throw new ValidationError(`Provider "${config.id}" has invalid resolver.clientProfile: must be a non-empty string.`, {
803
+ fix: `Set resolver.clientProfile for provider "${config.id}" to a transport-owned profile name.`,
804
+ });
805
+ }
806
+ }
807
+ function validateResolverLiteralArray(value, field, validValues, providerId) {
808
+ if (!Array.isArray(value)) {
809
+ throw new ValidationError(`Provider "${providerId}" has invalid ${field}: must be an array.`, {
810
+ fix: `Set ${field} for provider "${providerId}" to an array containing only: ${validValues.join(", ")}.`,
811
+ });
812
+ }
813
+ for (const [index, item] of value.entries()) {
814
+ if (typeof item === "string" && validValues.some((validValue) => validValue === item)) {
815
+ continue;
816
+ }
817
+ throw new ValidationError(`Provider "${providerId}" has invalid ${field}[${index}]: ${JSON.stringify(item)}. Expected one of: ${validValues.join(", ")}`, {
818
+ fix: `Set ${field}[${index}] for provider "${providerId}" to one of ${validValues.map((validValue) => `"${validValue}"`).join(", ")}.`,
819
+ });
820
+ }
821
+ }
202
822
  function validateOperationIds(providerId, operations) {
203
823
  for (const operationName of Object.keys(operations)) {
204
824
  if (!OPERATION_ID_REGEX.test(operationName))
@@ -335,6 +955,23 @@ function validateOperationObservability(providerId, operations) {
335
955
  }
336
956
  }
337
957
  }
958
+ function validateOperationErrorCodes(providerId, operations) {
959
+ for (const [operationName, operation] of Object.entries(operations)) {
960
+ for (const [index, errorCode] of (operation.docs?.errorCodes ?? []).entries()) {
961
+ if (errorCode.status !== undefined &&
962
+ !VALID_OPERATION_ERROR_STATUSES.some((status) => status === errorCode.status)) {
963
+ const field = `operations.${operationName}.docs.errorCodes[${index}].status`;
964
+ throw new ValidationError(`Provider "${providerId}" has invalid ${field}: ${String(errorCode.status)} is not an emittable provider error status.`, {
965
+ fix: `Set ${field} to one of ${VALID_OPERATION_ERROR_STATUSES.join(", ")}, or omit it.`,
966
+ });
967
+ }
968
+ if (errorCode.status !== undefined &&
969
+ SDK_RUNTIME_OWNED_ERROR_CODES.has(errorCode.code)) {
970
+ console.warn(`[provider-sdk] Provider "${providerId}" operation "${operationName}" declares status ${errorCode.status} for SDK-owned error code "${errorCode.code}"; the declared status is documentation-only and will be ignored at runtime.`);
971
+ }
972
+ }
973
+ }
974
+ }
338
975
  const JSON_TRANSPORT_FIELDS = new Set(["kind"]);
339
976
  const SSE_TRANSPORT_FIELDS = new Set([
340
977
  "kind",
@@ -500,6 +1137,7 @@ const HEALTH_CHECK_CASE_FIELDS = new Set([
500
1137
  "input",
501
1138
  "prepareInput",
502
1139
  "assertions",
1140
+ "scenario",
503
1141
  "degradedThresholdMs",
504
1142
  "timeoutMs",
505
1143
  "expectedStatus",
@@ -556,14 +1194,18 @@ function suggestField(unknown, candidates) {
556
1194
  }
557
1195
  return best;
558
1196
  }
559
- function rejectUnknownFields(value, allowed, fieldPath) {
1197
+ function rejectUnknownFields(value, allowed, fieldPath, providerId) {
560
1198
  for (const key of Object.keys(value)) {
561
1199
  if (allowed.has(key))
562
1200
  continue;
563
1201
  const hint = suggestField(key, allowed);
564
1202
  throw new ValidationError(hint
565
1203
  ? `Unknown field "${key}" on ${fieldPath}. Did you mean "${hint}"?`
566
- : `Unknown field "${key}" on ${fieldPath}.`, { fix: `Remove ${fieldPath}.${key} or rename it.` });
1204
+ : `Unknown field "${key}" on ${fieldPath}.`, {
1205
+ fix: providerId
1206
+ ? `Remove ${fieldPath}.${key} from provider "${providerId}" or rename it.`
1207
+ : `Remove ${fieldPath}.${key} or rename it.`,
1208
+ });
567
1209
  }
568
1210
  }
569
1211
  function assertBoundedIntegerMs(value, fieldPath, options) {
@@ -670,12 +1312,31 @@ function validateHealthCheckCase(providerId, operationName, caseValue, caseIndex
670
1312
  const c = caseValue;
671
1313
  if (typeof c.name !== "string" || c.name.length === 0)
672
1314
  throw new ValidationError(`Provider "${providerId}" ${fieldPath}.name must be a non-empty string.`);
673
- if (typeof c.assertions !== "function")
1315
+ const hasScenario = c.scenario !== undefined;
1316
+ const imperativeFields = [
1317
+ ...(c.prepareInput === undefined ? [] : ["prepareInput"]),
1318
+ ...(c.assertions === undefined ? [] : ["assertions"]),
1319
+ ];
1320
+ if (hasScenario && imperativeFields.length > 0)
1321
+ throw new ValidationError(`Provider "${providerId}" operation "${operationName}" health-check case "${c.name}" cannot declare scenario with ${imperativeFields.join(" and ")}.`, {
1322
+ fix: `Remove ${imperativeFields.map((field) => `${fieldPath}.${field}`).join(" and ")} and keep ${fieldPath}.scenario, or remove ${fieldPath}.scenario to keep the imperative hooks.`,
1323
+ });
1324
+ if (!hasScenario && typeof c.assertions !== "function")
674
1325
  throw new ValidationError(`Provider "${providerId}" ${fieldPath}.assertions must be a function.`, {
675
1326
  fix: `Set ${fieldPath}.assertions to (ctx) => { ... } that throws on failure.`,
676
1327
  });
677
1328
  if (c.prepareInput !== undefined && typeof c.prepareInput !== "function")
678
1329
  throw new ValidationError(`Provider "${providerId}" ${fieldPath}.prepareInput must be a function.`);
1330
+ if (hasScenario) {
1331
+ const parsedScenario = HealthScenarioSchema.safeParse(c.scenario);
1332
+ if (!parsedScenario.success)
1333
+ throw new ValidationError(`Provider "${providerId}" operation "${operationName}" health-check case "${c.name}" has an invalid scenario: it must conform to HealthScenario.`, { fix: `Build ${fieldPath}.scenario with defineHealthScenario().` });
1334
+ const unrelatedOperation = parsedScenario.data.coversOperations.find((operationId) => operationId !== operationName);
1335
+ if (unrelatedOperation !== undefined)
1336
+ throw new ValidationError(`Provider "${providerId}" operation "${operationName}" health-check case "${c.name}" scenario.coversOperations cannot claim unrelated operation "${unrelatedOperation}".`, {
1337
+ fix: `Set ${fieldPath}.scenario.coversOperations to ["${operationName}"].`,
1338
+ });
1339
+ }
679
1340
  if (c.degradedThresholdMs !== undefined &&
680
1341
  (typeof c.degradedThresholdMs !== "number" ||
681
1342
  !Number.isInteger(c.degradedThresholdMs) ||
@@ -776,6 +1437,7 @@ const HEALTH_JOURNEY_FIELDS = new Set([
776
1437
  "manualTrigger",
777
1438
  "steps",
778
1439
  "run",
1440
+ "scenario",
779
1441
  ]);
780
1442
  const HEALTH_JOURNEY_SCHEDULE_FIELDS = new Set(["kind", "interval", "jitter", "randomize"]);
781
1443
  const HEALTH_JOURNEY_STEP_FIELDS = new Set([
@@ -1198,6 +1860,10 @@ function validateHealthJourneys(providerId, operations, healthJourneys) {
1198
1860
  }
1199
1861
  if (journey.manualTrigger !== undefined)
1200
1862
  validateHealthJourneyManualTrigger(providerId, journey.id, journey.manualTrigger);
1863
+ if (journey.scenario !== undefined && journey.smsMatchers !== undefined)
1864
+ throw new ValidationError(`Provider "${providerId}" healthJourneys.${journey.id}.smsMatchers is not allowed on declarative scenarios.`);
1865
+ if (journey.scenario !== undefined && journey.requiredSecrets !== undefined)
1866
+ throw new ValidationError(`Provider "${providerId}" healthJourneys.${journey.id}.requiredSecrets is not allowed on declarative scenarios.`);
1201
1867
  if (journey.timeout !== undefined)
1202
1868
  assertIsoDuration(journey.timeout, `Provider "${providerId}" healthJourneys.${journey.id}.timeout`);
1203
1869
  if (journey.cooldown !== undefined)
@@ -1239,6 +1905,21 @@ function validateOperationFixtures(providerId, operations) {
1239
1905
  throw new ValidationError(`Operation handler must be defined for provider "${providerId}" operation "${operationName}"`, {
1240
1906
  fix: `Add operations.${operationName}.handler as an async function with signature (ctx, input) => Promise<output>`,
1241
1907
  });
1908
+ if (operation.fixtures?.recordedAt !== undefined) {
1909
+ const recordedAt = operation.fixtures.recordedAt;
1910
+ const parsed = typeof recordedAt === "string"
1911
+ ? new Date(`${recordedAt}T00:00:00.000Z`)
1912
+ : new Date(Number.NaN);
1913
+ const isCalendarDate = typeof recordedAt === "string" &&
1914
+ /^\d{4}-\d{2}-\d{2}$/.test(recordedAt) &&
1915
+ !Number.isNaN(parsed.getTime()) &&
1916
+ parsed.toISOString().slice(0, 10) === recordedAt;
1917
+ const kstToday = new Date(Date.now() + 9 * 60 * 60 * 1000).toISOString().slice(0, 10);
1918
+ if (!isCalendarDate || recordedAt > kstToday)
1919
+ throw new ValidationError(`Fixture recordedAt must be a valid, non-future KST calendar date for provider "${providerId}" operation "${operationName}"`, {
1920
+ fix: `Set operations.${operationName}.fixtures.recordedAt to the KST capture date in YYYY-MM-DD format; it must not be in the future.`,
1921
+ });
1922
+ }
1242
1923
  if (operation.fixtures?.request !== undefined) {
1243
1924
  const result = safeParseSchemaSync(operation.input, operation.fixtures.request, `operations.${operationName}.fixtures.request`);
1244
1925
  if (!result.success)
@@ -1257,6 +1938,28 @@ function validateOperationFixtures(providerId, operations) {
1257
1938
  }
1258
1939
  }
1259
1940
  }
1941
+ function resolveOperationFixtureRequests(operations) {
1942
+ let changed = false;
1943
+ const resolvedOperations = Object.fromEntries(Object.entries(operations).map(([operationName, operation]) => {
1944
+ if (operation.fixtures?.request === undefined)
1945
+ return [operationName, operation];
1946
+ const request = resolveHealthCheckInputDateTokens(operation.fixtures.request);
1947
+ if (request === operation.fixtures.request)
1948
+ return [operationName, operation];
1949
+ changed = true;
1950
+ return [
1951
+ operationName,
1952
+ {
1953
+ ...operation,
1954
+ fixtures: {
1955
+ ...operation.fixtures,
1956
+ request,
1957
+ },
1958
+ },
1959
+ ];
1960
+ }));
1961
+ return changed ? resolvedOperations : operations;
1962
+ }
1260
1963
  /**
1261
1964
  * Shallow shape guard only: the `deployment` object is passed through
1262
1965
  * verbatim and deliberately not deep-validated by the SDK — the APIFuse
@@ -1270,40 +1973,65 @@ function validateProviderDeployment(providerId, deployment) {
1270
1973
  fix: 'Pass deployment: { runtime: "shared" | "dedicated" | "browser", ... } or remove the field',
1271
1974
  });
1272
1975
  }
1273
- export function defineProvider(config) {
1274
- validateProviderShape(config);
1976
+ /** Establish a provider declaration before its operations are contextually typed. */
1977
+ export function defineProvider(declaration) {
1978
+ validateProviderDeclaration(declaration);
1979
+ const buildProvider = (implementation) => finalizeProvider({
1980
+ ...declaration,
1981
+ ...implementation,
1982
+ });
1983
+ return buildProvider;
1984
+ }
1985
+ function validateProviderDeclaration(config) {
1986
+ validateProviderDeclarationShape(config);
1275
1987
  if (!CONNECTOR_ID_REGEX.test(config.id))
1276
1988
  throw new ProviderError(`Invalid provider id: "${config.id}"`, {
1277
1989
  fix: 'Use lowercase alphanumeric with dashes, e.g., "korea-air-quality"',
1278
1990
  });
1279
- if (Object.keys(config.operations).length === 0)
1280
- throw new ProviderError(`Provider "${config.id}" must define at least one operation`, {
1281
- fix: "Add at least one operation to the operations object",
1282
- });
1283
- validateOperationIds(config.id, config.operations);
1284
- validateOperationAnnotations(config.id, config.operations);
1285
- validateOperationObservability(config.id, config.operations);
1286
- validateOperationTransports(config.id, config.operations);
1287
- validateOperationContracts(config.id, config.operations);
1288
- validateToolRouterMetadata(config.id, config.operations);
1289
- const journeyCoveredOperations = validateHealthJourneys(config.id, config.operations, config.healthJourneys);
1290
- validateOperationHealthChecks(config.id, config.operations, journeyCoveredOperations);
1291
1991
  if (config.healthMonitor !== undefined && config.healthProbe !== undefined)
1292
1992
  throw new ValidationError(`Provider "${config.id}" declares both healthMonitor and healthProbe. They are aliases; declare exactly one.`, {
1293
1993
  fix: "Keep healthProbe (the new name) and delete the healthMonitor block.",
1294
1994
  });
1295
1995
  validateProviderHealthMonitor(config.id, config.healthProbe ?? config.healthMonitor, config.healthProbe !== undefined ? "healthProbe" : "healthMonitor");
1296
- validateOperationFixtures(config.id, config.operations);
1297
1996
  validateProviderDeployment(config.id, config.deployment);
1997
+ try {
1998
+ validateNativeProviderConfig(config.native);
1999
+ }
2000
+ catch (error) {
2001
+ if (error instanceof NativeEgressPolicyValidationError)
2002
+ throw new ValidationError(error.message);
2003
+ throw error;
2004
+ }
1298
2005
  validateProviderProxy(config);
2006
+ validateProviderOcr(config);
1299
2007
  validateProviderStt(config);
2008
+ validateProviderResolver(config);
1300
2009
  if (config.runtime === "browser" && !config.browser)
1301
2010
  throw new ProviderError(`Provider "${config.id}" must define browser.engine when runtime is "browser"`, {
1302
2011
  fix: 'Add browser: { engine: "playwright-stealth" } for TypeScript providers, or another supported engine for your runtime',
1303
2012
  });
1304
2013
  if (config.browser && config.runtime !== "browser")
1305
2014
  throw new ProviderError(`Provider "${config.id}" cannot define browser config unless runtime is "browser"`, { fix: 'Set runtime: "browser" or remove the browser config' });
1306
- return {
2015
+ validateFailClosedProviderDeclaration(config);
2016
+ }
2017
+ function finalizeProvider(config) {
2018
+ validateProviderImplementationShape(config);
2019
+ const operations = resolveOperationFixtureRequests(config.operations);
2020
+ if (Object.keys(config.operations).length === 0)
2021
+ throw new ProviderError(`Provider "${config.id}" must define at least one operation`, {
2022
+ fix: "Add at least one operation to the operations object",
2023
+ });
2024
+ validateOperationIds(config.id, config.operations);
2025
+ validateOperationAnnotations(config.id, config.operations);
2026
+ validateOperationObservability(config.id, config.operations);
2027
+ validateOperationErrorCodes(config.id, config.operations);
2028
+ validateOperationTransports(config.id, config.operations);
2029
+ validateOperationContracts(config.id, config.operations);
2030
+ validateToolRouterMetadata(config.id, config.operations);
2031
+ const journeyCoveredOperations = validateHealthJourneys(config.id, config.operations, config.healthJourneys);
2032
+ validateOperationHealthChecks(config.id, config.operations, journeyCoveredOperations);
2033
+ validateOperationFixtures(config.id, operations);
2034
+ const provider = {
1307
2035
  id: config.id,
1308
2036
  version: config.version,
1309
2037
  runtime: config.runtime,
@@ -1311,9 +2039,12 @@ export function defineProvider(config) {
1311
2039
  // are owned by the APIFuse registry builder, not the SDK.
1312
2040
  deployment: config.deployment,
1313
2041
  allowedHosts: config.allowedHosts,
2042
+ native: config.native,
1314
2043
  stealth: config.stealth,
1315
2044
  proxy: config.proxy,
2045
+ ocr: config.ocr,
1316
2046
  stt: config.stt,
2047
+ resolver: config.resolver,
1317
2048
  browser: config.browser,
1318
2049
  auth: config.auth,
1319
2050
  reviewed: config.reviewed,
@@ -1322,11 +2053,15 @@ export function defineProvider(config) {
1322
2053
  credential: config.credential,
1323
2054
  context: config.context,
1324
2055
  meta: config.meta,
1325
- operations: config.operations,
2056
+ operations,
1326
2057
  // Transitional healthMonitor → healthProbe alias: mirror whichever field
1327
2058
  // was declared onto both so old and new consumers keep working.
1328
2059
  healthMonitor: config.healthMonitor ?? config.healthProbe,
1329
2060
  healthProbe: config.healthProbe ?? config.healthMonitor,
1330
2061
  healthJourneys: config.healthJourneys,
1331
2062
  };
2063
+ // Declaration validation never invokes handlers, so their declaration-bound
2064
+ // context parameter is irrelevant to the runtime ProviderDefinition shape.
2065
+ validateFailClosedOperationDeclaration(provider);
2066
+ return provider;
1332
2067
  }