@vercel/container 28.0.0 → 29.0.0-snapshot-c9dfd83f2293

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -106,7 +106,8 @@ async function generateProjectManifest({
106
106
  var diagnostics = (options) => (0, import_build_utils.createDiagnostics)(manifestSlot(options.config?.daemon?.name))(options);
107
107
 
108
108
  // src/index.ts
109
- var import_node_path29 = __toESM(require("path"));
109
+ var import_promises14 = require("fs/promises");
110
+ var import_node_path30 = __toESM(require("path"));
110
111
 
111
112
  // src/util.ts
112
113
  var import_build_utils2 = require("@vercel/build-utils");
@@ -669,6 +670,9 @@ function buildArgFlags(params) {
669
670
  function buildTargetFlags(params) {
670
671
  return params.buildTarget ? ["--target", params.buildTarget] : [];
671
672
  }
673
+ function exportsLayouts(engine) {
674
+ return engine.exportLayout !== void 0;
675
+ }
672
676
 
673
677
  // src/registry.ts
674
678
  async function resolveRegistryTarget(params) {
@@ -826,6 +830,15 @@ async function ensureRepository(repository, token, claims, span) {
826
830
  }
827
831
 
828
832
  // src/engines/buildah.ts
833
+ var ZSTD_OCI_ARGS = [
834
+ "--compression-format",
835
+ "zstd",
836
+ "--compression-level",
837
+ "3",
838
+ "--force-compression",
839
+ "--format",
840
+ "oci"
841
+ ];
829
842
  function localImageRef(params) {
830
843
  const { imageRef } = params;
831
844
  if (!params.useBuildahStoreCache) {
@@ -1032,15 +1045,7 @@ ${stderr}`)
1032
1045
  const digestDir = (0, import_node_fs3.mkdtempSync)((0, import_node_path6.join)((0, import_node_os5.tmpdir)(), "vercel-container-digest-"));
1033
1046
  const digestFile = (0, import_node_path6.join)(digestDir, "digest");
1034
1047
  const zstdEnabled = !readString(process.env.VERCEL_VCR_DISABLE_ZSTD);
1035
- const zstdArgs = zstdEnabled ? [
1036
- "--compression-format",
1037
- "zstd",
1038
- "--compression-level",
1039
- "3",
1040
- "--force-compression",
1041
- "--format",
1042
- "oci"
1043
- ] : [];
1048
+ const zstdArgs = zstdEnabled ? ZSTD_OCI_ARGS : [];
1044
1049
  info(
1045
1050
  `pushing ${params.imageRef} ` + (zstdEnabled ? "with zstd compression (level=3, force, oci)" : "with default compression (zstd disabled)")
1046
1051
  );
@@ -1084,6 +1089,14 @@ ${stderr}`)
1084
1089
  `--digestfile did not contain a digest (${JSON.stringify(digest)}) \u2014 resolving registry manifest`
1085
1090
  );
1086
1091
  return resolvePushedImageDigest(params);
1092
+ },
1093
+ async exportLayout(params, directory) {
1094
+ await client.run([
1095
+ "push",
1096
+ ...ZSTD_OCI_ARGS,
1097
+ localImageRef(params),
1098
+ `oci:${directory}`
1099
+ ]);
1087
1100
  }
1088
1101
  };
1089
1102
  }
@@ -2826,14 +2839,14 @@ var import_node_crypto7 = require("crypto");
2826
2839
  var import_node_fs8 = require("fs");
2827
2840
  var import_node_os9 = require("os");
2828
2841
  var import_node_path13 = require("path");
2829
- function localBuildImageDockerfile(buildImage, nodeMajor) {
2842
+ function localBuildImageDockerfile(buildImage2, nodeMajor) {
2830
2843
  const lines = [];
2831
2844
  if (nodeMajor !== void 0) {
2832
2845
  lines.push(
2833
2846
  `FROM docker.io/library/node:${nodeMajor}-bookworm-slim AS node`
2834
2847
  );
2835
2848
  }
2836
- lines.push(`FROM ${buildImage}`, "USER 0:0");
2849
+ lines.push(`FROM ${buildImage2}`, "USER 0:0");
2837
2850
  if (nodeMajor !== void 0) {
2838
2851
  lines.push(`COPY --from=node /usr/local /node${nodeMajor}`);
2839
2852
  }
@@ -3504,6 +3517,15 @@ async function buildAndPushBuildpack(params) {
3504
3517
  var import_node_fs15 = require("fs");
3505
3518
  var import_node_path20 = __toESM(require("path"));
3506
3519
  var DETECT_SENTINEL = "<detect>";
3520
+ var IMAGE_REFERENCE_PATTERN = /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*(?::[0-9]+)?\/)?[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*)*(?::[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127})?(?:@[a-zA-Z][a-zA-Z0-9]*(?:[-_.+][a-zA-Z][a-zA-Z0-9]*)*:[0-9a-fA-F]{32,})?$/;
3521
+ function assertValidImageReference(imageRef) {
3522
+ if (!IMAGE_REFERENCE_PATTERN.test(imageRef)) {
3523
+ throw new Error(
3524
+ `Prebuilt image reference "${imageRef}" is not a valid Docker image reference, e.g. "docker.io/library/nginx:1.27".`
3525
+ );
3526
+ }
3527
+ return imageRef;
3528
+ }
3507
3529
  function resolveImageSource(options, context) {
3508
3530
  const { config, workPath, entrypoint } = options;
3509
3531
  const entrypointRef = readString(entrypoint);
@@ -3516,7 +3538,10 @@ function resolveImageSource(options, context) {
3516
3538
  }
3517
3539
  const explicitImage = readString(config.handler);
3518
3540
  if (explicitImage && !(entrypointRef && isDockerfileRef(entrypointRef))) {
3519
- return { kind: "prebuilt", imageRef: explicitImage };
3541
+ return {
3542
+ kind: "prebuilt",
3543
+ imageRef: assertValidImageReference(explicitImage)
3544
+ };
3520
3545
  }
3521
3546
  if (buildpack && (config.daemon || readString(config.buildpackEntrypoint))) {
3522
3547
  return { kind: "buildpack", buildpack };
@@ -3530,7 +3555,10 @@ function resolveImageSource(options, context) {
3530
3555
  }
3531
3556
  const prebuiltImage = readString(config.handler) ?? (isDetectSentinel ? void 0 : entrypointRef);
3532
3557
  if (prebuiltImage) {
3533
- return { kind: "prebuilt", imageRef: prebuiltImage };
3558
+ return {
3559
+ kind: "prebuilt",
3560
+ imageRef: assertValidImageReference(prebuiltImage)
3561
+ };
3534
3562
  }
3535
3563
  if (buildpack) {
3536
3564
  return { kind: "buildpack", buildpack };
@@ -3822,1266 +3850,1484 @@ function failureReason(error) {
3822
3850
  return String(error?.message ?? error).trim().split("\n").at(-1) ?? "";
3823
3851
  }
3824
3852
 
3825
- // src/dev.ts
3826
- var import_build_utils9 = require("@vercel/build-utils");
3827
- var import_node_child_process4 = require("child_process");
3828
- var import_node_fs16 = require("fs");
3829
- var import_node_os12 = require("os");
3830
- var import_node_path23 = __toESM(require("path"));
3831
- var HOST_ONLY_ENV = /* @__PURE__ */ new Set([
3832
- "TMPDIR",
3833
- "TMP",
3834
- "TEMP",
3835
- "HOME",
3836
- "PATH",
3837
- "PWD",
3838
- "OLDPWD",
3839
- "SHELL",
3840
- "SHLVL",
3841
- "USER",
3842
- "LOGNAME",
3843
- "TERM",
3844
- "TERM_PROGRAM",
3845
- "TERM_PROGRAM_VERSION",
3846
- "TERM_SESSION_ID",
3847
- "COLORTERM",
3848
- "LANG",
3849
- "LC_ALL",
3850
- "LC_CTYPE",
3851
- "COMMAND_MODE",
3852
- "SECURITYSESSIONID",
3853
- "__CF_USER_TEXT_ENCODING",
3854
- "__CFBundleIdentifier"
3853
+ // src/oci-layout/layout.ts
3854
+ var import_node_crypto9 = require("crypto");
3855
+ var import_promises9 = require("fs/promises");
3856
+ var import_node_path23 = require("path");
3857
+ var OCI_LAYOUT_VERSION = "1.0.0";
3858
+ var OCI_INDEX_MEDIA_TYPE = "application/vnd.oci.image.index.v1+json";
3859
+ var OCI_MANIFEST_MEDIA_TYPE = "application/vnd.oci.image.manifest.v1+json";
3860
+ var DOCKER_MANIFEST_MEDIA_TYPE = "application/vnd.docker.distribution.manifest.v2+json";
3861
+ var DOCKER_MANIFEST_LIST_MEDIA_TYPE = "application/vnd.docker.distribution.manifest.list.v2+json";
3862
+ var OCI_CONFIG_MEDIA_TYPE = "application/vnd.oci.image.config.v1+json";
3863
+ var DOCKER_CONFIG_MEDIA_TYPE = "application/vnd.docker.container.image.v1+json";
3864
+ var MANIFEST_MEDIA_TYPES2 = /* @__PURE__ */ new Set([
3865
+ OCI_MANIFEST_MEDIA_TYPE,
3866
+ DOCKER_MANIFEST_MEDIA_TYPE
3855
3867
  ]);
3856
- function isHostOnlyEnvVar(key) {
3857
- return HOST_ONLY_ENV.has(key) || key.startsWith("__") || key.startsWith("XPC_") || key.startsWith("SSH_") || key.startsWith("Apple");
3868
+ var INDEX_MEDIA_TYPES = /* @__PURE__ */ new Set([
3869
+ OCI_INDEX_MEDIA_TYPE,
3870
+ DOCKER_MANIFEST_LIST_MEDIA_TYPE
3871
+ ]);
3872
+ var IMAGE_CONFIG_MEDIA_TYPES = /* @__PURE__ */ new Set([
3873
+ OCI_CONFIG_MEDIA_TYPE,
3874
+ DOCKER_CONFIG_MEDIA_TYPE
3875
+ ]);
3876
+ function isRecord(value) {
3877
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3858
3878
  }
3859
- function writeEnvFile(env) {
3860
- const dir = (0, import_node_fs16.mkdtempSync)(import_node_path23.default.join((0, import_node_os12.tmpdir)(), "vercel-container-dev-env-"));
3861
- const file = import_node_path23.default.join(dir, "env");
3862
- const lines = [];
3863
- for (const [key, value] of Object.entries(env)) {
3864
- if (value.includes("\n")) {
3865
- continue;
3866
- }
3867
- lines.push(`${key}=${value}`);
3868
- }
3869
- (0, import_node_fs16.writeFileSync)(file, `${lines.join("\n")}
3870
- `);
3871
- return file;
3879
+ function sha256Digest(bytes) {
3880
+ const view = bytes instanceof Uint8Array && !Buffer.isBuffer(bytes) ? bytes : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
3881
+ return `sha256:${(0, import_node_crypto9.createHash)("sha256").update(view).digest("hex")}`;
3872
3882
  }
3873
- function useContainerHost(endpoint) {
3874
- try {
3875
- const url = new URL(endpoint);
3876
- if (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]") {
3877
- url.hostname = "host.docker.internal";
3878
- return url.toString();
3879
- }
3880
- } catch {
3883
+ function parseSha256Hex(digest) {
3884
+ if (!DIGEST_RE.test(digest)) {
3885
+ throw new Error(`Unsupported OCI digest ${JSON.stringify(digest)}.`);
3881
3886
  }
3882
- return endpoint;
3887
+ return digest.slice("sha256:".length);
3883
3888
  }
3884
- function emit(out, line) {
3885
- if (out.onStderr) {
3886
- out.onStderr(Buffer.from(`${line}
3887
- `));
3888
- } else {
3889
- process.stderr.write(`${line}
3890
- `);
3889
+ function blobPath2(layoutDir, digest) {
3890
+ return (0, import_node_path23.join)(layoutDir, "blobs", "sha256", parseSha256Hex(digest));
3891
+ }
3892
+ function assertSafePathSegment(segment, imageRef) {
3893
+ if (!segment || segment === "." || segment === ".." || segment.includes("/") || segment.includes("\\")) {
3894
+ throw new Error(`Invalid image reference for OCI layout: "${imageRef}".`);
3891
3895
  }
3892
3896
  }
3893
- function runForwarded(cmd, args, out, opts = {}) {
3894
- return new Promise((resolve5, reject) => {
3895
- const child = (0, import_node_child_process4.spawn)(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
3896
- let stdout = "";
3897
- let stderr = "";
3898
- child.stdout?.on("data", (chunk) => {
3899
- stdout += chunk.toString();
3900
- if (!opts.quiet) {
3901
- if (out.onStdout) {
3902
- out.onStdout(chunk);
3903
- } else {
3904
- process.stderr.write(chunk.toString());
3905
- }
3906
- }
3907
- });
3908
- child.stderr?.on("data", (chunk) => {
3909
- stderr += chunk.toString();
3910
- if (!opts.quiet) {
3911
- if (out.onStderr) {
3912
- out.onStderr(chunk);
3913
- } else {
3914
- process.stderr.write(chunk.toString());
3915
- }
3916
- }
3917
- });
3918
- child.on("error", (err) => {
3919
- if (err.code === "ENOENT") {
3920
- reject(
3921
- new Error(
3922
- `Command not found: \`${cmd}\`. Ensure \`${cmd}\` is installed and on your PATH (Docker is required for \`vercel dev\` with container services).`
3923
- )
3924
- );
3925
- return;
3926
- }
3927
- reject(err);
3928
- });
3929
- child.on("close", (code) => {
3930
- if (code === 0) {
3931
- resolve5({ stdout });
3932
- } else {
3933
- const detail = stderr.trim().split("\n").slice(-5).join("\n");
3934
- reject(
3935
- new Error(
3936
- `\`${cmd} ${args.join(" ")}\` exited with code ${code}` + (detail ? `
3937
- ${detail}` : "")
3938
- )
3939
- );
3940
- }
3941
- });
3942
- });
3897
+ function layoutRefPath(layoutDir, imageRef) {
3898
+ const firstSlash = imageRef.indexOf("/");
3899
+ if (firstSlash <= 0 || firstSlash === imageRef.length - 1) {
3900
+ throw new Error(`Invalid image reference for OCI layout: "${imageRef}".`);
3901
+ }
3902
+ const registry = imageRef.slice(0, firstSlash);
3903
+ assertSafePathSegment(registry, imageRef);
3904
+ const remainder = imageRef.slice(firstSlash + 1);
3905
+ const atIndex = remainder.indexOf("@");
3906
+ if (atIndex !== -1) {
3907
+ const repository2 = remainder.slice(0, atIndex);
3908
+ const digest = remainder.slice(atIndex + 1);
3909
+ const repoParts2 = repository2.split("/");
3910
+ for (const part of repoParts2) {
3911
+ assertSafePathSegment(part, imageRef);
3912
+ }
3913
+ const hex = parseSha256Hex(digest);
3914
+ return (0, import_node_path23.join)(layoutDir, registry, ...repoParts2, "sha256", hex);
3915
+ }
3916
+ const colonIndex = remainder.lastIndexOf(":");
3917
+ if (colonIndex <= remainder.lastIndexOf("/") || colonIndex === remainder.length - 1) {
3918
+ throw new Error(`Invalid image reference for OCI layout: "${imageRef}".`);
3919
+ }
3920
+ const repository = remainder.slice(0, colonIndex);
3921
+ const tag = remainder.slice(colonIndex + 1);
3922
+ const repoParts = repository.split("/");
3923
+ for (const part of repoParts) {
3924
+ assertSafePathSegment(part, imageRef);
3925
+ }
3926
+ assertSafePathSegment(tag, imageRef);
3927
+ return (0, import_node_path23.join)(layoutDir, registry, ...repoParts, tag);
3943
3928
  }
3944
- var PULL_AUTH_ERROR = /unauthorized|authentication required|no basic auth credentials|pull access denied|denied:|forbidden|\b40[13]\b/i;
3945
- function prebuiltImagePullError(imageRef, detail) {
3946
- if (imageRef.startsWith("vcr.vercel.com/") && PULL_AUTH_ERROR.test(detail)) {
3947
- return new import_build_utils9.NowBuildError({
3948
- code: "CONTAINER_IMAGE_PULL_UNAUTHORIZED",
3949
- message: `Couldn't pull ${imageRef} from Vercel Container Registry. Log Docker in with \`vercel vcr login docker\`, check that this project can read the image, and run \`vercel dev\` again.
3950
-
3951
- ${detail}`
3952
- });
3929
+ function parseDescriptor(value, label) {
3930
+ if (!isRecord(value)) {
3931
+ throw new Error(`Invalid OCI ${label} descriptor.`);
3953
3932
  }
3954
- return new import_build_utils9.NowBuildError({
3955
- code: "CONTAINER_IMAGE_PULL_FAILED",
3956
- message: `Couldn't pull ${imageRef}.
3957
-
3958
- ${detail}`
3959
- });
3933
+ const { mediaType, digest, size } = value;
3934
+ if (typeof digest !== "string" || !DIGEST_RE.test(digest)) {
3935
+ throw new Error(`Invalid OCI ${label} digest: ${JSON.stringify(digest)}.`);
3936
+ }
3937
+ if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
3938
+ throw new Error(`Invalid OCI ${label} size: ${JSON.stringify(size)}.`);
3939
+ }
3940
+ if (mediaType !== void 0 && typeof mediaType !== "string") {
3941
+ throw new Error(`Invalid OCI ${label} mediaType.`);
3942
+ }
3943
+ return { mediaType, digest, size };
3960
3944
  }
3961
- async function hasLocalImage(imageRef, out) {
3945
+ function parseJson(text, label) {
3962
3946
  try {
3963
- await runForwarded(
3964
- "docker",
3965
- ["image", "inspect", "--format", "{{.Id}}", imageRef],
3966
- out,
3967
- { quiet: true }
3968
- );
3969
- return true;
3947
+ return JSON.parse(text);
3970
3948
  } catch {
3971
- return false;
3949
+ throw new Error(`OCI layout ${label} is not valid JSON.`);
3972
3950
  }
3973
3951
  }
3974
- async function pullPrebuiltImage(imageRef, out) {
3975
- emit(out, `\u25B2 container vercel dev: pulling ${imageRef}`);
3976
- try {
3977
- await runForwarded("docker", ["pull", imageRef], out);
3978
- } catch (err) {
3979
- const error = prebuiltImagePullError(imageRef, err.message);
3980
- if (!await hasLocalImage(imageRef, out)) {
3981
- throw error;
3952
+ async function readRegularJson(path4, label) {
3953
+ const stats = await (0, import_promises9.lstat)(path4).catch((error) => {
3954
+ if (error.code === "ENOENT") {
3955
+ throw new Error(`OCI layout is missing ${label}.`);
3982
3956
  }
3983
- const reason = error.code === "CONTAINER_IMAGE_PULL_UNAUTHORIZED" ? "the registry refused the pull; run `vercel vcr login docker` to get updates" : "the pull failed";
3984
- emit(
3985
- out,
3986
- `\u25B2 container vercel dev: warning: couldn't pull ${imageRef} (${reason}). Using the local copy, which may be out of date.`
3987
- );
3957
+ throw error;
3958
+ });
3959
+ if (!stats.isFile()) {
3960
+ throw new Error(`OCI layout ${label} must be a regular file.`);
3988
3961
  }
3962
+ return parseJson(await (0, import_promises9.readFile)(path4, "utf8"), label);
3989
3963
  }
3990
- async function resolveDevImage(options, out, span) {
3991
- const source = resolveImageSource(options, "dev");
3992
- if (source.kind === "prebuilt") {
3993
- await assertDockerAvailable(out);
3994
- span?.setAttributes({ "container.dev_mode": "prebuilt" });
3995
- emit(
3996
- out,
3997
- `\u25B2 container vercel dev: using prebuilt image ${source.imageRef}`
3964
+ async function readVerifiedBlob(layoutDir, descriptor, label) {
3965
+ const path4 = blobPath2(layoutDir, descriptor.digest);
3966
+ const stats = await (0, import_promises9.lstat)(path4).catch((error) => {
3967
+ if (error.code === "ENOENT") {
3968
+ throw new Error(
3969
+ `OCI layout is missing ${label} blob ${descriptor.digest}.`
3970
+ );
3971
+ }
3972
+ throw error;
3973
+ });
3974
+ if (!stats.isFile()) {
3975
+ throw new Error(
3976
+ `OCI layout ${label} blob ${descriptor.digest} must be a regular file.`
3998
3977
  );
3999
- await pullPrebuiltImage(source.imageRef, out);
4000
- return { image: source.imageRef };
4001
3978
  }
4002
- if (source.kind === "buildpack") {
3979
+ if (stats.size !== descriptor.size) {
4003
3980
  throw new Error(
4004
- `Unexpected buildpack image source in \`vercel dev\` for "${options.workPath}".`
3981
+ `OCI layout ${label} blob ${descriptor.digest} has size ${stats.size}, expected ${descriptor.size}.`
4005
3982
  );
4006
3983
  }
4007
- const { dockerfilePath } = source;
4008
- const serviceName = options.service?.name ?? "service";
4009
- const tag = devImageTag(serviceName);
4010
- const contextDir = await resolveBuildContext({
4011
- repoRootPath: options.repoRootPath,
4012
- workPath: options.workPath,
4013
- contextDir: options.service ? options.workPath : import_node_path23.default.dirname(dockerfilePath),
4014
- dockerfilePath
3984
+ const content = await (0, import_promises9.readFile)(path4);
3985
+ if (content.length !== descriptor.size) {
3986
+ throw new Error(
3987
+ `OCI layout ${label} blob ${descriptor.digest} has size ${content.length}, expected ${descriptor.size}.`
3988
+ );
3989
+ }
3990
+ const actual = sha256Digest(content);
3991
+ if (actual !== descriptor.digest) {
3992
+ throw new Error(
3993
+ `OCI layout ${label} blob ${descriptor.digest} hashes to ${actual}.`
3994
+ );
3995
+ }
3996
+ return content;
3997
+ }
3998
+ async function verifyBlobSize(layoutDir, descriptor, label) {
3999
+ const path4 = blobPath2(layoutDir, descriptor.digest);
4000
+ const stats = await (0, import_promises9.lstat)(path4).catch((error) => {
4001
+ if (error.code === "ENOENT") {
4002
+ throw new Error(
4003
+ `OCI layout is missing ${label} blob ${descriptor.digest}.`
4004
+ );
4005
+ }
4006
+ throw error;
4015
4007
  });
4016
- await assertDockerAvailable(out);
4017
- const buildArgFlags2 = [];
4018
- const buildEnv = options.meta?.buildEnv ?? {};
4019
- for (const [key, value] of Object.entries(buildEnv)) {
4020
- if (typeof value === "string") {
4021
- buildArgFlags2.push("--build-arg", `${key}=${value}`);
4008
+ if (!stats.isFile()) {
4009
+ throw new Error(
4010
+ `OCI layout ${label} blob ${descriptor.digest} must be a regular file.`
4011
+ );
4012
+ }
4013
+ if (stats.size !== descriptor.size) {
4014
+ throw new Error(
4015
+ `OCI layout ${label} blob ${descriptor.digest} has size ${stats.size}, expected ${descriptor.size}.`
4016
+ );
4017
+ }
4018
+ }
4019
+ async function readVerifiedJson(layoutDir, descriptor, label) {
4020
+ const bytes = await readVerifiedBlob(layoutDir, descriptor, label);
4021
+ return parseJson(bytes.toString("utf8"), `image ${label}`);
4022
+ }
4023
+ function manifestsOf(index, label) {
4024
+ if (!isRecord(index) || !Array.isArray(index.manifests)) {
4025
+ throw new Error(`OCI layout ${label} has no manifests list.`);
4026
+ }
4027
+ return index.manifests;
4028
+ }
4029
+ function platformOf(value) {
4030
+ if (!isRecord(value)) {
4031
+ return void 0;
4032
+ }
4033
+ const { os, architecture } = value;
4034
+ return typeof os === "string" && typeof architecture === "string" ? `${os}/${architecture}` : void 0;
4035
+ }
4036
+ async function collectTargetImages(search, manifests) {
4037
+ for (const entry of manifests) {
4038
+ const descriptor = parseDescriptor(entry, "manifest");
4039
+ const declared = platformOf(entry.platform);
4040
+ if (declared && declared !== TARGET_PLATFORM) {
4041
+ search.otherPlatforms.add(declared);
4042
+ continue;
4043
+ }
4044
+ const mediaType = descriptor.mediaType ?? "";
4045
+ if (INDEX_MEDIA_TYPES.has(mediaType)) {
4046
+ const index = await readVerifiedJson(
4047
+ search.layoutDir,
4048
+ descriptor,
4049
+ "index"
4050
+ );
4051
+ await collectTargetImages(search, manifestsOf(index, "image index"));
4052
+ } else if (MANIFEST_MEDIA_TYPES2.has(mediaType)) {
4053
+ await collectTargetImage(search, descriptor);
4022
4054
  }
4023
4055
  }
4024
- const buildTarget = resolveBuildTarget(options.config);
4025
- span?.setAttributes({ "container.dev_mode": "build", "image.tag": tag });
4026
- emit(
4027
- out,
4028
- `\u25B2 container vercel dev: building ${tag} (docker, host platform${buildTarget ? `, target ${buildTarget}` : ""})`
4056
+ }
4057
+ async function collectTargetImage(search, descriptor) {
4058
+ if (search.matches.has(descriptor.digest)) {
4059
+ return;
4060
+ }
4061
+ const manifest = await readVerifiedJson(
4062
+ search.layoutDir,
4063
+ descriptor,
4064
+ "manifest"
4029
4065
  );
4030
- await runForwarded(
4031
- "docker",
4032
- [
4033
- "build",
4034
- ...buildArgFlags2,
4035
- ...buildTargetFlags({ buildTarget }),
4036
- "-t",
4037
- tag,
4038
- "-f",
4039
- dockerfilePath,
4040
- contextDir
4041
- ],
4042
- out
4066
+ if (!isRecord(manifest)) {
4067
+ throw new Error("OCI layout image manifest must be a JSON object.");
4068
+ }
4069
+ const configDescriptor = parseDescriptor(manifest.config, "config");
4070
+ if (configDescriptor.mediaType && !IMAGE_CONFIG_MEDIA_TYPES.has(configDescriptor.mediaType)) {
4071
+ return;
4072
+ }
4073
+ const platform = platformOf(
4074
+ await readVerifiedJson(search.layoutDir, configDescriptor, "config")
4043
4075
  );
4044
- emit(out, `\u25B2 container built ${tag}`);
4045
- return { image: tag };
4046
- }
4047
- async function resolveContainerPort(image, out) {
4048
- try {
4049
- const { stdout } = await runForwarded(
4050
- "docker",
4051
- ["image", "inspect", "--format", "{{json .Config.ExposedPorts}}", image],
4052
- out,
4053
- { quiet: true }
4054
- );
4055
- const exposed = JSON.parse(stdout.trim() || "null");
4056
- if (exposed) {
4057
- const ports = Object.keys(exposed).map((key) => Number(key.split("/")[0])).filter((n) => Number.isFinite(n)).sort((a, b) => a - b);
4058
- if (ports.length > 0) {
4059
- return ports[0];
4060
- }
4076
+ if (platform !== TARGET_PLATFORM) {
4077
+ if (platform) {
4078
+ search.otherPlatforms.add(platform);
4061
4079
  }
4062
- } catch (err) {
4063
- debug(`could not inspect EXPOSE for ${image}: ${err.message}`);
4080
+ return;
4064
4081
  }
4065
- return 3e3;
4082
+ if (!Array.isArray(manifest.layers)) {
4083
+ throw new Error("OCI layout image manifest is missing layers.");
4084
+ }
4085
+ search.matches.set(descriptor.digest, {
4086
+ descriptor,
4087
+ layers: manifest.layers
4088
+ });
4066
4089
  }
4067
- async function readMappedHostPort(containerName, containerPort, out) {
4068
- const { stdout } = await runForwarded(
4069
- "docker",
4070
- ["port", containerName, `${containerPort}/tcp`],
4071
- out,
4072
- { quiet: true }
4090
+ async function verifyOciLayout(layoutDir) {
4091
+ const marker = await readRegularJson(
4092
+ (0, import_node_path23.join)(layoutDir, "oci-layout"),
4093
+ "oci-layout"
4073
4094
  );
4074
- const match = stdout.match(/:(\d+)\s*$/m);
4075
- if (!match) {
4095
+ if (!isRecord(marker) || marker.imageLayoutVersion !== OCI_LAYOUT_VERSION) {
4076
4096
  throw new Error(
4077
- `Could not determine mapped host port for ${containerName} (${containerPort}/tcp). Got: ${stdout.trim()}`
4097
+ `Unsupported OCI layout version in "${layoutDir}". Expected "${OCI_LAYOUT_VERSION}".`
4078
4098
  );
4079
4099
  }
4080
- return Number(match[1]);
4081
- }
4082
- function uniqueContainerName(serviceName) {
4083
- const safe = serviceName.toLowerCase().replace(/[^a-z0-9-_.]/g, "-");
4084
- return `vercel-dev-${safe || "service"}-${process.pid}-${Date.now().toString(36)}`;
4085
- }
4086
- async function assertDockerAvailable(out) {
4087
- try {
4088
- await runForwarded(
4089
- "docker",
4090
- ["info", "--format", "{{.ServerVersion}}"],
4091
- out,
4092
- {
4093
- quiet: true
4094
- }
4100
+ const index = await readRegularJson(
4101
+ (0, import_node_path23.join)(layoutDir, "index.json"),
4102
+ "index.json"
4103
+ );
4104
+ const search = {
4105
+ layoutDir,
4106
+ matches: /* @__PURE__ */ new Map(),
4107
+ otherPlatforms: /* @__PURE__ */ new Set()
4108
+ };
4109
+ await collectTargetImages(search, manifestsOf(index, "index.json"));
4110
+ const images = [...search.matches.values()];
4111
+ if (images.length === 0) {
4112
+ const others = [...search.otherPlatforms].filter(
4113
+ (platform) => platform !== "unknown/unknown"
4095
4114
  );
4096
- } catch (err) {
4097
- const message = err.message ?? "";
4098
- if (/command not found/i.test(message)) {
4099
- throw new Error(
4100
- "Docker is required for `vercel dev` with containers, but the `docker` command was not found. Install Docker and ensure it is on your PATH."
4101
- );
4102
- }
4103
4115
  throw new Error(
4104
- "Could not connect to the Docker daemon. Start Docker (e.g. open Docker Desktop) and run `vercel dev` again."
4116
+ `OCI layout has no ${TARGET_PLATFORM} image${others.length > 0 ? `; found ${others.join(", ")}` : ""}.`
4105
4117
  );
4106
4118
  }
4107
- }
4108
- function containerExitMessage(exitCode, stderr) {
4109
- const detail = stderr.trim().split("\n").slice(-5).join("\n");
4110
- const looksLikeDaemonDown = exitCode === 125 || /cannot connect to the docker daemon/i.test(stderr);
4111
- if (looksLikeDaemonDown) {
4112
- return "Could not start the container: the Docker daemon is not running or is unreachable. Start Docker (e.g. open Docker Desktop) and try `vercel dev` again." + (detail ? `
4113
-
4114
- Docker reported:
4115
- ${detail}` : "");
4119
+ if (images.length > 1) {
4120
+ throw new Error(
4121
+ `OCI layout has ${images.length} ${TARGET_PLATFORM} images; expected one.`
4122
+ );
4116
4123
  }
4117
- return `The container exited (code ${exitCode}) before becoming ready.` + (detail ? `
4118
-
4119
- Docker reported:
4120
- ${detail}` : "");
4124
+ const [{ descriptor, layers }] = images;
4125
+ if (layers.length === 0) {
4126
+ throw new Error("OCI layout image manifest has no layers.");
4127
+ }
4128
+ for (let i = 0; i < layers.length; i++) {
4129
+ const layerDescriptor = parseDescriptor(layers[i], `layer[${i}]`);
4130
+ await verifyBlobSize(layoutDir, layerDescriptor, `layer[${i}]`);
4131
+ }
4132
+ return { manifestDigest: descriptor.digest };
4121
4133
  }
4122
- var runningContainers = /* @__PURE__ */ new Map();
4123
- var pendingContainers = /* @__PURE__ */ new Map();
4124
- function containerReuseKey(options) {
4125
- return options.service?.name ?? `root:${options.workPath}`;
4134
+ async function moveDirectory(sourceDir, destinationDir) {
4135
+ const parentDir = (0, import_node_path23.dirname)(destinationDir);
4136
+ await (0, import_promises9.mkdir)(parentDir, { recursive: true });
4137
+ try {
4138
+ await (0, import_promises9.rename)(sourceDir, destinationDir);
4139
+ return;
4140
+ } catch (error) {
4141
+ if (error.code !== "EXDEV") {
4142
+ throw error;
4143
+ }
4144
+ }
4145
+ const tempDir = await (0, import_promises9.mkdtemp)((0, import_node_path23.join)(parentDir, ".oci-layout-"));
4146
+ try {
4147
+ await (0, import_promises9.cp)(sourceDir, tempDir, { recursive: true });
4148
+ await (0, import_promises9.rename)(tempDir, destinationDir);
4149
+ } catch (error) {
4150
+ await (0, import_promises9.rm)(tempDir, { recursive: true, force: true });
4151
+ throw error;
4152
+ }
4153
+ await (0, import_promises9.rm)(sourceDir, { recursive: true, force: true });
4126
4154
  }
4127
- async function startDevServer(options) {
4128
- const reuseKey = containerReuseKey(options);
4129
- const existing = runningContainers.get(reuseKey);
4130
- if (existing && existing.isRunning()) {
4131
- return existing.result;
4155
+
4156
+ // src/oci-layout/pull.ts
4157
+ var import_node_crypto10 = require("crypto");
4158
+ var import_promises10 = require("fs/promises");
4159
+ var import_node_path24 = require("path");
4160
+ var MANIFEST_ACCEPT_HEADER = [
4161
+ OCI_MANIFEST_MEDIA_TYPE,
4162
+ DOCKER_MANIFEST_MEDIA_TYPE,
4163
+ OCI_INDEX_MEDIA_TYPE,
4164
+ DOCKER_MANIFEST_LIST_MEDIA_TYPE
4165
+ ].join(", ");
4166
+ var PULL_ATTEMPTS = 3;
4167
+ var PULL_TIMEOUT_MS = 3e4;
4168
+ var MAX_REDIRECTS = 5;
4169
+ function parseDigestImageRef(imageRef) {
4170
+ const atIndex = imageRef.indexOf("@");
4171
+ if (atIndex === -1) {
4172
+ throw new Error(
4173
+ `Expected a digest-pinned image reference, got "${imageRef}".`
4174
+ );
4132
4175
  }
4133
- if (existing) {
4134
- runningContainers.delete(reuseKey);
4176
+ const namePart = imageRef.slice(0, atIndex);
4177
+ const digest = imageRef.slice(atIndex + 1);
4178
+ if (!DIGEST_RE.test(digest)) {
4179
+ throw new Error(
4180
+ `Expected a sha256 digest in image reference "${imageRef}".`
4181
+ );
4135
4182
  }
4136
- const inFlight = pendingContainers.get(reuseKey);
4137
- if (inFlight) {
4138
- return inFlight;
4183
+ const firstSlash = namePart.indexOf("/");
4184
+ if (firstSlash <= 0 || firstSlash === namePart.length - 1) {
4185
+ throw new Error(
4186
+ `Expected "<registry>/<repository>@sha256:..." image reference, got "${imageRef}".`
4187
+ );
4139
4188
  }
4140
- const startPromise = startContainer(options, reuseKey).finally(() => {
4141
- pendingContainers.delete(reuseKey);
4142
- });
4143
- pendingContainers.set(reuseKey, startPromise);
4144
- return startPromise;
4189
+ const registry = namePart.slice(0, firstSlash);
4190
+ const repository = namePart.slice(firstSlash + 1);
4191
+ if (repository.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
4192
+ throw new Error(`Invalid repository in image reference "${imageRef}".`);
4193
+ }
4194
+ return { registry, repository, digest };
4145
4195
  }
4146
- async function startContainer(options, reuseKey) {
4147
- return withSpan(
4148
- options.span,
4149
- "container.dev.start",
4150
- { "service.name": options.service?.name },
4151
- async (span) => {
4152
- const { config, meta, onStdout, onStderr } = options;
4153
- const out = { onStdout, onStderr };
4154
- const { image } = await withSpan(
4155
- span,
4156
- "container.dev.resolve_image",
4157
- {},
4158
- (s) => resolveDevImage(options, out, s)
4159
- );
4160
- const containerPort = await resolveContainerPort(image, out);
4161
- const containerName = uniqueContainerName(
4162
- options.service?.name ?? "service"
4196
+ function describeFetchError2(error) {
4197
+ const err = error;
4198
+ const cause = err.cause?.message;
4199
+ return cause ? `${err.message} (${cause})` : err.message;
4200
+ }
4201
+ var OciRegistryPuller = class {
4202
+ constructor(options) {
4203
+ this.options = options;
4204
+ this.fetchImpl = options.fetchImpl ?? fetch;
4205
+ this.retryDelayMs = options.retryDelayMs ?? 500;
4206
+ }
4207
+ async pullToLayout(imageRef, destinationDir) {
4208
+ const parsed = parseDigestImageRef(imageRef);
4209
+ if (parsed.registry !== this.options.credentials.registry) {
4210
+ throw new Error(
4211
+ `Registry credentials for ${this.options.credentials.registry} cannot be used to pull from ${parsed.registry}.`
4163
4212
  );
4164
- const mergedEnv = {};
4165
- const metaEnv = meta?.env ?? {};
4166
- for (const [key, value] of Object.entries(metaEnv)) {
4167
- if (typeof value === "string" && !isHostOnlyEnvVar(key)) {
4168
- mergedEnv[key] = value;
4169
- }
4170
- }
4171
- const devResourceEndpoints = meta?.devResourceEndpoints;
4172
- const runtimeCacheEndpoint = mergedEnv.RUNTIME_CACHE_ENDPOINT;
4173
- const runtimeCacheProxy = devResourceEndpoints?.runtimeCache;
4174
- const usesRuntimeCacheProxy = runtimeCacheEndpoint === runtimeCacheProxy?.direct;
4175
- const containerRuntimeCacheEndpoint = runtimeCacheEndpoint ? useContainerHost(
4176
- usesRuntimeCacheProxy && runtimeCacheProxy ? runtimeCacheProxy.proxy : runtimeCacheEndpoint
4177
- ) : void 0;
4178
- const queueBaseUrl = mergedEnv.VERCEL_QUEUE_BASE_URL;
4179
- const queueProxy = devResourceEndpoints?.queues;
4180
- const usesQueueProxy = queueBaseUrl === queueProxy?.direct;
4181
- const containerQueueBaseUrl = queueBaseUrl ? useContainerHost(
4182
- usesQueueProxy && queueProxy ? queueProxy.proxy : queueBaseUrl
4183
- ) : void 0;
4184
- const needsHostGateway = containerRuntimeCacheEndpoint !== void 0 && containerRuntimeCacheEndpoint !== runtimeCacheEndpoint || containerQueueBaseUrl !== void 0 && containerQueueBaseUrl !== queueBaseUrl;
4185
- if (containerRuntimeCacheEndpoint) {
4186
- mergedEnv.RUNTIME_CACHE_ENDPOINT = containerRuntimeCacheEndpoint;
4187
- }
4188
- if (containerQueueBaseUrl) {
4189
- mergedEnv.VERCEL_QUEUE_BASE_URL = containerQueueBaseUrl;
4190
- }
4191
- mergedEnv.PORT = String(containerPort);
4192
- const envFilePath = writeEnvFile(mergedEnv);
4193
- const rawCommand = config.command;
4194
- const command = normalizeCommand(rawCommand);
4195
- const requestedHostPort = typeof meta?.port === "number" ? meta.port : 0;
4196
- const args = [
4197
- "run",
4198
- "--rm",
4199
- "--name",
4200
- containerName,
4201
- // Publish the container port to the orchestrator-provided host port, or
4202
- // an ephemeral host port chosen by Docker when none was requested.
4203
- "-p",
4204
- `127.0.0.1:${requestedHostPort}:${containerPort}`,
4205
- ...needsHostGateway ? ["--add-host", "host.docker.internal:host-gateway"] : [],
4206
- "--env-file",
4207
- envFilePath,
4208
- image,
4209
- ...command ?? []
4210
- ];
4211
- emit(out, `\u25B2 container vercel dev: starting container ${image}`);
4212
- debug(`docker ${args.join(" ")}`);
4213
- const child = (0, import_node_child_process4.spawn)("docker", args, {
4214
- stdio: ["ignore", "pipe", "pipe"]
4215
- });
4216
- let runStderr = "";
4217
- child.stdout?.on("data", (data) => onStdout?.(data));
4218
- child.stderr?.on("data", (data) => {
4219
- runStderr += data.toString();
4220
- onStderr?.(data);
4221
- });
4222
- child.on("error", (err) => {
4223
- if (err.code === "ENOENT") {
4224
- runStderr += "Command not found: `docker`. Ensure Docker is installed and on your PATH, and that the Docker daemon is running.";
4225
- }
4226
- });
4227
- const cleanupEnvFile = () => {
4228
- (0, import_node_fs16.rmSync)(import_node_path23.default.dirname(envFilePath), { recursive: true, force: true });
4229
- };
4230
- const shutdown = async () => {
4231
- runningContainers.delete(reuseKey);
4232
- try {
4233
- await runForwarded("docker", ["stop", containerName], out, {
4234
- quiet: true
4235
- });
4236
- } catch (err) {
4237
- debug(
4238
- `docker stop ${containerName} failed: ${err.message}`
4213
+ }
4214
+ const baseUrl = (this.options.baseUrl ?? `https://${parsed.registry}`).replace(/\/+$/, "");
4215
+ const baseOrigin = new URL(baseUrl).origin;
4216
+ const requireHttps = new URL(baseUrl).protocol === "https:";
4217
+ const authorization = `Basic ${Buffer.from(
4218
+ `${this.options.credentials.username}:${this.options.credentials.token}`
4219
+ ).toString("base64")}`;
4220
+ const manifestUrl = `${baseUrl}/v2/${parsed.repository}/manifests/${parsed.digest}`;
4221
+ const manifestBytes = await this.fetchBytes({
4222
+ url: manifestUrl,
4223
+ baseOrigin,
4224
+ requireHttps,
4225
+ authorization,
4226
+ accept: MANIFEST_ACCEPT_HEADER,
4227
+ registry: parsed.registry,
4228
+ label: `manifest ${imageRef}`
4229
+ });
4230
+ const actualManifestDigest = sha256Digest(manifestBytes);
4231
+ if (actualManifestDigest !== parsed.digest) {
4232
+ throw new Error(
4233
+ `Manifest digest mismatch for ${imageRef}: expected ${parsed.digest}, received ${actualManifestDigest}.`
4234
+ );
4235
+ }
4236
+ let manifest;
4237
+ try {
4238
+ manifest = JSON.parse(new TextDecoder().decode(manifestBytes));
4239
+ } catch {
4240
+ throw new Error(`Manifest for ${imageRef} is not valid JSON.`);
4241
+ }
4242
+ if (!isRecord(manifest)) {
4243
+ throw new Error(`Manifest for ${imageRef} must be a JSON object.`);
4244
+ }
4245
+ if (Array.isArray(manifest.manifests) && (!manifest.config || !Array.isArray(manifest.layers))) {
4246
+ throw new Error(
4247
+ `Expected ${imageRef} to resolve to a single linux/amd64 image manifest, not an image index.`
4248
+ );
4249
+ }
4250
+ if (!Array.isArray(manifest.layers) || manifest.layers.length === 0) {
4251
+ throw new Error(`Manifest for ${imageRef} has no layers.`);
4252
+ }
4253
+ const configDescriptor = parseDescriptor(manifest.config, "config");
4254
+ const layerDescriptors = manifest.layers.map(
4255
+ (layer, index) => parseDescriptor(layer, `layer[${index}]`)
4256
+ );
4257
+ const blobsDir = (0, import_node_path24.join)(destinationDir, "blobs", "sha256");
4258
+ await (0, import_promises10.mkdir)(blobsDir, { recursive: true, mode: 493 });
4259
+ try {
4260
+ await (0, import_promises10.writeFile)(
4261
+ (0, import_node_path24.join)(blobsDir, parseSha256Hex(parsed.digest)),
4262
+ manifestBytes
4263
+ );
4264
+ const fetchBlob = async (descriptor, label) => {
4265
+ const written = await this.fetchToFile(
4266
+ {
4267
+ url: `${baseUrl}/v2/${parsed.repository}/blobs/${descriptor.digest}`,
4268
+ baseOrigin,
4269
+ requireHttps,
4270
+ authorization,
4271
+ registry: parsed.registry,
4272
+ label: `${label} ${descriptor.digest}`
4273
+ },
4274
+ blobPath2(destinationDir, descriptor.digest)
4275
+ );
4276
+ if (written.size !== descriptor.size) {
4277
+ throw new Error(
4278
+ `Blob size mismatch for ${label} ${descriptor.digest}: expected ${descriptor.size}, received ${written.size}.`
4239
4279
  );
4240
- } finally {
4241
- cleanupEnvFile();
4242
- }
4243
- };
4244
- let hostPort;
4245
- const deadline = Date.now() + 3e4;
4246
- let lastErr;
4247
- try {
4248
- while (Date.now() < deadline) {
4249
- if (child.exitCode !== null) {
4250
- throw new Error(containerExitMessage(child.exitCode, runStderr));
4251
- }
4252
- try {
4253
- hostPort = await readMappedHostPort(
4254
- containerName,
4255
- containerPort,
4256
- out
4257
- );
4258
- break;
4259
- } catch (err) {
4260
- lastErr = err;
4261
- await new Promise((resolve5) => setTimeout(resolve5, 250));
4262
- }
4263
4280
  }
4264
- if (hostPort === void 0) {
4281
+ if (written.digest !== descriptor.digest) {
4265
4282
  throw new Error(
4266
- `Timed out waiting for container "${containerName}" to publish port ${containerPort}.` + (lastErr ? ` Last error: ${lastErr.message}` : "")
4283
+ `Blob digest mismatch for ${label} ${descriptor.digest}: received ${written.digest}.`
4267
4284
  );
4268
4285
  }
4269
- } catch (err) {
4270
- await shutdown();
4271
- throw err;
4272
- }
4273
- span?.setAttributes({
4274
- "container.dev.host_port": String(hostPort),
4275
- "container.dev.container_port": String(containerPort),
4276
- "container.name": containerName
4277
- });
4278
- emit(out, `\u25B2 container container ready on localhost:${hostPort}`);
4279
- const result = {
4280
- port: hostPort,
4281
- pid: child.pid ?? 0,
4282
- shutdown,
4283
- // The container is a long-running server; the dev server should keep it
4284
- // alive across requests instead of tearing it down after each response.
4285
- persistent: true
4286
- };
4287
- const running = {
4288
- result,
4289
- containerName,
4290
- isRunning: () => child.exitCode === null
4291
4286
  };
4292
- child.on("close", () => {
4293
- if (runningContainers.get(reuseKey) === running) {
4294
- runningContainers.delete(reuseKey);
4287
+ const uniqueLayers = /* @__PURE__ */ new Map();
4288
+ for (const layer of layerDescriptors) {
4289
+ if (!uniqueLayers.has(layer.digest)) {
4290
+ uniqueLayers.set(layer.digest, layer);
4295
4291
  }
4296
- });
4297
- runningContainers.set(reuseKey, running);
4298
- return result;
4299
- }
4300
- );
4301
- }
4302
-
4303
- // src/prepare-cache.ts
4304
- var import_build_utils10 = require("@vercel/build-utils");
4305
- var import_node_path24 = require("path");
4306
- async function prepareCache(options) {
4307
- const root = (0, import_node_path24.resolve)(options.repoRootPath || options.workPath);
4308
- const buildpackFiles = await collectBuildpackCache(root);
4309
- const buildahStoreFiles = await BuildahStoreCache.forProject(
4310
- options,
4311
- new BuildahClient(sharedBuildahStoreLock)
4312
- ).afterBuilds();
4313
- return { ...buildpackFiles, ...buildahStoreFiles };
4314
- }
4315
- async function collectBuildpackCache(root) {
4316
- const start = Date.now();
4317
- const files = await (0, import_build_utils10.glob)(`${BUILDPACK_CACHE_DIR}/**`, root);
4318
- const count = Object.keys(files).length;
4319
- if (count > 0) {
4320
- info(
4321
- `cached ${count} file${count === 1 ? "" : "s"} under ${BUILDPACK_CACHE_DIR} in ${Date.now() - start}ms`
4322
- );
4323
- } else {
4324
- debug(`no cache to persist under ${BUILDPACK_CACHE_DIR}`);
4325
- }
4326
- return files;
4327
- }
4328
-
4329
- // src/executable-image/index.ts
4330
- var import_node_crypto11 = require("crypto");
4331
- var import_promises12 = require("fs/promises");
4332
- var import_node_path28 = require("path");
4333
-
4334
- // src/buildpacks/lifecycle/native.ts
4335
- var import_node_fs17 = require("fs");
4336
- var import_promises9 = require("fs/promises");
4337
- var import_node_path25 = require("path");
4338
- var import_smol_toml4 = require("smol-toml");
4339
- var PREBUILT_STATIC_GROUP = {
4340
- runtime: "prebuilt-static",
4341
- buildpacks: [vercelBuildpack("prebuilt-static")]
4342
- };
4343
- var HIVE_RUNTIME_MOUNTS = ["/tmp", "/opt/vercel"];
4344
- function assertLinuxX64(platform = process.platform, arch = process.arch) {
4345
- if (platform !== "linux" || arch !== "x64") {
4346
- throw new Error(
4347
- `Executable image builds require Linux x64 (current platform: ${platform}/${arch}).`
4348
- );
4349
- }
4350
- }
4351
- async function resolveNativeBuildUser(deps = {}) {
4352
- const uid = (deps.getuid ?? process.getuid)?.();
4353
- const gid = (deps.getgid ?? process.getgid)?.();
4354
- if (uid === void 0 || gid === void 0) {
4355
- throw new Error("The native CNB lifecycle requires Unix user IDs.");
4356
- }
4357
- if (uid !== 0 && gid !== 0) {
4358
- return { uid, gid, switchUser: false };
4359
- }
4360
- if (uid !== 0) {
4361
- throw new Error("The native CNB lifecycle cannot run with the root group.");
4362
- }
4363
- const passwd = await (deps.readPasswd ?? (() => (0, import_promises9.readFile)("/etc/passwd", "utf8")))();
4364
- const nobody = passwd.split("\n").map((line) => line.split(":")).find(([name]) => name === "nobody");
4365
- const unprivilegedUid = Number(nobody?.[2]);
4366
- const unprivilegedGid = Number(nobody?.[3]);
4367
- if (!Number.isInteger(unprivilegedUid) || !Number.isInteger(unprivilegedGid) || unprivilegedUid <= 0 || unprivilegedGid <= 0) {
4368
- throw new Error(
4369
- "The native CNB lifecycle requires a non-root nobody account."
4370
- );
4371
- }
4372
- return { uid: unprivilegedUid, gid: unprivilegedGid, switchUser: true };
4373
- }
4374
- async function resolveStagingParent(resolveRealpath = import_promises9.realpath) {
4375
- const parent = await resolveRealpath("/var/tmp");
4376
- if (HIVE_RUNTIME_MOUNTS.some(
4377
- (mount) => parent === mount || parent.startsWith(`${mount}/`)
4378
- )) {
4379
- throw new Error(
4380
- `Cannot stage the native CNB image in ${parent}: Hive mounts over that path at runtime.`
4381
- );
4382
- }
4383
- return parent;
4384
- }
4385
- async function chownRecursive(rootPath, uid, gid) {
4386
- const stats = await (0, import_promises9.lstat)(rootPath);
4387
- if (stats.isDirectory()) {
4388
- for (const entry of await (0, import_promises9.readdir)(rootPath)) {
4389
- await chownRecursive((0, import_node_path25.join)(rootPath, entry), uid, gid);
4292
+ }
4293
+ await settleAll([
4294
+ fetchBlob(configDescriptor, "config"),
4295
+ ...[...uniqueLayers.values()].map(
4296
+ (layer, index) => fetchBlob(layer, `layer[${index}]`)
4297
+ )
4298
+ ]);
4299
+ let config;
4300
+ try {
4301
+ config = JSON.parse(
4302
+ await (0, import_promises10.readFile)(
4303
+ blobPath2(destinationDir, configDescriptor.digest),
4304
+ "utf8"
4305
+ )
4306
+ );
4307
+ } catch {
4308
+ throw new Error(`Config blob for ${imageRef} is not valid JSON.`);
4309
+ }
4310
+ if (!isRecord(config) || config.os !== "linux" || config.architecture !== "amd64") {
4311
+ throw new Error(
4312
+ `Run image ${imageRef} must target linux/amd64, found ${JSON.stringify(
4313
+ isRecord(config) ? `${config.os}/${config.architecture}` : config
4314
+ )}.`
4315
+ );
4316
+ }
4317
+ const manifestMediaType = typeof manifest.mediaType === "string" ? manifest.mediaType : OCI_MANIFEST_MEDIA_TYPE;
4318
+ await (0, import_promises10.writeFile)(
4319
+ (0, import_node_path24.join)(destinationDir, "oci-layout"),
4320
+ JSON.stringify({ imageLayoutVersion: OCI_LAYOUT_VERSION })
4321
+ );
4322
+ await (0, import_promises10.writeFile)(
4323
+ (0, import_node_path24.join)(destinationDir, "index.json"),
4324
+ JSON.stringify({
4325
+ schemaVersion: 2,
4326
+ mediaType: OCI_INDEX_MEDIA_TYPE,
4327
+ manifests: [
4328
+ {
4329
+ mediaType: manifestMediaType,
4330
+ digest: parsed.digest,
4331
+ size: manifestBytes.byteLength
4332
+ }
4333
+ ]
4334
+ })
4335
+ );
4336
+ return { manifestDigest: parsed.digest };
4337
+ } catch (error) {
4338
+ await (0, import_promises10.rm)(destinationDir, { recursive: true, force: true });
4339
+ throw error;
4390
4340
  }
4391
4341
  }
4392
- await (0, import_promises9.lchown)(rootPath, uid, gid);
4393
- }
4394
- async function verifyLaunchCommand(layersDir, executablePath) {
4395
- const metadata = (0, import_smol_toml4.parse)(
4396
- await (0, import_promises9.readFile)((0, import_node_path25.join)(layersDir, "config", "metadata.toml"), "utf8")
4397
- );
4398
- const valid = metadata.processes?.some(
4399
- (proc) => proc.type === "web" && proc.direct === true && proc.command?.length === 1 && (proc.command[0] === executablePath || proc.command[0] === "./user-server")
4400
- );
4401
- if (!valid) {
4402
- throw new Error(
4403
- "The prebuilt-static buildpack did not declare the staged user-server as its direct web process."
4342
+ fetchBytes(request) {
4343
+ return this.fetchWithRetries(
4344
+ request,
4345
+ async (response) => new Uint8Array(await response.arrayBuffer())
4404
4346
  );
4405
4347
  }
4406
- }
4407
- var NativeLifecycleRunner = class {
4408
- constructor(options) {
4409
- this.options = options;
4410
- this.runCommand = options.runCommand ?? run;
4411
- }
4412
- async runPush(params) {
4413
- return this.execute(
4414
- params.executablePath,
4415
- {
4416
- kind: "registry",
4417
- imageRef: params.imageRef,
4418
- credentials: params.credentials
4419
- },
4420
- async (reportFile) => {
4421
- const digest = readReportDigest(await (0, import_promises9.readFile)(reportFile, "utf8"));
4422
- if (!digest) {
4423
- throw new Error("The CNB lifecycle did not report an image digest.");
4348
+ /** Streams a blob into `path`, hashing it on the way, and returns its size and digest. */
4349
+ fetchToFile(request, path4) {
4350
+ return this.fetchWithRetries(request, async (response) => {
4351
+ const hash = (0, import_node_crypto10.createHash)("sha256");
4352
+ let size = 0;
4353
+ const file = await (0, import_promises10.open)(path4, "w");
4354
+ try {
4355
+ if (response.body) {
4356
+ for await (const chunk of response.body) {
4357
+ hash.update(chunk);
4358
+ size += chunk.byteLength;
4359
+ await file.write(chunk);
4360
+ }
4424
4361
  }
4425
- return digest;
4426
- },
4427
- params.span
4428
- );
4429
- }
4430
- async runLayout(params) {
4431
- await this.execute(
4432
- params.executablePath,
4433
- {
4434
- kind: "oci-layout",
4435
- imageRef: params.outputImageRef,
4436
- layoutDir: params.layoutRoot
4437
- },
4438
- async () => void 0,
4439
- params.span
4440
- );
4362
+ } finally {
4363
+ await file.close();
4364
+ }
4365
+ return { size, digest: `sha256:${hash.digest("hex")}` };
4366
+ });
4441
4367
  }
4442
4368
  /**
4443
- * Runs the creator, then `readResult` while the creator's report still
4444
- * exists, so a failure in either is reported as a lifecycle failure.
4369
+ * GETs `request.url`, retrying network errors, 429 and 5xx responses.
4370
+ * `readBody` runs inside the retry, so a connection that drops while the
4371
+ * body streams is retried like one that drops before the headers arrive.
4445
4372
  */
4446
- async execute(executablePath, target, readResult, span) {
4447
- const executableStats = await (0, import_promises9.lstat)(executablePath);
4448
- if (!executableStats.isFile() || executableStats.size === 0) {
4449
- throw new Error(
4450
- "The prebuilt executable must be a nonempty regular file."
4451
- );
4373
+ async fetchWithRetries(request, readBody) {
4374
+ let lastError = `Failed to pull ${request.label}.`;
4375
+ for (let attempt = 1; attempt <= PULL_ATTEMPTS; attempt++) {
4376
+ debug(`registry pull (${attempt}/${PULL_ATTEMPTS}): GET ${request.url}`);
4377
+ try {
4378
+ const response = await this.fetchFollowingRedirects(
4379
+ request.url,
4380
+ request.baseOrigin,
4381
+ request.requireHttps,
4382
+ request.authorization,
4383
+ request.accept
4384
+ );
4385
+ if (response.ok) {
4386
+ return await readBody(response);
4387
+ }
4388
+ if (response.status === 401 || response.status === 403) {
4389
+ throw new NonRetryablePullError(
4390
+ request.registry === VCR_REGISTRY ? formatVcrAuthError(
4391
+ request.registry,
4392
+ this.options.credentials.username,
4393
+ `HTTP ${response.status} pulling ${request.label}.`
4394
+ ) : `Registry authentication failed pulling ${request.label}: HTTP ${response.status}.`
4395
+ );
4396
+ }
4397
+ lastError = `Failed to pull ${request.label}: HTTP ${response.status}.`;
4398
+ if (response.status !== 429 && response.status < 500) {
4399
+ throw new NonRetryablePullError(lastError);
4400
+ }
4401
+ } catch (error) {
4402
+ if (error instanceof NonRetryablePullError) {
4403
+ throw error;
4404
+ }
4405
+ lastError = `Failed to pull ${request.label}: ${describeFetchError2(error)}`;
4406
+ }
4407
+ if (attempt < PULL_ATTEMPTS) {
4408
+ await delay(this.retryDelayMs * 2 ** (attempt - 1));
4409
+ }
4452
4410
  }
4453
- const { user, stagingParent, cnbDir, platformDir, orderFile, runImage } = this.options;
4454
- const runRoot = await (0, import_promises9.mkdtemp)((0, import_node_path25.join)(stagingParent, "vercel-cnb-native-"));
4455
- try {
4456
- if (user.switchUser) {
4457
- await (0, import_promises9.chmod)(runRoot, 493);
4411
+ throw new Error(lastError);
4412
+ }
4413
+ async fetchFollowingRedirects(initialUrl, baseOrigin, requireHttps, authorization, accept) {
4414
+ let currentUrl = new URL(initialUrl);
4415
+ for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects++) {
4416
+ const headers = {};
4417
+ if (currentUrl.origin === baseOrigin) {
4418
+ headers.authorization = authorization;
4458
4419
  }
4459
- const workPath = (0, import_node_path25.join)(runRoot, "workspace");
4460
- const layers = (0, import_node_path25.join)(runRoot, "layers");
4461
- const reportDir = (0, import_node_path25.join)(runRoot, "report");
4462
- const home = (0, import_node_path25.join)(runRoot, "home");
4463
- const temp = (0, import_node_path25.join)(runRoot, "tmp");
4464
- const dirs = [workPath, layers, reportDir, home, temp];
4465
- for (const dir of dirs) {
4466
- await (0, import_promises9.mkdir)(dir, { mode: 448 });
4420
+ if (accept) {
4421
+ headers.accept = accept;
4467
4422
  }
4468
- const executable = (0, import_node_path25.join)(workPath, "user-server");
4469
- await (0, import_promises9.copyFile)(executablePath, executable, import_node_fs17.constants.COPYFILE_EXCL);
4470
- const handle = await (0, import_promises9.open)(
4471
- executable,
4472
- import_node_fs17.constants.O_RDONLY | import_node_fs17.constants.O_NOFOLLOW
4473
- );
4474
- try {
4475
- await handle.chmod(493);
4476
- if (user.switchUser) {
4477
- await handle.chown(user.uid, user.gid);
4478
- }
4479
- } finally {
4480
- await handle.close();
4423
+ const response = await this.fetchImpl(currentUrl.href, {
4424
+ method: "GET",
4425
+ headers,
4426
+ redirect: "manual",
4427
+ signal: AbortSignal.timeout(PULL_TIMEOUT_MS)
4428
+ });
4429
+ if (response.status < 300 || response.status >= 400) {
4430
+ return response;
4481
4431
  }
4482
- if (user.switchUser) {
4483
- for (const dir of dirs) {
4484
- await (0, import_promises9.chown)(dir, user.uid, user.gid);
4485
- }
4432
+ const location = response.headers.get("location");
4433
+ if (!location) {
4434
+ return response;
4486
4435
  }
4487
- const lifecycleDir = (0, import_node_path25.join)(cnbDir, "lifecycle");
4488
- const reportFile = (0, import_node_path25.join)(reportDir, "report.toml");
4489
- const { args: exportArgs, env: exportEnv } = creatorExport(target);
4490
- const args = [
4491
- `-app=${workPath}`,
4492
- `-layers=${layers}`,
4493
- `-buildpacks=${(0, import_node_path25.join)(cnbDir, "buildpacks")}`,
4494
- `-platform=${platformDir}`,
4495
- `-order=${orderFile}`,
4496
- `-launcher=${(0, import_node_path25.join)(lifecycleDir, "launcher")}`,
4497
- `-launcher-sbom=${lifecycleDir}`,
4498
- `-uid=${user.uid}`,
4499
- `-gid=${user.gid}`,
4500
- `-run-image=${runImage}`,
4501
- `-report=${reportFile}`,
4502
- "-skip-restore",
4503
- ...exportArgs
4504
- ];
4505
- const env = {
4506
- PATH: "/usr/bin:/bin",
4507
- HOME: home,
4508
- TMPDIR: temp,
4509
- ...target.kind === "registry" && { DOCKER_CONFIG: home },
4510
- CNB_PLATFORM_API,
4511
- ...exportEnv
4512
- };
4513
- try {
4514
- await this.runCommand((0, import_node_path25.join)(lifecycleDir, "creator"), args, {
4515
- cwd: workPath,
4516
- ...user.switchUser && { uid: user.uid, gid: user.gid },
4517
- env
4518
- });
4519
- await verifyLaunchCommand(layers, executable);
4520
- return await readResult(reportFile);
4521
- } catch (error) {
4522
- throw lifecycleFailure(error, {
4523
- buildpack: this.options.buildpack,
4524
- via: "native lifecycle",
4525
- workPath,
4526
- span
4527
- });
4436
+ if (redirects === MAX_REDIRECTS) {
4437
+ throw new NonRetryablePullError(
4438
+ `Too many redirects pulling ${initialUrl}.`
4439
+ );
4528
4440
  }
4529
- } finally {
4530
- await (0, import_promises9.rm)(runRoot, { recursive: true, force: true });
4441
+ const nextUrl = new URL(location, currentUrl);
4442
+ if (requireHttps && nextUrl.protocol !== "https:") {
4443
+ throw new NonRetryablePullError(
4444
+ `Refusing insecure redirect to ${nextUrl.protocol} while pulling from HTTPS registry.`
4445
+ );
4446
+ }
4447
+ currentUrl = nextUrl;
4531
4448
  }
4449
+ throw new NonRetryablePullError(
4450
+ `Too many redirects pulling ${initialUrl}.`
4451
+ );
4532
4452
  }
4533
4453
  };
4454
+ var NonRetryablePullError = class extends Error {
4455
+ };
4534
4456
 
4535
- // src/oci-layout/layout.ts
4536
- var import_node_crypto9 = require("crypto");
4537
- var import_promises10 = require("fs/promises");
4538
- var import_node_path26 = require("path");
4539
- var OCI_LAYOUT_VERSION = "1.0.0";
4540
- var OCI_INDEX_MEDIA_TYPE = "application/vnd.oci.image.index.v1+json";
4541
- var OCI_MANIFEST_MEDIA_TYPE = "application/vnd.oci.image.manifest.v1+json";
4542
- var DOCKER_MANIFEST_MEDIA_TYPE = "application/vnd.docker.distribution.manifest.v2+json";
4543
- var SINGLE_MANIFEST_MEDIA_TYPES = /* @__PURE__ */ new Set([
4544
- OCI_MANIFEST_MEDIA_TYPE,
4545
- DOCKER_MANIFEST_MEDIA_TYPE
4546
- ]);
4547
- function isRecord(value) {
4548
- return typeof value === "object" && value !== null && !Array.isArray(value);
4549
- }
4550
- function sha256Digest(bytes) {
4551
- const view = bytes instanceof Uint8Array && !Buffer.isBuffer(bytes) ? bytes : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
4552
- return `sha256:${(0, import_node_crypto9.createHash)("sha256").update(view).digest("hex")}`;
4457
+ // src/oci-layout/index.ts
4458
+ var CONTAINER_OCI_LAYOUT_ENV = "VERCEL_CONTAINER_OCI_LAYOUT";
4459
+ function ociLayoutRequested(env = process.env) {
4460
+ return env[CONTAINER_OCI_LAYOUT_ENV] === "1";
4553
4461
  }
4554
- function parseSha256Hex(digest) {
4555
- if (!DIGEST_RE.test(digest)) {
4556
- throw new Error(`Unsupported OCI digest ${JSON.stringify(digest)}.`);
4462
+
4463
+ // src/publish.ts
4464
+ var import_promises11 = require("fs/promises");
4465
+ var import_node_os12 = require("os");
4466
+ var import_node_path25 = require("path");
4467
+ function createImagePublisher(params) {
4468
+ const { build: build2, engine, exportLayout } = params;
4469
+ if (!exportLayout) {
4470
+ return new VcrPublisher(engine, build2);
4557
4471
  }
4558
- return digest.slice("sha256:".length);
4559
- }
4560
- function blobPath2(layoutDir, digest) {
4561
- return (0, import_node_path26.join)(layoutDir, "blobs", "sha256", parseSha256Hex(digest));
4562
- }
4563
- function assertSafePathSegment(segment, imageRef) {
4564
- if (!segment || segment === "." || segment === ".." || segment.includes("/") || segment.includes("\\")) {
4565
- throw new Error(`Invalid image reference for OCI layout: "${imageRef}".`);
4472
+ if (!exportsLayouts(engine)) {
4473
+ throw new Error(
4474
+ `${CONTAINER_OCI_LAYOUT_ENV}=1 needs Buildah to write the image as an OCI image layout, but this build uses ${engine.name}.`
4475
+ );
4566
4476
  }
4477
+ return new OciLayoutPublisher(engine, build2);
4567
4478
  }
4568
- function layoutRefPath(layoutDir, imageRef) {
4569
- const firstSlash = imageRef.indexOf("/");
4570
- if (firstSlash <= 0 || firstSlash === imageRef.length - 1) {
4571
- throw new Error(`Invalid image reference for OCI layout: "${imageRef}".`);
4479
+ var VcrPublisher = class {
4480
+ constructor(engine, build2) {
4481
+ this.engine = engine;
4482
+ this.build = build2;
4483
+ this.mode = "build_and_push";
4484
+ this.spanAttributes = { "container.registry": VCR_REGISTRY };
4572
4485
  }
4573
- const registry = imageRef.slice(0, firstSlash);
4574
- assertSafePathSegment(registry, imageRef);
4575
- const remainder = imageRef.slice(firstSlash + 1);
4576
- const atIndex = remainder.indexOf("@");
4577
- if (atIndex !== -1) {
4578
- const repository2 = remainder.slice(0, atIndex);
4579
- const digest = remainder.slice(atIndex + 1);
4580
- const repoParts2 = repository2.split("/");
4581
- for (const part of repoParts2) {
4582
- assertSafePathSegment(part, imageRef);
4583
- }
4584
- const hex = parseSha256Hex(digest);
4585
- return (0, import_node_path26.join)(layoutDir, registry, ...repoParts2, "sha256", hex);
4486
+ async resolve(span) {
4487
+ const { repository, tag } = this.build;
4488
+ const target = await resolveRegistryTarget({ repository, tag, span });
4489
+ span?.setAttributes({
4490
+ "container.repository": target.fullRepository,
4491
+ "image.tag": tag,
4492
+ "image.ref": target.imageRef,
4493
+ "registry.username": target.username
4494
+ });
4495
+ return {
4496
+ imageRef: target.imageRef,
4497
+ connect: (connectSpan) => this.connect(target, connectSpan),
4498
+ publish: (params, pushSpan) => this.push(target, params, pushSpan)
4499
+ };
4586
4500
  }
4587
- const colonIndex = remainder.lastIndexOf(":");
4588
- if (colonIndex <= remainder.lastIndexOf("/") || colonIndex === remainder.length - 1) {
4589
- throw new Error(`Invalid image reference for OCI layout: "${imageRef}".`);
4501
+ async connect(target, span) {
4502
+ await authenticateRegistry(this.engine, this.credentials(target), span);
4503
+ await withSpan(
4504
+ span,
4505
+ "container.ensure_repository",
4506
+ { "container.repository": this.build.repository },
4507
+ (s) => ensureRepository(this.build.repository, target.token, target.claims, s)
4508
+ );
4590
4509
  }
4591
- const repository = remainder.slice(0, colonIndex);
4592
- const tag = remainder.slice(colonIndex + 1);
4593
- const repoParts = repository.split("/");
4594
- for (const part of repoParts) {
4595
- assertSafePathSegment(part, imageRef);
4510
+ async push(target, params, span) {
4511
+ const { imageRef } = params;
4512
+ const pushStart = Date.now();
4513
+ step(`Pushing ${imageRef}`);
4514
+ const digest = await withSpan(
4515
+ span,
4516
+ "container.push",
4517
+ { "image.ref": imageRef },
4518
+ () => this.engine.push({
4519
+ ...params,
4520
+ ...this.credentials(target),
4521
+ repository: this.build.repository
4522
+ })
4523
+ );
4524
+ done(`pushed ${shortDigest(digest)} in ${elapsed(pushStart)}`);
4525
+ const reference = `${VCR_REGISTRY}/${target.fullRepository}@${digest}`;
4526
+ span?.setAttributes({
4527
+ "image.digest": digest,
4528
+ "image.resolved_ref": reference
4529
+ });
4530
+ info(`Image reference ${reference}`);
4531
+ return { kind: "registry", reference };
4596
4532
  }
4597
- assertSafePathSegment(tag, imageRef);
4598
- return (0, import_node_path26.join)(layoutDir, registry, ...repoParts, tag);
4533
+ credentials(target) {
4534
+ return {
4535
+ registry: VCR_REGISTRY,
4536
+ username: target.username,
4537
+ token: target.token
4538
+ };
4539
+ }
4540
+ };
4541
+ var OciLayoutPublisher = class {
4542
+ constructor(engine, build2) {
4543
+ this.engine = engine;
4544
+ this.build = build2;
4545
+ this.mode = "build_and_export";
4546
+ this.spanAttributes = {};
4547
+ }
4548
+ async resolve(span) {
4549
+ const imageRef = `localhost/${this.build.repository}:${this.build.tag}`;
4550
+ span?.setAttributes({ "image.tag": this.build.tag, "image.ref": imageRef });
4551
+ return {
4552
+ imageRef,
4553
+ publish: (params, exportSpan) => this.exportLayout(params, exportSpan)
4554
+ };
4555
+ }
4556
+ async exportLayout(params, span) {
4557
+ const { imageRef } = params;
4558
+ const exportStart = Date.now();
4559
+ step("Saving image");
4560
+ const directory = await createStagingDirectory();
4561
+ debug(`exporting ${imageRef} as an OCI image layout to ${directory}`);
4562
+ try {
4563
+ const { manifestDigest } = await withSpan(
4564
+ span,
4565
+ "container.export_layout",
4566
+ { "image.ref": imageRef },
4567
+ async () => {
4568
+ await this.engine.exportLayout(params, directory);
4569
+ return verifyOciLayout(directory);
4570
+ }
4571
+ );
4572
+ done(`saved ${shortDigest(manifestDigest)} in ${elapsed(exportStart)}`);
4573
+ span?.setAttributes({ "image.digest": manifestDigest });
4574
+ return { kind: "oci-layout", directory, manifestDigest };
4575
+ } catch (error) {
4576
+ await (0, import_promises11.rm)(directory, { recursive: true, force: true });
4577
+ throw error;
4578
+ }
4579
+ }
4580
+ };
4581
+ async function createStagingDirectory() {
4582
+ const parent = isBuildContainer() ? (0, import_node_path25.join)((0, import_node_path25.dirname)(BUILDAH_GRAPH_ROOT), "oci-layouts") : (0, import_node_os12.tmpdir)();
4583
+ await (0, import_promises11.mkdir)(parent, { recursive: true });
4584
+ return (0, import_promises11.mkdtemp)((0, import_node_path25.join)(parent, "vercel-container-layout-"));
4599
4585
  }
4600
- function parseDescriptor(value, label) {
4601
- if (!isRecord(value)) {
4602
- throw new Error(`Invalid OCI ${label} descriptor.`);
4586
+ async function authenticateRegistry(engine, credentials, span) {
4587
+ const forceLogin = readString(process.env.VERCEL_VCR_FORCE_LOGIN) === "1";
4588
+ const authFile = forceLogin ? void 0 : existingRegistryAuthFile();
4589
+ if (authFile) {
4590
+ debug(`registry auth file present: ${authFile}`);
4591
+ step(`Using registry credentials from ${authFile}`);
4592
+ span?.setAttributes({
4593
+ "container.registry": VCR_REGISTRY,
4594
+ "registry.username": credentials.username,
4595
+ "registry.auth_file": authFile,
4596
+ "registry.login_skipped": toTag(true)
4597
+ });
4598
+ done("authenticated via provisioned credentials");
4599
+ return;
4603
4600
  }
4604
- const { mediaType, digest, size } = value;
4605
- if (typeof digest !== "string" || !DIGEST_RE.test(digest)) {
4606
- throw new Error(`Invalid OCI ${label} digest: ${JSON.stringify(digest)}.`);
4601
+ step(`Authenticating to ${VCR_REGISTRY} as ${credentials.username}`);
4602
+ await withSpan(
4603
+ span,
4604
+ "container.registry_login",
4605
+ {
4606
+ "container.registry": VCR_REGISTRY,
4607
+ "registry.username": credentials.username
4608
+ },
4609
+ () => engine.login(credentials)
4610
+ );
4611
+ done("authenticated");
4612
+ }
4613
+
4614
+ // src/dev.ts
4615
+ var import_build_utils9 = require("@vercel/build-utils");
4616
+ var import_node_child_process4 = require("child_process");
4617
+ var import_node_fs16 = require("fs");
4618
+ var import_node_os13 = require("os");
4619
+ var import_node_path26 = __toESM(require("path"));
4620
+ var HOST_ONLY_ENV = /* @__PURE__ */ new Set([
4621
+ "TMPDIR",
4622
+ "TMP",
4623
+ "TEMP",
4624
+ "HOME",
4625
+ "PATH",
4626
+ "PWD",
4627
+ "OLDPWD",
4628
+ "SHELL",
4629
+ "SHLVL",
4630
+ "USER",
4631
+ "LOGNAME",
4632
+ "TERM",
4633
+ "TERM_PROGRAM",
4634
+ "TERM_PROGRAM_VERSION",
4635
+ "TERM_SESSION_ID",
4636
+ "COLORTERM",
4637
+ "LANG",
4638
+ "LC_ALL",
4639
+ "LC_CTYPE",
4640
+ "COMMAND_MODE",
4641
+ "SECURITYSESSIONID",
4642
+ "__CF_USER_TEXT_ENCODING",
4643
+ "__CFBundleIdentifier"
4644
+ ]);
4645
+ function isHostOnlyEnvVar(key) {
4646
+ return HOST_ONLY_ENV.has(key) || key.startsWith("__") || key.startsWith("XPC_") || key.startsWith("SSH_") || key.startsWith("Apple");
4647
+ }
4648
+ function writeEnvFile(env) {
4649
+ const dir = (0, import_node_fs16.mkdtempSync)(import_node_path26.default.join((0, import_node_os13.tmpdir)(), "vercel-container-dev-env-"));
4650
+ const file = import_node_path26.default.join(dir, "env");
4651
+ const lines = [];
4652
+ for (const [key, value] of Object.entries(env)) {
4653
+ if (value.includes("\n")) {
4654
+ continue;
4655
+ }
4656
+ lines.push(`${key}=${value}`);
4607
4657
  }
4608
- if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
4609
- throw new Error(`Invalid OCI ${label} size: ${JSON.stringify(size)}.`);
4658
+ (0, import_node_fs16.writeFileSync)(file, `${lines.join("\n")}
4659
+ `);
4660
+ return file;
4661
+ }
4662
+ function useContainerHost(endpoint) {
4663
+ try {
4664
+ const url = new URL(endpoint);
4665
+ if (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]") {
4666
+ url.hostname = "host.docker.internal";
4667
+ return url.toString();
4668
+ }
4669
+ } catch {
4610
4670
  }
4611
- if (mediaType !== void 0 && typeof mediaType !== "string") {
4612
- throw new Error(`Invalid OCI ${label} mediaType.`);
4671
+ return endpoint;
4672
+ }
4673
+ function emit(out, line) {
4674
+ if (out.onStderr) {
4675
+ out.onStderr(Buffer.from(`${line}
4676
+ `));
4677
+ } else {
4678
+ process.stderr.write(`${line}
4679
+ `);
4613
4680
  }
4614
- return { mediaType, digest, size };
4615
4681
  }
4616
- async function readRegularJson(path4, label) {
4617
- const stats = await (0, import_promises10.lstat)(path4).catch((error) => {
4618
- if (error.code === "ENOENT") {
4619
- throw new Error(`OCI layout is missing ${label}.`);
4620
- }
4621
- throw error;
4682
+ function runForwarded(cmd, args, out, opts = {}) {
4683
+ return new Promise((resolve5, reject) => {
4684
+ const child = (0, import_node_child_process4.spawn)(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
4685
+ let stdout = "";
4686
+ let stderr = "";
4687
+ child.stdout?.on("data", (chunk) => {
4688
+ stdout += chunk.toString();
4689
+ if (!opts.quiet) {
4690
+ if (out.onStdout) {
4691
+ out.onStdout(chunk);
4692
+ } else {
4693
+ process.stderr.write(chunk.toString());
4694
+ }
4695
+ }
4696
+ });
4697
+ child.stderr?.on("data", (chunk) => {
4698
+ stderr += chunk.toString();
4699
+ if (!opts.quiet) {
4700
+ if (out.onStderr) {
4701
+ out.onStderr(chunk);
4702
+ } else {
4703
+ process.stderr.write(chunk.toString());
4704
+ }
4705
+ }
4706
+ });
4707
+ child.on("error", (err) => {
4708
+ if (err.code === "ENOENT") {
4709
+ reject(
4710
+ new Error(
4711
+ `Command not found: \`${cmd}\`. Ensure \`${cmd}\` is installed and on your PATH (Docker is required for \`vercel dev\` with container services).`
4712
+ )
4713
+ );
4714
+ return;
4715
+ }
4716
+ reject(err);
4717
+ });
4718
+ child.on("close", (code) => {
4719
+ if (code === 0) {
4720
+ resolve5({ stdout });
4721
+ } else {
4722
+ const detail = stderr.trim().split("\n").slice(-5).join("\n");
4723
+ reject(
4724
+ new Error(
4725
+ `\`${cmd} ${args.join(" ")}\` exited with code ${code}` + (detail ? `
4726
+ ${detail}` : "")
4727
+ )
4728
+ );
4729
+ }
4730
+ });
4622
4731
  });
4623
- if (!stats.isFile()) {
4624
- throw new Error(`OCI layout ${label} must be a regular file.`);
4732
+ }
4733
+ var PULL_AUTH_ERROR = /unauthorized|authentication required|no basic auth credentials|pull access denied|denied:|forbidden|\b40[13]\b/i;
4734
+ function prebuiltImagePullError(imageRef, detail) {
4735
+ if (imageRef.startsWith("vcr.vercel.com/") && PULL_AUTH_ERROR.test(detail)) {
4736
+ return new import_build_utils9.NowBuildError({
4737
+ code: "CONTAINER_IMAGE_PULL_UNAUTHORIZED",
4738
+ message: `Couldn't pull ${imageRef} from Vercel Container Registry. Log Docker in with \`vercel vcr login docker\`, check that this project can read the image, and run \`vercel dev\` again.
4739
+
4740
+ ${detail}`
4741
+ });
4625
4742
  }
4743
+ return new import_build_utils9.NowBuildError({
4744
+ code: "CONTAINER_IMAGE_PULL_FAILED",
4745
+ message: `Couldn't pull ${imageRef}.
4746
+
4747
+ ${detail}`
4748
+ });
4749
+ }
4750
+ async function hasLocalImage(imageRef, out) {
4626
4751
  try {
4627
- return JSON.parse(await (0, import_promises10.readFile)(path4, "utf8"));
4752
+ await runForwarded(
4753
+ "docker",
4754
+ ["image", "inspect", "--format", "{{.Id}}", imageRef],
4755
+ out,
4756
+ { quiet: true }
4757
+ );
4758
+ return true;
4628
4759
  } catch {
4629
- throw new Error(`OCI layout ${label} is not valid JSON.`);
4760
+ return false;
4630
4761
  }
4631
4762
  }
4632
- async function readVerifiedBlob(layoutDir, descriptor, label) {
4633
- const path4 = blobPath2(layoutDir, descriptor.digest);
4634
- const stats = await (0, import_promises10.lstat)(path4).catch((error) => {
4635
- if (error.code === "ENOENT") {
4636
- throw new Error(
4637
- `OCI layout is missing ${label} blob ${descriptor.digest}.`
4638
- );
4763
+ async function pullPrebuiltImage(imageRef, out) {
4764
+ emit(out, `\u25B2 container vercel dev: pulling ${imageRef}`);
4765
+ try {
4766
+ await runForwarded("docker", ["pull", imageRef], out);
4767
+ } catch (err) {
4768
+ const error = prebuiltImagePullError(imageRef, err.message);
4769
+ if (!await hasLocalImage(imageRef, out)) {
4770
+ throw error;
4639
4771
  }
4640
- throw error;
4641
- });
4642
- if (!stats.isFile()) {
4643
- throw new Error(
4644
- `OCI layout ${label} blob ${descriptor.digest} must be a regular file.`
4772
+ const reason = error.code === "CONTAINER_IMAGE_PULL_UNAUTHORIZED" ? "the registry refused the pull; run `vercel vcr login docker` to get updates" : "the pull failed";
4773
+ emit(
4774
+ out,
4775
+ `\u25B2 container vercel dev: warning: couldn't pull ${imageRef} (${reason}). Using the local copy, which may be out of date.`
4645
4776
  );
4646
4777
  }
4647
- if (stats.size !== descriptor.size) {
4648
- throw new Error(
4649
- `OCI layout ${label} blob ${descriptor.digest} has size ${stats.size}, expected ${descriptor.size}.`
4778
+ }
4779
+ async function resolveDevImage(options, out, span) {
4780
+ const source = resolveImageSource(options, "dev");
4781
+ if (source.kind === "prebuilt") {
4782
+ await assertDockerAvailable(out);
4783
+ span?.setAttributes({ "container.dev_mode": "prebuilt" });
4784
+ emit(
4785
+ out,
4786
+ `\u25B2 container vercel dev: using prebuilt image ${source.imageRef}`
4650
4787
  );
4788
+ await pullPrebuiltImage(source.imageRef, out);
4789
+ return { image: source.imageRef };
4651
4790
  }
4652
- const content = await (0, import_promises10.readFile)(path4);
4653
- if (content.length !== descriptor.size) {
4791
+ if (source.kind === "buildpack") {
4654
4792
  throw new Error(
4655
- `OCI layout ${label} blob ${descriptor.digest} has size ${content.length}, expected ${descriptor.size}.`
4793
+ `Unexpected buildpack image source in \`vercel dev\` for "${options.workPath}".`
4656
4794
  );
4657
4795
  }
4658
- const actual = sha256Digest(content);
4659
- if (actual !== descriptor.digest) {
4660
- throw new Error(
4661
- `OCI layout ${label} blob ${descriptor.digest} hashes to ${actual}.`
4662
- );
4796
+ const { dockerfilePath } = source;
4797
+ const serviceName = options.service?.name ?? "service";
4798
+ const tag = devImageTag(serviceName);
4799
+ const contextDir = await resolveBuildContext({
4800
+ repoRootPath: options.repoRootPath,
4801
+ workPath: options.workPath,
4802
+ contextDir: options.service ? options.workPath : import_node_path26.default.dirname(dockerfilePath),
4803
+ dockerfilePath
4804
+ });
4805
+ await assertDockerAvailable(out);
4806
+ const buildArgFlags2 = [];
4807
+ const buildEnv = options.meta?.buildEnv ?? {};
4808
+ for (const [key, value] of Object.entries(buildEnv)) {
4809
+ if (typeof value === "string") {
4810
+ buildArgFlags2.push("--build-arg", `${key}=${value}`);
4811
+ }
4663
4812
  }
4664
- return content;
4813
+ const buildTarget = resolveBuildTarget(options.config);
4814
+ span?.setAttributes({ "container.dev_mode": "build", "image.tag": tag });
4815
+ emit(
4816
+ out,
4817
+ `\u25B2 container vercel dev: building ${tag} (docker, host platform${buildTarget ? `, target ${buildTarget}` : ""})`
4818
+ );
4819
+ await runForwarded(
4820
+ "docker",
4821
+ [
4822
+ "build",
4823
+ ...buildArgFlags2,
4824
+ ...buildTargetFlags({ buildTarget }),
4825
+ "-t",
4826
+ tag,
4827
+ "-f",
4828
+ dockerfilePath,
4829
+ contextDir
4830
+ ],
4831
+ out
4832
+ );
4833
+ emit(out, `\u25B2 container built ${tag}`);
4834
+ return { image: tag };
4665
4835
  }
4666
- async function verifyBlobSize(layoutDir, descriptor, label) {
4667
- const path4 = blobPath2(layoutDir, descriptor.digest);
4668
- const stats = await (0, import_promises10.lstat)(path4).catch((error) => {
4669
- if (error.code === "ENOENT") {
4670
- throw new Error(
4671
- `OCI layout is missing ${label} blob ${descriptor.digest}.`
4672
- );
4673
- }
4674
- throw error;
4675
- });
4676
- if (!stats.isFile()) {
4677
- throw new Error(
4678
- `OCI layout ${label} blob ${descriptor.digest} must be a regular file.`
4836
+ async function resolveContainerPort(image, out) {
4837
+ try {
4838
+ const { stdout } = await runForwarded(
4839
+ "docker",
4840
+ [
4841
+ "image",
4842
+ "inspect",
4843
+ "--format",
4844
+ "{{json .Config.ExposedPorts}}",
4845
+ "--",
4846
+ image
4847
+ ],
4848
+ out,
4849
+ { quiet: true }
4679
4850
  );
4851
+ const exposed = JSON.parse(stdout.trim() || "null");
4852
+ if (exposed) {
4853
+ const ports = Object.keys(exposed).map((key) => Number(key.split("/")[0])).filter((n) => Number.isFinite(n)).sort((a, b) => a - b);
4854
+ if (ports.length > 0) {
4855
+ return ports[0];
4856
+ }
4857
+ }
4858
+ } catch (err) {
4859
+ debug(`could not inspect EXPOSE for ${image}: ${err.message}`);
4680
4860
  }
4681
- if (stats.size !== descriptor.size) {
4861
+ return 3e3;
4862
+ }
4863
+ async function readMappedHostPort(containerName, containerPort, out) {
4864
+ const { stdout } = await runForwarded(
4865
+ "docker",
4866
+ ["port", containerName, `${containerPort}/tcp`],
4867
+ out,
4868
+ { quiet: true }
4869
+ );
4870
+ const match = stdout.match(/:(\d+)\s*$/m);
4871
+ if (!match) {
4682
4872
  throw new Error(
4683
- `OCI layout ${label} blob ${descriptor.digest} has size ${stats.size}, expected ${descriptor.size}.`
4873
+ `Could not determine mapped host port for ${containerName} (${containerPort}/tcp). Got: ${stdout.trim()}`
4684
4874
  );
4685
4875
  }
4876
+ return Number(match[1]);
4686
4877
  }
4687
- async function verifyOciLayout(layoutDir) {
4688
- const marker = await readRegularJson(
4689
- (0, import_node_path26.join)(layoutDir, "oci-layout"),
4690
- "oci-layout"
4691
- );
4692
- if (!isRecord(marker) || marker.imageLayoutVersion !== OCI_LAYOUT_VERSION) {
4693
- throw new Error(
4694
- `Unsupported OCI layout version in "${layoutDir}". Expected "${OCI_LAYOUT_VERSION}".`
4878
+ function uniqueContainerName(serviceName) {
4879
+ const safe = serviceName.toLowerCase().replace(/[^a-z0-9-_.]/g, "-");
4880
+ return `vercel-dev-${safe || "service"}-${process.pid}-${Date.now().toString(36)}`;
4881
+ }
4882
+ async function assertDockerAvailable(out) {
4883
+ try {
4884
+ await runForwarded(
4885
+ "docker",
4886
+ ["info", "--format", "{{.ServerVersion}}"],
4887
+ out,
4888
+ {
4889
+ quiet: true
4890
+ }
4695
4891
  );
4696
- }
4697
- const index = await readRegularJson(
4698
- (0, import_node_path26.join)(layoutDir, "index.json"),
4699
- "index.json"
4700
- );
4701
- if (!isRecord(index) || !Array.isArray(index.manifests)) {
4702
- throw new Error("OCI layout index.json has no manifests list.");
4703
- }
4704
- if (index.manifests.length !== 1) {
4892
+ } catch (err) {
4893
+ const message = err.message ?? "";
4894
+ if (/command not found/i.test(message)) {
4895
+ throw new Error(
4896
+ "Docker is required for `vercel dev` with containers, but the `docker` command was not found. Install Docker and ensure it is on your PATH."
4897
+ );
4898
+ }
4705
4899
  throw new Error(
4706
- `OCI layout index.json must contain exactly 1 manifest, found ${index.manifests.length}.`
4900
+ "Could not connect to the Docker daemon. Start Docker (e.g. open Docker Desktop) and run `vercel dev` again."
4707
4901
  );
4708
4902
  }
4709
- const manifestDescriptor = parseDescriptor(index.manifests[0], "manifest");
4710
- if (!manifestDescriptor.mediaType || !SINGLE_MANIFEST_MEDIA_TYPES.has(manifestDescriptor.mediaType)) {
4711
- throw new Error(
4712
- `OCI layout index.json must reference a single image manifest, found mediaType ${JSON.stringify(manifestDescriptor.mediaType)}.`
4713
- );
4903
+ }
4904
+ function containerExitMessage(exitCode, stderr) {
4905
+ const detail = stderr.trim().split("\n").slice(-5).join("\n");
4906
+ const looksLikeDaemonDown = exitCode === 125 || /cannot connect to the docker daemon/i.test(stderr);
4907
+ if (looksLikeDaemonDown) {
4908
+ return "Could not start the container: the Docker daemon is not running or is unreachable. Start Docker (e.g. open Docker Desktop) and try `vercel dev` again." + (detail ? `
4909
+
4910
+ Docker reported:
4911
+ ${detail}` : "");
4714
4912
  }
4715
- const manifestBytes = await readVerifiedBlob(
4716
- layoutDir,
4717
- manifestDescriptor,
4718
- "manifest"
4719
- );
4720
- let manifest;
4721
- try {
4722
- manifest = JSON.parse(manifestBytes.toString("utf8"));
4723
- } catch {
4724
- throw new Error("OCI layout image manifest is not valid JSON.");
4913
+ return `The container exited (code ${exitCode}) before becoming ready.` + (detail ? `
4914
+
4915
+ Docker reported:
4916
+ ${detail}` : "");
4917
+ }
4918
+ var runningContainers = /* @__PURE__ */ new Map();
4919
+ var pendingContainers = /* @__PURE__ */ new Map();
4920
+ function containerReuseKey(options) {
4921
+ return options.service?.name ?? `root:${options.workPath}`;
4922
+ }
4923
+ async function startDevServer(options) {
4924
+ const reuseKey = containerReuseKey(options);
4925
+ const existing = runningContainers.get(reuseKey);
4926
+ if (existing && existing.isRunning()) {
4927
+ return existing.result;
4725
4928
  }
4726
- if (!isRecord(manifest) || !Array.isArray(manifest.layers)) {
4727
- throw new Error("OCI layout image manifest is missing layers.");
4929
+ if (existing) {
4930
+ runningContainers.delete(reuseKey);
4728
4931
  }
4729
- if (manifest.layers.length === 0) {
4730
- throw new Error("OCI layout image manifest has no layers.");
4932
+ const inFlight = pendingContainers.get(reuseKey);
4933
+ if (inFlight) {
4934
+ return inFlight;
4731
4935
  }
4732
- const configDescriptor = parseDescriptor(manifest.config, "config");
4733
- const configBytes = await readVerifiedBlob(
4734
- layoutDir,
4735
- configDescriptor,
4736
- "config"
4936
+ const startPromise = startContainer(options, reuseKey).finally(() => {
4937
+ pendingContainers.delete(reuseKey);
4938
+ });
4939
+ pendingContainers.set(reuseKey, startPromise);
4940
+ return startPromise;
4941
+ }
4942
+ async function startContainer(options, reuseKey) {
4943
+ return withSpan(
4944
+ options.span,
4945
+ "container.dev.start",
4946
+ { "service.name": options.service?.name },
4947
+ async (span) => {
4948
+ const { config, meta, onStdout, onStderr } = options;
4949
+ const out = { onStdout, onStderr };
4950
+ const { image } = await withSpan(
4951
+ span,
4952
+ "container.dev.resolve_image",
4953
+ {},
4954
+ (s) => resolveDevImage(options, out, s)
4955
+ );
4956
+ const containerPort = await resolveContainerPort(image, out);
4957
+ const containerName = uniqueContainerName(
4958
+ options.service?.name ?? "service"
4959
+ );
4960
+ const mergedEnv = {};
4961
+ const metaEnv = meta?.env ?? {};
4962
+ for (const [key, value] of Object.entries(metaEnv)) {
4963
+ if (typeof value === "string" && !isHostOnlyEnvVar(key)) {
4964
+ mergedEnv[key] = value;
4965
+ }
4966
+ }
4967
+ const devResourceEndpoints = meta?.devResourceEndpoints;
4968
+ const runtimeCacheEndpoint = mergedEnv.RUNTIME_CACHE_ENDPOINT;
4969
+ const runtimeCacheProxy = devResourceEndpoints?.runtimeCache;
4970
+ const usesRuntimeCacheProxy = runtimeCacheEndpoint === runtimeCacheProxy?.direct;
4971
+ const containerRuntimeCacheEndpoint = runtimeCacheEndpoint ? useContainerHost(
4972
+ usesRuntimeCacheProxy && runtimeCacheProxy ? runtimeCacheProxy.proxy : runtimeCacheEndpoint
4973
+ ) : void 0;
4974
+ const queueBaseUrl = mergedEnv.VERCEL_QUEUE_BASE_URL;
4975
+ const queueProxy = devResourceEndpoints?.queues;
4976
+ const usesQueueProxy = queueBaseUrl === queueProxy?.direct;
4977
+ const containerQueueBaseUrl = queueBaseUrl ? useContainerHost(
4978
+ usesQueueProxy && queueProxy ? queueProxy.proxy : queueBaseUrl
4979
+ ) : void 0;
4980
+ const needsHostGateway = containerRuntimeCacheEndpoint !== void 0 && containerRuntimeCacheEndpoint !== runtimeCacheEndpoint || containerQueueBaseUrl !== void 0 && containerQueueBaseUrl !== queueBaseUrl;
4981
+ if (containerRuntimeCacheEndpoint) {
4982
+ mergedEnv.RUNTIME_CACHE_ENDPOINT = containerRuntimeCacheEndpoint;
4983
+ }
4984
+ if (containerQueueBaseUrl) {
4985
+ mergedEnv.VERCEL_QUEUE_BASE_URL = containerQueueBaseUrl;
4986
+ }
4987
+ mergedEnv.PORT = String(containerPort);
4988
+ const envFilePath = writeEnvFile(mergedEnv);
4989
+ const rawCommand = config.command;
4990
+ const command = normalizeCommand(rawCommand);
4991
+ const requestedHostPort = typeof meta?.port === "number" ? meta.port : 0;
4992
+ const args = [
4993
+ "run",
4994
+ "--rm",
4995
+ "--name",
4996
+ containerName,
4997
+ // Publish the container port to the orchestrator-provided host port, or
4998
+ // an ephemeral host port chosen by Docker when none was requested.
4999
+ "-p",
5000
+ `127.0.0.1:${requestedHostPort}:${containerPort}`,
5001
+ ...needsHostGateway ? ["--add-host", "host.docker.internal:host-gateway"] : [],
5002
+ "--env-file",
5003
+ envFilePath,
5004
+ "--",
5005
+ image,
5006
+ ...command ?? []
5007
+ ];
5008
+ emit(out, `\u25B2 container vercel dev: starting container ${image}`);
5009
+ debug(`docker ${args.join(" ")}`);
5010
+ const child = (0, import_node_child_process4.spawn)("docker", args, {
5011
+ stdio: ["ignore", "pipe", "pipe"]
5012
+ });
5013
+ let runStderr = "";
5014
+ child.stdout?.on("data", (data) => onStdout?.(data));
5015
+ child.stderr?.on("data", (data) => {
5016
+ runStderr += data.toString();
5017
+ onStderr?.(data);
5018
+ });
5019
+ child.on("error", (err) => {
5020
+ if (err.code === "ENOENT") {
5021
+ runStderr += "Command not found: `docker`. Ensure Docker is installed and on your PATH, and that the Docker daemon is running.";
5022
+ }
5023
+ });
5024
+ const cleanupEnvFile = () => {
5025
+ (0, import_node_fs16.rmSync)(import_node_path26.default.dirname(envFilePath), { recursive: true, force: true });
5026
+ };
5027
+ const shutdown = async () => {
5028
+ runningContainers.delete(reuseKey);
5029
+ try {
5030
+ await runForwarded("docker", ["stop", containerName], out, {
5031
+ quiet: true
5032
+ });
5033
+ } catch (err) {
5034
+ debug(
5035
+ `docker stop ${containerName} failed: ${err.message}`
5036
+ );
5037
+ } finally {
5038
+ cleanupEnvFile();
5039
+ }
5040
+ };
5041
+ let hostPort;
5042
+ const deadline = Date.now() + 3e4;
5043
+ let lastErr;
5044
+ try {
5045
+ while (Date.now() < deadline) {
5046
+ if (child.exitCode !== null) {
5047
+ throw new Error(containerExitMessage(child.exitCode, runStderr));
5048
+ }
5049
+ try {
5050
+ hostPort = await readMappedHostPort(
5051
+ containerName,
5052
+ containerPort,
5053
+ out
5054
+ );
5055
+ break;
5056
+ } catch (err) {
5057
+ lastErr = err;
5058
+ await new Promise((resolve5) => setTimeout(resolve5, 250));
5059
+ }
5060
+ }
5061
+ if (hostPort === void 0) {
5062
+ throw new Error(
5063
+ `Timed out waiting for container "${containerName}" to publish port ${containerPort}.` + (lastErr ? ` Last error: ${lastErr.message}` : "")
5064
+ );
5065
+ }
5066
+ } catch (err) {
5067
+ await shutdown();
5068
+ throw err;
5069
+ }
5070
+ span?.setAttributes({
5071
+ "container.dev.host_port": String(hostPort),
5072
+ "container.dev.container_port": String(containerPort),
5073
+ "container.name": containerName
5074
+ });
5075
+ emit(out, `\u25B2 container container ready on localhost:${hostPort}`);
5076
+ const result = {
5077
+ port: hostPort,
5078
+ pid: child.pid ?? 0,
5079
+ shutdown,
5080
+ // The container is a long-running server; the dev server should keep it
5081
+ // alive across requests instead of tearing it down after each response.
5082
+ persistent: true
5083
+ };
5084
+ const running = {
5085
+ result,
5086
+ containerName,
5087
+ isRunning: () => child.exitCode === null
5088
+ };
5089
+ child.on("close", () => {
5090
+ if (runningContainers.get(reuseKey) === running) {
5091
+ runningContainers.delete(reuseKey);
5092
+ }
5093
+ });
5094
+ runningContainers.set(reuseKey, running);
5095
+ return result;
5096
+ }
4737
5097
  );
4738
- let config;
4739
- try {
4740
- config = JSON.parse(configBytes.toString("utf8"));
4741
- } catch {
4742
- throw new Error("OCI layout image config is not valid JSON.");
5098
+ }
5099
+
5100
+ // src/prepare-cache.ts
5101
+ var import_build_utils10 = require("@vercel/build-utils");
5102
+ var import_node_path27 = require("path");
5103
+ async function prepareCache(options) {
5104
+ const root = (0, import_node_path27.resolve)(options.repoRootPath || options.workPath);
5105
+ const buildpackFiles = await collectBuildpackCache(root);
5106
+ const buildahStoreFiles = await BuildahStoreCache.forProject(
5107
+ options,
5108
+ new BuildahClient(sharedBuildahStoreLock)
5109
+ ).afterBuilds();
5110
+ return { ...buildpackFiles, ...buildahStoreFiles };
5111
+ }
5112
+ async function collectBuildpackCache(root) {
5113
+ const start = Date.now();
5114
+ const files = await (0, import_build_utils10.glob)(`${BUILDPACK_CACHE_DIR}/**`, root);
5115
+ const count = Object.keys(files).length;
5116
+ if (count > 0) {
5117
+ info(
5118
+ `cached ${count} file${count === 1 ? "" : "s"} under ${BUILDPACK_CACHE_DIR} in ${Date.now() - start}ms`
5119
+ );
5120
+ } else {
5121
+ debug(`no cache to persist under ${BUILDPACK_CACHE_DIR}`);
4743
5122
  }
4744
- if (!isRecord(config) || config.os !== "linux" || config.architecture !== "amd64") {
5123
+ return files;
5124
+ }
5125
+
5126
+ // src/executable-image/index.ts
5127
+ var import_node_crypto11 = require("crypto");
5128
+ var import_promises13 = require("fs/promises");
5129
+ var import_node_path29 = require("path");
5130
+
5131
+ // src/buildpacks/lifecycle/native.ts
5132
+ var import_node_fs17 = require("fs");
5133
+ var import_promises12 = require("fs/promises");
5134
+ var import_node_path28 = require("path");
5135
+ var import_smol_toml4 = require("smol-toml");
5136
+ var PREBUILT_STATIC_GROUP = {
5137
+ runtime: "prebuilt-static",
5138
+ buildpacks: [vercelBuildpack("prebuilt-static")]
5139
+ };
5140
+ var HIVE_RUNTIME_MOUNTS = ["/tmp", "/opt/vercel"];
5141
+ function assertLinuxX64(platform = process.platform, arch = process.arch) {
5142
+ if (platform !== "linux" || arch !== "x64") {
4745
5143
  throw new Error(
4746
- `OCI layout image must target linux/amd64, found ${JSON.stringify(
4747
- isRecord(config) ? `${config.os}/${config.architecture}` : config
4748
- )}.`
5144
+ `Executable image builds require Linux x64 (current platform: ${platform}/${arch}).`
4749
5145
  );
4750
5146
  }
4751
- for (let i = 0; i < manifest.layers.length; i++) {
4752
- const layerDescriptor = parseDescriptor(manifest.layers[i], `layer[${i}]`);
4753
- await verifyBlobSize(layoutDir, layerDescriptor, `layer[${i}]`);
4754
- }
4755
- return { manifestDigest: manifestDescriptor.digest };
4756
5147
  }
4757
- async function moveDirectory(sourceDir, destinationDir) {
4758
- const parentDir = (0, import_node_path26.dirname)(destinationDir);
4759
- await (0, import_promises10.mkdir)(parentDir, { recursive: true });
4760
- try {
4761
- await (0, import_promises10.rename)(sourceDir, destinationDir);
4762
- return;
4763
- } catch (error) {
4764
- if (error.code !== "EXDEV") {
4765
- throw error;
4766
- }
5148
+ async function resolveNativeBuildUser(deps = {}) {
5149
+ const uid = (deps.getuid ?? process.getuid)?.();
5150
+ const gid = (deps.getgid ?? process.getgid)?.();
5151
+ if (uid === void 0 || gid === void 0) {
5152
+ throw new Error("The native CNB lifecycle requires Unix user IDs.");
4767
5153
  }
4768
- const tempDir = await (0, import_promises10.mkdtemp)((0, import_node_path26.join)(parentDir, ".oci-layout-"));
4769
- try {
4770
- await (0, import_promises10.cp)(sourceDir, tempDir, { recursive: true });
4771
- await (0, import_promises10.rename)(tempDir, destinationDir);
4772
- } catch (error) {
4773
- await (0, import_promises10.rm)(tempDir, { recursive: true, force: true });
4774
- throw error;
5154
+ if (uid !== 0 && gid !== 0) {
5155
+ return { uid, gid, switchUser: false };
4775
5156
  }
4776
- await (0, import_promises10.rm)(sourceDir, { recursive: true, force: true });
4777
- }
4778
-
4779
- // src/oci-layout/pull.ts
4780
- var import_node_crypto10 = require("crypto");
4781
- var import_promises11 = require("fs/promises");
4782
- var import_node_path27 = require("path");
4783
- var MANIFEST_ACCEPT_HEADER = [
4784
- OCI_MANIFEST_MEDIA_TYPE,
4785
- DOCKER_MANIFEST_MEDIA_TYPE,
4786
- OCI_INDEX_MEDIA_TYPE,
4787
- "application/vnd.docker.distribution.manifest.list.v2+json"
4788
- ].join(", ");
4789
- var PULL_ATTEMPTS = 3;
4790
- var PULL_TIMEOUT_MS = 3e4;
4791
- var MAX_REDIRECTS = 5;
4792
- function parseDigestImageRef(imageRef) {
4793
- const atIndex = imageRef.indexOf("@");
4794
- if (atIndex === -1) {
4795
- throw new Error(
4796
- `Expected a digest-pinned image reference, got "${imageRef}".`
4797
- );
5157
+ if (uid !== 0) {
5158
+ throw new Error("The native CNB lifecycle cannot run with the root group.");
4798
5159
  }
4799
- const namePart = imageRef.slice(0, atIndex);
4800
- const digest = imageRef.slice(atIndex + 1);
4801
- if (!DIGEST_RE.test(digest)) {
5160
+ const passwd = await (deps.readPasswd ?? (() => (0, import_promises12.readFile)("/etc/passwd", "utf8")))();
5161
+ const nobody = passwd.split("\n").map((line) => line.split(":")).find(([name]) => name === "nobody");
5162
+ const unprivilegedUid = Number(nobody?.[2]);
5163
+ const unprivilegedGid = Number(nobody?.[3]);
5164
+ if (!Number.isInteger(unprivilegedUid) || !Number.isInteger(unprivilegedGid) || unprivilegedUid <= 0 || unprivilegedGid <= 0) {
4802
5165
  throw new Error(
4803
- `Expected a sha256 digest in image reference "${imageRef}".`
5166
+ "The native CNB lifecycle requires a non-root nobody account."
4804
5167
  );
4805
5168
  }
4806
- const firstSlash = namePart.indexOf("/");
4807
- if (firstSlash <= 0 || firstSlash === namePart.length - 1) {
5169
+ return { uid: unprivilegedUid, gid: unprivilegedGid, switchUser: true };
5170
+ }
5171
+ async function resolveStagingParent(resolveRealpath = import_promises12.realpath) {
5172
+ const parent = await resolveRealpath("/var/tmp");
5173
+ if (HIVE_RUNTIME_MOUNTS.some(
5174
+ (mount) => parent === mount || parent.startsWith(`${mount}/`)
5175
+ )) {
4808
5176
  throw new Error(
4809
- `Expected "<registry>/<repository>@sha256:..." image reference, got "${imageRef}".`
5177
+ `Cannot stage the native CNB image in ${parent}: Hive mounts over that path at runtime.`
4810
5178
  );
4811
5179
  }
4812
- const registry = namePart.slice(0, firstSlash);
4813
- const repository = namePart.slice(firstSlash + 1);
4814
- if (repository.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
4815
- throw new Error(`Invalid repository in image reference "${imageRef}".`);
5180
+ return parent;
5181
+ }
5182
+ async function chownRecursive(rootPath, uid, gid) {
5183
+ const stats = await (0, import_promises12.lstat)(rootPath);
5184
+ if (stats.isDirectory()) {
5185
+ for (const entry of await (0, import_promises12.readdir)(rootPath)) {
5186
+ await chownRecursive((0, import_node_path28.join)(rootPath, entry), uid, gid);
5187
+ }
4816
5188
  }
4817
- return { registry, repository, digest };
5189
+ await (0, import_promises12.lchown)(rootPath, uid, gid);
4818
5190
  }
4819
- function describeFetchError2(error) {
4820
- const err = error;
4821
- const cause = err.cause?.message;
4822
- return cause ? `${err.message} (${cause})` : err.message;
5191
+ async function verifyLaunchCommand(layersDir, executablePath) {
5192
+ const metadata = (0, import_smol_toml4.parse)(
5193
+ await (0, import_promises12.readFile)((0, import_node_path28.join)(layersDir, "config", "metadata.toml"), "utf8")
5194
+ );
5195
+ const valid = metadata.processes?.some(
5196
+ (proc) => proc.type === "web" && proc.direct === true && proc.command?.length === 1 && (proc.command[0] === executablePath || proc.command[0] === "./user-server")
5197
+ );
5198
+ if (!valid) {
5199
+ throw new Error(
5200
+ "The prebuilt-static buildpack did not declare the staged user-server as its direct web process."
5201
+ );
5202
+ }
4823
5203
  }
4824
- var OciRegistryPuller = class {
5204
+ var NativeLifecycleRunner = class {
4825
5205
  constructor(options) {
4826
5206
  this.options = options;
4827
- this.fetchImpl = options.fetchImpl ?? fetch;
4828
- this.retryDelayMs = options.retryDelayMs ?? 500;
4829
- }
4830
- async pullToLayout(imageRef, destinationDir) {
4831
- const parsed = parseDigestImageRef(imageRef);
4832
- if (parsed.registry !== this.options.credentials.registry) {
4833
- throw new Error(
4834
- `Registry credentials for ${this.options.credentials.registry} cannot be used to pull from ${parsed.registry}.`
4835
- );
4836
- }
4837
- const baseUrl = (this.options.baseUrl ?? `https://${parsed.registry}`).replace(/\/+$/, "");
4838
- const baseOrigin = new URL(baseUrl).origin;
4839
- const requireHttps = new URL(baseUrl).protocol === "https:";
4840
- const authorization = `Basic ${Buffer.from(
4841
- `${this.options.credentials.username}:${this.options.credentials.token}`
4842
- ).toString("base64")}`;
4843
- const manifestUrl = `${baseUrl}/v2/${parsed.repository}/manifests/${parsed.digest}`;
4844
- const manifestBytes = await this.fetchBytes({
4845
- url: manifestUrl,
4846
- baseOrigin,
4847
- requireHttps,
4848
- authorization,
4849
- accept: MANIFEST_ACCEPT_HEADER,
4850
- registry: parsed.registry,
4851
- label: `manifest ${imageRef}`
4852
- });
4853
- const actualManifestDigest = sha256Digest(manifestBytes);
4854
- if (actualManifestDigest !== parsed.digest) {
4855
- throw new Error(
4856
- `Manifest digest mismatch for ${imageRef}: expected ${parsed.digest}, received ${actualManifestDigest}.`
4857
- );
4858
- }
4859
- let manifest;
4860
- try {
4861
- manifest = JSON.parse(new TextDecoder().decode(manifestBytes));
4862
- } catch {
4863
- throw new Error(`Manifest for ${imageRef} is not valid JSON.`);
4864
- }
4865
- if (!isRecord(manifest)) {
4866
- throw new Error(`Manifest for ${imageRef} must be a JSON object.`);
4867
- }
4868
- if (Array.isArray(manifest.manifests) && (!manifest.config || !Array.isArray(manifest.layers))) {
4869
- throw new Error(
4870
- `Expected ${imageRef} to resolve to a single linux/amd64 image manifest, not an image index.`
4871
- );
4872
- }
4873
- if (!Array.isArray(manifest.layers) || manifest.layers.length === 0) {
4874
- throw new Error(`Manifest for ${imageRef} has no layers.`);
4875
- }
4876
- const configDescriptor = parseDescriptor(manifest.config, "config");
4877
- const layerDescriptors = manifest.layers.map(
4878
- (layer, index) => parseDescriptor(layer, `layer[${index}]`)
4879
- );
4880
- const blobsDir = (0, import_node_path27.join)(destinationDir, "blobs", "sha256");
4881
- await (0, import_promises11.mkdir)(blobsDir, { recursive: true, mode: 493 });
4882
- try {
4883
- await (0, import_promises11.writeFile)(
4884
- (0, import_node_path27.join)(blobsDir, parseSha256Hex(parsed.digest)),
4885
- manifestBytes
4886
- );
4887
- const fetchBlob = async (descriptor, label) => {
4888
- const written = await this.fetchToFile(
4889
- {
4890
- url: `${baseUrl}/v2/${parsed.repository}/blobs/${descriptor.digest}`,
4891
- baseOrigin,
4892
- requireHttps,
4893
- authorization,
4894
- registry: parsed.registry,
4895
- label: `${label} ${descriptor.digest}`
4896
- },
4897
- blobPath2(destinationDir, descriptor.digest)
4898
- );
4899
- if (written.size !== descriptor.size) {
4900
- throw new Error(
4901
- `Blob size mismatch for ${label} ${descriptor.digest}: expected ${descriptor.size}, received ${written.size}.`
4902
- );
4903
- }
4904
- if (written.digest !== descriptor.digest) {
4905
- throw new Error(
4906
- `Blob digest mismatch for ${label} ${descriptor.digest}: received ${written.digest}.`
4907
- );
4908
- }
4909
- };
4910
- const uniqueLayers = /* @__PURE__ */ new Map();
4911
- for (const layer of layerDescriptors) {
4912
- if (!uniqueLayers.has(layer.digest)) {
4913
- uniqueLayers.set(layer.digest, layer);
4914
- }
4915
- }
4916
- await settleAll([
4917
- fetchBlob(configDescriptor, "config"),
4918
- ...[...uniqueLayers.values()].map(
4919
- (layer, index) => fetchBlob(layer, `layer[${index}]`)
4920
- )
4921
- ]);
4922
- let config;
4923
- try {
4924
- config = JSON.parse(
4925
- await (0, import_promises11.readFile)(
4926
- blobPath2(destinationDir, configDescriptor.digest),
4927
- "utf8"
4928
- )
4929
- );
4930
- } catch {
4931
- throw new Error(`Config blob for ${imageRef} is not valid JSON.`);
4932
- }
4933
- if (!isRecord(config) || config.os !== "linux" || config.architecture !== "amd64") {
4934
- throw new Error(
4935
- `Run image ${imageRef} must target linux/amd64, found ${JSON.stringify(
4936
- isRecord(config) ? `${config.os}/${config.architecture}` : config
4937
- )}.`
4938
- );
4939
- }
4940
- const manifestMediaType = typeof manifest.mediaType === "string" ? manifest.mediaType : OCI_MANIFEST_MEDIA_TYPE;
4941
- await (0, import_promises11.writeFile)(
4942
- (0, import_node_path27.join)(destinationDir, "oci-layout"),
4943
- JSON.stringify({ imageLayoutVersion: OCI_LAYOUT_VERSION })
4944
- );
4945
- await (0, import_promises11.writeFile)(
4946
- (0, import_node_path27.join)(destinationDir, "index.json"),
4947
- JSON.stringify({
4948
- schemaVersion: 2,
4949
- mediaType: OCI_INDEX_MEDIA_TYPE,
4950
- manifests: [
4951
- {
4952
- mediaType: manifestMediaType,
4953
- digest: parsed.digest,
4954
- size: manifestBytes.byteLength
4955
- }
4956
- ]
4957
- })
4958
- );
4959
- return { manifestDigest: parsed.digest };
4960
- } catch (error) {
4961
- await (0, import_promises11.rm)(destinationDir, { recursive: true, force: true });
4962
- throw error;
4963
- }
4964
- }
4965
- fetchBytes(request) {
4966
- return this.fetchWithRetries(
4967
- request,
4968
- async (response) => new Uint8Array(await response.arrayBuffer())
4969
- );
5207
+ this.runCommand = options.runCommand ?? run;
4970
5208
  }
4971
- /** Streams a blob into `path`, hashing it on the way, and returns its size and digest. */
4972
- fetchToFile(request, path4) {
4973
- return this.fetchWithRetries(request, async (response) => {
4974
- const hash = (0, import_node_crypto10.createHash)("sha256");
4975
- let size = 0;
4976
- const file = await (0, import_promises11.open)(path4, "w");
4977
- try {
4978
- if (response.body) {
4979
- for await (const chunk of response.body) {
4980
- hash.update(chunk);
4981
- size += chunk.byteLength;
4982
- await file.write(chunk);
4983
- }
4984
- }
4985
- } finally {
4986
- await file.close();
4987
- }
4988
- return { size, digest: `sha256:${hash.digest("hex")}` };
4989
- });
5209
+ async runPush(params) {
5210
+ return this.execute(
5211
+ params.executablePath,
5212
+ {
5213
+ kind: "registry",
5214
+ imageRef: params.imageRef,
5215
+ credentials: params.credentials
5216
+ },
5217
+ async (reportFile) => {
5218
+ const digest = readReportDigest(await (0, import_promises12.readFile)(reportFile, "utf8"));
5219
+ if (!digest) {
5220
+ throw new Error("The CNB lifecycle did not report an image digest.");
5221
+ }
5222
+ return digest;
5223
+ },
5224
+ params.span
5225
+ );
5226
+ }
5227
+ async runLayout(params) {
5228
+ await this.execute(
5229
+ params.executablePath,
5230
+ {
5231
+ kind: "oci-layout",
5232
+ imageRef: params.outputImageRef,
5233
+ layoutDir: params.layoutRoot
5234
+ },
5235
+ async () => void 0,
5236
+ params.span
5237
+ );
4990
5238
  }
4991
5239
  /**
4992
- * GETs `request.url`, retrying network errors, 429 and 5xx responses.
4993
- * `readBody` runs inside the retry, so a connection that drops while the
4994
- * body streams is retried like one that drops before the headers arrive.
5240
+ * Runs the creator, then `readResult` while the creator's report still
5241
+ * exists, so a failure in either is reported as a lifecycle failure.
4995
5242
  */
4996
- async fetchWithRetries(request, readBody) {
4997
- let lastError = `Failed to pull ${request.label}.`;
4998
- for (let attempt = 1; attempt <= PULL_ATTEMPTS; attempt++) {
4999
- debug(`registry pull (${attempt}/${PULL_ATTEMPTS}): GET ${request.url}`);
5000
- try {
5001
- const response = await this.fetchFollowingRedirects(
5002
- request.url,
5003
- request.baseOrigin,
5004
- request.requireHttps,
5005
- request.authorization,
5006
- request.accept
5007
- );
5008
- if (response.ok) {
5009
- return await readBody(response);
5010
- }
5011
- if (response.status === 401 || response.status === 403) {
5012
- throw new NonRetryablePullError(
5013
- request.registry === VCR_REGISTRY ? formatVcrAuthError(
5014
- request.registry,
5015
- this.options.credentials.username,
5016
- `HTTP ${response.status} pulling ${request.label}.`
5017
- ) : `Registry authentication failed pulling ${request.label}: HTTP ${response.status}.`
5018
- );
5019
- }
5020
- lastError = `Failed to pull ${request.label}: HTTP ${response.status}.`;
5021
- if (response.status !== 429 && response.status < 500) {
5022
- throw new NonRetryablePullError(lastError);
5023
- }
5024
- } catch (error) {
5025
- if (error instanceof NonRetryablePullError) {
5026
- throw error;
5027
- }
5028
- lastError = `Failed to pull ${request.label}: ${describeFetchError2(error)}`;
5029
- }
5030
- if (attempt < PULL_ATTEMPTS) {
5031
- await delay(this.retryDelayMs * 2 ** (attempt - 1));
5032
- }
5243
+ async execute(executablePath, target, readResult, span) {
5244
+ const executableStats = await (0, import_promises12.lstat)(executablePath);
5245
+ if (!executableStats.isFile() || executableStats.size === 0) {
5246
+ throw new Error(
5247
+ "The prebuilt executable must be a nonempty regular file."
5248
+ );
5033
5249
  }
5034
- throw new Error(lastError);
5035
- }
5036
- async fetchFollowingRedirects(initialUrl, baseOrigin, requireHttps, authorization, accept) {
5037
- let currentUrl = new URL(initialUrl);
5038
- for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects++) {
5039
- const headers = {};
5040
- if (currentUrl.origin === baseOrigin) {
5041
- headers.authorization = authorization;
5042
- }
5043
- if (accept) {
5044
- headers.accept = accept;
5250
+ const { user, stagingParent, cnbDir, platformDir, orderFile, runImage } = this.options;
5251
+ const runRoot = await (0, import_promises12.mkdtemp)((0, import_node_path28.join)(stagingParent, "vercel-cnb-native-"));
5252
+ try {
5253
+ if (user.switchUser) {
5254
+ await (0, import_promises12.chmod)(runRoot, 493);
5045
5255
  }
5046
- const response = await this.fetchImpl(currentUrl.href, {
5047
- method: "GET",
5048
- headers,
5049
- redirect: "manual",
5050
- signal: AbortSignal.timeout(PULL_TIMEOUT_MS)
5051
- });
5052
- if (response.status < 300 || response.status >= 400) {
5053
- return response;
5256
+ const workPath = (0, import_node_path28.join)(runRoot, "workspace");
5257
+ const layers = (0, import_node_path28.join)(runRoot, "layers");
5258
+ const reportDir = (0, import_node_path28.join)(runRoot, "report");
5259
+ const home = (0, import_node_path28.join)(runRoot, "home");
5260
+ const temp = (0, import_node_path28.join)(runRoot, "tmp");
5261
+ const dirs = [workPath, layers, reportDir, home, temp];
5262
+ for (const dir of dirs) {
5263
+ await (0, import_promises12.mkdir)(dir, { mode: 448 });
5054
5264
  }
5055
- const location = response.headers.get("location");
5056
- if (!location) {
5057
- return response;
5265
+ const executable = (0, import_node_path28.join)(workPath, "user-server");
5266
+ await (0, import_promises12.copyFile)(executablePath, executable, import_node_fs17.constants.COPYFILE_EXCL);
5267
+ const handle = await (0, import_promises12.open)(
5268
+ executable,
5269
+ import_node_fs17.constants.O_RDONLY | import_node_fs17.constants.O_NOFOLLOW
5270
+ );
5271
+ try {
5272
+ await handle.chmod(493);
5273
+ if (user.switchUser) {
5274
+ await handle.chown(user.uid, user.gid);
5275
+ }
5276
+ } finally {
5277
+ await handle.close();
5058
5278
  }
5059
- if (redirects === MAX_REDIRECTS) {
5060
- throw new NonRetryablePullError(
5061
- `Too many redirects pulling ${initialUrl}.`
5062
- );
5279
+ if (user.switchUser) {
5280
+ for (const dir of dirs) {
5281
+ await (0, import_promises12.chown)(dir, user.uid, user.gid);
5282
+ }
5063
5283
  }
5064
- const nextUrl = new URL(location, currentUrl);
5065
- if (requireHttps && nextUrl.protocol !== "https:") {
5066
- throw new NonRetryablePullError(
5067
- `Refusing insecure redirect to ${nextUrl.protocol} while pulling from HTTPS registry.`
5068
- );
5284
+ const lifecycleDir = (0, import_node_path28.join)(cnbDir, "lifecycle");
5285
+ const reportFile = (0, import_node_path28.join)(reportDir, "report.toml");
5286
+ const { args: exportArgs, env: exportEnv } = creatorExport(target);
5287
+ const args = [
5288
+ `-app=${workPath}`,
5289
+ `-layers=${layers}`,
5290
+ `-buildpacks=${(0, import_node_path28.join)(cnbDir, "buildpacks")}`,
5291
+ `-platform=${platformDir}`,
5292
+ `-order=${orderFile}`,
5293
+ `-launcher=${(0, import_node_path28.join)(lifecycleDir, "launcher")}`,
5294
+ `-launcher-sbom=${lifecycleDir}`,
5295
+ `-uid=${user.uid}`,
5296
+ `-gid=${user.gid}`,
5297
+ `-run-image=${runImage}`,
5298
+ `-report=${reportFile}`,
5299
+ "-skip-restore",
5300
+ ...exportArgs
5301
+ ];
5302
+ const env = {
5303
+ PATH: "/usr/bin:/bin",
5304
+ HOME: home,
5305
+ TMPDIR: temp,
5306
+ ...target.kind === "registry" && { DOCKER_CONFIG: home },
5307
+ CNB_PLATFORM_API,
5308
+ ...exportEnv
5309
+ };
5310
+ try {
5311
+ await this.runCommand((0, import_node_path28.join)(lifecycleDir, "creator"), args, {
5312
+ cwd: workPath,
5313
+ ...user.switchUser && { uid: user.uid, gid: user.gid },
5314
+ env
5315
+ });
5316
+ await verifyLaunchCommand(layers, executable);
5317
+ return await readResult(reportFile);
5318
+ } catch (error) {
5319
+ throw lifecycleFailure(error, {
5320
+ buildpack: this.options.buildpack,
5321
+ via: "native lifecycle",
5322
+ workPath,
5323
+ span
5324
+ });
5069
5325
  }
5070
- currentUrl = nextUrl;
5326
+ } finally {
5327
+ await (0, import_promises12.rm)(runRoot, { recursive: true, force: true });
5071
5328
  }
5072
- throw new NonRetryablePullError(
5073
- `Too many redirects pulling ${initialUrl}.`
5074
- );
5075
5329
  }
5076
5330
  };
5077
- var NonRetryablePullError = class extends Error {
5078
- };
5079
-
5080
- // src/oci-layout/index.ts
5081
- var CONTAINER_OCI_LAYOUT_ENV = "VERCEL_CONTAINER_OCI_LAYOUT";
5082
- function ociLayoutRequested(env = process.env) {
5083
- return env[CONTAINER_OCI_LAYOUT_ENV] === "1";
5084
- }
5085
5331
 
5086
5332
  // src/executable-image/index.ts
5087
5333
  var ExecutableImageBuilder = class _ExecutableImageBuilder {
@@ -5104,22 +5350,22 @@ var ExecutableImageBuilder = class _ExecutableImageBuilder {
5104
5350
  const fetchDist = deps.fetchDistribution ?? fetchDistribution;
5105
5351
  const resolveTarget = deps.resolveRegistryTarget ?? resolveRegistryTarget;
5106
5352
  const ensureRepo = deps.ensureRepository ?? ensureRepository;
5107
- const sharedRoot = await (0, import_promises12.mkdtemp)(
5108
- (0, import_node_path28.join)(stagingParent, "vercel-cnb-executable-")
5353
+ const sharedRoot = await (0, import_promises13.mkdtemp)(
5354
+ (0, import_node_path29.join)(stagingParent, "vercel-cnb-executable-")
5109
5355
  );
5110
5356
  try {
5111
5357
  if (user.switchUser) {
5112
- await (0, import_promises12.chmod)(sharedRoot, 493);
5358
+ await (0, import_promises13.chmod)(sharedRoot, 493);
5113
5359
  }
5114
- const cnbDir = (0, import_node_path28.join)(sharedRoot, "cnb");
5115
- const platformDir = (0, import_node_path28.join)(sharedRoot, "platform");
5116
- await (0, import_promises12.mkdir)(cnbDir, { mode: 493 });
5117
- await (0, import_promises12.mkdir)(platformDir, { mode: 493 });
5360
+ const cnbDir = (0, import_node_path29.join)(sharedRoot, "cnb");
5361
+ const platformDir = (0, import_node_path29.join)(sharedRoot, "platform");
5362
+ await (0, import_promises13.mkdir)(cnbDir, { mode: 493 });
5363
+ await (0, import_promises13.mkdir)(platformDir, { mode: 493 });
5118
5364
  if (user.switchUser) {
5119
- await (0, import_promises12.chmod)(cnbDir, 493);
5120
- await (0, import_promises12.chmod)(platformDir, 493);
5365
+ await (0, import_promises13.chmod)(cnbDir, 493);
5366
+ await (0, import_promises13.chmod)(platformDir, 493);
5121
5367
  }
5122
- const orderFile = (0, import_node_path28.join)(
5368
+ const orderFile = (0, import_node_path29.join)(
5123
5369
  writeOrderDir(PREBUILT_STATIC_GROUP, sharedRoot),
5124
5370
  "order.toml"
5125
5371
  );
@@ -5139,8 +5385,8 @@ var ExecutableImageBuilder = class _ExecutableImageBuilder {
5139
5385
  runCommand: deps.runCommand
5140
5386
  });
5141
5387
  if (layoutMode) {
5142
- const layoutRoot = (0, import_node_path28.join)(sharedRoot, "layout");
5143
- await (0, import_promises12.mkdir)(layoutRoot, { mode: 448 });
5388
+ const layoutRoot = (0, import_node_path29.join)(sharedRoot, "layout");
5389
+ await (0, import_promises13.mkdir)(layoutRoot, { mode: 448 });
5144
5390
  const runImageLayoutDir = layoutRefPath(layoutRoot, runImage);
5145
5391
  const puller = new OciRegistryPuller({
5146
5392
  credentials: {
@@ -5191,7 +5437,7 @@ var ExecutableImageBuilder = class _ExecutableImageBuilder {
5191
5437
  options.span
5192
5438
  );
5193
5439
  } catch (error) {
5194
- await (0, import_promises12.rm)(sharedRoot, { recursive: true, force: true });
5440
+ await (0, import_promises13.rm)(sharedRoot, { recursive: true, force: true });
5195
5441
  throw error;
5196
5442
  }
5197
5443
  }
@@ -5217,7 +5463,7 @@ var ExecutableImageBuilder = class _ExecutableImageBuilder {
5217
5463
  if (this.closed)
5218
5464
  return;
5219
5465
  this.closed = true;
5220
- await (0, import_promises12.rm)(this.sharedRoot, { recursive: true, force: true });
5466
+ await (0, import_promises13.rm)(this.sharedRoot, { recursive: true, force: true });
5221
5467
  }
5222
5468
  async exportLayout(mode, tag, executable, span) {
5223
5469
  const outputImageRef = `oci.local/executable:${tag}`;
@@ -5240,7 +5486,7 @@ var ExecutableImageBuilder = class _ExecutableImageBuilder {
5240
5486
  manifestDigest
5241
5487
  };
5242
5488
  } finally {
5243
- await (0, import_promises12.rm)(exportedDir, { recursive: true, force: true });
5489
+ await (0, import_promises13.rm)(exportedDir, { recursive: true, force: true });
5244
5490
  }
5245
5491
  }
5246
5492
  async push(mode, tag, executable, span) {
@@ -5288,164 +5534,122 @@ function resolveImageTag() {
5288
5534
  }
5289
5535
  return `build-${Date.now().toString(36)}`;
5290
5536
  }
5291
- async function authenticateRegistry(engine, buildParams, span) {
5292
- const forceLogin = readString(process.env.VERCEL_VCR_FORCE_LOGIN) === "1";
5293
- const authFile = forceLogin ? void 0 : existingRegistryAuthFile();
5294
- if (authFile) {
5295
- debug(`registry auth file present: ${authFile}`);
5296
- step(`Using registry credentials from ${authFile}`);
5297
- span?.setAttributes({
5298
- "container.registry": VCR_REGISTRY,
5299
- "registry.username": buildParams.username,
5300
- "registry.auth_file": authFile,
5301
- "registry.login_skipped": toTag(true)
5302
- });
5303
- done("authenticated via provisioned credentials");
5304
- return;
5305
- }
5306
- step(`Authenticating to ${VCR_REGISTRY} as ${buildParams.username}`);
5537
+ async function prepareToolchain(engine, span) {
5307
5538
  await withSpan(
5308
5539
  span,
5309
- "container.registry_login",
5540
+ "container.ensure_toolchain_ready",
5541
+ { "container.engine": engine.name },
5542
+ (s) => engine.ensureReady(s)
5543
+ );
5544
+ await withSpan(
5545
+ span,
5546
+ "container.toolchain_diagnostics",
5547
+ { "container.engine": engine.name },
5548
+ (s) => engine.logDiagnostics(s)
5549
+ );
5550
+ await withSpan(
5551
+ span,
5552
+ "container.verify_storage",
5553
+ { "container.engine": engine.name },
5554
+ (s) => engine.verifyStorage?.(s) ?? Promise.resolve()
5555
+ );
5556
+ }
5557
+ async function buildImage(engine, buildParams, schedulesCommand, span) {
5558
+ const { imageRef, dockerfilePath, contextDir, buildArgs, buildTarget } = buildParams;
5559
+ debug(`dockerfile: ${dockerfilePath}`);
5560
+ debug(`context: ${contextDir}`);
5561
+ debug(`platform: ${TARGET_PLATFORM}`);
5562
+ debug(`target: ${buildTarget ?? "(last stage)"}`);
5563
+ debug(
5564
+ `build args: ${buildArgs ? Object.keys(buildArgs).length : 0} (from project build env)`
5565
+ );
5566
+ const buildStart = Date.now();
5567
+ step(
5568
+ `${engine.name} build (${TARGET_PLATFORM}${buildTarget ? `, target ${buildTarget}` : ""})`
5569
+ );
5570
+ await withSpan(
5571
+ span,
5572
+ "container.image_build",
5310
5573
  {
5311
- "container.registry": VCR_REGISTRY,
5312
- "registry.username": buildParams.username
5574
+ "image.ref": imageRef,
5575
+ "image.platform": TARGET_PLATFORM,
5576
+ "image.build_target": buildTarget
5313
5577
  },
5314
- () => engine.login(buildParams)
5578
+ async () => {
5579
+ if (schedulesCommand) {
5580
+ await buildSchedulesCommandImage(engine, buildParams);
5581
+ } else {
5582
+ await engine.build(buildParams);
5583
+ }
5584
+ }
5585
+ );
5586
+ done(`built in ${elapsed(buildStart)}`);
5587
+ }
5588
+ function reportStorage(engine, span) {
5589
+ return withSpan(
5590
+ span,
5591
+ "container.report_storage",
5592
+ { "container.engine": engine.name },
5593
+ (s) => engine.reportStorage?.(s) ?? Promise.resolve()
5315
5594
  );
5316
- done("authenticated");
5317
5595
  }
5318
- async function buildAndPushImage(params) {
5319
- const {
5320
- contextDir,
5321
- dockerfilePath,
5322
- repository,
5323
- tag,
5324
- buildArgs,
5325
- buildTarget,
5326
- buildahClient,
5327
- parentSpan
5328
- } = params;
5329
- const engine = selectContainerEngine(buildahClient);
5596
+ async function buildAndPublishImage(build2, exportLayout) {
5597
+ const engine = selectContainerEngine(build2.buildahClient);
5598
+ const publisher = createImagePublisher({ build: build2, engine, exportLayout });
5599
+ build2.parentSpan?.setAttributes({ "container.mode": publisher.mode });
5330
5600
  return withSpan(
5331
- parentSpan,
5332
- "container.build_and_push",
5601
+ build2.parentSpan,
5602
+ `container.${publisher.mode}`,
5333
5603
  {
5334
5604
  "container.engine": engine.name,
5335
- "container.registry": VCR_REGISTRY,
5336
- "container.repository": repository
5605
+ "container.repository": build2.repository,
5606
+ ...publisher.spanAttributes
5337
5607
  },
5338
5608
  async (buildSpan) => {
5339
- const target = await resolveRegistryTarget({
5340
- repository,
5341
- tag,
5609
+ const publication = await publisher.resolve(buildSpan);
5610
+ const { imageRef } = publication;
5611
+ const buildParams = {
5612
+ contextDir: build2.contextDir,
5613
+ dockerfilePath: build2.dockerfilePath,
5614
+ imageRef,
5615
+ buildArgs: build2.buildArgs,
5616
+ buildTarget: build2.buildTarget,
5617
+ useBuildahStoreCache: buildahStoreCacheEnabled(),
5342
5618
  span: buildSpan
5343
- });
5344
- const { token, claims, username, fullRepository, imageRef } = target;
5345
- buildSpan?.setAttributes({
5346
- "container.repository": fullRepository,
5347
- "image.tag": tag,
5348
- "image.ref": imageRef,
5349
- "registry.username": username
5350
- });
5619
+ };
5351
5620
  return engine.withRuntime(buildSpan, async () => {
5352
- await withSpan(
5353
- buildSpan,
5354
- "container.ensure_toolchain_ready",
5355
- { "container.engine": engine.name },
5356
- (s) => engine.ensureReady(s)
5357
- );
5358
- await withSpan(
5359
- buildSpan,
5360
- "container.toolchain_diagnostics",
5361
- { "container.engine": engine.name },
5362
- (s) => engine.logDiagnostics(s)
5363
- );
5364
- await withSpan(
5365
- buildSpan,
5366
- "container.verify_storage",
5367
- { "container.engine": engine.name },
5368
- (s) => engine.verifyStorage?.(s) ?? Promise.resolve()
5369
- );
5370
- const buildParams = {
5371
- contextDir,
5372
- dockerfilePath,
5373
- imageRef,
5374
- registry: VCR_REGISTRY,
5375
- username,
5376
- token,
5377
- repository,
5378
- buildArgs,
5379
- buildTarget,
5380
- useBuildahStoreCache: buildahStoreCacheEnabled(),
5381
- span: buildSpan
5382
- };
5383
- await authenticateRegistry(engine, buildParams, buildSpan);
5384
- await withSpan(
5385
- buildSpan,
5386
- "container.ensure_repository",
5387
- { "container.repository": repository },
5388
- (s) => ensureRepository(repository, token, claims, s)
5389
- );
5390
- info(`Building image ${imageRef} (${engine.name})`);
5391
- debug(`dockerfile: ${dockerfilePath}`);
5392
- debug(`context: ${contextDir}`);
5393
- debug(`platform: ${TARGET_PLATFORM}`);
5394
- debug(`target: ${buildTarget ?? "(last stage)"}`);
5395
- debug(
5396
- `build args: ${buildArgs ? Object.keys(buildArgs).length : 0} (from project build env)`
5397
- );
5621
+ await prepareToolchain(engine, buildSpan);
5622
+ await publication.connect?.(buildSpan);
5623
+ const imageName = exportLayout ? build2.repository : imageRef;
5624
+ info(`Building image ${imageName} (${engine.name})`);
5398
5625
  const buildStart = Date.now();
5399
- step(
5400
- `${engine.name} build (${TARGET_PLATFORM}${buildTarget ? `, target ${buildTarget}` : ""})`
5401
- );
5402
- await withSpan(
5403
- buildSpan,
5404
- "container.image_build",
5405
- {
5406
- "image.ref": imageRef,
5407
- "image.platform": TARGET_PLATFORM,
5408
- "image.build_target": buildTarget
5409
- },
5410
- async () => {
5411
- if (params.schedulesCommand) {
5412
- await buildSchedulesCommandImage(engine, buildParams);
5413
- } else {
5414
- await engine.build(buildParams);
5415
- }
5416
- }
5417
- );
5418
- done(`built in ${elapsed(buildStart)}`);
5419
- const pushStart = Date.now();
5420
- step(`Pushing ${imageRef}`);
5421
- const digest = await withSpan(
5422
- buildSpan,
5423
- "container.push",
5424
- { "image.ref": imageRef },
5425
- () => engine.push(buildParams)
5626
+ await buildImage(
5627
+ engine,
5628
+ buildParams,
5629
+ build2.schedulesCommand,
5630
+ buildSpan
5426
5631
  );
5427
- done(`pushed ${shortDigest(digest)} in ${elapsed(pushStart)}`);
5428
- await withSpan(
5429
- buildSpan,
5430
- "container.report_storage",
5431
- { "container.engine": engine.name },
5432
- (s) => engine.reportStorage?.(s) ?? Promise.resolve()
5433
- );
5434
- const resolvedRef = `${VCR_REGISTRY}/${fullRepository}@${digest}`;
5435
- buildSpan?.setAttributes({
5436
- "image.digest": digest,
5437
- "image.resolved_ref": resolvedRef
5438
- });
5439
- info(`Image reference ${resolvedRef}`);
5632
+ const image = await publication.publish(buildParams, buildSpan);
5633
+ await reportStorage(engine, buildSpan);
5440
5634
  debug(
5441
- `container build_and_push total: ${elapsed(buildStart)} (build + push + storage report)`
5635
+ `container ${publisher.mode} total: ${elapsed(buildStart)} (build + publish + storage report)`
5442
5636
  );
5443
- return resolvedRef;
5637
+ return image;
5444
5638
  });
5445
5639
  }
5446
5640
  );
5447
5641
  }
5448
- async function resolveImageHandler(options, source, buildahClient, span, schedulesCommand) {
5642
+ async function containerImageFields(image) {
5643
+ if (image.kind === "registry") {
5644
+ return { files: {}, handler: image.reference };
5645
+ }
5646
+ return {
5647
+ files: await (0, import_build_utils11.glob)("**", image.directory),
5648
+ handler: image.manifestDigest,
5649
+ image: { type: "oci-layout", path: "image" }
5650
+ };
5651
+ }
5652
+ async function resolveImageOutput(options, source, buildahClient, span, schedulesCommand) {
5449
5653
  const { config, meta } = options;
5450
5654
  const { daemon } = config;
5451
5655
  span?.setAttributes({
@@ -5455,7 +5659,7 @@ async function resolveImageHandler(options, source, buildahClient, span, schedul
5455
5659
  if (source.kind === "prebuilt") {
5456
5660
  span?.setAttributes({ "container.mode": "prebuilt" });
5457
5661
  info(`Using prebuilt image ${source.imageRef}`);
5458
- return source.imageRef;
5662
+ return { kind: "registry", reference: source.imageRef };
5459
5663
  }
5460
5664
  if (source.kind === "buildpack") {
5461
5665
  const { buildpack } = source;
@@ -5466,7 +5670,7 @@ async function resolveImageHandler(options, source, buildahClient, span, schedul
5466
5670
  "buildpack.runtime": buildpack.runtime,
5467
5671
  "image.tag": tag3
5468
5672
  });
5469
- return tag3;
5673
+ return { kind: "registry", reference: tag3 };
5470
5674
  }
5471
5675
  const repository2 = daemon ? (0, import_build_utils11.getDaemonImageRepository)(daemon.name) : sanitizeRepository(options.service?.name ?? buildpack.runtime);
5472
5676
  const tag2 = resolveImageTag();
@@ -5480,20 +5684,23 @@ async function resolveImageHandler(options, source, buildahClient, span, schedul
5480
5684
  meta?.buildEnv ?? (buildpack.runtime === "go" ? { CGO_ENABLED: process.env.CGO_ENABLED } : void 0)
5481
5685
  );
5482
5686
  try {
5483
- return await buildAndPushBuildpack({
5484
- buildpack,
5485
- files: options.files,
5486
- workPath: options.workPath,
5487
- repoRootPath: options.repoRootPath,
5488
- service: options.service,
5489
- repository: repository2,
5490
- tag: tag2,
5491
- config,
5492
- meta,
5493
- buildEnv,
5494
- buildahClient,
5495
- parentSpan: span
5496
- });
5687
+ return {
5688
+ kind: "registry",
5689
+ reference: await buildAndPushBuildpack({
5690
+ buildpack,
5691
+ files: options.files,
5692
+ workPath: options.workPath,
5693
+ repoRootPath: options.repoRootPath,
5694
+ service: options.service,
5695
+ repository: repository2,
5696
+ tag: tag2,
5697
+ config,
5698
+ meta,
5699
+ buildEnv,
5700
+ buildahClient,
5701
+ parentSpan: span
5702
+ })
5703
+ };
5497
5704
  } catch (error) {
5498
5705
  if (daemon && error.exitCode === BUILDPACK_FAILED_EXIT_CODE) {
5499
5706
  throw new Error(
@@ -5507,40 +5714,43 @@ async function resolveImageHandler(options, source, buildahClient, span, schedul
5507
5714
  if (meta?.isDev) {
5508
5715
  const serviceName = options.service?.name;
5509
5716
  const tag2 = devImageTag(
5510
- serviceName ?? import_node_path29.default.basename(dockerfileRel).split(".")[0]
5717
+ serviceName ?? import_node_path30.default.basename(dockerfileRel).split(".")[0]
5511
5718
  );
5512
5719
  span?.setAttributes({ "container.mode": "dev", "image.tag": tag2 });
5513
- return tag2;
5720
+ return { kind: "registry", reference: tag2 };
5514
5721
  }
5515
5722
  const repository = daemon ? (0, import_build_utils11.getDaemonImageRepository)(daemon.name) : sanitizeRepository(
5516
- options.service?.name ?? import_node_path29.default.basename(dockerfileRel).split(".")[0]
5723
+ options.service?.name ?? import_node_path30.default.basename(dockerfileRel).split(".")[0]
5517
5724
  );
5518
5725
  const tag = resolveImageTag();
5519
5726
  const contextDir = await resolveBuildContext({
5520
5727
  repoRootPath: options.repoRootPath,
5521
5728
  workPath: options.workPath,
5522
- contextDir: daemon || schedulesCommand || options.service ? options.workPath : import_node_path29.default.dirname(dockerfilePath),
5729
+ contextDir: daemon || schedulesCommand || options.service ? options.workPath : import_node_path30.default.dirname(dockerfilePath),
5523
5730
  dockerfilePath
5524
5731
  });
5525
- const contextIsRoot = Boolean(daemon || schedulesCommand || options.service) || import_node_path29.default.dirname(import_node_path29.default.normalize(dockerfileRel)) === ".";
5732
+ const contextIsRoot = Boolean(daemon || schedulesCommand || options.service) || import_node_path30.default.dirname(import_node_path30.default.normalize(dockerfileRel)) === ".";
5526
5733
  const buildArgs = buildArgsFromEnv(meta?.buildEnv);
5734
+ const shouldExportLayout = ociLayoutRequested() && !daemon;
5527
5735
  span?.setAttributes({
5528
- "container.mode": "build_and_push",
5529
5736
  "container.repository": repository,
5530
5737
  "container.context_is_root": toTag(contextIsRoot),
5531
5738
  "image.tag": tag
5532
5739
  });
5533
- return buildAndPushImage({
5534
- contextDir,
5535
- dockerfilePath,
5536
- repository,
5537
- tag,
5538
- buildArgs,
5539
- buildTarget: resolveBuildTarget(options.config),
5540
- buildahClient,
5541
- parentSpan: span,
5542
- schedulesCommand
5543
- });
5740
+ return buildAndPublishImage(
5741
+ {
5742
+ contextDir,
5743
+ dockerfilePath,
5744
+ repository,
5745
+ tag,
5746
+ buildArgs,
5747
+ buildTarget: resolveBuildTarget(options.config),
5748
+ buildahClient,
5749
+ parentSpan: span,
5750
+ schedulesCommand
5751
+ },
5752
+ shouldExportLayout
5753
+ );
5544
5754
  }
5545
5755
  function buildArgsFromEnv(env) {
5546
5756
  if (!env) {
@@ -5557,7 +5767,6 @@ function buildArgsFromEnv(env) {
5557
5767
  async function build(options) {
5558
5768
  const source = resolveImageSource(options, "build");
5559
5769
  const schedulesCommand = options.config.schedulesCommand;
5560
- const { daemon } = options.config;
5561
5770
  const buildahClient = new BuildahClient(sharedBuildahStoreLock);
5562
5771
  if (!options.meta?.isDev && selectContainerEngine(buildahClient).name === "buildah") {
5563
5772
  await BuildahStoreCache.forProject(options, buildahClient).beforeBuild({
@@ -5569,15 +5778,25 @@ async function build(options) {
5569
5778
  options.span,
5570
5779
  "container.resolve_image",
5571
5780
  { "service.name": options.service?.name },
5572
- (span) => resolveImageHandler(
5573
- options,
5574
- source,
5575
- buildahClient,
5576
- span,
5577
- schedulesCommand
5578
- )
5781
+ (span) => resolveImageOutput(options, source, buildahClient, span, schedulesCommand)
5579
5782
  );
5783
+ try {
5784
+ return await createBuildResult(options, source, schedulesCommand, image);
5785
+ } catch (error) {
5786
+ if (image.kind === "oci-layout") {
5787
+ await (0, import_promises14.rm)(image.directory, { recursive: true, force: true });
5788
+ }
5789
+ throw error;
5790
+ }
5791
+ }
5792
+ async function createBuildResult(options, source, schedulesCommand, image) {
5793
+ const { daemon } = options.config;
5580
5794
  if (daemon) {
5795
+ if (image.kind !== "registry") {
5796
+ throw new Error(
5797
+ `Daemon "${daemon.name}" was built as an OCI image layout, but daemons run from the registry.`
5798
+ );
5799
+ }
5581
5800
  await generateProjectManifest({
5582
5801
  workPath: options.workPath,
5583
5802
  framework: options.diagnosticsValues?.framework,
@@ -5588,7 +5807,7 @@ async function build(options) {
5588
5807
  daemons: {
5589
5808
  [daemon.name]: {
5590
5809
  runtime: "container",
5591
- image,
5810
+ image: image.reference,
5592
5811
  // Checked by vercel.json validation: a daemon sets one of them.
5593
5812
  instances: daemon.instances ?? daemon.replicas,
5594
5813
  // A command replaces the image's entrypoint, which for a buildpack
@@ -5643,20 +5862,15 @@ async function build(options) {
5643
5862
  return {
5644
5863
  routes: schedulesCommand ? [] : routes,
5645
5864
  output: {
5646
- [outputPath]: {
5647
- type: "Lambda",
5648
- files: {},
5649
- // For `runtime: 'container'` the OCI image reference is carried in
5650
- // `handler`; the platform surfaces it as the container image downstream
5651
- // (vercel/api#76729).
5652
- handler: image,
5865
+ [outputPath]: new import_build_utils11.ContainerImage({
5866
+ ...await containerImageFields(image),
5653
5867
  runtime: "container",
5654
5868
  environment: schedulesCommand ? {
5655
5869
  [SCHEDULES_COMMAND_ENV]: JSON.stringify(schedulesCommand.command)
5656
5870
  } : {},
5657
5871
  ...command ? { command } : {},
5658
5872
  ...lambdaOptions
5659
- }
5873
+ })
5660
5874
  }
5661
5875
  };
5662
5876
  }