@alytegen/sdk 0.6.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,6 +31,19 @@ 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.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
40
+ merchant-controlled early access: save a draft, preview, schedule or cancel, and attest or
41
+ revoke membership. They require a server at or after sandbox revision `alyte-sandbox-00133-v77`.
42
+ See [the access-rule workflow](./README.md#access-rules-and-membership)
43
+ for request identities, explicit-offset windows and revision checks.
44
+ Membership uses the `buyerId` returned by `buyerSessions.mint`; retain its mapping to
45
+ your own customer ID rather than passing your internal customer ID to `memberships.upsert`.
46
+
34
47
  ## Plugging in YOUR auth + user database (required for buyer flows)
35
48
 
36
49
  Your customers already have accounts with you — Alyte does not replace that.
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.6.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,75 @@ 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
+
100
+ ## Access rules and membership
101
+
102
+ Available since SDK 0.7.0; requires a server at or after sandbox revision
103
+ `alyte-sandbox-00133-v77`. Use a backend credential with `merchant:read` and
104
+ `merchant:write`. The console exposes the same flow to account owners.
105
+
106
+ An access rule grants an early window before a tier's general-sale opening. Create a
107
+ draft, review its current impact, then schedule it:
108
+
109
+ ```ts
110
+ const { program } = await alyte.memberships.createProgram(merchant.id, {
111
+ requestId: crypto.randomUUID(), name: 'Members', levels: ['Gold', 'Platinum'],
112
+ });
113
+ const { rule } = await alyte.accessRules.createDraft(merchant.id, {
114
+ requestId: crypto.randomUUID(), offerId: tier.id, name: 'Member presale',
115
+ audience: { kind: 'membership', programId: program.id, levels: ['Gold', 'Platinum'] },
116
+ opensAt: '2027-05-01T09:00:00+01:00',
117
+ closesAt: '2027-05-01T10:00:00+01:00', // must end by the tier's general-sale opening
118
+ });
119
+ const preview = await alyte.accessRules.preview(merchant.id, rule.id);
120
+ // Show preview.impact, preview.timeZone and the window to the operator for review.
121
+ const publication = {
122
+ requestId: crypto.randomUUID(), expectedRevision: rule.revision, previewId: preview.id,
123
+ };
124
+ // Persist publication before dispatch; reuse exactly this input after an uncertain response.
125
+ const scheduled = await alyte.accessRules.schedule(merchant.id, rule.id, publication);
126
+ ```
127
+
128
+ Persist **each** mutation's request UUID and input before dispatch. Exact replays are safe;
129
+ changed input requires a new UUID. `access_conflict` means refresh and review again.
130
+ Drafts remain inactive. To cancel, call `preview(shopId, ruleId, 'cancel')`, then
131
+ `cancel` with that preview ID, the current rule revision and a new request UUID.
132
+ Published rules cannot be edited.
133
+
134
+ The merchant supplies verified membership for the **Alyte buyer ID** returned as
135
+ `buyerId` by `buyerSessions.mint`. Store a mapping from your authenticated customer's
136
+ internal ID to this returned value, scoped to the Alyte account. Passing your own customer
137
+ ID directly will not match the buyer's Alyte agent. Obtain the identity during your existing
138
+ signed-in hand-off; never derive or guess it from an email address.
139
+
140
+ ```ts
141
+ const session = await alyte.buyerSessions.mint({
142
+ merchantId: merchant.id, email: user.email,
143
+ });
144
+ const evidence = {
145
+ requestId: crypto.randomUUID(), sourceRevision: 1, level: 'Gold',
146
+ validFrom: '2027-01-01T00:00:00Z', validUntil: '2028-01-01T00:00:00Z',
147
+ evidenceRef: 'membership-system:record-123', revoked: false,
148
+ };
149
+ await alyte.memberships.upsert(merchant.id, program.id, session.buyerId, evidence);
150
+ // Revoke using a new requestId, a strictly greater sourceRevision, and revoked: true.
151
+ ```
152
+
153
+ Levels are explicit, with no implied hierarchy. Membership does not grant payment permission.
154
+ Other audiences are `{ kind: 'everyone' }` and
155
+ `{ kind: 'scheme', schemes: ['amex'] }`; card eligibility uses the actual saved instrument.
156
+ Issuer claims and free-text loyalty claims are not accepted. All times require explicit offsets.
157
+ Impact counts are observations of access, not stock forecasts or guaranteed queue positions.
158
+
159
+ Deleting an offer archives its rules in the read API. `accessRules.list` omits them, so
160
+ they do not consume the active list's limit. `accessRules.get` still returns their historical
161
+ definition and revision with `status: 'archived'`; archived rules cannot be edited or published.
162
+
94
163
  ## Hand a signed-in customer to their agent
95
164
 
96
165
  Your users already have accounts with you. Your server attests one of them and redirects;
@@ -121,6 +190,43 @@ Two kinds of session, decided by how you mint:
121
190
  ceilings answers `403 merchant_consent_ceiling_exceeded` and Alyte's screen falls back to the
122
191
  buyer's own code; without the enablement, the mint answers `403 merchant_consent_not_enabled`.
123
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
+
124
230
  ## Receive purchases
125
231
 
126
232
  ```ts
@@ -149,9 +255,61 @@ const out = await agent.confirm(hold.id,
149
255
  No amount is passed at confirm — the charge is the locked quote. A spend-cap refusal means
150
256
  the buyer's mandate said no: surface it, don't retry.
151
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
+
152
302
  ## Current API and console capabilities
153
303
 
154
- SDK **0.6.0** adds inventory management: shared pools (`createPool`, `listPools`, `updatePool`),
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`,
311
+ `createDraft`, `updateDraft`, `preview`, `schedule`, `cancel`) and `memberships`
312
+ (`createProgram`, `upsert`). **0.6.0** added inventory management: shared pools (`createPool`, `listPools`, `updatePool`),
155
313
  optional venue locations with pinned versions (`createLocation`, `listLocations`, `updateLocation`,
156
314
  `getSlot`, `setSlotLocation`, `createEvent({ location })`) and a read-only `inventoryCatalog`
157
315
  observation. **0.5.0** typed the merchant-attested mint (`merchantAttested: true`), alongside the browser
@@ -0,0 +1,106 @@
1
+ import type { Transport } from './http.js';
2
+ export type AccessAudience = {
3
+ kind: 'everyone';
4
+ } | {
5
+ kind: 'membership';
6
+ programId: string;
7
+ levels: string[];
8
+ } | {
9
+ kind: 'scheme';
10
+ schemes: Array<'visa' | 'mastercard' | 'amex'>;
11
+ };
12
+ export interface AccessDraftInput {
13
+ requestId: string;
14
+ offerId: string;
15
+ name: string;
16
+ audience?: AccessAudience;
17
+ opensAt?: string;
18
+ closesAt?: string;
19
+ }
20
+ export interface AccessRule extends Omit<AccessDraftInput, 'requestId'> {
21
+ id: string;
22
+ revision: number;
23
+ status: 'draft' | 'scheduled' | 'cancelled' | 'archived';
24
+ }
25
+ export interface MembershipProgram {
26
+ id: string;
27
+ name: string;
28
+ levels: string[];
29
+ }
30
+ export interface AccessPreview {
31
+ id: string;
32
+ rule: AccessRule;
33
+ action: 'schedule' | 'cancel';
34
+ expiresAt: string;
35
+ observedAt: string;
36
+ impact: {
37
+ total: number;
38
+ earlier: number;
39
+ later: number;
40
+ unchanged: number;
41
+ };
42
+ timeZone: string;
43
+ generalSaleAt: string | null;
44
+ }
45
+ export interface AccessCommitInput {
46
+ requestId: string;
47
+ expectedRevision: number;
48
+ previewId: string;
49
+ }
50
+ export interface MembershipEvidence {
51
+ requestId: string;
52
+ sourceRevision: number;
53
+ level: string;
54
+ validFrom: string;
55
+ validUntil: string;
56
+ evidenceRef: string;
57
+ revoked: boolean;
58
+ }
59
+ /** Backend-only merchant access control. Save each request UUID before dispatch and
60
+ * reuse it only for the exact same operation. No mutation is retried automatically. */
61
+ export declare class MerchantAccessRules {
62
+ private readonly t;
63
+ constructor(t: Transport);
64
+ list(shop: string): Promise<{
65
+ rules: AccessRule[];
66
+ programs: MembershipProgram[];
67
+ }>;
68
+ get(shop: string, id: string): Promise<{
69
+ rule: AccessRule;
70
+ }>;
71
+ createDraft(shop: string, input: AccessDraftInput): Promise<{
72
+ rule: AccessRule;
73
+ }>;
74
+ updateDraft(shop: string, id: string, input: AccessDraftInput & {
75
+ expectedRevision: number;
76
+ }): Promise<{
77
+ rule: AccessRule;
78
+ }>;
79
+ preview(shop: string, id: string, action?: 'schedule' | 'cancel'): Promise<AccessPreview>;
80
+ schedule(shop: string, id: string, input: AccessCommitInput): Promise<{
81
+ rule: AccessRule;
82
+ }>;
83
+ cancel(shop: string, id: string, input: AccessCommitInput): Promise<{
84
+ rule: AccessRule;
85
+ }>;
86
+ }
87
+ /** A merchant attests membership in its own program, not payment permission. */
88
+ export declare class MerchantMemberships {
89
+ private readonly t;
90
+ constructor(t: Transport);
91
+ createProgram(shop: string, input: {
92
+ requestId: string;
93
+ name: string;
94
+ levels: string[];
95
+ }): Promise<{
96
+ program: MembershipProgram;
97
+ }>;
98
+ upsert(shop: string, programId: string, buyerId: string, input: MembershipEvidence): Promise<{
99
+ membership: {
100
+ programId: string;
101
+ buyerId: string;
102
+ sourceRevision: number;
103
+ revoked: boolean;
104
+ };
105
+ }>;
106
+ }
package/dist/access.js ADDED
@@ -0,0 +1,27 @@
1
+ const base = (shop) => `/v1/integration/merchants/${encodeURIComponent(shop)}/access`;
2
+ /** Backend-only merchant access control. Save each request UUID before dispatch and
3
+ * reuse it only for the exact same operation. No mutation is retried automatically. */
4
+ export class MerchantAccessRules {
5
+ t;
6
+ constructor(t) {
7
+ this.t = t;
8
+ }
9
+ list(shop) { return this.t.request('GET', base(shop)); }
10
+ get(shop, id) { return this.t.request('GET', `${base(shop)}/rules/${encodeURIComponent(id)}`); }
11
+ createDraft(shop, input) { return this.t.request('POST', `${base(shop)}/rules`, input); }
12
+ updateDraft(shop, id, input) { return this.t.request('PUT', `${base(shop)}/rules/${encodeURIComponent(id)}`, input); }
13
+ preview(shop, id, action = 'schedule') { return this.t.request('POST', `${base(shop)}/rules/${encodeURIComponent(id)}/preview`, { action }); }
14
+ schedule(shop, id, input) { return this.t.request('POST', `${base(shop)}/rules/${encodeURIComponent(id)}/schedule`, input); }
15
+ cancel(shop, id, input) { return this.t.request('POST', `${base(shop)}/rules/${encodeURIComponent(id)}/cancel`, input); }
16
+ }
17
+ /** A merchant attests membership in its own program, not payment permission. */
18
+ export class MerchantMemberships {
19
+ t;
20
+ constructor(t) {
21
+ this.t = t;
22
+ }
23
+ createProgram(shop, input) { return this.t.request('POST', `${base(shop)}/programs`, input); }
24
+ upsert(shop, programId, buyerId, input) {
25
+ return this.t.request('PUT', `${base(shop)}/programs/${encodeURIComponent(programId)}/members/${encodeURIComponent(buyerId)}`, input);
26
+ }
27
+ }
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;