sandcovery 0.5.0 → 0.6.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.
@@ -1,8 +1,14 @@
1
- import { Bn as toMillis, Bt as retry, Cn as ClockRef, En as currentTimeMillis$1, Kt as suspend, Ln as TaggedError, Mr as hasProperty, Rn as millis, St as flatMap, Yt as tapError, bt as fail, ht as catchTag, nn as void_, on as spaced, ot as acquireUseRelease, pt as catchDefect, qt as sync, sn as upTo, vt as die, zn as seconds } from "./Schema-fLas6rbA.mjs";
2
- import { D as CARD_FEE_TERMS, M as NO_MARKUP_TERMS, O as CREDIT_PURCHASE_MAX_MICRO_USD, _ as SandboxStatus, c as SpendLimit, j as MICRO_USD_PER_DOLLAR, k as CREDIT_PURCHASE_MIN_MICRO_USD, o as KeyKind, x as ProviderSort, y as DEFAULT_SLUG } from "./origin-5maEGWRg.mjs";
1
+ import { Bn as TaggedError, Br as isString, Ct as fail, E as decodeUnknownSync, En as ClockRef, Hn as seconds, Ir as hasProperty, Jn as isSuccess, O as fromJsonString, Qt as tapError, Tt as flatMap, Un as toMillis, Ut as retry, Vn as millis, Xt as sync, Yn as try_, Yt as suspend, _ as String$1, an as void_, ar as getOrThrowWith, cr as isSome, g as Record, gt as catchDefect, h as Number$1, kn as currentTimeMillis$1, ln as spaced, lt as acquireUseRelease, m as NullOr, n as Boolean, rr as getOrElse, sr as isNone, t as ArraySchema, u as Literals, un as upTo, ur as map, v as Struct, vt as catchTag, w as decodeUnknownOption, xt as die } from "./Schema-CoX0a2_o.mjs";
2
+ import { A as NO_MARKUP_TERMS, B as DEFAULT_SLUG, C as AUTO_TOP_UP_THRESHOLD_MIN_MICRO_USD, E as CREDIT_PURCHASE_MIN_MICRO_USD, F as Unauthorized, H as Forbidden, I as NotFound, P as Unsupported, S as AUTO_TOP_UP_THRESHOLD_MAX_MICRO_USD, T as CREDIT_PURCHASE_MAX_MICRO_USD, U as Conflict, V as ProviderSort, _ as KeyKind, h as SANDCOVERY_X_HANDLE, k as MICRO_USD_PER_DOLLAR, l as MONTH_TEXT, t as Sandcovery, v as SpendLimit, w as CARD_FEE_TERMS, z as SandboxStatus } from "./src-lrpT0LG_.mjs";
3
+ import { WebSocket } from "node:http";
4
+ import net from "node:net";
5
+ import readline from "node:readline";
6
+ import { spawn } from "node:child_process";
7
+ import crypto$1, { createHash } from "node:crypto";
8
+ import { once } from "node:events";
3
9
  import fs from "node:fs";
4
10
  import path from "node:path";
5
- import crypto from "node:crypto";
11
+ import { text } from "node:stream/consumers";
6
12
  import os from "node:os";
7
13
  // ../../node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/Clock.js
8
14
  /**
@@ -85,6 +91,328 @@ const Clock = ClockRef;
85
91
  * @since 2.0.0
86
92
  */
87
93
  const currentTimeMillis = currentTimeMillis$1;
94
+ // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/function/noop.mjs
95
+ /**
96
+ * A no-operation function that does nothing.
97
+ * This can be used as a placeholder or default function.
98
+ *
99
+ * @example
100
+ * noop(); // Does nothing
101
+ *
102
+ * @returns This function does not return anything.
103
+ */
104
+ function noop() {}
105
+ // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/math/clamp.mjs
106
+ /**
107
+ * Clamps a number within the specified bounds.
108
+ *
109
+ * This function takes a number and one or two bounds, and returns the number clamped within the specified bounds.
110
+ * If only one bound is provided, it returns the minimum of the value and the bound.
111
+ *
112
+ * @param value - The number to clamp.
113
+ * @param bound1 - The minimum bound to clamp the number, or the maximum bound if bound2 is not provided.
114
+ * @param [bound2] - The maximum bound to clamp the number. If not provided, the function will only consider bound1 as the upper limit.
115
+ * @returns The clamped number within the specified bounds.
116
+ *
117
+ * @example
118
+ * const result1 = clamp(10, 5); // result1 will be 5, as 10 is clamped to the bound 5
119
+ * const result2 = clamp(10, 5, 15); // result2 will be 10, as it is within the bounds 5 and 15
120
+ * const result3 = clamp(2, 5, 15); // result3 will be 5, as 2 is clamped to the lower bound 5
121
+ * const result4 = clamp(20, 5, 15); // result4 will be 15, as 20 is clamped to the upper bound 15
122
+ */
123
+ function clamp(value, bound1, bound2) {
124
+ if (bound2 == null) return Math.min(value, bound1);
125
+ return Math.min(Math.max(value, bound1), bound2);
126
+ }
127
+ // src/cli/detached.ts
128
+ const READY = "ready\n";
129
+ const PRIVATE_DIRECTORY_MODE = 448;
130
+ const PRIVATE_SOCKET_MODE = 384;
131
+ const TERMINAL_ERRORS = [
132
+ NotFound,
133
+ Unauthorized,
134
+ Forbidden,
135
+ Conflict,
136
+ Unsupported
137
+ ];
138
+ const decodeUnserved = decodeUnknownOption(Struct({ code: Literals([
139
+ "ECONNREFUSED",
140
+ "ECONNRESET",
141
+ "ENOENT"
142
+ ]) }));
143
+ const isTerminal = (cause) => TERMINAL_ERRORS.some((kind) => cause instanceof kind);
144
+ const socketOf = ({ name, settingsFile }) => {
145
+ const directory = path.dirname(settingsFile);
146
+ if (process.platform !== "win32") return path.join(directory, `${name}.sock`);
147
+ const digest = createHash("sha256").update(directory).digest("hex");
148
+ return String.raw`\\.\pipe\sandcovery-${name}-${digest.slice(0, 16)}`;
149
+ };
150
+ const answers = async (socketPath) => {
151
+ const socket = net.connect(socketPath);
152
+ try {
153
+ await once(socket, "connect");
154
+ return true;
155
+ } catch (error) {
156
+ if (isSome(decodeUnserved(error))) return false;
157
+ throw error;
158
+ } finally {
159
+ socket.destroy();
160
+ }
161
+ };
162
+ const listened = async (server, socketPath) => {
163
+ const { promise, resolve } = Promise.withResolvers();
164
+ server.once("error", resolve);
165
+ server.listen(socketPath, () => {
166
+ server.off("error", resolve);
167
+ resolve(void 0);
168
+ });
169
+ return await promise;
170
+ };
171
+ const servedAt = async (server, socketPath) => {
172
+ const windows = process.platform === "win32";
173
+ if (!windows) {
174
+ const directory = path.dirname(socketPath);
175
+ fs.mkdirSync(directory, {
176
+ mode: PRIVATE_DIRECTORY_MODE,
177
+ recursive: true
178
+ });
179
+ fs.chmodSync(directory, PRIVATE_DIRECTORY_MODE);
180
+ }
181
+ const failure = await listened(server, socketPath);
182
+ if (failure === void 0) {
183
+ if (!windows) fs.chmodSync(socketPath, PRIVATE_SOCKET_MODE);
184
+ return true;
185
+ }
186
+ if (failure.code !== "EADDRINUSE" || windows || await answers(socketPath)) return false;
187
+ fs.rmSync(socketPath, { force: true });
188
+ return await servedAt(server, socketPath);
189
+ };
190
+ const spawned = async ({ entry, env }) => {
191
+ const child = spawn(process.execPath, [entry], {
192
+ detached: true,
193
+ env: {
194
+ ...process.env,
195
+ ...env
196
+ },
197
+ stdio: [
198
+ "ignore",
199
+ "pipe",
200
+ "ignore"
201
+ ]
202
+ });
203
+ try {
204
+ await Promise.race([once(child.stdout, "data"), once(child, "exit")]);
205
+ } finally {
206
+ child.stdout.destroy();
207
+ child.unref();
208
+ }
209
+ };
210
+ const servedOrSpawned = async ({ attempt, entry, env }) => {
211
+ try {
212
+ return await attempt();
213
+ } catch (error) {
214
+ if (isNone(decodeUnserved(error))) throw error;
215
+ await spawned({
216
+ entry,
217
+ env
218
+ });
219
+ return await attempt();
220
+ }
221
+ };
222
+ // src/cli/kubectl-idle.ts
223
+ const IDLE_WATCHER_ENV = "__SANDCOVERY_KUBECTL_IDLE";
224
+ const IDLE_MS = 9e5;
225
+ const HEARTBEAT_MS = 6e4;
226
+ const DESTROY_TIMEOUT_MS = 3e4;
227
+ const REFUSED_STATUSES = /* @__PURE__ */ new Set([
228
+ 400,
229
+ 401,
230
+ 403,
231
+ 404,
232
+ 409,
233
+ 410,
234
+ 422
235
+ ]);
236
+ const decodeWatcher = decodeUnknownSync(fromJsonString(Struct({
237
+ idleMs: Number$1,
238
+ socketPath: String$1
239
+ })));
240
+ const decodeHold = decodeUnknownOption(fromJsonString(Struct({ origin: String$1 })));
241
+ const decodeAnswered = decodeUnknownOption(Struct({ cause: Struct({ status: Number$1 }) }));
242
+ const decodeCluster = decodeUnknownOption(fromJsonString(Struct({
243
+ expires_at: String$1,
244
+ key: String$1,
245
+ sandbox: String$1
246
+ })));
247
+ const idleSocket = (settingsFile) => socketOf({
248
+ name: "kubectl-idle",
249
+ settingsFile
250
+ });
251
+ const statusOf$1 = (failure) => getOrElse(map(decodeAnswered(failure), ({ cause }) => cause.status), () => 0);
252
+ const refused = (failure) => isTerminal(failure) || REFUSED_STATUSES.has(statusOf$1(failure));
253
+ const deadlinesOf = ({ cluster, destroying, due, holders }) => cluster === null ? [] : [cluster.expiresAt, ...holders === 0 && destroying === null ? [due] : []];
254
+ const ended = async ({ cluster, origin }) => {
255
+ try {
256
+ await new Sandcovery({
257
+ apiKey: cluster.key,
258
+ baseUrl: origin
259
+ }).sandboxes.destroy(cluster.sandbox, { signal: AbortSignal.timeout(DESTROY_TIMEOUT_MS) });
260
+ return true;
261
+ } catch (error) {
262
+ if (!(error instanceof Error)) throw error;
263
+ return refused(error);
264
+ }
265
+ };
266
+ const destroyed = async ({ entry, origin, settle }) => {
267
+ const { cluster } = entry;
268
+ if (cluster !== null && await ended({
269
+ cluster,
270
+ origin
271
+ })) {
272
+ if (entry.cluster?.sandbox === cluster.sandbox) entry.cluster = null;
273
+ } else entry.due = Date.now() + HEARTBEAT_MS;
274
+ entry.destroying = null;
275
+ settle();
276
+ };
277
+ const attached = (entry, line) => {
278
+ const cluster = decodeCluster(line);
279
+ if (isNone(cluster)) return false;
280
+ const { expires_at, key, sandbox } = cluster.value;
281
+ const expiresAt = Date.parse(expires_at);
282
+ if (Number.isNaN(expiresAt)) return false;
283
+ entry.cluster = {
284
+ expiresAt,
285
+ key,
286
+ sandbox
287
+ };
288
+ return true;
289
+ };
290
+ const watchIdle = async (config) => {
291
+ const { idleMs, socketPath } = decodeWatcher(config);
292
+ const watched = /* @__PURE__ */ new Map();
293
+ const listener = net.createServer();
294
+ const state = {
295
+ connections: 0,
296
+ timer: null
297
+ };
298
+ const check = () => {
299
+ const now = Date.now();
300
+ if (state.timer !== null) clearTimeout(state.timer);
301
+ for (const [origin, entry] of watched) {
302
+ if (entry.cluster !== null && now >= entry.cluster.expiresAt) entry.cluster = null;
303
+ if (entry.cluster !== null && entry.holders === 0 && entry.destroying === null && now >= entry.due) entry.destroying = destroyed({
304
+ entry,
305
+ origin,
306
+ settle: check
307
+ });
308
+ if (entry.cluster === null && entry.holders === 0 && entry.destroying === null) watched.delete(origin);
309
+ }
310
+ if (state.connections === 0 && watched.size === 0) {
311
+ listener.close();
312
+ return;
313
+ }
314
+ const next = Math.min(now + HEARTBEAT_MS, ...[...watched.values()].flatMap(deadlinesOf));
315
+ state.timer = setTimeout(check, clamp(next - now, 0, HEARTBEAT_MS));
316
+ };
317
+ const held = async (connection, origin) => {
318
+ const entry = watched.get(origin) ?? {
319
+ cluster: null,
320
+ destroying: null,
321
+ due: Date.now() + idleMs,
322
+ holders: 0
323
+ };
324
+ entry.holders += 1;
325
+ watched.set(origin, entry);
326
+ await entry.destroying;
327
+ connection.write(READY);
328
+ return entry;
329
+ };
330
+ listener.on("connection", (connection) => {
331
+ const hold = { entry: null };
332
+ const lines = readline.createInterface({ input: connection });
333
+ state.connections += 1;
334
+ connection.on("error", noop);
335
+ const received = async (line) => {
336
+ if (hold.entry !== null) {
337
+ if (!attached(await hold.entry, line)) connection.destroy();
338
+ return;
339
+ }
340
+ const asked = decodeHold(line);
341
+ if (isNone(asked)) {
342
+ connection.destroy();
343
+ return;
344
+ }
345
+ hold.entry = held(connection, asked.value.origin);
346
+ };
347
+ const released = async () => {
348
+ const entry = await hold.entry;
349
+ state.connections -= 1;
350
+ lines.close();
351
+ if (entry !== null) {
352
+ entry.holders -= 1;
353
+ entry.due = Date.now() + idleMs;
354
+ }
355
+ check();
356
+ };
357
+ lines.on("line", (line) => {
358
+ received(line);
359
+ });
360
+ connection.once("close", () => {
361
+ released();
362
+ });
363
+ });
364
+ const serving = await servedAt(listener, socketPath);
365
+ process.stdout.write(READY);
366
+ if (serving) state.timer = setTimeout(check, HEARTBEAT_MS);
367
+ };
368
+ const connected = async (socketPath) => {
369
+ const socket = net.connect(socketPath);
370
+ const { promise, reject, resolve } = Promise.withResolvers();
371
+ socket.once("connect", () => {
372
+ resolve(socket);
373
+ });
374
+ socket.once("error", reject);
375
+ return await promise;
376
+ };
377
+ const readied = async (socket) => {
378
+ const { promise, reject, resolve } = Promise.withResolvers();
379
+ socket.once("data", () => {
380
+ resolve(null);
381
+ });
382
+ socket.once("close", () => {
383
+ reject(/* @__PURE__ */ new Error("The idle watcher stopped before it answered."));
384
+ });
385
+ await promise;
386
+ };
387
+ const holdCluster = async ({ entry, origin, settingsFile }) => {
388
+ const socketPath = idleSocket(settingsFile);
389
+ const socket = await servedOrSpawned({
390
+ attempt: async () => await connected(socketPath),
391
+ entry,
392
+ env: { [IDLE_WATCHER_ENV]: JSON.stringify({
393
+ idleMs: IDLE_MS,
394
+ socketPath
395
+ }) }
396
+ });
397
+ socket.on("error", noop);
398
+ const ready = readied(socket);
399
+ socket.write(`${JSON.stringify({ origin })}\n`);
400
+ try {
401
+ await ready;
402
+ } catch (error) {
403
+ socket.destroy();
404
+ throw error;
405
+ }
406
+ return {
407
+ attach: (cluster) => {
408
+ socket.write(`${JSON.stringify(cluster)}\n`);
409
+ },
410
+ release: () => {
411
+ socket.end();
412
+ socket.unref();
413
+ }
414
+ };
415
+ };
88
416
  // ../cli-core/src/canceled.ts
89
417
  var Canceled = class extends TaggedError("Canceled") {};
90
418
  // ../cli-core/src/failure.ts
@@ -136,11 +464,13 @@ const reasons = {
136
464
  missing_key: "missing_input",
137
465
  missing_path: "missing_input",
138
466
  missing_port: "missing_input",
467
+ missing_process: "missing_input",
139
468
  missing_provider: "missing_input",
140
469
  missing_query: "missing_input",
141
470
  missing_run: "missing_input",
142
471
  missing_sandbox: "missing_input",
143
472
  missing_site: "missing_input",
473
+ missing_url: "missing_input",
144
474
  missing_value: "missing_input",
145
475
  mode_not_entitled: "conflict",
146
476
  network_error: "network",
@@ -190,17 +520,6 @@ const isWordCharacter = (character) => isDigit(character) || isUpper(character)
190
520
  const consistsOf = (text, allowed) => text !== "" && text.split("").every(allowed);
191
521
  const isDigits = (text) => consistsOf(text, isDigit);
192
522
  const codePoints = (text) => Array.from(text, (point) => point);
193
- // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/function/noop.mjs
194
- /**
195
- * A no-operation function that does nothing.
196
- * This can be used as a placeholder or default function.
197
- *
198
- * @example
199
- * noop(); // Does nothing
200
- *
201
- * @returns This function does not return anything.
202
- */
203
- function noop() {}
204
523
  // ../cli-core/src/sanitize.ts
205
524
  const ESC = 27;
206
525
  const BEL = 7;
@@ -752,7 +1071,7 @@ const writePrivateFile = ({ file, text }) => {
752
1071
  mode: 448,
753
1072
  recursive: true
754
1073
  });
755
- const pending = path.join(directory, `.${path.basename(file)}.${crypto.randomBytes(8).toString("hex")}.tmp`);
1074
+ const pending = path.join(directory, `.${path.basename(file)}.${crypto$1.randomBytes(8).toString("hex")}.tmp`);
756
1075
  fs.writeFileSync(pending, text, {
757
1076
  flag: "wx",
758
1077
  mode: 384
@@ -804,15 +1123,142 @@ const withFileLock = ({ bin, file, work }) => {
804
1123
  }), () => work, (own) => removeIf(lock, sameAs(own)));
805
1124
  };
806
1125
  // package.json
807
- var version = "0.5.0";
1126
+ var version = "0.6.0";
1127
+ // ../format/src/display.ts
1128
+ const LOCALE = "en-US";
1129
+ const UTC = "UTC";
1130
+ new Intl.DateTimeFormat(LOCALE, {
1131
+ day: "numeric",
1132
+ month: "short",
1133
+ timeZone: UTC,
1134
+ year: "numeric"
1135
+ });
1136
+ new Intl.DateTimeFormat(LOCALE, {
1137
+ day: "numeric",
1138
+ month: "long",
1139
+ timeZone: UTC,
1140
+ year: "numeric"
1141
+ });
1142
+ new Intl.DateTimeFormat(LOCALE, {
1143
+ hour: "numeric",
1144
+ minute: "2-digit",
1145
+ timeZone: UTC,
1146
+ timeZoneName: "short"
1147
+ });
1148
+ new Intl.DateTimeFormat(LOCALE, {
1149
+ month: "long",
1150
+ timeZone: UTC,
1151
+ year: "numeric"
1152
+ });
1153
+ new Intl.DateTimeFormat(LOCALE, {
1154
+ day: "numeric",
1155
+ month: "short",
1156
+ timeZone: UTC
1157
+ });
1158
+ new Intl.DateTimeFormat(LOCALE, {
1159
+ day: "numeric",
1160
+ month: "long",
1161
+ timeZone: UTC
1162
+ });
1163
+ const monthName = new Intl.DateTimeFormat(LOCALE, {
1164
+ month: "long",
1165
+ timeZone: UTC
1166
+ });
1167
+ Array.from({ length: 12 }, (_, month) => monthName.format(Date.UTC(2e3, month)));
1168
+ new Intl.DateTimeFormat(LOCALE, {
1169
+ day: "numeric",
1170
+ hour: "numeric",
1171
+ minute: "2-digit",
1172
+ month: "short",
1173
+ timeZone: "America/New_York",
1174
+ timeZoneName: "short",
1175
+ year: "numeric"
1176
+ });
1177
+ new Intl.DateTimeFormat(LOCALE, {
1178
+ day: "2-digit",
1179
+ hour: "2-digit",
1180
+ hourCycle: "h23",
1181
+ minute: "2-digit",
1182
+ month: "2-digit",
1183
+ timeZoneName: "short",
1184
+ year: "numeric"
1185
+ });
1186
+ const moneyFormats = {
1187
+ exact: new Intl.NumberFormat(LOCALE, {
1188
+ currency: "USD",
1189
+ maximumFractionDigits: 2,
1190
+ minimumFractionDigits: 2,
1191
+ style: "currency"
1192
+ }),
1193
+ signed: new Intl.NumberFormat(LOCALE, {
1194
+ currency: "USD",
1195
+ maximumFractionDigits: 2,
1196
+ minimumFractionDigits: 2,
1197
+ signDisplay: "exceptZero",
1198
+ style: "currency"
1199
+ }),
1200
+ subcent: new Intl.NumberFormat(LOCALE, {
1201
+ currency: "USD",
1202
+ maximumSignificantDigits: 3,
1203
+ style: "currency"
1204
+ }),
1205
+ trimmed: new Intl.NumberFormat(LOCALE, {
1206
+ currency: "USD",
1207
+ style: "currency",
1208
+ trailingZeroDisplay: "stripIfInteger"
1209
+ }),
1210
+ whole: new Intl.NumberFormat(LOCALE, {
1211
+ currency: "USD",
1212
+ maximumFractionDigits: 0,
1213
+ style: "currency"
1214
+ })
1215
+ };
1216
+ const formatMoney = ({ cents, style }) => moneyFormats[style].format(cents / 100);
1217
+ const countFormats = {
1218
+ compact: new Intl.NumberFormat(LOCALE, {
1219
+ maximumFractionDigits: 1,
1220
+ notation: "compact"
1221
+ }),
1222
+ whole: new Intl.NumberFormat(LOCALE, { maximumFractionDigits: 0 })
1223
+ };
1224
+ const formatCount = ({ count, style = "whole" }) => countFormats[style].format(count);
1225
+ const plural = new Intl.PluralRules(LOCALE);
1226
+ const counted = ({ count, one, other }) => `${formatCount({ count })} ${plural.select(count) === "one" ? one : other}`;
1227
+ const unitFormat = ({ unit }) => new Intl.NumberFormat(LOCALE, {
1228
+ style: "unit",
1229
+ unit,
1230
+ unitDisplay: "long"
1231
+ });
1232
+ unitFormat({ unit: "hour" }), unitFormat({ unit: "minute" }), unitFormat({ unit: "month" }), unitFormat({ unit: "second" });
1233
+ const percentFormats = {
1234
+ rate: new Intl.NumberFormat(LOCALE, {
1235
+ maximumFractionDigits: 2,
1236
+ minimumFractionDigits: 2,
1237
+ style: "percent"
1238
+ }),
1239
+ share: new Intl.NumberFormat(LOCALE, {
1240
+ maximumFractionDigits: 1,
1241
+ minimumFractionDigits: 1,
1242
+ style: "percent"
1243
+ }),
1244
+ whole: new Intl.NumberFormat(LOCALE, {
1245
+ maximumFractionDigits: 0,
1246
+ style: "percent"
1247
+ })
1248
+ };
1249
+ const formatPercent = ({ rate, style }) => percentFormats[style].format(rate);
1250
+ // ../sandcovery-contract/src/problem-report-limits.ts
1251
+ const PROBLEM_REPORT_MAX = 2e3;
808
1252
  // src/cli/spec.ts
809
1253
  const BIN = "sandcovery";
810
1254
  const SETUP_MARK = "# added by sandcovery setup";
811
1255
  const NULLABLE_TEXT = "string | null";
812
1256
  const NULLABLE_NUMBER = "number | null";
1257
+ const NULLABLE_OBJECT = "object | null";
813
1258
  const SANDBOX = "<SANDBOX>";
814
1259
  const SPEND_LIMIT = "spend-limit";
815
1260
  const NEEDS_MANAGEMENT = "Needs a management key.";
1261
+ const NEEDS_PERSON = "Needs a management key, which acts for the owner who minted it, or a login.";
816
1262
  const CLEARABLE = {
817
1263
  "expires-at": "expires_at",
818
1264
  "max-concurrent": "max_concurrent_sandboxes",
@@ -1226,6 +1672,30 @@ const sandboxesExec = {
1226
1672
  "2>&1"
1227
1673
  ],
1228
1674
  summary: "Start a server that keeps running after the CLI exits"
1675
+ },
1676
+ {
1677
+ argv: [
1678
+ "sandboxes",
1679
+ "exec",
1680
+ SANDBOX,
1681
+ "--interactive",
1682
+ "--tty",
1683
+ "--",
1684
+ "bash"
1685
+ ],
1686
+ summary: "Open a shell in the sandbox"
1687
+ },
1688
+ {
1689
+ argv: [
1690
+ "sandboxes",
1691
+ "exec",
1692
+ SANDBOX,
1693
+ "--interactive",
1694
+ "--",
1695
+ "wc",
1696
+ "-l"
1697
+ ],
1698
+ summary: "Count the lines piped to the CLI"
1229
1699
  }
1230
1700
  ],
1231
1701
  kind: "leaf",
@@ -1234,6 +1704,7 @@ const sandboxesExec = {
1234
1704
  "The command's stdout and stderr stream to this terminal's, and the CLI exits with the command's exit code.",
1235
1705
  "With --json, the CLI waits for the command and prints its stdout, stderr, exit code, and duration as one document.",
1236
1706
  "With --detach, the CLI returns once the provider starts the command, which keeps running until it exits or the sandbox ends, and its output is not kept, so redirect it to a file to read it later. A provider with no detached commands answers unsupported.",
1707
+ "With --interactive, the CLI sends its stdin to the command until stdin ends. With --tty, the command's stdout and stderr, and its stdin with --interactive, sit on a terminal of this terminal's size, and the output reaches this terminal unchanged. Either one runs the command as a process with no timeout that survives a dropped connection; Ctrl-C reaches the command, and a second Ctrl-C without --tty leaves it running and exits the CLI.",
1237
1708
  "The CLI never retries a command, since running it twice may change the sandbox twice."
1238
1709
  ],
1239
1710
  options: [
@@ -1249,13 +1720,21 @@ const sandboxesExec = {
1249
1720
  summary: "Start the command and return at once, leaving it running in the sandbox"
1250
1721
  }),
1251
1722
  env,
1723
+ flag({
1724
+ name: "interactive",
1725
+ summary: "Send this CLI's stdin to the command"
1726
+ }),
1252
1727
  json,
1253
1728
  {
1254
1729
  hint: "<SECONDS>",
1255
1730
  kind: "value",
1256
1731
  name: "timeout",
1257
1732
  summary: "Seconds after which the provider stops the command"
1258
- }
1733
+ },
1734
+ flag({
1735
+ name: "tty",
1736
+ summary: "Run the command on a terminal, as ssh -t does"
1737
+ })
1259
1738
  ],
1260
1739
  result: [
1261
1740
  {
@@ -1349,6 +1828,47 @@ const sandboxesPortsInspect = {
1349
1828
  ],
1350
1829
  summary: "Print a port's preview URL"
1351
1830
  };
1831
+ const sandboxesProcessesInspect = {
1832
+ arguments: [sandboxArgument("show a process"), required({
1833
+ message: "Can't show a process without its ID.",
1834
+ name: "process",
1835
+ reason: "missing_process",
1836
+ summary: "Process ID, such as proc_ and a UUID"
1837
+ })],
1838
+ examples: [{
1839
+ argv: [
1840
+ "sandboxes",
1841
+ "processes",
1842
+ "inspect",
1843
+ SANDBOX,
1844
+ "<PROCESS>"
1845
+ ],
1846
+ summary: "Show a process's status and exit code"
1847
+ }],
1848
+ kind: "leaf",
1849
+ name: "inspect",
1850
+ notes: ["A process is running until its command exits, then exited, or lost when the sandbox ended before the process reported an exit."],
1851
+ options: [baseUrl, json],
1852
+ result: [
1853
+ {
1854
+ name: "process.id",
1855
+ type: "string"
1856
+ },
1857
+ {
1858
+ name: "process.status",
1859
+ type: "\"exited\" | \"lost\" | \"running\""
1860
+ },
1861
+ {
1862
+ name: "process.exit_code",
1863
+ type: NULLABLE_NUMBER
1864
+ },
1865
+ {
1866
+ name: "process.signal",
1867
+ type: NULLABLE_TEXT
1868
+ }
1869
+ ],
1870
+ summary: "Show a process"
1871
+ };
1352
1872
  const filesList = {
1353
1873
  arguments: [sandboxArgument("list files"), pathArgument("list files")],
1354
1874
  examples: [{
@@ -1496,11 +2016,13 @@ const docker = {
1496
2016
  notes: [
1497
2017
  "Runs the Docker CLI in a sandbox with every word after docker, streams its stdout and stderr to this terminal's, and exits with its exit code.",
1498
2018
  "The first command starts a sandbox on a provider that runs Docker, as Sandcovery CI runners do, and later commands reuse it until it ends at its TTL, so images, containers, and volumes carry over between commands. sandcovery sandboxes destroy ends it sooner.",
1499
- "build, buildx, builder, and image build first copy the working directory into the sandbox, up to 100 MiB packed, so their relative paths resolve as they do here. Every other path names a file in the sandbox, as with a remote Docker daemon.",
1500
- "compose first copies the Compose project into the sandbox, up to 100 MiB packed: its Compose files and env files, each build context without what .dockerignore leaves out, and each bind-mounted file or directory, under the directory that holds them all. ps, logs, down, and other commands that only read the project copy only the Compose files and env files. The copy keeps what containers wrote there, and a file deleted here stays there. Variables in Compose files come only from .env and --env-file, and absolute and ~ paths name files in the sandbox.",
1501
- "When stdin is not a terminal and docker reads it, as with -i on run or exec without -d, start -i, login --password-stdin, load, import -, build -, or cp -, the command reads stdin to its end and hands it to docker.",
2019
+ "Before docker runs, the command copies the local files it reads into the sandbox at the same absolute paths, up to 100 MiB packed, and runs docker in the same working directory there, so relative and absolute paths resolve as they do here. Those files are the build context of build and bake without what .dockerignore leaves out, the files of a build's -f, --build-context, and --secret, the bind mount sources and env files of run and create, and the file that cp, load -i, or import reads.",
2020
+ "compose copies its Compose files and env files and, for commands that build or start containers, each build context and each bind-mounted file or directory. ps, logs, down, and other commands that only read the project copy only the Compose files and env files. Variables in Compose files come only from .env and --env-file, and ~ in a Compose file names the home folder of the sandbox.",
2021
+ "Only paths under your home folder or the working directory are copied, a symlink arrives as the link itself, and a path through a symlinked folder fails. What containers wrote stays in the sandbox and never comes back here, and a file deleted here since the last copy is deleted there.",
2022
+ "When stdin is not a terminal and docker reads it, as with -i on run or exec without -d, start -i, login --password-stdin, load, import -, build -, or cp -, the command streams stdin to docker as it reads it.",
1502
2023
  "When stdout is not a terminal and docker writes an archive there, as with save or export without -o, cp to -, or build -o -, the archive arrives byte for byte. save and export without -o refuse a terminal, as docker does.",
1503
- "The command gets no terminal and stops after an hour, so docker run -it does not work.",
2024
+ "A TCP port a container publishes answers on the same address and port here, through a process the command starts in the background, until the sandbox ends. A port another program here listens on, or one only an administrator may listen on, stays in the sandbox, and the command warns once.",
2025
+ "docker gets a terminal in the sandbox wherever this command's stdin, stdout, or stderr is one, so docker run -it, docker exec -it, and docker attach work. A command runs until it exits, and the sandbox stays up past its TTL while it runs.",
1504
2026
  "sandcovery-docker takes docker arguments alone, runs them in the same sandbox, and adds nothing to docker output, so alias docker=sandcovery-docker runs docker here."
1505
2027
  ],
1506
2028
  options: [baseUrl],
@@ -1508,6 +2030,54 @@ const docker = {
1508
2030
  result: [],
1509
2031
  summary: "Run a docker command in a sandbox"
1510
2032
  };
2033
+ const kubectl = {
2034
+ arguments: [{
2035
+ name: "args",
2036
+ optional: true,
2037
+ summary: "Arguments for kubectl, every word passed on unchanged, so sandcovery options such as --base-url go before kubectl",
2038
+ variadic: true
2039
+ }],
2040
+ examples: [
2041
+ {
2042
+ argv: [
2043
+ "kubectl",
2044
+ "apply",
2045
+ "--filename",
2046
+ "deployment.yaml"
2047
+ ],
2048
+ summary: "Apply a local manifest to a cluster in a sandbox"
2049
+ },
2050
+ {
2051
+ argv: [
2052
+ "kubectl",
2053
+ "get",
2054
+ "pods"
2055
+ ],
2056
+ summary: "List the pods of that cluster"
2057
+ },
2058
+ {
2059
+ argv: [
2060
+ "kubectl",
2061
+ "port-forward",
2062
+ "deployment/app",
2063
+ "8080:80"
2064
+ ],
2065
+ summary: "Reach a pod on port 8080 of this computer"
2066
+ }
2067
+ ],
2068
+ kind: "leaf",
2069
+ name: "kubectl",
2070
+ notes: [
2071
+ "Runs your own kubectl with every word after kubectl against a one-node Kubernetes cluster in a sandbox, so the output and exit code are kubectl's, local files reach apply -f, and port-forward, exec -it, and logs -f work as they do with a local cluster. kubectl must be on PATH.",
2072
+ "The first command that reaches the cluster starts a 2x4 sandbox on Freestyle, or a 2x8 sandbox on boxd when Freestyle cannot create it, and waits a few minutes for the cluster. Later commands reuse it, so what you applied carries over between commands. It stops 15 minutes after the last command that reached it ends, or at its TTL, whichever comes first, and a command that keeps running, such as port-forward or logs -f, keeps it running. sandcovery sandboxes destroy ends it sooner.",
2073
+ "kubectl reads a kubeconfig the CLI keeps beside its settings, through KUBECONFIG, so --kubeconfig names your own clusters instead. completion, config, help, kustomize, options, plugin, version --client, and --help start no cluster.",
2074
+ "sandcovery-kubectl takes kubectl arguments alone and adds nothing to kubectl output, so alias kubectl=sandcovery-kubectl runs kubectl here."
2075
+ ],
2076
+ options: [baseUrl],
2077
+ passthrough: true,
2078
+ result: [],
2079
+ summary: "Run a kubectl command against a cluster in a sandbox"
2080
+ };
1511
2081
  const setup = {
1512
2082
  arguments: [],
1513
2083
  examples: [{
@@ -1669,6 +2239,14 @@ const sandboxes = {
1669
2239
  name: "ports",
1670
2240
  shortcuts: ["port"],
1671
2241
  summary: "Preview a sandbox's ports"
2242
+ },
2243
+ {
2244
+ children: [sandboxesProcessesInspect],
2245
+ defaultChild: "inspect",
2246
+ kind: "group",
2247
+ name: "processes",
2248
+ shortcuts: ["process"],
2249
+ summary: "Show the processes of a sandbox"
1672
2250
  }
1673
2251
  ],
1674
2252
  kind: "group",
@@ -2073,9 +2651,48 @@ const credentials = {
2073
2651
  {
2074
2652
  name: "offer.remaining_vcpu_seconds",
2075
2653
  type: "number"
2654
+ },
2655
+ {
2656
+ name: "offer.x_post_counted",
2657
+ type: "boolean"
2076
2658
  }
2077
2659
  ],
2078
2660
  summary: "Show the free vCPU-hours offer"
2661
+ },
2662
+ {
2663
+ arguments: [required({
2664
+ message: "Can't count an X post without its URL.",
2665
+ name: "url",
2666
+ reason: "missing_url",
2667
+ summary: "The post's URL on x.com or twitter.com, such as https://x.com/<handle>/status/<id>"
2668
+ })],
2669
+ examples: [{
2670
+ argv: [
2671
+ "credentials",
2672
+ "count-x-post",
2673
+ "https://x.com/you/status/1234567890123456789"
2674
+ ],
2675
+ summary: `Count your post on X that tags @${SANDCOVERY_X_HANDLE} as one key`
2676
+ }],
2677
+ kind: "leaf",
2678
+ name: "count-x-post",
2679
+ notes: [`A post on X that tags @${SANDCOVERY_X_HANDLE} counts as one key toward the free vCPU-hours when the X account linked to your organization's owner wrote it. A repost counts nothing.`, "One post counts per account, and one X account counts for one Sandcovery account only. Needs a management key."],
2680
+ options: [baseUrl, json],
2681
+ result: [
2682
+ {
2683
+ name: "offer.keys_counted",
2684
+ type: "number"
2685
+ },
2686
+ {
2687
+ name: "offer.remaining_vcpu_seconds",
2688
+ type: "number"
2689
+ },
2690
+ {
2691
+ name: "offer.x_post_counted",
2692
+ type: "boolean"
2693
+ }
2694
+ ],
2695
+ summary: "Count an X post toward the free vCPU-hours"
2079
2696
  }
2080
2697
  ],
2081
2698
  defaultChild: "list",
@@ -2103,7 +2720,7 @@ const providers = {
2103
2720
  notes: [
2104
2721
  "Lists each provider with its status, 2x4 price per hour, and median create latency.",
2105
2722
  "A provider Sandcovery does not route to yet shows as Coming Soon.",
2106
- "Coming Soon also marks each figure or fact Sandcovery does not publish, and --json adds every fact with the page it was read from.",
2723
+ "Coming Soon also marks each figure no probe has measured and each fact Sandcovery has not read, and --json adds every fact with the page it was read from.",
2107
2724
  "With --routed, it lists only the providers on the provider board, and --json prints their board entries."
2108
2725
  ],
2109
2726
  options: [
@@ -2295,6 +2912,182 @@ const usage = {
2295
2912
  ],
2296
2913
  summary: "Show usage totals by day, week, month, and in total"
2297
2914
  },
2915
+ {
2916
+ children: [
2917
+ {
2918
+ arguments: [],
2919
+ examples: [{
2920
+ argv: [
2921
+ "usage",
2922
+ "shares",
2923
+ "list"
2924
+ ],
2925
+ summary: "List the live usage shares"
2926
+ }],
2927
+ kind: "leaf",
2928
+ name: "list",
2929
+ notes: [NEEDS_MANAGEMENT],
2930
+ options: [baseUrl, json],
2931
+ result: [
2932
+ {
2933
+ name: "shares",
2934
+ type: "array"
2935
+ },
2936
+ {
2937
+ name: "shares[].id",
2938
+ type: "string"
2939
+ },
2940
+ {
2941
+ name: "shares[].url",
2942
+ type: "string"
2943
+ }
2944
+ ],
2945
+ shortcuts: ["ls"],
2946
+ summary: "List usage shares"
2947
+ },
2948
+ {
2949
+ arguments: [],
2950
+ examples: [{
2951
+ argv: [
2952
+ "usage",
2953
+ "shares",
2954
+ "create"
2955
+ ],
2956
+ summary: "Share this month's usage without its cost"
2957
+ }, {
2958
+ argv: [
2959
+ "usage",
2960
+ "shares",
2961
+ "create",
2962
+ "--period",
2963
+ "total",
2964
+ "--figure",
2965
+ "sandbox_count",
2966
+ "--figure",
2967
+ "vcpu_seconds"
2968
+ ],
2969
+ summary: "Share only the sandboxes and vCPU-hours of all time"
2970
+ }],
2971
+ kind: "leaf",
2972
+ name: "create",
2973
+ notes: [
2974
+ "Reads the usage total of the window now and shares the chosen figures at a new public URL. Anyone with the URL sees them and your Sandcovery username, and nothing else of the organization, until you revoke the share.",
2975
+ "With no --figure, it shares every figure but the estimated cost.",
2976
+ "Needs the saved login of an owner or admin who picked a username in the share dialog on the usage page, since a key names no person."
2977
+ ],
2978
+ options: [
2979
+ baseUrl,
2980
+ {
2981
+ hint: "<FIGURE>",
2982
+ kind: "value",
2983
+ name: "figure",
2984
+ repeat: "append",
2985
+ summary: "Figure to share, such as sandbox_count or vcpu_seconds; repeat for each one"
2986
+ },
2987
+ json,
2988
+ {
2989
+ defaultText: "month",
2990
+ hint: "<PERIOD>",
2991
+ kind: "value",
2992
+ name: "period",
2993
+ summary: "Window to share: day, week, month, or total"
2994
+ }
2995
+ ],
2996
+ result: [
2997
+ {
2998
+ name: "share.id",
2999
+ type: "string"
3000
+ },
3001
+ {
3002
+ name: "share.url",
3003
+ type: "string"
3004
+ },
3005
+ {
3006
+ name: "share.image_url",
3007
+ type: "string"
3008
+ }
3009
+ ],
3010
+ summary: "Share usage at a public URL"
3011
+ },
3012
+ {
3013
+ arguments: [required({
3014
+ message: "Can't revoke a usage share without its ID.",
3015
+ name: "share",
3016
+ reason: "missing_value",
3017
+ summary: "Share ID, such as ush_ and a UUID, as sandcovery usage shares list prints it"
3018
+ })],
3019
+ examples: [{
3020
+ argv: [
3021
+ "usage",
3022
+ "shares",
3023
+ "revoke",
3024
+ "<SHARE>"
3025
+ ],
3026
+ summary: "Revoke a share after a prompt"
3027
+ }, {
3028
+ argv: [
3029
+ "usage",
3030
+ "shares",
3031
+ "revoke",
3032
+ "<SHARE>",
3033
+ "--yes"
3034
+ ],
3035
+ summary: "Revoke it in a script, after a person approved"
3036
+ }],
3037
+ kind: "leaf",
3038
+ name: "revoke",
3039
+ notes: ["Its URL answers 404 at once for everyone who has it.", `It asks first, and needs --yes without a terminal. ${NEEDS_MANAGEMENT}`],
3040
+ options: [
3041
+ baseUrl,
3042
+ json,
3043
+ yes
3044
+ ],
3045
+ result: [{
3046
+ name: "share.id",
3047
+ type: "string"
3048
+ }, {
3049
+ name: "outcome",
3050
+ type: "\"revoked\""
3051
+ }],
3052
+ shortcuts: ["delete", "rm"],
3053
+ summary: "Revoke a usage share"
3054
+ },
3055
+ {
3056
+ arguments: [required({
3057
+ message: "Can't show shared usage without its token.",
3058
+ name: "token",
3059
+ reason: "missing_value",
3060
+ summary: "Token, the 43 characters after /share/ in a share URL"
3061
+ })],
3062
+ examples: [{
3063
+ argv: [
3064
+ "usage",
3065
+ "shares",
3066
+ "inspect",
3067
+ "<TOKEN>"
3068
+ ],
3069
+ summary: "Show what a share URL shows"
3070
+ }],
3071
+ kind: "leaf",
3072
+ name: "inspect",
3073
+ notes: ["Shows the figures a share URL shows to anyone. Needs no key."],
3074
+ options: [baseUrl, json],
3075
+ result: [{
3076
+ name: "usage.period",
3077
+ type: "string"
3078
+ }, {
3079
+ name: "usage.figures",
3080
+ type: "array"
3081
+ }],
3082
+ summary: "Show the usage a share URL shows"
3083
+ }
3084
+ ],
3085
+ defaultChild: "list",
3086
+ kind: "group",
3087
+ name: "shares",
3088
+ shortcuts: ["share"],
3089
+ summary: "Share usage at public URLs"
3090
+ },
2298
3091
  {
2299
3092
  arguments: [],
2300
3093
  examples: [{
@@ -2420,95 +3213,307 @@ const activity = {
2420
3213
  summary: "Read what happened to your sandboxes"
2421
3214
  };
2422
3215
  const billing = {
2423
- children: [{
2424
- arguments: [],
2425
- examples: [{
2426
- argv: ["billing", "inspect"],
2427
- summary: "Show the plan and the credit balance"
2428
- }],
2429
- kind: "leaf",
2430
- name: "inspect",
2431
- notes: [`Shows the plan, the credit balance, and the Pro price. It fails as not found while billing is not set up. ${NEEDS_MANAGEMENT}`],
2432
- options: [baseUrl, json],
2433
- result: [
2434
- {
2435
- name: "billing.plan",
2436
- type: "\"free\" | \"pro\""
2437
- },
2438
- {
2439
- name: "billing.credit_balance_micro_usd",
2440
- type: "number"
2441
- },
2442
- {
2443
- name: "billing.credits_on_sale",
2444
- type: "boolean"
2445
- },
2446
- {
2447
- name: "billing.pro_price",
2448
- type: "object | null"
2449
- }
2450
- ],
2451
- summary: "Show the plan and credits"
2452
- }, {
2453
- arguments: [],
2454
- examples: [{
2455
- argv: [
2456
- "billing",
2457
- "buy-credits",
2458
- "--amount",
2459
- "100"
2460
- ],
2461
- summary: "Start a 100 USD credit purchase"
2462
- }],
2463
- kind: "leaf",
2464
- name: "buy-credits",
2465
- notes: [`Prints the Stripe Checkout page that takes the payment. The credits are the amount less the processing fee of ${CARD_FEE_TERMS}, and arrive once Stripe confirms the payment. ${NEEDS_MANAGEMENT}`],
2466
- options: [
2467
- {
2468
- hint: "<USD>",
2469
- kind: "value",
2470
- name: "amount",
2471
- required: true,
2472
- summary: `Whole US dollars to pay, from ${String(CREDIT_PURCHASE_MIN_MICRO_USD / MICRO_USD_PER_DOLLAR)} to ${String(CREDIT_PURCHASE_MAX_MICRO_USD / MICRO_USD_PER_DOLLAR)}`
2473
- },
2474
- baseUrl,
2475
- json
2476
- ],
2477
- result: [{
2478
- name: "checkout.url",
2479
- type: "string"
2480
- }],
2481
- summary: "Buy credits through Stripe Checkout"
2482
- }],
3216
+ children: [
3217
+ {
3218
+ arguments: [],
3219
+ examples: [{
3220
+ argv: ["billing", "inspect"],
3221
+ summary: "Show the plan and the credit balance"
3222
+ }],
3223
+ kind: "leaf",
3224
+ name: "inspect",
3225
+ notes: [`Shows the plan, the credit balance, the Pro and Enterprise prices, and auto top-up with the reason a failed charge turned it off. It fails as not found while billing is not set up. ${NEEDS_MANAGEMENT}`],
3226
+ options: [baseUrl, json],
3227
+ result: [
3228
+ {
3229
+ name: "billing.auto_top_up",
3230
+ type: "object"
3231
+ },
3232
+ {
3233
+ name: "billing.plan",
3234
+ type: "\"free\" | \"pro\" | \"enterprise\""
3235
+ },
3236
+ {
3237
+ name: "billing.credit_balance_micro_usd",
3238
+ type: "number"
3239
+ },
3240
+ {
3241
+ name: "billing.credits_on_sale",
3242
+ type: "boolean"
3243
+ },
3244
+ {
3245
+ name: "billing.pro_price",
3246
+ type: NULLABLE_OBJECT
3247
+ },
3248
+ {
3249
+ name: "billing.enterprise_price",
3250
+ type: NULLABLE_OBJECT
3251
+ },
3252
+ {
3253
+ name: "billing.github_enterprise",
3254
+ type: "boolean"
3255
+ }
3256
+ ],
3257
+ summary: "Show the plan and credits"
3258
+ },
3259
+ {
3260
+ arguments: [],
3261
+ examples: [{
3262
+ argv: [
3263
+ "billing",
3264
+ "buy-credits",
3265
+ "--amount",
3266
+ "100"
3267
+ ],
3268
+ summary: "Start a 100 USD credit purchase"
3269
+ }],
3270
+ kind: "leaf",
3271
+ name: "buy-credits",
3272
+ notes: [`Prints the Stripe Checkout page that takes the payment. The credits are the amount less the processing fee of ${CARD_FEE_TERMS}, and arrive once Stripe confirms the payment. ${NEEDS_MANAGEMENT}`],
3273
+ options: [
3274
+ {
3275
+ hint: "<USD>",
3276
+ kind: "value",
3277
+ name: "amount",
3278
+ required: true,
3279
+ summary: `Whole US dollars to pay, from ${String(CREDIT_PURCHASE_MIN_MICRO_USD / MICRO_USD_PER_DOLLAR)} to ${String(CREDIT_PURCHASE_MAX_MICRO_USD / MICRO_USD_PER_DOLLAR)}`
3280
+ },
3281
+ baseUrl,
3282
+ json
3283
+ ],
3284
+ result: [{
3285
+ name: "checkout.url",
3286
+ type: "string"
3287
+ }],
3288
+ summary: "Buy credits through Stripe Checkout"
3289
+ },
3290
+ {
3291
+ arguments: [],
3292
+ examples: [{
3293
+ argv: [
3294
+ "billing",
3295
+ "set-auto-top-up",
3296
+ "--amount",
3297
+ "25",
3298
+ "--threshold",
3299
+ "10"
3300
+ ],
3301
+ summary: "Charge 25 USD each time the credit balance falls below 10 USD"
3302
+ }],
3303
+ kind: "leaf",
3304
+ name: "set-auto-top-up",
3305
+ notes: [`While auto top-up is off, prints the Stripe Checkout page that saves a card and then turns auto top-up on with this threshold and amount, starting a fresh run of charges. While it is on, the threshold and amount apply at once. Each time the credit balance falls below the threshold, or a create is refused for credits one top-up covers, the saved card is charged the amount once, and the credit, the amount less the processing fee of ${CARD_FEE_TERMS}, arrives once Stripe confirms the charge. A declined card, a card that asks its holder to authenticate, or any other failed charge turns auto top-up off, and \`billing inspect\` shows why. ${NEEDS_MANAGEMENT}`],
3306
+ options: [
3307
+ {
3308
+ hint: "<USD>",
3309
+ kind: "value",
3310
+ name: "amount",
3311
+ required: true,
3312
+ summary: `Whole US dollars each top-up charges, from ${String(CREDIT_PURCHASE_MIN_MICRO_USD / MICRO_USD_PER_DOLLAR)} to ${String(CREDIT_PURCHASE_MAX_MICRO_USD / MICRO_USD_PER_DOLLAR)}`
3313
+ },
3314
+ {
3315
+ hint: "<USD>",
3316
+ kind: "value",
3317
+ name: "threshold",
3318
+ required: true,
3319
+ summary: `Whole US dollars of credit balance below which a top-up is charged, from ${String(AUTO_TOP_UP_THRESHOLD_MIN_MICRO_USD / MICRO_USD_PER_DOLLAR)} to ${String(AUTO_TOP_UP_THRESHOLD_MAX_MICRO_USD / MICRO_USD_PER_DOLLAR)}, and below the credit one top-up adds`
3320
+ },
3321
+ baseUrl,
3322
+ json
3323
+ ],
3324
+ result: [
3325
+ {
3326
+ name: "auto_top_up.enabled",
3327
+ type: "boolean"
3328
+ },
3329
+ {
3330
+ name: "auto_top_up.amount_micro_usd",
3331
+ type: NULLABLE_NUMBER
3332
+ },
3333
+ {
3334
+ name: "auto_top_up.threshold_micro_usd",
3335
+ type: NULLABLE_NUMBER
3336
+ },
3337
+ {
3338
+ name: "auto_top_up.failure",
3339
+ type: NULLABLE_TEXT
3340
+ },
3341
+ {
3342
+ name: "auto_top_up.failed_at",
3343
+ type: NULLABLE_TEXT
3344
+ },
3345
+ {
3346
+ name: "url",
3347
+ type: NULLABLE_TEXT
3348
+ }
3349
+ ],
3350
+ summary: "Set the auto top-up threshold and amount"
3351
+ },
3352
+ {
3353
+ arguments: [],
3354
+ examples: [{
3355
+ argv: ["billing", "stop-auto-top-up"],
3356
+ summary: "Stop charging the saved card"
3357
+ }],
3358
+ kind: "leaf",
3359
+ name: "stop-auto-top-up",
3360
+ notes: [`Turns auto top-up off, so the saved card is charged no more. A charge Stripe is still processing adds its credit once it succeeds. ${NEEDS_MANAGEMENT}`],
3361
+ options: [baseUrl, json],
3362
+ result: [
3363
+ {
3364
+ name: "auto_top_up.enabled",
3365
+ type: "boolean"
3366
+ },
3367
+ {
3368
+ name: "auto_top_up.amount_micro_usd",
3369
+ type: NULLABLE_NUMBER
3370
+ },
3371
+ {
3372
+ name: "auto_top_up.threshold_micro_usd",
3373
+ type: NULLABLE_NUMBER
3374
+ }
3375
+ ],
3376
+ summary: "Turn auto top-up off"
3377
+ }
3378
+ ],
2483
3379
  defaultChild: "inspect",
2484
3380
  kind: "group",
2485
3381
  name: "billing",
2486
- summary: "Show the plan and buy credits"
3382
+ summary: "Show the plan, buy credits, and set auto top-up"
2487
3383
  };
2488
3384
  const pricing = {
2489
3385
  children: [{
2490
3386
  arguments: [],
2491
3387
  examples: [{
2492
3388
  argv: ["pricing", "inspect"],
2493
- summary: "Show the Pro price and the credit terms"
3389
+ summary: "Show the plan prices and the credit terms"
2494
3390
  }],
2495
3391
  kind: "leaf",
2496
3392
  name: "inspect",
2497
- notes: ["Shows the Pro price, the smallest and largest credit purchase, and the processing fee that comes out of each purchase. It needs no key, and the Pro price reads Not on sale while Pro is not on sale.", NO_MARKUP_TERMS],
3393
+ notes: ["Shows the Pro and Enterprise prices, the smallest and largest credit purchase, and the processing fee that comes out of each purchase. It needs no key, and each price reads Not on sale while its plan is not on sale.", NO_MARKUP_TERMS],
2498
3394
  options: [baseUrl, json],
2499
- result: [{
2500
- name: "pricing.pro_price",
2501
- type: "object | null"
2502
- }, {
2503
- name: "pricing.credits",
2504
- type: "object"
3395
+ result: [
3396
+ {
3397
+ name: "pricing.pro_price",
3398
+ type: NULLABLE_OBJECT
3399
+ },
3400
+ {
3401
+ name: "pricing.enterprise_price",
3402
+ type: NULLABLE_OBJECT
3403
+ },
3404
+ {
3405
+ name: "pricing.credits",
3406
+ type: "object"
3407
+ }
3408
+ ],
3409
+ summary: "Show the plan prices and credit terms"
3410
+ }, {
3411
+ arguments: [],
3412
+ examples: [{
3413
+ argv: [
3414
+ "pricing",
3415
+ "monthly",
3416
+ "--size",
3417
+ "4x8",
3418
+ "--hours-per-day",
3419
+ "24"
3420
+ ],
3421
+ summary: "Price a 4x8 sandbox that runs all month on each provider"
2505
3422
  }],
2506
- summary: "Show the Pro price and credit terms"
3423
+ kind: "leaf",
3424
+ name: "monthly",
3425
+ notes: [`Prices one size on each provider Sandcovery routes to, cheapest first, for a sandbox that runs --hours-per-day hours on every day of ${MONTH_TEXT}, and prints the slug that routes a create to the cheapest. It needs no key and creates nothing.`, NO_MARKUP_TERMS],
3426
+ options: [
3427
+ baseUrl,
3428
+ {
3429
+ defaultText: String(8),
3430
+ hint: "<HOURS>",
3431
+ kind: "value",
3432
+ name: "hours-per-day",
3433
+ summary: `Hours a day the sandbox runs, above 0 and at most ${String(24)}, such as 8 or 0.5`
3434
+ },
3435
+ json,
3436
+ {
3437
+ defaultText: "2x4",
3438
+ hint: "<SIZE>",
3439
+ kind: "value",
3440
+ name: "size",
3441
+ summary: "Size as <vcpu>x<memory_gib>, such as 2x4 or 2x0.5"
3442
+ }
3443
+ ],
3444
+ result: [
3445
+ {
3446
+ name: "estimates",
3447
+ type: "array"
3448
+ },
3449
+ {
3450
+ name: "estimates[].provider",
3451
+ type: "string"
3452
+ },
3453
+ {
3454
+ name: "estimates[].slug",
3455
+ type: "string"
3456
+ },
3457
+ {
3458
+ name: "estimates[].monthly_micro_usd",
3459
+ type: "number"
3460
+ },
3461
+ {
3462
+ name: "slug",
3463
+ type: "string"
3464
+ }
3465
+ ],
3466
+ summary: "Price a size for a month on each provider"
2507
3467
  }],
2508
3468
  defaultChild: "inspect",
2509
3469
  kind: "group",
2510
3470
  name: "pricing",
2511
- summary: "Show the Pro price and the credit terms"
3471
+ summary: "Show the plan prices, the credit terms, and monthly costs"
3472
+ };
3473
+ const problems = {
3474
+ children: [{
3475
+ arguments: [{
3476
+ missing: {
3477
+ message: "Can't report a problem without a message.",
3478
+ reason: "missing_value"
3479
+ },
3480
+ name: "message",
3481
+ summary: `What went wrong, up to ${formatCount({ count: PROBLEM_REPORT_MAX })} characters; its words join with spaces`,
3482
+ variadic: true
3483
+ }],
3484
+ examples: [{
3485
+ argv: [
3486
+ "problems",
3487
+ "report",
3488
+ "The pricing table is cut off on my phone.",
3489
+ "--page",
3490
+ "/pricing"
3491
+ ],
3492
+ summary: "Report a problem with a page"
3493
+ }],
3494
+ kind: "leaf",
3495
+ name: "report",
3496
+ notes: [`Sends the report to the Sandcovery team, who track it as an issue. It needs no key, and Sandcovery takes ${String(3)} reports a minute from one network address.`],
3497
+ options: [
3498
+ baseUrl,
3499
+ json,
3500
+ {
3501
+ hint: "<PATH>",
3502
+ kind: "value",
3503
+ name: "page",
3504
+ summary: "Path of the Sandcovery page the problem is on"
3505
+ }
3506
+ ],
3507
+ result: [{
3508
+ name: "outcome",
3509
+ type: "\"sent\""
3510
+ }],
3511
+ summary: "Tell the Sandcovery team about a problem"
3512
+ }],
3513
+ kind: "group",
3514
+ name: "problems",
3515
+ shortcuts: ["problem"],
3516
+ summary: "Tell the Sandcovery team about a problem"
2512
3517
  };
2513
3518
  const ci = {
2514
3519
  children: [{
@@ -2680,6 +3685,85 @@ const ci = {
2680
3685
  name: "ci",
2681
3686
  summary: "Run GitHub Actions jobs on sandboxes"
2682
3687
  };
3688
+ const xAccount = {
3689
+ children: [
3690
+ {
3691
+ arguments: [],
3692
+ examples: [{
3693
+ argv: ["x-account", "inspect"],
3694
+ summary: "Show the X account linked to you"
3695
+ }],
3696
+ kind: "leaf",
3697
+ name: "inspect",
3698
+ notes: [`Shows the handle, X ID, and link time of the X account linked to you, and whether Sandcovery links X accounts now. ${NEEDS_PERSON}`],
3699
+ options: [baseUrl, json],
3700
+ result: [
3701
+ {
3702
+ name: "x_account.linked",
3703
+ type: NULLABLE_OBJECT
3704
+ },
3705
+ {
3706
+ name: "x_account.linked.username",
3707
+ type: "string"
3708
+ },
3709
+ {
3710
+ name: "x_account.linking_open",
3711
+ type: "boolean"
3712
+ }
3713
+ ],
3714
+ summary: "Show the linked X account"
3715
+ },
3716
+ {
3717
+ arguments: [],
3718
+ examples: [{
3719
+ argv: ["x-account", "link"],
3720
+ summary: "Print the page that links an X account"
3721
+ }],
3722
+ kind: "leaf",
3723
+ name: "link",
3724
+ notes: ["Prints the dashboard page where you link an X account, since X confirms the link in the browser. Linking asks X only to read your X profile and posts. It fails as not found while Sandcovery links no X accounts, and as a conflict while one is linked to you.", NEEDS_PERSON],
3725
+ options: [baseUrl, json],
3726
+ result: [{
3727
+ name: "link.url",
3728
+ type: "string"
3729
+ }],
3730
+ summary: "Link an X account in the browser"
3731
+ },
3732
+ {
3733
+ arguments: [],
3734
+ examples: [{
3735
+ argv: ["x-account", "unlink"],
3736
+ summary: "Unlink the X account after a prompt"
3737
+ }, {
3738
+ argv: [
3739
+ "x-account",
3740
+ "unlink",
3741
+ "--yes"
3742
+ ],
3743
+ summary: "Unlink it in a script, after a person approved"
3744
+ }],
3745
+ kind: "leaf",
3746
+ name: "unlink",
3747
+ notes: ["Deletes the ID, handle, and X token of the X account linked to you. It fails as not found while none is linked.", `It asks first, and needs --yes without a terminal. ${NEEDS_PERSON}`],
3748
+ options: [
3749
+ baseUrl,
3750
+ json,
3751
+ yes
3752
+ ],
3753
+ result: [{
3754
+ name: "outcome",
3755
+ type: "\"unlinked\""
3756
+ }],
3757
+ shortcuts: ["delete", "rm"],
3758
+ summary: "Unlink the X account"
3759
+ }
3760
+ ],
3761
+ defaultChild: "inspect",
3762
+ kind: "group",
3763
+ name: "x-account",
3764
+ shortcuts: ["x"],
3765
+ summary: "Link or unlink your X account"
3766
+ };
2683
3767
  const telemetryLeaf = ({ name, summary }) => ({
2684
3768
  arguments: [],
2685
3769
  examples: [{
@@ -2790,6 +3874,7 @@ const CLI = {
2790
3874
  children: [
2791
3875
  sandboxes,
2792
3876
  docker,
3877
+ kubectl,
2793
3878
  setup,
2794
3879
  keys,
2795
3880
  credentials,
@@ -2800,6 +3885,8 @@ const CLI = {
2800
3885
  billing,
2801
3886
  pricing,
2802
3887
  ci,
3888
+ xAccount,
3889
+ problems,
2803
3890
  login,
2804
3891
  logout,
2805
3892
  help,
@@ -2846,6 +3933,7 @@ const CLI = {
2846
3933
  ["sandboxes", "destroy"],
2847
3934
  ["sandboxes", "files"],
2848
3935
  ["docker"],
3936
+ ["kubectl"],
2849
3937
  ["setup"]
2850
3938
  ],
2851
3939
  title: "Sandboxes"
@@ -2854,10 +3942,12 @@ const CLI = {
2854
3942
  paths: [
2855
3943
  ["providers", "list"],
2856
3944
  ["pricing", "inspect"],
3945
+ ["pricing", "monthly"],
2857
3946
  ["usage", "estimate"],
2858
3947
  ["usage", "inspect"],
2859
3948
  ["usage", "live"],
2860
3949
  ["usage", "totals"],
3950
+ ["usage", "shares"],
2861
3951
  ["stats", "inspect"]
2862
3952
  ],
2863
3953
  title: "Providers and Cost"
@@ -2869,7 +3959,8 @@ const CLI = {
2869
3959
  ["keys"],
2870
3960
  ["credentials"],
2871
3961
  ["activity", "list"],
2872
- ["billing"]
3962
+ ["billing"],
3963
+ ["x-account"]
2873
3964
  ],
2874
3965
  title: "Account"
2875
3966
  },
@@ -2877,10 +3968,1125 @@ const CLI = {
2877
3968
  paths: [
2878
3969
  ["help"],
2879
3970
  ["help", "search"],
3971
+ ["problems", "report"],
2880
3972
  ["cli", "telemetry"]
2881
3973
  ],
2882
3974
  title: "Help and Settings"
2883
3975
  }
2884
3976
  ]
2885
3977
  };
2886
- export { remoteCell as A, exitCodeOf as B, clearLine as C, spinnerFrame as D, plainPrefix as E, isDigit as F, usageFailure as H, isDigits as I, isUpper as L, remoteText as M, noop as N, theme as O, consistsOf as P, isWordCharacter as R, valuesOf as S, glyph as T, Canceled as U, statusOf as V, Clock as W, lastValue as _, version as a, readOptionToken as b, writePrivateFile as c, modeOf as d, productVariable as f, isOptionValue as g, isOptionToken as h, SETUP_MARK as i, remoteLine as j, escapeUnprintable as k, enabledVariable as l, flagOf as m, CLEARABLE as n, configDirectory as o, closest as p, CLI as r, withFileLock as s, BIN as t, guidanceOn as u, parseFailure as v, ellipsis as w, rerunArgv as x, parseLeaf as y, CliFailure as z };
3978
+ // src/cli/commands/setup.ts
3979
+ const DROP_INS = [{
3980
+ binary: "sandcovery-docker",
3981
+ tool: "docker"
3982
+ }, {
3983
+ binary: "sandcovery-kubectl",
3984
+ tool: "kubectl"
3985
+ }];
3986
+ const LINE_MARK = ` ${SETUP_MARK}`;
3987
+ const SHIM_HEAD = `#!/bin/sh\n${SETUP_MARK}\n`;
3988
+ const BASH_LOGIN = [
3989
+ ".bash_profile",
3990
+ ".bash_login",
3991
+ ".profile"
3992
+ ];
3993
+ const ZSH_FILES = [".zshenv", ".zshrc"];
3994
+ const FILE_TYPE_UNIT = 4096;
3995
+ const UNREACHABLE = /* @__PURE__ */ new Set([
3996
+ "EACCES",
3997
+ "EEXIST",
3998
+ "EISDIR",
3999
+ "ENOTDIR",
4000
+ "EPERM",
4001
+ "EROFS"
4002
+ ]);
4003
+ const EMPTY = {
4004
+ changes: [],
4005
+ edits: []
4006
+ };
4007
+ const joined = (plans) => ({
4008
+ changes: plans.flatMap(({ changes }) => changes),
4009
+ edits: plans.flatMap(({ edits }) => edits)
4010
+ });
4011
+ const touched = ({ file, verb, work }) => {
4012
+ const done = try_(work);
4013
+ if (isSuccess(done)) return done.success;
4014
+ const { failure } = done;
4015
+ const code = hasProperty(failure, "code") && isString(failure.code) ? failure.code : "";
4016
+ if (!UNREACHABLE.has(code)) throw failure;
4017
+ throw new CliFailure({
4018
+ message: verb === "read" ? `Can't read ${file} (${code}). Nothing was changed.` : `Can't write ${file} (${code}). Run the command again once it is writable, and it lists what is left.`,
4019
+ reason: "permission_denied"
4020
+ });
4021
+ };
4022
+ const statOf = (file) => touched({
4023
+ file,
4024
+ verb: "read",
4025
+ work: () => fs.lstatSync(file, { throwIfNoEntry: false })
4026
+ });
4027
+ const textOf = (file) => fs.existsSync(file) ? touched({
4028
+ file,
4029
+ verb: "read",
4030
+ work: () => fs.readFileSync(file, "utf-8")
4031
+ }) : void 0;
4032
+ const envValue = (name) => {
4033
+ const value = process.env[name];
4034
+ return value === void 0 || value === "" ? void 0 : value;
4035
+ };
4036
+ const fishQuoted = (text) => text.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("$", "\\$");
4037
+ const posixQuoted = (text) => fishQuoted(text).replaceAll("`", "\\`");
4038
+ const posixLine = (shims) => `export PATH="${posixQuoted(shims)}:$PATH"${LINE_MARK}`;
4039
+ const fishLine = (shims) => `set -gx PATH "${fishQuoted(shims)}" $PATH${LINE_MARK}`;
4040
+ const shimText = (binary) => `${SHIM_HEAD}exec ${binary} "$@"\n`;
4041
+ const executable = (file) => {
4042
+ const found = try_(() => {
4043
+ fs.accessSync(file, fs.constants.X_OK);
4044
+ return fs.statSync(file).isFile();
4045
+ });
4046
+ return isSuccess(found) && found.success;
4047
+ };
4048
+ const onPath = ({ name, shims }) => (process.env.PATH ?? "").split(path.delimiter).flatMap((folder) => path.isAbsolute(folder) && path.resolve(folder) !== shims ? [path.join(folder, name)] : []).find(executable) ?? null;
4049
+ const zshFolder = (home) => envValue("ZDOTDIR") ?? home;
4050
+ const fishConfig = (configHome) => path.join(configHome, "fish", "config.fish");
4051
+ const defaultConfigHome = (home) => path.join(home, ".config");
4052
+ const shellsOf = (home) => {
4053
+ const bashLogin = BASH_LOGIN.map((name) => path.join(home, name)).find((file) => fs.existsSync(file)) ?? path.join(home, ".profile");
4054
+ return [
4055
+ {
4056
+ files: [path.join(home, ".bashrc"), bashLogin],
4057
+ line: posixLine,
4058
+ name: "bash"
4059
+ },
4060
+ {
4061
+ files: ZSH_FILES.map((name) => path.join(zshFolder(home), name)),
4062
+ line: posixLine,
4063
+ name: "zsh"
4064
+ },
4065
+ {
4066
+ files: [fishConfig(envValue("XDG_CONFIG_HOME") ?? defaultConfigHome(home))],
4067
+ line: fishLine,
4068
+ name: "fish"
4069
+ }
4070
+ ];
4071
+ };
4072
+ const everyStartupFile = (home) => [.../* @__PURE__ */ new Set([
4073
+ ...[".bashrc", ...BASH_LOGIN].map((name) => path.join(home, name)),
4074
+ ...[zshFolder(home), home].flatMap((folder) => ZSH_FILES.map((name) => path.join(folder, name))),
4075
+ ...[envValue("XDG_CONFIG_HOME") ?? defaultConfigHome(home), defaultConfigHome(home)].map(fishConfig)
4076
+ ])];
4077
+ const appended = (line) => (text) => {
4078
+ if (text.split("\n").includes(line)) return text;
4079
+ return `${text}${text === "" || text.endsWith("\n") ? "" : "\n"}${line}\n`;
4080
+ };
4081
+ const withoutMarked = (text) => text.split("\n").filter((line) => !line.endsWith(LINE_MARK)).join("\n");
4082
+ const folderEntries = (folder) => statOf(folder)?.isDirectory() === true ? touched({
4083
+ file: folder,
4084
+ verb: "read",
4085
+ work: () => fs.readdirSync(folder)
4086
+ }).map((name) => path.join(folder, name)).toSorted() : [];
4087
+ const isOwnShim = (file) => statOf(file)?.isFile() === true && (textOf(file) ?? "").startsWith(SHIM_HEAD);
4088
+ const shimDeletion = (file) => ({
4089
+ changes: [{
4090
+ action: "delete",
4091
+ file,
4092
+ line: null,
4093
+ summary: "Delete this shim",
4094
+ text: null
4095
+ }],
4096
+ edits: [{
4097
+ file,
4098
+ kind: "delete"
4099
+ }]
4100
+ });
4101
+ const shimWrite = ({ binary, shims, tool }) => {
4102
+ const file = path.join(shims, tool);
4103
+ const text = shimText(binary);
4104
+ const stat = statOf(file);
4105
+ if (stat !== void 0) {
4106
+ const current = stat.isFile() ? textOf(file) : void 0;
4107
+ if (current === text) return EMPTY;
4108
+ if (current === void 0 || !current.startsWith(SHIM_HEAD)) throw new CliFailure({
4109
+ message: `Can't write the ${tool} shim. ${file} is not a file sandcovery setup wrote, so it stays as it is.`,
4110
+ reason: "conflict",
4111
+ recovery: [{ instruction: `Move ${file} out of ${shims}, then run sandcovery setup again` }]
4112
+ });
4113
+ }
4114
+ return {
4115
+ changes: [{
4116
+ action: "write",
4117
+ file,
4118
+ line: null,
4119
+ summary: `Write a shim that runs ${binary}`,
4120
+ text
4121
+ }],
4122
+ edits: [{
4123
+ file,
4124
+ kind: "shim",
4125
+ text
4126
+ }]
4127
+ };
4128
+ };
4129
+ const shimPlan = ({ dropIns, shims }) => {
4130
+ const wanted = dropIns.filter(({ installed }) => installed);
4131
+ const tools = new Set(wanted.map(({ tool }) => tool));
4132
+ return joined([...wanted.map(({ binary, tool }) => shimWrite({
4133
+ binary,
4134
+ shims,
4135
+ tool
4136
+ })), ...folderEntries(shims).flatMap((file) => tools.has(path.basename(file)) || !isOwnShim(file) ? [] : [shimDeletion(file)])]);
4137
+ };
4138
+ const lineAddition = ({ file, text }) => {
4139
+ const current = textOf(file) ?? "";
4140
+ return appended(text)(current) === current ? EMPTY : {
4141
+ changes: [{
4142
+ action: "append",
4143
+ file,
4144
+ line: null,
4145
+ summary: `Add: ${text}`,
4146
+ text
4147
+ }],
4148
+ edits: [{
4149
+ change: appended(text),
4150
+ file,
4151
+ kind: "startup"
4152
+ }]
4153
+ };
4154
+ };
4155
+ const linePlan = ({ home, shims }) => {
4156
+ const login = path.basename(envValue("SHELL") ?? "");
4157
+ return joined(shellsOf(home).flatMap(({ files, line, name }) => name === login || files.some((file) => fs.existsSync(file)) ? files.map((file) => lineAddition({
4158
+ file,
4159
+ text: line(shims)
4160
+ })) : []));
4161
+ };
4162
+ const lineRemovals = (file) => {
4163
+ const text = textOf(file);
4164
+ if (text === void 0) return EMPTY;
4165
+ const marked = text.split("\n").flatMap((line, index) => line.endsWith(LINE_MARK) ? [{
4166
+ line: index + 1,
4167
+ text: line
4168
+ }] : []);
4169
+ if (marked.length === 0) return EMPTY;
4170
+ const deletion = withoutMarked(text) === "" && statOf(file)?.isFile() === true ? [{
4171
+ action: "delete",
4172
+ file,
4173
+ line: null,
4174
+ summary: "Delete this file, which holds nothing else",
4175
+ text: null
4176
+ }] : [];
4177
+ return {
4178
+ changes: [...marked.map(({ line, text: content }) => ({
4179
+ action: "remove",
4180
+ file,
4181
+ line,
4182
+ summary: `Remove line ${String(line)}: ${content}`,
4183
+ text: content
4184
+ })), ...deletion],
4185
+ edits: [{
4186
+ change: withoutMarked,
4187
+ file,
4188
+ kind: "startup"
4189
+ }]
4190
+ };
4191
+ };
4192
+ const undoPlan = ({ home, shims }) => {
4193
+ const entries = folderEntries(shims);
4194
+ const own = entries.filter(isOwnShim);
4195
+ const folderGoes = statOf(shims)?.isDirectory() === true && own.length === entries.length;
4196
+ return joined([
4197
+ ...everyStartupFile(home).map(lineRemovals),
4198
+ ...own.map(shimDeletion),
4199
+ folderGoes ? {
4200
+ changes: [{
4201
+ action: "delete",
4202
+ file: shims,
4203
+ line: null,
4204
+ summary: "Delete this empty folder",
4205
+ text: null
4206
+ }],
4207
+ edits: [{
4208
+ file: shims,
4209
+ kind: "folder"
4210
+ }]
4211
+ } : EMPTY
4212
+ ]);
4213
+ };
4214
+ const replaceText = ({ file, mode, text }) => {
4215
+ const folder = path.dirname(file);
4216
+ fs.mkdirSync(folder, { recursive: true });
4217
+ const pending = path.join(folder, `.${path.basename(file)}.${crypto$1.randomBytes(8).toString("hex")}.tmp`);
4218
+ fs.writeFileSync(pending, text, { flag: "wx" });
4219
+ if (mode !== void 0) fs.chmodSync(pending, mode);
4220
+ fs.renameSync(pending, file);
4221
+ };
4222
+ const rewrite = ({ change, file }) => {
4223
+ const target = fs.existsSync(file) ? fs.realpathSync(file) : file;
4224
+ const before = textOf(target) ?? "";
4225
+ const after = change(before);
4226
+ if (after === before) return;
4227
+ if (after === "" && statOf(file)?.isFile() === true) {
4228
+ fs.rmSync(file);
4229
+ return;
4230
+ }
4231
+ const stat = statOf(target);
4232
+ replaceText({
4233
+ file: target,
4234
+ mode: stat === void 0 ? void 0 : stat.mode % FILE_TYPE_UNIT,
4235
+ text: after
4236
+ });
4237
+ };
4238
+ const apply = (edit) => {
4239
+ touched({
4240
+ file: edit.file,
4241
+ verb: "write",
4242
+ work: () => {
4243
+ if (edit.kind === "startup") rewrite(edit);
4244
+ else if (edit.kind === "shim") {
4245
+ fs.mkdirSync(path.dirname(edit.file), {
4246
+ mode: 448,
4247
+ recursive: true
4248
+ });
4249
+ replaceText({
4250
+ file: edit.file,
4251
+ mode: 493,
4252
+ text: edit.text
4253
+ });
4254
+ } else if (edit.kind === "delete") fs.rmSync(edit.file, { force: true });
4255
+ else if (fs.readdirSync(edit.file).length === 0) fs.rmdirSync(edit.file);
4256
+ }
4257
+ });
4258
+ };
4259
+ const resultOf = ({ changes, dropIns }) => ({
4260
+ changes: changes.map(({ action, file, line, text }) => ({
4261
+ action,
4262
+ file,
4263
+ line,
4264
+ text
4265
+ })),
4266
+ drop_ins: dropIns
4267
+ });
4268
+ const toolNotes = (dropIns) => dropIns.map(({ binary, installed, real_path: realPath, tool }) => {
4269
+ if (!installed) return `${tool} stays as it is, since ${binary} isn't installed.`;
4270
+ return realPath === null ? `${tool} runs ${binary} in each new terminal.` : `${tool} runs ${binary} in each new terminal. Your own ${tool} stays at ${realPath} and runs by that full path.`;
4271
+ });
4272
+ const confirmed = async ({ changes, context, dropIns, notes, undo }) => {
4273
+ context.io.context(changes.map(({ file, summary }) => ({
4274
+ label: file,
4275
+ value: summary
4276
+ })));
4277
+ context.io.note(notes);
4278
+ if (flagOf(context.options, "yes") === true) return;
4279
+ if (!context.mode.interactive || context.prompter === void 0) throw new CliFailure({
4280
+ data: resultOf({
4281
+ changes,
4282
+ dropIns
4283
+ }),
4284
+ message: `Can't ${undo ? "undo sandcovery setup" : "set up drop-ins"} without --yes in non-interactive mode.`,
4285
+ reason: "confirmation_required",
4286
+ recovery: [{
4287
+ instruction: "After a person approves the changes listed, run",
4288
+ next: {
4289
+ argv: [...context.rerun, "--yes"],
4290
+ when: "Only after a human approves the listed changes"
4291
+ }
4292
+ }],
4293
+ userActionRequired: true
4294
+ });
4295
+ if (!await context.prompter.confirm("Make these changes?")) throw new Canceled({
4296
+ remote: "none",
4297
+ signal: "SIGINT"
4298
+ });
4299
+ };
4300
+ const shimsOf = (context) => path.join(path.dirname(context.settingsFile), "bin");
4301
+ const shimFolder = (context) => {
4302
+ const shims = shimsOf(context);
4303
+ const characters = new Set(shims);
4304
+ if (characters.has(path.delimiter) || characters.has("\n")) throw new CliFailure({
4305
+ message: `Can't put ${shims} on PATH, since PATH can't hold a folder whose name has a colon or a line break.`,
4306
+ reason: "invalid_arguments",
4307
+ recovery: [{ instruction: "Choose another settings folder with --global-config" }]
4308
+ });
4309
+ return shims;
4310
+ };
4311
+ const setupDropIns = async (context) => {
4312
+ if (process.platform === "win32") throw new CliFailure({
4313
+ message: "Can't set up drop-ins on Windows. sandcovery setup changes the startup files of bash, zsh, and fish.",
4314
+ reason: "unsupported"
4315
+ });
4316
+ const undo = flagOf(context.options, "undo") === true;
4317
+ const home = os.homedir();
4318
+ const shims = shimFolder(context);
4319
+ const dropIns = DROP_INS.map(({ binary, tool }) => ({
4320
+ binary,
4321
+ installed: onPath({
4322
+ name: binary,
4323
+ shims
4324
+ }) !== null,
4325
+ real_path: onPath({
4326
+ name: tool,
4327
+ shims
4328
+ }),
4329
+ tool
4330
+ }));
4331
+ if (!undo && dropIns.every(({ installed }) => !installed)) throw new CliFailure({
4332
+ message: `Can't set up drop-ins. None of ${DROP_INS.map(({ binary }) => binary).join(", ")} is on PATH.`,
4333
+ notes: ["They come with the sandcovery npm package: npm install --global sandcovery."],
4334
+ reason: "not_found"
4335
+ });
4336
+ const plan = undo ? undoPlan({
4337
+ home,
4338
+ shims
4339
+ }) : joined([shimPlan({
4340
+ dropIns,
4341
+ shims
4342
+ }), linePlan({
4343
+ home,
4344
+ shims
4345
+ })]);
4346
+ const notes = undo ? [] : toolNotes(dropIns);
4347
+ if (plan.changes.length === 0) {
4348
+ context.io.note([undo ? "Nothing to undo." : "Nothing to change.", ...notes]);
4349
+ return { document: resultOf({
4350
+ changes: [],
4351
+ dropIns
4352
+ }) };
4353
+ }
4354
+ await confirmed({
4355
+ changes: plan.changes,
4356
+ context,
4357
+ dropIns,
4358
+ notes,
4359
+ undo
4360
+ });
4361
+ for (const edit of plan.edits) apply(edit);
4362
+ context.io.receipt({
4363
+ outcome: undo ? "Undone" : "Set up",
4364
+ target: shims
4365
+ });
4366
+ if (!undo) context.io.note(["Open a new terminal, so the shims come first on PATH there."]);
4367
+ return { document: resultOf({
4368
+ changes: plan.changes,
4369
+ dropIns
4370
+ }) };
4371
+ };
4372
+ // ../../node_modules/.pnpm/uuid@14.0.3/node_modules/uuid/dist-node/stringify.js
4373
+ const byteToHex = [];
4374
+ for (let i = 0; i < 256; ++i) byteToHex.push((i + 256).toString(16).slice(1));
4375
+ function unsafeStringify(arr, offset = 0) {
4376
+ return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
4377
+ }
4378
+ // ../../node_modules/.pnpm/uuid@14.0.3/node_modules/uuid/dist-node/rng.js
4379
+ const rnds8 = /* @__PURE__ */ new Uint8Array(16);
4380
+ function rng() {
4381
+ return crypto.getRandomValues(rnds8);
4382
+ }
4383
+ // ../../node_modules/.pnpm/uuid@14.0.3/node_modules/uuid/dist-node/v7.js
4384
+ const _state = {};
4385
+ function v7(options, buf, offset) {
4386
+ let bytes;
4387
+ if (options) bytes = v7Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.seq, buf, offset);
4388
+ else {
4389
+ const now = Date.now();
4390
+ const rnds = rng();
4391
+ updateV7State(_state, now, rnds);
4392
+ bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset);
4393
+ }
4394
+ return buf ?? unsafeStringify(bytes);
4395
+ }
4396
+ function updateV7State(state, now, rnds) {
4397
+ state.msecs ??= -Infinity;
4398
+ state.seq ??= 0;
4399
+ if (now > state.msecs) {
4400
+ state.seq = v7Sequence(rnds);
4401
+ state.msecs = now;
4402
+ } else {
4403
+ state.seq = state.seq + 1 | 0;
4404
+ if (state.seq === 0) state.msecs++;
4405
+ }
4406
+ return state;
4407
+ }
4408
+ function v7Bytes(rnds, msecs, seq, buf, offset = 0) {
4409
+ if (rnds.length < 16) throw new Error("Random bytes length must be >= 16");
4410
+ if (!buf) {
4411
+ buf = /* @__PURE__ */ new Uint8Array(16);
4412
+ offset = 0;
4413
+ } else if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
4414
+ msecs ??= Date.now();
4415
+ seq ??= v7Sequence(rnds);
4416
+ buf[offset++] = msecs / 1099511627776 & 255;
4417
+ buf[offset++] = msecs / 4294967296 & 255;
4418
+ buf[offset++] = msecs / 16777216 & 255;
4419
+ buf[offset++] = msecs / 65536 & 255;
4420
+ buf[offset++] = msecs / 256 & 255;
4421
+ buf[offset++] = msecs & 255;
4422
+ buf[offset++] = 112 | seq >>> 28 & 15;
4423
+ buf[offset++] = seq >>> 20 & 255;
4424
+ buf[offset++] = 128 | seq >>> 14 & 63;
4425
+ buf[offset++] = seq >>> 6 & 255;
4426
+ buf[offset++] = seq << 2 & 255 | rnds[10] & 3;
4427
+ buf[offset++] = rnds[11];
4428
+ buf[offset++] = rnds[12];
4429
+ buf[offset++] = rnds[13];
4430
+ buf[offset++] = rnds[14];
4431
+ buf[offset++] = rnds[15];
4432
+ return buf;
4433
+ }
4434
+ function v7Sequence(rnds) {
4435
+ return (rnds[6] & 127) << 24 | rnds[7] << 16 | rnds[8] << 8 | rnds[9];
4436
+ }
4437
+ // src/cli/relay.ts
4438
+ const RELAY_PORT = 9951;
4439
+ const RELAY_TOKEN_HEADER = "x-sandcovery-relay-token";
4440
+ const RELAY_SOURCE = String.raw`import base64
4441
+ import hashlib
4442
+ import hmac
4443
+ import json
4444
+ import os
4445
+ import socket
4446
+ import subprocess
4447
+ import sys
4448
+ import threading
4449
+
4450
+ GUID = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
4451
+ HEADER_LIMIT = 16384
4452
+ CHUNK = 65536
4453
+ KEEPALIVE_SECONDS = 30
4454
+ TEXT, BINARY, CLOSE, PING, PONG = 1, 2, 8, 9, 10
4455
+ EVENTS = [
4456
+ "docker", "events", "--format", "{{.Actor.ID}}",
4457
+ "--filter", "type=container",
4458
+ "--filter", "event=start",
4459
+ "--filter", "event=die",
4460
+ ]
4461
+
4462
+
4463
+ def shut(sock, how=socket.SHUT_RDWR):
4464
+ try:
4465
+ sock.shutdown(how)
4466
+ except OSError:
4467
+ pass
4468
+
4469
+
4470
+ class Peer:
4471
+ def __init__(self, conn):
4472
+ self.conn = conn
4473
+ self.buffer = b""
4474
+ self.lock = threading.Lock()
4475
+ self.done = threading.Event()
4476
+
4477
+ def fill(self):
4478
+ chunk = self.conn.recv(CHUNK)
4479
+ if not chunk:
4480
+ raise EOFError
4481
+ self.buffer += chunk
4482
+
4483
+ def take(self, size):
4484
+ while len(self.buffer) < size:
4485
+ self.fill()
4486
+ data, self.buffer = self.buffer[:size], self.buffer[size:]
4487
+ return data
4488
+
4489
+ def head(self):
4490
+ while b"\r\n\r\n" not in self.buffer:
4491
+ if len(self.buffer) > HEADER_LIMIT:
4492
+ raise EOFError
4493
+ self.fill()
4494
+ head, self.buffer = self.buffer.split(b"\r\n\r\n", 1)
4495
+ return head.decode("latin-1").split("\r\n")
4496
+
4497
+ def send(self, opcode, payload=b""):
4498
+ size = len(payload)
4499
+ if size < 126:
4500
+ head = bytes([0x80 | opcode, size])
4501
+ elif size < 65536:
4502
+ head = bytes([0x80 | opcode, 126]) + size.to_bytes(2, "big")
4503
+ else:
4504
+ head = bytes([0x80 | opcode, 127]) + size.to_bytes(8, "big")
4505
+ with self.lock:
4506
+ self.conn.sendall(head + payload)
4507
+
4508
+ def frame(self):
4509
+ first, second = self.take(2)
4510
+ size = second & 0x7F
4511
+ if size == 126:
4512
+ size = int.from_bytes(self.take(2), "big")
4513
+ elif size == 127:
4514
+ size = int.from_bytes(self.take(8), "big")
4515
+ mask = self.take(4) if second & 0x80 else b""
4516
+ payload = self.take(size)
4517
+ if mask and size:
4518
+ key = (mask * (size // 4 + 1))[:size]
4519
+ mixed = int.from_bytes(payload, "little") ^ int.from_bytes(key, "little")
4520
+ payload = mixed.to_bytes(size, "little")
4521
+ return first & 0x80, first & 0x0F, payload
4522
+
4523
+ def message(self):
4524
+ kind, parts = 0, []
4525
+ while True:
4526
+ final, opcode, payload = self.frame()
4527
+ if opcode == PING:
4528
+ self.send(PONG, payload)
4529
+ elif opcode == CLOSE:
4530
+ return CLOSE, b""
4531
+ elif opcode != PONG:
4532
+ kind = kind or opcode
4533
+ parts.append(payload)
4534
+ if final:
4535
+ return kind, b"".join(parts)
4536
+
4537
+
4538
+ def refuse(peer, status):
4539
+ peer.conn.sendall(
4540
+ ("HTTP/1.1 " + status + "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").encode()
4541
+ )
4542
+
4543
+
4544
+ def keepalive(peer):
4545
+ while not peer.done.wait(KEEPALIVE_SECONDS):
4546
+ try:
4547
+ peer.send(PING)
4548
+ except OSError:
4549
+ return
4550
+
4551
+
4552
+ def accept(peer, key):
4553
+ digest = base64.b64encode(hashlib.sha1(key.encode() + GUID).digest()).decode()
4554
+ peer.conn.sendall(
4555
+ (
4556
+ "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n"
4557
+ "Connection: Upgrade\r\nSec-WebSocket-Accept: " + digest + "\r\n\r\n"
4558
+ ).encode()
4559
+ )
4560
+ threading.Thread(target=keepalive, args=(peer,), daemon=True).start()
4561
+
4562
+
4563
+ def send_down(peer, upstream):
4564
+ try:
4565
+ while True:
4566
+ data = upstream.recv(CHUNK)
4567
+ peer.send(BINARY, data)
4568
+ if not data:
4569
+ return
4570
+ except OSError:
4571
+ shut(peer.conn)
4572
+
4573
+
4574
+ def pipe(peer, upstream):
4575
+ with upstream:
4576
+ threading.Thread(target=send_down, args=(peer, upstream), daemon=True).start()
4577
+ try:
4578
+ while True:
4579
+ opcode, payload = peer.message()
4580
+ if opcode == CLOSE:
4581
+ return
4582
+ if payload:
4583
+ upstream.sendall(payload)
4584
+ else:
4585
+ shut(upstream, socket.SHUT_WR)
4586
+ finally:
4587
+ shut(upstream)
4588
+ try:
4589
+ peer.send(CLOSE)
4590
+ except OSError:
4591
+ pass
4592
+
4593
+
4594
+ def ports_snapshot():
4595
+ ids = subprocess.run(
4596
+ ["docker", "ps", "--quiet", "--no-trunc"], capture_output=True, text=True
4597
+ ).stdout.split()
4598
+ if not ids:
4599
+ return "[]"
4600
+ shown = subprocess.run(
4601
+ ["docker", "inspect", "--format", "{{json .NetworkSettings.Ports}}", *ids],
4602
+ capture_output=True,
4603
+ text=True,
4604
+ ).stdout
4605
+ return "[" + ",".join(line for line in shown.splitlines() if line) + "]"
4606
+
4607
+
4608
+ def events(peer, key):
4609
+ accept(peer, key)
4610
+ lock = threading.Lock()
4611
+ watcher = subprocess.Popen(EVENTS, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
4612
+
4613
+ def snapshot(tag=None):
4614
+ with lock:
4615
+ shown = '{"ports":' + ports_snapshot() + ',"tag":' + json.dumps(tag) + "}"
4616
+ peer.send(TEXT, shown.encode())
4617
+
4618
+ def watch():
4619
+ try:
4620
+ for _ in watcher.stdout:
4621
+ snapshot()
4622
+ except OSError:
4623
+ pass
4624
+ shut(peer.conn)
4625
+
4626
+ try:
4627
+ threading.Thread(target=watch, daemon=True).start()
4628
+ snapshot()
4629
+ while True:
4630
+ opcode, payload = peer.message()
4631
+ if opcode == CLOSE:
4632
+ return
4633
+ snapshot(payload.decode("utf-8", "replace"))
4634
+ finally:
4635
+ watcher.kill()
4636
+ watcher.wait()
4637
+
4638
+
4639
+ def handle(conn, token):
4640
+ with conn:
4641
+ peer = Peer(conn)
4642
+ try:
4643
+ lines = peer.head()
4644
+ request = lines[0].split(" ")
4645
+ fields = {}
4646
+ for line in lines[1:]:
4647
+ name, _, value = line.partition(":")
4648
+ fields[name.strip().lower()] = value.strip()
4649
+ offered = fields.get("${RELAY_TOKEN_HEADER}", "").encode()
4650
+ key = fields.get("sec-websocket-key", "")
4651
+ if not hmac.compare_digest(offered, token):
4652
+ return refuse(peer, "401 Unauthorized")
4653
+ if len(request) != 3 or not key or fields.get("upgrade", "").lower() != "websocket":
4654
+ return refuse(peer, "400 Bad Request")
4655
+ target = request[1].split("?")[0]
4656
+ if target.endswith("/events"):
4657
+ return events(peer, key)
4658
+ _, found, digits = target.rpartition("/tcp/")
4659
+ number = int(digits) if found and digits.isascii() and digits.isdigit() else 0
4660
+ if not 0 < number < 65536:
4661
+ return refuse(peer, "404 Not Found")
4662
+ try:
4663
+ upstream = socket.create_connection(("127.0.0.1", number))
4664
+ except OSError:
4665
+ return refuse(peer, "502 Bad Gateway")
4666
+ accept(peer, key)
4667
+ pipe(peer, upstream)
4668
+ except (EOFError, OSError, ValueError):
4669
+ pass
4670
+ finally:
4671
+ peer.done.set()
4672
+
4673
+
4674
+ def main():
4675
+ port, token_file = int(sys.argv[1]), sys.argv[2]
4676
+ with open(token_file, "rb") as file:
4677
+ token = file.read().strip()
4678
+ os.remove(token_file)
4679
+ if not token:
4680
+ raise SystemExit("the relay token file is empty")
4681
+ try:
4682
+ server = socket.create_server(("", port), family=socket.AF_INET6, dualstack_ipv6=True)
4683
+ except (OSError, ValueError):
4684
+ server = socket.create_server(("", port))
4685
+ child = os.fork()
4686
+ if child:
4687
+ print(server.getsockname()[1], child, flush=True)
4688
+ os._exit(0)
4689
+ os.setsid()
4690
+ devnull = os.open(os.devnull, os.O_RDWR)
4691
+ for descriptor in (0, 1, 2):
4692
+ os.dup2(devnull, descriptor)
4693
+ while True:
4694
+ conn, _ = server.accept()
4695
+ threading.Thread(target=handle, args=(conn, token), daemon=True).start()
4696
+
4697
+
4698
+ main()
4699
+ `;
4700
+ // src/cli/port-forwarder.ts
4701
+ const FORWARDER_ENV = "__SANDCOVERY_PORT_FORWARDER";
4702
+ const BUFFERED_LIMIT = 4194304;
4703
+ const DRAIN_POLL_MS = 10;
4704
+ const SYNC_MS = 15e3;
4705
+ const UNATTACHED_MS = 6e4;
4706
+ const PREVIEW_MARGIN_MS = 6e4;
4707
+ const LONGEST_TIMER_MS = 2147483647;
4708
+ const RETRY_MS = [
4709
+ 1e3,
4710
+ 2e3,
4711
+ 5e3,
4712
+ 1e4,
4713
+ 3e4
4714
+ ];
4715
+ const ANY_IPV4 = "0.0.0.0";
4716
+ const HIGHEST_PORT = 65535;
4717
+ const UnforwardedSchema = Struct({
4718
+ host: String$1,
4719
+ port: Number$1,
4720
+ reason: Literals(["busy", "denied"])
4721
+ });
4722
+ const decodeRequest = decodeUnknownOption(fromJsonString(Struct({
4723
+ attachment: Struct({
4724
+ expires_at: String$1,
4725
+ key: String$1,
4726
+ origin: String$1,
4727
+ sandbox: String$1,
4728
+ token: String$1
4729
+ }),
4730
+ sync: Boolean
4731
+ })));
4732
+ const decodeReply = decodeUnknownOption(fromJsonString(Struct({ unforwarded: ArraySchema(UnforwardedSchema) })));
4733
+ const SnapshotSchema = Struct({
4734
+ ports: ArraySchema(NullOr(Record(String$1, NullOr(ArraySchema(Struct({
4735
+ HostIp: String$1,
4736
+ HostPort: String$1
4737
+ })))))),
4738
+ tag: NullOr(String$1)
4739
+ });
4740
+ const decodeSnapshot = decodeUnknownOption(fromJsonString(SnapshotSchema));
4741
+ const keyOf = ({ host, port }) => `${host} ${String(port)}`;
4742
+ const isPort = (port) => Number.isInteger(port) && port > 0 && port <= HIGHEST_PORT;
4743
+ const publishedIn = (ports) => ports.flatMap((container) => Object.entries(container ?? {}).flatMap(([target, bindings]) => target.endsWith("/tcp") ? (bindings ?? []).flatMap(({ HostIp, HostPort }) => {
4744
+ const port = Number(HostPort);
4745
+ return isPort(port) ? [{
4746
+ host: HostIp === "" ? ANY_IPV4 : HostIp,
4747
+ port
4748
+ }] : [];
4749
+ }) : []));
4750
+ const errorCode = (error) => error.code ?? "";
4751
+ const cancel = (timer) => {
4752
+ if (timer !== null) clearTimeout(timer);
4753
+ return null;
4754
+ };
4755
+ const heldUntil = async (attachment) => {
4756
+ const [read] = await Promise.allSettled([new Sandcovery({
4757
+ apiKey: attachment.key,
4758
+ baseUrl: attachment.origin
4759
+ }).sandboxes.get(attachment.sandbox)]);
4760
+ return read.status === "fulfilled" && read.value.status === "running" ? Date.parse(read.value.expires_at) : Number.NEGATIVE_INFINITY;
4761
+ };
4762
+ const resumedWhenDrained = (remote, local) => {
4763
+ const timer = setInterval(() => {
4764
+ if (remote.bufferedAmount <= BUFFERED_LIMIT || remote.readyState !== WebSocket.OPEN) {
4765
+ clearInterval(timer);
4766
+ local.resume();
4767
+ }
4768
+ }, DRAIN_POLL_MS);
4769
+ };
4770
+ const carry = (local, remote) => {
4771
+ const ended = {
4772
+ local: false,
4773
+ remote: false
4774
+ };
4775
+ const finish = () => {
4776
+ if (ended.local && ended.remote) remote.close();
4777
+ };
4778
+ remote.addEventListener("open", () => {
4779
+ local.resume();
4780
+ });
4781
+ remote.addEventListener("message", ({ data }) => {
4782
+ if (!(data instanceof ArrayBuffer)) return;
4783
+ if (data.byteLength === 0) {
4784
+ ended.remote = true;
4785
+ local.end();
4786
+ finish();
4787
+ } else local.write(new Uint8Array(data));
4788
+ });
4789
+ remote.addEventListener("close", () => {
4790
+ if (!ended.local || !ended.remote) local.destroy();
4791
+ });
4792
+ local.on("data", (chunk) => {
4793
+ remote.send(chunk);
4794
+ if (remote.bufferedAmount > BUFFERED_LIMIT) {
4795
+ local.pause();
4796
+ resumedWhenDrained(remote, local);
4797
+ }
4798
+ });
4799
+ local.once("end", () => {
4800
+ ended.local = true;
4801
+ remote.send(/* @__PURE__ */ new Uint8Array());
4802
+ finish();
4803
+ });
4804
+ local.once("error", () => {
4805
+ remote.close();
4806
+ });
4807
+ };
4808
+ const forwarderSocket = (settingsFile) => socketOf({
4809
+ name: "docker-ports",
4810
+ settingsFile
4811
+ });
4812
+ const requested = async (connection) => {
4813
+ const chunks = [];
4814
+ const { promise, resolve } = Promise.withResolvers();
4815
+ connection.on("data", (chunk) => {
4816
+ chunks.push(chunk);
4817
+ });
4818
+ connection.once("end", () => {
4819
+ resolve(Buffer.concat(chunks).toString("utf-8"));
4820
+ });
4821
+ connection.once("close", () => {
4822
+ resolve("");
4823
+ });
4824
+ return await promise;
4825
+ };
4826
+ const forwardPorts = async (socketPath) => {
4827
+ const state = {
4828
+ applying: false,
4829
+ attachment: null,
4830
+ bound: /* @__PURE__ */ new Map(),
4831
+ connecting: false,
4832
+ control: null,
4833
+ expiry: null,
4834
+ failures: 0,
4835
+ latest: null,
4836
+ notices: /* @__PURE__ */ new Map(),
4837
+ relay: null,
4838
+ retry: null,
4839
+ syncs: /* @__PURE__ */ new Map()
4840
+ };
4841
+ const listener = net.createServer({ allowHalfOpen: true });
4842
+ const release = () => {
4843
+ for (const server of state.bound.values()) server.close();
4844
+ state.bound.clear();
4845
+ state.notices.clear();
4846
+ state.latest = null;
4847
+ state.relay = null;
4848
+ state.failures = 0;
4849
+ state.retry = cancel(state.retry);
4850
+ const { control } = state;
4851
+ state.control = null;
4852
+ control?.close();
4853
+ };
4854
+ const wakeSyncs = () => {
4855
+ for (const wake of state.syncs.values()) wake();
4856
+ };
4857
+ const stop = () => {
4858
+ release();
4859
+ state.attachment = null;
4860
+ state.expiry = cancel(state.expiry);
4861
+ listener.close();
4862
+ wakeSyncs();
4863
+ };
4864
+ const expireAt = (deadline) => {
4865
+ const settle = async () => {
4866
+ const { attachment } = state;
4867
+ const later = Date.now() < deadline || attachment === null ? deadline : await heldUntil(attachment);
4868
+ if (state.attachment !== attachment) return;
4869
+ if (later > Date.now()) expireAt(later);
4870
+ else stop();
4871
+ };
4872
+ cancel(state.expiry);
4873
+ state.expiry = setTimeout(() => {
4874
+ settle();
4875
+ }, clamp(deadline - Date.now(), 0, LONGEST_TIMER_MS));
4876
+ };
4877
+ const relay = async (attachment) => {
4878
+ if (state.relay !== null && state.relay.expiresAt - Date.now() > PREVIEW_MARGIN_MS) return state.relay;
4879
+ const preview = await new Sandcovery({
4880
+ apiKey: attachment.key,
4881
+ baseUrl: attachment.origin
4882
+ }).sandboxes.portPreview(attachment.sandbox, RELAY_PORT);
4883
+ state.relay = {
4884
+ expiresAt: preview.expires_at === null ? Number.POSITIVE_INFINITY : Date.parse(preview.expires_at),
4885
+ headers: preview.headers,
4886
+ url: preview.url
4887
+ };
4888
+ return state.relay;
4889
+ };
4890
+ const attempted = async (attachment, target, listen) => {
4891
+ try {
4892
+ const current = await relay(attachment);
4893
+ const url = new URL(current.url);
4894
+ url.pathname = `${url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname}${target}`;
4895
+ const socket = new WebSocket(url, { headers: {
4896
+ ...current.headers,
4897
+ [RELAY_TOKEN_HEADER]: attachment.token
4898
+ } });
4899
+ socket.binaryType = "arraybuffer";
4900
+ listen(socket);
4901
+ return socket;
4902
+ } catch (error) {
4903
+ if (error instanceof Error) return error;
4904
+ throw error;
4905
+ }
4906
+ };
4907
+ const tunnel = async (local, port) => {
4908
+ local.on("error", noop);
4909
+ const { attachment } = state;
4910
+ const outcome = attachment === null ? null : await attempted(attachment, `/tcp/${String(port)}`, (remote) => {
4911
+ carry(local, remote);
4912
+ });
4913
+ if (outcome === null || outcome instanceof Error) local.destroy();
4914
+ };
4915
+ const bind = async (published) => {
4916
+ const { host, port } = published;
4917
+ const server = net.createServer({
4918
+ allowHalfOpen: true,
4919
+ pauseOnConnect: true
4920
+ }, (local) => {
4921
+ tunnel(local, port);
4922
+ });
4923
+ const { promise, resolve } = Promise.withResolvers();
4924
+ server.once("error", (error) => {
4925
+ const code = errorCode(error);
4926
+ if (code === "EADDRINUSE") resolve({
4927
+ host,
4928
+ port,
4929
+ reason: "busy"
4930
+ });
4931
+ else if (code === "EACCES") resolve({
4932
+ host,
4933
+ port,
4934
+ reason: "denied"
4935
+ });
4936
+ else resolve(null);
4937
+ });
4938
+ server.listen({
4939
+ host,
4940
+ ipv6Only: host.includes(":"),
4941
+ port
4942
+ }, () => {
4943
+ server.on("error", noop);
4944
+ state.bound.set(keyOf(published), server);
4945
+ resolve(null);
4946
+ });
4947
+ return await promise;
4948
+ };
4949
+ const apply = async (published) => {
4950
+ const wanted = new Map(published.map((entry) => [keyOf(entry), entry]));
4951
+ for (const [key, server] of state.bound) if (!wanted.has(key)) {
4952
+ server.close();
4953
+ state.bound.delete(key);
4954
+ }
4955
+ for (const key of state.notices.keys()) if (!wanted.has(key)) state.notices.delete(key);
4956
+ const refused = await Promise.all([...wanted.values()].flatMap((entry) => state.bound.has(keyOf(entry)) ? [] : [bind(entry)]));
4957
+ for (const key of state.bound.keys()) state.notices.delete(key);
4958
+ for (const entry of refused) if (entry !== null && !state.notices.has(keyOf(entry))) state.notices.set(keyOf(entry), {
4959
+ entry,
4960
+ reported: false
4961
+ });
4962
+ };
4963
+ const applyLatest = async () => {
4964
+ const next = state.latest;
4965
+ if (next === null || state.applying) return;
4966
+ state.latest = null;
4967
+ state.applying = true;
4968
+ try {
4969
+ await apply(next.published);
4970
+ } finally {
4971
+ state.applying = false;
4972
+ }
4973
+ for (const tag of next.tags) state.syncs.get(tag)?.();
4974
+ await applyLatest();
4975
+ };
4976
+ const received = ({ ports, tag }) => {
4977
+ state.latest = {
4978
+ published: publishedIn(ports),
4979
+ tags: [...state.latest?.tags ?? [], ...tag === null ? [] : [tag]]
4980
+ };
4981
+ applyLatest();
4982
+ };
4983
+ const requestSync = (tag) => {
4984
+ if (state.control?.readyState === WebSocket.OPEN) state.control.send(tag);
4985
+ };
4986
+ const watch = (control) => {
4987
+ state.control = control;
4988
+ control.addEventListener("open", () => {
4989
+ state.failures = 0;
4990
+ for (const tag of state.syncs.keys()) requestSync(tag);
4991
+ });
4992
+ control.addEventListener("message", ({ data }) => {
4993
+ const snapshot = decodeSnapshot(data);
4994
+ if (isSome(snapshot)) received(snapshot.value);
4995
+ });
4996
+ };
4997
+ const connect = async () => {
4998
+ const { attachment } = state;
4999
+ if (attachment === null || state.control !== null || state.connecting) return;
5000
+ state.connecting = true;
5001
+ const { promise: ended, resolve: end } = Promise.withResolvers();
5002
+ const outcome = await attempted(attachment, "/events", (control) => {
5003
+ control.addEventListener("close", () => {
5004
+ end(null);
5005
+ });
5006
+ if (state.attachment?.sandbox === attachment.sandbox) watch(control);
5007
+ else control.close();
5008
+ });
5009
+ state.connecting = false;
5010
+ if (outcome instanceof Error) {
5011
+ state.relay = null;
5012
+ if (isTerminal(outcome)) stop();
5013
+ wakeSyncs();
5014
+ } else if (state.control === outcome) {
5015
+ await ended;
5016
+ if (state.control !== outcome) return;
5017
+ state.control = null;
5018
+ state.relay = null;
5019
+ wakeSyncs();
5020
+ }
5021
+ if (state.attachment === null || state.retry !== null) return;
5022
+ const delay = RETRY_MS[Math.min(state.failures, RETRY_MS.length - 1)];
5023
+ state.failures += 1;
5024
+ state.retry = setTimeout(() => {
5025
+ state.retry = null;
5026
+ connect();
5027
+ }, delay);
5028
+ };
5029
+ const attach = (attachment) => {
5030
+ if (state.attachment?.sandbox !== attachment.sandbox) release();
5031
+ state.attachment = attachment;
5032
+ expireAt(Date.parse(attachment.expires_at));
5033
+ connect();
5034
+ };
5035
+ const synced = async () => {
5036
+ const tag = v7();
5037
+ const { promise, resolve } = Promise.withResolvers();
5038
+ const wake = () => {
5039
+ resolve(null);
5040
+ };
5041
+ const timer = setTimeout(wake, SYNC_MS);
5042
+ state.syncs.set(tag, wake);
5043
+ requestSync(tag);
5044
+ await promise;
5045
+ clearTimeout(timer);
5046
+ state.syncs.delete(tag);
5047
+ };
5048
+ const notices = () => [...state.notices.values()].flatMap((notice) => {
5049
+ if (notice.reported) return [];
5050
+ notice.reported = true;
5051
+ return [notice.entry];
5052
+ });
5053
+ const answer = async (connection) => {
5054
+ connection.on("error", noop);
5055
+ const request = decodeRequest(await requested(connection));
5056
+ if (isNone(request)) {
5057
+ connection.destroy();
5058
+ return;
5059
+ }
5060
+ attach(request.value.attachment);
5061
+ if (request.value.sync) await synced();
5062
+ connection.end(`${JSON.stringify({ unforwarded: notices() })}\n`);
5063
+ };
5064
+ listener.on("connection", (connection) => {
5065
+ answer(connection);
5066
+ });
5067
+ const serving = await servedAt(listener, socketPath);
5068
+ process.stdout.write(READY);
5069
+ if (serving) expireAt(Date.now() + UNATTACHED_MS);
5070
+ };
5071
+ const asked = async ({ line, socketPath }) => {
5072
+ const socket = net.connect(socketPath);
5073
+ const reply = text(socket);
5074
+ socket.end(line);
5075
+ return await reply;
5076
+ };
5077
+ const attachForwarder = async ({ attachment, entry, socketPath, sync }) => {
5078
+ const line = `${JSON.stringify({
5079
+ attachment,
5080
+ sync
5081
+ })}\n`;
5082
+ const reply = await servedOrSpawned({
5083
+ attempt: async () => await asked({
5084
+ line,
5085
+ socketPath
5086
+ }),
5087
+ entry,
5088
+ env: { [FORWARDER_ENV]: socketPath }
5089
+ });
5090
+ return getOrThrowWith(decodeReply(reply), () => /* @__PURE__ */ new Error("The port forwarder stopped before it answered.")).unforwarded;
5091
+ };
5092
+ export { exitCodeOf as $, isOptionValue as A, plainPrefix as B, enabledVariable as C, closest as D, productVariable as E, rerunArgv as F, remoteLine as G, theme as H, valuesOf as I, isDigit as J, remoteText as K, clearLine as L, parseFailure as M, parseLeaf as N, flagOf as O, readOptionToken as P, CliFailure as Q, ellipsis as R, writePrivateFile as S, modeOf as T, escapeUnprintable as U, spinnerFrame as V, remoteCell as W, isUpper as X, isDigits as Y, isWordCharacter as Z, formatMoney as _, RELAY_PORT as a, holdCluster as at, configDirectory as b, onPath as c, Clock as ct, BIN as d, statusOf as et, CLEARABLE as f, formatCount as g, counted as h, forwarderSocket as i, IDLE_WATCHER_ENV as it, lastValue as j, isOptionToken as k, setupDropIns as l, PROBLEM_REPORT_MAX as m, attachForwarder as n, Canceled as nt, RELAY_SOURCE as o, watchIdle as ot, CLI as p, consistsOf as q, forwardPorts as r, IDLE_MS as rt, v7 as s, noop as st, FORWARDER_ENV as t, usageFailure as tt, shimsOf as u, formatPercent as v, guidanceOn as w, withFileLock as x, version as y, glyph as z };