@stackonward/onex-checkout 0.0.0-stage → 0.3.0

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.mjs ADDED
@@ -0,0 +1,478 @@
1
+ import { z } from 'zod';
2
+
3
+ class CheckoutProtocolError extends Error {
4
+ constructor(code, subject) {
5
+ super(`Checkout ${code}: ${subject}`);
6
+ this.code = code;
7
+ this.name = "CheckoutProtocolError";
8
+ }
9
+ }
10
+ function decode(schema, value, subject, code = "invalid_response") {
11
+ const result = schema.safeParse(value);
12
+ if (!result.success) {
13
+ throw new CheckoutProtocolError(code, subject);
14
+ }
15
+ return result.data;
16
+ }
17
+ const nonblank = z.string().min(1).refine((value) => value.trim().length > 0);
18
+ const countryCode = z.string().regex(/^[A-Z]{2}$/);
19
+ const revision = z.number().int().safe().positive();
20
+ const amount = z.string().regex(/^\d+(?:\.\d+)?$/);
21
+ const currency = z.string().regex(/^[A-Z]{3}$/);
22
+ const sessionStatus = z.enum([
23
+ "open",
24
+ "settling",
25
+ "closing",
26
+ "completing",
27
+ "completed",
28
+ "compensating",
29
+ "compensated",
30
+ "canceled",
31
+ "expired",
32
+ "requires_attention"
33
+ ]);
34
+ const executionStatus = z.enum([
35
+ "prepared",
36
+ "dispatch_pending",
37
+ "processing",
38
+ "requires_action",
39
+ "succeeded",
40
+ "failed",
41
+ "cancel_requested",
42
+ "canceling",
43
+ "canceled",
44
+ "expired",
45
+ "unknown"
46
+ ]);
47
+ const optionID = z.number().int().safe().positive().optional();
48
+ const purchaseOption = z.object({
49
+ purchase_option_id: optionID,
50
+ complete_without_payment: z.literal(true).optional(),
51
+ item_name: nonblank,
52
+ amount,
53
+ currency,
54
+ renewal_terms: z.object({
55
+ amount,
56
+ currency,
57
+ billing_period: z.enum(["weekly", "monthly", "quarterly", "semi_annual", "annual"]),
58
+ billing_interval: z.number().int().safe().positive()
59
+ }).optional()
60
+ });
61
+ const session = z.object({
62
+ checkout_session_no: nonblank,
63
+ status: sessionStatus,
64
+ revision,
65
+ expires_at: z.string().datetime({ offset: true }),
66
+ active_execution_no: nonblank.nullable(),
67
+ pricing_input: z.object({ currency, available_currencies: z.array(currency) }).optional(),
68
+ purchase_options: z.array(purchaseOption),
69
+ available_actions: z.array(z.enum(["list_payment_methods", "complete_without_payment"]))
70
+ });
71
+ const checkoutField = z.object({
72
+ requirement: z.enum([
73
+ "required",
74
+ "conditional",
75
+ "recommended",
76
+ "provider_auto",
77
+ "internal",
78
+ "not_collected"
79
+ ]),
80
+ collection: z.enum([
81
+ "checkout_form",
82
+ "provider_component",
83
+ "wallet_sheet",
84
+ "request_context",
85
+ "not_collected"
86
+ ]),
87
+ required_countries: z.array(countryCode).optional(),
88
+ reason: z.string().optional()
89
+ });
90
+ const authority = z.enum(["catalog_purchase_option", "target_policy"]);
91
+ const method = z.object({
92
+ method_reference: nonblank,
93
+ method_binding: nonblank,
94
+ provider: nonblank,
95
+ provider_environment: z.enum(["sandbox", "live"]),
96
+ pm_id: nonblank,
97
+ name: nonblank,
98
+ logo: z.string().optional(),
99
+ payment_authority_kind: authority,
100
+ purchase_option_id: optionID,
101
+ purchase_option_label: z.string().optional(),
102
+ renewal_policy: z.enum(["manual", "auto"]).optional(),
103
+ amount,
104
+ currency,
105
+ payment_required: z.boolean(),
106
+ provider_setup_required: z.boolean(),
107
+ setup_requirement: z.enum(["none", "reusable_authorization", "hosted_subscription", "both"]),
108
+ setup_execution_mode: z.enum(["none", "bundled_with_payment", "standalone"]),
109
+ country_code: countryCode.nullish(),
110
+ presentation_mode: nonblank,
111
+ presentation_flow: nonblank,
112
+ presentation_version: revision,
113
+ requires_provider_client_payload: z.boolean(),
114
+ checkout_fields: z.record(checkoutField)
115
+ });
116
+ const methods = z.object({
117
+ session_revision: revision,
118
+ groups: z.array(z.object({ key: nonblank, label: z.string(), methods: z.array(method) }))
119
+ });
120
+ const purpose = z.enum(["payment", "provider_setup"]);
121
+ const presentation = z.object({
122
+ mode: nonblank,
123
+ flow: nonblank,
124
+ version: revision,
125
+ checkout_url: z.string().nullable().optional(),
126
+ payload: z.unknown()
127
+ });
128
+ const billingAddress = z.object({
129
+ line1: nonblank.optional(),
130
+ line2: nonblank.optional(),
131
+ city: nonblank.optional(),
132
+ state: nonblank.optional(),
133
+ postal_code: nonblank.optional(),
134
+ country: countryCode.optional()
135
+ }).strict();
136
+ const CUSTOMER_NAME_MAX_LENGTH = 120;
137
+ const customerName = z.string().trim().min(1).max(CUSTOMER_NAME_MAX_LENGTH);
138
+ const execution = z.object({
139
+ checkout_session_no: nonblank,
140
+ execution_no: nonblank,
141
+ status: executionStatus,
142
+ purpose,
143
+ selection_status: z.enum(["active", "superseded", "session_closed"]).optional(),
144
+ order_no: z.string().optional(),
145
+ customer_name: customerName.optional(),
146
+ billing_address: billingAddress.optional(),
147
+ payment_no: nonblank.nullish(),
148
+ provider: nonblank.optional(),
149
+ pm_id: nonblank.optional(),
150
+ payment_authority_kind: authority,
151
+ purchase_option_id: optionID,
152
+ method_binding: nonblank,
153
+ amount,
154
+ currency,
155
+ presentation: presentation.nullable(),
156
+ command_status: z.string().optional()
157
+ });
158
+ const presentationContext = execution.pick({
159
+ amount: true,
160
+ purpose: true,
161
+ provider: true,
162
+ pm_id: true
163
+ });
164
+ const cancellation = z.object({
165
+ checkout_session_no: nonblank,
166
+ execution_no: nonblank,
167
+ session_status: sessionStatus,
168
+ execution_status: executionStatus,
169
+ command_status: z.string(),
170
+ pending_provider_commands: z.number().int().safe().nonnegative()
171
+ });
172
+ const completion = z.object({
173
+ checkout_session_no: nonblank,
174
+ session_status: sessionStatus,
175
+ order_no: nonblank,
176
+ fulfillment_status: nonblank
177
+ });
178
+ const reviseInput = z.object({ currency, expected_revision: revision }).strict();
179
+ const revisionResult = z.object({ checkout_session_no: nonblank, revision, currency });
180
+ const startInput = z.object({
181
+ session_revision: revision,
182
+ method_reference: nonblank,
183
+ customer_name: customerName.optional(),
184
+ billing_address: billingAddress.optional()
185
+ }).strict();
186
+
187
+ const airwallexMethods = [
188
+ { id: "card", submission: "form", requiresCardholderName: true },
189
+ { id: "apple_pay", submission: "native", requiresCardholderName: false },
190
+ { id: "google_pay", submission: "native", requiresCardholderName: false }
191
+ ];
192
+ const consent = z.object({
193
+ next_triggered_by: z.literal("merchant"),
194
+ merchant_trigger_reason: z.literal("scheduled")
195
+ });
196
+ const airwallexPayload = z.object({
197
+ sdk_environment: z.enum(["demo", "prod"]),
198
+ merchant_display_name: nonblank,
199
+ client_secret: nonblank,
200
+ payment_intent_id: nonblank,
201
+ customer_id: nonblank.optional(),
202
+ payment_consent: consent.optional(),
203
+ country_code: countryCode.optional(),
204
+ merchant_country_code: countryCode.optional()
205
+ });
206
+ function invalid$1(subject) {
207
+ throw new CheckoutProtocolError("invalid_response", subject);
208
+ }
209
+ function read(raw, context) {
210
+ const payload = decode(airwallexPayload, raw, "airwallex_dropin@2 payload");
211
+ const { pm_id, purpose, provider, amount } = context;
212
+ const method = airwallexMethods.find(({ id }) => id === pm_id);
213
+ if (provider !== "airwallex" || !method) {
214
+ throw new CheckoutProtocolError("unsupported_presentation", "Airwallex payment method");
215
+ }
216
+ if (method.submission === "native" && !payload.merchant_country_code) {
217
+ invalid$1("wallet merchant country");
218
+ }
219
+ const zeroAmount = /^0+(?:\.0+)?$/.test(amount);
220
+ if (zeroAmount !== (purpose === "provider_setup")) {
221
+ invalid$1("execution amount for purpose");
222
+ }
223
+ if (purpose === "provider_setup" && !payload.payment_consent) {
224
+ invalid$1("standalone authorization");
225
+ }
226
+ if (payload.payment_consent && !payload.customer_id) {
227
+ invalid$1("scheduled authorization customer");
228
+ }
229
+ return { mode: "embedded", flow: "airwallex_dropin", version: 2, payload };
230
+ }
231
+ function airwallexEnvironment(environment) {
232
+ return environment === "live" ? "prod" : "demo";
233
+ }
234
+ const airwallex = {
235
+ flow: "airwallex_dropin",
236
+ version: 2,
237
+ decode: read,
238
+ assertMethod(method, current) {
239
+ const environment = airwallexEnvironment(method.provider_environment);
240
+ const hasConsent = current.payload.payment_consent !== void 0;
241
+ if (environment !== current.payload.sdk_environment || hasConsent !== method.provider_setup_required) {
242
+ invalid$1("selected authorization terms");
243
+ }
244
+ }
245
+ };
246
+ function airwallexSession(execution) {
247
+ const payload = execution.presentation?.payload;
248
+ if (!payload) return invalid$1("missing payment presentation");
249
+ const values = {
250
+ amount: execution.amount,
251
+ currency: execution.currency,
252
+ clientSecret: payload.client_secret
253
+ };
254
+ if (execution.purpose === "provider_setup" && payload.customer_id && payload.payment_consent && payload.payment_intent_id) {
255
+ return {
256
+ ...values,
257
+ kind: "setup",
258
+ customerId: payload.customer_id,
259
+ intentId: payload.payment_intent_id
260
+ };
261
+ }
262
+ if (execution.purpose !== "payment" || !payload.payment_intent_id)
263
+ return invalid$1("payment purpose");
264
+ if (payload.payment_consent && payload.customer_id)
265
+ return {
266
+ ...values,
267
+ kind: "recurring",
268
+ intentId: payload.payment_intent_id,
269
+ customerId: payload.customer_id
270
+ };
271
+ if (payload.payment_consent) return invalid$1("scheduled consent without customer");
272
+ return { ...values, kind: "payment", intentId: payload.payment_intent_id };
273
+ }
274
+
275
+ function invalid(subject) {
276
+ throw new CheckoutProtocolError("invalid_response", subject);
277
+ }
278
+ function findDecoder(key, extensions) {
279
+ const registered = [
280
+ airwallex,
281
+ ...extensions
282
+ ];
283
+ return registered.find(({ flow, version }) => flow === key.flow && version === key.version);
284
+ }
285
+ function parsePresentation(value, context, decoders = []) {
286
+ const raw = decode(presentation, value, "execution presentation");
287
+ if (raw.mode !== "embedded" || raw.checkout_url != null) {
288
+ throw new CheckoutProtocolError("unsupported_presentation", "embedded execution");
289
+ }
290
+ const selected = decode(presentationContext, context, "execution presentation context");
291
+ const decoder = findDecoder(raw, decoders);
292
+ if (!decoder)
293
+ throw new CheckoutProtocolError("unsupported_presentation", "presentation flow or version");
294
+ return decoder.decode(raw.payload, selected);
295
+ }
296
+ function assertExecutionMethod(method, execution, decoders) {
297
+ if (method.method_binding !== execution.method_binding || method.payment_authority_kind !== execution.payment_authority_kind || method.purchase_option_id !== execution.purchase_option_id || execution.provider !== void 0 && execution.provider !== method.provider || execution.pm_id !== void 0 && execution.pm_id !== method.pm_id) {
298
+ invalid("execution method binding");
299
+ }
300
+ const current = execution.presentation;
301
+ if (!current) return;
302
+ if (method.presentation_mode !== current.mode || method.presentation_flow !== current.flow || method.presentation_version !== current.version) {
303
+ invalid("selected presentation");
304
+ }
305
+ const decoder = findDecoder(current, decoders ?? []);
306
+ if (decoders && !decoder)
307
+ throw new CheckoutProtocolError("unsupported_presentation", "presentation flow or version");
308
+ decoder?.assertMethod?.(method, current);
309
+ }
310
+
311
+ function relativeBase(path) {
312
+ if (!path.startsWith("/") || path.startsWith("//") || /[\\?#\s]/.test(path) || path.split("/").some((part) => part === "." || part === "..")) {
313
+ throw new CheckoutProtocolError("invalid_request", "same-origin base path");
314
+ }
315
+ return path.replace(/\/+$/, "");
316
+ }
317
+ function segment(value) {
318
+ if (!value.trim() || value === "." || value === ".." || /[\\/]/.test(value)) {
319
+ throw new CheckoutProtocolError("invalid_request", "resource number");
320
+ }
321
+ return encodeURIComponent(value);
322
+ }
323
+ function verifyScope(value, sessionNo, executionNo) {
324
+ if (value.checkout_session_no !== sessionNo || executionNo !== void 0 && value.execution_no !== executionNo) {
325
+ throw new CheckoutProtocolError("invalid_response", "resource number");
326
+ }
327
+ return value;
328
+ }
329
+ function checkIdempotencyKey(key) {
330
+ if (!key || key.trim() !== key || /[\r\n]/.test(key)) {
331
+ throw new CheckoutProtocolError("invalid_request", "idempotency key");
332
+ }
333
+ return key;
334
+ }
335
+ function createCheckoutClient(options) {
336
+ const presentations = [...options.presentations ?? []];
337
+ const base = relativeBase(options.basePath);
338
+ const transport = options.transport;
339
+ const sessionPath = (no) => [base, segment(no)].join("/");
340
+ const executionPath = (no, executionNo) => [sessionPath(no), "executions", segment(executionNo)].join("/");
341
+ async function post(path, body, signal, key) {
342
+ const headers = new Headers(await options.mutationHeaders?.());
343
+ if (key !== void 0) headers.set("Idempotency-Key", key);
344
+ return transport.post(path, body, { headers, signal });
345
+ }
346
+ function readExecution(raw, no, executionNo) {
347
+ const item = verifyScope(decode(execution, raw, "execution"), no, executionNo);
348
+ return {
349
+ ...item,
350
+ presentation: item.presentation === null ? null : parsePresentation(item.presentation, item, presentations)
351
+ };
352
+ }
353
+ return {
354
+ assertMethod(method, current) {
355
+ assertExecutionMethod(method, current, presentations);
356
+ },
357
+ async session(no, signal) {
358
+ const raw = await transport.get(sessionPath(no) + "/state", { signal });
359
+ return verifyScope(decode(session, raw, "session state"), no);
360
+ },
361
+ async methods(no, signal) {
362
+ const raw = await transport.get(sessionPath(no) + "/payment-methods", { signal });
363
+ return decode(methods, raw, "payment methods");
364
+ },
365
+ async revise(no, input, idempotencyKey, signal) {
366
+ const body = decode(reviseInput, input, "revise session", "invalid_request");
367
+ const raw = await post(
368
+ sessionPath(no) + "/revisions",
369
+ body,
370
+ signal,
371
+ checkIdempotencyKey(idempotencyKey)
372
+ );
373
+ const updated = verifyScope(decode(revisionResult, raw, "session revision"), no);
374
+ if (updated.currency !== body.currency)
375
+ throw new CheckoutProtocolError("invalid_response", "revision currency");
376
+ return updated;
377
+ },
378
+ async start(no, input, idempotencyKey, signal) {
379
+ const body = decode(startInput, input, "start execution", "invalid_request");
380
+ const raw = await post(
381
+ sessionPath(no) + "/executions",
382
+ body,
383
+ signal,
384
+ checkIdempotencyKey(idempotencyKey)
385
+ );
386
+ return readExecution(raw, no);
387
+ },
388
+ async execution(no, executionNo, signal) {
389
+ const raw = await transport.get(executionPath(no, executionNo), { signal });
390
+ return readExecution(raw, no, executionNo);
391
+ },
392
+ async reconcile(no, executionNo, signal) {
393
+ const raw = await post(executionPath(no, executionNo) + "/reconcile", void 0, signal);
394
+ return readExecution(raw, no, executionNo);
395
+ },
396
+ async cancel(no, executionNo, idempotencyKey, signal) {
397
+ const raw = await post(
398
+ executionPath(no, executionNo) + "/cancel",
399
+ void 0,
400
+ signal,
401
+ checkIdempotencyKey(idempotencyKey)
402
+ );
403
+ return verifyScope(decode(cancellation, raw, "cancel execution"), no, executionNo);
404
+ },
405
+ async complete(no, expectedRevision, idempotencyKey, signal) {
406
+ const body = {
407
+ expected_revision: decode(
408
+ revision,
409
+ expectedRevision,
410
+ "expected revision",
411
+ "invalid_request"
412
+ )
413
+ };
414
+ const raw = await post(
415
+ sessionPath(no) + "/complete",
416
+ body,
417
+ signal,
418
+ checkIdempotencyKey(idempotencyKey)
419
+ );
420
+ return verifyScope(decode(completion, raw, "complete session"), no);
421
+ }
422
+ };
423
+ }
424
+
425
+ const definitions = [
426
+ {
427
+ code: "cardholder_name",
428
+ key: "cardholder_name",
429
+ autocomplete: "cc-name",
430
+ maxLength: CUSTOMER_NAME_MAX_LENGTH
431
+ },
432
+ { code: "phone_number", key: "phone_number", autocomplete: "tel" },
433
+ { code: "billing_line1", key: "line1", autocomplete: "address-line1" },
434
+ { code: "billing_line2", key: "line2", autocomplete: "address-line2" },
435
+ { code: "billing_city", key: "city", autocomplete: "address-level2" },
436
+ { code: "billing_country", key: "country", autocomplete: "country" },
437
+ { code: "billing_region", key: "state", autocomplete: "address-level1" },
438
+ { code: "billing_postal_code", key: "postal_code", autocomplete: "postal-code" }
439
+ ];
440
+ function collected(field) {
441
+ return field?.collection === "checkout_form" && field.requirement !== "not_collected" && field.requirement !== "provider_auto";
442
+ }
443
+ function collectPayerFields(fields, country = "") {
444
+ return definitions.flatMap((definition) => {
445
+ const field = fields[definition.code];
446
+ if (!collected(field)) return [];
447
+ const required = field.requirement === "required" || field.requirement === "conditional" && Boolean(field.required_countries?.includes(country.trim().toUpperCase()));
448
+ return [{ ...definition, required }];
449
+ });
450
+ }
451
+ function isCardholderNameValid(name) {
452
+ const value = name.trim();
453
+ return value.length <= CUSTOMER_NAME_MAX_LENGTH && /^(?=.*\p{Script=Latin})[\p{Script=Latin}\p{Mark} .'-]+$/u.test(value);
454
+ }
455
+ function hasValidPayerValues(fields, values) {
456
+ return fields.every(({ key, required }) => {
457
+ const value = values[key]?.trim();
458
+ if (!value) return !required;
459
+ if (key === "country") return /^[A-Z]{2}$/.test(value);
460
+ return key !== "cardholder_name" || isCardholderNameValid(value);
461
+ });
462
+ }
463
+ function billingAddressInput(fields, values) {
464
+ const address = {};
465
+ for (const { key } of fields) {
466
+ if (key === "cardholder_name" || key === "phone_number") continue;
467
+ const value = values[key]?.trim();
468
+ if (value) address[key] = value;
469
+ }
470
+ return Object.keys(address).length ? address : void 0;
471
+ }
472
+ function supportsPayerFields(fields) {
473
+ return Object.entries(fields).every(
474
+ ([code, field]) => !collected(field) || !["required", "conditional"].includes(field.requirement) || code === "email" || definitions.some((definition) => definition.code === code)
475
+ );
476
+ }
477
+
478
+ export { CheckoutProtocolError, airwallexEnvironment, airwallexMethods, airwallexSession, assertExecutionMethod, billingAddressInput, collectPayerFields, createCheckoutClient, hasValidPayerValues, isCardholderNameValid, parsePresentation, supportsPayerFields };
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@stackonward/onex-checkout",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "Browser-facing buyer checkout contracts for OneX integrations",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.mjs",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.mjs"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "sideEffects": false,
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://onedev.yhy.gd.cn/platform/stackonward.git",
27
+ "directory": "packages/integrations/onex/checkout"
28
+ },
29
+ "dependencies": {
30
+ "zod": "^3.24.0",
31
+ "@stackonward/api-client": "0.0.4"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^22.0.0",
35
+ "unbuild": "^3.5.0",
36
+ "vitest": "^3.2.4"
37
+ },
38
+ "scripts": {
39
+ "build": "unbuild",
40
+ "typecheck": "tsc --noEmit",
41
+ "test": "vitest run"
42
+ }
6
43
  }