@agentpost-tools/resourceshark-sdk 0.0.0-stage → 0.1.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,101 @@
1
+ import { B as ErrorClass, Qt as RetainedHold, nt as Hold, sn as SlotsQuery } from "./client-C-4s_6Qp.js";
2
+ import { c as CommitInput, f as PlaceInput, i as commitHold, n as CommitOutcome, r as ExpiredLine, s as BuyInput, t as BuyOutcome, u as ExtendInput } from "./commit-BxtiTSez.js";
3
+ /**
4
+ * A refusal from one of the app's hooks, such as a hold longer than the
5
+ * app allows or a user at their cap of open holds. It reaches the page as
6
+ * the standard error body, with the same detail rules as service refusals.
7
+ */
8
+ export declare class HoldRefusal extends Error {
9
+ readonly code: string;
10
+ readonly status: 400 | 403 | 404 | 409 | 422;
11
+ readonly details?: unknown;
12
+ readonly errorClass: ErrorClass;
13
+ constructor(code: string, message: string, status?: 400 | 403 | 404 | 409 | 422, details?: unknown, errorClass?: ErrorClass);
14
+ }
15
+ export interface HoldEndpointOptions<Caller, Place, Extend, Commit> {
16
+ /** The project's secret key (`sk_test_…` or `sk_live_…`). */
17
+ secretKey: string;
18
+ /** resourceshark's API root. Defaults to the hosted API, `https://api.agentpost.tools/v1/resources`. */
19
+ baseUrl?: string;
20
+ fetch?: typeof fetch;
21
+ /** How long a resource read before a hold is reused, in ms. Default 0: read every time. */
22
+ resourceCacheMs?: number;
23
+ /**
24
+ * A stable key for the user, such as their principal ID. The helper
25
+ * hashes it with each attempt key to make the Idempotency-Key it sends.
26
+ */
27
+ callerKey(caller: Caller): string | Promise<string>;
28
+ /**
29
+ * Which slots this caller may read: the query to send, made from what
30
+ * the page asked (`resourceId`, `from`, `to`, `placeId`, `condition`, and
31
+ * `instanceId`, as strings). Throw a `HoldRefusal` to refuse.
32
+ */
33
+ slots(query: Partial<SlotsQuery>, caller: Caller): SlotsQuery | Promise<SlotsQuery>;
34
+ /**
35
+ * The hold to place for the page's request. The app's checks, such as a
36
+ * longest hold, a booking window, or a cap on open holds, run here.
37
+ * Throw a `HoldRefusal` to refuse.
38
+ */
39
+ place(input: Place, caller: Caller): PlaceInput | Promise<PlaceInput>;
40
+ /**
41
+ * Whether this caller may act on this hold, such as by its `holderRef`
42
+ * or `sourceKey`. Asked before every extend, release, and commit, and of
43
+ * the hold a place answers with. The hold carries its stored sourceKey,
44
+ * including on a `RetainedHold` (with `retainedAt`).
45
+ */
46
+ owns(hold: Hold | RetainedHold, caller: Caller): boolean | Promise<boolean>;
47
+ /** How long to extend this hold by. Throw a `HoldRefusal` to refuse. */
48
+ extend(hold: Hold | RetainedHold, input: Extend, caller: Caller): ExtendInput | Promise<ExtendInput>;
49
+ /**
50
+ * Opt-in: a page that commits its own hold, such as a free booking.
51
+ * Without it, commit answers 404. A paid hold commits from the payment
52
+ * handler, with `commitHold`.
53
+ */
54
+ commit?(hold: Hold | RetainedHold, input: Commit, caller: Caller): CommitInput | Promise<CommitInput>;
55
+ }
56
+ /** The standard error body, as `endpointTransport` reads it. */
57
+ export interface EndpointErrorBody {
58
+ error: {
59
+ /** resourceshark's error code, the workflow's (such as `place_required`), or the app's, from a `HoldRefusal`. */
60
+ code: string;
61
+ class: ErrorClass;
62
+ /** For agents reading the answer, not for the screen. */
63
+ message: string;
64
+ details?: unknown;
65
+ /** The page that explains the code. */
66
+ docs?: string;
67
+ };
68
+ }
69
+ /** What to answer the page with: an HTTP status, and a body in the wire format. */
70
+ export interface EndpointAnswer {
71
+ status: number;
72
+ body: unknown;
73
+ }
74
+ export interface HoldEndpoint<Caller, Place, Extend, Commit> {
75
+ /** 200 `{ slots, serverNow }`. */
76
+ slots(query: Partial<SlotsQuery>, caller: Caller): Promise<EndpointAnswer>;
77
+ /** 201 `{ hold, serverNow }`. */
78
+ place(input: Place, caller: Caller, attemptKey: string): Promise<EndpointAnswer>;
79
+ /** 200 `{ hold, serverNow }`. */
80
+ extend(holdId: string, input: Extend, caller: Caller, attemptKey: string): Promise<EndpointAnswer>;
81
+ /** 200 `{ hold, serverNow }`. */
82
+ release(holdId: string, caller: Caller, attemptKey: string): Promise<EndpointAnswer>;
83
+ /** 200 `{ hold, movements, serverNow }`, or 404 without a `commit` hook. */
84
+ commit(holdId: string, input: Commit, caller: Caller, attemptKey: string): Promise<EndpointAnswer>;
85
+ /**
86
+ * A Fetch-standard handler for the wire format: `GET /slots`, `POST
87
+ * /holds`, and `POST /holds/:id/extend`, `/release`, and `/commit`. It
88
+ * reads the end of the path, so mount it at any prefix. Each POST takes
89
+ * the attempt key in `Idempotency-Key` and, but for release, a JSON body
90
+ * `{ input }`.
91
+ */
92
+ handle(request: Request, caller: Caller): Promise<Response>;
93
+ }
94
+ /**
95
+ * The customer's hold endpoint. Each method answers a refusal as an
96
+ * `EndpointAnswer`. It throws, for the app to answer 500, when
97
+ * resourceshark can't be reached or refuses the secret key, or when a
98
+ * hook throws anything but a `HoldRefusal`.
99
+ */
100
+ export declare function createHoldEndpoint<Caller, Place, Extend = void, Commit = void>(options: HoldEndpointOptions<Caller, Place, Extend, Commit>): HoldEndpoint<Caller, Place, Extend, Commit>;
101
+ export { type BuyInput, type BuyOutcome, type CommitInput, type CommitOutcome, type ExpiredLine, type ExtendInput, type PlaceInput, commitHold };
package/dist/server.js ADDED
@@ -0,0 +1,250 @@
1
+ import { n as ResourcesharkApiError, r as createClient } from "./client-D2ya4ahY.js";
2
+ import { i as apiTransport, o as WorkflowFailure, t as commitHold } from "./commit-B_gOf0Ji.js";
3
+ // src/server.ts
4
+ const ERRORS_PAGE = "https://agentpost.tools/docs/resourceshark/errors#";
5
+ /**
6
+ * A refusal from one of the app's hooks, such as a hold longer than the
7
+ * app allows or a user at their cap of open holds. It reaches the page as
8
+ * the standard error body, with the same detail rules as service refusals.
9
+ */
10
+ var HoldRefusal = class extends Error {
11
+ code;
12
+ status;
13
+ details;
14
+ errorClass;
15
+ constructor(code, message, status = 400, details, errorClass = "change_the_request") {
16
+ super(message);
17
+ this.name = "HoldRefusal";
18
+ this.code = code;
19
+ this.status = status;
20
+ this.errorClass = errorClass;
21
+ if (details !== void 0) this.details = details;
22
+ }
23
+ };
24
+ /**
25
+ * The customer's hold endpoint. Each method answers a refusal as an
26
+ * `EndpointAnswer`. It throws, for the app to answer 500, when
27
+ * resourceshark can't be reached or refuses the secret key, or when a
28
+ * hook throws anything but a `HoldRefusal`.
29
+ */
30
+ function createHoldEndpoint(options) {
31
+ if (typeof options.secretKey !== "string" || options.secretKey === "") throw new Error("createHoldEndpoint needs the project’s secret key");
32
+ const client = createClient({
33
+ baseUrl: options.baseUrl ?? "https://api.agentpost.tools/v1/resources",
34
+ token: options.secretKey,
35
+ ...options.fetch ? { fetch: options.fetch } : {}
36
+ });
37
+ const api = apiTransport(client, options.resourceCacheMs === void 0 ? {} : { resourceCacheMs: options.resourceCacheMs });
38
+ async function callerKey(caller) {
39
+ const key = await options.callerKey(caller);
40
+ if (typeof key !== "string" || key === "") throw new Error("callerKey must give a nonempty string for each caller");
41
+ return key;
42
+ }
43
+ /** The hold, if it exists and the caller owns it; otherwise the 404 to answer. */
44
+ async function ownedHold(holdId, caller) {
45
+ if (typeof holdId !== "string" || holdId === "") return { answer: noHold(holdId) };
46
+ let hold;
47
+ try {
48
+ ({hold} = await client.holds.get(holdId));
49
+ } catch (caught) {
50
+ if (caught instanceof ResourcesharkApiError && caught.status === 404) return { answer: noHold(holdId) };
51
+ throw caught;
52
+ }
53
+ if (!await options.owns(hold, caller)) return { answer: noHold(holdId) };
54
+ return { hold };
55
+ }
56
+ /** Runs an action and allows hold details only after the ownership check. */
57
+ async function onOwnedHold(holdId, caller, attemptKey, act) {
58
+ const bad = badAttemptKey(attemptKey);
59
+ if (bad) return bad;
60
+ let ownedHoldId;
61
+ try {
62
+ const read = await ownedHold(holdId, caller);
63
+ if ("answer" in read) return read.answer;
64
+ ownedHoldId = read.hold.id;
65
+ const key = await namespacedKey(await callerKey(caller), attemptKey);
66
+ return await act(read.hold, key);
67
+ } catch (caught) {
68
+ return refused(caught, ownedHoldId);
69
+ }
70
+ }
71
+ const endpoint = {
72
+ async slots(query, caller) {
73
+ try {
74
+ const asked = await options.slots(query, caller);
75
+ return {
76
+ status: 200,
77
+ body: await api.slots(asked)
78
+ };
79
+ } catch (caught) {
80
+ return refused(caught);
81
+ }
82
+ },
83
+ async place(input, caller, attemptKey) {
84
+ const bad = badAttemptKey(attemptKey);
85
+ if (bad) return bad;
86
+ try {
87
+ const asked = await options.place(input, caller);
88
+ const placed = await api.place(asked, await namespacedKey(await callerKey(caller), attemptKey));
89
+ if (!await options.owns(placed.hold, caller)) return failure(409, "duplicate_source", "change_the_request", TAKEN, { docs: `${ERRORS_PAGE}duplicate_source` });
90
+ return {
91
+ status: 201,
92
+ body: placed
93
+ };
94
+ } catch (caught) {
95
+ return refused(caught);
96
+ }
97
+ },
98
+ extend(holdId, input, caller, attemptKey) {
99
+ return onOwnedHold(holdId, caller, attemptKey, async (hold, key) => {
100
+ const asked = await options.extend(hold, input, caller);
101
+ return {
102
+ status: 200,
103
+ body: await api.extend(holdId, asked, key)
104
+ };
105
+ });
106
+ },
107
+ release(holdId, caller, attemptKey) {
108
+ return onOwnedHold(holdId, caller, attemptKey, async (_hold, key) => ({
109
+ status: 200,
110
+ body: await api.release(holdId, key)
111
+ }));
112
+ },
113
+ async commit(holdId, input, caller, attemptKey) {
114
+ const commit = options.commit;
115
+ if (!commit) return noCommit();
116
+ return onOwnedHold(holdId, caller, attemptKey, async (hold, key) => {
117
+ const asked = await commit(hold, input, caller);
118
+ return {
119
+ status: 200,
120
+ body: await api.commit(holdId, asked, key)
121
+ };
122
+ });
123
+ },
124
+ async handle(request, caller) {
125
+ const { pathname, searchParams } = new URL(request.url);
126
+ const route = routeOf(pathname);
127
+ if (!route) return respond(failure(404, "not_found", "change_the_request", "the hold endpoint answers GET /slots, POST /holds, and POST /holds/:id/extend, /release, and /commit"));
128
+ const method = route.action === "slots" ? "GET" : "POST";
129
+ if (request.method.toUpperCase() !== method) return respond(failure(405, "method_not_allowed", "change_the_request", `${route.action === "slots" ? "/slots" : pathname} takes ${method}`), { allow: method });
130
+ if (route.action === "slots") return respond(await endpoint.slots(Object.fromEntries(searchParams), caller));
131
+ if (route.action === "commit" && !options.commit) return respond(noCommit());
132
+ const attemptKey = request.headers.get("idempotency-key") ?? "";
133
+ if (route.action === "release") return respond(await endpoint.release(route.holdId, caller, attemptKey));
134
+ const body = await bodyOf(request);
135
+ if (!body) return respond(failure(400, "invalid_request", "change_the_request", "the body is JSON: { \"input\": … }", { docs: `${ERRORS_PAGE}invalid_request` }));
136
+ switch (route.action) {
137
+ case "place": return respond(await endpoint.place(body.input, caller, attemptKey));
138
+ case "extend": return respond(await endpoint.extend(route.holdId, body.input, caller, attemptKey));
139
+ case "commit": return respond(await endpoint.commit(route.holdId, body.input, caller, attemptKey));
140
+ }
141
+ }
142
+ };
143
+ return endpoint;
144
+ }
145
+ const TAKEN = "the sourceKey is already used by a different request";
146
+ function failure(status, code, errorClass, message, extra = {}) {
147
+ return {
148
+ status,
149
+ body: { error: {
150
+ code,
151
+ class: errorClass,
152
+ message,
153
+ ...extra.details === void 0 ? {} : { details: extra.details },
154
+ ...extra.docs === void 0 ? {} : { docs: extra.docs }
155
+ } }
156
+ };
157
+ }
158
+ /** The one answer for a hold that doesn't exist and a hold the caller doesn't own. */
159
+ function noHold(holdId) {
160
+ return failure(404, "not_found", "change_the_request", `no hold ${holdId}`, { docs: `${ERRORS_PAGE}not_found` });
161
+ }
162
+ function noCommit() {
163
+ return failure(404, "not_found", "change_the_request", "commit is disabled", { docs: `${ERRORS_PAGE}not_found` });
164
+ }
165
+ function badAttemptKey(attemptKey) {
166
+ const key = typeof attemptKey === "string" ? attemptKey.trim() : "";
167
+ if (key.length > 0 && key.length <= 255) return void 0;
168
+ return failure(400, "invalid_request", "change_the_request", "each POST needs an Idempotency-Key of 1 to 255 characters", { docs: `${ERRORS_PAGE}invalid_request` });
169
+ }
170
+ /**
171
+ * A refusal as the page may see it, or a throw for what the page can't
172
+ * act on: resourceshark unreachable, the secret key refused (401 or 403),
173
+ * or a hook's own bug.
174
+ */
175
+ function refused(caught, ownedHoldId) {
176
+ if (caught instanceof HoldRefusal) return failure(caught.status, caught.code, caught.errorClass, caught.message, { details: pageDetails(caught.code, caught.details, ownedHoldId) });
177
+ if (caught instanceof WorkflowFailure) return failure(400, caught.code, "change_the_request", caught.message);
178
+ if (caught instanceof ResourcesharkApiError && caught.status !== 401 && caught.status !== 403) return failure(caught.status, caught.code, caught.errorClass ?? (caught.status >= 500 ? "retry_later" : "change_the_request"), caught.code === "duplicate_source" ? TAKEN : caught.message, {
179
+ details: pageDetails(caught.code, caught.details, ownedHoldId),
180
+ ...caught.docs === void 0 ? {} : { docs: caught.docs }
181
+ });
182
+ throw caught;
183
+ }
184
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
185
+ /** Refusal details that may reach the page. Lines and scopes go whole. */
186
+ function pageDetails(code, details, ownedHoldId) {
187
+ switch (code) {
188
+ case "insufficient_supply":
189
+ case "exhausted_until_supply":
190
+ case "assignment_infeasible": {
191
+ const given = record(details);
192
+ if (!given) return void 0;
193
+ const kept = {};
194
+ if (Array.isArray(given.lines)) kept.lines = given.lines;
195
+ if (typeof given.nextSupplyAt === "string") kept.nextSupplyAt = given.nextSupplyAt;
196
+ return Object.keys(kept).length > 0 ? kept : void 0;
197
+ }
198
+ case "hold_expired":
199
+ case "hold_resolved": return ownedHoldId && record(details)?.holdId === ownedHoldId ? details : void 0;
200
+ default: return;
201
+ }
202
+ }
203
+ const HOLD_ACTIONS = /* @__PURE__ */ new Set([
204
+ "extend",
205
+ "release",
206
+ "commit"
207
+ ]);
208
+ /** The route the end of the path names, under whatever prefix the app mounted it at. */
209
+ function routeOf(pathname) {
210
+ const parts = pathname.split("/").filter((part) => part !== "");
211
+ const n = parts.length;
212
+ if (n >= 3 && parts[n - 3] === "holds" && HOLD_ACTIONS.has(parts[n - 1])) {
213
+ let holdId;
214
+ try {
215
+ holdId = decodeURIComponent(parts[n - 2]);
216
+ } catch {
217
+ return;
218
+ }
219
+ return {
220
+ action: parts[n - 1],
221
+ holdId
222
+ };
223
+ }
224
+ if (parts[n - 1] === "holds") return { action: "place" };
225
+ if (parts[n - 1] === "slots") return { action: "slots" };
226
+ }
227
+ /** Reads the transport's JSON envelope. It sends `{}` for an undefined input. */
228
+ async function bodyOf(request) {
229
+ try {
230
+ return record(await request.json());
231
+ } catch {
232
+ return;
233
+ }
234
+ }
235
+ function respond(answer, headers = {}) {
236
+ return new Response(JSON.stringify(answer.body), {
237
+ status: answer.status,
238
+ headers: {
239
+ "content-type": "application/json; charset=utf-8",
240
+ "cache-control": "no-store",
241
+ ...headers
242
+ }
243
+ });
244
+ }
245
+ async function namespacedKey(callerKey, key) {
246
+ const value = JSON.stringify([callerKey, key.trim()]);
247
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
248
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
249
+ }
250
+ export { HoldRefusal, commitHold, createHoldEndpoint };
@@ -0,0 +1,103 @@
1
+ import { Qt as RetainedHold, an as ShortLine, nt as Hold, on as Slot, pt as HoldResolvedDetails, sn as SlotsQuery } from "../client-C-4s_6Qp.js";
2
+ import { a as WorkflowError, c as CommitInput, d as HoldTransport, f as PlaceInput, i as commitHold, l as EndpointTransportOptions, m as endpointTransport, n as CommitOutcome, o as ApiTransportOptions, p as apiTransport, r as ExpiredLine, s as BuyInput, t as BuyOutcome, u as ExtendInput } from "../commit-BxtiTSez.js";
3
+ interface Store<T> {
4
+ getSnapshot(): T;
5
+ subscribe(listener: () => void): () => void;
6
+ }
7
+ type HoldStep = 'idle' | 'held' | 'short' | 'expired' | 'committed' | 'released' | 'resolved';
8
+ type HoldAction = 'slots' | 'place' | 'extend' | 'release' | 'commit';
9
+ /** One read of a resource's slots. */
10
+ interface SlotRead {
11
+ query: SlotsQuery;
12
+ slots: Slot[];
13
+ }
14
+ interface HoldWorkflowState {
15
+ step: HoldStep;
16
+ /** One entry per scope read (resource, place, condition, and unit), the latest read of each; no pooling. */
17
+ slots: SlotRead[];
18
+ /** The hold as the service last answered it. */
19
+ hold: Hold | null;
20
+ expiresAt: string | null;
21
+ /** Whole seconds left by the server's clock (serverNow offset), while a hold is held; 0 once expired. Ticks only while subscribed. Advisory. */
22
+ secondsLeft: number | null;
23
+ /** What each short line has free, after a hold was refused in full. */
24
+ short: ShortLine[] | null;
25
+ /** Each line of an expired commit, with what is available now; null when retention removed them. */
26
+ expired: ExpiredLine[] | null;
27
+ /** True while a request is out. */
28
+ pending: boolean;
29
+ /** The write that is out, or `slots` while only reads are. */
30
+ pendingAction: HoldAction | null;
31
+ /** Why the last request failed or was refused, until the next write starts. */
32
+ error: WorkflowError | null;
33
+ }
34
+ type ListSlotsOutcome = {
35
+ status: 'listed';
36
+ slots: Slot[];
37
+ } | {
38
+ status: 'failed';
39
+ error: WorkflowError;
40
+ };
41
+ /**
42
+ * What a place came to. `short` is refused in full: nothing was held, and
43
+ * the workflow never asks again for less. `superseded` means `reset` ran
44
+ * before the answer came, so it was dropped.
45
+ */
46
+ type PlaceOutcome = {
47
+ status: 'held';
48
+ hold: Hold;
49
+ } | {
50
+ status: 'short';
51
+ lines: ShortLine[];
52
+ nextSupplyAt?: string;
53
+ } | {
54
+ status: 'failed';
55
+ error: WorkflowError;
56
+ } | {
57
+ status: 'superseded';
58
+ };
59
+ type ExtendOutcome = {
60
+ status: 'extended';
61
+ hold: Hold;
62
+ } | {
63
+ status: 'expired';
64
+ expiresAt: string;
65
+ } | {
66
+ status: 'resolved';
67
+ resolution: HoldResolvedDetails;
68
+ } | {
69
+ status: 'failed';
70
+ error: WorkflowError;
71
+ };
72
+ type ReleaseOutcome = {
73
+ status: 'released';
74
+ hold: Hold | RetainedHold;
75
+ } | {
76
+ status: 'resolved';
77
+ resolution: HoldResolvedDetails;
78
+ } | {
79
+ status: 'failed';
80
+ error: WorkflowError;
81
+ };
82
+ interface HoldWorkflow<P, E, C> extends Store<HoldWorkflowState> {
83
+ /** Reads one resource's slots; the read replaces the last one of the same scope in `slots`. */
84
+ listSlots(q: SlotsQuery): Promise<ListSlotsOutcome>;
85
+ /** Places a hold. Refused with `hold_open` while a hold is held and not past its expiry. */
86
+ place(input: P): Promise<PlaceOutcome>;
87
+ extend(input: E): Promise<ExtendOutcome>;
88
+ release(): Promise<ReleaseOutcome>;
89
+ /** Commits the hold, also after an extension was refused as expired, to learn what is available and get `buy`. */
90
+ commit(input: C): Promise<CommitOutcome>;
91
+ /** Back to idle, forgetting the hold and dropping any answer still out. It doesn't release an open hold: release it first, or it runs out at `expiresAt`. Slots stay. */
92
+ reset(): void;
93
+ /** Stops the countdown timer for good. */
94
+ dispose(): void;
95
+ }
96
+ interface HoldWorkflowOptions {
97
+ /** This device's clock, in ms since the epoch. */
98
+ now?: () => number;
99
+ setTimer?: typeof setTimeout;
100
+ clearTimer?: typeof clearTimeout;
101
+ }
102
+ export declare function createHoldWorkflow<P, E, C>(transport: HoldTransport<P, E, C>, options?: HoldWorkflowOptions): HoldWorkflow<P, E, C>;
103
+ export { type ApiTransportOptions, type BuyInput, type BuyOutcome, type CommitInput, type CommitOutcome, type EndpointTransportOptions, type ExpiredLine, type ExtendInput, type ExtendOutcome, type HoldAction, type HoldStep, type HoldTransport, type HoldWorkflow, type HoldWorkflowOptions, type HoldWorkflowState, type ListSlotsOutcome, type PlaceInput, type PlaceOutcome, type ReleaseOutcome, type SlotRead, type Store, type WorkflowError, apiTransport, commitHold, endpointTransport };