@thavguard/arc-pay 0.1.0 → 0.1.1

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/errors.ts","../../src/server/client.ts"],"names":[],"mappings":";AAqBO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EASrC,YAAY,IAAA,EAAuB;AACjC,IAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,cAAc,IAAA,CAAK,WAAA;AACxB,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AAAA,EACxB;AACF,CAAA;;;ACoBA,IAAM,gBAAA,GAAmB,6BAAA;AACzB,IAAM,WAAA,GAAc,YAAA;AAEpB,SAAS,kBAAkB,GAAA,EAAqC;AAC9D,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,CAAI,WAAW,CAAA,EAAG;AAC/C,IAAA,MAAM,IAAI,WAAA,CAAY;AAAA,MACpB,IAAA,EAAM,sBAAA;AAAA,MACN,IAAA,EAAM,oBAAA;AAAA,MACN,OAAA,EAAS,uCAAA;AAAA,MACT,SAAA,EAAW;AAAA,KACZ,CAAA;AAAA,EACH;AACA,EAAA,IAAI,CAAC,IAAI,UAAA,CAAW,UAAU,KAAK,CAAC,GAAA,CAAI,UAAA,CAAW,UAAU,CAAA,EAAG;AAC9D,IAAA,MAAM,IAAI,WAAA,CAAY;AAAA,MACpB,IAAA,EAA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AK;AAAA,EACzB;AACF;AAEO,IAAM,kBAAA,GAAqB,CAAC,OAAA,KACjC,IAAI,aAAa,OAAO","file":"index.mjs","sourcesContent":["export type ArcPayErrorType =\n | \"validation_error\"\n | \"authentication_error\"\n | \"authorization_error\"\n | \"state_error\"\n | \"rate_limit_error\"\n | \"api_error\"\n | \"network_error\"\n | \"challenge_aborted\";\n\nexport interface ArcPayErrorInit {\n type: ArcPayErrorType;\n message: string;\n code?: string;\n param?: string;\n paymentId?: string;\n declineCode?: string;\n retryable: boolean;\n requestId?: string;\n}\n\nexport class ArcPayError extends Error {\n readonly type: ArcPayErrorType;\n readonly code?: string;\n readonly param?: string;\n readonly paymentId?: string;\n readonly declineCode?: string;\n readonly retryable: boolean;\n readonly requestId?: string;\n\n constructor(init: ArcPayErrorInit) {\n super(init.message);\n this.name = \"ArcPayError\";\n this.type = init.type;\n this.code = init.code;\n this.param = init.param;\n this.paymentId = init.paymentId;\n this.declineCode = init.declineCode;\n this.retryable = init.retryable;\n this.requestId = init.requestId;\n }\n}\n\nexport const isValidationError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"validation_error\";\nexport const isAuthenticationError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"authentication_error\";\nexport const isAuthorizationError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"authorization_error\";\nexport const isStateError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"state_error\";\nexport const isRateLimitError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"rate_limit_error\";\nexport const isApiError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"api_error\";\nexport const isNetworkError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"network_error\";\nexport const isChallengeAborted = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"challenge_aborted\";\n","import { ArcPayError, type ArcPayErrorType } from \"../core/errors\";\nimport type {\n AvailablePaymentMethod,\n CaptureRequest,\n CheckoutSession,\n CompleteThreeDSMethodRequest,\n CreateCheckoutSessionRequest,\n CreateLinkRequest,\n CreatePaymentRequest,\n CreateRefundRequest,\n ExecutePaymentRequest,\n ExecutePaymentResponse,\n Link,\n ListAvailablePaymentMethodsQuery,\n ListPaymentsQuery,\n Payment,\n PaymentList,\n Refund,\n VoidRequest,\n} from \"./types\";\n\nexport type {\n AvailablePaymentMethod,\n CaptureMode,\n CaptureRequest,\n CheckoutSession,\n CompleteThreeDSMethodRequest,\n CreateCheckoutSessionRequest,\n CreateLinkRequest,\n CreatePaymentRequest,\n CreateRefundRequest,\n Currency,\n ExecutePaymentRequest,\n ExecutePaymentResponse,\n Link,\n ListAvailablePaymentMethodsQuery,\n ListPaymentsQuery,\n Payment,\n PaymentFlowMode,\n PaymentList,\n PaymentMethod,\n PaymentStatus,\n Refund,\n VoidRequest,\n} from \"./types\";\n\nexport interface ArcPayClientOptions {\n secretKey: string;\n apiBase?: string;\n fetch?: typeof fetch;\n}\n\nexport interface IdempotencyOptions {\n idempotencyKey: string;\n signal?: AbortSignal;\n}\n\nexport interface RequestOptions {\n signal?: AbortSignal;\n}\n\nconst DEFAULT_API_BASE = \"https://api.arcpay.space/v1\";\nconst API_VERSION = \"2026-05-06\";\n\nfunction validateSecretKey(key: unknown): asserts key is string {\n if (typeof key !== \"string\" || key.length === 0) {\n throw new ArcPayError({\n type: \"authentication_error\",\n code: \"invalid_secret_key\",\n message: \"Secret key must be a non-empty string\",\n retryable: false,\n });\n }\n if (!key.startsWith(\"sk_test_\") && !key.startsWith(\"sk_live_\")) {\n throw new ArcPayError({\n type: \"authentication_error\",\n code: \"invalid_secret_key\",\n message: \"Secret key must start with sk_test_ or sk_live_. Publishable keys cannot call server APIs.\",\n retryable: false,\n });\n }\n}\n\nconst normalizeBase = (base: string): string => base.replace(/\\/+$/, \"\");\n\nconst requireIdempotencyKey = (opts: IdempotencyOptions): string => {\n if (!opts.idempotencyKey) {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"missing_idempotency_key\",\n message: \"idempotencyKey is required for this operation\",\n retryable: false,\n });\n }\n return opts.idempotencyKey;\n};\n\nconst appendQuery = (path: string, query?: object): string => {\n if (!query) return path;\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null || value === \"\") continue;\n params.set(key, String(value));\n }\n const encoded = params.toString();\n return encoded ? `${path}?${encoded}` : path;\n};\n\ninterface APIErrorBody {\n error?: {\n type?: string;\n code?: string;\n message?: string;\n param?: string;\n request_id?: string;\n decline_code?: string;\n };\n}\n\nconst isPublicErrorType = (value: unknown): value is ArcPayErrorType =>\n value === \"validation_error\" ||\n value === \"authentication_error\" ||\n value === \"authorization_error\" ||\n value === \"state_error\" ||\n value === \"rate_limit_error\" ||\n value === \"api_error\";\n\nconst parseErrorResponse = async (res: Response): Promise<ArcPayError> => {\n let body: APIErrorBody = {};\n try {\n body = (await res.json()) as APIErrorBody;\n } catch {\n /* keep default error below */\n }\n const detail = body.error ?? {};\n const type = isPublicErrorType(detail.type)\n ? detail.type\n : res.status >= 500\n ? \"api_error\"\n : \"validation_error\";\n return new ArcPayError({\n type,\n code: detail.code,\n message: detail.message ?? `Request failed with status ${res.status}`,\n param: detail.param,\n requestId: detail.request_id,\n declineCode: detail.decline_code,\n retryable: type === \"api_error\" || type === \"rate_limit_error\",\n });\n};\n\nexport class ArcPayClient {\n private readonly secretKey: string;\n private readonly apiBase: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(options: ArcPayClientOptions) {\n const secretKey: unknown = options.secretKey;\n validateSecretKey(secretKey);\n if (!options.fetch && typeof fetch === \"undefined\") {\n throw new ArcPayError({\n type: \"api_error\",\n code: \"fetch_unavailable\",\n message: \"A fetch implementation is required in this runtime\",\n retryable: false,\n });\n }\n this.secretKey = secretKey;\n this.apiBase = normalizeBase(options.apiBase ?? DEFAULT_API_BASE);\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n async listPayments(query: ListPaymentsQuery = {}, opts: RequestOptions = {}): Promise<PaymentList> {\n return this.request<PaymentList>(\"GET\", appendQuery(\"/payments\", query), undefined, opts);\n }\n\n async createPayment(body: CreatePaymentRequest, opts: IdempotencyOptions): Promise<Payment> {\n return this.request<Payment>(\"POST\", \"/payments\", body, opts);\n }\n\n async getPayment(paymentId: string, opts: RequestOptions = {}): Promise<Payment> {\n return this.request<Payment>(\"GET\", `/payments/${encodeURIComponent(paymentId)}`, undefined, opts);\n }\n\n async capturePayment(\n paymentId: string,\n body: CaptureRequest,\n opts: IdempotencyOptions,\n ): Promise<Payment> {\n return this.request<Payment>(\"POST\", `/payments/${encodeURIComponent(paymentId)}/capture`, body, opts);\n }\n\n async voidPayment(\n paymentId: string,\n body: VoidRequest,\n opts: IdempotencyOptions,\n ): Promise<Payment> {\n return this.request<Payment>(\"POST\", `/payments/${encodeURIComponent(paymentId)}/void`, body, opts);\n }\n\n async createRefund(\n paymentId: string,\n body: CreateRefundRequest,\n opts: IdempotencyOptions,\n ): Promise<Refund> {\n return this.request<Refund>(\"POST\", `/payments/${encodeURIComponent(paymentId)}/refunds`, body, opts);\n }\n\n async executePayment(\n paymentId: string,\n body: ExecutePaymentRequest,\n opts: IdempotencyOptions,\n ): Promise<ExecutePaymentResponse> {\n return this.request<ExecutePaymentResponse>(\n \"POST\",\n `/payments/${encodeURIComponent(paymentId)}/execute`,\n body,\n opts,\n );\n }\n\n async completeThreeDSMethod(\n paymentId: string,\n body: CompleteThreeDSMethodRequest,\n opts: RequestOptions = {},\n ): Promise<ExecutePaymentResponse> {\n return this.request<ExecutePaymentResponse>(\n \"POST\",\n `/payments/${encodeURIComponent(paymentId)}/complete-3ds-method`,\n body,\n opts,\n );\n }\n\n async listAvailablePaymentMethods(\n query: ListAvailablePaymentMethodsQuery,\n opts: RequestOptions = {},\n ): Promise<AvailablePaymentMethod[]> {\n return this.request<AvailablePaymentMethod[]>(\n \"GET\",\n appendQuery(\"/payment-methods/available\", query),\n undefined,\n opts,\n );\n }\n\n async createLink(body: CreateLinkRequest, opts: IdempotencyOptions): Promise<Link> {\n return this.request<Link>(\"POST\", \"/links\", body, opts);\n }\n\n async createCheckoutSession(\n body: CreateCheckoutSessionRequest,\n opts: IdempotencyOptions,\n ): Promise<CheckoutSession> {\n return this.request<CheckoutSession>(\"POST\", \"/checkout/sessions\", body, opts);\n }\n\n private async request<T>(\n method: \"GET\" | \"POST\",\n path: string,\n body: unknown,\n opts: RequestOptions | IdempotencyOptions,\n ): Promise<T> {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.secretKey}`,\n \"X-Arc-Pay-API-Version\": API_VERSION,\n \"Content-Type\": \"application/json\",\n };\n if (\"idempotencyKey\" in opts) {\n headers[\"Idempotency-Key\"] = requireIdempotencyKey(opts);\n }\n\n let res: Response;\n try {\n res = await this.fetchImpl(`${this.apiBase}${path}`, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: opts.signal,\n });\n } catch (err) {\n throw new ArcPayError({\n type: \"network_error\",\n message: err instanceof Error ? err.message : \"Network request failed\",\n retryable: true,\n });\n }\n if (!res.ok) throw await parseErrorResponse(res);\n return (await res.json()) as T;\n }\n}\n\nexport const createArcPayClient = (options: ArcPayClientOptions): ArcPayClient =>\n new ArcPayClient(options);\n"]}
1
+ {"version":3,"sources":["../../src/core/errors.ts","../../src/server/client.ts"],"names":[],"mappings":";AAqBO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EASrC,YAAY,IAAA,EAAuB;AACjC,IAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACtB,IAAA,I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OAAA,KACjC,IAAI,aAAa,OAAO","file":"index.mjs","sourcesContent":["export type ArcPayErrorType =\n | \"validation_error\"\n | \"authentication_error\"\n | \"authorization_error\"\n | \"state_error\"\n | \"rate_limit_error\"\n | \"api_error\"\n | \"network_error\"\n | \"challenge_aborted\";\n\nexport interface ArcPayErrorInit {\n type: ArcPayErrorType;\n message: string;\n code?: string;\n param?: string;\n paymentId?: string;\n declineCode?: string;\n retryable: boolean;\n requestId?: string;\n}\n\nexport class ArcPayError extends Error {\n readonly type: ArcPayErrorType;\n readonly code?: string;\n readonly param?: string;\n readonly paymentId?: string;\n readonly declineCode?: string;\n readonly retryable: boolean;\n readonly requestId?: string;\n\n constructor(init: ArcPayErrorInit) {\n super(init.message);\n this.name = \"ArcPayError\";\n this.type = init.type;\n this.code = init.code;\n this.param = init.param;\n this.paymentId = init.paymentId;\n this.declineCode = init.declineCode;\n this.retryable = init.retryable;\n this.requestId = init.requestId;\n }\n}\n\nexport const isValidationError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"validation_error\";\nexport const isAuthenticationError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"authentication_error\";\nexport const isAuthorizationError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"authorization_error\";\nexport const isStateError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"state_error\";\nexport const isRateLimitError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"rate_limit_error\";\nexport const isApiError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"api_error\";\nexport const isNetworkError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"network_error\";\nexport const isChallengeAborted = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"challenge_aborted\";\n","import { ArcPayError, type ArcPayErrorType } from \"../core/errors\";\nimport type {\n AvailablePaymentMethod,\n CaptureRequest,\n CheckoutSession,\n CompleteThreeDSMethodRequest,\n CreateCheckoutSessionRequest,\n CreateLinkRequest,\n CreatePaymentRequest,\n CreateRefundRequest,\n ExecutePaymentRequest,\n ExecutePaymentResponse,\n Link,\n ListAvailablePaymentMethodsQuery,\n ListPaymentsQuery,\n Payment,\n PaymentList,\n Refund,\n VoidRequest,\n} from \"./types\";\n\nexport type {\n AvailablePaymentMethod,\n CaptureMode,\n CaptureRequest,\n CheckoutSession,\n CompleteThreeDSMethodRequest,\n CreateCheckoutSessionRequest,\n CreateLinkRequest,\n CreatePaymentRequest,\n CreateRefundRequest,\n Currency,\n ExecutePaymentRequest,\n ExecutePaymentResponse,\n Link,\n ListAvailablePaymentMethodsQuery,\n ListPaymentsQuery,\n Payment,\n PaymentFlowMode,\n PaymentList,\n PaymentMethod,\n PaymentStatus,\n Refund,\n VoidRequest,\n} from \"./types\";\n\nexport interface ArcPayClientOptions {\n secretKey: string;\n apiBase?: string;\n fetch?: typeof fetch;\n}\n\nexport interface IdempotencyOptions {\n idempotencyKey: string;\n signal?: AbortSignal;\n}\n\ntype RequestOptionsInput = RequestOptions | IdempotencyOptions | null | undefined;\n\nexport interface RequestOptions {\n signal?: AbortSignal;\n}\n\nconst DEFAULT_API_BASE = \"https://api.arcpay.space/v1\";\nconst API_VERSION = \"2026-05-06\";\n\nfunction validateSecretKey(key: unknown): asserts key is string {\n if (typeof key !== \"string\" || key.length === 0) {\n throw new ArcPayError({\n type: \"authentication_error\",\n code: \"invalid_secret_key\",\n message: \"Secret key must be a non-empty string\",\n retryable: false,\n });\n }\n if (!key.startsWith(\"sk_test_\") && !key.startsWith(\"sk_live_\")) {\n throw new ArcPayError({\n type: \"authentication_error\",\n code: \"invalid_secret_key\",\n message:\n \"Secret key must start with sk_test_ or sk_live_. Publishable keys cannot call server APIs.\",\n retryable: false,\n });\n }\n}\n\nconst normalizeBase = (base: string): string => base.replace(/\\/+$/, \"\");\n\ninterface RequestOptionsWithOptionalIdempotency extends RequestOptions {\n idempotencyKey?: string;\n}\n\nconst normalizeRequestOptions = (\n opts: RequestOptionsInput,\n): RequestOptionsWithOptionalIdempotency => opts ?? {};\n\nconst requireIdempotencyKey = (opts: RequestOptionsWithOptionalIdempotency): string => {\n if (!opts.idempotencyKey) {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"missing_idempotency_key\",\n message: \"idempotencyKey is required for this operation\",\n retryable: false,\n });\n }\n return opts.idempotencyKey;\n};\n\nconst appendQuery = (path: string, query?: object): string => {\n if (!query) return path;\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null || value === \"\") continue;\n params.set(key, String(value));\n }\n const encoded = params.toString();\n return encoded ? `${path}?${encoded}` : path;\n};\n\ninterface APIErrorBody {\n error?: {\n type?: string;\n code?: string;\n message?: string;\n param?: string;\n request_id?: string;\n decline_code?: string;\n };\n}\n\nconst isPublicErrorType = (value: unknown): value is ArcPayErrorType =>\n value === \"validation_error\" ||\n value === \"authentication_error\" ||\n value === \"authorization_error\" ||\n value === \"state_error\" ||\n value === \"rate_limit_error\" ||\n value === \"api_error\";\n\nconst parseErrorResponse = async (res: Response): Promise<ArcPayError> => {\n let body: APIErrorBody = {};\n try {\n body = (await res.json()) as APIErrorBody;\n } catch {\n /* keep default error below */\n }\n const detail = body.error ?? {};\n const type = isPublicErrorType(detail.type)\n ? detail.type\n : res.status >= 500\n ? \"api_error\"\n : \"validation_error\";\n return new ArcPayError({\n type,\n code: detail.code,\n message: detail.message ?? `Request failed with status ${res.status}`,\n param: detail.param,\n requestId: detail.request_id,\n declineCode: detail.decline_code,\n retryable: type === \"api_error\" || type === \"rate_limit_error\",\n });\n};\n\nexport class ArcPayClient {\n private readonly secretKey: string;\n private readonly apiBase: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(options: ArcPayClientOptions) {\n const secretKey: unknown = options.secretKey;\n validateSecretKey(secretKey);\n if (!options.fetch && typeof fetch === \"undefined\") {\n throw new ArcPayError({\n type: \"api_error\",\n code: \"fetch_unavailable\",\n message: \"A fetch implementation is required in this runtime\",\n retryable: false,\n });\n }\n this.secretKey = secretKey;\n this.apiBase = normalizeBase(options.apiBase ?? DEFAULT_API_BASE);\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n async listPayments(\n query: ListPaymentsQuery = {},\n opts: RequestOptions = {},\n ): Promise<PaymentList> {\n return this.request<PaymentList>(\"GET\", appendQuery(\"/payments\", query), undefined, opts);\n }\n\n async createPayment(body: CreatePaymentRequest, opts: IdempotencyOptions): Promise<Payment>;\n async createPayment(body: CreatePaymentRequest, opts: RequestOptionsInput): Promise<Payment> {\n return this.request<Payment>(\"POST\", \"/payments\", body, opts, true);\n }\n\n async getPayment(paymentId: string, opts: RequestOptions = {}): Promise<Payment> {\n return this.request<Payment>(\n \"GET\",\n `/payments/${encodeURIComponent(paymentId)}`,\n undefined,\n opts,\n );\n }\n\n async capturePayment(\n paymentId: string,\n body: CaptureRequest,\n opts: IdempotencyOptions,\n ): Promise<Payment>;\n async capturePayment(\n paymentId: string,\n body: CaptureRequest,\n opts: RequestOptionsInput,\n ): Promise<Payment> {\n return this.request<Payment>(\n \"POST\",\n `/payments/${encodeURIComponent(paymentId)}/capture`,\n body,\n opts,\n true,\n );\n }\n\n async voidPayment(\n paymentId: string,\n body: VoidRequest,\n opts: IdempotencyOptions,\n ): Promise<Payment>;\n async voidPayment(\n paymentId: string,\n body: VoidRequest,\n opts: RequestOptionsInput,\n ): Promise<Payment> {\n return this.request<Payment>(\n \"POST\",\n `/payments/${encodeURIComponent(paymentId)}/void`,\n body,\n opts,\n true,\n );\n }\n\n async createRefund(\n paymentId: string,\n body: CreateRefundRequest,\n opts: IdempotencyOptions,\n ): Promise<Refund>;\n async createRefund(\n paymentId: string,\n body: CreateRefundRequest,\n opts: RequestOptionsInput,\n ): Promise<Refund> {\n return this.request<Refund>(\n \"POST\",\n `/payments/${encodeURIComponent(paymentId)}/refunds`,\n body,\n opts,\n true,\n );\n }\n\n async executePayment(\n paymentId: string,\n body: ExecutePaymentRequest,\n opts: IdempotencyOptions,\n ): Promise<ExecutePaymentResponse>;\n async executePayment(\n paymentId: string,\n body: ExecutePaymentRequest,\n opts: RequestOptionsInput,\n ): Promise<ExecutePaymentResponse> {\n return this.request<ExecutePaymentResponse>(\n \"POST\",\n `/payments/${encodeURIComponent(paymentId)}/execute`,\n body,\n opts,\n true,\n );\n }\n\n async completeThreeDSMethod(\n paymentId: string,\n body: CompleteThreeDSMethodRequest,\n opts: RequestOptions = {},\n ): Promise<ExecutePaymentResponse> {\n return this.request<ExecutePaymentResponse>(\n \"POST\",\n `/payments/${encodeURIComponent(paymentId)}/complete-3ds-method`,\n body,\n opts,\n );\n }\n\n async listAvailablePaymentMethods(\n query: ListAvailablePaymentMethodsQuery,\n opts: RequestOptions = {},\n ): Promise<AvailablePaymentMethod[]> {\n return this.request<AvailablePaymentMethod[]>(\n \"GET\",\n appendQuery(\"/payment-methods/available\", query),\n undefined,\n opts,\n );\n }\n\n async createLink(body: CreateLinkRequest, opts: IdempotencyOptions): Promise<Link>;\n async createLink(body: CreateLinkRequest, opts: RequestOptionsInput): Promise<Link> {\n return this.request<Link>(\"POST\", \"/links\", body, opts, true);\n }\n\n async createCheckoutSession(\n body: CreateCheckoutSessionRequest,\n opts: IdempotencyOptions,\n ): Promise<CheckoutSession>;\n async createCheckoutSession(\n body: CreateCheckoutSessionRequest,\n opts: RequestOptionsInput,\n ): Promise<CheckoutSession> {\n return this.request<CheckoutSession>(\"POST\", \"/checkout/sessions\", body, opts, true);\n }\n\n private async request<T>(\n method: \"GET\" | \"POST\",\n path: string,\n body: unknown,\n opts: RequestOptionsInput = undefined,\n requireIdempotency = false,\n ): Promise<T> {\n const requestOpts = normalizeRequestOptions(opts);\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.secretKey}`,\n \"X-Arc-Pay-API-Version\": API_VERSION,\n \"Content-Type\": \"application/json\",\n };\n if (requireIdempotency) {\n headers[\"Idempotency-Key\"] = requireIdempotencyKey(requestOpts);\n } else if (requestOpts.idempotencyKey !== undefined) {\n headers[\"Idempotency-Key\"] = requireIdempotencyKey(requestOpts);\n }\n\n let res: Response;\n try {\n res = await this.fetchImpl(`${this.apiBase}${path}`, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: requestOpts.signal,\n });\n } catch (err) {\n throw new ArcPayError({\n type: \"network_error\",\n message: err instanceof Error ? err.message : \"Network request failed\",\n retryable: true,\n });\n }\n if (!res.ok) throw await parseErrorResponse(res);\n return (await res.json()) as T;\n }\n}\n\nexport const createArcPayClient = (options: ArcPayClientOptions): ArcPayClient =>\n new ArcPayClient(options);\n"]}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@thavguard/arc-pay",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Arc Pay browser SDK — publishable-key tokenization, Hosted Fields, and React bindings",
5
5
  "private": false,
6
- "license": "UNLICENSED",
6
+ "license": "MIT",
7
7
  "type": "module",
8
8
  "main": "./dist/index.cjs",
9
9
  "module": "./dist/index.mjs",
@@ -32,7 +32,8 @@
32
32
  },
33
33
  "files": [
34
34
  "dist",
35
- "README.md"
35
+ "README.md",
36
+ "LICENSE"
36
37
  ],
37
38
  "publishConfig": {
38
39
  "registry": "https://registry.npmjs.org/"
@@ -1,3 +0,0 @@
1
- var ArcPay=(function(exports){'use strict';var o=class extends Error{constructor(t){super(t.message),this.name="ArcPayError",this.type=t.type,this.code=t.code,this.param=t.param,this.paymentId=t.paymentId,this.declineCode=t.declineCode,this.retryable=t.retryable,this.requestId=t.requestId;}},A=e=>e instanceof o&&e.type==="validation_error",I=e=>e instanceof o&&e.type==="authentication_error",S=e=>e instanceof o&&e.type==="authorization_error",z=e=>e instanceof o&&e.type==="state_error",C=e=>e instanceof o&&e.type==="rate_limit_error",R=e=>e instanceof o&&e.type==="api_error",B=e=>e instanceof o&&e.type==="network_error",M=e=>e instanceof o&&e.type==="challenge_aborted";var L=()=>{var t;if(typeof document=="undefined")return null;let e=document.head.querySelector('meta[http-equiv="Content-Security-Policy"]');return (t=e==null?void 0:e.getAttribute("content"))!=null?t:null},F=(e,t)=>{let n=e.toLowerCase().indexOf(`${t} `);if(n===-1)return null;let s=e.slice(n+t.length+1),i=s.indexOf(";");return (i===-1?s:s.slice(0,i)).trim()},O=(e,t)=>{let r=e.split(/\s+/).filter(Boolean);return r.includes("*")?true:r.some(n=>{if(n===t)return true;if(n.startsWith("https://*")){let s=n.slice(9);return t.endsWith(s)}return false})},x=e=>{let t=L();if(!t)return;let r=F(t,"connect-src");if(r&&!O(r,e))throw new o({type:"validation_error",code:"csp_blocks_api",message:`CSP connect-src directive does not allow ${e}. Add it to your Content-Security-Policy header.`,retryable:false})};var g=e=>e.startsWith("pk_test_")?"sandbox":"live",w=e=>{if(typeof e!="string"||e.length===0)throw new o({type:"validation_error",code:"invalid_publishable_key",message:"Publishable key must be a non-empty string",retryable:false});if(!e.startsWith("pk_test_")&&!e.startsWith("pk_live_"))throw new o({type:"validation_error",code:"invalid_publishable_key",message:"Publishable key must start with pk_test_ or pk_live_. Secret keys (sk_*) cannot be used in browser.",retryable:false})};var _="data-arcpay-sandbox-banner",T=()=>{if(typeof document=="undefined"||document.querySelector(`[${_}]`))return;let e=document.createElement("div");e.setAttribute(_,""),e.style.cssText="position:fixed;top:0;left:0;right:0;z-index:2147483647;background:#ffd166;color:#222;font:13px/1.4 system-ui,sans-serif;padding:6px 12px;display:flex;align-items:center;justify-content:center;box-shadow:0 1px 3px rgba(0,0,0,0.1);";let t=document.createElement("span");t.textContent="ARC PAY TEST MODE \u2014 payments are simulated",e.appendChild(t);let r=document.createElement("button");r.type="button",r.setAttribute("data-arcpay-banner-dismiss",""),r.textContent="\xD7",r.setAttribute("aria-label","Dismiss test mode banner"),r.style.cssText="margin-left:12px;background:transparent;border:0;font-size:18px;cursor:pointer;color:inherit;",r.addEventListener("click",()=>e.remove()),e.appendChild(r),document.body.appendChild(e);};var W="arcpay:",H=e=>typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&e.type.startsWith(W),f=(e,t,r)=>{if(r==="*")throw new o({type:"validation_error",code:"wildcard_origin_forbidden",message:"postToIframe: targetOrigin cannot be '*'",retryable:false});if(!e.contentWindow)throw new o({type:"validation_error",code:"iframe_not_loaded",message:"postToIframe: iframe.contentWindow is null (iframe not mounted)",retryable:false});e.contentWindow.postMessage(t,r);},K=(e,t)=>{if(t==="*")throw new Error("postToParent: targetOrigin cannot be '*'");window.parent.postMessage(e,t);},p=(e,t)=>e.origin!==t||!H(e.data)?null:e.data;var $=new Set(["position","transform","pointer-events","z-index","top","left","right","bottom","inset"]),h=e=>{let t={};for(let[r,n]of Object.entries(e)){let s=r.toLowerCase();$.has(s)||(t[r]=n);}return t},u=e=>{let t={base:h(e.base)};return e.invalid!==void 0&&(t.invalid=h(e.invalid)),e.focus!==void 0&&(t.focus=h(e.focus)),t};var d=class{constructor(t,r,n){this.field=t;this.options=r;this.context=n;this.iframe=null;this.listeners=new Set;this.status="pending";this.messageHandler=null;}mount(t){if(this.iframe)throw new o({type:"validation_error",code:"already_mounted",message:`Element ${this.field} is already mounted`,retryable:false});let r=typeof t=="string"?document.querySelector(t):t;if(!(r instanceof HTMLElement))throw new o({type:"validation_error",code:"mount_target_not_found",message:`mount target not found: ${String(t)}`,retryable:false});let n=document.createElement("iframe");n.src=`${this.context.iframeBase}/iframe/${this.field}`,n.style.cssText="border:0;width:100%;height:100%;display:block;",n.setAttribute("allow","payment"),n.setAttribute("data-arcpay-element",this.field),r.appendChild(n),this.iframe=n;let s=new URL(this.context.iframeBase).origin;this.messageHandler=i=>{var c;if(i.source!==((c=this.iframe)==null?void 0:c.contentWindow))return;let l=p(i,s);l&&this.handleMessage(l);},window.addEventListener("message",this.messageHandler),n.addEventListener("load",()=>{if(!this.iframe)return;let i={type:"arcpay:hello",origin:window.location.origin,publishableKey:this.context.publishableKey,channelId:this.context.channelId};f(this.iframe,i,s);},{once:true});}handleMessage(t){t.type==="arcpay:ready"?(this.status="ready",this.options.style&&this.send({type:"arcpay:style",payload:u(this.options.style)}),this.emit({type:"ready"})):t.type==="arcpay:rejected"?(this.status="error",this.emit({type:"error",reason:t.reason})):t.type==="arcpay:change"&&t.field===this.field&&this.emit({type:"change",isValid:t.isValid,brand:t.brand,lastFour:t.lastFour});}update(t){t.style&&this.send({type:"arcpay:style",payload:u(t.style)});}destroy(){this.iframe&&(this.iframe.remove(),this.iframe=null),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.listeners.clear(),this.status="pending";}on(t,r){return this.listeners.add(r),()=>this.listeners.delete(r)}focus(){this.send({type:"arcpay:focus"});}clear(){this.send({type:"arcpay:clear"});}isReady(){return this.status==="ready"}getIframeContentWindow(){var t,r;return (r=(t=this.iframe)==null?void 0:t.contentWindow)!=null?r:null}send(t){if(!this.iframe)throw new o({type:"validation_error",code:"not_mounted",message:`Element ${this.field} is not mounted`,retryable:false});f(this.iframe,t,new URL(this.context.iframeBase).origin);}emit(t){for(let r of this.listeners)r(t);}};var D="https://sdk.arcpay.space",U=()=>{var e;if(!((e=globalThis.crypto)!=null&&e.randomUUID))throw new o({type:"validation_error",code:"crypto_unavailable",message:"crypto.randomUUID is required for Hosted Fields",retryable:false});return globalThis.crypto.randomUUID()},y=class{constructor(t){this.elementMap=new Map;this.tokenizeInFlight=false;var r;this.publishableKey=t.publishableKey,this.iframeBase=(r=t.iframeBase)!=null?r:D,this.channelId=U();}create(t,r={}){if(this.elementMap.has(t))throw new o({type:"validation_error",code:"duplicate_element",message:`Element for ${t} already created`,retryable:false});let n={iframeBase:this.iframeBase,publishableKey:this.publishableKey,channelId:this.channelId},s=new d(t,r,n);return this.elementMap.set(t,s),s}async tokenize(t,r){if(this.tokenizeInFlight)throw new o({type:"validation_error",code:"tokenize_in_progress",message:"A tokenize() call is already in progress for this Elements instance",retryable:false});let n=this.elementMap.get("cardNumber"),s=this.elementMap.get("cardExpiry"),i=this.elementMap.get("cardCvv");if(!n||!s||!i)throw new o({type:"validation_error",code:"incomplete_elements",message:"All three elements (cardNumber, cardExpiry, cardCvv) must be created and mounted before tokenize()",retryable:false});if(!n.isReady()||!s.isReady()||!i.isReady())throw new o({type:"validation_error",code:"elements_not_ready",message:"Wait for all elements to fire 'ready' event before tokenize()",retryable:false});this.tokenizeInFlight=true;try{return await this.doTokenize(n,t,r)}finally{this.tokenizeInFlight=false;}}doTokenize(t,r,n){let s=new URL(this.iframeBase).origin,i=t.getIframeContentWindow();return new Promise((l,c)=>{let E=window.setTimeout(()=>{window.removeEventListener("message",m),c(new o({type:"network_error",code:"tokenize_timeout",message:"tokenize() timed out after 30 seconds",retryable:true,paymentId:r}));},3e4),m=v=>{if(i!==null&&v.source!==i)return;let a=p(v,s);if(a){if(a.type==="arcpay:tokenize-result")clearTimeout(E),window.removeEventListener("message",m),l({cardTokenId:a.cardTokenId,cardMask:a.cardMask,cardScheme:a.cardScheme,cardBin:a.cardBin,expiresAt:a.expiresAt});else if(a.type==="arcpay:tokenize-error"){clearTimeout(E),window.removeEventListener("message",m);let P=a.errorType==="validation_error"||a.errorType==="api_error"?a.errorType:"api_error";c(new o({type:P,code:a.code,message:a.message,retryable:false,paymentId:r}));}}};window.addEventListener("message",m),t.send({type:"arcpay:tokenize",paymentId:r,idempotencyKey:n});})}destroy(){for(let t of this.elementMap.values())t.destroy();this.elementMap.clear();}};var q=w,k="https://api.arcpay.space",b=new Map,N=(e,t)=>{var n;let r=(n=t.apiBase)!=null?n:k;return x(r),g(e)==="sandbox"&&T(),{publishableKey:e,apiBase:r,environment:g(e),elements:s=>new y({publishableKey:e,iframeBase:s==null?void 0:s.iframeBase})}};function V(e,t={}){var i;try{q(e);}catch(l){return Promise.reject(l)}let r=`${e}|${(i=t.apiBase)!=null?i:k}`,n=b.get(r);if(n)return n;let s=Promise.resolve(N(e,t));return b.set(r,s),s}var j=()=>{b.clear();},Y={load:V,__resetForTests:j};var X=e=>{if(!/^\d+$/.test(e)||/^0+$/.test(e))return false;let t=0,r=false;for(let n=e.length-1;n>=0;n--){let s=e.charCodeAt(n)-48;r&&(s*=2,s>9&&(s-=9)),t+=s,r=!r;}return t%10===0};var Ee="0.1.0";
2
- exports.ArcPay=Y;exports.ArcPayError=o;exports.Element=d;exports.Elements=y;exports.SDK_VERSION=Ee;exports.isApiError=R;exports.isAuthenticationError=I;exports.isAuthorizationError=S;exports.isChallengeAborted=M;exports.isNetworkError=B;exports.isRateLimitError=C;exports.isStateError=z;exports.isValidationError=A;exports.luhnCheck=X;exports.parseIncoming=p;exports.postToIframe=f;exports.postToParent=K;exports.sanitizeStyle=u;return exports;})({});//# sourceMappingURL=arcpay.global.js.map
3
- //# sourceMappingURL=arcpay.global.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/core/errors.ts","../../src/core/csp.ts","../../src/core/env.ts","../../src/core/sandbox-banner.ts","../../src/elements/postmessage.ts","../../src/elements/style.ts","../../src/elements/element.ts","../../src/elements/elements.ts","../../src/core/arcpay.ts","../../src/tokenize/luhn.ts","../../src/index.ts"],"names":["ArcPayError","init","isValidationError","isAuthenticationError","isAuthorizationError","isStateError","isRateLimitError","isApiError","isNetworkError","isChallengeAborted","readCspContent","_a","meta","extractDirective","csp","name","idx","rest","end","directiveAllowsHost","directive","host","tokens","t","suffix","verifyCspAllowsApiBase","apiBase","detectEnvironment","publishableKey","validatePublishableKey","key","BANNER_ATTR","showSandboxBanner","bar","text","dismiss","ARCPAY_TYPE_PREFIX","isArcpayMessage","data","postToIframe","iframe","message","targetOrigin","postToParent","parseIncoming","event","expectedOrigin","FORBIDDEN_PROPERTIES","sanitizeBlock","block","out","value","normalizedKey","sanitizeStyle","style","result","Element","field","options","context","target","container","hello","_event","callback","_b","listener","DEFAULT_IFRAME_BASE","createChannelId","Elements","opts","ctx","element","paymentId","idempotencyKey","cardNumber","cardExpiry","cardCvv","iframeOrigin","cardIframeWindow","resolve","reject","timer","onMessage","errType","el","DEFAULT_API_BASE","cache","buildInstance","elemOpts","load","err","existing","promise","res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,GADI,CAAC,QAAQ,IAAA,CAAKA,CAAG,GACjB,MAAA,CAAO,IAAA,CAAKA,CAAG,CAAA,CAAG,OAAO,MAAA,CAC7B,IAAIC,CAAAA,CAAM,CAAA,CACNC,EAAY,KAAA,CAChB,IAAA,IAASC,EAAIH,CAAAA,CAAI,MAAA,CAAS,EAAGG,CAAAA,EAAK,CAAA,CAAGA,CAAAA,EAAAA,CAAK,CACxC,IAAIC,CAAAA,CAAIJ,EAAI,UAAA,CAAWG,CAAC,EAAI,EAAA,CACxBD,CAAAA,GACFE,GAAK,CAAA,CACDA,CAAAA,CAAI,CAAA,GAAGA,CAAAA,EAAK,CAAA,CAAA,CAAA,CAElBH,CAAAA,EAAOG,EACPF,CAAAA,CAAY,CAACA,EACf,CACA,OAAOD,EAAM,EAAA,GAAO,CACtB,ECEO,IAAMI,EAAAA,CAAc","file":"arcpay.global.js","sourcesContent":["export type ArcPayErrorType =\n | \"validation_error\"\n | \"authentication_error\"\n | \"authorization_error\"\n | \"state_error\"\n | \"rate_limit_error\"\n | \"api_error\"\n | \"network_error\"\n | \"challenge_aborted\";\n\nexport interface ArcPayErrorInit {\n type: ArcPayErrorType;\n message: string;\n code?: string;\n param?: string;\n paymentId?: string;\n declineCode?: string;\n retryable: boolean;\n requestId?: string;\n}\n\nexport class ArcPayError extends Error {\n readonly type: ArcPayErrorType;\n readonly code?: string;\n readonly param?: string;\n readonly paymentId?: string;\n readonly declineCode?: string;\n readonly retryable: boolean;\n readonly requestId?: string;\n\n constructor(init: ArcPayErrorInit) {\n super(init.message);\n this.name = \"ArcPayError\";\n this.type = init.type;\n this.code = init.code;\n this.param = init.param;\n this.paymentId = init.paymentId;\n this.declineCode = init.declineCode;\n this.retryable = init.retryable;\n this.requestId = init.requestId;\n }\n}\n\nexport const isValidationError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"validation_error\";\nexport const isAuthenticationError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"authentication_error\";\nexport const isAuthorizationError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"authorization_error\";\nexport const isStateError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"state_error\";\nexport const isRateLimitError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"rate_limit_error\";\nexport const isApiError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"api_error\";\nexport const isNetworkError = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"network_error\";\nexport const isChallengeAborted = (e: unknown): e is ArcPayError =>\n e instanceof ArcPayError && e.type === \"challenge_aborted\";\n","import { ArcPayError } from \"./errors\";\n\nconst readCspContent = (): string | null => {\n if (typeof document === \"undefined\") return null;\n const meta = document.head.querySelector<HTMLMetaElement>(\n 'meta[http-equiv=\"Content-Security-Policy\"]',\n );\n return meta?.getAttribute(\"content\") ?? null;\n};\n\nconst extractDirective = (csp: string, name: string): string | null => {\n const lower = csp.toLowerCase();\n const idx = lower.indexOf(`${name} `);\n if (idx === -1) return null;\n const rest = csp.slice(idx + name.length + 1);\n const end = rest.indexOf(\";\");\n return (end === -1 ? rest : rest.slice(0, end)).trim();\n};\n\nconst directiveAllowsHost = (directive: string, host: string): boolean => {\n const tokens = directive.split(/\\s+/).filter(Boolean);\n if (tokens.includes(\"*\")) return true;\n return tokens.some((t) => {\n if (t === host) return true;\n if (t.startsWith(\"https://*\")) {\n const suffix = t.slice(\"https://*\".length);\n return host.endsWith(suffix);\n }\n return false;\n });\n};\n\nexport const verifyCspAllowsApiBase = (apiBase: string): void => {\n const csp = readCspContent();\n if (!csp) return;\n const directive = extractDirective(csp, \"connect-src\");\n if (!directive) return;\n if (directiveAllowsHost(directive, apiBase)) return;\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"csp_blocks_api\",\n message: `CSP connect-src directive does not allow ${apiBase}. Add it to your Content-Security-Policy header.`,\n retryable: false,\n });\n};\n","import { ArcPayError } from \"./errors\";\n\nexport type Environment = \"sandbox\" | \"live\";\n\nexport const detectEnvironment = (publishableKey: string): Environment =>\n publishableKey.startsWith(\"pk_test_\") ? \"sandbox\" : \"live\";\n\nexport const validatePublishableKey = (key: unknown): asserts key is string => {\n if (typeof key !== \"string\" || key.length === 0) {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"invalid_publishable_key\",\n message: \"Publishable key must be a non-empty string\",\n retryable: false,\n });\n }\n if (!key.startsWith(\"pk_test_\") && !key.startsWith(\"pk_live_\")) {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"invalid_publishable_key\",\n message:\n \"Publishable key must start with pk_test_ or pk_live_. Secret keys (sk_*) cannot be used in browser.\",\n retryable: false,\n });\n }\n};\n","const BANNER_ATTR = \"data-arcpay-sandbox-banner\";\n\nexport const showSandboxBanner = (): void => {\n if (typeof document === \"undefined\") return;\n if (document.querySelector(`[${BANNER_ATTR}]`)) return;\n\n const bar = document.createElement(\"div\");\n bar.setAttribute(BANNER_ATTR, \"\");\n bar.style.cssText =\n \"position:fixed;top:0;left:0;right:0;z-index:2147483647;background:#ffd166;color:#222;font:13px/1.4 system-ui,sans-serif;padding:6px 12px;display:flex;align-items:center;justify-content:center;box-shadow:0 1px 3px rgba(0,0,0,0.1);\";\n\n const text = document.createElement(\"span\");\n text.textContent = \"ARC PAY TEST MODE — payments are simulated\";\n bar.appendChild(text);\n\n const dismiss = document.createElement(\"button\");\n dismiss.type = \"button\";\n dismiss.setAttribute(\"data-arcpay-banner-dismiss\", \"\");\n dismiss.textContent = \"×\";\n dismiss.setAttribute(\"aria-label\", \"Dismiss test mode banner\");\n dismiss.style.cssText =\n \"margin-left:12px;background:transparent;border:0;font-size:18px;cursor:pointer;color:inherit;\";\n dismiss.addEventListener(\"click\", () => bar.remove());\n bar.appendChild(dismiss);\n\n document.body.appendChild(bar);\n};\n","import { ArcPayError } from \"../core/errors\";\n\nexport type FieldType = \"cardNumber\" | \"cardExpiry\" | \"cardCvv\";\n\n// Parent → iframe\nexport type ParentToIframe =\n | { type: \"arcpay:hello\"; origin: string; publishableKey: string; channelId: string }\n | { type: \"arcpay:style\"; payload: StyleSubset }\n | { type: \"arcpay:focus\" }\n | { type: \"arcpay:clear\" }\n | { type: \"arcpay:tokenize\"; paymentId: string; idempotencyKey: string };\n\n// iframe → parent\nexport type IframeToParent =\n | { type: \"arcpay:ready\" }\n | { type: \"arcpay:rejected\"; reason: string }\n | {\n type: \"arcpay:change\";\n field: FieldType;\n isValid: boolean;\n brand?: string;\n lastFour?: string;\n }\n | {\n type: \"arcpay:tokenize-result\";\n cardTokenId: string;\n cardMask: string;\n cardScheme: string;\n cardBin: string;\n expiresAt: string;\n }\n | { type: \"arcpay:tokenize-error\"; errorType: string; code?: string; message: string };\n\nexport interface StyleSubset {\n base: Record<string, string>;\n invalid?: Record<string, string>;\n focus?: Record<string, string>;\n}\n\nconst ARCPAY_TYPE_PREFIX = \"arcpay:\";\n\nconst isArcpayMessage = (data: unknown): data is { type: string } =>\n typeof data === \"object\" &&\n data !== null &&\n \"type\" in data &&\n typeof (data as { type: unknown }).type === \"string\" &&\n (data as { type: string }).type.startsWith(ARCPAY_TYPE_PREFIX);\n\nexport const postToIframe = (\n iframe: HTMLIFrameElement,\n message: ParentToIframe,\n targetOrigin: string,\n): void => {\n if (targetOrigin === \"*\") {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"wildcard_origin_forbidden\",\n message: \"postToIframe: targetOrigin cannot be '*'\",\n retryable: false,\n });\n }\n if (!iframe.contentWindow) {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"iframe_not_loaded\",\n message: \"postToIframe: iframe.contentWindow is null (iframe not mounted)\",\n retryable: false,\n });\n }\n iframe.contentWindow.postMessage(message, targetOrigin);\n};\n\nexport const postToParent = (message: IframeToParent, targetOrigin: string): void => {\n if (targetOrigin === \"*\") {\n throw new Error(\"postToParent: targetOrigin cannot be '*'\");\n }\n window.parent.postMessage(message, targetOrigin);\n};\n\nexport const parseIncoming = <T extends { type: string }>(\n event: MessageEvent,\n expectedOrigin: string,\n): T | null => {\n if (event.origin !== expectedOrigin) return null;\n if (!isArcpayMessage(event.data)) return null;\n return event.data as T;\n};\n","import type { StyleSubset } from \"./postmessage\";\n\n// Spec calls out position:fixed, transform, pointer-events:none as forbidden.\n// We extend to cover the full clickjacking attack surface: any positioning\n// (fixed/absolute/sticky), transform, all pointer-events values, z-index, and\n// inset properties (top/left/right/bottom/inset). The legitimate use cases\n// for these in a 1-line input field are zero, so blanket drop.\nconst FORBIDDEN_PROPERTIES = new Set([\n \"position\",\n \"transform\",\n \"pointer-events\",\n \"z-index\",\n \"top\",\n \"left\",\n \"right\",\n \"bottom\",\n \"inset\",\n]);\n\nconst sanitizeBlock = (block: Record<string, string>): Record<string, string> => {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(block)) {\n const normalizedKey = key.toLowerCase();\n if (FORBIDDEN_PROPERTIES.has(normalizedKey)) {\n // Defense against position/transform-based clickjacking. Silently drop.\n continue;\n }\n out[key] = value;\n }\n return out;\n};\n\nexport const sanitizeStyle = (style: StyleSubset): StyleSubset => {\n const result: StyleSubset = { base: sanitizeBlock(style.base) };\n if (style.invalid !== undefined) result.invalid = sanitizeBlock(style.invalid);\n if (style.focus !== undefined) result.focus = sanitizeBlock(style.focus);\n return result;\n};\n","import { ArcPayError } from \"../core/errors\";\nimport {\n type FieldType,\n type ParentToIframe,\n type IframeToParent,\n type StyleSubset,\n postToIframe,\n parseIncoming,\n} from \"./postmessage\";\nimport { sanitizeStyle } from \"./style\";\n\nexport interface ElementOptions {\n /** StyleSubset applied via arcpay:style postMessage. */\n style?: StyleSubset;\n placeholder?: string;\n}\n\nexport type ElementEvent =\n | { type: \"ready\" }\n | { type: \"change\"; isValid: boolean; brand?: string; lastFour?: string }\n | { type: \"error\"; reason: string };\n\ntype Listener = (event: ElementEvent) => void;\n\nexport interface ElementContext {\n iframeBase: string;\n publishableKey: string;\n channelId: string;\n}\n\nexport class Element {\n private iframe: HTMLIFrameElement | null = null;\n private readonly listeners = new Set<Listener>();\n private status: \"pending\" | \"ready\" | \"error\" = \"pending\";\n private messageHandler: ((e: MessageEvent) => void) | null = null;\n\n constructor(\n public readonly field: FieldType,\n private readonly options: ElementOptions,\n private readonly context: ElementContext,\n ) {}\n\n mount(target: string | HTMLElement): void {\n if (this.iframe) {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"already_mounted\",\n message: `Element ${this.field} is already mounted`,\n retryable: false,\n });\n }\n const container = typeof target === \"string\" ? document.querySelector(target) : target;\n if (!(container instanceof HTMLElement)) {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"mount_target_not_found\",\n message: `mount target not found: ${String(target)}`,\n retryable: false,\n });\n }\n\n const iframe = document.createElement(\"iframe\");\n iframe.src = `${this.context.iframeBase}/iframe/${this.field}`;\n iframe.style.cssText = \"border:0;width:100%;height:100%;display:block;\";\n iframe.setAttribute(\"allow\", \"payment\");\n iframe.setAttribute(\"data-arcpay-element\", this.field);\n container.appendChild(iframe);\n this.iframe = iframe;\n\n const expectedOrigin = new URL(this.context.iframeBase).origin;\n\n this.messageHandler = (event: MessageEvent) => {\n // C1: source guard — only accept messages from this element's own iframe.\n // Without this, any iframe at the same origin (e.g. cardExpiry, cardCvv)\n // could trigger handlers on cardNumber and vice-versa.\n if (event.source !== this.iframe?.contentWindow) return;\n // C4: use parseIncoming for origin + arcpay: prefix guard.\n const data = parseIncoming<IframeToParent>(event, expectedOrigin);\n if (!data) return;\n this.handleMessage(data);\n };\n window.addEventListener(\"message\", this.messageHandler);\n\n iframe.addEventListener(\n \"load\",\n () => {\n if (!this.iframe) return;\n const hello: ParentToIframe = {\n type: \"arcpay:hello\",\n origin: window.location.origin,\n publishableKey: this.context.publishableKey,\n channelId: this.context.channelId,\n };\n postToIframe(this.iframe, hello, expectedOrigin);\n },\n { once: true },\n );\n }\n\n private handleMessage(data: IframeToParent): void {\n if (data.type === \"arcpay:ready\") {\n this.status = \"ready\";\n // Apply initial style if provided at construction time.\n if (this.options.style) {\n this.send({ type: \"arcpay:style\", payload: sanitizeStyle(this.options.style) });\n }\n this.emit({ type: \"ready\" });\n } else if (data.type === \"arcpay:rejected\") {\n this.status = \"error\";\n this.emit({ type: \"error\", reason: data.reason });\n } else if (data.type === \"arcpay:change\" && data.field === this.field) {\n this.emit({\n type: \"change\",\n isValid: data.isValid,\n brand: data.brand,\n lastFour: data.lastFour,\n });\n }\n // arcpay:tokenize-result / arcpay:tokenize-error handled by Elements factory (Task 9).\n }\n\n update(options: { style?: StyleSubset }): void {\n if (options.style) {\n this.send({ type: \"arcpay:style\", payload: sanitizeStyle(options.style) });\n }\n }\n\n destroy(): void {\n if (this.iframe) {\n this.iframe.remove();\n this.iframe = null;\n }\n if (this.messageHandler) {\n window.removeEventListener(\"message\", this.messageHandler);\n this.messageHandler = null;\n }\n this.listeners.clear();\n this.status = \"pending\";\n }\n\n on(_event: \"ready\" | \"change\" | \"error\", callback: Listener): () => void {\n this.listeners.add(callback);\n return () => this.listeners.delete(callback);\n }\n\n focus(): void {\n this.send({ type: \"arcpay:focus\" });\n }\n\n clear(): void {\n this.send({ type: \"arcpay:clear\" });\n }\n\n isReady(): boolean {\n return this.status === \"ready\";\n }\n\n /**\n * Internal: returns the iframe's contentWindow for source-filtering in\n * Elements.doTokenize(). Returns null when the iframe is not yet mounted\n * or when jsdom has not yet populated contentWindow (test environment).\n */\n getIframeContentWindow(): Window | null {\n return this.iframe?.contentWindow ?? null;\n }\n\n /** Internal: used by Elements factory to send tokenize commands. */\n send(message: ParentToIframe): void {\n if (!this.iframe) {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"not_mounted\",\n message: `Element ${this.field} is not mounted`,\n retryable: false,\n });\n }\n postToIframe(this.iframe, message, new URL(this.context.iframeBase).origin);\n }\n\n private emit(event: ElementEvent): void {\n for (const listener of this.listeners) {\n listener(event);\n }\n }\n}\n","import { ArcPayError } from \"../core/errors\";\nimport { Element, type ElementContext, type ElementOptions } from \"./element\";\nimport type { FieldType, IframeToParent } from \"./postmessage\";\nimport { parseIncoming } from \"./postmessage\";\nimport type { TokenizeResult } from \"../tokenize/tokenize\";\n\nexport type { TokenizeResult };\n\nexport interface ElementsOptions {\n iframeBase?: string;\n}\n\nconst DEFAULT_IFRAME_BASE = \"https://sdk.arcpay.space\";\n\nconst createChannelId = (): string => {\n if (!globalThis.crypto?.randomUUID) {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"crypto_unavailable\",\n message: \"crypto.randomUUID is required for Hosted Fields\",\n retryable: false,\n });\n }\n return globalThis.crypto.randomUUID();\n};\n\nexport class Elements {\n private readonly elementMap = new Map<FieldType, Element>();\n private readonly iframeBase: string;\n private readonly publishableKey: string;\n private readonly channelId: string;\n private tokenizeInFlight = false;\n\n constructor(opts: { publishableKey: string; iframeBase?: string }) {\n this.publishableKey = opts.publishableKey;\n this.iframeBase = opts.iframeBase ?? DEFAULT_IFRAME_BASE;\n this.channelId = createChannelId();\n }\n\n create(field: FieldType, options: ElementOptions = {}): Element {\n if (this.elementMap.has(field)) {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"duplicate_element\",\n message: `Element for ${field} already created`,\n retryable: false,\n });\n }\n const ctx: ElementContext = {\n iframeBase: this.iframeBase,\n publishableKey: this.publishableKey,\n channelId: this.channelId,\n };\n const element = new Element(field, options, ctx);\n this.elementMap.set(field, element);\n return element;\n }\n\n async tokenize(paymentId: string, idempotencyKey: string): Promise<TokenizeResult> {\n // C2: concurrent-call guard — only one tokenize() may be in-flight at a time.\n if (this.tokenizeInFlight) {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"tokenize_in_progress\",\n message: \"A tokenize() call is already in progress for this Elements instance\",\n retryable: false,\n });\n }\n\n const cardNumber = this.elementMap.get(\"cardNumber\");\n const cardExpiry = this.elementMap.get(\"cardExpiry\");\n const cardCvv = this.elementMap.get(\"cardCvv\");\n\n if (!cardNumber || !cardExpiry || !cardCvv) {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"incomplete_elements\",\n message:\n \"All three elements (cardNumber, cardExpiry, cardCvv) must be created and mounted before tokenize()\",\n retryable: false,\n });\n }\n if (!cardNumber.isReady() || !cardExpiry.isReady() || !cardCvv.isReady()) {\n throw new ArcPayError({\n type: \"validation_error\",\n code: \"elements_not_ready\",\n message: \"Wait for all elements to fire 'ready' event before tokenize()\",\n retryable: false,\n });\n }\n\n this.tokenizeInFlight = true;\n try {\n return await this.doTokenize(cardNumber, paymentId, idempotencyKey);\n } finally {\n this.tokenizeInFlight = false;\n }\n }\n\n private doTokenize(\n cardNumber: Element,\n paymentId: string,\n idempotencyKey: string,\n ): Promise<TokenizeResult> {\n const iframeOrigin = new URL(this.iframeBase).origin;\n // C1: obtain reference to the cardNumber iframe's contentWindow before\n // registering the listener so we can filter by source.\n const cardIframeWindow = cardNumber.getIframeContentWindow();\n\n return new Promise<TokenizeResult>((resolve, reject) => {\n // C3: 30-second timeout — rejects and cleans up if no result arrives.\n const timer = window.setTimeout(() => {\n window.removeEventListener(\"message\", onMessage);\n reject(\n new ArcPayError({\n type: \"network_error\",\n code: \"tokenize_timeout\",\n message: \"tokenize() timed out after 30 seconds\",\n retryable: true,\n paymentId,\n }),\n );\n }, 30_000);\n\n const onMessage = (event: MessageEvent) => {\n // C1: source guard — only accept messages from the cardNumber iframe.\n if (cardIframeWindow !== null && event.source !== cardIframeWindow) return;\n // C4: use parseIncoming for origin + arcpay: prefix guard.\n const data = parseIncoming<IframeToParent>(event, iframeOrigin);\n if (!data) return;\n\n if (data.type === \"arcpay:tokenize-result\") {\n clearTimeout(timer);\n window.removeEventListener(\"message\", onMessage);\n resolve({\n cardTokenId: data.cardTokenId,\n cardMask: data.cardMask,\n cardScheme: data.cardScheme,\n cardBin: data.cardBin,\n expiresAt: data.expiresAt,\n });\n } else if (data.type === \"arcpay:tokenize-error\") {\n clearTimeout(timer);\n window.removeEventListener(\"message\", onMessage);\n const errType =\n data.errorType === \"validation_error\" || data.errorType === \"api_error\"\n ? data.errorType\n : \"api_error\";\n reject(\n new ArcPayError({\n type: errType,\n code: data.code,\n message: data.message,\n retryable: false,\n paymentId,\n }),\n );\n }\n };\n\n window.addEventListener(\"message\", onMessage);\n cardNumber.send({ type: \"arcpay:tokenize\", paymentId, idempotencyKey });\n });\n }\n\n destroy(): void {\n for (const el of this.elementMap.values()) {\n el.destroy();\n }\n this.elementMap.clear();\n }\n}\n","import { verifyCspAllowsApiBase } from \"./csp\";\nimport { detectEnvironment, type Environment, validatePublishableKey as _validatePublishableKey } from \"./env\";\nimport { showSandboxBanner } from \"./sandbox-banner\";\nimport { Elements, type ElementsOptions } from \"../elements/elements\";\n\nconst validatePublishableKey: (key: unknown) => asserts key is string = _validatePublishableKey;\n\nexport interface ArcPayLoadOptions {\n apiBase?: string;\n}\n\nconst DEFAULT_API_BASE = \"https://api.arcpay.space\";\n\nexport interface ArcPayInstance {\n readonly publishableKey: string;\n readonly apiBase: string;\n readonly environment: Environment;\n elements: (opts?: ElementsOptions) => Elements;\n}\n\nconst cache = new Map<string, Promise<ArcPayInstance>>();\n\nconst buildInstance = (publishableKey: string, opts: ArcPayLoadOptions): ArcPayInstance => {\n const apiBase = opts.apiBase ?? DEFAULT_API_BASE;\n verifyCspAllowsApiBase(apiBase);\n if (detectEnvironment(publishableKey) === \"sandbox\") {\n showSandboxBanner();\n }\n return {\n publishableKey,\n apiBase,\n environment: detectEnvironment(publishableKey),\n elements: (elemOpts) => new Elements({ publishableKey, iframeBase: elemOpts?.iframeBase }),\n };\n};\n\nfunction load(publishableKey: string, opts: ArcPayLoadOptions = {}): Promise<ArcPayInstance> {\n try {\n validatePublishableKey(publishableKey);\n } catch (err) {\n return Promise.reject(err);\n }\n const key = `${publishableKey}|${opts.apiBase ?? DEFAULT_API_BASE}`;\n const existing = cache.get(key);\n if (existing) return existing;\n const promise = Promise.resolve(buildInstance(publishableKey, opts));\n cache.set(key, promise);\n return promise;\n}\n\nconst resetForTests = (): void => {\n cache.clear();\n};\n\nexport const ArcPay = {\n load,\n __resetForTests: resetForTests,\n};\n","export const luhnCheck = (pan: string): boolean => {\n if (!/^\\d+$/.test(pan)) return false;\n if (/^0+$/.test(pan)) return false;\n let sum = 0;\n let alternate = false;\n for (let i = pan.length - 1; i >= 0; i--) {\n let n = pan.charCodeAt(i) - 48;\n if (alternate) {\n n *= 2;\n if (n > 9) n -= 9;\n }\n sum += n;\n alternate = !alternate;\n }\n return sum % 10 === 0;\n};\n","export { ArcPay } from \"./core/arcpay\";\nexport type { ArcPayInstance, ArcPayLoadOptions } from \"./core/arcpay\";\nexport {\n ArcPayError,\n isValidationError,\n isAuthenticationError,\n isAuthorizationError,\n isStateError,\n isRateLimitError,\n isApiError,\n isNetworkError,\n isChallengeAborted,\n} from \"./core/errors\";\nexport type { ArcPayErrorType } from \"./core/errors\";\nexport type { Environment } from \"./core/env\";\nexport type { TokenizeRequest, TokenizeResult } from \"./tokenize/tokenize\";\nexport type { CardScheme } from \"./tokenize/scheme\";\nexport const SDK_VERSION = \"0.1.0\";\n\n// Hosted Fields postMessage protocol\nexport type {\n FieldType,\n ParentToIframe,\n IframeToParent,\n StyleSubset,\n} from \"./elements/postmessage\";\nexport { postToIframe, postToParent, parseIncoming } from \"./elements/postmessage\";\n\n// Style sanitizer — also used by elements iframe app (defense-in-depth on receipt)\nexport { sanitizeStyle } from \"./elements/style\";\n\n// Hosted Fields — Element class + Elements factory\nexport { Element } from \"./elements/element\";\nexport type { ElementOptions, ElementEvent, ElementContext } from \"./elements/element\";\nexport { Elements } from \"./elements/elements\";\nexport type { ElementsOptions } from \"./elements/elements\";\n\n// Luhn check (used by elements app for card-number validation)\nexport { luhnCheck } from \"./tokenize/luhn\";\n"]}