@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,519 @@
1
+ import { a as endpointTransport, c as resolvedOf, i as apiTransport, l as shortOf, n as expiredLines, r as expiredOutcome, s as expiredOf, t as commitHold, u as toWorkflowError } from "../commit-B_gOf0Ji.js";
2
+ // src/workflows/store.ts
3
+ function createStore(initial, onWatch) {
4
+ let snapshot = initial;
5
+ const listeners = /* @__PURE__ */ new Set();
6
+ return {
7
+ getSnapshot: () => snapshot,
8
+ subscribe(listener) {
9
+ listeners.add(listener);
10
+ if (listeners.size === 1) onWatch?.(true);
11
+ return () => {
12
+ if (listeners.delete(listener) && listeners.size === 0) onWatch?.(false);
13
+ };
14
+ },
15
+ set(next) {
16
+ let changed = false;
17
+ for (const key of Object.keys(next)) if (!Object.is(snapshot[key], next[key])) changed = true;
18
+ if (!changed) return;
19
+ snapshot = {
20
+ ...snapshot,
21
+ ...next
22
+ };
23
+ for (const listener of [...listeners]) listener();
24
+ },
25
+ watchers: () => listeners.size
26
+ };
27
+ }
28
+ // src/workflows/hold.ts
29
+ function createHoldWorkflow(transport, options = {}) {
30
+ const now = options.now ?? Date.now;
31
+ const schedule = (tick, ms) => options.setTimer ? options.setTimer(tick, ms) : setTimeout(tick, ms);
32
+ const unschedule = (handle) => {
33
+ if (options.clearTimer) options.clearTimer(handle);
34
+ else clearTimeout(handle);
35
+ };
36
+ let timer;
37
+ let disposed = false;
38
+ /** The server's clock less this device's, in ms. */
39
+ let offset = 0;
40
+ let running = null;
41
+ const reads = /* @__PURE__ */ new Map();
42
+ let retry = null;
43
+ let generation = 0;
44
+ const store = createStore({
45
+ step: "idle",
46
+ slots: [],
47
+ hold: null,
48
+ expiresAt: null,
49
+ secondsLeft: null,
50
+ short: null,
51
+ expired: null,
52
+ pending: false,
53
+ pendingAction: null,
54
+ error: null
55
+ }, (watching) => watching ? tick() : stopTimer());
56
+ function stopTimer() {
57
+ if (timer !== void 0) unschedule(timer);
58
+ timer = void 0;
59
+ }
60
+ const serverClock = () => now() + offset;
61
+ function setClock(serverNow) {
62
+ const at = Date.parse(serverNow);
63
+ if (Number.isFinite(at)) offset = at - now();
64
+ }
65
+ /** Whether the hold is past its expiry by the server's clock. */
66
+ function lapsed() {
67
+ const { expiresAt } = store.getSnapshot();
68
+ return expiresAt !== null && Date.parse(expiresAt) <= serverClock();
69
+ }
70
+ /** Brings `secondsLeft` up to date, and wakes again when its number next changes. */
71
+ function tick() {
72
+ stopTimer();
73
+ const { step, expiresAt } = store.getSnapshot();
74
+ if (step !== "held" || expiresAt === null) {
75
+ store.set({ secondsLeft: step === "expired" ? 0 : null });
76
+ return;
77
+ }
78
+ const left = Date.parse(expiresAt) - serverClock();
79
+ const seconds = Number.isFinite(left) ? Math.max(0, Math.ceil(left / 1e3)) : null;
80
+ store.set({ secondsLeft: seconds });
81
+ if (!disposed && seconds !== null && seconds > 0 && store.watchers() > 0) timer = schedule(tick, (left % 1e3 || 1e3) + 1);
82
+ }
83
+ function pendingState() {
84
+ return {
85
+ pending: running !== null || reads.size > 0,
86
+ pendingAction: running?.action ?? (reads.size > 0 ? "slots" : null)
87
+ };
88
+ }
89
+ /** Fails an action before any request. Except for `busy`, whose request already out answers for it, the error shows in the state. */
90
+ function refuse(code, message, details) {
91
+ const error = {
92
+ code,
93
+ message,
94
+ ...details === void 0 ? {} : { details }
95
+ };
96
+ if (code !== "busy") store.set({ error });
97
+ return {
98
+ status: "failed",
99
+ error
100
+ };
101
+ }
102
+ /** The request already out for the same action and input, or `busy`; null when none is out. */
103
+ function inFlight(action, signature) {
104
+ if (!running) return null;
105
+ if (running.action === action && running.signature === signature) return running.outcome;
106
+ return Promise.resolve(refuse("busy", `a ${running.action} request is still out; wait for its answer`));
107
+ }
108
+ /** Runs one write: its attempt key, its pending state, and what its answer leaves. */
109
+ function run(action, signature, work, failed, superseded) {
110
+ const key = retry && retry.action === action && retry.signature === signature ? retry.key : newKey();
111
+ const at = generation;
112
+ let settle;
113
+ const outcome = new Promise((resolve) => {
114
+ settle = resolve;
115
+ });
116
+ const entry = {
117
+ action,
118
+ signature,
119
+ outcome
120
+ };
121
+ running = entry;
122
+ store.set({
123
+ error: null,
124
+ ...pendingState()
125
+ });
126
+ const answer = async () => {
127
+ let answered;
128
+ try {
129
+ answered = await work(key);
130
+ if (at === generation) retry = null;
131
+ } catch (caught) {
132
+ const error = toWorkflowError(caught);
133
+ if (at === generation) retry = error.code === "network_error" ? {
134
+ action,
135
+ signature,
136
+ key
137
+ } : null;
138
+ answered = failed(error);
139
+ }
140
+ if (running === entry) running = null;
141
+ if (at !== generation) {
142
+ store.set(pendingState());
143
+ return superseded ?? answered.outcome;
144
+ }
145
+ store.set({
146
+ ...answered.state,
147
+ ...pendingState()
148
+ });
149
+ tick();
150
+ return answered.outcome;
151
+ };
152
+ settle(answer());
153
+ return outcome;
154
+ }
155
+ /** The state and outcome for `hold_expired` or `hold_resolved`, or null for another error. */
156
+ function ended(error) {
157
+ if (error.code === "hold_expired") {
158
+ const expiresAt = expiredOf(error)?.expiresAt ?? store.getSnapshot().expiresAt ?? "";
159
+ return {
160
+ outcome: {
161
+ status: "expired",
162
+ expiresAt
163
+ },
164
+ state: {
165
+ step: "expired",
166
+ expiresAt,
167
+ expired: null,
168
+ error
169
+ }
170
+ };
171
+ }
172
+ const resolution = resolvedOf(error);
173
+ if (resolution) return {
174
+ outcome: {
175
+ status: "resolved",
176
+ resolution
177
+ },
178
+ state: {
179
+ step: "resolved",
180
+ error
181
+ }
182
+ };
183
+ return null;
184
+ }
185
+ /** `busy` when a different write is out; null when none is, or the same kind is (its input decides). */
186
+ function busyWith(action) {
187
+ if (!running || running.action === action) return null;
188
+ return Promise.resolve(refuse("busy", `a ${running.action} request is still out; wait for its answer`));
189
+ }
190
+ /** The hold to act on, when the step allows the action. */
191
+ function holdIn(steps) {
192
+ const { step, hold } = store.getSnapshot();
193
+ return hold && steps.includes(step) ? hold : null;
194
+ }
195
+ const noHold = (action) => Promise.resolve(refuse("no_hold", `there is no open hold to ${action}`));
196
+ return {
197
+ subscribe: store.subscribe,
198
+ getSnapshot: store.getSnapshot,
199
+ listSlots(q) {
200
+ const signature = signatureOf(q);
201
+ const out = reads.get(signature);
202
+ if (out) return out;
203
+ const read = new Promise((resolve) => resolve(transport.slots(q))).then((answer) => {
204
+ setClock(answer.serverNow);
205
+ reads.delete(signature);
206
+ store.set({
207
+ slots: withRead(store.getSnapshot().slots, {
208
+ query: q,
209
+ slots: answer.slots
210
+ }),
211
+ ...pendingState()
212
+ });
213
+ return {
214
+ status: "listed",
215
+ slots: answer.slots
216
+ };
217
+ }, (caught) => {
218
+ const error = toWorkflowError(caught);
219
+ reads.delete(signature);
220
+ store.set({
221
+ error,
222
+ ...pendingState()
223
+ });
224
+ return {
225
+ status: "failed",
226
+ error
227
+ };
228
+ });
229
+ reads.set(signature, read);
230
+ store.set(pendingState());
231
+ return read;
232
+ },
233
+ place(input) {
234
+ const signature = signatureOf(input);
235
+ const out = inFlight("place", signature);
236
+ if (out) return out;
237
+ const { step, hold } = store.getSnapshot();
238
+ if (step === "held" && hold && !lapsed()) return Promise.resolve(refuse("hold_open", `hold ${hold.id} is still open: commit or release it first, or wait for it to run out`, { holdId: hold.id }));
239
+ return run("place", signature, async (key) => {
240
+ const answer = await transport.place(input, key);
241
+ setClock(answer.serverNow);
242
+ const placed = answer.hold;
243
+ if (isRetained(placed) || placed.status !== "open") {
244
+ const resolution = {
245
+ holdId: placed.id,
246
+ status: placed.status,
247
+ resolution: placed.resolution ?? { at: isRetained(placed) ? placed.retainedAt : placed.expiresAt }
248
+ };
249
+ const error = {
250
+ code: "hold_resolved",
251
+ message: `the sourceKey already named hold ${placed.id}, which is ${resolution.status}`,
252
+ details: resolution
253
+ };
254
+ return {
255
+ outcome: {
256
+ status: "failed",
257
+ error
258
+ },
259
+ state: {
260
+ step: "resolved",
261
+ hold: isRetained(placed) ? null : placed,
262
+ expiresAt: null,
263
+ short: null,
264
+ expired: null,
265
+ error
266
+ }
267
+ };
268
+ }
269
+ return {
270
+ outcome: {
271
+ status: "held",
272
+ hold: placed
273
+ },
274
+ state: {
275
+ step: "held",
276
+ hold: placed,
277
+ expiresAt: placed.expiresAt,
278
+ short: null,
279
+ expired: null
280
+ }
281
+ };
282
+ }, (error) => {
283
+ const short = shortOf(error);
284
+ if (short) return {
285
+ outcome: {
286
+ status: "short",
287
+ ...short
288
+ },
289
+ state: {
290
+ step: "short",
291
+ hold: null,
292
+ expiresAt: null,
293
+ short: short.lines,
294
+ expired: null,
295
+ error
296
+ }
297
+ };
298
+ return {
299
+ outcome: {
300
+ status: "failed",
301
+ error
302
+ },
303
+ state: { error }
304
+ };
305
+ }, { status: "superseded" });
306
+ },
307
+ extend(input) {
308
+ const busy = busyWith("extend");
309
+ if (busy) return busy;
310
+ const held = holdIn(["held"]);
311
+ if (!held) return noHold("extend");
312
+ const signature = `${held.id}:${signatureOf(input)}`;
313
+ const out = inFlight("extend", signature);
314
+ if (out) return out;
315
+ return run("extend", signature, async (key) => {
316
+ const answer = await transport.extend(held.id, input, key);
317
+ setClock(answer.serverNow);
318
+ const extended = answer.hold;
319
+ if (isRetained(extended)) return {
320
+ outcome: {
321
+ status: "resolved",
322
+ resolution: {
323
+ holdId: extended.id,
324
+ status: extended.status,
325
+ resolution: extended.resolution
326
+ }
327
+ },
328
+ state: { step: "resolved" }
329
+ };
330
+ return {
331
+ outcome: {
332
+ status: "extended",
333
+ hold: extended
334
+ },
335
+ state: {
336
+ hold: extended,
337
+ expiresAt: extended.expiresAt
338
+ }
339
+ };
340
+ }, (error) => ended(error) ?? {
341
+ outcome: {
342
+ status: "failed",
343
+ error
344
+ },
345
+ state: { error }
346
+ });
347
+ },
348
+ release() {
349
+ const busy = busyWith("release");
350
+ if (busy) return busy;
351
+ const held = holdIn(["held"]);
352
+ if (!held) return noHold("release");
353
+ const signature = held.id;
354
+ const out = inFlight("release", signature);
355
+ if (out) return out;
356
+ return run("release", signature, async (key) => {
357
+ const answer = await transport.release(held.id, key);
358
+ setClock(answer.serverNow);
359
+ const released = answer.hold;
360
+ return {
361
+ outcome: {
362
+ status: "released",
363
+ hold: released
364
+ },
365
+ state: {
366
+ step: "released",
367
+ ...isRetained(released) ? {} : { hold: released }
368
+ }
369
+ };
370
+ }, (error) => {
371
+ const resolution = resolvedOf(error);
372
+ if (resolution) return {
373
+ outcome: {
374
+ status: "resolved",
375
+ resolution
376
+ },
377
+ state: {
378
+ step: "resolved",
379
+ error
380
+ }
381
+ };
382
+ return {
383
+ outcome: {
384
+ status: "failed",
385
+ error
386
+ },
387
+ state: { error }
388
+ };
389
+ });
390
+ },
391
+ commit(input) {
392
+ const busy = busyWith("commit");
393
+ if (busy) return busy;
394
+ const held = holdIn(["held", "expired"]);
395
+ if (!held) return noHold("commit");
396
+ const signature = `${held.id}:${signatureOf(input)}`;
397
+ const out = inFlight("commit", signature);
398
+ if (out) return out;
399
+ const missing = linesLeftOut(input, held);
400
+ if (missing.length > 0) return Promise.resolve(refuse("invalid_request", `a commit that lists lines names every line of the hold; it leaves out ${missing.join(", ")}`, {
401
+ field: "lines",
402
+ missing
403
+ }));
404
+ return run("commit", signature, async (key) => {
405
+ const answer = await transport.commit(held.id, input, key);
406
+ setClock(answer.serverNow);
407
+ return {
408
+ outcome: {
409
+ status: "committed",
410
+ hold: answer.hold,
411
+ movements: answer.movements,
412
+ ...answer.duplicate ? { duplicate: true } : {}
413
+ },
414
+ state: {
415
+ step: "committed",
416
+ ...isRetained(answer.hold) ? {} : { hold: answer.hold },
417
+ short: null,
418
+ expired: null
419
+ }
420
+ };
421
+ }, (error) => {
422
+ if (error.code === "hold_expired") {
423
+ const details = expiredOf(error) ?? {
424
+ holdId: held.id,
425
+ expiresAt: held.expiresAt
426
+ };
427
+ const lines = expiredLines(details, held);
428
+ const buy = transport.buy?.bind(transport) ?? null;
429
+ return {
430
+ outcome: expiredOutcome(details, lines, buy),
431
+ state: {
432
+ step: "expired",
433
+ expiresAt: details.expiresAt,
434
+ expired: lines,
435
+ error
436
+ }
437
+ };
438
+ }
439
+ const resolution = resolvedOf(error);
440
+ if (resolution) return {
441
+ outcome: {
442
+ status: "resolved",
443
+ resolution
444
+ },
445
+ state: {
446
+ step: "resolved",
447
+ error
448
+ }
449
+ };
450
+ return {
451
+ outcome: {
452
+ status: "failed",
453
+ error
454
+ },
455
+ state: { error }
456
+ };
457
+ });
458
+ },
459
+ reset() {
460
+ generation += 1;
461
+ running = null;
462
+ retry = null;
463
+ store.set({
464
+ step: "idle",
465
+ hold: null,
466
+ expiresAt: null,
467
+ short: null,
468
+ expired: null,
469
+ error: null,
470
+ ...pendingState()
471
+ });
472
+ tick();
473
+ },
474
+ dispose() {
475
+ disposed = true;
476
+ stopTimer();
477
+ }
478
+ };
479
+ }
480
+ const isRetained = (hold) => "retainedAt" in hold;
481
+ /**
482
+ * The hold's lines a commit's nonempty `lines` leaves out, for a commit
483
+ * input shaped like `CommitInput`. An app's own commit shape, sent through
484
+ * its endpoint, is checked there instead.
485
+ */
486
+ function linesLeftOut(input, hold) {
487
+ const lines = input?.lines;
488
+ if (!Array.isArray(lines) || lines.length === 0) return [];
489
+ const named = new Set(lines.map((line) => line?.claimId));
490
+ if (![...named].every((id) => typeof id === "string")) return [];
491
+ return hold.lines.map(({ claimId }) => claimId).filter((id) => !named.has(id));
492
+ }
493
+ /** The slots kept, with this read in place of the last one of the same scope. */
494
+ function withRead(reads, read) {
495
+ const scopeOf = ({ query }) => signatureOf([
496
+ query.resourceId,
497
+ query.placeId,
498
+ query.condition,
499
+ query.instanceId
500
+ ]);
501
+ const key = scopeOf(read);
502
+ const at = reads.findIndex((kept) => scopeOf(kept) === key);
503
+ return at === -1 ? [...reads, read] : reads.map((kept, i) => i === at ? read : kept);
504
+ }
505
+ /** A stable text for an input, its object keys sorted, to tell the same action with the same input. */
506
+ function signatureOf(value) {
507
+ return JSON.stringify(value, (_key, field) => field !== null && typeof field === "object" && !Array.isArray(field) ? Object.fromEntries(Object.entries(field).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : field) ?? "";
508
+ }
509
+ /** A new attempt key. */
510
+ function newKey() {
511
+ const crypto = globalThis.crypto;
512
+ if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
513
+ const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
514
+ bytes[6] = bytes[6] & 15 | 64;
515
+ bytes[8] = bytes[8] & 63 | 128;
516
+ const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
517
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
518
+ }
519
+ export { apiTransport, commitHold, createHoldWorkflow, endpointTransport };
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@agentpost-tools/resourceshark-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "A typed client for resourceshark, for servers and browsers, with the framework-independent hold and booking workflows.",
5
+ "license": "SEE LICENSE IN LICENSE.md",
6
+ "homepage": "https://agentpost.tools/docs/resourceshark/sdk",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/jayalberts/agentpost.git",
10
+ "directory": "packages/resourceshark-sdk"
11
+ },
12
+ "type": "module",
13
+ "sideEffects": false,
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "./workflows": {
20
+ "types": "./dist/workflows/index.d.ts",
21
+ "default": "./dist/workflows/index.js"
22
+ },
23
+ "./server": {
24
+ "types": "./dist/server.d.ts",
25
+ "default": "./dist/server.js"
26
+ },
27
+ "./helpers": {
28
+ "types": "./dist/helpers/index.d.ts",
29
+ "default": "./dist/helpers/index.js"
30
+ }
31
+ },
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "publishConfig": {
36
+ "access": "public"
37
+ }
38
+ }