@sess.si/sdk 0.0.0-stage → 0.1.0-rc.4

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.
Files changed (95) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +9 -0
  4. package/README.md +136 -2
  5. package/dist/client.d.ts +12 -0
  6. package/dist/client.d.ts.map +1 -0
  7. package/dist/client.js +34 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/errors.d.ts +40 -0
  10. package/dist/errors.d.ts.map +1 -0
  11. package/dist/errors.js +52 -0
  12. package/dist/errors.js.map +1 -0
  13. package/dist/generated/openapi.d.ts +2462 -0
  14. package/dist/generated/openapi.d.ts.map +1 -0
  15. package/dist/generated/openapi.js +2 -0
  16. package/dist/generated/openapi.js.map +1 -0
  17. package/dist/index.d.ts +5 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +4 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/internal/decode.d.ts +21 -0
  22. package/dist/internal/decode.d.ts.map +1 -0
  23. package/dist/internal/decode.js +333 -0
  24. package/dist/internal/decode.js.map +1 -0
  25. package/dist/internal/json.d.ts +4 -0
  26. package/dist/internal/json.d.ts.map +1 -0
  27. package/dist/internal/json.js +75 -0
  28. package/dist/internal/json.js.map +1 -0
  29. package/dist/internal/time.d.ts +11 -0
  30. package/dist/internal/time.d.ts.map +1 -0
  31. package/dist/internal/time.js +71 -0
  32. package/dist/internal/time.js.map +1 -0
  33. package/dist/polling.d.ts +3 -0
  34. package/dist/polling.d.ts.map +1 -0
  35. package/dist/polling.js +61 -0
  36. package/dist/polling.js.map +1 -0
  37. package/dist/receipts/index.d.ts +5 -0
  38. package/dist/receipts/index.d.ts.map +1 -0
  39. package/dist/receipts/index.js +2 -0
  40. package/dist/receipts/index.js.map +1 -0
  41. package/dist/receipts/json.d.ts +22 -0
  42. package/dist/receipts/json.d.ts.map +1 -0
  43. package/dist/receipts/json.js +152 -0
  44. package/dist/receipts/json.js.map +1 -0
  45. package/dist/receipts/key-cache.d.ts +28 -0
  46. package/dist/receipts/key-cache.d.ts.map +1 -0
  47. package/dist/receipts/key-cache.js +110 -0
  48. package/dist/receipts/key-cache.js.map +1 -0
  49. package/dist/receipts/resource.d.ts +39 -0
  50. package/dist/receipts/resource.d.ts.map +1 -0
  51. package/dist/receipts/resource.js +119 -0
  52. package/dist/receipts/resource.js.map +1 -0
  53. package/dist/receipts/verify.d.ts +90 -0
  54. package/dist/receipts/verify.d.ts.map +1 -0
  55. package/dist/receipts/verify.js +294 -0
  56. package/dist/receipts/verify.js.map +1 -0
  57. package/dist/sessions.d.ts +19 -0
  58. package/dist/sessions.d.ts.map +1 -0
  59. package/dist/sessions.js +145 -0
  60. package/dist/sessions.js.map +1 -0
  61. package/dist/transport.d.ts +29 -0
  62. package/dist/transport.d.ts.map +1 -0
  63. package/dist/transport.js +447 -0
  64. package/dist/transport.js.map +1 -0
  65. package/dist/types.d.ts +149 -0
  66. package/dist/types.d.ts.map +1 -0
  67. package/dist/types.js +9 -0
  68. package/dist/types.js.map +1 -0
  69. package/dist/webhook-resource.d.ts +13 -0
  70. package/dist/webhook-resource.d.ts.map +1 -0
  71. package/dist/webhook-resource.js +52 -0
  72. package/dist/webhook-resource.js.map +1 -0
  73. package/dist/webhooks/index.d.ts +22 -0
  74. package/dist/webhooks/index.d.ts.map +1 -0
  75. package/dist/webhooks/index.js +184 -0
  76. package/dist/webhooks/index.js.map +1 -0
  77. package/package.json +74 -4
  78. package/src/client.ts +41 -0
  79. package/src/errors.ts +96 -0
  80. package/src/generated/openapi.ts +2578 -0
  81. package/src/index.ts +4 -0
  82. package/src/internal/decode.ts +317 -0
  83. package/src/internal/json.ts +64 -0
  84. package/src/internal/time.ts +85 -0
  85. package/src/polling.ts +77 -0
  86. package/src/receipts/index.ts +16 -0
  87. package/src/receipts/json.ts +168 -0
  88. package/src/receipts/key-cache.ts +143 -0
  89. package/src/receipts/resource.ts +227 -0
  90. package/src/receipts/verify.ts +468 -0
  91. package/src/sessions.ts +227 -0
  92. package/src/transport.ts +524 -0
  93. package/src/types.ts +135 -0
  94. package/src/webhook-resource.ts +81 -0
  95. package/src/webhooks/index.ts +246 -0
@@ -0,0 +1,524 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { SessError, attachRecovery } from './errors.js';
3
+ import type { SessErrorDetails, WriteOutcome } from './errors.js';
4
+ import type { ApiResult, CreateSessionResponse, RequestOptions, ResponseMeta, SessOptions } from './types.js';
5
+ import { isLoopback } from './internal/decode.js';
6
+ import { serializeBody } from './internal/json.js';
7
+ import { abortError, boundedNumber, deadline, delay, withSignal } from './internal/time.js';
8
+
9
+ export interface Operation<T> {
10
+ name: string;
11
+ method: 'GET' | 'POST' | 'PATCH' | 'PUT';
12
+ path: string;
13
+ status: number;
14
+ parse?: (value: unknown) => T;
15
+ body?: unknown;
16
+ versioned?: boolean;
17
+ retry: 'safe' | 'mutation' | 'never';
18
+ ifMatch?: string;
19
+ idempotencyKey?: string;
20
+ authenticated?: boolean;
21
+ }
22
+ const transientStatuses = new Set([408, 429, 500, 502, 503, 504]);
23
+ const rejections: Record<number, readonly string[]> = {
24
+ 400: ['INVALID_SCHEMA', 'UNKNOWN_COMPONENT', 'WEBHOOK_INVALID_URL'],
25
+ 401: ['UNAUTHORIZED'],
26
+ 403: ['ACTION_NOT_ALLOWED'],
27
+ 404: ['NOT_FOUND', 'SESSION_NOT_FOUND'],
28
+ 409: [
29
+ 'SESSION_REVISION_CONFLICT',
30
+ 'IDEMPOTENCY_CONFLICT',
31
+ 'SESSION_COMPLETED',
32
+ 'WEBHOOK_NOT_CONFIGURED',
33
+ 'RESPONSE_LIMIT_REACHED',
34
+ ],
35
+ 412: ['SESSION_REVISION_CONFLICT'],
36
+ 413: ['PAYLOAD_TOO_LARGE'],
37
+ 422: ['VALIDATION_FAILED', 'WEBHOOK_VERIFICATION_FAILED'],
38
+ 428: ['PRECONDITION_REQUIRED'],
39
+ };
40
+
41
+ function credential(value: unknown): string {
42
+ if (typeof value !== 'string' || !/^[\x21-\x7e]{1,4096}$/.test(value)) {
43
+ throw new SessError(
44
+ 'configuration',
45
+ 'Supply a nonempty server-side SESS API key without whitespace or control characters.',
46
+ { code: 'INVALID_API_KEY', outcome: 'not_sent' },
47
+ );
48
+ }
49
+ return value;
50
+ }
51
+ export function strongETag(value: unknown): value is string {
52
+ return typeof value === 'string' && /^"[\x21\x23-\x7e\x80-\xff]{0,1024}"$/.test(value);
53
+ }
54
+ export function pathSegment(value: string): string {
55
+ if (
56
+ typeof value !== 'string' ||
57
+ !value.length ||
58
+ value.length > 512 ||
59
+ /[\u0000-\u0020\u007f]/.test(value) ||
60
+ value === '.' ||
61
+ value === '..'
62
+ ) {
63
+ throw new SessError('configuration', 'Resource ID must be a nonempty path segment.', {
64
+ outcome: 'not_sent',
65
+ });
66
+ }
67
+ try {
68
+ return encodeURIComponent(value);
69
+ } catch {
70
+ throw new SessError('configuration', 'Resource ID has invalid encoding.', { outcome: 'not_sent' });
71
+ }
72
+ }
73
+ function origin(input: string | undefined, allowInsecure: boolean): string {
74
+ const text = input ?? 'https://api.sess.si';
75
+ let url: URL;
76
+ try {
77
+ url = new URL(text);
78
+ } catch {
79
+ throw new SessError('configuration', 'baseUrl must be a trusted absolute API origin.', {
80
+ outcome: 'not_sent',
81
+ });
82
+ }
83
+ if (
84
+ text !== text.trim() ||
85
+ /[\u0000-\u0020\u007f\\]/.test(text) ||
86
+ url.username ||
87
+ url.password ||
88
+ url.search ||
89
+ url.hash ||
90
+ url.pathname !== '/' ||
91
+ !(url.protocol === 'https:' || (url.protocol === 'http:' && allowInsecure && isLoopback(url.hostname)))
92
+ ) {
93
+ throw new SessError(
94
+ 'configuration',
95
+ 'baseUrl requires HTTPS and an origin without credentials, path, query, or fragment. Only explicit loopback development may use HTTP.',
96
+ { outcome: 'not_sent' },
97
+ );
98
+ }
99
+ return url.origin;
100
+ }
101
+ function safeText(
102
+ value: unknown,
103
+ pattern: RegExp,
104
+ key?: string,
105
+ opaqueIdentifier = false,
106
+ ): string | undefined {
107
+ if (
108
+ typeof value !== 'string' ||
109
+ !pattern.test(value) ||
110
+ /sess_(?:sk|mg|tk|mk)_|whsec_|eyJ/.test(value) ||
111
+ (opaqueIdentifier && /^[A-Za-z0-9_-]{43}$/.test(value)) ||
112
+ (key && value.includes(key))
113
+ )
114
+ return undefined;
115
+ return value;
116
+ }
117
+ export function retryAfter(header: string | null): number | undefined {
118
+ if (header === null) return undefined;
119
+ if (/^\d+$/.test(header.trim())) {
120
+ const ms = Number(header.trim()) * 1000;
121
+ return Number.isSafeInteger(ms) ? ms : undefined;
122
+ }
123
+ // HTTP-date only; Date.parse alone also accepts misleading values such as "1.5".
124
+ if (!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(header)) return undefined;
125
+ const date = Date.parse(header);
126
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : undefined;
127
+ }
128
+ async function readBody(response: Response, maxBytes: number, signal: AbortSignal): Promise<string> {
129
+ if (!response.body) return '';
130
+ const reader = response.body.getReader();
131
+ const parts: Uint8Array[] = [];
132
+ let bytes = 0;
133
+ let done = false;
134
+ try {
135
+ while (true) {
136
+ const result = await withSignal(
137
+ reader.read().catch(() => {
138
+ throw new SessError('transport', 'API response stream failed.');
139
+ }),
140
+ signal,
141
+ );
142
+ if (result.done) {
143
+ done = true;
144
+ break;
145
+ }
146
+ bytes += result.value.byteLength;
147
+ if (bytes > maxBytes)
148
+ throw new SessError('protocol', 'Response body exceeds the configured byte limit.', {
149
+ code: 'RESPONSE_TOO_LARGE',
150
+ });
151
+ parts.push(result.value);
152
+ }
153
+ try {
154
+ return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(parts, bytes));
155
+ } catch {
156
+ throw new SessError('protocol', 'Response contains invalid UTF-8.', { code: 'INVALID_RESPONSE' });
157
+ }
158
+ } finally {
159
+ if (!done) void reader.cancel().catch(() => {});
160
+ try {
161
+ reader.releaseLock();
162
+ } catch {
163
+ /* cancelled reader may still settle */
164
+ }
165
+ }
166
+ }
167
+
168
+ /** Shared policy for owner operations and unauthenticated receipt-key reads. */
169
+ export class Transport {
170
+ readonly baseUrl: string;
171
+ readonly receiptIssuer: string;
172
+ readonly expectedWorkspaceId?: string;
173
+ readonly operationTimeoutMs: number;
174
+ readonly allowInsecureLocalhost: boolean;
175
+ #apiKey: SessOptions['apiKey'];
176
+ #fetch: typeof globalThis.fetch;
177
+ #timeoutMs: number;
178
+ #maxRetries: number;
179
+ #maxResponseBytes: number;
180
+ #onRequestEvent?: SessOptions['onRequestEvent'];
181
+
182
+ constructor(options: SessOptions) {
183
+ if (!options || typeof options !== 'object')
184
+ throw new SessError('configuration', 'Sess options with apiKey are required.', { outcome: 'not_sent' });
185
+ this.#apiKey = typeof options.apiKey === 'function' ? options.apiKey : credential(options.apiKey);
186
+ this.allowInsecureLocalhost = options.allowInsecureLocalhost === true;
187
+ this.baseUrl = origin(options.baseUrl, this.allowInsecureLocalhost);
188
+ this.receiptIssuer = options.receiptIssuer ?? this.baseUrl;
189
+ if (
190
+ typeof this.receiptIssuer !== 'string' ||
191
+ !this.receiptIssuer.length ||
192
+ this.receiptIssuer.length > 2048 ||
193
+ /[\u0000-\u0020\u007f]/.test(this.receiptIssuer)
194
+ )
195
+ throw new SessError('configuration', 'receiptIssuer must be a trusted nonempty protocol identity.', {
196
+ outcome: 'not_sent',
197
+ });
198
+ if (
199
+ options.expectedWorkspaceId !== undefined &&
200
+ (typeof options.expectedWorkspaceId !== 'string' ||
201
+ !/^[A-Za-z0-9_:-]{1,128}$/.test(options.expectedWorkspaceId))
202
+ )
203
+ throw new SessError('configuration', 'expectedWorkspaceId must be a trusted workspace identifier.', {
204
+ outcome: 'not_sent',
205
+ });
206
+ this.expectedWorkspaceId = options.expectedWorkspaceId;
207
+ this.#fetch = options.fetch ?? globalThis.fetch;
208
+ if (typeof this.#fetch !== 'function')
209
+ throw new SessError('configuration', 'A compatible fetch implementation is required.', {
210
+ outcome: 'not_sent',
211
+ });
212
+ this.#timeoutMs = boundedNumber(options.timeoutMs, 12000, 'timeoutMs');
213
+ this.operationTimeoutMs = boundedNumber(options.operationTimeoutMs, 30000, 'operationTimeoutMs');
214
+ this.#maxRetries = boundedNumber(options.maxRetries, 2, 'maxRetries', 0, 10);
215
+ this.#maxResponseBytes = boundedNumber(
216
+ options.maxResponseBytes,
217
+ 16 * 1024 * 1024,
218
+ 'maxResponseBytes',
219
+ 1,
220
+ 256 * 1024 * 1024,
221
+ );
222
+ this.#onRequestEvent = options.onRequestEvent;
223
+ if (this.#onRequestEvent !== undefined && typeof this.#onRequestEvent !== 'function')
224
+ throw new SessError('configuration', 'onRequestEvent must be a function.', { outcome: 'not_sent' });
225
+ }
226
+
227
+ async request<T>(operation: Operation<T>, inputOptions: RequestOptions = {}): Promise<ApiResult<T>> {
228
+ // Capture every mutable input before the first asynchronous boundary.
229
+ const op = { ...operation };
230
+ const options = { ...inputOptions };
231
+ const isWrite = op.method !== 'GET';
232
+ const body = op.body === undefined ? undefined : serializeBody(op.body);
233
+ const timeoutMs = boundedNumber(options.timeoutMs, this.#timeoutMs, 'timeoutMs');
234
+ const totalMs = boundedNumber(options.operationTimeoutMs, this.operationTimeoutMs, 'operationTimeoutMs');
235
+ const retries = boundedNumber(options.maxRetries, this.#maxRetries, 'maxRetries', 0, 10);
236
+ const maxBytes = boundedNumber(
237
+ options.maxResponseBytes,
238
+ this.#maxResponseBytes,
239
+ 'maxResponseBytes',
240
+ 1,
241
+ 256 * 1024 * 1024,
242
+ );
243
+ if ('headers' in options || 'baseUrl' in options || 'apiKey' in options)
244
+ throw new SessError(
245
+ 'configuration',
246
+ 'Per-request authentication, host, and header overrides are not supported.',
247
+ { outcome: 'not_sent' },
248
+ );
249
+ if (options.signal !== undefined && !(options.signal instanceof AbortSignal))
250
+ throw new SessError('configuration', 'signal must be an AbortSignal.', { outcome: 'not_sent' });
251
+ if (
252
+ !op.path.startsWith('/') ||
253
+ op.path.startsWith('//') ||
254
+ op.path.includes('#') ||
255
+ op.path.includes('?')
256
+ )
257
+ throw new SessError('configuration', 'Invalid API resource path.', { outcome: 'not_sent' });
258
+ const headers: Record<string, string> = { Accept: 'application/json' };
259
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
260
+ let idempotencyKey: string | undefined;
261
+ if (op.retry === 'mutation') {
262
+ if (!strongETag(op.ifMatch))
263
+ throw new SessError(
264
+ 'configuration',
265
+ 'Publish and complete require an original strong quoted If-Match ETag.',
266
+ { code: 'INVALID_IF_MATCH', outcome: 'not_sent' },
267
+ );
268
+ if (op.idempotencyKey !== undefined && typeof op.idempotencyKey !== 'string')
269
+ throw new SessError('configuration', 'idempotencyKey must be a primitive string.', {
270
+ outcome: 'not_sent',
271
+ });
272
+ idempotencyKey = op.idempotencyKey === undefined ? randomUUID() : op.idempotencyKey;
273
+ if (!/^[A-Za-z0-9_.:-]{1,128}$/.test(idempotencyKey))
274
+ throw new SessError(
275
+ 'configuration',
276
+ 'idempotencyKey must contain 1–128 characters using only letters, digits, underscore, period, colon, or hyphen.',
277
+ { outcome: 'not_sent' },
278
+ );
279
+ headers['If-Match'] = op.ifMatch;
280
+ headers['Idempotency-Key'] = idempotencyKey;
281
+ }
282
+ const started = performance.now();
283
+ const expires = started + totalMs;
284
+ const whole = deadline(totalMs, options.signal);
285
+ let attempts = 0;
286
+ let dispatched = false;
287
+ let key: string | undefined;
288
+ let possiblePriorWrite = false;
289
+ try {
290
+ if (whole.signal.aborted) throw abortError(whole.signal);
291
+ if (op.authenticated !== false) {
292
+ const suppliedKey = new Promise<string | undefined>((resolve) => {
293
+ resolve(typeof this.#apiKey === 'function' ? this.#apiKey() : this.#apiKey);
294
+ }).catch(() => {
295
+ throw new SessError('configuration', 'The API credential provider did not supply a usable key.', {
296
+ code: 'CREDENTIAL_PROVIDER_FAILED',
297
+ outcome: 'not_sent',
298
+ });
299
+ });
300
+ key = credential(await withSignal(suppliedKey, whole.signal));
301
+ headers.Authorization = `Bearer ${key}`;
302
+ }
303
+ const budget = op.retry === 'never' ? 0 : retries;
304
+ for (;;) {
305
+ if (whole.signal.aborted) throw abortError(whole.signal);
306
+ attempts++;
307
+ const attempt = deadline(
308
+ Math.min(timeoutMs, Math.max(1, Math.ceil(expires - performance.now()))),
309
+ whole.signal,
310
+ );
311
+ let retryable = false;
312
+ let response: Response | undefined;
313
+ let error: SessError | undefined;
314
+ let recoveryBody: CreateSessionResponse | undefined;
315
+ try {
316
+ dispatched = true;
317
+ const pendingResponse = Promise.resolve()
318
+ .then(() =>
319
+ this.#fetch(`${this.baseUrl}${op.path}`, {
320
+ method: op.method,
321
+ headers: { ...headers },
322
+ ...(body !== undefined ? { body } : {}),
323
+ redirect: 'manual',
324
+ credentials: 'omit',
325
+ signal: attempt.signal,
326
+ }),
327
+ )
328
+ .catch(() => {
329
+ if (attempt.signal.aborted) throw abortError(attempt.signal);
330
+ throw new SessError('transport', 'API transport failed.');
331
+ });
332
+ pendingResponse.then(
333
+ (r) => {
334
+ if (attempt.signal.aborted) void r.body?.cancel().catch(() => {});
335
+ },
336
+ () => {},
337
+ );
338
+ response = await withSignal(pendingResponse, attempt.signal);
339
+ if (response.redirected || (response.status >= 300 && response.status < 400)) {
340
+ void response.body?.cancel().catch(() => {});
341
+ throw new SessError('protocol', 'Redirected API responses are refused.', {
342
+ code: 'REDIRECT_REFUSED',
343
+ status: response.status,
344
+ });
345
+ }
346
+ const requestId = safeText(
347
+ response.headers.get('x-request-id'),
348
+ /^[A-Za-z0-9._:-]{1,128}$/,
349
+ key,
350
+ true,
351
+ );
352
+ const retryAfterMs = retryAfter(response.headers.get('retry-after'));
353
+ const mediaType = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
354
+ const text = await readBody(
355
+ response,
356
+ response.ok ? maxBytes : Math.min(maxBytes, 65536),
357
+ attempt.signal,
358
+ );
359
+ if (!response.ok) {
360
+ let remote: Record<string, unknown> = {};
361
+ if (mediaType === 'application/json') {
362
+ try {
363
+ const value = JSON.parse(text) as { error?: unknown };
364
+ if (value.error && typeof value.error === 'object')
365
+ remote = value.error as Record<string, unknown>;
366
+ } catch {
367
+ /* gateway/unusable body remains redacted */
368
+ }
369
+ }
370
+ const code = safeText(remote.code, /^[A-Z][A-Z0-9_]{0,95}$/, key);
371
+ const reason = safeText(remote.reason, /^[a-z_]{1,40}$/, key);
372
+ const remoteId = safeText(remote.request_id, /^[A-Za-z0-9._:-]{1,128}$/, key, true) ?? requestId;
373
+ const rejected = code !== undefined && rejections[response.status]?.includes(code);
374
+ retryable = transientStatuses.has(response.status);
375
+ throw new SessError('api', 'SESS API request failed. Inspect the safe status and code fields.', {
376
+ code,
377
+ reason,
378
+ status: response.status,
379
+ requestId: remoteId,
380
+ retryAfterMs,
381
+ outcome: isWrite ? (rejected && !possiblePriorWrite ? 'rejected' : 'unknown') : undefined,
382
+ });
383
+ }
384
+ if (response.status !== op.status)
385
+ throw new SessError('protocol', 'Unexpected API success status.', {
386
+ code: 'INVALID_RESPONSE',
387
+ status: response.status,
388
+ });
389
+ let data: T;
390
+ if (op.parse) {
391
+ if (mediaType !== 'application/json')
392
+ throw new SessError('protocol', 'Expected an application/json response.', {
393
+ code: 'INVALID_RESPONSE',
394
+ });
395
+ let parsed: unknown;
396
+ try {
397
+ parsed = JSON.parse(text);
398
+ } catch {
399
+ throw new SessError('protocol', 'Response is not valid JSON.', { code: 'INVALID_RESPONSE' });
400
+ }
401
+ data = op.parse(parsed);
402
+ if (op.name === 'sessions.create') recoveryBody = data as CreateSessionResponse;
403
+ } else {
404
+ if (text.length !== 0)
405
+ throw new SessError('protocol', 'Expected an empty API success body.', {
406
+ code: 'INVALID_RESPONSE',
407
+ });
408
+ data = undefined as T;
409
+ }
410
+ const etag = response.headers.get('etag') ?? undefined;
411
+ if ((op.versioned || etag !== undefined) && !strongETag(etag))
412
+ throw new SessError('protocol', 'API response is missing a valid strong ETag.', {
413
+ code: 'INVALID_ETAG',
414
+ });
415
+ const workspaceHeader = response.headers.get('sess-workspace-id');
416
+ if (workspaceHeader !== null && !/^[A-Za-z0-9_:-]{1,128}$/.test(workspaceHeader))
417
+ throw new SessError('protocol', 'API response has an invalid workspace context.', {
418
+ code: 'INVALID_WORKSPACE_CONTEXT',
419
+ });
420
+ const meta: ResponseMeta = {
421
+ status: response.status,
422
+ attempts,
423
+ ...(etag ? { etag } : {}),
424
+ ...(requestId ? { requestId } : {}),
425
+ ...(workspaceHeader ? { workspaceId: workspaceHeader } : {}),
426
+ ...(idempotencyKey ? { idempotencyKey } : {}),
427
+ };
428
+ this.#observe(op.name, started, attempts, meta);
429
+ return { data, meta };
430
+ } catch (e) {
431
+ if (e instanceof SessError) error = e;
432
+ else {
433
+ error = new SessError(
434
+ attempt.signal.aborted ? abortError(attempt.signal).kind : 'transport',
435
+ attempt.signal.aborted
436
+ ? 'Request deadline or caller cancellation ended the local request.'
437
+ : 'API transport failed.',
438
+ );
439
+ retryable = true;
440
+ }
441
+ if (error.kind === 'timeout' || error.kind === 'transport') retryable = true;
442
+ const outcome: WriteOutcome | undefined = isWrite ? (error.outcome ?? 'unknown') : undefined;
443
+ if (outcome === 'unknown') possiblePriorWrite = true;
444
+ const details: SessErrorDetails = {
445
+ code: error.code,
446
+ reason: error.reason,
447
+ status: error.status ?? response?.status,
448
+ requestId: error.requestId,
449
+ retryAfterMs: error.retryAfterMs,
450
+ operation: op.name,
451
+ attempts,
452
+ outcome,
453
+ idempotencyKey,
454
+ };
455
+ error = new SessError(
456
+ op.name === 'sessions.create' && outcome === 'unknown' ? 'unknown_outcome' : error.kind,
457
+ op.name === 'sessions.create' && outcome === 'unknown'
458
+ ? 'Session creation may have succeeded. Do not automatically create again; inspect recovery information if available.'
459
+ : error.message,
460
+ details,
461
+ );
462
+ if (recoveryBody) attachRecovery(error, recoveryBody);
463
+ this.#observe(op.name, started, attempts, details);
464
+ } finally {
465
+ attempt.dispose();
466
+ }
467
+ if (!retryable || attempts > budget || whole.signal.aborted || options.signal?.aborted) throw error;
468
+ const backoffMs = Math.ceil(200 * 2 ** (attempts - 1) + Math.random() * 100);
469
+ const waitMs = Math.max(backoffMs, error.retryAfterMs ?? 0);
470
+ if (waitMs >= expires - performance.now()) throw error;
471
+ await delay(waitMs, whole.signal);
472
+ }
473
+ } catch (e) {
474
+ if (!(e instanceof SessError))
475
+ throw new SessError('transport', 'API operation failed.', {
476
+ operation: op.name,
477
+ attempts,
478
+ outcome: isWrite ? (dispatched ? 'unknown' : 'not_sent') : undefined,
479
+ idempotencyKey,
480
+ });
481
+ if (e.operation) throw e;
482
+ throw new SessError(
483
+ op.name === 'sessions.create' && dispatched ? 'unknown_outcome' : e.kind,
484
+ op.name === 'sessions.create' && dispatched
485
+ ? 'Session creation may have succeeded. Do not automatically create again.'
486
+ : e.message,
487
+ {
488
+ code: e.code,
489
+ reason: e.reason,
490
+ operation: op.name,
491
+ attempts,
492
+ outcome: isWrite ? (dispatched ? 'unknown' : 'not_sent') : undefined,
493
+ idempotencyKey,
494
+ },
495
+ );
496
+ } finally {
497
+ whole.dispose();
498
+ }
499
+ }
500
+
501
+ #observe(
502
+ operation: string,
503
+ started: number,
504
+ attempt: number,
505
+ meta: { status?: number; code?: string; requestId?: string },
506
+ ): void {
507
+ try {
508
+ const result = this.#onRequestEvent?.(
509
+ Object.freeze({
510
+ operation,
511
+ attempt,
512
+ durationMs: performance.now() - started,
513
+ status: meta.status,
514
+ code: meta.code,
515
+ requestId: meta.requestId,
516
+ }),
517
+ );
518
+ // An async callback's rejected promise cannot change request semantics either.
519
+ Promise.resolve(result).catch(() => {});
520
+ } catch {
521
+ /* optional observer failures are isolated */
522
+ }
523
+ }
524
+ }
package/src/types.ts ADDED
@@ -0,0 +1,135 @@
1
+ import type { components } from './generated/openapi.js';
2
+
3
+ /** Unmodified types generated from the reviewed public HTTP contract. */
4
+ export type { components, paths, operations } from './generated/openapi.js';
5
+ type Schemas = components['schemas'];
6
+ export type RawCreateSessionRequest = Schemas['CreateSessionRequest'];
7
+ export type RawPublishSessionRequest = Schemas['PatchSessionRequest'];
8
+ export type CreateSessionResponse = Schemas['CreateSessionResponse'];
9
+ export type DisplaySession = Schemas['SessionResponse'];
10
+ export type InteractiveSession = Schemas['InteractiveSessionResponse'];
11
+ export type Session = DisplaySession | InteractiveSession;
12
+ export type DisplaySurfaceRevision = Schemas['SessionResponse'];
13
+ export type InteractiveSurfaceRevision = Schemas['InteractiveSurfaceResponse'];
14
+ export type SurfaceRevision = DisplaySurfaceRevision | InteractiveSurfaceRevision;
15
+ export type AcceptedResponse = InteractiveSession['responses'][number];
16
+ export type SessionEvents = Schemas['SessionEventsResponse'];
17
+ export type SessionEvent = SessionEvents['events'][number];
18
+ export type Deliveries = Schemas['DeliveriesResponse'];
19
+ export type WebhookRegisterRequest = Schemas['WebhookRegisterRequest'];
20
+ export type WebhookRegisterResponse = Schemas['WebhookRegisterResponse'];
21
+ export type WebhookResponse = Schemas['WebhookResponse'];
22
+ export type WebhookRotateResponse = Schemas['WebhookRotateResponse'];
23
+ export type WebhookVerifyResponse = Schemas['WebhookVerifyResponse'];
24
+ export type RedeliverResponse = Schemas['RedeliverResponse'];
25
+ export type WebhookDelivery = Schemas['WebhookDelivery'];
26
+ export type WebhookVerification = Schemas['WebhookVerification'];
27
+ export type DisplayInteraction = DisplaySession['interaction'];
28
+ export type Action = InteractiveSession['interaction']['actions'][number];
29
+
30
+ type SchemaDocumentation = { title?: string; description?: string };
31
+ /** The documented restricted field-schema subset; the runtime validates it. */
32
+ export type FieldSchema = SchemaDocumentation &
33
+ (
34
+ | { type: 'string'; minLength?: number; maxLength?: number; enum?: string[] }
35
+ | {
36
+ type: 'number' | 'integer';
37
+ minimum?: number;
38
+ maximum?: number;
39
+ exclusiveMinimum?: number;
40
+ exclusiveMaximum?: number;
41
+ }
42
+ | { type: 'boolean' }
43
+ | {
44
+ type: 'array';
45
+ items: { type: 'string'; enum: string[] };
46
+ minItems?: number;
47
+ maxItems?: number;
48
+ uniqueItems?: true;
49
+ }
50
+ );
51
+ type WireComponent = Schemas['SurfaceComponent'];
52
+ export type SurfaceComponent =
53
+ | Exclude<WireComponent, { type: 'field' }>
54
+ | (Omit<Extract<WireComponent, { type: 'field' }>, 'schema'> & { schema: FieldSchema });
55
+ export type InteractiveInteraction = Omit<RawPublishSessionRequest['interaction'], 'source'> & {
56
+ source: { kind: 'sess_surface'; components: SurfaceComponent[] };
57
+ };
58
+ export type CreateSessionRequest = { interaction: DisplayInteraction | InteractiveInteraction };
59
+ export type PublishSessionRequest = { interaction: InteractiveInteraction };
60
+
61
+ export interface ResponseMeta {
62
+ status: number;
63
+ requestId?: string;
64
+ etag?: string;
65
+ /** Authenticated resource workspace, when supplied by the runtime. */
66
+ workspaceId?: string;
67
+ attempts: number;
68
+ idempotencyKey?: string;
69
+ }
70
+ export interface ApiResult<T> {
71
+ data: T;
72
+ meta: ResponseMeta;
73
+ }
74
+ export interface VersionedResult<T> extends ApiResult<T> {
75
+ meta: ResponseMeta & { etag: string };
76
+ }
77
+ export interface RequestEvent {
78
+ operation: string;
79
+ status?: number;
80
+ code?: string;
81
+ durationMs: number;
82
+ attempt: number;
83
+ requestId?: string;
84
+ }
85
+ export interface RequestOptions {
86
+ signal?: AbortSignal;
87
+ /** Deadline per attempt, including its response body. */
88
+ timeoutMs?: number;
89
+ /** Total logical-operation deadline, including credential resolution and retry delays. */
90
+ operationTimeoutMs?: number;
91
+ maxRetries?: number;
92
+ maxResponseBytes?: number;
93
+ }
94
+ export interface MutationOptions extends RequestOptions {
95
+ ifMatch: string;
96
+ /** Persist with the original body/If-Match. Primitive string matching ^[A-Za-z0-9_.:-]{1,128}$. */
97
+ idempotencyKey?: string;
98
+ }
99
+ export interface WaitOptions extends Omit<RequestOptions, 'timeoutMs'> {
100
+ revision: number;
101
+ /** Total human wait, default ten minutes. */
102
+ timeoutMs?: number;
103
+ intervalMs?: number;
104
+ /** Each poll inherits the client's logical-operation budget unless overridden, bounded by the remaining human wait. */
105
+ operationTimeoutMs?: number;
106
+ }
107
+ export interface WaitResult {
108
+ session: InteractiveSession;
109
+ response: AcceptedResponse;
110
+ /** The ETag is for this current snapshot, even when response is historical. */
111
+ meta: ResponseMeta & { etag: string };
112
+ }
113
+ export interface SessOptions {
114
+ apiKey: string | undefined | (() => string | Promise<string>);
115
+ baseUrl?: string;
116
+ fetch?: typeof globalThis.fetch;
117
+ timeoutMs?: number;
118
+ operationTimeoutMs?: number;
119
+ maxRetries?: number;
120
+ maxResponseBytes?: number;
121
+ receiptIssuer?: string;
122
+ expectedWorkspaceId?: string;
123
+ allowInsecureLocalhost?: boolean;
124
+ onRequestEvent?: (event: Readonly<RequestEvent>) => void;
125
+ }
126
+
127
+ /** Narrow a retrieved display/interactive Session without asserting business data. */
128
+ export function isInteractiveSession(session: Session): session is InteractiveSession {
129
+ return 'status' in session && session.interaction.mode === 'interactive';
130
+ }
131
+
132
+ /** Narrow immutable content before accessing interactive-only schema or actions. */
133
+ export function isInteractiveSurface(surface: SurfaceRevision): surface is InteractiveSurfaceRevision {
134
+ return 'response_schema' in surface && surface.interaction.mode === 'interactive';
135
+ }