ppio-sandbox 2.1.1 → 2.1.4-a1

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.
Files changed (34) hide show
  1. package/README.md +19 -0
  2. package/dist/{chunk-NRHSODSZ.mjs → chunk-PPBSBQ3N.mjs} +2 -2
  3. package/dist/{chunk-RIWYGA3J.mjs → chunk-Q4BOWZMT.mjs} +2 -2
  4. package/dist/chunk-Q4BOWZMT.mjs.map +1 -0
  5. package/dist/{chunk-M7G3KDGF.mjs → chunk-RWHOETVW.mjs} +695 -327
  6. package/dist/chunk-RWHOETVW.mjs.map +1 -0
  7. package/dist/code-interpreter.d.mts +2 -2
  8. package/dist/code-interpreter.d.ts +2 -2
  9. package/dist/code-interpreter.js +705 -335
  10. package/dist/code-interpreter.js.map +1 -1
  11. package/dist/code-interpreter.mjs +4 -2
  12. package/dist/code-interpreter.mjs.map +1 -1
  13. package/dist/desktop.d.mts +1 -1
  14. package/dist/desktop.d.ts +1 -1
  15. package/dist/desktop.js +705 -335
  16. package/dist/desktop.js.map +1 -1
  17. package/dist/desktop.mjs +4 -2
  18. package/dist/{index-CRwaZUdl.d.mts → index-DIHU8MXT.d.mts} +239 -61
  19. package/dist/{index-CRwaZUdl.d.ts → index-DIHU8MXT.d.ts} +239 -61
  20. package/dist/index.d.mts +2 -2
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.js +705 -335
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.mjs +3 -1
  25. package/dist/sandbox-6EPWOUGN.mjs +8 -0
  26. package/dist/sandbox-OKITI7WW.mjs +8 -0
  27. package/package.json +1 -1
  28. package/dist/chunk-M7G3KDGF.mjs.map +0 -1
  29. package/dist/chunk-RIWYGA3J.mjs.map +0 -1
  30. package/dist/sandbox-5PUSVOHB.mjs +0 -8
  31. package/dist/sandbox-VBQLLX3L.mjs +0 -8
  32. /package/dist/{chunk-NRHSODSZ.mjs.map → chunk-PPBSBQ3N.mjs.map} +0 -0
  33. /package/dist/{sandbox-5PUSVOHB.mjs.map → sandbox-6EPWOUGN.mjs.map} +0 -0
  34. /package/dist/{sandbox-VBQLLX3L.mjs.map → sandbox-OKITI7WW.mjs.map} +0 -0
@@ -60,7 +60,7 @@ import createClient from "openapi-fetch";
60
60
  import platform2 from "platform";
61
61
 
62
62
  // package.json
63
- var version = "2.1.1";
63
+ var version = "2.1.4-a1";
64
64
 
65
65
  // src/core/utils.ts
66
66
  import platform from "platform";
@@ -102,12 +102,6 @@ async function sha256(data) {
102
102
  function timeoutToSeconds(timeout) {
103
103
  return Math.ceil(timeout / 1e3);
104
104
  }
105
- function dynamicRequire(module) {
106
- if (runtime === "browser") {
107
- throw new Error("Browser runtime is not supported for require");
108
- }
109
- return __require(module);
110
- }
111
105
  async function dynamicImport(module) {
112
106
  if (runtime === "browser") {
113
107
  throw new Error("Browser runtime is not supported for dynamic import");
@@ -128,6 +122,9 @@ function toBlob(data) {
128
122
  if (data instanceof Blob) {
129
123
  return data;
130
124
  }
125
+ if (data instanceof Uint8Array) {
126
+ return new Blob([new Uint8Array(data)]);
127
+ }
131
128
  if (typeof data === "string" || data instanceof ArrayBuffer) {
132
129
  return new Blob([data]);
133
130
  }
@@ -138,7 +135,7 @@ function shellQuote(s) {
138
135
  }
139
136
  async function toUploadBody(data, gzip) {
140
137
  if (gzip) {
141
- const stream = data instanceof ReadableStream ? data : data instanceof Blob ? data.stream() : new Blob([data]).stream();
138
+ const stream = data instanceof ReadableStream ? data : (await toBlob(data)).stream();
142
139
  const compressed = stream.pipeThrough(new CompressionStream("gzip"));
143
140
  return new Response(compressed).blob();
144
141
  }
@@ -262,6 +259,8 @@ var FileUploadError = class extends BuildError {
262
259
  this.name = "FileUploadError";
263
260
  }
264
261
  };
262
+ var ImageConfigError = class extends BuildError {
263
+ };
265
264
  var VolumeError = class extends Error {
266
265
  constructor(message) {
267
266
  super(message);
@@ -1458,7 +1457,7 @@ var Filesystem2 = class {
1458
1457
  this.defaultWatchRecursive = false;
1459
1458
  this.rpc = createClient5(Filesystem, transport);
1460
1459
  }
1461
- async read(path2, opts) {
1460
+ async read(path3, opts) {
1462
1461
  var _a3;
1463
1462
  const format = (_a3 = opts == null ? void 0 : opts.format) != null ? _a3 : "text";
1464
1463
  let user = opts == null ? void 0 : opts.user;
@@ -1472,7 +1471,7 @@ var Filesystem2 = class {
1472
1471
  const res = await this.envdApi.api.GET("/files", {
1473
1472
  params: {
1474
1473
  query: {
1475
- path: path2,
1474
+ path: path3,
1476
1475
  username: user
1477
1476
  }
1478
1477
  },
@@ -1505,7 +1504,7 @@ var Filesystem2 = class {
1505
1504
  "Cannot specify both path and array of files. You have to specify either path and data for a single file or an array for multiple files."
1506
1505
  );
1507
1506
  }
1508
- const { path: path2, writeOpts, writeFiles } = typeof pathOrFiles === "string" ? {
1507
+ const { path: path3, writeOpts, writeFiles } = typeof pathOrFiles === "string" ? {
1509
1508
  path: pathOrFiles,
1510
1509
  writeOpts: opts,
1511
1510
  writeFiles: [
@@ -1535,7 +1534,7 @@ var Filesystem2 = class {
1535
1534
  }
1536
1535
  const uploadResults = await Promise.all(
1537
1536
  writeFiles.map(async (file) => {
1538
- const filePath = path2 != null ? path2 : file.path;
1537
+ const filePath = path3 != null ? path3 : file.path;
1539
1538
  const body = await toUploadBody(file.data, useGzip);
1540
1539
  const res = await this.envdApi.api.POST("/files", {
1541
1540
  params: {
@@ -1573,13 +1572,13 @@ var Filesystem2 = class {
1573
1572
  formData.append(
1574
1573
  "file",
1575
1574
  await toBlob(file.data),
1576
- (_a3 = file.path) != null ? _a3 : path2
1575
+ (_a3 = file.path) != null ? _a3 : path3
1577
1576
  );
1578
1577
  }
1579
1578
  const res = await this.envdApi.api.POST("/files", {
1580
1579
  params: {
1581
1580
  query: {
1582
- path: path2,
1581
+ path: path3,
1583
1582
  username: user
1584
1583
  }
1585
1584
  },
@@ -1597,7 +1596,7 @@ var Filesystem2 = class {
1597
1596
  }
1598
1597
  results.push(...files);
1599
1598
  }
1600
- return results.length === 1 && path2 ? results[0] : results;
1599
+ return results.length === 1 && path3 ? results[0] : results;
1601
1600
  }
1602
1601
  /**
1603
1602
  * Write multiple files.
@@ -1625,7 +1624,7 @@ var Filesystem2 = class {
1625
1624
  *
1626
1625
  * @returns list of entries in the sandbox filesystem directory.
1627
1626
  */
1628
- async list(path2, opts) {
1627
+ async list(path3, opts) {
1629
1628
  var _a3;
1630
1629
  if (typeof (opts == null ? void 0 : opts.depth) === "number" && opts.depth < 1) {
1631
1630
  throw new InvalidArgumentError("depth should be at least one");
@@ -1633,7 +1632,7 @@ var Filesystem2 = class {
1633
1632
  try {
1634
1633
  const res = await this.rpc.listDir(
1635
1634
  {
1636
- path: path2,
1635
+ path: path3,
1637
1636
  depth: (_a3 = opts == null ? void 0 : opts.depth) != null ? _a3 : 1
1638
1637
  },
1639
1638
  {
@@ -1672,10 +1671,10 @@ var Filesystem2 = class {
1672
1671
  *
1673
1672
  * @returns `true` if the directory was created, `false` if it already exists.
1674
1673
  */
1675
- async makeDir(path2, opts) {
1674
+ async makeDir(path3, opts) {
1676
1675
  try {
1677
1676
  await this.rpc.makeDir(
1678
- { path: path2 },
1677
+ { path: path3 },
1679
1678
  {
1680
1679
  headers: authenticationHeader(this.envdApi.version, opts == null ? void 0 : opts.user),
1681
1680
  signal: this.connectionConfig.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
@@ -1738,10 +1737,10 @@ var Filesystem2 = class {
1738
1737
  * @param path path to a file or directory.
1739
1738
  * @param opts connection options.
1740
1739
  */
1741
- async remove(path2, opts) {
1740
+ async remove(path3, opts) {
1742
1741
  try {
1743
1742
  await this.rpc.remove(
1744
- { path: path2 },
1743
+ { path: path3 },
1745
1744
  {
1746
1745
  headers: authenticationHeader(this.envdApi.version, opts == null ? void 0 : opts.user),
1747
1746
  signal: this.connectionConfig.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
@@ -1759,10 +1758,10 @@ var Filesystem2 = class {
1759
1758
  *
1760
1759
  * @returns `true` if the file or directory exists, `false` otherwise
1761
1760
  */
1762
- async exists(path2, opts) {
1761
+ async exists(path3, opts) {
1763
1762
  try {
1764
1763
  await this.rpc.stat(
1765
- { path: path2 },
1764
+ { path: path3 },
1766
1765
  {
1767
1766
  headers: authenticationHeader(this.envdApi.version, opts == null ? void 0 : opts.user),
1768
1767
  signal: this.connectionConfig.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
@@ -1786,10 +1785,10 @@ var Filesystem2 = class {
1786
1785
  *
1787
1786
  * @returns information about the file or directory like name, type, and path.
1788
1787
  */
1789
- async getInfo(path2, opts) {
1788
+ async getInfo(path3, opts) {
1790
1789
  try {
1791
1790
  const res = await this.rpc.stat(
1792
- { path: path2 },
1791
+ { path: path3 },
1793
1792
  {
1794
1793
  headers: authenticationHeader(this.envdApi.version, opts == null ? void 0 : opts.user),
1795
1794
  signal: this.connectionConfig.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
@@ -1825,7 +1824,7 @@ var Filesystem2 = class {
1825
1824
  *
1826
1825
  * @returns `WatchHandle` object for stopping watching directory.
1827
1826
  */
1828
- async watchDir(path2, onEvent, opts) {
1827
+ async watchDir(path3, onEvent, opts) {
1829
1828
  var _a3, _b, _c;
1830
1829
  if ((opts == null ? void 0 : opts.recursive) && this.envdApi.version && compareVersions3(this.envdApi.version, ENVD_VERSION_RECURSIVE_WATCH) < 0) {
1831
1830
  throw new TemplateError(
@@ -1839,7 +1838,7 @@ var Filesystem2 = class {
1839
1838
  }, requestTimeoutMs) : void 0;
1840
1839
  const events = this.rpc.watchDir(
1841
1840
  {
1842
- path: path2,
1841
+ path: path3,
1843
1842
  recursive: (_b = opts == null ? void 0 : opts.recursive) != null ? _b : this.defaultWatchRecursive
1844
1843
  },
1845
1844
  {
@@ -2060,11 +2059,11 @@ function parseGitStatus(output) {
2060
2059
  }
2061
2060
  const indexStatus = line[0];
2062
2061
  const workingTreeStatus = line[1];
2063
- const path2 = line.slice(3);
2062
+ const path3 = line.slice(3);
2064
2063
  let renamedFrom;
2065
- let name = path2;
2066
- if (path2.includes(" -> ")) {
2067
- const parts = path2.split(" -> ");
2064
+ let name = path3;
2065
+ if (path3.includes(" -> ")) {
2066
+ const parts = path3.split(" -> ");
2068
2067
  renamedFrom = parts[0];
2069
2068
  name = parts.slice(1).join(" -> ");
2070
2069
  }
@@ -2173,16 +2172,16 @@ function buildUpstreamErrorMessage(action) {
2173
2172
  }
2174
2173
  return "Git pull failed because no upstream branch is configured. Pass remote and branch explicitly, or set upstream once (push with { setUpstream: true } or run: git branch --set-upstream-to=origin/<branch> <branch>).";
2175
2174
  }
2176
- function getRepoPathForScope(scope, path2) {
2175
+ function getRepoPathForScope(scope, path3) {
2177
2176
  if (scope !== "local") {
2178
2177
  return void 0;
2179
2178
  }
2180
- if (!path2) {
2179
+ if (!path3) {
2181
2180
  throw new InvalidArgumentError(
2182
2181
  'A repository path is required when using scope "local".'
2183
2182
  );
2184
2183
  }
2185
- return path2;
2184
+ return path3;
2186
2185
  }
2187
2186
 
2188
2187
  // src/core/sandbox/git/index.ts
@@ -2206,7 +2205,7 @@ var Git = class {
2206
2205
  password,
2207
2206
  branch,
2208
2207
  depth,
2209
- path: path2,
2208
+ path: path3,
2210
2209
  dangerouslyStoreCredentials
2211
2210
  } = _a3, rest = __objRest(_a3, [
2212
2211
  "username",
@@ -2225,7 +2224,7 @@ var Git = class {
2225
2224
  const urlWithCreds = authUsername && authPassword ? withCredentials(url, authUsername, authPassword) : url;
2226
2225
  const sanitizedUrl = stripCredentials(urlWithCreds);
2227
2226
  const stripInlineCreds = !dangerouslyStoreCredentials && sanitizedUrl !== urlWithCreds;
2228
- const repoPath = stripInlineCreds ? path2 != null ? path2 : deriveRepoDirFromUrl(url) : path2;
2227
+ const repoPath = stripInlineCreds ? path3 != null ? path3 : deriveRepoDirFromUrl(url) : path3;
2229
2228
  if (stripInlineCreds && !repoPath) {
2230
2229
  throw new InvalidArgumentError(
2231
2230
  "A destination path is required when using credentials without storing them."
@@ -2263,7 +2262,7 @@ var Git = class {
2263
2262
  * @param opts Init options.
2264
2263
  * @returns Command result from the command runner.
2265
2264
  */
2266
- async init(path2, opts) {
2265
+ async init(path3, opts) {
2267
2266
  const _a3 = opts != null ? opts : {}, { bare, initialBranch } = _a3, rest = __objRest(_a3, ["bare", "initialBranch"]);
2268
2267
  const args = ["init"];
2269
2268
  if (initialBranch) {
@@ -2272,7 +2271,7 @@ var Git = class {
2272
2271
  if (bare) {
2273
2272
  args.push("--bare");
2274
2273
  }
2275
- args.push(path2);
2274
+ args.push(path3);
2276
2275
  return this.runGit(args, void 0, rest);
2277
2276
  }
2278
2277
  /**
@@ -2284,7 +2283,7 @@ var Git = class {
2284
2283
  * @param opts Remote add options.
2285
2284
  * @returns Command result from the command runner.
2286
2285
  */
2287
- async remoteAdd(path2, name, url, opts) {
2286
+ async remoteAdd(path3, name, url, opts) {
2288
2287
  if (!name || !url) {
2289
2288
  throw new InvalidArgumentError(
2290
2289
  "Both remote name and URL are required to add a git remote."
@@ -2297,13 +2296,13 @@ var Git = class {
2297
2296
  }
2298
2297
  addArgs.push(name, url);
2299
2298
  if (!overwrite) {
2300
- return this.runGit(addArgs, path2, rest);
2299
+ return this.runGit(addArgs, path3, rest);
2301
2300
  }
2302
- const addCmd = buildGitCommand(addArgs, path2);
2303
- const setUrlCmd = buildGitCommand(["remote", "set-url", name, url], path2);
2301
+ const addCmd = buildGitCommand(addArgs, path3);
2302
+ const setUrlCmd = buildGitCommand(["remote", "set-url", name, url], path3);
2304
2303
  let cmd = `${addCmd} || ${setUrlCmd}`;
2305
2304
  if (fetch2) {
2306
- const fetchCmd = buildGitCommand(["fetch", name], path2);
2305
+ const fetchCmd = buildGitCommand(["fetch", name], path3);
2307
2306
  cmd = `(${cmd}) && ${fetchCmd}`;
2308
2307
  }
2309
2308
  return this.runShell(cmd, rest);
@@ -2318,11 +2317,11 @@ var Git = class {
2318
2317
  * @param opts Command execution options.
2319
2318
  * @returns Remote URL if present.
2320
2319
  */
2321
- async remoteGet(path2, name, opts) {
2320
+ async remoteGet(path3, name, opts) {
2322
2321
  if (!name) {
2323
2322
  throw new InvalidArgumentError("Remote name is required.");
2324
2323
  }
2325
- const cmd = `${buildGitCommand(["remote", "get-url", name], path2)} || true`;
2324
+ const cmd = `${buildGitCommand(["remote", "get-url", name], path3)} || true`;
2326
2325
  const result = await this.runShell(cmd, opts);
2327
2326
  const trimmed = result.stdout.trim();
2328
2327
  return trimmed.length > 0 ? trimmed : void 0;
@@ -2334,10 +2333,10 @@ var Git = class {
2334
2333
  * @param opts Command execution options.
2335
2334
  * @returns Parsed git status.
2336
2335
  */
2337
- async status(path2, opts) {
2336
+ async status(path3, opts) {
2338
2337
  const result = await this.runGit(
2339
2338
  ["status", "--porcelain=1", "-b"],
2340
- path2,
2339
+ path3,
2341
2340
  opts
2342
2341
  );
2343
2342
  return parseGitStatus(result.stdout);
@@ -2349,10 +2348,10 @@ var Git = class {
2349
2348
  * @param opts Command execution options.
2350
2349
  * @returns Parsed branch list.
2351
2350
  */
2352
- async branches(path2, opts) {
2351
+ async branches(path3, opts) {
2353
2352
  const result = await this.runGit(
2354
2353
  ["branch", "--format=%(refname:short) %(HEAD)"],
2355
- path2,
2354
+ path3,
2356
2355
  opts
2357
2356
  );
2358
2357
  return parseGitBranches(result.stdout);
@@ -2365,8 +2364,8 @@ var Git = class {
2365
2364
  * @param opts Command execution options.
2366
2365
  * @returns Command result from the command runner.
2367
2366
  */
2368
- async createBranch(path2, branch, opts) {
2369
- return this.runGit(["checkout", "-b", branch], path2, opts);
2367
+ async createBranch(path3, branch, opts) {
2368
+ return this.runGit(["checkout", "-b", branch], path3, opts);
2370
2369
  }
2371
2370
  /**
2372
2371
  * Check out an existing branch.
@@ -2376,8 +2375,8 @@ var Git = class {
2376
2375
  * @param opts Command execution options.
2377
2376
  * @returns Command result from the command runner.
2378
2377
  */
2379
- async checkoutBranch(path2, branch, opts) {
2380
- return this.runGit(["checkout", branch], path2, opts);
2378
+ async checkoutBranch(path3, branch, opts) {
2379
+ return this.runGit(["checkout", branch], path3, opts);
2381
2380
  }
2382
2381
  /**
2383
2382
  * Delete a branch.
@@ -2387,10 +2386,10 @@ var Git = class {
2387
2386
  * @param opts Delete options.
2388
2387
  * @returns Command result from the command runner.
2389
2388
  */
2390
- async deleteBranch(path2, branch, opts) {
2389
+ async deleteBranch(path3, branch, opts) {
2391
2390
  const _a3 = opts != null ? opts : {}, { force } = _a3, rest = __objRest(_a3, ["force"]);
2392
2391
  const args = ["branch", force ? "-D" : "-d", branch];
2393
- return this.runGit(args, path2, rest);
2392
+ return this.runGit(args, path3, rest);
2394
2393
  }
2395
2394
  /**
2396
2395
  * Stage files for commit.
@@ -2399,7 +2398,7 @@ var Git = class {
2399
2398
  * @param opts Add options.
2400
2399
  * @returns Command result from the command runner.
2401
2400
  */
2402
- async add(path2, opts) {
2401
+ async add(path3, opts) {
2403
2402
  const _a3 = opts != null ? opts : {}, { files, all = true } = _a3, rest = __objRest(_a3, ["files", "all"]);
2404
2403
  const args = ["add"];
2405
2404
  if (!files || files.length === 0) {
@@ -2407,7 +2406,7 @@ var Git = class {
2407
2406
  } else {
2408
2407
  args.push("--", ...files);
2409
2408
  }
2410
- return this.runGit(args, path2, rest);
2409
+ return this.runGit(args, path3, rest);
2411
2410
  }
2412
2411
  /**
2413
2412
  * Create a commit in the repository.
@@ -2417,7 +2416,7 @@ var Git = class {
2417
2416
  * @param opts Commit options.
2418
2417
  * @returns Command result from the command runner.
2419
2418
  */
2420
- async commit(path2, message, opts) {
2419
+ async commit(path3, message, opts) {
2421
2420
  const _a3 = opts != null ? opts : {}, { authorName, authorEmail, allowEmpty } = _a3, rest = __objRest(_a3, ["authorName", "authorEmail", "allowEmpty"]);
2422
2421
  const args = ["commit", "-m", message];
2423
2422
  if (allowEmpty) {
@@ -2430,7 +2429,7 @@ var Git = class {
2430
2429
  if (authorEmail) {
2431
2430
  authorArgs.push("-c", `user.email=${authorEmail}`);
2432
2431
  }
2433
- return this.runGit([...authorArgs, ...args], path2, rest);
2432
+ return this.runGit([...authorArgs, ...args], path3, rest);
2434
2433
  }
2435
2434
  /**
2436
2435
  * Reset the current HEAD to a specified state.
@@ -2439,7 +2438,7 @@ var Git = class {
2439
2438
  * @param opts Reset options.
2440
2439
  * @returns Command result from the command runner.
2441
2440
  */
2442
- async reset(path2, opts) {
2441
+ async reset(path3, opts) {
2443
2442
  const _a3 = opts != null ? opts : {}, { mode, target, paths: paths2 } = _a3, rest = __objRest(_a3, ["mode", "target", "paths"]);
2444
2443
  const allowedModes = [
2445
2444
  "soft",
@@ -2463,7 +2462,7 @@ var Git = class {
2463
2462
  if (paths2 && paths2.length > 0) {
2464
2463
  args.push("--", ...paths2);
2465
2464
  }
2466
- return this.runGit(args, path2, rest);
2465
+ return this.runGit(args, path3, rest);
2467
2466
  }
2468
2467
  /**
2469
2468
  * Restore working tree files or unstage changes.
@@ -2472,7 +2471,7 @@ var Git = class {
2472
2471
  * @param opts Restore options.
2473
2472
  * @returns Command result from the command runner.
2474
2473
  */
2475
- async restore(path2, opts) {
2474
+ async restore(path3, opts) {
2476
2475
  const _a3 = opts, { paths: paths2, staged, worktree, source } = _a3, rest = __objRest(_a3, ["paths", "staged", "worktree", "source"]);
2477
2476
  if (!paths2 || paths2.length === 0) {
2478
2477
  throw new InvalidArgumentError("At least one path is required.");
@@ -2502,7 +2501,7 @@ var Git = class {
2502
2501
  args.push("--source", source);
2503
2502
  }
2504
2503
  args.push("--", ...paths2);
2505
- return this.runGit(args, path2, rest);
2504
+ return this.runGit(args, path3, rest);
2506
2505
  }
2507
2506
  /**
2508
2507
  * Push commits to a remote.
@@ -2511,7 +2510,7 @@ var Git = class {
2511
2510
  * @param opts Push options.
2512
2511
  * @returns Command result from the command runner.
2513
2512
  */
2514
- async push(path2, opts) {
2513
+ async push(path3, opts) {
2515
2514
  const _a3 = opts != null ? opts : {}, {
2516
2515
  remote,
2517
2516
  branch,
@@ -2531,16 +2530,16 @@ var Git = class {
2531
2530
  );
2532
2531
  }
2533
2532
  if (username && password) {
2534
- const remoteName = await this.resolveRemoteName(path2, remote, rest);
2533
+ const remoteName = await this.resolveRemoteName(path3, remote, rest);
2535
2534
  return this.withRemoteCredentials(
2536
- path2,
2535
+ path3,
2537
2536
  remoteName,
2538
2537
  username,
2539
2538
  password,
2540
2539
  rest,
2541
2540
  () => this.runGit(
2542
2541
  buildPushArgs(remoteName, { remote, branch, setUpstream }),
2543
- path2,
2542
+ path3,
2544
2543
  rest
2545
2544
  )
2546
2545
  );
@@ -2548,7 +2547,7 @@ var Git = class {
2548
2547
  try {
2549
2548
  return await this.runGit(
2550
2549
  buildPushArgs(void 0, { remote, branch, setUpstream }),
2551
- path2,
2550
+ path3,
2552
2551
  rest
2553
2552
  );
2554
2553
  } catch (err) {
@@ -2570,7 +2569,7 @@ var Git = class {
2570
2569
  * @param opts Pull options.
2571
2570
  * @returns Command result from the command runner.
2572
2571
  */
2573
- async pull(path2, opts) {
2572
+ async pull(path3, opts) {
2574
2573
  const _a3 = opts != null ? opts : {}, { remote, branch, username, password } = _a3, rest = __objRest(_a3, ["remote", "branch", "username", "password"]);
2575
2574
  if (password && !username) {
2576
2575
  throw new InvalidArgumentError(
@@ -2578,7 +2577,7 @@ var Git = class {
2578
2577
  );
2579
2578
  }
2580
2579
  if (!remote && !branch) {
2581
- const hasUpstream = await this.hasUpstream(path2, rest);
2580
+ const hasUpstream = await this.hasUpstream(path3, rest);
2582
2581
  if (!hasUpstream) {
2583
2582
  throw new GitUpstreamError(buildUpstreamErrorMessage("pull"));
2584
2583
  }
@@ -2595,18 +2594,18 @@ var Git = class {
2595
2594
  return args;
2596
2595
  };
2597
2596
  if (username && password) {
2598
- const remoteName = await this.resolveRemoteName(path2, remote, rest);
2597
+ const remoteName = await this.resolveRemoteName(path3, remote, rest);
2599
2598
  return this.withRemoteCredentials(
2600
- path2,
2599
+ path3,
2601
2600
  remoteName,
2602
2601
  username,
2603
2602
  password,
2604
2603
  rest,
2605
- () => this.runGit(buildArgs(remoteName), path2, rest)
2604
+ () => this.runGit(buildArgs(remoteName), path3, rest)
2606
2605
  );
2607
2606
  }
2608
2607
  try {
2609
- return await this.runGit(buildArgs(), path2, rest);
2608
+ return await this.runGit(buildArgs(), path3, rest);
2610
2609
  } catch (err) {
2611
2610
  if (isAuthFailure(err)) {
2612
2611
  throw new GitAuthError(
@@ -2743,8 +2742,8 @@ var Git = class {
2743
2742
  envs: mergedEnvs
2744
2743
  }));
2745
2744
  }
2746
- async getRemoteUrl(path2, remote, opts) {
2747
- const result = await this.runGit(["remote", "get-url", remote], path2, opts);
2745
+ async getRemoteUrl(path3, remote, opts) {
2746
+ const result = await this.runGit(["remote", "get-url", remote], path3, opts);
2748
2747
  const url = result.stdout.trim();
2749
2748
  if (!url) {
2750
2749
  throw new InvalidArgumentError(
@@ -2753,11 +2752,11 @@ var Git = class {
2753
2752
  }
2754
2753
  return url;
2755
2754
  }
2756
- async resolveRemoteName(path2, remote, opts) {
2755
+ async resolveRemoteName(path3, remote, opts) {
2757
2756
  if (remote) {
2758
2757
  return remote;
2759
2758
  }
2760
- const result = await this.runGit(["remote"], path2, opts);
2759
+ const result = await this.runGit(["remote"], path3, opts);
2761
2760
  const remotes = result.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
2762
2761
  if (remotes.length === 1) {
2763
2762
  return remotes[0];
@@ -2766,10 +2765,10 @@ var Git = class {
2766
2765
  "Remote is required when using username/password and the repository has multiple remotes."
2767
2766
  );
2768
2767
  }
2769
- async withRemoteCredentials(path2, remote, username, password, opts, operation) {
2770
- const originalUrl = await this.getRemoteUrl(path2, remote, opts);
2768
+ async withRemoteCredentials(path3, remote, username, password, opts, operation) {
2769
+ const originalUrl = await this.getRemoteUrl(path3, remote, opts);
2771
2770
  const credentialUrl = withCredentials(originalUrl, username, password);
2772
- await this.runGit(["remote", "set-url", remote, credentialUrl], path2, opts);
2771
+ await this.runGit(["remote", "set-url", remote, credentialUrl], path3, opts);
2773
2772
  let result;
2774
2773
  let operationError;
2775
2774
  try {
@@ -2779,7 +2778,7 @@ var Git = class {
2779
2778
  }
2780
2779
  let restoreError;
2781
2780
  try {
2782
- await this.runGit(["remote", "set-url", remote, originalUrl], path2, opts);
2781
+ await this.runGit(["remote", "set-url", remote, originalUrl], path3, opts);
2783
2782
  } catch (err) {
2784
2783
  restoreError = err;
2785
2784
  }
@@ -2791,11 +2790,11 @@ var Git = class {
2791
2790
  }
2792
2791
  return result;
2793
2792
  }
2794
- async hasUpstream(path2, opts) {
2793
+ async hasUpstream(path3, opts) {
2795
2794
  try {
2796
2795
  const result = await this.runGit(
2797
2796
  ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"],
2798
- path2,
2797
+ path3,
2799
2798
  opts
2800
2799
  );
2801
2800
  return result.stdout.trim().length > 0;
@@ -2963,11 +2962,11 @@ function normalizeSecretHosts(hosts) {
2963
2962
  }
2964
2963
  return normalizedHosts;
2965
2964
  }
2966
- async function request(method, path2, feature, opts, body) {
2965
+ async function request(method, path3, feature, opts, body) {
2967
2966
  const config = new ConnectionConfig(opts);
2968
2967
  raiseIfLegacy(config, feature, SecretError);
2969
2968
  const headers = __spreadValues(__spreadValues(__spreadValues(__spreadValues({}, config.headers), body ? { "Content-Type": "application/json" } : {}), config.apiKey ? { "X-API-KEY": config.apiKey } : {}), config.accessToken ? { Authorization: `Bearer ${config.accessToken}` } : {});
2970
- const response = await fetch(`${config.apiUrl}${path2}`, {
2969
+ const response = await fetch(`${config.apiUrl}${path3}`, {
2971
2970
  method,
2972
2971
  headers,
2973
2972
  body: body ? JSON.stringify(body) : void 0,
@@ -2999,11 +2998,14 @@ function bindingFromJson(data) {
2999
2998
 
3000
2999
  // src/core/sandbox/sandboxApi.ts
3001
3000
  async function createRawApiError(response) {
3002
- var _a3;
3001
+ var _a3, _b, _c;
3003
3002
  let message = response.statusText;
3004
3003
  try {
3005
3004
  const body = await response.json();
3006
3005
  message = (_a3 = body == null ? void 0 : body.message) != null ? _a3 : JSON.stringify(body);
3006
+ if ((body == null ? void 0 : body.item) || (body == null ? void 0 : body.reason)) {
3007
+ message = `${(_b = body.item) != null ? _b : "request"}: ${(_c = body.reason) != null ? _c : "error"}: ${message}`;
3008
+ }
3007
3009
  } catch (e) {
3008
3010
  try {
3009
3011
  message = await response.text();
@@ -3025,6 +3027,51 @@ async function createRawApiError(response) {
3025
3027
  function getRawApiHeaders(config, headers) {
3026
3028
  return __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({}, defaultHeaders), config.apiKey ? { "X-API-KEY": config.apiKey } : {}), config.accessToken ? { Authorization: `Bearer ${config.accessToken}` } : {}), config.headers), headers != null ? headers : {});
3027
3029
  }
3030
+ var MIB_PER_GIB = 1024;
3031
+ function gibToMib(value, name) {
3032
+ if (!Number.isFinite(value) || value <= 0) {
3033
+ throw new SandboxError(`resource target ${name} must be a positive number`);
3034
+ }
3035
+ const mib = value * MIB_PER_GIB;
3036
+ if (!Number.isSafeInteger(mib)) {
3037
+ throw new SandboxError(`resource target ${name} must be an exact number of MiB`);
3038
+ }
3039
+ return mib;
3040
+ }
3041
+ function resourceTargetsToApi(resources) {
3042
+ const unknown = Object.keys(resources != null ? resources : {}).filter(
3043
+ (key) => !["cpu", "memoryGiB", "diskGiB"].includes(key)
3044
+ );
3045
+ if (unknown.length) throw new SandboxError(`unsupported resource field: ${unknown.join(", ")}`);
3046
+ const body = {};
3047
+ const { cpu, memoryGiB, diskGiB } = resources != null ? resources : {};
3048
+ if (cpu !== void 0) {
3049
+ if (!Number.isSafeInteger(cpu) || cpu <= 0) {
3050
+ throw new SandboxError("resource target cpu must be a positive whole number");
3051
+ }
3052
+ body.vcpu = cpu;
3053
+ }
3054
+ if (memoryGiB !== void 0) body.memory_mb = gibToMib(memoryGiB, "memoryGiB");
3055
+ if (diskGiB !== void 0) body.disk_size_mb = gibToMib(diskGiB, "diskGiB");
3056
+ if (!Object.keys(body).length) throw new SandboxError("at least one resource target is required");
3057
+ return body;
3058
+ }
3059
+ function resizeResultFromApi(data) {
3060
+ var _a3, _b, _c;
3061
+ const result = {};
3062
+ for (const key of ["cpu", "memory", "disk"]) {
3063
+ const item = data == null ? void 0 : data[key];
3064
+ if (!item) continue;
3065
+ const divisor = key === "cpu" ? 1 : 1024;
3066
+ result[key] = __spreadProps(__spreadValues({}, item), {
3067
+ requested: ((_a3 = item.requested) != null ? _a3 : 0) / divisor,
3068
+ previous: ((_b = item.previous) != null ? _b : 0) / divisor,
3069
+ current: ((_c = item.current) != null ? _c : 0) / divisor,
3070
+ unit: key === "cpu" ? "cores" : "GiB"
3071
+ });
3072
+ }
3073
+ return result;
3074
+ }
3028
3075
  function getLifecycle(opts) {
3029
3076
  if (opts == null ? void 0 : opts.lifecycle) {
3030
3077
  return opts.lifecycle;
@@ -3222,28 +3269,24 @@ var SandboxApi = class {
3222
3269
  templateType: "snapshot_template"
3223
3270
  };
3224
3271
  }
3225
- static async hotplugMemory(sandboxId, requestedSizeMib, opts) {
3272
+ static async resize(sandboxId, resources, opts) {
3273
+ const body = resourceTargetsToApi(resources);
3226
3274
  const config = new ConnectionConfig(opts);
3227
- raiseIfLegacy(config, "Sandbox.hotplugMemory", SandboxError);
3275
+ raiseIfLegacy(config, "Sandbox.resize", SandboxError);
3228
3276
  const response = await fetch(
3229
- `${config.apiUrl}/sandboxes/${encodeURIComponent(sandboxId)}/hotplug-memory`,
3277
+ `${config.apiUrl}/sandboxes/${encodeURIComponent(sandboxId)}/resize`,
3230
3278
  {
3231
3279
  method: "POST",
3232
- headers: getRawApiHeaders(config, {
3233
- "Content-Type": "application/json"
3234
- }),
3235
- body: JSON.stringify({
3236
- requested_size_mib: requestedSizeMib
3237
- }),
3280
+ headers: getRawApiHeaders(config, { "Content-Type": "application/json" }),
3281
+ body: JSON.stringify(body),
3238
3282
  signal: config.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
3239
3283
  }
3240
3284
  );
3241
3285
  if (response.status === 404) {
3242
3286
  throw new SandboxNotFoundError(`Sandbox ${sandboxId} not found`);
3243
3287
  }
3244
- if (!response.ok) {
3245
- throw await createRawApiError(response);
3246
- }
3288
+ if (!response.ok) throw await createRawApiError(response);
3289
+ return resizeResultFromApi(await response.json());
3247
3290
  }
3248
3291
  static async reset(sandboxId, opts) {
3249
3292
  var _a3;
@@ -3282,7 +3325,7 @@ var SandboxApi = class {
3282
3325
  }
3283
3326
  return true;
3284
3327
  }
3285
- static async mountVolume(sandboxId, name, path2, opts) {
3328
+ static async mountVolume(sandboxId, name, path3, opts) {
3286
3329
  var _a3, _b;
3287
3330
  const config = new ConnectionConfig(opts);
3288
3331
  raiseIfLegacy(config, "Sandbox.mountVolume", SandboxError);
@@ -3293,7 +3336,7 @@ var SandboxApi = class {
3293
3336
  headers: getRawApiHeaders(config, {
3294
3337
  "Content-Type": "application/json"
3295
3338
  }),
3296
- body: JSON.stringify({ name, path: path2 }),
3339
+ body: JSON.stringify({ name, path: path3 }),
3297
3340
  signal: config.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
3298
3341
  }
3299
3342
  );
@@ -3318,14 +3361,14 @@ var SandboxApi = class {
3318
3361
  volumeMounts: (_b = data.volumeMounts) != null ? _b : []
3319
3362
  };
3320
3363
  }
3321
- static async unmountVolume(sandboxId, path2, opts) {
3364
+ static async unmountVolume(sandboxId, path3, opts) {
3322
3365
  var _a3, _b;
3323
3366
  const config = new ConnectionConfig(opts);
3324
3367
  raiseIfLegacy(config, "Sandbox.unmountVolume", SandboxError);
3325
3368
  const url = new URL(
3326
3369
  `${config.apiUrl}/sandboxes/${encodeURIComponent(sandboxId)}/volume-mounts`
3327
3370
  );
3328
- url.searchParams.set("path", path2);
3371
+ url.searchParams.set("path", path3);
3329
3372
  if (opts == null ? void 0 : opts.force) {
3330
3373
  url.searchParams.set("force", "true");
3331
3374
  }
@@ -3341,7 +3384,7 @@ var SandboxApi = class {
3341
3384
  throw await createRawApiError(response);
3342
3385
  }
3343
3386
  const data = await response.json();
3344
- return {
3387
+ return __spreadProps(__spreadValues({
3345
3388
  sandboxId: data.sandboxID,
3346
3389
  templateId: data.templateID,
3347
3390
  name: data.name,
@@ -3350,10 +3393,11 @@ var SandboxApi = class {
3350
3393
  endAt: new Date(data.endAt),
3351
3394
  state: data.state,
3352
3395
  cpuCount: data.cpuCount,
3353
- memoryMB: data.memoryMB,
3396
+ memoryMB: data.memoryMB
3397
+ }, data.diskSizeMB !== void 0 ? { diskSizeMB: data.diskSizeMB } : {}), {
3354
3398
  envdVersion: data.envdVersion,
3355
3399
  volumeMounts: (_b = data.volumeMounts) != null ? _b : []
3356
- };
3400
+ });
3357
3401
  }
3358
3402
  static async setNetwork(sandboxId, opts) {
3359
3403
  const config = new ConnectionConfig(opts);
@@ -3467,6 +3511,7 @@ var SandboxApi = class {
3467
3511
  state: res.data.state,
3468
3512
  cpuCount: res.data.cpuCount,
3469
3513
  memoryMB: res.data.memoryMB,
3514
+ diskSizeMB: res.data.diskSizeMB,
3470
3515
  network: res.data.network ? {
3471
3516
  allowOut: res.data.network.allowOut,
3472
3517
  denyOut: res.data.network.denyOut,
@@ -3619,17 +3664,25 @@ var SandboxApi = class {
3619
3664
  return true;
3620
3665
  }
3621
3666
  static async createSandbox(template, timeoutMs, opts) {
3622
- var _a3, _b, _c, _d, _e, _f;
3667
+ var _a3, _b, _c, _d, _e, _f, _g, _h;
3623
3668
  const config = new ConnectionConfig(opts);
3669
+ const longRunning = ((_a3 = opts == null ? void 0 : opts.metadata) == null ? void 0 : _a3.long_running) === "true";
3670
+ const metadata = longRunning ? __spreadValues({}, opts == null ? void 0 : opts.metadata) : opts == null ? void 0 : opts.metadata;
3671
+ const timeout = longRunning ? void 0 : timeoutToSeconds(timeoutMs);
3624
3672
  const lifecycle = getLifecycle(opts);
3625
3673
  const autoPause = lifecycle.onTimeout === "pause";
3626
- const autoResumeEnabled = lifecycle.onTimeout === "pause" ? (_a3 = lifecycle.autoResume) != null ? _a3 : false : void 0;
3674
+ const autoResumeEnabled = lifecycle.onTimeout === "pause" ? (_b = lifecycle.autoResume) != null ? _b : false : void 0;
3627
3675
  if (config.isLegacyDomain) {
3628
3676
  if (opts == null ? void 0 : opts.mcp) {
3629
3677
  raiseIfLegacy(config, "Sandbox.create mcp", SandboxError);
3630
3678
  }
3631
- if (opts == null ? void 0 : opts.network) {
3632
- raiseIfLegacy(config, "Sandbox.create network", SandboxError);
3679
+ const unsupportedNetworkOptions = Object.keys((_c = opts == null ? void 0 : opts.network) != null ? _c : {}).filter(
3680
+ (key) => key !== "allowPublicTraffic"
3681
+ );
3682
+ if (unsupportedNetworkOptions.length > 0) {
3683
+ throw new SandboxError(
3684
+ `Sandbox.create network only supports allowPublicTraffic on legacy domains; unsupported options: ${unsupportedNetworkOptions.join(", ")}`
3685
+ );
3633
3686
  }
3634
3687
  if (opts == null ? void 0 : opts.volumeMounts) {
3635
3688
  raiseIfLegacy(config, "Sandbox.create volumeMounts", SandboxError);
@@ -3637,14 +3690,17 @@ var SandboxApi = class {
3637
3690
  if (opts == null ? void 0 : opts.secretEnvs) {
3638
3691
  raiseIfLegacy(config, "Sandbox.create secretEnvs", SandboxError);
3639
3692
  }
3640
- const body2 = __spreadValues({
3693
+ if (opts == null ? void 0 : opts.resources) {
3694
+ raiseIfLegacy(config, "Sandbox.create resources", SandboxError);
3695
+ }
3696
+ const body2 = __spreadValues(__spreadValues({
3641
3697
  templateID: template,
3642
- timeout: timeoutToSeconds(timeoutMs),
3643
- metadata: (_b = opts == null ? void 0 : opts.metadata) != null ? _b : {},
3644
- envVars: (_c = opts == null ? void 0 : opts.envs) != null ? _c : {},
3645
- secure: (_d = opts == null ? void 0 : opts.secure) != null ? _d : false,
3698
+ timeout,
3699
+ metadata: metadata != null ? metadata : {},
3700
+ envVars: (_d = opts == null ? void 0 : opts.envs) != null ? _d : {},
3701
+ secure: (_e = opts == null ? void 0 : opts.secure) != null ? _e : false,
3646
3702
  autoPause: autoPause != null ? autoPause : false
3647
- }, (opts == null ? void 0 : opts.nodeId) ? { nodeID: opts.nodeId } : {});
3703
+ }, (opts == null ? void 0 : opts.network) ? { network: opts.network } : {}), (opts == null ? void 0 : opts.nodeId) ? { nodeID: opts.nodeId } : {});
3648
3704
  const response = await fetch(`${config.apiUrl}/sandboxes`, {
3649
3705
  method: "POST",
3650
3706
  headers: getRawApiHeaders(config, {
@@ -3668,18 +3724,18 @@ var SandboxApi = class {
3668
3724
  sandboxDomain: data.domain || void 0,
3669
3725
  envdVersion: data.envdVersion,
3670
3726
  envdAccessToken: data.envdAccessToken,
3671
- trafficAccessToken: void 0
3727
+ trafficAccessToken: data.trafficAccessToken || void 0
3672
3728
  };
3673
3729
  }
3674
3730
  const client = new ApiClient(config);
3675
3731
  const body = __spreadValues(__spreadValues(__spreadValues({
3676
3732
  templateID: template,
3677
- metadata: opts == null ? void 0 : opts.metadata,
3733
+ metadata,
3678
3734
  mcp: opts == null ? void 0 : opts.mcp,
3679
3735
  envVars: opts == null ? void 0 : opts.envs,
3680
- timeout: timeoutToSeconds(timeoutMs),
3681
- secure: (_e = opts == null ? void 0 : opts.secure) != null ? _e : true,
3682
- allow_internet_access: (_f = opts == null ? void 0 : opts.allowInternetAccess) != null ? _f : true,
3736
+ timeout,
3737
+ secure: (_f = opts == null ? void 0 : opts.secure) != null ? _f : true,
3738
+ allow_internet_access: (_g = opts == null ? void 0 : opts.allowInternetAccess) != null ? _g : true,
3683
3739
  network: opts == null ? void 0 : opts.network
3684
3740
  }, (opts == null ? void 0 : opts.nodeId) ? { nodeID: opts.nodeId } : {}), autoPause !== void 0 ? { autoPause } : {}), autoResumeEnabled !== void 0 ? { autoResume: { enabled: autoResumeEnabled } } : {});
3685
3741
  if (opts == null ? void 0 : opts.volumeMounts) {
@@ -3698,6 +3754,30 @@ var SandboxApi = class {
3698
3754
  ;
3699
3755
  body.secrets = validatedSecretEnvs;
3700
3756
  }
3757
+ if (opts == null ? void 0 : opts.resources) {
3758
+ const targets = resourceTargetsToApi(opts.resources);
3759
+ const response = await fetch(`${config.apiUrl}/sandboxes/custom`, {
3760
+ method: "POST",
3761
+ headers: getRawApiHeaders(config, { "Content-Type": "application/json" }),
3762
+ body: JSON.stringify(__spreadProps(__spreadValues({}, body), { resources: targets })),
3763
+ signal: config.getSignal((_h = opts == null ? void 0 : opts.requestTimeoutMs) != null ? _h : 36e4)
3764
+ });
3765
+ if (!response.ok) throw await createRawApiError(response);
3766
+ const data = await response.json();
3767
+ if (compareVersions4(data.envdVersion, "0.1.0") < 0) {
3768
+ await this.kill(data.sandboxID, opts);
3769
+ throw new TemplateError(
3770
+ "You need to update the template to use the new SDK. You can do this by running `ppio template build` in the directory with the template."
3771
+ );
3772
+ }
3773
+ return {
3774
+ sandboxId: data.sandboxID,
3775
+ sandboxDomain: data.domain || void 0,
3776
+ envdVersion: data.envdVersion,
3777
+ envdAccessToken: data.envdAccessToken,
3778
+ trafficAccessToken: data.trafficAccessToken || void 0
3779
+ };
3780
+ }
3701
3781
  const res = await client.api.POST("/sandboxes", {
3702
3782
  body,
3703
3783
  signal: config.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
@@ -3732,7 +3812,9 @@ var SandboxApi = class {
3732
3812
  headers: getRawApiHeaders(config, {
3733
3813
  "Content-Type": "application/json"
3734
3814
  }),
3735
- body: JSON.stringify({ timeout: timeoutToSeconds(timeoutMs) }),
3815
+ body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues({
3816
+ timeout: timeoutToSeconds(timeoutMs)
3817
+ }, (opts == null ? void 0 : opts.secure) !== void 0 ? { secure: opts.secure } : {}), (opts == null ? void 0 : opts.allowPublicTraffic) !== void 0 ? { allowPublicTraffic: opts.allowPublicTraffic } : {}), (opts == null ? void 0 : opts.network) ? { network: opts.network } : {})),
3736
3818
  signal: config.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
3737
3819
  }
3738
3820
  );
@@ -3748,7 +3830,7 @@ var SandboxApi = class {
3748
3830
  sandboxDomain: data.domain || void 0,
3749
3831
  envdVersion: data.envdVersion || "0.0.0",
3750
3832
  envdAccessToken: data.envdAccessToken,
3751
- trafficAccessToken: void 0
3833
+ trafficAccessToken: data.trafficAccessToken || void 0
3752
3834
  };
3753
3835
  }
3754
3836
  const client = new ApiClient(config);
@@ -4005,7 +4087,7 @@ var SnapshotPaginator = class extends BasePaginator {
4005
4087
 
4006
4088
  // src/core/sandbox/signature.ts
4007
4089
  async function getSignature({
4008
- path: path2,
4090
+ path: path3,
4009
4091
  operation,
4010
4092
  user,
4011
4093
  expirationInSeconds,
@@ -4022,9 +4104,9 @@ async function getSignature({
4022
4104
  user = "";
4023
4105
  }
4024
4106
  if (signatureExpiration === null) {
4025
- signatureRaw = `${path2}:${operation}:${user}:${envdAccessToken}`;
4107
+ signatureRaw = `${path3}:${operation}:${user}:${envdAccessToken}`;
4026
4108
  } else {
4027
- signatureRaw = `${path2}:${operation}:${user}:${envdAccessToken}:${signatureExpiration.toString()}`;
4109
+ signatureRaw = `${path3}:${operation}:${user}:${envdAccessToken}:${signatureExpiration.toString()}`;
4028
4110
  }
4029
4111
  const hashBase64 = await sha256(signatureRaw);
4030
4112
  const signature = "v1_" + hashBase64.replace(/=+$/, "");
@@ -4185,19 +4267,6 @@ var Sandbox = class extends SandboxApi {
4185
4267
  snapshotTemplateId: cloneResult.snapshotTemplateId
4186
4268
  };
4187
4269
  }
4188
- /**
4189
- * Dynamically adjust the hotplugged memory on a running sandbox.
4190
- *
4191
- * The value represents the new *total* plugged size in MiB, not a delta.
4192
- * Use `0` to unplug all hotplugged memory.
4193
- */
4194
- static async hotplugMemory(sandboxId, requestedSizeMib, opts) {
4195
- return await SandboxApi.hotplugMemory(
4196
- sandboxId,
4197
- requestedSizeMib,
4198
- opts
4199
- );
4200
- }
4201
4270
  /**
4202
4271
  * Mount a volume to a sandbox.
4203
4272
  *
@@ -4208,8 +4277,12 @@ var Sandbox = class extends SandboxApi {
4208
4277
  *
4209
4278
  * @returns updated sandbox information.
4210
4279
  */
4211
- static async mountVolume(sandboxId, name, path2, opts) {
4212
- return await SandboxApi.mountVolume(sandboxId, name, path2, opts);
4280
+ /** Increase running sandbox resources to absolute CPU and GiB targets. */
4281
+ static async resize(sandboxId, resources, opts) {
4282
+ return await SandboxApi.resize(sandboxId, resources, opts);
4283
+ }
4284
+ static async mountVolume(sandboxId, name, path3, opts) {
4285
+ return await SandboxApi.mountVolume(sandboxId, name, path3, opts);
4213
4286
  }
4214
4287
  /**
4215
4288
  * Unmount a volume from a sandbox.
@@ -4221,8 +4294,8 @@ var Sandbox = class extends SandboxApi {
4221
4294
  *
4222
4295
  * @returns updated sandbox information.
4223
4296
  */
4224
- static async unmountVolume(sandboxId, path2, opts) {
4225
- return await SandboxApi.unmountVolume(sandboxId, path2, opts);
4297
+ static async unmountVolume(sandboxId, path3, opts) {
4298
+ return await SandboxApi.unmountVolume(sandboxId, path3, opts);
4226
4299
  }
4227
4300
  /**
4228
4301
  * Commit a sandbox to create a snapshot template.
@@ -4457,11 +4530,11 @@ var Sandbox = class extends SandboxApi {
4457
4530
  *
4458
4531
  * @returns updated sandbox information.
4459
4532
  */
4460
- async mountVolume(name, path2, opts) {
4533
+ async mountVolume(name, path3, opts) {
4461
4534
  return await SandboxApi.mountVolume(
4462
4535
  this.sandboxId,
4463
4536
  name,
4464
- path2,
4537
+ path3,
4465
4538
  this.resolveApiOpts(opts)
4466
4539
  );
4467
4540
  }
@@ -4474,10 +4547,10 @@ var Sandbox = class extends SandboxApi {
4474
4547
  *
4475
4548
  * @returns updated sandbox information.
4476
4549
  */
4477
- async unmountVolume(path2, opts) {
4550
+ async unmountVolume(path3, opts) {
4478
4551
  return await SandboxApi.unmountVolume(
4479
4552
  this.sandboxId,
4480
- path2,
4553
+ path3,
4481
4554
  this.resolveApiOpts(opts)
4482
4555
  );
4483
4556
  }
@@ -4492,21 +4565,9 @@ var Sandbox = class extends SandboxApi {
4492
4565
  }
4493
4566
  await SandboxApi.kill(this.sandboxId, this.resolveApiOpts(opts));
4494
4567
  }
4495
- /**
4496
- * Dynamically adjust the hotplugged memory on a running sandbox.
4497
- *
4498
- * The value represents the new *total* plugged size in MiB, not a delta.
4499
- * Use `0` to unplug all hotplugged memory.
4500
- *
4501
- * @param requestedSizeMib new total plugged memory size in MiB.
4502
- * @param opts connection options.
4503
- */
4504
- async hotplugMemory(requestedSizeMib, opts) {
4505
- await SandboxApi.hotplugMemory(
4506
- this.sandboxId,
4507
- requestedSizeMib,
4508
- this.resolveApiOpts(opts)
4509
- );
4568
+ /** Increase this sandbox's resources to absolute CPU and GiB targets. */
4569
+ async resize(resources, opts) {
4570
+ return await SandboxApi.resize(this.sandboxId, resources, this.resolveApiOpts(opts));
4510
4571
  }
4511
4572
  /**
4512
4573
  * Pause a sandbox by its ID.
@@ -4611,7 +4672,7 @@ var Sandbox = class extends SandboxApi {
4611
4672
  *
4612
4673
  * @returns URL for uploading file.
4613
4674
  */
4614
- async uploadUrl(path2, opts) {
4675
+ async uploadUrl(path3, opts) {
4615
4676
  opts = opts != null ? opts : {};
4616
4677
  const useSignature = !!this.envdAccessToken;
4617
4678
  if (!useSignature && opts.useSignatureExpiration != void 0) {
@@ -4623,7 +4684,7 @@ var Sandbox = class extends SandboxApi {
4623
4684
  if (username == void 0 && compareVersions5(this.envdApi.version, ENVD_DEFAULT_USER) < 0) {
4624
4685
  username = defaultUsername;
4625
4686
  }
4626
- const filePath = path2 != null ? path2 : "";
4687
+ const filePath = path3 != null ? path3 : "";
4627
4688
  const fileUrl = this.fileUrl(filePath, username);
4628
4689
  if (useSignature) {
4629
4690
  const url = new URL(fileUrl);
@@ -4651,7 +4712,7 @@ var Sandbox = class extends SandboxApi {
4651
4712
  *
4652
4713
  * @returns URL for downloading file.
4653
4714
  */
4654
- async downloadUrl(path2, opts) {
4715
+ async downloadUrl(path3, opts) {
4655
4716
  opts = opts != null ? opts : {};
4656
4717
  const useSignature = !!this.envdAccessToken;
4657
4718
  if (!useSignature && opts.useSignatureExpiration != void 0) {
@@ -4663,11 +4724,11 @@ var Sandbox = class extends SandboxApi {
4663
4724
  if (username == void 0 && compareVersions5(this.envdApi.version, ENVD_DEFAULT_USER) < 0) {
4664
4725
  username = defaultUsername;
4665
4726
  }
4666
- const fileUrl = this.fileUrl(path2, username);
4727
+ const fileUrl = this.fileUrl(path3, username);
4667
4728
  if (useSignature) {
4668
4729
  const url = new URL(fileUrl);
4669
4730
  const sig = await getSignature({
4670
- path: path2,
4731
+ path: path3,
4671
4732
  operation: "read",
4672
4733
  user: username,
4673
4734
  expirationInSeconds: opts.useSignatureExpiration,
@@ -4721,13 +4782,13 @@ var Sandbox = class extends SandboxApi {
4721
4782
  resolveApiOpts(opts) {
4722
4783
  return __spreadValues(__spreadValues({}, this.connectionConfig), opts != null ? opts : {});
4723
4784
  }
4724
- fileUrl(path2, username) {
4785
+ fileUrl(path3, username) {
4725
4786
  const url = new URL("/files", this.envdApiUrl);
4726
4787
  if (username) {
4727
4788
  url.searchParams.set("username", username);
4728
4789
  }
4729
- if (path2) {
4730
- url.searchParams.set("path", path2);
4790
+ if (path3) {
4791
+ url.searchParams.set("path", path3);
4731
4792
  }
4732
4793
  return url.toString();
4733
4794
  }
@@ -4858,6 +4919,7 @@ function defaultBuildLogger(options) {
4858
4919
  import crypto2 from "crypto";
4859
4920
  import fs from "fs";
4860
4921
  import path from "path";
4922
+ import { fileURLToPath } from "url";
4861
4923
 
4862
4924
  // src/core/template/consts.ts
4863
4925
  var FINALIZE_STEP_NAME = "finalize";
@@ -4908,8 +4970,8 @@ function readDockerignore(contextPath) {
4908
4970
  const content = fs.readFileSync(dockerignorePath, "utf-8");
4909
4971
  return content.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
4910
4972
  }
4911
- function normalizePath(path2) {
4912
- return path2.replace(/\\/g, "/");
4973
+ function normalizePath(path3) {
4974
+ return path3.replace(/\\/g, "/");
4913
4975
  }
4914
4976
  async function getAllFilesInPath(src, contextPath, ignorePatterns, includeDirectories = true) {
4915
4977
  const { glob } = await dynamicImport("glob");
@@ -5021,7 +5083,6 @@ function getCallerDirectory(depth) {
5021
5083
  return void 0;
5022
5084
  }
5023
5085
  if (fileName.startsWith("file:")) {
5024
- const { fileURLToPath } = dynamicRequire("node:url");
5025
5086
  fileName = fileURLToPath(fileName);
5026
5087
  }
5027
5088
  return path.dirname(fileName);
@@ -5482,54 +5543,15 @@ function handleUserInstruction(instruction, templateBuilder) {
5482
5543
  }
5483
5544
  }
5484
5545
  function handleEnvInstruction(instruction, templateBuilder) {
5485
- const argumentsData = instruction.getArguments();
5486
- const keyword = instruction.getKeyword();
5487
- if (argumentsData && argumentsData.length >= 1) {
5488
- const envVars = {};
5489
- if (argumentsData.length === 2) {
5490
- const firstArg = argumentsData[0].getValue();
5491
- const secondArg = argumentsData[1].getValue();
5492
- if (firstArg.includes("=") && secondArg.includes("=")) {
5493
- for (const arg of argumentsData) {
5494
- const envString = arg.getValue();
5495
- const equalIndex = envString.indexOf("=");
5496
- if (equalIndex > 0) {
5497
- const key = envString.substring(0, equalIndex);
5498
- const value = envString.substring(equalIndex + 1);
5499
- envVars[key] = value;
5500
- }
5501
- }
5502
- } else {
5503
- envVars[firstArg] = secondArg;
5504
- }
5505
- } else if (argumentsData.length === 1) {
5506
- const envString = argumentsData[0].getValue();
5507
- const equalIndex = envString.indexOf("=");
5508
- if (equalIndex > 0) {
5509
- const key = envString.substring(0, equalIndex);
5510
- const value = envString.substring(equalIndex + 1);
5511
- envVars[key] = value;
5512
- } else if (keyword === "ARG" && envString.trim()) {
5513
- const key = envString.trim();
5514
- envVars[key] = "";
5515
- }
5516
- } else {
5517
- for (const arg of argumentsData) {
5518
- const envString = arg.getValue();
5519
- const equalIndex = envString.indexOf("=");
5520
- if (equalIndex > 0) {
5521
- const key = envString.substring(0, equalIndex);
5522
- const value = envString.substring(equalIndex + 1);
5523
- envVars[key] = value;
5524
- } else if (keyword === "ARG") {
5525
- const key = envString;
5526
- envVars[key] = "";
5527
- }
5528
- }
5529
- }
5530
- if (Object.keys(envVars).length > 0) {
5531
- templateBuilder.setEnvs(envVars);
5532
- }
5546
+ var _a3;
5547
+ const envVars = {};
5548
+ for (const property of instruction.getProperties()) {
5549
+ envVars[property.getName()] = (_a3 = property.getValue()) != null ? _a3 : "";
5550
+ }
5551
+ if (Object.keys(envVars).length) {
5552
+ templateBuilder.setEnvs(envVars, {
5553
+ runtime: instruction.getKeyword() === "ENV"
5554
+ });
5533
5555
  }
5534
5556
  }
5535
5557
  function handleCmdEntrypointInstruction(instruction, templateBuilder) {
@@ -5551,6 +5573,7 @@ function handleCmdEntrypointInstruction(instruction, templateBuilder) {
5551
5573
  var PROFILE_PATH = "/etc/profile.d/99-image-env.sh";
5552
5574
  var ENVIRONMENT_PATH = "/etc/environment";
5553
5575
  var SCRIPT_PATH = "/tmp/.ppio-image-env.sh";
5576
+ var BASE_ENV_PATH = "/etc/.ppio-image-env-base.sh";
5554
5577
  function unsettableEnvName(name) {
5555
5578
  return !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name);
5556
5579
  }
@@ -5570,54 +5593,112 @@ function expandableDoubleQuote(value) {
5570
5593
  const escaped = value.split("\\").join("\\\\").split('"').join('\\"').split("`").join("\\`").replace(/\$\(/g, "\\$(");
5571
5594
  return `"${escaped}"`;
5572
5595
  }
5573
- function envFilesScript(envs) {
5574
- const lines = [
5575
- "set -e",
5576
- `: > ${PROFILE_PATH}`,
5577
- `: > ${ENVIRONMENT_PATH}`
5578
- ];
5579
- for (const [name, declared] of Object.entries(envs)) {
5596
+ function envFilesScript(envs, literalEnvs = {}, envGroups, baseEnvPath) {
5597
+ const groups = envGroups != null ? envGroups : Object.entries(envs).map(([name, value]) => ({
5598
+ values: { [name]: value },
5599
+ runtime: true
5600
+ }));
5601
+ const lines = String.raw`set -e
5602
+ ${baseEnvPath ? ". " + shellQuote2(baseEnvPath) : ":"}
5603
+ ${baseEnvPath ? "command -p rm -f " + shellQuote2(baseEnvPath) : ":"}
5604
+ if [ -f "${PROFILE_PATH}" ]; then . "${PROFILE_PATH}"; fi
5605
+ command -p touch "${PROFILE_PATH}" "${ENVIRONMENT_PATH}"
5606
+ __ppio_build_env() {
5607
+ while [ "$#" -gt 0 ]; do export "$1=$2"; shift 2; done
5608
+ }
5609
+ __ppio_runtime_env() {
5610
+ while [ "$#" -gt 0 ]; do
5611
+ export "$1=$2"
5612
+ printf "export %s='" "$1" >> ${PROFILE_PATH}
5613
+ printf '%s' "$2" | command -p sed "s/'/'\\\\''/g" >> ${PROFILE_PATH}
5614
+ printf "'\n" >> ${PROFILE_PATH}
5615
+ command -p sed "/^$1=/d" ${ENVIRONMENT_PATH} > ${ENVIRONMENT_PATH}.tmp
5616
+ command -p cat ${ENVIRONMENT_PATH}.tmp > ${ENVIRONMENT_PATH}
5617
+ command -p rm -f ${ENVIRONMENT_PATH}.tmp
5618
+ case "$2" in
5619
+ *'"'*) ;;
5620
+ *) if [ "$(printf '%s' "$2" | command -p wc -l)" -eq 0 ]; then printf '%s=%s\n' "$1" "$2" >> ${ENVIRONMENT_PATH}; fi ;;
5621
+ esac
5622
+ shift 2
5623
+ done
5624
+ }`.split("\n");
5625
+ const quote = (value) => "'" + value.replace(/'/g, "'\\''") + "'";
5626
+ if (Object.keys(literalEnvs).length) {
5627
+ lines.push(
5628
+ "__ppio_runtime_env " + Object.entries(literalEnvs).map(([name, value]) => `${name} ${quote(value)}`).join(" ")
5629
+ );
5630
+ }
5631
+ for (const group of groups) {
5632
+ if (!Object.keys(group.values).length) continue;
5633
+ const fn = group.runtime ? "__ppio_runtime_env" : "__ppio_build_env";
5580
5634
  lines.push(
5581
- // Expand the declared value here, against the build's own environment.
5582
- `v=${expandableDoubleQuote(declared)}`,
5583
- // Export it before moving on, so a later value can reference this one --
5584
- // `ENV VIRTUAL_ENV=/opt/venv PYTHONPATH=$VIRTUAL_ENV/lib` is ordinary, and
5585
- // the platform's own ENV handling cannot be relied on for it (it ignores
5586
- // PATH entirely). Without this the reference expanded to empty.
5587
- `export ${name}="$v"`,
5588
- // profile.d: single-quoted, with any embedded quote closed and reopened.
5589
- `printf "export ${name}='%s'\\n" "$(printf '%s' "$v" | sed "s/'/'\\\\\\\\''/g")" >> ${PROFILE_PATH}`,
5590
- // pam_env: bare, and only when it can represent the value at all.
5591
- 'case "$v" in',
5592
- ` *'"'*) v= ;;`,
5593
- "esac",
5594
- `[ -n "$v" ] && [ "$(printf '%s' "$v" | wc -l)" -eq 0 ] && printf '${name}=%s\\n' "$v" >> ${ENVIRONMENT_PATH}`,
5595
- // `[ ... ] &&` above exits non-zero when the value is skipped, which would
5596
- // abort the script under `set -e`.
5597
- "true"
5635
+ fn + " " + Object.entries(group.values).map(([name, value]) => `${name} ${expandableDoubleQuote(value)}`).join(" ")
5598
5636
  );
5599
5637
  }
5600
- lines.push(`chmod 0644 ${PROFILE_PATH} ${ENVIRONMENT_PATH}`);
5638
+ lines.push(`command -p chmod 0644 ${PROFILE_PATH} ${ENVIRONMENT_PATH}`);
5601
5639
  return lines.join("\n");
5602
5640
  }
5603
- function envFilesCommand(envs) {
5604
- const { usable, skipped } = partitionEnvNames(Object.keys(envs));
5605
- if (usable.length === 0) {
5606
- return { command: null, skipped };
5607
- }
5608
- const script = envFilesScript(
5609
- Object.fromEntries(usable.map((name) => [name, envs[name]]))
5641
+ function envFilesCommand(envs, literalEnvs = {}, envGroups, baseEnvPath) {
5642
+ const groups = envGroups != null ? envGroups : Object.entries(envs).map(([name, value]) => ({
5643
+ values: { [name]: value },
5644
+ runtime: true
5645
+ }));
5646
+ const names = [
5647
+ .../* @__PURE__ */ new Set([
5648
+ ...Object.keys(literalEnvs),
5649
+ ...groups.flatMap((group) => Object.keys(group.values))
5650
+ ])
5651
+ ];
5652
+ const { usable, skipped } = partitionEnvNames(names);
5653
+ const allowed = new Set(usable);
5654
+ const filter = (values) => Object.fromEntries(
5655
+ Object.entries(values).filter(([name]) => allowed.has(name))
5610
5656
  );
5611
- const b64 = Buffer.from(script, "utf8").toString("base64");
5657
+ const literals = filter(literalEnvs);
5658
+ const filtered = groups.map((group) => ({
5659
+ values: filter(group.values),
5660
+ runtime: group.runtime
5661
+ }));
5662
+ if (!Object.keys(literals).length && !filtered.some((group) => group.runtime && Object.keys(group.values).length))
5663
+ return { command: null, skipped };
5664
+ const b64 = Buffer.from(
5665
+ envFilesScript({}, literals, filtered, baseEnvPath),
5666
+ "utf8"
5667
+ ).toString("base64");
5612
5668
  return {
5613
5669
  command: [
5614
- `echo ${b64} | base64 -d > ${SCRIPT_PATH}`,
5615
- `sh ${SCRIPT_PATH}`,
5616
- `rm -f ${SCRIPT_PATH}`
5670
+ `echo ${b64} | command -p base64 -d > ${SCRIPT_PATH}`,
5671
+ `command -p sh ${SCRIPT_PATH}`,
5672
+ `command -p rm -f ${SCRIPT_PATH}`
5617
5673
  ].join(" && "),
5618
5674
  skipped
5619
5675
  };
5620
5676
  }
5677
+ function shellQuote2(value) {
5678
+ return "'" + value.replace(/'/g, "'\\''") + "'";
5679
+ }
5680
+ function envSnapshotCommand(groups) {
5681
+ const { usable } = partitionEnvNames([
5682
+ ...new Set(groups.flatMap((group) => Object.keys(group.values)))
5683
+ ]);
5684
+ if (!usable.length) return null;
5685
+ const lines = [
5686
+ "set -e",
5687
+ "umask 077",
5688
+ `: > ${BASE_ENV_PATH}`,
5689
+ `command -p chmod 0600 ${BASE_ENV_PATH}`
5690
+ ];
5691
+ for (const name of usable) {
5692
+ lines.push(String.raw`if [ "${"${" + name + "+x}"}" = x ]; then
5693
+ printf "export ${name}='" >> ${BASE_ENV_PATH}
5694
+ printf '%s' "${"${" + name + "}"}" | command -p sed "s/'/'\\\\''/g" >> ${BASE_ENV_PATH}
5695
+ printf "'\n" >> ${BASE_ENV_PATH}
5696
+ else
5697
+ printf 'unset ${name}\n' >> ${BASE_ENV_PATH}
5698
+ fi`);
5699
+ }
5700
+ return "command -p sh -c " + shellQuote2(lines.join("\n"));
5701
+ }
5621
5702
 
5622
5703
  // src/core/template/imageConfig.ts
5623
5704
  var HUB_HOST = "registry-1.docker.io";
@@ -5639,6 +5720,7 @@ var SKIP_ENV = /* @__PURE__ */ new Set([
5639
5720
  ]);
5640
5721
  var RETRY_STATUS = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
5641
5722
  var READ_ATTEMPTS = 3;
5723
+ var TOKEN_CLIENT_ID = "ppio-sandbox";
5642
5724
  var backoffBaseMs = 1e3;
5643
5725
  function unsupportedBase(blob) {
5644
5726
  var _a3, _b, _c, _d, _e;
@@ -5652,9 +5734,15 @@ function unsupportedBase(blob) {
5652
5734
  return null;
5653
5735
  }
5654
5736
  const families = [
5655
- [/alpine-minirootfs|etc\/alpine-release|apk add|apk --no-cache/i, "Alpine (musl)"],
5737
+ [
5738
+ /alpine-minirootfs|etc\/alpine-release|apk add|apk --no-cache/i,
5739
+ "Alpine (musl)"
5740
+ ],
5656
5741
  [/^BusyBox /im, "BusyBox"],
5657
- [/microdnf|dnf install|yum install|rpm -i/i, "RPM-based (Fedora/RHEL/Rocky)"],
5742
+ [
5743
+ /microdnf|dnf install|yum install|rpm -i/i,
5744
+ "RPM-based (Fedora/RHEL/Rocky)"
5745
+ ],
5658
5746
  [/pacman -S/i, "Arch"],
5659
5747
  [/zypper|KIWI /i, "SUSE"]
5660
5748
  ];
@@ -5697,7 +5785,7 @@ function parseImageRef(image) {
5697
5785
  let reference;
5698
5786
  const at = ref.indexOf("@");
5699
5787
  if (at !== -1) {
5700
- repository = ref.slice(0, at);
5788
+ repository = ref.slice(0, at).replace(/:[^/]*$/, "");
5701
5789
  reference = ref.slice(at + 1);
5702
5790
  } else {
5703
5791
  const colon = ref.lastIndexOf(":");
@@ -5715,13 +5803,87 @@ function parseImageRef(image) {
5715
5803
  return { host, repository, reference };
5716
5804
  }
5717
5805
  var RegistryHttpError = class extends Error {
5718
- constructor(status, retryAfter, message) {
5806
+ constructor(status, retryAfter, message, challenge = null) {
5719
5807
  super(message);
5720
5808
  this.status = status;
5721
5809
  this.retryAfter = retryAfter;
5810
+ this.challenge = challenge;
5722
5811
  this.name = "RegistryHttpError";
5723
5812
  }
5724
5813
  };
5814
+ function parseChallenges(header) {
5815
+ const text = header != null ? header : "";
5816
+ const challenges = [];
5817
+ let index = 0;
5818
+ const skipSeparators = () => {
5819
+ while (index < text.length && " ,".includes(text[index])) {
5820
+ index++;
5821
+ }
5822
+ };
5823
+ const readToken = () => {
5824
+ const start = index;
5825
+ while (index < text.length && /[A-Za-z0-9\-_.:]/.test(text[index])) {
5826
+ index++;
5827
+ }
5828
+ return text.slice(start, index);
5829
+ };
5830
+ for (; ; ) {
5831
+ skipSeparators();
5832
+ const scheme = readToken();
5833
+ if (!scheme) {
5834
+ break;
5835
+ }
5836
+ const params = {};
5837
+ for (; ; ) {
5838
+ skipSeparators();
5839
+ if (index >= text.length) {
5840
+ break;
5841
+ }
5842
+ const keyStart = index;
5843
+ const key = readToken();
5844
+ if (!key) {
5845
+ break;
5846
+ }
5847
+ while (index < text.length && " ".includes(text[index])) {
5848
+ index++;
5849
+ }
5850
+ if (index >= text.length || text[index] !== "=") {
5851
+ index = keyStart;
5852
+ break;
5853
+ }
5854
+ index++;
5855
+ while (index < text.length && " ".includes(text[index])) {
5856
+ index++;
5857
+ }
5858
+ if (index < text.length && text[index] === '"') {
5859
+ index++;
5860
+ const chars = [];
5861
+ while (index < text.length) {
5862
+ if (text[index] === "\\" && index + 1 < text.length) {
5863
+ chars.push(text[index + 1]);
5864
+ index += 2;
5865
+ continue;
5866
+ }
5867
+ if (text[index] === '"') {
5868
+ index++;
5869
+ break;
5870
+ }
5871
+ chars.push(text[index]);
5872
+ index++;
5873
+ }
5874
+ params[key.toLowerCase()] = chars.join("");
5875
+ } else {
5876
+ const valueStart = index;
5877
+ while (index < text.length && text[index] !== ",") {
5878
+ index++;
5879
+ }
5880
+ params[key.toLowerCase()] = text.slice(valueStart, index).trim();
5881
+ }
5882
+ }
5883
+ challenges.push({ scheme, params });
5884
+ }
5885
+ return challenges;
5886
+ }
5725
5887
  var UnusableImageError = class extends Error {
5726
5888
  constructor(message) {
5727
5889
  super(message);
@@ -5744,19 +5906,27 @@ async function registryGet(url, headers, options) {
5744
5906
  for (let attempt = 0; attempt < attempts; attempt++) {
5745
5907
  if (attempt > 0) {
5746
5908
  await new Promise(
5747
- (resolve) => setTimeout(resolve, retryDelayMs(last, 2 ** (attempt - 1) * backoffBaseMs))
5909
+ (resolve) => setTimeout(
5910
+ resolve,
5911
+ retryDelayMs(last, 2 ** (attempt - 1) * backoffBaseMs)
5912
+ )
5748
5913
  );
5749
5914
  }
5750
5915
  try {
5751
- const response = await fetch(url, {
5916
+ const init = {
5752
5917
  headers,
5753
5918
  signal: AbortSignal.timeout(timeoutMs)
5754
- });
5919
+ };
5920
+ if ((options == null ? void 0 : options.dispatcher) !== void 0) {
5921
+ init.dispatcher = options.dispatcher;
5922
+ }
5923
+ const response = await fetch(url, init);
5755
5924
  if (!response.ok) {
5756
5925
  const error = new RegistryHttpError(
5757
5926
  response.status,
5758
5927
  response.headers.get("retry-after"),
5759
- `HTTP ${response.status} ${response.statusText}`
5928
+ `HTTP ${response.status} ${response.statusText}`,
5929
+ response.headers.get("www-authenticate")
5760
5930
  );
5761
5931
  if (!RETRY_STATUS.has(response.status)) {
5762
5932
  throw error;
@@ -5774,14 +5944,10 @@ async function registryGet(url, headers, options) {
5774
5944
  }
5775
5945
  throw last;
5776
5946
  }
5777
- async function authHeaders(host, repository, credentials) {
5947
+ async function authHeaders(host, repository, credentials, dispatcher) {
5778
5948
  const headers = { Accept: MANIFEST_TYPES };
5779
- if (credentials) {
5780
- const basic = Buffer.from(
5781
- `${credentials.username}:${credentials.password}`,
5782
- "utf8"
5783
- ).toString("base64");
5784
- headers.Authorization = `Basic ${basic}`;
5949
+ if ((credentials == null ? void 0 : credentials.username) && credentials.password) {
5950
+ headers.Authorization = basicHeader(credentials);
5785
5951
  }
5786
5952
  const services = {
5787
5953
  "registry-1.docker.io": ["auth.docker.io", "registry.docker.io"],
@@ -5795,9 +5961,9 @@ async function authHeaders(host, repository, credentials) {
5795
5961
  const url = `https://${authHost}/token?service=${serviceName}&scope=repository:${repository}:pull`;
5796
5962
  try {
5797
5963
  const tokenHeaders = headers.Authorization ? { Authorization: headers.Authorization } : {};
5798
- const body = await registryGet(url, tokenHeaders, {
5964
+ const body = await registryGet(url, tokenHeaders, __spreadValues({
5799
5965
  attempts: 1
5800
- });
5966
+ }, dispatcher === void 0 ? {} : { dispatcher }));
5801
5967
  if (body.token) {
5802
5968
  headers.Authorization = `Bearer ${body.token}`;
5803
5969
  }
@@ -5805,6 +5971,82 @@ async function authHeaders(host, repository, credentials) {
5805
5971
  }
5806
5972
  return headers;
5807
5973
  }
5974
+ var RegistrySession = class {
5975
+ constructor(repository, credentials, headers, dispatcher) {
5976
+ this.repository = repository;
5977
+ this.credentials = credentials;
5978
+ this.headers = headers;
5979
+ this.dispatcher = dispatcher;
5980
+ this.token = null;
5981
+ }
5982
+ /** GET `url`, resolving one Bearer challenge if the registry asks for it. */
5983
+ async get(url) {
5984
+ const headers = __spreadValues({}, this.headers);
5985
+ if (this.token) {
5986
+ headers.Authorization = `Bearer ${this.token}`;
5987
+ }
5988
+ try {
5989
+ return await registryGet(url, headers, __spreadValues({
5990
+ attempts: READ_ATTEMPTS
5991
+ }, this.dispatcher === void 0 ? {} : { dispatcher: this.dispatcher }));
5992
+ } catch (error) {
5993
+ if (!(error instanceof RegistryHttpError) || error.status !== 401) {
5994
+ throw error;
5995
+ }
5996
+ const token = await this.tokenFrom(error.challenge);
5997
+ if (token === null) {
5998
+ throw error;
5999
+ }
6000
+ this.token = token;
6001
+ headers.Authorization = `Bearer ${token}`;
6002
+ return registryGet(url, headers, __spreadValues({
6003
+ attempts: READ_ATTEMPTS
6004
+ }, this.dispatcher === void 0 ? {} : { dispatcher: this.dispatcher }));
6005
+ }
6006
+ }
6007
+ async tokenFrom(challenge) {
6008
+ for (const { scheme, params } of parseChallenges(challenge)) {
6009
+ if (scheme.toLowerCase() === "bearer") {
6010
+ return this.bearer(params);
6011
+ }
6012
+ }
6013
+ return null;
6014
+ }
6015
+ async bearer(params) {
6016
+ var _a3;
6017
+ const realm = params.realm;
6018
+ if (!realm || !/^https?:\/\//.test(realm)) {
6019
+ return null;
6020
+ }
6021
+ const url = new URL(realm);
6022
+ url.searchParams.set("client_id", TOKEN_CLIENT_ID);
6023
+ if (params.service) {
6024
+ url.searchParams.set("service", params.service);
6025
+ }
6026
+ url.searchParams.set(
6027
+ "scope",
6028
+ params.scope || `repository:${this.repository}:pull`
6029
+ );
6030
+ const headers = {};
6031
+ if (((_a3 = this.credentials) == null ? void 0 : _a3.username) && this.credentials.password) {
6032
+ headers.Authorization = basicHeader(this.credentials);
6033
+ }
6034
+ const body = await registryGet(url.toString(), headers, __spreadValues({
6035
+ attempts: 1
6036
+ }, this.dispatcher === void 0 ? {} : { dispatcher: this.dispatcher }));
6037
+ if (body === null || typeof body !== "object") {
6038
+ return null;
6039
+ }
6040
+ return body.token || body.access_token || null;
6041
+ }
6042
+ };
6043
+ function basicHeader(credentials) {
6044
+ const encoded = Buffer.from(
6045
+ `${credentials.username}:${credentials.password}`,
6046
+ "utf8"
6047
+ ).toString("base64");
6048
+ return `Basic ${encoded}`;
6049
+ }
5808
6050
  function platformName(entry) {
5809
6051
  var _a3, _b, _c;
5810
6052
  const p = (_a3 = entry.platform) != null ? _a3 : {};
@@ -5849,41 +6091,53 @@ function describeFailure(error, image, host, repository, authenticated) {
5849
6091
  const reason = `no such image: Docker Hub has no official image '${image}' (HTTP 401). The \`library/\` namespace has no private repositories, so this is a typo rather than a permissions problem`;
5850
6092
  return __spreadProps(__spreadValues({}, empty), { error: reason, unusable: reason });
5851
6093
  }
6094
+ if (error.status === 401) {
6095
+ const reason = authenticated ? `cannot read '${image}' (HTTP 401): the registry rejected the credentials. Check the username, the password, and the read permission on the repository` : `cannot read '${image}' (HTTP 401): the registry wants pull credentials for it. Pass the registry username and password, or check that the reference names an existing public image`;
6096
+ return __spreadProps(__spreadValues({}, empty), { error: reason });
6097
+ }
5852
6098
  return __spreadProps(__spreadValues({}, empty), { error: `${error.name}: ${error.message}` });
5853
6099
  }
5854
6100
  const message = error instanceof Error ? error.message : String(error);
5855
6101
  return __spreadProps(__spreadValues({}, empty), { error: message });
5856
6102
  }
5857
- async function fetchImageConfig(image, credentials) {
6103
+ async function fetchImageConfig(image, credentials, options) {
5858
6104
  var _a3, _b, _c, _d, _e, _f, _g;
6105
+ const dispatcher = options == null ? void 0 : options.dispatcher;
6106
+ const cacheable = dispatcher === void 0 && image.includes("@");
5859
6107
  const key = JSON.stringify([
5860
6108
  image,
5861
6109
  (_a3 = credentials == null ? void 0 : credentials.username) != null ? _a3 : null,
5862
6110
  (_b = credentials == null ? void 0 : credentials.password) != null ? _b : null
5863
6111
  ]);
5864
- const cached = CACHE.get(key);
5865
- if (cached) {
5866
- return copyConfig(cached);
6112
+ if (cacheable) {
6113
+ const cached = CACHE.get(key);
6114
+ if (cached) {
6115
+ return copyConfig(cached);
6116
+ }
5867
6117
  }
5868
6118
  const { host, repository, reference } = parseImageRef(image);
5869
6119
  let result;
5870
6120
  try {
5871
- const auth = await authHeaders(host, repository, credentials);
6121
+ const auth = await authHeaders(host, repository, credentials, dispatcher);
6122
+ const session = new RegistrySession(
6123
+ repository,
6124
+ credentials,
6125
+ auth,
6126
+ dispatcher
6127
+ );
5872
6128
  const base = `https://${host}/v2/${repository}`;
5873
- let manifest = await registryGet(
5874
- `${base}/manifests/${reference}`,
5875
- auth
6129
+ let manifest = await session.get(
6130
+ `${base}/manifests/${reference}`
5876
6131
  );
5877
6132
  if (manifest.manifests) {
5878
6133
  const digest = pickAmd64(manifest, image);
5879
- manifest = await registryGet(`${base}/manifests/${digest}`, auth);
6134
+ manifest = await session.get(`${base}/manifests/${digest}`);
5880
6135
  }
5881
6136
  if (!((_c = manifest.config) == null ? void 0 : _c.digest)) {
5882
6137
  throw new Error(`${image}: manifest names no config blob`);
5883
6138
  }
5884
- const blob = await registryGet(
5885
- `${base}/blobs/${manifest.config.digest}`,
5886
- auth
6139
+ const blob = await session.get(
6140
+ `${base}/blobs/${manifest.config.digest}`
5887
6141
  );
5888
6142
  const declared = (_d = blob.config) != null ? _d : {};
5889
6143
  const env = {};
@@ -5910,10 +6164,14 @@ async function fetchImageConfig(image, credentials) {
5910
6164
  image,
5911
6165
  host,
5912
6166
  repository,
5913
- credentials !== void 0
6167
+ // Both, because that is what the request actually carried: a lone username
6168
+ // is not a credential the registry could have rejected.
6169
+ Boolean((credentials == null ? void 0 : credentials.username) && (credentials == null ? void 0 : credentials.password))
5914
6170
  );
5915
6171
  }
5916
- CACHE.set(key, result);
6172
+ if (cacheable && !result.error) {
6173
+ CACHE.set(key, result);
6174
+ }
5917
6175
  return copyConfig(result);
5918
6176
  }
5919
6177
  function effectiveStartCmd(entrypoint, cmd) {
@@ -5921,7 +6179,7 @@ function effectiveStartCmd(entrypoint, cmd) {
5921
6179
  return parts.length > 0 ? parts.map(shellQuoteArg).join(" ") : null;
5922
6180
  }
5923
6181
  function shellQuoteArg(value) {
5924
- return /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
6182
+ return /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
5925
6183
  }
5926
6184
  function clearImageConfigCache() {
5927
6185
  CACHE.clear();
@@ -6085,6 +6343,8 @@ var TemplateBase = class _TemplateBase {
6085
6343
  // rather than written per call because the file is written once from the full
6086
6344
  // set -- a per-call write would clobber the previous call's file.
6087
6345
  this.envs = {};
6346
+ this.envDeclarations = [];
6347
+ this.imageEnvs = {};
6088
6348
  // Whether to restore what the base image declares -- see fromImage() and
6089
6349
  // resolveInheritedConfig(). Only meaningful for an image base; a Dockerfile
6090
6350
  // states its own ENV/WORKDIR/CMD, and a template base already carries them.
@@ -6096,6 +6356,13 @@ var TemplateBase = class _TemplateBase {
6096
6356
  // image's PATH -- the exact failure this reading exists to prevent.
6097
6357
  this.imageConfigError = void 0;
6098
6358
  this.imageUnusable = void 0;
6359
+ // What a failed read does. "warn" by default: one unreachable registry must not
6360
+ // abort a batch conversion, but a template silently missing the image's PATH is
6361
+ // the failure this reading exists to prevent, so it cannot pass unmentioned.
6362
+ this.imageOnConfigFailure = "warn";
6363
+ // Carries the TLS trust and proxy settings for a self-hosted registry, which
6364
+ // Node's fetch cannot be told about in any other per-request way.
6365
+ this.imageDispatcher = void 0;
6099
6366
  this.fileContextPath = runtime === "browser" ? "." : (_a2 = getCallerDirectory(STACK_TRACE_DEPTH)) != null ? _a2 : ".";
6100
6367
  this.fileIgnorePatterns = [];
6101
6368
  this.logsRefreshFrequency = 200;
@@ -6322,12 +6589,41 @@ var TemplateBase = class _TemplateBase {
6322
6589
  fromBaseImage() {
6323
6590
  return this.fromImage(this.defaultBaseImage);
6324
6591
  }
6592
+ /**
6593
+ * Build from a Docker image, restoring what the image declares.
6594
+ *
6595
+ * The image's ENV, WORKDIR and start command are read from its registry config
6596
+ * because the platform's own pull does not apply them. Reading is best-effort
6597
+ * and asynchronous, so it happens at build/serialize time.
6598
+ *
6599
+ * @param credentials registry username and password, for a private image.
6600
+ * @param options.inheritConfig restore the image's config (default true).
6601
+ * @param options.onConfigFailure what a failed read does — see
6602
+ * {@link ImageConfigFailureMode}. Defaults to `warn`.
6603
+ * @param options.dispatcher Node fetch `dispatcher` (an undici `Agent`), for a
6604
+ * self-hosted registry behind a private CA, a client certificate or a proxy.
6605
+ * For example, with a private CA:
6606
+ *
6607
+ * ```ts
6608
+ * import { Agent } from 'undici'
6609
+ * const dispatcher = new Agent({ connect: { ca: readFileSync('/ca.pem') } })
6610
+ * Template().fromImage('harbor.internal/app:1', undefined, { dispatcher })
6611
+ * ```
6612
+ */
6325
6613
  fromImage(baseImage, credentials, options) {
6326
- var _a3;
6614
+ var _a3, _b;
6615
+ if ((options == null ? void 0 : options.onConfigFailure) !== void 0 && !["warn", "raise", "ignore"].includes(options.onConfigFailure)) {
6616
+ throw new InvalidArgumentError(
6617
+ 'onConfigFailure must be "warn", "raise" or "ignore", got ' + String(options.onConfigFailure)
6618
+ );
6619
+ }
6327
6620
  this.baseImage = baseImage;
6328
6621
  this.baseTemplate = void 0;
6622
+ this.resetInheritedConfig();
6329
6623
  this.inheritImageConfig = (_a3 = options == null ? void 0 : options.inheritConfig) != null ? _a3 : true;
6330
6624
  this.imageCredentials = credentials;
6625
+ this.imageOnConfigFailure = (_b = options == null ? void 0 : options.onConfigFailure) != null ? _b : "warn";
6626
+ this.imageDispatcher = options == null ? void 0 : options.dispatcher;
6331
6627
  if (credentials) {
6332
6628
  this.registryConfig = {
6333
6629
  type: "registry",
@@ -6344,6 +6640,7 @@ var TemplateBase = class _TemplateBase {
6344
6640
  fromTemplate(template) {
6345
6641
  this.baseTemplate = template;
6346
6642
  this.baseImage = void 0;
6643
+ this.resetInheritedConfig();
6347
6644
  if (this.forceNextLayer) {
6348
6645
  this.force = true;
6349
6646
  }
@@ -6358,6 +6655,8 @@ var TemplateBase = class _TemplateBase {
6358
6655
  );
6359
6656
  this.baseImage = baseImage;
6360
6657
  this.baseTemplate = void 0;
6658
+ this.resetInheritedConfig();
6659
+ this.inheritImageConfig = true;
6361
6660
  if (this.forceNextLayer) {
6362
6661
  this.force = true;
6363
6662
  }
@@ -6367,6 +6666,7 @@ var TemplateBase = class _TemplateBase {
6367
6666
  fromAWSRegistry(image, credentials) {
6368
6667
  this.baseImage = image;
6369
6668
  this.baseTemplate = void 0;
6669
+ this.resetInheritedConfig();
6370
6670
  this.registryConfig = {
6371
6671
  type: "aws",
6372
6672
  awsAccessKeyId: credentials.accessKeyId,
@@ -6382,6 +6682,7 @@ var TemplateBase = class _TemplateBase {
6382
6682
  fromGCPRegistry(image, credentials) {
6383
6683
  this.baseImage = image;
6384
6684
  this.baseTemplate = void 0;
6685
+ this.resetInheritedConfig();
6385
6686
  this.registryConfig = {
6386
6687
  type: "gcp",
6387
6688
  serviceAccountJson: readGCPServiceAccountJSON(
@@ -6398,6 +6699,7 @@ var TemplateBase = class _TemplateBase {
6398
6699
  fromOCIRegistry(image, credentials) {
6399
6700
  this.baseImage = image;
6400
6701
  this.baseTemplate = void 0;
6702
+ this.resetInheritedConfig();
6401
6703
  this.registryConfig = {
6402
6704
  type: "oci",
6403
6705
  tenancyOcid: credentials.tenancyOcid,
@@ -6415,6 +6717,7 @@ var TemplateBase = class _TemplateBase {
6415
6717
  fromHuaweiCloudRegistry(image, credentials) {
6416
6718
  this.baseImage = image;
6417
6719
  this.baseTemplate = void 0;
6720
+ this.resetInheritedConfig();
6418
6721
  this.registryConfig = {
6419
6722
  type: "huawei",
6420
6723
  accessKeyId: credentials.accessKeyId,
@@ -6477,8 +6780,8 @@ var TemplateBase = class _TemplateBase {
6477
6780
  });
6478
6781
  return this;
6479
6782
  }
6480
- remove(path2, options) {
6481
- const paths2 = Array.isArray(path2) ? path2 : [path2];
6783
+ remove(path3, options) {
6784
+ const paths2 = Array.isArray(path3) ? path3 : [path3];
6482
6785
  const args = ["rm"];
6483
6786
  if (options == null ? void 0 : options.recursive) {
6484
6787
  args.push("-r");
@@ -6500,8 +6803,8 @@ var TemplateBase = class _TemplateBase {
6500
6803
  () => this.runCmd(args.join(" "), { user: options == null ? void 0 : options.user })
6501
6804
  );
6502
6805
  }
6503
- makeDir(path2, options) {
6504
- const paths2 = Array.isArray(path2) ? path2 : [path2];
6806
+ makeDir(path3, options) {
6807
+ const paths2 = Array.isArray(path3) ? path3 : [path3];
6505
6808
  const args = ["mkdir", "-p"];
6506
6809
  if (options == null ? void 0 : options.mode) {
6507
6810
  args.push(`-m ${padOctal(options.mode)}`);
@@ -6636,7 +6939,7 @@ var TemplateBase = class _TemplateBase {
6636
6939
  })
6637
6940
  );
6638
6941
  }
6639
- gitClone(url, path2, options) {
6942
+ gitClone(url, path3, options) {
6640
6943
  const args = ["git", "clone", url];
6641
6944
  if (options == null ? void 0 : options.branch) {
6642
6945
  args.push(`--branch ${options.branch}`);
@@ -6645,8 +6948,8 @@ var TemplateBase = class _TemplateBase {
6645
6948
  if (options == null ? void 0 : options.depth) {
6646
6949
  args.push(`--depth ${options.depth}`);
6647
6950
  }
6648
- if (path2) {
6649
- args.push(path2.toString());
6951
+ if (path3) {
6952
+ args.push(path3.toString());
6650
6953
  }
6651
6954
  return this.runInNewStackTraceContext(
6652
6955
  () => this.runCmd(args.join(" "), { user: options == null ? void 0 : options.user })
@@ -6676,7 +6979,8 @@ var TemplateBase = class _TemplateBase {
6676
6979
  this.collectStackTrace();
6677
6980
  return this;
6678
6981
  }
6679
- setEnvs(envs) {
6982
+ setEnvs(envs, options) {
6983
+ var _a3;
6680
6984
  if (Object.keys(envs).length === 0) {
6681
6985
  return this;
6682
6986
  }
@@ -6685,7 +6989,11 @@ var TemplateBase = class _TemplateBase {
6685
6989
  args: Object.entries(envs).flatMap(([key, value]) => [key, value]),
6686
6990
  force: this.forceNextLayer
6687
6991
  });
6688
- this.envs = __spreadValues(__spreadValues({}, this.envs), envs);
6992
+ this.envDeclarations.push({
6993
+ values: __spreadValues({}, envs),
6994
+ runtime: (_a3 = options == null ? void 0 : options.runtime) != null ? _a3 : false
6995
+ });
6996
+ if (options == null ? void 0 : options.runtime) this.envs = __spreadValues(__spreadValues({}, this.envs), envs);
6689
6997
  this.collectStackTrace();
6690
6998
  return this;
6691
6999
  }
@@ -6702,7 +7010,12 @@ var TemplateBase = class _TemplateBase {
6702
7010
  * second build of the same template append a duplicate layer.
6703
7011
  */
6704
7012
  runtimeEnvInstruction() {
6705
- const { command } = envFilesCommand(this.envs);
7013
+ const { command } = envFilesCommand(
7014
+ this.envs,
7015
+ this.imageEnvs,
7016
+ this.envDeclarations,
7017
+ envSnapshotCommand(this.envDeclarations) ? BASE_ENV_PATH : void 0
7018
+ );
6706
7019
  if (command === null) {
6707
7020
  return null;
6708
7021
  }
@@ -6721,7 +7034,10 @@ var TemplateBase = class _TemplateBase {
6721
7034
  */
6722
7035
  withRuntimeEnv(instructions) {
6723
7036
  const runtimeEnv = this.runtimeEnvInstruction();
6724
- return runtimeEnv ? [...instructions, runtimeEnv] : instructions;
7037
+ if (!runtimeEnv) return instructions;
7038
+ const snapshot = envSnapshotCommand(this.envDeclarations);
7039
+ const prefix = snapshot ? [{ type: "RUN" /* RUN */, args: [snapshot, "root"], force: false }] : [];
7040
+ return [...prefix, ...instructions, runtimeEnv];
6725
7041
  }
6726
7042
  /**
6727
7043
  * Restore what the base image declares: ENV, WORKDIR and its effective command.
@@ -6742,37 +7058,57 @@ var TemplateBase = class _TemplateBase {
6742
7058
  * restored config — but it is reported, since an image whose toolchain lives
6743
7059
  * behind its ENV will otherwise look installed and behave as though it is not.
6744
7060
  */
7061
+ /** The one wording a failed read is reported with, on every channel. */
7062
+ configFailureMessage() {
7063
+ return `Could not read ${this.baseImage}: ${this.imageConfigError}. The template will build without the environment, working directory and start command the image declares.`;
7064
+ }
7065
+ resetInheritedConfig() {
7066
+ this.imageEnvs = {};
7067
+ this.imageWorkdir = void 0;
7068
+ this.imageStartCmd = void 0;
7069
+ this.imageReadyCmd = void 0;
7070
+ this.imageConfigError = void 0;
7071
+ this.imageUnusable = void 0;
7072
+ this.imageCredentials = void 0;
7073
+ this.imageDispatcher = void 0;
7074
+ this.registryConfig = void 0;
7075
+ this.inheritImageConfig = false;
7076
+ }
6745
7077
  async resolveInheritedConfig(onBuildLogs) {
6746
- var _a3;
7078
+ var _a3, _b;
6747
7079
  if (!this.inheritImageConfig || this.baseImage === void 0) {
6748
7080
  return;
6749
7081
  }
6750
- this.inheritImageConfig = false;
6751
- const config = await fetchImageConfig(this.baseImage, this.imageCredentials);
7082
+ const config = await fetchImageConfig(
7083
+ this.baseImage,
7084
+ this.imageCredentials,
7085
+ this.imageDispatcher === void 0 ? void 0 : { dispatcher: this.imageDispatcher }
7086
+ );
7087
+ this.imageEnvs = {};
7088
+ this.imageWorkdir = void 0;
7089
+ this.imageStartCmd = void 0;
7090
+ this.imageReadyCmd = void 0;
6752
7091
  if (config.error) {
6753
7092
  this.imageConfigError = config.error;
6754
7093
  this.imageUnusable = config.unusable;
6755
- onBuildLogs == null ? void 0 : onBuildLogs(
6756
- new LogEntry(
6757
- /* @__PURE__ */ new Date(),
6758
- "warn",
6759
- `Could not read ${this.baseImage}: ${config.error}. The template will build without the environment, working directory and start command the image declares.`
6760
- )
6761
- );
7094
+ const message = this.configFailureMessage();
7095
+ if (this.imageOnConfigFailure === "raise") {
7096
+ throw new ImageConfigError(message);
7097
+ }
7098
+ if (this.imageOnConfigFailure !== "ignore") {
7099
+ console.warn(message);
7100
+ onBuildLogs == null ? void 0 : onBuildLogs(new LogEntry(/* @__PURE__ */ new Date(), "warn", message));
7101
+ }
6762
7102
  return;
6763
7103
  }
6764
- this.envs = __spreadValues(__spreadValues({}, config.env), this.envs);
6765
- if (config.workdir && !this.instructions.some((i) => i.type === "WORKDIR" /* WORKDIR */)) {
6766
- this.instructions.push({
6767
- type: "WORKDIR" /* WORKDIR */,
6768
- args: [config.workdir],
6769
- force: false
6770
- });
6771
- }
7104
+ this.imageEnvs = __spreadValues({}, config.env);
7105
+ this.imageWorkdir = (_a3 = config.workdir) != null ? _a3 : void 0;
7106
+ this.imageConfigError = void 0;
7107
+ this.imageUnusable = void 0;
6772
7108
  const startCmd = effectiveStartCmd(config.entrypoint, config.cmd);
6773
7109
  if (startCmd && this.startCmd === void 0) {
6774
- this.startCmd = startCmd;
6775
- this.readyCmd = (_a3 = this.readyCmd) != null ? _a3 : waitForTimeout(2e4).getCmd();
7110
+ this.imageStartCmd = startCmd;
7111
+ this.imageReadyCmd = (_b = this.readyCmd) != null ? _b : waitForTimeout(2e4).getCmd();
6776
7112
  }
6777
7113
  }
6778
7114
  /**
@@ -7110,9 +7446,20 @@ var TemplateBase = class _TemplateBase {
7110
7446
  * @returns Template data formatted for the API
7111
7447
  */
7112
7448
  serialize(steps) {
7449
+ var _a3, _b;
7450
+ if (this.imageWorkdir) {
7451
+ steps = [
7452
+ {
7453
+ type: "WORKDIR" /* WORKDIR */,
7454
+ args: [this.imageWorkdir],
7455
+ force: false
7456
+ },
7457
+ ...steps
7458
+ ];
7459
+ }
7113
7460
  const templateData = {
7114
- startCmd: this.startCmd,
7115
- readyCmd: this.readyCmd,
7461
+ startCmd: (_a3 = this.startCmd) != null ? _a3 : this.imageStartCmd,
7462
+ readyCmd: (_b = this.readyCmd) != null ? _b : this.imageReadyCmd,
7116
7463
  preBootScript: this.patchCmd,
7117
7464
  steps,
7118
7465
  force: this.force
@@ -7145,6 +7492,7 @@ Template.list = TemplateBase.list;
7145
7492
  Template.delete = TemplateBase.delete;
7146
7493
  Template.toJSON = TemplateBase.toJSON;
7147
7494
  Template.toDockerfile = TemplateBase.toDockerfile;
7495
+ Template.imageConfigFailure = TemplateBase.imageConfigFailure;
7148
7496
 
7149
7497
  // src/core/volume/index.ts
7150
7498
  function quotaInodesForSize(quotaSizeGiB) {
@@ -7361,6 +7709,8 @@ var Volume = class _Volume {
7361
7709
  };
7362
7710
 
7363
7711
  // src/core/client.ts
7712
+ import path2 from "path";
7713
+ import { fileURLToPath as fileURLToPath2 } from "url";
7364
7714
  function mergeConnectionOpts(base, next) {
7365
7715
  var _a3, _b;
7366
7716
  const baseHeaders = (_a3 = base.headers) != null ? _a3 : {};
@@ -7467,6 +7817,9 @@ var RuntimeSandboxNamespace = class {
7467
7817
  getQuota(opts) {
7468
7818
  return Sandbox.getQuota(mergeConnectionOpts(this.opts, opts));
7469
7819
  }
7820
+ resize(sandboxId, resources, opts) {
7821
+ return Sandbox.resize(sandboxId, resources, mergeConnectionOpts(this.opts, opts));
7822
+ }
7470
7823
  getEvents(opts) {
7471
7824
  return Sandbox.getEvents(mergeConnectionOpts(this.opts, opts));
7472
7825
  }
@@ -7554,6 +7907,9 @@ var SandboxNamespace = class {
7554
7907
  getQuota(opts) {
7555
7908
  return Sandbox.getQuota(mergeConnectionOpts(this.opts, opts));
7556
7909
  }
7910
+ resize(sandboxId, resources, opts) {
7911
+ return Sandbox.resize(sandboxId, resources, mergeConnectionOpts(this.opts, opts));
7912
+ }
7557
7913
  getEvents(opts) {
7558
7914
  return Sandbox.getEvents(mergeConnectionOpts(this.opts, opts));
7559
7915
  }
@@ -7565,7 +7921,18 @@ var TemplateNamespace = class {
7565
7921
  this.toDockerfile = Template.toDockerfile;
7566
7922
  }
7567
7923
  new(options) {
7568
- return Template(options);
7924
+ var _a3;
7925
+ let callerContext = ".";
7926
+ for (const site of callsites(2)) {
7927
+ const fileName = site.getFileName();
7928
+ if (fileName && (!fileName.includes("/src/core/") || fileName.includes("/src/core/tests/")) && !fileName.includes("/node_modules/ppio-sandbox/")) {
7929
+ callerContext = path2.dirname(fileName.startsWith("file:") ? fileURLToPath2(fileName) : fileName);
7930
+ break;
7931
+ }
7932
+ }
7933
+ return Template(__spreadProps(__spreadValues({}, options), {
7934
+ fileContextPath: (_a3 = options == null ? void 0 : options.fileContextPath) != null ? _a3 : callerContext
7935
+ }));
7569
7936
  }
7570
7937
  list(opts) {
7571
7938
  return Template.list(mergeConnectionOpts(this.opts, opts));
@@ -7694,12 +8061,12 @@ var PPIO = class {
7694
8061
  this.secret = new SecretNamespace(opts);
7695
8062
  this.codeInterpreter = new RuntimeSandboxNamespace(
7696
8063
  opts,
7697
- () => import("./sandbox-VBQLLX3L.mjs")
8064
+ () => import("./sandbox-OKITI7WW.mjs")
7698
8065
  );
7699
8066
  this.code_interpreter = this.codeInterpreter;
7700
8067
  this.desktop = new RuntimeSandboxNamespace(
7701
8068
  opts,
7702
- () => import("./sandbox-5PUSVOHB.mjs")
8069
+ () => import("./sandbox-6EPWOUGN.mjs")
7703
8070
  );
7704
8071
  }
7705
8072
  async create(templateOrOpts, opts) {
@@ -7742,6 +8109,7 @@ export {
7742
8109
  RateLimitError,
7743
8110
  BuildError,
7744
8111
  FileUploadError,
8112
+ ImageConfigError,
7745
8113
  VolumeError,
7746
8114
  SecretError,
7747
8115
  ApiClient,
@@ -7777,4 +8145,4 @@ export {
7777
8145
  ALL_TRAFFIC,
7778
8146
  core_default
7779
8147
  };
7780
- //# sourceMappingURL=chunk-M7G3KDGF.mjs.map
8148
+ //# sourceMappingURL=chunk-RWHOETVW.mjs.map