@apifuse/provider-sdk 2.2.0-beta.22 → 2.2.0-beta.23

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # @apifuse/provider-sdk Changelog
2
2
 
3
+ ## 2.2.0-beta.23
4
+
5
+ - Release candidate for main commit 36b3bedc9c14913c4152c4631cc87de71062f21f.
6
+
3
7
  ## 2.2.0-beta.22
4
8
 
5
9
  - Release candidate for main commit b8bf920b5ca053d1bf43018167fd4eedff01700d.
@@ -8,6 +8,7 @@ import {
8
8
  createCredentialContext,
9
9
  createEnvContext,
10
10
  createHttpClient,
11
+ createOcrClientFromEnv,
11
12
  createProviderCache,
12
13
  createProviderChoiceContext,
13
14
  createStealthClient,
@@ -96,6 +97,7 @@ export function createProviderContext(provider: ProviderDefinition): {
96
97
  state,
97
98
  trace: createTraceContext(),
98
99
  stealth: createStealthClient("http://localhost"),
100
+ ocr: createOcrClientFromEnv(provider.ocr),
99
101
  stt: createSttClientFromEnv(provider.stt),
100
102
  choice: createProviderChoiceContext({
101
103
  providerId: provider.id,
@@ -8,6 +8,7 @@ import { pathToFileURL } from "node:url";
8
8
  import {
9
9
  createBypassProviderCache,
10
10
  createHttpClient,
11
+ createOcrClientFromEnv,
11
12
  createProviderChoiceContext,
12
13
  createStealthClient,
13
14
  createSttClientFromEnv,
@@ -536,6 +537,7 @@ function createCaptureContext(provider: ProviderRuntime, baseUrl: string, saniti
536
537
  throw new Error("Auth prompts are not available in apifuse record.");
537
538
  },
538
539
  },
540
+ ocr: createOcrClientFromEnv(provider.ocr),
539
541
  stt: createSttClientFromEnv(provider.stt),
540
542
  choice: createProviderChoiceContext({
541
543
  providerId: provider.id,
@@ -11,6 +11,7 @@ export interface ProviderContractSnapshot {
11
11
  readonly allowedHosts?: readonly string[];
12
12
  readonly stealth?: JsonValue;
13
13
  readonly proxy?: JsonValue;
14
+ readonly ocr?: JsonValue;
14
15
  readonly stt?: JsonValue;
15
16
  readonly browser?: JsonValue;
16
17
  readonly auth?: JsonValue;
package/dist/contract.js CHANGED
@@ -7,6 +7,7 @@ export function extractProviderContract(provider) {
7
7
  const auth = extractAuth(provider.auth);
8
8
  const stealth = toJsonValue(provider.stealth);
9
9
  const proxy = toJsonValue(provider.proxy);
10
+ const ocr = toJsonValue(provider.ocr);
10
11
  const stt = toJsonValue(provider.stt);
11
12
  const browser = toJsonValue(provider.browser);
12
13
  const reviewed = toJsonValue(provider.reviewed);
@@ -30,6 +31,7 @@ export function extractProviderContract(provider) {
30
31
  ...(provider.allowedHosts ? { allowedHosts: [...provider.allowedHosts].sort() } : {}),
31
32
  ...(stealth === undefined ? {} : { stealth }),
32
33
  ...(proxy === undefined ? {} : { proxy }),
34
+ ...(ocr === undefined ? {} : { ocr }),
33
35
  ...(stt === undefined ? {} : { stt }),
34
36
  ...(browser === undefined ? {} : { browser }),
35
37
  ...(auth === undefined ? {} : { auth }),
package/dist/define.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AuthConfig, BrowserEngine, ContextDeclaration, CredentialDeclaration, HealthJourneyDefinition, HealthJourneySchedule, HealthScheduleRandomization, InferSchemaOutput, OperationDefinition, OperationHandlerResult, OperationHttpStreamTransport, OperationSseTransport, OperationWebSocketTransport, NativeProviderConfig, ProviderAccessConfig, ProviderDefinition, ProviderDeploymentOverrides, ProviderHealthMonitorConfig, ProviderProxyConfig, ProviderPublicProfile, ProviderReviewed, ProviderSecretDeclaration, ProviderStreamEvent, ProviderSttConfig, SchemaLike, SmsOtpMatcherDefinition, StealthPlatform } from "./types.js";
1
+ import type { AuthConfig, BrowserEngine, ContextDeclaration, CredentialDeclaration, HealthJourneyDefinition, HealthJourneySchedule, HealthScheduleRandomization, InferSchemaOutput, OperationDefinition, OperationHandlerResult, OperationHttpStreamTransport, OperationSseTransport, OperationWebSocketTransport, NativeProviderConfig, ProviderOcrConfig, ProviderAccessConfig, ProviderDefinition, ProviderDeploymentOverrides, ProviderHealthMonitorConfig, ProviderProxyConfig, ProviderPublicProfile, ProviderReviewed, ProviderSecretDeclaration, ProviderStreamEvent, ProviderSttConfig, SchemaLike, SmsOtpMatcherDefinition, StealthPlatform } from "./types.js";
2
2
  type ProviderImplementationSourceAccess = "official_api" | "private_api" | "browser_flow" | "hybrid";
3
3
  type ProviderImplementationCredentialStrategy = "apifuse_managed" | "workspace_secret" | "user_oauth" | "user_session" | "none";
4
4
  interface ProviderImplementationProfile {
@@ -55,6 +55,7 @@ export interface ProviderConfig<TOperations extends Record<string, ProviderOpera
55
55
  platform: StealthPlatform;
56
56
  };
57
57
  proxy?: ProviderProxyConfig;
58
+ ocr?: ProviderOcrConfig;
58
59
  stt?: ProviderSttConfig;
59
60
  browser?: {
60
61
  engine: BrowserEngine;
package/dist/define.js CHANGED
@@ -47,6 +47,7 @@ const VALID_PROVIDER_PROXY_AFFINITIES = [
47
47
  "auth-flow",
48
48
  "connection",
49
49
  ];
50
+ const VALID_PROVIDER_OCR_MODES = ["optional", "required"];
50
51
  const VALID_PROVIDER_STT_MODES = ["optional", "required"];
51
52
  const SMARTPROXY_APP_KEY_SECRET = "APIFUSE__PROXY__SMARTPROXY_APP_KEY";
52
53
  const NODEMAVEN_USERNAME_SECRET = "APIFUSE__PROXY__NODEMAVEN_USERNAME";
@@ -377,6 +378,18 @@ function validateProviderStt(config) {
377
378
  rejectUnknownFields(stt, new Set(["mode"]), "stt");
378
379
  assertLiteralField(stt.mode, "stt.mode", VALID_PROVIDER_STT_MODES, config.id);
379
380
  }
381
+ function validateProviderOcr(config) {
382
+ const ocr = config.ocr;
383
+ if (ocr === undefined)
384
+ return;
385
+ if (!ocr || typeof ocr !== "object" || Array.isArray(ocr)) {
386
+ throw new ValidationError(`Provider "${config.id}" has invalid ocr: must be an object.`, {
387
+ fix: `Use ocr: { mode: "required" } or ocr: { mode: "optional" }.`,
388
+ });
389
+ }
390
+ rejectUnknownFields(ocr, new Set(["mode"]), "ocr");
391
+ assertLiteralField(ocr.mode, "ocr.mode", VALID_PROVIDER_OCR_MODES, config.id);
392
+ }
380
393
  function validateOperationIds(providerId, operations) {
381
394
  for (const operationName of Object.keys(operations)) {
382
395
  if (!OPERATION_ID_REGEX.test(operationName))
@@ -1538,6 +1551,7 @@ export function defineProvider(config) {
1538
1551
  throw error;
1539
1552
  }
1540
1553
  validateProviderProxy(config);
1554
+ validateProviderOcr(config);
1541
1555
  validateProviderStt(config);
1542
1556
  if (config.runtime === "browser" && !config.browser)
1543
1557
  throw new ProviderError(`Provider "${config.id}" must define browser.engine when runtime is "browser"`, {
@@ -1556,6 +1570,7 @@ export function defineProvider(config) {
1556
1570
  native: config.native,
1557
1571
  stealth: config.stealth,
1558
1572
  proxy: config.proxy,
1573
+ ocr: config.ocr,
1559
1574
  stt: config.stt,
1560
1575
  browser: config.browser,
1561
1576
  auth: config.auth,
@@ -28,6 +28,7 @@ export const SDK_OWNED_PROVIDER_ERROR_CODES = new Set([
28
28
  "flow_expired",
29
29
  "turn_validation_error",
30
30
  "context_access_error",
31
+ "OCR_UPSTREAM_FAILED",
31
32
  "UNSUPPORTED_STT_OPTION",
32
33
  "INVALID_STT_AUDIO",
33
34
  "STT_AUDIO_TOO_LARGE",
@@ -82,6 +83,8 @@ export const SDK_OWNED_PROVIDER_ERROR_CODES = new Set([
82
83
  export const SDK_RUNTIME_OWNED_ERROR_CODES = new Set([
83
84
  ...SDK_OWNED_PROVIDER_ERROR_CODES,
84
85
  "reauth_required",
86
+ "OCR_UNAVAILABLE",
87
+ "UNSUPPORTED_OCR_BACKEND",
85
88
  "STT_UNAVAILABLE",
86
89
  "UNSUPPORTED_STT_BACKEND",
87
90
  "OUTPUT_VALIDATION_FAILED",
@@ -111,6 +114,8 @@ export const SDK_STATUS_MAPPED_PROVIDER_ERROR_CODES = new Map([
111
114
  ["UPSTREAM_REJECTED", 409],
112
115
  ["UPSTREAM_ERROR", 502],
113
116
  ["BLOCKED", 502],
117
+ ["OCR_UNAVAILABLE", 503],
118
+ ["UNSUPPORTED_OCR_BACKEND", 503],
114
119
  ["STT_UNAVAILABLE", 503],
115
120
  ["UNSUPPORTED_STT_BACKEND", 503],
116
121
  ["STATEFUL_FORWARDING_REPLAY_CACHE_FULL", 503],
package/dist/index.d.ts CHANGED
@@ -32,13 +32,14 @@ export { getProviderBaseUrl } from "./runtime/provider.js";
32
32
  export { assertRequiredSecretsPresent, listMissingRequiredSecrets, MISSING_SECRET_CODE, } from "./runtime/secrets.js";
33
33
  export { createUnsupportedProviderRuntimeState, UnsupportedProviderStateError, } from "./runtime/state.js";
34
34
  export { createStealthClient } from "./runtime/stealth.js";
35
+ export { APIFUSE__OCR__API_KEY_ENV, APIFUSE__OCR__BACKEND_ENV, APIFUSE__OCR__BASE_URL_ENV, APIFUSE__OCR__CLOUDFLARE_API_TOKEN_ENV, APIFUSE__OCR__MODEL_ENV, CLOUDFLARE_ACCOUNT_ID_ENV, CLOUDFLARE_WORKERS_AI_OCR_BACKEND, createCloudflareWorkersAiOcrClient, createOcrClientFromEnv, createOpenAiCompatibleOcrClient, createUnsupportedOcrClient, DEFAULT_CLOUDFLARE_WORKERS_AI_OCR_MODEL, extractCaptchaCandidates, OPENAI_COMPATIBLE_OCR_BACKEND, } from "./runtime/ocr.js";
35
36
  export { APIFUSE__STT__BACKEND_ENV, APIFUSE__STT__CLOUDFLARE_API_TOKEN_ENV, APIFUSE__STT__MODEL_ENV, createSttClientFromEnv, createUnsupportedSttClient, extractVerificationCode, resolveSttPrompt, } from "./runtime/stt.js";
36
37
  export { type CreateTraceContextOptions, createTraceContext, type Span, type TraceContext, } from "./runtime/trace.js";
37
38
  export { APIFUSE_DESCRIPTION_KEY_META_KEY, APIFUSE_REDACTION_MARKER, APIFUSE_SENSITIVE_KIND_META_KEY, APIFUSE_SENSITIVE_META_KEY, collectSensitivePaths, describeKey, field, fields, isSensitiveSchema, redactPayload, type SensitiveFieldKind, type SensitiveFieldOptions, type SensitivePath, sensitive, z, } from "./schema.js";
38
39
  export { createServerApp, ERROR_OBSERVABILITY_HEADER, type ServeOptions, serve, } from "./server/index.js";
39
40
  export { getStealthProfile, listStealthProfiles } from "./stealth/profiles.js";
40
41
  export * from "./stream.js";
41
- export type { ApiFuseResponse, AuthConfig, AuthContext, AuthFlowDefinition, AuthFlowInputHandler, AuthFlowStartHandler, AuthMode, AuthTurn, Bcp47Locale, BrowserEngine, BrowserOptions, BrowserResourceBody, BrowserResourceDecision, BrowserResourceMethod, BrowserResourcePolicy, BrowserResourceRequest, BrowserResourceRoute, ConnectionMode, ContextDeclaration, CookieJar, ContextScratchpad, CredentialContext, CredentialDeclaration, E164PhoneNumber, EnvContext, FlowContext, FlowContextStore, HealthCheckAssertionContext, HealthCheckCase, HealthCheckCaseResult, HealthCheckSuite, HealthCheckUnsupported, HealthJourneyDefinition, HealthJourneyEventContext, HealthJourneyGatewayContext, HealthJourneyJournalContext, HealthJourneyManualTriggerPolicy, HealthJourneyRunContext, HealthJourneyRunResult, HealthJourneySchedule, HealthScheduleRandomization, HealthJourneySmsContext, HealthJourneyStep, HttpClient, HttpMethod, HttpRedirectFailureReason, HttpRedirectPolicy, HttpRedirectPolicyMode, HttpResponse, HttpRetryOptions, HttpRetrySummary, HttpStreamResponse, IanaTimeZone, InferSchemaOutput, Iso3166Alpha2CountryCode, Iso4217CurrencyCode, Iso8601Duration, NativeContext, NativeNetworkClient, NativeNetworkCloseReason, NativeNetworkConnection, NativeNetworkConnectInput, NativeNetworkConnectOptions, NativeNetworkDynamicGrantOptions, NativeNetworkEgressGrant, NativeProviderConfig, NativeProviderContext, NativeProxyDrainHandler, NativeProxyEgressInfo, NativeProxyExpiringEvent, NativeProxyExpiringReason, NativeTcpDynamicEgressRule, NativeTcpEgressGrant, NativeTcpEgressRule, NativeTcpPortRange, NativeTcpTlsMode, NativeTlsConnectOptions, OperationAnnotations, OperationApprovalPolicy, OperationContractMetadata, OperationDefinition, OperationDeprecationMetadata, OperationDocMeta, OperationErrorCode, ProviderErrorStatus, OperationHandlerResult, OperationInputExample, OperationLifecycle, OperationObservabilityConfig, OperationObservabilitySensitiveConfig, OperationRelationships, OperationRiskClass, OperationSensitivePath, OperationToolRouterMetadata, OperationTransport, OperationTransportKind, ProbeInterval, ProviderAccessConfig, ProviderAccessVisibility, ProviderCache, ProviderCacheGetOrSetOptions, ProviderCacheKeyOptions, ProviderCacheLookupMeta, ProviderCacheResponseMeta, ProviderCacheResult, ProviderChoiceBindingOptions, ProviderChoiceContext, ProviderChoiceIssueOptions, ProviderChoiceParseOptions, ProviderContext, ProviderDefinition, ProviderDeploymentOverrides, ProviderFileRef, ProviderFilesContext, ProviderHealthMonitorConfig, ProviderHealthProbeConfig, ProviderLocale, ProviderLocaleKey, ProviderLocaleKeyInput, ProviderLogoProfile, ProviderLogoSource, ProviderMeta, ProviderProxyConfig, ProviderProxyMode, ProviderProxyPolicy, ProxiedOAuthConfig, ProviderProxyProvider, ProviderProxySessionAffinity, ProviderPublicConnectionMode, ProviderPublicProfile, ProviderReviewed, ProviderResolvedFile, ProviderRuntimeState, ProviderSecretDeclaration, ProviderStateDurationString, ProviderStateNamespace, ProviderStreamEvent, ProviderSttConfig, ProviderSttMode, ProviderSupportLevel, RequestOptions, RedirectRunReason, Rfc3339Instant, SchemaLike, SmsOrigin, SmsOtpExtractionPattern, SmsOtpMatcherDefinition, SseMessage, StandardSchemaV1, StateCasResult, StateNamespaceOptions, StateValue, StateWriteOptions, StealthClient, StealthCookieStore, StealthCookieStoreV1, StealthFetchOptions, StealthPlatform, StealthProfile, StealthRedirectHop, StealthRedirectRunOptions, StealthRedirectRunResult, StealthResponse, StealthSession, StealthSessionCookies, SttAudioInput, SttContext, SttPromptPolicy, SttSegment, SttTranscribeMode, SttTranscribeRequest, SttTranscript, SttUnsupportedOptionPolicy, SttUsage, SttVerificationCodeOptions, SttWarning, TraceConfig, TraceSpan, VerificationCodeCandidate, VerificationCodeCandidateSource, VerificationCodeExtractionResult, } from "./types.js";
42
+ export type { ApiFuseResponse, AuthConfig, AuthContext, AuthFlowDefinition, AuthFlowInputHandler, AuthFlowStartHandler, AuthMode, AuthTurn, Bcp47Locale, BrowserEngine, BrowserOptions, BrowserResourceBody, BrowserResourceDecision, BrowserResourceMethod, BrowserResourcePolicy, BrowserResourceRequest, BrowserResourceRoute, ConnectionMode, ContextDeclaration, CookieJar, ContextScratchpad, CredentialContext, CredentialDeclaration, E164PhoneNumber, EnvContext, FlowContext, FlowContextStore, HealthCheckAssertionContext, HealthCheckCase, HealthCheckCaseResult, HealthCheckSuite, HealthCheckUnsupported, HealthJourneyDefinition, HealthJourneyEventContext, HealthJourneyGatewayContext, HealthJourneyJournalContext, HealthJourneyManualTriggerPolicy, HealthJourneyRunContext, HealthJourneyRunResult, HealthJourneySchedule, HealthScheduleRandomization, HealthJourneySmsContext, HealthJourneyStep, HttpClient, HttpMethod, HttpRedirectFailureReason, HttpRedirectPolicy, HttpRedirectPolicyMode, HttpResponse, HttpRetryOptions, HttpRetrySummary, HttpStreamResponse, IanaTimeZone, InferSchemaOutput, Iso3166Alpha2CountryCode, Iso4217CurrencyCode, Iso8601Duration, NativeContext, NativeNetworkClient, NativeNetworkCloseReason, NativeNetworkConnection, NativeNetworkConnectInput, NativeNetworkConnectOptions, NativeNetworkDynamicGrantOptions, NativeNetworkEgressGrant, NativeProviderConfig, NativeProviderContext, NativeProxyDrainHandler, NativeProxyEgressInfo, NativeProxyExpiringEvent, NativeProxyExpiringReason, NativeTcpDynamicEgressRule, NativeTcpEgressGrant, NativeTcpEgressRule, NativeTcpPortRange, NativeTcpTlsMode, NativeTlsConnectOptions, OcrCaptchaCandidate, OcrCaptchaOptions, OcrCaptchaResult, OcrContext, OcrImageInput, OcrRecognizeRequest, OcrResult, OcrWarning, OperationAnnotations, OperationApprovalPolicy, OperationContractMetadata, OperationDefinition, OperationDeprecationMetadata, OperationDocMeta, OperationErrorCode, ProviderErrorStatus, OperationHandlerResult, OperationInputExample, OperationLifecycle, OperationObservabilityConfig, OperationObservabilitySensitiveConfig, OperationRelationships, OperationRiskClass, OperationSensitivePath, OperationToolRouterMetadata, OperationTransport, OperationTransportKind, ProbeInterval, ProviderAccessConfig, ProviderAccessVisibility, ProviderCache, ProviderCacheGetOrSetOptions, ProviderCacheKeyOptions, ProviderCacheLookupMeta, ProviderCacheResponseMeta, ProviderCacheResult, ProviderChoiceBindingOptions, ProviderChoiceContext, ProviderChoiceIssueOptions, ProviderChoiceParseOptions, ProviderContext, ProviderDefinition, ProviderDeploymentOverrides, ProviderFileRef, ProviderFilesContext, ProviderHealthMonitorConfig, ProviderHealthProbeConfig, ProviderLocale, ProviderLocaleKey, ProviderLocaleKeyInput, ProviderLogoProfile, ProviderLogoSource, ProviderMeta, ProviderOcrConfig, ProviderProxyConfig, ProviderProxyMode, ProviderProxyPolicy, ProxiedOAuthConfig, ProviderProxyProvider, ProviderProxySessionAffinity, ProviderPublicConnectionMode, ProviderPublicProfile, ProviderReviewed, ProviderResolvedFile, ProviderRuntimeState, ProviderSecretDeclaration, ProviderStateDurationString, ProviderStateNamespace, ProviderStreamEvent, ProviderSttConfig, ProviderSttMode, ProviderSupportLevel, RequestOptions, RedirectRunReason, Rfc3339Instant, SchemaLike, SmsOrigin, SmsOtpExtractionPattern, SmsOtpMatcherDefinition, SseMessage, StandardSchemaV1, StateCasResult, StateNamespaceOptions, StateValue, StateWriteOptions, StealthClient, StealthCookieStore, StealthCookieStoreV1, StealthFetchOptions, StealthPlatform, StealthProfile, StealthRedirectHop, StealthRedirectRunOptions, StealthRedirectRunResult, StealthResponse, StealthSession, StealthSessionCookies, SttAudioInput, SttContext, SttPromptPolicy, SttSegment, SttTranscribeMode, SttTranscribeRequest, SttTranscript, SttUnsupportedOptionPolicy, SttUsage, SttVerificationCodeOptions, SttWarning, TraceConfig, TraceSpan, VerificationCodeCandidate, VerificationCodeCandidateSource, VerificationCodeExtractionResult, } from "./types.js";
42
43
  export { DEFAULT_OPERATION_TRANSPORT, HttpRetryAfterPolicy, HttpRetryDelayStrategy, HttpRetryJitter, HttpRetryPreset, HttpRetryUnsafeMethodPolicy, PROBE_INTERVALS, 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";
43
44
  export * from "./utils/date.js";
44
45
  export * from "./utils/parse.js";
package/dist/index.js CHANGED
@@ -29,6 +29,7 @@ export { getProviderBaseUrl } from "./runtime/provider.js";
29
29
  export { assertRequiredSecretsPresent, listMissingRequiredSecrets, MISSING_SECRET_CODE, } from "./runtime/secrets.js";
30
30
  export { createUnsupportedProviderRuntimeState, UnsupportedProviderStateError, } from "./runtime/state.js";
31
31
  export { createStealthClient } from "./runtime/stealth.js";
32
+ export { APIFUSE__OCR__API_KEY_ENV, APIFUSE__OCR__BACKEND_ENV, APIFUSE__OCR__BASE_URL_ENV, APIFUSE__OCR__CLOUDFLARE_API_TOKEN_ENV, APIFUSE__OCR__MODEL_ENV, CLOUDFLARE_ACCOUNT_ID_ENV, CLOUDFLARE_WORKERS_AI_OCR_BACKEND, createCloudflareWorkersAiOcrClient, createOcrClientFromEnv, createOpenAiCompatibleOcrClient, createUnsupportedOcrClient, DEFAULT_CLOUDFLARE_WORKERS_AI_OCR_MODEL, extractCaptchaCandidates, OPENAI_COMPATIBLE_OCR_BACKEND, } from "./runtime/ocr.js";
32
33
  export { APIFUSE__STT__BACKEND_ENV, APIFUSE__STT__CLOUDFLARE_API_TOKEN_ENV, APIFUSE__STT__MODEL_ENV, createSttClientFromEnv, createUnsupportedSttClient, extractVerificationCode, resolveSttPrompt, } from "./runtime/stt.js";
33
34
  export { createTraceContext, } from "./runtime/trace.js";
34
35
  export { APIFUSE_DESCRIPTION_KEY_META_KEY, APIFUSE_REDACTION_MARKER, APIFUSE_SENSITIVE_KIND_META_KEY, APIFUSE_SENSITIVE_META_KEY, collectSensitivePaths, describeKey, field, fields, isSensitiveSchema, redactPayload, sensitive, z, } from "./schema.js";
@@ -1,4 +1,4 @@
1
- import type { ContextScratchpad, EnvContext, FlowContext, HttpClient, StealthClient, SttContext } from "../types.js";
1
+ import type { ContextScratchpad, EnvContext, FlowContext, HttpClient, OcrContext, StealthClient, SttContext } from "../types.js";
2
2
  export declare function createScratchpad(allowedKeys: string[], initial?: Record<string, unknown>): ContextScratchpad;
3
3
  export declare function createFlowContext(options: {
4
4
  flowId?: string;
@@ -11,5 +11,6 @@ export declare function createFlowContext(options: {
11
11
  externalRef?: string;
12
12
  allowedKeys: string[];
13
13
  initialContext?: Record<string, unknown>;
14
+ ocr?: OcrContext;
14
15
  stt?: SttContext;
15
16
  }): FlowContext;
@@ -1,5 +1,6 @@
1
1
  import { ContextAccessError } from "../errors.js";
2
2
  import { createAuthFlowHelpers } from "../auth.js";
3
+ import { createUnsupportedOcrClient } from "./ocr.js";
3
4
  import { createUnsupportedSttClient } from "./stt.js";
4
5
  function normalizeAllowedKeys(allowedKeys) {
5
6
  return new Set(allowedKeys.filter((key) => key.trim().length > 0));
@@ -41,6 +42,7 @@ export function createFlowContext(options) {
41
42
  stealth: options.stealth,
42
43
  env: options.env,
43
44
  context: createScratchpad(options.allowedKeys, options.initialContext),
45
+ ocr: options.ocr ?? createUnsupportedOcrClient(),
44
46
  stt: options.stt ?? createUnsupportedSttClient(),
45
47
  auth: createAuthFlowHelpers(),
46
48
  };
@@ -457,7 +457,7 @@ function normalizeWebSocketEndpoint(endpoint) {
457
457
  }
458
458
  throw new Error(`Unsupported WebSocket endpoint protocol: ${url.protocol}`);
459
459
  }
460
- class JsonRpcWebSocketClient {
460
+ class WebSocketCommandClient {
461
461
  nextId = 1;
462
462
  endpoint;
463
463
  listeners = new Map();
@@ -483,12 +483,7 @@ class JsonRpcWebSocketClient {
483
483
  const id = this.nextId++;
484
484
  return await new Promise((resolve, reject) => {
485
485
  this.pending.set(id, { resolve, reject });
486
- socket.send(JSON.stringify({
487
- id,
488
- jsonrpc: "2.0",
489
- method,
490
- params,
491
- }));
486
+ socket.send(JSON.stringify(this.createCommandFrame(id, method, params)));
492
487
  });
493
488
  }
494
489
  async close() {
@@ -526,7 +521,11 @@ class JsonRpcWebSocketClient {
526
521
  }
527
522
  this.pending.delete(payload.id);
528
523
  if (payload.error) {
529
- pending.reject(new Error(payload.error.message ?? "JSON-RPC command failed"));
524
+ const error = new Error(payload.error.message ?? "JSON-RPC command failed");
525
+ if (typeof payload.error.code === "number") {
526
+ Object.assign(error, { code: payload.error.code });
527
+ }
528
+ pending.reject(error);
530
529
  return;
531
530
  }
532
531
  pending.resolve(payload.result ?? {});
@@ -554,6 +553,26 @@ class JsonRpcWebSocketClient {
554
553
  return this.socketPromise;
555
554
  }
556
555
  }
556
+ class CdpWebSocketClient extends WebSocketCommandClient {
557
+ sessionId;
558
+ constructor(endpoint, sessionId) {
559
+ super(endpoint);
560
+ this.sessionId = sessionId;
561
+ }
562
+ createCommandFrame(id, method, params) {
563
+ return {
564
+ id,
565
+ method,
566
+ params,
567
+ ...(this.sessionId === undefined ? {} : { sessionId: this.sessionId }),
568
+ };
569
+ }
570
+ }
571
+ class JsonRpcWebSocketClient extends WebSocketCommandClient {
572
+ createCommandFrame(id, method, params) {
573
+ return { id, jsonrpc: "2.0", method, params };
574
+ }
575
+ }
557
576
  function flattenCdpFrameTree(node, out = []) {
558
577
  if (!node) {
559
578
  return out;
@@ -996,7 +1015,7 @@ class CdpPoolBrowserClient {
996
1015
  ...(this.allowedHosts.length > 0 ? { allowedHosts: this.allowedHosts } : {}),
997
1016
  ...(options?.isolatedContext ? { isolationMode: "browserContext" } : {}),
998
1017
  }));
999
- const pageClient = new JsonRpcWebSocketClient(acquireResult.wsEndpoint);
1018
+ const pageClient = new CdpWebSocketClient(acquireResult.wsEndpoint);
1000
1019
  const page = new CdpPoolBrowserPage(acquireResult.pageId, acquireResult.browserContextId, pageClient, async (request) => {
1001
1020
  await this.poolClient.send("release", request);
1002
1021
  });
@@ -0,0 +1,29 @@
1
+ import type { OcrCaptchaCandidate, OcrCaptchaOptions, OcrContext, ProviderOcrConfig } from "../types.js";
2
+ export { CLOUDFLARE_ACCOUNT_ID_ENV } from "./stt.js";
3
+ export declare const APIFUSE__OCR__BACKEND_ENV = "APIFUSE__OCR__BACKEND";
4
+ export declare const APIFUSE__OCR__MODEL_ENV = "APIFUSE__OCR__MODEL";
5
+ export declare const APIFUSE__OCR__CLOUDFLARE_API_TOKEN_ENV = "APIFUSE__OCR__CLOUDFLARE_API_TOKEN";
6
+ export declare const APIFUSE__OCR__BASE_URL_ENV = "APIFUSE__OCR__BASE_URL";
7
+ export declare const APIFUSE__OCR__API_KEY_ENV = "APIFUSE__OCR__API_KEY";
8
+ export declare const CLOUDFLARE_WORKERS_AI_OCR_BACKEND = "cloudflare-workers-ai";
9
+ export declare const OPENAI_COMPATIBLE_OCR_BACKEND = "openai-compatible";
10
+ export declare const DEFAULT_CLOUDFLARE_WORKERS_AI_OCR_MODEL = "@cf/google/gemma-4-26b-a4b-it";
11
+ export declare const DEFAULT_OCR_TIMEOUT_MS = 30000;
12
+ type EnvLike = Record<string, string | undefined>;
13
+ type CloudflareWorkersAiOcrClientOptions = {
14
+ accountId: string;
15
+ apiToken: string;
16
+ model?: string;
17
+ fetch?: typeof fetch;
18
+ };
19
+ type OpenAiCompatibleOcrClientOptions = {
20
+ baseUrl: string;
21
+ apiKey?: string;
22
+ model: string;
23
+ fetch?: typeof fetch;
24
+ };
25
+ export declare function createUnsupportedOcrClient(reason?: string): OcrContext;
26
+ export declare function createOcrClientFromEnv(config: ProviderOcrConfig | undefined, env?: EnvLike): OcrContext;
27
+ export declare function createCloudflareWorkersAiOcrClient(options: CloudflareWorkersAiOcrClientOptions): OcrContext;
28
+ export declare function createOpenAiCompatibleOcrClient(options: OpenAiCompatibleOcrClientOptions): OcrContext;
29
+ export declare function extractCaptchaCandidates(modelText: string, options?: OcrCaptchaOptions): readonly OcrCaptchaCandidate[];