ppio-sandbox 2.1.1 → 2.1.2

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-3L3K3WO3.mjs} +2 -2
  3. package/dist/{chunk-RIWYGA3J.mjs → chunk-3OWF5GCM.mjs} +2 -2
  4. package/dist/chunk-3OWF5GCM.mjs.map +1 -0
  5. package/dist/{chunk-M7G3KDGF.mjs → chunk-PQGBLWKQ.mjs} +593 -283
  6. package/dist/chunk-PQGBLWKQ.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 +602 -290
  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 +602 -290
  16. package/dist/desktop.js.map +1 -1
  17. package/dist/desktop.mjs +4 -2
  18. package/dist/{index-CRwaZUdl.d.mts → index-CAD08VLb.d.mts} +76 -58
  19. package/dist/{index-CRwaZUdl.d.ts → index-CAD08VLb.d.ts} +76 -58
  20. package/dist/index.d.mts +2 -2
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.js +602 -290
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.mjs +3 -1
  25. package/dist/sandbox-DMY2YDSO.mjs +8 -0
  26. package/dist/sandbox-TS3DDCSN.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-3L3K3WO3.mjs.map} +0 -0
  33. /package/dist/{sandbox-5PUSVOHB.mjs.map → sandbox-DMY2YDSO.mjs.map} +0 -0
  34. /package/dist/{sandbox-VBQLLX3L.mjs.map → sandbox-TS3DDCSN.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.2";
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,
@@ -3282,7 +3281,7 @@ var SandboxApi = class {
3282
3281
  }
3283
3282
  return true;
3284
3283
  }
3285
- static async mountVolume(sandboxId, name, path2, opts) {
3284
+ static async mountVolume(sandboxId, name, path3, opts) {
3286
3285
  var _a3, _b;
3287
3286
  const config = new ConnectionConfig(opts);
3288
3287
  raiseIfLegacy(config, "Sandbox.mountVolume", SandboxError);
@@ -3293,7 +3292,7 @@ var SandboxApi = class {
3293
3292
  headers: getRawApiHeaders(config, {
3294
3293
  "Content-Type": "application/json"
3295
3294
  }),
3296
- body: JSON.stringify({ name, path: path2 }),
3295
+ body: JSON.stringify({ name, path: path3 }),
3297
3296
  signal: config.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
3298
3297
  }
3299
3298
  );
@@ -3318,14 +3317,14 @@ var SandboxApi = class {
3318
3317
  volumeMounts: (_b = data.volumeMounts) != null ? _b : []
3319
3318
  };
3320
3319
  }
3321
- static async unmountVolume(sandboxId, path2, opts) {
3320
+ static async unmountVolume(sandboxId, path3, opts) {
3322
3321
  var _a3, _b;
3323
3322
  const config = new ConnectionConfig(opts);
3324
3323
  raiseIfLegacy(config, "Sandbox.unmountVolume", SandboxError);
3325
3324
  const url = new URL(
3326
3325
  `${config.apiUrl}/sandboxes/${encodeURIComponent(sandboxId)}/volume-mounts`
3327
3326
  );
3328
- url.searchParams.set("path", path2);
3327
+ url.searchParams.set("path", path3);
3329
3328
  if (opts == null ? void 0 : opts.force) {
3330
3329
  url.searchParams.set("force", "true");
3331
3330
  }
@@ -3619,17 +3618,25 @@ var SandboxApi = class {
3619
3618
  return true;
3620
3619
  }
3621
3620
  static async createSandbox(template, timeoutMs, opts) {
3622
- var _a3, _b, _c, _d, _e, _f;
3621
+ var _a3, _b, _c, _d, _e, _f, _g;
3623
3622
  const config = new ConnectionConfig(opts);
3623
+ const longRunning = ((_a3 = opts == null ? void 0 : opts.metadata) == null ? void 0 : _a3.long_running) === "true";
3624
+ const metadata = longRunning ? __spreadValues({}, opts == null ? void 0 : opts.metadata) : opts == null ? void 0 : opts.metadata;
3625
+ const timeout = longRunning ? void 0 : timeoutToSeconds(timeoutMs);
3624
3626
  const lifecycle = getLifecycle(opts);
3625
3627
  const autoPause = lifecycle.onTimeout === "pause";
3626
- const autoResumeEnabled = lifecycle.onTimeout === "pause" ? (_a3 = lifecycle.autoResume) != null ? _a3 : false : void 0;
3628
+ const autoResumeEnabled = lifecycle.onTimeout === "pause" ? (_b = lifecycle.autoResume) != null ? _b : false : void 0;
3627
3629
  if (config.isLegacyDomain) {
3628
3630
  if (opts == null ? void 0 : opts.mcp) {
3629
3631
  raiseIfLegacy(config, "Sandbox.create mcp", SandboxError);
3630
3632
  }
3631
- if (opts == null ? void 0 : opts.network) {
3632
- raiseIfLegacy(config, "Sandbox.create network", SandboxError);
3633
+ const unsupportedNetworkOptions = Object.keys((_c = opts == null ? void 0 : opts.network) != null ? _c : {}).filter(
3634
+ (key) => key !== "allowPublicTraffic"
3635
+ );
3636
+ if (unsupportedNetworkOptions.length > 0) {
3637
+ throw new SandboxError(
3638
+ `Sandbox.create network only supports allowPublicTraffic on legacy domains; unsupported options: ${unsupportedNetworkOptions.join(", ")}`
3639
+ );
3633
3640
  }
3634
3641
  if (opts == null ? void 0 : opts.volumeMounts) {
3635
3642
  raiseIfLegacy(config, "Sandbox.create volumeMounts", SandboxError);
@@ -3637,14 +3644,14 @@ var SandboxApi = class {
3637
3644
  if (opts == null ? void 0 : opts.secretEnvs) {
3638
3645
  raiseIfLegacy(config, "Sandbox.create secretEnvs", SandboxError);
3639
3646
  }
3640
- const body2 = __spreadValues({
3647
+ const body2 = __spreadValues(__spreadValues({
3641
3648
  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,
3649
+ timeout,
3650
+ metadata: metadata != null ? metadata : {},
3651
+ envVars: (_d = opts == null ? void 0 : opts.envs) != null ? _d : {},
3652
+ secure: (_e = opts == null ? void 0 : opts.secure) != null ? _e : false,
3646
3653
  autoPause: autoPause != null ? autoPause : false
3647
- }, (opts == null ? void 0 : opts.nodeId) ? { nodeID: opts.nodeId } : {});
3654
+ }, (opts == null ? void 0 : opts.network) ? { network: opts.network } : {}), (opts == null ? void 0 : opts.nodeId) ? { nodeID: opts.nodeId } : {});
3648
3655
  const response = await fetch(`${config.apiUrl}/sandboxes`, {
3649
3656
  method: "POST",
3650
3657
  headers: getRawApiHeaders(config, {
@@ -3668,18 +3675,18 @@ var SandboxApi = class {
3668
3675
  sandboxDomain: data.domain || void 0,
3669
3676
  envdVersion: data.envdVersion,
3670
3677
  envdAccessToken: data.envdAccessToken,
3671
- trafficAccessToken: void 0
3678
+ trafficAccessToken: data.trafficAccessToken || void 0
3672
3679
  };
3673
3680
  }
3674
3681
  const client = new ApiClient(config);
3675
3682
  const body = __spreadValues(__spreadValues(__spreadValues({
3676
3683
  templateID: template,
3677
- metadata: opts == null ? void 0 : opts.metadata,
3684
+ metadata,
3678
3685
  mcp: opts == null ? void 0 : opts.mcp,
3679
3686
  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,
3687
+ timeout,
3688
+ secure: (_f = opts == null ? void 0 : opts.secure) != null ? _f : true,
3689
+ allow_internet_access: (_g = opts == null ? void 0 : opts.allowInternetAccess) != null ? _g : true,
3683
3690
  network: opts == null ? void 0 : opts.network
3684
3691
  }, (opts == null ? void 0 : opts.nodeId) ? { nodeID: opts.nodeId } : {}), autoPause !== void 0 ? { autoPause } : {}), autoResumeEnabled !== void 0 ? { autoResume: { enabled: autoResumeEnabled } } : {});
3685
3692
  if (opts == null ? void 0 : opts.volumeMounts) {
@@ -3732,7 +3739,9 @@ var SandboxApi = class {
3732
3739
  headers: getRawApiHeaders(config, {
3733
3740
  "Content-Type": "application/json"
3734
3741
  }),
3735
- body: JSON.stringify({ timeout: timeoutToSeconds(timeoutMs) }),
3742
+ body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues({
3743
+ timeout: timeoutToSeconds(timeoutMs)
3744
+ }, (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
3745
  signal: config.getSignal(opts == null ? void 0 : opts.requestTimeoutMs)
3737
3746
  }
3738
3747
  );
@@ -3748,7 +3757,7 @@ var SandboxApi = class {
3748
3757
  sandboxDomain: data.domain || void 0,
3749
3758
  envdVersion: data.envdVersion || "0.0.0",
3750
3759
  envdAccessToken: data.envdAccessToken,
3751
- trafficAccessToken: void 0
3760
+ trafficAccessToken: data.trafficAccessToken || void 0
3752
3761
  };
3753
3762
  }
3754
3763
  const client = new ApiClient(config);
@@ -4005,7 +4014,7 @@ var SnapshotPaginator = class extends BasePaginator {
4005
4014
 
4006
4015
  // src/core/sandbox/signature.ts
4007
4016
  async function getSignature({
4008
- path: path2,
4017
+ path: path3,
4009
4018
  operation,
4010
4019
  user,
4011
4020
  expirationInSeconds,
@@ -4022,9 +4031,9 @@ async function getSignature({
4022
4031
  user = "";
4023
4032
  }
4024
4033
  if (signatureExpiration === null) {
4025
- signatureRaw = `${path2}:${operation}:${user}:${envdAccessToken}`;
4034
+ signatureRaw = `${path3}:${operation}:${user}:${envdAccessToken}`;
4026
4035
  } else {
4027
- signatureRaw = `${path2}:${operation}:${user}:${envdAccessToken}:${signatureExpiration.toString()}`;
4036
+ signatureRaw = `${path3}:${operation}:${user}:${envdAccessToken}:${signatureExpiration.toString()}`;
4028
4037
  }
4029
4038
  const hashBase64 = await sha256(signatureRaw);
4030
4039
  const signature = "v1_" + hashBase64.replace(/=+$/, "");
@@ -4208,8 +4217,8 @@ var Sandbox = class extends SandboxApi {
4208
4217
  *
4209
4218
  * @returns updated sandbox information.
4210
4219
  */
4211
- static async mountVolume(sandboxId, name, path2, opts) {
4212
- return await SandboxApi.mountVolume(sandboxId, name, path2, opts);
4220
+ static async mountVolume(sandboxId, name, path3, opts) {
4221
+ return await SandboxApi.mountVolume(sandboxId, name, path3, opts);
4213
4222
  }
4214
4223
  /**
4215
4224
  * Unmount a volume from a sandbox.
@@ -4221,8 +4230,8 @@ var Sandbox = class extends SandboxApi {
4221
4230
  *
4222
4231
  * @returns updated sandbox information.
4223
4232
  */
4224
- static async unmountVolume(sandboxId, path2, opts) {
4225
- return await SandboxApi.unmountVolume(sandboxId, path2, opts);
4233
+ static async unmountVolume(sandboxId, path3, opts) {
4234
+ return await SandboxApi.unmountVolume(sandboxId, path3, opts);
4226
4235
  }
4227
4236
  /**
4228
4237
  * Commit a sandbox to create a snapshot template.
@@ -4457,11 +4466,11 @@ var Sandbox = class extends SandboxApi {
4457
4466
  *
4458
4467
  * @returns updated sandbox information.
4459
4468
  */
4460
- async mountVolume(name, path2, opts) {
4469
+ async mountVolume(name, path3, opts) {
4461
4470
  return await SandboxApi.mountVolume(
4462
4471
  this.sandboxId,
4463
4472
  name,
4464
- path2,
4473
+ path3,
4465
4474
  this.resolveApiOpts(opts)
4466
4475
  );
4467
4476
  }
@@ -4474,10 +4483,10 @@ var Sandbox = class extends SandboxApi {
4474
4483
  *
4475
4484
  * @returns updated sandbox information.
4476
4485
  */
4477
- async unmountVolume(path2, opts) {
4486
+ async unmountVolume(path3, opts) {
4478
4487
  return await SandboxApi.unmountVolume(
4479
4488
  this.sandboxId,
4480
- path2,
4489
+ path3,
4481
4490
  this.resolveApiOpts(opts)
4482
4491
  );
4483
4492
  }
@@ -4611,7 +4620,7 @@ var Sandbox = class extends SandboxApi {
4611
4620
  *
4612
4621
  * @returns URL for uploading file.
4613
4622
  */
4614
- async uploadUrl(path2, opts) {
4623
+ async uploadUrl(path3, opts) {
4615
4624
  opts = opts != null ? opts : {};
4616
4625
  const useSignature = !!this.envdAccessToken;
4617
4626
  if (!useSignature && opts.useSignatureExpiration != void 0) {
@@ -4623,7 +4632,7 @@ var Sandbox = class extends SandboxApi {
4623
4632
  if (username == void 0 && compareVersions5(this.envdApi.version, ENVD_DEFAULT_USER) < 0) {
4624
4633
  username = defaultUsername;
4625
4634
  }
4626
- const filePath = path2 != null ? path2 : "";
4635
+ const filePath = path3 != null ? path3 : "";
4627
4636
  const fileUrl = this.fileUrl(filePath, username);
4628
4637
  if (useSignature) {
4629
4638
  const url = new URL(fileUrl);
@@ -4651,7 +4660,7 @@ var Sandbox = class extends SandboxApi {
4651
4660
  *
4652
4661
  * @returns URL for downloading file.
4653
4662
  */
4654
- async downloadUrl(path2, opts) {
4663
+ async downloadUrl(path3, opts) {
4655
4664
  opts = opts != null ? opts : {};
4656
4665
  const useSignature = !!this.envdAccessToken;
4657
4666
  if (!useSignature && opts.useSignatureExpiration != void 0) {
@@ -4663,11 +4672,11 @@ var Sandbox = class extends SandboxApi {
4663
4672
  if (username == void 0 && compareVersions5(this.envdApi.version, ENVD_DEFAULT_USER) < 0) {
4664
4673
  username = defaultUsername;
4665
4674
  }
4666
- const fileUrl = this.fileUrl(path2, username);
4675
+ const fileUrl = this.fileUrl(path3, username);
4667
4676
  if (useSignature) {
4668
4677
  const url = new URL(fileUrl);
4669
4678
  const sig = await getSignature({
4670
- path: path2,
4679
+ path: path3,
4671
4680
  operation: "read",
4672
4681
  user: username,
4673
4682
  expirationInSeconds: opts.useSignatureExpiration,
@@ -4721,13 +4730,13 @@ var Sandbox = class extends SandboxApi {
4721
4730
  resolveApiOpts(opts) {
4722
4731
  return __spreadValues(__spreadValues({}, this.connectionConfig), opts != null ? opts : {});
4723
4732
  }
4724
- fileUrl(path2, username) {
4733
+ fileUrl(path3, username) {
4725
4734
  const url = new URL("/files", this.envdApiUrl);
4726
4735
  if (username) {
4727
4736
  url.searchParams.set("username", username);
4728
4737
  }
4729
- if (path2) {
4730
- url.searchParams.set("path", path2);
4738
+ if (path3) {
4739
+ url.searchParams.set("path", path3);
4731
4740
  }
4732
4741
  return url.toString();
4733
4742
  }
@@ -4858,6 +4867,7 @@ function defaultBuildLogger(options) {
4858
4867
  import crypto2 from "crypto";
4859
4868
  import fs from "fs";
4860
4869
  import path from "path";
4870
+ import { fileURLToPath } from "url";
4861
4871
 
4862
4872
  // src/core/template/consts.ts
4863
4873
  var FINALIZE_STEP_NAME = "finalize";
@@ -4908,8 +4918,8 @@ function readDockerignore(contextPath) {
4908
4918
  const content = fs.readFileSync(dockerignorePath, "utf-8");
4909
4919
  return content.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
4910
4920
  }
4911
- function normalizePath(path2) {
4912
- return path2.replace(/\\/g, "/");
4921
+ function normalizePath(path3) {
4922
+ return path3.replace(/\\/g, "/");
4913
4923
  }
4914
4924
  async function getAllFilesInPath(src, contextPath, ignorePatterns, includeDirectories = true) {
4915
4925
  const { glob } = await dynamicImport("glob");
@@ -5021,7 +5031,6 @@ function getCallerDirectory(depth) {
5021
5031
  return void 0;
5022
5032
  }
5023
5033
  if (fileName.startsWith("file:")) {
5024
- const { fileURLToPath } = dynamicRequire("node:url");
5025
5034
  fileName = fileURLToPath(fileName);
5026
5035
  }
5027
5036
  return path.dirname(fileName);
@@ -5482,54 +5491,15 @@ function handleUserInstruction(instruction, templateBuilder) {
5482
5491
  }
5483
5492
  }
5484
5493
  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
- }
5494
+ var _a3;
5495
+ const envVars = {};
5496
+ for (const property of instruction.getProperties()) {
5497
+ envVars[property.getName()] = (_a3 = property.getValue()) != null ? _a3 : "";
5498
+ }
5499
+ if (Object.keys(envVars).length) {
5500
+ templateBuilder.setEnvs(envVars, {
5501
+ runtime: instruction.getKeyword() === "ENV"
5502
+ });
5533
5503
  }
5534
5504
  }
5535
5505
  function handleCmdEntrypointInstruction(instruction, templateBuilder) {
@@ -5551,6 +5521,7 @@ function handleCmdEntrypointInstruction(instruction, templateBuilder) {
5551
5521
  var PROFILE_PATH = "/etc/profile.d/99-image-env.sh";
5552
5522
  var ENVIRONMENT_PATH = "/etc/environment";
5553
5523
  var SCRIPT_PATH = "/tmp/.ppio-image-env.sh";
5524
+ var BASE_ENV_PATH = "/etc/.ppio-image-env-base.sh";
5554
5525
  function unsettableEnvName(name) {
5555
5526
  return !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name);
5556
5527
  }
@@ -5570,54 +5541,112 @@ function expandableDoubleQuote(value) {
5570
5541
  const escaped = value.split("\\").join("\\\\").split('"').join('\\"').split("`").join("\\`").replace(/\$\(/g, "\\$(");
5571
5542
  return `"${escaped}"`;
5572
5543
  }
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)) {
5544
+ function envFilesScript(envs, literalEnvs = {}, envGroups, baseEnvPath) {
5545
+ const groups = envGroups != null ? envGroups : Object.entries(envs).map(([name, value]) => ({
5546
+ values: { [name]: value },
5547
+ runtime: true
5548
+ }));
5549
+ const lines = String.raw`set -e
5550
+ ${baseEnvPath ? ". " + shellQuote2(baseEnvPath) : ":"}
5551
+ ${baseEnvPath ? "command -p rm -f " + shellQuote2(baseEnvPath) : ":"}
5552
+ if [ -f "${PROFILE_PATH}" ]; then . "${PROFILE_PATH}"; fi
5553
+ command -p touch "${PROFILE_PATH}" "${ENVIRONMENT_PATH}"
5554
+ __ppio_build_env() {
5555
+ while [ "$#" -gt 0 ]; do export "$1=$2"; shift 2; done
5556
+ }
5557
+ __ppio_runtime_env() {
5558
+ while [ "$#" -gt 0 ]; do
5559
+ export "$1=$2"
5560
+ printf "export %s='" "$1" >> ${PROFILE_PATH}
5561
+ printf '%s' "$2" | command -p sed "s/'/'\\\\''/g" >> ${PROFILE_PATH}
5562
+ printf "'\n" >> ${PROFILE_PATH}
5563
+ command -p sed "/^$1=/d" ${ENVIRONMENT_PATH} > ${ENVIRONMENT_PATH}.tmp
5564
+ command -p cat ${ENVIRONMENT_PATH}.tmp > ${ENVIRONMENT_PATH}
5565
+ command -p rm -f ${ENVIRONMENT_PATH}.tmp
5566
+ case "$2" in
5567
+ *'"'*) ;;
5568
+ *) if [ "$(printf '%s' "$2" | command -p wc -l)" -eq 0 ]; then printf '%s=%s\n' "$1" "$2" >> ${ENVIRONMENT_PATH}; fi ;;
5569
+ esac
5570
+ shift 2
5571
+ done
5572
+ }`.split("\n");
5573
+ const quote = (value) => "'" + value.replace(/'/g, "'\\''") + "'";
5574
+ if (Object.keys(literalEnvs).length) {
5580
5575
  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"
5576
+ "__ppio_runtime_env " + Object.entries(literalEnvs).map(([name, value]) => `${name} ${quote(value)}`).join(" ")
5598
5577
  );
5599
5578
  }
5600
- lines.push(`chmod 0644 ${PROFILE_PATH} ${ENVIRONMENT_PATH}`);
5579
+ for (const group of groups) {
5580
+ if (!Object.keys(group.values).length) continue;
5581
+ const fn = group.runtime ? "__ppio_runtime_env" : "__ppio_build_env";
5582
+ lines.push(
5583
+ fn + " " + Object.entries(group.values).map(([name, value]) => `${name} ${expandableDoubleQuote(value)}`).join(" ")
5584
+ );
5585
+ }
5586
+ lines.push(`command -p chmod 0644 ${PROFILE_PATH} ${ENVIRONMENT_PATH}`);
5601
5587
  return lines.join("\n");
5602
5588
  }
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]]))
5589
+ function envFilesCommand(envs, literalEnvs = {}, envGroups, baseEnvPath) {
5590
+ const groups = envGroups != null ? envGroups : Object.entries(envs).map(([name, value]) => ({
5591
+ values: { [name]: value },
5592
+ runtime: true
5593
+ }));
5594
+ const names = [
5595
+ .../* @__PURE__ */ new Set([
5596
+ ...Object.keys(literalEnvs),
5597
+ ...groups.flatMap((group) => Object.keys(group.values))
5598
+ ])
5599
+ ];
5600
+ const { usable, skipped } = partitionEnvNames(names);
5601
+ const allowed = new Set(usable);
5602
+ const filter = (values) => Object.fromEntries(
5603
+ Object.entries(values).filter(([name]) => allowed.has(name))
5610
5604
  );
5611
- const b64 = Buffer.from(script, "utf8").toString("base64");
5605
+ const literals = filter(literalEnvs);
5606
+ const filtered = groups.map((group) => ({
5607
+ values: filter(group.values),
5608
+ runtime: group.runtime
5609
+ }));
5610
+ if (!Object.keys(literals).length && !filtered.some((group) => group.runtime && Object.keys(group.values).length))
5611
+ return { command: null, skipped };
5612
+ const b64 = Buffer.from(
5613
+ envFilesScript({}, literals, filtered, baseEnvPath),
5614
+ "utf8"
5615
+ ).toString("base64");
5612
5616
  return {
5613
5617
  command: [
5614
- `echo ${b64} | base64 -d > ${SCRIPT_PATH}`,
5615
- `sh ${SCRIPT_PATH}`,
5616
- `rm -f ${SCRIPT_PATH}`
5618
+ `echo ${b64} | command -p base64 -d > ${SCRIPT_PATH}`,
5619
+ `command -p sh ${SCRIPT_PATH}`,
5620
+ `command -p rm -f ${SCRIPT_PATH}`
5617
5621
  ].join(" && "),
5618
5622
  skipped
5619
5623
  };
5620
5624
  }
5625
+ function shellQuote2(value) {
5626
+ return "'" + value.replace(/'/g, "'\\''") + "'";
5627
+ }
5628
+ function envSnapshotCommand(groups) {
5629
+ const { usable } = partitionEnvNames([
5630
+ ...new Set(groups.flatMap((group) => Object.keys(group.values)))
5631
+ ]);
5632
+ if (!usable.length) return null;
5633
+ const lines = [
5634
+ "set -e",
5635
+ "umask 077",
5636
+ `: > ${BASE_ENV_PATH}`,
5637
+ `command -p chmod 0600 ${BASE_ENV_PATH}`
5638
+ ];
5639
+ for (const name of usable) {
5640
+ lines.push(String.raw`if [ "${"${" + name + "+x}"}" = x ]; then
5641
+ printf "export ${name}='" >> ${BASE_ENV_PATH}
5642
+ printf '%s' "${"${" + name + "}"}" | command -p sed "s/'/'\\\\''/g" >> ${BASE_ENV_PATH}
5643
+ printf "'\n" >> ${BASE_ENV_PATH}
5644
+ else
5645
+ printf 'unset ${name}\n' >> ${BASE_ENV_PATH}
5646
+ fi`);
5647
+ }
5648
+ return "command -p sh -c " + shellQuote2(lines.join("\n"));
5649
+ }
5621
5650
 
5622
5651
  // src/core/template/imageConfig.ts
5623
5652
  var HUB_HOST = "registry-1.docker.io";
@@ -5639,6 +5668,7 @@ var SKIP_ENV = /* @__PURE__ */ new Set([
5639
5668
  ]);
5640
5669
  var RETRY_STATUS = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
5641
5670
  var READ_ATTEMPTS = 3;
5671
+ var TOKEN_CLIENT_ID = "ppio-sandbox";
5642
5672
  var backoffBaseMs = 1e3;
5643
5673
  function unsupportedBase(blob) {
5644
5674
  var _a3, _b, _c, _d, _e;
@@ -5652,9 +5682,15 @@ function unsupportedBase(blob) {
5652
5682
  return null;
5653
5683
  }
5654
5684
  const families = [
5655
- [/alpine-minirootfs|etc\/alpine-release|apk add|apk --no-cache/i, "Alpine (musl)"],
5685
+ [
5686
+ /alpine-minirootfs|etc\/alpine-release|apk add|apk --no-cache/i,
5687
+ "Alpine (musl)"
5688
+ ],
5656
5689
  [/^BusyBox /im, "BusyBox"],
5657
- [/microdnf|dnf install|yum install|rpm -i/i, "RPM-based (Fedora/RHEL/Rocky)"],
5690
+ [
5691
+ /microdnf|dnf install|yum install|rpm -i/i,
5692
+ "RPM-based (Fedora/RHEL/Rocky)"
5693
+ ],
5658
5694
  [/pacman -S/i, "Arch"],
5659
5695
  [/zypper|KIWI /i, "SUSE"]
5660
5696
  ];
@@ -5697,7 +5733,7 @@ function parseImageRef(image) {
5697
5733
  let reference;
5698
5734
  const at = ref.indexOf("@");
5699
5735
  if (at !== -1) {
5700
- repository = ref.slice(0, at);
5736
+ repository = ref.slice(0, at).replace(/:[^/]*$/, "");
5701
5737
  reference = ref.slice(at + 1);
5702
5738
  } else {
5703
5739
  const colon = ref.lastIndexOf(":");
@@ -5715,13 +5751,87 @@ function parseImageRef(image) {
5715
5751
  return { host, repository, reference };
5716
5752
  }
5717
5753
  var RegistryHttpError = class extends Error {
5718
- constructor(status, retryAfter, message) {
5754
+ constructor(status, retryAfter, message, challenge = null) {
5719
5755
  super(message);
5720
5756
  this.status = status;
5721
5757
  this.retryAfter = retryAfter;
5758
+ this.challenge = challenge;
5722
5759
  this.name = "RegistryHttpError";
5723
5760
  }
5724
5761
  };
5762
+ function parseChallenges(header) {
5763
+ const text = header != null ? header : "";
5764
+ const challenges = [];
5765
+ let index = 0;
5766
+ const skipSeparators = () => {
5767
+ while (index < text.length && " ,".includes(text[index])) {
5768
+ index++;
5769
+ }
5770
+ };
5771
+ const readToken = () => {
5772
+ const start = index;
5773
+ while (index < text.length && /[A-Za-z0-9\-_.:]/.test(text[index])) {
5774
+ index++;
5775
+ }
5776
+ return text.slice(start, index);
5777
+ };
5778
+ for (; ; ) {
5779
+ skipSeparators();
5780
+ const scheme = readToken();
5781
+ if (!scheme) {
5782
+ break;
5783
+ }
5784
+ const params = {};
5785
+ for (; ; ) {
5786
+ skipSeparators();
5787
+ if (index >= text.length) {
5788
+ break;
5789
+ }
5790
+ const keyStart = index;
5791
+ const key = readToken();
5792
+ if (!key) {
5793
+ break;
5794
+ }
5795
+ while (index < text.length && " ".includes(text[index])) {
5796
+ index++;
5797
+ }
5798
+ if (index >= text.length || text[index] !== "=") {
5799
+ index = keyStart;
5800
+ break;
5801
+ }
5802
+ index++;
5803
+ while (index < text.length && " ".includes(text[index])) {
5804
+ index++;
5805
+ }
5806
+ if (index < text.length && text[index] === '"') {
5807
+ index++;
5808
+ const chars = [];
5809
+ while (index < text.length) {
5810
+ if (text[index] === "\\" && index + 1 < text.length) {
5811
+ chars.push(text[index + 1]);
5812
+ index += 2;
5813
+ continue;
5814
+ }
5815
+ if (text[index] === '"') {
5816
+ index++;
5817
+ break;
5818
+ }
5819
+ chars.push(text[index]);
5820
+ index++;
5821
+ }
5822
+ params[key.toLowerCase()] = chars.join("");
5823
+ } else {
5824
+ const valueStart = index;
5825
+ while (index < text.length && text[index] !== ",") {
5826
+ index++;
5827
+ }
5828
+ params[key.toLowerCase()] = text.slice(valueStart, index).trim();
5829
+ }
5830
+ }
5831
+ challenges.push({ scheme, params });
5832
+ }
5833
+ return challenges;
5834
+ }
5725
5835
  var UnusableImageError = class extends Error {
5726
5836
  constructor(message) {
5727
5837
  super(message);
@@ -5744,19 +5854,27 @@ async function registryGet(url, headers, options) {
5744
5854
  for (let attempt = 0; attempt < attempts; attempt++) {
5745
5855
  if (attempt > 0) {
5746
5856
  await new Promise(
5747
- (resolve) => setTimeout(resolve, retryDelayMs(last, 2 ** (attempt - 1) * backoffBaseMs))
5857
+ (resolve) => setTimeout(
5858
+ resolve,
5859
+ retryDelayMs(last, 2 ** (attempt - 1) * backoffBaseMs)
5860
+ )
5748
5861
  );
5749
5862
  }
5750
5863
  try {
5751
- const response = await fetch(url, {
5864
+ const init = {
5752
5865
  headers,
5753
5866
  signal: AbortSignal.timeout(timeoutMs)
5754
- });
5867
+ };
5868
+ if ((options == null ? void 0 : options.dispatcher) !== void 0) {
5869
+ init.dispatcher = options.dispatcher;
5870
+ }
5871
+ const response = await fetch(url, init);
5755
5872
  if (!response.ok) {
5756
5873
  const error = new RegistryHttpError(
5757
5874
  response.status,
5758
5875
  response.headers.get("retry-after"),
5759
- `HTTP ${response.status} ${response.statusText}`
5876
+ `HTTP ${response.status} ${response.statusText}`,
5877
+ response.headers.get("www-authenticate")
5760
5878
  );
5761
5879
  if (!RETRY_STATUS.has(response.status)) {
5762
5880
  throw error;
@@ -5774,14 +5892,10 @@ async function registryGet(url, headers, options) {
5774
5892
  }
5775
5893
  throw last;
5776
5894
  }
5777
- async function authHeaders(host, repository, credentials) {
5895
+ async function authHeaders(host, repository, credentials, dispatcher) {
5778
5896
  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}`;
5897
+ if ((credentials == null ? void 0 : credentials.username) && credentials.password) {
5898
+ headers.Authorization = basicHeader(credentials);
5785
5899
  }
5786
5900
  const services = {
5787
5901
  "registry-1.docker.io": ["auth.docker.io", "registry.docker.io"],
@@ -5795,9 +5909,9 @@ async function authHeaders(host, repository, credentials) {
5795
5909
  const url = `https://${authHost}/token?service=${serviceName}&scope=repository:${repository}:pull`;
5796
5910
  try {
5797
5911
  const tokenHeaders = headers.Authorization ? { Authorization: headers.Authorization } : {};
5798
- const body = await registryGet(url, tokenHeaders, {
5912
+ const body = await registryGet(url, tokenHeaders, __spreadValues({
5799
5913
  attempts: 1
5800
- });
5914
+ }, dispatcher === void 0 ? {} : { dispatcher }));
5801
5915
  if (body.token) {
5802
5916
  headers.Authorization = `Bearer ${body.token}`;
5803
5917
  }
@@ -5805,6 +5919,82 @@ async function authHeaders(host, repository, credentials) {
5805
5919
  }
5806
5920
  return headers;
5807
5921
  }
5922
+ var RegistrySession = class {
5923
+ constructor(repository, credentials, headers, dispatcher) {
5924
+ this.repository = repository;
5925
+ this.credentials = credentials;
5926
+ this.headers = headers;
5927
+ this.dispatcher = dispatcher;
5928
+ this.token = null;
5929
+ }
5930
+ /** GET `url`, resolving one Bearer challenge if the registry asks for it. */
5931
+ async get(url) {
5932
+ const headers = __spreadValues({}, this.headers);
5933
+ if (this.token) {
5934
+ headers.Authorization = `Bearer ${this.token}`;
5935
+ }
5936
+ try {
5937
+ return await registryGet(url, headers, __spreadValues({
5938
+ attempts: READ_ATTEMPTS
5939
+ }, this.dispatcher === void 0 ? {} : { dispatcher: this.dispatcher }));
5940
+ } catch (error) {
5941
+ if (!(error instanceof RegistryHttpError) || error.status !== 401) {
5942
+ throw error;
5943
+ }
5944
+ const token = await this.tokenFrom(error.challenge);
5945
+ if (token === null) {
5946
+ throw error;
5947
+ }
5948
+ this.token = token;
5949
+ headers.Authorization = `Bearer ${token}`;
5950
+ return registryGet(url, headers, __spreadValues({
5951
+ attempts: READ_ATTEMPTS
5952
+ }, this.dispatcher === void 0 ? {} : { dispatcher: this.dispatcher }));
5953
+ }
5954
+ }
5955
+ async tokenFrom(challenge) {
5956
+ for (const { scheme, params } of parseChallenges(challenge)) {
5957
+ if (scheme.toLowerCase() === "bearer") {
5958
+ return this.bearer(params);
5959
+ }
5960
+ }
5961
+ return null;
5962
+ }
5963
+ async bearer(params) {
5964
+ var _a3;
5965
+ const realm = params.realm;
5966
+ if (!realm || !/^https?:\/\//.test(realm)) {
5967
+ return null;
5968
+ }
5969
+ const url = new URL(realm);
5970
+ url.searchParams.set("client_id", TOKEN_CLIENT_ID);
5971
+ if (params.service) {
5972
+ url.searchParams.set("service", params.service);
5973
+ }
5974
+ url.searchParams.set(
5975
+ "scope",
5976
+ params.scope || `repository:${this.repository}:pull`
5977
+ );
5978
+ const headers = {};
5979
+ if (((_a3 = this.credentials) == null ? void 0 : _a3.username) && this.credentials.password) {
5980
+ headers.Authorization = basicHeader(this.credentials);
5981
+ }
5982
+ const body = await registryGet(url.toString(), headers, __spreadValues({
5983
+ attempts: 1
5984
+ }, this.dispatcher === void 0 ? {} : { dispatcher: this.dispatcher }));
5985
+ if (body === null || typeof body !== "object") {
5986
+ return null;
5987
+ }
5988
+ return body.token || body.access_token || null;
5989
+ }
5990
+ };
5991
+ function basicHeader(credentials) {
5992
+ const encoded = Buffer.from(
5993
+ `${credentials.username}:${credentials.password}`,
5994
+ "utf8"
5995
+ ).toString("base64");
5996
+ return `Basic ${encoded}`;
5997
+ }
5808
5998
  function platformName(entry) {
5809
5999
  var _a3, _b, _c;
5810
6000
  const p = (_a3 = entry.platform) != null ? _a3 : {};
@@ -5849,41 +6039,53 @@ function describeFailure(error, image, host, repository, authenticated) {
5849
6039
  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
6040
  return __spreadProps(__spreadValues({}, empty), { error: reason, unusable: reason });
5851
6041
  }
6042
+ if (error.status === 401) {
6043
+ 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`;
6044
+ return __spreadProps(__spreadValues({}, empty), { error: reason });
6045
+ }
5852
6046
  return __spreadProps(__spreadValues({}, empty), { error: `${error.name}: ${error.message}` });
5853
6047
  }
5854
6048
  const message = error instanceof Error ? error.message : String(error);
5855
6049
  return __spreadProps(__spreadValues({}, empty), { error: message });
5856
6050
  }
5857
- async function fetchImageConfig(image, credentials) {
6051
+ async function fetchImageConfig(image, credentials, options) {
5858
6052
  var _a3, _b, _c, _d, _e, _f, _g;
6053
+ const dispatcher = options == null ? void 0 : options.dispatcher;
6054
+ const cacheable = dispatcher === void 0 && image.includes("@");
5859
6055
  const key = JSON.stringify([
5860
6056
  image,
5861
6057
  (_a3 = credentials == null ? void 0 : credentials.username) != null ? _a3 : null,
5862
6058
  (_b = credentials == null ? void 0 : credentials.password) != null ? _b : null
5863
6059
  ]);
5864
- const cached = CACHE.get(key);
5865
- if (cached) {
5866
- return copyConfig(cached);
6060
+ if (cacheable) {
6061
+ const cached = CACHE.get(key);
6062
+ if (cached) {
6063
+ return copyConfig(cached);
6064
+ }
5867
6065
  }
5868
6066
  const { host, repository, reference } = parseImageRef(image);
5869
6067
  let result;
5870
6068
  try {
5871
- const auth = await authHeaders(host, repository, credentials);
6069
+ const auth = await authHeaders(host, repository, credentials, dispatcher);
6070
+ const session = new RegistrySession(
6071
+ repository,
6072
+ credentials,
6073
+ auth,
6074
+ dispatcher
6075
+ );
5872
6076
  const base = `https://${host}/v2/${repository}`;
5873
- let manifest = await registryGet(
5874
- `${base}/manifests/${reference}`,
5875
- auth
6077
+ let manifest = await session.get(
6078
+ `${base}/manifests/${reference}`
5876
6079
  );
5877
6080
  if (manifest.manifests) {
5878
6081
  const digest = pickAmd64(manifest, image);
5879
- manifest = await registryGet(`${base}/manifests/${digest}`, auth);
6082
+ manifest = await session.get(`${base}/manifests/${digest}`);
5880
6083
  }
5881
6084
  if (!((_c = manifest.config) == null ? void 0 : _c.digest)) {
5882
6085
  throw new Error(`${image}: manifest names no config blob`);
5883
6086
  }
5884
- const blob = await registryGet(
5885
- `${base}/blobs/${manifest.config.digest}`,
5886
- auth
6087
+ const blob = await session.get(
6088
+ `${base}/blobs/${manifest.config.digest}`
5887
6089
  );
5888
6090
  const declared = (_d = blob.config) != null ? _d : {};
5889
6091
  const env = {};
@@ -5910,10 +6112,14 @@ async function fetchImageConfig(image, credentials) {
5910
6112
  image,
5911
6113
  host,
5912
6114
  repository,
5913
- credentials !== void 0
6115
+ // Both, because that is what the request actually carried: a lone username
6116
+ // is not a credential the registry could have rejected.
6117
+ Boolean((credentials == null ? void 0 : credentials.username) && (credentials == null ? void 0 : credentials.password))
5914
6118
  );
5915
6119
  }
5916
- CACHE.set(key, result);
6120
+ if (cacheable && !result.error) {
6121
+ CACHE.set(key, result);
6122
+ }
5917
6123
  return copyConfig(result);
5918
6124
  }
5919
6125
  function effectiveStartCmd(entrypoint, cmd) {
@@ -5921,7 +6127,7 @@ function effectiveStartCmd(entrypoint, cmd) {
5921
6127
  return parts.length > 0 ? parts.map(shellQuoteArg).join(" ") : null;
5922
6128
  }
5923
6129
  function shellQuoteArg(value) {
5924
- return /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
6130
+ return /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
5925
6131
  }
5926
6132
  function clearImageConfigCache() {
5927
6133
  CACHE.clear();
@@ -6085,6 +6291,8 @@ var TemplateBase = class _TemplateBase {
6085
6291
  // rather than written per call because the file is written once from the full
6086
6292
  // set -- a per-call write would clobber the previous call's file.
6087
6293
  this.envs = {};
6294
+ this.envDeclarations = [];
6295
+ this.imageEnvs = {};
6088
6296
  // Whether to restore what the base image declares -- see fromImage() and
6089
6297
  // resolveInheritedConfig(). Only meaningful for an image base; a Dockerfile
6090
6298
  // states its own ENV/WORKDIR/CMD, and a template base already carries them.
@@ -6096,6 +6304,13 @@ var TemplateBase = class _TemplateBase {
6096
6304
  // image's PATH -- the exact failure this reading exists to prevent.
6097
6305
  this.imageConfigError = void 0;
6098
6306
  this.imageUnusable = void 0;
6307
+ // What a failed read does. "warn" by default: one unreachable registry must not
6308
+ // abort a batch conversion, but a template silently missing the image's PATH is
6309
+ // the failure this reading exists to prevent, so it cannot pass unmentioned.
6310
+ this.imageOnConfigFailure = "warn";
6311
+ // Carries the TLS trust and proxy settings for a self-hosted registry, which
6312
+ // Node's fetch cannot be told about in any other per-request way.
6313
+ this.imageDispatcher = void 0;
6099
6314
  this.fileContextPath = runtime === "browser" ? "." : (_a2 = getCallerDirectory(STACK_TRACE_DEPTH)) != null ? _a2 : ".";
6100
6315
  this.fileIgnorePatterns = [];
6101
6316
  this.logsRefreshFrequency = 200;
@@ -6322,12 +6537,41 @@ var TemplateBase = class _TemplateBase {
6322
6537
  fromBaseImage() {
6323
6538
  return this.fromImage(this.defaultBaseImage);
6324
6539
  }
6540
+ /**
6541
+ * Build from a Docker image, restoring what the image declares.
6542
+ *
6543
+ * The image's ENV, WORKDIR and start command are read from its registry config
6544
+ * because the platform's own pull does not apply them. Reading is best-effort
6545
+ * and asynchronous, so it happens at build/serialize time.
6546
+ *
6547
+ * @param credentials registry username and password, for a private image.
6548
+ * @param options.inheritConfig restore the image's config (default true).
6549
+ * @param options.onConfigFailure what a failed read does — see
6550
+ * {@link ImageConfigFailureMode}. Defaults to `warn`.
6551
+ * @param options.dispatcher Node fetch `dispatcher` (an undici `Agent`), for a
6552
+ * self-hosted registry behind a private CA, a client certificate or a proxy.
6553
+ * For example, with a private CA:
6554
+ *
6555
+ * ```ts
6556
+ * import { Agent } from 'undici'
6557
+ * const dispatcher = new Agent({ connect: { ca: readFileSync('/ca.pem') } })
6558
+ * Template().fromImage('harbor.internal/app:1', undefined, { dispatcher })
6559
+ * ```
6560
+ */
6325
6561
  fromImage(baseImage, credentials, options) {
6326
- var _a3;
6562
+ var _a3, _b;
6563
+ if ((options == null ? void 0 : options.onConfigFailure) !== void 0 && !["warn", "raise", "ignore"].includes(options.onConfigFailure)) {
6564
+ throw new InvalidArgumentError(
6565
+ 'onConfigFailure must be "warn", "raise" or "ignore", got ' + String(options.onConfigFailure)
6566
+ );
6567
+ }
6327
6568
  this.baseImage = baseImage;
6328
6569
  this.baseTemplate = void 0;
6570
+ this.resetInheritedConfig();
6329
6571
  this.inheritImageConfig = (_a3 = options == null ? void 0 : options.inheritConfig) != null ? _a3 : true;
6330
6572
  this.imageCredentials = credentials;
6573
+ this.imageOnConfigFailure = (_b = options == null ? void 0 : options.onConfigFailure) != null ? _b : "warn";
6574
+ this.imageDispatcher = options == null ? void 0 : options.dispatcher;
6331
6575
  if (credentials) {
6332
6576
  this.registryConfig = {
6333
6577
  type: "registry",
@@ -6344,6 +6588,7 @@ var TemplateBase = class _TemplateBase {
6344
6588
  fromTemplate(template) {
6345
6589
  this.baseTemplate = template;
6346
6590
  this.baseImage = void 0;
6591
+ this.resetInheritedConfig();
6347
6592
  if (this.forceNextLayer) {
6348
6593
  this.force = true;
6349
6594
  }
@@ -6358,6 +6603,8 @@ var TemplateBase = class _TemplateBase {
6358
6603
  );
6359
6604
  this.baseImage = baseImage;
6360
6605
  this.baseTemplate = void 0;
6606
+ this.resetInheritedConfig();
6607
+ this.inheritImageConfig = true;
6361
6608
  if (this.forceNextLayer) {
6362
6609
  this.force = true;
6363
6610
  }
@@ -6367,6 +6614,7 @@ var TemplateBase = class _TemplateBase {
6367
6614
  fromAWSRegistry(image, credentials) {
6368
6615
  this.baseImage = image;
6369
6616
  this.baseTemplate = void 0;
6617
+ this.resetInheritedConfig();
6370
6618
  this.registryConfig = {
6371
6619
  type: "aws",
6372
6620
  awsAccessKeyId: credentials.accessKeyId,
@@ -6382,6 +6630,7 @@ var TemplateBase = class _TemplateBase {
6382
6630
  fromGCPRegistry(image, credentials) {
6383
6631
  this.baseImage = image;
6384
6632
  this.baseTemplate = void 0;
6633
+ this.resetInheritedConfig();
6385
6634
  this.registryConfig = {
6386
6635
  type: "gcp",
6387
6636
  serviceAccountJson: readGCPServiceAccountJSON(
@@ -6398,6 +6647,7 @@ var TemplateBase = class _TemplateBase {
6398
6647
  fromOCIRegistry(image, credentials) {
6399
6648
  this.baseImage = image;
6400
6649
  this.baseTemplate = void 0;
6650
+ this.resetInheritedConfig();
6401
6651
  this.registryConfig = {
6402
6652
  type: "oci",
6403
6653
  tenancyOcid: credentials.tenancyOcid,
@@ -6415,6 +6665,7 @@ var TemplateBase = class _TemplateBase {
6415
6665
  fromHuaweiCloudRegistry(image, credentials) {
6416
6666
  this.baseImage = image;
6417
6667
  this.baseTemplate = void 0;
6668
+ this.resetInheritedConfig();
6418
6669
  this.registryConfig = {
6419
6670
  type: "huawei",
6420
6671
  accessKeyId: credentials.accessKeyId,
@@ -6477,8 +6728,8 @@ var TemplateBase = class _TemplateBase {
6477
6728
  });
6478
6729
  return this;
6479
6730
  }
6480
- remove(path2, options) {
6481
- const paths2 = Array.isArray(path2) ? path2 : [path2];
6731
+ remove(path3, options) {
6732
+ const paths2 = Array.isArray(path3) ? path3 : [path3];
6482
6733
  const args = ["rm"];
6483
6734
  if (options == null ? void 0 : options.recursive) {
6484
6735
  args.push("-r");
@@ -6500,8 +6751,8 @@ var TemplateBase = class _TemplateBase {
6500
6751
  () => this.runCmd(args.join(" "), { user: options == null ? void 0 : options.user })
6501
6752
  );
6502
6753
  }
6503
- makeDir(path2, options) {
6504
- const paths2 = Array.isArray(path2) ? path2 : [path2];
6754
+ makeDir(path3, options) {
6755
+ const paths2 = Array.isArray(path3) ? path3 : [path3];
6505
6756
  const args = ["mkdir", "-p"];
6506
6757
  if (options == null ? void 0 : options.mode) {
6507
6758
  args.push(`-m ${padOctal(options.mode)}`);
@@ -6636,7 +6887,7 @@ var TemplateBase = class _TemplateBase {
6636
6887
  })
6637
6888
  );
6638
6889
  }
6639
- gitClone(url, path2, options) {
6890
+ gitClone(url, path3, options) {
6640
6891
  const args = ["git", "clone", url];
6641
6892
  if (options == null ? void 0 : options.branch) {
6642
6893
  args.push(`--branch ${options.branch}`);
@@ -6645,8 +6896,8 @@ var TemplateBase = class _TemplateBase {
6645
6896
  if (options == null ? void 0 : options.depth) {
6646
6897
  args.push(`--depth ${options.depth}`);
6647
6898
  }
6648
- if (path2) {
6649
- args.push(path2.toString());
6899
+ if (path3) {
6900
+ args.push(path3.toString());
6650
6901
  }
6651
6902
  return this.runInNewStackTraceContext(
6652
6903
  () => this.runCmd(args.join(" "), { user: options == null ? void 0 : options.user })
@@ -6676,7 +6927,8 @@ var TemplateBase = class _TemplateBase {
6676
6927
  this.collectStackTrace();
6677
6928
  return this;
6678
6929
  }
6679
- setEnvs(envs) {
6930
+ setEnvs(envs, options) {
6931
+ var _a3;
6680
6932
  if (Object.keys(envs).length === 0) {
6681
6933
  return this;
6682
6934
  }
@@ -6685,7 +6937,11 @@ var TemplateBase = class _TemplateBase {
6685
6937
  args: Object.entries(envs).flatMap(([key, value]) => [key, value]),
6686
6938
  force: this.forceNextLayer
6687
6939
  });
6688
- this.envs = __spreadValues(__spreadValues({}, this.envs), envs);
6940
+ this.envDeclarations.push({
6941
+ values: __spreadValues({}, envs),
6942
+ runtime: (_a3 = options == null ? void 0 : options.runtime) != null ? _a3 : false
6943
+ });
6944
+ if (options == null ? void 0 : options.runtime) this.envs = __spreadValues(__spreadValues({}, this.envs), envs);
6689
6945
  this.collectStackTrace();
6690
6946
  return this;
6691
6947
  }
@@ -6702,7 +6958,12 @@ var TemplateBase = class _TemplateBase {
6702
6958
  * second build of the same template append a duplicate layer.
6703
6959
  */
6704
6960
  runtimeEnvInstruction() {
6705
- const { command } = envFilesCommand(this.envs);
6961
+ const { command } = envFilesCommand(
6962
+ this.envs,
6963
+ this.imageEnvs,
6964
+ this.envDeclarations,
6965
+ envSnapshotCommand(this.envDeclarations) ? BASE_ENV_PATH : void 0
6966
+ );
6706
6967
  if (command === null) {
6707
6968
  return null;
6708
6969
  }
@@ -6721,7 +6982,10 @@ var TemplateBase = class _TemplateBase {
6721
6982
  */
6722
6983
  withRuntimeEnv(instructions) {
6723
6984
  const runtimeEnv = this.runtimeEnvInstruction();
6724
- return runtimeEnv ? [...instructions, runtimeEnv] : instructions;
6985
+ if (!runtimeEnv) return instructions;
6986
+ const snapshot = envSnapshotCommand(this.envDeclarations);
6987
+ const prefix = snapshot ? [{ type: "RUN" /* RUN */, args: [snapshot, "root"], force: false }] : [];
6988
+ return [...prefix, ...instructions, runtimeEnv];
6725
6989
  }
6726
6990
  /**
6727
6991
  * Restore what the base image declares: ENV, WORKDIR and its effective command.
@@ -6742,37 +7006,57 @@ var TemplateBase = class _TemplateBase {
6742
7006
  * restored config — but it is reported, since an image whose toolchain lives
6743
7007
  * behind its ENV will otherwise look installed and behave as though it is not.
6744
7008
  */
7009
+ /** The one wording a failed read is reported with, on every channel. */
7010
+ configFailureMessage() {
7011
+ return `Could not read ${this.baseImage}: ${this.imageConfigError}. The template will build without the environment, working directory and start command the image declares.`;
7012
+ }
7013
+ resetInheritedConfig() {
7014
+ this.imageEnvs = {};
7015
+ this.imageWorkdir = void 0;
7016
+ this.imageStartCmd = void 0;
7017
+ this.imageReadyCmd = void 0;
7018
+ this.imageConfigError = void 0;
7019
+ this.imageUnusable = void 0;
7020
+ this.imageCredentials = void 0;
7021
+ this.imageDispatcher = void 0;
7022
+ this.registryConfig = void 0;
7023
+ this.inheritImageConfig = false;
7024
+ }
6745
7025
  async resolveInheritedConfig(onBuildLogs) {
6746
- var _a3;
7026
+ var _a3, _b;
6747
7027
  if (!this.inheritImageConfig || this.baseImage === void 0) {
6748
7028
  return;
6749
7029
  }
6750
- this.inheritImageConfig = false;
6751
- const config = await fetchImageConfig(this.baseImage, this.imageCredentials);
7030
+ const config = await fetchImageConfig(
7031
+ this.baseImage,
7032
+ this.imageCredentials,
7033
+ this.imageDispatcher === void 0 ? void 0 : { dispatcher: this.imageDispatcher }
7034
+ );
7035
+ this.imageEnvs = {};
7036
+ this.imageWorkdir = void 0;
7037
+ this.imageStartCmd = void 0;
7038
+ this.imageReadyCmd = void 0;
6752
7039
  if (config.error) {
6753
7040
  this.imageConfigError = config.error;
6754
7041
  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
- );
7042
+ const message = this.configFailureMessage();
7043
+ if (this.imageOnConfigFailure === "raise") {
7044
+ throw new ImageConfigError(message);
7045
+ }
7046
+ if (this.imageOnConfigFailure !== "ignore") {
7047
+ console.warn(message);
7048
+ onBuildLogs == null ? void 0 : onBuildLogs(new LogEntry(/* @__PURE__ */ new Date(), "warn", message));
7049
+ }
6762
7050
  return;
6763
7051
  }
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
- }
7052
+ this.imageEnvs = __spreadValues({}, config.env);
7053
+ this.imageWorkdir = (_a3 = config.workdir) != null ? _a3 : void 0;
7054
+ this.imageConfigError = void 0;
7055
+ this.imageUnusable = void 0;
6772
7056
  const startCmd = effectiveStartCmd(config.entrypoint, config.cmd);
6773
7057
  if (startCmd && this.startCmd === void 0) {
6774
- this.startCmd = startCmd;
6775
- this.readyCmd = (_a3 = this.readyCmd) != null ? _a3 : waitForTimeout(2e4).getCmd();
7058
+ this.imageStartCmd = startCmd;
7059
+ this.imageReadyCmd = (_b = this.readyCmd) != null ? _b : waitForTimeout(2e4).getCmd();
6776
7060
  }
6777
7061
  }
6778
7062
  /**
@@ -7110,9 +7394,20 @@ var TemplateBase = class _TemplateBase {
7110
7394
  * @returns Template data formatted for the API
7111
7395
  */
7112
7396
  serialize(steps) {
7397
+ var _a3, _b;
7398
+ if (this.imageWorkdir) {
7399
+ steps = [
7400
+ {
7401
+ type: "WORKDIR" /* WORKDIR */,
7402
+ args: [this.imageWorkdir],
7403
+ force: false
7404
+ },
7405
+ ...steps
7406
+ ];
7407
+ }
7113
7408
  const templateData = {
7114
- startCmd: this.startCmd,
7115
- readyCmd: this.readyCmd,
7409
+ startCmd: (_a3 = this.startCmd) != null ? _a3 : this.imageStartCmd,
7410
+ readyCmd: (_b = this.readyCmd) != null ? _b : this.imageReadyCmd,
7116
7411
  preBootScript: this.patchCmd,
7117
7412
  steps,
7118
7413
  force: this.force
@@ -7145,6 +7440,7 @@ Template.list = TemplateBase.list;
7145
7440
  Template.delete = TemplateBase.delete;
7146
7441
  Template.toJSON = TemplateBase.toJSON;
7147
7442
  Template.toDockerfile = TemplateBase.toDockerfile;
7443
+ Template.imageConfigFailure = TemplateBase.imageConfigFailure;
7148
7444
 
7149
7445
  // src/core/volume/index.ts
7150
7446
  function quotaInodesForSize(quotaSizeGiB) {
@@ -7361,6 +7657,8 @@ var Volume = class _Volume {
7361
7657
  };
7362
7658
 
7363
7659
  // src/core/client.ts
7660
+ import path2 from "path";
7661
+ import { fileURLToPath as fileURLToPath2 } from "url";
7364
7662
  function mergeConnectionOpts(base, next) {
7365
7663
  var _a3, _b;
7366
7664
  const baseHeaders = (_a3 = base.headers) != null ? _a3 : {};
@@ -7565,7 +7863,18 @@ var TemplateNamespace = class {
7565
7863
  this.toDockerfile = Template.toDockerfile;
7566
7864
  }
7567
7865
  new(options) {
7568
- return Template(options);
7866
+ var _a3;
7867
+ let callerContext = ".";
7868
+ for (const site of callsites(2)) {
7869
+ const fileName = site.getFileName();
7870
+ if (fileName && (!fileName.includes("/src/core/") || fileName.includes("/src/core/tests/")) && !fileName.includes("/node_modules/ppio-sandbox/")) {
7871
+ callerContext = path2.dirname(fileName.startsWith("file:") ? fileURLToPath2(fileName) : fileName);
7872
+ break;
7873
+ }
7874
+ }
7875
+ return Template(__spreadProps(__spreadValues({}, options), {
7876
+ fileContextPath: (_a3 = options == null ? void 0 : options.fileContextPath) != null ? _a3 : callerContext
7877
+ }));
7569
7878
  }
7570
7879
  list(opts) {
7571
7880
  return Template.list(mergeConnectionOpts(this.opts, opts));
@@ -7694,12 +8003,12 @@ var PPIO = class {
7694
8003
  this.secret = new SecretNamespace(opts);
7695
8004
  this.codeInterpreter = new RuntimeSandboxNamespace(
7696
8005
  opts,
7697
- () => import("./sandbox-VBQLLX3L.mjs")
8006
+ () => import("./sandbox-DMY2YDSO.mjs")
7698
8007
  );
7699
8008
  this.code_interpreter = this.codeInterpreter;
7700
8009
  this.desktop = new RuntimeSandboxNamespace(
7701
8010
  opts,
7702
- () => import("./sandbox-5PUSVOHB.mjs")
8011
+ () => import("./sandbox-TS3DDCSN.mjs")
7703
8012
  );
7704
8013
  }
7705
8014
  async create(templateOrOpts, opts) {
@@ -7742,6 +8051,7 @@ export {
7742
8051
  RateLimitError,
7743
8052
  BuildError,
7744
8053
  FileUploadError,
8054
+ ImageConfigError,
7745
8055
  VolumeError,
7746
8056
  SecretError,
7747
8057
  ApiClient,
@@ -7777,4 +8087,4 @@ export {
7777
8087
  ALL_TRAFFIC,
7778
8088
  core_default
7779
8089
  };
7780
- //# sourceMappingURL=chunk-M7G3KDGF.mjs.map
8090
+ //# sourceMappingURL=chunk-PQGBLWKQ.mjs.map