@computesdk/brezel 0.1.1
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 +47 -0
- package/dist/index.d.mts +23 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +776 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +750 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +66 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,776 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __typeError = (msg) => {
|
|
7
|
+
throw TypeError(msg);
|
|
8
|
+
};
|
|
9
|
+
var __export = (target, all) => {
|
|
10
|
+
for (var name in all)
|
|
11
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
12
|
+
};
|
|
13
|
+
var __copyProps = (to, from, except, desc) => {
|
|
14
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
15
|
+
for (let key of __getOwnPropNames(from))
|
|
16
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
17
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
18
|
+
}
|
|
19
|
+
return to;
|
|
20
|
+
};
|
|
21
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
22
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
23
|
+
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
24
|
+
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
25
|
+
|
|
26
|
+
// src/index.ts
|
|
27
|
+
var index_exports = {};
|
|
28
|
+
__export(index_exports, {
|
|
29
|
+
brezel: () => brezel
|
|
30
|
+
});
|
|
31
|
+
module.exports = __toCommonJS(index_exports);
|
|
32
|
+
|
|
33
|
+
// ../../node_modules/.pnpm/@infercrane+brezel@0.1.1/node_modules/@infercrane/brezel/src/index.js
|
|
34
|
+
var import_node_crypto = require("crypto");
|
|
35
|
+
var import_node_fs = require("fs");
|
|
36
|
+
var MAX_JSON_BYTES = 4 << 20;
|
|
37
|
+
var MAX_EVENT_BYTES = 2 << 20;
|
|
38
|
+
var MAX_OUTPUT_BYTES = 64 << 20;
|
|
39
|
+
var BrezelError = class extends Error {
|
|
40
|
+
constructor(message, { code = "", status: status2 = 0, cause } = {}) {
|
|
41
|
+
super(message, cause === void 0 ? void 0 : { cause });
|
|
42
|
+
this.name = "BrezelError";
|
|
43
|
+
this.code = code;
|
|
44
|
+
this.status = status2;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
var CommandExitError = class extends BrezelError {
|
|
48
|
+
constructor(result) {
|
|
49
|
+
super(`command exited with status ${result.exitCode}`, { code: "command_exit" });
|
|
50
|
+
this.name = "CommandExitError";
|
|
51
|
+
this.result = result;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
var _BrezelClient_instances, ensureEnvironment_fn;
|
|
55
|
+
var _BrezelClient = class _BrezelClient {
|
|
56
|
+
constructor({
|
|
57
|
+
token,
|
|
58
|
+
baseUrl = "http://127.0.0.1:8080",
|
|
59
|
+
project = "brezel-default",
|
|
60
|
+
timeoutMs = 45e3,
|
|
61
|
+
fetch: fetchImplementation = globalThis.fetch
|
|
62
|
+
}) {
|
|
63
|
+
__privateAdd(this, _BrezelClient_instances);
|
|
64
|
+
if (typeof fetchImplementation !== "function") {
|
|
65
|
+
throw new TypeError("a fetch implementation is required");
|
|
66
|
+
}
|
|
67
|
+
this.baseUrl = validateBaseUrl(baseUrl);
|
|
68
|
+
this.token = validateToken(token);
|
|
69
|
+
this.project = validateProject(project);
|
|
70
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
71
|
+
throw new TypeError("timeoutMs must be positive");
|
|
72
|
+
}
|
|
73
|
+
this.timeoutMs = timeoutMs;
|
|
74
|
+
this.fetch = fetchImplementation;
|
|
75
|
+
}
|
|
76
|
+
static fromTokenFile(tokenFile, options = {}) {
|
|
77
|
+
return new _BrezelClient({ ...options, token: readPrivateToken(tokenFile) });
|
|
78
|
+
}
|
|
79
|
+
async createSandbox({
|
|
80
|
+
template,
|
|
81
|
+
environmentRevision: environmentRevision2,
|
|
82
|
+
ttlSeconds = 3600,
|
|
83
|
+
standbyAfterSeconds = 0,
|
|
84
|
+
allowInternet: allowInternet2 = false,
|
|
85
|
+
workspaceMounts = []
|
|
86
|
+
} = {}) {
|
|
87
|
+
if (template !== void 0 && environmentRevision2 !== void 0) {
|
|
88
|
+
throw new TypeError("template and environmentRevision are mutually exclusive");
|
|
89
|
+
}
|
|
90
|
+
const revision = environmentRevision2 === void 0 ? await __privateMethod(this, _BrezelClient_instances, ensureEnvironment_fn).call(this, template ?? "base") : validateEnvironmentRevision(environmentRevision2);
|
|
91
|
+
const lifecycle = { expires_after_seconds: ttlSeconds };
|
|
92
|
+
if (standbyAfterSeconds > 0) {
|
|
93
|
+
Object.assign(lifecycle, {
|
|
94
|
+
standby_after_seconds: standbyAfterSeconds,
|
|
95
|
+
standby_checkpoint_kind: "full_state",
|
|
96
|
+
auto_resume: true
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
const body = {
|
|
100
|
+
environment_revision: revision,
|
|
101
|
+
lifecycle,
|
|
102
|
+
network: { allow_internet: allowInternet2 }
|
|
103
|
+
};
|
|
104
|
+
if (workspaceMounts.length > 0) {
|
|
105
|
+
body.workspace_mounts = workspaceMounts;
|
|
106
|
+
}
|
|
107
|
+
const payload = await this.requestJSON("POST", "/v1/sandboxes", {
|
|
108
|
+
body,
|
|
109
|
+
idempotencyKey: randomKey("sandbox")
|
|
110
|
+
});
|
|
111
|
+
const resource = requiredObject(payload, "resource");
|
|
112
|
+
return new Sandbox(this, requiredString(resource, "id"), resource);
|
|
113
|
+
}
|
|
114
|
+
async sandbox(id) {
|
|
115
|
+
const resource = await this.requestJSON("GET", `/v1/sandboxes/${segment(id)}`);
|
|
116
|
+
if (!isObject(resource)) {
|
|
117
|
+
throw new BrezelError("Brezel returned an invalid sandbox response", { code: "invalid_response" });
|
|
118
|
+
}
|
|
119
|
+
return new Sandbox(this, id, resource);
|
|
120
|
+
}
|
|
121
|
+
async listSandboxes({ includeTerminal = false } = {}) {
|
|
122
|
+
const suffix = includeTerminal ? "?include_terminal=true" : "";
|
|
123
|
+
const payload = await this.requestJSON("GET", `/v1/sandboxes${suffix}`);
|
|
124
|
+
if (!isObject(payload) || !Array.isArray(payload.sandboxes) || !payload.sandboxes.every(isObject)) {
|
|
125
|
+
throw new BrezelError("Brezel returned an invalid sandbox list", { code: "invalid_response" });
|
|
126
|
+
}
|
|
127
|
+
return payload.sandboxes;
|
|
128
|
+
}
|
|
129
|
+
async requestJSON(method, path, { body, idempotencyKey = "", timeoutMs = this.timeoutMs } = {}) {
|
|
130
|
+
const encoded = body === void 0 ? void 0 : JSON.stringify(body);
|
|
131
|
+
const response = await this.request(method, path, {
|
|
132
|
+
body: encoded,
|
|
133
|
+
contentType: encoded === void 0 ? "" : "application/json",
|
|
134
|
+
idempotencyKey,
|
|
135
|
+
timeoutMs
|
|
136
|
+
});
|
|
137
|
+
return decodeJSONResponse(response, MAX_JSON_BYTES, "Brezel JSON response");
|
|
138
|
+
}
|
|
139
|
+
async request(method, path, { body, contentType = "", idempotencyKey = "", timeoutMs = this.timeoutMs } = {}) {
|
|
140
|
+
const url = new URL(path.replace(/^\/+/, ""), `${this.baseUrl}/`);
|
|
141
|
+
const headers = {
|
|
142
|
+
Authorization: `Bearer ${this.token}`,
|
|
143
|
+
"X-Project-ID": this.project,
|
|
144
|
+
Accept: "application/json"
|
|
145
|
+
};
|
|
146
|
+
if (contentType) headers["Content-Type"] = contentType;
|
|
147
|
+
if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
|
|
148
|
+
let response;
|
|
149
|
+
try {
|
|
150
|
+
response = await this.fetch(url, {
|
|
151
|
+
method,
|
|
152
|
+
headers,
|
|
153
|
+
body,
|
|
154
|
+
redirect: "manual",
|
|
155
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
156
|
+
});
|
|
157
|
+
} catch (error) {
|
|
158
|
+
throw new BrezelError(`Brezel request failed: ${error.message}`, { code: "transport_error", cause: error });
|
|
159
|
+
}
|
|
160
|
+
if (!response.ok) {
|
|
161
|
+
let code = "http_error";
|
|
162
|
+
let message = `Brezel API returned HTTP ${response.status}`;
|
|
163
|
+
try {
|
|
164
|
+
const payload = await decodeJSONResponse(response, 1 << 20, "Brezel error response");
|
|
165
|
+
if (isObject(payload?.error)) {
|
|
166
|
+
code = typeof payload.error.code === "string" ? payload.error.code : code;
|
|
167
|
+
message = typeof payload.error.message === "string" ? payload.error.message : message;
|
|
168
|
+
}
|
|
169
|
+
} catch {
|
|
170
|
+
}
|
|
171
|
+
throw new BrezelError(message, { code, status: response.status });
|
|
172
|
+
}
|
|
173
|
+
return response;
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
_BrezelClient_instances = new WeakSet();
|
|
177
|
+
ensureEnvironment_fn = async function(template) {
|
|
178
|
+
template = template.trim();
|
|
179
|
+
if (!template) throw new TypeError("template cannot be empty");
|
|
180
|
+
const name = safeName(template) ? template : `brezel-${(0, import_node_crypto.createHash)("sha256").update(template).digest("hex").slice(0, 16)}`;
|
|
181
|
+
const payload = await this.requestJSON("POST", "/v1/environments", {
|
|
182
|
+
body: { name, template },
|
|
183
|
+
idempotencyKey: stableKey("environment", template)
|
|
184
|
+
});
|
|
185
|
+
return requiredString(requiredObject(payload, "resource"), "revision_id");
|
|
186
|
+
};
|
|
187
|
+
var BrezelClient = _BrezelClient;
|
|
188
|
+
var _Sandbox_instances, lifecycle_fn;
|
|
189
|
+
var Sandbox = class {
|
|
190
|
+
constructor(client, id, resource = {}) {
|
|
191
|
+
__privateAdd(this, _Sandbox_instances);
|
|
192
|
+
this.client = client;
|
|
193
|
+
this.id = id;
|
|
194
|
+
this.resource = { ...resource };
|
|
195
|
+
this.deleted = false;
|
|
196
|
+
}
|
|
197
|
+
async run(argv, { cwd = "", env = {}, timeoutSeconds = 300, check = false, onEvent } = {}) {
|
|
198
|
+
if (!Array.isArray(argv) || argv.length === 0 || !argv.every((item) => typeof item === "string")) {
|
|
199
|
+
throw new TypeError("argv must be a non-empty string array");
|
|
200
|
+
}
|
|
201
|
+
const response = await this.client.request(
|
|
202
|
+
"POST",
|
|
203
|
+
`/v1/sandboxes/${segment(this.id)}/commands`,
|
|
204
|
+
{
|
|
205
|
+
body: JSON.stringify({ argv, cwd, env, timeout_seconds: timeoutSeconds }),
|
|
206
|
+
contentType: "application/json",
|
|
207
|
+
timeoutMs: Math.max(this.client.timeoutMs, (timeoutSeconds + 5) * 1e3)
|
|
208
|
+
}
|
|
209
|
+
);
|
|
210
|
+
if (!response.body) {
|
|
211
|
+
throw new BrezelError("command response did not contain a stream", { code: "invalid_response" });
|
|
212
|
+
}
|
|
213
|
+
if ((response.headers.get("content-type") || "").split(";", 1)[0].trim().toLowerCase() !== "application/x-ndjson") {
|
|
214
|
+
await response.body.cancel();
|
|
215
|
+
throw new BrezelError("command response used an unexpected media type", { code: "invalid_response" });
|
|
216
|
+
}
|
|
217
|
+
const stdout = [];
|
|
218
|
+
const stderr = [];
|
|
219
|
+
let outputBytes = 0;
|
|
220
|
+
let executionId = "";
|
|
221
|
+
let exitCode;
|
|
222
|
+
for await (const event of ndjsonEvents(response.body)) {
|
|
223
|
+
if (onEvent) onEvent(event);
|
|
224
|
+
if (typeof event.execution_id === "string") executionId = event.execution_id;
|
|
225
|
+
if (event.type === "stdout" || event.type === "stderr") {
|
|
226
|
+
if (typeof event.data !== "string" || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(event.data)) {
|
|
227
|
+
throw new BrezelError("command stream contained invalid output encoding", { code: "invalid_response" });
|
|
228
|
+
}
|
|
229
|
+
const chunk = Buffer.from(event.data, "base64");
|
|
230
|
+
outputBytes += chunk.byteLength;
|
|
231
|
+
if (outputBytes > MAX_OUTPUT_BYTES) {
|
|
232
|
+
throw new BrezelError("command output exceeded the SDK limit", { code: "response_too_large" });
|
|
233
|
+
}
|
|
234
|
+
(event.type === "stdout" ? stdout : stderr).push(chunk);
|
|
235
|
+
} else if (event.type === "exited") {
|
|
236
|
+
if (exitCode !== void 0 || !Number.isSafeInteger(event.exit_code)) {
|
|
237
|
+
throw new BrezelError("command stream contained an invalid terminal event", { code: "invalid_response" });
|
|
238
|
+
}
|
|
239
|
+
exitCode = event.exit_code;
|
|
240
|
+
} else if (event.type === "error") {
|
|
241
|
+
throw new BrezelError("command outcome is indeterminate", { code: "command_indeterminate" });
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if (exitCode === void 0) {
|
|
245
|
+
throw new BrezelError("command stream ended without a confirmed exit", { code: "command_indeterminate" });
|
|
246
|
+
}
|
|
247
|
+
const stdoutBuffer = Buffer.concat(stdout);
|
|
248
|
+
const stderrBuffer = Buffer.concat(stderr);
|
|
249
|
+
const result = {
|
|
250
|
+
executionId,
|
|
251
|
+
exitCode,
|
|
252
|
+
stdout: stdoutBuffer,
|
|
253
|
+
stderr: stderrBuffer,
|
|
254
|
+
stdoutText: stdoutBuffer.toString("utf8"),
|
|
255
|
+
stderrText: stderrBuffer.toString("utf8")
|
|
256
|
+
};
|
|
257
|
+
if (check && exitCode !== 0) throw new CommandExitError(result);
|
|
258
|
+
return result;
|
|
259
|
+
}
|
|
260
|
+
async writeFile(path, data) {
|
|
261
|
+
const body = typeof data === "string" ? new TextEncoder().encode(data) : data;
|
|
262
|
+
if (!(body instanceof Uint8Array)) throw new TypeError("data must be a string or Uint8Array");
|
|
263
|
+
const response = await this.client.request(
|
|
264
|
+
"PUT",
|
|
265
|
+
`/v1/sandboxes/${segment(this.id)}/files?path=${encodeURIComponent(path)}`,
|
|
266
|
+
{ body, contentType: "application/octet-stream" }
|
|
267
|
+
);
|
|
268
|
+
return decodeJSONResponse(response, MAX_JSON_BYTES, "file metadata");
|
|
269
|
+
}
|
|
270
|
+
async readFile(path) {
|
|
271
|
+
const response = await this.client.request(
|
|
272
|
+
"GET",
|
|
273
|
+
`/v1/sandboxes/${segment(this.id)}/files?path=${encodeURIComponent(path)}`
|
|
274
|
+
);
|
|
275
|
+
return readLimited(response.body, 64 << 20, "file");
|
|
276
|
+
}
|
|
277
|
+
async preview(port, { ttlSeconds = 300 } = {}) {
|
|
278
|
+
if (!Number.isSafeInteger(port) || port < 1 || port > 65535) {
|
|
279
|
+
throw new TypeError("port must be between 1 and 65535");
|
|
280
|
+
}
|
|
281
|
+
const payload = await this.client.requestJSON(
|
|
282
|
+
"POST",
|
|
283
|
+
`/v1/sandboxes/${segment(this.id)}/ports/${port}/leases`,
|
|
284
|
+
{ body: { ttl_seconds: ttlSeconds } }
|
|
285
|
+
);
|
|
286
|
+
return new URL(requiredString(payload, "path").replace(/^\/+/, ""), `${this.client.baseUrl}/`).toString();
|
|
287
|
+
}
|
|
288
|
+
pause() {
|
|
289
|
+
return __privateMethod(this, _Sandbox_instances, lifecycle_fn).call(this, "pause");
|
|
290
|
+
}
|
|
291
|
+
resume() {
|
|
292
|
+
return __privateMethod(this, _Sandbox_instances, lifecycle_fn).call(this, "resume");
|
|
293
|
+
}
|
|
294
|
+
async delete() {
|
|
295
|
+
if (this.deleted) return this.resource;
|
|
296
|
+
const payload = await this.client.requestJSON("DELETE", `/v1/sandboxes/${segment(this.id)}`, {
|
|
297
|
+
idempotencyKey: randomKey("delete")
|
|
298
|
+
});
|
|
299
|
+
this.resource = { ...requiredObject(payload, "resource") };
|
|
300
|
+
this.deleted = true;
|
|
301
|
+
return this.resource;
|
|
302
|
+
}
|
|
303
|
+
async [Symbol.asyncDispose]() {
|
|
304
|
+
await this.delete();
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
_Sandbox_instances = new WeakSet();
|
|
308
|
+
lifecycle_fn = async function(action) {
|
|
309
|
+
const payload = await this.client.requestJSON(
|
|
310
|
+
"POST",
|
|
311
|
+
`/v1/sandboxes/${segment(this.id)}:${action}`,
|
|
312
|
+
{ idempotencyKey: randomKey(action) }
|
|
313
|
+
);
|
|
314
|
+
this.resource = { ...requiredObject(payload, "resource") };
|
|
315
|
+
return this.resource;
|
|
316
|
+
};
|
|
317
|
+
async function* ndjsonEvents(stream) {
|
|
318
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
319
|
+
let buffer = "";
|
|
320
|
+
for await (const chunk of stream) {
|
|
321
|
+
try {
|
|
322
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
323
|
+
} catch (error) {
|
|
324
|
+
throw new BrezelError("command stream contained invalid UTF-8", { code: "invalid_response", cause: error });
|
|
325
|
+
}
|
|
326
|
+
if (Buffer.byteLength(buffer) > MAX_EVENT_BYTES && !buffer.includes("\n")) {
|
|
327
|
+
throw new BrezelError("command event exceeded the SDK limit", { code: "response_too_large" });
|
|
328
|
+
}
|
|
329
|
+
while (true) {
|
|
330
|
+
const newline = buffer.indexOf("\n");
|
|
331
|
+
if (newline < 0) break;
|
|
332
|
+
const line = buffer.slice(0, newline);
|
|
333
|
+
buffer = buffer.slice(newline + 1);
|
|
334
|
+
if (!line) continue;
|
|
335
|
+
if (Buffer.byteLength(line) > MAX_EVENT_BYTES) {
|
|
336
|
+
throw new BrezelError("command event exceeded the SDK limit", { code: "response_too_large" });
|
|
337
|
+
}
|
|
338
|
+
try {
|
|
339
|
+
const event = JSON.parse(line);
|
|
340
|
+
if (!isObject(event)) throw new Error("event must be an object");
|
|
341
|
+
yield event;
|
|
342
|
+
} catch (error) {
|
|
343
|
+
throw new BrezelError("command stream contained invalid JSON", { code: "invalid_response", cause: error });
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
try {
|
|
348
|
+
buffer += decoder.decode();
|
|
349
|
+
} catch (error) {
|
|
350
|
+
throw new BrezelError("command stream contained invalid UTF-8", { code: "invalid_response", cause: error });
|
|
351
|
+
}
|
|
352
|
+
if (buffer.trim()) {
|
|
353
|
+
if (Buffer.byteLength(buffer) > MAX_EVENT_BYTES) {
|
|
354
|
+
throw new BrezelError("command event exceeded the SDK limit", { code: "response_too_large" });
|
|
355
|
+
}
|
|
356
|
+
try {
|
|
357
|
+
const event = JSON.parse(buffer);
|
|
358
|
+
if (!isObject(event)) throw new Error("event must be an object");
|
|
359
|
+
yield event;
|
|
360
|
+
} catch (error) {
|
|
361
|
+
throw new BrezelError("command stream contained invalid JSON", { code: "invalid_response", cause: error });
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
function validateBaseUrl(value) {
|
|
366
|
+
let url;
|
|
367
|
+
try {
|
|
368
|
+
url = new URL(value.replace(/\/+$/, ""));
|
|
369
|
+
} catch {
|
|
370
|
+
throw new TypeError("baseUrl must be an absolute HTTP(S) URL");
|
|
371
|
+
}
|
|
372
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
373
|
+
throw new TypeError("baseUrl must be an absolute HTTP(S) URL without credentials, query, or fragment");
|
|
374
|
+
}
|
|
375
|
+
if (url.protocol === "http:" && !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)) {
|
|
376
|
+
throw new TypeError("remote Brezel URLs must use HTTPS");
|
|
377
|
+
}
|
|
378
|
+
return url.toString().replace(/\/$/, "");
|
|
379
|
+
}
|
|
380
|
+
function validateToken(value) {
|
|
381
|
+
if (typeof value !== "string") throw new TypeError("token is required");
|
|
382
|
+
const token = value.trim();
|
|
383
|
+
if (token.length < 32 || /[\r\n]/.test(token)) {
|
|
384
|
+
throw new TypeError("token must contain one line of at least 32 characters");
|
|
385
|
+
}
|
|
386
|
+
return token;
|
|
387
|
+
}
|
|
388
|
+
function validateProject(value) {
|
|
389
|
+
if (typeof value !== "string" || !value || /[\r\n]/.test(value)) {
|
|
390
|
+
throw new TypeError("project is required");
|
|
391
|
+
}
|
|
392
|
+
return value;
|
|
393
|
+
}
|
|
394
|
+
function validateEnvironmentRevision(value) {
|
|
395
|
+
if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value)) {
|
|
396
|
+
throw new TypeError("environmentRevision must be one non-empty resource ID");
|
|
397
|
+
}
|
|
398
|
+
return value;
|
|
399
|
+
}
|
|
400
|
+
function readPrivateToken(path) {
|
|
401
|
+
const before = (0, import_node_fs.lstatSync)(path);
|
|
402
|
+
validatePrivateFile(before);
|
|
403
|
+
const noFollow = process.platform === "win32" ? 0 : import_node_fs.constants.O_NOFOLLOW;
|
|
404
|
+
const fd = (0, import_node_fs.openSync)(path, import_node_fs.constants.O_RDONLY | noFollow);
|
|
405
|
+
try {
|
|
406
|
+
const opened = (0, import_node_fs.fstatSync)(fd);
|
|
407
|
+
validatePrivateFile(opened);
|
|
408
|
+
if (before.dev !== opened.dev || before.ino !== opened.ino) {
|
|
409
|
+
throw new TypeError("tokenFile changed while opening");
|
|
410
|
+
}
|
|
411
|
+
const data = Buffer.alloc(4097);
|
|
412
|
+
const bytesRead = (0, import_node_fs.readSync)(fd, data, 0, data.length, 0);
|
|
413
|
+
if (bytesRead > 4096) throw new TypeError("tokenFile exceeds 4096 bytes");
|
|
414
|
+
const value = new TextDecoder("utf-8", { fatal: true }).decode(data.subarray(0, bytesRead));
|
|
415
|
+
const after = (0, import_node_fs.lstatSync)(path);
|
|
416
|
+
validatePrivateFile(after);
|
|
417
|
+
if (opened.dev !== after.dev || opened.ino !== after.ino) {
|
|
418
|
+
throw new TypeError("tokenFile changed while reading");
|
|
419
|
+
}
|
|
420
|
+
return validateToken(value);
|
|
421
|
+
} finally {
|
|
422
|
+
(0, import_node_fs.closeSync)(fd);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
function validatePrivateFile(info) {
|
|
426
|
+
if (!info.isFile() || info.isSymbolicLink()) {
|
|
427
|
+
throw new TypeError("tokenFile must be a regular file, not a symlink");
|
|
428
|
+
}
|
|
429
|
+
if (![256, 384].includes(info.mode & 511) || info.nlink !== 1) {
|
|
430
|
+
throw new TypeError("tokenFile permissions must be 0400 or 0600 with one hard link");
|
|
431
|
+
}
|
|
432
|
+
if (typeof process.geteuid === "function" && info.uid !== process.geteuid()) {
|
|
433
|
+
throw new TypeError("tokenFile must be owned by the effective user");
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
async function decodeJSONResponse(response, maximum, description) {
|
|
437
|
+
const bytes = await readLimited(response.body, maximum, description);
|
|
438
|
+
try {
|
|
439
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
440
|
+
} catch (error) {
|
|
441
|
+
throw new BrezelError(`${description} contained invalid JSON`, { code: "invalid_response", cause: error });
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
async function readLimited(stream, maximum, description) {
|
|
445
|
+
if (!stream) {
|
|
446
|
+
throw new BrezelError(`${description} response did not contain a body`, { code: "invalid_response" });
|
|
447
|
+
}
|
|
448
|
+
const chunks = [];
|
|
449
|
+
let total = 0;
|
|
450
|
+
for await (const chunk of stream) {
|
|
451
|
+
const bytes = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
|
|
452
|
+
total += bytes.byteLength;
|
|
453
|
+
if (total > maximum) {
|
|
454
|
+
await stream.cancel().catch(() => {
|
|
455
|
+
});
|
|
456
|
+
throw new BrezelError(`${description} exceeded the SDK limit`, { code: "response_too_large" });
|
|
457
|
+
}
|
|
458
|
+
chunks.push(bytes);
|
|
459
|
+
}
|
|
460
|
+
const result = new Uint8Array(total);
|
|
461
|
+
let offset = 0;
|
|
462
|
+
for (const chunk of chunks) {
|
|
463
|
+
result.set(chunk, offset);
|
|
464
|
+
offset += chunk.byteLength;
|
|
465
|
+
}
|
|
466
|
+
return result;
|
|
467
|
+
}
|
|
468
|
+
function requiredObject(value, key) {
|
|
469
|
+
const result = isObject(value) ? value[key] : void 0;
|
|
470
|
+
if (!isObject(result)) {
|
|
471
|
+
throw new BrezelError(`Brezel response is missing ${key}`, { code: "invalid_response" });
|
|
472
|
+
}
|
|
473
|
+
return result;
|
|
474
|
+
}
|
|
475
|
+
function requiredString(value, key) {
|
|
476
|
+
const result = isObject(value) ? value[key] : void 0;
|
|
477
|
+
if (typeof result !== "string" || !result) {
|
|
478
|
+
throw new BrezelError(`Brezel response is missing ${key}`, { code: "invalid_response" });
|
|
479
|
+
}
|
|
480
|
+
return result;
|
|
481
|
+
}
|
|
482
|
+
function isObject(value) {
|
|
483
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
484
|
+
}
|
|
485
|
+
function segment(value) {
|
|
486
|
+
if (typeof value !== "string" || !value || /[\/\r\n]/.test(value)) {
|
|
487
|
+
throw new TypeError("resource ID must be one non-empty path segment");
|
|
488
|
+
}
|
|
489
|
+
return encodeURIComponent(value);
|
|
490
|
+
}
|
|
491
|
+
function safeName(value) {
|
|
492
|
+
return /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value);
|
|
493
|
+
}
|
|
494
|
+
function randomKey(prefix) {
|
|
495
|
+
return `${prefix}-${(0, import_node_crypto.randomBytes)(12).toString("hex")}`;
|
|
496
|
+
}
|
|
497
|
+
function stableKey(prefix, value) {
|
|
498
|
+
return `${prefix}-${(0, import_node_crypto.createHash)("sha256").update(value).digest("hex").slice(0, 24)}`;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// src/index.ts
|
|
502
|
+
var import_provider = require("@computesdk/provider");
|
|
503
|
+
var DEFAULT_TIMEOUT_MS = 3e5;
|
|
504
|
+
var DELETE_TIMEOUT_MS = 12e4;
|
|
505
|
+
var POLL_INTERVAL_MS = 100;
|
|
506
|
+
var MIN_SANDBOX_TTL_MS = 3e4;
|
|
507
|
+
var MAX_SANDBOX_TTL_MS = 2592e6;
|
|
508
|
+
var sandboxTimeouts = /* @__PURE__ */ new WeakMap();
|
|
509
|
+
var sandboxClients = /* @__PURE__ */ new WeakMap();
|
|
510
|
+
function required(value, variable) {
|
|
511
|
+
if (!value) throw new Error(`Missing ${variable}. Provide it in config or set ${variable}.`);
|
|
512
|
+
return value;
|
|
513
|
+
}
|
|
514
|
+
function getClient(config) {
|
|
515
|
+
if (!config.__client) {
|
|
516
|
+
config.__client = new BrezelClient({
|
|
517
|
+
token: required(config.apiKey ?? process.env.BREZEL_API_KEY, "BREZEL_API_KEY"),
|
|
518
|
+
baseUrl: required(config.baseUrl ?? process.env.BREZEL_API_URL, "BREZEL_API_URL"),
|
|
519
|
+
project: required(config.project ?? process.env.BREZEL_PROJECT_ID, "BREZEL_PROJECT_ID"),
|
|
520
|
+
timeoutMs: config.apiTimeoutMs
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
return config.__client;
|
|
524
|
+
}
|
|
525
|
+
function environmentRevision(config, options) {
|
|
526
|
+
return required(
|
|
527
|
+
options?.templateId ?? config.environmentRevision ?? process.env.BREZEL_ENVIRONMENT_REVISION,
|
|
528
|
+
"BREZEL_ENVIRONMENT_REVISION"
|
|
529
|
+
);
|
|
530
|
+
}
|
|
531
|
+
function allowInternet(config) {
|
|
532
|
+
if (config.allowInternet !== void 0) return config.allowInternet;
|
|
533
|
+
const raw = process.env.BREZEL_ALLOW_INTERNET;
|
|
534
|
+
if (raw === void 0) return false;
|
|
535
|
+
if (raw === "true") return true;
|
|
536
|
+
if (raw === "false") return false;
|
|
537
|
+
throw new Error("BREZEL_ALLOW_INTERNET must be exactly true or false");
|
|
538
|
+
}
|
|
539
|
+
function terminal(status2) {
|
|
540
|
+
return status2 === "deleted" || status2 === "expired";
|
|
541
|
+
}
|
|
542
|
+
function status(state) {
|
|
543
|
+
if (state === "failed") return "error";
|
|
544
|
+
if (state === "paused" || state === "standby" || state === "stopped" || terminal(state)) return "stopped";
|
|
545
|
+
return "running";
|
|
546
|
+
}
|
|
547
|
+
function isMissing(error) {
|
|
548
|
+
return error instanceof BrezelError && error.status === 404;
|
|
549
|
+
}
|
|
550
|
+
function resourceString(resource, name) {
|
|
551
|
+
const value = resource[name];
|
|
552
|
+
if (typeof value !== "string" || !value) {
|
|
553
|
+
throw new Error(`Brezel sandbox response is missing ${name}`);
|
|
554
|
+
}
|
|
555
|
+
return value;
|
|
556
|
+
}
|
|
557
|
+
function validateEnvironment(environment) {
|
|
558
|
+
const result = {};
|
|
559
|
+
for (const [name, value] of Object.entries(environment ?? {})) {
|
|
560
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
|
|
561
|
+
throw new Error(`Invalid environment variable name: ${JSON.stringify(name)}`);
|
|
562
|
+
}
|
|
563
|
+
result[name] = String(value);
|
|
564
|
+
}
|
|
565
|
+
return result;
|
|
566
|
+
}
|
|
567
|
+
function createTimeout(options) {
|
|
568
|
+
const timeoutMs = options?.timeout ?? DEFAULT_TIMEOUT_MS;
|
|
569
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
570
|
+
throw new Error("Brezel sandbox timeout must be a positive finite number of milliseconds");
|
|
571
|
+
}
|
|
572
|
+
if (timeoutMs > MAX_SANDBOX_TTL_MS) {
|
|
573
|
+
throw new Error(
|
|
574
|
+
`Brezel sandbox timeout cannot exceed ${MAX_SANDBOX_TTL_MS} milliseconds (30 days)`
|
|
575
|
+
);
|
|
576
|
+
}
|
|
577
|
+
return {
|
|
578
|
+
timeoutMs,
|
|
579
|
+
ttlSeconds: Math.ceil(Math.max(timeoutMs, MIN_SANDBOX_TTL_MS) / 1e3)
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
function validateCreateOptions(options) {
|
|
583
|
+
if (options?.snapshotId) throw new Error("Brezel snapshots are not exposed through ComputeSDK yet");
|
|
584
|
+
if (options?.image) throw new Error("Use a prequalified Brezel environment revision instead of image");
|
|
585
|
+
const environment = validateEnvironment(options?.envs);
|
|
586
|
+
if (Object.keys(environment).length > 0) {
|
|
587
|
+
throw new Error(
|
|
588
|
+
"Brezel does not support durable create-time envs through ComputeSDK yet; set environment variables on runCommand instead."
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
function commandArgv(command, background) {
|
|
593
|
+
if (!background) return ["/bin/sh", "-lc", command];
|
|
594
|
+
return [
|
|
595
|
+
"/bin/sh",
|
|
596
|
+
"-lc",
|
|
597
|
+
'nohup /bin/sh -lc "$1" sh >/dev/null 2>&1 </dev/null &',
|
|
598
|
+
"sh",
|
|
599
|
+
command
|
|
600
|
+
];
|
|
601
|
+
}
|
|
602
|
+
async function sleep(milliseconds) {
|
|
603
|
+
await new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
604
|
+
}
|
|
605
|
+
async function waitUntilDeleted(client, id) {
|
|
606
|
+
const deadline = Date.now() + DELETE_TIMEOUT_MS;
|
|
607
|
+
while (Date.now() < deadline) {
|
|
608
|
+
try {
|
|
609
|
+
const current = await client.sandbox(id);
|
|
610
|
+
if (terminal(current.resource.state)) return;
|
|
611
|
+
} catch (error) {
|
|
612
|
+
if (isMissing(error)) return;
|
|
613
|
+
throw error;
|
|
614
|
+
}
|
|
615
|
+
await sleep(POLL_INTERVAL_MS);
|
|
616
|
+
}
|
|
617
|
+
throw new Error(`Timed out waiting for Brezel sandbox deletion: ${id}`);
|
|
618
|
+
}
|
|
619
|
+
var brezel = (0, import_provider.defineProvider)({
|
|
620
|
+
name: "brezel",
|
|
621
|
+
methods: {
|
|
622
|
+
sandbox: {
|
|
623
|
+
create: async (config, options) => {
|
|
624
|
+
validateCreateOptions(options);
|
|
625
|
+
const { timeoutMs, ttlSeconds } = createTimeout(options);
|
|
626
|
+
if (options?.signal?.aborted) throw options.signal.reason ?? new Error("Sandbox creation aborted");
|
|
627
|
+
const sandbox = await getClient(config).createSandbox({
|
|
628
|
+
environmentRevision: environmentRevision(config, options),
|
|
629
|
+
ttlSeconds,
|
|
630
|
+
allowInternet: allowInternet(config)
|
|
631
|
+
});
|
|
632
|
+
sandboxTimeouts.set(sandbox, timeoutMs);
|
|
633
|
+
sandboxClients.set(sandbox, getClient(config));
|
|
634
|
+
return { sandbox, sandboxId: sandbox.id };
|
|
635
|
+
},
|
|
636
|
+
getById: async (config, sandboxId) => {
|
|
637
|
+
try {
|
|
638
|
+
const sandbox = await getClient(config).sandbox(sandboxId);
|
|
639
|
+
if (terminal(sandbox.resource.state)) return null;
|
|
640
|
+
sandboxClients.set(sandbox, getClient(config));
|
|
641
|
+
return { sandbox, sandboxId };
|
|
642
|
+
} catch (error) {
|
|
643
|
+
if (isMissing(error)) return null;
|
|
644
|
+
throw error;
|
|
645
|
+
}
|
|
646
|
+
},
|
|
647
|
+
list: async (config) => {
|
|
648
|
+
const client = getClient(config);
|
|
649
|
+
const resources = await client.listSandboxes();
|
|
650
|
+
const active = resources.filter((resource) => !terminal(resource.state));
|
|
651
|
+
return Promise.all(active.map(async (resource) => {
|
|
652
|
+
const sandbox = await client.sandbox(resourceString(resource, "id"));
|
|
653
|
+
sandboxClients.set(sandbox, client);
|
|
654
|
+
return { sandbox, sandboxId: sandbox.id };
|
|
655
|
+
}));
|
|
656
|
+
},
|
|
657
|
+
destroy: async (config, sandboxId) => {
|
|
658
|
+
const client = getClient(config);
|
|
659
|
+
try {
|
|
660
|
+
const sandbox = await client.sandbox(sandboxId);
|
|
661
|
+
await sandbox.delete();
|
|
662
|
+
} catch (error) {
|
|
663
|
+
if (!isMissing(error)) throw error;
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
await waitUntilDeleted(client, sandboxId);
|
|
667
|
+
},
|
|
668
|
+
runCommand,
|
|
669
|
+
// Brezel streams command events over its management API. Registering the
|
|
670
|
+
// same implementation here prevents ComputeSDK from bootstrapping its
|
|
671
|
+
// generic in-sandbox SSE bridge when callbacks are requested.
|
|
672
|
+
streamCommand: runCommand,
|
|
673
|
+
getInfo: async (sandbox) => {
|
|
674
|
+
const client = sandboxClients.get(sandbox);
|
|
675
|
+
if (!client) throw new Error(`Brezel client is unavailable for sandbox: ${sandbox.id}`);
|
|
676
|
+
const current = await client.sandbox(sandbox.id);
|
|
677
|
+
const resource = current.resource;
|
|
678
|
+
return {
|
|
679
|
+
id: sandbox.id,
|
|
680
|
+
provider: "brezel",
|
|
681
|
+
status: status(resource.state),
|
|
682
|
+
createdAt: new Date(resourceString(resource, "created_at")),
|
|
683
|
+
timeout: sandboxTimeouts.get(sandbox) ?? DEFAULT_TIMEOUT_MS,
|
|
684
|
+
metadata: {
|
|
685
|
+
environmentRevision: resource.environment_revision,
|
|
686
|
+
revision: resource.revision
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
},
|
|
690
|
+
getUrl: async (sandbox, options) => {
|
|
691
|
+
const value = await sandbox.preview(options.port);
|
|
692
|
+
if (!options.protocol) return value;
|
|
693
|
+
const url = new URL(value);
|
|
694
|
+
url.protocol = `${options.protocol}:`;
|
|
695
|
+
return url.toString();
|
|
696
|
+
},
|
|
697
|
+
getInstance: (sandbox) => sandbox,
|
|
698
|
+
filesystem: {
|
|
699
|
+
readFile: async (sandbox, path) => {
|
|
700
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(await sandbox.readFile(path));
|
|
701
|
+
},
|
|
702
|
+
writeFile: async (sandbox, path, content) => {
|
|
703
|
+
await sandbox.writeFile(path, content);
|
|
704
|
+
},
|
|
705
|
+
mkdir: async (sandbox, path) => {
|
|
706
|
+
await sandbox.run(["mkdir", "-p", "--", path], { check: true });
|
|
707
|
+
},
|
|
708
|
+
readdir: async (sandbox, path) => {
|
|
709
|
+
const result = await sandbox.run([
|
|
710
|
+
"find",
|
|
711
|
+
path,
|
|
712
|
+
"-mindepth",
|
|
713
|
+
"1",
|
|
714
|
+
"-maxdepth",
|
|
715
|
+
"1",
|
|
716
|
+
"-printf",
|
|
717
|
+
"%f\\0%y\\0%s\\0%T@\\0"
|
|
718
|
+
], { check: true });
|
|
719
|
+
const values = result.stdoutText.split("\0");
|
|
720
|
+
const entries = [];
|
|
721
|
+
for (let offset = 0; offset + 3 < values.length; offset += 4) {
|
|
722
|
+
if (!values[offset]) continue;
|
|
723
|
+
entries.push({
|
|
724
|
+
name: values[offset],
|
|
725
|
+
type: values[offset + 1] === "d" ? "directory" : "file",
|
|
726
|
+
size: Number.parseInt(values[offset + 2], 10) || 0,
|
|
727
|
+
modified: new Date(Number.parseFloat(values[offset + 3]) * 1e3)
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
return entries;
|
|
731
|
+
},
|
|
732
|
+
exists: async (sandbox, path) => {
|
|
733
|
+
const result = await sandbox.run(["/bin/sh", "-c", 'test -e "$1"', "sh", path]);
|
|
734
|
+
return result.exitCode === 0;
|
|
735
|
+
},
|
|
736
|
+
remove: async (sandbox, path) => {
|
|
737
|
+
await sandbox.run(["rm", "-rf", "--", path], { check: true });
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
});
|
|
743
|
+
async function runCommand(sandbox, command, options) {
|
|
744
|
+
const startedAt = performance.now();
|
|
745
|
+
const timeoutMs = options?.timeout ?? sandboxTimeouts.get(sandbox) ?? DEFAULT_TIMEOUT_MS;
|
|
746
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
747
|
+
throw new Error("Brezel command timeout must be a positive finite number of milliseconds");
|
|
748
|
+
}
|
|
749
|
+
const stdoutDecoder = new TextDecoder();
|
|
750
|
+
const stderrDecoder = new TextDecoder();
|
|
751
|
+
const result = await sandbox.run(commandArgv(command, options?.background ?? false), {
|
|
752
|
+
cwd: options?.cwd,
|
|
753
|
+
env: validateEnvironment(options?.env),
|
|
754
|
+
timeoutSeconds: Math.max(1, Math.ceil(timeoutMs / 1e3)),
|
|
755
|
+
onEvent: (event) => {
|
|
756
|
+
if ((event.type === "stdout" || event.type === "stderr") && typeof event.data === "string") {
|
|
757
|
+
const chunk = Buffer.from(event.data, "base64");
|
|
758
|
+
if (event.type === "stdout") options?.onStdout?.(stdoutDecoder.decode(chunk, { stream: true }));
|
|
759
|
+
else options?.onStderr?.(stderrDecoder.decode(chunk, { stream: true }));
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
});
|
|
763
|
+
options?.onStdout?.(stdoutDecoder.decode());
|
|
764
|
+
options?.onStderr?.(stderrDecoder.decode());
|
|
765
|
+
return {
|
|
766
|
+
stdout: result.stdoutText,
|
|
767
|
+
stderr: result.stderrText,
|
|
768
|
+
exitCode: result.exitCode,
|
|
769
|
+
durationMs: performance.now() - startedAt
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
773
|
+
0 && (module.exports = {
|
|
774
|
+
brezel
|
|
775
|
+
});
|
|
776
|
+
//# sourceMappingURL=index.js.map
|