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

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 (165) hide show
  1. package/AUTHORING.md +14 -0
  2. package/CHANGELOG.md +4 -0
  3. package/bin/apifuse-check.ts +18 -58
  4. package/bin/apifuse-create.ts +1 -1
  5. package/bin/apifuse-dev.ts +27 -52
  6. package/bin/apifuse-pack-smoke.ts +22 -81
  7. package/bin/apifuse-pack-types.ts +266 -0
  8. package/bin/apifuse-perf.ts +45 -127
  9. package/bin/apifuse-record.ts +23 -61
  10. package/bin/apifuse-submit-check.ts +26 -21
  11. package/bin/apifuse.ts +1 -1
  12. package/bin/submit-check-xml.ts +1 -1
  13. package/dist/auth-turn/index.d.ts +1 -1
  14. package/dist/auth.d.ts +2 -2
  15. package/dist/auth.js +9 -18
  16. package/dist/ceremonies/index.d.ts +1 -1
  17. package/dist/ceremonies/index.js +8 -18
  18. package/dist/config/loader.d.ts +2 -2
  19. package/dist/config/loader.js +19 -42
  20. package/dist/contract-serialization.d.ts +2 -2
  21. package/dist/contract-serialization.js +3 -6
  22. package/dist/contract-types.d.ts +2 -2
  23. package/dist/contract.d.ts +3 -3
  24. package/dist/contract.js +4 -6
  25. package/dist/define.d.ts +8 -1
  26. package/dist/define.js +57 -115
  27. package/dist/dev.d.ts +1 -1
  28. package/dist/dev.js +1 -1
  29. package/dist/errors.d.ts +1 -1
  30. package/dist/errors.js +1 -3
  31. package/dist/i18n/catalog.d.ts +2 -2
  32. package/dist/i18n/catalog.js +4 -10
  33. package/dist/i18n/index.d.ts +2 -2
  34. package/dist/i18n/index.js +2 -2
  35. package/dist/i18n/keys.d.ts +2 -2
  36. package/dist/index.d.ts +43 -42
  37. package/dist/index.js +38 -37
  38. package/dist/lint.js +8 -15
  39. package/dist/provider.d.ts +11 -11
  40. package/dist/provider.js +9 -9
  41. package/dist/public-schema-field-lint.d.ts +1 -1
  42. package/dist/recipes/gov-api.js +1 -1
  43. package/dist/runtime/auth-flow.d.ts +1 -1
  44. package/dist/runtime/auth-flow.js +3 -3
  45. package/dist/runtime/browser.d.ts +1 -1
  46. package/dist/runtime/browser.js +15 -29
  47. package/dist/runtime/cache.d.ts +1 -1
  48. package/dist/runtime/cache.js +4 -8
  49. package/dist/runtime/choice.d.ts +1 -1
  50. package/dist/runtime/choice.js +12 -34
  51. package/dist/runtime/credential.d.ts +1 -1
  52. package/dist/runtime/credential.js +1 -1
  53. package/dist/runtime/env.d.ts +1 -1
  54. package/dist/runtime/executor.d.ts +1 -1
  55. package/dist/runtime/executor.js +2 -2
  56. package/dist/runtime/http.d.ts +2 -2
  57. package/dist/runtime/http.js +5 -5
  58. package/dist/runtime/insights.d.ts +1 -1
  59. package/dist/runtime/insights.js +6 -13
  60. package/dist/runtime/instrumentation.d.ts +2 -2
  61. package/dist/runtime/instrumentation.js +5 -15
  62. package/dist/runtime/keyring.js +1 -1
  63. package/dist/runtime/namespace.js +1 -1
  64. package/dist/runtime/otlp.d.ts +1 -1
  65. package/dist/runtime/perf.d.ts +1 -1
  66. package/dist/runtime/provider.d.ts +1 -1
  67. package/dist/runtime/provider.js +1 -2
  68. package/dist/runtime/proxy-errors.d.ts +1 -1
  69. package/dist/runtime/proxy-errors.js +3 -5
  70. package/dist/runtime/proxy-retry-policy.d.ts +2 -2
  71. package/dist/runtime/proxy-retry-policy.js +2 -2
  72. package/dist/runtime/proxy-telemetry.d.ts +1 -1
  73. package/dist/runtime/proxy-telemetry.js +16 -48
  74. package/dist/runtime/redis.d.ts +1 -1
  75. package/dist/runtime/redis.js +2 -4
  76. package/dist/runtime/request-options.d.ts +1 -1
  77. package/dist/runtime/state.d.ts +2 -2
  78. package/dist/runtime/state.js +3 -3
  79. package/dist/runtime/stealth.d.ts +2 -2
  80. package/dist/runtime/stealth.js +6 -6
  81. package/dist/runtime/stt.d.ts +1 -1
  82. package/dist/runtime/stt.js +11 -15
  83. package/dist/runtime/trace.d.ts +2 -2
  84. package/dist/runtime/trace.js +2 -4
  85. package/dist/runtime/waterfall.d.ts +1 -1
  86. package/dist/schema.d.ts +1 -1
  87. package/dist/schema.js +7 -15
  88. package/dist/serve.d.ts +1 -1
  89. package/dist/serve.js +1 -1
  90. package/dist/server/index.d.ts +7 -7
  91. package/dist/server/index.js +6 -6
  92. package/dist/server/self-test-redaction.d.ts +1 -1
  93. package/dist/server/self-test-redaction.js +1 -1
  94. package/dist/server/self-test.d.ts +3 -3
  95. package/dist/server/self-test.js +3 -3
  96. package/dist/server/serve.d.ts +3 -3
  97. package/dist/server/serve.js +36 -49
  98. package/dist/server/types.js +2 -7
  99. package/dist/stealth/profiles.d.ts +1 -1
  100. package/dist/stealth/profiles.js +5 -14
  101. package/dist/stream.d.ts +1 -1
  102. package/dist/testing/index.d.ts +2 -2
  103. package/dist/testing/index.js +2 -2
  104. package/dist/testing/run.d.ts +1 -1
  105. package/dist/testing/run.js +7 -14
  106. package/dist/types.d.ts +57 -0
  107. package/dist/user-input.d.ts +30 -0
  108. package/dist/user-input.js +66 -0
  109. package/package.json +6 -4
  110. package/src/auth-turn/index.ts +1 -1
  111. package/src/auth.ts +28 -86
  112. package/src/ceremonies/index.ts +24 -78
  113. package/src/config/loader.ts +58 -176
  114. package/src/contract-serialization.ts +5 -11
  115. package/src/contract-types.ts +2 -2
  116. package/src/contract.ts +12 -28
  117. package/src/define.ts +174 -495
  118. package/src/dev.ts +4 -9
  119. package/src/errors.ts +4 -11
  120. package/src/i18n/catalog.ts +10 -32
  121. package/src/i18n/index.ts +2 -2
  122. package/src/i18n/keys.ts +5 -11
  123. package/src/index.ts +44 -42
  124. package/src/lint.ts +89 -159
  125. package/src/provider.ts +12 -11
  126. package/src/public-schema-field-lint.ts +7 -33
  127. package/src/recipes/gov-api.ts +2 -5
  128. package/src/runtime/auth-flow.ts +5 -7
  129. package/src/runtime/browser.ts +64 -187
  130. package/src/runtime/cache.ts +20 -67
  131. package/src/runtime/choice.ts +55 -129
  132. package/src/runtime/credential.ts +2 -2
  133. package/src/runtime/env.ts +1 -1
  134. package/src/runtime/executor.ts +9 -19
  135. package/src/runtime/http.ts +7 -7
  136. package/src/runtime/insights.ts +15 -53
  137. package/src/runtime/instrumentation.ts +19 -58
  138. package/src/runtime/keyring.ts +7 -19
  139. package/src/runtime/namespace.ts +2 -7
  140. package/src/runtime/otlp.ts +12 -23
  141. package/src/runtime/perf.ts +1 -1
  142. package/src/runtime/provider.ts +4 -9
  143. package/src/runtime/proxy-errors.ts +17 -38
  144. package/src/runtime/proxy-retry-policy.ts +3 -3
  145. package/src/runtime/proxy-telemetry.ts +23 -72
  146. package/src/runtime/redis.ts +4 -12
  147. package/src/runtime/request-options.ts +4 -13
  148. package/src/runtime/state.ts +30 -109
  149. package/src/runtime/stealth.ts +8 -8
  150. package/src/runtime/stt.ts +38 -94
  151. package/src/runtime/trace.ts +14 -44
  152. package/src/runtime/waterfall.ts +5 -18
  153. package/src/schema.ts +23 -84
  154. package/src/serve.ts +1 -1
  155. package/src/server/index.ts +7 -7
  156. package/src/server/self-test-redaction.ts +2 -2
  157. package/src/server/self-test.ts +5 -5
  158. package/src/server/serve.ts +87 -242
  159. package/src/server/types.ts +6 -19
  160. package/src/stealth/profiles.ts +10 -26
  161. package/src/stream.ts +8 -19
  162. package/src/testing/index.ts +2 -2
  163. package/src/testing/run.ts +19 -67
  164. package/src/types.ts +58 -0
  165. package/src/user-input.ts +118 -0
@@ -1,4 +1,4 @@
1
- import { CredentialModeError } from "../errors";
1
+ import { CredentialModeError } from "../errors.js";
2
2
  function getAllowedKeys(allowedKeys, values) {
3
3
  if (allowedKeys) {
4
4
  return allowedKeys;
@@ -1,2 +1,2 @@
1
- import type { EnvContext } from "../types";
1
+ import type { EnvContext } from "../types.js";
2
2
  export declare function createEnvContext(allowedKeys?: string[]): EnvContext;
@@ -1,4 +1,4 @@
1
- import type { ProviderContext, ProviderDefinition } from "../types";
1
+ import type { ProviderContext, ProviderDefinition } from "../types.js";
2
2
  export declare function isStreamingOperation(provider: ProviderDefinition, operationId: string): boolean;
3
3
  /**
4
4
  * Execute a provider operation by calling its handler.
@@ -1,5 +1,5 @@
1
- import { isSessionExpiredError, ProviderError, SessionExpiredError } from "../errors";
2
- import { parseSchema } from "../schema";
1
+ import { isSessionExpiredError, ProviderError, SessionExpiredError } from "../errors.js";
2
+ import { parseSchema } from "../schema.js";
3
3
  export function isStreamingOperation(provider, operationId) {
4
4
  const kind = provider.operations[operationId]?.transport?.kind ?? "json";
5
5
  return kind !== "json";
@@ -1,5 +1,5 @@
1
- import type { ProxyResolutionOptions } from "../config/loader";
2
- import type { HttpClient, HttpRetrySummary } from "../types";
1
+ import type { ProxyResolutionOptions } from "../config/loader.js";
2
+ import type { HttpClient, HttpRetrySummary } from "../types.js";
3
3
  export type HttpClientOptions = ProxyResolutionOptions & {
4
4
  warn?: (message: string) => void;
5
5
  userAgent?: string;
@@ -1,8 +1,8 @@
1
- import { resolveProxyConfigAsync } from "../config/loader";
2
- import { ProviderError, TransportError } from "../errors";
3
- import { parseSseStream, readableBytes, readableLines, readableTextChunks } from "../stream";
4
- import { computeProxyAttemptIndex, computeProxyTransportRetryDelayMs, createDefaultProxyTransportRetryOptions, isProxyTransportRetryMethod, normalizeProxyTransportRetryOptions, proxyTransportRetryErrorCode, proxyTransportRetryErrorStatus, shouldRetryProxyTransportAttempt, validateUnsafeProxyTransportRetryMethods, } from "./proxy-retry-policy";
5
- import { appendQueryParams, normalizeHttpRequestBody } from "./request-options";
1
+ import { resolveProxyConfigAsync } from "../config/loader.js";
2
+ import { ProviderError, TransportError } from "../errors.js";
3
+ import { parseSseStream, readableBytes, readableLines, readableTextChunks } from "../stream.js";
4
+ import { computeProxyAttemptIndex, computeProxyTransportRetryDelayMs, createDefaultProxyTransportRetryOptions, isProxyTransportRetryMethod, normalizeProxyTransportRetryOptions, proxyTransportRetryErrorCode, proxyTransportRetryErrorStatus, shouldRetryProxyTransportAttempt, validateUnsafeProxyTransportRetryMethods, } from "./proxy-retry-policy.js";
5
+ import { appendQueryParams, normalizeHttpRequestBody } from "./request-options.js";
6
6
  const DEFAULT_HTTP_BASE_URL = "http://localhost";
7
7
  function isHttpStatusOutcome(outcome) {
8
8
  return "kind" in outcome && outcome.kind === "http-status";
@@ -1,4 +1,4 @@
1
- import type { Span } from "./trace";
1
+ import type { Span } from "./trace.js";
2
2
  export type InsightSeverity = "info" | "warning" | "error";
3
3
  export type Insight = {
4
4
  id: string;
@@ -1,4 +1,4 @@
1
- import { computePercentile } from "./perf";
1
+ import { computePercentile } from "./perf.js";
2
2
  const LARGE_RESPONSE_BYTES = 100_000;
3
3
  const SLOW_TRANSFORM_MS = 10;
4
4
  const DNS_WARN_MS = 5;
@@ -188,8 +188,7 @@ function getDnsRepeatedCandidate(spans) {
188
188
  if (entry.totalCount < 2) {
189
189
  continue;
190
190
  }
191
- const avgDnsMs = entry.dnsDurations.reduce((sum, value) => sum + value, 0) /
192
- entry.dnsDurations.length;
191
+ const avgDnsMs = entry.dnsDurations.reduce((sum, value) => sum + value, 0) / entry.dnsDurations.length;
193
192
  const reuseRate = entry.reuseCount / entry.totalCount;
194
193
  if (avgDnsMs > DNS_WARN_MS && reuseRate < 0.2) {
195
194
  if (!candidate || avgDnsMs > candidate.avgDnsMs) {
@@ -218,9 +217,7 @@ function getDnsRepeatedInsight(spans) {
218
217
  }
219
218
  function getProxyOverheadInsight(spans) {
220
219
  const requestSpans = spans.filter(isRequestSpan);
221
- const proxiedDurations = requestSpans
222
- .filter(hasProxy)
223
- .map((span) => span.duration_ms);
220
+ const proxiedDurations = requestSpans.filter(hasProxy).map((span) => span.duration_ms);
224
221
  const directDurations = requestSpans
225
222
  .filter((span) => !hasProxy(span))
226
223
  .map((span) => span.duration_ms);
@@ -230,10 +227,8 @@ function getProxyOverheadInsight(spans) {
230
227
  message: "✓ Proxy overhead: insufficient proxy/direct samples",
231
228
  };
232
229
  }
233
- const proxyAvg = proxiedDurations.reduce((sum, value) => sum + value, 0) /
234
- proxiedDurations.length;
235
- const directAvg = directDurations.reduce((sum, value) => sum + value, 0) /
236
- directDurations.length;
230
+ const proxyAvg = proxiedDurations.reduce((sum, value) => sum + value, 0) / proxiedDurations.length;
231
+ const directAvg = directDurations.reduce((sum, value) => sum + value, 0) / directDurations.length;
237
232
  if (directAvg > 0 && proxyAvg >= directAvg * 2) {
238
233
  return {
239
234
  triggered: true,
@@ -254,9 +249,7 @@ function getBrowserIdleInsight(spans) {
254
249
  if (waitMs !== undefined) {
255
250
  return waitMs;
256
251
  }
257
- return span.name.toLowerCase().includes("wait")
258
- ? span.duration_ms
259
- : undefined;
252
+ return span.name.toLowerCase().includes("wait") ? span.duration_ms : undefined;
260
253
  })
261
254
  .filter((value) => value !== undefined);
262
255
  if (waits.length === 0) {
@@ -1,5 +1,5 @@
1
- import type { ProviderContext } from "../types";
2
- import { type CreateTraceContextOptions, type TraceContext } from "./trace";
1
+ import type { ProviderContext } from "../types.js";
2
+ import { type CreateTraceContextOptions, type TraceContext } from "./trace.js";
3
3
  export interface InstrumentationOptions extends CreateTraceContextOptions {
4
4
  }
5
5
  export type InstrumentedProviderContext<T extends ProviderContext> = Omit<T, "trace"> & {
@@ -1,11 +1,5 @@
1
- import { createTraceContext, getTraceRecorder, } from "./trace";
2
- const BROWSER_PAGE_METHODS = new Set([
3
- "goto",
4
- "fill",
5
- "click",
6
- "type",
7
- "waitForSelector",
8
- ]);
1
+ import { createTraceContext, getTraceRecorder, } from "./trace.js";
2
+ const BROWSER_PAGE_METHODS = new Set(["goto", "fill", "click", "type", "waitForSelector"]);
9
3
  function getErrorStatus(error) {
10
4
  if (typeof error === "object" &&
11
5
  error !== null &&
@@ -69,9 +63,7 @@ function buildSpanAttributes(namespace, methodName, args, result, error) {
69
63
  const attributes = {};
70
64
  const url = getUrl(namespace, args, result);
71
65
  const method = getMethod(namespace, methodName, args);
72
- const status = error
73
- ? getErrorStatus(error)
74
- : getResponseStatus(namespace, result);
66
+ const status = error ? getErrorStatus(error) : getResponseStatus(namespace, result);
75
67
  const duration = error ? undefined : getResponseDuration(result);
76
68
  if (url) {
77
69
  attributes.url = url;
@@ -79,8 +71,7 @@ function buildSpanAttributes(namespace, methodName, args, result, error) {
79
71
  if (method) {
80
72
  attributes.method = method;
81
73
  }
82
- if (status !== undefined &&
83
- (namespace === "http" || namespace === "stealth")) {
74
+ if (status !== undefined && (namespace === "http" || namespace === "stealth")) {
84
75
  attributes.status = status;
85
76
  }
86
77
  if (duration !== undefined) {
@@ -192,8 +183,7 @@ function wrapNamespace(namespace, target, trace) {
192
183
  if (namespaceTarget &&
193
184
  typeof namespaceTarget === "object" &&
194
185
  "engine" in namespaceTarget &&
195
- typeof namespaceTarget.engine ===
196
- "string") {
186
+ typeof namespaceTarget.engine === "string") {
197
187
  attributes.engine = namespaceTarget.engine;
198
188
  }
199
189
  return attributes;
@@ -1,4 +1,4 @@
1
- import { ConfigurationError, decodeMasterKey } from "./key-derivation";
1
+ import { ConfigurationError, decodeMasterKey } from "./key-derivation.js";
2
2
  const DEFAULT_KEY_PREFIX = "APIFUSE__KEYRING__MASTER_KEY_V";
3
3
  const DEFAULT_ACCEPT_LIST_VAR = "APIFUSE__KEYRING__MASTER_KEY_ACCEPT_LIST";
4
4
  const DEFAULT_WRITER_VERSION_VAR = "APIFUSE__KEYRING__MASTER_KEY_WRITER_VERSION";
@@ -1,5 +1,5 @@
1
1
  import { createHmac } from "node:crypto";
2
- import { deriveSubkey } from "./key-derivation";
2
+ import { deriveSubkey } from "./key-derivation.js";
3
3
  const HMAC_HEX_LENGTH = 16;
4
4
  /**
5
5
  * @internal Trusted loaders only; not re-exported to provider-importable paths.
@@ -1,4 +1,4 @@
1
- import type { TraceSpan } from "../types";
1
+ import type { TraceSpan } from "../types.js";
2
2
  export interface OTLPExportOptions {
3
3
  endpoint: string;
4
4
  headers?: Record<string, string>;
@@ -1,4 +1,4 @@
1
- import type { Span } from "./trace";
1
+ import type { Span } from "./trace.js";
2
2
  export type PerfStats = {
3
3
  p50: number;
4
4
  p95: number;
@@ -1,2 +1,2 @@
1
- import type { ProviderDefinition } from "../types";
1
+ import type { ProviderDefinition } from "../types.js";
2
2
  export declare function getProviderBaseUrl(provider: ProviderDefinition): string | undefined;
@@ -1,8 +1,7 @@
1
1
  export function getProviderBaseUrl(provider) {
2
2
  const operations = Object.values(provider.operations);
3
3
  for (const operation of operations) {
4
- const baseUrl = operation.upstream
5
- ?.baseUrl;
4
+ const baseUrl = operation.upstream?.baseUrl;
6
5
  if (typeof baseUrl === "string" && baseUrl.length > 0) {
7
6
  return baseUrl;
8
7
  }
@@ -1,4 +1,4 @@
1
- import { TransportError } from "../errors";
1
+ import { TransportError } from "../errors.js";
2
2
  export declare const PROXY_AUTH_IP_DENIED_CODE = "PROXY_AUTH_IP_DENIED";
3
3
  export declare const PROXY_AUTH_IP_DENIED_MESSAGE = "Proxy source IP is not authorized. Add the runtime egress IP to the proxy provider allowlist.";
4
4
  export declare const PROXY_EDGE_AUTH_REJECTED_CODE = "PROXY_EDGE_AUTH_REJECTED";
@@ -1,4 +1,4 @@
1
- import { TransportError } from "../errors";
1
+ import { TransportError } from "../errors.js";
2
2
  export const PROXY_AUTH_IP_DENIED_CODE = "PROXY_AUTH_IP_DENIED";
3
3
  export const PROXY_AUTH_IP_DENIED_MESSAGE = "Proxy source IP is not authorized. Add the runtime egress IP to the proxy provider allowlist.";
4
4
  export const PROXY_EDGE_AUTH_REJECTED_CODE = "PROXY_EDGE_AUTH_REJECTED";
@@ -42,8 +42,7 @@ export function isProxyPoolStaleMessage(message) {
42
42
  return PROXY_POOL_STALE_MESSAGE_PATTERN.test(message);
43
43
  }
44
44
  export function isProxyPoolRefreshableError(error) {
45
- if (error instanceof TransportError &&
46
- error.code === PROXY_AUTH_IP_DENIED_CODE) {
45
+ if (error instanceof TransportError && error.code === PROXY_AUTH_IP_DENIED_CODE) {
47
46
  return false;
48
47
  }
49
48
  if (error instanceof TransportError &&
@@ -57,8 +56,7 @@ export function isProxyPoolRefreshableError(error) {
57
56
  error instanceof Error ? error.message : String(error),
58
57
  cause instanceof Error ? cause.message : "",
59
58
  ].join(" ");
60
- return (PROXY_POOL_STALE_MESSAGE_PATTERN.test(message) ||
61
- PROXY_EDGE_AUTH_REJECTED_PATTERN.test(message));
59
+ return (PROXY_POOL_STALE_MESSAGE_PATTERN.test(message) || PROXY_EDGE_AUTH_REJECTED_PATTERN.test(message));
62
60
  }
63
61
  export const isProxyPoolStaleError = isProxyPoolRefreshableError;
64
62
  export function createProxyPoolStaleError(status, cause) {
@@ -1,5 +1,5 @@
1
- import type { HttpMethod, HttpRetryOptions, RequestOptions } from "../types";
2
- import { HttpRetryPreset } from "../types";
1
+ import type { HttpMethod, HttpRetryOptions, RequestOptions } from "../types.js";
2
+ import { HttpRetryPreset } from "../types.js";
3
3
  export type NormalizedProxyTransportRetryOptions = Required<Pick<HttpRetryOptions, "attempts" | "delayStrategy" | "baseDelayMs" | "maxDelayMs" | "jitter" | "retryAfter" | "unsafeMethodPolicy">> & {
4
4
  preset?: HttpRetryPreset;
5
5
  methods: readonly string[];
@@ -1,5 +1,5 @@
1
- import { ProviderError, TransportError } from "../errors";
2
- import { HttpRetryAfterPolicy, HttpRetryDelayStrategy, HttpRetryJitter, HttpRetryPreset, HttpRetryUnsafeMethodPolicy, } from "../types";
1
+ import { ProviderError, TransportError } from "../errors.js";
2
+ import { HttpRetryAfterPolicy, HttpRetryDelayStrategy, HttpRetryJitter, HttpRetryPreset, HttpRetryUnsafeMethodPolicy, } from "../types.js";
3
3
  export const DEFAULT_PROXY_TRANSPORT_RETRY_METHODS = ["GET", "HEAD", "OPTIONS"];
4
4
  export const DEFAULT_PROXY_TRANSPORT_RETRY_ERROR_CODES = [
5
5
  "transport_network_error",
@@ -1,4 +1,4 @@
1
- import type { ProxyAttemptTelemetryEvent, ProxyResolutionTelemetryEvent, ProxyTelemetrySink } from "../config/loader";
1
+ import type { ProxyAttemptTelemetryEvent, ProxyResolutionTelemetryEvent, ProxyTelemetrySink } from "../config/loader.js";
2
2
  export declare const PROVIDER_TELEMETRY_HEADER = "X-ApiFuse-Provider-Telemetry";
3
3
  export declare class ProxyTelemetryCollector implements ProxyTelemetrySink {
4
4
  #private;
@@ -20,9 +20,7 @@ function maxOptional(left, right) {
20
20
  return values.length > 0 ? Math.max(...values) : undefined;
21
21
  }
22
22
  function worseStatus(left, right) {
23
- return CACHE_STATUS_SEVERITY[right] > CACHE_STATUS_SEVERITY[left]
24
- ? right
25
- : left;
23
+ return CACHE_STATUS_SEVERITY[right] > CACHE_STATUS_SEVERITY[left] ? right : left;
26
24
  }
27
25
  function encodeBase64Url(value) {
28
26
  return Buffer.from(value, "utf8").toString("base64url");
@@ -36,9 +34,7 @@ export class ProxyTelemetryCollector {
36
34
  cacheStatus: event.cacheStatus,
37
35
  cacheHit: event.cacheHit,
38
36
  resolutionMs: Math.max(0, Math.floor(event.resolutionMs)),
39
- allocatorMs: event.allocatorMs === undefined
40
- ? undefined
41
- : Math.max(0, Math.floor(event.allocatorMs)),
37
+ allocatorMs: event.allocatorMs === undefined ? undefined : Math.max(0, Math.floor(event.allocatorMs)),
42
38
  allocatorStatus: event.allocatorStatus === undefined
43
39
  ? undefined
44
40
  : Math.max(0, Math.floor(event.allocatorStatus)),
@@ -46,25 +42,15 @@ export class ProxyTelemetryCollector {
46
42
  allocatorAttempts: event.allocatorAttempts === undefined
47
43
  ? undefined
48
44
  : Math.max(1, Math.floor(event.allocatorAttempts)),
49
- lockWaitMs: event.lockWaitMs === undefined
50
- ? undefined
51
- : Math.max(0, Math.floor(event.lockWaitMs)),
52
- redisReadMs: event.redisReadMs === undefined
53
- ? undefined
54
- : Math.max(0, Math.floor(event.redisReadMs)),
55
- redisWriteMs: event.redisWriteMs === undefined
56
- ? undefined
57
- : Math.max(0, Math.floor(event.redisWriteMs)),
58
- poolAgeMs: event.poolAgeMs === undefined
59
- ? undefined
60
- : Math.max(0, Math.floor(event.poolAgeMs)),
45
+ lockWaitMs: event.lockWaitMs === undefined ? undefined : Math.max(0, Math.floor(event.lockWaitMs)),
46
+ redisReadMs: event.redisReadMs === undefined ? undefined : Math.max(0, Math.floor(event.redisReadMs)),
47
+ redisWriteMs: event.redisWriteMs === undefined ? undefined : Math.max(0, Math.floor(event.redisWriteMs)),
48
+ poolAgeMs: event.poolAgeMs === undefined ? undefined : Math.max(0, Math.floor(event.poolAgeMs)),
61
49
  poolExpiresInMs: event.poolExpiresInMs === undefined
62
50
  ? undefined
63
51
  : Math.max(0, Math.floor(event.poolExpiresInMs)),
64
52
  attempts: Math.max(1, Math.floor(event.attempts || 1)),
65
- refreshes: event.refreshes === undefined
66
- ? undefined
67
- : Math.max(0, Math.floor(event.refreshes)),
53
+ refreshes: event.refreshes === undefined ? undefined : Math.max(0, Math.floor(event.refreshes)),
68
54
  });
69
55
  }
70
56
  recordProxyAttempt(event) {
@@ -79,9 +65,7 @@ export class ProxyTelemetryCollector {
79
65
  ...(event.proxyHash ? { proxyHash: event.proxyHash.slice(0, 16) } : {}),
80
66
  outcome: event.outcome === "ok" ? "ok" : "error",
81
67
  ...(event.errorCode ? { errorCode: event.errorCode.slice(0, 80) } : {}),
82
- ...(event.status === undefined
83
- ? {}
84
- : { status: Math.max(0, Math.floor(event.status)) }),
68
+ ...(event.status === undefined ? {} : { status: Math.max(0, Math.floor(event.status)) }),
85
69
  ...(event.durationMs === undefined
86
70
  ? {}
87
71
  : { durationMs: Math.max(0, Math.floor(event.durationMs)) }),
@@ -115,9 +99,7 @@ export class ProxyTelemetryCollector {
115
99
  cacheStatus: aggregate.cacheStatus,
116
100
  cacheHit: aggregate.cacheHit,
117
101
  resolutionMs: aggregate.resolutionMs,
118
- ...(aggregate.allocatorMs !== undefined
119
- ? { allocatorMs: aggregate.allocatorMs }
120
- : {}),
102
+ ...(aggregate.allocatorMs !== undefined ? { allocatorMs: aggregate.allocatorMs } : {}),
121
103
  ...(aggregate.allocatorStatus !== undefined
122
104
  ? { allocatorStatus: aggregate.allocatorStatus }
123
105
  : {}),
@@ -127,40 +109,26 @@ export class ProxyTelemetryCollector {
127
109
  ...(aggregate.allocatorAttempts !== undefined
128
110
  ? { allocatorAttempts: aggregate.allocatorAttempts }
129
111
  : {}),
130
- ...(aggregate.lockWaitMs !== undefined
131
- ? { lockWaitMs: aggregate.lockWaitMs }
132
- : {}),
133
- ...(aggregate.redisReadMs !== undefined
134
- ? { redisReadMs: aggregate.redisReadMs }
135
- : {}),
136
- ...(aggregate.redisWriteMs !== undefined
137
- ? { redisWriteMs: aggregate.redisWriteMs }
138
- : {}),
139
- ...(aggregate.poolAgeMs !== undefined
140
- ? { poolAgeMs: aggregate.poolAgeMs }
141
- : {}),
112
+ ...(aggregate.lockWaitMs !== undefined ? { lockWaitMs: aggregate.lockWaitMs } : {}),
113
+ ...(aggregate.redisReadMs !== undefined ? { redisReadMs: aggregate.redisReadMs } : {}),
114
+ ...(aggregate.redisWriteMs !== undefined ? { redisWriteMs: aggregate.redisWriteMs } : {}),
115
+ ...(aggregate.poolAgeMs !== undefined ? { poolAgeMs: aggregate.poolAgeMs } : {}),
142
116
  ...(aggregate.poolExpiresInMs !== undefined
143
117
  ? { poolExpiresInMs: aggregate.poolExpiresInMs }
144
118
  : {}),
145
119
  attempts: aggregate.attempts,
146
- ...(aggregate.refreshes !== undefined
147
- ? { refreshes: aggregate.refreshes }
148
- : {}),
120
+ ...(aggregate.refreshes !== undefined ? { refreshes: aggregate.refreshes } : {}),
149
121
  ...(this.#attempts.length > 0
150
122
  ? {
151
123
  attemptSamples: this.#attempts.map((attempt, index) => ({
152
124
  n: index + 1,
153
125
  a: attempt.attempt,
154
- ...(attempt.poolIndex === undefined
155
- ? {}
156
- : { i: attempt.poolIndex }),
126
+ ...(attempt.poolIndex === undefined ? {} : { i: attempt.poolIndex }),
157
127
  ...(attempt.proxyHash ? { h: attempt.proxyHash } : {}),
158
128
  o: attempt.outcome,
159
129
  ...(attempt.errorCode ? { c: attempt.errorCode } : {}),
160
130
  ...(attempt.status === undefined ? {} : { s: attempt.status }),
161
- ...(attempt.durationMs === undefined
162
- ? {}
163
- : { d: attempt.durationMs }),
131
+ ...(attempt.durationMs === undefined ? {} : { d: attempt.durationMs }),
164
132
  })),
165
133
  }
166
134
  : {}),
@@ -1,4 +1,4 @@
1
- import Redis from "ioredis";
1
+ import { Redis } from "ioredis";
2
2
  export type ProviderRedisClient = Redis;
3
3
  export type ProviderRedisClientOptions = {
4
4
  readonly redisUrl: string;
@@ -1,4 +1,4 @@
1
- import Redis from "ioredis";
1
+ import { Redis } from "ioredis";
2
2
  export function createProviderRedisClient(options) {
3
3
  const redis = new Redis(options.redisUrl, {
4
4
  connectTimeout: options.timeoutMs,
@@ -23,9 +23,7 @@ export async function withRedisTimeout(operation, options) {
23
23
  }
24
24
  }, options.timeoutMs);
25
25
  });
26
- const operationResult = options.onError
27
- ? operation().catch(options.onError)
28
- : operation();
26
+ const operationResult = options.onError ? operation().catch(options.onError) : operation();
29
27
  return await Promise.race([operationResult, timeout]);
30
28
  }
31
29
  finally {
@@ -1,3 +1,3 @@
1
- import type { RequestParams } from "../types";
1
+ import type { RequestParams } from "../types.js";
2
2
  export declare function appendQueryParams(url: string, params?: RequestParams): string;
3
3
  export declare function normalizeHttpRequestBody(body: unknown): string | Buffer | undefined;
@@ -1,5 +1,5 @@
1
- import { ProviderError } from "../errors";
2
- import type { ProviderRuntimeState } from "../types";
1
+ import { ProviderError } from "../errors.js";
2
+ import type { ProviderRuntimeState } from "../types.js";
3
3
  type RedisProviderRuntimeStateOptions = {
4
4
  readonly redisUrl: string;
5
5
  readonly providerId?: string;
@@ -1,6 +1,6 @@
1
- import { providerStateRedisUrlFromEnv } from "../config/loader";
2
- import { ProviderError } from "../errors";
3
- import { createProviderRedisClient, ensureRedisReady, withRedisTimeout, } from "./redis";
1
+ import { providerStateRedisUrlFromEnv } from "../config/loader.js";
2
+ import { ProviderError } from "../errors.js";
3
+ import { createProviderRedisClient, ensureRedisReady, withRedisTimeout, } from "./redis.js";
4
4
  const DEFAULT_REDIS_TIMEOUT_MS = 250;
5
5
  const REDIS_STATE_PREFIX = "apifuse:provider-state:v1";
6
6
  const redisBackends = new Map();
@@ -1,6 +1,6 @@
1
1
  import type { ImpitResponse } from "impit";
2
- import type { ProxyResolutionOptions } from "../config/loader";
3
- import type { StealthClient, StealthResponse } from "../types";
2
+ import type { ProxyResolutionOptions } from "../config/loader.js";
3
+ import type { StealthClient, StealthResponse } from "../types.js";
4
4
  export type StealthClientOptions = ProxyResolutionOptions & {
5
5
  warn?: (message: string) => void;
6
6
  /**
@@ -1,11 +1,11 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { Impit } from "impit";
3
- import { DEFAULT_SMARTPROXY_POOL_SIZE, invalidateProxyResolutionCacheAsync, ProxyResolutionError, resolveProxyConfigAsync, SMARTPROXY_MAX_POOL_SIZE, } from "../config/loader";
4
- import { SDKError, TransportError } from "../errors";
5
- import { getStealthProfile } from "../stealth/profiles";
6
- import { createProxyAuthIpDeniedError, createProxyEdgeAuthRejectedError, createProxyEdgeTlsRejectedError, createProxyPoolExhaustedError, createProxyPoolStaleError, isProxyAuthIpDeniedMessage, isProxyEdgeAuthRejectedMessage, isProxyEdgeTlsRejectedResponse, isProxyPoolRefreshableError, isProxyPoolStaleMessage, isProxyPoolStaleStatus, PROXY_EDGE_AUTH_REJECTED_CODE, PROXY_POOL_STALE_CODE, } from "./proxy-errors";
7
- import { computeProxyAttemptIndex, computeProxyTransportRetryDelayMs, createDefaultProxyTransportRetryOptions, normalizeProxyTransportRetryOptions, shouldRetryProxyTransportAttempt, validateUnsafeProxyTransportRetryMethods, } from "./proxy-retry-policy";
8
- import { appendQueryParams } from "./request-options";
3
+ import { DEFAULT_SMARTPROXY_POOL_SIZE, invalidateProxyResolutionCacheAsync, ProxyResolutionError, resolveProxyConfigAsync, SMARTPROXY_MAX_POOL_SIZE, } from "../config/loader.js";
4
+ import { SDKError, TransportError } from "../errors.js";
5
+ import { getStealthProfile } from "../stealth/profiles.js";
6
+ import { createProxyAuthIpDeniedError, createProxyEdgeAuthRejectedError, createProxyEdgeTlsRejectedError, createProxyPoolExhaustedError, createProxyPoolStaleError, isProxyAuthIpDeniedMessage, isProxyEdgeAuthRejectedMessage, isProxyEdgeTlsRejectedResponse, isProxyPoolRefreshableError, isProxyPoolStaleMessage, isProxyPoolStaleStatus, PROXY_EDGE_AUTH_REJECTED_CODE, PROXY_POOL_STALE_CODE, } from "./proxy-errors.js";
7
+ import { computeProxyAttemptIndex, computeProxyTransportRetryDelayMs, createDefaultProxyTransportRetryOptions, normalizeProxyTransportRetryOptions, shouldRetryProxyTransportAttempt, validateUnsafeProxyTransportRetryMethods, } from "./proxy-retry-policy.js";
8
+ import { appendQueryParams } from "./request-options.js";
9
9
  const DEFAULT_PROFILE = "chrome-146";
10
10
  const MISSING_PROXY_WARNING = "[provider-sdk] Provider requested proxy routing, but no proxy URL was configured. Continuing without proxy.";
11
11
  const MAX_POLICY_PROXY_RETRY_ATTEMPTS = SMARTPROXY_MAX_POOL_SIZE;
@@ -1,4 +1,4 @@
1
- import type { ProviderSttConfig, SttContext, SttTranscribeRequest, SttVerificationCodeOptions, VerificationCodeExtractionResult } from "../types";
1
+ import type { ProviderSttConfig, SttContext, SttTranscribeRequest, SttVerificationCodeOptions, VerificationCodeExtractionResult } from "../types.js";
2
2
  export declare const APIFUSE__STT__BACKEND_ENV = "APIFUSE__STT__BACKEND";
3
3
  export declare const APIFUSE__STT__MODEL_ENV = "APIFUSE__STT__MODEL";
4
4
  export declare const CLOUDFLARE_ACCOUNT_ID_ENV = "APIFUSE__CLOUDFLARE__ACCOUNT_ID";
@@ -1,4 +1,4 @@
1
- import { ProviderError, TransportError, ValidationError } from "../errors";
1
+ import { ProviderError, TransportError, ValidationError } from "../errors.js";
2
2
  export const APIFUSE__STT__BACKEND_ENV = "APIFUSE__STT__BACKEND";
3
3
  export const APIFUSE__STT__MODEL_ENV = "APIFUSE__STT__MODEL";
4
4
  export const CLOUDFLARE_ACCOUNT_ID_ENV = "APIFUSE__CLOUDFLARE__ACCOUNT_ID";
@@ -59,17 +59,12 @@ export function createSttClientFromEnv(config, env = process.env) {
59
59
  return createCloudflareWorkersAiSttClient({
60
60
  accountId,
61
61
  apiToken,
62
- model: normalizedEnvValue(env, APIFUSE__STT__MODEL_ENV) ??
63
- DEFAULT_CLOUDFLARE_WORKERS_AI_STT_MODEL,
62
+ model: normalizedEnvValue(env, APIFUSE__STT__MODEL_ENV) ?? DEFAULT_CLOUDFLARE_WORKERS_AI_STT_MODEL,
64
63
  });
65
64
  }
66
65
  function base64ByteLength(data) {
67
66
  const normalized = data.trim();
68
- const padding = normalized.endsWith("==")
69
- ? 2
70
- : normalized.endsWith("=")
71
- ? 1
72
- : 0;
67
+ const padding = normalized.endsWith("==") ? 2 : normalized.endsWith("=") ? 1 : 0;
73
68
  return Math.floor((normalized.length * 3) / 4) - padding;
74
69
  }
75
70
  function assertBase64Audio(audio, maxAudioBytes) {
@@ -80,9 +75,7 @@ function assertBase64Audio(audio, maxAudioBytes) {
80
75
  });
81
76
  }
82
77
  const data = audio.data.trim();
83
- if (data.length === 0 ||
84
- data.length % 4 !== 0 ||
85
- !BASE64_AUDIO_PATTERN.test(data)) {
78
+ if (data.length === 0 || data.length % 4 !== 0 || !BASE64_AUDIO_PATTERN.test(data)) {
86
79
  throw new ValidationError("STT audio.data must be a base64-encoded string", {
87
80
  code: "INVALID_STT_AUDIO",
88
81
  });
@@ -90,7 +83,9 @@ function assertBase64Audio(audio, maxAudioBytes) {
90
83
  const bytes = base64ByteLength(data);
91
84
  const maxBytes = maxAudioBytes ?? DEFAULT_STT_MAX_AUDIO_BYTES;
92
85
  if (bytes > maxBytes) {
93
- throw new ValidationError(`STT audio exceeds maxAudioBytes (${bytes} > ${maxBytes})`, { code: "STT_AUDIO_TOO_LARGE" });
86
+ throw new ValidationError(`STT audio exceeds maxAudioBytes (${bytes} > ${maxBytes})`, {
87
+ code: "STT_AUDIO_TOO_LARGE",
88
+ });
94
89
  }
95
90
  return bytes;
96
91
  }
@@ -227,8 +222,7 @@ export function createCloudflareWorkersAiSttClient(options) {
227
222
  return {
228
223
  async transcribe(request) {
229
224
  const warnings = [];
230
- if (request.initialPrompt &&
231
- effectivePromptPolicy(request) !== "custom-hint") {
225
+ if (request.initialPrompt && effectivePromptPolicy(request) !== "custom-hint") {
232
226
  const warning = warnOrThrowUnsupportedOption(request, "initialPrompt is honored only when promptPolicy is custom-hint");
233
227
  if (warning)
234
228
  warnings.push(warning);
@@ -350,7 +344,9 @@ function lengthSet(codeLengths) {
350
344
  }
351
345
  function validCodeLength(value) {
352
346
  if (!Number.isInteger(value) || value < 1 || value > 32) {
353
- throw new ValidationError("STT verification code length must be an integer between 1 and 32", { code: "INVALID_STT_VERIFICATION_CODE_OPTIONS" });
347
+ throw new ValidationError("STT verification code length must be an integer between 1 and 32", {
348
+ code: "INVALID_STT_VERIFICATION_CODE_OPTIONS",
349
+ });
354
350
  }
355
351
  return value;
356
352
  }
@@ -1,5 +1,5 @@
1
- import type { TraceContext as BaseTraceContext, TraceAttributeValue, TraceConfig, TraceSpan } from "../types";
2
- import { type OTLPExportOptions } from "./otlp";
1
+ import type { TraceContext as BaseTraceContext, TraceAttributeValue, TraceConfig, TraceSpan } from "../types.js";
2
+ import { type OTLPExportOptions } from "./otlp.js";
3
3
  export type SpanAttributeValue = TraceAttributeValue;
4
4
  export type Span = TraceSpan;
5
5
  export interface TraceContext extends BaseTraceContext {
@@ -1,5 +1,5 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import { exportSpansOTLP } from "./otlp";
2
+ import { exportSpansOTLP } from "./otlp.js";
3
3
  export const TRACE_RECORDER = Symbol.for("@apifuse/provider-sdk/runtime/trace-recorder");
4
4
  function buildOTLPExportOptions(config) {
5
5
  if (config?.exporter !== "otlp") {
@@ -23,9 +23,7 @@ export function resolveTraceContextOptions(config) {
23
23
  };
24
24
  }
25
25
  function normalizeAttributeValue(value) {
26
- if (typeof value === "string" ||
27
- typeof value === "number" ||
28
- typeof value === "boolean") {
26
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
29
27
  return value;
30
28
  }
31
29
  if (value === null || value === undefined) {
@@ -1,4 +1,4 @@
1
- import type { Span } from "./trace";
1
+ import type { Span } from "./trace.js";
2
2
  export type WaterfallRequest = {
3
3
  method: string;
4
4
  path: string;
package/dist/schema.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type ZodString, type ZodType, z } from "zod";
2
- import type { InferSchemaOutput, ProviderLocaleKey, SchemaLike } from "./types";
2
+ import type { InferSchemaOutput, ProviderLocaleKey, SchemaLike } from "./types.js";
3
3
  export { z };
4
4
  export type SchemaValidationResult<TSchema extends SchemaLike> = {
5
5
  success: true;