@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,38 @@
1
+ /**
2
+ * NoMac from JavaScript and TypeScript: a cloud Mac or an iPhone Simulator for each of your users and agents, billed per minute,
3
+ * over NoMac's REST API (https://nomac.app/docs/api). No dependencies; runs wherever fetch and Web Crypto do (Node 20 and later,
4
+ * Bun, Deno, workers).
5
+ */
6
+ import { Labels, Webhooks } from "./account.ts";
7
+ import { type ClientOptions, type RequestOptions } from "./http.ts";
8
+ import { Mac, Macs } from "./mac.ts";
9
+ import { Phone, Phones } from "./phone.ts";
10
+ import type { Credits } from "./types.ts";
11
+ export declare class NoMac {
12
+ #private;
13
+ /** Macs: start one (for one of your users with a label), read, list. */
14
+ readonly macs: Macs;
15
+ /** Phones (iPhone and iPad Simulators): start one, read, list. */
16
+ readonly phones: Phones;
17
+ /** Your users, by label: what NoMac keeps for each, and deleting it. */
18
+ readonly labels: Labels;
19
+ /** Webhooks for your users' Macs, drives and phones, and the account's credit. */
20
+ readonly webhooks: Webhooks;
21
+ /** With the account's API key (apiKey, or NOMAC_API_KEY), or with one Mac's or phone's token (token), for that one only. */
22
+ constructor(options?: ClientOptions);
23
+ /** A Mac by its id, without reading it: what a Mac's token reaches (new NoMac({ token }).mac(id)). */
24
+ mac(id: string): Mac;
25
+ /** A phone by its id, without reading it: what a phone's token reaches. */
26
+ phone(id: string): Phone;
27
+ /** The account's prepaid credit: what it can spend and the time that buys. */
28
+ credits(): Promise<Credits>;
29
+ /** One call to the REST API directly: JSON in and out, NoMac's error as a NoMacError. */
30
+ request<T = Record<string, any>>(method: string, path: string, options?: RequestOptions): Promise<T>;
31
+ }
32
+ export { NoMacError, requestKey } from "./errors.ts";
33
+ export { verifyWebhook } from "./webhooks.ts";
34
+ export { Mac, Macs, MacFiles, MacJobs } from "./mac.ts";
35
+ export { Phone, Phones } from "./phone.ts";
36
+ export { Labels, Webhooks } from "./account.ts";
37
+ export type { ClientOptions, RequestOptions } from "./http.ts";
38
+ export type * from "./types.ts";
package/dist/index.js ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * NoMac from JavaScript and TypeScript: a cloud Mac or an iPhone Simulator for each of your users and agents, billed per minute,
3
+ * over NoMac's REST API (https://nomac.app/docs/api). No dependencies; runs wherever fetch and Web Crypto do (Node 20 and later,
4
+ * Bun, Deno, workers).
5
+ */
6
+ import { credits, Labels, Webhooks } from "./account.js";
7
+ import { Http } from "./http.js";
8
+ import { Mac, Macs } from "./mac.js";
9
+ import { Phone, Phones } from "./phone.js";
10
+ export class NoMac {
11
+ #http;
12
+ /** Macs: start one (for one of your users with a label), read, list. */
13
+ macs;
14
+ /** Phones (iPhone and iPad Simulators): start one, read, list. */
15
+ phones;
16
+ /** Your users, by label: what NoMac keeps for each, and deleting it. */
17
+ labels;
18
+ /** Webhooks for your users' Macs, drives and phones, and the account's credit. */
19
+ webhooks;
20
+ /** With the account's API key (apiKey, or NOMAC_API_KEY), or with one Mac's or phone's token (token), for that one only. */
21
+ constructor(options = {}) {
22
+ this.#http = new Http(options);
23
+ this.macs = new Macs(this.#http);
24
+ this.phones = new Phones(this.#http);
25
+ this.labels = new Labels(this.#http);
26
+ this.webhooks = new Webhooks(this.#http);
27
+ }
28
+ /** A Mac by its id, without reading it: what a Mac's token reaches (new NoMac({ token }).mac(id)). */
29
+ mac(id) {
30
+ return new Mac(this.#http, { id });
31
+ }
32
+ /** A phone by its id, without reading it: what a phone's token reaches. */
33
+ phone(id) {
34
+ return new Phone(this.#http, { id });
35
+ }
36
+ /** The account's prepaid credit: what it can spend and the time that buys. */
37
+ credits() {
38
+ return credits(this.#http);
39
+ }
40
+ /** One call to the REST API directly: JSON in and out, NoMac's error as a NoMacError. */
41
+ request(method, path, options) {
42
+ return this.#http.request(method, path, options);
43
+ }
44
+ }
45
+ export { NoMacError, requestKey } from "./errors.js";
46
+ export { verifyWebhook } from "./webhooks.js";
47
+ export { Mac, Macs, MacFiles, MacJobs } from "./mac.js";
48
+ export { Phone, Phones } from "./phone.js";
49
+ export { Labels, Webhooks } from "./account.js";
package/dist/mac.d.ts ADDED
@@ -0,0 +1,178 @@
1
+ import { type Transport } from "./http.ts";
2
+ import type { CommandResult, FileLink, InputAction, Job, MacSession, MacStartOptions, RunOptions, Screenshot, SessionToken, StopNotice, ViewLink } from "./types.ts";
3
+ /** The account's Macs: start one (for one of your users with a label), read one, list them. */
4
+ export declare class Macs {
5
+ #private;
6
+ constructor(http: Transport);
7
+ /**
8
+ * Starts a Mac and answers it at once (queued, then provisioning): mac.waitUntilReady() follows it, usually under a minute.
9
+ * With label, it is your user's Mac: their drive at ~/drive and none of the account's secrets; with reuse too, the user's
10
+ * running Mac is the answer (mac.reused). Pass the same idempotencyKey to retry a start.
11
+ */
12
+ start(options?: MacStartOptions, { idempotencyKey }?: {
13
+ idempotencyKey?: string;
14
+ }): Promise<Mac>;
15
+ /** A Mac by its id, read. */
16
+ get(id: string): Promise<Mac>;
17
+ /**
18
+ * Your users' Macs, newest first: one user's (label) or all of them (labeled: true), live or ended, a page at a time
19
+ * (before: the last id of the page before; more says whether another follows). Without label or labeled, the newest
20
+ * 100 of the account's own Macs.
21
+ */
22
+ list(filter?: {
23
+ label?: string;
24
+ labeled?: boolean;
25
+ state?: "live" | "ended";
26
+ before?: string;
27
+ limit?: number;
28
+ }): Promise<{
29
+ macs: Mac[];
30
+ more: boolean;
31
+ }>;
32
+ }
33
+ /** A Mac: its session (state, label, drive, cost, limits) and what can be done on it. */
34
+ export declare class Mac {
35
+ #private;
36
+ readonly id: string;
37
+ session: MacSession;
38
+ /** Whether a start with reuse answered this running Mac instead of a new one. */
39
+ readonly reused: boolean;
40
+ /** As of the last refresh(), run() or extend(): set in the Mac's last 15 minutes before a limit or the credit's end. */
41
+ stopNotice: StopNotice | null;
42
+ readonly files: MacFiles;
43
+ readonly jobs: MacJobs;
44
+ constructor(http: Transport, session: MacSession, reused?: boolean);
45
+ get state(): import("./types.ts").SessionState;
46
+ /** Your user's id, for a Mac started with a label. */
47
+ get label(): string | undefined;
48
+ /** Reads the Mac again. */
49
+ refresh(): Promise<this>;
50
+ /**
51
+ * Waits until the Mac is ready: usually under a minute. A start waiting in line (queue_seconds) is waited for until its line
52
+ * ends, whatever timeoutMs says, so a Mac that starts in its turn is never left running unwatched.
53
+ */
54
+ waitUntilReady({ timeoutMs, intervalMs }?: {
55
+ timeoutMs?: number;
56
+ intervalMs?: number;
57
+ }): Promise<this>;
58
+ /**
59
+ * Runs a command and waits for it to end: {exitCode, stdout, stderr}, with the whole output. A string runs in bash -lc
60
+ * (pipes, &&, globs); an array runs as it is. A command that ends with a non-zero code is answered, not thrown.
61
+ */
62
+ run(command: string | string[], options?: RunOptions & {
63
+ timeoutMs?: number;
64
+ }): Promise<CommandResult>;
65
+ /** A JPEG of the desktop (1440x900, image pixels are screen points) or of the booted Simulator, with what is on the screen. */
66
+ screenshot({ target }?: {
67
+ target?: "screen" | "simulator";
68
+ }): Promise<Screenshot>;
69
+ /** The keyboard and mouse, which macOS takes as a person's (also on the lock screen and in password dialogs). Not repeated by itself: a retry types again. */
70
+ input(action: InputAction | (Omit<Extract<InputAction, {
71
+ action: "key";
72
+ }>, "keys"> & {
73
+ keys: string;
74
+ })): Promise<Record<string, any>>;
75
+ /** Starts a video of the screen (or of the Simulator), which stops by itself after maxSeconds (300 by default, 1,800 at most). */
76
+ startRecording({ target, maxSeconds }?: {
77
+ target?: "screen" | "simulator";
78
+ maxSeconds?: number;
79
+ }): Promise<Record<string, any>>;
80
+ /** Stops the recording and answers its MP4 as a download link ({recording, link}); safe to repeat. */
81
+ stopRecording(): Promise<Record<string, any>>;
82
+ /** The Mac's login password ({user, password, variable}), also $NOMAC_MAC_PASSWORD on the Mac; each read is audited. */
83
+ password(): Promise<{
84
+ user: string;
85
+ password: string;
86
+ variable: string;
87
+ }>;
88
+ /**
89
+ * A link to the Mac's desktop for a person, no sign-in, in a browser or an iframe (add ?embed=1): watch only, or control
90
+ * (one controller at a time; the newest takes over). Your user's Mac only (started with a label). Lasts 2 hours by default,
91
+ * a day at most; DELETE .../token (revokeTokens) ends it.
92
+ */
93
+ viewLink({ control, minutes }?: {
94
+ control?: boolean;
95
+ minutes?: number;
96
+ }): Promise<ViewLink>;
97
+ /**
98
+ * A token for this Mac only, to hand your user or their agent: new NoMac({ token }).mac(id) reaches its commands, files,
99
+ * screen, input and view links, never another Mac, a start, a stop or the account. 2 hours by default, a day at most.
100
+ */
101
+ token({ minutes }?: {
102
+ minutes?: number;
103
+ }): Promise<SessionToken>;
104
+ /** Revokes every token and link of this Mac made so far; the Mac runs on, and new ones work. The account's key only. */
105
+ revokeTokens(): Promise<{
106
+ revoked_at: string;
107
+ }>;
108
+ /**
109
+ * Keeps the Mac running longer: its time limit goes up by minutes (60 by default; a Mac has no longest time), and its
110
+ * spend cap by what that time costs. The account's key only. Not sent again by itself: a repeat adds more time.
111
+ */
112
+ extend({ minutes }?: {
113
+ minutes?: number;
114
+ }): Promise<this>;
115
+ /**
116
+ * Stops the Mac: it and every file outside ~/drive are deleted, and ~/drive is saved for the next Mac. The account's key
117
+ * only. confirm: stop it even while another API key is using it (the account's own Macs ask; a user's Mac never does).
118
+ */
119
+ stop({ confirm }?: {
120
+ confirm?: boolean;
121
+ }): Promise<this>;
122
+ }
123
+ /** Commands on a Mac: start one, read it, wait for its end, cancel it. mac.run() is start and wait in one. */
124
+ export declare class MacJobs {
125
+ #private;
126
+ constructor(http: Transport, base: string, notice: (notice: StopNotice | undefined) => void);
127
+ /** Starts a command (a string runs in bash -lc) and answers its job, maybe already ended. The same idempotencyKey never runs it twice. */
128
+ start(command: string | string[], { cwd, env, timeoutSeconds, idempotencyKey }?: RunOptions): Promise<Job>;
129
+ /** A job as it is now; with waitSeconds (up to 50), waits that long for it to end first. */
130
+ get(id: string, { waitSeconds }?: {
131
+ waitSeconds?: number;
132
+ }): Promise<Job>;
133
+ /**
134
+ * Waits for a job (its id, or the job start answered) to end and answers its whole output. Never run a command again for its
135
+ * output: wait for its job.
136
+ */
137
+ wait(job: string | Job, { timeoutMs }?: {
138
+ timeoutMs?: number;
139
+ }): Promise<CommandResult>;
140
+ /** Stops a running command and what it started; a finished one is answered as it is. */
141
+ cancel(id: string): Promise<Job>;
142
+ }
143
+ /** Files on a Mac: up to 3 MiB in a call, and any size up to 2 GiB through a link. Relative paths are in the workspace; ~ is home. */
144
+ export declare class MacFiles {
145
+ #private;
146
+ constructor(http: Transport, base: string);
147
+ /** Writes a file (folders made, the file replaced in one step, so safe to repeat). Larger than 3 MiB goes by an upload link. */
148
+ write(path: string, content: string | Uint8Array | ArrayBuffer | Blob, { executable }?: {
149
+ executable?: boolean;
150
+ }): Promise<Record<string, any>>;
151
+ /** A file's bytes, any size up to 2 GiB (larger than 3 MiB comes by a download link). */
152
+ readBytes(path: string): Promise<Uint8Array>;
153
+ /** A text file, as UTF-8. */
154
+ read(path: string): Promise<string>;
155
+ /**
156
+ * A link that puts one file on the Mac at path, for a person (url: a page, no account) or a program (upload_url, then the
157
+ * link's own address to place it): extract unpacks a zip or tar into path. 60 minutes by default, a day at most.
158
+ */
159
+ uploadLink(path: string, options?: {
160
+ executable?: boolean;
161
+ extract?: "zip" | "tar";
162
+ minutes?: number;
163
+ }): Promise<FileLink>;
164
+ /** A link to a file or a folder (as a zip) on the Mac, which keeps working after the Mac stops, until it expires. */
165
+ downloadLink(path: string, options?: {
166
+ minutes?: number;
167
+ waitSeconds?: number;
168
+ }): Promise<FileLink>;
169
+ /** Puts bytes on the Mac at path through an upload link, and waits until the Mac has them. */
170
+ upload(path: string, data: string | Uint8Array | ArrayBuffer | Blob, options?: {
171
+ executable?: boolean;
172
+ extract?: "zip" | "tar";
173
+ }): Promise<Record<string, any>>;
174
+ /** A file's bytes (a folder's as a zip) from the Mac through a download link. */
175
+ download(path: string): Promise<Uint8Array>;
176
+ /** The same as a stream, for a file too large to hold in memory (up to 2 GiB): pipe it to a file or onward. */
177
+ downloadStream(path: string): Promise<ReadableStream<Uint8Array>>;
178
+ }
package/dist/mac.js ADDED
@@ -0,0 +1,344 @@
1
+ import { NoMacError, requestKey } from "./errors.js";
2
+ import { asBytes, fromBase64, sleep, toBase64 } from "./http.js";
3
+ const SESSIONS = "/api/v1/mac/sessions";
4
+ const ENDED = new Set(["stopping", "stopped", "failed"]);
5
+ const FINISHED = new Set(["exited", "unknown"]);
6
+ // The longest a request waits for a command on NoMac's side; the SDK asks again until the command ends.
7
+ const WAIT_SECONDS = 40;
8
+ // What one file call carries (larger files go by a link).
9
+ const FILE_CALL_BYTES = 3 * 1024 * 1024;
10
+ const decoder = new TextDecoder();
11
+ /** The account's Macs: start one (for one of your users with a label), read one, list them. */
12
+ export class Macs {
13
+ #http;
14
+ constructor(http) {
15
+ this.#http = http;
16
+ }
17
+ /**
18
+ * Starts a Mac and answers it at once (queued, then provisioning): mac.waitUntilReady() follows it, usually under a minute.
19
+ * With label, it is your user's Mac: their drive at ~/drive and none of the account's secrets; with reuse too, the user's
20
+ * running Mac is the answer (mac.reused). Pass the same idempotencyKey to retry a start.
21
+ */
22
+ async start(options = {}, { idempotencyKey = requestKey("start") } = {}) {
23
+ const answer = await this.#http.request("POST", SESSIONS, { body: options, idempotencyKey });
24
+ return new Mac(this.#http, answer.session, Boolean(answer.reused));
25
+ }
26
+ /** A Mac by its id, read. */
27
+ async get(id) {
28
+ return new Mac(this.#http, { id }).refresh();
29
+ }
30
+ /**
31
+ * Your users' Macs, newest first: one user's (label) or all of them (labeled: true), live or ended, a page at a time
32
+ * (before: the last id of the page before; more says whether another follows). Without label or labeled, the newest
33
+ * 100 of the account's own Macs.
34
+ */
35
+ async list(filter = {}) {
36
+ const query = new URLSearchParams();
37
+ if (filter.label)
38
+ query.set("label", filter.label);
39
+ if (filter.labeled)
40
+ query.set("labeled", "true");
41
+ if (filter.state)
42
+ query.set("state", filter.state);
43
+ if (filter.before)
44
+ query.set("before", filter.before);
45
+ if (filter.limit)
46
+ query.set("limit", String(filter.limit));
47
+ const answer = await this.#http.request("GET", `${SESSIONS}${query.size ? `?${query}` : ""}`);
48
+ return { macs: answer.sessions.map(session => new Mac(this.#http, session)), more: Boolean(answer.more) };
49
+ }
50
+ }
51
+ /** A Mac: its session (state, label, drive, cost, limits) and what can be done on it. */
52
+ export class Mac {
53
+ #http;
54
+ id;
55
+ session;
56
+ /** Whether a start with reuse answered this running Mac instead of a new one. */
57
+ reused;
58
+ /** As of the last refresh(), run() or extend(): set in the Mac's last 15 minutes before a limit or the credit's end. */
59
+ stopNotice = null;
60
+ files;
61
+ jobs;
62
+ constructor(http, session, reused = false) {
63
+ this.#http = http;
64
+ this.id = session.id;
65
+ this.session = session;
66
+ this.reused = reused;
67
+ this.files = new MacFiles(http, this.#path());
68
+ this.jobs = new MacJobs(http, this.#path(), notice => { this.stopNotice = notice ?? this.stopNotice; });
69
+ }
70
+ get state() {
71
+ return this.session.state;
72
+ }
73
+ /** Your user's id, for a Mac started with a label. */
74
+ get label() {
75
+ return this.session.label;
76
+ }
77
+ #path(rest = "") {
78
+ return `${SESSIONS}/${encodeURIComponent(this.id)}${rest}`;
79
+ }
80
+ /** Reads the Mac again. */
81
+ async refresh() {
82
+ const answer = await this.#http.request("GET", this.#path());
83
+ this.session = answer.session;
84
+ this.stopNotice = answer.stop_notice ?? null;
85
+ return this;
86
+ }
87
+ /**
88
+ * Waits until the Mac is ready: usually under a minute. A start waiting in line (queue_seconds) is waited for until its line
89
+ * ends, whatever timeoutMs says, so a Mac that starts in its turn is never left running unwatched.
90
+ */
91
+ async waitUntilReady({ timeoutMs = 20 * 60_000, intervalMs = 2_000 } = {}) {
92
+ const lineEnds = Date.parse(String(this.session.queue_expires_at ?? "")) + 10 * 60_000;
93
+ const by = Math.max(Date.now() + timeoutMs, Number.isFinite(lineEnds) ? lineEnds : 0);
94
+ for (;;) {
95
+ if (this.state === "ready")
96
+ return this;
97
+ if (ENDED.has(this.state))
98
+ throw new NoMacError("mac_ended", `The Mac ended before it was ready (${this.session.failure_code ?? this.state}).`, 0, this.session);
99
+ if (Date.now() >= by)
100
+ throw new NoMacError("timeout", `The Mac was not ready within ${Math.round(timeoutMs / 1000)} s (${this.state}).`, 0, this.session);
101
+ await sleep(intervalMs);
102
+ await this.refresh();
103
+ }
104
+ }
105
+ /**
106
+ * Runs a command and waits for it to end: {exitCode, stdout, stderr}, with the whole output. A string runs in bash -lc
107
+ * (pipes, &&, globs); an array runs as it is. A command that ends with a non-zero code is answered, not thrown.
108
+ */
109
+ async run(command, options = {}) {
110
+ // A quick command ends within the start's own wait, and its answer carries the output: no second read.
111
+ return this.jobs.wait(await this.jobs.start(command, options), { timeoutMs: options.timeoutMs });
112
+ }
113
+ /** A JPEG of the desktop (1440x900, image pixels are screen points) or of the booted Simulator, with what is on the screen. */
114
+ async screenshot({ target = "screen" } = {}) {
115
+ const { image_base64, ...rest } = await this.#http.request("POST", this.#path("/screenshot"), { body: { target }, timeoutMs: 120_000 });
116
+ return { ...rest, image: fromBase64(String(image_base64 ?? "")) };
117
+ }
118
+ /** The keyboard and mouse, which macOS takes as a person's (also on the lock screen and in password dialogs). Not repeated by itself: a retry types again. */
119
+ async input(action) {
120
+ // keys is a list; one key or chord may be given as a string.
121
+ const body = action.action === "key" && typeof action.keys === "string" ? { ...action, keys: [action.keys] } : action;
122
+ // Typing 500 characters and the screenshot after can take the server close to two minutes.
123
+ return this.#http.request("POST", this.#path("/input"), { body, timeoutMs: 120_000 });
124
+ }
125
+ /** Starts a video of the screen (or of the Simulator), which stops by itself after maxSeconds (300 by default, 1,800 at most). */
126
+ async startRecording({ target, maxSeconds } = {}) {
127
+ return this.#http.request("POST", this.#path("/recording"), { body: { ...(target ? { target } : {}), ...(maxSeconds ? { max_seconds: maxSeconds } : {}) } });
128
+ }
129
+ /** Stops the recording and answers its MP4 as a download link ({recording, link}); safe to repeat. */
130
+ async stopRecording() {
131
+ return this.#http.request("DELETE", this.#path("/recording"), { timeoutMs: 300_000 });
132
+ }
133
+ /** The Mac's login password ({user, password, variable}), also $NOMAC_MAC_PASSWORD on the Mac; each read is audited. */
134
+ async password() {
135
+ return this.#http.request("GET", this.#path("/password"));
136
+ }
137
+ /**
138
+ * A link to the Mac's desktop for a person, no sign-in, in a browser or an iframe (add ?embed=1): watch only, or control
139
+ * (one controller at a time; the newest takes over). Your user's Mac only (started with a label). Lasts 2 hours by default,
140
+ * a day at most; DELETE .../token (revokeTokens) ends it.
141
+ */
142
+ async viewLink({ control = false, minutes } = {}) {
143
+ return this.#http.request("POST", this.#path("/view"), { body: { control, ...(minutes ? { minutes } : {}) } });
144
+ }
145
+ /**
146
+ * A token for this Mac only, to hand your user or their agent: new NoMac({ token }).mac(id) reaches its commands, files,
147
+ * screen, input and view links, never another Mac, a start, a stop or the account. 2 hours by default, a day at most.
148
+ */
149
+ async token({ minutes } = {}) {
150
+ // Your user's Mac only (started with a label): the account's own Macs carry its secrets (not_a_platform_mac).
151
+ return this.#http.request("POST", this.#path("/token"), { body: minutes ? { minutes } : {} });
152
+ }
153
+ /** Revokes every token and link of this Mac made so far; the Mac runs on, and new ones work. The account's key only. */
154
+ async revokeTokens() {
155
+ return this.#http.request("DELETE", this.#path("/token"));
156
+ }
157
+ /**
158
+ * Keeps the Mac running longer: its time limit goes up by minutes (60 by default; a Mac has no longest time), and its
159
+ * spend cap by what that time costs. The account's key only. Not sent again by itself: a repeat adds more time.
160
+ */
161
+ async extend({ minutes } = {}) {
162
+ const answer = await this.#http.request("POST", this.#path("/extend"), { body: minutes ? { minutes } : {} });
163
+ this.session = answer.session;
164
+ this.stopNotice = answer.stop_notice ?? null;
165
+ return this;
166
+ }
167
+ /**
168
+ * Stops the Mac: it and every file outside ~/drive are deleted, and ~/drive is saved for the next Mac. The account's key
169
+ * only. confirm: stop it even while another API key is using it (the account's own Macs ask; a user's Mac never does).
170
+ */
171
+ async stop({ confirm = false } = {}) {
172
+ const answer = await this.#http.request("DELETE", this.#path(confirm ? "?confirm=true" : ""));
173
+ this.session = answer.session;
174
+ return this;
175
+ }
176
+ }
177
+ /** Commands on a Mac: start one, read it, wait for its end, cancel it. mac.run() is start and wait in one. */
178
+ export class MacJobs {
179
+ #http;
180
+ #base;
181
+ #notice;
182
+ constructor(http, base, notice) {
183
+ this.#http = http;
184
+ this.#base = base;
185
+ this.#notice = notice;
186
+ }
187
+ /** Starts a command (a string runs in bash -lc) and answers its job, maybe already ended. The same idempotencyKey never runs it twice. */
188
+ async start(command, { cwd, env, timeoutSeconds, idempotencyKey = requestKey("run") } = {}) {
189
+ const argv = typeof command === "string" ? ["/bin/bash", "-lc", command] : command;
190
+ if (!argv.length)
191
+ throw new NoMacError("invalid_request", "Give a command: a string, or argv with at least one item.");
192
+ const job = await this.#http.request("POST", `${this.#base}/jobs?wait=${WAIT_SECONDS}`, {
193
+ body: { argv, ...(cwd ? { cwd } : {}), ...(env ? { env } : {}), ...(timeoutSeconds ? { timeout_seconds: timeoutSeconds } : {}) }, idempotencyKey, timeoutMs: (WAIT_SECONDS + 50) * 1000
194
+ });
195
+ this.#notice(job.stop_notice);
196
+ return job;
197
+ }
198
+ /** A job as it is now; with waitSeconds (up to 50), waits that long for it to end first. */
199
+ async get(id, { waitSeconds } = {}) {
200
+ const job = await this.#http.request("GET", `${this.#base}/jobs/${encodeURIComponent(id)}${waitSeconds ? `?wait=${waitSeconds}` : ""}`, { timeoutMs: ((waitSeconds ?? 0) + 50) * 1000 });
201
+ this.#notice(job.stop_notice);
202
+ return job;
203
+ }
204
+ /**
205
+ * Waits for a job (its id, or the job start answered) to end and answers its whole output. Never run a command again for its
206
+ * output: wait for its job.
207
+ */
208
+ async wait(job, { timeoutMs = 2 * 60 * 60_000 } = {}) {
209
+ const by = Date.now() + timeoutMs, id = typeof job === "string" ? job : job.id;
210
+ // Only a waiting read answers an ended job's output: each read waits, the first one too.
211
+ let current = typeof job === "string" ? await this.get(id, { waitSeconds: WAIT_SECONDS }) : job;
212
+ while (!FINISHED.has(current.state)) {
213
+ if (Date.now() >= by)
214
+ throw new NoMacError("timeout", `The command ${id} was still running; it keeps running on the Mac: mac.jobs.wait("${id}") later.`, 0, current);
215
+ current = await this.get(id, { waitSeconds: WAIT_SECONDS });
216
+ }
217
+ const ended = current;
218
+ const exitCode = typeof ended.exit_code === "number" ? ended.exit_code : null;
219
+ try {
220
+ const [stdout, stderr] = await Promise.all([this.#stream(ended, "stdout"), this.#stream(ended, "stderr")]);
221
+ return { exitCode, stdout: stdout.text, stderr: stderr.text, truncated: stdout.truncated || stderr.truncated, job: ended };
222
+ }
223
+ catch (error) {
224
+ // The command ended, but its output could not be read (old output removed: output_expired): its exit code still counts.
225
+ // A credential that no longer reaches the Mac is the caller's to know, not a missing output.
226
+ if (!(error instanceof NoMacError) || error.status === 401 || error.status === 403)
227
+ throw error;
228
+ return { exitCode, stdout: "", stderr: "", truncated: false, job: ended, outputError: error.code };
229
+ }
230
+ }
231
+ /** Stops a running command and what it started; a finished one is answered as it is. */
232
+ async cancel(id) {
233
+ return this.#http.request("POST", `${this.#base}/jobs/${encodeURIComponent(id)}/cancel`);
234
+ }
235
+ /** A stream of an ended job, whole: what its answer carries, then the rest read from the Mac, and past 8 MiB its kept tail. */
236
+ async #stream(job, stream) {
237
+ if (typeof job[stream] === "string" && !job[`${stream}_more`]) {
238
+ const tail = job[`${stream}_tail`];
239
+ return { text: `${job[stream]}${typeof tail === "string" ? tail : ""}`, truncated: Boolean(job[`${stream}_truncated`]) };
240
+ }
241
+ const parts = [];
242
+ let truncated = false;
243
+ for (let cursor = 0, reads = 0; reads < 1000; reads++) {
244
+ const part = await this.#http.request("GET", `${this.#base}/jobs/${encodeURIComponent(job.id)}/output?stream=${stream}&cursor=${cursor}`);
245
+ parts.push(fromBase64(String(part.data_base64 ?? "")));
246
+ const next = Number.isSafeInteger(part.next_cursor) ? part.next_cursor : cursor;
247
+ if (part.eof || next === cursor) {
248
+ // Past the 8 MiB both streams share, a stream's last 64 KiB was kept apart: add what the kept start does not hold.
249
+ if (part.tail_base64 && Number(part.total_bytes) > next) {
250
+ const tail = fromBase64(String(part.tail_base64)), start = Number(part.tail_offset);
251
+ parts.push(start > next ? tail : tail.subarray(next - start));
252
+ truncated = true;
253
+ }
254
+ break;
255
+ }
256
+ cursor = next;
257
+ }
258
+ const whole = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
259
+ let at = 0;
260
+ for (const part of parts) {
261
+ whole.set(part, at);
262
+ at += part.length;
263
+ }
264
+ return { text: decoder.decode(whole), truncated };
265
+ }
266
+ }
267
+ /** Files on a Mac: up to 3 MiB in a call, and any size up to 2 GiB through a link. Relative paths are in the workspace; ~ is home. */
268
+ export class MacFiles {
269
+ #http;
270
+ #base;
271
+ constructor(http, base) {
272
+ this.#http = http;
273
+ this.#base = base;
274
+ }
275
+ /** Writes a file (folders made, the file replaced in one step, so safe to repeat). Larger than 3 MiB goes by an upload link. */
276
+ async write(path, content, { executable } = {}) {
277
+ // A large Blob goes to its link as it is, never read into memory here.
278
+ if (typeof Blob !== "undefined" && content instanceof Blob && content.size > FILE_CALL_BYTES)
279
+ return this.upload(path, content, { executable });
280
+ const bytes = await asBytes(content);
281
+ if (bytes.byteLength > FILE_CALL_BYTES)
282
+ return this.upload(path, bytes, { executable });
283
+ return this.#http.request("POST", `${this.#base}/files`, { body: typeof content === "string" ? { path, content, ...(executable ? { executable } : {}) } : { path, content_base64: toBase64(bytes), ...(executable ? { executable } : {}) } });
284
+ }
285
+ /** A file's bytes, any size up to 2 GiB (larger than 3 MiB comes by a download link). */
286
+ async readBytes(path) {
287
+ const file = await this.#http.request("GET", `${this.#base}/files?path=${encodeURIComponent(path)}&max_bytes=${FILE_CALL_BYTES}`);
288
+ if (!file.truncated)
289
+ return file.encoding === "base64" ? fromBase64(String(file.content_base64 ?? "")) : new TextEncoder().encode(String(file.content ?? ""));
290
+ return this.download(path);
291
+ }
292
+ /** A text file, as UTF-8. */
293
+ async read(path) {
294
+ return decoder.decode(await this.readBytes(path));
295
+ }
296
+ /**
297
+ * A link that puts one file on the Mac at path, for a person (url: a page, no account) or a program (upload_url, then the
298
+ * link's own address to place it): extract unpacks a zip or tar into path. 60 minutes by default, a day at most.
299
+ */
300
+ async uploadLink(path, options = {}) {
301
+ return this.#http.request("POST", `${this.#base}/links`, { body: { direction: "upload", path, ...(options.executable ? { executable: true } : {}), ...(options.extract ? { extract: options.extract } : {}), ...(options.minutes ? { expires_in_minutes: options.minutes } : {}) } });
302
+ }
303
+ /** A link to a file or a folder (as a zip) on the Mac, which keeps working after the Mac stops, until it expires. */
304
+ async downloadLink(path, options = {}) {
305
+ return this.#http.request("POST", `${this.#base}/links`, { body: { direction: "download", path, wait_seconds: options.waitSeconds ?? 30, ...(options.minutes ? { expires_in_minutes: options.minutes } : {}) } });
306
+ }
307
+ /** Puts bytes on the Mac at path through an upload link, and waits until the Mac has them. */
308
+ async upload(path, data, options = {}) {
309
+ const link = await this.uploadLink(path, options);
310
+ if (!link.upload_url)
311
+ throw new NoMacError("upload_unavailable", `The upload link is ${link.state}; ask for a new one.`, 0, link);
312
+ await this.#http.upload(link.upload_url, typeof Blob !== "undefined" && data instanceof Blob ? data : await asBytes(data));
313
+ return this.#follow(link, ["placed"]);
314
+ }
315
+ /** A file's bytes (a folder's as a zip) from the Mac through a download link. */
316
+ async download(path) {
317
+ return this.#http.download(await this.#ready(path));
318
+ }
319
+ /** The same as a stream, for a file too large to hold in memory (up to 2 GiB): pipe it to a file or onward. */
320
+ async downloadStream(path) {
321
+ return this.#http.downloadStream(await this.#ready(path));
322
+ }
323
+ async #ready(path) {
324
+ const link = await this.#follow(await this.downloadLink(path), ["ready"]);
325
+ if (!link.download_url)
326
+ throw new NoMacError("download_unavailable", `The download link is ${link.state}.`, 0, link);
327
+ return String(link.download_url);
328
+ }
329
+ /** Reads a link (its own address, no credential needed) until it reaches one of states, or fails or expires. */
330
+ async #follow(link, states) {
331
+ const token = new URL(link.url).pathname.split("/").pop();
332
+ for (let current = link, rounds = 0; rounds < 200; rounds++) {
333
+ if (states.includes(current.state))
334
+ return current;
335
+ // A failed link says why (file_not_found, mac_stopped, ...) under error.
336
+ const why = current.error;
337
+ if (current.state === "failed" || current.state === "expired")
338
+ throw new NoMacError(why?.code ?? `link_${current.state}`, why?.message ?? String(current.message ?? `The link ${current.state}.`), 0, current);
339
+ // GET reads the link, moving an arrived upload onto the Mac, and waits for that move or a download's copy.
340
+ current = await this.#http.request("GET", `/api/v1/mac/links/${encodeURIComponent(String(token))}?wait=20`, { timeoutMs: 80_000 });
341
+ }
342
+ throw new NoMacError("timeout", "The file did not arrive in time; the link keeps going.", 0, link);
343
+ }
344
+ }