@agentpost-tools/resourceshark-sdk 0.0.0-stage → 0.2.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.
@@ -0,0 +1,384 @@
1
+ // src/workflows/errors.ts
2
+ /** A failure the workflow or a transport finds itself, before any request. */
3
+ var WorkflowFailure = class extends Error {
4
+ code;
5
+ details;
6
+ constructor(code, message, details) {
7
+ super(message);
8
+ this.name = "WorkflowFailure";
9
+ this.code = code;
10
+ this.details = details;
11
+ }
12
+ };
13
+ /**
14
+ * The workflow's error for anything a transport threw. An error with a
15
+ * numeric `status` and a string `code`, such as `ResourcesharkApiError` or
16
+ * the endpoint transport's own, is an answer; anything else never reached
17
+ * an answer, and is a `network_error`.
18
+ */
19
+ function toWorkflowError(error) {
20
+ if (error instanceof WorkflowFailure) return {
21
+ code: error.code,
22
+ message: error.message,
23
+ ...error.details === void 0 ? {} : { details: error.details }
24
+ };
25
+ if (isAnswer(error)) {
26
+ const { errorClass, docs, details } = error;
27
+ return {
28
+ code: error.code,
29
+ message: error.message,
30
+ status: error.status,
31
+ ...typeof errorClass === "string" ? { errorClass } : {},
32
+ ...typeof docs === "string" ? { docs } : {},
33
+ ...details === void 0 ? {} : { details }
34
+ };
35
+ }
36
+ return {
37
+ code: "network_error",
38
+ message: error instanceof Error ? error.message : String(error)
39
+ };
40
+ }
41
+ function isAnswer(error) {
42
+ return error instanceof Error && typeof error.status === "number" && typeof error.code === "string";
43
+ }
44
+ const record = (value) => typeof value === "object" && value !== null ? value : void 0;
45
+ /** The short lines of `insufficient_supply`, `exhausted_until_supply` (with its `nextSupplyAt`), or `assignment_infeasible`. */
46
+ function shortOf(error) {
47
+ if (error.code !== "insufficient_supply" && error.code !== "exhausted_until_supply" && error.code !== "assignment_infeasible") return void 0;
48
+ const details = record(error.details);
49
+ const lines = Array.isArray(details?.lines) ? details.lines : [];
50
+ const next = details?.nextSupplyAt;
51
+ return {
52
+ lines,
53
+ ...typeof next === "string" ? { nextSupplyAt: next } : {}
54
+ };
55
+ }
56
+ /** What `hold_expired` carries: when the hold ran out, and on a commit, each line's availability. */
57
+ function expiredOf(error) {
58
+ if (error.code !== "hold_expired") return void 0;
59
+ const details = record(error.details);
60
+ if (!details || typeof details.expiresAt !== "string") return void 0;
61
+ return details;
62
+ }
63
+ /** What `hold_resolved` carries: how the hold first ended. */
64
+ function resolvedOf(error) {
65
+ if (error.code !== "hold_resolved") return void 0;
66
+ const details = record(error.details);
67
+ if (!details || typeof details.status !== "string") return void 0;
68
+ return details;
69
+ }
70
+ // src/workflows/transport.ts
71
+ const holderCheck = (line, resource, index, input) => {
72
+ if (!resource.scope.holders || line.scope?.holderRef !== void 0) return line;
73
+ if (input.holderRef === void 0) throw new WorkflowFailure("holder_required", `line ${index} is on resource ${resource.id}, which is held per holder: name scope.holderRef on the line, or holderRef on the hold`, {
74
+ line: index,
75
+ resourceId: resource.id,
76
+ field: "scope.holderRef"
77
+ });
78
+ return {
79
+ ...line,
80
+ scope: {
81
+ ...line.scope,
82
+ holderRef: input.holderRef
83
+ }
84
+ };
85
+ };
86
+ const placeCheck = (line, resource, index) => {
87
+ if (!resource.scope.places || line.scope?.placeId !== void 0) return line;
88
+ throw new WorkflowFailure("place_required", `line ${index} is on resource ${resource.id}, which is kept by place: name scope.placeId on the line`, {
89
+ line: index,
90
+ resourceId: resource.id,
91
+ field: "scope.placeId"
92
+ });
93
+ };
94
+ const LINE_CHECKS = [holderCheck, placeCheck];
95
+ function required(value, field, example) {
96
+ if (typeof value === "string" && value.trim() !== "") return;
97
+ throw new WorkflowFailure("invalid_request", `${field} is required, such as ${example}; the workflow has no default`, { field });
98
+ }
99
+ /**
100
+ * Secret-key transport. Before a hold it reads each line's resource
101
+ * (`resources.get`) and:
102
+ * - copies `holderRef` into `scope.holderRef` on each line of a resource
103
+ * with `scope.holders`, or fails `holder_required` naming the line when
104
+ * neither is given;
105
+ * - fails `place_required` naming the line when a resource with
106
+ * `scope.places` has no `scope.placeId`.
107
+ * A missing `ttl`, `sourceKey`, or line fails `invalid_request` before any
108
+ * request, as the service would. `serverNow` is this process's clock.
109
+ */
110
+ function apiTransport(client, options = {}) {
111
+ const cacheMs = options.resourceCacheMs ?? 0;
112
+ const cache = /* @__PURE__ */ new Map();
113
+ const serverNow = () => (/* @__PURE__ */ new Date()).toISOString();
114
+ function resourceOf(id) {
115
+ const at = Date.now();
116
+ const hit = cache.get(id);
117
+ if (cacheMs > 0 && hit && at - hit.at < cacheMs) return hit.resource;
118
+ const resource = client.resources.get(id).then(({ resource }) => resource);
119
+ if (cacheMs > 0) {
120
+ const entry = {
121
+ at,
122
+ resource
123
+ };
124
+ cache.set(id, entry);
125
+ resource.catch(() => {
126
+ if (cache.get(id) === entry) cache.delete(id);
127
+ });
128
+ }
129
+ return resource;
130
+ }
131
+ async function checkedLines(input) {
132
+ const ids = [...new Set(input.lines.map((line) => line.resourceId))];
133
+ const read = await Promise.all(ids.map(resourceOf));
134
+ const resources = new Map(ids.map((id, i) => [id, read[i]]));
135
+ return input.lines.map((line, index) => LINE_CHECKS.reduce((checked, check) => check(checked, resources.get(line.resourceId), index, input), line));
136
+ }
137
+ return {
138
+ async slots(q) {
139
+ const { slots } = await client.slots.list(q);
140
+ return {
141
+ slots,
142
+ serverNow: serverNow()
143
+ };
144
+ },
145
+ async place(input, attemptKey) {
146
+ if (!Array.isArray(input?.lines) || input.lines.length === 0) throw new WorkflowFailure("invalid_request", "a hold needs at least one line", { field: "lines" });
147
+ required(input.ttl, "ttl", "\"15m\"");
148
+ required(input.sourceKey, "sourceKey", "\"checkout:chk_123\"");
149
+ const body = {
150
+ lines: await checkedLines(input),
151
+ ttl: input.ttl,
152
+ sourceKey: input.sourceKey,
153
+ ...input.holderRef === void 0 ? {} : { holderRef: input.holderRef },
154
+ ...input.label === void 0 ? {} : { label: input.label },
155
+ ...input.reference === void 0 ? {} : { reference: input.reference }
156
+ };
157
+ const { hold } = await client.holds.create(body, { idempotencyKey: attemptKey });
158
+ return {
159
+ hold,
160
+ serverNow: serverNow()
161
+ };
162
+ },
163
+ async extend(holdId, input, attemptKey) {
164
+ required(input?.ttl, "ttl", "\"15m\"");
165
+ const { hold } = await client.holds.extend(holdId, { ttl: input.ttl }, { idempotencyKey: attemptKey });
166
+ return {
167
+ hold,
168
+ serverNow: serverNow()
169
+ };
170
+ },
171
+ async release(holdId, attemptKey) {
172
+ const { hold } = await client.holds.release(holdId, { idempotencyKey: attemptKey });
173
+ return {
174
+ hold,
175
+ serverNow: serverNow()
176
+ };
177
+ },
178
+ async commit(holdId, input, attemptKey) {
179
+ const answer = await client.holds.commit(holdId, commitBody(input), { idempotencyKey: attemptKey });
180
+ return {
181
+ hold: answer.hold,
182
+ movements: answer.movements,
183
+ ...answer.duplicate ? { duplicate: true } : {},
184
+ serverNow: serverNow()
185
+ };
186
+ },
187
+ buy(lines, input) {
188
+ return client.claims.consume({
189
+ lines,
190
+ evidence: input.evidence,
191
+ sourceKey: input.sourceKey
192
+ }, { idempotencyKey: input.idempotencyKey });
193
+ }
194
+ };
195
+ }
196
+ /** The commit request as the API reads it, with no field the app left out. */
197
+ function commitBody(input) {
198
+ return {
199
+ evidence: input.evidence,
200
+ sourceKey: input.sourceKey,
201
+ ...input.lines === void 0 ? {} : { lines: input.lines }
202
+ };
203
+ }
204
+ /** An error answer from the customer's endpoint, in the same shape the client gives. */
205
+ var EndpointError = class extends Error {
206
+ status;
207
+ code;
208
+ errorClass;
209
+ details;
210
+ docs;
211
+ constructor(status, code, message, extra = {}) {
212
+ super(message);
213
+ this.name = "EndpointError";
214
+ this.status = status;
215
+ this.code = code;
216
+ if (extra.errorClass !== void 0) this.errorClass = extra.errorClass;
217
+ if (extra.details !== void 0) this.details = extra.details;
218
+ if (extra.docs !== void 0) this.docs = extra.docs;
219
+ }
220
+ };
221
+ /**
222
+ * Browser transport to the customer's endpoint: `GET /slots`, `POST
223
+ * /holds`, `POST /holds/:id/extend`, `/release`, and `/commit` under
224
+ * `url`, each POST with the attempt key as its `Idempotency-Key`. Place,
225
+ * Extend, and Commit are the app's own shapes, sent as `{ input }`. An
226
+ * expired commit's `buy` is null here: a late payment is taken on the
227
+ * server, with `commitHold`.
228
+ */
229
+ function endpointTransport(options) {
230
+ const base = options.url.replace(/\/+$/, "");
231
+ const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
232
+ async function call(method, path, attemptKey, body) {
233
+ const headers = {
234
+ accept: "application/json",
235
+ ...await options.headers?.()
236
+ };
237
+ if (attemptKey !== void 0) headers["idempotency-key"] = attemptKey;
238
+ if (body !== void 0) headers["content-type"] = "application/json";
239
+ const response = await doFetch(`${base}${path}`, {
240
+ method,
241
+ headers,
242
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
243
+ });
244
+ const text = await response.text();
245
+ let parsed;
246
+ try {
247
+ parsed = text ? JSON.parse(text) : void 0;
248
+ } catch {
249
+ parsed = void 0;
250
+ }
251
+ if (!response.ok) throw errorOf(response.status, parsed, method, path);
252
+ if (typeof parsed !== "object" || parsed === null) throw new EndpointError(response.status, "unknown", `${method} ${path} answered ${response.status} without a JSON body`);
253
+ return parsed;
254
+ }
255
+ const holdPath = (holdId, action) => `/holds/${encodeURIComponent(holdId)}/${action}`;
256
+ return {
257
+ slots(q) {
258
+ const search = new URLSearchParams();
259
+ for (const [key, value] of Object.entries(q)) if (value !== void 0 && value !== null) search.set(key, String(value));
260
+ return call("GET", `/slots?${search}`);
261
+ },
262
+ place(input, attemptKey) {
263
+ return call("POST", "/holds", attemptKey, { input });
264
+ },
265
+ extend(holdId, input, attemptKey) {
266
+ return call("POST", holdPath(holdId, "extend"), attemptKey, { input });
267
+ },
268
+ release(holdId, attemptKey) {
269
+ return call("POST", holdPath(holdId, "release"), attemptKey);
270
+ },
271
+ commit(holdId, input, attemptKey) {
272
+ return call("POST", holdPath(holdId, "commit"), attemptKey, { input });
273
+ }
274
+ };
275
+ }
276
+ function errorOf(status, body, method, path) {
277
+ const error = body?.error;
278
+ if (typeof error !== "object" || error === null || typeof error.code !== "string") return new EndpointError(status, "unknown", `${method} ${path.split("?")[0]} failed with ${status}`);
279
+ return new EndpointError(status, error.code, typeof error.message === "string" ? error.message : error.code, {
280
+ ...typeof error.class === "string" ? { errorClass: error.class } : {},
281
+ ...error.details === void 0 ? {} : { details: error.details },
282
+ ...typeof error.docs === "string" ? { docs: error.docs } : {}
283
+ });
284
+ }
285
+ // src/workflows/commit.ts
286
+ /** The expired lines, each with the span of the hold line it names. Null when `hold_expired` carried no lines. */
287
+ function expiredLines(details, hold) {
288
+ if (!details.lines) return null;
289
+ const spans = new Map((hold?.lines ?? []).flatMap((line) => line.span ? [[line.claimId, line.span]] : []));
290
+ return details.lines.map((line) => {
291
+ const span = spans.get(line.claimId);
292
+ return {
293
+ claimId: line.claimId,
294
+ resourceId: line.resourceId,
295
+ scope: line.scope,
296
+ ...span ? { span } : {},
297
+ quantity: line.quantity,
298
+ available: line.available,
299
+ enough: line.available >= line.quantity
300
+ };
301
+ });
302
+ }
303
+ /**
304
+ * The outcome of an expired commit. `buy` is offered when `consume` is,
305
+ * and some line asked for more than nothing; it consumes those lines with
306
+ * their scopes whole and the hold lines' spans.
307
+ */
308
+ function expiredOutcome(details, lines, consume) {
309
+ const claimLines = (lines ?? []).filter(({ quantity }) => quantity > 0).map((line) => ({
310
+ resourceId: line.resourceId,
311
+ scope: line.scope,
312
+ quantity: line.quantity,
313
+ ...line.span ? { span: line.span } : {}
314
+ }));
315
+ return {
316
+ status: "expired",
317
+ expiresAt: details.expiresAt,
318
+ lines,
319
+ allFit: lines !== null && lines.every(({ enough }) => enough),
320
+ buy: consume && claimLines.length > 0 ? (input) => buyWith(consume, claimLines, input) : null
321
+ };
322
+ }
323
+ async function buyWith(consume, lines, input) {
324
+ try {
325
+ return {
326
+ status: "bought",
327
+ response: await consume(lines, input)
328
+ };
329
+ } catch (caught) {
330
+ const error = toWorkflowError(caught);
331
+ const short = shortOf(error);
332
+ if (short) return {
333
+ status: "short",
334
+ ...short
335
+ };
336
+ return {
337
+ status: "failed",
338
+ error
339
+ };
340
+ }
341
+ }
342
+ /**
343
+ * The server-side commit, for the app's payment handler: the same outcome
344
+ * as the workflow's, with `buy` set. On `hold_expired` with lines, it reads
345
+ * the hold for its lines' spans; if that read fails, `buy` is null.
346
+ */
347
+ async function commitHold(client, holdId, input, options) {
348
+ try {
349
+ const answer = await client.holds.commit(holdId, commitBody(input), { idempotencyKey: options.idempotencyKey });
350
+ return {
351
+ status: "committed",
352
+ hold: answer.hold,
353
+ movements: answer.movements,
354
+ ...answer.duplicate ? { duplicate: true } : {}
355
+ };
356
+ } catch (caught) {
357
+ const error = toWorkflowError(caught);
358
+ const expired = expiredOf(error);
359
+ if (expired) {
360
+ let hold = null;
361
+ if (expired.lines?.length) try {
362
+ hold = (await client.holds.get(holdId)).hold;
363
+ } catch {
364
+ hold = null;
365
+ }
366
+ const consume = hold ? (lines, buy) => client.claims.consume({
367
+ lines,
368
+ evidence: buy.evidence,
369
+ sourceKey: buy.sourceKey
370
+ }, { idempotencyKey: buy.idempotencyKey }) : null;
371
+ return expiredOutcome(expired, expiredLines(expired, hold), consume);
372
+ }
373
+ const resolution = resolvedOf(error);
374
+ if (resolution) return {
375
+ status: "resolved",
376
+ resolution
377
+ };
378
+ return {
379
+ status: "failed",
380
+ error
381
+ };
382
+ }
383
+ }
384
+ export { endpointTransport as a, resolvedOf as c, apiTransport as i, shortOf as l, expiredLines as n, WorkflowFailure as o, expiredOutcome as r, expiredOf as s, commitHold as t, toWorkflowError as u };
@@ -0,0 +1,108 @@
1
+ import { Cn as SupplyResponse, En as TotalsBalance, H as Duration, It as MovementReason, Jt as Quantity, On as TotalsReport, Pn as Unit, Qt as ResourceId, Rt as MovementSums, Tn as SupplyReverseResponse, Y as Evidence, _ as Attributes, _n as SupplyCreateInput, bn as SupplyId, cn as Scope, l as ResourcesharkClient, o as ResourcesharkApiError, pn as Slot } from "../client-DEn-MdAz.js";
2
+ type Cadence = {
3
+ every: 'month';
4
+ count: number;
5
+ timeZone: string;
6
+ dayOverflow: 'clamp' | 'roll';
7
+ } | {
8
+ every: 'day';
9
+ count: number;
10
+ timeZone: string;
11
+ } | {
12
+ every: 'duration';
13
+ length: Duration;
14
+ };
15
+ interface Period {
16
+ index: number;
17
+ start: string;
18
+ end: string;
19
+ }
20
+ interface SupplyRule {
21
+ resourceId: ResourceId;
22
+ scope: Scope;
23
+ quantity: Quantity;
24
+ kind: 'added';
25
+ cadence: Cadence;
26
+ from: string;
27
+ periods: number;
28
+ expires: boolean;
29
+ evidence(p: Period): Evidence;
30
+ sourceKey(p: Period): string;
31
+ attributes?(p: Period): Attributes;
32
+ drawOrder?: number;
33
+ }
34
+ /**
35
+ * Creates half-open periods from the anchor. Calendar dates and times without
36
+ * offsets use the cadence's zone. An elapsed cadence starts at the given
37
+ * instant, with a date alone read as UTC midnight.
38
+ */
39
+ export declare function supplyPeriods(rule: SupplyRule): {
40
+ period: Period;
41
+ entry: SupplyCreateInput;
42
+ }[];
43
+ /** Posts periods in order, stopping at the first failed write. */
44
+ export declare function postSupplyPeriods(client: ResourcesharkClient, entries: {
45
+ entry: SupplyCreateInput;
46
+ }[], o: {
47
+ idempotencyKey(entry: SupplyCreateInput): string;
48
+ }): Promise<SupplyResponse[]>;
49
+ interface TotalsSum {
50
+ unit: Unit;
51
+ resourceIds: ResourceId[];
52
+ balance: TotalsBalance | null;
53
+ movements: MovementSums;
54
+ chosen?: Quantity;
55
+ bucketed: ResourceId[];
56
+ }
57
+ /** Sums each combination of unit code and precision independently. */
58
+ export declare function sumTotals(report: TotalsReport, o: {
59
+ resourceIds?: ResourceId[];
60
+ reasons?: MovementReason[];
61
+ }): TotalsSum[];
62
+ /** Sums the rows for each grouping value, including the unnamed group. */
63
+ export declare function sumGroups(report: TotalsReport, o: {
64
+ resourceIds?: ResourceId[];
65
+ }): Map<string | null, TotalsSum[]>;
66
+ export declare function periodLength(report: TotalsReport): {
67
+ ms: number;
68
+ days: number;
69
+ } | null;
70
+ export declare function hasEnough(line: {
71
+ quantity: Quantity;
72
+ available: Quantity;
73
+ }): boolean;
74
+ export declare function shortBy(line: {
75
+ quantity: Quantity;
76
+ available: Quantity;
77
+ }): Quantity;
78
+ type TakeBackOutcome = {
79
+ status: 'taken';
80
+ asked: Quantity;
81
+ taken: Quantity;
82
+ response: SupplyReverseResponse;
83
+ } | {
84
+ status: 'nothing_left';
85
+ } | {
86
+ status: 'failed';
87
+ error: ResourcesharkApiError;
88
+ };
89
+ /** Retries a short reversal with the quantity the service says is available. */
90
+ export declare function takeBackUpTo(client: ResourcesharkClient, supplyId: SupplyId, input: {
91
+ quantity: Quantity;
92
+ evidence: Evidence;
93
+ sourceKey: string;
94
+ idempotencyKey: string;
95
+ attempts?: number;
96
+ }): Promise<TakeBackOutcome>;
97
+ export declare function slotIn(slot: Slot, timeZone: string): {
98
+ date: string;
99
+ time: string;
100
+ offsetMinutes: number;
101
+ endDate: string;
102
+ endTime: string;
103
+ };
104
+ export declare function formatSlot(slot: Slot, o: {
105
+ timeZone: string;
106
+ locale?: string;
107
+ } & Intl.DateTimeFormatOptions): string;
108
+ export type { Cadence, Period, SupplyRule, TakeBackOutcome, TotalsSum };