@orqex/checkout-js 0.0.1 → 0.1.0-beta-a7744cf

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -339,9 +339,9 @@ function projectView(state) {
339
339
  amount: catalogue.amount,
340
340
  methods: catalogue.methods,
341
341
  country: catalogue.country,
342
- currencies: catalogue.currencies,
342
+ currencyOptions: catalogue.currencyOptions,
343
343
  supportsAnyCountry: catalogue.supportsAnyCountry,
344
- previousPhones: checkout.previous_used_phones ?? []
344
+ previousPhones: state.previousPhones
345
345
  };
346
346
  if (checkout.restriction) ctx.restriction = checkout.restriction;
347
347
  if (checkout.customer) ctx.customer = checkout.customer;
@@ -413,6 +413,7 @@ function result(state, kind) {
413
413
  function initialState() {
414
414
  return {
415
415
  catalogue: null,
416
+ previousPhones: [],
416
417
  checkout: null,
417
418
  message: "",
418
419
  phase: "loading",
@@ -424,11 +425,11 @@ function initialState() {
424
425
  };
425
426
  }
426
427
  function extractCatalogue(checkout) {
427
- const { country, currencies, amount, methods } = checkout;
428
- if (!country || !currencies || !amount || !methods) return null;
428
+ const { country, currency_options, amount, methods } = checkout;
429
+ if (!country || !currency_options || !amount || !methods) return null;
429
430
  return {
430
431
  country,
431
- currencies,
432
+ currencyOptions: currency_options,
432
433
  amount,
433
434
  methods,
434
435
  supportsAnyCountry: checkout.supports_any_country ?? false
@@ -603,6 +604,9 @@ var CheckoutEngine = class {
603
604
  const catalogue = extractCatalogue(checkout);
604
605
  if (catalogue) next.catalogue = catalogue;
605
606
  }
607
+ if (checkout.previous_used_phones != null) {
608
+ next.previousPhones = checkout.previous_used_phones;
609
+ }
606
610
  this.setState(next);
607
611
  this.reconcilePolling();
608
612
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/key.ts","../src/config.ts","../src/embedded.ts","../src/event-bus.ts","../../engine/src/types/errors.ts","../../engine/src/transport/http-transport.ts","../../engine/src/engine/phase.ts","../../engine/src/engine/project.ts","../../engine/src/engine/state.ts","../../engine/src/engine/engine.ts","../src/redirect-effect.ts","../src/headless.ts","../src/redirect.ts","../src/orqex.ts","../src/embed-projection.ts","../src/index.ts"],"names":[],"mappings":";;;;AAMA,IAAM,UAAA,GAAa,+BAAA;AAOZ,SAAS,oBAAoB,GAAA,EAAwB;AAC1D,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,CAAC,UAAA,CAAW,IAAA,CAAK,GAAG,CAAA,EAAG;AACpD,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AACA,EAAA,OAAO,EAAE,GAAA,EAAK,QAAA,EAAU,GAAA,CAAI,UAAA,CAAW,UAAU,CAAA,EAAE;AACrD;;;ACbO,IAAM,yBAAA,GAA4B,4BAAA;AAOlC,IAAM,oBAAA,GAAuB,uBAAA;AAoB7B,SAAS,aAAA,CAAc,cAAA,EAAwB,OAAA,GAAwB,EAAC,EAAmB;AAChG,EAAA,MAAM,EAAE,GAAA,EAAK,QAAA,EAAS,GAAI,oBAAoB,cAAc,CAAA;AAC5D,EAAA,MAAM,GAAA,GAAM,QAAQ,eAAA,IAAmB,yBAAA;AACvC,EAAA,MAAM,eAAA,GAAkB,GAAA,CAAI,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AAC9C,EAAA,IAAI,cAAA;AACJ,EAAA,IAAI;AACF,IAAA,cAAA,GAAiB,IAAI,GAAA,CAAI,eAAe,CAAA,CAAE,MAAA;AAAA,EAC5C,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,gCAAA,EAAmC,GAAG,CAAA,EAAA,CAAI,CAAA;AAAA,EAC5D;AACA,EAAA,MAAM,cAAc,OAAA,CAAQ,UAAA,IAAc,oBAAA,EAAsB,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAClF,EAAA,OAAO,EAAE,cAAA,EAAgB,GAAA,EAAK,QAAA,EAAU,eAAA,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EAAK,CAAA,UAAA,EAAa,MAAM,CAAA,CAAA,EAAG;AAAA,EAC7E,CAAA,MAAA,IAAW,IAAA,CAAK,IAAA,KAAS,QAAA,EAAU;AACjC,IAAA,MAAM,MAAA,GAAS,MAAA,CAAO,IAAA,CAAK,GAAA,CAAI,MAAM,CAAA;AACrC,IAAA,UAAA,GAAa,EAAE,OAAA,EAAS,YAAA,CAAa,MAAA,EAAQ,IAAA,CAAK,GAAA,CAAI,OAAO,CAAA,EAAG,GAAA,EAAK,CAAA,OAAA,EAAU,MAAM,CAAA,CAAA,EAAG;AAAA,EAC1F,CAAA,MAAA,IAAW,IAAA,CAAK,IAAA,KAAS,QAAA,EAAU;AACjC,IAAA,MAAM,MAAA,GAAS,MAAA,CAAO,IAAA,CAAK,GAAA,CAAI,MAAM,CAAA;AACrC,IAAA,UAAA,GAAa,EAAE,SAAS,YAAA,CAAa,MAAM,GAAG,GAAA,EAAK,CAAA,OAAA,EAAU,MAAM,CAAA,CAAA,EAAG;AAAA,EACxE;AAEA,EAAA,IAAI,CAAC,UAAA,IAAc,UAAA,CAAW,GAAA,KAAQ,SAAS,OAAO,IAAA;AACtD,EAAA,OAAO,UAAA;AACT;;;ACzBO,IAAM,WAAA,GAAc","file":"index.js","sourcesContent":["/** Parsed publishable key: the raw string plus the environment it targets. */\nexport interface ParsedKey {\n key: string;\n livemode: boolean;\n}\n\nconst PK_PATTERN = /^pk_(live|test)_[A-Za-z0-9]+$/;\n\n/**\n * Validate the client key shape. Only `pk_live_…` / `pk_test_…` are accepted;\n * anything else (empty, `sk_…`, M2M secret, malformed) throws. The publishable\n * key is public by design, so no value here is treated as sensitive.\n */\nexport function parsePublishableKey(key: string): ParsedKey {\n if (typeof key !== 'string' || !PK_PATTERN.test(key)) {\n throw new Error(\n 'Orqex: a publishable key (\"pk_live_…\" or \"pk_test_…\") is required. Never pass a secret key to the browser.',\n );\n }\n return { key, livemode: key.startsWith('pk_live_') };\n}\n","import { parsePublishableKey } from './key';\n\n/**\n * Default hosted-checkout origin. PLACEHOLDER — confirm the real production\n * origin before release; merchants can always override via\n * `Orqex(pk, { checkoutBaseUrl })`.\n */\nexport const DEFAULT_CHECKOUT_BASE_URL = 'https://checkout.orqex.com';\n\n/**\n * Default API origin the headless engine calls with pk_. PLACEHOLDER — confirm\n * the real production API origin before release; override via\n * `Orqex(pk, { apiBaseUrl })`.\n */\nexport const DEFAULT_API_BASE_URL = 'https://api.orqex.com';\n\nexport interface OrqexOptions {\n /** Override the hosted-checkout origin (e.g. a staging or self-hosted deploy). */\n checkoutBaseUrl?: string;\n /** Override the API origin the headless engine calls (e.g. staging). */\n apiBaseUrl?: string;\n}\n\nexport interface ResolvedConfig {\n publishableKey: string;\n livemode: boolean;\n /** Hosted-checkout base, no trailing slash. */\n checkoutBaseUrl: string;\n /** Origin of `checkoutBaseUrl`; the only origin we accept inbound messages from. */\n checkoutOrigin: string;\n /** API origin for headless engine requests, no trailing slash. */\n apiBaseUrl: string;\n}\n\nexport function resolveConfig(publishableKey: string, options: OrqexOptions = {}): ResolvedConfig {\n const { key, livemode } = parsePublishableKey(publishableKey);\n const raw = options.checkoutBaseUrl ?? DEFAULT_CHECKOUT_BASE_URL;\n const checkoutBaseUrl = raw.replace(/\\/+$/, '');\n let checkoutOrigin: string;\n try {\n checkoutOrigin = new URL(checkoutBaseUrl).origin;\n } catch {\n throw new Error(`Orqex: invalid checkoutBaseUrl \"${raw}\".`);\n }\n const apiBaseUrl = (options.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\\/+$/, '');\n return { publishableKey: key, livemode, checkoutBaseUrl, checkoutOrigin, apiBaseUrl };\n}\n\nexport function buildEmbedUrl(config: ResolvedConfig, publicId: string, parentOrigin: string): string {\n const id = encodeURIComponent(publicId);\n return `${config.checkoutBaseUrl}/${id}?embed=1&origin=${encodeURIComponent(parentOrigin)}`;\n}\n\nexport function buildRedirectUrl(config: ResolvedConfig, publicId: string): string {\n return `${config.checkoutBaseUrl}/${encodeURIComponent(publicId)}`;\n}\n","import { buildEmbedUrl, type ResolvedConfig } from './config';\nimport type { EventBus } from './event-bus';\nimport { isEmbedMessage, type EmbedMessage } from './protocol';\n\nexport interface MountOptions {\n publicId: string;\n}\n\nexport interface EmbeddedControllerDeps {\n config: ResolvedConfig;\n bus: EventBus;\n /** Injectable for tests; defaults to the global window. */\n win?: Window;\n /** Top-level navigation for redirect messages; injectable for tests. */\n navigate?: (url: string) => void;\n}\n\nconst SANDBOX = 'allow-scripts allow-same-origin allow-forms allow-popups';\n\n/**\n * Owns the sandboxed hosted-checkout iframe: creation, the origin-guarded\n * message listener, auto-resize, redirect bubbling, and teardown.\n */\nexport class EmbeddedController {\n private readonly config: ResolvedConfig;\n private readonly bus: EventBus;\n private readonly win: Window;\n private readonly navigate: (url: string) => void;\n\n private iframe: HTMLIFrameElement | null = null;\n private listener: ((event: MessageEvent) => void) | null = null;\n\n constructor(deps: EmbeddedControllerDeps) {\n this.config = deps.config;\n this.bus = deps.bus;\n this.win = deps.win ?? window;\n this.navigate = deps.navigate ?? ((url) => this.win.location.assign(url));\n }\n\n mount(target: string | HTMLElement, options: MountOptions): void {\n if (!options.publicId) throw new Error('Orqex: mount requires a publicId.');\n const host = this.resolveHost(target);\n this.unmount();\n\n const iframe = this.win.document.createElement('iframe');\n iframe.src = buildEmbedUrl(this.config, options.publicId, this.win.location.origin);\n iframe.setAttribute('sandbox', SANDBOX);\n iframe.setAttribute('allow', 'payment');\n iframe.setAttribute('title', 'Orqex Checkout');\n iframe.style.width = '100%';\n iframe.style.border = 'none';\n iframe.style.height = '150px';\n host.appendChild(iframe);\n this.iframe = iframe;\n\n const listener = (event: MessageEvent): void => {\n if (event.origin !== this.config.checkoutOrigin) return;\n if (event.source !== iframe.contentWindow) return;\n if (!isEmbedMessage(event.data)) return;\n this.handle(event.data);\n };\n this.win.addEventListener('message', listener);\n this.listener = listener;\n }\n\n unmount(): void {\n if (this.listener) {\n this.win.removeEventListener('message', this.listener);\n this.listener = null;\n }\n if (this.iframe) {\n this.iframe.remove();\n this.iframe = null;\n }\n }\n\n private handle(message: EmbedMessage): void {\n switch (message.type) {\n case 'resize':\n if (this.iframe) this.iframe.style.height = `${message.height}px`;\n break;\n case 'success':\n this.bus.emit('success', { status: message.status });\n break;\n case 'error':\n this.bus.emit('error', { code: message.code, message: message.message });\n break;\n case 'close':\n this.bus.emit('close', { status: message.status });\n break;\n case 'redirect':\n // The iframe cannot navigate the top window; the SDK does it here.\n this.bus.emit('redirect', { url: message.url });\n this.navigate(message.url);\n break;\n case 'ready':\n break;\n }\n }\n\n private resolveHost(target: string | HTMLElement): HTMLElement {\n const host = typeof target === 'string' ? this.win.document.querySelector<HTMLElement>(target) : target;\n if (!host) throw new Error(`Orqex: mount target \"${String(target)}\" not found.`);\n return host;\n }\n}\n","/** Merchant-facing lifecycle events for embedded/redirect modes. */\nexport type MerchantEvent = 'success' | 'error' | 'redirect' | 'close';\n\nexport interface EventPayloads {\n success: { status: string };\n error: { code: string; message: string };\n redirect: { url: string };\n close: { status: string };\n}\n\ntype Handler<TEvent extends MerchantEvent> = (payload: EventPayloads[TEvent]) => void;\n\n/**\n * Minimal typed pub/sub. A handler that throws is caught and logged so a single\n * bad merchant callback cannot break delivery to the others.\n */\nexport class EventBus {\n private readonly handlers: { [TEvent in MerchantEvent]: Set<Handler<TEvent>> } = {\n success: new Set(),\n error: new Set(),\n redirect: new Set(),\n close: new Set(),\n };\n\n on<TEvent extends MerchantEvent>(event: TEvent, handler: Handler<TEvent>): () => void {\n this.handlers[event].add(handler);\n return () => this.off(event, handler);\n }\n\n off<TEvent extends MerchantEvent>(event: TEvent, handler: Handler<TEvent>): void {\n this.handlers[event].delete(handler);\n }\n\n emit<TEvent extends MerchantEvent>(event: TEvent, payload: EventPayloads[TEvent]): void {\n for (const handler of this.handlers[event]) {\n try {\n handler(payload);\n } catch (cause) {\n // eslint-disable-next-line no-console\n console.error(`Orqex: \"${event}\" event handler threw`, cause);\n }\n }\n }\n}\n","/**\n * Typed error model. The envelope `message` from the server is customer-safe\n * and is carried through verbatim.\n */\n\nexport const CHECKOUT_ERROR_CODE = [\n // 404: token unknown or expired\n 'not_found',\n // 400: session not open\n 'not_open',\n // 422: validation / intent final / restriction\n 'unprocessable',\n // 429: throttle:60,1\n 'rate_limited',\n // transport failure / no response\n 'network',\n 'unknown',\n] as const;\nexport type CheckoutErrorCode = (typeof CHECKOUT_ERROR_CODE)[number];\n\nexport class CheckoutError extends Error {\n readonly code: CheckoutErrorCode;\n readonly httpStatus?: number;\n\n constructor(code: CheckoutErrorCode, message: string, httpStatus?: number) {\n super(message);\n this.name = 'CheckoutError';\n this.code = code;\n this.httpStatus = httpStatus;\n }\n}\n\nexport function errorCodeFromStatus(status: number): CheckoutErrorCode {\n switch (status) {\n case 400:\n return 'not_open';\n case 404:\n return 'not_found';\n case 422:\n return 'unprocessable';\n case 429:\n return 'rate_limited';\n default:\n return status >= 500 ? 'network' : 'unknown';\n }\n}\n\n/** Terminal errors close the checkout; others are recoverable in-place. */\nexport function isTerminalError(code: CheckoutErrorCode): boolean {\n return code === 'not_found' || code === 'not_open';\n}\n","import type {\n AuthorizeInput,\n CountriesResponse,\n Envelope,\n HostedCheckout,\n PayInput,\n ShowQuery,\n} from '../types/contract';\nimport { CheckoutError, errorCodeFromStatus } from '../types/errors';\n\nimport type { Transport } from './transport';\n\ntype FetchLike = (input: string, init?: RequestInit) => Promise<Response>;\n\n/**\n * Publishable-key auth (Stripe-aligned, backend PR #105 onward).\n *\n * `publishableKey` is the project `pk_...`, obtained server-side via the M2M\n * `/checkout/bootstrap` call and handed to the client. It is sent as\n * `Authorization: Bearer pk_...` on every checkout request. `publicId` is the\n * `cs_...` CheckoutSession pointer, addressed as `/checkout/{publicId}`.\n *\n * `pk_` is publishable: client exposure is expected. No secret ever reaches the\n * browser, so nothing here needs to be hidden from the instance.\n */\nexport interface PublishableKeyAuth {\n /** pk_... project publishable key. */\n publishableKey: string;\n /** cs_... CheckoutSession public id. */\n publicId: string;\n}\n\nexport interface HttpTransportOptions {\n /** API base, e.g. \"https://api.orqex.com\". No trailing slash required. */\n baseUrl: string;\n /** Publishable-key auth (pk_ + public_id). */\n auth: PublishableKeyAuth;\n /** BCP-47 language for Accept-Language (e.g. from appearance.lang). */\n locale?: string;\n /** Injectable fetch (defaults to global). Keeps the engine env-agnostic. */\n fetchImpl?: FetchLike;\n /** Per-request timeout in ms. Default 20000. */\n timeoutMs?: number;\n}\n\n/**\n * Real transport against the hosted-checkout endpoints.\n *\n * Auth is `Bearer pk_` against `/checkout/{publicId}`. Errors map to\n * CheckoutError; the server's `message` is preserved for customer display.\n */\nexport class HttpTransport implements Transport {\n private readonly baseUrl: string;\n private readonly auth: PublishableKeyAuth;\n private readonly locale?: string;\n private readonly fetchImpl: FetchLike;\n private readonly timeoutMs: number;\n\n constructor(options: HttpTransportOptions) {\n // Bind to globalThis: a bare `globalThis.fetch` reference loses its `this`\n // and browsers reject the detached call (\"Illegal invocation\").\n const fetchImpl =\n options.fetchImpl ??\n (typeof globalThis.fetch === 'function' ? (globalThis.fetch.bind(globalThis) as FetchLike) : undefined);\n if (!fetchImpl) {\n throw new CheckoutError('unknown', 'No fetch implementation available; pass options.fetchImpl.');\n }\n if (!options.auth?.publishableKey || !options.auth?.publicId) {\n throw new CheckoutError('unknown', 'HttpTransport requires `auth` with publishableKey and publicId.');\n }\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '');\n this.auth = options.auth;\n this.locale = options.locale;\n this.fetchImpl = fetchImpl;\n this.timeoutMs = options.timeoutMs ?? 20_000;\n }\n\n show(query?: ShowQuery): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('GET', this.path(''), {\n query: { country: query?.country, currency: query?.currency },\n });\n }\n\n countries(): Promise<CountriesResponse> {\n return this.request<CountriesResponse>('GET', this.path('/countries'));\n }\n\n pay(body: PayInput): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('POST', this.path('/pay'), { body });\n }\n\n authorize(body: AuthorizeInput): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('POST', this.path('/authorize'), { body });\n }\n\n poll(): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('GET', this.path('/poll'));\n }\n\n /**\n * Build the resource path: `/checkout/{publicId}{suffix}`.\n *\n * One surface shared by the hosted page and the SDK (backend PR #105):\n * `GET ''` (show), `POST /pay`, `POST /authorize`, `GET /poll`,\n * `GET /countries`. Scoped to the pk_'s project — a public_id from another\n * project returns 404 (the engine maps that to a terminal not_found).\n */\n private path(suffix: string): string {\n return `/checkout/${encodeURIComponent(this.auth.publicId)}${suffix}`;\n }\n\n private async request<T>(\n method: string,\n path: string,\n opts?: { query?: Record<string, string | undefined>; body?: unknown },\n ): Promise<T> {\n const url = this.baseUrl + path + this.queryString(opts?.query);\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const headers: Record<string, string> = { Accept: 'application/json' };\n if (this.locale) headers['Accept-Language'] = this.locale;\n headers.Authorization = `Bearer ${this.auth.publishableKey}`;\n if (opts?.body !== undefined) headers['Content-Type'] = 'application/json';\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method,\n headers,\n body: opts?.body === undefined ? undefined : JSON.stringify(opts.body),\n signal: controller.signal,\n });\n } catch (cause) {\n throw new CheckoutError('network', describeNetworkError(cause));\n } finally {\n clearTimeout(timer);\n }\n\n return this.parse<T>(response);\n }\n\n private async parse<T>(response: Response): Promise<T> {\n const text = await response.text().catch(() => '');\n let json: unknown;\n if (text) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n\n if (!response.ok) {\n const message = extractMessage(json) ?? `Request failed with status ${response.status}`;\n throw new CheckoutError(errorCodeFromStatus(response.status), message, response.status);\n }\n\n if (json === undefined) {\n throw new CheckoutError('unknown', 'Empty or non-JSON response body.', response.status);\n }\n return json as T;\n }\n\n private queryString(query?: Record<string, string | undefined>): string {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== '') params.set(key, value);\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n }\n}\n\nfunction extractMessage(json: unknown): string | undefined {\n if (json && typeof json === 'object' && 'message' in json) {\n const message = (json as { message: unknown }).message;\n if (typeof message === 'string') return message;\n }\n return undefined;\n}\n\nfunction describeNetworkError(cause: unknown): string {\n if (cause instanceof Error && cause.name === 'AbortError') return 'Request timed out.';\n if (cause instanceof Error) return cause.message;\n return 'Network request failed.';\n}\n","import type { HostedCheckout } from '../types/contract';\n\nimport type { CheckoutPhase } from './state';\n\n/**\n * Project server state into a phase. The SERVER owns the state machine; this is\n * a pure read-only projection. Order matters — first match wins.\n *\n * intent completed -> succeeded\n * intent failed/expired -> failed\n * session not open (not completed) -> closed\n * attempt action_required -> action_required\n * attempt processing -> processing\n * else (open, no/failed attempt) -> collecting (retry)\n */\nexport function derivePhase(checkout: HostedCheckout | null): CheckoutPhase {\n if (!checkout) return 'loading';\n\n const session = checkout.session.status;\n const intent = checkout.payment?.status;\n const attempt = checkout.attempt?.status;\n\n if (intent === 'completed') return 'succeeded';\n if (intent === 'failed' || intent === 'expired') return 'failed';\n\n if (session !== 'open') {\n return session === 'completed' ? 'succeeded' : 'closed';\n }\n\n // Session is open from here.\n if (attempt === 'action_required') return 'action_required';\n if (attempt === 'processing') return 'processing';\n\n // No attempt yet, or the last attempt failed/cancelled while the session is\n // still open: the customer can retry.\n return 'collecting';\n}\n\n/** Phases at which polling makes sense. */\nexport function isPollablePhase(phase: CheckoutPhase): boolean {\n return phase === 'processing' || phase === 'action_required';\n}\n\nexport function isTerminalPhase(phase: CheckoutPhase): boolean {\n return phase === 'succeeded' || phase === 'failed' || phase === 'closed';\n}\n","import type { AttemptSummary } from '../types/contract';\nimport type { NextAction } from '../types/next-action';\nimport type { ActionCompletion, CheckoutView, FormContext, ResultContext, WaitingContext } from '../types/view';\n\nimport type { EngineState } from './state';\n\n/**\n * Behavior mapping: given a next_action type, how does it complete? This is\n * the single place that decides submit/poll/redirect/sdk so a theme never has\n * to. Unknown types fail closed to `poll`.\n */\nexport function actionCompletion(action: NextAction): ActionCompletion {\n switch (action.type) {\n case 'collect_otp':\n return 'submit';\n case 'complete_with_sdk':\n return 'sdk';\n case 'redirect_to_url':\n return 'redirect';\n case 'embed_iframe':\n case 'approve_on_phone':\n case 'scan_qr_code':\n case 'display_payment_instructions':\n return 'poll';\n case 'none':\n return 'poll';\n default:\n // Unknown/forward-compat action type: wait and poll, never crash a theme.\n return 'poll';\n }\n}\n\n/** An action is renderable as an `action` view only if it asks for something. */\nfunction isActionable(action: NextAction | null): action is NextAction {\n return action !== null && action.type !== 'none';\n}\n\n/**\n * Pure projection: EngineState -> CheckoutView. No I/O, no mutation.\n */\nexport function projectView(state: EngineState): CheckoutView {\n const { phase, checkout, catalogue } = state;\n\n if (phase === 'loading') {\n return { kind: 'loading' };\n }\n if (!checkout) {\n // Forced terminal phase before any checkout loaded (e.g. 404 on first load).\n const kind = phase === 'succeeded' || phase === 'failed' ? phase : 'closed';\n return { kind, ctx: result(state, kind) };\n }\n\n const attempt = checkout.attempt;\n // Appearance is bootstrap-scoped now (not on show/pay/poll), so it lives in\n // engine state and is projected onto every view.\n const appearance = state.appearance;\n\n switch (phase) {\n case 'collecting': {\n if (!catalogue) return { kind: 'loading' };\n const ctx: FormContext = {\n amount: catalogue.amount,\n methods: catalogue.methods,\n country: catalogue.country,\n currencies: catalogue.currencies,\n supportsAnyCountry: catalogue.supportsAnyCountry,\n previousPhones: checkout.previous_used_phones ?? [],\n };\n if (checkout.restriction) ctx.restriction = checkout.restriction;\n if (checkout.customer) ctx.customer = checkout.customer;\n if (checkout.project) ctx.project = checkout.project;\n if (appearance) ctx.appearance = appearance;\n if (!state.dismissedError) {\n if (state.error) ctx.lastError = state.error;\n if (isFailedAttempt(attempt)) ctx.retryOf = attempt;\n }\n return { kind: 'form', ctx };\n }\n\n case 'action_required': {\n const action = attempt?.next_action ?? null;\n // action_required but nothing to render (null / none) -> wait + poll.\n if (!attempt || !isActionable(action)) {\n return attempt ? { kind: 'processing', ctx: waiting(state, attempt) } : { kind: 'loading' };\n }\n return {\n kind: 'action',\n ctx: {\n action,\n attempt,\n completion: actionCompletion(action),\n ...(catalogue ? { amount: catalogue.amount } : {}),\n ...(checkout.project ? { project: checkout.project } : {}),\n ...(appearance ? { appearance } : {}),\n },\n };\n }\n\n case 'processing': {\n return attempt ? { kind: 'processing', ctx: waiting(state, attempt) } : { kind: 'loading' };\n }\n\n case 'succeeded':\n return { kind: 'succeeded', ctx: result(state, 'succeeded') };\n\n case 'failed':\n return { kind: 'failed', ctx: result(state, 'failed') };\n\n case 'closed':\n return { kind: 'closed', ctx: result(state, 'closed') };\n\n default:\n return { kind: 'loading' };\n }\n}\n\nfunction isFailedAttempt(attempt: AttemptSummary | undefined): attempt is AttemptSummary {\n return attempt != null && (attempt.status === 'failed' || attempt.status === 'cancelled');\n}\n\nfunction waiting(state: EngineState, attempt: AttemptSummary): WaitingContext {\n const ctx: WaitingContext = { attempt };\n if (state.catalogue) ctx.amount = state.catalogue.amount;\n if (state.checkout?.project) ctx.project = state.checkout.project;\n if (state.appearance) ctx.appearance = state.appearance;\n return ctx;\n}\n\nfunction result(state: EngineState, kind: 'succeeded' | 'failed' | 'closed'): ResultContext {\n const checkout = state.checkout;\n\n // A closed checkout is closed because of the SESSION (expired/cancelled);\n // the intent may still read 'pending'. Success/failure come from the intent.\n const status =\n kind === 'closed'\n ? (checkout?.session.status ?? 'expired')\n : (checkout?.payment?.status ?? checkout?.session.status ?? 'expired');\n\n // For a failure, the customer-facing reason is the attempt's failure message,\n // not the generic envelope message. Terminal copy is otherwise the theme's job.\n const failureMessage = kind === 'failed' ? checkout?.attempt?.failure.message : undefined;\n\n let message = '';\n if (kind === 'failed') message = failureMessage ?? '';\n else if (kind === 'succeeded') message = state.message;\n const ctx: ResultContext = { status, message };\n if (checkout?.payment) ctx.payment = checkout.payment;\n if (state.catalogue) ctx.amount = state.catalogue.amount;\n if (checkout?.project) ctx.project = checkout.project;\n if (state.appearance) ctx.appearance = state.appearance;\n if (state.returnUrl) ctx.returnUrl = state.returnUrl;\n return ctx;\n}\n","import type { Appearance, Country, Currency, HostedCheckout, PaymentMethod, ResolvedAmount } from '../types/contract';\nimport type { CheckoutError } from '../types/errors';\n\n/**\n * The resolved catalogue is returned ONLY by `show`. `pay`/`authorize`/`poll`\n * omit it, so the engine caches the last good catalogue and re-fetches it only\n * when country/currency changes. See contract.ts › HostedCheckout.\n */\nexport interface ResolvedCatalogue {\n country: Country;\n currencies: Currency[];\n amount: ResolvedAmount;\n methods: PaymentMethod[];\n supportsAnyCountry: boolean;\n}\n\nexport type CheckoutPhase =\n | 'loading'\n | 'closed'\n | 'succeeded'\n | 'failed'\n | 'action_required'\n | 'processing'\n | 'collecting';\n\nexport interface EngineState {\n /** Last good catalogue from `show`. */\n catalogue: ResolvedCatalogue | null;\n /** Last response from any endpoint. */\n checkout: HostedCheckout | null;\n /** Server `message` from the last successful response. */\n message: string;\n phase: CheckoutPhase;\n error: CheckoutError | null;\n /**\n * The customer dismissed the current error banner (e.g. by reselecting a\n * method). Suppresses both banner sources (`lastError`, `retryOf`) until the\n * next server response, which resets it.\n */\n dismissedError: boolean;\n /**\n * Session-scoped chrome from the bootstrap payload. `appearance` is no longer\n * on show/pay/poll responses, so the engine holds it here and projects it on\n * every view. `returnUrl` (nullable, may be absent for old sessions) is the\n * merchant redirect target for the terminal \"return\" CTA.\n */\n appearance: Appearance | null;\n returnUrl: string | null;\n polling: boolean;\n}\n\nexport function initialState(): EngineState {\n return {\n catalogue: null,\n checkout: null,\n message: '',\n phase: 'loading',\n error: null,\n dismissedError: false,\n appearance: null,\n returnUrl: null,\n polling: false,\n };\n}\n\n/** Pull the catalogue out of a `show` response; null if not present. */\nexport function extractCatalogue(checkout: HostedCheckout): ResolvedCatalogue | null {\n const { country, currencies, amount, methods } = checkout;\n if (!country || !currencies || !amount || !methods) return null;\n return {\n country,\n currencies,\n amount,\n methods,\n supportsAnyCountry: checkout.supports_any_country ?? false,\n };\n}\n","import type { Appearance, AuthorizeInput, CountrySimplified, HostedCheckout, PayInput } from '../types/contract';\nimport { CheckoutError } from '../types/errors';\nimport type { CheckoutView } from '../types/view';\nimport type { Transport } from '../transport/transport';\n\nimport { derivePhase, isTerminalPhase } from './phase';\nimport { actionCompletion, projectView } from './project';\nimport { extractCatalogue, initialState, type EngineState } from './state';\n\nexport interface CheckoutEngineOptions {\n /** Auto-manage the polling loop based on phase. Default true. */\n autoPoll?: boolean;\n /** Backoff delays (ms) for the first polls. Default [2000,2000,3000,5000]. */\n pollIntervalsMs?: number[];\n /** Steady interval (ms) after the backoff ramp. Default 5000. */\n steadyIntervalMs?: number;\n /** Clock injection for tests. Default Date.now. */\n now?: () => number;\n /** Timer injection for tests. Default global setTimeout/clearTimeout. */\n setTimeoutImpl?: (cb: () => void, ms: number) => ReturnType<typeof setTimeout>;\n clearTimeoutImpl?: (handle: ReturnType<typeof setTimeout>) => void;\n}\n\ntype Listener = (view: CheckoutView) => void;\n\n/**\n * The engine facade themes consume. Owns state, the polling loop, and all\n * transport calls. Themes never see the Transport, the wire types, or the\n * token — only CheckoutView (via getView/subscribe) and these action methods.\n */\nexport class CheckoutEngine {\n private state: EngineState = initialState();\n private readonly listeners = new Set<Listener>();\n\n private readonly autoPoll: boolean;\n private readonly intervals: number[];\n private readonly steady: number;\n private readonly now: () => number;\n private readonly setTimeoutImpl: NonNullable<CheckoutEngineOptions['setTimeoutImpl']>;\n private readonly clearTimeoutImpl: NonNullable<CheckoutEngineOptions['clearTimeoutImpl']>;\n\n private pollHandle: ReturnType<typeof setTimeout> | null = null;\n private pollTick = 0;\n private pollInFlight = false;\n private destroyed = false;\n\n constructor(\n private readonly transport: Transport,\n options: CheckoutEngineOptions = {},\n ) {\n this.autoPoll = options.autoPoll ?? true;\n this.intervals = options.pollIntervalsMs ?? [2000, 2000, 3000, 5000];\n this.steady = options.steadyIntervalMs ?? 5000;\n this.now = options.now ?? Date.now;\n this.setTimeoutImpl = options.setTimeoutImpl ?? ((cb, ms) => setTimeout(cb, ms));\n this.clearTimeoutImpl = options.clearTimeoutImpl ?? ((handle) => clearTimeout(handle));\n }\n\n // --- read surface ---\n\n getView(): CheckoutView {\n return projectView(this.state);\n }\n\n /** Subscribe to view changes. Fires immediately with the current view. */\n subscribe(fn: Listener): () => void {\n this.listeners.add(fn);\n fn(this.getView());\n return () => {\n this.listeners.delete(fn);\n };\n }\n\n // --- actions ---\n\n /**\n * Seed state from a server-fetched `show` payload (SSR) so the first paint is\n * the form, not the loading screen — no transport call. The host passes the\n * `GET /checkout/{public_id}` payload the SSR layer fetched after bootstrap.\n * Treated exactly like a `show`, so the resolved catalogue is cached. The\n * engine may still `poll()`/`load()` afterwards to refresh.\n */\n hydrate(checkout: HostedCheckout, message = ''): void {\n this.applyResponse(checkout, message, true);\n }\n\n /**\n * Seed session-scoped chrome from the SSR bootstrap payload. `appearance` and\n * `return_url` no longer ride on show/pay/poll responses, so the host passes\n * them once here and the engine projects them onto every view. Call before the\n * first render (alongside `hydrate`) so the theme paints branded from frame 1.\n */\n seedBootstrap(input: { appearance?: Appearance | null; returnUrl?: string | null }): void {\n const next: Partial<EngineState> = {};\n if (input.appearance) next.appearance = input.appearance;\n if (input.returnUrl !== undefined) next.returnUrl = input.returnUrl;\n if (Object.keys(next).length > 0) this.setState(next);\n }\n\n async load(): Promise<void> {\n await this.runShow(undefined);\n }\n\n async selectCountry(country: string): Promise<void> {\n await this.runShow({ country });\n }\n\n async selectCurrency(currency: string): Promise<void> {\n // Preserve the resolved country. Sending `currency` alone makes the server\n // re-resolve the country to its default, silently switching it — the bug when\n // a country exposes more than one currency (e.g. CD: CDF/USD). `selectCountry`\n // deliberately omits currency so the server picks the new country's default.\n const country = this.state.catalogue?.country.code;\n await this.runShow(country ? { country, currency } : { currency });\n }\n\n /** Full selectable country catalogue for the picker (not part of the view). */\n async listCountries(): Promise<CountrySimplified[]> {\n try {\n const res = await this.transport.countries();\n return res.data;\n } catch (cause) {\n this.setError(cause);\n return [];\n }\n }\n\n async pay(input: PayInput): Promise<void> {\n await this.runMutation(() => this.transport.pay(this.withCatalogueDefaults(input)), false);\n }\n\n /**\n * Dismiss the current error banner (both `lastError` and a failed-attempt\n * `retryOf`). Themes call this when the customer selects a method again so a\n * stale error doesn't linger; the next server response clears the dismissal.\n */\n clearError(): void {\n if (this.state.error === null && this.state.dismissedError) return;\n this.setState({ error: null, dismissedError: true });\n }\n\n async authorize(input: AuthorizeInput): Promise<void> {\n await this.runMutation(() => this.transport.authorize(input), false);\n }\n\n async poll(): Promise<void> {\n await this.runMutation(() => this.transport.poll(), false);\n }\n\n /** Called when the customer returns from an external redirect. Just polls. */\n async resumeFromRedirect(): Promise<void> {\n await this.poll();\n }\n\n // --- polling control (host wires visibility/focus to these) ---\n\n startPolling(): void {\n if (this.destroyed || this.state.polling) return;\n this.setState({ polling: true });\n this.pollTick = 0;\n this.scheduleNextPoll();\n }\n\n stopPolling(): void {\n if (this.pollHandle !== null) {\n this.clearTimeoutImpl(this.pollHandle);\n this.pollHandle = null;\n }\n if (this.state.polling) this.setState({ polling: false });\n }\n\n destroy(): void {\n this.destroyed = true;\n this.stopPolling();\n this.listeners.clear();\n }\n\n // --- internals ---\n\n private async runShow(query: { country?: string; currency?: string } | undefined): Promise<void> {\n try {\n const res = await this.transport.show(query);\n this.applyResponse(res.data, res.message ?? '', true);\n } catch (cause) {\n this.setError(cause);\n }\n }\n\n private async runMutation(\n call: () => Promise<{ data: HostedCheckout; message?: string }>,\n isShow: boolean,\n ): Promise<void> {\n try {\n const res = await call();\n this.applyResponse(res.data, res.message ?? '', isShow);\n } catch (cause) {\n this.setError(cause);\n }\n }\n\n /**\n * Stamp the pay payload with the currently-resolved country/currency from the\n * cached catalogue. Themes call `selectCountry`/`selectCurrency` (which refetch\n * the catalogue) but never thread that selection back into `pay` — without this\n * the server falls back to its default country and rejects methods that aren't\n * available there. A value already on the input always wins; currency is only\n * stamped when DCC is in effect (the only time the server expects it).\n */\n private withCatalogueDefaults(input: PayInput): PayInput {\n const catalogue = this.state.catalogue;\n if (!catalogue) return input;\n\n const next: PayInput = { ...input };\n if (next.country === undefined) next.country = catalogue.country.code;\n if (next.currency === undefined && catalogue.amount.is_dcc) {\n const currency = catalogue.amount.final.currency;\n if (currency) next.currency = currency;\n }\n return next;\n }\n\n private applyResponse(checkout: HostedCheckout, message: string, isShow: boolean): void {\n const next: Partial<EngineState> = {\n checkout,\n message,\n phase: derivePhase(checkout),\n error: null,\n // A fresh response (incl. a new failed attempt) is shown, not suppressed.\n dismissedError: false,\n };\n if (isShow) {\n const catalogue = extractCatalogue(checkout);\n if (catalogue) next.catalogue = catalogue;\n }\n this.setState(next);\n this.reconcilePolling();\n }\n\n private setError(cause: unknown): void {\n const error = cause instanceof CheckoutError ? cause : new CheckoutError('unknown', toMessage(cause));\n\n // Terminal errors close the checkout; recoverable ones keep the phase so the\n // theme can show the message inline (e.g. 422 on pay stays in `collecting`).\n const isTerminalError = error.code === 'not_found' || error.code === 'not_open';\n const keepPhase = !isTerminalError && this.state.checkout;\n const phase: EngineState['phase'] = keepPhase ? this.state.phase : 'closed';\n\n this.setState({ error, phase, message: error.message, dismissedError: false });\n this.reconcilePolling();\n }\n\n private reconcilePolling(): void {\n if (!this.autoPoll || this.destroyed) return;\n if (isTerminalPhase(this.state.phase)) {\n this.stopPolling();\n return;\n }\n if (this.shouldPoll()) {\n this.startPolling();\n } else {\n this.stopPolling();\n }\n }\n\n /**\n * Poll while an attempt is `processing`, or while it is `action_required`\n * with a poll-completion action (approve_on_phone, scan_qr_code,\n * display_payment_instructions, embed_iframe). Do NOT poll while waiting on\n * the customer to submit (collect_otp), redirect, or run an SDK.\n */\n private shouldPoll(): boolean {\n if (this.state.phase === 'processing') return true;\n if (this.state.phase === 'action_required') {\n const action = this.state.checkout?.attempt?.next_action;\n return action != null && actionCompletion(action) === 'poll';\n }\n return false;\n }\n\n private scheduleNextPoll(): void {\n if (this.destroyed || !this.state.polling) return;\n\n const delay = this.intervals[this.pollTick] ?? this.steady;\n this.pollTick++;\n\n // Cap to session expiry: stop scheduling once we're past expires_at.\n const expiresAt = this.expiresAtMs();\n if (expiresAt !== null && this.now() >= expiresAt) {\n this.stopPolling();\n return;\n }\n\n this.pollHandle = this.setTimeoutImpl(() => {\n this.tickPoll().catch(() => undefined);\n }, delay);\n }\n\n private async tickPoll(): Promise<void> {\n if (this.destroyed || !this.state.polling || this.pollInFlight) return;\n this.pollInFlight = true;\n try {\n await this.poll();\n } finally {\n this.pollInFlight = false;\n }\n // poll() -> applyResponse -> reconcilePolling may have stopped us.\n if (this.state.polling && !isTerminalPhase(this.state.phase)) {\n this.scheduleNextPoll();\n }\n }\n\n private expiresAtMs(): number | null {\n const raw = this.state.checkout?.session.expires_at;\n if (!raw) return null;\n const ms = Date.parse(raw);\n return Number.isNaN(ms) ? null : ms;\n }\n\n private setState(partial: Partial<EngineState>): void {\n this.state = { ...this.state, ...partial };\n this.emit();\n }\n\n private emit(): void {\n const view = this.getView();\n for (const listener of this.listeners) listener(view);\n }\n}\n\nfunction toMessage(cause: unknown): string {\n if (cause instanceof Error) return cause.message;\n return 'Unexpected error.';\n}\n","import type { RedirectToUrlAction } from '@orqex/checkout-engine';\n\ninterface RedirectEffectDeps {\n /** Top-level navigation for GET redirects. Default window.location.assign. */\n navigate?: (url: string) => void;\n /** Injectable document for tests. Default global document. */\n doc?: Document;\n}\n\n/**\n * Execute a redirect next-action in a headless page. GET navigates the\n * top-level document; POST auto-submits a hidden form (some 3-D Secure ACS\n * endpoints). Refuses any non-https URL as defense-in-depth — the primary trust\n * boundary is the server, but we never navigate to javascript:/data: schemes.\n */\nexport function performActionRedirect(action: RedirectToUrlAction, deps: RedirectEffectDeps = {}): void {\n const doc = deps.doc ?? document;\n const navigate = deps.navigate ?? ((url: string) => window.location.assign(url));\n\n if (!isHttps(action.url)) {\n // eslint-disable-next-line no-console\n console.error(`Orqex: refused redirect to non-https URL \"${action.url}\".`);\n return;\n }\n\n if (action.method === 'POST') {\n const form = doc.createElement('form');\n form.method = 'POST';\n form.action = action.url;\n form.style.display = 'none';\n for (const [name, value] of Object.entries(action.post_data ?? {})) {\n const input = doc.createElement('input');\n input.type = 'hidden';\n input.name = name;\n input.value = typeof value === 'string' ? value : JSON.stringify(value);\n form.appendChild(input);\n }\n doc.body.appendChild(form);\n form.submit();\n return;\n }\n\n navigate(action.url);\n}\n\nfunction isHttps(url: string): boolean {\n try {\n return new URL(url).protocol === 'https:';\n } catch {\n return false;\n }\n}\n","import {\n CheckoutEngine,\n HttpTransport,\n type AuthorizeInput,\n type CheckoutView,\n type CountrySimplified,\n type PayInput,\n type RedirectToUrlAction,\n} from '@orqex/checkout-engine';\n\nimport type { ResolvedConfig } from './config';\nimport { performActionRedirect } from './redirect-effect';\n\nexport interface CreateEngineOptions {\n /** cs_… checkout handle minted server-side by the merchant. */\n publicId: string;\n /** BCP-47 locale for Accept-Language. Default navigator.language. */\n locale?: string;\n /**\n * When true, the SDK persists publicId across a redirect and auto-resumes on\n * return, and auto-performs redirect actions. Default false (fully manual).\n */\n autoResume?: boolean;\n}\n\n/** Narrowed, browser-facing surface over CheckoutEngine. Cross-SDK contract. */\nexport interface OrqexCheckout {\n subscribe(fn: (view: CheckoutView) => void): () => void;\n getView(): CheckoutView;\n pay(input: PayInput): Promise<void>;\n authorize(input: AuthorizeInput): Promise<void>;\n poll(): Promise<void>;\n selectCountry(country: string): Promise<void>;\n selectCurrency(currency: string): Promise<void>;\n listCountries(): Promise<CountrySimplified[]>;\n /** Poll the current server state (call on return from an external redirect). */\n resumeFromRedirect(): Promise<void>;\n startPolling(): void;\n stopPolling(): void;\n /** Perform the pending redirect action; no-op if the current view is not one. */\n performRedirect(): void;\n destroy(): void;\n}\n\nexport interface HeadlessDeps {\n /** Injected engine for tests; when omitted a real one is built. */\n engine?: CheckoutEngine;\n /** Injectable window for tests. Default global window. */\n win?: Window;\n /** Injectable storage for autoResume tests. Default window.sessionStorage. */\n storage?: Storage;\n /** Injectable fetch passed to HttpTransport. Default global fetch. */\n fetchImpl?: (input: string, init?: RequestInit) => Promise<Response>;\n}\n\n/** Extract the current redirect action from a view, or null. */\nfunction redirectActionOf(view: CheckoutView): RedirectToUrlAction | null {\n if (view.kind === 'action' && view.ctx.completion === 'redirect' && view.ctx.action.type === 'redirect_to_url') {\n return view.ctx.action;\n }\n return null;\n}\n\nconst markerKey = (publicId: string): string => `orqex:redirect:${publicId}`;\n\nfunction wireAutoResume(engine: CheckoutEngine, publicId: string, ctx: { storage: Storage; win: Window }): () => void {\n const key = markerKey(publicId);\n\n // Returning from a redirect: a pending marker means we just came back.\n if (ctx.storage.getItem(key) !== null) {\n ctx.storage.removeItem(key);\n engine.resumeFromRedirect();\n }\n\n // Auto-perform the redirect once per (attempt, action).\n let handled: string | null = null;\n const unsubscribe = engine.subscribe((view) => {\n const action = redirectActionOf(view);\n if (!action || !action.can_auto_redirect || view.kind !== 'action') return;\n const dedupe = `${view.ctx.attempt.id}:${action.type}`;\n if (handled === dedupe) return;\n handled = dedupe;\n ctx.storage.setItem(key, view.ctx.attempt.id);\n performActionRedirect(action, { navigate: (url) => ctx.win.location.assign(url), doc: ctx.win.document });\n });\n\n const onPageShow = (): void => {\n const kind = engine.getView().kind;\n if (kind === 'action' || kind === 'processing') engine.resumeFromRedirect();\n };\n ctx.win.addEventListener('pageshow', onPageShow);\n\n return () => {\n unsubscribe();\n ctx.win.removeEventListener('pageshow', onPageShow);\n };\n}\n\n/**\n * Build the headless checkout: a real CheckoutEngine over HttpTransport (pk_),\n * wrapped in the narrowed OrqexCheckout facade. Manual mode; autoResume wiring\n * is conditionally applied when `options.autoResume` is true.\n */\nexport function createHeadlessCheckout(\n config: ResolvedConfig,\n options: CreateEngineOptions,\n deps: HeadlessDeps = {},\n): OrqexCheckout {\n const win = deps.win ?? window;\n const engine =\n deps.engine ??\n new CheckoutEngine(\n new HttpTransport({\n baseUrl: config.apiBaseUrl,\n auth: { publishableKey: config.publishableKey, publicId: options.publicId },\n locale: options.locale ?? (typeof navigator === 'undefined' ? undefined : navigator.language),\n fetchImpl: deps.fetchImpl,\n }),\n );\n\n let autoResumeTeardown: () => void = () => {};\n\n const facade: OrqexCheckout = {\n subscribe: (fn) => engine.subscribe(fn),\n getView: () => engine.getView(),\n pay: (input) => engine.pay(input),\n authorize: (input) => engine.authorize(input),\n poll: () => engine.poll(),\n selectCountry: (country) => engine.selectCountry(country),\n selectCurrency: (currency) => engine.selectCurrency(currency),\n listCountries: () => engine.listCountries(),\n resumeFromRedirect: () => engine.resumeFromRedirect(),\n startPolling: () => engine.startPolling(),\n stopPolling: () => engine.stopPolling(),\n performRedirect: () => {\n const action = redirectActionOf(engine.getView());\n if (action) performActionRedirect(action, { navigate: (url) => win.location.assign(url), doc: win.document });\n },\n destroy: () => {\n autoResumeTeardown();\n engine.destroy();\n },\n };\n\n if (options.autoResume) {\n autoResumeTeardown = wireAutoResume(engine, options.publicId, { storage: deps.storage ?? win.sessionStorage, win });\n }\n\n engine.load();\n return facade;\n}\n","import { buildRedirectUrl, type ResolvedConfig } from './config';\n\nexport interface RedirectOptions {\n /** cs_… checkout handle minted server-side by the merchant. */\n publicId: string;\n}\n\ntype Navigate = (url: string) => void;\n\nconst defaultNavigate: Navigate = (url) => {\n window.location.assign(url);\n};\n\n/** Full-page navigation to the hosted checkout. */\nexport function redirectToCheckout(\n config: ResolvedConfig,\n options: RedirectOptions,\n navigate: Navigate = defaultNavigate,\n): void {\n if (!options.publicId) {\n throw new Error('Orqex: redirectToCheckout requires a publicId.');\n }\n navigate(buildRedirectUrl(config, options.publicId));\n}\n","import { resolveConfig, type OrqexOptions } from './config';\nimport { EmbeddedController, type MountOptions } from './embedded';\nimport { EventBus, type EventPayloads, type MerchantEvent } from './event-bus';\nimport { createHeadlessCheckout, type CreateEngineOptions, type OrqexCheckout } from './headless';\nimport { redirectToCheckout, type RedirectOptions } from './redirect';\n\nexport interface OrqexInstance {\n /** Embedded mode: hosted checkout in a sandboxed iframe. */\n mount(target: string | HTMLElement, options: MountOptions): void;\n /** Redirect mode: full-page navigation to the hosted checkout. */\n redirectToCheckout(options: RedirectOptions): void;\n /** Subscribe to a lifecycle event; returns a disposer. */\n on<TEvent extends MerchantEvent>(event: TEvent, handler: (payload: EventPayloads[TEvent]) => void): () => void;\n /** Tear down the embedded iframe and its listener (no-op in redirect mode). */\n unmount(): void;\n /** Headless mode: run the engine in this page and render your own UI. */\n createEngine(options: CreateEngineOptions): OrqexCheckout;\n}\n\n/**\n * SDK entry point. `Orqex('pk_…')` validates the key, then exposes embedded,\n * redirect, and headless (`createEngine`) modes over one event bus.\n */\nexport function Orqex(publishableKey: string, options?: OrqexOptions): OrqexInstance {\n const config = resolveConfig(publishableKey, options);\n const bus = new EventBus();\n const embedded = new EmbeddedController({ config, bus });\n\n return {\n mount(target, mountOptions) {\n embedded.mount(target, mountOptions);\n },\n redirectToCheckout(redirectOptions) {\n redirectToCheckout(config, redirectOptions);\n },\n on(event, handler) {\n return bus.on(event, handler);\n },\n unmount() {\n embedded.unmount();\n },\n createEngine(engineOptions) {\n return createHeadlessCheckout(config, engineOptions);\n },\n };\n}\n","import type { CheckoutView } from '@orqex/checkout-engine';\n\nimport { closeMessage, errorMessage, successMessage, type EmbedMessage } from './protocol';\n\nexport interface EmbedProjection {\n message: EmbedMessage;\n /** Dedup key so the host posts each terminal state at most once. */\n key: string;\n}\n\n/**\n * Pure mapping from the engine's projected view to an embed lifecycle message.\n * Terminal views only; `redirect` is handled by the host's redirect override\n * (a redirect action is not a terminal view). Returns null when there is\n * nothing new to post or `key` equals `lastKey`.\n */\nexport function projectEmbedMessage(view: CheckoutView, lastKey: string | null): EmbedProjection | null {\n let projection: EmbedProjection | null = null;\n\n if (view.kind === 'succeeded') {\n const status = String(view.ctx.status);\n projection = { message: successMessage(status), key: `succeeded:${status}` };\n } else if (view.kind === 'failed') {\n const status = String(view.ctx.status);\n projection = { message: errorMessage(status, view.ctx.message), key: `failed:${status}` };\n } else if (view.kind === 'closed') {\n const status = String(view.ctx.status);\n projection = { message: closeMessage(status), key: `closed:${status}` };\n }\n\n if (!projection || projection.key === lastKey) return null;\n return projection;\n}\n","/**\n * @orqex/checkout-js — client-side SDK for Orqex payments.\n *\n * Browser-host glue over the existing engine + hosted checkout. Never accepts a\n * secret key; the publishable key (pk_) is public by design.\n */\n\nexport const SDK_VERSION = '0.0.1';\n\nexport { Orqex } from './orqex';\nexport type { OrqexInstance } from './orqex';\nexport type { OrqexOptions } from './config';\nexport type { MountOptions } from './embedded';\nexport type { RedirectOptions } from './redirect';\nexport type { MerchantEvent, EventPayloads } from './event-bus';\nexport type { OrqexCheckout, CreateEngineOptions } from './headless';\n// Engine contract re-exported so headless merchants render against the typed view.\nexport type { CheckoutView, PayInput, AuthorizeInput, CountrySimplified } from '@orqex/checkout-engine';\n\n// Embed protocol + view→message projection: re-exported so the hosted app\n// (checkout-next) imports the single source of truth for the wire contract.\nexport * from './protocol';\nexport { projectEmbedMessage } from './embed-projection';\nexport type { EmbedProjection } from './embed-projection';\n"]}
1
+ {"version":3,"sources":["../src/key.ts","../src/config.ts","../src/embedded.ts","../src/event-bus.ts","../../engine/src/types/errors.ts","../../engine/src/transport/http-transport.ts","../../engine/src/engine/phase.ts","../../engine/src/engine/project.ts","../../engine/src/engine/state.ts","../../engine/src/engine/engine.ts","../src/redirect-effect.ts","../src/headless.ts","../src/redirect.ts","../src/orqex.ts","../src/embed-projection.ts","../src/index.ts"],"names":[],"mappings":";;;;AAMA,IAAM,UAAA,GAAa,+BAAA;AAOZ,SAAS,oBAAoB,GAAA,EAAwB;AAC1D,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,CAAC,UAAA,CAAW,IAAA,CAAK,GAAG,CAAA,EAAG;AACpD,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;A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A,CAAa,MAAA,EAAQ,IAAA,CAAK,GAAA,CAAI,OAAO,CAAA,EAAG,GAAA,EAAK,CAAA,OAAA,EAAU,MAAM,CAAA,CAAA,EAAG;AAAA,EAC1F,CAAA,MAAA,IAAW,IAAA,CAAK,IAAA,KAAS,QAAA,EAAU;AACjC,IAAA,MAAM,MAAA,GAAS,MAAA,CAAO,IAAA,CAAK,GAAA,CAAI,MAAM,CAAA;AACrC,IAAA,UAAA,GAAa,EAAE,SAAS,YAAA,CAAa,MAAM,GAAG,GAAA,EAAK,CAAA,OAAA,EAAU,MAAM,CAAA,CAAA,EAAG;AAAA,EACxE;AAEA,EAAA,IAAI,CAAC,UAAA,IAAc,UAAA,CAAW,GAAA,KAAQ,SAAS,OAAO,IAAA;AACtD,EAAA,OAAO,UAAA;AACT;;;ACzBO,IAAM,WAAA,GAAc","file":"index.js","sourcesContent":["/** Parsed publishable key: the raw string plus the environment it targets. */\nexport interface ParsedKey {\n key: string;\n livemode: boolean;\n}\n\nconst PK_PATTERN = /^pk_(live|test)_[A-Za-z0-9]+$/;\n\n/**\n * Validate the client key shape. Only `pk_live_…` / `pk_test_…` are accepted;\n * anything else (empty, `sk_…`, M2M secret, malformed) throws. The publishable\n * key is public by design, so no value here is treated as sensitive.\n */\nexport function parsePublishableKey(key: string): ParsedKey {\n if (typeof key !== 'string' || !PK_PATTERN.test(key)) {\n throw new Error(\n 'Orqex: a publishable key (\"pk_live_…\" or \"pk_test_…\") is required. Never pass a secret key to the browser.',\n );\n }\n return { key, livemode: key.startsWith('pk_live_') };\n}\n","import { parsePublishableKey } from './key';\n\n/**\n * Default hosted-checkout origin. PLACEHOLDER — confirm the real production\n * origin before release; merchants can always override via\n * `Orqex(pk, { checkoutBaseUrl })`.\n */\nexport const DEFAULT_CHECKOUT_BASE_URL = 'https://checkout.orqex.com';\n\n/**\n * Default API origin the headless engine calls with pk_. PLACEHOLDER — confirm\n * the real production API origin before release; override via\n * `Orqex(pk, { apiBaseUrl })`.\n */\nexport const DEFAULT_API_BASE_URL = 'https://api.orqex.com';\n\nexport interface OrqexOptions {\n /** Override the hosted-checkout origin (e.g. a staging or self-hosted deploy). */\n checkoutBaseUrl?: string;\n /** Override the API origin the headless engine calls (e.g. staging). */\n apiBaseUrl?: string;\n}\n\nexport interface ResolvedConfig {\n publishableKey: string;\n livemode: boolean;\n /** Hosted-checkout base, no trailing slash. */\n checkoutBaseUrl: string;\n /** Origin of `checkoutBaseUrl`; the only origin we accept inbound messages from. */\n checkoutOrigin: string;\n /** API origin for headless engine requests, no trailing slash. */\n apiBaseUrl: string;\n}\n\nexport function resolveConfig(publishableKey: string, options: OrqexOptions = {}): ResolvedConfig {\n const { key, livemode } = parsePublishableKey(publishableKey);\n const raw = options.checkoutBaseUrl ?? DEFAULT_CHECKOUT_BASE_URL;\n const checkoutBaseUrl = raw.replace(/\\/+$/, '');\n let checkoutOrigin: string;\n try {\n checkoutOrigin = new URL(checkoutBaseUrl).origin;\n } catch {\n throw new Error(`Orqex: invalid checkoutBaseUrl \"${raw}\".`);\n }\n const apiBaseUrl = (options.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\\/+$/, '');\n return { publishableKey: key, livemode, checkoutBaseUrl, checkoutOrigin, apiBaseUrl };\n}\n\nexport function buildEmbedUrl(config: ResolvedConfig, publicId: string, parentOrigin: string): string {\n const id = encodeURIComponent(publicId);\n return `${config.checkoutBaseUrl}/${id}?embed=1&origin=${encodeURIComponent(parentOrigin)}`;\n}\n\nexport function buildRedirectUrl(config: ResolvedConfig, publicId: string): string {\n return `${config.checkoutBaseUrl}/${encodeURIComponent(publicId)}`;\n}\n","import { buildEmbedUrl, type ResolvedConfig } from './config';\nimport type { EventBus } from './event-bus';\nimport { isEmbedMessage, type EmbedMessage } from './protocol';\n\nexport interface MountOptions {\n publicId: string;\n}\n\nexport interface EmbeddedControllerDeps {\n config: ResolvedConfig;\n bus: EventBus;\n /** Injectable for tests; defaults to the global window. */\n win?: Window;\n /** Top-level navigation for redirect messages; injectable for tests. */\n navigate?: (url: string) => void;\n}\n\nconst SANDBOX = 'allow-scripts allow-same-origin allow-forms allow-popups';\n\n/**\n * Owns the sandboxed hosted-checkout iframe: creation, the origin-guarded\n * message listener, auto-resize, redirect bubbling, and teardown.\n */\nexport class EmbeddedController {\n private readonly config: ResolvedConfig;\n private readonly bus: EventBus;\n private readonly win: Window;\n private readonly navigate: (url: string) => void;\n\n private iframe: HTMLIFrameElement | null = null;\n private listener: ((event: MessageEvent) => void) | null = null;\n\n constructor(deps: EmbeddedControllerDeps) {\n this.config = deps.config;\n this.bus = deps.bus;\n this.win = deps.win ?? window;\n this.navigate = deps.navigate ?? ((url) => this.win.location.assign(url));\n }\n\n mount(target: string | HTMLElement, options: MountOptions): void {\n if (!options.publicId) throw new Error('Orqex: mount requires a publicId.');\n const host = this.resolveHost(target);\n this.unmount();\n\n const iframe = this.win.document.createElement('iframe');\n iframe.src = buildEmbedUrl(this.config, options.publicId, this.win.location.origin);\n iframe.setAttribute('sandbox', SANDBOX);\n iframe.setAttribute('allow', 'payment');\n iframe.setAttribute('title', 'Orqex Checkout');\n iframe.style.width = '100%';\n iframe.style.border = 'none';\n iframe.style.height = '150px';\n host.appendChild(iframe);\n this.iframe = iframe;\n\n const listener = (event: MessageEvent): void => {\n if (event.origin !== this.config.checkoutOrigin) return;\n if (event.source !== iframe.contentWindow) return;\n if (!isEmbedMessage(event.data)) return;\n this.handle(event.data);\n };\n this.win.addEventListener('message', listener);\n this.listener = listener;\n }\n\n unmount(): void {\n if (this.listener) {\n this.win.removeEventListener('message', this.listener);\n this.listener = null;\n }\n if (this.iframe) {\n this.iframe.remove();\n this.iframe = null;\n }\n }\n\n private handle(message: EmbedMessage): void {\n switch (message.type) {\n case 'resize':\n if (this.iframe) this.iframe.style.height = `${message.height}px`;\n break;\n case 'success':\n this.bus.emit('success', { status: message.status });\n break;\n case 'error':\n this.bus.emit('error', { code: message.code, message: message.message });\n break;\n case 'close':\n this.bus.emit('close', { status: message.status });\n break;\n case 'redirect':\n // The iframe cannot navigate the top window; the SDK does it here.\n this.bus.emit('redirect', { url: message.url });\n this.navigate(message.url);\n break;\n case 'ready':\n break;\n }\n }\n\n private resolveHost(target: string | HTMLElement): HTMLElement {\n const host = typeof target === 'string' ? this.win.document.querySelector<HTMLElement>(target) : target;\n if (!host) throw new Error(`Orqex: mount target \"${String(target)}\" not found.`);\n return host;\n }\n}\n","/** Merchant-facing lifecycle events for embedded/redirect modes. */\nexport type MerchantEvent = 'success' | 'error' | 'redirect' | 'close';\n\nexport interface EventPayloads {\n success: { status: string };\n error: { code: string; message: string };\n redirect: { url: string };\n close: { status: string };\n}\n\ntype Handler<TEvent extends MerchantEvent> = (payload: EventPayloads[TEvent]) => void;\n\n/**\n * Minimal typed pub/sub. A handler that throws is caught and logged so a single\n * bad merchant callback cannot break delivery to the others.\n */\nexport class EventBus {\n private readonly handlers: { [TEvent in MerchantEvent]: Set<Handler<TEvent>> } = {\n success: new Set(),\n error: new Set(),\n redirect: new Set(),\n close: new Set(),\n };\n\n on<TEvent extends MerchantEvent>(event: TEvent, handler: Handler<TEvent>): () => void {\n this.handlers[event].add(handler);\n return () => this.off(event, handler);\n }\n\n off<TEvent extends MerchantEvent>(event: TEvent, handler: Handler<TEvent>): void {\n this.handlers[event].delete(handler);\n }\n\n emit<TEvent extends MerchantEvent>(event: TEvent, payload: EventPayloads[TEvent]): void {\n for (const handler of this.handlers[event]) {\n try {\n handler(payload);\n } catch (cause) {\n // eslint-disable-next-line no-console\n console.error(`Orqex: \"${event}\" event handler threw`, cause);\n }\n }\n }\n}\n","/**\n * Typed error model. The envelope `message` from the server is customer-safe\n * and is carried through verbatim.\n */\n\nexport const CHECKOUT_ERROR_CODE = [\n // 404: token unknown or expired\n 'not_found',\n // 400: session not open\n 'not_open',\n // 422: validation / intent final / restriction\n 'unprocessable',\n // 429: throttle:60,1\n 'rate_limited',\n // transport failure / no response\n 'network',\n 'unknown',\n] as const;\nexport type CheckoutErrorCode = (typeof CHECKOUT_ERROR_CODE)[number];\n\nexport class CheckoutError extends Error {\n readonly code: CheckoutErrorCode;\n readonly httpStatus?: number;\n\n constructor(code: CheckoutErrorCode, message: string, httpStatus?: number) {\n super(message);\n this.name = 'CheckoutError';\n this.code = code;\n this.httpStatus = httpStatus;\n }\n}\n\nexport function errorCodeFromStatus(status: number): CheckoutErrorCode {\n switch (status) {\n case 400:\n return 'not_open';\n case 404:\n return 'not_found';\n case 422:\n return 'unprocessable';\n case 429:\n return 'rate_limited';\n default:\n return status >= 500 ? 'network' : 'unknown';\n }\n}\n\n/** Terminal errors close the checkout; others are recoverable in-place. */\nexport function isTerminalError(code: CheckoutErrorCode): boolean {\n return code === 'not_found' || code === 'not_open';\n}\n","import type {\n AuthorizeInput,\n CountriesResponse,\n Envelope,\n HostedCheckout,\n PayInput,\n ShowQuery,\n} from '../types/contract';\nimport { CheckoutError, errorCodeFromStatus } from '../types/errors';\n\nimport type { Transport } from './transport';\n\ntype FetchLike = (input: string, init?: RequestInit) => Promise<Response>;\n\n/**\n * Publishable-key auth (Stripe-aligned, backend PR #105 onward).\n *\n * `publishableKey` is the project `pk_...`, obtained server-side via the M2M\n * `/checkout/bootstrap` call and handed to the client. It is sent as\n * `Authorization: Bearer pk_...` on every checkout request. `publicId` is the\n * `cs_...` CheckoutSession pointer, addressed as `/checkout/{publicId}`.\n *\n * `pk_` is publishable: client exposure is expected. No secret ever reaches the\n * browser, so nothing here needs to be hidden from the instance.\n */\nexport interface PublishableKeyAuth {\n /** pk_... project publishable key. */\n publishableKey: string;\n /** cs_... CheckoutSession public id. */\n publicId: string;\n}\n\nexport interface HttpTransportOptions {\n /** API base, e.g. \"https://api.orqex.com\". No trailing slash required. */\n baseUrl: string;\n /** Publishable-key auth (pk_ + public_id). */\n auth: PublishableKeyAuth;\n /** BCP-47 language for Accept-Language (e.g. from appearance.lang). */\n locale?: string;\n /** Injectable fetch (defaults to global). Keeps the engine env-agnostic. */\n fetchImpl?: FetchLike;\n /** Per-request timeout in ms. Default 20000. */\n timeoutMs?: number;\n}\n\n/**\n * Real transport against the hosted-checkout endpoints.\n *\n * Auth is `Bearer pk_` against `/checkout/{publicId}`. Errors map to\n * CheckoutError; the server's `message` is preserved for customer display.\n */\nexport class HttpTransport implements Transport {\n private readonly baseUrl: string;\n private readonly auth: PublishableKeyAuth;\n private readonly locale?: string;\n private readonly fetchImpl: FetchLike;\n private readonly timeoutMs: number;\n\n constructor(options: HttpTransportOptions) {\n // Bind to globalThis: a bare `globalThis.fetch` reference loses its `this`\n // and browsers reject the detached call (\"Illegal invocation\").\n const fetchImpl =\n options.fetchImpl ??\n (typeof globalThis.fetch === 'function' ? (globalThis.fetch.bind(globalThis) as FetchLike) : undefined);\n if (!fetchImpl) {\n throw new CheckoutError('unknown', 'No fetch implementation available; pass options.fetchImpl.');\n }\n if (!options.auth?.publishableKey || !options.auth?.publicId) {\n throw new CheckoutError('unknown', 'HttpTransport requires `auth` with publishableKey and publicId.');\n }\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '');\n this.auth = options.auth;\n this.locale = options.locale;\n this.fetchImpl = fetchImpl;\n this.timeoutMs = options.timeoutMs ?? 20_000;\n }\n\n show(query?: ShowQuery): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('GET', this.path(''), {\n query: { country: query?.country, currency: query?.currency },\n });\n }\n\n countries(): Promise<CountriesResponse> {\n return this.request<CountriesResponse>('GET', this.path('/countries'));\n }\n\n pay(body: PayInput): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('POST', this.path('/pay'), { body });\n }\n\n authorize(body: AuthorizeInput): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('POST', this.path('/authorize'), { body });\n }\n\n poll(): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('GET', this.path('/poll'));\n }\n\n /**\n * Build the resource path: `/checkout/{publicId}{suffix}`.\n *\n * One surface shared by the hosted page and the SDK (backend PR #105):\n * `GET ''` (show), `POST /pay`, `POST /authorize`, `GET /poll`,\n * `GET /countries`. Scoped to the pk_'s project — a public_id from another\n * project returns 404 (the engine maps that to a terminal not_found).\n */\n private path(suffix: string): string {\n return `/checkout/${encodeURIComponent(this.auth.publicId)}${suffix}`;\n }\n\n private async request<T>(\n method: string,\n path: string,\n opts?: { query?: Record<string, string | undefined>; body?: unknown },\n ): Promise<T> {\n const url = this.baseUrl + path + this.queryString(opts?.query);\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const headers: Record<string, string> = { Accept: 'application/json' };\n if (this.locale) headers['Accept-Language'] = this.locale;\n headers.Authorization = `Bearer ${this.auth.publishableKey}`;\n if (opts?.body !== undefined) headers['Content-Type'] = 'application/json';\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method,\n headers,\n body: opts?.body === undefined ? undefined : JSON.stringify(opts.body),\n signal: controller.signal,\n });\n } catch (cause) {\n throw new CheckoutError('network', describeNetworkError(cause));\n } finally {\n clearTimeout(timer);\n }\n\n return this.parse<T>(response);\n }\n\n private async parse<T>(response: Response): Promise<T> {\n const text = await response.text().catch(() => '');\n let json: unknown;\n if (text) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n\n if (!response.ok) {\n const message = extractMessage(json) ?? `Request failed with status ${response.status}`;\n throw new CheckoutError(errorCodeFromStatus(response.status), message, response.status);\n }\n\n if (json === undefined) {\n throw new CheckoutError('unknown', 'Empty or non-JSON response body.', response.status);\n }\n return json as T;\n }\n\n private queryString(query?: Record<string, string | undefined>): string {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== '') params.set(key, value);\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n }\n}\n\nfunction extractMessage(json: unknown): string | undefined {\n if (json && typeof json === 'object' && 'message' in json) {\n const message = (json as { message: unknown }).message;\n if (typeof message === 'string') return message;\n }\n return undefined;\n}\n\nfunction describeNetworkError(cause: unknown): string {\n if (cause instanceof Error && cause.name === 'AbortError') return 'Request timed out.';\n if (cause instanceof Error) return cause.message;\n return 'Network request failed.';\n}\n","import type { HostedCheckout } from '../types/contract';\n\nimport type { CheckoutPhase } from './state';\n\n/**\n * Project server state into a phase. The SERVER owns the state machine; this is\n * a pure read-only projection. Order matters — first match wins.\n *\n * intent completed -> succeeded\n * intent failed/expired -> failed\n * session not open (not completed) -> closed\n * attempt action_required -> action_required\n * attempt processing -> processing\n * else (open, no/failed attempt) -> collecting (retry)\n */\nexport function derivePhase(checkout: HostedCheckout | null): CheckoutPhase {\n if (!checkout) return 'loading';\n\n const session = checkout.session.status;\n const intent = checkout.payment?.status;\n const attempt = checkout.attempt?.status;\n\n if (intent === 'completed') return 'succeeded';\n if (intent === 'failed' || intent === 'expired') return 'failed';\n\n if (session !== 'open') {\n return session === 'completed' ? 'succeeded' : 'closed';\n }\n\n // Session is open from here.\n if (attempt === 'action_required') return 'action_required';\n if (attempt === 'processing') return 'processing';\n\n // No attempt yet, or the last attempt failed/cancelled while the session is\n // still open: the customer can retry.\n return 'collecting';\n}\n\n/** Phases at which polling makes sense. */\nexport function isPollablePhase(phase: CheckoutPhase): boolean {\n return phase === 'processing' || phase === 'action_required';\n}\n\nexport function isTerminalPhase(phase: CheckoutPhase): boolean {\n return phase === 'succeeded' || phase === 'failed' || phase === 'closed';\n}\n","import type { AttemptSummary } from '../types/contract';\nimport type { NextAction } from '../types/next-action';\nimport type { ActionCompletion, CheckoutView, FormContext, ResultContext, WaitingContext } from '../types/view';\n\nimport type { EngineState } from './state';\n\n/**\n * Behavior mapping: given a next_action type, how does it complete? This is\n * the single place that decides submit/poll/redirect/sdk so a theme never has\n * to. Unknown types fail closed to `poll`.\n */\nexport function actionCompletion(action: NextAction): ActionCompletion {\n switch (action.type) {\n case 'collect_otp':\n return 'submit';\n case 'complete_with_sdk':\n return 'sdk';\n case 'redirect_to_url':\n return 'redirect';\n case 'embed_iframe':\n case 'approve_on_phone':\n case 'scan_qr_code':\n case 'display_payment_instructions':\n return 'poll';\n case 'none':\n return 'poll';\n default:\n // Unknown/forward-compat action type: wait and poll, never crash a theme.\n return 'poll';\n }\n}\n\n/** An action is renderable as an `action` view only if it asks for something. */\nfunction isActionable(action: NextAction | null): action is NextAction {\n return action !== null && action.type !== 'none';\n}\n\n/**\n * Pure projection: EngineState -> CheckoutView. No I/O, no mutation.\n */\nexport function projectView(state: EngineState): CheckoutView {\n const { phase, checkout, catalogue } = state;\n\n if (phase === 'loading') {\n return { kind: 'loading' };\n }\n if (!checkout) {\n // Forced terminal phase before any checkout loaded (e.g. 404 on first load).\n const kind = phase === 'succeeded' || phase === 'failed' ? phase : 'closed';\n return { kind, ctx: result(state, kind) };\n }\n\n const attempt = checkout.attempt;\n // Appearance is bootstrap-scoped now (not on show/pay/poll), so it lives in\n // engine state and is projected onto every view.\n const appearance = state.appearance;\n\n switch (phase) {\n case 'collecting': {\n if (!catalogue) return { kind: 'loading' };\n const ctx: FormContext = {\n amount: catalogue.amount,\n methods: catalogue.methods,\n country: catalogue.country,\n currencyOptions: catalogue.currencyOptions,\n supportsAnyCountry: catalogue.supportsAnyCountry,\n previousPhones: state.previousPhones,\n };\n if (checkout.restriction) ctx.restriction = checkout.restriction;\n if (checkout.customer) ctx.customer = checkout.customer;\n if (checkout.project) ctx.project = checkout.project;\n if (appearance) ctx.appearance = appearance;\n if (!state.dismissedError) {\n if (state.error) ctx.lastError = state.error;\n if (isFailedAttempt(attempt)) ctx.retryOf = attempt;\n }\n return { kind: 'form', ctx };\n }\n\n case 'action_required': {\n const action = attempt?.next_action ?? null;\n // action_required but nothing to render (null / none) -> wait + poll.\n if (!attempt || !isActionable(action)) {\n return attempt ? { kind: 'processing', ctx: waiting(state, attempt) } : { kind: 'loading' };\n }\n return {\n kind: 'action',\n ctx: {\n action,\n attempt,\n completion: actionCompletion(action),\n ...(catalogue ? { amount: catalogue.amount } : {}),\n ...(checkout.project ? { project: checkout.project } : {}),\n ...(appearance ? { appearance } : {}),\n },\n };\n }\n\n case 'processing': {\n return attempt ? { kind: 'processing', ctx: waiting(state, attempt) } : { kind: 'loading' };\n }\n\n case 'succeeded':\n return { kind: 'succeeded', ctx: result(state, 'succeeded') };\n\n case 'failed':\n return { kind: 'failed', ctx: result(state, 'failed') };\n\n case 'closed':\n return { kind: 'closed', ctx: result(state, 'closed') };\n\n default:\n return { kind: 'loading' };\n }\n}\n\nfunction isFailedAttempt(attempt: AttemptSummary | undefined): attempt is AttemptSummary {\n return attempt != null && (attempt.status === 'failed' || attempt.status === 'cancelled');\n}\n\nfunction waiting(state: EngineState, attempt: AttemptSummary): WaitingContext {\n const ctx: WaitingContext = { attempt };\n if (state.catalogue) ctx.amount = state.catalogue.amount;\n if (state.checkout?.project) ctx.project = state.checkout.project;\n if (state.appearance) ctx.appearance = state.appearance;\n return ctx;\n}\n\nfunction result(state: EngineState, kind: 'succeeded' | 'failed' | 'closed'): ResultContext {\n const checkout = state.checkout;\n\n // A closed checkout is closed because of the SESSION (expired/cancelled);\n // the intent may still read 'pending'. Success/failure come from the intent.\n const status =\n kind === 'closed'\n ? (checkout?.session.status ?? 'expired')\n : (checkout?.payment?.status ?? checkout?.session.status ?? 'expired');\n\n // For a failure, the customer-facing reason is the attempt's failure message,\n // not the generic envelope message. Terminal copy is otherwise the theme's job.\n const failureMessage = kind === 'failed' ? checkout?.attempt?.failure.message : undefined;\n\n let message = '';\n if (kind === 'failed') message = failureMessage ?? '';\n else if (kind === 'succeeded') message = state.message;\n const ctx: ResultContext = { status, message };\n if (checkout?.payment) ctx.payment = checkout.payment;\n if (state.catalogue) ctx.amount = state.catalogue.amount;\n if (checkout?.project) ctx.project = checkout.project;\n if (state.appearance) ctx.appearance = state.appearance;\n if (state.returnUrl) ctx.returnUrl = state.returnUrl;\n return ctx;\n}\n","import type {\n Appearance,\n Country,\n CurrencyOption,\n HostedCheckout,\n PaymentMethod,\n PreviousPhone,\n ResolvedAmount,\n} from '../types/contract';\nimport type { CheckoutError } from '../types/errors';\n\n/**\n * The resolved catalogue is returned ONLY by `show`. `pay`/`authorize`/`poll`\n * omit it, so the engine caches the last good catalogue and re-fetches it only\n * when country/currency changes. See contract.ts › HostedCheckout.\n */\nexport interface ResolvedCatalogue {\n country: Country;\n currencyOptions: CurrencyOption[];\n amount: ResolvedAmount;\n methods: PaymentMethod[];\n supportsAnyCountry: boolean;\n}\n\nexport type CheckoutPhase =\n | 'loading'\n | 'closed'\n | 'succeeded'\n | 'failed'\n | 'action_required'\n | 'processing'\n | 'collecting';\n\nexport interface EngineState {\n /** Last good catalogue from `show`. */\n catalogue: ResolvedCatalogue | null;\n /**\n * Customer's saved phones, cached like the catalogue. `show`/`hydrate` return\n * them, but `pay`/`authorize`/`poll` responses carry `previous_used_phones:\n * null`, so reading them off the live checkout would make the recent-phone\n * card vanish after a failed attempt. Cached here and refreshed only when a\n * response actually provides them.\n */\n previousPhones: PreviousPhone[];\n /** Last response from any endpoint. */\n checkout: HostedCheckout | null;\n /** Server `message` from the last successful response. */\n message: string;\n phase: CheckoutPhase;\n error: CheckoutError | null;\n /**\n * The customer dismissed the current error banner (e.g. by reselecting a\n * method). Suppresses both banner sources (`lastError`, `retryOf`) until the\n * next server response, which resets it.\n */\n dismissedError: boolean;\n /**\n * Session-scoped chrome from the bootstrap payload. `appearance` is no longer\n * on show/pay/poll responses, so the engine holds it here and projects it on\n * every view. `returnUrl` (nullable, may be absent for old sessions) is the\n * merchant redirect target for the terminal \"return\" CTA.\n */\n appearance: Appearance | null;\n returnUrl: string | null;\n polling: boolean;\n}\n\nexport function initialState(): EngineState {\n return {\n catalogue: null,\n previousPhones: [],\n checkout: null,\n message: '',\n phase: 'loading',\n error: null,\n dismissedError: false,\n appearance: null,\n returnUrl: null,\n polling: false,\n };\n}\n\n/** Pull the catalogue out of a `show` response; null if not present. */\nexport function extractCatalogue(checkout: HostedCheckout): ResolvedCatalogue | null {\n const { country, currency_options, amount, methods } = checkout;\n if (!country || !currency_options || !amount || !methods) return null;\n return {\n country,\n currencyOptions: currency_options,\n amount,\n methods,\n supportsAnyCountry: checkout.supports_any_country ?? false,\n };\n}\n","import type { Appearance, AuthorizeInput, CountrySimplified, HostedCheckout, PayInput } from '../types/contract';\nimport { CheckoutError } from '../types/errors';\nimport type { CheckoutView } from '../types/view';\nimport type { Transport } from '../transport/transport';\n\nimport { derivePhase, isTerminalPhase } from './phase';\nimport { actionCompletion, projectView } from './project';\nimport { extractCatalogue, initialState, type EngineState } from './state';\n\nexport interface CheckoutEngineOptions {\n /** Auto-manage the polling loop based on phase. Default true. */\n autoPoll?: boolean;\n /** Backoff delays (ms) for the first polls. Default [2000,2000,3000,5000]. */\n pollIntervalsMs?: number[];\n /** Steady interval (ms) after the backoff ramp. Default 5000. */\n steadyIntervalMs?: number;\n /** Clock injection for tests. Default Date.now. */\n now?: () => number;\n /** Timer injection for tests. Default global setTimeout/clearTimeout. */\n setTimeoutImpl?: (cb: () => void, ms: number) => ReturnType<typeof setTimeout>;\n clearTimeoutImpl?: (handle: ReturnType<typeof setTimeout>) => void;\n}\n\ntype Listener = (view: CheckoutView) => void;\n\n/**\n * The engine facade themes consume. Owns state, the polling loop, and all\n * transport calls. Themes never see the Transport, the wire types, or the\n * token — only CheckoutView (via getView/subscribe) and these action methods.\n */\nexport class CheckoutEngine {\n private state: EngineState = initialState();\n private readonly listeners = new Set<Listener>();\n\n private readonly autoPoll: boolean;\n private readonly intervals: number[];\n private readonly steady: number;\n private readonly now: () => number;\n private readonly setTimeoutImpl: NonNullable<CheckoutEngineOptions['setTimeoutImpl']>;\n private readonly clearTimeoutImpl: NonNullable<CheckoutEngineOptions['clearTimeoutImpl']>;\n\n private pollHandle: ReturnType<typeof setTimeout> | null = null;\n private pollTick = 0;\n private pollInFlight = false;\n private destroyed = false;\n\n constructor(\n private readonly transport: Transport,\n options: CheckoutEngineOptions = {},\n ) {\n this.autoPoll = options.autoPoll ?? true;\n this.intervals = options.pollIntervalsMs ?? [2000, 2000, 3000, 5000];\n this.steady = options.steadyIntervalMs ?? 5000;\n this.now = options.now ?? Date.now;\n this.setTimeoutImpl = options.setTimeoutImpl ?? ((cb, ms) => setTimeout(cb, ms));\n this.clearTimeoutImpl = options.clearTimeoutImpl ?? ((handle) => clearTimeout(handle));\n }\n\n // --- read surface ---\n\n getView(): CheckoutView {\n return projectView(this.state);\n }\n\n /** Subscribe to view changes. Fires immediately with the current view. */\n subscribe(fn: Listener): () => void {\n this.listeners.add(fn);\n fn(this.getView());\n return () => {\n this.listeners.delete(fn);\n };\n }\n\n // --- actions ---\n\n /**\n * Seed state from a server-fetched `show` payload (SSR) so the first paint is\n * the form, not the loading screen — no transport call. The host passes the\n * `GET /checkout/{public_id}` payload the SSR layer fetched after bootstrap.\n * Treated exactly like a `show`, so the resolved catalogue is cached. The\n * engine may still `poll()`/`load()` afterwards to refresh.\n */\n hydrate(checkout: HostedCheckout, message = ''): void {\n this.applyResponse(checkout, message, true);\n }\n\n /**\n * Seed session-scoped chrome from the SSR bootstrap payload. `appearance` and\n * `return_url` no longer ride on show/pay/poll responses, so the host passes\n * them once here and the engine projects them onto every view. Call before the\n * first render (alongside `hydrate`) so the theme paints branded from frame 1.\n */\n seedBootstrap(input: { appearance?: Appearance | null; returnUrl?: string | null }): void {\n const next: Partial<EngineState> = {};\n if (input.appearance) next.appearance = input.appearance;\n if (input.returnUrl !== undefined) next.returnUrl = input.returnUrl;\n if (Object.keys(next).length > 0) this.setState(next);\n }\n\n async load(): Promise<void> {\n await this.runShow(undefined);\n }\n\n async selectCountry(country: string): Promise<void> {\n await this.runShow({ country });\n }\n\n async selectCurrency(currency: string): Promise<void> {\n // Preserve the resolved country. Sending `currency` alone makes the server\n // re-resolve the country to its default, silently switching it — the bug when\n // a country exposes more than one currency (e.g. CD: CDF/USD). `selectCountry`\n // deliberately omits currency so the server picks the new country's default.\n const country = this.state.catalogue?.country.code;\n await this.runShow(country ? { country, currency } : { currency });\n }\n\n /** Full selectable country catalogue for the picker (not part of the view). */\n async listCountries(): Promise<CountrySimplified[]> {\n try {\n const res = await this.transport.countries();\n return res.data;\n } catch (cause) {\n this.setError(cause);\n return [];\n }\n }\n\n async pay(input: PayInput): Promise<void> {\n await this.runMutation(() => this.transport.pay(this.withCatalogueDefaults(input)), false);\n }\n\n /**\n * Dismiss the current error banner (both `lastError` and a failed-attempt\n * `retryOf`). Themes call this when the customer selects a method again so a\n * stale error doesn't linger; the next server response clears the dismissal.\n */\n clearError(): void {\n if (this.state.error === null && this.state.dismissedError) return;\n this.setState({ error: null, dismissedError: true });\n }\n\n async authorize(input: AuthorizeInput): Promise<void> {\n await this.runMutation(() => this.transport.authorize(input), false);\n }\n\n async poll(): Promise<void> {\n await this.runMutation(() => this.transport.poll(), false);\n }\n\n /** Called when the customer returns from an external redirect. Just polls. */\n async resumeFromRedirect(): Promise<void> {\n await this.poll();\n }\n\n // --- polling control (host wires visibility/focus to these) ---\n\n startPolling(): void {\n if (this.destroyed || this.state.polling) return;\n this.setState({ polling: true });\n this.pollTick = 0;\n this.scheduleNextPoll();\n }\n\n stopPolling(): void {\n if (this.pollHandle !== null) {\n this.clearTimeoutImpl(this.pollHandle);\n this.pollHandle = null;\n }\n if (this.state.polling) this.setState({ polling: false });\n }\n\n destroy(): void {\n this.destroyed = true;\n this.stopPolling();\n this.listeners.clear();\n }\n\n // --- internals ---\n\n private async runShow(query: { country?: string; currency?: string } | undefined): Promise<void> {\n try {\n const res = await this.transport.show(query);\n this.applyResponse(res.data, res.message ?? '', true);\n } catch (cause) {\n this.setError(cause);\n }\n }\n\n private async runMutation(\n call: () => Promise<{ data: HostedCheckout; message?: string }>,\n isShow: boolean,\n ): Promise<void> {\n try {\n const res = await call();\n this.applyResponse(res.data, res.message ?? '', isShow);\n } catch (cause) {\n this.setError(cause);\n }\n }\n\n /**\n * Stamp the pay payload with the currently-resolved country/currency from the\n * cached catalogue. Themes call `selectCountry`/`selectCurrency` (which refetch\n * the catalogue) but never thread that selection back into `pay` — without this\n * the server falls back to its default country and rejects methods that aren't\n * available there. A value already on the input always wins; currency is only\n * stamped when DCC is in effect (the only time the server expects it).\n */\n private withCatalogueDefaults(input: PayInput): PayInput {\n const catalogue = this.state.catalogue;\n if (!catalogue) return input;\n\n const next: PayInput = { ...input };\n if (next.country === undefined) next.country = catalogue.country.code;\n if (next.currency === undefined && catalogue.amount.is_dcc) {\n const currency = catalogue.amount.final.currency;\n if (currency) next.currency = currency;\n }\n return next;\n }\n\n private applyResponse(checkout: HostedCheckout, message: string, isShow: boolean): void {\n const next: Partial<EngineState> = {\n checkout,\n message,\n phase: derivePhase(checkout),\n error: null,\n // A fresh response (incl. a new failed attempt) is shown, not suppressed.\n dismissedError: false,\n };\n if (isShow) {\n const catalogue = extractCatalogue(checkout);\n if (catalogue) next.catalogue = catalogue;\n }\n // Cache saved phones whenever a response actually carries them; mutation\n // responses null them out, so keep the last known list across retries.\n if (checkout.previous_used_phones != null) {\n next.previousPhones = checkout.previous_used_phones;\n }\n this.setState(next);\n this.reconcilePolling();\n }\n\n private setError(cause: unknown): void {\n const error = cause instanceof CheckoutError ? cause : new CheckoutError('unknown', toMessage(cause));\n\n // Terminal errors close the checkout; recoverable ones keep the phase so the\n // theme can show the message inline (e.g. 422 on pay stays in `collecting`).\n const isTerminalError = error.code === 'not_found' || error.code === 'not_open';\n const keepPhase = !isTerminalError && this.state.checkout;\n const phase: EngineState['phase'] = keepPhase ? this.state.phase : 'closed';\n\n this.setState({ error, phase, message: error.message, dismissedError: false });\n this.reconcilePolling();\n }\n\n private reconcilePolling(): void {\n if (!this.autoPoll || this.destroyed) return;\n if (isTerminalPhase(this.state.phase)) {\n this.stopPolling();\n return;\n }\n if (this.shouldPoll()) {\n this.startPolling();\n } else {\n this.stopPolling();\n }\n }\n\n /**\n * Poll while an attempt is `processing`, or while it is `action_required`\n * with a poll-completion action (approve_on_phone, scan_qr_code,\n * display_payment_instructions, embed_iframe). Do NOT poll while waiting on\n * the customer to submit (collect_otp), redirect, or run an SDK.\n */\n private shouldPoll(): boolean {\n if (this.state.phase === 'processing') return true;\n if (this.state.phase === 'action_required') {\n const action = this.state.checkout?.attempt?.next_action;\n return action != null && actionCompletion(action) === 'poll';\n }\n return false;\n }\n\n private scheduleNextPoll(): void {\n if (this.destroyed || !this.state.polling) return;\n\n const delay = this.intervals[this.pollTick] ?? this.steady;\n this.pollTick++;\n\n // Cap to session expiry: stop scheduling once we're past expires_at.\n const expiresAt = this.expiresAtMs();\n if (expiresAt !== null && this.now() >= expiresAt) {\n this.stopPolling();\n return;\n }\n\n this.pollHandle = this.setTimeoutImpl(() => {\n this.tickPoll().catch(() => undefined);\n }, delay);\n }\n\n private async tickPoll(): Promise<void> {\n if (this.destroyed || !this.state.polling || this.pollInFlight) return;\n this.pollInFlight = true;\n try {\n await this.poll();\n } finally {\n this.pollInFlight = false;\n }\n // poll() -> applyResponse -> reconcilePolling may have stopped us.\n if (this.state.polling && !isTerminalPhase(this.state.phase)) {\n this.scheduleNextPoll();\n }\n }\n\n private expiresAtMs(): number | null {\n const raw = this.state.checkout?.session.expires_at;\n if (!raw) return null;\n const ms = Date.parse(raw);\n return Number.isNaN(ms) ? null : ms;\n }\n\n private setState(partial: Partial<EngineState>): void {\n this.state = { ...this.state, ...partial };\n this.emit();\n }\n\n private emit(): void {\n const view = this.getView();\n for (const listener of this.listeners) listener(view);\n }\n}\n\nfunction toMessage(cause: unknown): string {\n if (cause instanceof Error) return cause.message;\n return 'Unexpected error.';\n}\n","import type { RedirectToUrlAction } from '@orqex/checkout-engine';\n\ninterface RedirectEffectDeps {\n /** Top-level navigation for GET redirects. Default window.location.assign. */\n navigate?: (url: string) => void;\n /** Injectable document for tests. Default global document. */\n doc?: Document;\n}\n\n/**\n * Execute a redirect next-action in a headless page. GET navigates the\n * top-level document; POST auto-submits a hidden form (some 3-D Secure ACS\n * endpoints). Refuses any non-https URL as defense-in-depth — the primary trust\n * boundary is the server, but we never navigate to javascript:/data: schemes.\n */\nexport function performActionRedirect(action: RedirectToUrlAction, deps: RedirectEffectDeps = {}): void {\n const doc = deps.doc ?? document;\n const navigate = deps.navigate ?? ((url: string) => window.location.assign(url));\n\n if (!isHttps(action.url)) {\n // eslint-disable-next-line no-console\n console.error(`Orqex: refused redirect to non-https URL \"${action.url}\".`);\n return;\n }\n\n if (action.method === 'POST') {\n const form = doc.createElement('form');\n form.method = 'POST';\n form.action = action.url;\n form.style.display = 'none';\n for (const [name, value] of Object.entries(action.post_data ?? {})) {\n const input = doc.createElement('input');\n input.type = 'hidden';\n input.name = name;\n input.value = typeof value === 'string' ? value : JSON.stringify(value);\n form.appendChild(input);\n }\n doc.body.appendChild(form);\n form.submit();\n return;\n }\n\n navigate(action.url);\n}\n\nfunction isHttps(url: string): boolean {\n try {\n return new URL(url).protocol === 'https:';\n } catch {\n return false;\n }\n}\n","import {\n CheckoutEngine,\n HttpTransport,\n type AuthorizeInput,\n type CheckoutView,\n type CountrySimplified,\n type PayInput,\n type RedirectToUrlAction,\n} from '@orqex/checkout-engine';\n\nimport type { ResolvedConfig } from './config';\nimport { performActionRedirect } from './redirect-effect';\n\nexport interface CreateEngineOptions {\n /** cs_… checkout handle minted server-side by the merchant. */\n publicId: string;\n /** BCP-47 locale for Accept-Language. Default navigator.language. */\n locale?: string;\n /**\n * When true, the SDK persists publicId across a redirect and auto-resumes on\n * return, and auto-performs redirect actions. Default false (fully manual).\n */\n autoResume?: boolean;\n}\n\n/** Narrowed, browser-facing surface over CheckoutEngine. Cross-SDK contract. */\nexport interface OrqexCheckout {\n subscribe(fn: (view: CheckoutView) => void): () => void;\n getView(): CheckoutView;\n pay(input: PayInput): Promise<void>;\n authorize(input: AuthorizeInput): Promise<void>;\n poll(): Promise<void>;\n selectCountry(country: string): Promise<void>;\n selectCurrency(currency: string): Promise<void>;\n listCountries(): Promise<CountrySimplified[]>;\n /** Poll the current server state (call on return from an external redirect). */\n resumeFromRedirect(): Promise<void>;\n startPolling(): void;\n stopPolling(): void;\n /** Perform the pending redirect action; no-op if the current view is not one. */\n performRedirect(): void;\n destroy(): void;\n}\n\nexport interface HeadlessDeps {\n /** Injected engine for tests; when omitted a real one is built. */\n engine?: CheckoutEngine;\n /** Injectable window for tests. Default global window. */\n win?: Window;\n /** Injectable storage for autoResume tests. Default window.sessionStorage. */\n storage?: Storage;\n /** Injectable fetch passed to HttpTransport. Default global fetch. */\n fetchImpl?: (input: string, init?: RequestInit) => Promise<Response>;\n}\n\n/** Extract the current redirect action from a view, or null. */\nfunction redirectActionOf(view: CheckoutView): RedirectToUrlAction | null {\n if (view.kind === 'action' && view.ctx.completion === 'redirect' && view.ctx.action.type === 'redirect_to_url') {\n return view.ctx.action;\n }\n return null;\n}\n\nconst markerKey = (publicId: string): string => `orqex:redirect:${publicId}`;\n\nfunction wireAutoResume(engine: CheckoutEngine, publicId: string, ctx: { storage: Storage; win: Window }): () => void {\n const key = markerKey(publicId);\n\n // Returning from a redirect: a pending marker means we just came back.\n if (ctx.storage.getItem(key) !== null) {\n ctx.storage.removeItem(key);\n engine.resumeFromRedirect();\n }\n\n // Auto-perform the redirect once per (attempt, action).\n let handled: string | null = null;\n const unsubscribe = engine.subscribe((view) => {\n const action = redirectActionOf(view);\n if (!action || !action.can_auto_redirect || view.kind !== 'action') return;\n const dedupe = `${view.ctx.attempt.id}:${action.type}`;\n if (handled === dedupe) return;\n handled = dedupe;\n ctx.storage.setItem(key, view.ctx.attempt.id);\n performActionRedirect(action, { navigate: (url) => ctx.win.location.assign(url), doc: ctx.win.document });\n });\n\n const onPageShow = (): void => {\n const kind = engine.getView().kind;\n if (kind === 'action' || kind === 'processing') engine.resumeFromRedirect();\n };\n ctx.win.addEventListener('pageshow', onPageShow);\n\n return () => {\n unsubscribe();\n ctx.win.removeEventListener('pageshow', onPageShow);\n };\n}\n\n/**\n * Build the headless checkout: a real CheckoutEngine over HttpTransport (pk_),\n * wrapped in the narrowed OrqexCheckout facade. Manual mode; autoResume wiring\n * is conditionally applied when `options.autoResume` is true.\n */\nexport function createHeadlessCheckout(\n config: ResolvedConfig,\n options: CreateEngineOptions,\n deps: HeadlessDeps = {},\n): OrqexCheckout {\n const win = deps.win ?? window;\n const engine =\n deps.engine ??\n new CheckoutEngine(\n new HttpTransport({\n baseUrl: config.apiBaseUrl,\n auth: { publishableKey: config.publishableKey, publicId: options.publicId },\n locale: options.locale ?? (typeof navigator === 'undefined' ? undefined : navigator.language),\n fetchImpl: deps.fetchImpl,\n }),\n );\n\n let autoResumeTeardown: () => void = () => {};\n\n const facade: OrqexCheckout = {\n subscribe: (fn) => engine.subscribe(fn),\n getView: () => engine.getView(),\n pay: (input) => engine.pay(input),\n authorize: (input) => engine.authorize(input),\n poll: () => engine.poll(),\n selectCountry: (country) => engine.selectCountry(country),\n selectCurrency: (currency) => engine.selectCurrency(currency),\n listCountries: () => engine.listCountries(),\n resumeFromRedirect: () => engine.resumeFromRedirect(),\n startPolling: () => engine.startPolling(),\n stopPolling: () => engine.stopPolling(),\n performRedirect: () => {\n const action = redirectActionOf(engine.getView());\n if (action) performActionRedirect(action, { navigate: (url) => win.location.assign(url), doc: win.document });\n },\n destroy: () => {\n autoResumeTeardown();\n engine.destroy();\n },\n };\n\n if (options.autoResume) {\n autoResumeTeardown = wireAutoResume(engine, options.publicId, { storage: deps.storage ?? win.sessionStorage, win });\n }\n\n engine.load();\n return facade;\n}\n","import { buildRedirectUrl, type ResolvedConfig } from './config';\n\nexport interface RedirectOptions {\n /** cs_… checkout handle minted server-side by the merchant. */\n publicId: string;\n}\n\ntype Navigate = (url: string) => void;\n\nconst defaultNavigate: Navigate = (url) => {\n window.location.assign(url);\n};\n\n/** Full-page navigation to the hosted checkout. */\nexport function redirectToCheckout(\n config: ResolvedConfig,\n options: RedirectOptions,\n navigate: Navigate = defaultNavigate,\n): void {\n if (!options.publicId) {\n throw new Error('Orqex: redirectToCheckout requires a publicId.');\n }\n navigate(buildRedirectUrl(config, options.publicId));\n}\n","import { resolveConfig, type OrqexOptions } from './config';\nimport { EmbeddedController, type MountOptions } from './embedded';\nimport { EventBus, type EventPayloads, type MerchantEvent } from './event-bus';\nimport { createHeadlessCheckout, type CreateEngineOptions, type OrqexCheckout } from './headless';\nimport { redirectToCheckout, type RedirectOptions } from './redirect';\n\nexport interface OrqexInstance {\n /** Embedded mode: hosted checkout in a sandboxed iframe. */\n mount(target: string | HTMLElement, options: MountOptions): void;\n /** Redirect mode: full-page navigation to the hosted checkout. */\n redirectToCheckout(options: RedirectOptions): void;\n /** Subscribe to a lifecycle event; returns a disposer. */\n on<TEvent extends MerchantEvent>(event: TEvent, handler: (payload: EventPayloads[TEvent]) => void): () => void;\n /** Tear down the embedded iframe and its listener (no-op in redirect mode). */\n unmount(): void;\n /** Headless mode: run the engine in this page and render your own UI. */\n createEngine(options: CreateEngineOptions): OrqexCheckout;\n}\n\n/**\n * SDK entry point. `Orqex('pk_…')` validates the key, then exposes embedded,\n * redirect, and headless (`createEngine`) modes over one event bus.\n */\nexport function Orqex(publishableKey: string, options?: OrqexOptions): OrqexInstance {\n const config = resolveConfig(publishableKey, options);\n const bus = new EventBus();\n const embedded = new EmbeddedController({ config, bus });\n\n return {\n mount(target, mountOptions) {\n embedded.mount(target, mountOptions);\n },\n redirectToCheckout(redirectOptions) {\n redirectToCheckout(config, redirectOptions);\n },\n on(event, handler) {\n return bus.on(event, handler);\n },\n unmount() {\n embedded.unmount();\n },\n createEngine(engineOptions) {\n return createHeadlessCheckout(config, engineOptions);\n },\n };\n}\n","import type { CheckoutView } from '@orqex/checkout-engine';\n\nimport { closeMessage, errorMessage, successMessage, type EmbedMessage } from './protocol';\n\nexport interface EmbedProjection {\n message: EmbedMessage;\n /** Dedup key so the host posts each terminal state at most once. */\n key: string;\n}\n\n/**\n * Pure mapping from the engine's projected view to an embed lifecycle message.\n * Terminal views only; `redirect` is handled by the host's redirect override\n * (a redirect action is not a terminal view). Returns null when there is\n * nothing new to post or `key` equals `lastKey`.\n */\nexport function projectEmbedMessage(view: CheckoutView, lastKey: string | null): EmbedProjection | null {\n let projection: EmbedProjection | null = null;\n\n if (view.kind === 'succeeded') {\n const status = String(view.ctx.status);\n projection = { message: successMessage(status), key: `succeeded:${status}` };\n } else if (view.kind === 'failed') {\n const status = String(view.ctx.status);\n projection = { message: errorMessage(status, view.ctx.message), key: `failed:${status}` };\n } else if (view.kind === 'closed') {\n const status = String(view.ctx.status);\n projection = { message: closeMessage(status), key: `closed:${status}` };\n }\n\n if (!projection || projection.key === lastKey) return null;\n return projection;\n}\n","/**\n * @orqex/checkout-js — client-side SDK for Orqex payments.\n *\n * Browser-host glue over the existing engine + hosted checkout. Never accepts a\n * secret key; the publishable key (pk_) is public by design.\n */\n\nexport const SDK_VERSION = '0.0.1';\n\nexport { Orqex } from './orqex';\nexport type { OrqexInstance } from './orqex';\nexport type { OrqexOptions } from './config';\nexport type { MountOptions } from './embedded';\nexport type { RedirectOptions } from './redirect';\nexport type { MerchantEvent, EventPayloads } from './event-bus';\nexport type { OrqexCheckout, CreateEngineOptions } from './headless';\n// Engine contract re-exported so headless merchants render against the typed view.\nexport type { CheckoutView, PayInput, AuthorizeInput, CountrySimplified } from '@orqex/checkout-engine';\n\n// Embed protocol + view→message projection: re-exported so the hosted app\n// (checkout-next) imports the single source of truth for the wire contract.\nexport * from './protocol';\nexport { projectEmbedMessage } from './embed-projection';\nexport type { EmbedProjection } from './embed-projection';\n"]}
@@ -1,3 +1,3 @@
1
- var OrqexSdk=(function(exports){'use strict';var j=Object.defineProperty;var B=(r,e,t)=>e in r?j(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t;var a=(r,e,t)=>B(r,typeof e!="symbol"?e+"":e,t);var V=/^pk_(live|test)_[A-Za-z0-9]+$/;function E(r){if(typeof r!="string"||!V.test(r))throw new Error('Orqex: a publishable key ("pk_live_\u2026" or "pk_test_\u2026") is required. Never pass a secret key to the browser.');return {key:r,livemode:r.startsWith("pk_live_")}}var z="https://checkout.orqex.com",$="https://api.orqex.com";function C(r,e={}){let{key:t,livemode:o}=E(r),n=e.checkoutBaseUrl??z,i=n.replace(/\/+$/,""),s;try{s=new URL(i).origin;}catch{throw new Error(`Orqex: invalid checkoutBaseUrl "${n}".`)}let c=(e.apiBaseUrl??$).replace(/\/+$/,"");return {publishableKey:t,livemode:o,checkoutBaseUrl:i,checkoutOrigin:s,apiBaseUrl:c}}function k(r,e,t){let o=encodeURIComponent(e);return `${r.checkoutBaseUrl}/${o}?embed=1&origin=${encodeURIComponent(t)}`}function w(r,e){return `${r.checkoutBaseUrl}/${encodeURIComponent(e)}`}var ae=1,K=["ready","resize","success","error","redirect","close"];function P(r){if(r===null||typeof r!="object")return false;let e=r;return e.__orqex===true&&e.v===1&&typeof e.type=="string"&&K.includes(e.type)}function p(r){return {__orqex:true,v:1,type:r}}function ce(){return p("ready")}function ue(r){return {...p("resize"),height:r}}function T(r){return {...p("success"),status:r}}function R(r,e){return {...p("error"),code:r,message:e}}function le(r){return {...p("redirect"),url:r}}function O(r){return {...p("close"),status:r}}var F="allow-scripts allow-same-origin allow-forms allow-popups",f=class{constructor(e){a(this,"config");a(this,"bus");a(this,"win");a(this,"navigate");a(this,"iframe",null);a(this,"listener",null);this.config=e.config,this.bus=e.bus,this.win=e.win??window,this.navigate=e.navigate??(t=>this.win.location.assign(t));}mount(e,t){if(!t.publicId)throw new Error("Orqex: mount requires a publicId.");let o=this.resolveHost(e);this.unmount();let n=this.win.document.createElement("iframe");n.src=k(this.config,t.publicId,this.win.location.origin),n.setAttribute("sandbox",F),n.setAttribute("allow","payment"),n.setAttribute("title","Orqex Checkout"),n.style.width="100%",n.style.border="none",n.style.height="150px",o.appendChild(n),this.iframe=n;let i=s=>{s.origin===this.config.checkoutOrigin&&s.source===n.contentWindow&&P(s.data)&&this.handle(s.data);};this.win.addEventListener("message",i),this.listener=i;}unmount(){this.listener&&(this.win.removeEventListener("message",this.listener),this.listener=null),this.iframe&&(this.iframe.remove(),this.iframe=null);}handle(e){switch(e.type){case "resize":this.iframe&&(this.iframe.style.height=`${e.height}px`);break;case "success":this.bus.emit("success",{status:e.status});break;case "error":this.bus.emit("error",{code:e.code,message:e.message});break;case "close":this.bus.emit("close",{status:e.status});break;case "redirect":this.bus.emit("redirect",{url:e.url}),this.navigate(e.url);break;}}resolveHost(e){let t=typeof e=="string"?this.win.document.querySelector(e):e;if(!t)throw new Error(`Orqex: mount target "${String(e)}" not found.`);return t}};var g=class{constructor(){a(this,"handlers",{success:new Set,error:new Set,redirect:new Set,close:new Set});}on(e,t){return this.handlers[e].add(t),()=>this.off(e,t)}off(e,t){this.handlers[e].delete(t);}emit(e,t){for(let o of this.handlers[e])try{o(t);}catch(n){console.error(`Orqex: "${e}" event handler threw`,n);}}};var u=class extends Error{constructor(t,o,n){super(o);a(this,"code");a(this,"httpStatus");this.name="CheckoutError",this.code=t,this.httpStatus=n;}};function M(r){switch(r){case 400:return "not_open";case 404:return "not_found";case 422:return "unprocessable";case 429:return "rate_limited";default:return r>=500?"network":"unknown"}}var d=class{constructor(e){a(this,"baseUrl");a(this,"auth");a(this,"locale");a(this,"fetchImpl");a(this,"timeoutMs");let t=e.fetchImpl??(typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0);if(!t)throw new u("unknown","No fetch implementation available; pass options.fetchImpl.");if(!e.auth?.publishableKey||!e.auth?.publicId)throw new u("unknown","HttpTransport requires `auth` with publishableKey and publicId.");this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.auth=e.auth,this.locale=e.locale,this.fetchImpl=t,this.timeoutMs=e.timeoutMs??2e4;}show(e){return this.request("GET",this.path(""),{query:{country:e?.country,currency:e?.currency}})}countries(){return this.request("GET",this.path("/countries"))}pay(e){return this.request("POST",this.path("/pay"),{body:e})}authorize(e){return this.request("POST",this.path("/authorize"),{body:e})}poll(){return this.request("GET",this.path("/poll"))}path(e){return `/checkout/${encodeURIComponent(this.auth.publicId)}${e}`}async request(e,t,o){let n=this.baseUrl+t+this.queryString(o?.query),i={Accept:"application/json"};this.locale&&(i["Accept-Language"]=this.locale),i.Authorization=`Bearer ${this.auth.publishableKey}`,o?.body!==void 0&&(i["Content-Type"]="application/json");let s=new AbortController,c=setTimeout(()=>s.abort(),this.timeoutMs),l;try{l=await this.fetchImpl(n,{method:e,headers:i,body:o?.body===void 0?void 0:JSON.stringify(o.body),signal:s.signal});}catch(m){throw new u("network",W(m))}finally{clearTimeout(c);}return this.parse(l)}async parse(e){let t=await e.text().catch(()=>""),o;if(t)try{o=JSON.parse(t);}catch{o=void 0;}if(!e.ok){let n=D(o)??`Request failed with status ${e.status}`;throw new u(M(e.status),n,e.status)}if(o===void 0)throw new u("unknown","Empty or non-JSON response body.",e.status);return o}queryString(e){if(!e)return "";let t=new URLSearchParams;for(let[n,i]of Object.entries(e))i!==void 0&&i!==""&&t.set(n,i);let o=t.toString();return o?`?${o}`:""}};function D(r){if(r&&typeof r=="object"&&"message"in r){let e=r.message;if(typeof e=="string")return e}}function W(r){return r instanceof Error&&r.name==="AbortError"?"Request timed out.":r instanceof Error?r.message:"Network request failed."}function I(r){if(!r)return "loading";let e=r.session.status,t=r.payment?.status,o=r.attempt?.status;return t==="completed"?"succeeded":t==="failed"||t==="expired"?"failed":e!=="open"?e==="completed"?"succeeded":"closed":o==="action_required"?"action_required":o==="processing"?"processing":"collecting"}function v(r){return r==="succeeded"||r==="failed"||r==="closed"}function b(r){switch(r.type){case "collect_otp":return "submit";case "complete_with_sdk":return "sdk";case "redirect_to_url":return "redirect";case "embed_iframe":case "approve_on_phone":case "scan_qr_code":case "display_payment_instructions":return "poll";case "none":return "poll";default:return "poll"}}function Q(r){return r!==null&&r.type!=="none"}function _(r){let{phase:e,checkout:t,catalogue:o}=r;if(e==="loading")return {kind:"loading"};if(!t){let s=e==="succeeded"||e==="failed"?e:"closed";return {kind:s,ctx:y(r,s)}}let n=t.attempt,i=r.appearance;switch(e){case "collecting":{if(!o)return {kind:"loading"};let s={amount:o.amount,methods:o.methods,country:o.country,currencies:o.currencies,supportsAnyCountry:o.supportsAnyCountry,previousPhones:t.previous_used_phones??[]};return t.restriction&&(s.restriction=t.restriction),t.customer&&(s.customer=t.customer),t.project&&(s.project=t.project),i&&(s.appearance=i),r.dismissedError||(r.error&&(s.lastError=r.error),J(n)&&(s.retryOf=n)),{kind:"form",ctx:s}}case "action_required":{let s=n?.next_action??null;return !n||!Q(s)?n?{kind:"processing",ctx:S(r,n)}:{kind:"loading"}:{kind:"action",ctx:{action:s,attempt:n,completion:b(s),...o?{amount:o.amount}:{},...t.project?{project:t.project}:{},...i?{appearance:i}:{}}}}case "processing":return n?{kind:"processing",ctx:S(r,n)}:{kind:"loading"};case "succeeded":return {kind:"succeeded",ctx:y(r,"succeeded")};case "failed":return {kind:"failed",ctx:y(r,"failed")};case "closed":return {kind:"closed",ctx:y(r,"closed")};default:return {kind:"loading"}}}function J(r){return r!=null&&(r.status==="failed"||r.status==="cancelled")}function S(r,e){let t={attempt:e};return r.catalogue&&(t.amount=r.catalogue.amount),r.checkout?.project&&(t.project=r.checkout.project),r.appearance&&(t.appearance=r.appearance),t}function y(r,e){let t=r.checkout,o=e==="closed"?t?.session.status??"expired":t?.payment?.status??t?.session.status??"expired",n=e==="failed"?t?.attempt?.failure.message:void 0,i="";e==="failed"?i=n??"":e==="succeeded"&&(i=r.message);let s={status:o,message:i};return t?.payment&&(s.payment=t.payment),r.catalogue&&(s.amount=r.catalogue.amount),t?.project&&(s.project=t.project),r.appearance&&(s.appearance=r.appearance),r.returnUrl&&(s.returnUrl=r.returnUrl),s}function q(){return {catalogue:null,checkout:null,message:"",phase:"loading",error:null,dismissedError:false,appearance:null,returnUrl:null,polling:false}}function A(r){let{country:e,currencies:t,amount:o,methods:n}=r;return !e||!t||!o||!n?null:{country:e,currencies:t,amount:o,methods:n,supportsAnyCountry:r.supports_any_country??false}}var h=class{constructor(e,t={}){a(this,"transport",e);a(this,"state",q());a(this,"listeners",new Set);a(this,"autoPoll");a(this,"intervals");a(this,"steady");a(this,"now");a(this,"setTimeoutImpl");a(this,"clearTimeoutImpl");a(this,"pollHandle",null);a(this,"pollTick",0);a(this,"pollInFlight",false);a(this,"destroyed",false);this.autoPoll=t.autoPoll??true,this.intervals=t.pollIntervalsMs??[2e3,2e3,3e3,5e3],this.steady=t.steadyIntervalMs??5e3,this.now=t.now??Date.now,this.setTimeoutImpl=t.setTimeoutImpl??((o,n)=>setTimeout(o,n)),this.clearTimeoutImpl=t.clearTimeoutImpl??(o=>clearTimeout(o));}getView(){return _(this.state)}subscribe(e){return this.listeners.add(e),e(this.getView()),()=>{this.listeners.delete(e);}}hydrate(e,t=""){this.applyResponse(e,t,true);}seedBootstrap(e){let t={};e.appearance&&(t.appearance=e.appearance),e.returnUrl!==void 0&&(t.returnUrl=e.returnUrl),Object.keys(t).length>0&&this.setState(t);}async load(){await this.runShow(void 0);}async selectCountry(e){await this.runShow({country:e});}async selectCurrency(e){let t=this.state.catalogue?.country.code;await this.runShow(t?{country:t,currency:e}:{currency:e});}async listCountries(){try{return (await this.transport.countries()).data}catch(e){return this.setError(e),[]}}async pay(e){await this.runMutation(()=>this.transport.pay(this.withCatalogueDefaults(e)),false);}clearError(){this.state.error===null&&this.state.dismissedError||this.setState({error:null,dismissedError:true});}async authorize(e){await this.runMutation(()=>this.transport.authorize(e),false);}async poll(){await this.runMutation(()=>this.transport.poll(),false);}async resumeFromRedirect(){await this.poll();}startPolling(){this.destroyed||this.state.polling||(this.setState({polling:true}),this.pollTick=0,this.scheduleNextPoll());}stopPolling(){this.pollHandle!==null&&(this.clearTimeoutImpl(this.pollHandle),this.pollHandle=null),this.state.polling&&this.setState({polling:false});}destroy(){this.destroyed=true,this.stopPolling(),this.listeners.clear();}async runShow(e){try{let t=await this.transport.show(e);this.applyResponse(t.data,t.message??"",!0);}catch(t){this.setError(t);}}async runMutation(e,t){try{let o=await e();this.applyResponse(o.data,o.message??"",t);}catch(o){this.setError(o);}}withCatalogueDefaults(e){let t=this.state.catalogue;if(!t)return e;let o={...e};if(o.country===void 0&&(o.country=t.country.code),o.currency===void 0&&t.amount.is_dcc){let n=t.amount.final.currency;n&&(o.currency=n);}return o}applyResponse(e,t,o){let n={checkout:e,message:t,phase:I(e),error:null,dismissedError:false};if(o){let i=A(e);i&&(n.catalogue=i);}this.setState(n),this.reconcilePolling();}setError(e){let t=e instanceof u?e:new u("unknown",X(e)),i=!(t.code==="not_found"||t.code==="not_open")&&this.state.checkout?this.state.phase:"closed";this.setState({error:t,phase:i,message:t.message,dismissedError:false}),this.reconcilePolling();}reconcilePolling(){if(!(!this.autoPoll||this.destroyed)){if(v(this.state.phase)){this.stopPolling();return}this.shouldPoll()?this.startPolling():this.stopPolling();}}shouldPoll(){if(this.state.phase==="processing")return true;if(this.state.phase==="action_required"){let e=this.state.checkout?.attempt?.next_action;return e!=null&&b(e)==="poll"}return false}scheduleNextPoll(){if(this.destroyed||!this.state.polling)return;let e=this.intervals[this.pollTick]??this.steady;this.pollTick++;let t=this.expiresAtMs();if(t!==null&&this.now()>=t){this.stopPolling();return}this.pollHandle=this.setTimeoutImpl(()=>{this.tickPoll().catch(()=>{});},e);}async tickPoll(){if(!(this.destroyed||!this.state.polling||this.pollInFlight)){this.pollInFlight=true;try{await this.poll();}finally{this.pollInFlight=false;}this.state.polling&&!v(this.state.phase)&&this.scheduleNextPoll();}}expiresAtMs(){let e=this.state.checkout?.session.expires_at;if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}setState(e){this.state={...this.state,...e},this.emit();}emit(){let e=this.getView();for(let t of this.listeners)t(e);}};function X(r){return r instanceof Error?r.message:"Unexpected error."}function x(r,e={}){let t=e.doc??document,o=e.navigate??(n=>window.location.assign(n));if(!G(r.url)){console.error(`Orqex: refused redirect to non-https URL "${r.url}".`);return}if(r.method==="POST"){let n=t.createElement("form");n.method="POST",n.action=r.url,n.style.display="none";for(let[i,s]of Object.entries(r.post_data??{})){let c=t.createElement("input");c.type="hidden",c.name=i,c.value=typeof s=="string"?s:JSON.stringify(s),n.appendChild(c);}t.body.appendChild(n),n.submit();return}o(r.url);}function G(r){try{return new URL(r).protocol==="https:"}catch{return false}}function U(r){return r.kind==="action"&&r.ctx.completion==="redirect"&&r.ctx.action.type==="redirect_to_url"?r.ctx.action:null}var Y=r=>`orqex:redirect:${r}`;function Z(r,e,t){let o=Y(e);t.storage.getItem(o)!==null&&(t.storage.removeItem(o),r.resumeFromRedirect());let n=null,i=r.subscribe(c=>{let l=U(c);if(!l||!l.can_auto_redirect||c.kind!=="action")return;let m=`${c.ctx.attempt.id}:${l.type}`;n!==m&&(n=m,t.storage.setItem(o,c.ctx.attempt.id),x(l,{navigate:L=>t.win.location.assign(L),doc:t.win.document}));}),s=()=>{let c=r.getView().kind;(c==="action"||c==="processing")&&r.resumeFromRedirect();};return t.win.addEventListener("pageshow",s),()=>{i(),t.win.removeEventListener("pageshow",s);}}function H(r,e,t={}){let o=t.win??window,n=t.engine??new h(new d({baseUrl:r.apiBaseUrl,auth:{publishableKey:r.publishableKey,publicId:e.publicId},locale:e.locale??(typeof navigator>"u"?void 0:navigator.language),fetchImpl:t.fetchImpl})),i=()=>{},s={subscribe:c=>n.subscribe(c),getView:()=>n.getView(),pay:c=>n.pay(c),authorize:c=>n.authorize(c),poll:()=>n.poll(),selectCountry:c=>n.selectCountry(c),selectCurrency:c=>n.selectCurrency(c),listCountries:()=>n.listCountries(),resumeFromRedirect:()=>n.resumeFromRedirect(),startPolling:()=>n.startPolling(),stopPolling:()=>n.stopPolling(),performRedirect:()=>{let c=U(n.getView());c&&x(c,{navigate:l=>o.location.assign(l),doc:o.document});},destroy:()=>{i(),n.destroy();}};return e.autoResume&&(i=Z(n,e.publicId,{storage:t.storage??o.sessionStorage,win:o})),n.load(),s}var ee=r=>{window.location.assign(r);};function N(r,e,t=ee){if(!e.publicId)throw new Error("Orqex: redirectToCheckout requires a publicId.");t(w(r,e.publicId));}function te(r,e){let t=C(r,e),o=new g,n=new f({config:t,bus:o});return {mount(i,s){n.mount(i,s);},redirectToCheckout(i){N(t,i);},on(i,s){return o.on(i,s)},unmount(){n.unmount();},createEngine(i){return H(t,i)}}}function re(r,e){let t=null;if(r.kind==="succeeded"){let o=String(r.ctx.status);t={message:T(o),key:`succeeded:${o}`};}else if(r.kind==="failed"){let o=String(r.ctx.status);t={message:R(o,r.ctx.message),key:`failed:${o}`};}else if(r.kind==="closed"){let o=String(r.ctx.status);t={message:O(o),key:`closed:${o}`};}return !t||t.key===e?null:t}var Xe="0.0.1";if (typeof window !== "undefined" && window.OrqexSdk) { window.Orqex = window.OrqexSdk.Orqex; }
1
+ var OrqexSdk=(function(exports){'use strict';var j=Object.defineProperty;var B=(r,e,t)=>e in r?j(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t;var a=(r,e,t)=>B(r,typeof e!="symbol"?e+"":e,t);var V=/^pk_(live|test)_[A-Za-z0-9]+$/;function E(r){if(typeof r!="string"||!V.test(r))throw new Error('Orqex: a publishable key ("pk_live_\u2026" or "pk_test_\u2026") is required. Never pass a secret key to the browser.');return {key:r,livemode:r.startsWith("pk_live_")}}var z="https://checkout.orqex.com",$="https://api.orqex.com";function C(r,e={}){let{key:t,livemode:o}=E(r),n=e.checkoutBaseUrl??z,i=n.replace(/\/+$/,""),s;try{s=new URL(i).origin;}catch{throw new Error(`Orqex: invalid checkoutBaseUrl "${n}".`)}let c=(e.apiBaseUrl??$).replace(/\/+$/,"");return {publishableKey:t,livemode:o,checkoutBaseUrl:i,checkoutOrigin:s,apiBaseUrl:c}}function k(r,e,t){let o=encodeURIComponent(e);return `${r.checkoutBaseUrl}/${o}?embed=1&origin=${encodeURIComponent(t)}`}function w(r,e){return `${r.checkoutBaseUrl}/${encodeURIComponent(e)}`}var ae=1,K=["ready","resize","success","error","redirect","close"];function P(r){if(r===null||typeof r!="object")return false;let e=r;return e.__orqex===true&&e.v===1&&typeof e.type=="string"&&K.includes(e.type)}function p(r){return {__orqex:true,v:1,type:r}}function ce(){return p("ready")}function ue(r){return {...p("resize"),height:r}}function T(r){return {...p("success"),status:r}}function R(r,e){return {...p("error"),code:r,message:e}}function le(r){return {...p("redirect"),url:r}}function O(r){return {...p("close"),status:r}}var F="allow-scripts allow-same-origin allow-forms allow-popups",f=class{constructor(e){a(this,"config");a(this,"bus");a(this,"win");a(this,"navigate");a(this,"iframe",null);a(this,"listener",null);this.config=e.config,this.bus=e.bus,this.win=e.win??window,this.navigate=e.navigate??(t=>this.win.location.assign(t));}mount(e,t){if(!t.publicId)throw new Error("Orqex: mount requires a publicId.");let o=this.resolveHost(e);this.unmount();let n=this.win.document.createElement("iframe");n.src=k(this.config,t.publicId,this.win.location.origin),n.setAttribute("sandbox",F),n.setAttribute("allow","payment"),n.setAttribute("title","Orqex Checkout"),n.style.width="100%",n.style.border="none",n.style.height="150px",o.appendChild(n),this.iframe=n;let i=s=>{s.origin===this.config.checkoutOrigin&&s.source===n.contentWindow&&P(s.data)&&this.handle(s.data);};this.win.addEventListener("message",i),this.listener=i;}unmount(){this.listener&&(this.win.removeEventListener("message",this.listener),this.listener=null),this.iframe&&(this.iframe.remove(),this.iframe=null);}handle(e){switch(e.type){case "resize":this.iframe&&(this.iframe.style.height=`${e.height}px`);break;case "success":this.bus.emit("success",{status:e.status});break;case "error":this.bus.emit("error",{code:e.code,message:e.message});break;case "close":this.bus.emit("close",{status:e.status});break;case "redirect":this.bus.emit("redirect",{url:e.url}),this.navigate(e.url);break;}}resolveHost(e){let t=typeof e=="string"?this.win.document.querySelector(e):e;if(!t)throw new Error(`Orqex: mount target "${String(e)}" not found.`);return t}};var g=class{constructor(){a(this,"handlers",{success:new Set,error:new Set,redirect:new Set,close:new Set});}on(e,t){return this.handlers[e].add(t),()=>this.off(e,t)}off(e,t){this.handlers[e].delete(t);}emit(e,t){for(let o of this.handlers[e])try{o(t);}catch(n){console.error(`Orqex: "${e}" event handler threw`,n);}}};var u=class extends Error{constructor(t,o,n){super(o);a(this,"code");a(this,"httpStatus");this.name="CheckoutError",this.code=t,this.httpStatus=n;}};function M(r){switch(r){case 400:return "not_open";case 404:return "not_found";case 422:return "unprocessable";case 429:return "rate_limited";default:return r>=500?"network":"unknown"}}var d=class{constructor(e){a(this,"baseUrl");a(this,"auth");a(this,"locale");a(this,"fetchImpl");a(this,"timeoutMs");let t=e.fetchImpl??(typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0);if(!t)throw new u("unknown","No fetch implementation available; pass options.fetchImpl.");if(!e.auth?.publishableKey||!e.auth?.publicId)throw new u("unknown","HttpTransport requires `auth` with publishableKey and publicId.");this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.auth=e.auth,this.locale=e.locale,this.fetchImpl=t,this.timeoutMs=e.timeoutMs??2e4;}show(e){return this.request("GET",this.path(""),{query:{country:e?.country,currency:e?.currency}})}countries(){return this.request("GET",this.path("/countries"))}pay(e){return this.request("POST",this.path("/pay"),{body:e})}authorize(e){return this.request("POST",this.path("/authorize"),{body:e})}poll(){return this.request("GET",this.path("/poll"))}path(e){return `/checkout/${encodeURIComponent(this.auth.publicId)}${e}`}async request(e,t,o){let n=this.baseUrl+t+this.queryString(o?.query),i={Accept:"application/json"};this.locale&&(i["Accept-Language"]=this.locale),i.Authorization=`Bearer ${this.auth.publishableKey}`,o?.body!==void 0&&(i["Content-Type"]="application/json");let s=new AbortController,c=setTimeout(()=>s.abort(),this.timeoutMs),l;try{l=await this.fetchImpl(n,{method:e,headers:i,body:o?.body===void 0?void 0:JSON.stringify(o.body),signal:s.signal});}catch(m){throw new u("network",W(m))}finally{clearTimeout(c);}return this.parse(l)}async parse(e){let t=await e.text().catch(()=>""),o;if(t)try{o=JSON.parse(t);}catch{o=void 0;}if(!e.ok){let n=D(o)??`Request failed with status ${e.status}`;throw new u(M(e.status),n,e.status)}if(o===void 0)throw new u("unknown","Empty or non-JSON response body.",e.status);return o}queryString(e){if(!e)return "";let t=new URLSearchParams;for(let[n,i]of Object.entries(e))i!==void 0&&i!==""&&t.set(n,i);let o=t.toString();return o?`?${o}`:""}};function D(r){if(r&&typeof r=="object"&&"message"in r){let e=r.message;if(typeof e=="string")return e}}function W(r){return r instanceof Error&&r.name==="AbortError"?"Request timed out.":r instanceof Error?r.message:"Network request failed."}function I(r){if(!r)return "loading";let e=r.session.status,t=r.payment?.status,o=r.attempt?.status;return t==="completed"?"succeeded":t==="failed"||t==="expired"?"failed":e!=="open"?e==="completed"?"succeeded":"closed":o==="action_required"?"action_required":o==="processing"?"processing":"collecting"}function v(r){return r==="succeeded"||r==="failed"||r==="closed"}function b(r){switch(r.type){case "collect_otp":return "submit";case "complete_with_sdk":return "sdk";case "redirect_to_url":return "redirect";case "embed_iframe":case "approve_on_phone":case "scan_qr_code":case "display_payment_instructions":return "poll";case "none":return "poll";default:return "poll"}}function Q(r){return r!==null&&r.type!=="none"}function _(r){let{phase:e,checkout:t,catalogue:o}=r;if(e==="loading")return {kind:"loading"};if(!t){let s=e==="succeeded"||e==="failed"?e:"closed";return {kind:s,ctx:y(r,s)}}let n=t.attempt,i=r.appearance;switch(e){case "collecting":{if(!o)return {kind:"loading"};let s={amount:o.amount,methods:o.methods,country:o.country,currencyOptions:o.currencyOptions,supportsAnyCountry:o.supportsAnyCountry,previousPhones:r.previousPhones};return t.restriction&&(s.restriction=t.restriction),t.customer&&(s.customer=t.customer),t.project&&(s.project=t.project),i&&(s.appearance=i),r.dismissedError||(r.error&&(s.lastError=r.error),J(n)&&(s.retryOf=n)),{kind:"form",ctx:s}}case "action_required":{let s=n?.next_action??null;return !n||!Q(s)?n?{kind:"processing",ctx:S(r,n)}:{kind:"loading"}:{kind:"action",ctx:{action:s,attempt:n,completion:b(s),...o?{amount:o.amount}:{},...t.project?{project:t.project}:{},...i?{appearance:i}:{}}}}case "processing":return n?{kind:"processing",ctx:S(r,n)}:{kind:"loading"};case "succeeded":return {kind:"succeeded",ctx:y(r,"succeeded")};case "failed":return {kind:"failed",ctx:y(r,"failed")};case "closed":return {kind:"closed",ctx:y(r,"closed")};default:return {kind:"loading"}}}function J(r){return r!=null&&(r.status==="failed"||r.status==="cancelled")}function S(r,e){let t={attempt:e};return r.catalogue&&(t.amount=r.catalogue.amount),r.checkout?.project&&(t.project=r.checkout.project),r.appearance&&(t.appearance=r.appearance),t}function y(r,e){let t=r.checkout,o=e==="closed"?t?.session.status??"expired":t?.payment?.status??t?.session.status??"expired",n=e==="failed"?t?.attempt?.failure.message:void 0,i="";e==="failed"?i=n??"":e==="succeeded"&&(i=r.message);let s={status:o,message:i};return t?.payment&&(s.payment=t.payment),r.catalogue&&(s.amount=r.catalogue.amount),t?.project&&(s.project=t.project),r.appearance&&(s.appearance=r.appearance),r.returnUrl&&(s.returnUrl=r.returnUrl),s}function q(){return {catalogue:null,previousPhones:[],checkout:null,message:"",phase:"loading",error:null,dismissedError:false,appearance:null,returnUrl:null,polling:false}}function A(r){let{country:e,currency_options:t,amount:o,methods:n}=r;return !e||!t||!o||!n?null:{country:e,currencyOptions:t,amount:o,methods:n,supportsAnyCountry:r.supports_any_country??false}}var h=class{constructor(e,t={}){a(this,"transport",e);a(this,"state",q());a(this,"listeners",new Set);a(this,"autoPoll");a(this,"intervals");a(this,"steady");a(this,"now");a(this,"setTimeoutImpl");a(this,"clearTimeoutImpl");a(this,"pollHandle",null);a(this,"pollTick",0);a(this,"pollInFlight",false);a(this,"destroyed",false);this.autoPoll=t.autoPoll??true,this.intervals=t.pollIntervalsMs??[2e3,2e3,3e3,5e3],this.steady=t.steadyIntervalMs??5e3,this.now=t.now??Date.now,this.setTimeoutImpl=t.setTimeoutImpl??((o,n)=>setTimeout(o,n)),this.clearTimeoutImpl=t.clearTimeoutImpl??(o=>clearTimeout(o));}getView(){return _(this.state)}subscribe(e){return this.listeners.add(e),e(this.getView()),()=>{this.listeners.delete(e);}}hydrate(e,t=""){this.applyResponse(e,t,true);}seedBootstrap(e){let t={};e.appearance&&(t.appearance=e.appearance),e.returnUrl!==void 0&&(t.returnUrl=e.returnUrl),Object.keys(t).length>0&&this.setState(t);}async load(){await this.runShow(void 0);}async selectCountry(e){await this.runShow({country:e});}async selectCurrency(e){let t=this.state.catalogue?.country.code;await this.runShow(t?{country:t,currency:e}:{currency:e});}async listCountries(){try{return (await this.transport.countries()).data}catch(e){return this.setError(e),[]}}async pay(e){await this.runMutation(()=>this.transport.pay(this.withCatalogueDefaults(e)),false);}clearError(){this.state.error===null&&this.state.dismissedError||this.setState({error:null,dismissedError:true});}async authorize(e){await this.runMutation(()=>this.transport.authorize(e),false);}async poll(){await this.runMutation(()=>this.transport.poll(),false);}async resumeFromRedirect(){await this.poll();}startPolling(){this.destroyed||this.state.polling||(this.setState({polling:true}),this.pollTick=0,this.scheduleNextPoll());}stopPolling(){this.pollHandle!==null&&(this.clearTimeoutImpl(this.pollHandle),this.pollHandle=null),this.state.polling&&this.setState({polling:false});}destroy(){this.destroyed=true,this.stopPolling(),this.listeners.clear();}async runShow(e){try{let t=await this.transport.show(e);this.applyResponse(t.data,t.message??"",!0);}catch(t){this.setError(t);}}async runMutation(e,t){try{let o=await e();this.applyResponse(o.data,o.message??"",t);}catch(o){this.setError(o);}}withCatalogueDefaults(e){let t=this.state.catalogue;if(!t)return e;let o={...e};if(o.country===void 0&&(o.country=t.country.code),o.currency===void 0&&t.amount.is_dcc){let n=t.amount.final.currency;n&&(o.currency=n);}return o}applyResponse(e,t,o){let n={checkout:e,message:t,phase:I(e),error:null,dismissedError:false};if(o){let i=A(e);i&&(n.catalogue=i);}e.previous_used_phones!=null&&(n.previousPhones=e.previous_used_phones),this.setState(n),this.reconcilePolling();}setError(e){let t=e instanceof u?e:new u("unknown",X(e)),i=!(t.code==="not_found"||t.code==="not_open")&&this.state.checkout?this.state.phase:"closed";this.setState({error:t,phase:i,message:t.message,dismissedError:false}),this.reconcilePolling();}reconcilePolling(){if(!(!this.autoPoll||this.destroyed)){if(v(this.state.phase)){this.stopPolling();return}this.shouldPoll()?this.startPolling():this.stopPolling();}}shouldPoll(){if(this.state.phase==="processing")return true;if(this.state.phase==="action_required"){let e=this.state.checkout?.attempt?.next_action;return e!=null&&b(e)==="poll"}return false}scheduleNextPoll(){if(this.destroyed||!this.state.polling)return;let e=this.intervals[this.pollTick]??this.steady;this.pollTick++;let t=this.expiresAtMs();if(t!==null&&this.now()>=t){this.stopPolling();return}this.pollHandle=this.setTimeoutImpl(()=>{this.tickPoll().catch(()=>{});},e);}async tickPoll(){if(!(this.destroyed||!this.state.polling||this.pollInFlight)){this.pollInFlight=true;try{await this.poll();}finally{this.pollInFlight=false;}this.state.polling&&!v(this.state.phase)&&this.scheduleNextPoll();}}expiresAtMs(){let e=this.state.checkout?.session.expires_at;if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}setState(e){this.state={...this.state,...e},this.emit();}emit(){let e=this.getView();for(let t of this.listeners)t(e);}};function X(r){return r instanceof Error?r.message:"Unexpected error."}function x(r,e={}){let t=e.doc??document,o=e.navigate??(n=>window.location.assign(n));if(!G(r.url)){console.error(`Orqex: refused redirect to non-https URL "${r.url}".`);return}if(r.method==="POST"){let n=t.createElement("form");n.method="POST",n.action=r.url,n.style.display="none";for(let[i,s]of Object.entries(r.post_data??{})){let c=t.createElement("input");c.type="hidden",c.name=i,c.value=typeof s=="string"?s:JSON.stringify(s),n.appendChild(c);}t.body.appendChild(n),n.submit();return}o(r.url);}function G(r){try{return new URL(r).protocol==="https:"}catch{return false}}function U(r){return r.kind==="action"&&r.ctx.completion==="redirect"&&r.ctx.action.type==="redirect_to_url"?r.ctx.action:null}var Y=r=>`orqex:redirect:${r}`;function Z(r,e,t){let o=Y(e);t.storage.getItem(o)!==null&&(t.storage.removeItem(o),r.resumeFromRedirect());let n=null,i=r.subscribe(c=>{let l=U(c);if(!l||!l.can_auto_redirect||c.kind!=="action")return;let m=`${c.ctx.attempt.id}:${l.type}`;n!==m&&(n=m,t.storage.setItem(o,c.ctx.attempt.id),x(l,{navigate:L=>t.win.location.assign(L),doc:t.win.document}));}),s=()=>{let c=r.getView().kind;(c==="action"||c==="processing")&&r.resumeFromRedirect();};return t.win.addEventListener("pageshow",s),()=>{i(),t.win.removeEventListener("pageshow",s);}}function H(r,e,t={}){let o=t.win??window,n=t.engine??new h(new d({baseUrl:r.apiBaseUrl,auth:{publishableKey:r.publishableKey,publicId:e.publicId},locale:e.locale??(typeof navigator>"u"?void 0:navigator.language),fetchImpl:t.fetchImpl})),i=()=>{},s={subscribe:c=>n.subscribe(c),getView:()=>n.getView(),pay:c=>n.pay(c),authorize:c=>n.authorize(c),poll:()=>n.poll(),selectCountry:c=>n.selectCountry(c),selectCurrency:c=>n.selectCurrency(c),listCountries:()=>n.listCountries(),resumeFromRedirect:()=>n.resumeFromRedirect(),startPolling:()=>n.startPolling(),stopPolling:()=>n.stopPolling(),performRedirect:()=>{let c=U(n.getView());c&&x(c,{navigate:l=>o.location.assign(l),doc:o.document});},destroy:()=>{i(),n.destroy();}};return e.autoResume&&(i=Z(n,e.publicId,{storage:t.storage??o.sessionStorage,win:o})),n.load(),s}var ee=r=>{window.location.assign(r);};function N(r,e,t=ee){if(!e.publicId)throw new Error("Orqex: redirectToCheckout requires a publicId.");t(w(r,e.publicId));}function te(r,e){let t=C(r,e),o=new g,n=new f({config:t,bus:o});return {mount(i,s){n.mount(i,s);},redirectToCheckout(i){N(t,i);},on(i,s){return o.on(i,s)},unmount(){n.unmount();},createEngine(i){return H(t,i)}}}function re(r,e){let t=null;if(r.kind==="succeeded"){let o=String(r.ctx.status);t={message:T(o),key:`succeeded:${o}`};}else if(r.kind==="failed"){let o=String(r.ctx.status);t={message:R(o,r.ctx.message),key:`failed:${o}`};}else if(r.kind==="closed"){let o=String(r.ctx.status);t={message:O(o),key:`closed:${o}`};}return !t||t.key===e?null:t}var Xe="0.0.1";if (typeof window !== "undefined" && window.OrqexSdk) { window.Orqex = window.OrqexSdk.Orqex; }
2
2
  exports.ORQEX_PROTOCOL_VERSION=ae;exports.Orqex=te;exports.SDK_VERSION=Xe;exports.closeMessage=O;exports.errorMessage=R;exports.isEmbedMessage=P;exports.projectEmbedMessage=re;exports.readyMessage=ce;exports.redirectMessage=le;exports.resizeMessage=ue;exports.successMessage=T;return exports;})({});//# sourceMappingURL=orqex.global.js.map
3
3
  //# sourceMappingURL=orqex.global.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/key.ts","../src/config.ts","../src/protocol.ts","../src/embedded.ts","../src/event-bus.ts","../../engine/src/types/errors.ts","../../engine/src/transport/http-transport.ts","../../engine/src/engine/phase.ts","../../engine/src/engine/project.ts","../../engine/src/engine/state.ts","../../engine/src/engine/engine.ts","../src/redirect-effect.ts","../src/headless.ts","../src/redirect.ts","../src/orqex.ts","../src/embed-projection.ts","../src/index.ts"],"names":["PK_PATTERN","parsePublishableKey","key","DEFAULT_CHECKOUT_BASE_URL","DEFAULT_API_BASE_URL","resolveConfig","publishableKey","options","livemode","raw","checkoutBaseUrl","checkoutOrigin","apiBaseUrl","buildEmbedUrl","config","publicId","parentOrigin","id","buildRedirectUrl","ORQEX_PROTOCOL_VERSION","KNOWN_TYPES","isEmbedMessage","data","record","base","type","readyMessage","resizeMessage","height","successMessage","status","errorMessage","code","message","redirectMessage","url","closeMessage","SANDBOX","EmbeddedController","deps","__publicField","target","host","iframe","listener","event","EventBus","handler","payload","cause","CheckoutError","httpStatus","errorCodeFromStatus","HttpTransport","fetchImpl","query","body","suffix","method","path","opts","headers","controller","timer","response","describeNetworkError","text","json","extractMessage","params","value","qs","derivePhase","checkout","session","intent","attempt","isTerminalPhase","phase","actionCompletion","action","isActionable","projectView","state","catalogue","kind","result","appearance","ctx","isFailedAttempt","waiting","failureMessage","initialState","extractCatalogue","country","currencies","amount","methods","CheckoutEngine","transport","cb","ms","handle","fn","input","next","currency","res","call","isShow","error","toMessage","delay","expiresAt","partial","view","performActionRedirect","doc","navigate","isHttps","form","name","redirectActionOf","markerKey","wireAutoResume","engine","handled","unsubscribe","dedupe","onPageShow","createHeadlessCheckout","win","autoResumeTeardown","facade","defaultNavigate","redirectToCheckout","Orqex","bus","embedded","mountOptions","redirectOptions","engineOptions","projectEmbedMessage","lastKey","projection","SDK_VERSION"],"mappings":"uNAMA,IAAMA,CAAA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CAAM,CAAA,CAAG,EAC1F,SAAWqF,CAAAA,CAAK,IAAA,GAAS,SAAU,CACjC,IAAMrF,CAAAA,CAAS,MAAA,CAAOqF,CAAAA,CAAK,GAAA,CAAI,MAAM,CAAA,CACrC6B,CAAAA,CAAa,CAAE,OAAA,CAAS5G,CAAAA,CAAaN,CAAM,CAAA,CAAG,GAAA,CAAK,CAAA,OAAA,EAAUA,CAAM,CAAA,CAAG,EACxE,CAEA,OAAI,CAACkH,GAAcA,CAAAA,CAAW,GAAA,GAAQD,EAAgB,IAAA,CAC/CC,CACT,CCzBO,IAAMC,EAAAA,CAAc","file":"orqex.global.js","sourcesContent":["/** Parsed publishable key: the raw string plus the environment it targets. */\nexport interface ParsedKey {\n key: string;\n livemode: boolean;\n}\n\nconst PK_PATTERN = /^pk_(live|test)_[A-Za-z0-9]+$/;\n\n/**\n * Validate the client key shape. Only `pk_live_…` / `pk_test_…` are accepted;\n * anything else (empty, `sk_…`, M2M secret, malformed) throws. The publishable\n * key is public by design, so no value here is treated as sensitive.\n */\nexport function parsePublishableKey(key: string): ParsedKey {\n if (typeof key !== 'string' || !PK_PATTERN.test(key)) {\n throw new Error(\n 'Orqex: a publishable key (\"pk_live_…\" or \"pk_test_…\") is required. Never pass a secret key to the browser.',\n );\n }\n return { key, livemode: key.startsWith('pk_live_') };\n}\n","import { parsePublishableKey } from './key';\n\n/**\n * Default hosted-checkout origin. PLACEHOLDER — confirm the real production\n * origin before release; merchants can always override via\n * `Orqex(pk, { checkoutBaseUrl })`.\n */\nexport const DEFAULT_CHECKOUT_BASE_URL = 'https://checkout.orqex.com';\n\n/**\n * Default API origin the headless engine calls with pk_. PLACEHOLDER — confirm\n * the real production API origin before release; override via\n * `Orqex(pk, { apiBaseUrl })`.\n */\nexport const DEFAULT_API_BASE_URL = 'https://api.orqex.com';\n\nexport interface OrqexOptions {\n /** Override the hosted-checkout origin (e.g. a staging or self-hosted deploy). */\n checkoutBaseUrl?: string;\n /** Override the API origin the headless engine calls (e.g. staging). */\n apiBaseUrl?: string;\n}\n\nexport interface ResolvedConfig {\n publishableKey: string;\n livemode: boolean;\n /** Hosted-checkout base, no trailing slash. */\n checkoutBaseUrl: string;\n /** Origin of `checkoutBaseUrl`; the only origin we accept inbound messages from. */\n checkoutOrigin: string;\n /** API origin for headless engine requests, no trailing slash. */\n apiBaseUrl: string;\n}\n\nexport function resolveConfig(publishableKey: string, options: OrqexOptions = {}): ResolvedConfig {\n const { key, livemode } = parsePublishableKey(publishableKey);\n const raw = options.checkoutBaseUrl ?? DEFAULT_CHECKOUT_BASE_URL;\n const checkoutBaseUrl = raw.replace(/\\/+$/, '');\n let checkoutOrigin: string;\n try {\n checkoutOrigin = new URL(checkoutBaseUrl).origin;\n } catch {\n throw new Error(`Orqex: invalid checkoutBaseUrl \"${raw}\".`);\n }\n const apiBaseUrl = (options.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\\/+$/, '');\n return { publishableKey: key, livemode, checkoutBaseUrl, checkoutOrigin, apiBaseUrl };\n}\n\nexport function buildEmbedUrl(config: ResolvedConfig, publicId: string, parentOrigin: string): string {\n const id = encodeURIComponent(publicId);\n return `${config.checkoutBaseUrl}/${id}?embed=1&origin=${encodeURIComponent(parentOrigin)}`;\n}\n\nexport function buildRedirectUrl(config: ResolvedConfig, publicId: string): string {\n return `${config.checkoutBaseUrl}/${encodeURIComponent(publicId)}`;\n}\n","/**\n * The embed postMessage protocol: the wire contract between the hosted checkout\n * (inside a sandboxed iframe) and the SDK running in the merchant's top window.\n *\n * Every message carries `__orqex: true` and `v` (version) so each side can\n * reject foreign or mis-versioned traffic. This module is the single source of\n * truth: `checkout-next` imports it to emit, `checkout-js` imports it to receive.\n */\n\nexport const ORQEX_PROTOCOL_VERSION = 1;\n\nexport type EmbedMessageType = 'ready' | 'resize' | 'success' | 'error' | 'redirect' | 'close';\n\ninterface Base<T extends EmbedMessageType> {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __orqex: true;\n v: number;\n type: T;\n}\n\nexport type ReadyMessage = Base<'ready'>;\nexport interface ResizeMessage extends Base<'resize'> {\n height: number;\n}\nexport interface SuccessMessage extends Base<'success'> {\n status: string;\n}\nexport interface ErrorMessage extends Base<'error'> {\n code: string;\n message: string;\n}\nexport interface RedirectMessage extends Base<'redirect'> {\n url: string;\n}\nexport interface CloseMessage extends Base<'close'> {\n status: string;\n}\n\nexport type EmbedMessage =\n | ReadyMessage\n | ResizeMessage\n | SuccessMessage\n | ErrorMessage\n | RedirectMessage\n | CloseMessage;\n\nconst KNOWN_TYPES: ReadonlyArray<EmbedMessageType> = ['ready', 'resize', 'success', 'error', 'redirect', 'close'];\n\n/** Structural + version guard for messages arriving over postMessage. */\nexport function isEmbedMessage(data: unknown): data is EmbedMessage {\n if (data === null || typeof data !== 'object') return false;\n const record = data as Record<string, unknown>;\n return (\n record.__orqex === true &&\n record.v === ORQEX_PROTOCOL_VERSION &&\n typeof record.type === 'string' &&\n KNOWN_TYPES.includes(record.type as EmbedMessageType)\n );\n}\n\nfunction base<T extends EmbedMessageType>(type: T): Base<T> {\n // eslint-disable-next-line @typescript-eslint/naming-convention, id-length\n return { __orqex: true, v: ORQEX_PROTOCOL_VERSION, type };\n}\n\nexport function readyMessage(): ReadyMessage {\n return base('ready');\n}\nexport function resizeMessage(height: number): ResizeMessage {\n return { ...base('resize'), height };\n}\nexport function successMessage(status: string): SuccessMessage {\n return { ...base('success'), status };\n}\nexport function errorMessage(code: string, message: string): ErrorMessage {\n return { ...base('error'), code, message };\n}\nexport function redirectMessage(url: string): RedirectMessage {\n return { ...base('redirect'), url };\n}\nexport function closeMessage(status: string): CloseMessage {\n return { ...base('close'), status };\n}\n","import { buildEmbedUrl, type ResolvedConfig } from './config';\nimport type { EventBus } from './event-bus';\nimport { isEmbedMessage, type EmbedMessage } from './protocol';\n\nexport interface MountOptions {\n publicId: string;\n}\n\nexport interface EmbeddedControllerDeps {\n config: ResolvedConfig;\n bus: EventBus;\n /** Injectable for tests; defaults to the global window. */\n win?: Window;\n /** Top-level navigation for redirect messages; injectable for tests. */\n navigate?: (url: string) => void;\n}\n\nconst SANDBOX = 'allow-scripts allow-same-origin allow-forms allow-popups';\n\n/**\n * Owns the sandboxed hosted-checkout iframe: creation, the origin-guarded\n * message listener, auto-resize, redirect bubbling, and teardown.\n */\nexport class EmbeddedController {\n private readonly config: ResolvedConfig;\n private readonly bus: EventBus;\n private readonly win: Window;\n private readonly navigate: (url: string) => void;\n\n private iframe: HTMLIFrameElement | null = null;\n private listener: ((event: MessageEvent) => void) | null = null;\n\n constructor(deps: EmbeddedControllerDeps) {\n this.config = deps.config;\n this.bus = deps.bus;\n this.win = deps.win ?? window;\n this.navigate = deps.navigate ?? ((url) => this.win.location.assign(url));\n }\n\n mount(target: string | HTMLElement, options: MountOptions): void {\n if (!options.publicId) throw new Error('Orqex: mount requires a publicId.');\n const host = this.resolveHost(target);\n this.unmount();\n\n const iframe = this.win.document.createElement('iframe');\n iframe.src = buildEmbedUrl(this.config, options.publicId, this.win.location.origin);\n iframe.setAttribute('sandbox', SANDBOX);\n iframe.setAttribute('allow', 'payment');\n iframe.setAttribute('title', 'Orqex Checkout');\n iframe.style.width = '100%';\n iframe.style.border = 'none';\n iframe.style.height = '150px';\n host.appendChild(iframe);\n this.iframe = iframe;\n\n const listener = (event: MessageEvent): void => {\n if (event.origin !== this.config.checkoutOrigin) return;\n if (event.source !== iframe.contentWindow) return;\n if (!isEmbedMessage(event.data)) return;\n this.handle(event.data);\n };\n this.win.addEventListener('message', listener);\n this.listener = listener;\n }\n\n unmount(): void {\n if (this.listener) {\n this.win.removeEventListener('message', this.listener);\n this.listener = null;\n }\n if (this.iframe) {\n this.iframe.remove();\n this.iframe = null;\n }\n }\n\n private handle(message: EmbedMessage): void {\n switch (message.type) {\n case 'resize':\n if (this.iframe) this.iframe.style.height = `${message.height}px`;\n break;\n case 'success':\n this.bus.emit('success', { status: message.status });\n break;\n case 'error':\n this.bus.emit('error', { code: message.code, message: message.message });\n break;\n case 'close':\n this.bus.emit('close', { status: message.status });\n break;\n case 'redirect':\n // The iframe cannot navigate the top window; the SDK does it here.\n this.bus.emit('redirect', { url: message.url });\n this.navigate(message.url);\n break;\n case 'ready':\n break;\n }\n }\n\n private resolveHost(target: string | HTMLElement): HTMLElement {\n const host = typeof target === 'string' ? this.win.document.querySelector<HTMLElement>(target) : target;\n if (!host) throw new Error(`Orqex: mount target \"${String(target)}\" not found.`);\n return host;\n }\n}\n","/** Merchant-facing lifecycle events for embedded/redirect modes. */\nexport type MerchantEvent = 'success' | 'error' | 'redirect' | 'close';\n\nexport interface EventPayloads {\n success: { status: string };\n error: { code: string; message: string };\n redirect: { url: string };\n close: { status: string };\n}\n\ntype Handler<TEvent extends MerchantEvent> = (payload: EventPayloads[TEvent]) => void;\n\n/**\n * Minimal typed pub/sub. A handler that throws is caught and logged so a single\n * bad merchant callback cannot break delivery to the others.\n */\nexport class EventBus {\n private readonly handlers: { [TEvent in MerchantEvent]: Set<Handler<TEvent>> } = {\n success: new Set(),\n error: new Set(),\n redirect: new Set(),\n close: new Set(),\n };\n\n on<TEvent extends MerchantEvent>(event: TEvent, handler: Handler<TEvent>): () => void {\n this.handlers[event].add(handler);\n return () => this.off(event, handler);\n }\n\n off<TEvent extends MerchantEvent>(event: TEvent, handler: Handler<TEvent>): void {\n this.handlers[event].delete(handler);\n }\n\n emit<TEvent extends MerchantEvent>(event: TEvent, payload: EventPayloads[TEvent]): void {\n for (const handler of this.handlers[event]) {\n try {\n handler(payload);\n } catch (cause) {\n // eslint-disable-next-line no-console\n console.error(`Orqex: \"${event}\" event handler threw`, cause);\n }\n }\n }\n}\n","/**\n * Typed error model. The envelope `message` from the server is customer-safe\n * and is carried through verbatim.\n */\n\nexport const CHECKOUT_ERROR_CODE = [\n // 404: token unknown or expired\n 'not_found',\n // 400: session not open\n 'not_open',\n // 422: validation / intent final / restriction\n 'unprocessable',\n // 429: throttle:60,1\n 'rate_limited',\n // transport failure / no response\n 'network',\n 'unknown',\n] as const;\nexport type CheckoutErrorCode = (typeof CHECKOUT_ERROR_CODE)[number];\n\nexport class CheckoutError extends Error {\n readonly code: CheckoutErrorCode;\n readonly httpStatus?: number;\n\n constructor(code: CheckoutErrorCode, message: string, httpStatus?: number) {\n super(message);\n this.name = 'CheckoutError';\n this.code = code;\n this.httpStatus = httpStatus;\n }\n}\n\nexport function errorCodeFromStatus(status: number): CheckoutErrorCode {\n switch (status) {\n case 400:\n return 'not_open';\n case 404:\n return 'not_found';\n case 422:\n return 'unprocessable';\n case 429:\n return 'rate_limited';\n default:\n return status >= 500 ? 'network' : 'unknown';\n }\n}\n\n/** Terminal errors close the checkout; others are recoverable in-place. */\nexport function isTerminalError(code: CheckoutErrorCode): boolean {\n return code === 'not_found' || code === 'not_open';\n}\n","import type {\n AuthorizeInput,\n CountriesResponse,\n Envelope,\n HostedCheckout,\n PayInput,\n ShowQuery,\n} from '../types/contract';\nimport { CheckoutError, errorCodeFromStatus } from '../types/errors';\n\nimport type { Transport } from './transport';\n\ntype FetchLike = (input: string, init?: RequestInit) => Promise<Response>;\n\n/**\n * Publishable-key auth (Stripe-aligned, backend PR #105 onward).\n *\n * `publishableKey` is the project `pk_...`, obtained server-side via the M2M\n * `/checkout/bootstrap` call and handed to the client. It is sent as\n * `Authorization: Bearer pk_...` on every checkout request. `publicId` is the\n * `cs_...` CheckoutSession pointer, addressed as `/checkout/{publicId}`.\n *\n * `pk_` is publishable: client exposure is expected. No secret ever reaches the\n * browser, so nothing here needs to be hidden from the instance.\n */\nexport interface PublishableKeyAuth {\n /** pk_... project publishable key. */\n publishableKey: string;\n /** cs_... CheckoutSession public id. */\n publicId: string;\n}\n\nexport interface HttpTransportOptions {\n /** API base, e.g. \"https://api.orqex.com\". No trailing slash required. */\n baseUrl: string;\n /** Publishable-key auth (pk_ + public_id). */\n auth: PublishableKeyAuth;\n /** BCP-47 language for Accept-Language (e.g. from appearance.lang). */\n locale?: string;\n /** Injectable fetch (defaults to global). Keeps the engine env-agnostic. */\n fetchImpl?: FetchLike;\n /** Per-request timeout in ms. Default 20000. */\n timeoutMs?: number;\n}\n\n/**\n * Real transport against the hosted-checkout endpoints.\n *\n * Auth is `Bearer pk_` against `/checkout/{publicId}`. Errors map to\n * CheckoutError; the server's `message` is preserved for customer display.\n */\nexport class HttpTransport implements Transport {\n private readonly baseUrl: string;\n private readonly auth: PublishableKeyAuth;\n private readonly locale?: string;\n private readonly fetchImpl: FetchLike;\n private readonly timeoutMs: number;\n\n constructor(options: HttpTransportOptions) {\n // Bind to globalThis: a bare `globalThis.fetch` reference loses its `this`\n // and browsers reject the detached call (\"Illegal invocation\").\n const fetchImpl =\n options.fetchImpl ??\n (typeof globalThis.fetch === 'function' ? (globalThis.fetch.bind(globalThis) as FetchLike) : undefined);\n if (!fetchImpl) {\n throw new CheckoutError('unknown', 'No fetch implementation available; pass options.fetchImpl.');\n }\n if (!options.auth?.publishableKey || !options.auth?.publicId) {\n throw new CheckoutError('unknown', 'HttpTransport requires `auth` with publishableKey and publicId.');\n }\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '');\n this.auth = options.auth;\n this.locale = options.locale;\n this.fetchImpl = fetchImpl;\n this.timeoutMs = options.timeoutMs ?? 20_000;\n }\n\n show(query?: ShowQuery): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('GET', this.path(''), {\n query: { country: query?.country, currency: query?.currency },\n });\n }\n\n countries(): Promise<CountriesResponse> {\n return this.request<CountriesResponse>('GET', this.path('/countries'));\n }\n\n pay(body: PayInput): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('POST', this.path('/pay'), { body });\n }\n\n authorize(body: AuthorizeInput): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('POST', this.path('/authorize'), { body });\n }\n\n poll(): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('GET', this.path('/poll'));\n }\n\n /**\n * Build the resource path: `/checkout/{publicId}{suffix}`.\n *\n * One surface shared by the hosted page and the SDK (backend PR #105):\n * `GET ''` (show), `POST /pay`, `POST /authorize`, `GET /poll`,\n * `GET /countries`. Scoped to the pk_'s project — a public_id from another\n * project returns 404 (the engine maps that to a terminal not_found).\n */\n private path(suffix: string): string {\n return `/checkout/${encodeURIComponent(this.auth.publicId)}${suffix}`;\n }\n\n private async request<T>(\n method: string,\n path: string,\n opts?: { query?: Record<string, string | undefined>; body?: unknown },\n ): Promise<T> {\n const url = this.baseUrl + path + this.queryString(opts?.query);\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const headers: Record<string, string> = { Accept: 'application/json' };\n if (this.locale) headers['Accept-Language'] = this.locale;\n headers.Authorization = `Bearer ${this.auth.publishableKey}`;\n if (opts?.body !== undefined) headers['Content-Type'] = 'application/json';\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method,\n headers,\n body: opts?.body === undefined ? undefined : JSON.stringify(opts.body),\n signal: controller.signal,\n });\n } catch (cause) {\n throw new CheckoutError('network', describeNetworkError(cause));\n } finally {\n clearTimeout(timer);\n }\n\n return this.parse<T>(response);\n }\n\n private async parse<T>(response: Response): Promise<T> {\n const text = await response.text().catch(() => '');\n let json: unknown;\n if (text) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n\n if (!response.ok) {\n const message = extractMessage(json) ?? `Request failed with status ${response.status}`;\n throw new CheckoutError(errorCodeFromStatus(response.status), message, response.status);\n }\n\n if (json === undefined) {\n throw new CheckoutError('unknown', 'Empty or non-JSON response body.', response.status);\n }\n return json as T;\n }\n\n private queryString(query?: Record<string, string | undefined>): string {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== '') params.set(key, value);\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n }\n}\n\nfunction extractMessage(json: unknown): string | undefined {\n if (json && typeof json === 'object' && 'message' in json) {\n const message = (json as { message: unknown }).message;\n if (typeof message === 'string') return message;\n }\n return undefined;\n}\n\nfunction describeNetworkError(cause: unknown): string {\n if (cause instanceof Error && cause.name === 'AbortError') return 'Request timed out.';\n if (cause instanceof Error) return cause.message;\n return 'Network request failed.';\n}\n","import type { HostedCheckout } from '../types/contract';\n\nimport type { CheckoutPhase } from './state';\n\n/**\n * Project server state into a phase. The SERVER owns the state machine; this is\n * a pure read-only projection. Order matters — first match wins.\n *\n * intent completed -> succeeded\n * intent failed/expired -> failed\n * session not open (not completed) -> closed\n * attempt action_required -> action_required\n * attempt processing -> processing\n * else (open, no/failed attempt) -> collecting (retry)\n */\nexport function derivePhase(checkout: HostedCheckout | null): CheckoutPhase {\n if (!checkout) return 'loading';\n\n const session = checkout.session.status;\n const intent = checkout.payment?.status;\n const attempt = checkout.attempt?.status;\n\n if (intent === 'completed') return 'succeeded';\n if (intent === 'failed' || intent === 'expired') return 'failed';\n\n if (session !== 'open') {\n return session === 'completed' ? 'succeeded' : 'closed';\n }\n\n // Session is open from here.\n if (attempt === 'action_required') return 'action_required';\n if (attempt === 'processing') return 'processing';\n\n // No attempt yet, or the last attempt failed/cancelled while the session is\n // still open: the customer can retry.\n return 'collecting';\n}\n\n/** Phases at which polling makes sense. */\nexport function isPollablePhase(phase: CheckoutPhase): boolean {\n return phase === 'processing' || phase === 'action_required';\n}\n\nexport function isTerminalPhase(phase: CheckoutPhase): boolean {\n return phase === 'succeeded' || phase === 'failed' || phase === 'closed';\n}\n","import type { AttemptSummary } from '../types/contract';\nimport type { NextAction } from '../types/next-action';\nimport type { ActionCompletion, CheckoutView, FormContext, ResultContext, WaitingContext } from '../types/view';\n\nimport type { EngineState } from './state';\n\n/**\n * Behavior mapping: given a next_action type, how does it complete? This is\n * the single place that decides submit/poll/redirect/sdk so a theme never has\n * to. Unknown types fail closed to `poll`.\n */\nexport function actionCompletion(action: NextAction): ActionCompletion {\n switch (action.type) {\n case 'collect_otp':\n return 'submit';\n case 'complete_with_sdk':\n return 'sdk';\n case 'redirect_to_url':\n return 'redirect';\n case 'embed_iframe':\n case 'approve_on_phone':\n case 'scan_qr_code':\n case 'display_payment_instructions':\n return 'poll';\n case 'none':\n return 'poll';\n default:\n // Unknown/forward-compat action type: wait and poll, never crash a theme.\n return 'poll';\n }\n}\n\n/** An action is renderable as an `action` view only if it asks for something. */\nfunction isActionable(action: NextAction | null): action is NextAction {\n return action !== null && action.type !== 'none';\n}\n\n/**\n * Pure projection: EngineState -> CheckoutView. No I/O, no mutation.\n */\nexport function projectView(state: EngineState): CheckoutView {\n const { phase, checkout, catalogue } = state;\n\n if (phase === 'loading') {\n return { kind: 'loading' };\n }\n if (!checkout) {\n // Forced terminal phase before any checkout loaded (e.g. 404 on first load).\n const kind = phase === 'succeeded' || phase === 'failed' ? phase : 'closed';\n return { kind, ctx: result(state, kind) };\n }\n\n const attempt = checkout.attempt;\n // Appearance is bootstrap-scoped now (not on show/pay/poll), so it lives in\n // engine state and is projected onto every view.\n const appearance = state.appearance;\n\n switch (phase) {\n case 'collecting': {\n if (!catalogue) return { kind: 'loading' };\n const ctx: FormContext = {\n amount: catalogue.amount,\n methods: catalogue.methods,\n country: catalogue.country,\n currencies: catalogue.currencies,\n supportsAnyCountry: catalogue.supportsAnyCountry,\n previousPhones: checkout.previous_used_phones ?? [],\n };\n if (checkout.restriction) ctx.restriction = checkout.restriction;\n if (checkout.customer) ctx.customer = checkout.customer;\n if (checkout.project) ctx.project = checkout.project;\n if (appearance) ctx.appearance = appearance;\n if (!state.dismissedError) {\n if (state.error) ctx.lastError = state.error;\n if (isFailedAttempt(attempt)) ctx.retryOf = attempt;\n }\n return { kind: 'form', ctx };\n }\n\n case 'action_required': {\n const action = attempt?.next_action ?? null;\n // action_required but nothing to render (null / none) -> wait + poll.\n if (!attempt || !isActionable(action)) {\n return attempt ? { kind: 'processing', ctx: waiting(state, attempt) } : { kind: 'loading' };\n }\n return {\n kind: 'action',\n ctx: {\n action,\n attempt,\n completion: actionCompletion(action),\n ...(catalogue ? { amount: catalogue.amount } : {}),\n ...(checkout.project ? { project: checkout.project } : {}),\n ...(appearance ? { appearance } : {}),\n },\n };\n }\n\n case 'processing': {\n return attempt ? { kind: 'processing', ctx: waiting(state, attempt) } : { kind: 'loading' };\n }\n\n case 'succeeded':\n return { kind: 'succeeded', ctx: result(state, 'succeeded') };\n\n case 'failed':\n return { kind: 'failed', ctx: result(state, 'failed') };\n\n case 'closed':\n return { kind: 'closed', ctx: result(state, 'closed') };\n\n default:\n return { kind: 'loading' };\n }\n}\n\nfunction isFailedAttempt(attempt: AttemptSummary | undefined): attempt is AttemptSummary {\n return attempt != null && (attempt.status === 'failed' || attempt.status === 'cancelled');\n}\n\nfunction waiting(state: EngineState, attempt: AttemptSummary): WaitingContext {\n const ctx: WaitingContext = { attempt };\n if (state.catalogue) ctx.amount = state.catalogue.amount;\n if (state.checkout?.project) ctx.project = state.checkout.project;\n if (state.appearance) ctx.appearance = state.appearance;\n return ctx;\n}\n\nfunction result(state: EngineState, kind: 'succeeded' | 'failed' | 'closed'): ResultContext {\n const checkout = state.checkout;\n\n // A closed checkout is closed because of the SESSION (expired/cancelled);\n // the intent may still read 'pending'. Success/failure come from the intent.\n const status =\n kind === 'closed'\n ? (checkout?.session.status ?? 'expired')\n : (checkout?.payment?.status ?? checkout?.session.status ?? 'expired');\n\n // For a failure, the customer-facing reason is the attempt's failure message,\n // not the generic envelope message. Terminal copy is otherwise the theme's job.\n const failureMessage = kind === 'failed' ? checkout?.attempt?.failure.message : undefined;\n\n let message = '';\n if (kind === 'failed') message = failureMessage ?? '';\n else if (kind === 'succeeded') message = state.message;\n const ctx: ResultContext = { status, message };\n if (checkout?.payment) ctx.payment = checkout.payment;\n if (state.catalogue) ctx.amount = state.catalogue.amount;\n if (checkout?.project) ctx.project = checkout.project;\n if (state.appearance) ctx.appearance = state.appearance;\n if (state.returnUrl) ctx.returnUrl = state.returnUrl;\n return ctx;\n}\n","import type { Appearance, Country, Currency, HostedCheckout, PaymentMethod, ResolvedAmount } from '../types/contract';\nimport type { CheckoutError } from '../types/errors';\n\n/**\n * The resolved catalogue is returned ONLY by `show`. `pay`/`authorize`/`poll`\n * omit it, so the engine caches the last good catalogue and re-fetches it only\n * when country/currency changes. See contract.ts › HostedCheckout.\n */\nexport interface ResolvedCatalogue {\n country: Country;\n currencies: Currency[];\n amount: ResolvedAmount;\n methods: PaymentMethod[];\n supportsAnyCountry: boolean;\n}\n\nexport type CheckoutPhase =\n | 'loading'\n | 'closed'\n | 'succeeded'\n | 'failed'\n | 'action_required'\n | 'processing'\n | 'collecting';\n\nexport interface EngineState {\n /** Last good catalogue from `show`. */\n catalogue: ResolvedCatalogue | null;\n /** Last response from any endpoint. */\n checkout: HostedCheckout | null;\n /** Server `message` from the last successful response. */\n message: string;\n phase: CheckoutPhase;\n error: CheckoutError | null;\n /**\n * The customer dismissed the current error banner (e.g. by reselecting a\n * method). Suppresses both banner sources (`lastError`, `retryOf`) until the\n * next server response, which resets it.\n */\n dismissedError: boolean;\n /**\n * Session-scoped chrome from the bootstrap payload. `appearance` is no longer\n * on show/pay/poll responses, so the engine holds it here and projects it on\n * every view. `returnUrl` (nullable, may be absent for old sessions) is the\n * merchant redirect target for the terminal \"return\" CTA.\n */\n appearance: Appearance | null;\n returnUrl: string | null;\n polling: boolean;\n}\n\nexport function initialState(): EngineState {\n return {\n catalogue: null,\n checkout: null,\n message: '',\n phase: 'loading',\n error: null,\n dismissedError: false,\n appearance: null,\n returnUrl: null,\n polling: false,\n };\n}\n\n/** Pull the catalogue out of a `show` response; null if not present. */\nexport function extractCatalogue(checkout: HostedCheckout): ResolvedCatalogue | null {\n const { country, currencies, amount, methods } = checkout;\n if (!country || !currencies || !amount || !methods) return null;\n return {\n country,\n currencies,\n amount,\n methods,\n supportsAnyCountry: checkout.supports_any_country ?? false,\n };\n}\n","import type { Appearance, AuthorizeInput, CountrySimplified, HostedCheckout, PayInput } from '../types/contract';\nimport { CheckoutError } from '../types/errors';\nimport type { CheckoutView } from '../types/view';\nimport type { Transport } from '../transport/transport';\n\nimport { derivePhase, isTerminalPhase } from './phase';\nimport { actionCompletion, projectView } from './project';\nimport { extractCatalogue, initialState, type EngineState } from './state';\n\nexport interface CheckoutEngineOptions {\n /** Auto-manage the polling loop based on phase. Default true. */\n autoPoll?: boolean;\n /** Backoff delays (ms) for the first polls. Default [2000,2000,3000,5000]. */\n pollIntervalsMs?: number[];\n /** Steady interval (ms) after the backoff ramp. Default 5000. */\n steadyIntervalMs?: number;\n /** Clock injection for tests. Default Date.now. */\n now?: () => number;\n /** Timer injection for tests. Default global setTimeout/clearTimeout. */\n setTimeoutImpl?: (cb: () => void, ms: number) => ReturnType<typeof setTimeout>;\n clearTimeoutImpl?: (handle: ReturnType<typeof setTimeout>) => void;\n}\n\ntype Listener = (view: CheckoutView) => void;\n\n/**\n * The engine facade themes consume. Owns state, the polling loop, and all\n * transport calls. Themes never see the Transport, the wire types, or the\n * token — only CheckoutView (via getView/subscribe) and these action methods.\n */\nexport class CheckoutEngine {\n private state: EngineState = initialState();\n private readonly listeners = new Set<Listener>();\n\n private readonly autoPoll: boolean;\n private readonly intervals: number[];\n private readonly steady: number;\n private readonly now: () => number;\n private readonly setTimeoutImpl: NonNullable<CheckoutEngineOptions['setTimeoutImpl']>;\n private readonly clearTimeoutImpl: NonNullable<CheckoutEngineOptions['clearTimeoutImpl']>;\n\n private pollHandle: ReturnType<typeof setTimeout> | null = null;\n private pollTick = 0;\n private pollInFlight = false;\n private destroyed = false;\n\n constructor(\n private readonly transport: Transport,\n options: CheckoutEngineOptions = {},\n ) {\n this.autoPoll = options.autoPoll ?? true;\n this.intervals = options.pollIntervalsMs ?? [2000, 2000, 3000, 5000];\n this.steady = options.steadyIntervalMs ?? 5000;\n this.now = options.now ?? Date.now;\n this.setTimeoutImpl = options.setTimeoutImpl ?? ((cb, ms) => setTimeout(cb, ms));\n this.clearTimeoutImpl = options.clearTimeoutImpl ?? ((handle) => clearTimeout(handle));\n }\n\n // --- read surface ---\n\n getView(): CheckoutView {\n return projectView(this.state);\n }\n\n /** Subscribe to view changes. Fires immediately with the current view. */\n subscribe(fn: Listener): () => void {\n this.listeners.add(fn);\n fn(this.getView());\n return () => {\n this.listeners.delete(fn);\n };\n }\n\n // --- actions ---\n\n /**\n * Seed state from a server-fetched `show` payload (SSR) so the first paint is\n * the form, not the loading screen — no transport call. The host passes the\n * `GET /checkout/{public_id}` payload the SSR layer fetched after bootstrap.\n * Treated exactly like a `show`, so the resolved catalogue is cached. The\n * engine may still `poll()`/`load()` afterwards to refresh.\n */\n hydrate(checkout: HostedCheckout, message = ''): void {\n this.applyResponse(checkout, message, true);\n }\n\n /**\n * Seed session-scoped chrome from the SSR bootstrap payload. `appearance` and\n * `return_url` no longer ride on show/pay/poll responses, so the host passes\n * them once here and the engine projects them onto every view. Call before the\n * first render (alongside `hydrate`) so the theme paints branded from frame 1.\n */\n seedBootstrap(input: { appearance?: Appearance | null; returnUrl?: string | null }): void {\n const next: Partial<EngineState> = {};\n if (input.appearance) next.appearance = input.appearance;\n if (input.returnUrl !== undefined) next.returnUrl = input.returnUrl;\n if (Object.keys(next).length > 0) this.setState(next);\n }\n\n async load(): Promise<void> {\n await this.runShow(undefined);\n }\n\n async selectCountry(country: string): Promise<void> {\n await this.runShow({ country });\n }\n\n async selectCurrency(currency: string): Promise<void> {\n // Preserve the resolved country. Sending `currency` alone makes the server\n // re-resolve the country to its default, silently switching it — the bug when\n // a country exposes more than one currency (e.g. CD: CDF/USD). `selectCountry`\n // deliberately omits currency so the server picks the new country's default.\n const country = this.state.catalogue?.country.code;\n await this.runShow(country ? { country, currency } : { currency });\n }\n\n /** Full selectable country catalogue for the picker (not part of the view). */\n async listCountries(): Promise<CountrySimplified[]> {\n try {\n const res = await this.transport.countries();\n return res.data;\n } catch (cause) {\n this.setError(cause);\n return [];\n }\n }\n\n async pay(input: PayInput): Promise<void> {\n await this.runMutation(() => this.transport.pay(this.withCatalogueDefaults(input)), false);\n }\n\n /**\n * Dismiss the current error banner (both `lastError` and a failed-attempt\n * `retryOf`). Themes call this when the customer selects a method again so a\n * stale error doesn't linger; the next server response clears the dismissal.\n */\n clearError(): void {\n if (this.state.error === null && this.state.dismissedError) return;\n this.setState({ error: null, dismissedError: true });\n }\n\n async authorize(input: AuthorizeInput): Promise<void> {\n await this.runMutation(() => this.transport.authorize(input), false);\n }\n\n async poll(): Promise<void> {\n await this.runMutation(() => this.transport.poll(), false);\n }\n\n /** Called when the customer returns from an external redirect. Just polls. */\n async resumeFromRedirect(): Promise<void> {\n await this.poll();\n }\n\n // --- polling control (host wires visibility/focus to these) ---\n\n startPolling(): void {\n if (this.destroyed || this.state.polling) return;\n this.setState({ polling: true });\n this.pollTick = 0;\n this.scheduleNextPoll();\n }\n\n stopPolling(): void {\n if (this.pollHandle !== null) {\n this.clearTimeoutImpl(this.pollHandle);\n this.pollHandle = null;\n }\n if (this.state.polling) this.setState({ polling: false });\n }\n\n destroy(): void {\n this.destroyed = true;\n this.stopPolling();\n this.listeners.clear();\n }\n\n // --- internals ---\n\n private async runShow(query: { country?: string; currency?: string } | undefined): Promise<void> {\n try {\n const res = await this.transport.show(query);\n this.applyResponse(res.data, res.message ?? '', true);\n } catch (cause) {\n this.setError(cause);\n }\n }\n\n private async runMutation(\n call: () => Promise<{ data: HostedCheckout; message?: string }>,\n isShow: boolean,\n ): Promise<void> {\n try {\n const res = await call();\n this.applyResponse(res.data, res.message ?? '', isShow);\n } catch (cause) {\n this.setError(cause);\n }\n }\n\n /**\n * Stamp the pay payload with the currently-resolved country/currency from the\n * cached catalogue. Themes call `selectCountry`/`selectCurrency` (which refetch\n * the catalogue) but never thread that selection back into `pay` — without this\n * the server falls back to its default country and rejects methods that aren't\n * available there. A value already on the input always wins; currency is only\n * stamped when DCC is in effect (the only time the server expects it).\n */\n private withCatalogueDefaults(input: PayInput): PayInput {\n const catalogue = this.state.catalogue;\n if (!catalogue) return input;\n\n const next: PayInput = { ...input };\n if (next.country === undefined) next.country = catalogue.country.code;\n if (next.currency === undefined && catalogue.amount.is_dcc) {\n const currency = catalogue.amount.final.currency;\n if (currency) next.currency = currency;\n }\n return next;\n }\n\n private applyResponse(checkout: HostedCheckout, message: string, isShow: boolean): void {\n const next: Partial<EngineState> = {\n checkout,\n message,\n phase: derivePhase(checkout),\n error: null,\n // A fresh response (incl. a new failed attempt) is shown, not suppressed.\n dismissedError: false,\n };\n if (isShow) {\n const catalogue = extractCatalogue(checkout);\n if (catalogue) next.catalogue = catalogue;\n }\n this.setState(next);\n this.reconcilePolling();\n }\n\n private setError(cause: unknown): void {\n const error = cause instanceof CheckoutError ? cause : new CheckoutError('unknown', toMessage(cause));\n\n // Terminal errors close the checkout; recoverable ones keep the phase so the\n // theme can show the message inline (e.g. 422 on pay stays in `collecting`).\n const isTerminalError = error.code === 'not_found' || error.code === 'not_open';\n const keepPhase = !isTerminalError && this.state.checkout;\n const phase: EngineState['phase'] = keepPhase ? this.state.phase : 'closed';\n\n this.setState({ error, phase, message: error.message, dismissedError: false });\n this.reconcilePolling();\n }\n\n private reconcilePolling(): void {\n if (!this.autoPoll || this.destroyed) return;\n if (isTerminalPhase(this.state.phase)) {\n this.stopPolling();\n return;\n }\n if (this.shouldPoll()) {\n this.startPolling();\n } else {\n this.stopPolling();\n }\n }\n\n /**\n * Poll while an attempt is `processing`, or while it is `action_required`\n * with a poll-completion action (approve_on_phone, scan_qr_code,\n * display_payment_instructions, embed_iframe). Do NOT poll while waiting on\n * the customer to submit (collect_otp), redirect, or run an SDK.\n */\n private shouldPoll(): boolean {\n if (this.state.phase === 'processing') return true;\n if (this.state.phase === 'action_required') {\n const action = this.state.checkout?.attempt?.next_action;\n return action != null && actionCompletion(action) === 'poll';\n }\n return false;\n }\n\n private scheduleNextPoll(): void {\n if (this.destroyed || !this.state.polling) return;\n\n const delay = this.intervals[this.pollTick] ?? this.steady;\n this.pollTick++;\n\n // Cap to session expiry: stop scheduling once we're past expires_at.\n const expiresAt = this.expiresAtMs();\n if (expiresAt !== null && this.now() >= expiresAt) {\n this.stopPolling();\n return;\n }\n\n this.pollHandle = this.setTimeoutImpl(() => {\n this.tickPoll().catch(() => undefined);\n }, delay);\n }\n\n private async tickPoll(): Promise<void> {\n if (this.destroyed || !this.state.polling || this.pollInFlight) return;\n this.pollInFlight = true;\n try {\n await this.poll();\n } finally {\n this.pollInFlight = false;\n }\n // poll() -> applyResponse -> reconcilePolling may have stopped us.\n if (this.state.polling && !isTerminalPhase(this.state.phase)) {\n this.scheduleNextPoll();\n }\n }\n\n private expiresAtMs(): number | null {\n const raw = this.state.checkout?.session.expires_at;\n if (!raw) return null;\n const ms = Date.parse(raw);\n return Number.isNaN(ms) ? null : ms;\n }\n\n private setState(partial: Partial<EngineState>): void {\n this.state = { ...this.state, ...partial };\n this.emit();\n }\n\n private emit(): void {\n const view = this.getView();\n for (const listener of this.listeners) listener(view);\n }\n}\n\nfunction toMessage(cause: unknown): string {\n if (cause instanceof Error) return cause.message;\n return 'Unexpected error.';\n}\n","import type { RedirectToUrlAction } from '@orqex/checkout-engine';\n\ninterface RedirectEffectDeps {\n /** Top-level navigation for GET redirects. Default window.location.assign. */\n navigate?: (url: string) => void;\n /** Injectable document for tests. Default global document. */\n doc?: Document;\n}\n\n/**\n * Execute a redirect next-action in a headless page. GET navigates the\n * top-level document; POST auto-submits a hidden form (some 3-D Secure ACS\n * endpoints). Refuses any non-https URL as defense-in-depth — the primary trust\n * boundary is the server, but we never navigate to javascript:/data: schemes.\n */\nexport function performActionRedirect(action: RedirectToUrlAction, deps: RedirectEffectDeps = {}): void {\n const doc = deps.doc ?? document;\n const navigate = deps.navigate ?? ((url: string) => window.location.assign(url));\n\n if (!isHttps(action.url)) {\n // eslint-disable-next-line no-console\n console.error(`Orqex: refused redirect to non-https URL \"${action.url}\".`);\n return;\n }\n\n if (action.method === 'POST') {\n const form = doc.createElement('form');\n form.method = 'POST';\n form.action = action.url;\n form.style.display = 'none';\n for (const [name, value] of Object.entries(action.post_data ?? {})) {\n const input = doc.createElement('input');\n input.type = 'hidden';\n input.name = name;\n input.value = typeof value === 'string' ? value : JSON.stringify(value);\n form.appendChild(input);\n }\n doc.body.appendChild(form);\n form.submit();\n return;\n }\n\n navigate(action.url);\n}\n\nfunction isHttps(url: string): boolean {\n try {\n return new URL(url).protocol === 'https:';\n } catch {\n return false;\n }\n}\n","import {\n CheckoutEngine,\n HttpTransport,\n type AuthorizeInput,\n type CheckoutView,\n type CountrySimplified,\n type PayInput,\n type RedirectToUrlAction,\n} from '@orqex/checkout-engine';\n\nimport type { ResolvedConfig } from './config';\nimport { performActionRedirect } from './redirect-effect';\n\nexport interface CreateEngineOptions {\n /** cs_… checkout handle minted server-side by the merchant. */\n publicId: string;\n /** BCP-47 locale for Accept-Language. Default navigator.language. */\n locale?: string;\n /**\n * When true, the SDK persists publicId across a redirect and auto-resumes on\n * return, and auto-performs redirect actions. Default false (fully manual).\n */\n autoResume?: boolean;\n}\n\n/** Narrowed, browser-facing surface over CheckoutEngine. Cross-SDK contract. */\nexport interface OrqexCheckout {\n subscribe(fn: (view: CheckoutView) => void): () => void;\n getView(): CheckoutView;\n pay(input: PayInput): Promise<void>;\n authorize(input: AuthorizeInput): Promise<void>;\n poll(): Promise<void>;\n selectCountry(country: string): Promise<void>;\n selectCurrency(currency: string): Promise<void>;\n listCountries(): Promise<CountrySimplified[]>;\n /** Poll the current server state (call on return from an external redirect). */\n resumeFromRedirect(): Promise<void>;\n startPolling(): void;\n stopPolling(): void;\n /** Perform the pending redirect action; no-op if the current view is not one. */\n performRedirect(): void;\n destroy(): void;\n}\n\nexport interface HeadlessDeps {\n /** Injected engine for tests; when omitted a real one is built. */\n engine?: CheckoutEngine;\n /** Injectable window for tests. Default global window. */\n win?: Window;\n /** Injectable storage for autoResume tests. Default window.sessionStorage. */\n storage?: Storage;\n /** Injectable fetch passed to HttpTransport. Default global fetch. */\n fetchImpl?: (input: string, init?: RequestInit) => Promise<Response>;\n}\n\n/** Extract the current redirect action from a view, or null. */\nfunction redirectActionOf(view: CheckoutView): RedirectToUrlAction | null {\n if (view.kind === 'action' && view.ctx.completion === 'redirect' && view.ctx.action.type === 'redirect_to_url') {\n return view.ctx.action;\n }\n return null;\n}\n\nconst markerKey = (publicId: string): string => `orqex:redirect:${publicId}`;\n\nfunction wireAutoResume(engine: CheckoutEngine, publicId: string, ctx: { storage: Storage; win: Window }): () => void {\n const key = markerKey(publicId);\n\n // Returning from a redirect: a pending marker means we just came back.\n if (ctx.storage.getItem(key) !== null) {\n ctx.storage.removeItem(key);\n engine.resumeFromRedirect();\n }\n\n // Auto-perform the redirect once per (attempt, action).\n let handled: string | null = null;\n const unsubscribe = engine.subscribe((view) => {\n const action = redirectActionOf(view);\n if (!action || !action.can_auto_redirect || view.kind !== 'action') return;\n const dedupe = `${view.ctx.attempt.id}:${action.type}`;\n if (handled === dedupe) return;\n handled = dedupe;\n ctx.storage.setItem(key, view.ctx.attempt.id);\n performActionRedirect(action, { navigate: (url) => ctx.win.location.assign(url), doc: ctx.win.document });\n });\n\n const onPageShow = (): void => {\n const kind = engine.getView().kind;\n if (kind === 'action' || kind === 'processing') engine.resumeFromRedirect();\n };\n ctx.win.addEventListener('pageshow', onPageShow);\n\n return () => {\n unsubscribe();\n ctx.win.removeEventListener('pageshow', onPageShow);\n };\n}\n\n/**\n * Build the headless checkout: a real CheckoutEngine over HttpTransport (pk_),\n * wrapped in the narrowed OrqexCheckout facade. Manual mode; autoResume wiring\n * is conditionally applied when `options.autoResume` is true.\n */\nexport function createHeadlessCheckout(\n config: ResolvedConfig,\n options: CreateEngineOptions,\n deps: HeadlessDeps = {},\n): OrqexCheckout {\n const win = deps.win ?? window;\n const engine =\n deps.engine ??\n new CheckoutEngine(\n new HttpTransport({\n baseUrl: config.apiBaseUrl,\n auth: { publishableKey: config.publishableKey, publicId: options.publicId },\n locale: options.locale ?? (typeof navigator === 'undefined' ? undefined : navigator.language),\n fetchImpl: deps.fetchImpl,\n }),\n );\n\n let autoResumeTeardown: () => void = () => {};\n\n const facade: OrqexCheckout = {\n subscribe: (fn) => engine.subscribe(fn),\n getView: () => engine.getView(),\n pay: (input) => engine.pay(input),\n authorize: (input) => engine.authorize(input),\n poll: () => engine.poll(),\n selectCountry: (country) => engine.selectCountry(country),\n selectCurrency: (currency) => engine.selectCurrency(currency),\n listCountries: () => engine.listCountries(),\n resumeFromRedirect: () => engine.resumeFromRedirect(),\n startPolling: () => engine.startPolling(),\n stopPolling: () => engine.stopPolling(),\n performRedirect: () => {\n const action = redirectActionOf(engine.getView());\n if (action) performActionRedirect(action, { navigate: (url) => win.location.assign(url), doc: win.document });\n },\n destroy: () => {\n autoResumeTeardown();\n engine.destroy();\n },\n };\n\n if (options.autoResume) {\n autoResumeTeardown = wireAutoResume(engine, options.publicId, { storage: deps.storage ?? win.sessionStorage, win });\n }\n\n engine.load();\n return facade;\n}\n","import { buildRedirectUrl, type ResolvedConfig } from './config';\n\nexport interface RedirectOptions {\n /** cs_… checkout handle minted server-side by the merchant. */\n publicId: string;\n}\n\ntype Navigate = (url: string) => void;\n\nconst defaultNavigate: Navigate = (url) => {\n window.location.assign(url);\n};\n\n/** Full-page navigation to the hosted checkout. */\nexport function redirectToCheckout(\n config: ResolvedConfig,\n options: RedirectOptions,\n navigate: Navigate = defaultNavigate,\n): void {\n if (!options.publicId) {\n throw new Error('Orqex: redirectToCheckout requires a publicId.');\n }\n navigate(buildRedirectUrl(config, options.publicId));\n}\n","import { resolveConfig, type OrqexOptions } from './config';\nimport { EmbeddedController, type MountOptions } from './embedded';\nimport { EventBus, type EventPayloads, type MerchantEvent } from './event-bus';\nimport { createHeadlessCheckout, type CreateEngineOptions, type OrqexCheckout } from './headless';\nimport { redirectToCheckout, type RedirectOptions } from './redirect';\n\nexport interface OrqexInstance {\n /** Embedded mode: hosted checkout in a sandboxed iframe. */\n mount(target: string | HTMLElement, options: MountOptions): void;\n /** Redirect mode: full-page navigation to the hosted checkout. */\n redirectToCheckout(options: RedirectOptions): void;\n /** Subscribe to a lifecycle event; returns a disposer. */\n on<TEvent extends MerchantEvent>(event: TEvent, handler: (payload: EventPayloads[TEvent]) => void): () => void;\n /** Tear down the embedded iframe and its listener (no-op in redirect mode). */\n unmount(): void;\n /** Headless mode: run the engine in this page and render your own UI. */\n createEngine(options: CreateEngineOptions): OrqexCheckout;\n}\n\n/**\n * SDK entry point. `Orqex('pk_…')` validates the key, then exposes embedded,\n * redirect, and headless (`createEngine`) modes over one event bus.\n */\nexport function Orqex(publishableKey: string, options?: OrqexOptions): OrqexInstance {\n const config = resolveConfig(publishableKey, options);\n const bus = new EventBus();\n const embedded = new EmbeddedController({ config, bus });\n\n return {\n mount(target, mountOptions) {\n embedded.mount(target, mountOptions);\n },\n redirectToCheckout(redirectOptions) {\n redirectToCheckout(config, redirectOptions);\n },\n on(event, handler) {\n return bus.on(event, handler);\n },\n unmount() {\n embedded.unmount();\n },\n createEngine(engineOptions) {\n return createHeadlessCheckout(config, engineOptions);\n },\n };\n}\n","import type { CheckoutView } from '@orqex/checkout-engine';\n\nimport { closeMessage, errorMessage, successMessage, type EmbedMessage } from './protocol';\n\nexport interface EmbedProjection {\n message: EmbedMessage;\n /** Dedup key so the host posts each terminal state at most once. */\n key: string;\n}\n\n/**\n * Pure mapping from the engine's projected view to an embed lifecycle message.\n * Terminal views only; `redirect` is handled by the host's redirect override\n * (a redirect action is not a terminal view). Returns null when there is\n * nothing new to post or `key` equals `lastKey`.\n */\nexport function projectEmbedMessage(view: CheckoutView, lastKey: string | null): EmbedProjection | null {\n let projection: EmbedProjection | null = null;\n\n if (view.kind === 'succeeded') {\n const status = String(view.ctx.status);\n projection = { message: successMessage(status), key: `succeeded:${status}` };\n } else if (view.kind === 'failed') {\n const status = String(view.ctx.status);\n projection = { message: errorMessage(status, view.ctx.message), key: `failed:${status}` };\n } else if (view.kind === 'closed') {\n const status = String(view.ctx.status);\n projection = { message: closeMessage(status), key: `closed:${status}` };\n }\n\n if (!projection || projection.key === lastKey) return null;\n return projection;\n}\n","/**\n * @orqex/checkout-js — client-side SDK for Orqex payments.\n *\n * Browser-host glue over the existing engine + hosted checkout. Never accepts a\n * secret key; the publishable key (pk_) is public by design.\n */\n\nexport const SDK_VERSION = '0.0.1';\n\nexport { Orqex } from './orqex';\nexport type { OrqexInstance } from './orqex';\nexport type { OrqexOptions } from './config';\nexport type { MountOptions } from './embedded';\nexport type { RedirectOptions } from './redirect';\nexport type { MerchantEvent, EventPayloads } from './event-bus';\nexport type { OrqexCheckout, CreateEngineOptions } from './headless';\n// Engine contract re-exported so headless merchants render against the typed view.\nexport type { CheckoutView, PayInput, AuthorizeInput, CountrySimplified } from '@orqex/checkout-engine';\n\n// Embed protocol + view→message projection: re-exported so the hosted app\n// (checkout-next) imports the single source of truth for the wire contract.\nexport * from './protocol';\nexport { projectEmbedMessage } from './embed-projection';\nexport type { EmbedProjection } from './embed-projection';\n"]}
1
+ {"version":3,"sources":["../src/key.ts","../src/config.ts","../src/protocol.ts","../src/embedded.ts","../src/event-bus.ts","../../engine/src/types/errors.ts","../../engine/src/transport/http-transport.ts","../../engine/src/engine/phase.ts","../../engine/src/engine/project.ts","../../engine/src/engine/state.ts","../../engine/src/engine/engine.ts","../src/redirect-effect.ts","../src/headless.ts","../src/redirect.ts","../src/orqex.ts","../src/embed-projection.ts","../src/index.ts"],"names":["PK_PATTERN","parsePublishableKey","key","DEFAULT_CHECKOUT_BASE_URL","DEFAULT_API_BASE_URL","resolveConfig","publishableKey","options","livemode","raw","checkoutBaseUrl","checkoutOrigin","apiBaseUrl","buildEmbedUrl","config","publicId","parentOrigin","id","buildRedirectUrl","ORQEX_PROTOCOL_VERSION","KNOWN_TYPES","isEmbedMessage","data","record","base","type","readyMessage","resizeMessage","height","successMessage","status","errorMessage","code","message","redirectMessage","url","closeMessage","SANDBOX","EmbeddedController","deps","__publicField","target","host","iframe","listener","event","EventBus","handler","payload","cause","CheckoutError","httpStatus","errorCodeFromStatus","HttpTransport","fetchImpl","query","body","suffix","method","path","opts","headers","controller","timer","response","describeNetworkError","text","json","extractMessage","params","value","qs","derivePhase","checkout","session","intent","attempt","isTerminalPhase","phase","actionCompletion","action","isActionable","projectView","state","catalogue","kind","result","appearance","ctx","isFailedAttempt","waiting","failureMessage","initialState","extractCatalogue","country","currency_options","amount","methods","CheckoutEngine","transport","cb","ms","handle","fn","input","next","currency","res","call","isShow","error","toMessage","delay","expiresAt","partial","view","performActionRedirect","doc","navigate","isHttps","form","name","redirectActionOf","markerKey","wireAutoResume","engine","handled","unsubscribe","dedupe","onPageShow","createHeadlessCheckout","win","autoResumeTeardown","facade","defaultNavigate","redirectToCheckout","Orqex","bus","embedded","mountOptions","redirectOptions","engineOptions","projectEmbedMessage","lastKey","projection","SDK_VERSION"],"mappings":"uNAMA,IAAMA,CAAAA,CAAa,gCAOZ,SAASC,CAAAA,CAAoBC,EAAwB,CAC1D,GAAI,OAAOA,CAAAA,EAAQ,QAAA,EAAY,CAACF,CAAAA,CAAW,IAAA,CAAKE,CAAG,CAAA,CACjD,MAAM,IAAI,KAAA,CACR,sHACF,CAAA,CAEF,OAAO,CAAE,GAAA,CAAAA,EAAK,QAAA,CAAUA,CAAAA,CAAI,WAAW,UAAU,CAAE,CACrD,CCbO,IAAMC,EAA4B,4BAAA,CAO5BC,CAAAA,CAAuB,wBAoB7B,SAASC,CAAAA,CAAcC,EAAwBC,CAAAA,CAAwB,GAAoB,CAChG,GAAM,CAAE,GAAA,CAAAL,CAAAA,CAAK,QAAA,CAAAM,CAAS,CAAA,CAAIP,CAAAA,CAAoBK,CAAc,CAAA,CACtDG,CAAAA,CAAMF,EAAQ,eAAA,EAAmBJ,CAAAA,CACjCO,EAAkBD,CAAAA,CAAI,OAAA,CAAQ,OAAQ,EAAE,CAAA,CAC1CE,EACJ,GAAI,CACFA,EAAiB,IAAI,GAAA,CAAID,CAAe,CAAA,CAAE,OAC5C,CAAA,KAAQ,CACN,MAAM,IAAI,MAAM,CAAA,gCAAA,EAAmCD,CAAG,IAAI,CAC5D,CACA,IAAMG,CAAAA,CAAAA,CAA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EAAa,CAAE,OAAA,CAASnH,EAAeC,CAAM,CAAA,CAAG,IAAK,CAAA,UAAA,EAAaA,CAAM,EAAG,EAC7E,CAAA,KAAA,GAAWqF,EAAK,IAAA,GAAS,QAAA,CAAU,CACjC,IAAMrF,CAAAA,CAAS,MAAA,CAAOqF,CAAAA,CAAK,GAAA,CAAI,MAAM,EACrC6B,CAAAA,CAAa,CAAE,QAASjH,CAAAA,CAAaD,CAAAA,CAAQqF,EAAK,GAAA,CAAI,OAAO,EAAG,GAAA,CAAK,CAAA,OAAA,EAAUrF,CAAM,CAAA,CAAG,EAC1F,SAAWqF,CAAAA,CAAK,IAAA,GAAS,SAAU,CACjC,IAAMrF,CAAAA,CAAS,MAAA,CAAOqF,CAAAA,CAAK,GAAA,CAAI,MAAM,CAAA,CACrC6B,CAAAA,CAAa,CAAE,OAAA,CAAS5G,CAAAA,CAAaN,CAAM,CAAA,CAAG,GAAA,CAAK,CAAA,OAAA,EAAUA,CAAM,CAAA,CAAG,EACxE,CAEA,OAAI,CAACkH,GAAcA,CAAAA,CAAW,GAAA,GAAQD,EAAgB,IAAA,CAC/CC,CACT,CCzBO,IAAMC,EAAAA,CAAc","file":"orqex.global.js","sourcesContent":["/** Parsed publishable key: the raw string plus the environment it targets. */\nexport interface ParsedKey {\n key: string;\n livemode: boolean;\n}\n\nconst PK_PATTERN = /^pk_(live|test)_[A-Za-z0-9]+$/;\n\n/**\n * Validate the client key shape. Only `pk_live_…` / `pk_test_…` are accepted;\n * anything else (empty, `sk_…`, M2M secret, malformed) throws. The publishable\n * key is public by design, so no value here is treated as sensitive.\n */\nexport function parsePublishableKey(key: string): ParsedKey {\n if (typeof key !== 'string' || !PK_PATTERN.test(key)) {\n throw new Error(\n 'Orqex: a publishable key (\"pk_live_…\" or \"pk_test_…\") is required. Never pass a secret key to the browser.',\n );\n }\n return { key, livemode: key.startsWith('pk_live_') };\n}\n","import { parsePublishableKey } from './key';\n\n/**\n * Default hosted-checkout origin. PLACEHOLDER — confirm the real production\n * origin before release; merchants can always override via\n * `Orqex(pk, { checkoutBaseUrl })`.\n */\nexport const DEFAULT_CHECKOUT_BASE_URL = 'https://checkout.orqex.com';\n\n/**\n * Default API origin the headless engine calls with pk_. PLACEHOLDER — confirm\n * the real production API origin before release; override via\n * `Orqex(pk, { apiBaseUrl })`.\n */\nexport const DEFAULT_API_BASE_URL = 'https://api.orqex.com';\n\nexport interface OrqexOptions {\n /** Override the hosted-checkout origin (e.g. a staging or self-hosted deploy). */\n checkoutBaseUrl?: string;\n /** Override the API origin the headless engine calls (e.g. staging). */\n apiBaseUrl?: string;\n}\n\nexport interface ResolvedConfig {\n publishableKey: string;\n livemode: boolean;\n /** Hosted-checkout base, no trailing slash. */\n checkoutBaseUrl: string;\n /** Origin of `checkoutBaseUrl`; the only origin we accept inbound messages from. */\n checkoutOrigin: string;\n /** API origin for headless engine requests, no trailing slash. */\n apiBaseUrl: string;\n}\n\nexport function resolveConfig(publishableKey: string, options: OrqexOptions = {}): ResolvedConfig {\n const { key, livemode } = parsePublishableKey(publishableKey);\n const raw = options.checkoutBaseUrl ?? DEFAULT_CHECKOUT_BASE_URL;\n const checkoutBaseUrl = raw.replace(/\\/+$/, '');\n let checkoutOrigin: string;\n try {\n checkoutOrigin = new URL(checkoutBaseUrl).origin;\n } catch {\n throw new Error(`Orqex: invalid checkoutBaseUrl \"${raw}\".`);\n }\n const apiBaseUrl = (options.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\\/+$/, '');\n return { publishableKey: key, livemode, checkoutBaseUrl, checkoutOrigin, apiBaseUrl };\n}\n\nexport function buildEmbedUrl(config: ResolvedConfig, publicId: string, parentOrigin: string): string {\n const id = encodeURIComponent(publicId);\n return `${config.checkoutBaseUrl}/${id}?embed=1&origin=${encodeURIComponent(parentOrigin)}`;\n}\n\nexport function buildRedirectUrl(config: ResolvedConfig, publicId: string): string {\n return `${config.checkoutBaseUrl}/${encodeURIComponent(publicId)}`;\n}\n","/**\n * The embed postMessage protocol: the wire contract between the hosted checkout\n * (inside a sandboxed iframe) and the SDK running in the merchant's top window.\n *\n * Every message carries `__orqex: true` and `v` (version) so each side can\n * reject foreign or mis-versioned traffic. This module is the single source of\n * truth: `checkout-next` imports it to emit, `checkout-js` imports it to receive.\n */\n\nexport const ORQEX_PROTOCOL_VERSION = 1;\n\nexport type EmbedMessageType = 'ready' | 'resize' | 'success' | 'error' | 'redirect' | 'close';\n\ninterface Base<T extends EmbedMessageType> {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __orqex: true;\n v: number;\n type: T;\n}\n\nexport type ReadyMessage = Base<'ready'>;\nexport interface ResizeMessage extends Base<'resize'> {\n height: number;\n}\nexport interface SuccessMessage extends Base<'success'> {\n status: string;\n}\nexport interface ErrorMessage extends Base<'error'> {\n code: string;\n message: string;\n}\nexport interface RedirectMessage extends Base<'redirect'> {\n url: string;\n}\nexport interface CloseMessage extends Base<'close'> {\n status: string;\n}\n\nexport type EmbedMessage =\n | ReadyMessage\n | ResizeMessage\n | SuccessMessage\n | ErrorMessage\n | RedirectMessage\n | CloseMessage;\n\nconst KNOWN_TYPES: ReadonlyArray<EmbedMessageType> = ['ready', 'resize', 'success', 'error', 'redirect', 'close'];\n\n/** Structural + version guard for messages arriving over postMessage. */\nexport function isEmbedMessage(data: unknown): data is EmbedMessage {\n if (data === null || typeof data !== 'object') return false;\n const record = data as Record<string, unknown>;\n return (\n record.__orqex === true &&\n record.v === ORQEX_PROTOCOL_VERSION &&\n typeof record.type === 'string' &&\n KNOWN_TYPES.includes(record.type as EmbedMessageType)\n );\n}\n\nfunction base<T extends EmbedMessageType>(type: T): Base<T> {\n // eslint-disable-next-line @typescript-eslint/naming-convention, id-length\n return { __orqex: true, v: ORQEX_PROTOCOL_VERSION, type };\n}\n\nexport function readyMessage(): ReadyMessage {\n return base('ready');\n}\nexport function resizeMessage(height: number): ResizeMessage {\n return { ...base('resize'), height };\n}\nexport function successMessage(status: string): SuccessMessage {\n return { ...base('success'), status };\n}\nexport function errorMessage(code: string, message: string): ErrorMessage {\n return { ...base('error'), code, message };\n}\nexport function redirectMessage(url: string): RedirectMessage {\n return { ...base('redirect'), url };\n}\nexport function closeMessage(status: string): CloseMessage {\n return { ...base('close'), status };\n}\n","import { buildEmbedUrl, type ResolvedConfig } from './config';\nimport type { EventBus } from './event-bus';\nimport { isEmbedMessage, type EmbedMessage } from './protocol';\n\nexport interface MountOptions {\n publicId: string;\n}\n\nexport interface EmbeddedControllerDeps {\n config: ResolvedConfig;\n bus: EventBus;\n /** Injectable for tests; defaults to the global window. */\n win?: Window;\n /** Top-level navigation for redirect messages; injectable for tests. */\n navigate?: (url: string) => void;\n}\n\nconst SANDBOX = 'allow-scripts allow-same-origin allow-forms allow-popups';\n\n/**\n * Owns the sandboxed hosted-checkout iframe: creation, the origin-guarded\n * message listener, auto-resize, redirect bubbling, and teardown.\n */\nexport class EmbeddedController {\n private readonly config: ResolvedConfig;\n private readonly bus: EventBus;\n private readonly win: Window;\n private readonly navigate: (url: string) => void;\n\n private iframe: HTMLIFrameElement | null = null;\n private listener: ((event: MessageEvent) => void) | null = null;\n\n constructor(deps: EmbeddedControllerDeps) {\n this.config = deps.config;\n this.bus = deps.bus;\n this.win = deps.win ?? window;\n this.navigate = deps.navigate ?? ((url) => this.win.location.assign(url));\n }\n\n mount(target: string | HTMLElement, options: MountOptions): void {\n if (!options.publicId) throw new Error('Orqex: mount requires a publicId.');\n const host = this.resolveHost(target);\n this.unmount();\n\n const iframe = this.win.document.createElement('iframe');\n iframe.src = buildEmbedUrl(this.config, options.publicId, this.win.location.origin);\n iframe.setAttribute('sandbox', SANDBOX);\n iframe.setAttribute('allow', 'payment');\n iframe.setAttribute('title', 'Orqex Checkout');\n iframe.style.width = '100%';\n iframe.style.border = 'none';\n iframe.style.height = '150px';\n host.appendChild(iframe);\n this.iframe = iframe;\n\n const listener = (event: MessageEvent): void => {\n if (event.origin !== this.config.checkoutOrigin) return;\n if (event.source !== iframe.contentWindow) return;\n if (!isEmbedMessage(event.data)) return;\n this.handle(event.data);\n };\n this.win.addEventListener('message', listener);\n this.listener = listener;\n }\n\n unmount(): void {\n if (this.listener) {\n this.win.removeEventListener('message', this.listener);\n this.listener = null;\n }\n if (this.iframe) {\n this.iframe.remove();\n this.iframe = null;\n }\n }\n\n private handle(message: EmbedMessage): void {\n switch (message.type) {\n case 'resize':\n if (this.iframe) this.iframe.style.height = `${message.height}px`;\n break;\n case 'success':\n this.bus.emit('success', { status: message.status });\n break;\n case 'error':\n this.bus.emit('error', { code: message.code, message: message.message });\n break;\n case 'close':\n this.bus.emit('close', { status: message.status });\n break;\n case 'redirect':\n // The iframe cannot navigate the top window; the SDK does it here.\n this.bus.emit('redirect', { url: message.url });\n this.navigate(message.url);\n break;\n case 'ready':\n break;\n }\n }\n\n private resolveHost(target: string | HTMLElement): HTMLElement {\n const host = typeof target === 'string' ? this.win.document.querySelector<HTMLElement>(target) : target;\n if (!host) throw new Error(`Orqex: mount target \"${String(target)}\" not found.`);\n return host;\n }\n}\n","/** Merchant-facing lifecycle events for embedded/redirect modes. */\nexport type MerchantEvent = 'success' | 'error' | 'redirect' | 'close';\n\nexport interface EventPayloads {\n success: { status: string };\n error: { code: string; message: string };\n redirect: { url: string };\n close: { status: string };\n}\n\ntype Handler<TEvent extends MerchantEvent> = (payload: EventPayloads[TEvent]) => void;\n\n/**\n * Minimal typed pub/sub. A handler that throws is caught and logged so a single\n * bad merchant callback cannot break delivery to the others.\n */\nexport class EventBus {\n private readonly handlers: { [TEvent in MerchantEvent]: Set<Handler<TEvent>> } = {\n success: new Set(),\n error: new Set(),\n redirect: new Set(),\n close: new Set(),\n };\n\n on<TEvent extends MerchantEvent>(event: TEvent, handler: Handler<TEvent>): () => void {\n this.handlers[event].add(handler);\n return () => this.off(event, handler);\n }\n\n off<TEvent extends MerchantEvent>(event: TEvent, handler: Handler<TEvent>): void {\n this.handlers[event].delete(handler);\n }\n\n emit<TEvent extends MerchantEvent>(event: TEvent, payload: EventPayloads[TEvent]): void {\n for (const handler of this.handlers[event]) {\n try {\n handler(payload);\n } catch (cause) {\n // eslint-disable-next-line no-console\n console.error(`Orqex: \"${event}\" event handler threw`, cause);\n }\n }\n }\n}\n","/**\n * Typed error model. The envelope `message` from the server is customer-safe\n * and is carried through verbatim.\n */\n\nexport const CHECKOUT_ERROR_CODE = [\n // 404: token unknown or expired\n 'not_found',\n // 400: session not open\n 'not_open',\n // 422: validation / intent final / restriction\n 'unprocessable',\n // 429: throttle:60,1\n 'rate_limited',\n // transport failure / no response\n 'network',\n 'unknown',\n] as const;\nexport type CheckoutErrorCode = (typeof CHECKOUT_ERROR_CODE)[number];\n\nexport class CheckoutError extends Error {\n readonly code: CheckoutErrorCode;\n readonly httpStatus?: number;\n\n constructor(code: CheckoutErrorCode, message: string, httpStatus?: number) {\n super(message);\n this.name = 'CheckoutError';\n this.code = code;\n this.httpStatus = httpStatus;\n }\n}\n\nexport function errorCodeFromStatus(status: number): CheckoutErrorCode {\n switch (status) {\n case 400:\n return 'not_open';\n case 404:\n return 'not_found';\n case 422:\n return 'unprocessable';\n case 429:\n return 'rate_limited';\n default:\n return status >= 500 ? 'network' : 'unknown';\n }\n}\n\n/** Terminal errors close the checkout; others are recoverable in-place. */\nexport function isTerminalError(code: CheckoutErrorCode): boolean {\n return code === 'not_found' || code === 'not_open';\n}\n","import type {\n AuthorizeInput,\n CountriesResponse,\n Envelope,\n HostedCheckout,\n PayInput,\n ShowQuery,\n} from '../types/contract';\nimport { CheckoutError, errorCodeFromStatus } from '../types/errors';\n\nimport type { Transport } from './transport';\n\ntype FetchLike = (input: string, init?: RequestInit) => Promise<Response>;\n\n/**\n * Publishable-key auth (Stripe-aligned, backend PR #105 onward).\n *\n * `publishableKey` is the project `pk_...`, obtained server-side via the M2M\n * `/checkout/bootstrap` call and handed to the client. It is sent as\n * `Authorization: Bearer pk_...` on every checkout request. `publicId` is the\n * `cs_...` CheckoutSession pointer, addressed as `/checkout/{publicId}`.\n *\n * `pk_` is publishable: client exposure is expected. No secret ever reaches the\n * browser, so nothing here needs to be hidden from the instance.\n */\nexport interface PublishableKeyAuth {\n /** pk_... project publishable key. */\n publishableKey: string;\n /** cs_... CheckoutSession public id. */\n publicId: string;\n}\n\nexport interface HttpTransportOptions {\n /** API base, e.g. \"https://api.orqex.com\". No trailing slash required. */\n baseUrl: string;\n /** Publishable-key auth (pk_ + public_id). */\n auth: PublishableKeyAuth;\n /** BCP-47 language for Accept-Language (e.g. from appearance.lang). */\n locale?: string;\n /** Injectable fetch (defaults to global). Keeps the engine env-agnostic. */\n fetchImpl?: FetchLike;\n /** Per-request timeout in ms. Default 20000. */\n timeoutMs?: number;\n}\n\n/**\n * Real transport against the hosted-checkout endpoints.\n *\n * Auth is `Bearer pk_` against `/checkout/{publicId}`. Errors map to\n * CheckoutError; the server's `message` is preserved for customer display.\n */\nexport class HttpTransport implements Transport {\n private readonly baseUrl: string;\n private readonly auth: PublishableKeyAuth;\n private readonly locale?: string;\n private readonly fetchImpl: FetchLike;\n private readonly timeoutMs: number;\n\n constructor(options: HttpTransportOptions) {\n // Bind to globalThis: a bare `globalThis.fetch` reference loses its `this`\n // and browsers reject the detached call (\"Illegal invocation\").\n const fetchImpl =\n options.fetchImpl ??\n (typeof globalThis.fetch === 'function' ? (globalThis.fetch.bind(globalThis) as FetchLike) : undefined);\n if (!fetchImpl) {\n throw new CheckoutError('unknown', 'No fetch implementation available; pass options.fetchImpl.');\n }\n if (!options.auth?.publishableKey || !options.auth?.publicId) {\n throw new CheckoutError('unknown', 'HttpTransport requires `auth` with publishableKey and publicId.');\n }\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '');\n this.auth = options.auth;\n this.locale = options.locale;\n this.fetchImpl = fetchImpl;\n this.timeoutMs = options.timeoutMs ?? 20_000;\n }\n\n show(query?: ShowQuery): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('GET', this.path(''), {\n query: { country: query?.country, currency: query?.currency },\n });\n }\n\n countries(): Promise<CountriesResponse> {\n return this.request<CountriesResponse>('GET', this.path('/countries'));\n }\n\n pay(body: PayInput): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('POST', this.path('/pay'), { body });\n }\n\n authorize(body: AuthorizeInput): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('POST', this.path('/authorize'), { body });\n }\n\n poll(): Promise<Envelope<HostedCheckout>> {\n return this.request<Envelope<HostedCheckout>>('GET', this.path('/poll'));\n }\n\n /**\n * Build the resource path: `/checkout/{publicId}{suffix}`.\n *\n * One surface shared by the hosted page and the SDK (backend PR #105):\n * `GET ''` (show), `POST /pay`, `POST /authorize`, `GET /poll`,\n * `GET /countries`. Scoped to the pk_'s project — a public_id from another\n * project returns 404 (the engine maps that to a terminal not_found).\n */\n private path(suffix: string): string {\n return `/checkout/${encodeURIComponent(this.auth.publicId)}${suffix}`;\n }\n\n private async request<T>(\n method: string,\n path: string,\n opts?: { query?: Record<string, string | undefined>; body?: unknown },\n ): Promise<T> {\n const url = this.baseUrl + path + this.queryString(opts?.query);\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const headers: Record<string, string> = { Accept: 'application/json' };\n if (this.locale) headers['Accept-Language'] = this.locale;\n headers.Authorization = `Bearer ${this.auth.publishableKey}`;\n if (opts?.body !== undefined) headers['Content-Type'] = 'application/json';\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method,\n headers,\n body: opts?.body === undefined ? undefined : JSON.stringify(opts.body),\n signal: controller.signal,\n });\n } catch (cause) {\n throw new CheckoutError('network', describeNetworkError(cause));\n } finally {\n clearTimeout(timer);\n }\n\n return this.parse<T>(response);\n }\n\n private async parse<T>(response: Response): Promise<T> {\n const text = await response.text().catch(() => '');\n let json: unknown;\n if (text) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n\n if (!response.ok) {\n const message = extractMessage(json) ?? `Request failed with status ${response.status}`;\n throw new CheckoutError(errorCodeFromStatus(response.status), message, response.status);\n }\n\n if (json === undefined) {\n throw new CheckoutError('unknown', 'Empty or non-JSON response body.', response.status);\n }\n return json as T;\n }\n\n private queryString(query?: Record<string, string | undefined>): string {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== '') params.set(key, value);\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n }\n}\n\nfunction extractMessage(json: unknown): string | undefined {\n if (json && typeof json === 'object' && 'message' in json) {\n const message = (json as { message: unknown }).message;\n if (typeof message === 'string') return message;\n }\n return undefined;\n}\n\nfunction describeNetworkError(cause: unknown): string {\n if (cause instanceof Error && cause.name === 'AbortError') return 'Request timed out.';\n if (cause instanceof Error) return cause.message;\n return 'Network request failed.';\n}\n","import type { HostedCheckout } from '../types/contract';\n\nimport type { CheckoutPhase } from './state';\n\n/**\n * Project server state into a phase. The SERVER owns the state machine; this is\n * a pure read-only projection. Order matters — first match wins.\n *\n * intent completed -> succeeded\n * intent failed/expired -> failed\n * session not open (not completed) -> closed\n * attempt action_required -> action_required\n * attempt processing -> processing\n * else (open, no/failed attempt) -> collecting (retry)\n */\nexport function derivePhase(checkout: HostedCheckout | null): CheckoutPhase {\n if (!checkout) return 'loading';\n\n const session = checkout.session.status;\n const intent = checkout.payment?.status;\n const attempt = checkout.attempt?.status;\n\n if (intent === 'completed') return 'succeeded';\n if (intent === 'failed' || intent === 'expired') return 'failed';\n\n if (session !== 'open') {\n return session === 'completed' ? 'succeeded' : 'closed';\n }\n\n // Session is open from here.\n if (attempt === 'action_required') return 'action_required';\n if (attempt === 'processing') return 'processing';\n\n // No attempt yet, or the last attempt failed/cancelled while the session is\n // still open: the customer can retry.\n return 'collecting';\n}\n\n/** Phases at which polling makes sense. */\nexport function isPollablePhase(phase: CheckoutPhase): boolean {\n return phase === 'processing' || phase === 'action_required';\n}\n\nexport function isTerminalPhase(phase: CheckoutPhase): boolean {\n return phase === 'succeeded' || phase === 'failed' || phase === 'closed';\n}\n","import type { AttemptSummary } from '../types/contract';\nimport type { NextAction } from '../types/next-action';\nimport type { ActionCompletion, CheckoutView, FormContext, ResultContext, WaitingContext } from '../types/view';\n\nimport type { EngineState } from './state';\n\n/**\n * Behavior mapping: given a next_action type, how does it complete? This is\n * the single place that decides submit/poll/redirect/sdk so a theme never has\n * to. Unknown types fail closed to `poll`.\n */\nexport function actionCompletion(action: NextAction): ActionCompletion {\n switch (action.type) {\n case 'collect_otp':\n return 'submit';\n case 'complete_with_sdk':\n return 'sdk';\n case 'redirect_to_url':\n return 'redirect';\n case 'embed_iframe':\n case 'approve_on_phone':\n case 'scan_qr_code':\n case 'display_payment_instructions':\n return 'poll';\n case 'none':\n return 'poll';\n default:\n // Unknown/forward-compat action type: wait and poll, never crash a theme.\n return 'poll';\n }\n}\n\n/** An action is renderable as an `action` view only if it asks for something. */\nfunction isActionable(action: NextAction | null): action is NextAction {\n return action !== null && action.type !== 'none';\n}\n\n/**\n * Pure projection: EngineState -> CheckoutView. No I/O, no mutation.\n */\nexport function projectView(state: EngineState): CheckoutView {\n const { phase, checkout, catalogue } = state;\n\n if (phase === 'loading') {\n return { kind: 'loading' };\n }\n if (!checkout) {\n // Forced terminal phase before any checkout loaded (e.g. 404 on first load).\n const kind = phase === 'succeeded' || phase === 'failed' ? phase : 'closed';\n return { kind, ctx: result(state, kind) };\n }\n\n const attempt = checkout.attempt;\n // Appearance is bootstrap-scoped now (not on show/pay/poll), so it lives in\n // engine state and is projected onto every view.\n const appearance = state.appearance;\n\n switch (phase) {\n case 'collecting': {\n if (!catalogue) return { kind: 'loading' };\n const ctx: FormContext = {\n amount: catalogue.amount,\n methods: catalogue.methods,\n country: catalogue.country,\n currencyOptions: catalogue.currencyOptions,\n supportsAnyCountry: catalogue.supportsAnyCountry,\n previousPhones: state.previousPhones,\n };\n if (checkout.restriction) ctx.restriction = checkout.restriction;\n if (checkout.customer) ctx.customer = checkout.customer;\n if (checkout.project) ctx.project = checkout.project;\n if (appearance) ctx.appearance = appearance;\n if (!state.dismissedError) {\n if (state.error) ctx.lastError = state.error;\n if (isFailedAttempt(attempt)) ctx.retryOf = attempt;\n }\n return { kind: 'form', ctx };\n }\n\n case 'action_required': {\n const action = attempt?.next_action ?? null;\n // action_required but nothing to render (null / none) -> wait + poll.\n if (!attempt || !isActionable(action)) {\n return attempt ? { kind: 'processing', ctx: waiting(state, attempt) } : { kind: 'loading' };\n }\n return {\n kind: 'action',\n ctx: {\n action,\n attempt,\n completion: actionCompletion(action),\n ...(catalogue ? { amount: catalogue.amount } : {}),\n ...(checkout.project ? { project: checkout.project } : {}),\n ...(appearance ? { appearance } : {}),\n },\n };\n }\n\n case 'processing': {\n return attempt ? { kind: 'processing', ctx: waiting(state, attempt) } : { kind: 'loading' };\n }\n\n case 'succeeded':\n return { kind: 'succeeded', ctx: result(state, 'succeeded') };\n\n case 'failed':\n return { kind: 'failed', ctx: result(state, 'failed') };\n\n case 'closed':\n return { kind: 'closed', ctx: result(state, 'closed') };\n\n default:\n return { kind: 'loading' };\n }\n}\n\nfunction isFailedAttempt(attempt: AttemptSummary | undefined): attempt is AttemptSummary {\n return attempt != null && (attempt.status === 'failed' || attempt.status === 'cancelled');\n}\n\nfunction waiting(state: EngineState, attempt: AttemptSummary): WaitingContext {\n const ctx: WaitingContext = { attempt };\n if (state.catalogue) ctx.amount = state.catalogue.amount;\n if (state.checkout?.project) ctx.project = state.checkout.project;\n if (state.appearance) ctx.appearance = state.appearance;\n return ctx;\n}\n\nfunction result(state: EngineState, kind: 'succeeded' | 'failed' | 'closed'): ResultContext {\n const checkout = state.checkout;\n\n // A closed checkout is closed because of the SESSION (expired/cancelled);\n // the intent may still read 'pending'. Success/failure come from the intent.\n const status =\n kind === 'closed'\n ? (checkout?.session.status ?? 'expired')\n : (checkout?.payment?.status ?? checkout?.session.status ?? 'expired');\n\n // For a failure, the customer-facing reason is the attempt's failure message,\n // not the generic envelope message. Terminal copy is otherwise the theme's job.\n const failureMessage = kind === 'failed' ? checkout?.attempt?.failure.message : undefined;\n\n let message = '';\n if (kind === 'failed') message = failureMessage ?? '';\n else if (kind === 'succeeded') message = state.message;\n const ctx: ResultContext = { status, message };\n if (checkout?.payment) ctx.payment = checkout.payment;\n if (state.catalogue) ctx.amount = state.catalogue.amount;\n if (checkout?.project) ctx.project = checkout.project;\n if (state.appearance) ctx.appearance = state.appearance;\n if (state.returnUrl) ctx.returnUrl = state.returnUrl;\n return ctx;\n}\n","import type {\n Appearance,\n Country,\n CurrencyOption,\n HostedCheckout,\n PaymentMethod,\n PreviousPhone,\n ResolvedAmount,\n} from '../types/contract';\nimport type { CheckoutError } from '../types/errors';\n\n/**\n * The resolved catalogue is returned ONLY by `show`. `pay`/`authorize`/`poll`\n * omit it, so the engine caches the last good catalogue and re-fetches it only\n * when country/currency changes. See contract.ts › HostedCheckout.\n */\nexport interface ResolvedCatalogue {\n country: Country;\n currencyOptions: CurrencyOption[];\n amount: ResolvedAmount;\n methods: PaymentMethod[];\n supportsAnyCountry: boolean;\n}\n\nexport type CheckoutPhase =\n | 'loading'\n | 'closed'\n | 'succeeded'\n | 'failed'\n | 'action_required'\n | 'processing'\n | 'collecting';\n\nexport interface EngineState {\n /** Last good catalogue from `show`. */\n catalogue: ResolvedCatalogue | null;\n /**\n * Customer's saved phones, cached like the catalogue. `show`/`hydrate` return\n * them, but `pay`/`authorize`/`poll` responses carry `previous_used_phones:\n * null`, so reading them off the live checkout would make the recent-phone\n * card vanish after a failed attempt. Cached here and refreshed only when a\n * response actually provides them.\n */\n previousPhones: PreviousPhone[];\n /** Last response from any endpoint. */\n checkout: HostedCheckout | null;\n /** Server `message` from the last successful response. */\n message: string;\n phase: CheckoutPhase;\n error: CheckoutError | null;\n /**\n * The customer dismissed the current error banner (e.g. by reselecting a\n * method). Suppresses both banner sources (`lastError`, `retryOf`) until the\n * next server response, which resets it.\n */\n dismissedError: boolean;\n /**\n * Session-scoped chrome from the bootstrap payload. `appearance` is no longer\n * on show/pay/poll responses, so the engine holds it here and projects it on\n * every view. `returnUrl` (nullable, may be absent for old sessions) is the\n * merchant redirect target for the terminal \"return\" CTA.\n */\n appearance: Appearance | null;\n returnUrl: string | null;\n polling: boolean;\n}\n\nexport function initialState(): EngineState {\n return {\n catalogue: null,\n previousPhones: [],\n checkout: null,\n message: '',\n phase: 'loading',\n error: null,\n dismissedError: false,\n appearance: null,\n returnUrl: null,\n polling: false,\n };\n}\n\n/** Pull the catalogue out of a `show` response; null if not present. */\nexport function extractCatalogue(checkout: HostedCheckout): ResolvedCatalogue | null {\n const { country, currency_options, amount, methods } = checkout;\n if (!country || !currency_options || !amount || !methods) return null;\n return {\n country,\n currencyOptions: currency_options,\n amount,\n methods,\n supportsAnyCountry: checkout.supports_any_country ?? false,\n };\n}\n","import type { Appearance, AuthorizeInput, CountrySimplified, HostedCheckout, PayInput } from '../types/contract';\nimport { CheckoutError } from '../types/errors';\nimport type { CheckoutView } from '../types/view';\nimport type { Transport } from '../transport/transport';\n\nimport { derivePhase, isTerminalPhase } from './phase';\nimport { actionCompletion, projectView } from './project';\nimport { extractCatalogue, initialState, type EngineState } from './state';\n\nexport interface CheckoutEngineOptions {\n /** Auto-manage the polling loop based on phase. Default true. */\n autoPoll?: boolean;\n /** Backoff delays (ms) for the first polls. Default [2000,2000,3000,5000]. */\n pollIntervalsMs?: number[];\n /** Steady interval (ms) after the backoff ramp. Default 5000. */\n steadyIntervalMs?: number;\n /** Clock injection for tests. Default Date.now. */\n now?: () => number;\n /** Timer injection for tests. Default global setTimeout/clearTimeout. */\n setTimeoutImpl?: (cb: () => void, ms: number) => ReturnType<typeof setTimeout>;\n clearTimeoutImpl?: (handle: ReturnType<typeof setTimeout>) => void;\n}\n\ntype Listener = (view: CheckoutView) => void;\n\n/**\n * The engine facade themes consume. Owns state, the polling loop, and all\n * transport calls. Themes never see the Transport, the wire types, or the\n * token — only CheckoutView (via getView/subscribe) and these action methods.\n */\nexport class CheckoutEngine {\n private state: EngineState = initialState();\n private readonly listeners = new Set<Listener>();\n\n private readonly autoPoll: boolean;\n private readonly intervals: number[];\n private readonly steady: number;\n private readonly now: () => number;\n private readonly setTimeoutImpl: NonNullable<CheckoutEngineOptions['setTimeoutImpl']>;\n private readonly clearTimeoutImpl: NonNullable<CheckoutEngineOptions['clearTimeoutImpl']>;\n\n private pollHandle: ReturnType<typeof setTimeout> | null = null;\n private pollTick = 0;\n private pollInFlight = false;\n private destroyed = false;\n\n constructor(\n private readonly transport: Transport,\n options: CheckoutEngineOptions = {},\n ) {\n this.autoPoll = options.autoPoll ?? true;\n this.intervals = options.pollIntervalsMs ?? [2000, 2000, 3000, 5000];\n this.steady = options.steadyIntervalMs ?? 5000;\n this.now = options.now ?? Date.now;\n this.setTimeoutImpl = options.setTimeoutImpl ?? ((cb, ms) => setTimeout(cb, ms));\n this.clearTimeoutImpl = options.clearTimeoutImpl ?? ((handle) => clearTimeout(handle));\n }\n\n // --- read surface ---\n\n getView(): CheckoutView {\n return projectView(this.state);\n }\n\n /** Subscribe to view changes. Fires immediately with the current view. */\n subscribe(fn: Listener): () => void {\n this.listeners.add(fn);\n fn(this.getView());\n return () => {\n this.listeners.delete(fn);\n };\n }\n\n // --- actions ---\n\n /**\n * Seed state from a server-fetched `show` payload (SSR) so the first paint is\n * the form, not the loading screen — no transport call. The host passes the\n * `GET /checkout/{public_id}` payload the SSR layer fetched after bootstrap.\n * Treated exactly like a `show`, so the resolved catalogue is cached. The\n * engine may still `poll()`/`load()` afterwards to refresh.\n */\n hydrate(checkout: HostedCheckout, message = ''): void {\n this.applyResponse(checkout, message, true);\n }\n\n /**\n * Seed session-scoped chrome from the SSR bootstrap payload. `appearance` and\n * `return_url` no longer ride on show/pay/poll responses, so the host passes\n * them once here and the engine projects them onto every view. Call before the\n * first render (alongside `hydrate`) so the theme paints branded from frame 1.\n */\n seedBootstrap(input: { appearance?: Appearance | null; returnUrl?: string | null }): void {\n const next: Partial<EngineState> = {};\n if (input.appearance) next.appearance = input.appearance;\n if (input.returnUrl !== undefined) next.returnUrl = input.returnUrl;\n if (Object.keys(next).length > 0) this.setState(next);\n }\n\n async load(): Promise<void> {\n await this.runShow(undefined);\n }\n\n async selectCountry(country: string): Promise<void> {\n await this.runShow({ country });\n }\n\n async selectCurrency(currency: string): Promise<void> {\n // Preserve the resolved country. Sending `currency` alone makes the server\n // re-resolve the country to its default, silently switching it — the bug when\n // a country exposes more than one currency (e.g. CD: CDF/USD). `selectCountry`\n // deliberately omits currency so the server picks the new country's default.\n const country = this.state.catalogue?.country.code;\n await this.runShow(country ? { country, currency } : { currency });\n }\n\n /** Full selectable country catalogue for the picker (not part of the view). */\n async listCountries(): Promise<CountrySimplified[]> {\n try {\n const res = await this.transport.countries();\n return res.data;\n } catch (cause) {\n this.setError(cause);\n return [];\n }\n }\n\n async pay(input: PayInput): Promise<void> {\n await this.runMutation(() => this.transport.pay(this.withCatalogueDefaults(input)), false);\n }\n\n /**\n * Dismiss the current error banner (both `lastError` and a failed-attempt\n * `retryOf`). Themes call this when the customer selects a method again so a\n * stale error doesn't linger; the next server response clears the dismissal.\n */\n clearError(): void {\n if (this.state.error === null && this.state.dismissedError) return;\n this.setState({ error: null, dismissedError: true });\n }\n\n async authorize(input: AuthorizeInput): Promise<void> {\n await this.runMutation(() => this.transport.authorize(input), false);\n }\n\n async poll(): Promise<void> {\n await this.runMutation(() => this.transport.poll(), false);\n }\n\n /** Called when the customer returns from an external redirect. Just polls. */\n async resumeFromRedirect(): Promise<void> {\n await this.poll();\n }\n\n // --- polling control (host wires visibility/focus to these) ---\n\n startPolling(): void {\n if (this.destroyed || this.state.polling) return;\n this.setState({ polling: true });\n this.pollTick = 0;\n this.scheduleNextPoll();\n }\n\n stopPolling(): void {\n if (this.pollHandle !== null) {\n this.clearTimeoutImpl(this.pollHandle);\n this.pollHandle = null;\n }\n if (this.state.polling) this.setState({ polling: false });\n }\n\n destroy(): void {\n this.destroyed = true;\n this.stopPolling();\n this.listeners.clear();\n }\n\n // --- internals ---\n\n private async runShow(query: { country?: string; currency?: string } | undefined): Promise<void> {\n try {\n const res = await this.transport.show(query);\n this.applyResponse(res.data, res.message ?? '', true);\n } catch (cause) {\n this.setError(cause);\n }\n }\n\n private async runMutation(\n call: () => Promise<{ data: HostedCheckout; message?: string }>,\n isShow: boolean,\n ): Promise<void> {\n try {\n const res = await call();\n this.applyResponse(res.data, res.message ?? '', isShow);\n } catch (cause) {\n this.setError(cause);\n }\n }\n\n /**\n * Stamp the pay payload with the currently-resolved country/currency from the\n * cached catalogue. Themes call `selectCountry`/`selectCurrency` (which refetch\n * the catalogue) but never thread that selection back into `pay` — without this\n * the server falls back to its default country and rejects methods that aren't\n * available there. A value already on the input always wins; currency is only\n * stamped when DCC is in effect (the only time the server expects it).\n */\n private withCatalogueDefaults(input: PayInput): PayInput {\n const catalogue = this.state.catalogue;\n if (!catalogue) return input;\n\n const next: PayInput = { ...input };\n if (next.country === undefined) next.country = catalogue.country.code;\n if (next.currency === undefined && catalogue.amount.is_dcc) {\n const currency = catalogue.amount.final.currency;\n if (currency) next.currency = currency;\n }\n return next;\n }\n\n private applyResponse(checkout: HostedCheckout, message: string, isShow: boolean): void {\n const next: Partial<EngineState> = {\n checkout,\n message,\n phase: derivePhase(checkout),\n error: null,\n // A fresh response (incl. a new failed attempt) is shown, not suppressed.\n dismissedError: false,\n };\n if (isShow) {\n const catalogue = extractCatalogue(checkout);\n if (catalogue) next.catalogue = catalogue;\n }\n // Cache saved phones whenever a response actually carries them; mutation\n // responses null them out, so keep the last known list across retries.\n if (checkout.previous_used_phones != null) {\n next.previousPhones = checkout.previous_used_phones;\n }\n this.setState(next);\n this.reconcilePolling();\n }\n\n private setError(cause: unknown): void {\n const error = cause instanceof CheckoutError ? cause : new CheckoutError('unknown', toMessage(cause));\n\n // Terminal errors close the checkout; recoverable ones keep the phase so the\n // theme can show the message inline (e.g. 422 on pay stays in `collecting`).\n const isTerminalError = error.code === 'not_found' || error.code === 'not_open';\n const keepPhase = !isTerminalError && this.state.checkout;\n const phase: EngineState['phase'] = keepPhase ? this.state.phase : 'closed';\n\n this.setState({ error, phase, message: error.message, dismissedError: false });\n this.reconcilePolling();\n }\n\n private reconcilePolling(): void {\n if (!this.autoPoll || this.destroyed) return;\n if (isTerminalPhase(this.state.phase)) {\n this.stopPolling();\n return;\n }\n if (this.shouldPoll()) {\n this.startPolling();\n } else {\n this.stopPolling();\n }\n }\n\n /**\n * Poll while an attempt is `processing`, or while it is `action_required`\n * with a poll-completion action (approve_on_phone, scan_qr_code,\n * display_payment_instructions, embed_iframe). Do NOT poll while waiting on\n * the customer to submit (collect_otp), redirect, or run an SDK.\n */\n private shouldPoll(): boolean {\n if (this.state.phase === 'processing') return true;\n if (this.state.phase === 'action_required') {\n const action = this.state.checkout?.attempt?.next_action;\n return action != null && actionCompletion(action) === 'poll';\n }\n return false;\n }\n\n private scheduleNextPoll(): void {\n if (this.destroyed || !this.state.polling) return;\n\n const delay = this.intervals[this.pollTick] ?? this.steady;\n this.pollTick++;\n\n // Cap to session expiry: stop scheduling once we're past expires_at.\n const expiresAt = this.expiresAtMs();\n if (expiresAt !== null && this.now() >= expiresAt) {\n this.stopPolling();\n return;\n }\n\n this.pollHandle = this.setTimeoutImpl(() => {\n this.tickPoll().catch(() => undefined);\n }, delay);\n }\n\n private async tickPoll(): Promise<void> {\n if (this.destroyed || !this.state.polling || this.pollInFlight) return;\n this.pollInFlight = true;\n try {\n await this.poll();\n } finally {\n this.pollInFlight = false;\n }\n // poll() -> applyResponse -> reconcilePolling may have stopped us.\n if (this.state.polling && !isTerminalPhase(this.state.phase)) {\n this.scheduleNextPoll();\n }\n }\n\n private expiresAtMs(): number | null {\n const raw = this.state.checkout?.session.expires_at;\n if (!raw) return null;\n const ms = Date.parse(raw);\n return Number.isNaN(ms) ? null : ms;\n }\n\n private setState(partial: Partial<EngineState>): void {\n this.state = { ...this.state, ...partial };\n this.emit();\n }\n\n private emit(): void {\n const view = this.getView();\n for (const listener of this.listeners) listener(view);\n }\n}\n\nfunction toMessage(cause: unknown): string {\n if (cause instanceof Error) return cause.message;\n return 'Unexpected error.';\n}\n","import type { RedirectToUrlAction } from '@orqex/checkout-engine';\n\ninterface RedirectEffectDeps {\n /** Top-level navigation for GET redirects. Default window.location.assign. */\n navigate?: (url: string) => void;\n /** Injectable document for tests. Default global document. */\n doc?: Document;\n}\n\n/**\n * Execute a redirect next-action in a headless page. GET navigates the\n * top-level document; POST auto-submits a hidden form (some 3-D Secure ACS\n * endpoints). Refuses any non-https URL as defense-in-depth — the primary trust\n * boundary is the server, but we never navigate to javascript:/data: schemes.\n */\nexport function performActionRedirect(action: RedirectToUrlAction, deps: RedirectEffectDeps = {}): void {\n const doc = deps.doc ?? document;\n const navigate = deps.navigate ?? ((url: string) => window.location.assign(url));\n\n if (!isHttps(action.url)) {\n // eslint-disable-next-line no-console\n console.error(`Orqex: refused redirect to non-https URL \"${action.url}\".`);\n return;\n }\n\n if (action.method === 'POST') {\n const form = doc.createElement('form');\n form.method = 'POST';\n form.action = action.url;\n form.style.display = 'none';\n for (const [name, value] of Object.entries(action.post_data ?? {})) {\n const input = doc.createElement('input');\n input.type = 'hidden';\n input.name = name;\n input.value = typeof value === 'string' ? value : JSON.stringify(value);\n form.appendChild(input);\n }\n doc.body.appendChild(form);\n form.submit();\n return;\n }\n\n navigate(action.url);\n}\n\nfunction isHttps(url: string): boolean {\n try {\n return new URL(url).protocol === 'https:';\n } catch {\n return false;\n }\n}\n","import {\n CheckoutEngine,\n HttpTransport,\n type AuthorizeInput,\n type CheckoutView,\n type CountrySimplified,\n type PayInput,\n type RedirectToUrlAction,\n} from '@orqex/checkout-engine';\n\nimport type { ResolvedConfig } from './config';\nimport { performActionRedirect } from './redirect-effect';\n\nexport interface CreateEngineOptions {\n /** cs_… checkout handle minted server-side by the merchant. */\n publicId: string;\n /** BCP-47 locale for Accept-Language. Default navigator.language. */\n locale?: string;\n /**\n * When true, the SDK persists publicId across a redirect and auto-resumes on\n * return, and auto-performs redirect actions. Default false (fully manual).\n */\n autoResume?: boolean;\n}\n\n/** Narrowed, browser-facing surface over CheckoutEngine. Cross-SDK contract. */\nexport interface OrqexCheckout {\n subscribe(fn: (view: CheckoutView) => void): () => void;\n getView(): CheckoutView;\n pay(input: PayInput): Promise<void>;\n authorize(input: AuthorizeInput): Promise<void>;\n poll(): Promise<void>;\n selectCountry(country: string): Promise<void>;\n selectCurrency(currency: string): Promise<void>;\n listCountries(): Promise<CountrySimplified[]>;\n /** Poll the current server state (call on return from an external redirect). */\n resumeFromRedirect(): Promise<void>;\n startPolling(): void;\n stopPolling(): void;\n /** Perform the pending redirect action; no-op if the current view is not one. */\n performRedirect(): void;\n destroy(): void;\n}\n\nexport interface HeadlessDeps {\n /** Injected engine for tests; when omitted a real one is built. */\n engine?: CheckoutEngine;\n /** Injectable window for tests. Default global window. */\n win?: Window;\n /** Injectable storage for autoResume tests. Default window.sessionStorage. */\n storage?: Storage;\n /** Injectable fetch passed to HttpTransport. Default global fetch. */\n fetchImpl?: (input: string, init?: RequestInit) => Promise<Response>;\n}\n\n/** Extract the current redirect action from a view, or null. */\nfunction redirectActionOf(view: CheckoutView): RedirectToUrlAction | null {\n if (view.kind === 'action' && view.ctx.completion === 'redirect' && view.ctx.action.type === 'redirect_to_url') {\n return view.ctx.action;\n }\n return null;\n}\n\nconst markerKey = (publicId: string): string => `orqex:redirect:${publicId}`;\n\nfunction wireAutoResume(engine: CheckoutEngine, publicId: string, ctx: { storage: Storage; win: Window }): () => void {\n const key = markerKey(publicId);\n\n // Returning from a redirect: a pending marker means we just came back.\n if (ctx.storage.getItem(key) !== null) {\n ctx.storage.removeItem(key);\n engine.resumeFromRedirect();\n }\n\n // Auto-perform the redirect once per (attempt, action).\n let handled: string | null = null;\n const unsubscribe = engine.subscribe((view) => {\n const action = redirectActionOf(view);\n if (!action || !action.can_auto_redirect || view.kind !== 'action') return;\n const dedupe = `${view.ctx.attempt.id}:${action.type}`;\n if (handled === dedupe) return;\n handled = dedupe;\n ctx.storage.setItem(key, view.ctx.attempt.id);\n performActionRedirect(action, { navigate: (url) => ctx.win.location.assign(url), doc: ctx.win.document });\n });\n\n const onPageShow = (): void => {\n const kind = engine.getView().kind;\n if (kind === 'action' || kind === 'processing') engine.resumeFromRedirect();\n };\n ctx.win.addEventListener('pageshow', onPageShow);\n\n return () => {\n unsubscribe();\n ctx.win.removeEventListener('pageshow', onPageShow);\n };\n}\n\n/**\n * Build the headless checkout: a real CheckoutEngine over HttpTransport (pk_),\n * wrapped in the narrowed OrqexCheckout facade. Manual mode; autoResume wiring\n * is conditionally applied when `options.autoResume` is true.\n */\nexport function createHeadlessCheckout(\n config: ResolvedConfig,\n options: CreateEngineOptions,\n deps: HeadlessDeps = {},\n): OrqexCheckout {\n const win = deps.win ?? window;\n const engine =\n deps.engine ??\n new CheckoutEngine(\n new HttpTransport({\n baseUrl: config.apiBaseUrl,\n auth: { publishableKey: config.publishableKey, publicId: options.publicId },\n locale: options.locale ?? (typeof navigator === 'undefined' ? undefined : navigator.language),\n fetchImpl: deps.fetchImpl,\n }),\n );\n\n let autoResumeTeardown: () => void = () => {};\n\n const facade: OrqexCheckout = {\n subscribe: (fn) => engine.subscribe(fn),\n getView: () => engine.getView(),\n pay: (input) => engine.pay(input),\n authorize: (input) => engine.authorize(input),\n poll: () => engine.poll(),\n selectCountry: (country) => engine.selectCountry(country),\n selectCurrency: (currency) => engine.selectCurrency(currency),\n listCountries: () => engine.listCountries(),\n resumeFromRedirect: () => engine.resumeFromRedirect(),\n startPolling: () => engine.startPolling(),\n stopPolling: () => engine.stopPolling(),\n performRedirect: () => {\n const action = redirectActionOf(engine.getView());\n if (action) performActionRedirect(action, { navigate: (url) => win.location.assign(url), doc: win.document });\n },\n destroy: () => {\n autoResumeTeardown();\n engine.destroy();\n },\n };\n\n if (options.autoResume) {\n autoResumeTeardown = wireAutoResume(engine, options.publicId, { storage: deps.storage ?? win.sessionStorage, win });\n }\n\n engine.load();\n return facade;\n}\n","import { buildRedirectUrl, type ResolvedConfig } from './config';\n\nexport interface RedirectOptions {\n /** cs_… checkout handle minted server-side by the merchant. */\n publicId: string;\n}\n\ntype Navigate = (url: string) => void;\n\nconst defaultNavigate: Navigate = (url) => {\n window.location.assign(url);\n};\n\n/** Full-page navigation to the hosted checkout. */\nexport function redirectToCheckout(\n config: ResolvedConfig,\n options: RedirectOptions,\n navigate: Navigate = defaultNavigate,\n): void {\n if (!options.publicId) {\n throw new Error('Orqex: redirectToCheckout requires a publicId.');\n }\n navigate(buildRedirectUrl(config, options.publicId));\n}\n","import { resolveConfig, type OrqexOptions } from './config';\nimport { EmbeddedController, type MountOptions } from './embedded';\nimport { EventBus, type EventPayloads, type MerchantEvent } from './event-bus';\nimport { createHeadlessCheckout, type CreateEngineOptions, type OrqexCheckout } from './headless';\nimport { redirectToCheckout, type RedirectOptions } from './redirect';\n\nexport interface OrqexInstance {\n /** Embedded mode: hosted checkout in a sandboxed iframe. */\n mount(target: string | HTMLElement, options: MountOptions): void;\n /** Redirect mode: full-page navigation to the hosted checkout. */\n redirectToCheckout(options: RedirectOptions): void;\n /** Subscribe to a lifecycle event; returns a disposer. */\n on<TEvent extends MerchantEvent>(event: TEvent, handler: (payload: EventPayloads[TEvent]) => void): () => void;\n /** Tear down the embedded iframe and its listener (no-op in redirect mode). */\n unmount(): void;\n /** Headless mode: run the engine in this page and render your own UI. */\n createEngine(options: CreateEngineOptions): OrqexCheckout;\n}\n\n/**\n * SDK entry point. `Orqex('pk_…')` validates the key, then exposes embedded,\n * redirect, and headless (`createEngine`) modes over one event bus.\n */\nexport function Orqex(publishableKey: string, options?: OrqexOptions): OrqexInstance {\n const config = resolveConfig(publishableKey, options);\n const bus = new EventBus();\n const embedded = new EmbeddedController({ config, bus });\n\n return {\n mount(target, mountOptions) {\n embedded.mount(target, mountOptions);\n },\n redirectToCheckout(redirectOptions) {\n redirectToCheckout(config, redirectOptions);\n },\n on(event, handler) {\n return bus.on(event, handler);\n },\n unmount() {\n embedded.unmount();\n },\n createEngine(engineOptions) {\n return createHeadlessCheckout(config, engineOptions);\n },\n };\n}\n","import type { CheckoutView } from '@orqex/checkout-engine';\n\nimport { closeMessage, errorMessage, successMessage, type EmbedMessage } from './protocol';\n\nexport interface EmbedProjection {\n message: EmbedMessage;\n /** Dedup key so the host posts each terminal state at most once. */\n key: string;\n}\n\n/**\n * Pure mapping from the engine's projected view to an embed lifecycle message.\n * Terminal views only; `redirect` is handled by the host's redirect override\n * (a redirect action is not a terminal view). Returns null when there is\n * nothing new to post or `key` equals `lastKey`.\n */\nexport function projectEmbedMessage(view: CheckoutView, lastKey: string | null): EmbedProjection | null {\n let projection: EmbedProjection | null = null;\n\n if (view.kind === 'succeeded') {\n const status = String(view.ctx.status);\n projection = { message: successMessage(status), key: `succeeded:${status}` };\n } else if (view.kind === 'failed') {\n const status = String(view.ctx.status);\n projection = { message: errorMessage(status, view.ctx.message), key: `failed:${status}` };\n } else if (view.kind === 'closed') {\n const status = String(view.ctx.status);\n projection = { message: closeMessage(status), key: `closed:${status}` };\n }\n\n if (!projection || projection.key === lastKey) return null;\n return projection;\n}\n","/**\n * @orqex/checkout-js — client-side SDK for Orqex payments.\n *\n * Browser-host glue over the existing engine + hosted checkout. Never accepts a\n * secret key; the publishable key (pk_) is public by design.\n */\n\nexport const SDK_VERSION = '0.0.1';\n\nexport { Orqex } from './orqex';\nexport type { OrqexInstance } from './orqex';\nexport type { OrqexOptions } from './config';\nexport type { MountOptions } from './embedded';\nexport type { RedirectOptions } from './redirect';\nexport type { MerchantEvent, EventPayloads } from './event-bus';\nexport type { OrqexCheckout, CreateEngineOptions } from './headless';\n// Engine contract re-exported so headless merchants render against the typed view.\nexport type { CheckoutView, PayInput, AuthorizeInput, CountrySimplified } from '@orqex/checkout-engine';\n\n// Embed protocol + view→message projection: re-exported so the hosted app\n// (checkout-next) imports the single source of truth for the wire contract.\nexport * from './protocol';\nexport { projectEmbedMessage } from './embed-projection';\nexport type { EmbedProjection } from './embed-projection';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orqex/checkout-js",
3
- "version": "0.0.1",
3
+ "version": "0.1.0-beta-a7744cf",
4
4
  "type": "module",
5
5
  "description": "Client-side JavaScript SDK for Orqex payments: Orqex(pk_) init, redirectToCheckout, embedded iframe mount, typed event bus, and the embed postMessage protocol.",
6
6
  "license": "MIT",