@siglume/direct-request-payment 0.4.4 → 0.4.5

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export const DEFAULT_SIGLUME_API_BASE = \"https://siglume.com/v1\";\nexport const DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME = \"siglume-external-402-v1\";\n// Recurring (subscription / scheduled autopay) approval uses a DISTINCT scheme\n// with cadence bound into the HMAC, so a one-time checkout challenge can never\n// be replayed as a recurring authorization and vice versa.\nexport const DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME = \"siglume-external-402-recurring-v1\";\nexport const DIRECT_REQUEST_PAYMENT_MODE = \"external_402\";\nexport const DIRECT_REQUEST_PAYMENT_RECEIPT_KIND = \"sdrp_direct_payment\";\nexport const DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND = \"sdrp_direct_payment_allowance\";\nexport const DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE = \"sdrp_direct_payment_requirement\";\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\nexport const DIRECT_REQUEST_PAYMENT_SDK_VERSION = \"0.4.4\";\nconst DIRECT_REQUEST_PAYMENT_CONFIRMED_WEBHOOK_MODES = new Set([DIRECT_REQUEST_PAYMENT_MODE, \"metered_settlement_batch\"]);\n\nexport type DirectRequestPaymentCurrency = \"JPY\" | \"USD\";\nexport type DirectRequestPaymentToken = \"JPYC\" | \"USDC\";\nexport type DirectRequestPaymentMeteredPlanType = \"micro\" | \"nano\";\nexport type DirectRequestPaymentMinorAmount = string | number;\n\nexport interface DirectRequestPaymentBuyerMeteredQuery {\n plan_type?: DirectRequestPaymentMeteredPlanType | string;\n token_symbol?: DirectRequestPaymentToken | string;\n}\n\nexport interface DirectRequestPaymentMeteredListQuery extends DirectRequestPaymentBuyerMeteredQuery {\n status?: string;\n limit?: number;\n}\n\nexport interface DirectRequestPaymentProviderMeteredQuery extends DirectRequestPaymentBuyerMeteredQuery {\n listing_id?: string;\n capability_key?: string;\n}\n\nexport interface DirectRequestPaymentProviderMeteredListQuery extends DirectRequestPaymentProviderMeteredQuery {\n status?: string;\n limit?: number;\n}\n\nexport interface DirectRequestPaymentListResponse<T> {\n items: T[];\n next_cursor?: string | null;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentBuyerUsageEvent {\n metered_usage_id: string;\n created_at?: string | null;\n plan_type: string;\n settlement_cadence: string;\n product_listing_id?: string | null;\n listing_id?: string | null;\n capability_key?: string | null;\n operation_key?: string | null;\n currency: string;\n token_symbol: string;\n provider_usage_amount_minor: DirectRequestPaymentMinorAmount;\n protocol_fee_minor: DirectRequestPaymentMinorAmount;\n gross_buyer_debit_minor: DirectRequestPaymentMinorAmount;\n status: string;\n period_start?: string | null;\n period_end?: string | null;\n settlement_batch_id?: string | null;\n expected_scheduled_debit_at?: string | null;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentProviderUsageEvent {\n metered_usage_id: string;\n created_at?: string | null;\n plan_type: string;\n settlement_cadence: string;\n product_listing_id?: string | null;\n listing_id?: string | null;\n capability_key?: string | null;\n operation_key?: string | null;\n currency: string;\n token_symbol: string;\n provider_receivable_minor: DirectRequestPaymentMinorAmount;\n protocol_fee_minor: DirectRequestPaymentMinorAmount;\n gross_buyer_debit_minor: DirectRequestPaymentMinorAmount;\n status: string;\n period_start?: string | null;\n period_end?: string | null;\n expected_scheduled_debit_at?: string | null;\n settlement_batch_id?: string | null;\n buyer_period_ref?: string | null;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentSettlementBatch {\n settlement_batch_id: string;\n plan_type: string;\n settlement_cadence: string;\n status: string;\n notice_status?: string | null;\n period_start?: string | null;\n period_end?: string | null;\n close_at?: string | null;\n expected_scheduled_debit_at?: string | null;\n scheduled_debit_at?: string | null;\n not_before_attempt_at?: string | null;\n execution_status?: string | null;\n latest_execution_attempt_status?: string | null;\n chain_receipt_id?: string | null;\n usage_event_digest?: string | null;\n protocol_fee_minor?: DirectRequestPaymentMinorAmount;\n gross_buyer_debit_minor?: DirectRequestPaymentMinorAmount;\n rounding_delta_minor?: DirectRequestPaymentMinorAmount;\n buyer_debit_minor?: DirectRequestPaymentMinorAmount;\n provider_usage_amount_minor?: DirectRequestPaymentMinorAmount;\n provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n settled_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n unsettled_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n past_due_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n buyer_period_ref?: string | null;\n failure_reason_code?: string | null;\n failure_reason_label?: string | null;\n failure_reason_help?: string | null;\n support_reference?: string | null;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentBuyerMeteredSummary {\n role: \"buyer\";\n open_periods: Array<Record<string, unknown>>;\n settlement_batches: DirectRequestPaymentSettlementBatch[];\n past_due_blocks: Array<Record<string, unknown>>;\n balance_sufficiency?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentProviderMeteredSummary {\n role: \"provider\";\n timezone?: string | null;\n filters?: Record<string, unknown>;\n open_periods: Array<Record<string, unknown>>;\n periods: DirectRequestPaymentSettlementBatch[];\n totals: Record<string, DirectRequestPaymentMinorAmount>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface ParsedDirectRequestPaymentChallenge {\n scheme: string;\n nonce: string;\n signature: string;\n}\n\n/** \"monthly\" authorizes a Siglume-swept subscription; \"daily\" authorizes\n * merchant-triggered scheduled autopay. It is an approval tag, not a\n * run-count limiter. */\nexport type DirectRequestPaymentRecurringCadence = \"monthly\" | \"daily\";\n\nexport interface DirectRequestPaymentRecurringChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentRecurringChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n cadence: DirectRequestPaymentRecurringCadence;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface Web3TransactionRequest {\n network?: string;\n chain_id?: number;\n from?: string;\n to?: string;\n data?: string;\n value?: string | number;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectPaymentRequirement {\n direct_payment_requirement_id: string;\n requirement_id: string;\n id: string;\n mode: string;\n merchant?: string | null;\n challenge_hash?: string | null;\n buyer_user_id: string;\n agent_id?: string | null;\n product_listing_id: string;\n listing_id: string;\n access_grant_id?: string | null;\n capability_key: string;\n requirement_hash: string;\n request_hash: string;\n request_hash_v2?: string | null;\n siglume_signature: string;\n token_symbol: string;\n currency: string;\n amount_minor: number;\n fee_bps: number;\n pricing_band?: \"standard\" | DirectRequestPaymentMeteredPlanType | string | null;\n settlement_cadence?: \"per_payment\" | \"weekly\" | \"monthly\" | string | null;\n finality?: string | null;\n protocol_fee_minor?: DirectRequestPaymentMinorAmount | null;\n settlement_status?: string | null;\n status: string;\n expires_at?: string | null;\n confirmed_at?: string | null;\n spent_at?: string | null;\n chain_receipt_id?: string | null;\n transaction_request: Web3TransactionRequest;\n approve_transaction_request?: Web3TransactionRequest | null;\n buyer_confirmation?: string | null;\n non_custodial: boolean;\n metadata_jsonb?: Record<string, unknown>;\n created_at?: string | null;\n updated_at?: string | null;\n}\n\nexport interface DirectPaymentRequirementCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n token_symbol?: DirectRequestPaymentToken | string;\n allowance_amount_minor?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectPaymentVerifyInput {\n receipt_id?: string | null;\n chain_receipt_id?: string | null;\n await_finality?: boolean;\n await_required_status?: string | null;\n await_timeout_seconds?: number;\n await_poll_seconds?: number;\n}\n\nexport interface Web3PreparedTransactionExecutePayload {\n transaction_request: Web3TransactionRequest;\n receipt_kind: string;\n reference_type: typeof DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE;\n reference_id: string;\n metadata?: Record<string, unknown>;\n await_finality?: boolean;\n}\n\nexport interface Web3PreparedTransactionExecuteResult {\n receipt?: Record<string, unknown>;\n finalization?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentClientOptions {\n auth_token?: string;\n base_url?: string;\n fetch?: typeof fetch;\n timeout_ms?: number;\n user_agent?: string;\n}\n\nexport type DirectRequestPaymentBillingPlan = \"launch\" | \"free\" | \"starter\" | \"growth\" | \"pro\";\n\nexport interface DirectRequestPaymentMerchantAccount {\n merchant_account_id: string;\n merchant: string;\n merchant_user_id: string;\n user_wallet_id?: string | null;\n billing_mandate_id?: string | null;\n display_name?: string | null;\n status?: string | null;\n billing_status?: string | null;\n billing_plan?: string | null;\n billing_currency?: string | null;\n token_symbol?: string | null;\n monthly_fee_minor?: number | null;\n settlement_fee_bps?: number | null;\n settlement_fee_min_minor?: number | null;\n included_monthly_payments?: number | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantSetupInput {\n merchant: string;\n display_name?: string;\n billing_plan?: DirectRequestPaymentBillingPlan | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n allowed_currencies?: Record<string, string> | Array<DirectRequestPaymentCurrency | string>;\n webhook_callback_url?: string;\n billing_mandate_cap_minor?: number;\n max_amount_minor?: number;\n // Hosted Checkout return-URL origin allowlist (open-redirect defense). Each\n // entry is an absolute origin such as \"https://shop.example.com\". The origin\n // of webhook_callback_url is auto-allowed in addition to these.\n checkout_allowed_origins?: string[];\n}\n\nexport interface HostedCheckoutSessionCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n success_url: string;\n cancel_url: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface HostedCheckoutSessionCreateResult {\n checkout_url: string;\n session_id: string;\n challenge_hash: string;\n status?: string;\n expires_at?: string | null;\n}\n\nexport interface HostedCheckoutSession {\n session_id: string;\n merchant: string;\n currency: string;\n token_symbol: string;\n amount_minor: number;\n status: string;\n challenge_hash: string;\n requirement_id?: string | null;\n success_url: string;\n cancel_url: string;\n expires_at?: string | null;\n authenticated_at?: string | null;\n paid_at?: string | null;\n cancelled_at?: string | null;\n created_at?: string | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantBillingMandateInput {\n currency?: DirectRequestPaymentCurrency | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantResponse {\n merchant_account: DirectRequestPaymentMerchantAccount;\n challenge_secret?: string | null;\n challenge_secret_created?: boolean;\n created?: boolean | null;\n listing_id?: string | null;\n mandate?: Record<string, unknown> | null;\n next_steps?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscriptionInput {\n callback_url: string;\n description?: string;\n event_types?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscription {\n webhook_subscription_id?: string;\n subscription_id?: string;\n id?: string;\n callback_url?: string;\n signing_secret?: string;\n status?: string;\n event_types?: string[];\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupInput extends DirectRequestPaymentMerchantSetupInput {\n create_webhook_subscription?: boolean;\n prepare_billing_mandate?: boolean;\n webhook_event_types?: string[];\n webhook_description?: string;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupResult {\n merchant: DirectRequestPaymentMerchantResponse;\n billing_mandate?: DirectRequestPaymentMerchantResponse | null;\n webhook_subscription?: DirectRequestPaymentWebhookSubscription | null;\n env: Record<string, string>;\n}\n\nexport interface SiglumeEnvelopeMeta {\n request_id?: string | null;\n trace_id?: string | null;\n [key: string]: unknown;\n}\n\nexport interface WebhookSignatureVerification {\n timestamp: number;\n signature: string;\n}\n\nexport interface DirectRequestPaymentWebhookEvent {\n id: string;\n type: \"direct_payment.confirmed\" | string;\n api_version: string;\n occurred_at: string;\n data: {\n mode?: string;\n merchant?: string;\n direct_payment_requirement_id?: string;\n requirement_id?: string;\n challenge_hash?: string;\n amount_minor?: number;\n currency?: string;\n token_symbol?: string;\n status?: string;\n request_hash_v2?: string | null;\n pricing_band?: \"standard\" | DirectRequestPaymentMeteredPlanType | string | null;\n settlement_cadence?: \"per_payment\" | \"weekly\" | \"monthly\" | string | null;\n finality?: string | null;\n protocol_fee_minor?: DirectRequestPaymentMinorAmount | null;\n settlement_status?: string | null;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport class SiglumeDirectRequestPaymentError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeDirectRequestPaymentError\";\n }\n}\n\nexport class SiglumeApiError extends SiglumeDirectRequestPaymentError {\n readonly status: number;\n readonly code: string;\n readonly data: unknown;\n\n constructor(message: string, options: { status: number; code?: string; data?: unknown }) {\n super(message);\n this.name = \"SiglumeApiError\";\n this.status = options.status;\n this.code = options.code ?? \"SIGLUME_API_ERROR\";\n this.data = options.data;\n }\n}\n\nexport class HostedCheckoutNotAvailableError extends SiglumeApiError {\n constructor(message = \"Hosted Checkout is not enabled for this account yet (server rollout in progress).\") {\n super(message, { status: 409, code: \"HOSTED_CHECKOUT_NOT_ENABLED\" });\n this.name = \"HostedCheckoutNotAvailableError\";\n }\n}\n\nexport class SiglumeWebhookSignatureError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookSignatureError\";\n }\n}\n\nexport class SiglumeWebhookPayloadError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookPayloadError\";\n }\n}\n\nexport class DirectRequestPaymentClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A buyer Siglume bearer token is required for Direct Request Payment API calls. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? `@siglume/direct-request-payment/${DIRECT_REQUEST_PAYMENT_SDK_VERSION}`;\n this.fetch_impl = fetchImpl;\n }\n\n async createPaymentRequirement(input: DirectPaymentRequirementCreateInput): Promise<DirectPaymentRequirement> {\n const payload: Record<string, unknown> = {\n mode: DIRECT_REQUEST_PAYMENT_MODE,\n merchant: normalizeMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n challenge: requireNonEmpty(input.challenge, \"challenge\"),\n };\n if (input.token_symbol !== undefined) {\n payload.token_symbol = normalizeToken(input.token_symbol);\n }\n if (input.allowance_amount_minor !== undefined) {\n payload.allowance_amount_minor = positiveInteger(input.allowance_amount_minor, \"allowance_amount_minor\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectPaymentRequirement>(\"POST\", \"/sdrp/direct-payments/requirements\", payload);\n }\n\n async getPaymentRequirement(requirement_id: string): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"GET\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}`,\n );\n }\n\n async verifyPaymentRequirement(\n requirement_id: string,\n input: DirectPaymentVerifyInput,\n ): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"POST\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}/verify`,\n input,\n );\n }\n\n async executePreparedTransaction(\n payload: Web3PreparedTransactionExecutePayload,\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.request<Web3PreparedTransactionExecuteResult>(\n \"POST\",\n \"/market/web3/transactions/execute-prepared\",\n payload,\n );\n }\n\n async executePaymentTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildPaymentExecutionPayload(requirement, options));\n }\n\n async executeAllowanceTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildAllowanceExecutionPayload(requirement, options));\n }\n\n async getBuyerMeteredSummary(\n input: DirectRequestPaymentBuyerMeteredQuery = {},\n ): Promise<DirectRequestPaymentBuyerMeteredSummary> {\n return this.request<DirectRequestPaymentBuyerMeteredSummary>(\n \"GET\",\n meteredQueryPath(\"/sdrp/metered/my-summary\", input),\n );\n }\n\n async listBuyerUsageEvents(\n input: DirectRequestPaymentMeteredListQuery = {},\n ): Promise<DirectRequestPaymentListResponse<DirectRequestPaymentBuyerUsageEvent>> {\n return this.request<DirectRequestPaymentListResponse<DirectRequestPaymentBuyerUsageEvent>>(\n \"GET\",\n meteredQueryPath(\"/sdrp/metered/my-usage-events\", input),\n );\n }\n\n async listBuyerSettlementBatches(\n input: DirectRequestPaymentMeteredListQuery = {},\n ): Promise<DirectRequestPaymentListResponse<DirectRequestPaymentSettlementBatch>> {\n return this.request<DirectRequestPaymentListResponse<DirectRequestPaymentSettlementBatch>>(\n \"GET\",\n meteredQueryPath(\"/sdrp/metered/my-settlement-batches\", input),\n );\n }\n\n async getProviderMeteredSummary(\n input: DirectRequestPaymentProviderMeteredQuery = {},\n ): Promise<DirectRequestPaymentProviderMeteredSummary> {\n return this.request<DirectRequestPaymentProviderMeteredSummary>(\n \"GET\",\n meteredQueryPath(\"/sdrp/metered/provider/summary\", input),\n );\n }\n\n async listProviderUsageEvents(\n input: DirectRequestPaymentProviderMeteredListQuery = {},\n ): Promise<DirectRequestPaymentListResponse<DirectRequestPaymentProviderUsageEvent>> {\n return this.request<DirectRequestPaymentListResponse<DirectRequestPaymentProviderUsageEvent>>(\n \"GET\",\n meteredQueryPath(\"/sdrp/metered/provider/usage-events\", input),\n );\n }\n\n async listProviderSettlementBatches(\n input: DirectRequestPaymentProviderMeteredListQuery = {},\n ): Promise<DirectRequestPaymentListResponse<DirectRequestPaymentSettlementBatch>> {\n return this.request<DirectRequestPaymentListResponse<DirectRequestPaymentSettlementBatch>>(\n \"GET\",\n meteredQueryPath(\"/sdrp/metered/provider/settlement-batches\", input),\n );\n }\n\n async getProviderSettlementBatch(\n settlement_batch_id: string,\n input: Pick<DirectRequestPaymentProviderMeteredQuery, \"listing_id\" | \"capability_key\"> = {},\n ): Promise<DirectRequestPaymentSettlementBatch> {\n return this.request<DirectRequestPaymentSettlementBatch>(\n \"GET\",\n meteredQueryPath(\n `/sdrp/metered/provider/settlement-batches/${encodeURIComponent(\n requireNonEmpty(settlement_batch_id, \"settlement_batch_id\"),\n )}`,\n input,\n ),\n );\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport class DirectRequestPaymentMerchantClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_MERCHANT_AUTH_TOKEN\") ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A merchant Siglume bearer token is required for Direct Request Payment merchant setup. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? `@siglume/direct-request-payment/${DIRECT_REQUEST_PAYMENT_SDK_VERSION}`;\n this.fetch_impl = fetchImpl;\n }\n\n async setupMerchant(input: DirectRequestPaymentMerchantSetupInput): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n billing_plan: normalizeBillingPlan(input.billing_plan ?? \"launch\"),\n billing_currency: normalizeCurrency(input.billing_currency ?? \"JPY\"),\n };\n if (input.display_name !== undefined) {\n payload.display_name = requireNonEmpty(input.display_name, \"display_name\");\n }\n if (input.allowed_currencies !== undefined) {\n payload.allowed_currencies = normalizeAllowedCurrencies(input.allowed_currencies);\n }\n if (input.webhook_callback_url !== undefined) {\n payload.webhook_callback_url = requireNonEmpty(input.webhook_callback_url, \"webhook_callback_url\");\n }\n if (input.billing_mandate_cap_minor !== undefined) {\n payload.billing_mandate_cap_minor = positiveInteger(input.billing_mandate_cap_minor, \"billing_mandate_cap_minor\");\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n if (input.checkout_allowed_origins !== undefined) {\n payload.checkout_allowed_origins = normalizeOriginList(input.checkout_allowed_origins);\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\"POST\", \"/sdrp/direct-payments/merchants\", payload);\n }\n\n /**\n * Create a Hosted Checkout session (Stripe-Checkout-equivalent for human web\n * shoppers). Siglume authors the challenge server-side, persists a single-use\n * expiring session, and returns a `checkout_url`. Redirect the shopper there;\n * they log into Siglume, approve, and pay from their own wallet, then return\n * to your `success_url`. Fulfill on the `direct_payment.confirmed` webhook\n * (the source of truth), exactly as with the agent flow.\n *\n * `success_url`/`cancel_url` must be on an origin you registered via\n * `checkout_allowed_origins` (or your `webhook_callback_url` origin).\n */\n async createCheckoutSession(input: HostedCheckoutSessionCreateInput): Promise<HostedCheckoutSessionCreateResult> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n nonce: normalizeChallengeNonce(input.nonce),\n success_url: requireNonEmpty(input.success_url, \"success_url\"),\n cancel_url: requireNonEmpty(input.cancel_url, \"cancel_url\"),\n };\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.requestHostedCheckout<HostedCheckoutSessionCreateResult>(\n \"POST\",\n \"/sdrp/direct-payments/checkout-sessions\",\n payload,\n );\n }\n\n /** Read a Hosted Checkout session's status (open / authenticated / paid / expired / cancelled / failed). */\n async getCheckoutSession(session_id: string): Promise<HostedCheckoutSession> {\n return this.requestHostedCheckout<HostedCheckoutSession>(\n \"GET\",\n `/sdrp/direct-payments/checkout-sessions/${encodeURIComponent(requireNonEmpty(session_id, \"session_id\"))}`,\n );\n }\n\n async getMerchant(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"GET\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}`,\n );\n }\n\n async rotateChallengeSecret(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/challenge-secret/rotate`,\n );\n }\n\n async prepareBillingMandate(\n merchant: string,\n input: DirectRequestPaymentMerchantBillingMandateInput = {},\n ): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {};\n if (input.currency !== undefined) {\n payload.currency = normalizeCurrency(input.currency);\n }\n if (input.billing_currency !== undefined) {\n payload.billing_currency = normalizeCurrency(input.billing_currency);\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/billing-mandate`,\n payload,\n );\n }\n\n async createWebhookSubscription(\n input: DirectRequestPaymentWebhookSubscriptionInput,\n ): Promise<DirectRequestPaymentWebhookSubscription> {\n const payload: Record<string, unknown> = {\n callback_url: requireNonEmpty(input.callback_url, \"callback_url\"),\n event_types: input.event_types?.length\n ? input.event_types.map((eventType) => requireNonEmpty(eventType, \"event_type\"))\n : [\"direct_payment.confirmed\", \"direct_payment.spent\"],\n };\n if (input.description !== undefined) {\n payload.description = requireNonEmpty(input.description, \"description\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectRequestPaymentWebhookSubscription>(\"POST\", \"/market/webhooks/subscriptions\", payload);\n }\n\n async setupCheckout(input: DirectRequestPaymentCheckoutSetupInput): Promise<DirectRequestPaymentCheckoutSetupResult> {\n const merchant = await this.setupMerchant(input);\n const merchantKey = merchant.merchant_account.merchant;\n const billing_mandate = input.prepare_billing_mandate === false\n ? null\n : await this.prepareBillingMandate(merchantKey, {\n billing_currency: merchant.merchant_account.billing_currency ?? input.billing_currency ?? \"JPY\",\n max_amount_minor: input.max_amount_minor ?? input.billing_mandate_cap_minor,\n });\n const shouldCreateWebhook = input.create_webhook_subscription ?? Boolean(input.webhook_callback_url);\n const webhook_subscription = shouldCreateWebhook && input.webhook_callback_url\n ? await this.createWebhookSubscription({\n callback_url: input.webhook_callback_url,\n description: input.webhook_description ?? `${merchantKey} Direct Request Payment`,\n event_types: input.webhook_event_types,\n metadata: { merchant: merchantKey, sdk: \"@siglume/direct-request-payment\" },\n })\n : null;\n const env: Record<string, string> = {\n SIGLUME_DIRECT_PAYMENT_MERCHANT: merchantKey,\n };\n if (merchant.challenge_secret) {\n env.SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET = merchant.challenge_secret;\n }\n const webhookSecret = stringOrNull(webhook_subscription?.signing_secret);\n if (webhookSecret) {\n env.SIGLUME_WEBHOOK_SECRET = webhookSecret;\n }\n return { merchant, billing_mandate, webhook_subscription, env };\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n private async requestHostedCheckout<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n try {\n return await this.request<T>(method, path, json_body);\n } catch (error) {\n if (isHostedCheckoutUnavailable(error)) {\n throw new HostedCheckoutNotAvailableError();\n }\n throw error;\n }\n }\n}\n\nexport async function createDirectRequestPaymentChallenge(\n input: DirectRequestPaymentChallengeInput,\n): Promise<DirectRequestPaymentChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = normalizeChallengeNonce(input.nonce);\n const material = `${merchant}:${amount}:${currency}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport function parseDirectRequestPaymentChallenge(challenge: string): ParsedDirectRequestPaymentChallenge {\n const parts = requireNonEmpty(challenge, \"challenge\").split(\":\");\n if (parts.length !== 3) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge must be scheme:nonce:signature.\");\n }\n const [scheme, nonce, signature] = parts;\n if (!scheme || !nonce || !signature) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge is incomplete.\");\n }\n return { scheme, nonce, signature };\n}\n\n/** Merchant-side, ONE-TIME approval of a recurring authorization: amount +\n * currency + cadence are bound into the HMAC. Recurring charges afterwards\n * are deliberately challenge-free; the recurring authorization and the\n * buyer's mandate/budget caps are the per-charge integrity checks. Cadence\n * \"monthly\" = subscription, \"daily\" = scheduled autopay approval tag. */\nexport async function createDirectRequestPaymentRecurringChallenge(\n input: DirectRequestPaymentRecurringChallengeInput,\n): Promise<DirectRequestPaymentRecurringChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentRecurringChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentRecurringChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = normalizeChallengeNonce(input.nonce);\n // MUST stay byte-identical to the server's\n // _external_402_recurring_challenge_signature — both sides change together.\n const material = `${merchant}:${amount}:${currency}:${cadence}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport async function verifyDirectRequestPaymentRecurringChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentRecurringChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n cadence: input.cadence,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function verifyDirectRequestPaymentChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function directRequestPaymentChallengeHash(challenge: string): Promise<string> {\n return sha256Prefixed(requireNonEmpty(challenge, \"challenge\"));\n}\n\nexport async function directRequestPaymentRequestHash(input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n}): Promise<string> {\n const material = `${normalizeMerchant(input.merchant)}${positiveInteger(input.amount_minor, \"amount_minor\")}${normalizeCurrency(input.currency)}${requireNonEmpty(input.challenge, \"challenge\")}`;\n return sha256Prefixed(material);\n}\n\nexport async function directRequestPaymentRequestHashV2(input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n}): Promise<string> {\n const material = JSON.stringify({\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n challenge: requireNonEmpty(input.challenge, \"challenge\"),\n currency: normalizeCurrency(input.currency),\n merchant: normalizeMerchant(input.merchant),\n version: 2,\n });\n return sha256Prefixed(material);\n}\n\nexport function buildPaymentExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n return buildPreparedTransactionExecutionPayload(requirement, requirement.transaction_request, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildAllowanceExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n const approveRequest = requirement.approve_transaction_request;\n if (!approveRequest || Object.keys(approveRequest).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"This payment requirement does not include an allowance approval transaction.\");\n }\n return buildPreparedTransactionExecutionPayload(requirement, approveRequest, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildPreparedTransactionExecutionPayload(\n requirement: DirectPaymentRequirement,\n transaction_request: Web3TransactionRequest,\n options: {\n receipt_kind: string;\n await_finality?: boolean;\n metadata?: Record<string, unknown>;\n },\n): Web3PreparedTransactionExecutePayload {\n const metadata = {\n ...(isRecord(transaction_request.metadata_jsonb) ? transaction_request.metadata_jsonb : {}),\n ...(options.metadata ?? {}),\n };\n return {\n transaction_request,\n receipt_kind: requireNonEmpty(options.receipt_kind, \"receipt_kind\"),\n reference_type: DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE,\n reference_id: requirement.requirement_id,\n metadata,\n await_finality: Boolean(options.await_finality),\n };\n}\n\nexport async function computeWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp: number },\n): Promise<string> {\n if (!signing_secret) {\n throw new SiglumeWebhookSignatureError(\"SIGLUME webhook signing secret is required.\");\n }\n const timestamp = Math.trunc(options.timestamp);\n const bytes = bodyBytes(body);\n const prefix = new TextEncoder().encode(`${timestamp}.`);\n const payload = new Uint8Array(prefix.length + bytes.length);\n payload.set(prefix, 0);\n payload.set(bytes, prefix.length);\n return hmacSha256Hex(signing_secret, payload);\n}\n\nexport async function buildWebhookSignatureHeader(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp?: number } = {},\n): Promise<string> {\n const timestamp = Math.trunc(options.timestamp ?? Date.now() / 1000);\n const signature = await computeWebhookSignature(signing_secret, body, { timestamp });\n return `t=${timestamp},v1=${signature}`;\n}\n\nexport async function verifyWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<WebhookSignatureVerification> {\n const { timestamp, signature } = parseSignatureHeader(signature_header);\n const toleranceSeconds = Math.max(1, Math.trunc(options.tolerance_seconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS));\n const nowSeconds = Math.trunc(options.now ?? Date.now() / 1000);\n if (Math.abs(nowSeconds - timestamp) > toleranceSeconds) {\n throw new SiglumeWebhookSignatureError(\"Webhook timestamp is outside the allowed tolerance window.\");\n }\n const expected = await computeWebhookSignature(signing_secret, body, { timestamp });\n if (!(await timingSafeEqualHex(expected, signature))) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature did not match.\");\n }\n return { timestamp, signature };\n}\n\nexport function parseDirectRequestPaymentWebhookEvent(payload: unknown): DirectRequestPaymentWebhookEvent {\n const event = requireRecord(payload, \"webhook event\");\n const data = requireRecord(event.data, \"webhook event data\");\n const parsed = {\n ...event,\n id: requireNonEmpty(stringOrNull(event.id) ?? \"\", \"webhook event id\"),\n type: requireNonEmpty(stringOrNull(event.type) ?? \"\", \"webhook event type\"),\n api_version: requireNonEmpty(stringOrNull(event.api_version) ?? \"\", \"webhook api_version\"),\n occurred_at: requireNonEmpty(stringOrNull(event.occurred_at) ?? \"\", \"webhook occurred_at\"),\n data: { ...data },\n } as DirectRequestPaymentWebhookEvent;\n if (\n parsed.type === \"direct_payment.confirmed\" &&\n !DIRECT_REQUEST_PAYMENT_CONFIRMED_WEBHOOK_MODES.has(String(parsed.data.mode ?? \"\"))\n ) {\n throw new SiglumeWebhookPayloadError(\n \"direct_payment.confirmed webhook must carry a supported Direct Request Payment mode.\",\n );\n }\n return parsed;\n}\n\nexport async function verifyDirectRequestPaymentWebhook(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<{ event: DirectRequestPaymentWebhookEvent; verification: WebhookSignatureVerification }> {\n const verification = await verifyWebhookSignature(signing_secret, body, signature_header, options);\n const text = new TextDecoder().decode(bodyBytes(body));\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new SiglumeWebhookPayloadError(\"Webhook body must contain valid JSON.\");\n }\n return { event: parseDirectRequestPaymentWebhookEvent(parsed), verification };\n}\n\nexport const createExternal402Challenge = createDirectRequestPaymentChallenge;\nexport const verifyExternal402Challenge = verifyDirectRequestPaymentChallenge;\nexport const createExternal402RecurringChallenge = createDirectRequestPaymentRecurringChallenge;\nexport const verifyExternal402RecurringChallenge = verifyDirectRequestPaymentRecurringChallenge;\n\nfunction normalizeMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9._-]{0,95}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be a lowercase key using letters, numbers, dot, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeSelfServiceMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9_-]{2,63}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be 3-64 chars using lowercase letters, numbers, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeBillingPlan(value: string): DirectRequestPaymentBillingPlan {\n const plan = requireNonEmpty(value, \"billing_plan\").toLowerCase();\n if (plan === \"launch\" || plan === \"free\" || plan === \"starter\" || plan === \"growth\" || plan === \"pro\") {\n return plan;\n }\n throw new SiglumeDirectRequestPaymentError(\"billing_plan must be launch, starter, growth, or pro.\");\n}\n\nfunction normalizeCurrency(value: string): DirectRequestPaymentCurrency {\n const currency = requireNonEmpty(value, \"currency\").toUpperCase();\n if (currency !== \"JPY\" && currency !== \"USD\") {\n throw new SiglumeDirectRequestPaymentError(\"currency must be JPY or USD.\");\n }\n return currency;\n}\n\nfunction normalizeToken(value: string): DirectRequestPaymentToken {\n const token = requireNonEmpty(value, \"token_symbol\").toUpperCase();\n if (token !== \"JPYC\" && token !== \"USDC\") {\n throw new SiglumeDirectRequestPaymentError(\"token_symbol must be JPYC or USDC.\");\n }\n return token;\n}\n\nfunction normalizeMeteredPlanType(value: string): DirectRequestPaymentMeteredPlanType {\n const planType = requireNonEmpty(value, \"plan_type\").toLowerCase();\n if (planType === \"micro\" || planType === \"nano\") {\n return planType;\n }\n throw new SiglumeDirectRequestPaymentError(\"plan_type must be micro or nano.\");\n}\n\nfunction normalizeAllowedCurrencies(value: Record<string, string> | Array<DirectRequestPaymentCurrency | string>): Record<string, string> {\n const normalized: Record<string, string> = {};\n if (Array.isArray(value)) {\n for (const item of value) {\n const currency = normalizeCurrency(item);\n normalized[currency] = defaultTokenForCurrency(currency);\n }\n } else if (isRecord(value)) {\n for (const [rawCurrency, rawToken] of Object.entries(value)) {\n normalized[normalizeCurrency(rawCurrency)] = normalizeToken(String(rawToken));\n }\n } else {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must be an array or a currency-to-token object.\");\n }\n if (Object.keys(normalized).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must include at least one currency.\");\n }\n return normalized;\n}\n\nfunction defaultTokenForCurrency(currency: DirectRequestPaymentCurrency): DirectRequestPaymentToken {\n return currency === \"JPY\" ? \"JPYC\" : \"USDC\";\n}\n\nfunction normalizeOriginList(value: string[]): string[] {\n if (!Array.isArray(value)) {\n throw new SiglumeDirectRequestPaymentError(\"checkout_allowed_origins must be an array of origin URLs.\");\n }\n const seen = new Set<string>();\n const origins: string[] = [];\n for (const item of value) {\n let url: URL;\n try {\n url = new URL(requireNonEmpty(String(item), \"checkout_allowed_origins entry\"));\n } catch {\n throw new SiglumeDirectRequestPaymentError(\n \"each checkout_allowed_origins entry must be an absolute origin such as https://shop.example.com.\",\n );\n }\n if (url.username || url.password) {\n throw new SiglumeDirectRequestPaymentError(\"checkout_allowed_origins entries must not include userinfo.\");\n }\n if (!isAllowedCheckoutOriginScheme(url)) {\n throw new SiglumeDirectRequestPaymentError(\n \"checkout_allowed_origins entries must use https, except http is allowed for localhost, 127.0.0.1, or [::1].\",\n );\n }\n const origin = url.origin.toLowerCase();\n if (!seen.has(origin)) {\n seen.add(origin);\n origins.push(origin);\n }\n }\n return origins;\n}\n\nfunction isAllowedCheckoutOriginScheme(url: URL): boolean {\n if (url.protocol === \"https:\") {\n return Boolean(url.hostname);\n }\n if (url.protocol !== \"http:\") {\n return false;\n }\n const hostname = url.hostname.toLowerCase();\n return hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\" || hostname === \"::1\";\n}\n\nfunction meteredQueryPath(\n path: string,\n input: DirectRequestPaymentBuyerMeteredQuery | DirectRequestPaymentMeteredListQuery | DirectRequestPaymentProviderMeteredQuery | DirectRequestPaymentProviderMeteredListQuery,\n): string {\n const params = new URLSearchParams();\n if (input.plan_type !== undefined) {\n params.set(\"plan_type\", normalizeMeteredPlanType(input.plan_type));\n }\n if (input.token_symbol !== undefined) {\n params.set(\"token_symbol\", normalizeToken(input.token_symbol));\n }\n if (\"status\" in input && input.status !== undefined) {\n params.set(\"status\", requireNonEmpty(input.status, \"status\"));\n }\n if (\"listing_id\" in input && input.listing_id !== undefined) {\n params.set(\"listing_id\", requireNonEmpty(input.listing_id, \"listing_id\"));\n }\n if (\"capability_key\" in input && input.capability_key !== undefined) {\n params.set(\"capability_key\", requireNonEmpty(input.capability_key, \"capability_key\"));\n }\n if (\"limit\" in input && input.limit !== undefined) {\n params.set(\"limit\", String(positiveInteger(input.limit, \"limit\")));\n }\n const query = params.toString();\n return query ? `${path}?${query}` : path;\n}\n\nfunction positiveInteger(value: unknown, name: string): number {\n if (typeof value !== \"number\") {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a positive safe integer.`);\n }\n const parsed = value;\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a positive safe integer.`);\n }\n return parsed;\n}\n\nfunction requireNonEmpty(value: string, name: string): string {\n const text = String(value ?? \"\").trim();\n if (!text) {\n throw new SiglumeDirectRequestPaymentError(`${name} is required.`);\n }\n return text;\n}\n\nfunction normalizeChallengeNonce(value: string): string {\n const nonce = requireNonEmpty(value, \"nonce\");\n if (nonce.includes(\":\")) {\n throw new SiglumeDirectRequestPaymentError(\"nonce must not contain ':'.\");\n }\n return nonce;\n}\n\nfunction normalizeRecurringCadence(value: string): DirectRequestPaymentRecurringCadence {\n const cadence = requireNonEmpty(value, \"cadence\").toLowerCase();\n if (cadence !== \"monthly\" && cadence !== \"daily\") {\n throw new SiglumeDirectRequestPaymentError(\n 'cadence must be \"monthly\" (subscription) or \"daily\" (scheduled autopay).',\n );\n }\n return cadence;\n}\n\nfunction cloneJsonObject(value: Record<string, unknown>, name: string): Record<string, unknown> {\n try {\n const cloned = JSON.parse(JSON.stringify(value)) as unknown;\n if (!isRecord(cloned)) {\n throw new Error(\"not an object\");\n }\n return cloned;\n } catch (error) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a JSON-serializable object.`);\n }\n}\n\nfunction parseJson(rawText: string): unknown {\n try {\n return JSON.parse(rawText);\n } catch (error) {\n throw new SiglumeApiError(\"Siglume API returned invalid JSON.\", {\n status: 502,\n code: \"INVALID_JSON_RESPONSE\",\n data: rawText,\n });\n }\n}\n\nfunction stringOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const text = value.trim();\n return text ? text : null;\n}\n\nfunction isHostedCheckoutUnavailable(error: unknown): boolean {\n if (!(error instanceof SiglumeApiError)) {\n return false;\n }\n const code = error.code.toUpperCase();\n if (error.status === 409 && (code === \"HOSTED_CHECKOUT_NOT_ENABLED\" || code === \"FEATURE_DISABLED\")) {\n return true;\n }\n return (\n error.status === 404 &&\n (code === \"HTTP_404\" || code === \"NOT_FOUND\" || code === \"ROUTE_NOT_FOUND\" || code === \"FEATURE_DISABLED\")\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requireRecord(value: unknown, name: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new SiglumeWebhookPayloadError(`${name} must be an object.`);\n }\n return value;\n}\n\nfunction envValue(name: string): string | undefined {\n if (typeof process === \"undefined\") {\n return undefined;\n }\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nfunction bodyBytes(body: Uint8Array | ArrayBuffer | string | Record<string, unknown>): Uint8Array {\n if (body instanceof Uint8Array) {\n return body;\n }\n if (body instanceof ArrayBuffer) {\n return new Uint8Array(body);\n }\n if (typeof body === \"string\") {\n return new TextEncoder().encode(body);\n }\n if (isRecord(body)) {\n return new TextEncoder().encode(JSON.stringify(body));\n }\n throw new SiglumeWebhookPayloadError(\"Webhook body must be raw bytes, a string, or a JSON object.\");\n}\n\nfunction parseSignatureHeader(signatureHeader: string): { timestamp: number; signature: string } {\n let timestamp: number | null = null;\n let signature: string | null = null;\n for (const item of String(signatureHeader ?? \"\").split(\",\")) {\n const [key, value] = item.trim().split(\"=\", 2);\n if (key === \"t\") {\n const parsed = Number.parseInt(value ?? \"\", 10);\n if (!Number.isFinite(parsed)) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature timestamp is invalid.\");\n }\n timestamp = parsed;\n }\n if (key === \"v1\") {\n signature = String(value ?? \"\").trim();\n }\n }\n if (timestamp === null || !signature) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature header is incomplete.\");\n }\n return { timestamp, signature };\n}\n\nasync function randomNonce(): Promise<string> {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(bytes);\n } else if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n bytes.set(crypto.randomBytes(16));\n } else {\n throw new SiglumeDirectRequestPaymentError(\"Crypto random number generation is unavailable in this runtime.\");\n }\n return bytesToHex(bytes);\n}\n\nasync function hmacSha256Hex(secret: string, payload: Uint8Array): Promise<string> {\n if (globalThis.crypto?.subtle) {\n const stablePayload = new Uint8Array(payload.byteLength);\n stablePayload.set(payload);\n const key = await globalThis.crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const digest = await globalThis.crypto.subtle.sign(\"HMAC\", key, stablePayload);\n return bytesToHex(new Uint8Array(digest));\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return crypto.createHmac(\"sha256\", secret).update(Buffer.from(payload)).digest(\"hex\");\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for HMAC-SHA256 in this runtime.\");\n}\n\nasync function sha256Prefixed(material: string): Promise<string> {\n const bytes = new TextEncoder().encode(material);\n if (globalThis.crypto?.subtle) {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return `sha256:${bytesToHex(new Uint8Array(digest))}`;\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return `sha256:${crypto.createHash(\"sha256\").update(Buffer.from(bytes)).digest(\"hex\")}`;\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for SHA-256 in this runtime.\");\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return [...bytes].map((item) => item.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const normalized = String(hex ?? \"\").trim().toLowerCase();\n if (normalized.length % 2 !== 0 || !/^[0-9a-f]*$/.test(normalized)) {\n throw new SiglumeWebhookSignatureError(\"Hex digest is invalid.\");\n }\n const bytes = new Uint8Array(normalized.length / 2);\n for (let index = 0; index < normalized.length; index += 2) {\n bytes[index / 2] = Number.parseInt(normalized.slice(index, index + 2), 16);\n }\n return bytes;\n}\n\nasync function timingSafeEqualHex(left: string, right: string): Promise<boolean> {\n const leftBytes = hexToBytes(left);\n const rightBytes = hexToBytes(right);\n if (leftBytes.length !== rightBytes.length) {\n return false;\n }\n let diff = 0;\n for (let index = 0; index < leftBytes.length; index += 1) {\n diff |= leftBytes[index]! ^ rightBytes[index]!;\n }\n return diff === 0;\n}\n"],"mappings":";AAAO,IAAM,2BAA2B;AACjC,IAAM,0CAA0C;AAIhD,IAAM,oDAAoD;AAC1D,IAAM,8BAA8B;AACpC,IAAM,sCAAsC;AAC5C,IAAM,gDAAgD;AACtD,IAAM,wCAAwC;AAC9C,IAAM,oCAAoC;AAC1C,IAAM,qCAAqC;AAClD,IAAM,iDAAiD,oBAAI,IAAI,CAAC,6BAA6B,0BAA0B,CAAC;AAkbjH,IAAM,mCAAN,cAA+C,MAAM;AAAA,EAC1D,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,kBAAN,cAA8B,iCAAiC;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,SAAiB,SAA4D;AACvF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ;AACtB,SAAK,OAAO,QAAQ,QAAQ;AAC5B,SAAK,OAAO,QAAQ;AAAA,EACtB;AACF;AAEO,IAAM,kCAAN,cAA8C,gBAAgB;AAAA,EACnE,YAAY,UAAU,qFAAqF;AACzG,UAAM,SAAS,EAAE,QAAQ,KAAK,MAAM,8BAA8B,CAAC;AACnE,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,+BAAN,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AAE,KAAK,EAAE;AAC7E;AAEA,SAAS,WAAW,KAAyB;AAC3C,QAAM,aAAa,OAAO,OAAO,EAAE,EAAE,KAAK,EAAE,YAAY;AACxD,MAAI,WAAW,SAAS,MAAM,KAAK,CAAC,cAAc,KAAK,UAAU,GAAG;AAClE,UAAM,IAAI,6BAA6B,wBAAwB;AAAA,EACjE;AACA,QAAM,QAAQ,IAAI,WAAW,WAAW,SAAS,CAAC;AAClD,WAAS,QAAQ,GAAG,QAAQ,WAAW,QAAQ,SAAS,GAAG;AACzD,UAAM,QAAQ,CAAC,IAAI,OAAO,SAAS,WAAW,MAAM,OAAO,QAAQ,CAAC,GAAG,EAAE;AAAA,EAC3E;AACA,SAAO;AACT;AAEA,eAAe,mBAAmB,MAAc,OAAiC;AAC/E,QAAM,YAAY,WAAW,IAAI;AACjC,QAAM,aAAa,WAAW,KAAK;AACnC,MAAI,UAAU,WAAW,WAAW,QAAQ;AAC1C,WAAO;AAAA,EACT;AACA,MAAI,OAAO;AACX,WAAS,QAAQ,GAAG,QAAQ,UAAU,QAAQ,SAAS,GAAG;AACxD,YAAQ,UAAU,KAAK,IAAK,WAAW,KAAK;AAAA,EAC9C;AACA,SAAO,SAAS;AAClB;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export const DEFAULT_SIGLUME_API_BASE = \"https://siglume.com/v1\";\nexport const DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME = \"siglume-external-402-v1\";\n// Recurring (subscription / scheduled autopay) approval uses a DISTINCT scheme\n// with cadence bound into the HMAC, so a one-time checkout challenge can never\n// be replayed as a recurring authorization and vice versa.\nexport const DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME = \"siglume-external-402-recurring-v1\";\nexport const DIRECT_REQUEST_PAYMENT_MODE = \"external_402\";\nexport const DIRECT_REQUEST_PAYMENT_RECEIPT_KIND = \"sdrp_direct_payment\";\nexport const DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND = \"sdrp_direct_payment_allowance\";\nexport const DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE = \"sdrp_direct_payment_requirement\";\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\nexport const DIRECT_REQUEST_PAYMENT_SDK_VERSION = \"0.4.5\";\nconst DIRECT_REQUEST_PAYMENT_CONFIRMED_WEBHOOK_MODES = new Set([DIRECT_REQUEST_PAYMENT_MODE, \"metered_settlement_batch\"]);\n\nexport type DirectRequestPaymentCurrency = \"JPY\" | \"USD\";\nexport type DirectRequestPaymentToken = \"JPYC\" | \"USDC\";\nexport type DirectRequestPaymentMeteredPlanType = \"micro\" | \"nano\";\nexport type DirectRequestPaymentMinorAmount = string;\n\nexport interface DirectRequestPaymentBuyerMeteredQuery {\n plan_type?: DirectRequestPaymentMeteredPlanType | string;\n token_symbol?: DirectRequestPaymentToken | string;\n}\n\nexport interface DirectRequestPaymentMeteredListQuery extends DirectRequestPaymentBuyerMeteredQuery {\n status?: string;\n cursor?: string;\n limit?: number;\n}\n\nexport interface DirectRequestPaymentProviderMeteredQuery extends DirectRequestPaymentBuyerMeteredQuery {\n listing_id?: string;\n capability_key?: string;\n}\n\nexport interface DirectRequestPaymentProviderMeteredListQuery extends DirectRequestPaymentProviderMeteredQuery {\n status?: string;\n cursor?: string;\n limit?: number;\n}\n\nexport interface DirectRequestPaymentListResponse<T> {\n items: T[];\n next_cursor?: string | null;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentBuyerUsageEvent {\n metered_usage_id: string;\n created_at?: string | null;\n plan_type: string;\n settlement_cadence: string;\n product_listing_id?: string | null;\n listing_id?: string | null;\n capability_key?: string | null;\n operation_key?: string | null;\n currency: string;\n token_symbol: string;\n provider_usage_amount_minor: DirectRequestPaymentMinorAmount;\n protocol_fee_minor: DirectRequestPaymentMinorAmount;\n gross_buyer_debit_minor: DirectRequestPaymentMinorAmount;\n status: string;\n period_start?: string | null;\n period_end?: string | null;\n settlement_batch_id?: string | null;\n expected_scheduled_debit_at?: string | null;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentProviderUsageEvent {\n metered_usage_id: string;\n created_at?: string | null;\n plan_type: string;\n settlement_cadence: string;\n product_listing_id?: string | null;\n listing_id?: string | null;\n capability_key?: string | null;\n operation_key?: string | null;\n currency: string;\n token_symbol: string;\n provider_receivable_minor: DirectRequestPaymentMinorAmount;\n protocol_fee_minor: DirectRequestPaymentMinorAmount;\n gross_buyer_debit_minor: DirectRequestPaymentMinorAmount;\n status: string;\n period_start?: string | null;\n period_end?: string | null;\n expected_scheduled_debit_at?: string | null;\n settlement_batch_id?: string | null;\n buyer_period_ref?: string | null;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentSettlementBatch {\n settlement_batch_id: string;\n plan_type: string;\n settlement_cadence: string;\n status: string;\n notice_status?: string | null;\n period_start?: string | null;\n period_end?: string | null;\n close_at?: string | null;\n expected_scheduled_debit_at?: string | null;\n scheduled_debit_at?: string | null;\n not_before_attempt_at?: string | null;\n execution_status?: string | null;\n latest_execution_attempt_status?: string | null;\n attempt_count?: number | null;\n next_attempt_at?: string | null;\n chain_receipt_id?: string | null;\n usage_event_digest?: string | null;\n protocol_fee_minor?: DirectRequestPaymentMinorAmount;\n gross_buyer_debit_minor?: DirectRequestPaymentMinorAmount;\n rounding_delta_minor?: DirectRequestPaymentMinorAmount;\n buyer_debit_minor?: DirectRequestPaymentMinorAmount;\n provider_usage_amount_minor?: DirectRequestPaymentMinorAmount;\n provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n settled_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n unsettled_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n past_due_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n buyer_period_ref?: string | null;\n failure_reason_code?: string | null;\n failure_reason_label?: string | null;\n failure_reason_help?: string | null;\n support_reference?: string | null;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentBuyerMeteredSummary {\n role: \"buyer\";\n open_periods: Array<Record<string, unknown>>;\n settlement_batches: DirectRequestPaymentSettlementBatch[];\n past_due_blocks: Array<Record<string, unknown>>;\n balance_sufficiency?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentProviderMeteredSummary {\n role: \"provider\";\n timezone?: string | null;\n filters?: Record<string, unknown>;\n open_periods: Array<Record<string, unknown>>;\n periods: DirectRequestPaymentSettlementBatch[];\n totals: Record<string, DirectRequestPaymentMinorAmount>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface ParsedDirectRequestPaymentChallenge {\n scheme: string;\n nonce: string;\n signature: string;\n}\n\n/** \"monthly\" authorizes a Siglume-swept subscription; \"daily\" authorizes\n * merchant-triggered scheduled autopay. It is an approval tag, not a\n * run-count limiter. */\nexport type DirectRequestPaymentRecurringCadence = \"monthly\" | \"daily\";\n\nexport interface DirectRequestPaymentRecurringChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentRecurringChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n cadence: DirectRequestPaymentRecurringCadence;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface Web3TransactionRequest {\n network?: string;\n chain_id?: number;\n from?: string;\n to?: string;\n data?: string;\n value?: string | number;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectPaymentRequirement {\n direct_payment_requirement_id: string;\n requirement_id: string;\n id: string;\n mode: string;\n merchant?: string | null;\n challenge_hash?: string | null;\n buyer_user_id: string;\n agent_id?: string | null;\n product_listing_id: string;\n listing_id: string;\n access_grant_id?: string | null;\n capability_key: string;\n requirement_hash: string;\n request_hash: string;\n request_hash_v2?: string | null;\n siglume_signature: string;\n token_symbol: string;\n currency: string;\n amount_minor: number;\n fee_bps: number;\n pricing_band?: \"standard\" | DirectRequestPaymentMeteredPlanType | string | null;\n settlement_cadence?: \"per_payment\" | \"weekly\" | \"monthly\" | string | null;\n finality?: string | null;\n protocol_fee_minor?: DirectRequestPaymentMinorAmount | null;\n settlement_status?: string | null;\n status: string;\n expires_at?: string | null;\n confirmed_at?: string | null;\n spent_at?: string | null;\n chain_receipt_id?: string | null;\n transaction_request: Web3TransactionRequest;\n approve_transaction_request?: Web3TransactionRequest | null;\n buyer_confirmation?: string | null;\n non_custodial: boolean;\n metadata_jsonb?: Record<string, unknown>;\n created_at?: string | null;\n updated_at?: string | null;\n}\n\nexport interface DirectPaymentRequirementCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n token_symbol?: DirectRequestPaymentToken | string;\n allowance_amount_minor?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectPaymentVerifyInput {\n receipt_id?: string | null;\n chain_receipt_id?: string | null;\n await_finality?: boolean;\n await_required_status?: string | null;\n await_timeout_seconds?: number;\n await_poll_seconds?: number;\n}\n\nexport interface Web3PreparedTransactionExecutePayload {\n transaction_request: Web3TransactionRequest;\n receipt_kind: string;\n reference_type: typeof DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE;\n reference_id: string;\n metadata?: Record<string, unknown>;\n await_finality?: boolean;\n}\n\nexport interface Web3PreparedTransactionExecuteResult {\n receipt?: Record<string, unknown>;\n finalization?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentClientOptions {\n auth_token?: string;\n base_url?: string;\n fetch?: typeof fetch;\n timeout_ms?: number;\n user_agent?: string;\n}\n\nexport type DirectRequestPaymentBillingPlan = \"launch\" | \"free\" | \"starter\" | \"growth\" | \"pro\";\n\nexport interface DirectRequestPaymentMerchantAccount {\n merchant_account_id: string;\n merchant: string;\n merchant_user_id: string;\n user_wallet_id?: string | null;\n billing_mandate_id?: string | null;\n display_name?: string | null;\n status?: string | null;\n billing_status?: string | null;\n billing_plan?: string | null;\n billing_currency?: string | null;\n token_symbol?: string | null;\n monthly_fee_minor?: number | null;\n settlement_fee_bps?: number | null;\n settlement_fee_min_minor?: number | null;\n included_monthly_payments?: number | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantSetupInput {\n merchant: string;\n display_name?: string;\n billing_plan?: DirectRequestPaymentBillingPlan | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n allowed_currencies?: Record<string, string> | Array<DirectRequestPaymentCurrency | string>;\n webhook_callback_url?: string;\n billing_mandate_cap_minor?: number;\n max_amount_minor?: number;\n // Hosted Checkout return-URL origin allowlist (open-redirect defense). Each\n // entry is an absolute origin such as \"https://shop.example.com\". The origin\n // of webhook_callback_url is auto-allowed in addition to these.\n checkout_allowed_origins?: string[];\n}\n\nexport interface HostedCheckoutSessionCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n success_url: string;\n cancel_url: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface HostedCheckoutSessionCreateResult {\n checkout_url: string;\n session_id: string;\n challenge_hash: string;\n status?: string;\n expires_at?: string | null;\n}\n\nexport interface HostedCheckoutSession {\n session_id: string;\n merchant: string;\n currency: string;\n token_symbol: string;\n amount_minor: number;\n status: string;\n challenge_hash: string;\n requirement_id?: string | null;\n success_url: string;\n cancel_url: string;\n expires_at?: string | null;\n authenticated_at?: string | null;\n paid_at?: string | null;\n cancelled_at?: string | null;\n created_at?: string | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantBillingMandateInput {\n currency?: DirectRequestPaymentCurrency | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantResponse {\n merchant_account: DirectRequestPaymentMerchantAccount;\n challenge_secret?: string | null;\n challenge_secret_created?: boolean;\n created?: boolean | null;\n listing_id?: string | null;\n mandate?: Record<string, unknown> | null;\n next_steps?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscriptionInput {\n callback_url: string;\n description?: string;\n event_types?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscription {\n webhook_subscription_id?: string;\n subscription_id?: string;\n id?: string;\n callback_url?: string;\n signing_secret?: string;\n status?: string;\n event_types?: string[];\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupInput extends DirectRequestPaymentMerchantSetupInput {\n create_webhook_subscription?: boolean;\n prepare_billing_mandate?: boolean;\n webhook_event_types?: string[];\n webhook_description?: string;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupResult {\n merchant: DirectRequestPaymentMerchantResponse;\n billing_mandate?: DirectRequestPaymentMerchantResponse | null;\n webhook_subscription?: DirectRequestPaymentWebhookSubscription | null;\n env: Record<string, string>;\n}\n\nexport interface SiglumeEnvelopeMeta {\n request_id?: string | null;\n trace_id?: string | null;\n [key: string]: unknown;\n}\n\nexport interface WebhookSignatureVerification {\n timestamp: number;\n signature: string;\n}\n\nexport interface DirectRequestPaymentWebhookEvent {\n id: string;\n type: \"direct_payment.confirmed\" | string;\n api_version: string;\n occurred_at: string;\n data: {\n mode?: string;\n merchant?: string;\n direct_payment_requirement_id?: string;\n requirement_id?: string;\n challenge_hash?: string;\n amount_minor?: number;\n currency?: string;\n token_symbol?: string;\n status?: string;\n request_hash_v2?: string | null;\n pricing_band?: \"standard\" | DirectRequestPaymentMeteredPlanType | string | null;\n settlement_cadence?: \"per_payment\" | \"weekly\" | \"monthly\" | string | null;\n finality?: string | null;\n protocol_fee_minor?: DirectRequestPaymentMinorAmount | null;\n settlement_status?: string | null;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport class SiglumeDirectRequestPaymentError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeDirectRequestPaymentError\";\n }\n}\n\nexport class SiglumeApiError extends SiglumeDirectRequestPaymentError {\n readonly status: number;\n readonly code: string;\n readonly data: unknown;\n\n constructor(message: string, options: { status: number; code?: string; data?: unknown }) {\n super(message);\n this.name = \"SiglumeApiError\";\n this.status = options.status;\n this.code = options.code ?? \"SIGLUME_API_ERROR\";\n this.data = options.data;\n }\n}\n\nexport class HostedCheckoutNotAvailableError extends SiglumeApiError {\n constructor(message = \"Hosted Checkout is not enabled for this account yet (server rollout in progress).\") {\n super(message, { status: 409, code: \"HOSTED_CHECKOUT_NOT_ENABLED\" });\n this.name = \"HostedCheckoutNotAvailableError\";\n }\n}\n\nexport class SiglumeWebhookSignatureError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookSignatureError\";\n }\n}\n\nexport class SiglumeWebhookPayloadError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookPayloadError\";\n }\n}\n\nexport class DirectRequestPaymentClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A buyer or provider Siglume user bearer token is required for Direct Request Payment API calls. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? `@siglume/direct-request-payment/${DIRECT_REQUEST_PAYMENT_SDK_VERSION}`;\n this.fetch_impl = fetchImpl;\n }\n\n async createPaymentRequirement(input: DirectPaymentRequirementCreateInput): Promise<DirectPaymentRequirement> {\n const payload: Record<string, unknown> = {\n mode: DIRECT_REQUEST_PAYMENT_MODE,\n merchant: normalizeMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n challenge: requireNonEmpty(input.challenge, \"challenge\"),\n };\n if (input.token_symbol !== undefined) {\n payload.token_symbol = normalizeToken(input.token_symbol);\n }\n if (input.allowance_amount_minor !== undefined) {\n payload.allowance_amount_minor = positiveInteger(input.allowance_amount_minor, \"allowance_amount_minor\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectPaymentRequirement>(\"POST\", \"/sdrp/direct-payments/requirements\", payload);\n }\n\n async getPaymentRequirement(requirement_id: string): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"GET\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}`,\n );\n }\n\n async verifyPaymentRequirement(\n requirement_id: string,\n input: DirectPaymentVerifyInput,\n ): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"POST\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}/verify`,\n input,\n );\n }\n\n async executePreparedTransaction(\n payload: Web3PreparedTransactionExecutePayload,\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.request<Web3PreparedTransactionExecuteResult>(\n \"POST\",\n \"/market/web3/transactions/execute-prepared\",\n payload,\n );\n }\n\n async executePaymentTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildPaymentExecutionPayload(requirement, options));\n }\n\n async executeAllowanceTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildAllowanceExecutionPayload(requirement, options));\n }\n\n async getBuyerMeteredSummary(\n input: DirectRequestPaymentBuyerMeteredQuery = {},\n ): Promise<DirectRequestPaymentBuyerMeteredSummary> {\n return this.request<DirectRequestPaymentBuyerMeteredSummary>(\n \"GET\",\n meteredQueryPath(\"/sdrp/metered/my-summary\", input),\n );\n }\n\n async listBuyerUsageEvents(\n input: DirectRequestPaymentMeteredListQuery = {},\n ): Promise<DirectRequestPaymentListResponse<DirectRequestPaymentBuyerUsageEvent>> {\n return this.request<DirectRequestPaymentListResponse<DirectRequestPaymentBuyerUsageEvent>>(\n \"GET\",\n meteredQueryPath(\"/sdrp/metered/my-usage-events\", input),\n );\n }\n\n async listBuyerSettlementBatches(\n input: DirectRequestPaymentMeteredListQuery = {},\n ): Promise<DirectRequestPaymentListResponse<DirectRequestPaymentSettlementBatch>> {\n return this.request<DirectRequestPaymentListResponse<DirectRequestPaymentSettlementBatch>>(\n \"GET\",\n meteredQueryPath(\"/sdrp/metered/my-settlement-batches\", input),\n );\n }\n\n async getProviderMeteredSummary(\n input: DirectRequestPaymentProviderMeteredQuery = {},\n ): Promise<DirectRequestPaymentProviderMeteredSummary> {\n return this.request<DirectRequestPaymentProviderMeteredSummary>(\n \"GET\",\n meteredQueryPath(\"/sdrp/metered/provider/summary\", input),\n );\n }\n\n async listProviderUsageEvents(\n input: DirectRequestPaymentProviderMeteredListQuery = {},\n ): Promise<DirectRequestPaymentListResponse<DirectRequestPaymentProviderUsageEvent>> {\n return this.request<DirectRequestPaymentListResponse<DirectRequestPaymentProviderUsageEvent>>(\n \"GET\",\n meteredQueryPath(\"/sdrp/metered/provider/usage-events\", input),\n );\n }\n\n async listProviderSettlementBatches(\n input: DirectRequestPaymentProviderMeteredListQuery = {},\n ): Promise<DirectRequestPaymentListResponse<DirectRequestPaymentSettlementBatch>> {\n return this.request<DirectRequestPaymentListResponse<DirectRequestPaymentSettlementBatch>>(\n \"GET\",\n meteredQueryPath(\"/sdrp/metered/provider/settlement-batches\", input),\n );\n }\n\n async getProviderSettlementBatch(\n settlement_batch_id: string,\n input: Pick<DirectRequestPaymentProviderMeteredQuery, \"listing_id\" | \"capability_key\"> = {},\n ): Promise<DirectRequestPaymentSettlementBatch> {\n return this.request<DirectRequestPaymentSettlementBatch>(\n \"GET\",\n meteredQueryPath(\n `/sdrp/metered/provider/settlement-batches/${encodeURIComponent(\n requireNonEmpty(settlement_batch_id, \"settlement_batch_id\"),\n )}`,\n input,\n ),\n );\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport class DirectRequestPaymentMerchantClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_MERCHANT_AUTH_TOKEN\") ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A merchant Siglume bearer token is required for Direct Request Payment merchant setup. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? `@siglume/direct-request-payment/${DIRECT_REQUEST_PAYMENT_SDK_VERSION}`;\n this.fetch_impl = fetchImpl;\n }\n\n async setupMerchant(input: DirectRequestPaymentMerchantSetupInput): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n billing_plan: normalizeBillingPlan(input.billing_plan ?? \"launch\"),\n billing_currency: normalizeCurrency(input.billing_currency ?? \"JPY\"),\n };\n if (input.display_name !== undefined) {\n payload.display_name = requireNonEmpty(input.display_name, \"display_name\");\n }\n if (input.allowed_currencies !== undefined) {\n payload.allowed_currencies = normalizeAllowedCurrencies(input.allowed_currencies);\n }\n if (input.webhook_callback_url !== undefined) {\n payload.webhook_callback_url = requireNonEmpty(input.webhook_callback_url, \"webhook_callback_url\");\n }\n if (input.billing_mandate_cap_minor !== undefined) {\n payload.billing_mandate_cap_minor = positiveInteger(input.billing_mandate_cap_minor, \"billing_mandate_cap_minor\");\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n if (input.checkout_allowed_origins !== undefined) {\n payload.checkout_allowed_origins = normalizeOriginList(input.checkout_allowed_origins);\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\"POST\", \"/sdrp/direct-payments/merchants\", payload);\n }\n\n /**\n * Create a Hosted Checkout session (Stripe-Checkout-equivalent for human web\n * shoppers). Siglume authors the challenge server-side, persists a single-use\n * expiring session, and returns a `checkout_url`. Redirect the shopper there;\n * they log into Siglume, approve, and pay from their own wallet, then return\n * to your `success_url`. Fulfill on the `direct_payment.confirmed` webhook\n * (the source of truth), exactly as with the agent flow.\n *\n * `success_url`/`cancel_url` must be on an origin you registered via\n * `checkout_allowed_origins` (or your `webhook_callback_url` origin).\n */\n async createCheckoutSession(input: HostedCheckoutSessionCreateInput): Promise<HostedCheckoutSessionCreateResult> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n nonce: normalizeChallengeNonce(input.nonce),\n success_url: requireNonEmpty(input.success_url, \"success_url\"),\n cancel_url: requireNonEmpty(input.cancel_url, \"cancel_url\"),\n };\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.requestHostedCheckout<HostedCheckoutSessionCreateResult>(\n \"POST\",\n \"/sdrp/direct-payments/checkout-sessions\",\n payload,\n );\n }\n\n /** Read a Hosted Checkout session's status (open / authenticated / paid / expired / cancelled / failed). */\n async getCheckoutSession(session_id: string): Promise<HostedCheckoutSession> {\n return this.requestHostedCheckout<HostedCheckoutSession>(\n \"GET\",\n `/sdrp/direct-payments/checkout-sessions/${encodeURIComponent(requireNonEmpty(session_id, \"session_id\"))}`,\n );\n }\n\n async getMerchant(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"GET\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}`,\n );\n }\n\n async rotateChallengeSecret(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/challenge-secret/rotate`,\n );\n }\n\n async prepareBillingMandate(\n merchant: string,\n input: DirectRequestPaymentMerchantBillingMandateInput = {},\n ): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {};\n if (input.currency !== undefined) {\n payload.currency = normalizeCurrency(input.currency);\n }\n if (input.billing_currency !== undefined) {\n payload.billing_currency = normalizeCurrency(input.billing_currency);\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/billing-mandate`,\n payload,\n );\n }\n\n async createWebhookSubscription(\n input: DirectRequestPaymentWebhookSubscriptionInput,\n ): Promise<DirectRequestPaymentWebhookSubscription> {\n const payload: Record<string, unknown> = {\n callback_url: requireNonEmpty(input.callback_url, \"callback_url\"),\n event_types: input.event_types?.length\n ? input.event_types.map((eventType) => requireNonEmpty(eventType, \"event_type\"))\n : [\"direct_payment.confirmed\", \"direct_payment.spent\"],\n };\n if (input.description !== undefined) {\n payload.description = requireNonEmpty(input.description, \"description\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectRequestPaymentWebhookSubscription>(\"POST\", \"/market/webhooks/subscriptions\", payload);\n }\n\n async setupCheckout(input: DirectRequestPaymentCheckoutSetupInput): Promise<DirectRequestPaymentCheckoutSetupResult> {\n const merchant = await this.setupMerchant(input);\n const merchantKey = merchant.merchant_account.merchant;\n const billing_mandate = input.prepare_billing_mandate === false\n ? null\n : await this.prepareBillingMandate(merchantKey, {\n billing_currency: merchant.merchant_account.billing_currency ?? input.billing_currency ?? \"JPY\",\n max_amount_minor: input.max_amount_minor ?? input.billing_mandate_cap_minor,\n });\n const shouldCreateWebhook = input.create_webhook_subscription ?? Boolean(input.webhook_callback_url);\n const webhook_subscription = shouldCreateWebhook && input.webhook_callback_url\n ? await this.createWebhookSubscription({\n callback_url: input.webhook_callback_url,\n description: input.webhook_description ?? `${merchantKey} Direct Request Payment`,\n event_types: input.webhook_event_types,\n metadata: { merchant: merchantKey, sdk: \"@siglume/direct-request-payment\" },\n })\n : null;\n const env: Record<string, string> = {\n SIGLUME_DIRECT_PAYMENT_MERCHANT: merchantKey,\n };\n if (merchant.challenge_secret) {\n env.SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET = merchant.challenge_secret;\n }\n const webhookSecret = stringOrNull(webhook_subscription?.signing_secret);\n if (webhookSecret) {\n env.SIGLUME_WEBHOOK_SECRET = webhookSecret;\n }\n return { merchant, billing_mandate, webhook_subscription, env };\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n private async requestHostedCheckout<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n try {\n return await this.request<T>(method, path, json_body);\n } catch (error) {\n if (isHostedCheckoutUnavailable(error)) {\n throw new HostedCheckoutNotAvailableError();\n }\n throw error;\n }\n }\n}\n\nexport async function createDirectRequestPaymentChallenge(\n input: DirectRequestPaymentChallengeInput,\n): Promise<DirectRequestPaymentChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = normalizeChallengeNonce(input.nonce);\n const material = `${merchant}:${amount}:${currency}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport function parseDirectRequestPaymentChallenge(challenge: string): ParsedDirectRequestPaymentChallenge {\n const parts = requireNonEmpty(challenge, \"challenge\").split(\":\");\n if (parts.length !== 3) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge must be scheme:nonce:signature.\");\n }\n const [scheme, nonce, signature] = parts;\n if (!scheme || !nonce || !signature) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge is incomplete.\");\n }\n return { scheme, nonce, signature };\n}\n\n/** Merchant-side, ONE-TIME approval of a recurring authorization: amount +\n * currency + cadence are bound into the HMAC. Recurring charges afterwards\n * are deliberately challenge-free; the recurring authorization and the\n * buyer's mandate/budget caps are the per-charge integrity checks. Cadence\n * \"monthly\" = subscription, \"daily\" = scheduled autopay approval tag. */\nexport async function createDirectRequestPaymentRecurringChallenge(\n input: DirectRequestPaymentRecurringChallengeInput,\n): Promise<DirectRequestPaymentRecurringChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentRecurringChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentRecurringChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = normalizeChallengeNonce(input.nonce);\n // MUST stay byte-identical to the server's\n // _external_402_recurring_challenge_signature — both sides change together.\n const material = `${merchant}:${amount}:${currency}:${cadence}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport async function verifyDirectRequestPaymentRecurringChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentRecurringChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n cadence: input.cadence,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function verifyDirectRequestPaymentChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function directRequestPaymentChallengeHash(challenge: string): Promise<string> {\n return sha256Prefixed(requireNonEmpty(challenge, \"challenge\"));\n}\n\nexport async function directRequestPaymentRequestHash(input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n}): Promise<string> {\n const material = `${normalizeMerchant(input.merchant)}${positiveInteger(input.amount_minor, \"amount_minor\")}${normalizeCurrency(input.currency)}${requireNonEmpty(input.challenge, \"challenge\")}`;\n return sha256Prefixed(material);\n}\n\nexport async function directRequestPaymentRequestHashV2(input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n}): Promise<string> {\n const material = JSON.stringify({\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n challenge: requireNonEmpty(input.challenge, \"challenge\"),\n currency: normalizeCurrency(input.currency),\n merchant: normalizeMerchant(input.merchant),\n version: 2,\n });\n return sha256Prefixed(material);\n}\n\nexport function buildPaymentExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n return buildPreparedTransactionExecutionPayload(requirement, requirement.transaction_request, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildAllowanceExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n const approveRequest = requirement.approve_transaction_request;\n if (!approveRequest || Object.keys(approveRequest).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"This payment requirement does not include an allowance approval transaction.\");\n }\n return buildPreparedTransactionExecutionPayload(requirement, approveRequest, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildPreparedTransactionExecutionPayload(\n requirement: DirectPaymentRequirement,\n transaction_request: Web3TransactionRequest,\n options: {\n receipt_kind: string;\n await_finality?: boolean;\n metadata?: Record<string, unknown>;\n },\n): Web3PreparedTransactionExecutePayload {\n const metadata = {\n ...(isRecord(transaction_request.metadata_jsonb) ? transaction_request.metadata_jsonb : {}),\n ...(options.metadata ?? {}),\n };\n return {\n transaction_request,\n receipt_kind: requireNonEmpty(options.receipt_kind, \"receipt_kind\"),\n reference_type: DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE,\n reference_id: requirement.requirement_id,\n metadata,\n await_finality: Boolean(options.await_finality),\n };\n}\n\nexport async function computeWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp: number },\n): Promise<string> {\n if (!signing_secret) {\n throw new SiglumeWebhookSignatureError(\"SIGLUME webhook signing secret is required.\");\n }\n const timestamp = Math.trunc(options.timestamp);\n const bytes = bodyBytes(body);\n const prefix = new TextEncoder().encode(`${timestamp}.`);\n const payload = new Uint8Array(prefix.length + bytes.length);\n payload.set(prefix, 0);\n payload.set(bytes, prefix.length);\n return hmacSha256Hex(signing_secret, payload);\n}\n\nexport async function buildWebhookSignatureHeader(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp?: number } = {},\n): Promise<string> {\n const timestamp = Math.trunc(options.timestamp ?? Date.now() / 1000);\n const signature = await computeWebhookSignature(signing_secret, body, { timestamp });\n return `t=${timestamp},v1=${signature}`;\n}\n\nexport async function verifyWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<WebhookSignatureVerification> {\n const { timestamp, signature } = parseSignatureHeader(signature_header);\n const toleranceSeconds = Math.max(1, Math.trunc(options.tolerance_seconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS));\n const nowSeconds = Math.trunc(options.now ?? Date.now() / 1000);\n if (Math.abs(nowSeconds - timestamp) > toleranceSeconds) {\n throw new SiglumeWebhookSignatureError(\"Webhook timestamp is outside the allowed tolerance window.\");\n }\n const expected = await computeWebhookSignature(signing_secret, body, { timestamp });\n if (!(await timingSafeEqualHex(expected, signature))) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature did not match.\");\n }\n return { timestamp, signature };\n}\n\nexport function parseDirectRequestPaymentWebhookEvent(payload: unknown): DirectRequestPaymentWebhookEvent {\n const event = requireRecord(payload, \"webhook event\");\n const data = requireRecord(event.data, \"webhook event data\");\n const parsed = {\n ...event,\n id: requireNonEmpty(stringOrNull(event.id) ?? \"\", \"webhook event id\"),\n type: requireNonEmpty(stringOrNull(event.type) ?? \"\", \"webhook event type\"),\n api_version: requireNonEmpty(stringOrNull(event.api_version) ?? \"\", \"webhook api_version\"),\n occurred_at: requireNonEmpty(stringOrNull(event.occurred_at) ?? \"\", \"webhook occurred_at\"),\n data: { ...data },\n } as DirectRequestPaymentWebhookEvent;\n if (\n parsed.type === \"direct_payment.confirmed\" &&\n !DIRECT_REQUEST_PAYMENT_CONFIRMED_WEBHOOK_MODES.has(String(parsed.data.mode ?? \"\"))\n ) {\n throw new SiglumeWebhookPayloadError(\n \"direct_payment.confirmed webhook must carry a supported Direct Request Payment mode.\",\n );\n }\n return parsed;\n}\n\nexport async function verifyDirectRequestPaymentWebhook(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<{ event: DirectRequestPaymentWebhookEvent; verification: WebhookSignatureVerification }> {\n const verification = await verifyWebhookSignature(signing_secret, body, signature_header, options);\n const text = new TextDecoder().decode(bodyBytes(body));\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new SiglumeWebhookPayloadError(\"Webhook body must contain valid JSON.\");\n }\n return { event: parseDirectRequestPaymentWebhookEvent(parsed), verification };\n}\n\nexport const createExternal402Challenge = createDirectRequestPaymentChallenge;\nexport const verifyExternal402Challenge = verifyDirectRequestPaymentChallenge;\nexport const createExternal402RecurringChallenge = createDirectRequestPaymentRecurringChallenge;\nexport const verifyExternal402RecurringChallenge = verifyDirectRequestPaymentRecurringChallenge;\n\nfunction normalizeMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9._-]{0,95}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be a lowercase key using letters, numbers, dot, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeSelfServiceMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9_-]{2,63}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be 3-64 chars using lowercase letters, numbers, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeBillingPlan(value: string): DirectRequestPaymentBillingPlan {\n const plan = requireNonEmpty(value, \"billing_plan\").toLowerCase();\n if (plan === \"launch\" || plan === \"free\" || plan === \"starter\" || plan === \"growth\" || plan === \"pro\") {\n return plan;\n }\n throw new SiglumeDirectRequestPaymentError(\"billing_plan must be launch, starter, growth, or pro.\");\n}\n\nfunction normalizeCurrency(value: string): DirectRequestPaymentCurrency {\n const currency = requireNonEmpty(value, \"currency\").toUpperCase();\n if (currency !== \"JPY\" && currency !== \"USD\") {\n throw new SiglumeDirectRequestPaymentError(\"currency must be JPY or USD.\");\n }\n return currency;\n}\n\nfunction normalizeToken(value: string): DirectRequestPaymentToken {\n const token = requireNonEmpty(value, \"token_symbol\").toUpperCase();\n if (token !== \"JPYC\" && token !== \"USDC\") {\n throw new SiglumeDirectRequestPaymentError(\"token_symbol must be JPYC or USDC.\");\n }\n return token;\n}\n\nfunction normalizeMeteredPlanType(value: string): DirectRequestPaymentMeteredPlanType {\n const planType = requireNonEmpty(value, \"plan_type\").toLowerCase();\n if (planType === \"micro\" || planType === \"nano\") {\n return planType;\n }\n throw new SiglumeDirectRequestPaymentError(\"plan_type must be micro or nano.\");\n}\n\nfunction normalizeAllowedCurrencies(value: Record<string, string> | Array<DirectRequestPaymentCurrency | string>): Record<string, string> {\n const normalized: Record<string, string> = {};\n if (Array.isArray(value)) {\n for (const item of value) {\n const currency = normalizeCurrency(item);\n normalized[currency] = defaultTokenForCurrency(currency);\n }\n } else if (isRecord(value)) {\n for (const [rawCurrency, rawToken] of Object.entries(value)) {\n normalized[normalizeCurrency(rawCurrency)] = normalizeToken(String(rawToken));\n }\n } else {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must be an array or a currency-to-token object.\");\n }\n if (Object.keys(normalized).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must include at least one currency.\");\n }\n return normalized;\n}\n\nfunction defaultTokenForCurrency(currency: DirectRequestPaymentCurrency): DirectRequestPaymentToken {\n return currency === \"JPY\" ? \"JPYC\" : \"USDC\";\n}\n\nfunction normalizeOriginList(value: string[]): string[] {\n if (!Array.isArray(value)) {\n throw new SiglumeDirectRequestPaymentError(\"checkout_allowed_origins must be an array of origin URLs.\");\n }\n const seen = new Set<string>();\n const origins: string[] = [];\n for (const item of value) {\n let url: URL;\n try {\n url = new URL(requireNonEmpty(String(item), \"checkout_allowed_origins entry\"));\n } catch {\n throw new SiglumeDirectRequestPaymentError(\n \"each checkout_allowed_origins entry must be an absolute origin such as https://shop.example.com.\",\n );\n }\n if (url.username || url.password) {\n throw new SiglumeDirectRequestPaymentError(\"checkout_allowed_origins entries must not include userinfo.\");\n }\n if (!isAllowedCheckoutOriginScheme(url)) {\n throw new SiglumeDirectRequestPaymentError(\n \"checkout_allowed_origins entries must use https, except http is allowed for localhost, 127.0.0.1, or [::1].\",\n );\n }\n const origin = url.origin.toLowerCase();\n if (!seen.has(origin)) {\n seen.add(origin);\n origins.push(origin);\n }\n }\n return origins;\n}\n\nfunction isAllowedCheckoutOriginScheme(url: URL): boolean {\n if (url.protocol === \"https:\") {\n return Boolean(url.hostname);\n }\n if (url.protocol !== \"http:\") {\n return false;\n }\n const hostname = url.hostname.toLowerCase();\n return hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\" || hostname === \"::1\";\n}\n\nfunction meteredQueryPath(\n path: string,\n input: DirectRequestPaymentBuyerMeteredQuery | DirectRequestPaymentMeteredListQuery | DirectRequestPaymentProviderMeteredQuery | DirectRequestPaymentProviderMeteredListQuery,\n): string {\n const params = new URLSearchParams();\n if (input.plan_type !== undefined) {\n params.set(\"plan_type\", normalizeMeteredPlanType(input.plan_type));\n }\n if (input.token_symbol !== undefined) {\n params.set(\"token_symbol\", normalizeToken(input.token_symbol));\n }\n if (\"status\" in input && input.status !== undefined) {\n params.set(\"status\", requireNonEmpty(input.status, \"status\"));\n }\n if (\"listing_id\" in input && input.listing_id !== undefined) {\n params.set(\"listing_id\", requireNonEmpty(input.listing_id, \"listing_id\"));\n }\n if (\"capability_key\" in input && input.capability_key !== undefined) {\n params.set(\"capability_key\", requireNonEmpty(input.capability_key, \"capability_key\"));\n }\n if (\"limit\" in input && input.limit !== undefined) {\n params.set(\"limit\", String(positiveInteger(input.limit, \"limit\")));\n }\n if (\"cursor\" in input && input.cursor !== undefined) {\n params.set(\"cursor\", requireNonEmpty(input.cursor, \"cursor\"));\n }\n const query = params.toString();\n return query ? `${path}?${query}` : path;\n}\n\nfunction positiveInteger(value: unknown, name: string): number {\n if (typeof value !== \"number\") {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a positive safe integer.`);\n }\n const parsed = value;\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a positive safe integer.`);\n }\n return parsed;\n}\n\nfunction requireNonEmpty(value: string, name: string): string {\n const text = String(value ?? \"\").trim();\n if (!text) {\n throw new SiglumeDirectRequestPaymentError(`${name} is required.`);\n }\n return text;\n}\n\nfunction normalizeChallengeNonce(value: string): string {\n const nonce = requireNonEmpty(value, \"nonce\");\n if (nonce.includes(\":\")) {\n throw new SiglumeDirectRequestPaymentError(\"nonce must not contain ':'.\");\n }\n return nonce;\n}\n\nfunction normalizeRecurringCadence(value: string): DirectRequestPaymentRecurringCadence {\n const cadence = requireNonEmpty(value, \"cadence\").toLowerCase();\n if (cadence !== \"monthly\" && cadence !== \"daily\") {\n throw new SiglumeDirectRequestPaymentError(\n 'cadence must be \"monthly\" (subscription) or \"daily\" (scheduled autopay).',\n );\n }\n return cadence;\n}\n\nfunction cloneJsonObject(value: Record<string, unknown>, name: string): Record<string, unknown> {\n try {\n const cloned = JSON.parse(JSON.stringify(value)) as unknown;\n if (!isRecord(cloned)) {\n throw new Error(\"not an object\");\n }\n return cloned;\n } catch (error) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a JSON-serializable object.`);\n }\n}\n\nfunction parseJson(rawText: string): unknown {\n try {\n return JSON.parse(rawText);\n } catch (error) {\n throw new SiglumeApiError(\"Siglume API returned invalid JSON.\", {\n status: 502,\n code: \"INVALID_JSON_RESPONSE\",\n data: rawText,\n });\n }\n}\n\nfunction stringOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const text = value.trim();\n return text ? text : null;\n}\n\nfunction isHostedCheckoutUnavailable(error: unknown): boolean {\n if (!(error instanceof SiglumeApiError)) {\n return false;\n }\n const code = error.code.toUpperCase();\n if (error.status === 409 && (code === \"HOSTED_CHECKOUT_NOT_ENABLED\" || code === \"FEATURE_DISABLED\")) {\n return true;\n }\n return (\n error.status === 404 &&\n (code === \"HTTP_404\" || code === \"NOT_FOUND\" || code === \"ROUTE_NOT_FOUND\" || code === \"FEATURE_DISABLED\")\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requireRecord(value: unknown, name: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new SiglumeWebhookPayloadError(`${name} must be an object.`);\n }\n return value;\n}\n\nfunction envValue(name: string): string | undefined {\n if (typeof process === \"undefined\") {\n return undefined;\n }\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nfunction bodyBytes(body: Uint8Array | ArrayBuffer | string | Record<string, unknown>): Uint8Array {\n if (body instanceof Uint8Array) {\n return body;\n }\n if (body instanceof ArrayBuffer) {\n return new Uint8Array(body);\n }\n if (typeof body === \"string\") {\n return new TextEncoder().encode(body);\n }\n if (isRecord(body)) {\n return new TextEncoder().encode(JSON.stringify(body));\n }\n throw new SiglumeWebhookPayloadError(\"Webhook body must be raw bytes, a string, or a JSON object.\");\n}\n\nfunction parseSignatureHeader(signatureHeader: string): { timestamp: number; signature: string } {\n let timestamp: number | null = null;\n let signature: string | null = null;\n for (const item of String(signatureHeader ?? \"\").split(\",\")) {\n const [key, value] = item.trim().split(\"=\", 2);\n if (key === \"t\") {\n const parsed = Number.parseInt(value ?? \"\", 10);\n if (!Number.isFinite(parsed)) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature timestamp is invalid.\");\n }\n timestamp = parsed;\n }\n if (key === \"v1\") {\n signature = String(value ?? \"\").trim();\n }\n }\n if (timestamp === null || !signature) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature header is incomplete.\");\n }\n return { timestamp, signature };\n}\n\nasync function randomNonce(): Promise<string> {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(bytes);\n } else if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n bytes.set(crypto.randomBytes(16));\n } else {\n throw new SiglumeDirectRequestPaymentError(\"Crypto random number generation is unavailable in this runtime.\");\n }\n return bytesToHex(bytes);\n}\n\nasync function hmacSha256Hex(secret: string, payload: Uint8Array): Promise<string> {\n if (globalThis.crypto?.subtle) {\n const stablePayload = new Uint8Array(payload.byteLength);\n stablePayload.set(payload);\n const key = await globalThis.crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const digest = await globalThis.crypto.subtle.sign(\"HMAC\", key, stablePayload);\n return bytesToHex(new Uint8Array(digest));\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return crypto.createHmac(\"sha256\", secret).update(Buffer.from(payload)).digest(\"hex\");\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for HMAC-SHA256 in this runtime.\");\n}\n\nasync function sha256Prefixed(material: string): Promise<string> {\n const bytes = new TextEncoder().encode(material);\n if (globalThis.crypto?.subtle) {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return `sha256:${bytesToHex(new Uint8Array(digest))}`;\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return `sha256:${crypto.createHash(\"sha256\").update(Buffer.from(bytes)).digest(\"hex\")}`;\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for SHA-256 in this runtime.\");\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return [...bytes].map((item) => item.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const normalized = String(hex ?? \"\").trim().toLowerCase();\n if (normalized.length % 2 !== 0 || !/^[0-9a-f]*$/.test(normalized)) {\n throw new SiglumeWebhookSignatureError(\"Hex digest is invalid.\");\n }\n const bytes = new Uint8Array(normalized.length / 2);\n for (let index = 0; index < normalized.length; index += 2) {\n bytes[index / 2] = Number.parseInt(normalized.slice(index, index + 2), 16);\n }\n return bytes;\n}\n\nasync function timingSafeEqualHex(left: string, right: string): Promise<boolean> {\n const leftBytes = hexToBytes(left);\n const rightBytes = hexToBytes(right);\n if (leftBytes.length !== rightBytes.length) {\n return false;\n }\n let diff = 0;\n for (let index = 0; index < leftBytes.length; index += 1) {\n diff |= leftBytes[index]! ^ rightBytes[index]!;\n }\n return diff === 0;\n}\n"],"mappings":";AAAO,IAAM,2BAA2B;AACjC,IAA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AAS,WAAW,MAAM,OAAO,QAAQ,CAAC,GAAG,EAAE;AAAA,EAC3E;AACA,SAAO;AACT;AAEA,eAAe,mBAAmB,MAAc,OAAiC;AAC/E,QAAM,YAAY,WAAW,IAAI;AACjC,QAAM,aAAa,WAAW,KAAK;AACnC,MAAI,UAAU,WAAW,WAAW,QAAQ;AAC1C,WAAO;AAAA,EACT;AACA,MAAI,OAAO;AACX,WAAS,QAAQ,GAAG,QAAQ,UAAU,QAAQ,SAAS,GAAG;AACxD,YAAQ,UAAU,KAAK,IAAK,WAAW,KAAK;AAAA,EAC9C;AACA,SAAO,SAAS;AAClB;","names":[]}
@@ -72,7 +72,7 @@ Standard Payment は1決済ごとに精算します。Micro / Nano は金額帯
72
72
  - **休日・失敗・再試行・繰越**: オンチェーン精算のため銀行休業日の影響はなく、曜日に関係なくカレンダー境界で締まります。精算が失敗した場合(例: 精算時に購入者ウォレットの残高・allowance・BudgetVault 設定が不足/無効)は自動で再試行され、その購入者の同一トークンの Micro/Nano は未解決の精算が片付くまで一時停止します。past due は記録・表示されますが、最終的な回収や provider への支払いを保証するものではありません。
73
73
  - **rejected / 課金なし**: 購入者ウォレットの予算枠は **グロス額**(料金+プロトコルフィー)で予約されますが、これは支払い原資・残高・allowance をロック、保全、保証するものではありません。予算・scope・金額帯が満たされない場合は **課金なしで拒否**され、リクエストは実行されず、精算にも計上されません。
74
74
 
75
- **確定事項と可変事項**: 周期は固定です(**Micro は週次、Nano は月次**。確定はオンチェーン精算後)。具体的な締めスロット、予定引き落とし時刻、再試行間隔はプラットフォーム側で管理されるため、暦をハードコードせず statement API の `status`、`not_before_attempt_at`、`fee_bps` を正本としてください。運用マニュアルは [Micro / Nano Statements and Notices](./metered-statements.md) を参照してください。
75
+ **確定事項と可変事項**: 周期は固定です(**Micro は週次、Nano は月次**。確定はオンチェーン精算後)。具体的な締めスロット、予定引き落とし時刻、再試行間隔はプラットフォーム側で管理されるため、暦をハードコードしないでください。Standard Payment は payment requirement の `fee_bps`、Micro / Nano は statement API の `protocol_fee_minor`、`buyer_debit_minor`、`rounding_delta_minor`、`status`、`not_before_attempt_at` を正本としてください。運用マニュアルは [Micro / Nano Statements and Notices](./metered-statements.md) を参照してください。
76
76
 
77
77
  ## 最短導入
78
78
 
@@ -36,7 +36,7 @@ and no new webhook.
36
36
  | --- | --- | --- |
37
37
  | `SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET` | merchant server | HMAC secret for order challenges |
38
38
  | `SIGLUME_MERCHANT_AUTH_TOKEN` | merchant setup helper | merchant Siglume bearer token for self-service setup |
39
- | `SIGLUME_AUTH_TOKEN` | buyer payment helper | buyer Siglume bearer token for API calls |
39
+ | `SIGLUME_AUTH_TOKEN` | user-authenticated helper | buyer Siglume bearer token for payment / buyer statements, or provider Siglume bearer token for provider statements |
40
40
  | `SIGLUME_API_BASE` | optional | API base URL override; defaults to `https://siglume.com/v1` |
41
41
  | `SIGLUME_WEBHOOK_SECRET` | merchant server | webhook signing secret returned as `whsec_...` |
42
42
 
@@ -505,8 +505,10 @@ or rotation.
505
505
  ## `DirectRequestPaymentClient`
506
506
 
507
507
  Thin wrapper around the current Siglume Direct Request Payment HTTP contract.
508
- Use it with the authenticated buyer's Siglume bearer token. Developer Portal
509
- `cli_` API keys are not accepted by these buyer-authenticated routes.
508
+ Use it with the authenticated Siglume user bearer token for the route you call:
509
+ buyer tokens for buyer payment and buyer statement routes, provider / merchant
510
+ tokens for provider statement routes. Developer Portal `cli_` API keys are not
511
+ accepted by these user-authenticated routes.
510
512
 
511
513
  This client creates SDRP Standard Payment requirements for external merchant
512
514
  checkout flows. Micro Payment and Nano Payment are applied automatically by
@@ -522,14 +524,14 @@ statement API amount fields (`protocol_fee_minor`, `gross_buyer_debit_minor`,
522
524
 
523
525
  ```ts
524
526
  const siglume = new DirectRequestPaymentClient({
525
- auth_token: buyerSiglumeBearerToken,
527
+ auth_token: buyerOrProviderSiglumeBearerToken,
526
528
  base_url: "https://siglume.com/v1",
527
529
  });
528
530
  ```
529
531
 
530
532
  ```py
531
533
  siglume = DirectRequestPaymentClient(
532
- auth_token=buyer_siglume_bearer_token,
534
+ auth_token=buyer_or_provider_siglume_bearer_token,
533
535
  base_url="https://siglume.com/v1",
534
536
  )
535
537
  ```
@@ -556,6 +558,13 @@ Input:
556
558
  - `allowance_amount_minor`: optional positive integer
557
559
  - `metadata`: optional JSON object
558
560
 
561
+ There is no public `idempotency_key` field on this requirement-create request.
562
+ For one-time external checkout, idempotency is the merchant-signed challenge
563
+ nonce: derive `nonce` from a durable order payment attempt, store the returned
564
+ `challenge_hash`, and use `request_hash_v2` when you need a canonical machine
565
+ hash for the same payment request. Do not retry the same order by minting a new
566
+ nonce unless you intentionally want a new payment attempt.
567
+
559
568
  The returned requirement includes both compatibility and machine-readable
560
569
  settlement fields:
561
570
 
@@ -723,8 +732,9 @@ SDK methods:
723
732
  - TypeScript: `listBuyerUsageEvents(...)`, `listBuyerSettlementBatches(...)`
724
733
  - Python: `list_buyer_usage_events(...)`, `list_buyer_settlement_batches(...)`
725
734
 
726
- Each accepts `plan_type`, `token_symbol`, `status`, and `limit`, and returns
727
- `{items, next_cursor}`.
735
+ Each accepts `plan_type`, `token_symbol`, `status`, `limit`, and `cursor`, and
736
+ returns `{items, next_cursor}`. When `next_cursor` is non-null, pass it back as
737
+ `cursor` to fetch the next page.
728
738
 
729
739
  Buyer-facing amount names are centered on the debit:
730
740
 
@@ -783,9 +793,10 @@ SDK methods:
783
793
  `list_provider_settlement_batches(...)`, `get_provider_settlement_batch(...)`
784
794
 
785
795
  Provider list methods accept `plan_type`, `token_symbol`, `status`,
786
- `listing_id`, `capability_key`, and `limit`. Detail accepts
796
+ `listing_id`, `capability_key`, `limit`, and `cursor`. Detail accepts
787
797
  `settlement_batch_id`, plus optional `listing_id` and `capability_key`. List
788
- methods return `{items, next_cursor}`.
798
+ methods return `{items, next_cursor}`. When `next_cursor` is non-null, pass it
799
+ back as `cursor` to fetch the next page.
789
800
 
790
801
  Provider-facing amount names:
791
802
 
@@ -843,6 +854,13 @@ metered_usage_id,created_at,plan_type,settlement_cadence,period_start,period_end
843
854
  ```
844
855
 
845
856
  The CSV uses `buyer_period_ref`, not raw buyer account identifiers.
857
+ The CSV keeps the `rounding_delta_minor` column for schema stability, but usage
858
+ rows report `0`; the authoritative rounding adjustment is the settlement batch
859
+ field `rounding_delta_minor`.
860
+
861
+ Micro / Nano amount fields are decimal minor-unit strings. In JavaScript, do
862
+ not aggregate them with `number`; parse them with a decimal library. In Python,
863
+ use `Decimal` for accounting and reconciliation.
846
864
 
847
865
  ## Payload Builders
848
866
 
@@ -106,12 +106,21 @@ buyer_debit_minor = ceil(gross_buyer_debit_minor)
106
106
  rounding_delta_minor = buyer_debit_minor - gross_buyer_debit_minor
107
107
  ```
108
108
 
109
+ For low-count Nano batches, the ceiling can make the effective buyer burden per
110
+ usage higher than the headline "USD 0.001 / usage" protocol fee. The protocol
111
+ fee remains the decimal statement amount; the extra integer-minor-unit
112
+ adjustment is recorded as `rounding_delta_minor` on the settlement batch.
113
+
109
114
  `rounding_delta_minor` belongs to the buyer debit and Siglume's rounding
110
115
  adjustment accounting for that batch. It is not provider revenue. Provider
111
116
  reports should use `provider_receivable_minor`,
112
117
  `settled_provider_receivable_minor`, `unsettled_provider_receivable_minor`, and
113
118
  `past_due_provider_receivable_minor`.
114
119
 
120
+ Micro / Nano amount fields are decimal minor-unit strings. JavaScript
121
+ integrations should aggregate them with a decimal library, not `number`. Python
122
+ integrations should use `Decimal` for accounting.
123
+
115
124
  ### Usage Events
116
125
 
117
126
  ```text
@@ -123,6 +132,7 @@ Query parameters:
123
132
  - `plan_type`: `micro` or `nano`
124
133
  - `token_symbol`: `JPYC` or `USDC`
125
134
  - `status`: for example `pending_settlement`, `settled`, `failed_chargeable`
135
+ - `cursor`: pass the previous response's `next_cursor` to fetch the next page
126
136
  - `limit`: 1 to 500
127
137
 
128
138
  SDK methods: `listBuyerUsageEvents(...)` / `list_buyer_usage_events(...)`.
@@ -148,6 +158,7 @@ Query parameters:
148
158
  - `token_symbol`: `JPYC` or `USDC`
149
159
  - `status`: `notice_pending`, `ready`, `submitted`, `settled`, `failed`,
150
160
  `past_due`, or `notice_delivery_failed`
161
+ - `cursor`: pass the previous response's `next_cursor` to fetch the next page
151
162
  - `limit`: 1 to 200
152
163
 
153
164
  SDK methods: `listBuyerSettlementBatches(...)` /
@@ -233,6 +244,7 @@ Query parameters:
233
244
  - `status`
234
245
  - `listing_id`
235
246
  - `capability_key`
247
+ - `cursor`: pass the previous response's `next_cursor` to fetch the next page
236
248
  - `limit`: 1 to 500
237
249
 
238
250
  SDK methods: `listProviderUsageEvents(...)` /
@@ -266,6 +278,7 @@ Query parameters for the list endpoint:
266
278
  - `status`
267
279
  - `listing_id`
268
280
  - `capability_key`
281
+ - `cursor`: pass the previous response's `next_cursor` to fetch the next page
269
282
  - `limit`: 1 to 200
270
283
 
271
284
  The detail endpoint also accepts `listing_id` and `capability_key`.
@@ -317,6 +330,10 @@ metered_usage_id,created_at,plan_type,settlement_cadence,period_start,period_end
317
330
  ```
318
331
 
319
332
  The CSV uses `buyer_period_ref`, not `buyer_user_id`.
333
+ `rounding_delta_minor` is present for a stable usage-event schema, but per-row
334
+ values are `0`. The authoritative rounding adjustment is the settlement batch
335
+ `rounding_delta_minor`; do not allocate that adjustment to provider revenue
336
+ from individual CSV rows.
320
337
 
321
338
  ## Notifications
322
339
 
@@ -392,6 +409,11 @@ using stable idempotency keys and provider-side completion records.
392
409
  | `past_due` | Buyer has an unresolved settlement block; provider sees past-due revenue | New Micro / Nano usage for the same buyer / plan / token is paused | Operator requeue or manual resolution only | Do not promise collection or provider payment. Ask the buyer to repair balance / allowance / BudgetVault / caps and reference `support_reference`. |
393
410
  | `failed_chargeable` | Usage is still chargeable because provider work was accepted or completed | Included in later settlement attempts | Review if the provider disputes completion | Keep fulfillment idempotent and preserve evidence keyed by idempotency key. |
394
411
 
412
+ Future platform versions may add explicit terminal states such as
413
+ `closed_unpaid`, `uncollectible`, or `written_off`. Treat unknown terminal
414
+ settlement states as not settled unless `status === "settled"` and
415
+ `chain_receipt_id` is present.
416
+
395
417
  ## Operational Recipes
396
418
 
397
419
  ### "How much did we use this week or month?"
package/docs/pricing.md CHANGED
@@ -179,6 +179,13 @@ revenue. Providers should reconcile their revenue with
179
179
  `unsettled_provider_receivable_minor`, and
180
180
  `past_due_provider_receivable_minor`, not with `buyer_debit_minor`.
181
181
 
182
+ For low-count Nano batches, the integer ceiling can make the effective buyer
183
+ burden per usage higher than the headline USD 0.001 / usage protocol fee. The
184
+ decimal protocol fee remains visible as `protocol_fee_minor`; the difference
185
+ created by integer-token settlement is visible as `rounding_delta_minor` on the
186
+ batch. JavaScript integrations should not sum Micro / Nano minor amounts with
187
+ `number`; use a decimal library. Python integrations should use `Decimal`.
188
+
182
189
  ## Statement APIs and Notices
183
190
 
184
191
  Micro and Nano require operational reconciliation after usage is accepted. The