@computesdk/kosa8 1.0.4 → 1.0.5
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/README.md +20 -4
- package/dist/index.d.mts +117 -10
- package/dist/index.d.ts +117 -10
- package/dist/index.js +668 -47
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +657 -48
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
8
|
var __export = (target, all) => {
|
|
7
9
|
for (var name in all)
|
|
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
17
|
}
|
|
16
18
|
return to;
|
|
17
19
|
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
18
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
29
|
|
|
20
30
|
// src/index.ts
|
|
@@ -22,17 +32,481 @@ var index_exports = {};
|
|
|
22
32
|
__export(index_exports, {
|
|
23
33
|
MAX_EXEC_BODY_BYTES: () => MAX_EXEC_BODY_BYTES,
|
|
24
34
|
SCRIPT_ENV: () => SCRIPT_ENV,
|
|
35
|
+
SNAPSHOT_CAPABILITIES: () => SNAPSHOT_CAPABILITIES,
|
|
25
36
|
WRITE_CHUNK_CHARS: () => WRITE_CHUNK_CHARS,
|
|
26
37
|
createBody: () => createBody,
|
|
27
38
|
default: () => index_default,
|
|
39
|
+
directFiles: () => directFiles,
|
|
28
40
|
execArgv: () => execArgv,
|
|
29
41
|
execBody: () => execBody,
|
|
30
42
|
kosa8: () => kosa8,
|
|
31
43
|
writeFileViaExec: () => writeFileViaExec
|
|
32
44
|
});
|
|
33
45
|
module.exports = __toCommonJS(index_exports);
|
|
46
|
+
var import_provider2 = require("@computesdk/provider");
|
|
47
|
+
|
|
48
|
+
// src/transport.ts
|
|
49
|
+
var nativeFetch = typeof fetch === "function" ? fetch : void 0;
|
|
50
|
+
var http2Load;
|
|
51
|
+
function loadHttp2() {
|
|
52
|
+
http2Load ?? (http2Load = import("http2").then(
|
|
53
|
+
(m) => m.default ?? m,
|
|
54
|
+
() => null
|
|
55
|
+
));
|
|
56
|
+
return http2Load;
|
|
57
|
+
}
|
|
58
|
+
var origins = /* @__PURE__ */ new Map();
|
|
59
|
+
var inFlight = /* @__PURE__ */ new WeakMap();
|
|
60
|
+
var retired = /* @__PURE__ */ new WeakSet();
|
|
61
|
+
function hold(s) {
|
|
62
|
+
inFlight.set(s, (inFlight.get(s) ?? 0) + 1);
|
|
63
|
+
s.ref();
|
|
64
|
+
}
|
|
65
|
+
function release(s) {
|
|
66
|
+
const n = (inFlight.get(s) ?? 1) - 1;
|
|
67
|
+
inFlight.set(s, n);
|
|
68
|
+
if (n > 0 || s.destroyed) return;
|
|
69
|
+
if (retired.has(s)) s.close();
|
|
70
|
+
else s.unref();
|
|
71
|
+
}
|
|
72
|
+
function abortError(signal) {
|
|
73
|
+
return signal.reason ?? new Error("The operation was aborted");
|
|
74
|
+
}
|
|
75
|
+
function untilAborted(p, signal) {
|
|
76
|
+
if (!signal) return p;
|
|
77
|
+
if (signal.aborted) return Promise.reject(abortError(signal));
|
|
78
|
+
return new Promise((resolve, reject) => {
|
|
79
|
+
const onAbort = () => reject(abortError(signal));
|
|
80
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
81
|
+
p.then(
|
|
82
|
+
(v) => {
|
|
83
|
+
signal.removeEventListener("abort", onAbort);
|
|
84
|
+
resolve(v);
|
|
85
|
+
},
|
|
86
|
+
(e) => {
|
|
87
|
+
signal.removeEventListener("abort", onAbort);
|
|
88
|
+
reject(e);
|
|
89
|
+
}
|
|
90
|
+
);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
var WINDOW_BYTES = 16 * 1024 * 1024;
|
|
94
|
+
var SESSION_WINDOW_BYTES = 64 * 1024 * 1024;
|
|
95
|
+
var CONNECT_TIMEOUT_MS = 1e4;
|
|
96
|
+
function mode() {
|
|
97
|
+
const m = typeof process !== "undefined" ? process.env?.KOSA8_HTTP_TRANSPORT : void 0;
|
|
98
|
+
return m === "fetch" || m === "http2" ? m : "auto";
|
|
99
|
+
}
|
|
100
|
+
function originOf(url) {
|
|
101
|
+
try {
|
|
102
|
+
const u = new URL(url);
|
|
103
|
+
if (u.protocol === "https:") return u.origin;
|
|
104
|
+
const loopback = u.hostname === "127.0.0.1" || u.hostname === "localhost" || u.hostname === "[::1]";
|
|
105
|
+
return u.protocol === "http:" && loopback && mode() === "http2" ? u.origin : null;
|
|
106
|
+
} catch {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function useHttp2() {
|
|
111
|
+
if (typeof process === "undefined" || !process.versions?.node) return false;
|
|
112
|
+
const m = mode();
|
|
113
|
+
if (m === "fetch") return false;
|
|
114
|
+
return m === "http2" || typeof fetch === "function" && fetch === nativeFetch;
|
|
115
|
+
}
|
|
116
|
+
function session(origin) {
|
|
117
|
+
let o = origins.get(origin);
|
|
118
|
+
if (!o) {
|
|
119
|
+
o = {};
|
|
120
|
+
origins.set(origin, o);
|
|
121
|
+
}
|
|
122
|
+
if (o.failed) return Promise.resolve(null);
|
|
123
|
+
if (o.session) return o.session;
|
|
124
|
+
const entry = o;
|
|
125
|
+
const opening = loadHttp2().then((http2) => {
|
|
126
|
+
if (!http2) {
|
|
127
|
+
entry.failed = true;
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
return new Promise((resolve) => {
|
|
131
|
+
let settled = false;
|
|
132
|
+
const s = http2.connect(origin, { settings: { initialWindowSize: WINDOW_BYTES } });
|
|
133
|
+
const timer = setTimeout(() => {
|
|
134
|
+
if (settled) return;
|
|
135
|
+
settled = true;
|
|
136
|
+
entry.failed = true;
|
|
137
|
+
s.destroy();
|
|
138
|
+
resolve(null);
|
|
139
|
+
}, CONNECT_TIMEOUT_MS);
|
|
140
|
+
timer.unref?.();
|
|
141
|
+
const forget = () => {
|
|
142
|
+
if (entry.session === opening) entry.session = void 0;
|
|
143
|
+
};
|
|
144
|
+
s.once("connect", () => {
|
|
145
|
+
if (settled) return;
|
|
146
|
+
settled = true;
|
|
147
|
+
clearTimeout(timer);
|
|
148
|
+
try {
|
|
149
|
+
s.setLocalWindowSize(SESSION_WINDOW_BYTES);
|
|
150
|
+
} catch {
|
|
151
|
+
}
|
|
152
|
+
if (!inFlight.get(s)) s.unref();
|
|
153
|
+
resolve(s);
|
|
154
|
+
});
|
|
155
|
+
s.on("error", () => {
|
|
156
|
+
forget();
|
|
157
|
+
if (!settled) {
|
|
158
|
+
settled = true;
|
|
159
|
+
clearTimeout(timer);
|
|
160
|
+
entry.failed = true;
|
|
161
|
+
resolve(null);
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
s.once("goaway", () => {
|
|
165
|
+
forget();
|
|
166
|
+
retired.add(s);
|
|
167
|
+
if (!inFlight.get(s)) s.close();
|
|
168
|
+
});
|
|
169
|
+
s.once("close", forget);
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
entry.session = opening;
|
|
173
|
+
return opening;
|
|
174
|
+
}
|
|
175
|
+
function preconnect(url) {
|
|
176
|
+
const origin = originOf(url);
|
|
177
|
+
if (!origin || !useHttp2()) return;
|
|
178
|
+
void session(origin);
|
|
179
|
+
}
|
|
180
|
+
async function viaFetch(url, init) {
|
|
181
|
+
const res = await fetch(url, {
|
|
182
|
+
method: init.method,
|
|
183
|
+
headers: init.headers,
|
|
184
|
+
// A Uint8Array body is sent as its bytes (BodyInit types leave out views over a SharedArrayBuffer).
|
|
185
|
+
body: init.body,
|
|
186
|
+
signal: init.signal
|
|
187
|
+
});
|
|
188
|
+
const headers = {};
|
|
189
|
+
res.headers?.forEach?.((v, k) => headers[k.toLowerCase()] = v);
|
|
190
|
+
if (init.binary) {
|
|
191
|
+
return { status: res.status, ok: res.ok, text: "", bytes: new Uint8Array(await res.arrayBuffer()), headers };
|
|
192
|
+
}
|
|
193
|
+
return { status: res.status, ok: res.ok, text: await res.text(), headers };
|
|
194
|
+
}
|
|
195
|
+
async function httpRequest(url, init) {
|
|
196
|
+
const origin = originOf(url);
|
|
197
|
+
if (!origin || !useHttp2()) return viaFetch(url, init);
|
|
198
|
+
const s = await untilAborted(session(origin), init.signal);
|
|
199
|
+
if (!s || s.closed || s.destroyed) return viaFetch(url, init);
|
|
200
|
+
hold(s);
|
|
201
|
+
try {
|
|
202
|
+
return await viaSession(s, url, init);
|
|
203
|
+
} catch (e) {
|
|
204
|
+
if (notProcessed(e) && !init.signal?.aborted) return await viaFetch(url, init);
|
|
205
|
+
throw e;
|
|
206
|
+
} finally {
|
|
207
|
+
release(s);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
function notProcessed(e) {
|
|
211
|
+
const x = e;
|
|
212
|
+
return !!x && (x.code === "ERR_HTTP2_GOAWAY_SESSION" || x.code === "ERR_HTTP2_INVALID_SESSION" || x.rstCode === 7);
|
|
213
|
+
}
|
|
214
|
+
function viaSession(s, url, init) {
|
|
215
|
+
const u = new URL(url);
|
|
216
|
+
return new Promise((resolve, reject) => {
|
|
217
|
+
const headers = {
|
|
218
|
+
":method": init.method,
|
|
219
|
+
":path": u.pathname + u.search
|
|
220
|
+
};
|
|
221
|
+
for (const [k, v] of Object.entries(init.headers)) headers[k.toLowerCase()] = v;
|
|
222
|
+
let req;
|
|
223
|
+
try {
|
|
224
|
+
req = s.request(headers);
|
|
225
|
+
} catch (e) {
|
|
226
|
+
reject(e);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
let done = false;
|
|
230
|
+
const finish = (f) => {
|
|
231
|
+
if (done) return;
|
|
232
|
+
done = true;
|
|
233
|
+
init.signal?.removeEventListener("abort", onAbort);
|
|
234
|
+
f();
|
|
235
|
+
};
|
|
236
|
+
const aborted = () => init.signal ? abortError(init.signal) : new Error("The operation was aborted");
|
|
237
|
+
const onAbort = () => {
|
|
238
|
+
finish(() => reject(aborted()));
|
|
239
|
+
req.close(8);
|
|
240
|
+
};
|
|
241
|
+
if (init.signal) {
|
|
242
|
+
if (init.signal.aborted) {
|
|
243
|
+
onAbort();
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
init.signal.addEventListener("abort", onAbort, { once: true });
|
|
247
|
+
}
|
|
248
|
+
const chunks = [];
|
|
249
|
+
let status = 0;
|
|
250
|
+
const got = {};
|
|
251
|
+
req.on("response", (h) => {
|
|
252
|
+
status = Number(h[":status"] ?? 0);
|
|
253
|
+
for (const [k, v] of Object.entries(h)) if (!k.startsWith(":") && v !== void 0) got[k] = String(v);
|
|
254
|
+
});
|
|
255
|
+
req.on("data", (c) => chunks.push(c));
|
|
256
|
+
let ended = false;
|
|
257
|
+
req.on("end", () => {
|
|
258
|
+
ended = !s.destroyed;
|
|
259
|
+
});
|
|
260
|
+
req.on("close", () => {
|
|
261
|
+
if (status !== 0 && ended && !req.rstCode) {
|
|
262
|
+
const body = Buffer.concat(chunks);
|
|
263
|
+
finish(
|
|
264
|
+
() => resolve({
|
|
265
|
+
status,
|
|
266
|
+
ok: status >= 200 && status < 300,
|
|
267
|
+
text: init.binary ? "" : body.toString("utf8"),
|
|
268
|
+
...init.binary ? { bytes: new Uint8Array(body.buffer, body.byteOffset, body.byteLength) } : {},
|
|
269
|
+
headers: got
|
|
270
|
+
})
|
|
271
|
+
);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
const why = status === 0 ? "without a response" : "before the response completed";
|
|
275
|
+
finish(() => reject(new Error(`kosa8: the HTTP/2 stream closed ${why}`)));
|
|
276
|
+
});
|
|
277
|
+
req.on(
|
|
278
|
+
"error",
|
|
279
|
+
(e) => finish(() => reject(init.signal?.aborted ? aborted() : Object.assign(e, { rstCode: req.rstCode })))
|
|
280
|
+
);
|
|
281
|
+
req.end(init.body);
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// src/files.ts
|
|
34
286
|
var import_node_crypto = require("crypto");
|
|
35
287
|
var import_provider = require("@computesdk/provider");
|
|
288
|
+
var fileParts = { bytes: 64 * 1024 * 1024, concurrency: 4, writeConcurrency: 2 };
|
|
289
|
+
var FILE_RETRIES = 2;
|
|
290
|
+
var RETRY_STATUS = /* @__PURE__ */ new Set([500, 502, 503, 504]);
|
|
291
|
+
var DIRECT_REFUSED = /* @__PURE__ */ new Set([401, 409, 501, 521, 522, 523, 530]);
|
|
292
|
+
var WRITE_CHUNK_CHARS = 48 * 1024;
|
|
293
|
+
var INLINE_READ_BYTES = 1024 * 1024;
|
|
294
|
+
var NOT_FOUND_EXIT = 44;
|
|
295
|
+
var MIB = 1024 * 1024;
|
|
296
|
+
var q = (s) => `"${(0, import_provider.escapeShellArg)(s)}"`;
|
|
297
|
+
var notFound = (path) => new Error(`ENOENT: no such file or directory, open '${path}'`);
|
|
298
|
+
var apiTarget = (sandbox) => ({
|
|
299
|
+
url: `${sandbox.baseUrl}/v1/sandboxes/${encodeURIComponent(sandbox.id)}/files`,
|
|
300
|
+
token: sandbox.apiKey
|
|
301
|
+
});
|
|
302
|
+
function errorDetail(res) {
|
|
303
|
+
const text = res.text || (res.bytes ? Buffer.from(res.bytes).toString("utf8") : "");
|
|
304
|
+
try {
|
|
305
|
+
const parsed = JSON.parse(text);
|
|
306
|
+
if (parsed && (parsed.error || parsed.message)) return [parsed.error, parsed.message].filter(Boolean).join(": ");
|
|
307
|
+
} catch {
|
|
308
|
+
}
|
|
309
|
+
return text.slice(0, 500);
|
|
310
|
+
}
|
|
311
|
+
function fileError(res, op, path) {
|
|
312
|
+
const detail = errorDetail(res);
|
|
313
|
+
if (res.status === 404) return notFound(path);
|
|
314
|
+
if (res.status === 403) return new Error(`EACCES: permission denied, ${op} '${path}'${detail ? `: ${detail}` : ""}`);
|
|
315
|
+
if (res.status === 507) return new Error(`ENOSPC: no space left on device, ${op} '${path}'${detail ? `: ${detail}` : ""}`);
|
|
316
|
+
return new Error(`kosa8 file ${op} '${path}' failed (${res.status})${detail ? `: ${detail}` : ""}`);
|
|
317
|
+
}
|
|
318
|
+
function olderFileApi(res) {
|
|
319
|
+
return res.status === 413 || res.status === 501 || res.status === 400 && /workspace/i.test(errorDetail(res));
|
|
320
|
+
}
|
|
321
|
+
async function send(t, method, path, { body, offset, range } = {}) {
|
|
322
|
+
const url = `${t.url}?path=${encodeURIComponent(path)}${offset ? `&offset=${offset}` : ""}`;
|
|
323
|
+
const headers = { Authorization: `Bearer ${t.token}` };
|
|
324
|
+
if (body) headers["Content-Type"] = "application/octet-stream";
|
|
325
|
+
if (range) headers.Range = `bytes=${range[0]}-${range[1]}`;
|
|
326
|
+
for (let attempt = 0; ; attempt++) {
|
|
327
|
+
try {
|
|
328
|
+
const res = await httpRequest(url, { method, headers, body, binary: true });
|
|
329
|
+
if (!RETRY_STATUS.has(res.status) || attempt >= FILE_RETRIES) return res;
|
|
330
|
+
} catch (err) {
|
|
331
|
+
if (attempt >= FILE_RETRIES) throw err;
|
|
332
|
+
}
|
|
333
|
+
await new Promise((r) => setTimeout(r, 250 * (attempt + 1)));
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
async function inParallel(items, limit, task) {
|
|
337
|
+
let next = 0;
|
|
338
|
+
let failed = null;
|
|
339
|
+
let thrown;
|
|
340
|
+
const worker = async () => {
|
|
341
|
+
while (!failed && !thrown && next < items.length) {
|
|
342
|
+
try {
|
|
343
|
+
const r = await task(items[next++]);
|
|
344
|
+
if (r) failed ?? (failed = r);
|
|
345
|
+
} catch (err) {
|
|
346
|
+
thrown ?? (thrown = { err });
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
351
|
+
if (thrown) throw thrown.err;
|
|
352
|
+
return failed;
|
|
353
|
+
}
|
|
354
|
+
async function writeTo(t, path, bytes) {
|
|
355
|
+
const first = await send(t, "PUT", path, { body: bytes.subarray(0, fileParts.bytes) });
|
|
356
|
+
if (!first.ok) return first;
|
|
357
|
+
const offsets = [];
|
|
358
|
+
for (let at = fileParts.bytes; at < bytes.length; at += fileParts.bytes) offsets.push(at);
|
|
359
|
+
return inParallel(offsets, fileParts.writeConcurrency, async (at) => {
|
|
360
|
+
const res = await send(t, "PUT", path, { body: bytes.subarray(at, at + fileParts.bytes), offset: at });
|
|
361
|
+
return res.ok ? null : res;
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
async function readFrom(t, path) {
|
|
365
|
+
const first = await send(t, "GET", path, { range: [0, fileParts.bytes - 1] });
|
|
366
|
+
if (first.status === 416) return new Uint8Array();
|
|
367
|
+
if (first.status === 200) return first.bytes ?? new Uint8Array();
|
|
368
|
+
if (first.status !== 206) return first;
|
|
369
|
+
const head = first.bytes ?? new Uint8Array();
|
|
370
|
+
const total = Number(/\/(\d+)\s*$/.exec(first.headers["content-range"] ?? "")?.[1] ?? head.length);
|
|
371
|
+
if (total <= head.length) return head;
|
|
372
|
+
const starts = [];
|
|
373
|
+
for (let at = head.length; at < total; at += fileParts.bytes) starts.push(at);
|
|
374
|
+
const parts = /* @__PURE__ */ new Map();
|
|
375
|
+
const failed = await inParallel(starts, fileParts.concurrency, async (at) => {
|
|
376
|
+
const res = await send(t, "GET", path, { range: [at, Math.min(total, at + fileParts.bytes) - 1] });
|
|
377
|
+
if (res.status !== 206 && res.status !== 200) return res;
|
|
378
|
+
parts.set(at, res.bytes ?? new Uint8Array());
|
|
379
|
+
return null;
|
|
380
|
+
});
|
|
381
|
+
if (failed) return failed;
|
|
382
|
+
const all = Buffer.concat([head, ...starts.map((at) => parts.get(at))]);
|
|
383
|
+
if (all.length !== total) {
|
|
384
|
+
throw new Error(`open '${path}' failed: read ${all.length} of ${total} bytes (the file changed while it was read?)`);
|
|
385
|
+
}
|
|
386
|
+
return all;
|
|
387
|
+
}
|
|
388
|
+
async function writeFileNative(sandbox, path, content, run, direct = null) {
|
|
389
|
+
const bytes = Buffer.from(content, "utf8");
|
|
390
|
+
const staged = bytes.length > fileParts.bytes ? `${path}.computesdk-${(0, import_node_crypto.randomBytes)(6).toString("hex")}` : null;
|
|
391
|
+
const dest = staged ?? path;
|
|
392
|
+
const commit = async () => {
|
|
393
|
+
if (staged) {
|
|
394
|
+
await mustSucceed(
|
|
395
|
+
run,
|
|
396
|
+
sandbox,
|
|
397
|
+
`if [ -d ${q(path)} ]; then echo 'target is a directory' >&2; exit 1; fi; mv -f ${q(staged)} ${q(path)}`,
|
|
398
|
+
"write",
|
|
399
|
+
path
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
try {
|
|
404
|
+
if (direct) {
|
|
405
|
+
const res = await writeTo(direct, dest, bytes).catch(() => void 0);
|
|
406
|
+
if (res === null) {
|
|
407
|
+
await commit();
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
if (res && !DIRECT_REFUSED.has(res.status)) throw fileError(res, "write", path);
|
|
411
|
+
if (res && (res.status === 401 || res.status === 501)) sandbox.directFiles = false;
|
|
412
|
+
}
|
|
413
|
+
if (sandbox.files !== false) {
|
|
414
|
+
const res = await writeTo(apiTarget(sandbox), dest, bytes);
|
|
415
|
+
if (!res) {
|
|
416
|
+
await commit();
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
if (!olderFileApi(res)) throw fileError(res, "write", path);
|
|
420
|
+
if (res.status === 501) sandbox.files = false;
|
|
421
|
+
}
|
|
422
|
+
return writeFileViaExec(sandbox, path, bytes, run);
|
|
423
|
+
} finally {
|
|
424
|
+
if (staged) await run(sandbox, `rm -f ${q(staged)}`).catch(() => {
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
async function mustSucceed(run, sandbox, command, what, path, env) {
|
|
429
|
+
const result = await run(sandbox, command, env ? { env } : void 0);
|
|
430
|
+
if (result.exitCode === NOT_FOUND_EXIT) throw notFound(path);
|
|
431
|
+
if (result.exitCode !== 0) {
|
|
432
|
+
const detail = (result.stderr || result.stdout).trim();
|
|
433
|
+
throw new Error(`${what} '${path}' failed (exit ${result.exitCode})${detail ? `: ${detail}` : ""}`);
|
|
434
|
+
}
|
|
435
|
+
if (result.stdoutTruncated) {
|
|
436
|
+
throw new Error(`${what} '${path}' failed: the command's output was cut off at the exec API's limit`);
|
|
437
|
+
}
|
|
438
|
+
return result.stdout;
|
|
439
|
+
}
|
|
440
|
+
async function writeFileViaExec(sandbox, path, content, run) {
|
|
441
|
+
const target = q(path);
|
|
442
|
+
const tmp = q(`${path}.computesdk-${(0, import_node_crypto.randomBytes)(6).toString("hex")}`);
|
|
443
|
+
const encoded = Buffer.from(content).toString("base64");
|
|
444
|
+
const mkParent = `d=$(dirname ${target}) && mkdir -p "$d"`;
|
|
445
|
+
if (encoded.length <= WRITE_CHUNK_CHARS) {
|
|
446
|
+
const cmd = `${mkParent} && printf '%s' "$KOSA8_CHUNK" | base64 -d > ${tmp} && mv -f ${tmp} ${target} || { s=$?; rm -f ${tmp}; exit $s; }`;
|
|
447
|
+
await mustSucceed(run, sandbox, cmd, "write", path, { KOSA8_CHUNK: encoded });
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
try {
|
|
451
|
+
await mustSucceed(run, sandbox, `${mkParent} && : > ${tmp}`, "write", path);
|
|
452
|
+
for (let i = 0; i < encoded.length; i += WRITE_CHUNK_CHARS) {
|
|
453
|
+
await mustSucceed(run, sandbox, `printf '%s' "$KOSA8_CHUNK" | base64 -d >> ${tmp}`, "write", path, {
|
|
454
|
+
KOSA8_CHUNK: encoded.slice(i, i + WRITE_CHUNK_CHARS)
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, "write", path);
|
|
458
|
+
} catch (err) {
|
|
459
|
+
await run(sandbox, `rm -f ${tmp}`).catch(() => {
|
|
460
|
+
});
|
|
461
|
+
throw err;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
var fromBase64 = (s) => Buffer.from(s.replace(/\s+/g, ""), "base64");
|
|
465
|
+
async function readFileNative(sandbox, path, run, direct = null) {
|
|
466
|
+
if (direct) {
|
|
467
|
+
const got = await readFrom(direct, path).catch(() => void 0);
|
|
468
|
+
if (got instanceof Uint8Array) return Buffer.from(got).toString("utf8");
|
|
469
|
+
if (got && !DIRECT_REFUSED.has(got.status)) throw fileError(got, "open", path);
|
|
470
|
+
if (got && (got.status === 401 || got.status === 501)) sandbox.directFiles = false;
|
|
471
|
+
}
|
|
472
|
+
if (sandbox.files !== false) {
|
|
473
|
+
const got = await readFrom(apiTarget(sandbox), path);
|
|
474
|
+
if (got instanceof Uint8Array) return Buffer.from(got).toString("utf8");
|
|
475
|
+
if (!olderFileApi(got)) throw fileError(got, "open", path);
|
|
476
|
+
if (got.status === 501) sandbox.files = false;
|
|
477
|
+
}
|
|
478
|
+
return readFileViaExec(sandbox, path, run);
|
|
479
|
+
}
|
|
480
|
+
async function readFileViaExec(sandbox, path, run) {
|
|
481
|
+
const p = q(path);
|
|
482
|
+
const out = await mustSucceed(
|
|
483
|
+
run,
|
|
484
|
+
sandbox,
|
|
485
|
+
`[ -f ${p} ] || exit ${NOT_FOUND_EXIT}; s=$(wc -c < ${p} | tr -d ' ') || exit $?; echo "$s"; if [ "$s" -le ${INLINE_READ_BYTES} ]; then base64 < ${p}; fi`,
|
|
486
|
+
"open",
|
|
487
|
+
path
|
|
488
|
+
);
|
|
489
|
+
const nl = out.indexOf("\n");
|
|
490
|
+
const size = Number(out.slice(0, nl < 0 ? void 0 : nl).trim());
|
|
491
|
+
if (!Number.isInteger(size) || size < 0) throw new Error(`open '${path}' failed: unexpected answer from the sandbox`);
|
|
492
|
+
if (size <= INLINE_READ_BYTES) return fromBase64(nl < 0 ? "" : out.slice(nl + 1)).toString("utf8");
|
|
493
|
+
const chunks = new Array(Math.ceil(size / INLINE_READ_BYTES));
|
|
494
|
+
let next = 0;
|
|
495
|
+
const worker = async () => {
|
|
496
|
+
while (next < chunks.length) {
|
|
497
|
+
const i = next++;
|
|
498
|
+
chunks[i] = fromBase64(
|
|
499
|
+
await mustSucceed(run, sandbox, `[ -f ${p} ] || exit ${NOT_FOUND_EXIT}; dd if=${p} bs=${MIB} skip=${i} count=1 2>/dev/null | base64`, "open", path)
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
};
|
|
503
|
+
await Promise.all(Array.from({ length: Math.min(fileParts.concurrency, chunks.length) }, worker));
|
|
504
|
+
const all = Buffer.concat(chunks);
|
|
505
|
+
if (all.length !== size) throw new Error(`open '${path}' failed: read ${all.length} of ${size} bytes (the file changed while it was read?)`);
|
|
506
|
+
return all.toString("utf8");
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// src/index.ts
|
|
36
510
|
var MIN_TTL_S = 60;
|
|
37
511
|
var MAX_TTL_S = 90 * 86400;
|
|
38
512
|
var TIMEOUT_EXIT = 124;
|
|
@@ -49,11 +523,10 @@ var UNSUPPORTED_CREATE_OPTIONS = [
|
|
|
49
523
|
"memoryMb",
|
|
50
524
|
"diskMb",
|
|
51
525
|
"diskMiB",
|
|
52
|
-
"image",
|
|
53
|
-
"snapshotId",
|
|
54
526
|
"envs",
|
|
55
527
|
"volumes"
|
|
56
528
|
];
|
|
529
|
+
var SNAPSHOT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
57
530
|
function resolveConfig(config) {
|
|
58
531
|
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
59
532
|
const apiKey = config.apiKey || env?.KOSA8_API_KEY || "";
|
|
@@ -66,7 +539,7 @@ function resolveConfig(config) {
|
|
|
66
539
|
return { apiKey, baseUrl };
|
|
67
540
|
}
|
|
68
541
|
async function request(auth, method, path, body, signal) {
|
|
69
|
-
const res = await
|
|
542
|
+
const res = await httpRequest(`${auth.baseUrl}${path}`, {
|
|
70
543
|
method,
|
|
71
544
|
headers: {
|
|
72
545
|
Authorization: `Bearer ${auth.apiKey}`,
|
|
@@ -76,7 +549,7 @@ async function request(auth, method, path, body, signal) {
|
|
|
76
549
|
signal
|
|
77
550
|
});
|
|
78
551
|
if (res.status === 404) return null;
|
|
79
|
-
const text =
|
|
552
|
+
const text = res.text;
|
|
80
553
|
if (!res.ok) {
|
|
81
554
|
let detail = text;
|
|
82
555
|
try {
|
|
@@ -89,23 +562,93 @@ async function request(auth, method, path, body, signal) {
|
|
|
89
562
|
return text ? JSON.parse(text) : null;
|
|
90
563
|
}
|
|
91
564
|
var sandboxPath = (id, rest = "") => `/v1/sandboxes/${encodeURIComponent(id)}${rest}`;
|
|
92
|
-
function toSandbox(auth, data) {
|
|
93
|
-
|
|
565
|
+
function toSandbox(auth, data, direct) {
|
|
566
|
+
const sandbox = { id: data.id, data, apiKey: auth.apiKey, baseUrl: auth.baseUrl };
|
|
567
|
+
if (isDirect(direct)) {
|
|
568
|
+
sandbox.direct = direct;
|
|
569
|
+
preconnect(direct.exec_url);
|
|
570
|
+
}
|
|
571
|
+
return sandbox;
|
|
572
|
+
}
|
|
573
|
+
function isDirect(d) {
|
|
574
|
+
const x = d;
|
|
575
|
+
return !!x && typeof x.exec_url === "string" && /^https:\/\//.test(x.exec_url) && typeof x.token === "string" && typeof x.expires_at === "number";
|
|
576
|
+
}
|
|
577
|
+
var DIRECT_MARGIN_MS = 15e3;
|
|
578
|
+
var DIRECT_REFRESH_MS = 6e4;
|
|
579
|
+
var DIRECT_NOT_RUN = /* @__PURE__ */ new Set([401, 403, 404, 409, 501, 521, 522, 523, 530]);
|
|
580
|
+
function directFiles(sandbox) {
|
|
581
|
+
const d = sandbox.direct;
|
|
582
|
+
if (!d?.files_url || sandbox.directFiles === false || !/^https:\/\//.test(d.files_url)) return null;
|
|
583
|
+
const left = d.expires_at - Date.now();
|
|
584
|
+
if (left < DIRECT_REFRESH_MS) refreshDirect(sandbox);
|
|
585
|
+
return left < DIRECT_MARGIN_MS ? null : { url: d.files_url, token: d.token };
|
|
586
|
+
}
|
|
587
|
+
function refreshDirect(sandbox) {
|
|
588
|
+
if (sandbox.refreshing) return;
|
|
589
|
+
sandbox.refreshing = request(sandbox, "POST", sandboxPath(sandbox.id, "/direct")).then((r) => {
|
|
590
|
+
if (isDirect(r?.direct)) sandbox.direct = r.direct;
|
|
591
|
+
}).catch(() => {
|
|
592
|
+
}).finally(() => {
|
|
593
|
+
sandbox.refreshing = void 0;
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
async function runDirect(sandbox, body, signal) {
|
|
597
|
+
const d = sandbox.direct;
|
|
598
|
+
if (!d) return null;
|
|
599
|
+
const left = d.expires_at - Date.now();
|
|
600
|
+
if (left < DIRECT_REFRESH_MS) refreshDirect(sandbox);
|
|
601
|
+
if (left < DIRECT_MARGIN_MS) return null;
|
|
602
|
+
const res = await httpRequest(d.exec_url, {
|
|
603
|
+
method: "POST",
|
|
604
|
+
headers: { Authorization: `Bearer ${d.token}`, "Content-Type": "application/json" },
|
|
605
|
+
body: JSON.stringify(body),
|
|
606
|
+
signal
|
|
607
|
+
});
|
|
608
|
+
const text = res.text;
|
|
609
|
+
if (DIRECT_NOT_RUN.has(res.status)) {
|
|
610
|
+
if (sandbox.direct === d) sandbox.direct = void 0;
|
|
611
|
+
return null;
|
|
612
|
+
}
|
|
613
|
+
if (!res.ok) {
|
|
614
|
+
let detail = text;
|
|
615
|
+
try {
|
|
616
|
+
const parsed = JSON.parse(text);
|
|
617
|
+
if (parsed?.error) detail = parsed.error;
|
|
618
|
+
} catch {
|
|
619
|
+
}
|
|
620
|
+
throw new Error(`kosa8 host error (${res.status}) on exec in ${sandbox.id}: ${detail}`);
|
|
621
|
+
}
|
|
622
|
+
return JSON.parse(text);
|
|
94
623
|
}
|
|
95
624
|
function createBody(config, options = {}) {
|
|
96
625
|
for (const key of UNSUPPORTED_CREATE_OPTIONS) {
|
|
97
626
|
if (options[key] !== void 0) {
|
|
98
627
|
throw new Error(
|
|
99
|
-
`kosa8 does not support the '${key}' create option. A sandbox's size and image come from its template; pick one with 'templateId' (list them with provider.template.list()).`
|
|
628
|
+
`kosa8 does not support the '${key}' create option. A sandbox's size and image come from its template; pick one with 'templateId' (list them with provider.template.list()), or boot an OCI image with 'image'.`
|
|
100
629
|
);
|
|
101
630
|
}
|
|
102
631
|
}
|
|
103
632
|
const body = {};
|
|
104
633
|
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
634
|
+
if (options.snapshotId !== void 0) {
|
|
635
|
+
for (const key of ["templateId", "image", "region"]) {
|
|
636
|
+
if (options[key] !== void 0) {
|
|
637
|
+
throw new Error(`kosa8 restores a snapshot with its own template, image and region; leave out '${key}' with 'snapshotId'.`);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
body.snapshot = options.snapshotId;
|
|
641
|
+
} else if (options.image !== void 0) {
|
|
642
|
+
body.image = options.image;
|
|
643
|
+
if (options.templateId) body.template = options.templateId;
|
|
644
|
+
} else {
|
|
645
|
+
const template = options.templateId ?? config.template ?? (env?.KOSA8_TEMPLATE || void 0);
|
|
646
|
+
if (template) body.template = template;
|
|
647
|
+
}
|
|
648
|
+
if (options.snapshotId === void 0) {
|
|
649
|
+
const region = typeof options.region === "string" ? options.region : config.region ?? (env?.KOSA8_REGION || void 0);
|
|
650
|
+
if (region) body.region = region;
|
|
651
|
+
}
|
|
109
652
|
if (options.sleepAfterSeconds !== void 0) body.sleep_after_s = options.sleepAfterSeconds;
|
|
110
653
|
if (typeof options.timeout === "number" && options.timeout > 0) {
|
|
111
654
|
body.ttl_s = Math.min(MAX_TTL_S, Math.max(MIN_TTL_S, Math.ceil(options.timeout / 1e3)));
|
|
@@ -114,13 +657,13 @@ function createBody(config, options = {}) {
|
|
|
114
657
|
}
|
|
115
658
|
function execArgv(command, options) {
|
|
116
659
|
let cmd = command;
|
|
117
|
-
if (options?.cwd) cmd = `cd "${(0,
|
|
660
|
+
if (options?.cwd) cmd = `cd "${(0, import_provider2.escapeShellArg)(options.cwd)}" && ${cmd}`;
|
|
118
661
|
if (options?.background) {
|
|
119
|
-
cmd = `nohup sh -c "${(0,
|
|
662
|
+
cmd = `nohup sh -c "${(0, import_provider2.escapeShellArg)(cmd)}" >/dev/null 2>&1 &`;
|
|
120
663
|
} else if (options?.timeout && options.timeout > 0) {
|
|
121
664
|
const seconds = Math.max(1, Math.ceil(options.timeout / 1e3));
|
|
122
|
-
const plain = `sh -c "${(0,
|
|
123
|
-
const marked = `sh -c "${(0,
|
|
665
|
+
const plain = `sh -c "${(0, import_provider2.escapeShellArg)(cmd)}"`;
|
|
666
|
+
const marked = `sh -c "${(0, import_provider2.escapeShellArg)(`(
|
|
124
667
|
${cmd}
|
|
125
668
|
); s=$?; : > "$${DONE_ENV}"; exit $s`)}"`;
|
|
126
669
|
cmd = `if command -v timeout >/dev/null 2>&1 && ${DONE_ENV}=$(mktemp 2>/dev/null); then rm -f "$${DONE_ENV}"; export ${DONE_ENV}; t0=$(date +%s); timeout -s KILL ${seconds} ${marked}; s=$?; if [ $s -eq 137 ] && [ ! -e "$${DONE_ENV}" ] && [ $(( $(date +%s) - t0 )) -ge ${seconds} ]; then s=${TIMEOUT_EXIT}; fi; rm -f "$${DONE_ENV}"; exit $s; else ${plain}; fi`;
|
|
@@ -154,42 +697,67 @@ function execEnv(env) {
|
|
|
154
697
|
}
|
|
155
698
|
function infoStatus(state) {
|
|
156
699
|
if (state === "error") return "error";
|
|
157
|
-
if (state === "running") return "running";
|
|
700
|
+
if (state === "running" || state === "sleeping") return "running";
|
|
158
701
|
return "stopped";
|
|
159
702
|
}
|
|
160
703
|
async function getData(sandbox) {
|
|
161
704
|
const data = await request(sandbox, "GET", sandboxPath(sandbox.id));
|
|
162
705
|
return data?.sandbox ?? null;
|
|
163
706
|
}
|
|
164
|
-
var
|
|
165
|
-
var
|
|
166
|
-
async function
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
707
|
+
var BOOT_POLL_MS = 150;
|
|
708
|
+
var BOOT_TIMEOUT_MS = 5 * 6e4;
|
|
709
|
+
async function waitUntilRunning(sandbox, signal) {
|
|
710
|
+
const deadline = Date.now() + BOOT_TIMEOUT_MS;
|
|
711
|
+
while (sandbox.data.state === "creating") {
|
|
712
|
+
if (Date.now() > deadline) throw new Error(`kosa8 sandbox ${sandbox.id} did not start within ${BOOT_TIMEOUT_MS / 1e3} s`);
|
|
713
|
+
signal?.throwIfAborted();
|
|
714
|
+
await new Promise((r) => setTimeout(r, BOOT_POLL_MS));
|
|
715
|
+
const current = await request(sandbox, "GET", sandboxPath(sandbox.id), void 0, signal);
|
|
716
|
+
if (!current?.sandbox) throw new Error(`kosa8 sandbox ${sandbox.id} was deleted while it started`);
|
|
717
|
+
sandbox.data = current.sandbox;
|
|
171
718
|
}
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
for (const chunk of chunks) {
|
|
182
|
-
await mustSucceed(run, sandbox, `printf '%s' "$KOSA8_CHUNK" | base64 -d >> ${tmp}`, path, { KOSA8_CHUNK: chunk });
|
|
719
|
+
if (sandbox.data.state !== "running") {
|
|
720
|
+
const why = sandbox.data.last_error ? `: ${sandbox.data.last_error}` : "";
|
|
721
|
+
throw new Error(`kosa8 sandbox ${sandbox.id} is ${sandbox.data.state}, not running${why}`);
|
|
722
|
+
}
|
|
723
|
+
if (!sandbox.direct) {
|
|
724
|
+
const r = await request(sandbox, "POST", sandboxPath(sandbox.id, "/direct")).catch(() => null);
|
|
725
|
+
if (isDirect(r?.direct)) {
|
|
726
|
+
sandbox.direct = r.direct;
|
|
727
|
+
preconnect(r.direct.exec_url);
|
|
183
728
|
}
|
|
184
|
-
await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, path);
|
|
185
|
-
} catch (err) {
|
|
186
|
-
await run(sandbox, `rm -f ${tmp}`).catch(() => {
|
|
187
|
-
});
|
|
188
|
-
throw err;
|
|
189
729
|
}
|
|
190
730
|
}
|
|
731
|
+
function toSnapshot(s, createMs) {
|
|
732
|
+
return {
|
|
733
|
+
id: s.id,
|
|
734
|
+
provider: "kosa8",
|
|
735
|
+
createdAt: new Date(s.created_at),
|
|
736
|
+
metadata: {
|
|
737
|
+
name: s.name ?? null,
|
|
738
|
+
sourceInstanceId: s.source_sandbox_id,
|
|
739
|
+
state: s.state,
|
|
740
|
+
template: s.template,
|
|
741
|
+
cpus: s.cpus,
|
|
742
|
+
memMb: s.mem_mb,
|
|
743
|
+
image: s.image ?? null,
|
|
744
|
+
bytes: s.bytes ?? 0,
|
|
745
|
+
region: s.region ?? null,
|
|
746
|
+
...createMs !== void 0 ? { createMs } : {}
|
|
747
|
+
}
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
var SNAPSHOT_CAPABILITIES = {
|
|
751
|
+
scope: "rootfs",
|
|
752
|
+
memory: true,
|
|
753
|
+
destroysSource: false,
|
|
754
|
+
source: "kept",
|
|
755
|
+
fork: true,
|
|
756
|
+
readiness: "immediate"
|
|
757
|
+
};
|
|
758
|
+
var shellFs = (sandbox, run) => new import_provider2.ShellFileSystem((command, options) => run(sandbox, command, options));
|
|
191
759
|
var notAvailable = (what) => new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);
|
|
192
|
-
var
|
|
760
|
+
var provider = (0, import_provider2.defineProvider)({
|
|
193
761
|
name: "kosa8",
|
|
194
762
|
methods: {
|
|
195
763
|
instances: {
|
|
@@ -203,7 +771,17 @@ var kosa8 = (0, import_provider.defineProvider)({
|
|
|
203
771
|
options?.signal
|
|
204
772
|
);
|
|
205
773
|
if (!data?.sandbox) throw new Error("kosa8 API returned no sandbox on create");
|
|
206
|
-
|
|
774
|
+
const sandbox = toSandbox(auth, data.sandbox, data.direct);
|
|
775
|
+
if (sandbox.data.state !== "running") {
|
|
776
|
+
try {
|
|
777
|
+
await waitUntilRunning(sandbox, options?.signal);
|
|
778
|
+
} catch (err) {
|
|
779
|
+
await request(auth, "DELETE", sandboxPath(sandbox.id)).catch(() => {
|
|
780
|
+
});
|
|
781
|
+
throw err;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
return { instance: sandbox, instanceId: sandbox.id };
|
|
207
785
|
},
|
|
208
786
|
getById: async (config, instanceId) => {
|
|
209
787
|
const auth = resolveConfig(config);
|
|
@@ -223,14 +801,22 @@ var kosa8 = (0, import_provider.defineProvider)({
|
|
|
223
801
|
const start = Date.now();
|
|
224
802
|
const body = execBody(command, options);
|
|
225
803
|
const signal = options?.timeout && options.timeout > 0 && !options.background ? AbortSignal.timeout(options.timeout + 3e4) : void 0;
|
|
226
|
-
const data = await request(sandbox, "POST", sandboxPath(sandbox.id, "/exec"), body, signal);
|
|
804
|
+
const data = await runDirect(sandbox, body, signal) ?? await request(sandbox, "POST", sandboxPath(sandbox.id, "/exec"), body, signal);
|
|
227
805
|
if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);
|
|
228
|
-
|
|
806
|
+
const result = {
|
|
229
807
|
stdout: data.stdout ?? "",
|
|
230
808
|
stderr: data.stderr ?? "",
|
|
231
809
|
exitCode: Number.isInteger(data.exit) ? data.exit : -1,
|
|
232
810
|
durationMs: Date.now() - start
|
|
233
811
|
};
|
|
812
|
+
if (typeof data.stdout_truncated === "boolean" || typeof data.stderr_truncated === "boolean") {
|
|
813
|
+
result.stdoutTruncated = data.stdout_truncated === true;
|
|
814
|
+
result.stderrTruncated = data.stderr_truncated === true;
|
|
815
|
+
result.truncated = result.stdoutTruncated || result.stderrTruncated;
|
|
816
|
+
}
|
|
817
|
+
if (typeof data.stdout_bytes === "number") result.stdoutBytes = data.stdout_bytes;
|
|
818
|
+
if (typeof data.stderr_bytes === "number") result.stderrBytes = data.stderr_bytes;
|
|
819
|
+
return result;
|
|
234
820
|
},
|
|
235
821
|
getInfo: async (sandbox) => {
|
|
236
822
|
const current = await getData(sandbox) ?? { ...sandbox.data, state: "deleted" };
|
|
@@ -284,17 +870,43 @@ var kosa8 = (0, import_provider.defineProvider)({
|
|
|
284
870
|
if (data.sandbox) sandbox.data = data.sandbox;
|
|
285
871
|
},
|
|
286
872
|
getInstance: (sandbox) => sandbox,
|
|
287
|
-
//
|
|
288
|
-
//
|
|
873
|
+
// File content straight to the sandbox's host with the direct token, else through the API's
|
|
874
|
+
// file stream, else (an older host) exec (files.ts); the rest are single shell commands.
|
|
289
875
|
filesystem: {
|
|
290
|
-
readFile: (sandbox, path, run) =>
|
|
291
|
-
writeFile: (sandbox, path, content, run) =>
|
|
876
|
+
readFile: (sandbox, path, run) => readFileNative(sandbox, path, run, directFiles(sandbox)),
|
|
877
|
+
writeFile: (sandbox, path, content, run) => writeFileNative(sandbox, path, content, run, directFiles(sandbox)),
|
|
292
878
|
mkdir: (sandbox, path, run) => shellFs(sandbox, run).mkdir(path),
|
|
293
879
|
readdir: (sandbox, path, run) => shellFs(sandbox, run).readdir(path),
|
|
294
880
|
exists: (sandbox, path, run) => shellFs(sandbox, run).exists(path),
|
|
295
881
|
remove: (sandbox, path, run) => shellFs(sandbox, run).remove(path)
|
|
296
882
|
}
|
|
297
883
|
},
|
|
884
|
+
snapshot: {
|
|
885
|
+
capabilities: SNAPSHOT_CAPABILITIES,
|
|
886
|
+
// POST /v1/sandboxes/{id}/snapshots: the VM saved as it is now, memory and disk; it keeps running.
|
|
887
|
+
create: async (config, instanceId, options) => {
|
|
888
|
+
const auth = resolveConfig(config);
|
|
889
|
+
const name = typeof options?.name === "string" && SNAPSHOT_NAME.test(options.name) ? options.name : void 0;
|
|
890
|
+
const data = await request(
|
|
891
|
+
auth,
|
|
892
|
+
"POST",
|
|
893
|
+
sandboxPath(instanceId, "/snapshots"),
|
|
894
|
+
name ? { name } : {}
|
|
895
|
+
);
|
|
896
|
+
if (!data?.snapshot) throw new Error(`kosa8 sandbox ${instanceId} not found`);
|
|
897
|
+
return toSnapshot(data.snapshot, typeof data.ms === "number" ? data.ms : null);
|
|
898
|
+
},
|
|
899
|
+
list: async (config) => {
|
|
900
|
+
const auth = resolveConfig(config);
|
|
901
|
+
const data = await request(auth, "GET", "/v1/snapshots");
|
|
902
|
+
return (data?.snapshots ?? []).map((s) => toSnapshot(s));
|
|
903
|
+
},
|
|
904
|
+
// A snapshot that is already gone answers 404, which request() returns as null.
|
|
905
|
+
delete: async (config, snapshotId) => {
|
|
906
|
+
const auth = resolveConfig(config);
|
|
907
|
+
await request(auth, "DELETE", `/v1/snapshots/${encodeURIComponent(snapshotId)}`);
|
|
908
|
+
}
|
|
909
|
+
},
|
|
298
910
|
template: {
|
|
299
911
|
create: async () => {
|
|
300
912
|
throw notAvailable("creating templates (templates are offered by the hosts)");
|
|
@@ -310,13 +922,22 @@ var kosa8 = (0, import_provider.defineProvider)({
|
|
|
310
922
|
}
|
|
311
923
|
}
|
|
312
924
|
});
|
|
925
|
+
var kosa8 = (config) => {
|
|
926
|
+
try {
|
|
927
|
+
preconnect(resolveConfig(config).baseUrl);
|
|
928
|
+
} catch {
|
|
929
|
+
}
|
|
930
|
+
return provider(config);
|
|
931
|
+
};
|
|
313
932
|
var index_default = kosa8;
|
|
314
933
|
// Annotate the CommonJS export names for ESM import in node:
|
|
315
934
|
0 && (module.exports = {
|
|
316
935
|
MAX_EXEC_BODY_BYTES,
|
|
317
936
|
SCRIPT_ENV,
|
|
937
|
+
SNAPSHOT_CAPABILITIES,
|
|
318
938
|
WRITE_CHUNK_CHARS,
|
|
319
939
|
createBody,
|
|
940
|
+
directFiles,
|
|
320
941
|
execArgv,
|
|
321
942
|
execBody,
|
|
322
943
|
kosa8,
|