@siglume/direct-request-payment 0.4.15 → 0.4.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +14 -9
- package/dist/index.cjs +59 -17
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +73 -11
- package/dist/index.d.ts +73 -11
- package/dist/index.js +59 -17
- package/dist/index.js.map +1 -1
- package/docs/announcement-ja.md +1 -1
- package/docs/api-reference.md +19 -0
- package/docs/merchant-quickstart.md +11 -4
- package/docs/metered-statements.md +25 -6
- package/docs/pricing.md +31 -24
- package/examples/express-checkout.ts +3 -1
- package/package.json +1 -1
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.15\";\nexport const DIRECT_REQUEST_PAYMENT_STANDARD_SETTLED_STATUS = \"settled\";\nexport const DIRECT_REQUEST_PAYMENT_METERED_ACCEPTED_STATUS = \"pending_settlement\";\nexport const DIRECT_REQUEST_PAYMENT_STANDARD_FINALITY = \"per_payment_onchain\";\nexport const DIRECT_REQUEST_PAYMENT_METERED_FINALITY = \"aggregated_onchain_settlement\";\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;\nexport type DirectRequestPaymentRawWebhookBody = Uint8Array | ArrayBuffer | string;\nexport type DirectRequestPaymentWebhookSignatureBody = DirectRequestPaymentRawWebhookBody | Record<string, unknown>;\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_gross_amount_minor: DirectRequestPaymentMinorAmount;\n provider_usage_amount_minor: DirectRequestPaymentMinorAmount;\n protocol_fee_minor: DirectRequestPaymentMinorAmount;\n gross_buyer_debit_minor: DirectRequestPaymentMinorAmount;\n buyer_debit_minor?: DirectRequestPaymentMinorAmount;\n rounding_delta_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_gross_amount_minor: DirectRequestPaymentMinorAmount;\n provider_usage_amount_minor: DirectRequestPaymentMinorAmount;\n provider_receivable_minor: DirectRequestPaymentMinorAmount;\n protocol_fee_minor: DirectRequestPaymentMinorAmount;\n gross_buyer_debit_minor: DirectRequestPaymentMinorAmount;\n buyer_debit_minor?: DirectRequestPaymentMinorAmount;\n rounding_delta_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 settlement_trigger?: \"amount_threshold\" | \"scheduled_close\" | string | null;\n settlement_threshold_minor?: DirectRequestPaymentMinorAmount | null;\n threshold_reached_at?: string | null;\n total_unsettled_exposure_minor?: DirectRequestPaymentMinorAmount | null;\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_gross_amount_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 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 chain_receipt_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 settlement_batch_id?: string | null;\n chain_receipt_id?: string | null;\n usage_event_digest?: string | null;\n settled_at?: string | null;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport type DirectPaymentConfirmationKind =\n | \"standard_settled\"\n | \"metered_usage_accepted\"\n | \"metered_batch_settled\"\n | \"unknown\";\n\nexport type DirectPaymentConfirmationUnknownReason =\n | \"not_direct_payment_confirmed\"\n | \"invalid_metered_settlement_confirmation\"\n | \"missing_standard_settlement_fields\"\n | \"missing_metered_usage_fields\"\n | \"unknown_confirmation_shape\";\n\nexport interface DirectPaymentStandardSettledClassification {\n kind: \"standard_settled\";\n event: DirectRequestPaymentWebhookEvent;\n data: DirectRequestPaymentWebhookEvent[\"data\"];\n requirement_id: string;\n challenge_hash: string;\n chain_receipt_id: string;\n request_hash_v2?: string | null;\n}\n\nexport interface DirectPaymentMeteredUsageAcceptedClassification {\n kind: \"metered_usage_accepted\";\n event: DirectRequestPaymentWebhookEvent;\n data: DirectRequestPaymentWebhookEvent[\"data\"];\n pricing_band: DirectRequestPaymentMeteredPlanType;\n settlement_cadence: \"weekly\" | \"monthly\";\n requirement_id: string;\n challenge_hash: string;\n request_hash_v2?: string | null;\n}\n\nexport interface DirectPaymentMeteredBatchSettledClassification {\n kind: \"metered_batch_settled\";\n event: DirectRequestPaymentWebhookEvent;\n data: DirectRequestPaymentWebhookEvent[\"data\"];\n pricing_band: DirectRequestPaymentMeteredPlanType;\n settlement_cadence: \"weekly\" | \"monthly\";\n settlement_batch_id: string;\n chain_receipt_id: string;\n usage_event_digest: string;\n settled_at?: string | null;\n}\n\nexport interface DirectPaymentUnknownClassification {\n kind: \"unknown\";\n event: DirectRequestPaymentWebhookEvent;\n data: DirectRequestPaymentWebhookEvent[\"data\"];\n reason: DirectPaymentConfirmationUnknownReason;\n requirement_id?: string | null;\n settlement_batch_id?: string | null;\n pricing_band?: string | null;\n settlement_cadence?: string | null;\n settlement_status?: string | null;\n finality?: string | null;\n}\n\nexport type DirectPaymentConfirmationClassification =\n | DirectPaymentStandardSettledClassification\n | DirectPaymentMeteredUsageAcceptedClassification\n | DirectPaymentMeteredBatchSettledClassification\n | DirectPaymentUnknownClassification;\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 Eboth 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: DirectRequestPaymentWebhookSignatureBody,\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: DirectRequestPaymentWebhookSignatureBody,\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: DirectRequestPaymentRawWebhookBody,\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 rawBody = rawWebhookBodyBytes(body);\n const expected = await computeWebhookSignature(signing_secret, rawBody, { 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 function classifyDirectPaymentConfirmation(\n event: DirectRequestPaymentWebhookEvent,\n): DirectPaymentConfirmationClassification {\n const data = event.data;\n const requirementId = stringOrNull(data.requirement_id) ?? stringOrNull(data.direct_payment_requirement_id);\n const challengeHash = stringOrNull(data.challenge_hash);\n const pricingBand = stringOrNull(data.pricing_band);\n const settlementCadence = stringOrNull(data.settlement_cadence);\n const finality = stringOrNull(data.finality);\n const settlementStatus = stringOrNull(data.settlement_status);\n\n if (event.type !== \"direct_payment.confirmed\") {\n return {\n kind: \"unknown\",\n event,\n data,\n reason: \"not_direct_payment_confirmed\",\n requirement_id: requirementId,\n settlement_batch_id: stringOrNull(data.settlement_batch_id),\n pricing_band: pricingBand,\n settlement_cadence: settlementCadence,\n settlement_status: settlementStatus,\n finality,\n };\n }\n\n if (data.mode === \"metered_settlement_batch\") {\n const settlementBatchId = stringOrNull(data.settlement_batch_id);\n const chainReceiptId = stringOrNull(data.chain_receipt_id);\n const usageEventDigest = stringOrNull(data.usage_event_digest);\n if (\n settlementStatus === DIRECT_REQUEST_PAYMENT_STANDARD_SETTLED_STATUS &&\n finality === DIRECT_REQUEST_PAYMENT_METERED_FINALITY &&\n (pricingBand === \"micro\" || pricingBand === \"nano\") &&\n settlementCadence === (pricingBand === \"micro\" ? \"weekly\" : \"monthly\") &&\n settlementBatchId &&\n chainReceiptId &&\n usageEventDigest\n ) {\n return {\n kind: \"metered_batch_settled\",\n event,\n data,\n pricing_band: pricingBand,\n settlement_cadence: pricingBand === \"micro\" ? \"weekly\" : \"monthly\",\n settlement_batch_id: settlementBatchId,\n chain_receipt_id: chainReceiptId,\n usage_event_digest: usageEventDigest,\n settled_at: stringOrNull(data.settled_at),\n };\n }\n return {\n kind: \"unknown\",\n event,\n data,\n reason: \"invalid_metered_settlement_confirmation\",\n requirement_id: requirementId,\n settlement_batch_id: settlementBatchId,\n pricing_band: pricingBand,\n settlement_cadence: settlementCadence,\n settlement_status: settlementStatus,\n finality,\n };\n }\n\n if (pricingBand === \"standard\") {\n const chainReceiptId = stringOrNull(data.chain_receipt_id);\n if (\n finality === DIRECT_REQUEST_PAYMENT_STANDARD_FINALITY &&\n settlementStatus === DIRECT_REQUEST_PAYMENT_STANDARD_SETTLED_STATUS &&\n requirementId &&\n challengeHash &&\n chainReceiptId\n ) {\n return {\n kind: \"standard_settled\",\n event,\n data,\n requirement_id: requirementId,\n challenge_hash: challengeHash,\n chain_receipt_id: chainReceiptId,\n request_hash_v2: stringOrNull(data.request_hash_v2),\n };\n }\n return {\n kind: \"unknown\",\n event,\n data,\n reason: \"missing_standard_settlement_fields\",\n requirement_id: requirementId,\n pricing_band: pricingBand,\n settlement_cadence: settlementCadence,\n settlement_status: settlementStatus,\n finality,\n };\n }\n\n if (pricingBand === \"micro\" || pricingBand === \"nano\") {\n if (\n finality === DIRECT_REQUEST_PAYMENT_METERED_FINALITY &&\n settlementStatus === DIRECT_REQUEST_PAYMENT_METERED_ACCEPTED_STATUS &&\n settlementCadence === (pricingBand === \"micro\" ? \"weekly\" : \"monthly\") &&\n requirementId &&\n challengeHash\n ) {\n return {\n kind: \"metered_usage_accepted\",\n event,\n data,\n pricing_band: pricingBand,\n settlement_cadence: pricingBand === \"micro\" ? \"weekly\" : \"monthly\",\n requirement_id: requirementId,\n challenge_hash: challengeHash,\n request_hash_v2: stringOrNull(data.request_hash_v2),\n };\n }\n return {\n kind: \"unknown\",\n event,\n data,\n reason: \"missing_metered_usage_fields\",\n requirement_id: requirementId,\n pricing_band: pricingBand,\n settlement_cadence: settlementCadence,\n settlement_status: settlementStatus,\n finality,\n };\n }\n\n return {\n kind: \"unknown\",\n event,\n data,\n reason: \"unknown_confirmation_shape\",\n requirement_id: requirementId,\n settlement_batch_id: stringOrNull(data.settlement_batch_id),\n pricing_band: pricingBand,\n settlement_cadence: settlementCadence,\n settlement_status: settlementStatus,\n finality,\n };\n}\n\nexport async function verifyDirectRequestPaymentWebhook(\n signing_secret: string,\n body: DirectRequestPaymentRawWebhookBody,\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(rawWebhookBodyBytes(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: DirectRequestPaymentWebhookSignatureBody): 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 rawWebhookBodyBytes(body: 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 throw new SiglumeWebhookPayloadError(\n \"Webhook verification requires the exact raw request body bytes or raw body string; JSON objects are only accepted by buildWebhookSignatureHeader for tests.\",\n );\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;AAC3C,IAAM,iDAAiD;AACvD,IAAM,iDAAiD;AACvD,IAAM,2CAA2C;AACjD,IAAM,0CAA0C;AACvD,IAAM,iDAAiD,oBAAI,IAAI,CAAC,6BAA6B,0BAA0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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.17\";\nexport const DIRECT_REQUEST_PAYMENT_STANDARD_SETTLED_STATUS = \"settled\";\nexport const DIRECT_REQUEST_PAYMENT_METERED_ACCEPTED_STATUS = \"pending_settlement\";\nexport const DIRECT_REQUEST_PAYMENT_STANDARD_FINALITY = \"per_payment_onchain\";\nexport const DIRECT_REQUEST_PAYMENT_METERED_FINALITY = \"aggregated_onchain_settlement\";\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 DirectRequestPaymentSettlementTrigger = \"amount_threshold\" | \"scheduled_close\";\nexport type DirectRequestPaymentMinorAmount = string;\nexport type DirectRequestPaymentRawWebhookBody = Uint8Array | ArrayBuffer | string;\nexport type DirectRequestPaymentWebhookSignatureBody = DirectRequestPaymentRawWebhookBody | Record<string, unknown>;\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_gross_amount_minor: DirectRequestPaymentMinorAmount;\n provider_usage_amount_minor: DirectRequestPaymentMinorAmount;\n protocol_fee_minor: DirectRequestPaymentMinorAmount;\n gross_buyer_debit_minor: DirectRequestPaymentMinorAmount;\n buyer_debit_minor?: DirectRequestPaymentMinorAmount;\n rounding_delta_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_gross_amount_minor: DirectRequestPaymentMinorAmount;\n provider_usage_amount_minor: DirectRequestPaymentMinorAmount;\n provider_receivable_minor: DirectRequestPaymentMinorAmount;\n protocol_fee_minor: DirectRequestPaymentMinorAmount;\n gross_buyer_debit_minor: DirectRequestPaymentMinorAmount;\n buyer_debit_minor?: DirectRequestPaymentMinorAmount;\n rounding_delta_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 settlement_trigger?: DirectRequestPaymentSettlementTrigger | null;\n settlement_threshold_minor?: DirectRequestPaymentMinorAmount | null;\n threshold_reached_at?: string | null;\n total_unsettled_exposure_minor?: DirectRequestPaymentMinorAmount | null;\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_gross_amount_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 terminal_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n uncollectible_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n written_off_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n terminal_status?: \"uncollectible\" | \"written_off\" | string | null;\n terminal_marked_at?: string | null;\n terminal_reason_code?: string | null;\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 DirectRequestPaymentMeteredOpenPeriod {\n plan_type?: DirectRequestPaymentMeteredPlanType | string;\n settlement_cadence?: \"weekly\" | \"monthly\" | string;\n currency?: DirectRequestPaymentCurrency | string;\n token_symbol?: DirectRequestPaymentToken | string;\n period_start?: string | null;\n period_end?: string | null;\n close_at?: string | null;\n settlement_trigger?: DirectRequestPaymentSettlementTrigger | null;\n settlement_threshold_minor?: DirectRequestPaymentMinorAmount | null;\n threshold_reached_at?: string | null;\n provider_gross_amount_minor?: DirectRequestPaymentMinorAmount;\n provider_usage_amount_minor?: DirectRequestPaymentMinorAmount;\n protocol_fee_minor?: DirectRequestPaymentMinorAmount;\n provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n buyer_debit_minor?: DirectRequestPaymentMinorAmount;\n total_unsettled_exposure_minor?: DirectRequestPaymentMinorAmount | null;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentPastDueBlock {\n settlement_batch_id?: string;\n plan_type?: DirectRequestPaymentMeteredPlanType | string;\n currency?: DirectRequestPaymentCurrency | string;\n token_symbol?: DirectRequestPaymentToken | string;\n total_unsettled_exposure_minor?: DirectRequestPaymentMinorAmount | null;\n past_due_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n failure_reason_code?: string | null;\n support_reference?: string | null;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentBalanceSufficiency {\n sufficient?: boolean;\n currency?: DirectRequestPaymentCurrency | string;\n token_symbol?: DirectRequestPaymentToken | string;\n required_minor?: DirectRequestPaymentMinorAmount;\n available_minor?: DirectRequestPaymentMinorAmount;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentProviderMeteredTotals {\n settled_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n unsettled_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n past_due_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n terminal_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n uncollectible_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n written_off_provider_receivable_minor?: DirectRequestPaymentMinorAmount;\n [key: string]: DirectRequestPaymentMinorAmount | undefined;\n}\n\nexport interface DirectRequestPaymentBuyerMeteredSummary {\n role: \"buyer\";\n open_periods: DirectRequestPaymentMeteredOpenPeriod[];\n settlement_batches: DirectRequestPaymentSettlementBatch[];\n past_due_blocks: DirectRequestPaymentPastDueBlock[];\n balance_sufficiency?: DirectRequestPaymentBalanceSufficiency;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentProviderMeteredSummary {\n role: \"provider\";\n timezone?: string | null;\n filters?: Record<string, unknown>;\n open_periods: DirectRequestPaymentMeteredOpenPeriod[];\n periods: DirectRequestPaymentSettlementBatch[];\n totals: DirectRequestPaymentProviderMeteredTotals;\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 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 chain_receipt_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 provider_gross_amount_minor?: DirectRequestPaymentMinorAmount | null;\n provider_usage_amount_minor?: DirectRequestPaymentMinorAmount | null;\n provider_receivable_minor?: DirectRequestPaymentMinorAmount | null;\n buyer_debit_minor?: DirectRequestPaymentMinorAmount | null;\n settlement_trigger?: DirectRequestPaymentSettlementTrigger | string | null;\n settlement_threshold_minor?: DirectRequestPaymentMinorAmount | null;\n threshold_reached_at?: string | null;\n total_unsettled_exposure_minor?: DirectRequestPaymentMinorAmount | null;\n settlement_status?: string | null;\n settlement_batch_id?: string | null;\n chain_receipt_id?: string | null;\n usage_event_digest?: string | null;\n settled_at?: string | null;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport type DirectPaymentConfirmationKind =\n | \"standard_settled\"\n | \"metered_usage_accepted\"\n | \"metered_batch_settled\"\n | \"unknown\";\n\nexport type DirectPaymentConfirmationUnknownReason =\n | \"not_direct_payment_confirmed\"\n | \"unsupported_confirmation_mode\"\n | \"invalid_metered_settlement_confirmation\"\n | \"missing_standard_settlement_fields\"\n | \"missing_metered_usage_fields\"\n | \"unknown_confirmation_shape\";\n\nexport interface DirectPaymentStandardSettledClassification {\n kind: \"standard_settled\";\n event: DirectRequestPaymentWebhookEvent;\n data: DirectRequestPaymentWebhookEvent[\"data\"];\n requirement_id: string;\n challenge_hash: string;\n chain_receipt_id: string;\n request_hash_v2?: string | null;\n}\n\nexport interface DirectPaymentMeteredUsageAcceptedClassification {\n kind: \"metered_usage_accepted\";\n event: DirectRequestPaymentWebhookEvent;\n data: DirectRequestPaymentWebhookEvent[\"data\"];\n pricing_band: DirectRequestPaymentMeteredPlanType;\n settlement_cadence: \"weekly\" | \"monthly\";\n requirement_id: string;\n challenge_hash: string;\n request_hash_v2?: string | null;\n}\n\nexport interface DirectPaymentMeteredBatchSettledClassification {\n kind: \"metered_batch_settled\";\n event: DirectRequestPaymentWebhookEvent;\n data: DirectRequestPaymentWebhookEvent[\"data\"];\n pricing_band: DirectRequestPaymentMeteredPlanType;\n settlement_cadence: \"weekly\" | \"monthly\";\n settlement_batch_id: string;\n chain_receipt_id: string;\n usage_event_digest: string;\n settled_at?: string | null;\n}\n\nexport interface DirectPaymentUnknownClassification {\n kind: \"unknown\";\n event: DirectRequestPaymentWebhookEvent;\n data: DirectRequestPaymentWebhookEvent[\"data\"];\n reason: DirectPaymentConfirmationUnknownReason;\n requirement_id?: string | null;\n settlement_batch_id?: string | null;\n pricing_band?: string | null;\n settlement_cadence?: string | null;\n settlement_status?: string | null;\n finality?: string | null;\n}\n\nexport type DirectPaymentConfirmationClassification =\n | DirectPaymentStandardSettledClassification\n | DirectPaymentMeteredUsageAcceptedClassification\n | DirectPaymentMeteredBatchSettledClassification\n | DirectPaymentUnknownClassification;\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 #authToken: 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.#authToken = authToken;\n this.base_url = normalizeApiBaseUrl(options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE);\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.#authToken}`,\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 #authToken: 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.#authToken = authToken;\n this.base_url = normalizeApiBaseUrl(options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE);\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 = normalizeHttpsUrl(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: normalizeHttpsUrl(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.#authToken}`,\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 Eboth 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: DirectRequestPaymentWebhookSignatureBody,\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: DirectRequestPaymentWebhookSignatureBody,\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: DirectRequestPaymentRawWebhookBody,\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 rawBody = rawWebhookBodyBytes(body);\n const expected = await computeWebhookSignature(signing_secret, rawBody, { 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 return parsed;\n}\n\nexport function classifyDirectPaymentConfirmation(\n event: DirectRequestPaymentWebhookEvent,\n): DirectPaymentConfirmationClassification {\n const data = event.data;\n const requirementId = stringOrNull(data.requirement_id) ?? stringOrNull(data.direct_payment_requirement_id);\n const challengeHash = stringOrNull(data.challenge_hash);\n const pricingBand = stringOrNull(data.pricing_band);\n const settlementCadence = stringOrNull(data.settlement_cadence);\n const finality = stringOrNull(data.finality);\n const settlementStatus = stringOrNull(data.settlement_status);\n const mode = stringOrNull(data.mode);\n\n if (event.type !== \"direct_payment.confirmed\") {\n return {\n kind: \"unknown\",\n event,\n data,\n reason: \"not_direct_payment_confirmed\",\n requirement_id: requirementId,\n settlement_batch_id: stringOrNull(data.settlement_batch_id),\n pricing_band: pricingBand,\n settlement_cadence: settlementCadence,\n settlement_status: settlementStatus,\n finality,\n };\n }\n\n if (!DIRECT_REQUEST_PAYMENT_CONFIRMED_WEBHOOK_MODES.has(mode ?? \"\")) {\n return {\n kind: \"unknown\",\n event,\n data,\n reason: \"unsupported_confirmation_mode\",\n requirement_id: requirementId,\n settlement_batch_id: stringOrNull(data.settlement_batch_id),\n pricing_band: pricingBand,\n settlement_cadence: settlementCadence,\n settlement_status: settlementStatus,\n finality,\n };\n }\n\n if (mode === \"metered_settlement_batch\") {\n const settlementBatchId = stringOrNull(data.settlement_batch_id);\n const chainReceiptId = stringOrNull(data.chain_receipt_id);\n const usageEventDigest = stringOrNull(data.usage_event_digest);\n if (\n settlementStatus === DIRECT_REQUEST_PAYMENT_STANDARD_SETTLED_STATUS &&\n finality === DIRECT_REQUEST_PAYMENT_METERED_FINALITY &&\n (pricingBand === \"micro\" || pricingBand === \"nano\") &&\n settlementCadence === (pricingBand === \"micro\" ? \"weekly\" : \"monthly\") &&\n settlementBatchId &&\n chainReceiptId &&\n usageEventDigest\n ) {\n return {\n kind: \"metered_batch_settled\",\n event,\n data,\n pricing_band: pricingBand,\n settlement_cadence: pricingBand === \"micro\" ? \"weekly\" : \"monthly\",\n settlement_batch_id: settlementBatchId,\n chain_receipt_id: chainReceiptId,\n usage_event_digest: usageEventDigest,\n settled_at: stringOrNull(data.settled_at),\n };\n }\n return {\n kind: \"unknown\",\n event,\n data,\n reason: \"invalid_metered_settlement_confirmation\",\n requirement_id: requirementId,\n settlement_batch_id: settlementBatchId,\n pricing_band: pricingBand,\n settlement_cadence: settlementCadence,\n settlement_status: settlementStatus,\n finality,\n };\n }\n\n if (pricingBand === \"standard\") {\n const chainReceiptId = stringOrNull(data.chain_receipt_id);\n if (\n finality === DIRECT_REQUEST_PAYMENT_STANDARD_FINALITY &&\n settlementStatus === DIRECT_REQUEST_PAYMENT_STANDARD_SETTLED_STATUS &&\n requirementId &&\n challengeHash &&\n chainReceiptId\n ) {\n return {\n kind: \"standard_settled\",\n event,\n data,\n requirement_id: requirementId,\n challenge_hash: challengeHash,\n chain_receipt_id: chainReceiptId,\n request_hash_v2: stringOrNull(data.request_hash_v2),\n };\n }\n return {\n kind: \"unknown\",\n event,\n data,\n reason: \"missing_standard_settlement_fields\",\n requirement_id: requirementId,\n pricing_band: pricingBand,\n settlement_cadence: settlementCadence,\n settlement_status: settlementStatus,\n finality,\n };\n }\n\n if (pricingBand === \"micro\" || pricingBand === \"nano\") {\n if (\n finality === DIRECT_REQUEST_PAYMENT_METERED_FINALITY &&\n settlementStatus === DIRECT_REQUEST_PAYMENT_METERED_ACCEPTED_STATUS &&\n settlementCadence === (pricingBand === \"micro\" ? \"weekly\" : \"monthly\") &&\n requirementId &&\n challengeHash\n ) {\n return {\n kind: \"metered_usage_accepted\",\n event,\n data,\n pricing_band: pricingBand,\n settlement_cadence: pricingBand === \"micro\" ? \"weekly\" : \"monthly\",\n requirement_id: requirementId,\n challenge_hash: challengeHash,\n request_hash_v2: stringOrNull(data.request_hash_v2),\n };\n }\n return {\n kind: \"unknown\",\n event,\n data,\n reason: \"missing_metered_usage_fields\",\n requirement_id: requirementId,\n pricing_band: pricingBand,\n settlement_cadence: settlementCadence,\n settlement_status: settlementStatus,\n finality,\n };\n }\n\n return {\n kind: \"unknown\",\n event,\n data,\n reason: \"unknown_confirmation_shape\",\n requirement_id: requirementId,\n settlement_batch_id: stringOrNull(data.settlement_batch_id),\n pricing_band: pricingBand,\n settlement_cadence: settlementCadence,\n settlement_status: settlementStatus,\n finality,\n };\n}\n\nexport async function verifyDirectRequestPaymentWebhook(\n signing_secret: string,\n body: DirectRequestPaymentRawWebhookBody,\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(rawWebhookBodyBytes(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 normalizeApiBaseUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(requireNonEmpty(value, \"base_url\"));\n } catch {\n throw new SiglumeDirectRequestPaymentError(\"base_url must be an absolute URL such as https://siglume.com/v1.\");\n }\n if (url.username || url.password) {\n throw new SiglumeDirectRequestPaymentError(\"base_url must not include userinfo.\");\n }\n if (!isAllowedCheckoutOriginScheme(url)) {\n throw new SiglumeDirectRequestPaymentError(\n \"base_url must use https, except http is allowed for localhost, 127.0.0.1, or [::1].\",\n );\n }\n return url.toString().replace(/\\/+$/, \"\");\n}\n\nfunction normalizeHttpsUrl(value: string, name: string): string {\n let url: URL;\n try {\n url = new URL(requireNonEmpty(value, name));\n } catch {\n throw new SiglumeDirectRequestPaymentError(`${name} must be an absolute https URL.`);\n }\n if (url.username || url.password) {\n throw new SiglumeDirectRequestPaymentError(`${name} must not include userinfo.`);\n }\n if (url.protocol !== \"https:\" || !url.hostname) {\n throw new SiglumeDirectRequestPaymentError(`${name} must use https.`);\n }\n return url.toString();\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: DirectRequestPaymentWebhookSignatureBody): 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 rawWebhookBodyBytes(body: 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 throw new SiglumeWebhookPayloadError(\n \"Webhook verification requires the exact raw request body bytes or raw body string; JSON objects are only accepted by buildWebhookSignatureHeader for tests.\",\n );\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;AA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AS,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":[]}
|
package/docs/announcement-ja.md
CHANGED
|
@@ -57,7 +57,7 @@ Siglume Direct Request Payment は、merchantが注文・金額・通貨をサ
|
|
|
57
57
|
|
|
58
58
|
ここでの Tx は1件のSDRP決済を指し、集約精算のオンチェーンTxではありません。
|
|
59
59
|
|
|
60
|
-
Standard Payment は1決済ごとに精算します。Micro / Nano は金額帯で自動適用され、週次 / 月次でまとめて精算されます。SDRP の導入・merchant setup・billing mandate は、この Micro / Nano
|
|
60
|
+
Standard Payment は1決済ごとに精算します。Micro / Nano は金額帯で自動適用され、週次 / 月次でまとめて精算されます。SDRP の導入・merchant setup・billing mandate は、この Micro / Nano の後払い的な集約精算を受け入れる前提です。self-service setup では、この受諾が `merchant_account.metadata_jsonb.metered_risk_acceptance` に `terms_version`、`accepted_at`、`principal_user_id`、`receipt_id`、固定市場閾値 JPY 10000 / USD 10000 として記録されます。このリスクを受け入れない商品は、JPY 500 以下 / USD 3 以下では提供せず、Standard Payment 帯の価格にしてください。締め・支払い予定・未精算・精算済み・past due は statement API と CSV で確認します。なお、少額の支払いは実行前に購入者ウォレットの予算が確認され、予算・scope・金額帯のいずれかが満たされない場合はその場で拒否され、課金は発生しません(リクエストは実行されません)。
|
|
61
61
|
|
|
62
62
|
公開されている Direct Payment / Hosted Checkout の `amount_minor` は通貨の最小単位の正の整数です。そのため、一回払いの公開経路で表現できる最小金額は JPY 1 / USD 0.01 であり、この経路での Nano Payment は JPY 1-49 / USD 0.01-0.30 を指します。USD 0.001 / SDRP Tx などのサブマイナー単位は、外部チェックアウトの商品価格ではなく、集約精算時のプロトコルフィー会計です。
|
|
63
63
|
|
package/docs/api-reference.md
CHANGED
|
@@ -353,6 +353,11 @@ Returns:
|
|
|
353
353
|
- `webhook_subscription`: webhook subscription response, when created
|
|
354
354
|
- `env`: server environment values to store, including returned secrets
|
|
355
355
|
|
|
356
|
+
`merchant.merchant_account.metadata_jsonb.metered_risk_acceptance` records the
|
|
357
|
+
merchant's Micro / Nano delayed-settlement risk acceptance receipt with
|
|
358
|
+
`terms_version`, `accepted_at`, `principal_user_id`, `receipt_id`, and fixed
|
|
359
|
+
market thresholds `JPY: 10000` / `USD: 10000`.
|
|
360
|
+
|
|
356
361
|
Secrets are returned only when created or rotated. Existing secrets are not
|
|
357
362
|
replayed by `getMerchant` / `get_merchant`.
|
|
358
363
|
|
|
@@ -852,6 +857,9 @@ Provider-facing amount names:
|
|
|
852
857
|
- `settled_provider_receivable_minor`
|
|
853
858
|
- `unsettled_provider_receivable_minor`
|
|
854
859
|
- `past_due_provider_receivable_minor`
|
|
860
|
+
- `terminal_provider_receivable_minor`
|
|
861
|
+
- `uncollectible_provider_receivable_minor`
|
|
862
|
+
- `written_off_provider_receivable_minor`
|
|
855
863
|
|
|
856
864
|
Schedule and execution fields:
|
|
857
865
|
|
|
@@ -869,6 +877,9 @@ Schedule and execution fields:
|
|
|
869
877
|
- `usage_event_digest`
|
|
870
878
|
- `attempt_count`
|
|
871
879
|
- `next_attempt_at`
|
|
880
|
+
- `terminal_status`
|
|
881
|
+
- `terminal_marked_at`
|
|
882
|
+
- `terminal_reason_code`
|
|
872
883
|
|
|
873
884
|
Failure fields are sanitized for public display:
|
|
874
885
|
|
|
@@ -882,6 +893,14 @@ address, relayer id, nonce, gas data, raw RPC errors, or raw
|
|
|
882
893
|
`failure_message`. Use `buyer_period_ref` for provider-side reconciliation
|
|
883
894
|
within a period.
|
|
884
895
|
|
|
896
|
+
Terminal statuses `uncollectible` and `written_off` are operator resolutions
|
|
897
|
+
after past-due manual review. Their receivable fields are reported separately
|
|
898
|
+
from settled, unsettled, and past-due revenue.
|
|
899
|
+
|
|
900
|
+
If a Micro / Nano execution idempotency key is reused with a different input
|
|
901
|
+
payload, execution fails closed before provider execution with
|
|
902
|
+
`IDEMPOTENCY_KEY_REUSED_WITH_DIFFERENT_PAYLOAD` and HTTP status `409`.
|
|
903
|
+
|
|
885
904
|
### Provider CSV export
|
|
886
905
|
|
|
887
906
|
```text
|
|
@@ -24,13 +24,19 @@ This quickstart uses Standard-band example amounts. Micro Payment and Nano
|
|
|
24
24
|
Payment are applied automatically by amount through the same Hosted Checkout or
|
|
25
25
|
agent/API flow; you do not create a separate Micro/Nano object or manually
|
|
26
26
|
select the amount band. Micro/Nano are settled on account-assigned weekly /
|
|
27
|
-
monthly slots
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
monthly slots, or earlier when the same buyer / provider / token / pricing band
|
|
28
|
+
reaches the fixed market threshold, after the final notice and
|
|
29
|
+
close-plus-3-day window (see [Pricing](./pricing.md#settlement-schedule)), and
|
|
30
|
+
provider revenue remains unsettled until the later on-chain settlement succeeds.
|
|
31
|
+
Completing merchant
|
|
30
32
|
setup and the billing mandate means accepting this Micro/Nano delayed aggregated
|
|
31
33
|
settlement model for low-price items. If your product requires immediate
|
|
32
34
|
on-chain settlement, keep its price above the Micro/Nano thresholds instead of
|
|
33
35
|
offering JPY 500-and-under or USD 3-and-under amounts.
|
|
36
|
+
The setup response records this acceptance at
|
|
37
|
+
`merchant.merchant_account.metadata_jsonb.metered_risk_acceptance` with a
|
|
38
|
+
`terms_version`, `accepted_at`, `principal_user_id`, `receipt_id`, and fixed
|
|
39
|
+
market thresholds `JPY: 10000` / `USD: 10000`.
|
|
34
40
|
|
|
35
41
|
## Two Buyer Systems
|
|
36
42
|
|
|
@@ -612,7 +618,8 @@ manual, including buyer past-due blocks and public failure fields.
|
|
|
612
618
|
before new payments can be accepted.
|
|
613
619
|
- `METERED_SETTLEMENT_PAST_DUE` (Micro / Nano only): a previous Micro / Nano
|
|
614
620
|
metered settlement for this buyer is unresolved, so new Micro / Nano usage in
|
|
615
|
-
the same
|
|
621
|
+
the same buyer / provider / token / pricing band is paused until it settles.
|
|
622
|
+
Siglume retries settlement
|
|
616
623
|
automatically every 6 hours, up to 28 attempts, before it requires manual
|
|
617
624
|
resolution. The provider's Micro / Nano revenue stays unsettled until the
|
|
618
625
|
settlement succeeds. This is a settlement-side state, not a per-request
|