@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.
- package/LICENSE +21 -0
- package/README.md +143 -2
- package/dist/account.d.ts +42 -0
- package/dist/account.js +50 -0
- package/dist/cjs/account.d.ts +42 -0
- package/dist/cjs/account.js +56 -0
- package/dist/cjs/embed.d.ts +47 -0
- package/dist/cjs/embed.js +70 -0
- package/dist/cjs/errors.d.ts +11 -0
- package/dist/cjs/errors.js +22 -0
- package/dist/cjs/http.d.ts +48 -0
- package/dist/cjs/http.js +145 -0
- package/dist/cjs/index.d.ts +42 -0
- package/dist/cjs/index.js +71 -0
- package/dist/cjs/mac.d.ts +176 -0
- package/dist/cjs/mac.js +353 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/phone.d.ts +134 -0
- package/dist/cjs/phone.js +205 -0
- package/dist/cjs/types.d.ts +424 -0
- package/dist/cjs/types.js +3 -0
- package/dist/cjs/webhooks.d.ts +10 -0
- package/dist/cjs/webhooks.js +24 -0
- package/dist/embed.d.ts +47 -0
- package/dist/embed.js +64 -0
- package/dist/errors.d.ts +11 -0
- package/dist/errors.js +17 -0
- package/dist/http.d.ts +48 -0
- package/dist/http.js +136 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.js +54 -0
- package/dist/mac.d.ts +176 -0
- package/dist/mac.js +346 -0
- package/dist/phone.d.ts +134 -0
- package/dist/phone.js +200 -0
- package/dist/types.d.ts +424 -0
- package/dist/types.js +2 -0
- package/dist/webhooks.d.ts +10 -0
- package/dist/webhooks.js +21 -0
- package/package.json +48 -4
package/dist/embed.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { Transport } from "./http.ts";
|
|
2
|
+
import type { EmbedSettings, ViewLinkOptions } from "./types.ts";
|
|
3
|
+
/** A view link's request body: the options given, in NoMac's names. */
|
|
4
|
+
export declare function viewBody({ control, minutes, allowedOrigins, visitor }?: ViewLinkOptions): {
|
|
5
|
+
visitor?: string | undefined;
|
|
6
|
+
allowed_origins?: string[] | undefined;
|
|
7
|
+
minutes?: number | undefined;
|
|
8
|
+
control: boolean;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* How the account's view links may be shown, for a platform that embeds its users' Macs and phones: the sites that may frame
|
|
12
|
+
* them, and whether each opens only for a visitor your server signed. The account's key only.
|
|
13
|
+
*/
|
|
14
|
+
export declare class Embed {
|
|
15
|
+
#private;
|
|
16
|
+
constructor(http: Transport);
|
|
17
|
+
get(): Promise<EmbedSettings>;
|
|
18
|
+
/**
|
|
19
|
+
* Replaces both settings, for every view link made from now on (the links in each phone's answer and those a Mac's or phone's
|
|
20
|
+
* token makes among them): allowedOrigins ([] for any site) and requireVisitor (newSecret first). Links made before keep theirs.
|
|
21
|
+
*/
|
|
22
|
+
set({ allowedOrigins, requireVisitor }: {
|
|
23
|
+
allowedOrigins: string[];
|
|
24
|
+
requireVisitor: boolean;
|
|
25
|
+
}): Promise<EmbedSettings>;
|
|
26
|
+
/**
|
|
27
|
+
* A new embed secret (nme_...), in this answer only: keep it on your server and sign each visitor with it (signVisitor). It
|
|
28
|
+
* replaces the one before at once; views already open keep working.
|
|
29
|
+
*/
|
|
30
|
+
newSecret(): Promise<{
|
|
31
|
+
secret: string;
|
|
32
|
+
created_at: string;
|
|
33
|
+
}>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Signs a visitor for a view link, on your server: an HS256 JWT (sub: the visitor, sid: the Mac's or phone's id, exp) under the
|
|
37
|
+
* account's embed secret. Add it to the link after #visitor= when your page shows it; the link then opens for that visitor, on
|
|
38
|
+
* that Mac or phone. It lasts expiresInSeconds (300 by default, 900 at most): sign a new one for each page load. Never send the
|
|
39
|
+
* secret to a browser.
|
|
40
|
+
*/
|
|
41
|
+
export declare function signVisitor({ secret, sessionId, visitor, expiresInSeconds, now }: {
|
|
42
|
+
secret: string;
|
|
43
|
+
sessionId: string;
|
|
44
|
+
visitor: string;
|
|
45
|
+
expiresInSeconds?: number;
|
|
46
|
+
now?: number;
|
|
47
|
+
}): Promise<string>;
|
package/dist/embed.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { NoMacError } from "./errors.js";
|
|
2
|
+
const EMBED = "/api/v1/embed";
|
|
3
|
+
const encoder = new TextEncoder();
|
|
4
|
+
/** How long a signed visitor may last at most: NoMac refuses a longer one. */
|
|
5
|
+
const VISITOR_MAX_SECONDS = 15 * 60;
|
|
6
|
+
/** A view link's request body: the options given, in NoMac's names. */
|
|
7
|
+
export function viewBody({ control = false, minutes, allowedOrigins, visitor } = {}) {
|
|
8
|
+
return { control, ...(minutes ? { minutes } : {}), ...(allowedOrigins !== undefined ? { allowed_origins: allowedOrigins } : {}), ...(visitor !== undefined ? { visitor } : {}) };
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* How the account's view links may be shown, for a platform that embeds its users' Macs and phones: the sites that may frame
|
|
12
|
+
* them, and whether each opens only for a visitor your server signed. The account's key only.
|
|
13
|
+
*/
|
|
14
|
+
export class Embed {
|
|
15
|
+
#http;
|
|
16
|
+
constructor(http) {
|
|
17
|
+
this.#http = http;
|
|
18
|
+
}
|
|
19
|
+
async get() {
|
|
20
|
+
return this.#http.request("GET", EMBED);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Replaces both settings, for every view link made from now on (the links in each phone's answer and those a Mac's or phone's
|
|
24
|
+
* token makes among them): allowedOrigins ([] for any site) and requireVisitor (newSecret first). Links made before keep theirs.
|
|
25
|
+
*/
|
|
26
|
+
async set({ allowedOrigins, requireVisitor }) {
|
|
27
|
+
return this.#http.request("PUT", EMBED, { body: { allowed_origins: allowedOrigins, require_visitor: requireVisitor } });
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* A new embed secret (nme_...), in this answer only: keep it on your server and sign each visitor with it (signVisitor). It
|
|
31
|
+
* replaces the one before at once; views already open keep working.
|
|
32
|
+
*/
|
|
33
|
+
async newSecret() {
|
|
34
|
+
return this.#http.request("POST", `${EMBED}/secret`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const base64url = (bytes) => {
|
|
38
|
+
let text = "";
|
|
39
|
+
for (const byte of bytes)
|
|
40
|
+
text += String.fromCharCode(byte);
|
|
41
|
+
return btoa(text).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Signs a visitor for a view link, on your server: an HS256 JWT (sub: the visitor, sid: the Mac's or phone's id, exp) under the
|
|
45
|
+
* account's embed secret. Add it to the link after #visitor= when your page shows it; the link then opens for that visitor, on
|
|
46
|
+
* that Mac or phone. It lasts expiresInSeconds (300 by default, 900 at most): sign a new one for each page load. Never send the
|
|
47
|
+
* secret to a browser.
|
|
48
|
+
*/
|
|
49
|
+
export async function signVisitor({ secret, sessionId, visitor, expiresInSeconds = 300, now = Date.now() }) {
|
|
50
|
+
if (typeof secret !== "string" || !secret.startsWith("nme_"))
|
|
51
|
+
throw new NoMacError("invalid_secret", "Sign with the account's embed secret (nme_...), from client.embed.newSecret(), never the API key.");
|
|
52
|
+
if (!/^ses_[A-Za-z0-9_-]{1,80}$/.test(sessionId))
|
|
53
|
+
throw new NoMacError("invalid_request", "sessionId: the Mac's or the phone's id (ses_...).");
|
|
54
|
+
if (!/^[A-Za-z0-9._:@-]{1,128}$/.test(visitor))
|
|
55
|
+
throw new NoMacError("invalid_request", "visitor: your user's id, letters, digits and . _ : @ -, up to 128.");
|
|
56
|
+
if (!Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > VISITOR_MAX_SECONDS)
|
|
57
|
+
throw new NoMacError("invalid_request", `expiresInSeconds: a whole number from 1 to ${VISITOR_MAX_SECONDS}.`);
|
|
58
|
+
const issued = Math.floor(now / 1000);
|
|
59
|
+
const header = base64url(encoder.encode(JSON.stringify({ alg: "HS256", typ: "JWT" })));
|
|
60
|
+
const payload = base64url(encoder.encode(JSON.stringify({ sub: visitor, sid: sessionId, iat: issued, exp: issued + expiresInSeconds })));
|
|
61
|
+
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
62
|
+
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(`${header}.${payload}`)));
|
|
63
|
+
return `${header}.${payload}.${base64url(mac)}`;
|
|
64
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -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("");
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
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 { Embed } from "./embed.ts";
|
|
8
|
+
import { type ClientOptions, type RequestOptions } from "./http.ts";
|
|
9
|
+
import { Mac, Macs } from "./mac.ts";
|
|
10
|
+
import { Phone, Phones } from "./phone.ts";
|
|
11
|
+
import type { Credits } from "./types.ts";
|
|
12
|
+
export declare class NoMac {
|
|
13
|
+
#private;
|
|
14
|
+
/** Macs: start one (for one of your users with a label), read, list. */
|
|
15
|
+
readonly macs: Macs;
|
|
16
|
+
/** Phones (iPhone and iPad Simulators): start one, read, list. */
|
|
17
|
+
readonly phones: Phones;
|
|
18
|
+
/** Your users, by label: what NoMac keeps for each, and deleting it. */
|
|
19
|
+
readonly labels: Labels;
|
|
20
|
+
/** Webhooks for your users' Macs, drives and phones, and the account's credit. */
|
|
21
|
+
readonly webhooks: Webhooks;
|
|
22
|
+
/** Where your users' view links may be shown: the sites that may frame them, and a visitor your server signs. */
|
|
23
|
+
readonly embed: Embed;
|
|
24
|
+
/** 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. */
|
|
25
|
+
constructor(options?: ClientOptions);
|
|
26
|
+
/** A Mac by its id, without reading it: what a Mac's token reaches (new NoMac({ token }).mac(id)). */
|
|
27
|
+
mac(id: string): Mac;
|
|
28
|
+
/** A phone by its id, without reading it: what a phone's token reaches. */
|
|
29
|
+
phone(id: string): Phone;
|
|
30
|
+
/** The account's prepaid credit: what it can spend and the time that buys. */
|
|
31
|
+
credits(): Promise<Credits>;
|
|
32
|
+
/** One call to the REST API directly: JSON in and out, NoMac's error as a NoMacError. */
|
|
33
|
+
request<T = Record<string, any>>(method: string, path: string, options?: RequestOptions): Promise<T>;
|
|
34
|
+
}
|
|
35
|
+
export { NoMacError, requestKey } from "./errors.ts";
|
|
36
|
+
export { verifyWebhook } from "./webhooks.ts";
|
|
37
|
+
export { Embed, signVisitor } from "./embed.ts";
|
|
38
|
+
export { Mac, Macs, MacFiles, MacJobs } from "./mac.ts";
|
|
39
|
+
export { Phone, Phones } from "./phone.ts";
|
|
40
|
+
export { Labels, Webhooks } from "./account.ts";
|
|
41
|
+
export type { ClientOptions, RequestOptions } from "./http.ts";
|
|
42
|
+
export type * from "./types.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
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 { Embed } from "./embed.js";
|
|
8
|
+
import { Http } from "./http.js";
|
|
9
|
+
import { Mac, Macs } from "./mac.js";
|
|
10
|
+
import { Phone, Phones } from "./phone.js";
|
|
11
|
+
export class NoMac {
|
|
12
|
+
#http;
|
|
13
|
+
/** Macs: start one (for one of your users with a label), read, list. */
|
|
14
|
+
macs;
|
|
15
|
+
/** Phones (iPhone and iPad Simulators): start one, read, list. */
|
|
16
|
+
phones;
|
|
17
|
+
/** Your users, by label: what NoMac keeps for each, and deleting it. */
|
|
18
|
+
labels;
|
|
19
|
+
/** Webhooks for your users' Macs, drives and phones, and the account's credit. */
|
|
20
|
+
webhooks;
|
|
21
|
+
/** Where your users' view links may be shown: the sites that may frame them, and a visitor your server signs. */
|
|
22
|
+
embed;
|
|
23
|
+
/** 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. */
|
|
24
|
+
constructor(options = {}) {
|
|
25
|
+
this.#http = new Http(options);
|
|
26
|
+
this.macs = new Macs(this.#http);
|
|
27
|
+
this.phones = new Phones(this.#http);
|
|
28
|
+
this.labels = new Labels(this.#http);
|
|
29
|
+
this.webhooks = new Webhooks(this.#http);
|
|
30
|
+
this.embed = new Embed(this.#http);
|
|
31
|
+
}
|
|
32
|
+
/** A Mac by its id, without reading it: what a Mac's token reaches (new NoMac({ token }).mac(id)). */
|
|
33
|
+
mac(id) {
|
|
34
|
+
return new Mac(this.#http, { id });
|
|
35
|
+
}
|
|
36
|
+
/** A phone by its id, without reading it: what a phone's token reaches. */
|
|
37
|
+
phone(id) {
|
|
38
|
+
return new Phone(this.#http, { id });
|
|
39
|
+
}
|
|
40
|
+
/** The account's prepaid credit: what it can spend and the time that buys. */
|
|
41
|
+
credits() {
|
|
42
|
+
return credits(this.#http);
|
|
43
|
+
}
|
|
44
|
+
/** One call to the REST API directly: JSON in and out, NoMac's error as a NoMacError. */
|
|
45
|
+
request(method, path, options) {
|
|
46
|
+
return this.#http.request(method, path, options);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export { NoMacError, requestKey } from "./errors.js";
|
|
50
|
+
export { verifyWebhook } from "./webhooks.js";
|
|
51
|
+
export { Embed, signVisitor } from "./embed.js";
|
|
52
|
+
export { Mac, Macs, MacFiles, MacJobs } from "./mac.js";
|
|
53
|
+
export { Phone, Phones } from "./phone.js";
|
|
54
|
+
export { Labels, Webhooks } from "./account.js";
|
package/dist/mac.d.ts
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { type Transport } from "./http.ts";
|
|
2
|
+
import type { CommandResult, FileLink, InputAction, Job, MacSession, MacStartOptions, RunOptions, Screenshot, SessionToken, StopNotice, ViewLink, ViewLinkOptions } 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. allowedOrigins keeps it to frames on your sites, and visitor to your
|
|
92
|
+
* user, signed by your server (signVisitor); the account's embed settings apply when they are left out.
|
|
93
|
+
*/
|
|
94
|
+
viewLink(options?: ViewLinkOptions): Promise<ViewLink>;
|
|
95
|
+
/**
|
|
96
|
+
* A token for this Mac only, to hand your user or their agent: new NoMac({ token }).mac(id) reaches its commands, files,
|
|
97
|
+
* screen, input and view links, never another Mac, a start, a stop or the account. 2 hours by default, a day at most.
|
|
98
|
+
*/
|
|
99
|
+
token({ minutes }?: {
|
|
100
|
+
minutes?: number;
|
|
101
|
+
}): Promise<SessionToken>;
|
|
102
|
+
/** Revokes every token and link of this Mac made so far; the Mac runs on, and new ones work. The account's key only. */
|
|
103
|
+
revokeTokens(): Promise<{
|
|
104
|
+
revoked_at: string;
|
|
105
|
+
}>;
|
|
106
|
+
/**
|
|
107
|
+
* Keeps the Mac running longer: its time limit goes up by minutes (60 by default; a Mac has no longest time), and its
|
|
108
|
+
* spend cap by what that time costs. The account's key only. Not sent again by itself: a repeat adds more time.
|
|
109
|
+
*/
|
|
110
|
+
extend({ minutes }?: {
|
|
111
|
+
minutes?: number;
|
|
112
|
+
}): Promise<this>;
|
|
113
|
+
/**
|
|
114
|
+
* Stops the Mac: it and every file outside ~/drive are deleted, and ~/drive is saved for the next Mac. The account's key
|
|
115
|
+
* only. confirm: stop it even while another API key is using it (the account's own Macs ask; a user's Mac never does).
|
|
116
|
+
*/
|
|
117
|
+
stop({ confirm }?: {
|
|
118
|
+
confirm?: boolean;
|
|
119
|
+
}): Promise<this>;
|
|
120
|
+
}
|
|
121
|
+
/** Commands on a Mac: start one, read it, wait for its end, cancel it. mac.run() is start and wait in one. */
|
|
122
|
+
export declare class MacJobs {
|
|
123
|
+
#private;
|
|
124
|
+
constructor(http: Transport, base: string, notice: (notice: StopNotice | undefined) => void);
|
|
125
|
+
/** Starts a command (a string runs in bash -lc) and answers its job, maybe already ended. The same idempotencyKey never runs it twice. */
|
|
126
|
+
start(command: string | string[], { cwd, env, timeoutSeconds, idempotencyKey }?: RunOptions): Promise<Job>;
|
|
127
|
+
/** A job as it is now; with waitSeconds (up to 50), waits that long for it to end first. */
|
|
128
|
+
get(id: string, { waitSeconds }?: {
|
|
129
|
+
waitSeconds?: number;
|
|
130
|
+
}): Promise<Job>;
|
|
131
|
+
/**
|
|
132
|
+
* 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
|
|
133
|
+
* output: wait for its job.
|
|
134
|
+
*/
|
|
135
|
+
wait(job: string | Job, { timeoutMs }?: {
|
|
136
|
+
timeoutMs?: number;
|
|
137
|
+
}): Promise<CommandResult>;
|
|
138
|
+
/** Stops a running command and what it started; a finished one is answered as it is. */
|
|
139
|
+
cancel(id: string): Promise<Job>;
|
|
140
|
+
}
|
|
141
|
+
/** 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. */
|
|
142
|
+
export declare class MacFiles {
|
|
143
|
+
#private;
|
|
144
|
+
constructor(http: Transport, base: string);
|
|
145
|
+
/** Writes a file (folders made, the file replaced in one step, so safe to repeat). Larger than 3 MiB goes by an upload link. */
|
|
146
|
+
write(path: string, content: string | Uint8Array | ArrayBuffer | Blob, { executable }?: {
|
|
147
|
+
executable?: boolean;
|
|
148
|
+
}): Promise<Record<string, any>>;
|
|
149
|
+
/** A file's bytes, any size up to 2 GiB (larger than 3 MiB comes by a download link). */
|
|
150
|
+
readBytes(path: string): Promise<Uint8Array>;
|
|
151
|
+
/** A text file, as UTF-8. */
|
|
152
|
+
read(path: string): Promise<string>;
|
|
153
|
+
/**
|
|
154
|
+
* 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
|
|
155
|
+
* link's own address to place it): extract unpacks a zip or tar into path. 60 minutes by default, a day at most.
|
|
156
|
+
*/
|
|
157
|
+
uploadLink(path: string, options?: {
|
|
158
|
+
executable?: boolean;
|
|
159
|
+
extract?: "zip" | "tar";
|
|
160
|
+
minutes?: number;
|
|
161
|
+
}): Promise<FileLink>;
|
|
162
|
+
/** A link to a file or a folder (as a zip) on the Mac, which keeps working after the Mac stops, until it expires. */
|
|
163
|
+
downloadLink(path: string, options?: {
|
|
164
|
+
minutes?: number;
|
|
165
|
+
waitSeconds?: number;
|
|
166
|
+
}): Promise<FileLink>;
|
|
167
|
+
/** Puts bytes on the Mac at path through an upload link, and waits until the Mac has them. */
|
|
168
|
+
upload(path: string, data: string | Uint8Array | ArrayBuffer | Blob, options?: {
|
|
169
|
+
executable?: boolean;
|
|
170
|
+
extract?: "zip" | "tar";
|
|
171
|
+
}): Promise<Record<string, any>>;
|
|
172
|
+
/** A file's bytes (a folder's as a zip) from the Mac through a download link. */
|
|
173
|
+
download(path: string): Promise<Uint8Array>;
|
|
174
|
+
/** 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. */
|
|
175
|
+
downloadStream(path: string): Promise<ReadableStream<Uint8Array>>;
|
|
176
|
+
}
|