@nomac/sdk 0.0.0-stage → 1.0.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,398 @@
1
+ /** The SDK's data, in the REST API's own field names (docs: https://nomac.app/docs/api). */
2
+ export type SessionState = "queued" | "provisioning" | "ready" | "stopping" | "stopped" | "failed";
3
+ /** What a session may cost and how long it may run. A Mac has no longest time; a phone runs 8 hours at most. */
4
+ export interface Limits {
5
+ /** The longest it runs, in seconds (7,200 by default). */
6
+ max_duration_seconds?: number;
7
+ /** Stopped after this long without a command, a call or a viewer, in seconds (600 by default, 60 to 3,600). */
8
+ idle_timeout_seconds?: number;
9
+ /** The most it may cost, in microdollars (USD x 1,000,000; "5000000", $5, by default). */
10
+ spend_cap_microunits?: string;
11
+ }
12
+ /** billable_seconds: the usage; billed_seconds: it as charged (whole minutes, at least one). */
13
+ export interface Cost {
14
+ currency: string;
15
+ accrued_microunits: string;
16
+ billable_seconds: number;
17
+ billed_seconds: number;
18
+ [field: string]: unknown;
19
+ }
20
+ /** When a Mac or phone stops, why, and what to do first. */
21
+ export interface StopNotice {
22
+ stops_at: string;
23
+ minutes_left: number;
24
+ reason: "time_limit" | "spend_cap" | "credit";
25
+ /** extend: extend() keeps it running; buy_credit: the account's owner adds credit (buy_url); save_state: a phone cannot be extended further. */
26
+ next_action?: "extend_mac" | "extend" | "save_state" | "buy_credit";
27
+ buy_url?: string;
28
+ message: string;
29
+ }
30
+ /** What a Mac starts with (the REST start's body): a label makes it a platform's user's Mac. */
31
+ export interface MacStartOptions {
32
+ /** Your user's id (letters, digits and . _ : @ -, up to 64): the Mac gets that user's drive and none of the account's secrets. */
33
+ label?: string;
34
+ /** With label: the user's starting or running Mac is the answer (mac.reused) instead of a second one. With access.drive: that drive's Mac. */
35
+ reuse?: boolean;
36
+ /** With label: the start ends (drive_unavailable, nothing charged) rather than run without the user's drive. */
37
+ require_drive?: boolean;
38
+ /** Wait in line, free, up to this long (300 to 3,600 s) when no Mac is free or the account runs its most at once. */
39
+ queue_seconds?: number;
40
+ limits?: Limits;
41
+ /** prompts "ask" keeps macOS's usual prompts; gatekeeper "on" | "off"; permissions; drive: "account", a name, or "none"; drive_from. */
42
+ access?: {
43
+ prompts?: "ask";
44
+ gatekeeper?: "on" | "off";
45
+ permissions?: Record<string, string[]> | "all";
46
+ drive?: string;
47
+ drive_from?: string;
48
+ [field: string]: unknown;
49
+ };
50
+ /** A second Mac beside the account's running one (an account that has bought credit). */
51
+ parallel?: boolean;
52
+ /** An SSH public key; leave it out for HTTPS only. */
53
+ public_key?: string;
54
+ }
55
+ export interface MacDrive {
56
+ id?: string;
57
+ name: string;
58
+ label?: string;
59
+ state?: string;
60
+ used_bytes?: number;
61
+ message?: string;
62
+ [field: string]: unknown;
63
+ }
64
+ export interface MacSession {
65
+ id: string;
66
+ state: SessionState;
67
+ label?: string;
68
+ limits?: Required<Limits>;
69
+ cost?: Cost;
70
+ ready_at?: string | null;
71
+ shutdown_at?: string | null;
72
+ cleanup_confirmed?: boolean;
73
+ failure_code?: string | null;
74
+ end_reason?: string | null;
75
+ drive?: MacDrive | null;
76
+ activity?: {
77
+ state: string;
78
+ idle_deadline_at: number | null;
79
+ hard_deadline_at: number | null;
80
+ };
81
+ started_from?: string | null;
82
+ last_command_at?: string | null;
83
+ created_at?: string;
84
+ [field: string]: unknown;
85
+ }
86
+ /** A command's end: its exit code and its whole output (or, past NoMac's 8 MiB, the start and the end with truncated set). */
87
+ export interface CommandResult {
88
+ exitCode: number | null;
89
+ stdout: string;
90
+ stderr: string;
91
+ /** More than 8 MiB of output: stdout and stderr hold the kept start and each stream's last 64 KiB. */
92
+ truncated: boolean;
93
+ /** The job as NoMac answered it: id, state, timings. */
94
+ job: Job;
95
+ /** Set when the command ended but its output could not be read (output_expired): exitCode still holds. */
96
+ outputError?: string;
97
+ }
98
+ export interface Job {
99
+ id: string;
100
+ state: "running" | "exited" | "unknown" | (string & {});
101
+ exit_code?: number | null;
102
+ [field: string]: unknown;
103
+ }
104
+ export interface RunOptions {
105
+ /** The folder to run in: relative to the workspace, ~/... or absolute. */
106
+ cwd?: string;
107
+ env?: Record<string, string>;
108
+ /** Stop the command after this many seconds (300 by default, 3,600 at most). */
109
+ timeoutSeconds?: number;
110
+ /** The same key makes a retry the same command (never run twice). */
111
+ idempotencyKey?: string;
112
+ }
113
+ export interface Screenshot {
114
+ /** The JPEG's bytes. */
115
+ image: Uint8Array;
116
+ mime_type: string;
117
+ width: number;
118
+ height: number;
119
+ target: "screen" | "simulator";
120
+ front_app?: string;
121
+ screen_locked?: boolean | null;
122
+ dialog?: string;
123
+ next_step?: string;
124
+ [field: string]: unknown;
125
+ }
126
+ export type InputAction =
127
+ /** text: up to 500 characters (longer: put it on the clipboard with run(), then key ["cmd+v"]). */
128
+ {
129
+ action: "type";
130
+ text: string;
131
+ screenshot?: boolean;
132
+ }
133
+ /** keys: one or more keys or chords, pressed in turn, like ["return"] or ["cmd+s"]. */
134
+ | {
135
+ action: "key";
136
+ keys: string[];
137
+ screenshot?: boolean;
138
+ } | {
139
+ action: "click";
140
+ x: number;
141
+ y: number;
142
+ button?: "left" | "right";
143
+ double?: boolean;
144
+ screenshot?: boolean;
145
+ } | {
146
+ action: "move";
147
+ x: number;
148
+ y: number;
149
+ screenshot?: boolean;
150
+ } | {
151
+ action: "scroll";
152
+ x: number;
153
+ y: number;
154
+ steps: number;
155
+ screenshot?: boolean;
156
+ } | {
157
+ action: "password" | "unlock" | "size";
158
+ screenshot?: boolean;
159
+ };
160
+ export interface FileLink {
161
+ url: string;
162
+ state: "waiting_for_upload" | "placing" | "placed" | "copying" | "ready" | "failed" | "expired" | (string & {});
163
+ error?: {
164
+ code: string;
165
+ message: string;
166
+ };
167
+ upload_url?: string;
168
+ download_url?: string;
169
+ expires_at?: string;
170
+ [field: string]: unknown;
171
+ }
172
+ export type PhoneDevice = "iphone" | "ipad" | "iphone-pro-max";
173
+ export interface PhoneStartOptions {
174
+ device?: PhoneDevice;
175
+ /** Your user's id: letters, digits and . _ : @ -, up to 64. */
176
+ label?: string;
177
+ /** With label: answer the live phone with that label instead of starting another. */
178
+ reuse?: boolean;
179
+ limits?: Limits;
180
+ }
181
+ export interface PhoneSession {
182
+ id: string;
183
+ state: SessionState;
184
+ device?: PhoneDevice;
185
+ label?: string | null;
186
+ ready_at?: string | null;
187
+ shutdown_at?: string | null;
188
+ failure_code?: string | null;
189
+ end_reason?: string | null;
190
+ queue_expires_at?: string;
191
+ created_at?: string;
192
+ cost?: Cost;
193
+ limits?: Required<Limits>;
194
+ /** While queued: how many phones were asked for before it, how many run at once, and how many are in use. */
195
+ queue?: {
196
+ ahead: number;
197
+ phones: number;
198
+ in_use: number;
199
+ };
200
+ message?: string;
201
+ [field: string]: unknown;
202
+ }
203
+ export interface PhoneLinks {
204
+ view?: string;
205
+ control?: string;
206
+ replay?: string;
207
+ [name: string]: string | undefined;
208
+ }
209
+ export type ToolName = "devices" | "device_use" | "app_run" | "ui_look" | "ui_act" | "app_control" | "app_logs" | "tests_run" | "job_status" | "job_cancel" | "screen_record";
210
+ export interface ToolResult {
211
+ /** The tool's text: what it did, what is on the screen, and what to do next. Files it names are links. */
212
+ text: string;
213
+ content: Array<{
214
+ type: "text";
215
+ text: string;
216
+ } | {
217
+ type: "image";
218
+ data: string;
219
+ mimeType: string;
220
+ } | {
221
+ type: string;
222
+ [field: string]: unknown;
223
+ }>;
224
+ isError: boolean;
225
+ /** "phone_restarted" when the phone restarted since the last call (apps and data kept). */
226
+ notices: string[];
227
+ stopNotice: StopNotice | null;
228
+ raw: Record<string, unknown>;
229
+ }
230
+ /** A screen_record still running when its phone stopped ends there: url is its MP4, about a minute after the stop, for 7 days. */
231
+ export interface PhoneRecording {
232
+ url: string;
233
+ started_at: string;
234
+ seconds: number;
235
+ message: string;
236
+ }
237
+ export interface OperationOptions {
238
+ idempotencyKey?: string;
239
+ /** How long to follow it before NoMacError "timeout" (30 minutes by default); the same key reads it later. */
240
+ timeoutMs?: number;
241
+ }
242
+ export interface ViewLink {
243
+ url: string;
244
+ mode: "watch" | "control";
245
+ expires_at: string;
246
+ }
247
+ export interface SessionToken {
248
+ token: string;
249
+ session_id: string;
250
+ expires_at: string;
251
+ }
252
+ /** What NoMac keeps for one of your users (a label): their running Macs and phones, and their drive. */
253
+ export interface LabelView {
254
+ label: string;
255
+ macs: {
256
+ running: string[];
257
+ drive: {
258
+ used_bytes: number;
259
+ saved_at: string | null;
260
+ saving: boolean;
261
+ charged: boolean;
262
+ expires_at: string;
263
+ } | null;
264
+ };
265
+ phones: {
266
+ running: string[];
267
+ [field: string]: unknown;
268
+ };
269
+ [field: string]: unknown;
270
+ }
271
+ export interface Credits {
272
+ currency: string;
273
+ spendable_microunits: string;
274
+ spendable_seconds: number;
275
+ [field: string]: unknown;
276
+ }
277
+ export type WebhookEventType = "mac.ready" | "mac.ending_soon" | "mac.ended" | "drive.saved" | "drive.deleted" | "credit.low" | "phone.ready" | "phone.ended";
278
+ export interface Webhook {
279
+ id: string;
280
+ url: string;
281
+ events: WebhookEventType[];
282
+ created_at: string;
283
+ /** Deliveries given up in the last 7 days (none answered 2xx in 12 tries). */
284
+ failing?: number;
285
+ }
286
+ export interface WebhookDelivery {
287
+ id: string;
288
+ event: WebhookEventType;
289
+ /** What it is about: a session's id, a drive's version, a credit episode. */
290
+ subject?: string;
291
+ session_id: string | null;
292
+ state: "delivered" | "retrying" | "gave_up";
293
+ attempts: number;
294
+ last_error: string | null;
295
+ created_at: string;
296
+ delivered_at: string | null;
297
+ next_attempt_at: string | null;
298
+ }
299
+ /** Why a Mac or phone ended. crashed: it or its host failed (failure_code says more). */
300
+ export type EndReason = "stopped" | "idle" | "time_limit" | "spend_cap" | "credit" | "crashed" | "no_capacity" | "start_failed" | "queue_expired" | "drive_unavailable";
301
+ export interface WebhookSession {
302
+ id: string;
303
+ state: SessionState;
304
+ label: string | null;
305
+ ready_at: string | null;
306
+ shutdown_at: string | null;
307
+ failure_code: string | null;
308
+ cost: Cost;
309
+ /** A Mac's drive: on mac.ready its state (mounted, preparing, unavailable, none), on mac.ended whether its save is still to come. */
310
+ drive?: {
311
+ name?: string;
312
+ label?: string;
313
+ state?: string;
314
+ saving?: boolean;
315
+ };
316
+ device?: PhoneDevice;
317
+ }
318
+ export type WebhookEvent = {
319
+ id: string;
320
+ type: "mac.ready";
321
+ created_at: string;
322
+ data: {
323
+ session: WebhookSession;
324
+ };
325
+ } | {
326
+ id: string;
327
+ type: "mac.ending_soon";
328
+ created_at: string;
329
+ data: {
330
+ session: {
331
+ id: string;
332
+ label: string | null;
333
+ };
334
+ stops_at: string;
335
+ seconds_left: number;
336
+ reason: "time_limit" | "spend_cap" | "credit";
337
+ };
338
+ } | {
339
+ id: string;
340
+ type: "mac.ended";
341
+ created_at: string;
342
+ data: {
343
+ session: WebhookSession;
344
+ reason: EndReason;
345
+ };
346
+ } | {
347
+ id: string;
348
+ type: "drive.saved";
349
+ created_at: string;
350
+ data: {
351
+ drive: {
352
+ label: string;
353
+ version: number;
354
+ head: boolean;
355
+ used_bytes: number;
356
+ changed_bytes: number;
357
+ charge_microunits: string;
358
+ };
359
+ session_id: string;
360
+ };
361
+ } | {
362
+ id: string;
363
+ type: "drive.deleted";
364
+ created_at: string;
365
+ data: {
366
+ drive: {
367
+ label: string;
368
+ reason: "deleted" | "expired";
369
+ };
370
+ };
371
+ } | {
372
+ id: string;
373
+ type: "credit.low";
374
+ created_at: string;
375
+ data: {
376
+ credit: {
377
+ spendable_microunits: string;
378
+ running_macs: number;
379
+ running_phones: number;
380
+ covers_seconds: number;
381
+ };
382
+ };
383
+ } | {
384
+ id: string;
385
+ type: "phone.ready";
386
+ created_at: string;
387
+ data: {
388
+ session: WebhookSession;
389
+ };
390
+ } | {
391
+ id: string;
392
+ type: "phone.ended";
393
+ created_at: string;
394
+ data: {
395
+ session: WebhookSession;
396
+ reason: EndReason;
397
+ };
398
+ };
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ /** The SDK's data, in the REST API's own field names (docs: https://nomac.app/docs/api). */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,10 @@
1
+ import type { WebhookEvent } from "./types.ts";
2
+ /**
3
+ * Checks a webhook delivery and answers its event: body (the raw request body, as received), signature (the nomac-signature
4
+ * header), secret (the endpoint's whsec_... secret). Refused when the signature does not match or is older than toleranceSeconds
5
+ * (5 minutes). A delivery can come more than once: key on its id (the nomac-delivery header).
6
+ */
7
+ export declare function verifyWebhook(body: string | Uint8Array, signature: string | null | undefined, secret: string, { toleranceSeconds, now }?: {
8
+ toleranceSeconds?: number;
9
+ now?: number;
10
+ }): Promise<WebhookEvent>;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.verifyWebhook = verifyWebhook;
4
+ const errors_ts_1 = require("./errors.js");
5
+ const encoder = new TextEncoder();
6
+ /**
7
+ * Checks a webhook delivery and answers its event: body (the raw request body, as received), signature (the nomac-signature
8
+ * header), secret (the endpoint's whsec_... secret). Refused when the signature does not match or is older than toleranceSeconds
9
+ * (5 minutes). A delivery can come more than once: key on its id (the nomac-delivery header).
10
+ */
11
+ async function verifyWebhook(body, signature, secret, { toleranceSeconds = 300, now = Date.now() } = {}) {
12
+ const text = typeof body === "string" ? body : new TextDecoder().decode(body);
13
+ const parts = Object.fromEntries(String(signature ?? "").split(",").map(part => part.trim().split("=", 2)));
14
+ const timestamp = Number(parts.t);
15
+ if (!Number.isInteger(timestamp) || !/^[a-f0-9]{64}$/.test(parts.v1 ?? ""))
16
+ throw new errors_ts_1.NoMacError("webhook_signature_invalid", "The nomac-signature header is missing or malformed.");
17
+ if (Math.abs(now / 1000 - timestamp) > toleranceSeconds)
18
+ throw new errors_ts_1.NoMacError("webhook_signature_expired", "The delivery's signature is too old; it may be a replay.");
19
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
20
+ const mac = new Uint8Array(parts.v1.match(/../g).map(byte => parseInt(byte, 16)));
21
+ if (!(await crypto.subtle.verify("HMAC", key, mac, encoder.encode(`${timestamp}.${text}`))))
22
+ throw new errors_ts_1.NoMacError("webhook_signature_invalid", "The delivery's signature does not match this webhook's secret.");
23
+ return JSON.parse(text);
24
+ }
@@ -0,0 +1,11 @@
1
+ /** NoMac's refusal, in its own words: code (stable, for code to branch on), message (for a person), the HTTP status (0 when none). */
2
+ export declare class NoMacError extends Error {
3
+ readonly code: string;
4
+ readonly status: number;
5
+ readonly details: unknown;
6
+ /** A keyed request's key (a start, a command): the same request with it reads the first one's result, never doing it twice. */
7
+ requestKey?: string;
8
+ constructor(code: string, message: string, status?: number, details?: unknown);
9
+ }
10
+ /** A request key: the same key makes a retry the same request (a start, a command, a tool call, a fetch). */
11
+ export declare const requestKey: (prefix?: string) => string;
package/dist/errors.js ADDED
@@ -0,0 +1,17 @@
1
+ /** NoMac's refusal, in its own words: code (stable, for code to branch on), message (for a person), the HTTP status (0 when none). */
2
+ export class NoMacError extends Error {
3
+ code;
4
+ status;
5
+ details;
6
+ /** A keyed request's key (a start, a command): the same request with it reads the first one's result, never doing it twice. */
7
+ requestKey;
8
+ constructor(code, message, status = 0, details = undefined) {
9
+ super(message);
10
+ this.name = "NoMacError";
11
+ this.code = code;
12
+ this.status = status;
13
+ this.details = details;
14
+ }
15
+ }
16
+ /** A request key: the same key makes a retry the same request (a start, a command, a tool call, a fetch). */
17
+ export const requestKey = (prefix = "sdk") => `${prefix}-${crypto.randomUUID()}`;
package/dist/http.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ export declare const DEFAULT_BASE_URL = "https://nomac.app";
2
+ export declare const sleep: (ms: number) => Promise<void>;
3
+ export interface ClientOptions {
4
+ /** The account's API key (nmk_...). NOMAC_API_KEY when neither it nor token is passed. */
5
+ apiKey?: string;
6
+ /** One Mac's token (nmm_...) or one phone's (nmp_...), from mac.token() or phone.token(): its own Mac or phone only. */
7
+ token?: string;
8
+ /** https://nomac.app by default. */
9
+ baseUrl?: string;
10
+ /** A fetch to use instead of the global one (a proxy, a test). */
11
+ fetch?: typeof fetch;
12
+ }
13
+ export interface RequestOptions {
14
+ body?: unknown;
15
+ /** The same key makes a retry the same request: NoMac answers the first one's result. */
16
+ idempotencyKey?: string;
17
+ /** How long one try may take, in milliseconds (90 s by default). */
18
+ timeoutMs?: number;
19
+ }
20
+ /** What the resources reach NoMac with: JSON calls, and bytes to and from links NoMac signed. */
21
+ export interface Transport {
22
+ request<T = Record<string, any>>(method: string, path: string, options?: RequestOptions): Promise<T>;
23
+ upload(url: string, data: Uint8Array | ArrayBuffer | Blob): Promise<void>;
24
+ download(url: string): Promise<Uint8Array>;
25
+ downloadStream(url: string): Promise<ReadableStream<Uint8Array>>;
26
+ }
27
+ export declare class Http implements Transport {
28
+ #private;
29
+ constructor(options?: ClientOptions);
30
+ /**
31
+ * One call to the REST API: JSON in and out, NoMac's error as a NoMacError. A read, a stop and a request with a key are sent
32
+ * again up to five times when NoMac is busy or does not answer, and a keyed request NoMac is still starting (operation_pending)
33
+ * is asked again with its key. A request without a key is sent again only after a 429 rate_limited, which nothing did. A
34
+ * keyed request's error carries its key (requestKey), so its result can be read later instead of doing it twice.
35
+ */
36
+ request<T = Record<string, any>>(method: string, path: string, { body, idempotencyKey, timeoutMs }?: RequestOptions): Promise<T>;
37
+ /** PUTs bytes (a Blob as it is, never read into memory first) to a link NoMac signed: no NoMac credential goes with them. */
38
+ upload(url: string, data: Uint8Array | ArrayBuffer | Blob): Promise<void>;
39
+ /** GETs bytes from a link NoMac signed (a download link): no NoMac credential goes with them. */
40
+ download(url: string): Promise<Uint8Array<ArrayBuffer>>;
41
+ /** The same download as a stream, so a large file never sits in memory. */
42
+ downloadStream(url: string): Promise<ReadableStream<Uint8Array>>;
43
+ }
44
+ /** Base64 to bytes and back, in any runtime with atob and btoa. */
45
+ export declare function fromBase64(data: string): Uint8Array;
46
+ export declare function toBase64(bytes: Uint8Array): string;
47
+ export declare function asBytes(data: string | Uint8Array | ArrayBuffer | Blob): Promise<Uint8Array>;
48
+ export declare const hex: (bytes: ArrayBuffer | Uint8Array) => string;
package/dist/http.js ADDED
@@ -0,0 +1,136 @@
1
+ import { NoMacError } from "./errors.js";
2
+ export const DEFAULT_BASE_URL = "https://nomac.app";
3
+ // Statuses that pass: NoMac or the Mac busy for a moment.
4
+ const PASSING = new Set([429, 502, 503, 504]);
5
+ const ATTEMPTS = 6;
6
+ export const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
7
+ const pause = (attempt, retryAfter) => sleep(retryAfter !== undefined && Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 30) * 1000 : attempt * 2000);
8
+ export class Http {
9
+ #auth;
10
+ #base;
11
+ #fetch;
12
+ constructor(options = {}) {
13
+ const credential = options.apiKey ?? options.token ?? globalThis.process?.env?.NOMAC_API_KEY;
14
+ if (!credential)
15
+ throw new NoMacError("credential_required", "Pass apiKey (the account's nmk_ key) or token (one Mac's nmm_ or one phone's nmp_ token), or set NOMAC_API_KEY.");
16
+ this.#auth = `Bearer ${credential}`;
17
+ this.#base = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
18
+ this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
19
+ }
20
+ /**
21
+ * One call to the REST API: JSON in and out, NoMac's error as a NoMacError. A read, a stop and a request with a key are sent
22
+ * again up to five times when NoMac is busy or does not answer, and a keyed request NoMac is still starting (operation_pending)
23
+ * is asked again with its key. A request without a key is sent again only after a 429 rate_limited, which nothing did. A
24
+ * keyed request's error carries its key (requestKey), so its result can be read later instead of doing it twice.
25
+ */
26
+ async request(method, path, { body, idempotencyKey, timeoutMs = 90_000 } = {}) {
27
+ const headers = { authorization: this.#auth };
28
+ if (idempotencyKey)
29
+ headers["idempotency-key"] = idempotencyKey;
30
+ if (body !== undefined)
31
+ headers["content-type"] = "application/json";
32
+ const repeatable = method === "GET" || method === "DELETE" || Boolean(idempotencyKey);
33
+ const keyed = (error) => { if (idempotencyKey)
34
+ error.requestKey = idempotencyKey; return error; };
35
+ for (let attempt = 1;; attempt++) {
36
+ let response;
37
+ try {
38
+ response = await this.#fetch(`${this.#base}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs) });
39
+ }
40
+ catch (error) {
41
+ if (repeatable && attempt < ATTEMPTS) {
42
+ await pause(attempt);
43
+ continue;
44
+ }
45
+ throw keyed(new NoMacError("unreachable", `NoMac did not answer (${describe(error)}).${idempotencyKey ? ` Send the same request with the same key (${idempotencyKey}) to read its result; it is never done twice.` : ""}`));
46
+ }
47
+ const text = await response.text();
48
+ let payload = {};
49
+ try {
50
+ payload = text ? JSON.parse(text) : {};
51
+ }
52
+ catch {
53
+ payload = {};
54
+ }
55
+ if (response.ok)
56
+ return payload;
57
+ // A repeated DELETE whose first try was taken (its answer lost on the way) finds nothing left to delete.
58
+ if (method === "DELETE" && attempt > 1 && response.status === 404 && /\/webhooks\//.test(path))
59
+ return { deleted: true };
60
+ const error = payload?.error ?? {};
61
+ const again = (PASSING.has(response.status) && (repeatable || (response.status === 429 && error.code === "rate_limited")))
62
+ // A keyed request still being started by an earlier try of it: the same key answers it once started.
63
+ || (Boolean(idempotencyKey) && error.code === "operation_pending");
64
+ if (again && attempt < ATTEMPTS) {
65
+ await pause(attempt, Number(response.headers.get("retry-after") ?? error.retry_after_seconds ?? undefined));
66
+ continue;
67
+ }
68
+ throw keyed(new NoMacError(error.code ?? `http_${response.status}`, error.message ?? `NoMac answered ${response.status}.`, response.status, error));
69
+ }
70
+ }
71
+ /** PUTs bytes (a Blob as it is, never read into memory first) to a link NoMac signed: no NoMac credential goes with them. */
72
+ async upload(url, data) {
73
+ let response;
74
+ try {
75
+ response = await this.#fetch(url, { method: "PUT", body: data, signal: AbortSignal.timeout(30 * 60_000) });
76
+ }
77
+ catch (error) {
78
+ throw new NoMacError("upload_failed", `The upload did not reach NoMac's storage (${cause(error)}); a network that allows only some hosts must allow *.r2.cloudflarestorage.com.`);
79
+ }
80
+ if (!response.ok)
81
+ throw new NoMacError("upload_failed", `The upload was refused (${response.status}); ask for a new upload link.`, response.status);
82
+ }
83
+ /** GETs bytes from a link NoMac signed (a download link): no NoMac credential goes with them. */
84
+ async download(url) {
85
+ return new Uint8Array(await (await this.#get(url)).arrayBuffer());
86
+ }
87
+ /** The same download as a stream, so a large file never sits in memory. */
88
+ async downloadStream(url) {
89
+ const response = await this.#get(url);
90
+ if (!response.body)
91
+ throw new NoMacError("download_failed", "The download arrived without a body; ask for a new download link.");
92
+ return response.body;
93
+ }
94
+ async #get(url) {
95
+ let response;
96
+ try {
97
+ response = await this.#fetch(url, { signal: AbortSignal.timeout(30 * 60_000) });
98
+ }
99
+ catch (error) {
100
+ throw new NoMacError("download_failed", `The download did not arrive (${cause(error)}); a network that allows only some hosts must allow *.r2.cloudflarestorage.com.`);
101
+ }
102
+ if (!response.ok)
103
+ throw new NoMacError("download_failed", `The download was refused (${response.status}); ask for a new download link.`, response.status);
104
+ return response;
105
+ }
106
+ }
107
+ const describe = (error) => error?.message ?? String(error);
108
+ /** What a failed fetch says, with its underlying cause (Node's "fetch failed" names it only there). */
109
+ const cause = (error) => {
110
+ const e = error;
111
+ return [e?.message, e?.cause?.code ?? e?.cause?.message].filter(Boolean).join(": ") || String(error);
112
+ };
113
+ /** Base64 to bytes and back, in any runtime with atob and btoa. */
114
+ export function fromBase64(data) {
115
+ const binary = atob(data);
116
+ const bytes = new Uint8Array(binary.length);
117
+ for (let i = 0; i < binary.length; i++)
118
+ bytes[i] = binary.charCodeAt(i);
119
+ return bytes;
120
+ }
121
+ export function toBase64(bytes) {
122
+ let binary = "";
123
+ for (let i = 0; i < bytes.length; i += 0x8000)
124
+ binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
125
+ return btoa(binary);
126
+ }
127
+ export async function asBytes(data) {
128
+ if (typeof data === "string")
129
+ return new TextEncoder().encode(data);
130
+ if (data instanceof Uint8Array)
131
+ return data;
132
+ if (data instanceof ArrayBuffer)
133
+ return new Uint8Array(data);
134
+ return new Uint8Array(await data.arrayBuffer());
135
+ }
136
+ export const hex = (bytes) => Array.from(new Uint8Array(bytes), b => b.toString(16).padStart(2, "0")).join("");