@nomac/sdk 0.0.0-stage → 1.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,205 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Phone = exports.Phones = void 0;
4
+ const errors_ts_1 = require("./errors.js");
5
+ const embed_ts_1 = require("./embed.js");
6
+ const http_ts_1 = require("./http.js");
7
+ const SESSIONS = "/api/v1/simulator/sessions";
8
+ const ENDED = new Set(["stopping", "stopped", "failed"]);
9
+ const JOB = /Next: job_status \{job_id: "([^"]+)"\}/;
10
+ // job_status's answer while the job still runs (simulator-use's tools/jobs.ts): read it again with the same job.
11
+ const STILL_RUNNING = /\nNext: job_status again, or job_cancel\./;
12
+ /** The account's phones (iPhone and iPad Simulators): start one (for one of your users with a label), read one, list them. */
13
+ class Phones {
14
+ #http;
15
+ constructor(http) {
16
+ this.#http = http;
17
+ }
18
+ /**
19
+ * Starts a phone and answers it at once, usually queued: phone.waitUntilReady() follows it (a phone from the pool is ready
20
+ * in seconds). With reuse and a label, the user's live phone is the answer (phone.reused). The same idempotencyKey retries.
21
+ */
22
+ async start(options = {}, { idempotencyKey = (0, errors_ts_1.requestKey)("start") } = {}) {
23
+ const answer = await this.#http.request("POST", SESSIONS, { body: options, idempotencyKey });
24
+ return new Phone(this.#http, answer.session, answer.links, Boolean(answer.reused));
25
+ }
26
+ /** The account's phones, newest first; with label, one user's. */
27
+ async list({ label } = {}) {
28
+ const answer = await this.#http.request("GET", `${SESSIONS}${label ? `?label=${encodeURIComponent(label)}` : ""}`);
29
+ return answer.sessions.map(session => new Phone(this.#http, session));
30
+ }
31
+ /** A phone by its id, read. */
32
+ async get(id) {
33
+ return new Phone(this.#http, { id }).refresh();
34
+ }
35
+ }
36
+ exports.Phones = Phones;
37
+ /** A phone: its session (state, device, label, cost, deadlines) and links, and what can be done with it. */
38
+ class Phone {
39
+ #http;
40
+ id;
41
+ session;
42
+ links;
43
+ /** Whether a start with reuse answered this live phone instead of a new one. */
44
+ reused;
45
+ /** As of the last refresh(): set in the phone's last 15 minutes before a limit or the credit's end. */
46
+ stopNotice = null;
47
+ /** As of stop() or the last refresh(): the MP4 of a screen_record the phone's stop ended. */
48
+ recording = null;
49
+ constructor(http, session, links, reused = false) {
50
+ this.#http = http;
51
+ this.id = session.id;
52
+ this.session = session;
53
+ this.links = links;
54
+ this.reused = reused;
55
+ }
56
+ get state() {
57
+ return this.session.state;
58
+ }
59
+ #path(rest = "") {
60
+ return `${SESSIONS}/${encodeURIComponent(this.id)}${rest}`;
61
+ }
62
+ /** Reads the phone again. */
63
+ async refresh() {
64
+ const answer = await this.#http.request("GET", this.#path());
65
+ this.session = answer.session;
66
+ this.links = answer.links ?? this.links;
67
+ this.stopNotice = answer.stop_notice ?? null;
68
+ this.recording = answer.recording ?? null;
69
+ return this;
70
+ }
71
+ /** Waits until the phone is ready (a phone from the pool takes seconds; a queued one up to 5 minutes). */
72
+ async waitUntilReady({ timeoutMs = 6 * 60_000, intervalMs = 1_000 } = {}) {
73
+ const by = Date.now() + timeoutMs;
74
+ for (;;) {
75
+ if (this.state === "ready")
76
+ return this;
77
+ if (ENDED.has(this.state))
78
+ throw new errors_ts_1.NoMacError("phone_ended", `The phone ended before it was ready (${this.session.failure_code ?? this.state}).`, 0, this.session);
79
+ if (Date.now() >= by)
80
+ throw new errors_ts_1.NoMacError("timeout", `The phone was not ready within ${Math.round(timeoutMs / 1000)} s (${this.state}).`, 0, this.session);
81
+ await (0, http_ts_1.sleep)(intervalMs);
82
+ await this.refresh();
83
+ }
84
+ }
85
+ /**
86
+ * Runs one of the phone's tools (ui_look, ui_act, app_run, tests_run, app_control, ...) and waits for its result: {text,
87
+ * content, isError, raw}. A long build that hands back a job is followed with job_status until it ends, unless waitForJobs is false.
88
+ */
89
+ async tool(name, args = {}, { idempotencyKey = (0, errors_ts_1.requestKey)(name), intervalMs = 1_000, timeoutMs = 60 * 60_000, waitForJobs = true } = {}) {
90
+ const by = Date.now() + timeoutMs;
91
+ let result = await this.#call(name, args, idempotencyKey, by, intervalMs);
92
+ const job = waitForJobs && !result.isError ? JOB.exec(result.text)?.[1] : undefined;
93
+ // Each job_status waits up to 40 s for the job; one still running answers "job_status again".
94
+ // Followed until it ends or timeoutMs is spent: a running build is never answered as if it had finished.
95
+ for (let rounds = 0; job; rounds++) {
96
+ result = await this.#call("job_status", { job_id: job }, (0, errors_ts_1.requestKey)("job_status"), by, intervalMs);
97
+ if (result.isError || !STILL_RUNNING.test(result.text))
98
+ break;
99
+ if (Date.now() >= by || rounds >= 10_000)
100
+ throw new errors_ts_1.NoMacError("timeout", `${name}'s job ${job} was still running; read it later with phone.tool("job_status", { job_id: "${job}" }).`, 0, result.raw);
101
+ }
102
+ return result;
103
+ }
104
+ async #call(name, args, idempotencyKey, by, intervalMs) {
105
+ let answer = await this.#http.request("POST", this.#path(`/tools/${encodeURIComponent(name)}`), { body: args, idempotencyKey });
106
+ while (answer.state === "running" && typeof answer.id === "string") {
107
+ if (Date.now() >= by)
108
+ throw new errors_ts_1.NoMacError("timeout", `${name} was still running; cancel it with phone.cancel("${answer.id}") or read it later.`, 0, answer);
109
+ await (0, http_ts_1.sleep)(intervalMs);
110
+ answer = await this.#http.request("GET", this.#path(`/calls/${answer.id}`));
111
+ }
112
+ if (answer.state === "cancelled")
113
+ return { text: `${name} was cancelled.`, content: [], isError: true, notices: [], stopNotice: answer.stop_notice ?? null, raw: answer };
114
+ if (!answer.result)
115
+ throw new errors_ts_1.NoMacError(answer.error ?? "tool_failed", `${name} failed on the phone: ${answer.message ?? answer.error ?? answer.state}.`, 0, answer);
116
+ const content = answer.result.content ?? [];
117
+ const text = content.filter((c) => c.type === "text").map((c) => c.text ?? "").join("\n");
118
+ return { text, content, isError: Boolean(answer.result.isError), notices: Array.isArray(answer.notices) ? answer.notices : [], stopNotice: answer.stop_notice ?? null, raw: answer };
119
+ }
120
+ /** Stops a running tool call; a finished one is answered as it is. */
121
+ async cancel(callId) {
122
+ return this.#http.request("POST", this.#path(`/calls/${encodeURIComponent(callId)}/cancel`));
123
+ }
124
+ // An operation the phone runs for a while (a fetch, a save): the same request with the same key reads it until done.
125
+ async #operation(path, body, idempotencyKey, timeoutMs = 30 * 60_000, intervalMs = 1_000) {
126
+ const by = Date.now() + timeoutMs;
127
+ for (;;) {
128
+ const answer = await this.#http.request("POST", this.#path(path), { body, idempotencyKey });
129
+ if (answer.state === "running") {
130
+ if (Date.now() >= by)
131
+ throw new errors_ts_1.NoMacError("timeout", `The phone was still at it after ${Math.round(timeoutMs / 60_000)} minutes; the same call with idempotencyKey ${idempotencyKey} reads it later.`, 0, answer);
132
+ await (0, http_ts_1.sleep)(intervalMs);
133
+ continue;
134
+ }
135
+ if (answer.state === "failed")
136
+ throw new errors_ts_1.NoMacError(answer.error ?? "operation_failed", answer.message ?? `The phone could not do it (${answer.error ?? "failed"}).`, 0, answer);
137
+ return answer;
138
+ }
139
+ }
140
+ /**
141
+ * A git repository into the phone's workspace: {url, ref?, token? | secret?}. A private repository's token is token itself
142
+ * (used for this fetch, kept nowhere) or secret, the account's secret holding it. Answers {root, commit}: root is the path
143
+ * app_run and tests_run take.
144
+ */
145
+ async fetchGit({ url, ref, token, secret }, { idempotencyKey = (0, errors_ts_1.requestKey)("git"), timeoutMs } = {}) {
146
+ return this.#operation("/sync/git", { url, ...(ref ? { ref } : {}), ...(token ? { token } : {}), ...(secret ? { secret } : {}) }, idempotencyKey, timeoutMs);
147
+ }
148
+ /** An archive (.tar.gz or .zip of a project, or of a Simulator .app) into the workspace under name, up to 2 GiB. Answers {root, app?}. */
149
+ async uploadArchive(data, { name, idempotencyKey = (0, errors_ts_1.requestKey)("upload"), timeoutMs } = {}) {
150
+ const bytes = await (0, http_ts_1.asBytes)(data);
151
+ const sha256 = (0, http_ts_1.hex)(await crypto.subtle.digest("SHA-256", bytes));
152
+ const link = await this.#http.request("POST", this.#path("/sync/upload"), { body: { size: bytes.byteLength, sha256 } });
153
+ await this.#http.upload(link.upload_url, bytes);
154
+ return this.#operation("/sync/fetch", { sha256, ...(name ? { name } : {}) }, idempotencyKey, timeoutMs);
155
+ }
156
+ /**
157
+ * A link to the phone's live view for a person, no sign-in: watch only, or control: true. allowedOrigins keeps it to frames on
158
+ * your sites, and visitor to your user, signed by your server (signVisitor); the account's embed settings apply when left out.
159
+ */
160
+ async viewLink(options = {}) {
161
+ return this.#http.request("POST", this.#path("/view"), { body: (0, embed_ts_1.viewBody)(options) });
162
+ }
163
+ /** A token for this phone only, for your user or their agent: new NoMac({ token }).phone(id). 2 hours by default, a day at most. */
164
+ async token({ minutes } = {}) {
165
+ return this.#http.request("POST", this.#path("/token"), { body: minutes ? { minutes } : {} });
166
+ }
167
+ /** Revokes every token and link of this phone made so far; the phone runs on. The account's key only. */
168
+ async revokeTokens() {
169
+ return this.#http.request("DELETE", this.#path("/token"));
170
+ }
171
+ /** The phone's replay: recording, saving after its stop, then ready with its video, its calls and a link. */
172
+ async replay() {
173
+ return this.#http.request("GET", this.#path("/replay"));
174
+ }
175
+ /** Saves the phone's apps, their data, its keychain and permissions under name, for the account (and the label). */
176
+ async saveState(name, { idempotencyKey = (0, errors_ts_1.requestKey)("state"), timeoutMs } = {}) {
177
+ return this.#operation("/state", { action: "save", name }, idempotencyKey, timeoutMs);
178
+ }
179
+ /** Puts a saved state back, onto a phone of the same model and iOS. */
180
+ async restoreState(name, { idempotencyKey = (0, errors_ts_1.requestKey)("state"), timeoutMs } = {}) {
181
+ return this.#operation("/state", { action: "restore", name }, idempotencyKey, timeoutMs);
182
+ }
183
+ /** The saved states, one per name (its newest save). */
184
+ async listStates() {
185
+ return (await this.#operation("/state", { action: "list" }, (0, errors_ts_1.requestKey)("state"))).states ?? [];
186
+ }
187
+ async deleteState(name) {
188
+ return this.#operation("/state", { action: "delete", name }, (0, errors_ts_1.requestKey)("state"));
189
+ }
190
+ /** More time (60 minutes by default, up to 8 hours in all), its spend cap with it; the account's key only. A repeat adds more. */
191
+ async extend({ minutes } = {}) {
192
+ const answer = await this.#http.request("POST", this.#path("/extend"), { body: minutes ? { minutes } : {} });
193
+ this.session = answer.session;
194
+ this.stopNotice = answer.stop_notice ?? null;
195
+ return this;
196
+ }
197
+ /** Stops the phone: its apps and data go, its workspace stays for the next phone, its replay is saved. */
198
+ async stop() {
199
+ const answer = await this.#http.request("DELETE", this.#path());
200
+ this.session = answer.session;
201
+ this.recording = answer.recording ?? null;
202
+ return this;
203
+ }
204
+ }
205
+ exports.Phone = Phone;
@@ -0,0 +1,424 @@
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
+ /** A view link; allowed_origins, visitor_required and visitor say what it is limited to, when it is. */
243
+ export interface ViewLink {
244
+ url: string;
245
+ mode: "watch" | "control";
246
+ expires_at: string;
247
+ allowed_origins?: string[];
248
+ visitor_required?: boolean;
249
+ visitor?: string;
250
+ }
251
+ export interface ViewLinkOptions {
252
+ /** The person's clicks and keys reach the Mac or phone (one at a time). Watch only by default. */
253
+ control?: boolean;
254
+ /** How long the link works: 120 by default, a day at most. */
255
+ minutes?: number;
256
+ /**
257
+ * The sites that may show the link in a frame, such as https://app.example.com, https://*.example.com or
258
+ * http://localhost:3000 (up to 10). It then opens only in a frame on one of them. The account's own list when left out.
259
+ */
260
+ allowedOrigins?: string[];
261
+ /** It opens only for this visitor (your user's id), with your server's signature from signVisitor. */
262
+ visitor?: string;
263
+ }
264
+ /** How the account's view links may be shown: they apply to every link made after they are saved. */
265
+ export interface EmbedSettings {
266
+ allowed_origins: string[];
267
+ require_visitor: boolean;
268
+ /** The embed secret's age; its value is in newSecret's answer only. */
269
+ secret: {
270
+ created_at: string;
271
+ } | null;
272
+ }
273
+ export interface SessionToken {
274
+ token: string;
275
+ session_id: string;
276
+ expires_at: string;
277
+ }
278
+ /** What NoMac keeps for one of your users (a label): their running Macs and phones, and their drive. */
279
+ export interface LabelView {
280
+ label: string;
281
+ macs: {
282
+ running: string[];
283
+ drive: {
284
+ used_bytes: number;
285
+ saved_at: string | null;
286
+ saving: boolean;
287
+ charged: boolean;
288
+ expires_at: string;
289
+ } | null;
290
+ };
291
+ phones: {
292
+ running: string[];
293
+ [field: string]: unknown;
294
+ };
295
+ [field: string]: unknown;
296
+ }
297
+ export interface Credits {
298
+ currency: string;
299
+ spendable_microunits: string;
300
+ spendable_seconds: number;
301
+ [field: string]: unknown;
302
+ }
303
+ export type WebhookEventType = "mac.ready" | "mac.ending_soon" | "mac.ended" | "drive.saved" | "drive.deleted" | "credit.low" | "phone.ready" | "phone.ended";
304
+ export interface Webhook {
305
+ id: string;
306
+ url: string;
307
+ events: WebhookEventType[];
308
+ created_at: string;
309
+ /** Deliveries given up in the last 7 days (none answered 2xx in 12 tries). */
310
+ failing?: number;
311
+ }
312
+ export interface WebhookDelivery {
313
+ id: string;
314
+ event: WebhookEventType;
315
+ /** What it is about: a session's id, a drive's version, a credit episode. */
316
+ subject?: string;
317
+ session_id: string | null;
318
+ state: "delivered" | "retrying" | "gave_up";
319
+ attempts: number;
320
+ last_error: string | null;
321
+ created_at: string;
322
+ delivered_at: string | null;
323
+ next_attempt_at: string | null;
324
+ }
325
+ /** Why a Mac or phone ended. crashed: it or its host failed (failure_code says more). */
326
+ export type EndReason = "stopped" | "idle" | "time_limit" | "spend_cap" | "credit" | "crashed" | "no_capacity" | "start_failed" | "queue_expired" | "drive_unavailable";
327
+ export interface WebhookSession {
328
+ id: string;
329
+ state: SessionState;
330
+ label: string | null;
331
+ ready_at: string | null;
332
+ shutdown_at: string | null;
333
+ failure_code: string | null;
334
+ cost: Cost;
335
+ /** A Mac's drive: on mac.ready its state (mounted, preparing, unavailable, none), on mac.ended whether its save is still to come. */
336
+ drive?: {
337
+ name?: string;
338
+ label?: string;
339
+ state?: string;
340
+ saving?: boolean;
341
+ };
342
+ device?: PhoneDevice;
343
+ }
344
+ export type WebhookEvent = {
345
+ id: string;
346
+ type: "mac.ready";
347
+ created_at: string;
348
+ data: {
349
+ session: WebhookSession;
350
+ };
351
+ } | {
352
+ id: string;
353
+ type: "mac.ending_soon";
354
+ created_at: string;
355
+ data: {
356
+ session: {
357
+ id: string;
358
+ label: string | null;
359
+ };
360
+ stops_at: string;
361
+ seconds_left: number;
362
+ reason: "time_limit" | "spend_cap" | "credit";
363
+ };
364
+ } | {
365
+ id: string;
366
+ type: "mac.ended";
367
+ created_at: string;
368
+ data: {
369
+ session: WebhookSession;
370
+ reason: EndReason;
371
+ };
372
+ } | {
373
+ id: string;
374
+ type: "drive.saved";
375
+ created_at: string;
376
+ data: {
377
+ drive: {
378
+ label: string;
379
+ version: number;
380
+ head: boolean;
381
+ used_bytes: number;
382
+ changed_bytes: number;
383
+ charge_microunits: string;
384
+ };
385
+ session_id: string;
386
+ };
387
+ } | {
388
+ id: string;
389
+ type: "drive.deleted";
390
+ created_at: string;
391
+ data: {
392
+ drive: {
393
+ label: string;
394
+ reason: "deleted" | "expired";
395
+ };
396
+ };
397
+ } | {
398
+ id: string;
399
+ type: "credit.low";
400
+ created_at: string;
401
+ data: {
402
+ credit: {
403
+ spendable_microunits: string;
404
+ running_macs: number;
405
+ running_phones: number;
406
+ covers_seconds: number;
407
+ };
408
+ };
409
+ } | {
410
+ id: string;
411
+ type: "phone.ready";
412
+ created_at: string;
413
+ data: {
414
+ session: WebhookSession;
415
+ };
416
+ } | {
417
+ id: string;
418
+ type: "phone.ended";
419
+ created_at: string;
420
+ data: {
421
+ session: WebhookSession;
422
+ reason: EndReason;
423
+ };
424
+ };
@@ -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
+ }