@alytegen/sdk 0.7.0 → 0.8.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/BROWSER.md CHANGED
@@ -93,8 +93,10 @@ const attempt = { agentId, tierId, quantity: 1, attemptId: crypto.randomUUID() }
93
93
  // across reloads and reconnects. Namespace it to this buyer/shop/cart.
94
94
  await attempts.save(attempt);
95
95
  const purchase = await buyer.buy(attempt);
96
- if (purchase.status === 'pending') {
97
- const receipt = await buyer.payment(purchase.intentId); // refresh later if pending
96
+ if (purchase.status === 'pending' && 'purchaseId' in purchase && purchase.purchaseId) {
97
+ const state = await buyer.resumePurchase(purchase.purchaseId); // same purchase, never buy again
98
+ } else if (purchase.status === 'pending' && 'intentId' in purchase) {
99
+ const receipt = await buyer.payment(purchase.intentId); // legacy receipt
98
100
  }
99
101
  ```
100
102
 
@@ -102,8 +104,8 @@ The UUID is required; the SDK never invents one or retries requests automaticall
102
104
  After a network failure, resume with the **same saved attempt**, including agent,
103
105
  tier, quantity and ID. Never create a fresh attempt to retry an uncertain charge.
104
106
  `settled` is success; `pending` remains unresolved. `sca_required` is an authentication
105
- continuation requirement; browser SCA resume is not yet available. Do not treat it
106
- as success or dispatch a new purchase. Non-2xx responses throw `AlyteApiError` with
107
+ continuation requirement: use `openChallenge` when a `purchaseId` is present. Do not
108
+ treat it as success or dispatch a new purchase. Non-2xx responses throw `AlyteApiError` with
107
109
  `status`, `code` and `details`; purchase `402` outcome bodies are in `details`.
108
110
 
109
111
  Other methods: `me()`, `catalog()`, `agents()`, `instruments()`, `instrumentCaps()`,
@@ -114,3 +116,82 @@ live availability. An ordinary bounded bearer cannot create or widen spending au
114
116
 
115
117
  Your backend still fulfills from verified settlement webhooks, idempotently.
116
118
  Browser completion messages are presentation state, not fulfillment evidence.
119
+
120
+ ## Finish a bank challenge for an existing purchase
121
+
122
+ On deployments supporting buyer-present purchases, `buy()` can return
123
+ `{ status: 'sca_required', purchaseId, challenge: { expiresAt } }`. Keep the opaque
124
+ `purchaseId` alongside the original attempt. Do not call `buy()` again or allocate
125
+ another attempt ID to handle the challenge.
126
+
127
+ ```ts
128
+ import { createBuyerClient, openChallenge } from '@alytegen/sdk/browser';
129
+
130
+ const client = createBuyerClient({ baseUrl, bearer });
131
+ const purchase = await client.buy(savedAttempt);
132
+ if (['sca_required', 'pending'].includes(purchase.status) && 'purchaseId' in purchase && purchase.purchaseId) {
133
+ const result = await openChallenge({
134
+ baseUrl, merchantId, bearer, purchaseId: purchase.purchaseId,
135
+ container: document.querySelector('#bank-approval')!,
136
+ signal: modalAbortController.signal,
137
+ onStatus: ({ purchaseId, status }) => showPurchaseStatus(purchaseId, status),
138
+ });
139
+ // result has only purchaseId and the server's terminal status:
140
+ // settled | refused | cancelled | expired.
141
+ }
142
+ ```
143
+
144
+ The launcher uses the same registered parent origin, in-memory bounded bearer,
145
+ shop binding and optional theme/language parameters as `openConsent`. It opens a
146
+ separate challenge view. Only the Alyte frame retrieves provider action material.
147
+ Stripe uses `handleNextAction`; Adyen sandbox native 3DS2 uses the pinned Adyen Web
148
+ component, real browser information, and the server's bound action round. The
149
+ server verifies the original payment and its details proof. No browser `approved` flag is accepted. Parent callbacks
150
+ contain only the purchase ID and safe status, never provider secrets or receipts.
151
+
152
+ `openChallenge` remains open for pending or action-required purchases. It polls
153
+ `resume` at a bounded interval while visible, with at most one request in flight,
154
+ and pauses polling during issuer interaction. Aborting removes the frame and
155
+ rejects with `challenge_closed`; it does not cancel or retry the purchase.
156
+ Reopening with the same purchase ID recovers it. The buyer can explicitly request
157
+ cancellation inside the frame; the UI waits for the server's verified outcome.
158
+
159
+ For status outside the frame, use `client.purchase(purchaseId)` (read the durable
160
+ state), `client.resumePurchase(purchaseId)` (ask the server to retrieve/advance the
161
+ same payment), or `client.cancelPurchase(purchaseId)` (request verified
162
+ cancellation). Resume and cancel send an empty body and are never automatically
163
+ retried by these client methods. The SDK intentionally exposes no action-material
164
+ method. Older mock flows may return `sca_required` without a purchase ID; this
165
+ launcher does not turn those mock tokens into real bank authentication.
166
+
167
+
168
+ ## Recover a queued purchase
169
+
170
+ A watch can become `awaiting_sca`. Its safe `result` carries `purchaseId` and
171
+ `challenge.expiresAt`. A `firing` watch can also carry a pending `purchaseId` while
172
+ its provider outcome is uncertain. Open that existing purchase with `openChallenge`;
173
+ do not call `buy`, create another watch, or infer cancellation from the deadline.
174
+ `observeWatch` keeps reading until the server reports a terminal watch state.
175
+
176
+ ```ts
177
+ const { watch } = await client.getWatch(savedWatchId);
178
+ if (['awaiting_sca', 'firing'].includes(watch.status) && watch.result?.purchaseId) {
179
+ await openChallenge({ baseUrl, merchantId, bearer,
180
+ purchaseId: watch.result.purchaseId, container: challengeContainer,
181
+ signal: modalAbortController.signal });
182
+ }
183
+ ```
184
+
185
+ The merchant webhook SDK exposes `onWatchActionRequired` for signed
186
+ `watch.action_required` deliveries. The event contains safe watch/purchase IDs,
187
+ `buyerRef`, merchant/tenant scope, and the original deadline. Deduplicate by
188
+ `eventId` and relay the action through the merchant's own buyer channel; the SDK
189
+ deliberately passes redeliveries to the handler. A link grants no authority: the
190
+ buyer still needs their own shop-bound session. This event is never fulfilment.
191
+ A verified `approval_expired` or `buyer_cancelled` outcome ends the watch without
192
+ automatically starting another purchase.
193
+
194
+ Adyen action/details remain exclusive to the Alyte challenge frame. The public
195
+ browser client exposes safe status/resume/cancel only. Native sandbox actions are
196
+ supported by this slice; redirect actions, production activation, and real-provider
197
+ qualification remain separate gates. Closing the frame preserves the purchase.
package/QUICKSTART.md CHANGED
@@ -31,7 +31,12 @@ const { tier } = await alyte.createTier({ eventId: event.id, title: 'GA', priceM
31
31
 
32
32
  Money is **integer minor units** everywhere (`4900` = €49.00). Floats are refused.
33
33
 
34
- SDK 0.7.0 also includes `alyte.accessRules` and `alyte.memberships` for
34
+ SDK 0.8.0 adds per-event ticket limits (`setEventPurchaseLimit`, `getEventPurchaseLimit`,
35
+ `clearEventPurchaseLimit`), idempotent pool creation (`createPool({ externalRef })`),
36
+ all-or-nothing basket checkout on `AlyteAgent` (`reserveBasket`, `getReservation`,
37
+ `quoteReservation`, `confirmReservation`, `releaseReservation`, `resolveBasketSca`), and
38
+ browser queue-place / bank-challenge continuation (`createWatch`, `observeWatch`,
39
+ `openChallenge`). SDK 0.7.0 added `alyte.accessRules` and `alyte.memberships` for
35
40
  merchant-controlled early access: save a draft, preview, schedule or cancel, and attest or
36
41
  revoke membership. They require a server at or after sandbox revision `alyte-sandbox-00133-v77`.
37
42
  See [the access-rule workflow](./README.md#access-rules-and-membership)
package/README.md CHANGED
@@ -21,9 +21,9 @@ npm install @alytegen/sdk
21
21
  | `AlyteMerchant` | API token (console → API keys) | your server only | shops, events, tiers, PSP links, buyer-session mint, payments visibility |
22
22
  | `AlyteAgent` | agent JWT | your agent runtime | discover → quote → hold → confirm |
23
23
  | `createWebhookHandler` / `verifyWebhookSignature` | webhook secret | your server | signed, at-least-once purchase events with typed dispatch |
24
- | `exchangeBuyerSession` / `createBuyerClient` / `openConsent` from `@alytegen/sdk/browser` | bounded buyer bearer | partner browser/chat | isolated consent, then buy/watch/list/revoke within existing authority |
24
+ | `exchangeBuyerSession` / `createBuyerClient` / `openConsent` / `openChallenge` from `@alytegen/sdk/browser` | bounded buyer bearer | partner browser/chat | isolated consent and challenge continuation, then buy/watch/list/revoke within existing authority |
25
25
 
26
- The browser entry arrived in 0.4.0; 0.7.0 is the current release. See [the chat integration](./BROWSER.md) for setup,
26
+ The browser entry arrived in 0.4.0; 0.8.0 is the current release. See [the chat integration](./BROWSER.md) for setup,
27
27
  cookie-independent consent, reconnecting and handling uncertain purchases.
28
28
 
29
29
  ## Merchant: onboard in four calls
@@ -91,6 +91,12 @@ with `catalog_too_large` if any source relation exceeds 2,000 rows, including pr
91
91
  eligibility rows. `listLocations` has a separate 2,000-row bound. Neither returns a
92
92
  truncated result.
93
93
 
94
+ Use `setEventPurchaseLimit`, `getEventPurchaseLimit` and `clearEventPurchaseLimit` to
95
+ cap the tickets one customer can hold or buy across an event (`maxPerCustomer`, optional
96
+ `maxHeldPerCustomer` for unpaid holds, and optional `countWaitingWatches` for queued
97
+ purchases). `PUT` replaces the whole limit, and the first `PUT` counts earlier sales on
98
+ the event.
99
+
94
100
  ## Access rules and membership
95
101
 
96
102
  Available since SDK 0.7.0; requires a server at or after sandbox revision
@@ -184,6 +190,43 @@ Two kinds of session, decided by how you mint:
184
190
  ceilings answers `403 merchant_consent_ceiling_exceeded` and Alyte's screen falls back to the
185
191
  buyer's own code; without the enablement, the mint answers `403 merchant_consent_not_enabled`.
186
192
 
193
+ ## Queue a buyer's agent and show their place in line
194
+
195
+ Available since SDK 0.8.0 (requires a server with `GET /v1/buyer/watch-capabilities`). From the browser entry point,
196
+ with the bounded buyer bearer:
197
+
198
+ ```ts
199
+ import { createBuyerClient, observeWatch } from '@alytegen/sdk/browser';
200
+
201
+ const buyer = createBuyerClient({ baseUrl: ALYTE_URL, bearer });
202
+ // Save the whole instruction (never the bearer) BEFORE sending; resend the SAME one after a timeout.
203
+ const instruction = {
204
+ requestId: crypto.randomUUID(),
205
+ agentId,
206
+ request: { kind: 'ticketing' as const, tierId, quantity: 2 },
207
+ condition: { kind: 'price_at_or_below' as const, maxChargeMinor: 10_000, currency: 'EUR' as const },
208
+ expiresAt: '2026-12-01T12:00:00Z',
209
+ };
210
+ await saved.put(instruction);
211
+ const { watch } = await buyer.createWatch(instruction);
212
+
213
+ const stop = new AbortController();
214
+ observeWatch({ client: buyer, watchId: watch.id, signal: stop.signal,
215
+ onUpdate: (w) => render(w.queue), // { place: { kind, position, requestsAhead }, waitingReason, … }
216
+ onError: (_e, last, stopped) => showStale(last, stopped) });
217
+ ```
218
+
219
+ `maxChargeMinor` is the most the buyer pays **for the whole charge**, tax and buyer fees included;
220
+ equality qualifies. `{ kind: 'available' }` buys as soon as the units are there. An older server
221
+ refuses `createWatch` — it never falls back to the legacy `watch()`, which would drop the condition.
222
+
223
+ The place comes from Alyte's dispatcher, never from counting a list: one place per request (four
224
+ tickets are one place), counted within the capacity the requests compete for and within the
225
+ buyer's access window (`queue.phaseLabel`). The order is oldest first; a smaller request may be
226
+ served past an older, larger one at most three times, then the line holds for it. A request
227
+ waiting on its own price target has no place until it qualifies. A place is not a reservation or
228
+ a promise of tickets.
229
+
187
230
  ## Receive purchases
188
231
 
189
232
  ```ts
@@ -212,9 +255,59 @@ const out = await agent.confirm(hold.id,
212
255
  No amount is passed at confirm — the charge is the locked quote. A spend-cap refusal means
213
256
  the buyer's mandate said no: surface it, don't retry.
214
257
 
258
+ ## Agent: baskets with one payment
259
+
260
+ Available since SDK 0.8.0. Use `reserveBasket`, `getReservation`, `quoteReservation`,
261
+ `confirmReservation`, `releaseReservation` and `resolveBasketSca` for the existing
262
+ `/v1/reservations/*` API. Reading a reservation requires `payments:read`; the other
263
+ methods require `payments:write`. Discovery also exposes tier `role`, `category`,
264
+ `countsTowardPartySize` and `linkRule` so an agent can include required parent tickets.
265
+
266
+ ```ts
267
+ const reservation = await agent.reserveBasket({
268
+ lines: [{ tierId: adultTierId, quantity: 2 }, { tierId: childTierId, quantity: 1 }],
269
+ scheme: 'visa', geo: 'DE',
270
+ });
271
+ const quote = await agent.quoteReservation(reservation.id);
272
+ // Persist the reservation ID, these inputs and the key BEFORE confirming.
273
+ const input = { quoteId: quote.id, instrumentToken, scheme: 'visa' as const, geo: 'DE' };
274
+ const options = { idempotencyKey: crypto.randomUUID() };
275
+ const outcome = await agent.confirmReservation(reservation.id, input, options);
276
+ if (outcome.status === 'settled' && outcome.result.status === 'authorized'
277
+ && outcome.reservationStatus === 'confirmed') {
278
+ // The complete basket was paid and confirmed.
279
+ }
280
+ ```
281
+
282
+ A basket holds 1–20 lines from one merchant in one currency, atomically. Partial
283
+ fills and seated allocation are not supported. The server enforces link rules,
284
+ party-size limits, add-on permission and spending caps across the whole basket.
285
+ The `BasketQuote` has `lines` and one `chargeMinor`; it has no single `unitPriceMinor`.
286
+
287
+ Both confirmation and SCA resolution return the complete `ConfirmReservationOutcome`,
288
+ including HTTP 402 business outcomes. `sca_required` keeps the basket held; continue
289
+ the original challenge with `resolveBasketSca(continueToken, outcome)` using the
290
+ same authenticated agent and the server's verified challenge flow. `sca_failed`
291
+ releases it. A settled decline is a known refusal. `payment_pending`, or a settled
292
+ error with `reservationStatus: 'reconcile'`, needs payment recovery; do not fulfil,
293
+ release stock, or create a new purchase to retry it. Ordinary API refusals still
294
+ throw `AlyteApiError` with their code and details.
295
+
296
+ The client never retries automatically. After a lost confirmation response, reuse
297
+ the saved reservation, inputs and idempotency key. Reserve is not idempotent: retrying
298
+ it creates another hold. If a buyer abandons a known unpaid basket, call
299
+ `releaseReservation(reservation.id)`; the server refuses release during payment.
300
+ See [`examples/agent-basket.ts`](./examples/agent-basket.ts) for a runnable example.
301
+
215
302
  ## Current API and console capabilities
216
303
 
217
- SDK **0.7.0** adds merchant-controlled early access: `accessRules` (`list`, `get`,
304
+ SDK **0.8.0** adds:
305
+ - **Per-event customer ticket limits (`AlyteMerchant`):** `setEventPurchaseLimit`, `getEventPurchaseLimit` and `clearEventPurchaseLimit`, plus idempotent pool creation via `createPool({ externalRef })`.
306
+ - **All-or-nothing basket checkout (`AlyteAgent`):** `reserveBasket`, `getReservation`, `quoteReservation`, `confirmReservation`, `releaseReservation` and `resolveBasketSca`, plus tier `role`, `category`, `categoryLabel`, `countsTowardPartySize` and `linkRule` on discovery/catalogue reads.
307
+ - **Buyer queue place & price targets (`@alytegen/sdk/browser`):** `watchCapabilities`, `createWatch`, `getWatch` and `observeWatch`, plus `watches[].waiting` on `AlyteMerchant.insights`.
308
+ - **Buyer-present bank challenge continuation (`@alytegen/sdk/browser` & webhooks):** `openChallenge`, `purchase`, `resumePurchase` and `cancelPurchase` (with `authenticationRetry` on `BuyerPurchaseState`, `awaiting_sca` on `BuyerWatch`, and `onWatchActionRequired` on `createWebhookHandler`; server-side buyer-present payment flags remain gated on deployment qualification).
309
+
310
+ SDK **0.7.0** added merchant-controlled early access: `accessRules` (`list`, `get`,
218
311
  `createDraft`, `updateDraft`, `preview`, `schedule`, `cancel`) and `memberships`
219
312
  (`createProgram`, `upsert`). **0.6.0** added inventory management: shared pools (`createPool`, `listPools`, `updatePool`),
220
313
  optional venue locations with pinned versions (`createLocation`, `listLocations`, `updateLocation`,
package/dist/agent.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type ClientOptions } from './http.js';
2
2
  import type { ConfirmOutcome, DiscoveredEvent, Hold, Merchant, Quote, Scheme } from './types.js';
3
+ import { type BasketQuote, type ConfirmReservationInput, type ConfirmReservationOutcome, type Reservation, type ReserveBasketInput } from './baskets.js';
3
4
  /**
4
5
  * Agent buy-path client — the discover → quote → hold → confirm flow, with an
5
6
  * agent JWT (`catalog:read` / `payments:write` scopes).
@@ -43,7 +44,8 @@ export declare class AlyteAgent {
43
44
  /**
44
45
  * Pay the locked quote and confirm the hold. Pass a stable `idempotencyKey`
45
46
  * per purchase intent so retries can NEVER double-charge. Outcomes:
46
- * `settled` · `sca_required` (resume via `resolveSca`) · a thrown
47
+ * `settled` · `sca_required` (purchaseId → buyer openChallenge; legacy mock
48
+ * continueToken → resolveSca) · a thrown
47
49
  * AlyteApiError on refusal (stable `code`, e.g. spend-cap or scheme refusals).
48
50
  */
49
51
  confirm(holdId: string, input: {
@@ -54,8 +56,30 @@ export declare class AlyteAgent {
54
56
  }, opts?: {
55
57
  idempotencyKey?: string;
56
58
  }): Promise<ConfirmOutcome>;
57
- /** Resolve a pending SCA challenge (bound to the creating agent) and resume. */
59
+ /** Legacy mock challenge only. A durable purchaseId must be completed by the buyer
60
+ * through openChallenge; a caller-supplied outcome cannot authenticate a real payment. */
58
61
  resolveSca(continueToken: string, outcome: 'approved' | 'failed'): Promise<ConfirmOutcome>;
62
+ /** Hold all basket lines atomically. The server checks links, party size and add-on
63
+ * permission across the entire basket. This call does not charge or auto-retry. */
64
+ reserveBasket(input: ReserveBasketInput): Promise<Reservation>;
65
+ /** Read the current basket and every line, including any reconciliation state. Requires payments:read. */
66
+ getReservation(reservationId: string): Promise<Reservation>;
67
+ /** Lock one total for all held lines; the response retains each line's price. */
68
+ quoteReservation(reservationId: string): Promise<BasketQuote>;
69
+ /** Confirm the entire basket as one payment. Persist and reuse the same
70
+ * idempotency key and inputs after a lost response; never create a new purchase
71
+ * to retry an uncertain result. HTTP 402 basket outcomes are returned intact. */
72
+ confirmReservation(reservationId: string, input: ConfirmReservationInput, opts?: {
73
+ idempotencyKey?: string;
74
+ }): Promise<ConfirmReservationOutcome>;
75
+ /** Release every line early. The server refuses release while payment is in flight. */
76
+ releaseReservation(reservationId: string): Promise<{
77
+ ok: true;
78
+ }>;
79
+ /** Legacy mock basket challenge only, bound to its creating principal. A durable
80
+ * purchaseId uses buyer openChallenge, never this caller-supplied outcome. */
81
+ resolveBasketSca(continueToken: string, outcome: 'approved' | 'failed'): Promise<ConfirmReservationOutcome>;
82
+ private reservationOutcome;
59
83
  /** Vaulted payment instruments this agent may spend from (opaque tokens only). */
60
84
  listInstruments(): Promise<{
61
85
  instruments: Array<{
package/dist/agent.js CHANGED
@@ -1,4 +1,5 @@
1
- import { Transport } from './http.js';
1
+ import { AlyteApiError, Transport } from './http.js';
2
+ import { isReservationRefusal } from './baskets.js';
2
3
  /**
3
4
  * Agent buy-path client — the discover → quote → hold → confirm flow, with an
4
5
  * agent JWT (`catalog:read` / `payments:write` scopes).
@@ -39,16 +40,57 @@ export class AlyteAgent {
39
40
  /**
40
41
  * Pay the locked quote and confirm the hold. Pass a stable `idempotencyKey`
41
42
  * per purchase intent so retries can NEVER double-charge. Outcomes:
42
- * `settled` · `sca_required` (resume via `resolveSca`) · a thrown
43
+ * `settled` · `sca_required` (purchaseId → buyer openChallenge; legacy mock
44
+ * continueToken → resolveSca) · a thrown
43
45
  * AlyteApiError on refusal (stable `code`, e.g. spend-cap or scheme refusals).
44
46
  */
45
47
  confirm(holdId, input, opts) {
46
48
  return this.t.request('POST', `/v1/holds/${encodeURIComponent(holdId)}/confirm`, input, opts?.idempotencyKey ? { 'idempotency-key': opts.idempotencyKey } : undefined);
47
49
  }
48
- /** Resolve a pending SCA challenge (bound to the creating agent) and resume. */
50
+ /** Legacy mock challenge only. A durable purchaseId must be completed by the buyer
51
+ * through openChallenge; a caller-supplied outcome cannot authenticate a real payment. */
49
52
  resolveSca(continueToken, outcome) {
50
53
  return this.t.request('POST', `/v1/sca/${encodeURIComponent(continueToken)}/resolve`, { outcome });
51
54
  }
55
+ /** Hold all basket lines atomically. The server checks links, party size and add-on
56
+ * permission across the entire basket. This call does not charge or auto-retry. */
57
+ reserveBasket(input) {
58
+ return this.t.request('POST', '/v1/reservations', input);
59
+ }
60
+ /** Read the current basket and every line, including any reconciliation state. Requires payments:read. */
61
+ getReservation(reservationId) {
62
+ return this.t.request('GET', `/v1/reservations/${encodeURIComponent(reservationId)}`);
63
+ }
64
+ /** Lock one total for all held lines; the response retains each line's price. */
65
+ quoteReservation(reservationId) {
66
+ return this.t.request('POST', `/v1/reservations/${encodeURIComponent(reservationId)}/quotes`, {});
67
+ }
68
+ /** Confirm the entire basket as one payment. Persist and reuse the same
69
+ * idempotency key and inputs after a lost response; never create a new purchase
70
+ * to retry an uncertain result. HTTP 402 basket outcomes are returned intact. */
71
+ confirmReservation(reservationId, input, opts) {
72
+ return this.reservationOutcome(`/v1/reservations/${encodeURIComponent(reservationId)}/confirm`, input, opts?.idempotencyKey ? { 'idempotency-key': opts.idempotencyKey } : undefined);
73
+ }
74
+ /** Release every line early. The server refuses release while payment is in flight. */
75
+ releaseReservation(reservationId) {
76
+ return this.t.request('DELETE', `/v1/reservations/${encodeURIComponent(reservationId)}`);
77
+ }
78
+ /** Legacy mock basket challenge only, bound to its creating principal. A durable
79
+ * purchaseId uses buyer openChallenge, never this caller-supplied outcome. */
80
+ resolveBasketSca(continueToken, outcome) {
81
+ return this.reservationOutcome(`/v1/reservations/sca/${encodeURIComponent(continueToken)}/resolve`, { outcome });
82
+ }
83
+ async reservationOutcome(path, input, headers) {
84
+ try {
85
+ return await this.t.request('POST', path, input, headers);
86
+ }
87
+ catch (error) {
88
+ if (error instanceof AlyteApiError && error.status === 402 && error.code === 'http_402'
89
+ && isReservationRefusal(error.details))
90
+ return error.details;
91
+ throw error;
92
+ }
93
+ }
52
94
  /** Vaulted payment instruments this agent may spend from (opaque tokens only). */
53
95
  listInstruments() {
54
96
  return this.t.request('GET', '/v1/instruments');
@@ -0,0 +1,86 @@
1
+ import type { Hold, PaymentResult, Quote, Scheme } from './types.js';
2
+ /** One requested tier in an all-or-nothing basket. Repeated tiers are merged by the server. */
3
+ export interface BasketLineInput {
4
+ tierId: string;
5
+ /** Whole units, 1..999 per submitted line. Partial fills are not supported. */
6
+ quantity: number;
7
+ }
8
+ export interface ReserveBasketInput {
9
+ /** 1..20 lines from one merchant, in one currency. */
10
+ lines: BasketLineInput[];
11
+ scheme?: Scheme;
12
+ geo?: string;
13
+ }
14
+ export type ReservationStatus = 'held' | 'confirmed' | 'released' | 'expired' | 'reconcile';
15
+ /** A reservation line is a hold; reconcile protects stock while a payment is uncertain. */
16
+ export interface ReservationLine extends Omit<Hold, 'status'> {
17
+ tenantId: string;
18
+ reservationId?: string;
19
+ status: ReservationStatus;
20
+ confirmToken?: string;
21
+ }
22
+ export interface Reservation {
23
+ id: string;
24
+ tenantId: string;
25
+ merchantId: string;
26
+ /** Derived from the lines, including reconciliation protection. */
27
+ status: ReservationStatus;
28
+ lines: ReservationLine[];
29
+ /** Original number of lines; fewer remaining lines means an incomplete basket. */
30
+ lineCount?: number;
31
+ expiresAt: string;
32
+ createdAt: string;
33
+ confirmToken?: string;
34
+ }
35
+ export interface BasketQuoteLine {
36
+ lineNo: number;
37
+ tierId: string;
38
+ holdId?: string;
39
+ quantity: number;
40
+ unitPriceMinor: number;
41
+ subtotalMinor: number;
42
+ }
43
+ /** One locked total, with per-line prices. A basket has no single unit price or tier ID. */
44
+ export interface BasketQuote extends Omit<Quote, 'tierId' | 'unitPriceMinor'> {
45
+ reservationId: string;
46
+ lines: BasketQuoteLine[];
47
+ }
48
+ /** The server derives the amount and authority from the quote and authenticated principal. */
49
+ export interface ConfirmReservationInput {
50
+ quoteId: string;
51
+ instrumentToken: string;
52
+ scheme: Scheme;
53
+ geo: string;
54
+ }
55
+ /** Fulfil only a settled/authorized result with confirmed inventory. An error result
56
+ * with reconcile inventory is uncertain, not a known decline or permission to re-charge. */
57
+ export type ConfirmReservationOutcome = {
58
+ status: 'settled';
59
+ result: PaymentResult;
60
+ reservationStatus: string;
61
+ reservation?: Reservation;
62
+ } | {
63
+ status: 'payment_pending';
64
+ result: PaymentResult;
65
+ reservationStatus: string;
66
+ } | {
67
+ status: 'sca_required';
68
+ purchaseId: string;
69
+ challenge: {
70
+ expiresAt: string;
71
+ };
72
+ reservationStatus: 'reconcile';
73
+ } | {
74
+ status: 'sca_required';
75
+ challenge: {
76
+ continueToken: string;
77
+ [k: string]: unknown;
78
+ };
79
+ reservationStatus: 'held';
80
+ } | {
81
+ status: 'sca_failed';
82
+ reservationStatus: 'released';
83
+ };
84
+ /** REST deliberately sends completed refusals and uncertain outcomes as HTTP 402.
85
+ * Only recognize that documented union; ordinary error envelopes still throw. */
86
+ export declare function isReservationRefusal(value: unknown): value is ConfirmReservationOutcome;
@@ -0,0 +1,13 @@
1
+ /** REST deliberately sends completed refusals and uncertain outcomes as HTTP 402.
2
+ * Only recognize that documented union; ordinary error envelopes still throw. */
3
+ export function isReservationRefusal(value) {
4
+ if (!value || typeof value !== 'object')
5
+ return false;
6
+ const body = value;
7
+ if (body.status === 'sca_failed')
8
+ return body.reservationStatus === 'released';
9
+ if (body.status !== 'settled' || typeof body.reservationStatus !== 'string' || !body.result || typeof body.result !== 'object')
10
+ return false;
11
+ const result = body.result;
12
+ return typeof result.intentId === 'string' && (result.status === 'declined' || result.status === 'error');
13
+ }
package/dist/browser.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { DiscoveredEvent, Scheme } from './types.js';
1
+ import type { DiscoveredEvent, PaymentResult, Scheme } from './types.js';
2
2
  export { AlyteApiError } from './http.js';
3
3
  export interface BuyerConnection {
4
4
  bearer: string;
@@ -54,11 +54,78 @@ export interface BuyerWatch {
54
54
  merchantId: string;
55
55
  tierId: string;
56
56
  quantity: number;
57
- status: 'queued' | 'paused' | 'firing' | 'fired' | 'failed' | 'cancelled' | 'expired';
58
- result?: Record<string, unknown>;
57
+ status: 'queued' | 'paused' | 'firing' | 'awaiting_sca' | 'fired' | 'failed' | 'cancelled' | 'expired';
58
+ result?: BuyerWatchResult;
59
59
  expiresAt?: string;
60
60
  createdAt: string;
61
61
  firedAt?: string;
62
+ /** Absent on legacy watches and older servers: treat as availability. */
63
+ conditionSpec?: WatchCondition;
64
+ /** Server-computed place in line. Absent on older servers = unavailable, never position zero. */
65
+ queue?: WatchQueueSnapshot;
66
+ }
67
+ /** A pending purchase keeps its original identity; openChallenge never buys or requeues it. */
68
+ export type BuyerWatchResult = Record<string, unknown> & {
69
+ status?: string;
70
+ purchaseId?: string;
71
+ challenge?: {
72
+ expiresAt: string;
73
+ };
74
+ code?: string;
75
+ };
76
+ export type WatchCondition = {
77
+ kind: 'available';
78
+ } | {
79
+ kind: 'price_at_or_below';
80
+ maxChargeMinor: number;
81
+ currency: 'EUR' | 'GBP' | 'USD';
82
+ };
83
+ /** Unknown future values must render as a generic waiting state. */
84
+ export type WatchWaitingReason = 'access_window' | 'price_target' | 'stock' | 'whole_party' | (string & {});
85
+ export type QueuePlace = {
86
+ kind: 'assigned' | 'provisional';
87
+ position: number;
88
+ requestsAhead: number;
89
+ } | {
90
+ kind: 'unassigned';
91
+ reason: 'condition_not_met' | 'paused' | (string & {});
92
+ } | {
93
+ kind: 'not_waiting';
94
+ reason: 'processing' | 'reconciling' | 'terminal' | (string & {});
95
+ } | {
96
+ kind: 'unavailable';
97
+ };
98
+ export interface WatchQueueSnapshot {
99
+ schemaVersion: 1;
100
+ /** Decimal monotonic sequence — compare with BigInt, never Number. */
101
+ revision: string;
102
+ observedAt: string;
103
+ refreshAfterMs: number;
104
+ /** `phaseId` 'general' or 'rule:<id>' (an access window, labelled by the merchant); a place counts within its phase. */
105
+ queue: {
106
+ id: string;
107
+ label: string;
108
+ phaseId?: string;
109
+ phaseLabel?: string;
110
+ };
111
+ policyVersion: string;
112
+ place: QueuePlace;
113
+ waitingReason?: WatchWaitingReason;
114
+ nextEligibleAt?: string;
115
+ observedChargeMinor?: number;
116
+ }
117
+ export interface WatchInstruction {
118
+ /** Save the whole instruction (not the bearer) BEFORE sending; reuse this UUID after an uncertain response. */
119
+ requestId: string;
120
+ agentId: string;
121
+ request: {
122
+ kind: 'ticketing';
123
+ tierId: string;
124
+ quantity: number;
125
+ };
126
+ condition: WatchCondition;
127
+ /** ISO-8601 with an explicit offset, e.g. 2026-11-01T12:00:00Z. */
128
+ expiresAt: string;
62
129
  }
63
130
  export type BuyerPurchase = {
64
131
  status: 'settled' | 'pending';
@@ -69,10 +136,34 @@ export type BuyerPurchase = {
69
136
  agentName?: string;
70
137
  } | {
71
138
  status: 'sca_required';
139
+ purchaseId: string;
140
+ challenge: {
141
+ expiresAt: string;
142
+ };
143
+ } | {
144
+ status: 'sca_required';
145
+ purchaseId?: never;
146
+ challenge?: never;
147
+ } | {
148
+ status: 'pending';
149
+ purchaseId: string;
72
150
  } | {
73
151
  status: 'refused' | 'error';
74
152
  outcome: unknown;
75
153
  };
154
+ export type BuyerPurchaseStatus = 'pending' | 'sca_required' | 'settled' | 'refused' | 'cancelled' | 'expired';
155
+ export interface BuyerPurchaseState {
156
+ authenticationRetry?: boolean;
157
+ provider?: 'stripe' | 'adyen';
158
+ purchaseId: string;
159
+ status: BuyerPurchaseStatus;
160
+ chargeMinor?: number;
161
+ currency?: string;
162
+ challenge?: {
163
+ expiresAt: string;
164
+ };
165
+ result?: PaymentResult;
166
+ }
76
167
  export interface BuyerReceipt {
77
168
  intentId: string;
78
169
  status: 'settled' | 'pending' | 'refused';
@@ -126,6 +217,10 @@ export declare function createBuyerClient(opts: BuyerClientOptions): {
126
217
  quantity: number;
127
218
  attemptId: string;
128
219
  }) => Promise<BuyerPurchase>;
220
+ /** Recover this purchase; never start a new buy after an uncertain response or a challenge. */
221
+ purchase: (purchaseId: string) => Promise<BuyerPurchaseState>;
222
+ resumePurchase: (purchaseId: string) => Promise<BuyerPurchaseState>;
223
+ cancelPurchase: (purchaseId: string) => Promise<BuyerPurchaseState>;
129
224
  payment: (intentId: string) => Promise<BuyerReceipt>;
130
225
  watch: (input: {
131
226
  agentId: string;
@@ -138,6 +233,26 @@ export declare function createBuyerClient(opts: BuyerClientOptions): {
138
233
  cancelWatch: (watchId: string) => Promise<{
139
234
  watch: BuyerWatch;
140
235
  }>;
236
+ /** What this deployment enforces. Discovery only — the server still refuses anything unsupported. */
237
+ watchCapabilities: () => Promise<{
238
+ schemaVersion: 1;
239
+ requestKinds: string[];
240
+ conditions: string[];
241
+ queuePolicy: string;
242
+ }>;
243
+ /**
244
+ * Conditional watch on its own strict route. Never falls back to `watch()` (which would drop the
245
+ * condition) and never retries by itself: after an uncertain response, resend the SAME instruction.
246
+ */
247
+ createWatch: (input: WatchInstruction) => Promise<{
248
+ watch: BuyerWatch;
249
+ replayed: boolean;
250
+ }>;
251
+ getWatch: (watchId: string, init?: {
252
+ signal?: AbortSignal;
253
+ }) => Promise<{
254
+ watch: BuyerWatch;
255
+ }>;
141
256
  revokeMandate: (mandateId: string) => Promise<{
142
257
  ok: true;
143
258
  id: string;
@@ -145,6 +260,21 @@ export declare function createBuyerClient(opts: BuyerClientOptions): {
145
260
  }>;
146
261
  };
147
262
  export type BuyerClient = ReturnType<typeof createBuyerClient>;
263
+ export interface ObserveWatchOptions {
264
+ client: Pick<BuyerClient, 'getWatch'>;
265
+ watchId: string;
266
+ signal: AbortSignal;
267
+ onUpdate: (watch: BuyerWatch) => void;
268
+ /** A read failed; `last` is the last snapshot, now stale. Polling continues with backoff unless `stopped`. */
269
+ onError?: (error: unknown, last: BuyerWatch | undefined, stopped: boolean) => void;
270
+ }
271
+ /**
272
+ * Read-only polling of one watch: one request in flight, server-directed interval (bounded),
273
+ * bounded backoff on read failures, older revisions discarded, paused while the page is hidden.
274
+ * Stops on a terminal state, an authorization/not-found refusal, or abort. It never creates,
275
+ * cancels, pays or consents.
276
+ */
277
+ export declare function observeWatch(opts: ObserveWatchOptions): void;
148
278
  export interface ConsentTheme {
149
279
  accent?: string;
150
280
  background?: string;
@@ -181,3 +311,25 @@ export declare class AlyteConsentError extends Error {
181
311
  }
182
312
  /** Mount Alyte's isolated consent surface; the full verification credential never leaves it. */
183
313
  export declare function openConsent(opts: ConsentOptions): Promise<ConsentResult>;
314
+ export interface ChallengeStatus {
315
+ purchaseId: string;
316
+ status: BuyerPurchaseStatus;
317
+ }
318
+ export interface ChallengeResult extends ChallengeStatus {
319
+ status: 'settled' | 'refused' | 'cancelled' | 'expired';
320
+ }
321
+ export interface ChallengeOptions extends Omit<ConsentOptions, 'tierId' | 'quantity'> {
322
+ purchaseId: string;
323
+ /** Safe status only. Provider action material never leaves the Alyte frame. */
324
+ onStatus?: (state: ChallengeStatus) => void;
325
+ }
326
+ export declare class AlyteChallengeError extends Error {
327
+ readonly code: string;
328
+ constructor(code: string);
329
+ }
330
+ /**
331
+ * Complete an existing purchase in Alyte's isolated frame. No buy, purchase key,
332
+ * payment details or caller-supplied approval is sent. Aborting closes only the
333
+ * frame; the server purchase remains recoverable until its verified outcome.
334
+ */
335
+ export declare function openChallenge(opts: ChallengeOptions): Promise<ChallengeResult>;
package/dist/browser.js CHANGED
@@ -10,8 +10,8 @@ function baseOrigin(value) {
10
10
  return url.origin;
11
11
  }
12
12
  /** HTTP errors retain the server taxonomy; no request is automatically retried. */
13
- async function request(fetcher, base, path, method, bearer, body) {
14
- const res = await fetcher(base + path, { method, credentials: 'omit', redirect: 'error', cache: 'no-store',
13
+ async function request(fetcher, base, path, method, bearer, body, signal) {
14
+ const res = await fetcher(base + path, { method, credentials: 'omit', redirect: 'error', cache: 'no-store', signal,
15
15
  headers: { ...(bearer ? { authorization: `Bearer ${bearer}` } : {}), ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },
16
16
  body: body === undefined ? undefined : JSON.stringify(body),
17
17
  });
@@ -33,7 +33,7 @@ export function createBuyerClient(opts) {
33
33
  const base = baseOrigin(opts.baseUrl), fetcher = opts.fetch ?? globalThis.fetch;
34
34
  if (typeof opts.bearer !== 'string' || !opts.bearer)
35
35
  throw new TypeError('bearer is required');
36
- const call = (method, path, body) => request(fetcher, base, '/v1/buyer' + path, method, opts.bearer, body);
36
+ const call = (method, path, body, signal) => request(fetcher, base, '/v1/buyer' + path, method, opts.bearer, body, signal);
37
37
  return {
38
38
  me: () => call('GET', '/me'),
39
39
  catalog: () => call('GET', '/catalog'),
@@ -47,12 +47,98 @@ export function createBuyerClient(opts) {
47
47
  throw new TypeError('A saved UUID attemptId is required');
48
48
  return call('POST', `/agents/${encodeURIComponent(input.agentId)}/buy`, { tierId: input.tierId, quantity: input.quantity, attemptId: input.attemptId });
49
49
  },
50
+ /** Recover this purchase; never start a new buy after an uncertain response or a challenge. */
51
+ purchase: (purchaseId) => call('GET', `/purchases/${encodeURIComponent(purchaseId)}`),
52
+ resumePurchase: (purchaseId) => call('POST', `/purchases/${encodeURIComponent(purchaseId)}/resume`, {}),
53
+ cancelPurchase: (purchaseId) => call('POST', `/purchases/${encodeURIComponent(purchaseId)}/cancel`, {}),
50
54
  payment: (intentId) => call('GET', `/payments/${encodeURIComponent(intentId)}`),
51
55
  watch: (input) => call('POST', '/watches', input),
52
56
  cancelWatch: (watchId) => call('DELETE', `/watches/${encodeURIComponent(watchId)}`),
57
+ /** What this deployment enforces. Discovery only — the server still refuses anything unsupported. */
58
+ watchCapabilities: () => call('GET', '/watch-capabilities'),
59
+ /**
60
+ * Conditional watch on its own strict route. Never falls back to `watch()` (which would drop the
61
+ * condition) and never retries by itself: after an uncertain response, resend the SAME instruction.
62
+ */
63
+ createWatch: (input) => {
64
+ if (typeof input.requestId !== 'string' || !UUID.test(input.requestId))
65
+ throw new TypeError('A saved UUID requestId is required');
66
+ if (input.condition?.kind === 'price_at_or_below' && !Number.isSafeInteger(input.condition.maxChargeMinor))
67
+ throw new TypeError('maxChargeMinor must be an integer in minor units');
68
+ return call('POST', '/watch-requests', input);
69
+ },
70
+ getWatch: (watchId, init) => call('GET', `/watches/${encodeURIComponent(watchId)}`, undefined, init?.signal),
53
71
  revokeMandate: (mandateId) => call('DELETE', `/mandates/${encodeURIComponent(mandateId)}`),
54
72
  };
55
73
  }
74
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
75
+ const MIN_POLL_MS = 2000, MAX_POLL_MS = 60_000;
76
+ /**
77
+ * Read-only polling of one watch: one request in flight, server-directed interval (bounded),
78
+ * bounded backoff on read failures, older revisions discarded, paused while the page is hidden.
79
+ * Stops on a terminal state, an authorization/not-found refusal, or abort. It never creates,
80
+ * cancels, pays or consents.
81
+ */
82
+ export function observeWatch(opts) {
83
+ let last, failures = 0, timer, inFlight = false;
84
+ const doc = globalThis.document;
85
+ const stop = () => { if (timer)
86
+ clearTimeout(timer); doc?.removeEventListener('visibilitychange', onVisible); };
87
+ const schedule = (ms) => { if (timer)
88
+ clearTimeout(timer); if (!opts.signal.aborted)
89
+ timer = setTimeout(tick, Math.min(MAX_POLL_MS, Math.max(MIN_POLL_MS, ms))); };
90
+ const onVisible = () => {
91
+ if (doc?.visibilityState !== 'visible' || opts.signal.aborted || inFlight)
92
+ return; // one request in flight, ever
93
+ if (timer)
94
+ clearTimeout(timer);
95
+ timer = undefined;
96
+ void tick();
97
+ };
98
+ async function tick() {
99
+ timer = undefined;
100
+ if (opts.signal.aborted)
101
+ return stop();
102
+ if (inFlight)
103
+ return;
104
+ if (doc?.visibilityState === 'hidden')
105
+ return; // resumes on visibilitychange
106
+ inFlight = true;
107
+ try {
108
+ const { watch } = await opts.client.getWatch(opts.watchId, { signal: opts.signal });
109
+ failures = 0;
110
+ const older = last?.queue && watch.queue && BigInt(watch.queue.revision) < BigInt(last.queue.revision);
111
+ if (!older) {
112
+ last = watch;
113
+ opts.onUpdate(watch);
114
+ }
115
+ const current = last;
116
+ const finished = current.queue
117
+ ? current.queue.place.kind === 'not_waiting' && current.queue.place.reason === 'terminal'
118
+ : ['fired', 'failed', 'cancelled', 'expired'].includes(current.status); // older server: no snapshot
119
+ if (finished)
120
+ return stop();
121
+ schedule(current.queue?.refreshAfterMs ?? 5000);
122
+ }
123
+ catch (error) {
124
+ if (opts.signal.aborted)
125
+ return stop();
126
+ const status = error instanceof AlyteApiError ? error.status : 0;
127
+ const fatal = status === 401 || status === 403 || status === 404;
128
+ opts.onError?.(error, last, fatal);
129
+ if (fatal)
130
+ return stop();
131
+ failures++;
132
+ schedule(MIN_POLL_MS * 2 ** Math.min(failures, 5));
133
+ }
134
+ finally {
135
+ inFlight = false;
136
+ }
137
+ }
138
+ opts.signal.addEventListener('abort', stop, { once: true });
139
+ doc?.addEventListener('visibilitychange', onVisible);
140
+ void tick();
141
+ }
56
142
  export class AlyteConsentError extends Error {
57
143
  code;
58
144
  constructor(code) {
@@ -157,3 +243,110 @@ export function openConsent(opts) {
157
243
  opts.container.append(iframe);
158
244
  });
159
245
  }
246
+ export class AlyteChallengeError extends Error {
247
+ code;
248
+ constructor(code) {
249
+ super(`Alyte challenge: ${code}`);
250
+ this.code = code;
251
+ this.name = 'AlyteChallengeError';
252
+ }
253
+ }
254
+ /**
255
+ * Complete an existing purchase in Alyte's isolated frame. No buy, purchase key,
256
+ * payment details or caller-supplied approval is sent. Aborting closes only the
257
+ * frame; the server purchase remains recoverable until its verified outcome.
258
+ */
259
+ export function openChallenge(opts) {
260
+ const base = baseOrigin(opts.baseUrl);
261
+ if (!opts.merchantId || !opts.bearer)
262
+ throw new TypeError('merchantId and bearer are required');
263
+ if (typeof opts.purchaseId !== 'string' || !opts.purchaseId || opts.purchaseId.length > 512)
264
+ throw new TypeError('purchaseId is required');
265
+ const doc = opts.container.ownerDocument, host = doc.defaultView;
266
+ if (!host)
267
+ throw new TypeError('container must belong to a browser document');
268
+ if (opts.readyTimeoutMs !== undefined && (!Number.isFinite(opts.readyTimeoutMs) || opts.readyTimeoutMs <= 0))
269
+ throw new TypeError('readyTimeoutMs must be positive');
270
+ const url = new URL(`/shop/${encodeURIComponent(opts.merchantId)}/authorize`, base);
271
+ url.searchParams.set('view', 'challenge');
272
+ url.searchParams.set('embed', '1');
273
+ url.searchParams.set('purchase', opts.purchaseId);
274
+ if (opts.lang)
275
+ url.searchParams.set('lang', opts.lang);
276
+ if (opts.returnUrl) {
277
+ const back = new URL(opts.returnUrl);
278
+ if (back.origin !== host.location.origin)
279
+ throw new TypeError('returnUrl must belong to the host origin');
280
+ url.searchParams.set('return', back.href);
281
+ }
282
+ for (const key of ['accent', 'background', 'surface', 'text', 'font', 'radius', 'scheme']) {
283
+ const value = opts.theme?.[key];
284
+ if ((typeof value === 'string' || typeof value === 'number') && String(value).length <= 64)
285
+ url.searchParams.set(key, String(value));
286
+ }
287
+ const statuses = ['pending', 'sca_required', 'settled', 'refused', 'cancelled', 'expired'];
288
+ return new Promise((resolve, reject) => {
289
+ const iframe = doc.createElement('iframe');
290
+ iframe.title = 'Alyte bank authentication';
291
+ iframe.src = url.href;
292
+ iframe.referrerPolicy = 'no-referrer';
293
+ iframe.style.width = '100%';
294
+ iframe.style.height = '640px';
295
+ iframe.style.border = '0';
296
+ let done = false, ready = false;
297
+ let timer;
298
+ const cleanup = () => { clearTimeout(timer); host.removeEventListener('message', receive); opts.signal?.removeEventListener('abort', abort); iframe.remove(); };
299
+ const fail = (code) => { if (!done) {
300
+ done = true;
301
+ cleanup();
302
+ reject(new AlyteChallengeError(code));
303
+ } };
304
+ const abort = () => fail('challenge_closed');
305
+ const receive = (event) => {
306
+ if (done || event.origin !== base || event.source !== iframe.contentWindow)
307
+ return;
308
+ const data = event.data;
309
+ if (!data || data.type !== 'alyte:challenge' || data.merchantId !== opts.merchantId || data.purchaseId !== opts.purchaseId)
310
+ return;
311
+ if (data.event === 'ready') {
312
+ ready = true;
313
+ clearTimeout(timer);
314
+ iframe.contentWindow?.postMessage({ type: 'alyte:challenge', event: 'bootstrap', purchaseId: opts.purchaseId, bearer: opts.bearer }, base);
315
+ }
316
+ else if (data.event === 'status' && ready && statuses.includes(data.status)) {
317
+ // Copy only this allowlist. Neither unexpected fields nor result payloads
318
+ // from a future frame version become a merchant callback or receipt.
319
+ const state = { purchaseId: opts.purchaseId, status: data.status };
320
+ if (state.status !== 'pending' && state.status !== 'sca_required') {
321
+ done = true;
322
+ cleanup();
323
+ resolve(state);
324
+ }
325
+ opts.onStatus?.(state);
326
+ }
327
+ else if (data.event === 'error') {
328
+ fail(data.code === 'unauthorized' ? 'unauthorized' : 'challenge_unavailable');
329
+ }
330
+ else if (data.event === 'resize' && Number.isFinite(data.height)) {
331
+ iframe.style.height = `${Math.max(240, Math.min(1200, Math.ceil(data.height)))}px`;
332
+ }
333
+ else if (data.event === 'navigate' && typeof data.url === 'string') {
334
+ try {
335
+ const back = new URL(data.url);
336
+ if (back.origin === host.location.origin)
337
+ opts.onNavigate?.(back.href);
338
+ }
339
+ catch { /* Ignore malformed navigation messages. */ }
340
+ }
341
+ };
342
+ if (opts.signal?.aborted) {
343
+ abort();
344
+ return;
345
+ }
346
+ host.addEventListener('message', receive);
347
+ opts.signal?.addEventListener('abort', abort, { once: true });
348
+ timer = setTimeout(() => fail('challenge_unavailable'), opts.readyTimeoutMs ?? 15_000);
349
+ iframe.addEventListener('error', () => fail('challenge_unavailable'), { once: true });
350
+ opts.container.append(iframe);
351
+ });
352
+ }
package/dist/index.d.ts CHANGED
@@ -2,6 +2,6 @@ export { AlyteMerchant } from './merchant.js';
2
2
  export { AlyteAgent } from './agent.js';
3
3
  export { AlyteApiError, type ClientOptions } from './http.js';
4
4
  export { verifyWebhookSignature } from './webhookVerify.js';
5
- export { handleWebhook, createWebhookHandler, type AlyteEventEnvelope, type PaymentSettled, type WatchFailed, type WebhookTest, type PurchaseHandlers, type OnPurchaseOptions, type WebhookResult, } from './onPurchase.js';
5
+ export { handleWebhook, createWebhookHandler, type AlyteEventEnvelope, type PaymentSettled, type WatchFailed, type WatchActionRequired, type WebhookTest, type PurchaseHandlers, type OnPurchaseOptions, type WebhookResult, } from './onPurchase.js';
6
6
  export type * from './types.js';
7
7
  export type { AccessAudience, AccessDraftInput, AccessRule, AccessPreview, AccessCommitInput, MembershipProgram, MembershipEvidence } from './access.js';
@@ -5,6 +5,8 @@ export interface InventoryPool {
5
5
  tenantId: string;
6
6
  merchantId: string;
7
7
  eventId?: string;
8
+ /** The integrator's stable id (per tenant), when the pool was created with one. */
9
+ externalRef?: string;
8
10
  title: string;
9
11
  capacity: number;
10
12
  availableCount: number;
@@ -1,6 +1,6 @@
1
1
  import { type ClientOptions } from './http.js';
2
2
  import { MerchantAccessRules, MerchantMemberships } from './access.js';
3
- import type { BuyerSessionMint, CatalogMerchant, Merchant, EventItem, MerchantPspLink, Tier, TierKind, FeeBearer, Scheme, PaymentRow, WebhookEndpoint, MerchantInsights, InventoryCatalog, InventoryLocation, InventoryLocationBinding, InventoryOccurrence, InventoryPool } from './types.js';
3
+ import type { BuyerSessionMint, CatalogMerchant, Merchant, EventItem, MerchantPspLink, Tier, TierKind, FeeBearer, Scheme, PaymentRow, WebhookEndpoint, MerchantInsights, InventoryCatalog, InventoryLocation, InventoryLocationBinding, InventoryOccurrence, InventoryPool, PurchaseLimit, PurchaseLimitReadiness, SetPurchaseLimitInput } from './types.js';
4
4
  /**
5
5
  * Merchant integration client — drives the `/v1/integration/*` surface with a
6
6
  * console-minted API token (`merchant:read` / `merchant:write` scopes; `merchant:admin` for
@@ -99,6 +99,31 @@ export declare class AlyteMerchant {
99
99
  deleteEvent(eventId: string): Promise<{
100
100
  ok: boolean;
101
101
  }>;
102
+ /**
103
+ * Set or replace the per-customer ticket limit for an event (`merchant:write`).
104
+ * `maxPerCustomer` (`1..1000`) caps the tickets one customer can hold or buy;
105
+ * `maxHeldPerCustomer` optionally caps unpaid tickets held at once;
106
+ * `countWaitingWatches` decides whether queued purchases count while waiting.
107
+ * PUT replaces the whole limit, and the first PUT counts the event's earlier sales.
108
+ */
109
+ setEventPurchaseLimit(eventId: string, input: SetPurchaseLimitInput): Promise<{
110
+ purchaseLimit: PurchaseLimit;
111
+ readiness: PurchaseLimitReadiness;
112
+ }>;
113
+ /**
114
+ * Read an event's per-customer ticket limit (`null` when it has none) and how many
115
+ * of its tickets the limit can count against a customer (`merchant:read`).
116
+ */
117
+ getEventPurchaseLimit(eventId: string): Promise<{
118
+ purchaseLimit: PurchaseLimit | null;
119
+ readiness: PurchaseLimitReadiness;
120
+ }>;
121
+ /**
122
+ * Remove an event's per-customer ticket limit (`merchant:write`).
123
+ */
124
+ clearEventPurchaseLimit(eventId: string): Promise<{
125
+ cleared: boolean;
126
+ }>;
102
127
  /** Observed stock and base prices for one shop; not a reserved or quoted offer.
103
128
  * Read scope does not grant writes. A read/write key can also manage this inventory.
104
129
  * Fails with catalog_too_large if any source relation exceeds 2,000 rows. */
@@ -129,13 +154,17 @@ export declare class AlyteMerchant {
129
154
  setSlotLocation(merchantId: string, slotId: string, input: InventoryLocationBinding): Promise<{
130
155
  slot: InventoryOccurrence;
131
156
  }>;
157
+ /** Create a shared pool. With `externalRef` (your stable id, unique per tenant) the create is
158
+ * idempotent: a repeat returns the existing pool untouched with `existing: true`. */
132
159
  createPool(input: {
133
160
  merchantId: string;
134
161
  eventId?: string | null;
135
162
  title: string;
136
163
  capacity: number;
164
+ externalRef?: string;
137
165
  }): Promise<{
138
166
  pool: InventoryPool;
167
+ existing?: boolean;
139
168
  }>;
140
169
  listPools(merchantId: string): Promise<{
141
170
  pools: InventoryPool[];
package/dist/merchant.js CHANGED
@@ -54,6 +54,29 @@ export class AlyteMerchant {
54
54
  deleteEvent(eventId) {
55
55
  return this.t.request('DELETE', `/v1/integration/events/${encodeURIComponent(eventId)}`);
56
56
  }
57
+ /**
58
+ * Set or replace the per-customer ticket limit for an event (`merchant:write`).
59
+ * `maxPerCustomer` (`1..1000`) caps the tickets one customer can hold or buy;
60
+ * `maxHeldPerCustomer` optionally caps unpaid tickets held at once;
61
+ * `countWaitingWatches` decides whether queued purchases count while waiting.
62
+ * PUT replaces the whole limit, and the first PUT counts the event's earlier sales.
63
+ */
64
+ setEventPurchaseLimit(eventId, input) {
65
+ return this.t.request('PUT', `/v1/integration/events/${encodeURIComponent(eventId)}/purchase-limit`, input);
66
+ }
67
+ /**
68
+ * Read an event's per-customer ticket limit (`null` when it has none) and how many
69
+ * of its tickets the limit can count against a customer (`merchant:read`).
70
+ */
71
+ getEventPurchaseLimit(eventId) {
72
+ return this.t.request('GET', `/v1/integration/events/${encodeURIComponent(eventId)}/purchase-limit`);
73
+ }
74
+ /**
75
+ * Remove an event's per-customer ticket limit (`merchant:write`).
76
+ */
77
+ clearEventPurchaseLimit(eventId) {
78
+ return this.t.request('DELETE', `/v1/integration/events/${encodeURIComponent(eventId)}/purchase-limit`);
79
+ }
57
80
  /** Observed stock and base prices for one shop; not a reserved or quoted offer.
58
81
  * Read scope does not grant writes. A read/write key can also manage this inventory.
59
82
  * Fails with catalog_too_large if any source relation exceeds 2,000 rows. */
@@ -77,6 +100,8 @@ export class AlyteMerchant {
77
100
  setSlotLocation(merchantId, slotId, input) {
78
101
  return this.t.request('PUT', `/v1/integration/merchants/${encodeURIComponent(merchantId)}/slots/${encodeURIComponent(slotId)}/location`, input);
79
102
  }
103
+ /** Create a shared pool. With `externalRef` (your stable id, unique per tenant) the create is
104
+ * idempotent: a repeat returns the existing pool untouched with `existing: true`. */
80
105
  createPool(input) {
81
106
  return this.t.request('POST', '/v1/integration/pools', input);
82
107
  }
@@ -13,6 +13,8 @@ export interface AlyteEventEnvelope<T = unknown> {
13
13
  }
14
14
  /** A purchase that authorized and captured. Fulfil on `tierId` + `quantity`. */
15
15
  export interface PaymentSettled {
16
+ /** Verified purchase facts when the PSP reports them; not a liability-shift assertion. */
17
+ authentication?: import('./types.js').PurchaseAuthentication;
16
18
  intentId: string;
17
19
  merchantId: string;
18
20
  /** Integer minor units. NEVER a float — see formatMinor for display. */
@@ -45,6 +47,18 @@ export interface WatchFailed {
45
47
  };
46
48
  failedAt: string;
47
49
  }
50
+ /** Relay to the merchant's buyer before the deadline. This event grants no authority and is not fulfilment. */
51
+ export interface WatchActionRequired {
52
+ tenantId: string;
53
+ merchantId: string;
54
+ buyerRef: string;
55
+ watchId: string;
56
+ purchaseId: string;
57
+ deadline: string;
58
+ agentId?: string;
59
+ tierId?: string;
60
+ quantity?: number;
61
+ }
48
62
  /** A signed delivery carrying no payment data. NEVER fulfil on this. */
49
63
  export interface WebhookTest {
50
64
  [key: string]: unknown;
@@ -54,6 +68,8 @@ export interface PurchaseHandlers {
54
68
  onSettled?: (data: PaymentSettled, event: AlyteEventEnvelope<PaymentSettled>) => Promise<void> | void;
55
69
  /** A queued purchase terminally refused. Tell the buyer why. */
56
70
  onWatchFailed?: (data: WatchFailed, event: AlyteEventEnvelope<WatchFailed>) => Promise<void> | void;
71
+ /** The merchant owns buyer outreach. Deduplicate by eventId; do not buy again or fulfil. */
72
+ onWatchActionRequired?: (data: WatchActionRequired, event: AlyteEventEnvelope<WatchActionRequired>) => Promise<void> | void;
57
73
  /** A test delivery — use it to prove your signature check works. */
58
74
  onTest?: (event: AlyteEventEnvelope<WebhookTest>) => Promise<void> | void;
59
75
  /** Any event type this SDK version does not know. Default: ignored. */
@@ -62,6 +62,9 @@ export async function handleWebhook(rawBody, signatureHeader, handlers, options)
62
62
  case 'watch.failed':
63
63
  await handlers.onWatchFailed?.(event.data, event);
64
64
  break;
65
+ case 'watch.action_required':
66
+ await handlers.onWatchActionRequired?.(event.data, event);
67
+ break;
65
68
  case 'webhook.test':
66
69
  await handlers.onTest?.(event);
67
70
  break;
package/dist/types.d.ts CHANGED
@@ -6,6 +6,19 @@ export type Scheme = 'visa' | 'mastercard' | 'amex';
6
6
  export type TierKind = 'general' | 'seated';
7
7
  export type FeeBearer = 'buyer' | 'merchant';
8
8
  export type * from './inventoryTypes.js';
9
+ export type { BasketLineInput, ReserveBasketInput, ReservationStatus, ReservationLine, Reservation, BasketQuoteLine, BasketQuote, ConfirmReservationInput, ConfirmReservationOutcome } from './baskets.js';
10
+ export type TierRole = 'primary' | 'addon';
11
+ /** A server-enforced add-on rule. Qualifying parent tickets must be in the same event and basket. */
12
+ export interface TierLinkRule {
13
+ parentScope: 'any_primary_in_event' | 'specific_tiers';
14
+ parentTierIds?: string[];
15
+ scaling: 'per_basket' | 'per_parent_unit';
16
+ minQty?: number;
17
+ maxQty?: number;
18
+ minPerParent?: number;
19
+ maxPerParent?: number;
20
+ parentGroupSize?: number;
21
+ }
9
22
  export interface Merchant {
10
23
  id: string;
11
24
  name: string;
@@ -29,6 +42,35 @@ export interface EventItem {
29
42
  title: string;
30
43
  /** ISO-8601 start time. */
31
44
  startsAt: string;
45
+ /** Per-customer ticket limit on this event, when set. */
46
+ purchaseLimit?: {
47
+ maxPerCustomer: number;
48
+ maxHeldPerCustomer?: number;
49
+ };
50
+ }
51
+ /** Per-event customer ticket limit record (`GET/PUT /v1/integration/events/:id/purchase-limit`). */
52
+ export interface PurchaseLimit {
53
+ eventId: string;
54
+ merchantId: string;
55
+ maxPerCustomer: number;
56
+ maxHeldPerCustomer?: number;
57
+ /** Whether queued purchases count toward the limit while waiting; null when not chosen, which counts. */
58
+ countWaitingWatches: boolean | null;
59
+ revision: number;
60
+ updatedBy?: string;
61
+ updatedAt: string;
62
+ }
63
+ /** How an event's per-customer ticket limit recognises customers and how many tickets it covers. */
64
+ export interface PurchaseLimitReadiness {
65
+ identifiers: string[];
66
+ ticketsCounted: number;
67
+ ticketsNotCounted: number;
68
+ }
69
+ /** Body for `AlyteMerchant.setEventPurchaseLimit`. Whole numbers only (`1..1000`); PUT replaces the whole limit. */
70
+ export interface SetPurchaseLimitInput {
71
+ maxPerCustomer: number;
72
+ maxHeldPerCustomer?: number;
73
+ countWaitingWatches?: boolean;
32
74
  }
33
75
  export interface Tier {
34
76
  id: string;
@@ -41,6 +83,11 @@ export interface Tier {
41
83
  availableCount?: number;
42
84
  /** When present, availability comes from this shared pool. Restock the pool. */
43
85
  poolId?: string;
86
+ role?: TierRole;
87
+ category?: string;
88
+ categoryLabel?: string;
89
+ countsTowardPartySize?: boolean;
90
+ linkRule?: TierLinkRule;
44
91
  maxQtyPerPurchase?: number;
45
92
  sellable?: boolean;
46
93
  onSaleStart?: string;
@@ -98,7 +145,25 @@ export interface Hold {
98
145
  requestedQuantity?: number;
99
146
  partialReason?: string;
100
147
  }
148
+ /** Verified purchase authentication facts; never an assertion of liability shift. */
149
+ export type PurchaseAuthentication = ({
150
+ provider: 'stripe';
151
+ paymentIntentId: string;
152
+ chargeId?: string;
153
+ } | {
154
+ provider: 'adyen';
155
+ pspReference: string;
156
+ }) & {
157
+ result: string;
158
+ flow?: string;
159
+ version?: string;
160
+ eci?: string;
161
+ transactionId?: string;
162
+ observedAt: string;
163
+ };
101
164
  export interface PaymentResult {
165
+ purchaseId?: string;
166
+ authentication?: PurchaseAuthentication;
102
167
  intentId: string;
103
168
  status: string;
104
169
  psp?: string;
@@ -107,9 +172,20 @@ export interface PaymentResult {
107
172
  [k: string]: unknown;
108
173
  }
109
174
  export type ConfirmOutcome = {
175
+ status: 'payment_pending';
176
+ result: PaymentResult;
177
+ holdStatus: 'reconcile';
178
+ } | {
110
179
  status: 'settled';
111
180
  result: PaymentResult;
112
181
  holdStatus: string;
182
+ } | {
183
+ status: 'sca_required';
184
+ purchaseId: string;
185
+ challenge: {
186
+ expiresAt: string;
187
+ };
188
+ holdStatus: 'reconcile';
113
189
  } | {
114
190
  status: 'sca_required';
115
191
  challenge: {
@@ -193,5 +269,12 @@ export interface MerchantInsights {
193
269
  failed: number;
194
270
  cancelled: number;
195
271
  expired: number;
272
+ /** Why queued requests wait, as the dispatcher last decided. Absent on older servers. */
273
+ waiting?: {
274
+ stock: number;
275
+ whole_party: number;
276
+ price_target: number;
277
+ access_window: number;
278
+ };
196
279
  }>;
197
280
  }
@@ -0,0 +1,28 @@
1
+ /** Reserve, quote and release a basket without charging.
2
+ * ALYTE_BASE_URL=… ALYTE_AGENT_TOKEN=… ADULT_TIER_ID=… CHILD_TIER_ID=… npx tsx agent-basket.ts
3
+ * Requires catalog:read + payments:read + payments:write and a covering mandate.
4
+ */
5
+ import { AlyteAgent, type ConfirmReservationOutcome } from '@alytegen/sdk';
6
+
7
+ const agent = new AlyteAgent({ baseUrl: process.env.ALYTE_BASE_URL!, token: process.env.ALYTE_AGENT_TOKEN! });
8
+ const reservation = await agent.reserveBasket({ lines: [
9
+ { tierId: process.env.ADULT_TIER_ID!, quantity: 2 },
10
+ { tierId: process.env.CHILD_TIER_ID!, quantity: 1 },
11
+ ], scheme: 'visa', geo: 'DE' });
12
+ const quote = await agent.quoteReservation(reservation.id);
13
+ console.log({ reservationId: reservation.id, quoteId: quote.id, lines: quote.lines,
14
+ chargeMinor: quote.chargeMinor, currency: quote.currency, expiresAt: reservation.expiresAt });
15
+
16
+ // A real application persists the reservation, quote, instrument and idempotency
17
+ // key before calling confirmReservation. This example stops before any charge.
18
+ await agent.releaseReservation(reservation.id);
19
+
20
+ /** Interpret confirmation or resolveBasketSca results without treating an uncertain
21
+ * payment as a decline. Only an authorized, confirmed basket may be fulfilled. */
22
+ export function purchaseState(outcome: ConfirmReservationOutcome): 'paid' | 'challenge' | 'refused' | 'pending' {
23
+ if (outcome.status === 'sca_required') return 'challenge';
24
+ if (outcome.status === 'sca_failed') return 'refused';
25
+ if (outcome.status === 'payment_pending' || outcome.reservationStatus === 'reconcile') return 'pending';
26
+ if (outcome.result.status === 'authorized' && outcome.reservationStatus === 'confirmed') return 'paid';
27
+ return outcome.result.status === 'declined' ? 'refused' : 'pending';
28
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alytegen/sdk",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Alyte client SDK \u2014 merchant integration (catalog, PSP links, buyer sessions, payments visibility) and the agent buy path (discover \u2192 quote \u2192 hold \u2192 confirm).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",