@vercel/python 6.54.0 → 6.55.1

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
@@ -137,12 +137,12 @@ var require_isexe = __commonJS({
137
137
  if (typeof Promise !== "function") {
138
138
  throw new TypeError("callback not provided");
139
139
  }
140
- return new Promise(function(resolve3, reject) {
140
+ return new Promise(function(resolve4, reject) {
141
141
  isexe(path, options || {}, function(er, is) {
142
142
  if (er) {
143
143
  reject(er);
144
144
  } else {
145
- resolve3(is);
145
+ resolve4(is);
146
146
  }
147
147
  });
148
148
  });
@@ -423,15 +423,15 @@ var require_readShebang = __commonJS({
423
423
  var require_semver = __commonJS({
424
424
  "../../node_modules/.pnpm/semver@5.7.2/node_modules/semver/semver.js"(exports, module2) {
425
425
  exports = module2.exports = SemVer;
426
- var debug17;
426
+ var debug18;
427
427
  if (typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
428
- debug17 = function() {
428
+ debug18 = function() {
429
429
  var args = Array.prototype.slice.call(arguments, 0);
430
430
  args.unshift("SEMVER");
431
431
  console.log.apply(console, args);
432
432
  };
433
433
  } else {
434
- debug17 = function() {
434
+ debug18 = function() {
435
435
  };
436
436
  }
437
437
  exports.SEMVER_SPEC_VERSION = "2.0.0";
@@ -540,7 +540,7 @@ var require_semver = __commonJS({
540
540
  var STAR = R++;
541
541
  src[STAR] = "(<|>)?=?\\s*\\*";
542
542
  for (i = 0; i < R; i++) {
543
- debug17(i, src[i]);
543
+ debug18(i, src[i]);
544
544
  if (!re[i]) {
545
545
  re[i] = new RegExp(src[i]);
546
546
  safeRe[i] = new RegExp(makeSafeRe(src[i]));
@@ -607,7 +607,7 @@ var require_semver = __commonJS({
607
607
  if (!(this instanceof SemVer)) {
608
608
  return new SemVer(version2, options);
609
609
  }
610
- debug17("SemVer", version2, options);
610
+ debug18("SemVer", version2, options);
611
611
  this.options = options;
612
612
  this.loose = !!options.loose;
613
613
  var m = version2.trim().match(options.loose ? safeRe[LOOSE] : safeRe[FULL]);
@@ -654,7 +654,7 @@ var require_semver = __commonJS({
654
654
  return this.version;
655
655
  };
656
656
  SemVer.prototype.compare = function(other) {
657
- debug17("SemVer.compare", this.version, this.options, other);
657
+ debug18("SemVer.compare", this.version, this.options, other);
658
658
  if (!(other instanceof SemVer)) {
659
659
  other = new SemVer(other, this.options);
660
660
  }
@@ -681,7 +681,7 @@ var require_semver = __commonJS({
681
681
  do {
682
682
  var a = this.prerelease[i2];
683
683
  var b = other.prerelease[i2];
684
- debug17("prerelease compare", i2, a, b);
684
+ debug18("prerelease compare", i2, a, b);
685
685
  if (a === void 0 && b === void 0) {
686
686
  return 0;
687
687
  } else if (b === void 0) {
@@ -935,7 +935,7 @@ var require_semver = __commonJS({
935
935
  return new Comparator(comp, options);
936
936
  }
937
937
  comp = comp.trim().split(/\s+/).join(" ");
938
- debug17("comparator", comp, options);
938
+ debug18("comparator", comp, options);
939
939
  this.options = options;
940
940
  this.loose = !!options.loose;
941
941
  this.parse(comp);
@@ -944,7 +944,7 @@ var require_semver = __commonJS({
944
944
  } else {
945
945
  this.value = this.operator + this.semver.version;
946
946
  }
947
- debug17("comp", this);
947
+ debug18("comp", this);
948
948
  }
949
949
  var ANY = {};
950
950
  Comparator.prototype.parse = function(comp) {
@@ -967,7 +967,7 @@ var require_semver = __commonJS({
967
967
  return this.value;
968
968
  };
969
969
  Comparator.prototype.test = function(version2) {
970
- debug17("Comparator.test", version2, this.options.loose);
970
+ debug18("Comparator.test", version2, this.options.loose);
971
971
  if (this.semver === ANY) {
972
972
  return true;
973
973
  }
@@ -1050,9 +1050,9 @@ var require_semver = __commonJS({
1050
1050
  var loose = this.options.loose;
1051
1051
  var hr = loose ? safeRe[HYPHENRANGELOOSE] : safeRe[HYPHENRANGE];
1052
1052
  range = range.replace(hr, hyphenReplace);
1053
- debug17("hyphen replace", range);
1053
+ debug18("hyphen replace", range);
1054
1054
  range = range.replace(safeRe[COMPARATORTRIM], comparatorTrimReplace);
1055
- debug17("comparator trim", range, safeRe[COMPARATORTRIM]);
1055
+ debug18("comparator trim", range, safeRe[COMPARATORTRIM]);
1056
1056
  range = range.replace(safeRe[TILDETRIM], tildeTrimReplace);
1057
1057
  range = range.replace(safeRe[CARETTRIM], caretTrimReplace);
1058
1058
  var compRe = loose ? safeRe[COMPARATORLOOSE] : safeRe[COMPARATOR];
@@ -1092,15 +1092,15 @@ var require_semver = __commonJS({
1092
1092
  });
1093
1093
  }
1094
1094
  function parseComparator(comp, options) {
1095
- debug17("comp", comp, options);
1095
+ debug18("comp", comp, options);
1096
1096
  comp = replaceCarets(comp, options);
1097
- debug17("caret", comp);
1097
+ debug18("caret", comp);
1098
1098
  comp = replaceTildes(comp, options);
1099
- debug17("tildes", comp);
1099
+ debug18("tildes", comp);
1100
1100
  comp = replaceXRanges(comp, options);
1101
- debug17("xrange", comp);
1101
+ debug18("xrange", comp);
1102
1102
  comp = replaceStars(comp, options);
1103
- debug17("stars", comp);
1103
+ debug18("stars", comp);
1104
1104
  return comp;
1105
1105
  }
1106
1106
  function isX(id) {
@@ -1114,7 +1114,7 @@ var require_semver = __commonJS({
1114
1114
  function replaceTilde(comp, options) {
1115
1115
  var r = options.loose ? safeRe[TILDELOOSE] : safeRe[TILDE];
1116
1116
  return comp.replace(r, function(_, M, m, p, pr) {
1117
- debug17("tilde", comp, _, M, m, p, pr);
1117
+ debug18("tilde", comp, _, M, m, p, pr);
1118
1118
  var ret;
1119
1119
  if (isX(M)) {
1120
1120
  ret = "";
@@ -1123,12 +1123,12 @@ var require_semver = __commonJS({
1123
1123
  } else if (isX(p)) {
1124
1124
  ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
1125
1125
  } else if (pr) {
1126
- debug17("replaceTilde pr", pr);
1126
+ debug18("replaceTilde pr", pr);
1127
1127
  ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0";
1128
1128
  } else {
1129
1129
  ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0";
1130
1130
  }
1131
- debug17("tilde return", ret);
1131
+ debug18("tilde return", ret);
1132
1132
  return ret;
1133
1133
  });
1134
1134
  }
@@ -1138,10 +1138,10 @@ var require_semver = __commonJS({
1138
1138
  }).join(" ");
1139
1139
  }
1140
1140
  function replaceCaret(comp, options) {
1141
- debug17("caret", comp, options);
1141
+ debug18("caret", comp, options);
1142
1142
  var r = options.loose ? safeRe[CARETLOOSE] : safeRe[CARET];
1143
1143
  return comp.replace(r, function(_, M, m, p, pr) {
1144
- debug17("caret", comp, _, M, m, p, pr);
1144
+ debug18("caret", comp, _, M, m, p, pr);
1145
1145
  var ret;
1146
1146
  if (isX(M)) {
1147
1147
  ret = "";
@@ -1154,7 +1154,7 @@ var require_semver = __commonJS({
1154
1154
  ret = ">=" + M + "." + m + ".0 <" + (+M + 1) + ".0.0";
1155
1155
  }
1156
1156
  } else if (pr) {
1157
- debug17("replaceCaret pr", pr);
1157
+ debug18("replaceCaret pr", pr);
1158
1158
  if (M === "0") {
1159
1159
  if (m === "0") {
1160
1160
  ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + m + "." + (+p + 1);
@@ -1165,7 +1165,7 @@ var require_semver = __commonJS({
1165
1165
  ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + (+M + 1) + ".0.0";
1166
1166
  }
1167
1167
  } else {
1168
- debug17("no pr");
1168
+ debug18("no pr");
1169
1169
  if (M === "0") {
1170
1170
  if (m === "0") {
1171
1171
  ret = ">=" + M + "." + m + "." + p + " <" + M + "." + m + "." + (+p + 1);
@@ -1176,12 +1176,12 @@ var require_semver = __commonJS({
1176
1176
  ret = ">=" + M + "." + m + "." + p + " <" + (+M + 1) + ".0.0";
1177
1177
  }
1178
1178
  }
1179
- debug17("caret return", ret);
1179
+ debug18("caret return", ret);
1180
1180
  return ret;
1181
1181
  });
1182
1182
  }
1183
1183
  function replaceXRanges(comp, options) {
1184
- debug17("replaceXRanges", comp, options);
1184
+ debug18("replaceXRanges", comp, options);
1185
1185
  return comp.split(/\s+/).map(function(comp2) {
1186
1186
  return replaceXRange(comp2, options);
1187
1187
  }).join(" ");
@@ -1190,7 +1190,7 @@ var require_semver = __commonJS({
1190
1190
  comp = comp.trim();
1191
1191
  var r = options.loose ? safeRe[XRANGELOOSE] : safeRe[XRANGE];
1192
1192
  return comp.replace(r, function(ret, gtlt, M, m, p, pr) {
1193
- debug17("xRange", comp, ret, gtlt, M, m, p, pr);
1193
+ debug18("xRange", comp, ret, gtlt, M, m, p, pr);
1194
1194
  var xM = isX(M);
1195
1195
  var xm = xM || isX(m);
1196
1196
  var xp = xm || isX(p);
@@ -1233,12 +1233,12 @@ var require_semver = __commonJS({
1233
1233
  } else if (xp) {
1234
1234
  ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
1235
1235
  }
1236
- debug17("xRange return", ret);
1236
+ debug18("xRange return", ret);
1237
1237
  return ret;
1238
1238
  });
1239
1239
  }
1240
1240
  function replaceStars(comp, options) {
1241
- debug17("replaceStars", comp, options);
1241
+ debug18("replaceStars", comp, options);
1242
1242
  return comp.trim().replace(safeRe[STAR], "");
1243
1243
  }
1244
1244
  function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
@@ -1286,7 +1286,7 @@ var require_semver = __commonJS({
1286
1286
  }
1287
1287
  if (version2.prerelease.length && !options.includePrerelease) {
1288
1288
  for (i2 = 0; i2 < set.length; i2++) {
1289
- debug17(set[i2].semver);
1289
+ debug18(set[i2].semver);
1290
1290
  if (set[i2].semver === ANY) {
1291
1291
  continue;
1292
1292
  }
@@ -2042,7 +2042,7 @@ var require_get_stream = __commonJS({
2042
2042
  options = Object.assign({ maxBuffer: Infinity }, options);
2043
2043
  const { maxBuffer } = options;
2044
2044
  let stream;
2045
- return new Promise((resolve3, reject) => {
2045
+ return new Promise((resolve4, reject) => {
2046
2046
  const rejectPromise = (error) => {
2047
2047
  if (error) {
2048
2048
  error.bufferedData = stream.getBufferedValue();
@@ -2054,7 +2054,7 @@ var require_get_stream = __commonJS({
2054
2054
  rejectPromise(error);
2055
2055
  return;
2056
2056
  }
2057
- resolve3();
2057
+ resolve4();
2058
2058
  });
2059
2059
  stream.on("data", () => {
2060
2060
  if (stream.getBufferedLength() > maxBuffer) {
@@ -2078,11 +2078,11 @@ var require_p_finally = __commonJS({
2078
2078
  onFinally = onFinally || (() => {
2079
2079
  });
2080
2080
  return promise.then(
2081
- (val) => new Promise((resolve3) => {
2082
- resolve3(onFinally());
2081
+ (val) => new Promise((resolve4) => {
2082
+ resolve4(onFinally());
2083
2083
  }).then(() => val),
2084
- (err) => new Promise((resolve3) => {
2085
- resolve3(onFinally());
2084
+ (err) => new Promise((resolve4) => {
2085
+ resolve4(onFinally());
2086
2086
  }).then(() => {
2087
2087
  throw err;
2088
2088
  })
@@ -2461,8 +2461,8 @@ var require_execa = __commonJS({
2461
2461
  }
2462
2462
  let ret;
2463
2463
  if (!buffer) {
2464
- ret = new Promise((resolve3, reject) => {
2465
- process2[stream].once("end", resolve3).once("error", reject);
2464
+ ret = new Promise((resolve4, reject) => {
2465
+ process2[stream].once("end", resolve4).once("error", reject);
2466
2466
  });
2467
2467
  } else if (encoding) {
2468
2468
  ret = _getStream(process2[stream], {
@@ -2551,19 +2551,19 @@ ${stderr}${stdout}`;
2551
2551
  spawned.kill(parsed.opts.killSignal);
2552
2552
  }, parsed.opts.timeout);
2553
2553
  }
2554
- const processDone = new Promise((resolve3) => {
2554
+ const processDone = new Promise((resolve4) => {
2555
2555
  spawned.on("exit", (code, signal) => {
2556
2556
  cleanup();
2557
- resolve3({ code, signal });
2557
+ resolve4({ code, signal });
2558
2558
  });
2559
2559
  spawned.on("error", (err) => {
2560
2560
  cleanup();
2561
- resolve3({ error: err });
2561
+ resolve4({ error: err });
2562
2562
  });
2563
2563
  if (spawned.stdin) {
2564
2564
  spawned.stdin.on("error", (err) => {
2565
2565
  cleanup();
2566
- resolve3({ error: err });
2566
+ resolve4({ error: err });
2567
2567
  });
2568
2568
  }
2569
2569
  });
@@ -3301,9 +3301,9 @@ var require_pep440 = __commonJS({
3301
3301
  var require_lib = __commonJS({
3302
3302
  "../../node_modules/.pnpm/which@3.0.0/node_modules/which/lib/index.js"(exports, module2) {
3303
3303
  var isexe = require_isexe();
3304
- var { join: join20, delimiter: delimiter2, sep: sep3, posix } = require("path");
3304
+ var { join: join21, delimiter: delimiter2, sep: sep4, posix } = require("path");
3305
3305
  var isWindows = process.platform === "win32";
3306
- var rSlash = new RegExp(`[${posix.sep}${sep3 === posix.sep ? "" : sep3}]`.replace(/(\\)/g, "\\$1"));
3306
+ var rSlash = new RegExp(`[${posix.sep}${sep4 === posix.sep ? "" : sep4}]`.replace(/(\\)/g, "\\$1"));
3307
3307
  var rRel = new RegExp(`^\\.${rSlash.source}`);
3308
3308
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
3309
3309
  var getPathInfo = (cmd, {
@@ -3330,7 +3330,7 @@ var require_lib = __commonJS({
3330
3330
  var getPathPart = (raw, cmd) => {
3331
3331
  const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw;
3332
3332
  const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : "";
3333
- return prefix + join20(pathPart, cmd);
3333
+ return prefix + join21(pathPart, cmd);
3334
3334
  };
3335
3335
  var which2 = async (cmd, opt = {}) => {
3336
3336
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
@@ -3389,15 +3389,15 @@ var require_lib = __commonJS({
3389
3389
  var require_semver2 = __commonJS({
3390
3390
  "../../node_modules/.pnpm/semver@6.3.1/node_modules/semver/semver.js"(exports, module2) {
3391
3391
  exports = module2.exports = SemVer;
3392
- var debug17;
3392
+ var debug18;
3393
3393
  if (typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
3394
- debug17 = function() {
3394
+ debug18 = function() {
3395
3395
  var args = Array.prototype.slice.call(arguments, 0);
3396
3396
  args.unshift("SEMVER");
3397
3397
  console.log.apply(console, args);
3398
3398
  };
3399
3399
  } else {
3400
- debug17 = function() {
3400
+ debug18 = function() {
3401
3401
  };
3402
3402
  }
3403
3403
  exports.SEMVER_SPEC_VERSION = "2.0.0";
@@ -3515,7 +3515,7 @@ var require_semver2 = __commonJS({
3515
3515
  tok("STAR");
3516
3516
  src[t.STAR] = "(<|>)?=?\\s*\\*";
3517
3517
  for (i = 0; i < R; i++) {
3518
- debug17(i, src[i]);
3518
+ debug18(i, src[i]);
3519
3519
  if (!re[i]) {
3520
3520
  re[i] = new RegExp(src[i]);
3521
3521
  safeRe[i] = new RegExp(makeSafeRe(src[i]));
@@ -3582,7 +3582,7 @@ var require_semver2 = __commonJS({
3582
3582
  if (!(this instanceof SemVer)) {
3583
3583
  return new SemVer(version2, options);
3584
3584
  }
3585
- debug17("SemVer", version2, options);
3585
+ debug18("SemVer", version2, options);
3586
3586
  this.options = options;
3587
3587
  this.loose = !!options.loose;
3588
3588
  var m = version2.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]);
@@ -3629,7 +3629,7 @@ var require_semver2 = __commonJS({
3629
3629
  return this.version;
3630
3630
  };
3631
3631
  SemVer.prototype.compare = function(other) {
3632
- debug17("SemVer.compare", this.version, this.options, other);
3632
+ debug18("SemVer.compare", this.version, this.options, other);
3633
3633
  if (!(other instanceof SemVer)) {
3634
3634
  other = new SemVer(other, this.options);
3635
3635
  }
@@ -3656,7 +3656,7 @@ var require_semver2 = __commonJS({
3656
3656
  do {
3657
3657
  var a = this.prerelease[i2];
3658
3658
  var b = other.prerelease[i2];
3659
- debug17("prerelease compare", i2, a, b);
3659
+ debug18("prerelease compare", i2, a, b);
3660
3660
  if (a === void 0 && b === void 0) {
3661
3661
  return 0;
3662
3662
  } else if (b === void 0) {
@@ -3678,7 +3678,7 @@ var require_semver2 = __commonJS({
3678
3678
  do {
3679
3679
  var a = this.build[i2];
3680
3680
  var b = other.build[i2];
3681
- debug17("prerelease compare", i2, a, b);
3681
+ debug18("prerelease compare", i2, a, b);
3682
3682
  if (a === void 0 && b === void 0) {
3683
3683
  return 0;
3684
3684
  } else if (b === void 0) {
@@ -3938,7 +3938,7 @@ var require_semver2 = __commonJS({
3938
3938
  return new Comparator(comp, options);
3939
3939
  }
3940
3940
  comp = comp.trim().split(/\s+/).join(" ");
3941
- debug17("comparator", comp, options);
3941
+ debug18("comparator", comp, options);
3942
3942
  this.options = options;
3943
3943
  this.loose = !!options.loose;
3944
3944
  this.parse(comp);
@@ -3947,7 +3947,7 @@ var require_semver2 = __commonJS({
3947
3947
  } else {
3948
3948
  this.value = this.operator + this.semver.version;
3949
3949
  }
3950
- debug17("comp", this);
3950
+ debug18("comp", this);
3951
3951
  }
3952
3952
  var ANY = {};
3953
3953
  Comparator.prototype.parse = function(comp) {
@@ -3970,7 +3970,7 @@ var require_semver2 = __commonJS({
3970
3970
  return this.value;
3971
3971
  };
3972
3972
  Comparator.prototype.test = function(version2) {
3973
- debug17("Comparator.test", version2, this.options.loose);
3973
+ debug18("Comparator.test", version2, this.options.loose);
3974
3974
  if (this.semver === ANY || version2 === ANY) {
3975
3975
  return true;
3976
3976
  }
@@ -4063,9 +4063,9 @@ var require_semver2 = __commonJS({
4063
4063
  var loose = this.options.loose;
4064
4064
  var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE];
4065
4065
  range = range.replace(hr, hyphenReplace);
4066
- debug17("hyphen replace", range);
4066
+ debug18("hyphen replace", range);
4067
4067
  range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace);
4068
- debug17("comparator trim", range, safeRe[t.COMPARATORTRIM]);
4068
+ debug18("comparator trim", range, safeRe[t.COMPARATORTRIM]);
4069
4069
  range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace);
4070
4070
  range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace);
4071
4071
  range = range.split(/\s+/).join(" ");
@@ -4118,15 +4118,15 @@ var require_semver2 = __commonJS({
4118
4118
  });
4119
4119
  }
4120
4120
  function parseComparator(comp, options) {
4121
- debug17("comp", comp, options);
4121
+ debug18("comp", comp, options);
4122
4122
  comp = replaceCarets(comp, options);
4123
- debug17("caret", comp);
4123
+ debug18("caret", comp);
4124
4124
  comp = replaceTildes(comp, options);
4125
- debug17("tildes", comp);
4125
+ debug18("tildes", comp);
4126
4126
  comp = replaceXRanges(comp, options);
4127
- debug17("xrange", comp);
4127
+ debug18("xrange", comp);
4128
4128
  comp = replaceStars(comp, options);
4129
- debug17("stars", comp);
4129
+ debug18("stars", comp);
4130
4130
  return comp;
4131
4131
  }
4132
4132
  function isX(id) {
@@ -4140,7 +4140,7 @@ var require_semver2 = __commonJS({
4140
4140
  function replaceTilde(comp, options) {
4141
4141
  var r = options.loose ? safeRe[t.TILDELOOSE] : safeRe[t.TILDE];
4142
4142
  return comp.replace(r, function(_, M, m, p, pr) {
4143
- debug17("tilde", comp, _, M, m, p, pr);
4143
+ debug18("tilde", comp, _, M, m, p, pr);
4144
4144
  var ret;
4145
4145
  if (isX(M)) {
4146
4146
  ret = "";
@@ -4149,12 +4149,12 @@ var require_semver2 = __commonJS({
4149
4149
  } else if (isX(p)) {
4150
4150
  ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
4151
4151
  } else if (pr) {
4152
- debug17("replaceTilde pr", pr);
4152
+ debug18("replaceTilde pr", pr);
4153
4153
  ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0";
4154
4154
  } else {
4155
4155
  ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0";
4156
4156
  }
4157
- debug17("tilde return", ret);
4157
+ debug18("tilde return", ret);
4158
4158
  return ret;
4159
4159
  });
4160
4160
  }
@@ -4164,10 +4164,10 @@ var require_semver2 = __commonJS({
4164
4164
  }).join(" ");
4165
4165
  }
4166
4166
  function replaceCaret(comp, options) {
4167
- debug17("caret", comp, options);
4167
+ debug18("caret", comp, options);
4168
4168
  var r = options.loose ? safeRe[t.CARETLOOSE] : safeRe[t.CARET];
4169
4169
  return comp.replace(r, function(_, M, m, p, pr) {
4170
- debug17("caret", comp, _, M, m, p, pr);
4170
+ debug18("caret", comp, _, M, m, p, pr);
4171
4171
  var ret;
4172
4172
  if (isX(M)) {
4173
4173
  ret = "";
@@ -4180,7 +4180,7 @@ var require_semver2 = __commonJS({
4180
4180
  ret = ">=" + M + "." + m + ".0 <" + (+M + 1) + ".0.0";
4181
4181
  }
4182
4182
  } else if (pr) {
4183
- debug17("replaceCaret pr", pr);
4183
+ debug18("replaceCaret pr", pr);
4184
4184
  if (M === "0") {
4185
4185
  if (m === "0") {
4186
4186
  ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + m + "." + (+p + 1);
@@ -4191,7 +4191,7 @@ var require_semver2 = __commonJS({
4191
4191
  ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + (+M + 1) + ".0.0";
4192
4192
  }
4193
4193
  } else {
4194
- debug17("no pr");
4194
+ debug18("no pr");
4195
4195
  if (M === "0") {
4196
4196
  if (m === "0") {
4197
4197
  ret = ">=" + M + "." + m + "." + p + " <" + M + "." + m + "." + (+p + 1);
@@ -4202,12 +4202,12 @@ var require_semver2 = __commonJS({
4202
4202
  ret = ">=" + M + "." + m + "." + p + " <" + (+M + 1) + ".0.0";
4203
4203
  }
4204
4204
  }
4205
- debug17("caret return", ret);
4205
+ debug18("caret return", ret);
4206
4206
  return ret;
4207
4207
  });
4208
4208
  }
4209
4209
  function replaceXRanges(comp, options) {
4210
- debug17("replaceXRanges", comp, options);
4210
+ debug18("replaceXRanges", comp, options);
4211
4211
  return comp.split(/\s+/).map(function(comp2) {
4212
4212
  return replaceXRange(comp2, options);
4213
4213
  }).join(" ");
@@ -4216,7 +4216,7 @@ var require_semver2 = __commonJS({
4216
4216
  comp = comp.trim();
4217
4217
  var r = options.loose ? safeRe[t.XRANGELOOSE] : safeRe[t.XRANGE];
4218
4218
  return comp.replace(r, function(ret, gtlt, M, m, p, pr) {
4219
- debug17("xRange", comp, ret, gtlt, M, m, p, pr);
4219
+ debug18("xRange", comp, ret, gtlt, M, m, p, pr);
4220
4220
  var xM = isX(M);
4221
4221
  var xm = xM || isX(m);
4222
4222
  var xp = xm || isX(p);
@@ -4260,12 +4260,12 @@ var require_semver2 = __commonJS({
4260
4260
  } else if (xp) {
4261
4261
  ret = ">=" + M + "." + m + ".0" + pr + " <" + M + "." + (+m + 1) + ".0" + pr;
4262
4262
  }
4263
- debug17("xRange return", ret);
4263
+ debug18("xRange return", ret);
4264
4264
  return ret;
4265
4265
  });
4266
4266
  }
4267
4267
  function replaceStars(comp, options) {
4268
- debug17("replaceStars", comp, options);
4268
+ debug18("replaceStars", comp, options);
4269
4269
  return comp.trim().replace(safeRe[t.STAR], "");
4270
4270
  }
4271
4271
  function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
@@ -4317,7 +4317,7 @@ var require_semver2 = __commonJS({
4317
4317
  }
4318
4318
  if (version2.prerelease.length && !options.includePrerelease) {
4319
4319
  for (i2 = 0; i2 < set.length; i2++) {
4320
- debug17(set[i2].semver);
4320
+ debug18(set[i2].semver);
4321
4321
  if (set[i2].semver === ANY) {
4322
4322
  continue;
4323
4323
  }
@@ -4574,14 +4574,14 @@ var require_filesystem = __commonJS({
4574
4574
  });
4575
4575
  return buffer.subarray(0, bytesRead);
4576
4576
  };
4577
- var readFile2 = (path) => new Promise((resolve3, reject) => {
4577
+ var readFile2 = (path) => new Promise((resolve4, reject) => {
4578
4578
  fs19.open(path, "r", (err, fd) => {
4579
4579
  if (err) {
4580
4580
  reject(err);
4581
4581
  } else {
4582
4582
  const buffer = Buffer.alloc(MAX_LENGTH);
4583
4583
  fs19.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => {
4584
- resolve3(buffer.subarray(0, bytesRead));
4584
+ resolve4(buffer.subarray(0, bytesRead));
4585
4585
  fs19.close(fd, () => {
4586
4586
  });
4587
4587
  });
@@ -4649,10 +4649,10 @@ var require_detect_libc = __commonJS({
4649
4649
  var commandOut = "";
4650
4650
  var safeCommand = () => {
4651
4651
  if (!commandOut) {
4652
- return new Promise((resolve3) => {
4652
+ return new Promise((resolve4) => {
4653
4653
  childProcess.exec(command, (err, out) => {
4654
4654
  commandOut = err ? " " : out;
4655
- resolve3(commandOut);
4655
+ resolve4(commandOut);
4656
4656
  });
4657
4657
  });
4658
4658
  }
@@ -4905,14 +4905,14 @@ var require_get_port = __commonJS({
4905
4905
  };
4906
4906
  var releaseOldLockedPortsIntervalMs = 1e3 * 15;
4907
4907
  var interval;
4908
- var getAvailablePort = (options) => new Promise((resolve3, reject) => {
4908
+ var getAvailablePort = (options) => new Promise((resolve4, reject) => {
4909
4909
  const server = net.createServer();
4910
4910
  server.unref();
4911
4911
  server.on("error", reject);
4912
4912
  server.listen(options, () => {
4913
4913
  const { port } = server.address();
4914
4914
  server.close(() => {
4915
- resolve3(port);
4915
+ resolve4(port);
4916
4916
  });
4917
4917
  });
4918
4918
  });
@@ -4984,7 +4984,7 @@ var require_is_port_reachable = __commonJS({
4984
4984
  "use strict";
4985
4985
  var net = require("net");
4986
4986
  module2.exports = async (port, { timeout = 1e3, host } = {}) => {
4987
- const promise = new Promise((resolve3, reject) => {
4987
+ const promise = new Promise((resolve4, reject) => {
4988
4988
  const socket = new net.Socket();
4989
4989
  const onError = () => {
4990
4990
  socket.destroy();
@@ -4995,7 +4995,7 @@ var require_is_port_reachable = __commonJS({
4995
4995
  socket.once("timeout", onError);
4996
4996
  socket.connect(port, host, () => {
4997
4997
  socket.end();
4998
- resolve3();
4998
+ resolve4();
4999
4999
  });
5000
5000
  });
5001
5001
  try {
@@ -5011,8 +5011,6 @@ var require_is_port_reachable = __commonJS({
5011
5011
  // src/index.ts
5012
5012
  var src_exports = {};
5013
5013
  __export(src_exports, {
5014
- addCollectedVendorBytecode: () => addCollectedVendorBytecode,
5015
- addVendorBytecodeInTiers: () => addVendorBytecodeInTiers,
5016
5014
  build: () => build,
5017
5015
  defaultShouldServe: () => defaultShouldServe,
5018
5016
  detectEntrypoint: () => detectEntrypoint,
@@ -5021,6 +5019,7 @@ __export(src_exports, {
5021
5019
  getDevSidecars: () => getDevSidecars,
5022
5020
  installRequirement: () => installRequirement,
5023
5021
  installRequirementsFile: () => installRequirementsFile,
5022
+ moduleKeysForClosurePaths: () => moduleKeysForClosurePaths,
5024
5023
  prepareCache: () => prepareCache,
5025
5024
  runFrameworkHook: () => runFrameworkHook,
5026
5025
  shouldServe: () => shouldServe,
@@ -5030,7 +5029,7 @@ __export(src_exports, {
5030
5029
  module.exports = __toCommonJS(src_exports);
5031
5030
  var import_assert = __toESM(require("assert"));
5032
5031
  var import_fs20 = __toESM(require("fs"));
5033
- var import_path20 = require("path");
5032
+ var import_path21 = require("path");
5034
5033
 
5035
5034
  // src/package-versions.ts
5036
5035
  var VERCEL_RUNTIME_VERSION = "0.17.0";
@@ -5266,7 +5265,7 @@ async function queryPythonVercelSdkVersion({
5266
5265
  }
5267
5266
 
5268
5267
  // src/index.ts
5269
- var import_build_utils23 = require("@vercel/build-utils");
5268
+ var import_build_utils24 = require("@vercel/build-utils");
5270
5269
 
5271
5270
  // src/install.ts
5272
5271
  var import_execa4 = __toESM(require_execa());
@@ -8151,10 +8150,24 @@ async function resolveQueueSubscribers({
8151
8150
  kind,
8152
8151
  integrations
8153
8152
  });
8153
+ const hint = kind === "workflow" ? "; ensure the entrypoint instantiates vercel.workflow.Workflows" : "";
8154
+ const unmatchedTopicPatterns = getUnmatchedQueueTopicPatterns(
8155
+ declaration,
8156
+ introspected
8157
+ );
8158
+ if (unmatchedTopicPatterns.length > 0) {
8159
+ const introspectedTopics = introspected.map(({ topic }) => topic);
8160
+ throw subscriberError(
8161
+ `${kind} "${declaration.name}" declared topics [${unmatchedTopicPatterns.join(
8162
+ ", "
8163
+ )}] but no introspected queue subscriptions matched them; introspected topics [${introspectedTopics.join(
8164
+ ", "
8165
+ )}]${hint}`
8166
+ );
8167
+ }
8154
8168
  const subscriptions = filterQueueSubscriptions(declaration, introspected);
8155
8169
  if (subscriptions.length === 0) {
8156
8170
  const declared = declaration.topicPatterns?.join(", ") ?? "*";
8157
- const hint = kind === "workflow" ? "; ensure the entrypoint instantiates vercel.workflow.Workflows" : "";
8158
8171
  throw subscriberError(
8159
8172
  `${kind} "${declaration.name}" declared topics [${declared}] but no introspected queue subscriptions matched${hint}`
8160
8173
  );
@@ -8173,6 +8186,13 @@ function filterQueueSubscriptions(declaration, subscriptions) {
8173
8186
  )
8174
8187
  );
8175
8188
  }
8189
+ function getUnmatchedQueueTopicPatterns(declaration, subscriptions) {
8190
+ return (declaration.topicPatterns ?? []).filter(
8191
+ (pattern) => !subscriptions.some(
8192
+ (subscription) => queueTopicPatternsOverlap(pattern, subscription.topic)
8193
+ )
8194
+ );
8195
+ }
8176
8196
  function queueTopicPatternsOverlap(left, right) {
8177
8197
  if (left === "*" || right === "*") {
8178
8198
  return true;
@@ -8551,7 +8571,7 @@ function createLogListener(callback, stream) {
8551
8571
  };
8552
8572
  }
8553
8573
  function sleep(ms) {
8554
- return new Promise((resolve3) => setTimeout(resolve3, ms));
8574
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
8555
8575
  }
8556
8576
  async function checkForPort(port, timeout) {
8557
8577
  const start = Date.now();
@@ -8698,7 +8718,7 @@ async function runSync({
8698
8718
  (0, import_build_utils14.debug)(`Unknown manifest type: ${manifestType}`);
8699
8719
  return;
8700
8720
  }
8701
- await new Promise((resolve3, reject) => {
8721
+ await new Promise((resolve4, reject) => {
8702
8722
  (0, import_build_utils14.debug)(`Running "${spawnCmd} ${spawnArgs.join(" ")}" in ${projectDir}...`);
8703
8723
  const child = (0, import_child_process2.spawn)(spawnCmd, spawnArgs, {
8704
8724
  cwd: projectDir,
@@ -8722,7 +8742,7 @@ async function runSync({
8722
8742
  child.on("error", reject);
8723
8743
  child.on("exit", (code, signal) => {
8724
8744
  if (code === 0) {
8725
- resolve3();
8745
+ resolve4();
8726
8746
  } else {
8727
8747
  reject(
8728
8748
  new Error(
@@ -8788,7 +8808,7 @@ async function doInstallInjectedDevPackage(pkg, opts) {
8788
8808
  ...excludeOverride,
8789
8809
  dep
8790
8810
  ];
8791
- await new Promise((resolve3, reject) => {
8811
+ await new Promise((resolve4, reject) => {
8792
8812
  const child = (0, import_child_process2.spawn)(pip.cmd, spawnArgs, {
8793
8813
  cwd: workPath,
8794
8814
  env: getProtectedUvEnv(env),
@@ -8811,7 +8831,7 @@ async function doInstallInjectedDevPackage(pkg, opts) {
8811
8831
  child.on("error", reject);
8812
8832
  child.on("exit", (code, signal) => {
8813
8833
  if (code === 0) {
8814
- resolve3();
8834
+ resolve4();
8815
8835
  } else {
8816
8836
  reject(
8817
8837
  new Error(
@@ -9019,8 +9039,8 @@ var startDevServer = async (opts) => {
9019
9039
  let resolveChildReady;
9020
9040
  let rejectChildReady;
9021
9041
  const childReady = new Promise(
9022
- (resolve3, reject) => {
9023
- resolveChildReady = resolve3;
9042
+ (resolve4, reject) => {
9043
+ resolveChildReady = resolve4;
9024
9044
  rejectChildReady = reject;
9025
9045
  }
9026
9046
  );
@@ -9943,6 +9963,49 @@ async function runFastAPICollectStatic(venvPath, workPath, env, outputStaticDir,
9943
9963
  // src/index.ts
9944
9964
  var import_python_analysis12 = require("@vercel/python-analysis");
9945
9965
 
9966
+ // src/bytecode-packing.ts
9967
+ function isBytecodeAnalysisDisabled() {
9968
+ const val = process.env.VERCEL_PYTHON_DISABLE_BYTECODE_ANALYSIS;
9969
+ if (val === void 0 || val === "")
9970
+ return false;
9971
+ const lower = val.toLowerCase();
9972
+ return lower === "1" || lower === "true";
9973
+ }
9974
+ function annotateBytecodeItems(items, importedModules, timings) {
9975
+ return items.map((item) => ({
9976
+ ...item,
9977
+ imported: importedModules?.has(item.moduleKey) ?? false,
9978
+ compileSeconds: timings?.get(item.sourceAbsPath)
9979
+ }));
9980
+ }
9981
+ function rankBytecodeItems(items) {
9982
+ const densities = items.filter((i) => i.compileSeconds != null && i.size > 0).map((i) => i.compileSeconds / i.size).sort((a, b) => a - b);
9983
+ const medianDensity = densities.length > 0 ? densities[Math.floor(densities.length / 2)] : null;
9984
+ return [...items].sort((a, b) => {
9985
+ if (a.imported !== b.imported)
9986
+ return a.imported ? -1 : 1;
9987
+ if (medianDensity !== null) {
9988
+ const da = a.compileSeconds != null && a.size > 0 ? a.compileSeconds / a.size : medianDensity;
9989
+ const db = b.compileSeconds != null && b.size > 0 ? b.compileSeconds / b.size : medianDensity;
9990
+ if (da !== db)
9991
+ return db - da;
9992
+ }
9993
+ return b.size - a.size;
9994
+ });
9995
+ }
9996
+ function fillBytecodeWithinCapacity(files, rankedItems, capacity) {
9997
+ let remaining = capacity;
9998
+ for (const item of rankedItems) {
9999
+ if (remaining <= 0)
10000
+ break;
10001
+ if (item.size <= remaining) {
10002
+ files[item.bundlePath] = item.file;
10003
+ remaining -= item.size;
10004
+ }
10005
+ }
10006
+ return remaining;
10007
+ }
10008
+
9946
10009
  // src/compileall.ts
9947
10010
  var import_execa10 = __toESM(require_execa());
9948
10011
  var import_build_utils20 = require("@vercel/build-utils");
@@ -9980,7 +10043,7 @@ async function runCompileAll({
9980
10043
  }) {
9981
10044
  const uniqueSourceFiles = [...new Set(sourceFiles)];
9982
10045
  if (uniqueSourceFiles.length === 0) {
9983
- return false;
10046
+ return { success: false };
9984
10047
  }
9985
10048
  let tempDir;
9986
10049
  try {
@@ -9989,17 +10052,25 @@ async function runCompileAll({
9989
10052
  );
9990
10053
  const listPath = (0, import_path17.join)(tempDir, "pysources.json");
9991
10054
  await import_fs17.default.promises.writeFile(listPath, JSON.stringify(uniqueSourceFiles));
10055
+ const timingsPath = (0, import_path17.join)(tempDir, "timings.json");
9992
10056
  const scriptPath4 = (0, import_path17.join)(__dirname, "..", "templates", "vc_compileall.py");
9993
10057
  const baseEnv = env || process.env;
9994
10058
  const subprocessEnv = pycachePrefix ? { ...baseEnv, PYTHONPYCACHEPREFIX: pycachePrefix } : baseEnv;
9995
- await (0, import_execa10.default)(pythonBin, [scriptPath4, listPath], {
10059
+ await (0, import_execa10.default)(pythonBin, [scriptPath4, listPath, timingsPath], {
9996
10060
  env: subprocessEnv,
9997
10061
  timeout: COMPILEALL_TIMEOUT_MS
9998
10062
  });
9999
- return true;
10063
+ let timings;
10064
+ try {
10065
+ const raw = await import_fs17.default.promises.readFile(timingsPath, "utf8");
10066
+ timings = new Map(Object.entries(JSON.parse(raw)));
10067
+ } catch (err) {
10068
+ (0, import_build_utils20.debug)(`compileall timings unavailable: ${String(err)}`);
10069
+ }
10070
+ return { success: true, timings };
10000
10071
  } catch (err) {
10001
10072
  (0, import_build_utils20.debug)(`compileall error details: ${JSON.stringify(err)}`);
10002
- return false;
10073
+ return { success: false };
10003
10074
  } finally {
10004
10075
  if (tempDir) {
10005
10076
  try {
@@ -10066,9 +10137,10 @@ async function collectAppPrefixBytecodeFiles({
10066
10137
  for (const bundlePath of Object.keys(appFiles)) {
10067
10138
  if (!bundlePath.endsWith(".py"))
10068
10139
  continue;
10140
+ const sourceAbsPath = (0, import_path17.join)(workPath, bundlePath.replaceAll("/", import_path17.sep));
10069
10141
  const stagedFsPath = deriveStagedPycFsPath(
10070
10142
  stagingDir,
10071
- (0, import_path17.join)(workPath, bundlePath.replaceAll("/", import_path17.sep)),
10143
+ sourceAbsPath,
10072
10144
  pythonMajor,
10073
10145
  pythonMinor
10074
10146
  );
@@ -10079,13 +10151,24 @@ async function collectAppPrefixBytecodeFiles({
10079
10151
  );
10080
10152
  if (!stagedFsPath || !pycBundlePath)
10081
10153
  continue;
10082
- pending.push({ bundlePath: pycBundlePath, srcFsPath: stagedFsPath });
10154
+ pending.push({
10155
+ bundlePath: pycBundlePath,
10156
+ srcFsPath: stagedFsPath,
10157
+ moduleKey: bundlePath,
10158
+ sourceAbsPath
10159
+ });
10083
10160
  }
10084
10161
  const results = await Promise.all(
10085
- pending.map(async ({ bundlePath, srcFsPath }) => {
10162
+ pending.map(async ({ bundlePath, srcFsPath, moduleKey, sourceAbsPath }) => {
10086
10163
  try {
10087
10164
  const stats = await import_fs17.default.promises.stat(srcFsPath);
10088
- return { bundlePath, srcFsPath, size: stats.size };
10165
+ return {
10166
+ bundlePath,
10167
+ srcFsPath,
10168
+ moduleKey,
10169
+ sourceAbsPath,
10170
+ size: stats.size
10171
+ };
10089
10172
  } catch {
10090
10173
  return null;
10091
10174
  }
@@ -10093,18 +10176,27 @@ async function collectAppPrefixBytecodeFiles({
10093
10176
  );
10094
10177
  const files = {};
10095
10178
  const perItemSizes = /* @__PURE__ */ new Map();
10179
+ const items = [];
10096
10180
  let totalSize = 0;
10097
10181
  for (const result of results) {
10098
10182
  if (!result)
10099
10183
  continue;
10100
- files[result.bundlePath] = new import_build_utils20.FileFsRef({
10184
+ const file = new import_build_utils20.FileFsRef({
10101
10185
  fsPath: result.srcFsPath,
10102
10186
  size: result.size
10103
10187
  });
10188
+ files[result.bundlePath] = file;
10104
10189
  perItemSizes.set(result.bundlePath, result.size);
10190
+ items.push({
10191
+ bundlePath: result.bundlePath,
10192
+ file,
10193
+ size: result.size,
10194
+ moduleKey: result.moduleKey,
10195
+ sourceAbsPath: result.sourceAbsPath
10196
+ });
10105
10197
  totalSize += result.size;
10106
10198
  }
10107
- return { files, totalSize, perItemSizes };
10199
+ return { files, totalSize, perItemSizes, items };
10108
10200
  }
10109
10201
  async function collectAppBytecodeFiles({
10110
10202
  workPath,
@@ -10119,14 +10211,22 @@ async function collectAppBytecodeFiles({
10119
10211
  continue;
10120
10212
  pending.push({
10121
10213
  bundlePath: pycRel,
10122
- srcFsPath: (0, import_path17.join)(workPath, pycRel.replaceAll("/", import_path17.sep))
10214
+ srcFsPath: (0, import_path17.join)(workPath, pycRel.replaceAll("/", import_path17.sep)),
10215
+ moduleKey: bundlePath,
10216
+ sourceAbsPath: (0, import_path17.join)(workPath, bundlePath.replaceAll("/", import_path17.sep))
10123
10217
  });
10124
10218
  }
10125
10219
  const results = await Promise.all(
10126
- pending.map(async ({ bundlePath, srcFsPath }) => {
10220
+ pending.map(async ({ bundlePath, srcFsPath, moduleKey, sourceAbsPath }) => {
10127
10221
  try {
10128
10222
  const stats = await import_fs17.default.promises.stat(srcFsPath);
10129
- return { bundlePath, srcFsPath, size: stats.size };
10223
+ return {
10224
+ bundlePath,
10225
+ srcFsPath,
10226
+ moduleKey,
10227
+ sourceAbsPath,
10228
+ size: stats.size
10229
+ };
10130
10230
  } catch {
10131
10231
  return null;
10132
10232
  }
@@ -10134,18 +10234,27 @@ async function collectAppBytecodeFiles({
10134
10234
  );
10135
10235
  const files = {};
10136
10236
  const perItemSizes = /* @__PURE__ */ new Map();
10237
+ const items = [];
10137
10238
  let totalSize = 0;
10138
10239
  for (const result of results) {
10139
10240
  if (!result)
10140
10241
  continue;
10141
- files[result.bundlePath] = new import_build_utils20.FileFsRef({
10242
+ const file = new import_build_utils20.FileFsRef({
10142
10243
  fsPath: result.srcFsPath,
10143
10244
  size: result.size
10144
10245
  });
10246
+ files[result.bundlePath] = file;
10145
10247
  perItemSizes.set(result.bundlePath, result.size);
10248
+ items.push({
10249
+ bundlePath: result.bundlePath,
10250
+ file,
10251
+ size: result.size,
10252
+ moduleKey: result.moduleKey,
10253
+ sourceAbsPath: result.sourceAbsPath
10254
+ });
10146
10255
  totalSize += result.size;
10147
10256
  }
10148
- return { files, totalSize, perItemSizes };
10257
+ return { files, totalSize, perItemSizes, items };
10149
10258
  }
10150
10259
 
10151
10260
  // src/installed-distributions.ts
@@ -10235,6 +10344,13 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10235
10344
  this.pythonMajor = options.pythonMajor;
10236
10345
  this.pythonMinor = options.pythonMinor;
10237
10346
  }
10347
+ /**
10348
+ * Site-packages roots of the build venv (resolved). Used as import-closure
10349
+ * search roots and to map traced module files to vendor module keys.
10350
+ */
10351
+ getSitePackageDirs() {
10352
+ return this.sitePackageDirs;
10353
+ }
10238
10354
  async mirrorPackagesIntoVendor({
10239
10355
  vendorDirName,
10240
10356
  includePackages
@@ -10333,7 +10449,7 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10333
10449
  includePackages
10334
10450
  }) {
10335
10451
  if (this.pythonMajor == null || this.pythonMinor == null) {
10336
- return { files: {}, totalSize: 0, perItemSizes: /* @__PURE__ */ new Map() };
10452
+ return { files: {}, totalSize: 0, perItemSizes: /* @__PURE__ */ new Map(), items: [] };
10337
10453
  }
10338
10454
  const pending = [];
10339
10455
  const distributionGroups = getDistributionFileGroups({
@@ -10343,8 +10459,9 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10343
10459
  });
10344
10460
  for (const { packageName, sitePackagesDir, files } of distributionGroups) {
10345
10461
  for (const { relativePath } of files) {
10462
+ const moduleKey = relativePath.replaceAll(import_path18.sep, "/");
10346
10463
  const pycRelativePath = derivePycPath(
10347
- relativePath.replaceAll(import_path18.sep, "/"),
10464
+ moduleKey,
10348
10465
  this.pythonMajor,
10349
10466
  this.pythonMinor
10350
10467
  );
@@ -10354,7 +10471,9 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10354
10471
  pending.push({
10355
10472
  bundlePath: (0, import_path18.join)(vendorDirName, pycFilePath).replace(/\\/g, "/"),
10356
10473
  srcFsPath: (0, import_path18.join)(sitePackagesDir, pycFilePath),
10357
- packageName
10474
+ packageName,
10475
+ moduleKey,
10476
+ sourceAbsPath: (0, import_path18.join)(sitePackagesDir, relativePath)
10358
10477
  });
10359
10478
  }
10360
10479
  }
@@ -10370,7 +10489,7 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10370
10489
  includePackages
10371
10490
  }) {
10372
10491
  if (this.pythonMajor == null || this.pythonMinor == null) {
10373
- return { files: {}, totalSize: 0, perItemSizes: /* @__PURE__ */ new Map() };
10492
+ return { files: {}, totalSize: 0, perItemSizes: /* @__PURE__ */ new Map(), items: [] };
10374
10493
  }
10375
10494
  const pending = [];
10376
10495
  const distributionGroups = getDistributionFileGroups({
@@ -10396,7 +10515,13 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10396
10515
  );
10397
10516
  if (!srcFsPath || !bundlePath)
10398
10517
  continue;
10399
- pending.push({ bundlePath, srcFsPath, packageName });
10518
+ pending.push({
10519
+ bundlePath,
10520
+ srcFsPath,
10521
+ packageName,
10522
+ moduleKey: recordPath,
10523
+ sourceAbsPath: absolutePath
10524
+ });
10400
10525
  }
10401
10526
  }
10402
10527
  const result = await this.collectExistingBytecode(pending);
@@ -10407,32 +10532,56 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10407
10532
  }
10408
10533
  async collectExistingBytecode(pending) {
10409
10534
  const results = await Promise.all(
10410
- pending.map(async ({ bundlePath, srcFsPath, packageName }) => {
10411
- try {
10412
- const stats = await import_fs18.default.promises.stat(srcFsPath);
10413
- return { bundlePath, srcFsPath, size: stats.size, packageName };
10414
- } catch {
10415
- return null;
10535
+ pending.map(
10536
+ async ({
10537
+ bundlePath,
10538
+ srcFsPath,
10539
+ packageName,
10540
+ moduleKey,
10541
+ sourceAbsPath
10542
+ }) => {
10543
+ try {
10544
+ const stats = await import_fs18.default.promises.stat(srcFsPath);
10545
+ return {
10546
+ bundlePath,
10547
+ srcFsPath,
10548
+ size: stats.size,
10549
+ packageName,
10550
+ moduleKey,
10551
+ sourceAbsPath
10552
+ };
10553
+ } catch {
10554
+ return null;
10555
+ }
10416
10556
  }
10417
- })
10557
+ )
10418
10558
  );
10419
10559
  const files = {};
10420
10560
  let totalSize = 0;
10421
10561
  const perItemSizes = /* @__PURE__ */ new Map();
10562
+ const items = [];
10422
10563
  for (const result of results) {
10423
10564
  if (!result)
10424
10565
  continue;
10425
- files[result.bundlePath] = new import_build_utils21.FileFsRef({
10566
+ const file = new import_build_utils21.FileFsRef({
10426
10567
  fsPath: result.srcFsPath,
10427
10568
  size: result.size
10428
10569
  });
10570
+ files[result.bundlePath] = file;
10429
10571
  totalSize += result.size;
10430
10572
  perItemSizes.set(
10431
10573
  result.packageName,
10432
10574
  (perItemSizes.get(result.packageName) ?? 0) + result.size
10433
10575
  );
10576
+ items.push({
10577
+ bundlePath: result.bundlePath,
10578
+ file,
10579
+ size: result.size,
10580
+ moduleKey: result.moduleKey,
10581
+ sourceAbsPath: result.sourceAbsPath
10582
+ });
10434
10583
  }
10435
- return { files, totalSize, perItemSizes };
10584
+ return { files, totalSize, perItemSizes, items };
10436
10585
  }
10437
10586
  };
10438
10587
 
@@ -10514,6 +10663,72 @@ function workflowError(message) {
10514
10663
  });
10515
10664
  }
10516
10665
 
10666
+ // src/import-closure.ts
10667
+ var import_path20 = require("path");
10668
+ var import_build_utils23 = require("@vercel/build-utils");
10669
+ var RUNTIME_BOOTSTRAP_MODULE = "vercel_runtime.vc_init";
10670
+ var IMPORT_CLOSURE_TIMEOUT_MS = 3e4;
10671
+ async function withTimeout(promise, ms, label) {
10672
+ let timer;
10673
+ const timeout = new Promise((resolvePromise) => {
10674
+ timer = setTimeout(() => {
10675
+ (0, import_build_utils23.debug)(`${label} timed out after ${ms}ms`);
10676
+ resolvePromise(void 0);
10677
+ }, ms);
10678
+ });
10679
+ try {
10680
+ return await Promise.race([promise, timeout]);
10681
+ } finally {
10682
+ clearTimeout(timer);
10683
+ }
10684
+ }
10685
+ function getImportClosureOptions({
10686
+ workPath,
10687
+ entrypoint,
10688
+ frameworkSeeds,
10689
+ extraPythonPath,
10690
+ subscriberDeclarations,
10691
+ subscribers,
10692
+ workflows,
10693
+ workflowMode,
10694
+ sitePackageDirs
10695
+ }) {
10696
+ const workerModules = [
10697
+ ...subscriberDeclarations.map((declaration) => declaration.moduleName),
10698
+ ...workflows.map((workflow) => workflow.moduleName)
10699
+ ];
10700
+ const generatedWorkerModules = [
10701
+ ...subscribers.map(
10702
+ (subscriber) => generatedPythonPathToModule(
10703
+ getGeneratedQueueHandlerPath(getSubscriberOutputPath(subscriber.name))
10704
+ )
10705
+ ),
10706
+ ...workflowMode === "queue" ? workflows.map(
10707
+ (workflow) => generatedPythonPathToModule(
10708
+ getGeneratedQueueHandlerPath(getWorkflowOutputPath(workflow.name))
10709
+ )
10710
+ ) : []
10711
+ ];
10712
+ return {
10713
+ seeds: [
10714
+ .../* @__PURE__ */ new Set([
10715
+ RUNTIME_BOOTSTRAP_MODULE,
10716
+ ...entrypoint ? [(0, import_path20.join)(workPath, entrypoint)] : [],
10717
+ ...frameworkSeeds,
10718
+ ...workerModules,
10719
+ ...generatedWorkerModules
10720
+ ])
10721
+ ],
10722
+ searchRoots: [
10723
+ .../* @__PURE__ */ new Set([
10724
+ ...extraPythonPath ? [extraPythonPath] : [],
10725
+ workPath,
10726
+ ...sitePackageDirs
10727
+ ])
10728
+ ]
10729
+ };
10730
+ }
10731
+
10517
10732
  // src/index.ts
10518
10733
  var writeFile = import_fs20.default.promises.writeFile;
10519
10734
  var PYTHON_ENTRYPOINT_DOCS_URL2 = "https://vercel.com/docs/functions/runtimes/python#python-entrypoints";
@@ -10535,9 +10750,9 @@ async function getDevSidecars({
10535
10750
  service
10536
10751
  }) {
10537
10752
  const framework = build2.config?.framework;
10538
- const isPyprojectEntrypoint = (0, import_path20.basename)(build2.src ?? "") === "pyproject.toml";
10539
- const isPyprojectService = service !== void 0 && (0, import_path20.basename)(service.entrypoint ?? "") === "pyproject.toml";
10540
- if (build2.config?.middleware === true || service !== void 0 && !isPyprojectService || service === void 0 && !isPyprojectEntrypoint && (typeof framework !== "string" || !(0, import_build_utils23.isPythonFramework)(framework))) {
10753
+ const isPyprojectEntrypoint = (0, import_path21.basename)(build2.src ?? "") === "pyproject.toml";
10754
+ const isPyprojectService = service !== void 0 && (0, import_path21.basename)(service.entrypoint ?? "") === "pyproject.toml";
10755
+ if (build2.config?.middleware === true || service !== void 0 && !isPyprojectService || service === void 0 && !isPyprojectEntrypoint && (typeof framework !== "string" || !(0, import_build_utils24.isPythonFramework)(framework))) {
10541
10756
  return [];
10542
10757
  }
10543
10758
  const legacyWorkers = await isLegacyWorkersProject(workPath);
@@ -10591,96 +10806,19 @@ function addFiles(target, source) {
10591
10806
  target[p] = f;
10592
10807
  }
10593
10808
  }
10594
- function addBytecodeWithinCapacity(files, bytecodeInfo, capacity) {
10595
- if (!bytecodeInfo || bytecodeInfo.totalSize <= 0 || capacity <= 0) {
10596
- return capacity;
10597
- }
10598
- if (bytecodeInfo.totalSize <= capacity) {
10599
- addFiles(files, bytecodeInfo.files);
10600
- return capacity - bytecodeInfo.totalSize;
10601
- }
10602
- const selected = lambdaKnapsack(bytecodeInfo.perItemSizes, capacity);
10603
- let remainingCapacity = capacity;
10604
- for (const p of selected) {
10605
- const file = bytecodeInfo.files[p];
10606
- if (!file)
10607
- continue;
10608
- files[p] = file;
10609
- remainingCapacity -= bytecodeInfo.perItemSizes.get(p) ?? 0;
10610
- }
10611
- return remainingCapacity;
10612
- }
10613
- async function addVendorBytecodeWithinCapacity({
10614
- files,
10615
- installedDistributions,
10616
- vendorDir,
10617
- bytecodeInfo,
10618
- capacity
10619
- }) {
10620
- if (!bytecodeInfo || bytecodeInfo.totalSize <= 0 || capacity <= 0) {
10621
- return capacity;
10622
- }
10623
- if (bytecodeInfo.totalSize <= capacity) {
10624
- addFiles(files, bytecodeInfo.files);
10625
- return capacity - bytecodeInfo.totalSize;
10626
- }
10627
- const selectedPkgs = lambdaKnapsack(bytecodeInfo.perItemSizes, capacity);
10628
- if (selectedPkgs.length === 0)
10629
- return capacity;
10630
- const selectedBytecode = await installedDistributions.collectBytecodeFiles({
10631
- vendorDirName: vendorDir,
10632
- includePackages: selectedPkgs
10633
- });
10634
- addFiles(files, selectedBytecode.files);
10635
- return capacity - selectedBytecode.totalSize;
10636
- }
10637
- async function addVendorBytecodeInTiers({
10638
- files,
10639
- installedDistributions,
10640
- vendorDir,
10641
- capacity,
10642
- vendorPackageTiers
10643
- }) {
10644
- let remainingCapacity = capacity;
10645
- for (const tier of vendorPackageTiers) {
10646
- if (remainingCapacity <= 0)
10647
- break;
10648
- if (tier && tier.length === 0)
10649
- continue;
10650
- const bytecodeInfo = await installedDistributions.collectBytecodeFiles({
10651
- vendorDirName: vendorDir,
10652
- includePackages: tier
10653
- });
10654
- remainingCapacity = await addVendorBytecodeWithinCapacity({
10655
- files,
10656
- installedDistributions,
10657
- vendorDir,
10658
- bytecodeInfo,
10659
- capacity: remainingCapacity
10660
- });
10809
+ function moduleKeysForClosurePaths(paths, workPath, sitePackageDirs) {
10810
+ const keys = /* @__PURE__ */ new Set();
10811
+ const roots = [...sitePackageDirs, workPath].map((r) => (0, import_path21.resolve)(r));
10812
+ for (const p of paths) {
10813
+ for (const root of roots) {
10814
+ const rel = (0, import_path21.relative)(root, p);
10815
+ if (rel && !rel.startsWith("..") && !(0, import_path21.isAbsolute)(rel)) {
10816
+ keys.add(rel.split(import_path21.sep).join("/"));
10817
+ break;
10818
+ }
10819
+ }
10661
10820
  }
10662
- return remainingCapacity;
10663
- }
10664
- async function addCollectedVendorBytecode({
10665
- files,
10666
- capacity,
10667
- collect
10668
- }) {
10669
- if (capacity <= 0)
10670
- return capacity;
10671
- const info = await collect(void 0);
10672
- if (!info || info.totalSize <= 0)
10673
- return capacity;
10674
- if (info.totalSize <= capacity) {
10675
- addFiles(files, info.files);
10676
- return capacity - info.totalSize;
10677
- }
10678
- const selected = lambdaKnapsack(info.perItemSizes, capacity);
10679
- if (selected.length === 0)
10680
- return capacity;
10681
- const selectedInfo = await collect(selected);
10682
- addFiles(files, selectedInfo.files);
10683
- return capacity - selectedInfo.totalSize;
10821
+ return keys;
10684
10822
  }
10685
10823
  async function runFrameworkHook(framework, ctx) {
10686
10824
  const hook = framework ? frameworkHooks[framework] : void 0;
@@ -10695,13 +10833,13 @@ var frameworkHooks = {
10695
10833
  }) => {
10696
10834
  let baseDir = detected?.baseDir;
10697
10835
  if (baseDir === void 0) {
10698
- if (!import_fs20.default.existsSync((0, import_path20.join)(workPath, "manage.py"))) {
10699
- (0, import_build_utils23.debug)("Django hook: no manage.py detected, skipping");
10836
+ if (!import_fs20.default.existsSync((0, import_path21.join)(workPath, "manage.py"))) {
10837
+ (0, import_build_utils24.debug)("Django hook: no manage.py detected, skipping");
10700
10838
  return;
10701
10839
  }
10702
10840
  baseDir = "";
10703
10841
  }
10704
- const djangoPath = (0, import_path20.join)(workPath, baseDir);
10842
+ const djangoPath = (0, import_path21.join)(workPath, baseDir);
10705
10843
  let settingsResult;
10706
10844
  try {
10707
10845
  settingsResult = await getDjangoSettings(djangoPath, pythonEnv);
@@ -10713,13 +10851,13 @@ Hint: activate a venv or run with \`uv run vercel dev\``;
10713
10851
  } else {
10714
10852
  detail = err?.stderr || err?.message || String(err);
10715
10853
  }
10716
- throw new import_build_utils23.NowBuildError({
10854
+ throw new import_build_utils24.NowBuildError({
10717
10855
  code: "DJANGO_SETTINGS_FAILED",
10718
10856
  message: `Failed to read Django application settings from ${djangoPath}/manage.py:
10719
10857
  ${detail}`
10720
10858
  });
10721
10859
  }
10722
- (0, import_build_utils23.debug)(`Django settings: ${JSON.stringify(settingsResult)}`);
10860
+ (0, import_build_utils24.debug)(`Django settings: ${JSON.stringify(settingsResult)}`);
10723
10861
  const { djangoSettings, settingsModule, djangoVersion } = settingsResult;
10724
10862
  if (djangoVersion) {
10725
10863
  console.log(`Django ${djangoVersion.join(".")} detected`);
@@ -10731,7 +10869,7 @@ ${detail}`
10731
10869
  const variableName = parts.at(-1);
10732
10870
  const rel = `${parts.slice(0, -1).join("/")}.py`;
10733
10871
  const ep = baseDir ? `${baseDir}/${rel}` : rel;
10734
- (0, import_build_utils23.debug)(`Django hook: ASGI entrypoint: ${ep} (variable: ${variableName})`);
10872
+ (0, import_build_utils24.debug)(`Django hook: ASGI entrypoint: ${ep} (variable: ${variableName})`);
10735
10873
  resolvedEntrypoint = { entrypoint: ep, variableName };
10736
10874
  } else {
10737
10875
  const wsgiApp = djangoSettings["WSGI_APPLICATION"];
@@ -10740,7 +10878,7 @@ ${detail}`
10740
10878
  const variableName = parts.at(-1);
10741
10879
  const rel = `${parts.slice(0, -1).join("/")}.py`;
10742
10880
  const ep = baseDir ? `${baseDir}/${rel}` : rel;
10743
- (0, import_build_utils23.debug)(
10881
+ (0, import_build_utils24.debug)(
10744
10882
  `Django hook: WSGI entrypoint: ${ep} (variable: ${variableName})`
10745
10883
  );
10746
10884
  resolvedEntrypoint = { entrypoint: ep, variableName };
@@ -10748,7 +10886,7 @@ ${detail}`
10748
10886
  }
10749
10887
  let djangoStatic = null;
10750
10888
  if (workPath && venvPath) {
10751
- const outputStaticDir = (0, import_path20.join)(workPath, ".vercel", "output", "static");
10889
+ const outputStaticDir = (0, import_path21.join)(workPath, ".vercel", "output", "static");
10752
10890
  djangoStatic = await runDjangoCollectStatic(
10753
10891
  venvPath,
10754
10892
  workPath,
@@ -10760,10 +10898,17 @@ ${detail}`
10760
10898
  djangoVersion
10761
10899
  );
10762
10900
  }
10901
+ const importSeeds = [
10902
+ settingsModule,
10903
+ djangoSettings["ROOT_URLCONF"],
10904
+ ...djangoSettings["INSTALLED_APPS"] ?? [],
10905
+ ...djangoSettings["MIDDLEWARE"] ?? []
10906
+ ].filter((s) => typeof s === "string");
10763
10907
  return {
10764
10908
  entrypoint: resolvedEntrypoint,
10765
10909
  djangoStatic,
10766
- extraPythonPath: baseDir ? (0, import_path20.join)(workPath, baseDir) : void 0
10910
+ importSeeds,
10911
+ extraPythonPath: baseDir ? (0, import_path21.join)(workPath, baseDir) : void 0
10767
10912
  };
10768
10913
  },
10769
10914
  fastapi: async ({
@@ -10774,27 +10919,27 @@ ${detail}`
10774
10919
  pyprojectData
10775
10920
  }) => {
10776
10921
  if (!detected?.entrypoint || !workPath || !venvPath) {
10777
- (0, import_build_utils23.debug)(
10922
+ (0, import_build_utils24.debug)(
10778
10923
  `FastAPI hook: skipping \u2014 detected.entrypoint=${JSON.stringify(detected?.entrypoint)}, workPath=${workPath}, venvPath=${venvPath}`
10779
10924
  );
10780
10925
  return;
10781
10926
  }
10782
10927
  const { entrypoint: entrypointRel, variableName } = detected.entrypoint;
10783
- (0, import_build_utils23.debug)(
10928
+ (0, import_build_utils24.debug)(
10784
10929
  `FastAPI hook: entrypoint=${entrypointRel}, variableName=${variableName}`
10785
10930
  );
10786
- const entrypointAbs = (0, import_path20.join)(workPath, entrypointRel);
10787
- const outputStaticDir = (0, import_path20.join)(workPath, ".vercel", "output", "static");
10931
+ const entrypointAbs = (0, import_path21.join)(workPath, entrypointRel);
10932
+ const outputStaticDir = (0, import_path21.join)(workPath, ".vercel", "output", "static");
10788
10933
  const cdnEnv = process.env.VERCEL_FASTAPI_STATIC_CDN?.toLowerCase();
10789
10934
  if (cdnEnv !== "1" && cdnEnv !== "true") {
10790
- (0, import_build_utils23.debug)(
10935
+ (0, import_build_utils24.debug)(
10791
10936
  "FastAPI: VERCEL_FASTAPI_STATIC_CDN not set, skipping static CDN collection"
10792
10937
  );
10793
10938
  return;
10794
10939
  }
10795
10940
  const staticCdn = pyprojectData?.tool?.vercel?.fastapi?.static?.cdn;
10796
10941
  if (staticCdn === false) {
10797
- (0, import_build_utils23.debug)(
10942
+ (0, import_build_utils24.debug)(
10798
10943
  "FastAPI: static.cdn = false in pyproject.toml, skipping CDN collection"
10799
10944
  );
10800
10945
  return;
@@ -10867,23 +11012,23 @@ async function downloadFilesInWorkPath({
10867
11012
  files,
10868
11013
  meta = {}
10869
11014
  }) {
10870
- (0, import_build_utils23.debug)("Downloading user files...");
10871
- let downloadedFiles = await (0, import_build_utils23.download)(files, workPath, meta);
11015
+ (0, import_build_utils24.debug)("Downloading user files...");
11016
+ let downloadedFiles = await (0, import_build_utils24.download)(files, workPath, meta);
10872
11017
  if (meta.isDev && entrypoint) {
10873
11018
  const normalizedEntrypoint = entrypoint.endsWith(".py") ? entrypoint : `${entrypoint}.py`;
10874
11019
  if (!hasProp(downloadedFiles, entrypoint) && !hasProp(downloadedFiles, normalizedEntrypoint)) {
10875
- throw new import_build_utils23.NowBuildError({
11020
+ throw new import_build_utils24.NowBuildError({
10876
11021
  code: "PYTHON_ENTRYPOINT_NOT_FOUND",
10877
11022
  message: `Configured Python entrypoint "${normalizedEntrypoint}" was not found.`,
10878
11023
  link: PYTHON_ENTRYPOINT_DOCS_URL2,
10879
11024
  action: "Learn More"
10880
11025
  });
10881
11026
  }
10882
- const { devCacheDir = (0, import_path20.join)(workPath, ".now", "cache") } = meta;
10883
- const cacheKey = (0, import_path20.basename)(entrypoint).replace(/\./g, "_");
10884
- const destCache = (0, import_path20.join)(devCacheDir, cacheKey);
10885
- await (0, import_build_utils23.download)(downloadedFiles, destCache);
10886
- downloadedFiles = await (0, import_build_utils23.glob)("**", destCache);
11027
+ const { devCacheDir = (0, import_path21.join)(workPath, ".now", "cache") } = meta;
11028
+ const cacheKey = (0, import_path21.basename)(entrypoint).replace(/\./g, "_");
11029
+ const destCache = (0, import_path21.join)(devCacheDir, cacheKey);
11030
+ await (0, import_build_utils24.download)(downloadedFiles, destCache);
11031
+ downloadedFiles = await (0, import_build_utils24.glob)("**", destCache);
10887
11032
  workPath = destCache;
10888
11033
  }
10889
11034
  return workPath;
@@ -10919,7 +11064,7 @@ async function getPythonLambdaOptions({
10919
11064
  sources.add(entrypoint.slice(0, -".py".length));
10920
11065
  }
10921
11066
  for (const sourceFile of sources) {
10922
- const lambdaOptions = await (0, import_build_utils23.getLambdaOptionsFromFunction)({
11067
+ const lambdaOptions = await (0, import_build_utils24.getLambdaOptionsFromFunction)({
10923
11068
  sourceFile,
10924
11069
  config
10925
11070
  });
@@ -10940,11 +11085,11 @@ async function installInjectedPackage({
10940
11085
  projectDir,
10941
11086
  pipPlatformArgs
10942
11087
  }) {
10943
- const localDir = (0, import_path20.join)(__dirname, "..", "..", "..", "python", name);
10944
- const isLocalDev = allowLocalSource && import_fs20.default.existsSync((0, import_path20.join)(localDir, "pyproject.toml"));
11088
+ const localDir = (0, import_path21.join)(__dirname, "..", "..", "..", "python", name);
11089
+ const isLocalDev = allowLocalSource && import_fs20.default.existsSync((0, import_path21.join)(localDir, "pyproject.toml"));
10945
11090
  const dep = envOverride || (isLocalDev ? localDir : requirement);
10946
11091
  const noExclude = ["--exclude-newer-package", `${name}=false`];
10947
- (0, import_build_utils23.debug)(`Installing ${dep}`);
11092
+ (0, import_build_utils24.debug)(`Installing ${dep}`);
10948
11093
  await uv.pip({
10949
11094
  venvPath,
10950
11095
  projectDir,
@@ -10970,14 +11115,14 @@ var build = async ({
10970
11115
  registerPreDeploy
10971
11116
  }) => {
10972
11117
  let entrypoint = rawEntrypoint === "<detect>" ? void 0 : rawEntrypoint;
10973
- const isPyprojectEntrypoint = entrypoint !== void 0 && (0, import_path20.basename)(entrypoint) === "pyproject.toml";
11118
+ const isPyprojectEntrypoint = entrypoint !== void 0 && (0, import_path21.basename)(entrypoint) === "pyproject.toml";
10974
11119
  if (isPyprojectEntrypoint && entrypoint !== "pyproject.toml") {
10975
- throw new import_build_utils23.NowBuildError({
11120
+ throw new import_build_utils24.NowBuildError({
10976
11121
  code: "PYTHON_INVALID_PYPROJECT_ENTRYPOINT",
10977
- message: `A "pyproject.toml" entrypoint must sit at the service root. Set the service "root" to "${(0, import_path20.dirname)(entrypoint)}" and use entrypoint "pyproject.toml".`
11122
+ message: `A "pyproject.toml" entrypoint must sit at the service root. Set the service "root" to "${(0, import_path21.dirname)(entrypoint)}" and use entrypoint "pyproject.toml".`
10978
11123
  });
10979
11124
  }
10980
- const builderSpan = parentSpan ?? new import_build_utils23.Span({ name: "vc.builder" });
11125
+ const builderSpan = parentSpan ?? new import_build_utils24.Span({ name: "vc.builder" });
10981
11126
  const framework = config?.framework;
10982
11127
  let subscriberDeclarations = [];
10983
11128
  let subscribers = [];
@@ -10988,7 +11133,7 @@ var build = async ({
10988
11133
  let projectInstallCommand;
10989
11134
  let hasCustomCommand = false;
10990
11135
  const target = getTargetPlatform(meta.isDev ?? false);
10991
- (0, import_build_utils23.debug)(`workPath: ${workPath}`);
11136
+ (0, import_build_utils24.debug)(`workPath: ${workPath}`);
10992
11137
  workPath = await downloadFilesInWorkPath({
10993
11138
  workPath,
10994
11139
  files: originalFiles,
@@ -10996,7 +11141,7 @@ var build = async ({
10996
11141
  meta
10997
11142
  });
10998
11143
  legacyWorkersProject = await isLegacyWorkersProject(workPath);
10999
- if (isPyprojectEntrypoint || !service && (0, import_build_utils23.isPythonFramework)(framework)) {
11144
+ if (isPyprojectEntrypoint || !service && (0, import_build_utils24.isPythonFramework)(framework)) {
11000
11145
  subscriberDeclarations = await getPyprojectSubscribers(workPath, {
11001
11146
  legacySchema: legacyWorkersProject
11002
11147
  });
@@ -11004,7 +11149,7 @@ var build = async ({
11004
11149
  }
11005
11150
  try {
11006
11151
  if (meta.isDev) {
11007
- const setupCfg = (0, import_path20.join)(workPath, "setup.cfg");
11152
+ const setupCfg = (0, import_path21.join)(workPath, "setup.cfg");
11008
11153
  await writeFile(setupCfg, "[install]\nprefix=\n");
11009
11154
  }
11010
11155
  } catch (err) {
@@ -11018,7 +11163,7 @@ var build = async ({
11018
11163
  if (declared) {
11019
11164
  detected = { entrypoint: declared };
11020
11165
  } else if (subscriberDeclarations.length === 0 && workflows.length === 0) {
11021
- throw new import_build_utils23.NowBuildError({
11166
+ throw new import_build_utils24.NowBuildError({
11022
11167
  code: "PYTHON_PYPROJECT_NOTHING_TO_BUILD",
11023
11168
  message: 'Entrypoint "pyproject.toml" declares nothing to build. Set "tool.vercel.entrypoint" for a web app and/or declare "[[tool.vercel.subscribers]]" or "[[tool.vercel.workflows]]" entries in pyproject.toml.'
11024
11169
  });
@@ -11032,7 +11177,7 @@ var build = async ({
11032
11177
  filePath: entrypoint,
11033
11178
  // For schedule-triggered jobs, the WSGI variable is always 'app' (created dynamically).
11034
11179
  // For other services, handlerFunction is used as the entrypoint variable name.
11035
- varName: service && (0, import_build_utils23.isScheduleTriggeredService)(service) ? void 0 : handlerFunction
11180
+ varName: service && (0, import_build_utils24.isScheduleTriggeredService)(service) ? void 0 : handlerFunction
11036
11181
  } : void 0,
11037
11182
  service,
11038
11183
  repoRootPath
@@ -11041,8 +11186,8 @@ var build = async ({
11041
11186
  if (detected?.error && detected?.baseDir === void 0) {
11042
11187
  throw detected?.error;
11043
11188
  }
11044
- const entryDirectory = detected?.baseDir ?? (entrypoint ? (0, import_path20.dirname)(entrypoint) : ".");
11045
- const entrypointAbsDir = (0, import_path20.join)(workPath, entryDirectory);
11189
+ const entryDirectory = detected?.baseDir ?? (entrypoint ? (0, import_path21.dirname)(entrypoint) : ".");
11190
+ const entrypointAbsDir = (0, import_path21.join)(workPath, entryDirectory);
11046
11191
  const rootDir = repoRootPath ?? workPath;
11047
11192
  const pythonPackage = await builderSpan.child("vc.builder.python.discover").trace(
11048
11193
  () => discoverPackage({
@@ -11083,12 +11228,12 @@ var build = async ({
11083
11228
  }
11084
11229
  const uvVersion = checkUvBinaryVersion(uv.getPath());
11085
11230
  console.log(`Using ${uvVersion}`);
11086
- const venvPath = service?.name ? (0, import_path20.join)(workPath, ".vercel", "python", "services", service.name, ".venv") : (0, import_path20.join)(workPath, ".vercel", "python", ".venv");
11087
- const hasCachedVenv = import_fs20.default.existsSync((0, import_path20.join)(venvPath, "pyvenv.cfg"));
11231
+ const venvPath = service?.name ? (0, import_path21.join)(workPath, ".vercel", "python", "services", service.name, ".venv") : (0, import_path21.join)(workPath, ".vercel", "python", ".venv");
11232
+ const hasCachedVenv = import_fs20.default.existsSync((0, import_path21.join)(venvPath, "pyvenv.cfg"));
11088
11233
  const hasCachedUv = import_fs20.default.existsSync(uvCacheDir);
11089
11234
  const restoredCache = hasCachedVenv && hasCachedUv ? "both" : hasCachedVenv ? "venv" : hasCachedUv ? "uv" : "none";
11090
11235
  if (hasCachedVenv || hasCachedUv) {
11091
- (0, import_build_utils23.debug)(
11236
+ (0, import_build_utils24.debug)(
11092
11237
  `Build cache detected: venv=${hasCachedVenv}, uv-cache=${hasCachedUv}`
11093
11238
  );
11094
11239
  }
@@ -11100,14 +11245,14 @@ var build = async ({
11100
11245
  uvCacheDir
11101
11246
  });
11102
11247
  });
11103
- if ((0, import_build_utils23.isPythonFramework)(framework)) {
11248
+ if ((0, import_build_utils24.isPythonFramework)(framework)) {
11104
11249
  const {
11105
11250
  cliType,
11106
11251
  lockfileVersion,
11107
11252
  packageJsonPackageManager,
11108
11253
  turboSupportsCorepackHome
11109
- } = await (0, import_build_utils23.scanParentDirs)(workPath, true);
11110
- spawnEnv = (0, import_build_utils23.getEnvForPackageManager)({
11254
+ } = await (0, import_build_utils24.scanParentDirs)(workPath, true);
11255
+ spawnEnv = (0, import_build_utils24.getEnvForPackageManager)({
11111
11256
  cliType,
11112
11257
  lockfileVersion,
11113
11258
  packageJsonPackageManager,
@@ -11133,7 +11278,7 @@ var build = async ({
11133
11278
  let uvProjectDir = null;
11134
11279
  let projectName;
11135
11280
  let usedUvManagedInstall = false;
11136
- await builderSpan.child(import_build_utils23.BUILDER_INSTALLER_STEP, {
11281
+ await builderSpan.child(import_build_utils24.BUILDER_INSTALLER_STEP, {
11137
11282
  installCommand: projectInstallCommand || void 0,
11138
11283
  runtime: "python",
11139
11284
  "python.cache.restored": restoredCache
@@ -11150,7 +11295,7 @@ var build = async ({
11150
11295
  console.log(
11151
11296
  `Running "install" command: \`${projectInstallCommand}\`...`
11152
11297
  );
11153
- await (0, import_build_utils23.execCommand)(projectInstallCommand, {
11298
+ await (0, import_build_utils24.execCommand)(projectInstallCommand, {
11154
11299
  env: pythonEnv,
11155
11300
  cwd: workPath
11156
11301
  });
@@ -11171,7 +11316,7 @@ var build = async ({
11171
11316
  }
11172
11317
  if (!assumeDepsInstalled) {
11173
11318
  const lockCacheKey = service?.name ? `uv.lock.${service.name}` : "uv.lock";
11174
- const cachedLockPath = (0, import_path20.join)(uvCacheDir, lockCacheKey);
11319
+ const cachedLockPath = (0, import_path21.join)(uvCacheDir, lockCacheKey);
11175
11320
  const { projectDir, lockPath, lockFileProvidedByUser } = await ensureUvProject({
11176
11321
  workPath,
11177
11322
  rootDir,
@@ -11199,15 +11344,15 @@ var build = async ({
11199
11344
  }
11200
11345
  }
11201
11346
  });
11202
- if ((0, import_build_utils23.isPythonFramework)(framework)) {
11347
+ if ((0, import_build_utils24.isPythonFramework)(framework)) {
11203
11348
  const projectBuildCommand = config?.projectSettings?.buildCommand ?? // fallback if provided directly on config (some callers set this)
11204
11349
  config?.buildCommand;
11205
- await builderSpan.child(import_build_utils23.BUILDER_COMPILE_STEP, {
11350
+ await builderSpan.child(import_build_utils24.BUILDER_COMPILE_STEP, {
11206
11351
  buildCommand: projectBuildCommand || void 0
11207
11352
  }).trace(async () => {
11208
11353
  if (projectBuildCommand) {
11209
11354
  console.log(`Running "${projectBuildCommand}"`);
11210
- await (0, import_build_utils23.execCommand)(projectBuildCommand, {
11355
+ await (0, import_build_utils24.execCommand)(projectBuildCommand, {
11211
11356
  env: pythonEnv,
11212
11357
  cwd: workPath
11213
11358
  });
@@ -11235,13 +11380,14 @@ var build = async ({
11235
11380
  entrypoint = resolved?.entrypoint;
11236
11381
  const isWorkersOnly = !entrypoint && isPyprojectEntrypoint && (subscriberDeclarations.length > 0 || workflows.length > 0);
11237
11382
  if (!entrypoint && !isWorkersOnly) {
11238
- throw new import_build_utils23.NowBuildError({
11383
+ throw new import_build_utils24.NowBuildError({
11239
11384
  code: "PYTHON_ENTRYPOINT_NOT_FOUND",
11240
11385
  message: "No Python entrypoint could be detected. Please specify an entrypoint file."
11241
11386
  });
11242
11387
  }
11243
11388
  const djangoStatic = hookResult?.djangoStatic ?? null;
11244
11389
  const fastapiStatic = hookResult?.fastapiStatic ?? null;
11390
+ const importSeeds = hookResult?.importSeeds ?? [];
11245
11391
  const cdnOutputDir = djangoStatic?.cdnOutputDir ?? fastapiStatic?.cdnOutputDir ?? null;
11246
11392
  const pipPlatformArgs = target.uvPlatform ? ["--python-platform", target.uvPlatform] : [];
11247
11393
  await installInjectedPackage({
@@ -11251,7 +11397,7 @@ var build = async ({
11251
11397
  allowLocalSource: true,
11252
11398
  uv,
11253
11399
  venvPath,
11254
- projectDir: (0, import_path20.join)(workPath, entryDirectory),
11400
+ projectDir: (0, import_path21.join)(workPath, entryDirectory),
11255
11401
  pipPlatformArgs
11256
11402
  });
11257
11403
  const conditionalInjectedPackages = usedUvManagedInstall && !legacyWorkersProject ? await getConditionalInjectedPackages({
@@ -11263,7 +11409,7 @@ var build = async ({
11263
11409
  ...injectedPackage,
11264
11410
  uv,
11265
11411
  venvPath,
11266
- projectDir: (0, import_path20.join)(workPath, entryDirectory),
11412
+ projectDir: (0, import_path21.join)(workPath, entryDirectory),
11267
11413
  pipPlatformArgs
11268
11414
  });
11269
11415
  }
@@ -11272,7 +11418,7 @@ var build = async ({
11272
11418
  pythonPackage,
11273
11419
  uv,
11274
11420
  venvPath,
11275
- projectDir: (0, import_path20.join)(workPath, entryDirectory),
11421
+ projectDir: (0, import_path21.join)(workPath, entryDirectory),
11276
11422
  uvLockPath
11277
11423
  });
11278
11424
  }
@@ -11285,7 +11431,7 @@ var build = async ({
11285
11431
  allowLocalSource: true,
11286
11432
  uv,
11287
11433
  venvPath,
11288
- projectDir: (0, import_path20.join)(workPath, entryDirectory),
11434
+ projectDir: (0, import_path21.join)(workPath, entryDirectory),
11289
11435
  pipPlatformArgs
11290
11436
  });
11291
11437
  }
@@ -11296,11 +11442,11 @@ var build = async ({
11296
11442
  const queueIntegrations = legacyWorkersProject ? [] : await getQueueIntegrations({ pythonPackage });
11297
11443
  const writeGeneratedQueueHandler = async (outputPath, declaration) => {
11298
11444
  const generatedPath = getGeneratedQueueHandlerPath(outputPath);
11299
- await import_fs20.default.promises.mkdir((0, import_path20.dirname)((0, import_path20.join)(workPath, generatedPath)), {
11445
+ await import_fs20.default.promises.mkdir((0, import_path21.dirname)((0, import_path21.join)(workPath, generatedPath)), {
11300
11446
  recursive: true
11301
11447
  });
11302
11448
  await import_fs20.default.promises.writeFile(
11303
- (0, import_path20.join)(workPath, generatedPath),
11449
+ (0, import_path21.join)(workPath, generatedPath),
11304
11450
  createQueueHandlerModule(declaration, queueIntegrations)
11305
11451
  );
11306
11452
  };
@@ -11309,7 +11455,7 @@ var build = async ({
11309
11455
  declarations: subscriberDeclarations,
11310
11456
  uv,
11311
11457
  venvPath,
11312
- projectDir: (0, import_path20.join)(workPath, entryDirectory),
11458
+ projectDir: (0, import_path21.join)(workPath, entryDirectory),
11313
11459
  integrations: queueIntegrations
11314
11460
  });
11315
11461
  if (workflowMode === "queue") {
@@ -11340,7 +11486,7 @@ var build = async ({
11340
11486
  })),
11341
11487
  uv,
11342
11488
  venvPath,
11343
- projectDir: (0, import_path20.join)(workPath, entryDirectory),
11489
+ projectDir: (0, import_path21.join)(workPath, entryDirectory),
11344
11490
  kind: "workflow",
11345
11491
  integrations: queueIntegrations
11346
11492
  });
@@ -11357,11 +11503,11 @@ var build = async ({
11357
11503
  const capturedEnv = { ...pythonEnv };
11358
11504
  const capturedCwd = workPath;
11359
11505
  registerPreDeploy(async () => {
11360
- await builderSpan.child(import_build_utils23.BUILDER_PRE_DEPLOY_STEP, {
11506
+ await builderSpan.child(import_build_utils24.BUILDER_PRE_DEPLOY_STEP, {
11361
11507
  preDeployCommand
11362
11508
  }).trace(async () => {
11363
11509
  console.log(`Running pre-deploy command: \`${preDeployCommand}\``);
11364
- await (0, import_build_utils23.execCommand)(preDeployCommand, {
11510
+ await (0, import_build_utils24.execCommand)(preDeployCommand, {
11365
11511
  env: capturedEnv,
11366
11512
  cwd: capturedCwd
11367
11513
  });
@@ -11372,14 +11518,14 @@ var build = async ({
11372
11518
  let crons;
11373
11519
  let runtimeTrampoline;
11374
11520
  if (entrypoint) {
11375
- (0, import_build_utils23.debug)("Entrypoint is", entrypoint);
11521
+ (0, import_build_utils24.debug)("Entrypoint is", entrypoint);
11376
11522
  const moduleName = entrypointToModule(entrypoint);
11377
11523
  if (handlerFunction) {
11378
- const entrypointPath = (0, import_path20.join)(workPath, entrypoint);
11524
+ const entrypointPath = (0, import_path21.join)(workPath, entrypoint);
11379
11525
  const source = await import_fs20.default.promises.readFile(entrypointPath, "utf-8");
11380
11526
  const found = await (0, import_python_analysis12.containsTopLevelCallable)(source, handlerFunction);
11381
11527
  if (!found) {
11382
- throw new import_build_utils23.NowBuildError({
11528
+ throw new import_build_utils24.NowBuildError({
11383
11529
  code: "PYTHON_HANDLER_NOT_FOUND",
11384
11530
  message: `Handler function "${handlerFunction}" not found in ${entrypoint}. Ensure it is defined at the module's top level.`
11385
11531
  });
@@ -11387,7 +11533,7 @@ var build = async ({
11387
11533
  }
11388
11534
  const suffix = meta.isDev && !entrypoint.endsWith(".py") ? ".py" : "";
11389
11535
  const entrypointWithSuffix = `${entrypoint}${suffix}`;
11390
- (0, import_build_utils23.debug)("Entrypoint with suffix is", entrypointWithSuffix);
11536
+ (0, import_build_utils24.debug)("Entrypoint with suffix is", entrypointWithSuffix);
11391
11537
  crons = await getServiceCrons({
11392
11538
  service,
11393
11539
  entrypoint,
@@ -11453,17 +11599,17 @@ var build = async ({
11453
11599
  cwd: workPath,
11454
11600
  ignore: config && typeof config.excludeFiles === "string" ? [...predefinedExcludes, config.excludeFiles] : predefinedExcludes
11455
11601
  };
11456
- const files = await (0, import_build_utils23.glob)("**", globOptions);
11457
- const appPythonSourceFiles = Object.keys(files).filter((file) => file.endsWith(".py")).map((file) => (0, import_path20.join)(workPath, file)).sort();
11602
+ const files = await (0, import_build_utils24.glob)("**", globOptions);
11603
+ const appPythonSourceFiles = Object.keys(files).filter((file) => file.endsWith(".py")).map((file) => (0, import_path21.join)(workPath, file)).sort();
11458
11604
  if (djangoStatic?.manifestRelPath) {
11459
- files[djangoStatic.manifestRelPath] = new import_build_utils23.FileFsRef({
11460
- fsPath: (0, import_path20.join)(workPath, djangoStatic.manifestRelPath)
11605
+ files[djangoStatic.manifestRelPath] = new import_build_utils24.FileFsRef({
11606
+ fsPath: (0, import_path21.join)(workPath, djangoStatic.manifestRelPath)
11461
11607
  });
11462
11608
  }
11463
11609
  const handlerPyFilename = "vc__handler__python";
11464
11610
  if (config.framework === "fasthtml") {
11465
11611
  const { SESSKEY = "" } = process.env;
11466
- files[".sesskey"] = new import_build_utils23.FileBlob({ data: `"${SESSKEY}"` });
11612
+ files[".sesskey"] = new import_build_utils24.FileBlob({ data: `"${SESSKEY}"` });
11467
11613
  }
11468
11614
  await builderSpan.child("vc.builder.python.bundle").trace(async (bundleSpan) => {
11469
11615
  const installedDistributions = await InstalledPythonDistributions.load({
@@ -11504,15 +11650,17 @@ var build = async ({
11504
11650
  pycachePrefix
11505
11651
  }) => {
11506
11652
  if (!compileAllOptions)
11507
- return;
11653
+ return void 0;
11508
11654
  const vendorSourceFiles = installedDistributions.getPythonSourceFiles(includePackages);
11655
+ let timings;
11509
11656
  await builderSpan.child("vc.builder.python.compileall").trace(async (compileSpan) => {
11510
11657
  console.log("Compiling Python bytecode...");
11511
- await runCompileAll({
11658
+ const result = await runCompileAll({
11512
11659
  ...compileAllOptions,
11513
11660
  sourceFiles: [...appPythonSourceFiles, ...vendorSourceFiles],
11514
11661
  pycachePrefix
11515
11662
  });
11663
+ timings = result.timings;
11516
11664
  compileSpan.setAttributes({
11517
11665
  "python.compileall.enabled": "true",
11518
11666
  "python.compileall.appSourceFileCount": String(
@@ -11523,39 +11671,119 @@ var build = async ({
11523
11671
  )
11524
11672
  });
11525
11673
  });
11674
+ return timings;
11526
11675
  };
11527
- const runCompileAllAndFillBytecode = async (capacityBytes, vendorPackageTiers) => {
11528
- try {
11529
- await compileSources({
11530
- includePackages: vendorPackageTiers?.flat()
11531
- });
11532
- const currentSize = await calculateBundleSize(files);
11533
- let remainingCapacity = capacityBytes - currentSize;
11534
- if (pythonVersion.major != null && pythonVersion.minor != null) {
11535
- const appBytecodeInfo = await collectAppBytecodeFiles({
11676
+ let importClosurePromise;
11677
+ const getImportClosureKeys = () => {
11678
+ importClosurePromise ??= (async () => {
11679
+ try {
11680
+ const sitePackageDirs = installedDistributions.getSitePackageDirs();
11681
+ const closure = await withTimeout(
11682
+ (0, import_python_analysis12.collectImportClosure)(
11683
+ getImportClosureOptions({
11684
+ workPath,
11685
+ entrypoint,
11686
+ frameworkSeeds: importSeeds,
11687
+ extraPythonPath: hookResult?.extraPythonPath,
11688
+ subscriberDeclarations,
11689
+ subscribers,
11690
+ workflows,
11691
+ workflowMode,
11692
+ sitePackageDirs
11693
+ })
11694
+ ),
11695
+ IMPORT_CLOSURE_TIMEOUT_MS,
11696
+ "import closure"
11697
+ );
11698
+ if (!closure)
11699
+ return void 0;
11700
+ const keys = moduleKeysForClosurePaths(
11701
+ closure.files,
11536
11702
  workPath,
11537
- files,
11538
- pythonMajor: pythonVersion.major,
11539
- pythonMinor: pythonVersion.minor
11540
- });
11541
- remainingCapacity = addBytecodeWithinCapacity(
11542
- files,
11543
- appBytecodeInfo,
11544
- remainingCapacity
11703
+ sitePackageDirs
11704
+ );
11705
+ (0, import_build_utils24.debug)(
11706
+ `import closure: ${closure.files.size} files, ${keys.size} bundled modules` + (closure.truncated ? " (truncated)" : "")
11545
11707
  );
11708
+ return keys;
11709
+ } catch (err) {
11710
+ (0, import_build_utils24.debug)(
11711
+ `import closure unavailable, ranking by compile density only: ${err}`
11712
+ );
11713
+ return void 0;
11546
11714
  }
11547
- await addVendorBytecodeInTiers({
11715
+ })();
11716
+ return importClosurePromise;
11717
+ };
11718
+ const fillBytecodeWithValueRanking = async ({
11719
+ items,
11720
+ totalSize,
11721
+ capacity,
11722
+ timings
11723
+ }) => {
11724
+ if (totalSize <= 0 || capacity <= 0)
11725
+ return 0;
11726
+ if (totalSize <= capacity) {
11727
+ for (const item of items) {
11728
+ files[item.bundlePath] = item.file;
11729
+ }
11730
+ return totalSize;
11731
+ }
11732
+ return bundleSpan.child("vc.builder.python.bundle.optimize").trace(async (optimizeSpan) => {
11733
+ console.log("Optimizing Python bundle...");
11734
+ const analysisDisabled = isBytecodeAnalysisDisabled();
11735
+ if (analysisDisabled) {
11736
+ (0, import_build_utils24.debug)(
11737
+ "bytecode analysis disabled via VERCEL_PYTHON_DISABLE_BYTECODE_ANALYSIS; ranking by size"
11738
+ );
11739
+ }
11740
+ const importedModules = analysisDisabled ? void 0 : await getImportClosureKeys();
11741
+ const ranked = rankBytecodeItems(
11742
+ annotateBytecodeItems(
11743
+ items,
11744
+ importedModules,
11745
+ analysisDisabled ? void 0 : timings
11746
+ )
11747
+ );
11748
+ const selectedSize = capacity - fillBytecodeWithinCapacity(files, ranked, capacity);
11749
+ optimizeSpan.setAttributes({
11750
+ "python.bundle.optimize.bytecodeCoveragePercent": (selectedSize / totalSize * 100).toFixed(2)
11751
+ });
11752
+ return selectedSize;
11753
+ });
11754
+ };
11755
+ const runAdjacentCompileAndFill = async (capacityBytes, includePackages) => {
11756
+ try {
11757
+ const pyMajor = pythonVersion.major;
11758
+ const pyMinor = pythonVersion.minor;
11759
+ if (pyMajor == null || pyMinor == null)
11760
+ return;
11761
+ const timings = await compileSources({ includePackages });
11762
+ const currentSize = await calculateBundleSize(files);
11763
+ const remaining = capacityBytes - currentSize;
11764
+ if (remaining <= 0)
11765
+ return;
11766
+ const appInfo = await collectAppBytecodeFiles({
11767
+ workPath,
11548
11768
  files,
11549
- installedDistributions,
11550
- vendorDir,
11551
- capacity: remainingCapacity,
11552
- vendorPackageTiers: vendorPackageTiers ?? [void 0]
11769
+ pythonMajor: pyMajor,
11770
+ pythonMinor: pyMinor
11771
+ });
11772
+ const vendorInfo = await installedDistributions.collectBytecodeFiles({
11773
+ vendorDirName: vendorDir,
11774
+ includePackages
11775
+ });
11776
+ await fillBytecodeWithValueRanking({
11777
+ items: [...appInfo.items, ...vendorInfo.items],
11778
+ totalSize: appInfo.totalSize + vendorInfo.totalSize,
11779
+ capacity: remaining,
11780
+ timings
11553
11781
  });
11554
11782
  } catch (err) {
11555
11783
  console.log(
11556
11784
  "Bytecode precompilation failed; continuing without precompiled bytecode."
11557
11785
  );
11558
- (0, import_build_utils23.debug)(`bytecode precompilation error details: ${err}`);
11786
+ (0, import_build_utils24.debug)(`bytecode precompilation error details: ${err}`);
11559
11787
  }
11560
11788
  };
11561
11789
  const runPrefixCompileAndFill = async (bundleResult) => {
@@ -11565,25 +11793,27 @@ var build = async ({
11565
11793
  return;
11566
11794
  try {
11567
11795
  const currentSize = await calculateBundleSize(files);
11568
- let remainingCapacity = BYTECODE_FILL_CEILING_BYTES - currentSize;
11796
+ const remainingCapacity = BYTECODE_FILL_CEILING_BYTES - currentSize;
11569
11797
  if (remainingCapacity <= 0) {
11570
- (0, import_build_utils23.debug)(
11798
+ (0, import_build_utils24.debug)(
11571
11799
  `skipping bytecode precompilation: no zip capacity remaining (bundle is ${(currentSize / (1024 * 1024)).toFixed(2)} MB)`
11572
11800
  );
11573
11801
  return;
11574
11802
  }
11575
- const stagingDir = (0, import_path20.join)(workPath, ".vercel", "python", "pycache");
11803
+ const stagingDir = (0, import_path21.join)(workPath, ".vercel", "python", "pycache");
11576
11804
  await import_fs20.default.promises.rm(stagingDir, { recursive: true, force: true });
11577
11805
  await import_fs20.default.promises.mkdir(stagingDir, { recursive: true });
11578
- await compileSources({
11806
+ const alwaysBundled = bundleResult.alwaysBundledPackages ?? [];
11807
+ const bundledPublic = bundleResult.bundledPublicPackages ?? [];
11808
+ const externalized = bundleResult.externalizedPublicPackages ?? [];
11809
+ const timings = await compileSources({
11579
11810
  includePackages: [
11580
- ...bundleResult.alwaysBundledPackages ?? [],
11581
- ...bundleResult.bundledPublicPackages ?? [],
11582
- ...bundleResult.externalizedPublicPackages ?? []
11811
+ ...alwaysBundled,
11812
+ ...bundledPublic,
11813
+ ...externalized
11583
11814
  ],
11584
11815
  pycachePrefix: stagingDir
11585
11816
  });
11586
- const beforeCount = Object.keys(files).length;
11587
11817
  const appInfo = await collectAppPrefixBytecodeFiles({
11588
11818
  stagingDir,
11589
11819
  workPath,
@@ -11592,39 +11822,34 @@ var build = async ({
11592
11822
  pythonMajor: pyMajor,
11593
11823
  pythonMinor: pyMinor
11594
11824
  });
11595
- remainingCapacity = addBytecodeWithinCapacity(
11596
- files,
11597
- appInfo,
11598
- remainingCapacity
11599
- );
11600
- const alwaysBundled = bundleResult.alwaysBundledPackages ?? [];
11601
- remainingCapacity = await addCollectedVendorBytecode({
11602
- files,
11603
- capacity: remainingCapacity,
11604
- collect: (include) => installedDistributions.collectPrefixBytecodeFiles({
11605
- stagingDir,
11606
- runtimeRoot: `/var/task/${vendorDir}`,
11607
- includePackages: include ?? alwaysBundled
11608
- })
11825
+ const bundledVendorInfo = await installedDistributions.collectPrefixBytecodeFiles({
11826
+ stagingDir,
11827
+ runtimeRoot: `/var/task/${vendorDir}`,
11828
+ includePackages: [...alwaysBundled, ...bundledPublic]
11609
11829
  });
11610
- const externalized = bundleResult.externalizedPublicPackages ?? [];
11611
- await addCollectedVendorBytecode({
11612
- files,
11830
+ const externalizedInfo = await installedDistributions.collectPrefixBytecodeFiles({
11831
+ stagingDir,
11832
+ runtimeRoot: `${RUNTIME_DEPS_DIR}/lib/python${pyMajor}.${pyMinor}/site-packages`,
11833
+ includePackages: externalized
11834
+ });
11835
+ const bytesAdded = await fillBytecodeWithValueRanking({
11836
+ items: [
11837
+ ...appInfo.items,
11838
+ ...bundledVendorInfo.items,
11839
+ ...externalizedInfo.items
11840
+ ],
11841
+ totalSize: appInfo.totalSize + bundledVendorInfo.totalSize + externalizedInfo.totalSize,
11613
11842
  capacity: remainingCapacity,
11614
- collect: (include) => installedDistributions.collectPrefixBytecodeFiles({
11615
- stagingDir,
11616
- runtimeRoot: `${RUNTIME_DEPS_DIR}/lib/python${pyMajor}.${pyMinor}/site-packages`,
11617
- includePackages: include ?? externalized
11618
- })
11843
+ timings
11619
11844
  });
11620
- if (Object.keys(files).length > beforeCount) {
11845
+ if (bytesAdded > 0) {
11621
11846
  lambdaEnv.PYTHONPYCACHEPREFIX = RUNTIME_PYCACHE_PREFIX;
11622
11847
  }
11623
11848
  } catch (err) {
11624
11849
  console.log(
11625
11850
  "Bytecode precompilation failed; continuing without precompiled bytecode."
11626
11851
  );
11627
- (0, import_build_utils23.debug)(`bytecode precompilation error details: ${err}`);
11852
+ (0, import_build_utils24.debug)(`bytecode precompilation error details: ${err}`);
11628
11853
  }
11629
11854
  };
11630
11855
  const announceLargeFunction = () => console.log(
@@ -11641,9 +11866,7 @@ var build = async ({
11641
11866
  packingMode = "hive";
11642
11867
  announceLargeFunction();
11643
11868
  if (compileAllEnabled) {
11644
- await runCompileAllAndFillBytecode(
11645
- LARGE_FUNCTION_FILL_CEILING_BYTES
11646
- );
11869
+ await runAdjacentCompileAndFill(LARGE_FUNCTION_FILL_CEILING_BYTES);
11647
11870
  }
11648
11871
  } else if (bundleResult.packingMode === "bytecode-first") {
11649
11872
  await runPrefixCompileAndFill(bundleResult);
@@ -11651,12 +11874,12 @@ var build = async ({
11651
11874
  const currentSize = await calculateBundleSize(files);
11652
11875
  const capacity = BYTECODE_FILL_CEILING_BYTES - currentSize;
11653
11876
  if (capacity > 0) {
11654
- await runCompileAllAndFillBytecode(BYTECODE_FILL_CEILING_BYTES, [
11655
- bundleResult.alwaysBundledPackages ?? [],
11656
- bundleResult.bundledPublicPackages ?? []
11877
+ await runAdjacentCompileAndFill(BYTECODE_FILL_CEILING_BYTES, [
11878
+ ...bundleResult.alwaysBundledPackages ?? [],
11879
+ ...bundleResult.bundledPublicPackages ?? []
11657
11880
  ]);
11658
11881
  } else {
11659
- (0, import_build_utils23.debug)(
11882
+ (0, import_build_utils24.debug)(
11660
11883
  `skipping bytecode precompilation: no zip capacity remaining (bundle is ${(currentSize / (1024 * 1024)).toFixed(2)} MB)`
11661
11884
  );
11662
11885
  }
@@ -11669,18 +11892,16 @@ var build = async ({
11669
11892
  announceLargeFunction();
11670
11893
  }
11671
11894
  if (compileAllEnabled) {
11672
- await runCompileAllAndFillBytecode(
11673
- LARGE_FUNCTION_FILL_CEILING_BYTES
11674
- );
11895
+ await runAdjacentCompileAndFill(LARGE_FUNCTION_FILL_CEILING_BYTES);
11675
11896
  }
11676
11897
  } else {
11677
11898
  packingMode = "standard";
11678
11899
  if (compileAllEnabled) {
11679
11900
  const capacity = BYTECODE_FILL_CEILING_BYTES - depAnalysis.totalBundleSize;
11680
11901
  if (capacity > 0) {
11681
- await runCompileAllAndFillBytecode(BYTECODE_FILL_CEILING_BYTES);
11902
+ await runAdjacentCompileAndFill(BYTECODE_FILL_CEILING_BYTES);
11682
11903
  } else {
11683
- (0, import_build_utils23.debug)(
11904
+ (0, import_build_utils24.debug)(
11684
11905
  `skipping bytecode precompilation: no zip capacity remaining (bundle is ${(depAnalysis.totalBundleSize / (1024 * 1024)).toFixed(2)} MB)`
11685
11906
  );
11686
11907
  }
@@ -11698,13 +11919,13 @@ var build = async ({
11698
11919
  if (entrypoint && runtimeTrampoline) {
11699
11920
  const webFiles = {
11700
11921
  ...files,
11701
- [`${handlerPyFilename}.py`]: new import_build_utils23.FileBlob({ data: runtimeTrampoline })
11922
+ [`${handlerPyFilename}.py`]: new import_build_utils24.FileBlob({ data: runtimeTrampoline })
11702
11923
  };
11703
11924
  const lambdaOptions = await getPythonLambdaOptions({
11704
11925
  config,
11705
11926
  entrypoint
11706
11927
  });
11707
- output = new import_build_utils23.Lambda({
11928
+ output = new import_build_utils24.Lambda({
11708
11929
  files: webFiles,
11709
11930
  handler: `${handlerPyFilename}.vc_handler`,
11710
11931
  runtime: pythonVersion.runtime,
@@ -11733,10 +11954,10 @@ var build = async ({
11733
11954
  ...subscription.triggerDefaults
11734
11955
  })
11735
11956
  );
11736
- subscriberLambdas[outputPath] = new import_build_utils23.Lambda({
11957
+ subscriberLambdas[outputPath] = new import_build_utils24.Lambda({
11737
11958
  files: {
11738
11959
  ...files,
11739
- [`${handlerPyFilename}.py`]: new import_build_utils23.FileBlob({
11960
+ [`${handlerPyFilename}.py`]: new import_build_utils24.FileBlob({
11740
11961
  data: createRuntimeTrampoline({
11741
11962
  moduleName: generatedPythonPathToModule(generatedHandlerPath),
11742
11963
  entrypoint: generatedHandlerPath,
@@ -11766,10 +11987,10 @@ var build = async ({
11766
11987
  consumer,
11767
11988
  ...legacy.triggerDefaults
11768
11989
  }));
11769
- subscriberLambdas[outputPath] = new import_build_utils23.Lambda({
11990
+ subscriberLambdas[outputPath] = new import_build_utils24.Lambda({
11770
11991
  files: {
11771
11992
  ...files,
11772
- [`${handlerPyFilename}.py`]: new import_build_utils23.FileBlob({
11993
+ [`${handlerPyFilename}.py`]: new import_build_utils24.FileBlob({
11773
11994
  data: createRuntimeTrampoline({
11774
11995
  moduleName: declaration.moduleName,
11775
11996
  entrypoint: declaration.entrypoint,
@@ -11802,10 +12023,10 @@ var build = async ({
11802
12023
  ...subscription.triggerDefaults
11803
12024
  })
11804
12025
  );
11805
- workflowLambdas[outputPath] = new import_build_utils23.Lambda({
12026
+ workflowLambdas[outputPath] = new import_build_utils24.Lambda({
11806
12027
  files: {
11807
12028
  ...files,
11808
- [`${handlerPyFilename}.py`]: new import_build_utils23.FileBlob({
12029
+ [`${handlerPyFilename}.py`]: new import_build_utils24.FileBlob({
11809
12030
  data: createRuntimeTrampoline({
11810
12031
  moduleName: generatedPythonPathToModule(generatedHandlerPath),
11811
12032
  entrypoint: generatedHandlerPath,
@@ -11831,10 +12052,10 @@ var build = async ({
11831
12052
  consumer: getWorkflowConsumerName(workflow.name)
11832
12053
  }
11833
12054
  ];
11834
- workflowLambdas[outputPath] = new import_build_utils23.Lambda({
12055
+ workflowLambdas[outputPath] = new import_build_utils24.Lambda({
11835
12056
  files: {
11836
12057
  ...files,
11837
- [`${handlerPyFilename}.py`]: new import_build_utils23.FileBlob({
12058
+ [`${handlerPyFilename}.py`]: new import_build_utils24.FileBlob({
11838
12059
  data: createRuntimeTrampoline({
11839
12060
  moduleName: workflow.moduleName,
11840
12061
  entrypoint: workflow.entrypoint,
@@ -11859,21 +12080,21 @@ var build = async ({
11859
12080
  pythonVersion,
11860
12081
  uvLockPath,
11861
12082
  framework,
11862
- serviceType: service ? (0, import_build_utils23.getReportedServiceType)(service) : void 0
12083
+ serviceType: service ? (0, import_build_utils24.getReportedServiceType)(service) : void 0
11863
12084
  });
11864
12085
  } catch (err) {
11865
- (0, import_build_utils23.debug)(
12086
+ (0, import_build_utils24.debug)(
11866
12087
  `Failed to write project manifest: ${err instanceof Error ? err.message : String(err)}`
11867
12088
  );
11868
12089
  }
11869
12090
  }
11870
- if (!(0, import_build_utils23.isPythonFramework)(framework) && !service?.name && !isPyprojectEntrypoint) {
12091
+ if (!(0, import_build_utils24.isPythonFramework)(framework) && !service?.name && !isPyprojectEntrypoint) {
11871
12092
  (0, import_assert.default)(output, "web Lambda must exist for non-service builds");
11872
12093
  return { resultVersion: 3, result: { output } };
11873
12094
  }
11874
12095
  const frameworkLambdaName = framework ?? "python";
11875
12096
  const lambdaPath = service?.name && service.type ? `_svc/${service.name}/index` : frameworkLambdaName;
11876
- const staticFiles = cdnOutputDir ? await (0, import_build_utils23.glob)("**", { cwd: cdnOutputDir }) : {};
12097
+ const staticFiles = cdnOutputDir ? await (0, import_build_utils24.glob)("**", { cwd: cdnOutputDir }) : {};
11877
12098
  const isNonWebService = service?.name && service.type && service.type !== "web";
11878
12099
  const queueRoutes = queueRoutePaths.map((outputPath) => ({
11879
12100
  src: `/${outputPath}`,
@@ -11926,14 +12147,14 @@ var prepareCache = async ({
11926
12147
  }
11927
12148
  } catch {
11928
12149
  }
11929
- return (0, import_build_utils23.glob)("**/.vercel/python/{.venv,services/*/.venv,cache/uv}/**", {
12150
+ return (0, import_build_utils24.glob)("**/.vercel/python/{.venv,services/*/.venv,cache/uv}/**", {
11930
12151
  cwd: root,
11931
12152
  ignore
11932
12153
  });
11933
12154
  };
11934
12155
  var shouldServe = (opts) => {
11935
12156
  const framework = opts.config.framework;
11936
- if ((0, import_build_utils23.isPythonFramework)(framework)) {
12157
+ if ((0, import_build_utils24.isPythonFramework)(framework)) {
11937
12158
  const requestPath = opts.requestPath.replace(/\/$/, "");
11938
12159
  if (requestPath.startsWith("api") && opts.hasMatched) {
11939
12160
  return false;
@@ -11952,7 +12173,7 @@ var defaultShouldServe = ({
11952
12173
  if (entrypoint === requestPath && hasProp(files, entrypoint)) {
11953
12174
  return true;
11954
12175
  }
11955
- const { dir, name } = (0, import_path20.parse)(entrypoint);
12176
+ const { dir, name } = (0, import_path21.parse)(entrypoint);
11956
12177
  if (name === "index" && dir === requestPath && hasProp(files, entrypoint)) {
11957
12178
  return true;
11958
12179
  }
@@ -11963,8 +12184,6 @@ function hasProp(obj, key) {
11963
12184
  }
11964
12185
  // Annotate the CommonJS export names for ESM import in node:
11965
12186
  0 && (module.exports = {
11966
- addCollectedVendorBytecode,
11967
- addVendorBytecodeInTiers,
11968
12187
  build,
11969
12188
  defaultShouldServe,
11970
12189
  detectEntrypoint,
@@ -11973,6 +12192,7 @@ function hasProp(obj, key) {
11973
12192
  getDevSidecars,
11974
12193
  installRequirement,
11975
12194
  installRequirementsFile,
12195
+ moduleKeysForClosurePaths,
11976
12196
  prepareCache,
11977
12197
  runFrameworkHook,
11978
12198
  shouldServe,