@vercel/python 6.20.1 → 6.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -48,7 +48,7 @@ var require_windows = __commonJS({
48
48
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(exports, module2) {
49
49
  module2.exports = isexe;
50
50
  isexe.sync = sync;
51
- var fs8 = require("fs");
51
+ var fs9 = require("fs");
52
52
  function checkPathExt(path, options) {
53
53
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
54
54
  if (!pathext) {
@@ -73,12 +73,12 @@ var require_windows = __commonJS({
73
73
  return checkPathExt(path, options);
74
74
  }
75
75
  function isexe(path, options, cb) {
76
- fs8.stat(path, function(er, stat) {
76
+ fs9.stat(path, function(er, stat) {
77
77
  cb(er, er ? false : checkStat(stat, path, options));
78
78
  });
79
79
  }
80
80
  function sync(path, options) {
81
- return checkStat(fs8.statSync(path), path, options);
81
+ return checkStat(fs9.statSync(path), path, options);
82
82
  }
83
83
  }
84
84
  });
@@ -88,14 +88,14 @@ var require_mode = __commonJS({
88
88
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(exports, module2) {
89
89
  module2.exports = isexe;
90
90
  isexe.sync = sync;
91
- var fs8 = require("fs");
91
+ var fs9 = require("fs");
92
92
  function isexe(path, options, cb) {
93
- fs8.stat(path, function(er, stat) {
93
+ fs9.stat(path, function(er, stat) {
94
94
  cb(er, er ? false : checkStat(stat, options));
95
95
  });
96
96
  }
97
97
  function sync(path, options) {
98
- return checkStat(fs8.statSync(path), options);
98
+ return checkStat(fs9.statSync(path), options);
99
99
  }
100
100
  function checkStat(stat, options) {
101
101
  return stat.isFile() && checkMode(stat, options);
@@ -119,7 +119,7 @@ var require_mode = __commonJS({
119
119
  // ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
120
120
  var require_isexe = __commonJS({
121
121
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(exports, module2) {
122
- var fs8 = require("fs");
122
+ var fs9 = require("fs");
123
123
  var core;
124
124
  if (process.platform === "win32" || global.TESTING_WINDOWS) {
125
125
  core = require_windows();
@@ -395,7 +395,7 @@ var require_shebang_command = __commonJS({
395
395
  var require_readShebang = __commonJS({
396
396
  "../../node_modules/.pnpm/cross-spawn@6.0.5/node_modules/cross-spawn/lib/util/readShebang.js"(exports, module2) {
397
397
  "use strict";
398
- var fs8 = require("fs");
398
+ var fs9 = require("fs");
399
399
  var shebangCommand = require_shebang_command();
400
400
  function readShebang(command) {
401
401
  const size = 150;
@@ -408,9 +408,9 @@ var require_readShebang = __commonJS({
408
408
  }
409
409
  let fd;
410
410
  try {
411
- fd = fs8.openSync(command, "r");
412
- fs8.readSync(fd, buffer, 0, size, 0);
413
- fs8.closeSync(fd);
411
+ fd = fs9.openSync(command, "r");
412
+ fs9.readSync(fd, buffer, 0, size, 0);
413
+ fs9.closeSync(fd);
414
414
  } catch (e) {
415
415
  }
416
416
  return shebangCommand(buffer.toString());
@@ -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 debug10;
426
+ var debug11;
427
427
  if (typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
428
- debug10 = function() {
428
+ debug11 = 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
- debug10 = function() {
434
+ debug11 = 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
- debug10(i, src[i]);
543
+ debug11(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
- debug10("SemVer", version2, options);
610
+ debug11("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
- debug10("SemVer.compare", this.version, this.options, other);
657
+ debug11("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
- debug10("prerelease compare", i2, a, b);
684
+ debug11("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
- debug10("comparator", comp, options);
938
+ debug11("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
- debug10("comp", this);
947
+ debug11("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
- debug10("Comparator.test", version2, this.options.loose);
970
+ debug11("Comparator.test", version2, this.options.loose);
971
971
  if (this.semver === ANY) {
972
972
  return true;
973
973
  }
@@ -989,10 +989,10 @@ var require_semver = __commonJS({
989
989
  var rangeTmp;
990
990
  if (this.operator === "") {
991
991
  rangeTmp = new Range(comp.value, options);
992
- return satisfies2(this.value, rangeTmp, options);
992
+ return satisfies(this.value, rangeTmp, options);
993
993
  } else if (comp.operator === "") {
994
994
  rangeTmp = new Range(this.value, options);
995
- return satisfies2(comp.semver, rangeTmp, options);
995
+ return satisfies(comp.semver, rangeTmp, options);
996
996
  }
997
997
  var sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">");
998
998
  var sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<");
@@ -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
- debug10("hyphen replace", range);
1053
+ debug11("hyphen replace", range);
1054
1054
  range = range.replace(safeRe[COMPARATORTRIM], comparatorTrimReplace);
1055
- debug10("comparator trim", range, safeRe[COMPARATORTRIM]);
1055
+ debug11("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
- debug10("comp", comp, options);
1095
+ debug11("comp", comp, options);
1096
1096
  comp = replaceCarets(comp, options);
1097
- debug10("caret", comp);
1097
+ debug11("caret", comp);
1098
1098
  comp = replaceTildes(comp, options);
1099
- debug10("tildes", comp);
1099
+ debug11("tildes", comp);
1100
1100
  comp = replaceXRanges(comp, options);
1101
- debug10("xrange", comp);
1101
+ debug11("xrange", comp);
1102
1102
  comp = replaceStars(comp, options);
1103
- debug10("stars", comp);
1103
+ debug11("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
- debug10("tilde", comp, _, M, m, p, pr);
1117
+ debug11("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
- debug10("replaceTilde pr", pr);
1126
+ debug11("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
- debug10("tilde return", ret);
1131
+ debug11("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
- debug10("caret", comp, options);
1141
+ debug11("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
- debug10("caret", comp, _, M, m, p, pr);
1144
+ debug11("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
- debug10("replaceCaret pr", pr);
1157
+ debug11("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
- debug10("no pr");
1168
+ debug11("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
- debug10("caret return", ret);
1179
+ debug11("caret return", ret);
1180
1180
  return ret;
1181
1181
  });
1182
1182
  }
1183
1183
  function replaceXRanges(comp, options) {
1184
- debug10("replaceXRanges", comp, options);
1184
+ debug11("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
- debug10("xRange", comp, ret, gtlt, M, m, p, pr);
1193
+ debug11("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
- debug10("xRange return", ret);
1236
+ debug11("xRange return", ret);
1237
1237
  return ret;
1238
1238
  });
1239
1239
  }
1240
1240
  function replaceStars(comp, options) {
1241
- debug10("replaceStars", comp, options);
1241
+ debug11("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
- debug10(set[i2].semver);
1289
+ debug11(set[i2].semver);
1290
1290
  if (set[i2].semver === ANY) {
1291
1291
  continue;
1292
1292
  }
@@ -1301,8 +1301,8 @@ var require_semver = __commonJS({
1301
1301
  }
1302
1302
  return true;
1303
1303
  }
1304
- exports.satisfies = satisfies2;
1305
- function satisfies2(version2, range, options) {
1304
+ exports.satisfies = satisfies;
1305
+ function satisfies(version2, range, options) {
1306
1306
  try {
1307
1307
  range = new Range(range, options);
1308
1308
  } catch (er) {
@@ -1430,7 +1430,7 @@ var require_semver = __commonJS({
1430
1430
  default:
1431
1431
  throw new TypeError('Must provide a hilo val of "<" or ">"');
1432
1432
  }
1433
- if (satisfies2(version2, range, options)) {
1433
+ if (satisfies(version2, range, options)) {
1434
1434
  return false;
1435
1435
  }
1436
1436
  for (var i2 = 0; i2 < range.set.length; ++i2) {
@@ -1895,9 +1895,9 @@ var require_pump = __commonJS({
1895
1895
  "../../node_modules/.pnpm/pump@3.0.2/node_modules/pump/index.js"(exports, module2) {
1896
1896
  var once = require_once();
1897
1897
  var eos = require_end_of_stream();
1898
- var fs8;
1898
+ var fs9;
1899
1899
  try {
1900
- fs8 = require("fs");
1900
+ fs9 = require("fs");
1901
1901
  } catch (e) {
1902
1902
  }
1903
1903
  var noop = function() {
@@ -1909,9 +1909,9 @@ var require_pump = __commonJS({
1909
1909
  var isFS = function(stream) {
1910
1910
  if (!ancient)
1911
1911
  return false;
1912
- if (!fs8)
1912
+ if (!fs9)
1913
1913
  return false;
1914
- return (stream instanceof (fs8.ReadStream || noop) || stream instanceof (fs8.WriteStream || noop)) && isFn(stream.close);
1914
+ return (stream instanceof (fs9.ReadStream || noop) || stream instanceof (fs9.WriteStream || noop)) && isFn(stream.close);
1915
1915
  };
1916
1916
  var isRequest = function(stream) {
1917
1917
  return stream.setHeader && isFn(stream.abort);
@@ -2651,7 +2651,7 @@ ${stderr}${stdout}`;
2651
2651
  var require_lib = __commonJS({
2652
2652
  "../../node_modules/.pnpm/which@3.0.0/node_modules/which/lib/index.js"(exports, module2) {
2653
2653
  var isexe = require_isexe();
2654
- var { join: join10, delimiter: delimiter2, sep: sep2, posix } = require("path");
2654
+ var { join: join12, delimiter: delimiter2, sep: sep2, posix } = require("path");
2655
2655
  var isWindows = process.platform === "win32";
2656
2656
  var rSlash = new RegExp(`[${posix.sep}${sep2 === posix.sep ? "" : sep2}]`.replace(/(\\)/g, "\\$1"));
2657
2657
  var rRel = new RegExp(`^\\.${rSlash.source}`);
@@ -2680,7 +2680,7 @@ var require_lib = __commonJS({
2680
2680
  var getPathPart = (raw, cmd) => {
2681
2681
  const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw;
2682
2682
  const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : "";
2683
- return prefix + join10(pathPart, cmd);
2683
+ return prefix + join12(pathPart, cmd);
2684
2684
  };
2685
2685
  var which2 = async (cmd, opt = {}) => {
2686
2686
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
@@ -2862,28 +2862,29 @@ __export(src_exports, {
2862
2862
  downloadFilesInWorkPath: () => downloadFilesInWorkPath,
2863
2863
  installRequirement: () => installRequirement,
2864
2864
  installRequirementsFile: () => installRequirementsFile,
2865
+ prepareCache: () => prepareCache,
2866
+ runFrameworkHook: () => runFrameworkHook,
2865
2867
  shouldServe: () => shouldServe,
2866
2868
  startDevServer: () => startDevServer,
2867
2869
  version: () => version
2868
2870
  });
2869
2871
  module.exports = __toCommonJS(src_exports);
2870
- var import_fs8 = __toESM(require("fs"));
2871
- var import_util2 = require("util");
2872
- var import_path10 = require("path");
2872
+ var import_fs10 = __toESM(require("fs"));
2873
+ var import_path12 = require("path");
2873
2874
 
2874
2875
  // src/package-versions.ts
2875
- var VERCEL_RUNTIME_VERSION = "0.5.5";
2876
- var VERCEL_WORKERS_VERSION = "0.0.11";
2876
+ var VERCEL_RUNTIME_VERSION = "0.6.0";
2877
+ var VERCEL_WORKERS_VERSION = "0.0.12";
2877
2878
 
2878
2879
  // src/index.ts
2879
- var import_build_utils12 = require("@vercel/build-utils");
2880
+ var import_build_utils13 = require("@vercel/build-utils");
2880
2881
 
2881
2882
  // src/install.ts
2882
2883
  var import_execa3 = __toESM(require_execa());
2883
2884
  var import_fs3 = __toESM(require("fs"));
2884
- var import_path4 = require("path");
2885
+ var import_path5 = require("path");
2885
2886
  var import_build_utils4 = require("@vercel/build-utils");
2886
- var import_python_analysis = require("@vercel/python-analysis");
2887
+ var import_python_analysis2 = require("@vercel/python-analysis");
2887
2888
 
2888
2889
  // src/utils.ts
2889
2890
  var import_fs2 = __toESM(require("fs"));
@@ -2903,14 +2904,19 @@ var import_build_utils = require("@vercel/build-utils");
2903
2904
  var UV_VERSION = "0.9.22";
2904
2905
  var UV_PYTHON_PATH_PREFIX = "/uv/python/";
2905
2906
  var UV_PYTHON_DOWNLOADS_MODE = "automatic";
2907
+ var UV_CACHE_DIR_SUBPATH = [".vercel", "python", "cache", "uv"];
2906
2908
  var isWin = process.platform === "win32";
2907
2909
  var uvExec = isWin ? "uv.exe" : "uv";
2908
2910
  function findUvInPath() {
2909
2911
  return import_which.default.sync("uv", { nothrow: true });
2910
2912
  }
2913
+ function getUvCacheDir(workPath) {
2914
+ return (0, import_path.join)(workPath, ...UV_CACHE_DIR_SUBPATH);
2915
+ }
2911
2916
  var UvRunner = class {
2912
- constructor(uvPath) {
2917
+ constructor(uvPath, uvCacheDir) {
2913
2918
  this.uvPath = uvPath;
2919
+ this.uvCacheDir = uvCacheDir;
2914
2920
  }
2915
2921
  getPath() {
2916
2922
  return this.uvPath;
@@ -2987,7 +2993,7 @@ var UvRunner = class {
2987
2993
  try {
2988
2994
  await (0, import_execa.default)(this.uvPath, args, {
2989
2995
  cwd: projectDir,
2990
- env: getProtectedUvEnv(process.env)
2996
+ env: getProtectedUvEnv(process.env, this.uvCacheDir)
2991
2997
  });
2992
2998
  } catch (err) {
2993
2999
  const error = new Error(
@@ -3052,7 +3058,7 @@ var UvRunner = class {
3052
3058
  const binDir = isWin ? (0, import_path.join)(venvPath, "Scripts") : (0, import_path.join)(venvPath, "bin");
3053
3059
  const existingPath = process.env.PATH || "";
3054
3060
  return {
3055
- ...getProtectedUvEnv(process.env),
3061
+ ...getProtectedUvEnv(process.env, this.uvCacheDir),
3056
3062
  VIRTUAL_ENV: venvPath,
3057
3063
  PATH: existingPath ? `${binDir}${import_path2.delimiter}${existingPath}` : binDir
3058
3064
  };
@@ -3159,11 +3165,15 @@ async function getUvBinaryOrInstall(pythonPath) {
3159
3165
  function filterUnsafeUvPipArgs(args) {
3160
3166
  return args.filter((arg) => arg !== "--no-warn-script-location");
3161
3167
  }
3162
- function getProtectedUvEnv(baseEnv = process.env) {
3163
- return {
3168
+ function getProtectedUvEnv(baseEnv = process.env, uvCacheDir) {
3169
+ const env = {
3164
3170
  ...baseEnv,
3165
3171
  UV_PYTHON_DOWNLOADS: UV_PYTHON_DOWNLOADS_MODE
3166
3172
  };
3173
+ if (uvCacheDir) {
3174
+ env.UV_CACHE_DIR = uvCacheDir;
3175
+ }
3176
+ return env;
3167
3177
  }
3168
3178
  var UV_BUNDLE_DIR = "_uv";
3169
3179
  async function getUvBinaryForBundling(pythonPath) {
@@ -3202,9 +3212,9 @@ function useVirtualEnv(workPath, env, systemPython) {
3202
3212
  }
3203
3213
  return { pythonCmd };
3204
3214
  }
3205
- function createVenvEnv(venvPath, baseEnv = process.env) {
3215
+ function createVenvEnv(venvPath, baseEnv = process.env, uvCacheDir) {
3206
3216
  const env = {
3207
- ...getProtectedUvEnv(baseEnv),
3217
+ ...getProtectedUvEnv(baseEnv, uvCacheDir),
3208
3218
  VIRTUAL_ENV: venvPath
3209
3219
  };
3210
3220
  const binDir = getVenvBinDir(venvPath);
@@ -3216,6 +3226,7 @@ async function ensureVenv({
3216
3226
  pythonPath,
3217
3227
  venvPath,
3218
3228
  uvPath,
3229
+ uvCacheDir,
3219
3230
  quiet
3220
3231
  }) {
3221
3232
  const marker = (0, import_path3.join)(venvPath, "pyvenv.cfg");
@@ -3229,7 +3240,9 @@ async function ensureVenv({
3229
3240
  console.log(`Creating virtual environment at "${venvPath}"...`);
3230
3241
  }
3231
3242
  if (uvPath) {
3232
- await (0, import_execa2.default)(uvPath, ["venv", venvPath]);
3243
+ await (0, import_execa2.default)(uvPath, ["venv", venvPath], {
3244
+ env: getProtectedUvEnv(process.env, uvCacheDir)
3245
+ });
3233
3246
  } else {
3234
3247
  await (0, import_execa2.default)(pythonPath, ["-m", "venv", venvPath]);
3235
3248
  }
@@ -3269,72 +3282,41 @@ async function runPyprojectScript(workPath, scriptNames, env, useUserVirtualEnv
3269
3282
  }
3270
3283
  return false;
3271
3284
  }
3272
- function findDir({
3273
- file,
3274
- entryDirectory,
3275
- workPath,
3276
- fsFiles
3277
- }) {
3278
- if (fsFiles[(0, import_path3.join)(entryDirectory, file)]) {
3279
- return (0, import_path3.join)(workPath, entryDirectory);
3280
- }
3281
- if (fsFiles[file]) {
3282
- return workPath;
3283
- }
3284
- return null;
3285
- }
3286
3285
 
3287
3286
  // src/version.ts
3287
+ var import_path4 = require("path");
3288
3288
  var import_build_utils3 = require("@vercel/build-utils");
3289
- var DEFAULT_PYTHON_VERSION = "3.12";
3289
+ var import_python_analysis = require("@vercel/python-analysis");
3290
+ function pythonVersionString(pv) {
3291
+ return `${pv.major}.${pv.minor}`;
3292
+ }
3293
+ var DEFAULT_PYTHON_VERSION = makePythonVersion(3, 12);
3294
+ var DEFAULT_PYTHON_VERSION_STRING = pythonVersionString(
3295
+ DEFAULT_PYTHON_VERSION
3296
+ );
3297
+ function makePythonVersion(major, minor, discontinueDate) {
3298
+ return {
3299
+ major,
3300
+ minor,
3301
+ pipPath: `pip${major}.${minor}`,
3302
+ pythonPath: `python${major}.${minor}`,
3303
+ runtime: `python${major}.${minor}`,
3304
+ discontinueDate
3305
+ };
3306
+ }
3290
3307
  var allOptions = [
3291
- {
3292
- version: "3.14",
3293
- pipPath: "pip3.14",
3294
- pythonPath: "python3.14",
3295
- runtime: "python3.14"
3296
- },
3297
- {
3298
- version: "3.13",
3299
- pipPath: "pip3.13",
3300
- pythonPath: "python3.13",
3301
- runtime: "python3.13"
3302
- },
3303
- {
3304
- version: "3.12",
3305
- pipPath: "pip3.12",
3306
- pythonPath: "python3.12",
3307
- runtime: "python3.12"
3308
- },
3309
- {
3310
- version: "3.11",
3311
- pipPath: "pip3.11",
3312
- pythonPath: "python3.11",
3313
- runtime: "python3.11"
3314
- },
3315
- {
3316
- version: "3.10",
3317
- pipPath: "pip3.10",
3318
- pythonPath: "python3.10",
3319
- runtime: "python3.10"
3320
- },
3321
- {
3322
- version: "3.9",
3323
- pipPath: "pip3.9",
3324
- pythonPath: "python3.9",
3325
- runtime: "python3.9"
3326
- },
3327
- {
3328
- version: "3.6",
3329
- pipPath: "pip3.6",
3330
- pythonPath: "python3.6",
3331
- runtime: "python3.6",
3332
- discontinueDate: /* @__PURE__ */ new Date("2022-07-18")
3333
- }
3308
+ makePythonVersion(3, 14),
3309
+ makePythonVersion(3, 13),
3310
+ makePythonVersion(3, 12),
3311
+ makePythonVersion(3, 11),
3312
+ makePythonVersion(3, 10),
3313
+ makePythonVersion(3, 9),
3314
+ makePythonVersion(3, 6, /* @__PURE__ */ new Date("2022-07-18"))
3334
3315
  ];
3335
3316
  function getDevPythonVersion() {
3336
3317
  return {
3337
- version: "3",
3318
+ major: 3,
3319
+ minor: 0,
3338
3320
  pipPath: "pip3",
3339
3321
  pythonPath: "python3",
3340
3322
  runtime: "python3"
@@ -3347,7 +3329,7 @@ function getDefaultPythonVersion({
3347
3329
  return getDevPythonVersion();
3348
3330
  }
3349
3331
  const defaultOption = allOptions.find(
3350
- (opt) => opt.version === DEFAULT_PYTHON_VERSION && isInstalled(opt)
3332
+ (opt) => versionsEqual(opt, DEFAULT_PYTHON_VERSION) && isInstalled(opt)
3351
3333
  );
3352
3334
  if (defaultOption) {
3353
3335
  return defaultOption;
@@ -3362,148 +3344,143 @@ function getDefaultPythonVersion({
3362
3344
  }
3363
3345
  return selection;
3364
3346
  }
3365
- function parseVersionTuple(input) {
3366
- const cleaned = input.trim().replace(/\s+/g, "");
3367
- const m = cleaned.match(/^(\d+)(?:\.(\d+))?/);
3368
- if (!m)
3369
- return null;
3370
- const major = Number(m[1]);
3371
- const minor = m[2] !== void 0 ? Number(m[2]) : 0;
3372
- if (Number.isNaN(major) || Number.isNaN(minor))
3373
- return null;
3374
- return [major, minor];
3347
+ function versionsEqual(a, b) {
3348
+ return a.major === b.major && a.minor === b.minor;
3375
3349
  }
3376
- function compareTuples(a, b) {
3377
- if (a[0] !== b[0])
3378
- return a[0] - b[0];
3379
- return a[1] - b[1];
3350
+ function versionLessOrEqual(a, b) {
3351
+ if (a.major !== b.major)
3352
+ return a.major < b.major;
3353
+ return a.minor <= b.minor;
3380
3354
  }
3381
- function parseSpecifier(spec) {
3382
- const s = spec.trim();
3383
- const m = s.match(
3384
- /^(<=|>=|==|!=|~=|<|>)\s*([0-9]+(?:\.[0-9]+)?)(?:\.[0-9]+)?(?:\.\*)?$/
3385
- ) || // Bare version like "3.11" or "3.11.4" -> implied ==
3386
- s.match(/^()([0-9]+(?:\.[0-9]+)?)(?:\.[0-9]+)?(?:\.\*)?$/);
3387
- if (!m)
3388
- return null;
3389
- const op = m[1] || "==";
3390
- const vt = parseVersionTuple(m[2]);
3391
- if (!vt)
3392
- return null;
3393
- return { op, ver: vt };
3355
+ function toPythonBuild(opt) {
3356
+ return {
3357
+ version: { major: opt.major, minor: opt.minor },
3358
+ implementation: "cpython",
3359
+ variant: "default",
3360
+ os: "linux",
3361
+ architecture: "x86_64",
3362
+ libc: "gnu"
3363
+ };
3394
3364
  }
3395
- function satisfies(candidate, spec) {
3396
- const cmp = compareTuples(candidate, spec.ver);
3397
- switch (spec.op) {
3398
- case "==":
3399
- return cmp === 0;
3400
- case "!=":
3401
- return cmp !== 0;
3402
- case "<":
3403
- return cmp < 0;
3404
- case "<=":
3405
- return cmp <= 0;
3406
- case ">":
3407
- return cmp > 0;
3408
- case ">=":
3409
- return cmp >= 0;
3410
- case "~=": {
3411
- const lowerOk = cmp >= 0;
3412
- const upper = [spec.ver[0], spec.ver[1] + 1];
3413
- return lowerOk && compareTuples(candidate, upper) < 0;
3414
- }
3415
- default:
3416
- return false;
3417
- }
3365
+ function getAvailablePythonBuilds() {
3366
+ const installed = allOptions.filter(
3367
+ (opt) => !isDiscontinued(opt) && isInstalled(opt)
3368
+ );
3369
+ const defaultOpt = installed.find(
3370
+ (opt) => versionsEqual(opt, DEFAULT_PYTHON_VERSION)
3371
+ );
3372
+ const rest = installed.filter(
3373
+ (opt) => !versionsEqual(opt, DEFAULT_PYTHON_VERSION)
3374
+ );
3375
+ const ordered = defaultOpt ? [defaultOpt, ...rest] : rest;
3376
+ return ordered.map(toPythonBuild);
3418
3377
  }
3419
- function selectFromRequiresPython(expr) {
3420
- const raw = expr.trim();
3421
- if (!raw)
3422
- return void 0;
3423
- const parts = raw.split(",").map((p) => p.trim()).filter(Boolean);
3424
- const specifiers = [];
3425
- for (const p of parts) {
3426
- const sp = parseSpecifier(p);
3427
- if (sp)
3428
- specifiers.push(sp);
3429
- }
3430
- if (specifiers.length === 0) {
3431
- return allOptions.find((o) => o.version === raw);
3432
- }
3433
- const matches = allOptions.filter((opt) => {
3434
- const vt = parseVersionTuple(opt.version);
3435
- return specifiers.every((sp) => satisfies(vt, sp));
3436
- });
3437
- if (matches.length === 0)
3438
- return void 0;
3439
- const defaultMatch = matches.find(
3440
- (opt) => opt.version === DEFAULT_PYTHON_VERSION && isInstalled(opt)
3378
+ function getAllPythonBuilds() {
3379
+ return allOptions.map(toPythonBuild);
3380
+ }
3381
+ function getPythonVersionForBuild(build2) {
3382
+ return allOptions.find(
3383
+ (opt) => opt.major === build2.version.major && opt.minor === build2.version.minor
3441
3384
  );
3442
- if (defaultMatch) {
3443
- return defaultMatch;
3444
- }
3445
- const installedMatch = matches.find(isInstalled);
3446
- return installedMatch ?? matches[0];
3447
3385
  }
3448
- function getSupportedPythonVersion({
3386
+ function resolvePythonVersion({
3449
3387
  isDev,
3450
- declaredPythonVersion
3388
+ pythonPackage,
3389
+ rootDir
3451
3390
  }) {
3452
3391
  if (isDev) {
3453
- return getDevPythonVersion();
3392
+ return {
3393
+ pythonVersion: getDevPythonVersion(),
3394
+ pythonPackage
3395
+ };
3454
3396
  }
3455
- let selection = getDefaultPythonVersion({ isDev: false });
3456
- if (declaredPythonVersion) {
3457
- const { version: version2, source } = declaredPythonVersion;
3458
- let requested;
3459
- if (source === "pyproject.toml" || source === ".python-version") {
3460
- requested = selectFromRequiresPython(version2);
3461
- } else {
3462
- requested = allOptions.find((o) => o.version === version2);
3463
- }
3464
- if (requested) {
3465
- if (isDiscontinued(requested)) {
3397
+ const constraints = pythonPackage.requiresPython;
3398
+ const defaultPv = getDefaultPythonVersion({ isDev: false });
3399
+ let selection;
3400
+ let source;
3401
+ let autoUpgraded = false;
3402
+ if (!constraints || constraints.length === 0) {
3403
+ console.log(
3404
+ `No Python version specified in .python-version, pyproject.toml, or Pipfile.lock. Using python version: ${pythonVersionString(defaultPv)}`
3405
+ );
3406
+ selection = defaultPv;
3407
+ } else {
3408
+ const defaultBuild = toPythonBuild(defaultPv);
3409
+ const availableBuilds = getAvailablePythonBuilds();
3410
+ const allBuilds = getAllPythonBuilds();
3411
+ const result = (0, import_python_analysis.selectPythonVersion)({
3412
+ constraints,
3413
+ availableBuilds,
3414
+ allBuilds,
3415
+ defaultBuild,
3416
+ majorMinorOnly: true,
3417
+ legacyTildeEquals: true
3418
+ });
3419
+ source = result.source;
3420
+ selection = getPythonVersionForBuild(result.build) ?? defaultPv;
3421
+ if (pythonPackage.manifest?.origin && !result.notAvailable && !result.invalidConstraint && !versionLessOrEqual(defaultPv, selection)) {
3422
+ const originalVersion = pythonVersionString(selection);
3423
+ selection = defaultPv;
3424
+ autoUpgraded = true;
3425
+ console.log(
3426
+ `Python version ${originalVersion} detected in ${source} is below the minimum supported version. Using python version: ${pythonVersionString(selection)}`
3427
+ );
3428
+ } else if (result.notAvailable) {
3429
+ const npv = getPythonVersionForBuild(result.notAvailable.build);
3430
+ if (npv && isDiscontinued(npv)) {
3466
3431
  throw new import_build_utils3.NowBuildError({
3467
3432
  code: "BUILD_UTILS_PYTHON_VERSION_DISCONTINUED",
3468
3433
  link: "https://vercel.link/python-version",
3469
- message: `Python version "${requested.version}" detected in ${source} is discontinued and must be upgraded.`
3434
+ message: `Python version "${pythonVersionString(npv)}" detected in ${source} is discontinued and must be upgraded.`
3470
3435
  });
3471
3436
  }
3472
- if (isInstalled(requested)) {
3473
- selection = requested;
3474
- console.log(`Using Python ${selection.version} from ${source}`);
3475
- } else {
3437
+ if (npv) {
3476
3438
  console.warn(
3477
- `Warning: Python version "${version2}" detected in ${source} is not installed and will be ignored. https://vercel.link/python-version`
3439
+ `Warning: Python version "${pythonVersionString(npv)}" detected in ${source} is not installed and will be ignored. https://vercel.link/python-version`
3478
3440
  );
3479
- console.log(`Using python version: ${selection.version}`);
3480
3441
  }
3481
- } else {
3442
+ console.log(`Using python version: ${pythonVersionString(selection)}`);
3443
+ } else if (result.invalidConstraint) {
3482
3444
  console.warn(
3483
- `Warning: Python version "${version2}" detected in ${source} is invalid and will be ignored. https://vercel.link/python-version`
3445
+ `Warning: Python version "${result.invalidConstraint.versionString}" detected in ${source} is invalid and will be ignored. https://vercel.link/python-version`
3446
+ );
3447
+ console.log(`Using python version: ${pythonVersionString(selection)}`);
3448
+ } else {
3449
+ console.log(
3450
+ `Using Python ${pythonVersionString(selection)} from ${source}`
3484
3451
  );
3485
- console.log(`Using python version: ${selection.version}`);
3486
3452
  }
3487
- } else {
3488
- console.log(
3489
- `No Python version specified in .python-version, pyproject.toml, or Pipfile.lock. Using python version: ${selection.version}`
3490
- );
3491
3453
  }
3492
3454
  if (isDiscontinued(selection)) {
3493
3455
  throw new import_build_utils3.NowBuildError({
3494
3456
  code: "BUILD_UTILS_PYTHON_VERSION_DISCONTINUED",
3495
3457
  link: "https://vercel.link/python-version",
3496
- message: `Python version "${selection.version}" declared in project configuration is discontinued and must be upgraded.`
3458
+ message: `Python version "${pythonVersionString(selection)}" declared in project configuration is discontinued and must be upgraded.`
3497
3459
  });
3498
3460
  }
3499
3461
  if (selection.discontinueDate) {
3500
3462
  const d = selection.discontinueDate.toISOString().split("T")[0];
3501
- const srcSuffix = declaredPythonVersion ? `detected in ${declaredPythonVersion.source}` : "selected by runtime";
3463
+ const srcSuffix = source ? `detected in ${source}` : "selected by runtime";
3502
3464
  console.warn(
3503
- `Error: Python version "${selection.version}" ${srcSuffix} has reached End-of-Life. Deployments created on or after ${d} will fail to build. https://vercel.link/python-version`
3465
+ `Error: Python version "${pythonVersionString(selection)}" ${srcSuffix} has reached End-of-Life. Deployments created on or after ${d} will fail to build. https://vercel.link/python-version`
3504
3466
  );
3505
3467
  }
3506
- return selection;
3468
+ let pinVersionFilePath;
3469
+ const hasPythonVersionFile = pythonPackage.configs?.some(
3470
+ (configSet) => configSet[import_python_analysis.PythonConfigKind.PythonVersion] !== void 0
3471
+ ) ?? false;
3472
+ if (!hasPythonVersionFile && pythonPackage.manifest && versionLessOrEqual(selection, defaultPv)) {
3473
+ if (autoUpgraded || !pythonPackage.manifest.origin && source?.endsWith("pyproject.toml")) {
3474
+ const manifestDir = (0, import_path4.join)(rootDir, (0, import_path4.dirname)(pythonPackage.manifest.path));
3475
+ pinVersionFilePath = (0, import_path4.join)(manifestDir, ".python-version");
3476
+ }
3477
+ }
3478
+ return {
3479
+ pythonVersion: selection,
3480
+ pythonPackage,
3481
+ versionSource: source,
3482
+ pinVersionFilePath
3483
+ };
3507
3484
  }
3508
3485
  function isDiscontinued({ discontinueDate }) {
3509
3486
  const today = Date.now();
@@ -3526,10 +3503,10 @@ function getInstalledPythons() {
3526
3503
  installedPythonsCache = uv.listInstalledPythons();
3527
3504
  return installedPythonsCache;
3528
3505
  }
3529
- function isInstalled({ version: version2 }) {
3506
+ function isInstalled(pv) {
3530
3507
  try {
3531
3508
  const installed = getInstalledPythons();
3532
- return installed.has(version2);
3509
+ return installed.has(pythonVersionString(pv));
3533
3510
  } catch (err) {
3534
3511
  throw new import_build_utils3.NowBuildError({
3535
3512
  code: "UV_ERROR",
@@ -3554,11 +3531,11 @@ async function isInstalled2(pythonPath, dependency, cwd) {
3554
3531
  {
3555
3532
  stdio: "pipe",
3556
3533
  cwd,
3557
- env: { ...process.env, PYTHONPATH: (0, import_path4.join)(cwd, resolveVendorDir()) }
3534
+ env: { ...process.env, PYTHONPATH: (0, import_path5.join)(cwd, resolveVendorDir()) }
3558
3535
  }
3559
3536
  );
3560
3537
  return stdout.startsWith(cwd);
3561
- } catch (err) {
3538
+ } catch (_err) {
3562
3539
  return false;
3563
3540
  }
3564
3541
  }
@@ -3577,11 +3554,11 @@ async function areRequirementsInstalled(pythonPath, requirementsPath, cwd) {
3577
3554
  {
3578
3555
  stdio: "pipe",
3579
3556
  cwd,
3580
- env: { ...process.env, PYTHONPATH: (0, import_path4.join)(cwd, resolveVendorDir()) }
3557
+ env: { ...process.env, PYTHONPATH: (0, import_path5.join)(cwd, resolveVendorDir()) }
3581
3558
  }
3582
3559
  );
3583
3560
  return true;
3584
- } catch (err) {
3561
+ } catch (_err) {
3585
3562
  return false;
3586
3563
  }
3587
3564
  }
@@ -3615,88 +3592,74 @@ function resolveVendorDir() {
3615
3592
  const vendorDir = process.env.VERCEL_PYTHON_VENDOR_DIR || "_vendor";
3616
3593
  return vendorDir;
3617
3594
  }
3618
- function toBuildError(error) {
3619
- return new import_build_utils4.NowBuildError({
3620
- code: error.code,
3621
- message: error.message,
3622
- link: error.link,
3623
- action: error.action
3624
- });
3625
- }
3626
- async function detectInstallSource({
3627
- workPath,
3628
- entryDirectory,
3629
- repoRootPath
3595
+ async function discoverPackage({
3596
+ entrypointDir,
3597
+ rootDir
3630
3598
  }) {
3631
- const entrypointDir = (0, import_path4.join)(workPath, entryDirectory);
3632
- const rootDir = repoRootPath ?? workPath;
3633
- let pythonPackage;
3634
3599
  try {
3635
- pythonPackage = await (0, import_python_analysis.discoverPythonPackage)({
3636
- entrypointDir,
3637
- rootDir
3638
- });
3600
+ return await (0, import_python_analysis2.discoverPythonPackage)({ entrypointDir, rootDir });
3639
3601
  } catch (error) {
3640
- if (error instanceof import_python_analysis.PythonAnalysisError) {
3602
+ if (error instanceof import_python_analysis2.PythonAnalysisError) {
3641
3603
  if (error.fileContent && (error.code.endsWith("_PARSE_ERROR") || error.code.endsWith("_VALIDATION_ERROR"))) {
3642
3604
  console.log(
3643
3605
  `Failed to parse "${error.path}". File content:
3644
3606
  ${error.fileContent}`
3645
3607
  );
3646
3608
  }
3647
- throw toBuildError(error);
3609
+ throw new import_build_utils4.NowBuildError({
3610
+ code: error.code,
3611
+ message: error.message,
3612
+ link: error.link,
3613
+ action: error.action
3614
+ });
3648
3615
  }
3649
3616
  throw error;
3650
3617
  }
3618
+ }
3619
+ function detectInstallSource(pythonPackage, rootDir) {
3651
3620
  let manifestType = null;
3652
3621
  let manifestPath = null;
3653
3622
  const lockFile = pythonPackage.manifest?.lockFile ?? pythonPackage.workspaceLockFile;
3654
3623
  if (lockFile) {
3655
- if (lockFile.kind === import_python_analysis.PythonLockFileKind.UvLock) {
3624
+ if (lockFile.kind === import_python_analysis2.PythonLockFileKind.UvLock) {
3656
3625
  manifestType = "uv.lock";
3657
- manifestPath = (0, import_path4.join)(rootDir, lockFile.path);
3658
- } else if (lockFile.kind === import_python_analysis.PythonLockFileKind.PylockToml) {
3626
+ manifestPath = (0, import_path5.join)(rootDir, lockFile.path);
3627
+ } else if (lockFile.kind === import_python_analysis2.PythonLockFileKind.PylockToml) {
3659
3628
  manifestType = "pylock.toml";
3660
- manifestPath = (0, import_path4.join)(rootDir, lockFile.path);
3629
+ manifestPath = (0, import_path5.join)(rootDir, lockFile.path);
3661
3630
  }
3662
3631
  } else if (pythonPackage.manifest) {
3663
3632
  manifestType = "pyproject.toml";
3664
- manifestPath = (0, import_path4.join)(rootDir, pythonPackage.manifest.path);
3633
+ manifestPath = (0, import_path5.join)(rootDir, pythonPackage.manifest.path);
3665
3634
  }
3666
3635
  return { manifestPath, manifestType, pythonPackage };
3667
3636
  }
3668
3637
  async function ensureUvProject({
3669
3638
  workPath,
3670
- entryDirectory,
3671
- repoRootPath,
3639
+ rootDir,
3640
+ pythonPackage,
3672
3641
  pythonVersion,
3673
3642
  uv,
3674
3643
  generateLockFile = false,
3675
3644
  requireBinaryWheels = false
3676
3645
  }) {
3677
- const rootDir = repoRootPath ?? workPath;
3678
- const installInfo = await detectInstallSource({
3679
- workPath,
3680
- entryDirectory,
3681
- repoRootPath
3682
- });
3683
- const { manifestType, pythonPackage } = installInfo;
3684
- const manifest = pythonPackage?.manifest;
3646
+ const { manifestType } = detectInstallSource(pythonPackage, rootDir);
3647
+ const manifest = pythonPackage.manifest;
3685
3648
  let projectDir;
3686
3649
  let pyprojectPath;
3687
3650
  let lockPath = null;
3688
3651
  let lockFileProvidedByUser = false;
3689
3652
  if (manifestType === "uv.lock" || manifestType === "pylock.toml") {
3690
3653
  lockFileProvidedByUser = true;
3691
- const lockFile = pythonPackage?.manifest?.lockFile ?? pythonPackage?.workspaceLockFile;
3654
+ const lockFile = pythonPackage.manifest?.lockFile ?? pythonPackage.workspaceLockFile;
3692
3655
  if (!lockFile) {
3693
3656
  throw new Error(
3694
3657
  `Expected lock file path to be resolved, but it was null`
3695
3658
  );
3696
3659
  }
3697
- lockPath = (0, import_path4.join)(rootDir, lockFile.path);
3698
- projectDir = (0, import_path4.dirname)(lockPath);
3699
- pyprojectPath = (0, import_path4.join)(projectDir, "pyproject.toml");
3660
+ lockPath = (0, import_path5.join)(rootDir, lockFile.path);
3661
+ projectDir = (0, import_path5.dirname)(lockPath);
3662
+ pyprojectPath = (0, import_path5.join)(projectDir, "pyproject.toml");
3700
3663
  if (!import_fs3.default.existsSync(pyprojectPath)) {
3701
3664
  throw new Error(
3702
3665
  `Expected "pyproject.toml" next to "${lockFile.kind}" in "${projectDir}"`
@@ -3704,14 +3667,14 @@ async function ensureUvProject({
3704
3667
  }
3705
3668
  console.log(`Installing required dependencies from ${lockFile.kind}...`);
3706
3669
  } else if (manifest) {
3707
- projectDir = (0, import_path4.join)(rootDir, (0, import_path4.dirname)(manifest.path));
3708
- pyprojectPath = (0, import_path4.join)(rootDir, manifest.path);
3670
+ projectDir = (0, import_path5.join)(rootDir, (0, import_path5.dirname)(manifest.path));
3671
+ pyprojectPath = (0, import_path5.join)(rootDir, manifest.path);
3709
3672
  const originKind = manifest.origin?.kind;
3710
- if (originKind === import_python_analysis.PythonManifestConvertedKind.Pipfile) {
3673
+ if (originKind === import_python_analysis2.PythonManifestConvertedKind.Pipfile) {
3711
3674
  console.log("Installing required dependencies from Pipfile...");
3712
- } else if (originKind === import_python_analysis.PythonManifestConvertedKind.PipfileLock) {
3675
+ } else if (originKind === import_python_analysis2.PythonManifestConvertedKind.PipfileLock) {
3713
3676
  console.log("Installing required dependencies from Pipfile.lock...");
3714
- } else if (originKind === import_python_analysis.PythonManifestConvertedKind.RequirementsTxt || originKind === import_python_analysis.PythonManifestConvertedKind.RequirementsIn) {
3677
+ } else if (originKind === import_python_analysis2.PythonManifestConvertedKind.RequirementsTxt || originKind === import_python_analysis2.PythonManifestConvertedKind.RequirementsIn) {
3715
3678
  console.log(
3716
3679
  `Installing required dependencies from ${manifest.origin?.path ?? "requirements.txt"}...`
3717
3680
  );
@@ -3719,16 +3682,16 @@ async function ensureUvProject({
3719
3682
  console.log("Installing required dependencies from pyproject.toml...");
3720
3683
  }
3721
3684
  if (manifest.origin) {
3722
- if (manifest.data.project && !manifest.data.project["requires-python"]) {
3685
+ if (manifest.data.project) {
3723
3686
  manifest.data.project["requires-python"] = `~=${pythonVersion}.0`;
3724
3687
  }
3725
- const content = (0, import_python_analysis.stringifyManifest)(manifest.data);
3726
- pyprojectPath = (0, import_path4.join)(projectDir, "pyproject.toml");
3688
+ const content = (0, import_python_analysis2.stringifyManifest)(manifest.data);
3689
+ pyprojectPath = (0, import_path5.join)(projectDir, "pyproject.toml");
3727
3690
  await import_fs3.default.promises.writeFile(pyprojectPath, content);
3728
3691
  }
3729
- const workspaceLockFile = pythonPackage?.workspaceLockFile;
3692
+ const workspaceLockFile = pythonPackage.workspaceLockFile;
3730
3693
  if (workspaceLockFile) {
3731
- lockPath = (0, import_path4.join)(rootDir, workspaceLockFile.path);
3694
+ lockPath = (0, import_path5.join)(rootDir, workspaceLockFile.path);
3732
3695
  } else {
3733
3696
  await uv.lock(
3734
3697
  projectDir,
@@ -3743,24 +3706,24 @@ async function ensureUvProject({
3743
3706
  }
3744
3707
  } else {
3745
3708
  projectDir = workPath;
3746
- pyprojectPath = (0, import_path4.join)(projectDir, "pyproject.toml");
3709
+ pyprojectPath = (0, import_path5.join)(projectDir, "pyproject.toml");
3747
3710
  console.log(
3748
3711
  "No Python manifest found; creating an empty pyproject.toml and uv.lock..."
3749
3712
  );
3750
3713
  const requiresPython = `~=${pythonVersion}.0`;
3751
- const minimalManifest = (0, import_python_analysis.createMinimalManifest)({
3714
+ const minimalManifest = (0, import_python_analysis2.createMinimalManifest)({
3752
3715
  name: "app",
3753
3716
  requiresPython,
3754
3717
  dependencies: []
3755
3718
  });
3756
- const content = (0, import_python_analysis.stringifyManifest)(minimalManifest);
3719
+ const content = (0, import_python_analysis2.stringifyManifest)(minimalManifest);
3757
3720
  await import_fs3.default.promises.writeFile(pyprojectPath, content);
3758
3721
  await uv.lock(
3759
3722
  projectDir,
3760
3723
  requireBinaryWheels ? { noBuild: true, upgrade: true } : void 0
3761
3724
  );
3762
3725
  }
3763
- const resolvedLockPath = lockPath && import_fs3.default.existsSync(lockPath) ? lockPath : (0, import_path4.join)(projectDir, "uv.lock");
3726
+ const resolvedLockPath = lockPath && import_fs3.default.existsSync(lockPath) ? lockPath : (0, import_path5.join)(projectDir, "uv.lock");
3764
3727
  return {
3765
3728
  projectDir,
3766
3729
  pyprojectPath,
@@ -3769,7 +3732,7 @@ async function ensureUvProject({
3769
3732
  };
3770
3733
  }
3771
3734
  async function pipInstall(pipPath, uvPath, workPath, args, targetDir) {
3772
- const target = targetDir ? (0, import_path4.join)(targetDir, resolveVendorDir()) : resolveVendorDir();
3735
+ const target = targetDir ? (0, import_path5.join)(targetDir, resolveVendorDir()) : resolveVendorDir();
3773
3736
  process.env.PIP_USER = "0";
3774
3737
  if (uvPath) {
3775
3738
  const uvArgs = [
@@ -3786,7 +3749,7 @@ async function pipInstall(pipPath, uvPath, workPath, args, targetDir) {
3786
3749
  try {
3787
3750
  await (0, import_execa3.default)(uvPath, uvArgs, {
3788
3751
  cwd: workPath,
3789
- env: getProtectedUvEnv()
3752
+ env: getProtectedUvEnv(process.env, getUvCacheDir(workPath))
3790
3753
  });
3791
3754
  return;
3792
3755
  } catch (err) {
@@ -3863,9 +3826,9 @@ async function installRequirementsFile({
3863
3826
  // src/dependency-externalizer.ts
3864
3827
  var import_fs4 = __toESM(require("fs"));
3865
3828
  var import_util = require("util");
3866
- var import_path5 = require("path");
3829
+ var import_path6 = require("path");
3867
3830
  var import_build_utils5 = require("@vercel/build-utils");
3868
- var import_python_analysis2 = require("@vercel/python-analysis");
3831
+ var import_python_analysis3 = require("@vercel/python-analysis");
3869
3832
  var readFile = (0, import_util.promisify)(import_fs4.default.readFile);
3870
3833
  var LAMBDA_SIZE_THRESHOLD_BYTES = 249 * 1024 * 1024;
3871
3834
  var LAMBDA_PACKING_TARGET_BYTES = 245 * 1024 * 1024;
@@ -4002,9 +3965,9 @@ To fix this, either:
4002
3965
  }
4003
3966
  let lockFile;
4004
3967
  try {
4005
- lockFile = (0, import_python_analysis2.parseUvLock)(lockContent, this.uvLockPath);
3968
+ lockFile = (0, import_python_analysis3.parseUvLock)(lockContent, this.uvLockPath);
4006
3969
  } catch (error) {
4007
- if (error instanceof import_python_analysis2.PythonAnalysisError) {
3970
+ if (error instanceof import_python_analysis3.PythonAnalysisError) {
4008
3971
  if (error.fileContent) {
4009
3972
  console.log(
4010
3973
  `Failed to parse "${error.path}". File content:
@@ -4025,7 +3988,7 @@ ${error.fileContent}`
4025
3988
  `Excluding project package "${this.projectName}" from runtime installation`
4026
3989
  );
4027
3990
  }
4028
- const classification = (0, import_python_analysis2.classifyPackages)({
3991
+ const classification = (0, import_python_analysis3.classifyPackages)({
4029
3992
  lockFile,
4030
3993
  excludePackages
4031
3994
  });
@@ -4089,11 +4052,11 @@ ${error.fileContent}`
4089
4052
  ...bundledPublic,
4090
4053
  ...this.alwaysBundlePackages
4091
4054
  ];
4092
- const projectDirRel = (0, import_path5.relative)(this.workPath, this.uvProjectDir);
4093
- const uvLockRel = (0, import_path5.relative)(this.workPath, this.uvLockPath);
4055
+ const projectDirRel = (0, import_path6.relative)(this.workPath, this.uvProjectDir);
4056
+ const uvLockRel = (0, import_path6.relative)(this.workPath, this.uvLockPath);
4094
4057
  const isOutsideWorkPath = projectDirRel.startsWith("..") || uvLockRel.startsWith("..");
4095
4058
  if (isOutsideWorkPath) {
4096
- const srcPyproject = (0, import_path5.join)(this.uvProjectDir, "pyproject.toml");
4059
+ const srcPyproject = (0, import_path6.join)(this.uvProjectDir, "pyproject.toml");
4097
4060
  files[`${UV_BUNDLE_DIR}/pyproject.toml`] = new import_build_utils5.FileFsRef({
4098
4061
  fsPath: srcPyproject
4099
4062
  });
@@ -4111,8 +4074,8 @@ ${error.fileContent}`
4111
4074
  if (process.env.VERCEL_BUILD_IMAGE) {
4112
4075
  try {
4113
4076
  const uvBinaryPath = await getUvBinaryForBundling(this.pythonPath);
4114
- const uvBundleDir = (0, import_path5.join)(this.workPath, UV_BUNDLE_DIR);
4115
- const uvLocalPath = (0, import_path5.join)(uvBundleDir, "uv");
4077
+ const uvBundleDir = (0, import_path6.join)(this.workPath, UV_BUNDLE_DIR);
4078
+ const uvLocalPath = (0, import_path6.join)(uvBundleDir, "uv");
4116
4079
  await import_fs4.default.promises.mkdir(uvBundleDir, { recursive: true });
4117
4080
  await import_fs4.default.promises.copyFile(uvBinaryPath, uvLocalPath);
4118
4081
  await import_fs4.default.promises.chmod(uvLocalPath, 493);
@@ -4152,30 +4115,30 @@ async function mirrorPackagesIntoVendor({
4152
4115
  if (includePackages && includePackages.length === 0) {
4153
4116
  return vendorFiles;
4154
4117
  }
4155
- const includeSet = includePackages ? new Set(includePackages.map(import_python_analysis2.normalizePackageName)) : null;
4118
+ const includeSet = includePackages ? new Set(includePackages.map(import_python_analysis3.normalizePackageName)) : null;
4156
4119
  const sitePackageDirs = await getVenvSitePackagesDirs(venvPath);
4157
4120
  for (const dir of sitePackageDirs) {
4158
4121
  if (!import_fs4.default.existsSync(dir))
4159
4122
  continue;
4160
- const resolvedDir = (0, import_path5.resolve)(dir);
4161
- const dirPrefix = resolvedDir + import_path5.sep;
4162
- const distributions = await (0, import_python_analysis2.scanDistributions)(dir);
4123
+ const resolvedDir = (0, import_path6.resolve)(dir);
4124
+ const dirPrefix = resolvedDir + import_path6.sep;
4125
+ const distributions = await (0, import_python_analysis3.scanDistributions)(dir);
4163
4126
  for (const [name, dist] of distributions) {
4164
4127
  if (includeSet && !includeSet.has(name))
4165
4128
  continue;
4166
4129
  for (const { path: rawPath } of dist.files) {
4167
- const filePath = rawPath.replaceAll("/", import_path5.sep);
4168
- if (!(0, import_path5.resolve)(resolvedDir, filePath).startsWith(dirPrefix)) {
4130
+ const filePath = rawPath.replaceAll("/", import_path6.sep);
4131
+ if (!(0, import_path6.resolve)(resolvedDir, filePath).startsWith(dirPrefix)) {
4169
4132
  continue;
4170
4133
  }
4171
- if (filePath.endsWith(".pyc") || filePath.split(import_path5.sep).includes("__pycache__")) {
4134
+ if (filePath.endsWith(".pyc") || filePath.split(import_path6.sep).includes("__pycache__")) {
4172
4135
  continue;
4173
4136
  }
4174
- const srcFsPath = (0, import_path5.join)(dir, filePath);
4137
+ const srcFsPath = (0, import_path6.join)(dir, filePath);
4175
4138
  if (!import_fs4.default.existsSync(srcFsPath)) {
4176
4139
  continue;
4177
4140
  }
4178
- const bundlePath = (0, import_path5.join)(vendorDirName, filePath).replace(/\\/g, "/");
4141
+ const bundlePath = (0, import_path6.join)(vendorDirName, filePath).replace(/\\/g, "/");
4179
4142
  vendorFiles[bundlePath] = new import_build_utils5.FileFsRef({ fsPath: srcFsPath });
4180
4143
  }
4181
4144
  }
@@ -4226,21 +4189,21 @@ async function calculatePerPackageSizes(venvPath) {
4226
4189
  for (const dir of sitePackageDirs) {
4227
4190
  if (!import_fs4.default.existsSync(dir))
4228
4191
  continue;
4229
- const resolvedDir = (0, import_path5.resolve)(dir);
4230
- const dirPrefix = resolvedDir + import_path5.sep;
4231
- const distributions = await (0, import_python_analysis2.scanDistributions)(dir);
4192
+ const resolvedDir = (0, import_path6.resolve)(dir);
4193
+ const dirPrefix = resolvedDir + import_path6.sep;
4194
+ const distributions = await (0, import_python_analysis3.scanDistributions)(dir);
4232
4195
  for (const [name, dist] of distributions) {
4233
4196
  let totalSize = 0;
4234
4197
  for (const { path: rawPath } of dist.files) {
4235
- const filePath = rawPath.replaceAll("/", import_path5.sep);
4236
- if (!(0, import_path5.resolve)(resolvedDir, filePath).startsWith(dirPrefix)) {
4198
+ const filePath = rawPath.replaceAll("/", import_path6.sep);
4199
+ if (!(0, import_path6.resolve)(resolvedDir, filePath).startsWith(dirPrefix)) {
4237
4200
  continue;
4238
4201
  }
4239
- if (filePath.endsWith(".pyc") || filePath.split(import_path5.sep).includes("__pycache__")) {
4202
+ if (filePath.endsWith(".pyc") || filePath.split(import_path6.sep).includes("__pycache__")) {
4240
4203
  continue;
4241
4204
  }
4242
4205
  try {
4243
- const stats = await import_fs4.default.promises.stat((0, import_path5.join)(dir, filePath));
4206
+ const stats = await import_fs4.default.promises.stat((0, import_path6.join)(dir, filePath));
4244
4207
  totalSize += stats.size;
4245
4208
  } catch {
4246
4209
  }
@@ -4251,19 +4214,17 @@ async function calculatePerPackageSizes(venvPath) {
4251
4214
  return sizes;
4252
4215
  }
4253
4216
 
4254
- // src/index.ts
4255
- var import_build_utils13 = require("@vercel/build-utils");
4256
-
4257
4217
  // src/start-dev-server.ts
4258
4218
  var import_child_process2 = require("child_process");
4259
- var import_fs5 = require("fs");
4260
- var import_path7 = require("path");
4219
+ var import_fs6 = require("fs");
4220
+ var import_path8 = require("path");
4261
4221
  var import_build_utils8 = require("@vercel/build-utils");
4262
4222
  var import_get_port = __toESM(require_get_port());
4263
4223
  var import_is_port_reachable = __toESM(require_is_port_reachable());
4264
4224
 
4265
4225
  // src/entrypoint.ts
4266
- var import_path6 = require("path");
4226
+ var import_fs5 = __toESM(require("fs"));
4227
+ var import_path7 = require("path");
4267
4228
  var import_build_utils6 = require("@vercel/build-utils");
4268
4229
  var import_build_utils7 = require("@vercel/build-utils");
4269
4230
  var PYTHON_ENTRYPOINT_FILENAMES = [
@@ -4281,12 +4242,26 @@ var PYTHON_CANDIDATE_ENTRYPOINTS = getCandidateEntrypointsInDirs(
4281
4242
  function getCandidateEntrypointsInDirs(dirs) {
4282
4243
  return dirs.flatMap(
4283
4244
  (dir) => PYTHON_ENTRYPOINT_FILENAMES.map(
4284
- (filename) => import_path6.posix.join(dir, `${filename}.py`)
4245
+ (filename) => import_path7.posix.join(dir, `${filename}.py`)
4285
4246
  )
4286
4247
  );
4287
4248
  }
4249
+ async function fileExists(filePath) {
4250
+ try {
4251
+ const stat = await import_fs5.default.promises.stat(filePath);
4252
+ return stat.isFile();
4253
+ } catch {
4254
+ return false;
4255
+ }
4256
+ }
4257
+ async function checkEntrypoint(workPath, relPath) {
4258
+ const absPath = (0, import_path7.join)(workPath, relPath);
4259
+ if (!await fileExists(absPath))
4260
+ return false;
4261
+ return (0, import_build_utils6.isPythonEntrypoint)({ fsPath: absPath });
4262
+ }
4288
4263
  async function getPyprojectEntrypoint(workPath) {
4289
- const pyprojectData = await (0, import_build_utils7.readConfigFile)((0, import_path6.join)(workPath, "pyproject.toml"));
4264
+ const pyprojectData = await (0, import_build_utils7.readConfigFile)((0, import_path7.join)(workPath, "pyproject.toml"));
4290
4265
  if (!pyprojectData)
4291
4266
  return null;
4292
4267
  const scripts = pyprojectData.project?.scripts;
@@ -4298,46 +4273,56 @@ async function getPyprojectEntrypoint(workPath) {
4298
4273
  return null;
4299
4274
  const modulePath = match[1];
4300
4275
  const relPath = modulePath.replace(/\./g, "/");
4301
- try {
4302
- const fsFiles = await (0, import_build_utils6.glob)("**", workPath);
4303
- const candidates = [`${relPath}.py`, `${relPath}/__init__.py`];
4304
- for (const candidate of candidates) {
4305
- if (fsFiles[candidate])
4306
- return candidate;
4307
- }
4308
- return null;
4309
- } catch {
4310
- (0, import_build_utils6.debug)("Failed to discover Python entrypoint from pyproject.toml");
4311
- return null;
4276
+ const candidates = [`${relPath}.py`, `${relPath}/__init__.py`];
4277
+ for (const candidate of candidates) {
4278
+ if (await fileExists((0, import_path7.join)(workPath, candidate)))
4279
+ return candidate;
4312
4280
  }
4281
+ return null;
4313
4282
  }
4314
- async function findValidEntrypoint(fsFiles, candidates) {
4283
+ async function findValidEntrypoint(workPath, candidates) {
4315
4284
  for (const candidate of candidates) {
4316
- if (fsFiles[candidate]) {
4317
- const isValid = await (0, import_build_utils6.isPythonEntrypoint)(fsFiles[candidate]);
4318
- if (isValid) {
4319
- (0, import_build_utils6.debug)(`Detected Python entrypoint: ${candidate}`);
4320
- return candidate;
4321
- }
4285
+ if (await checkEntrypoint(workPath, candidate)) {
4286
+ (0, import_build_utils6.debug)(`Detected Python entrypoint: ${candidate}`);
4287
+ return candidate;
4322
4288
  }
4323
4289
  }
4324
4290
  return null;
4325
4291
  }
4292
+ async function checkDjangoManage(workPath) {
4293
+ const managePath = (0, import_path7.join)(workPath, "manage.py");
4294
+ try {
4295
+ const content = await import_fs5.default.promises.readFile(managePath, "utf-8");
4296
+ if (!content.includes("DJANGO_SETTINGS_MODULE"))
4297
+ return false;
4298
+ (0, import_build_utils6.debug)(`Found Django manage.py with DJANGO_SETTINGS_MODULE at ${workPath}`);
4299
+ return true;
4300
+ } catch {
4301
+ return false;
4302
+ }
4303
+ }
4304
+ async function getSubdirectories(workPath) {
4305
+ try {
4306
+ const entries = await import_fs5.default.promises.readdir(workPath, {
4307
+ withFileTypes: true
4308
+ });
4309
+ return entries.filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name).sort();
4310
+ } catch {
4311
+ return [];
4312
+ }
4313
+ }
4326
4314
  async function detectGenericPythonEntrypoint(workPath, configuredEntrypoint) {
4327
4315
  const entry = configuredEntrypoint.endsWith(".py") ? configuredEntrypoint : `${configuredEntrypoint}.py`;
4328
4316
  try {
4329
- const fsFiles = await (0, import_build_utils6.glob)("**", workPath);
4330
- if (fsFiles[entry]) {
4331
- const isValid = await (0, import_build_utils6.isPythonEntrypoint)(fsFiles[entry]);
4332
- if (isValid) {
4333
- (0, import_build_utils6.debug)(`Using configured Python entrypoint: ${entry}`);
4334
- return entry;
4335
- }
4317
+ if (await checkEntrypoint(workPath, entry)) {
4318
+ (0, import_build_utils6.debug)(`Using configured Python entrypoint: ${entry}`);
4319
+ return { entrypoint: entry };
4336
4320
  }
4337
- const candidates = PYTHON_CANDIDATE_ENTRYPOINTS.filter(
4338
- (c) => !!fsFiles[c]
4321
+ const found = await findValidEntrypoint(
4322
+ workPath,
4323
+ PYTHON_CANDIDATE_ENTRYPOINTS
4339
4324
  );
4340
- return findValidEntrypoint(fsFiles, candidates);
4325
+ return found ? { entrypoint: found } : null;
4341
4326
  } catch {
4342
4327
  (0, import_build_utils6.debug)("Failed to discover Python entrypoint");
4343
4328
  return null;
@@ -4346,52 +4331,37 @@ async function detectGenericPythonEntrypoint(workPath, configuredEntrypoint) {
4346
4331
  async function detectDjangoPythonEntrypoint(workPath, configuredEntrypoint) {
4347
4332
  const entry = configuredEntrypoint.endsWith(".py") ? configuredEntrypoint : `${configuredEntrypoint}.py`;
4348
4333
  try {
4349
- const fsFiles = await (0, import_build_utils6.glob)("**", workPath);
4350
- if (fsFiles[entry]) {
4351
- const isValid = await (0, import_build_utils6.isPythonEntrypoint)(fsFiles[entry]);
4352
- if (isValid) {
4353
- (0, import_build_utils6.debug)(`Using configured Python entrypoint: ${entry}`);
4354
- return entry;
4355
- }
4334
+ if (await checkEntrypoint(workPath, entry)) {
4335
+ (0, import_build_utils6.debug)(`Using configured Python entrypoint: ${entry}`);
4336
+ return { entrypoint: entry };
4356
4337
  }
4357
- const rootGlobs = await (0, import_build_utils6.glob)("*", {
4358
- cwd: workPath,
4359
- includeDirectories: true
4360
- });
4361
- const rootDirs = [
4362
- "",
4363
- ...Object.keys(rootGlobs).filter(
4364
- (name) => !name.startsWith(".") && rootGlobs[name].mode != null && (0, import_build_utils6.isDirectory)(rootGlobs[name].mode)
4365
- )
4366
- ];
4338
+ const subdirs = await getSubdirectories(workPath);
4339
+ const rootDirs = ["", ...subdirs];
4367
4340
  for (const rootDir of rootDirs) {
4368
- const currPath = (0, import_path6.join)(workPath, rootDir);
4369
- const wsgiEntry = await (0, import_build_utils6.getDjangoEntrypoint)(currPath);
4370
- if (wsgiEntry) {
4371
- const fullWsgiEntry = import_path6.posix.join(rootDir, wsgiEntry);
4372
- if (fsFiles[fullWsgiEntry]) {
4373
- (0, import_build_utils6.debug)(`Using Django WSGI entrypoint: ${fullWsgiEntry}`);
4374
- return fullWsgiEntry;
4375
- }
4341
+ const currPath = (0, import_path7.join)(workPath, rootDir);
4342
+ const isDjango = await checkDjangoManage(currPath);
4343
+ if (isDjango) {
4344
+ return { baseDir: rootDir };
4376
4345
  }
4377
4346
  }
4378
- const baseCandidates = getCandidateEntrypointsInDirs(rootDirs);
4379
- const candidates = baseCandidates.filter((c) => !!fsFiles[c]);
4380
- return findValidEntrypoint(fsFiles, candidates);
4347
+ const candidates = getCandidateEntrypointsInDirs(rootDirs);
4348
+ const found = await findValidEntrypoint(workPath, candidates);
4349
+ return found ? { entrypoint: found } : null;
4381
4350
  } catch {
4382
4351
  (0, import_build_utils6.debug)("Failed to discover Django Python entrypoint");
4383
4352
  return null;
4384
4353
  }
4385
4354
  }
4386
4355
  async function detectPythonEntrypoint(framework, workPath, configuredEntrypoint) {
4387
- const entrypoint = framework === "django" ? await detectDjangoPythonEntrypoint(workPath, configuredEntrypoint) : await detectGenericPythonEntrypoint(workPath, configuredEntrypoint);
4388
- if (entrypoint)
4389
- return entrypoint;
4390
- return await getPyprojectEntrypoint(workPath);
4356
+ const result = framework === "django" ? await detectDjangoPythonEntrypoint(workPath, configuredEntrypoint) : await detectGenericPythonEntrypoint(workPath, configuredEntrypoint);
4357
+ if (result)
4358
+ return result;
4359
+ const pyprojectEntry = await getPyprojectEntrypoint(workPath);
4360
+ return pyprojectEntry ? { entrypoint: pyprojectEntry } : null;
4391
4361
  }
4392
4362
 
4393
4363
  // src/start-dev-server.ts
4394
- var import_python_analysis3 = require("@vercel/python-analysis");
4364
+ var import_python_analysis4 = require("@vercel/python-analysis");
4395
4365
  var DEV_SERVER_STARTUP_TIMEOUT = 1e4;
4396
4366
  function silenceNodeWarnings() {
4397
4367
  const original = process.emitWarning.bind(
@@ -4464,22 +4434,24 @@ async function syncDependencies({
4464
4434
  onStdout,
4465
4435
  onStderr
4466
4436
  }) {
4467
- const installInfo = await detectInstallSource({
4468
- workPath,
4469
- entryDirectory: "."
4437
+ const pythonPackage = await discoverPackage({
4438
+ entrypointDir: workPath,
4439
+ rootDir: workPath
4470
4440
  });
4471
- let { manifestType, manifestPath } = installInfo;
4472
- const manifest = installInfo.pythonPackage?.manifest;
4441
+ const installInfo = detectInstallSource(pythonPackage, workPath);
4442
+ const { manifestType } = installInfo;
4443
+ let { manifestPath } = installInfo;
4444
+ const manifest = pythonPackage.manifest;
4473
4445
  if (!manifestType || !manifestPath) {
4474
4446
  (0, import_build_utils8.debug)("No Python project manifest found, skipping dependency sync");
4475
4447
  return;
4476
4448
  }
4477
4449
  if (manifest?.origin && manifestType === "pyproject.toml") {
4478
- const syncDir = (0, import_path7.join)(workPath, ".vercel", "python", "sync");
4479
- (0, import_fs5.mkdirSync)(syncDir, { recursive: true });
4480
- const tempPyproject = (0, import_path7.join)(syncDir, "pyproject.toml");
4481
- const content = (0, import_python_analysis3.stringifyManifest)(manifest.data);
4482
- (0, import_fs5.writeFileSync)(tempPyproject, content, "utf8");
4450
+ const syncDir = (0, import_path8.join)(workPath, ".vercel", "python", "sync");
4451
+ (0, import_fs6.mkdirSync)(syncDir, { recursive: true });
4452
+ const tempPyproject = (0, import_path8.join)(syncDir, "pyproject.toml");
4453
+ const content = (0, import_python_analysis4.stringifyManifest)(manifest.data);
4454
+ (0, import_fs6.writeFileSync)(tempPyproject, content, "utf8");
4483
4455
  manifestPath = tempPyproject;
4484
4456
  (0, import_build_utils8.debug)(
4485
4457
  `Wrote converted ${manifest.origin.kind} manifest to ${tempPyproject}`
@@ -4529,7 +4501,7 @@ async function runSync({
4529
4501
  onStdout,
4530
4502
  onStderr
4531
4503
  }) {
4532
- const projectDir = (0, import_path7.dirname)(manifestPath);
4504
+ const projectDir = (0, import_path8.dirname)(manifestPath);
4533
4505
  const pip = uvPath ? { cmd: uvPath, prefix: ["pip", "install"] } : { cmd: pythonBin, prefix: ["-m", "pip", "install"] };
4534
4506
  let spawnCmd;
4535
4507
  let spawnArgs;
@@ -4639,21 +4611,26 @@ function installGlobalCleanupHandlers() {
4639
4611
  }
4640
4612
  function createDevShim(workPath, entry, modulePath) {
4641
4613
  try {
4642
- const vercelPythonDir = (0, import_path7.join)(workPath, ".vercel", "python");
4643
- (0, import_fs5.mkdirSync)(vercelPythonDir, { recursive: true });
4614
+ const vercelPythonDir = (0, import_path8.join)(workPath, ".vercel", "python");
4615
+ (0, import_fs6.mkdirSync)(vercelPythonDir, { recursive: true });
4644
4616
  let qualifiedModule = modulePath;
4645
4617
  let extraPythonPath;
4646
- if ((0, import_fs5.existsSync)((0, import_path7.join)(workPath, "__init__.py"))) {
4647
- const pkgName = (0, import_path7.basename)(workPath);
4618
+ if ((0, import_fs6.existsSync)((0, import_path8.join)(workPath, "__init__.py"))) {
4619
+ const pkgName = (0, import_path8.basename)(workPath);
4648
4620
  qualifiedModule = `${pkgName}.${modulePath}`;
4649
- extraPythonPath = (0, import_path7.dirname)(workPath);
4650
- }
4651
- const entryAbs = (0, import_path7.join)(workPath, entry);
4652
- const shimPath = (0, import_path7.join)(vercelPythonDir, `${DEV_SHIM_MODULE}.py`);
4653
- const templatePath = (0, import_path7.join)(__dirname, "..", `${DEV_SHIM_MODULE}.py`);
4654
- const template = (0, import_fs5.readFileSync)(templatePath, "utf8");
4621
+ extraPythonPath = (0, import_path8.dirname)(workPath);
4622
+ }
4623
+ const entryAbs = (0, import_path8.join)(workPath, entry);
4624
+ const shimPath = (0, import_path8.join)(vercelPythonDir, `${DEV_SHIM_MODULE}.py`);
4625
+ const templatePath = (0, import_path8.join)(
4626
+ __dirname,
4627
+ "..",
4628
+ "templates",
4629
+ `${DEV_SHIM_MODULE}.py`
4630
+ );
4631
+ const template = (0, import_fs6.readFileSync)(templatePath, "utf8");
4655
4632
  const shimSource = template.replace(/__VC_DEV_MODULE_NAME__/g, qualifiedModule).replace(/__VC_DEV_ENTRY_ABS__/g, entryAbs);
4656
- (0, import_fs5.writeFileSync)(shimPath, shimSource, "utf8");
4633
+ (0, import_fs6.writeFileSync)(shimPath, shimSource, "utf8");
4657
4634
  (0, import_build_utils8.debug)(`Prepared Python dev shim at ${shimPath}`);
4658
4635
  return { module: DEV_SHIM_MODULE, extraPythonPath };
4659
4636
  } catch (err) {
@@ -4667,13 +4644,18 @@ async function getMultiServicePythonRunner(workPath, env, systemPython, uvPath)
4667
4644
  (0, import_build_utils8.debug)(`Using existing virtualenv at ${venvRoot} for multi-service dev`);
4668
4645
  return { command: pythonCmd, args: [] };
4669
4646
  }
4670
- const venvPath = (0, import_path7.join)(workPath, ".venv");
4671
- await ensureVenv({ pythonPath: systemPython, venvPath, uvPath, quiet: true });
4647
+ const venvPath = (0, import_path8.join)(workPath, ".venv");
4648
+ await ensureVenv({
4649
+ pythonPath: systemPython,
4650
+ venvPath,
4651
+ uvPath,
4652
+ quiet: true
4653
+ });
4672
4654
  (0, import_build_utils8.debug)(`Created virtualenv at ${venvPath} for multi-service dev`);
4673
4655
  const pythonBin = getVenvPythonBin(venvPath);
4674
4656
  const binDir = getVenvBinDir(venvPath);
4675
4657
  env.VIRTUAL_ENV = venvPath;
4676
- env.PATH = `${binDir}${import_path7.delimiter}${env.PATH || ""}`;
4658
+ env.PATH = `${binDir}${import_path8.delimiter}${env.PATH || ""}`;
4677
4659
  return { command: pythonBin, args: [] };
4678
4660
  }
4679
4661
  var startDevServer = async (opts) => {
@@ -4686,29 +4668,7 @@ var startDevServer = async (opts) => {
4686
4668
  onStderr
4687
4669
  } = opts;
4688
4670
  const framework = config?.framework;
4689
- if (!framework) {
4690
- return null;
4691
- }
4692
- if (!restoreWarnings)
4693
- restoreWarnings = silenceNodeWarnings();
4694
- installGlobalCleanupHandlers();
4695
- const entry = await detectPythonEntrypoint(
4696
- framework,
4697
- workPath,
4698
- rawEntrypoint
4699
- );
4700
- if (!entry) {
4701
- const searched = PYTHON_CANDIDATE_ENTRYPOINTS.join(", ");
4702
- throw new import_build_utils8.NowBuildError({
4703
- code: "PYTHON_ENTRYPOINT_NOT_FOUND",
4704
- message: `No ${framework} entrypoint found. Add an 'app' script in pyproject.toml or define an entrypoint in one of: ${searched}.`,
4705
- link: `https://vercel.com/docs/frameworks/backend/${framework?.toLowerCase()}#exporting-the-${framework?.toLowerCase()}-application`,
4706
- action: "Learn More"
4707
- });
4708
- }
4709
- const modulePath = entry.replace(/\.py$/i, "").replace(/[\\/]/g, ".");
4710
- const env = { ...process.env, ...meta.env || {} };
4711
- const serverKey = `${workPath}::${entry}::${framework}`;
4671
+ const serverKey = `${workPath}::${framework}`;
4712
4672
  const existing = PERSISTENT_SERVERS.get(serverKey);
4713
4673
  if (existing) {
4714
4674
  return {
@@ -4730,6 +4690,38 @@ var startDevServer = async (opts) => {
4730
4690
  };
4731
4691
  }
4732
4692
  }
4693
+ if (!framework) {
4694
+ return null;
4695
+ }
4696
+ if (!restoreWarnings)
4697
+ restoreWarnings = silenceNodeWarnings();
4698
+ installGlobalCleanupHandlers();
4699
+ const detected = await detectPythonEntrypoint(
4700
+ framework,
4701
+ workPath,
4702
+ rawEntrypoint
4703
+ );
4704
+ const env = { ...process.env, ...meta.env || {} };
4705
+ let entry = detected?.entrypoint;
4706
+ if (!entry) {
4707
+ const hookResult = await runFrameworkHook(framework, {
4708
+ pythonEnv: env,
4709
+ projectDir: (0, import_path8.join)(workPath, detected?.baseDir ?? ""),
4710
+ entrypoint: rawEntrypoint,
4711
+ detected: detected ?? void 0
4712
+ });
4713
+ entry = hookResult?.entrypoint;
4714
+ }
4715
+ if (!entry) {
4716
+ const searched = PYTHON_CANDIDATE_ENTRYPOINTS.join(", ");
4717
+ throw new import_build_utils8.NowBuildError({
4718
+ code: "PYTHON_ENTRYPOINT_NOT_FOUND",
4719
+ message: `No ${framework} entrypoint found. Add an 'app' script in pyproject.toml or define an entrypoint in one of: ${searched}.`,
4720
+ link: `https://vercel.com/docs/frameworks/backend/${framework?.toLowerCase()}#exporting-the-${framework?.toLowerCase()}-application`,
4721
+ action: "Learn More"
4722
+ });
4723
+ }
4724
+ const modulePath = entry.replace(/\.py$/i, "").replace(/[\\/]/g, ".");
4733
4725
  let childProcess = null;
4734
4726
  let stdoutLogListener = null;
4735
4727
  let stderrLogListener = null;
@@ -4821,7 +4813,7 @@ If you are using a virtual environment, activate it before running "vercel dev",
4821
4813
  env.PORT = `${port}`;
4822
4814
  const devShim = createDevShim(workPath, entry, modulePath);
4823
4815
  if (devShim) {
4824
- const vercelPythonDir = (0, import_path7.join)(workPath, ".vercel", "python");
4816
+ const vercelPythonDir = (0, import_path8.join)(workPath, ".vercel", "python");
4825
4817
  const pathParts = [vercelPythonDir];
4826
4818
  if (devShim.extraPythonPath) {
4827
4819
  pathParts.push(devShim.extraPythonPath);
@@ -4830,7 +4822,7 @@ If you are using a virtual environment, activate it before running "vercel dev",
4830
4822
  if (existingPythonPath) {
4831
4823
  pathParts.push(existingPythonPath);
4832
4824
  }
4833
- env.PYTHONPATH = pathParts.join(import_path7.delimiter);
4825
+ env.PYTHONPATH = pathParts.join(import_path8.delimiter);
4834
4826
  }
4835
4827
  const moduleToRun = devShim?.module || modulePath;
4836
4828
  const pythonArgs = ["-u", "-m", moduleToRun];
@@ -4890,7 +4882,7 @@ If you are using a virtual environment, activate it before running "vercel dev",
4890
4882
 
4891
4883
  // src/quirks/index.ts
4892
4884
  var import_build_utils11 = require("@vercel/build-utils");
4893
- var import_python_analysis5 = require("@vercel/python-analysis");
4885
+ var import_python_analysis6 = require("@vercel/python-analysis");
4894
4886
 
4895
4887
  // src/quirks/matplotlib.ts
4896
4888
  var matplotlibQuirk = {
@@ -4903,8 +4895,8 @@ var matplotlibQuirk = {
4903
4895
  };
4904
4896
 
4905
4897
  // src/quirks/litellm.ts
4906
- var import_fs6 = __toESM(require("fs"));
4907
- var import_path8 = require("path");
4898
+ var import_fs7 = __toESM(require("fs"));
4899
+ var import_path9 = require("path");
4908
4900
  var import_build_utils9 = require("@vercel/build-utils");
4909
4901
  var LAMBDA_ROOT = "/var/task";
4910
4902
  var CONFIG_CANDIDATES = [
@@ -4915,9 +4907,9 @@ var CONFIG_CANDIDATES = [
4915
4907
  ];
4916
4908
  async function findConfigFile(workPath) {
4917
4909
  for (const name of CONFIG_CANDIDATES) {
4918
- const candidate = (0, import_path8.join)(workPath, name);
4910
+ const candidate = (0, import_path9.join)(workPath, name);
4919
4911
  try {
4920
- await import_fs6.default.promises.access(candidate);
4912
+ await import_fs7.default.promises.access(candidate);
4921
4913
  return name;
4922
4914
  } catch {
4923
4915
  }
@@ -4932,14 +4924,14 @@ var litellmQuirk = {
4932
4924
  const env = {};
4933
4925
  const sitePackagesDirs = await getVenvSitePackagesDirs(ctx.venvPath);
4934
4926
  for (const sitePackages of sitePackagesDirs) {
4935
- const schemaPath = (0, import_path8.join)(
4927
+ const schemaPath = (0, import_path9.join)(
4936
4928
  sitePackages,
4937
4929
  "litellm",
4938
4930
  "proxy",
4939
4931
  "schema.prisma"
4940
4932
  );
4941
4933
  try {
4942
- await import_fs6.default.promises.access(schemaPath);
4934
+ await import_fs7.default.promises.access(schemaPath);
4943
4935
  (0, import_build_utils9.debug)(`LiteLLM quirk: found schema at ${schemaPath}`);
4944
4936
  buildEnv.PRISMA_SCHEMA_PATH = schemaPath;
4945
4937
  break;
@@ -4953,8 +4945,8 @@ var litellmQuirk = {
4953
4945
  const configName = await findConfigFile(ctx.workPath);
4954
4946
  if (configName) {
4955
4947
  (0, import_build_utils9.debug)(`LiteLLM quirk: found config at ${configName}`);
4956
- buildEnv.CONFIG_FILE_PATH = (0, import_path8.join)(ctx.workPath, configName);
4957
- env.CONFIG_FILE_PATH = (0, import_path8.join)(LAMBDA_ROOT, configName);
4948
+ buildEnv.CONFIG_FILE_PATH = (0, import_path9.join)(ctx.workPath, configName);
4949
+ env.CONFIG_FILE_PATH = (0, import_path9.join)(LAMBDA_ROOT, configName);
4958
4950
  }
4959
4951
  } else {
4960
4952
  (0, import_build_utils9.debug)(
@@ -4966,11 +4958,11 @@ var litellmQuirk = {
4966
4958
  };
4967
4959
 
4968
4960
  // src/quirks/prisma.ts
4969
- var import_fs7 = __toESM(require("fs"));
4970
- var import_path9 = require("path");
4961
+ var import_fs8 = __toESM(require("fs"));
4962
+ var import_path10 = require("path");
4971
4963
  var import_execa4 = __toESM(require_execa());
4972
4964
  var import_build_utils10 = require("@vercel/build-utils");
4973
- var import_python_analysis4 = require("@vercel/python-analysis");
4965
+ var import_python_analysis5 = require("@vercel/python-analysis");
4974
4966
  function execErrorMessage(err) {
4975
4967
  if (err != null && typeof err === "object" && "stderr" in err) {
4976
4968
  const stderr = String(err.stderr);
@@ -5006,9 +4998,9 @@ model DummyModel {
5006
4998
  async function findUserSchema(workPath) {
5007
4999
  const envPath = process.env.PRISMA_SCHEMA_PATH;
5008
5000
  if (envPath) {
5009
- const resolved = (0, import_path9.isAbsolute)(envPath) ? envPath : (0, import_path9.join)(workPath, envPath);
5001
+ const resolved = (0, import_path10.isAbsolute)(envPath) ? envPath : (0, import_path10.join)(workPath, envPath);
5010
5002
  try {
5011
- await import_fs7.default.promises.access(resolved);
5003
+ await import_fs8.default.promises.access(resolved);
5012
5004
  return resolved;
5013
5005
  } catch {
5014
5006
  (0, import_build_utils10.debug)(`PRISMA_SCHEMA_PATH=${envPath} not found at ${resolved}`);
@@ -5016,12 +5008,12 @@ async function findUserSchema(workPath) {
5016
5008
  }
5017
5009
  }
5018
5010
  const candidates = [
5019
- (0, import_path9.join)(workPath, "schema.prisma"),
5020
- (0, import_path9.join)(workPath, "prisma", "schema.prisma")
5011
+ (0, import_path10.join)(workPath, "schema.prisma"),
5012
+ (0, import_path10.join)(workPath, "prisma", "schema.prisma")
5021
5013
  ];
5022
5014
  for (const candidate of candidates) {
5023
5015
  try {
5024
- await import_fs7.default.promises.access(candidate);
5016
+ await import_fs8.default.promises.access(candidate);
5025
5017
  return candidate;
5026
5018
  } catch {
5027
5019
  }
@@ -5032,32 +5024,32 @@ async function collectFiles(dir, base) {
5032
5024
  const result = [];
5033
5025
  let entries;
5034
5026
  try {
5035
- entries = await import_fs7.default.promises.readdir(dir, { withFileTypes: true });
5027
+ entries = await import_fs8.default.promises.readdir(dir, { withFileTypes: true });
5036
5028
  } catch {
5037
5029
  return result;
5038
5030
  }
5039
5031
  for (const entry of entries) {
5040
5032
  if (entry.name === "__pycache__")
5041
5033
  continue;
5042
- const full = (0, import_path9.join)(dir, entry.name);
5034
+ const full = (0, import_path10.join)(dir, entry.name);
5043
5035
  if (entry.isDirectory()) {
5044
5036
  result.push(...await collectFiles(full, base));
5045
5037
  } else {
5046
- result.push((0, import_path9.relative)(base, full));
5038
+ result.push((0, import_path10.relative)(base, full));
5047
5039
  }
5048
5040
  }
5049
5041
  return result;
5050
5042
  }
5051
5043
  async function cleanCacheArtifacts(cacheDir, extras = []) {
5052
5044
  const paths = [
5053
- (0, import_path9.join)(cacheDir, "node_modules"),
5054
- (0, import_path9.join)(cacheDir, "package.json"),
5055
- (0, import_path9.join)(cacheDir, "package-lock.json"),
5045
+ (0, import_path10.join)(cacheDir, "node_modules"),
5046
+ (0, import_path10.join)(cacheDir, "package.json"),
5047
+ (0, import_path10.join)(cacheDir, "package-lock.json"),
5056
5048
  ...extras
5057
5049
  ];
5058
5050
  for (const p of paths) {
5059
5051
  try {
5060
- await import_fs7.default.promises.rm(p, { recursive: true, force: true });
5052
+ await import_fs8.default.promises.rm(p, { recursive: true, force: true });
5061
5053
  } catch (err) {
5062
5054
  console.warn(
5063
5055
  `could not clean up ${p}: ${err instanceof Error ? err.message : String(err)}`
@@ -5081,7 +5073,7 @@ var prismaQuirk = {
5081
5073
  async run(ctx) {
5082
5074
  const { venvPath, pythonEnv, workPath } = ctx;
5083
5075
  const pythonPath = getVenvPythonBin(venvPath);
5084
- const runtimeCacheDir = (0, import_path9.join)(
5076
+ const runtimeCacheDir = (0, import_path10.join)(
5085
5077
  LAMBDA_ROOT2,
5086
5078
  resolveVendorDir(),
5087
5079
  "prisma",
@@ -5091,7 +5083,7 @@ var prismaQuirk = {
5091
5083
  let sitePackages;
5092
5084
  for (const dir of sitePackagesDirs) {
5093
5085
  try {
5094
- await import_fs7.default.promises.access((0, import_path9.join)(dir, "prisma"));
5086
+ await import_fs8.default.promises.access((0, import_path10.join)(dir, "prisma"));
5095
5087
  sitePackages = dir;
5096
5088
  break;
5097
5089
  } catch {
@@ -5103,15 +5095,15 @@ var prismaQuirk = {
5103
5095
  );
5104
5096
  return {};
5105
5097
  }
5106
- const cacheDir = (0, import_path9.join)(sitePackages, "prisma", "__bincache__");
5107
- await import_fs7.default.promises.mkdir(cacheDir, { recursive: true });
5098
+ const cacheDir = (0, import_path10.join)(sitePackages, "prisma", "__bincache__");
5099
+ await import_fs8.default.promises.mkdir(cacheDir, { recursive: true });
5108
5100
  const generateEnv = {
5109
5101
  ...pythonEnv,
5110
5102
  PRISMA_BINARY_CACHE_DIR: cacheDir
5111
5103
  };
5112
- const generatedDir = (0, import_path9.join)(workPath, "_prisma_generated");
5113
- const dummySchemaPath = (0, import_path9.join)(workPath, DUMMY_SCHEMA_NAME);
5114
- await import_fs7.default.promises.writeFile(
5104
+ const generatedDir = (0, import_path10.join)(workPath, "_prisma_generated");
5105
+ const dummySchemaPath = (0, import_path10.join)(workPath, DUMMY_SCHEMA_NAME);
5106
+ await import_fs8.default.promises.writeFile(
5115
5107
  dummySchemaPath,
5116
5108
  buildDummySchema(generatedDir)
5117
5109
  );
@@ -5139,21 +5131,21 @@ var prismaQuirk = {
5139
5131
  }
5140
5132
  const srcBinaryPrefix = `query-engine-${getLambdaBinaryTarget()}`;
5141
5133
  const runtimeName = `prisma-query-engine-rhel-openssl-${RUNTIME_OPENSSL_VERSION}.x`;
5142
- const nodeModulesDir = (0, import_path9.join)(cacheDir, "node_modules", "prisma");
5134
+ const nodeModulesDir = (0, import_path10.join)(cacheDir, "node_modules", "prisma");
5143
5135
  let engineCopied = false;
5144
5136
  try {
5145
- const entries = await import_fs7.default.promises.readdir(nodeModulesDir);
5137
+ const entries = await import_fs8.default.promises.readdir(nodeModulesDir);
5146
5138
  for (const entry of entries) {
5147
5139
  if (!entry.startsWith(srcBinaryPrefix))
5148
5140
  continue;
5149
- const srcPath = (0, import_path9.join)(nodeModulesDir, entry);
5150
- const destPath = (0, import_path9.join)(cacheDir, runtimeName);
5141
+ const srcPath = (0, import_path10.join)(nodeModulesDir, entry);
5142
+ const destPath = (0, import_path10.join)(cacheDir, runtimeName);
5151
5143
  try {
5152
- await import_fs7.default.promises.access(destPath);
5144
+ await import_fs8.default.promises.access(destPath);
5153
5145
  (0, import_build_utils10.debug)(`Engine binary: ${runtimeName} already exists, skipping`);
5154
5146
  } catch {
5155
5147
  (0, import_build_utils10.debug)(`Engine binary: copying ${entry} -> ${runtimeName}`);
5156
- await import_fs7.default.promises.copyFile(srcPath, destPath);
5148
+ await import_fs8.default.promises.copyFile(srcPath, destPath);
5157
5149
  }
5158
5150
  engineCopied = true;
5159
5151
  }
@@ -5170,16 +5162,16 @@ var prismaQuirk = {
5170
5162
  message: `could not find engine binary matching "${srcBinaryPrefix}*" in "${nodeModulesDir}". This may indicate an incompatible prisma version or an unsupported platform (${process.arch}).`
5171
5163
  });
5172
5164
  }
5173
- const shimPath = (0, import_path9.join)(cacheDir, "openssl");
5174
- await import_fs7.default.promises.writeFile(
5165
+ const shimPath = (0, import_path10.join)(cacheDir, "openssl");
5166
+ await import_fs8.default.promises.writeFile(
5175
5167
  shimPath,
5176
5168
  `#!/bin/sh
5177
5169
  echo "OpenSSL ${RUNTIME_OPENSSL_VERSION}.0 1 Jan 2024 (Library: OpenSSL ${RUNTIME_OPENSSL_VERSION}.0)"
5178
5170
  `
5179
5171
  );
5180
- await import_fs7.default.promises.chmod(shimPath, 493);
5172
+ await import_fs8.default.promises.chmod(shimPath, 493);
5181
5173
  for (const p of [generatedDir, dummySchemaPath]) {
5182
- await import_fs7.default.promises.rm(p, { recursive: true, force: true });
5174
+ await import_fs8.default.promises.rm(p, { recursive: true, force: true });
5183
5175
  }
5184
5176
  await cleanCacheArtifacts(cacheDir);
5185
5177
  const generateMode = (process.env.VERCEL_PRISMA_GENERATE_CLIENT ?? "auto").toLowerCase();
@@ -5226,10 +5218,10 @@ echo "OpenSSL ${RUNTIME_OPENSSL_VERSION}.0 1 Jan 2024 (Library: OpenSSL ${RUNTIM
5226
5218
  }
5227
5219
  try {
5228
5220
  const allFiles = await collectFiles(
5229
- (0, import_path9.join)(sitePackages, "prisma"),
5221
+ (0, import_path10.join)(sitePackages, "prisma"),
5230
5222
  sitePackages
5231
5223
  );
5232
- const count = await (0, import_python_analysis4.extendDistRecord)(sitePackages, "prisma", allFiles);
5224
+ const count = await (0, import_python_analysis5.extendDistRecord)(sitePackages, "prisma", allFiles);
5233
5225
  if (count > 0) {
5234
5226
  (0, import_build_utils10.debug)(`Appended ${count} entries to prisma RECORD`);
5235
5227
  }
@@ -5254,7 +5246,7 @@ var quirks = [litellmQuirk, prismaQuirk, matplotlibQuirk];
5254
5246
  function toposortQuirks(activated) {
5255
5247
  const nameToQuirk = /* @__PURE__ */ new Map();
5256
5248
  for (const q of activated) {
5257
- nameToQuirk.set((0, import_python_analysis5.normalizePackageName)(q.dependency), q);
5249
+ nameToQuirk.set((0, import_python_analysis6.normalizePackageName)(q.dependency), q);
5258
5250
  }
5259
5251
  const adj = /* @__PURE__ */ new Map();
5260
5252
  const inDegree = /* @__PURE__ */ new Map();
@@ -5265,7 +5257,7 @@ function toposortQuirks(activated) {
5265
5257
  for (const q of activated) {
5266
5258
  if (q.runsBefore) {
5267
5259
  for (const dep of q.runsBefore) {
5268
- const target = nameToQuirk.get((0, import_python_analysis5.normalizePackageName)(dep));
5260
+ const target = nameToQuirk.get((0, import_python_analysis6.normalizePackageName)(dep));
5269
5261
  if (target) {
5270
5262
  adj.get(q).add(target);
5271
5263
  inDegree.set(target, inDegree.get(target) + 1);
@@ -5274,7 +5266,7 @@ function toposortQuirks(activated) {
5274
5266
  }
5275
5267
  if (q.runsAfter) {
5276
5268
  for (const dep of q.runsAfter) {
5277
- const source = nameToQuirk.get((0, import_python_analysis5.normalizePackageName)(dep));
5269
+ const source = nameToQuirk.get((0, import_python_analysis6.normalizePackageName)(dep));
5278
5270
  if (source) {
5279
5271
  adj.get(source).add(q);
5280
5272
  inDegree.set(q, inDegree.get(q) + 1);
@@ -5315,14 +5307,14 @@ async function runQuirks(ctx) {
5315
5307
  const installedNames = /* @__PURE__ */ new Set();
5316
5308
  const sitePackageDirs = await getVenvSitePackagesDirs(ctx.venvPath);
5317
5309
  for (const dir of sitePackageDirs) {
5318
- const distributions = await (0, import_python_analysis5.scanDistributions)(dir);
5310
+ const distributions = await (0, import_python_analysis6.scanDistributions)(dir);
5319
5311
  for (const name of distributions.keys()) {
5320
- installedNames.add((0, import_python_analysis5.normalizePackageName)(name));
5312
+ installedNames.add((0, import_python_analysis6.normalizePackageName)(name));
5321
5313
  }
5322
5314
  }
5323
5315
  const activated = quirks.filter((quirk) => {
5324
5316
  const installed = installedNames.has(
5325
- (0, import_python_analysis5.normalizePackageName)(quirk.dependency)
5317
+ (0, import_python_analysis6.normalizePackageName)(quirk.dependency)
5326
5318
  );
5327
5319
  if (!installed) {
5328
5320
  (0, import_build_utils11.debug)(`Quirk "${quirk.dependency}": not installed, skipping`);
@@ -5351,23 +5343,74 @@ async function runQuirks(ctx) {
5351
5343
  };
5352
5344
  }
5353
5345
 
5346
+ // src/django.ts
5347
+ var import_fs9 = require("fs");
5348
+ var import_path11 = require("path");
5349
+ var import_execa5 = __toESM(require_execa());
5350
+ var import_build_utils12 = require("@vercel/build-utils");
5351
+ var scriptPath = (0, import_path11.join)(__dirname, "..", "templates", "vc_django_settings.py");
5352
+ var script = (0, import_fs9.readFileSync)(scriptPath, "utf-8");
5353
+ async function getDjangoSettings(projectDir, env) {
5354
+ try {
5355
+ const { stdout } = await (0, import_execa5.default)("python", ["-c", script], {
5356
+ env,
5357
+ cwd: projectDir
5358
+ });
5359
+ return JSON.parse(stdout);
5360
+ } catch (err) {
5361
+ (0, import_build_utils12.debug)(`Django hook: failed to discover settings from manage.py: ${err}`);
5362
+ return null;
5363
+ }
5364
+ }
5365
+
5354
5366
  // src/index.ts
5355
- var readFile2 = (0, import_util2.promisify)(import_fs8.default.readFile);
5356
- var writeFile = (0, import_util2.promisify)(import_fs8.default.writeFile);
5367
+ var import_python_analysis7 = require("@vercel/python-analysis");
5368
+ var writeFile = import_fs10.default.promises.writeFile;
5357
5369
  var version = 3;
5370
+ async function runFrameworkHook(framework, ctx) {
5371
+ const hook = framework ? frameworkHooks[framework] : void 0;
5372
+ return hook?.(ctx);
5373
+ }
5374
+ var frameworkHooks = {
5375
+ django: async ({ pythonEnv, projectDir, detected }) => {
5376
+ if (detected?.baseDir === void 0) {
5377
+ (0, import_build_utils13.debug)("Django hook: no manage.py detected, skipping");
5378
+ return;
5379
+ }
5380
+ const settings = await getDjangoSettings(projectDir, pythonEnv);
5381
+ (0, import_build_utils13.debug)(`Django settings: ${JSON.stringify(settings)}`);
5382
+ if (!settings)
5383
+ return;
5384
+ const baseDir = detected?.baseDir ?? "";
5385
+ const asgiApp = settings["ASGI_APPLICATION"];
5386
+ if (typeof asgiApp === "string") {
5387
+ const rel = `${asgiApp.split(".").slice(0, -1).join("/")}.py`;
5388
+ const entrypoint = baseDir ? `${baseDir}/${rel}` : rel;
5389
+ (0, import_build_utils13.debug)(`Django hook: ASGI entrypoint: ${entrypoint}`);
5390
+ return { entrypoint };
5391
+ }
5392
+ const wsgiApp = settings["WSGI_APPLICATION"];
5393
+ if (typeof wsgiApp === "string") {
5394
+ const rel = `${wsgiApp.split(".").slice(0, -1).join("/")}.py`;
5395
+ const entrypoint = baseDir ? `${baseDir}/${rel}` : rel;
5396
+ (0, import_build_utils13.debug)(`Django hook: WSGI entrypoint: ${entrypoint}`);
5397
+ return { entrypoint };
5398
+ }
5399
+ }
5400
+ };
5358
5401
  async function downloadFilesInWorkPath({
5359
5402
  entrypoint,
5360
5403
  workPath,
5361
5404
  files,
5362
5405
  meta = {}
5363
5406
  }) {
5364
- (0, import_build_utils12.debug)("Downloading user files...");
5365
- let downloadedFiles = await (0, import_build_utils12.download)(files, workPath, meta);
5407
+ (0, import_build_utils13.debug)("Downloading user files...");
5408
+ let downloadedFiles = await (0, import_build_utils13.download)(files, workPath, meta);
5366
5409
  if (meta.isDev) {
5367
- const { devCacheDir = (0, import_path10.join)(workPath, ".now", "cache") } = meta;
5368
- const destCache = (0, import_path10.join)(devCacheDir, (0, import_path10.basename)(entrypoint, ".py"));
5369
- await (0, import_build_utils12.download)(downloadedFiles, destCache);
5370
- downloadedFiles = await (0, import_build_utils12.glob)("**", destCache);
5410
+ const { devCacheDir = (0, import_path12.join)(workPath, ".now", "cache") } = meta;
5411
+ const destCache = (0, import_path12.join)(devCacheDir, (0, import_path12.basename)(entrypoint, ".py"));
5412
+ await (0, import_build_utils13.download)(downloadedFiles, destCache);
5413
+ downloadedFiles = await (0, import_build_utils13.glob)("**", destCache);
5371
5414
  workPath = destCache;
5372
5415
  }
5373
5416
  return workPath;
@@ -5381,13 +5424,13 @@ var build = async ({
5381
5424
  config,
5382
5425
  span: parentSpan
5383
5426
  }) => {
5384
- const builderSpan = parentSpan ?? new import_build_utils12.Span({ name: "vc.builder" });
5427
+ const builderSpan = parentSpan ?? new import_build_utils13.Span({ name: "vc.builder" });
5385
5428
  const framework = config?.framework;
5386
5429
  const shouldInstallVercelWorkers = config?.hasWorkerServices === true;
5387
5430
  let spawnEnv;
5388
5431
  let projectInstallCommand;
5389
5432
  let hasCustomCommand = false;
5390
- (0, import_build_utils12.debug)(`workPath: ${workPath}`);
5433
+ (0, import_build_utils13.debug)(`workPath: ${workPath}`);
5391
5434
  workPath = await downloadFilesInWorkPath({
5392
5435
  workPath,
5393
5436
  files: originalFiles,
@@ -5396,28 +5439,31 @@ var build = async ({
5396
5439
  });
5397
5440
  try {
5398
5441
  if (meta.isDev) {
5399
- const setupCfg = (0, import_path10.join)(workPath, "setup.cfg");
5442
+ const setupCfg = (0, import_path12.join)(workPath, "setup.cfg");
5400
5443
  await writeFile(setupCfg, "[install]\nprefix=\n");
5401
5444
  }
5402
5445
  } catch (err) {
5403
5446
  console.log('Failed to create "setup.cfg" file');
5404
5447
  throw err;
5405
5448
  }
5406
- let fsFiles = await (0, import_build_utils12.glob)("**", workPath);
5407
- if ((0, import_build_utils12.isPythonFramework)(framework) && (!fsFiles[entrypoint] || !entrypoint.endsWith(".py"))) {
5408
- const detected = await detectPythonEntrypoint(
5449
+ let fsFiles = await (0, import_build_utils13.glob)("**", workPath);
5450
+ let detected;
5451
+ let entrypointNotFound;
5452
+ if ((0, import_build_utils13.isPythonFramework)(framework) && // XXX: we might want to detect anyway for django!
5453
+ (!fsFiles[entrypoint] || !entrypoint.endsWith(".py"))) {
5454
+ detected = await detectPythonEntrypoint(
5409
5455
  config.framework,
5410
5456
  workPath,
5411
5457
  entrypoint
5412
- );
5413
- if (detected) {
5414
- (0, import_build_utils12.debug)(
5415
- `Resolved Python entrypoint to "${detected}" (configured "${entrypoint}" not found).`
5458
+ ) ?? void 0;
5459
+ if (detected?.entrypoint) {
5460
+ (0, import_build_utils13.debug)(
5461
+ `Resolved Python entrypoint to "${detected.entrypoint}" (configured "${entrypoint}" not found).`
5416
5462
  );
5417
- entrypoint = detected;
5463
+ entrypoint = detected.entrypoint;
5418
5464
  } else {
5419
5465
  const searchedList = PYTHON_CANDIDATE_ENTRYPOINTS.join(", ");
5420
- throw new import_build_utils12.NowBuildError({
5466
+ entrypointNotFound = new import_build_utils13.NowBuildError({
5421
5467
  code: `${framework.toUpperCase()}_ENTRYPOINT_NOT_FOUND`,
5422
5468
  message: `No ${framework} entrypoint found. Add an 'app' script in pyproject.toml or define an entrypoint in one of: ${searchedList}.`,
5423
5469
  link: `https://vercel.com/docs/frameworks/backend/${framework}#exporting-the-${framework}-application`,
@@ -5425,120 +5471,58 @@ var build = async ({
5425
5471
  });
5426
5472
  }
5427
5473
  }
5428
- const entryDirectory = (0, import_path10.dirname)(entrypoint);
5429
- const pyprojectDir = findDir({
5430
- file: "pyproject.toml",
5431
- entryDirectory,
5432
- workPath,
5433
- fsFiles
5434
- });
5435
- const pipfileLockDir = findDir({
5436
- file: "Pipfile.lock",
5437
- entryDirectory,
5438
- workPath,
5439
- fsFiles
5440
- });
5441
- const pythonVersionFileDir = findDir({
5442
- file: ".python-version",
5443
- entryDirectory,
5444
- workPath,
5445
- fsFiles
5446
- });
5447
- const { pythonVersion, declaredPythonVersion } = await builderSpan.child("vc.builder.python.version").trace(async (versionSpan) => {
5448
- let declared;
5449
- if (pythonVersionFileDir) {
5450
- try {
5451
- const content = await readFile2(
5452
- (0, import_path10.join)(pythonVersionFileDir, ".python-version"),
5453
- "utf8"
5454
- );
5455
- const version2 = parsePythonVersionFile(content);
5456
- if (version2) {
5457
- declared = { version: version2, source: ".python-version" };
5458
- (0, import_build_utils12.debug)(`Found Python version ${version2} in .python-version`);
5459
- }
5460
- } catch (err) {
5461
- (0, import_build_utils12.debug)("Failed to read .python-version file", err);
5462
- }
5463
- }
5464
- if (!declared && pyprojectDir) {
5465
- let requiresPython;
5466
- try {
5467
- const pyproject = await (0, import_build_utils13.readConfigFile)((0, import_path10.join)(pyprojectDir, "pyproject.toml"));
5468
- requiresPython = pyproject?.project?.["requires-python"];
5469
- } catch (err) {
5470
- (0, import_build_utils12.debug)("Failed to parse pyproject.toml", err);
5471
- }
5472
- if (typeof requiresPython === "string" && requiresPython.trim()) {
5473
- declared = {
5474
- version: requiresPython.trim(),
5475
- source: "pyproject.toml"
5476
- };
5477
- (0, import_build_utils12.debug)(`Found requires-python "${requiresPython}" in pyproject.toml`);
5478
- }
5479
- }
5480
- if (!declared && pipfileLockDir) {
5481
- let lock = {};
5482
- const pipfileLockPath = (0, import_path10.join)(pipfileLockDir, "Pipfile.lock");
5483
- try {
5484
- const pipfileLockContent = await readFile2(pipfileLockPath, "utf8");
5485
- try {
5486
- lock = JSON.parse(pipfileLockContent);
5487
- } catch (err) {
5488
- console.log(
5489
- `Failed to parse "Pipfile.lock". File content:
5490
- ${pipfileLockContent}`
5491
- );
5492
- throw err;
5493
- }
5494
- } catch (err) {
5495
- throw new import_build_utils12.NowBuildError({
5496
- code: "INVALID_PIPFILE_LOCK",
5497
- message: "Unable to parse Pipfile.lock"
5498
- });
5499
- }
5500
- const pyFromLock = lock?._meta?.requires?.python_version;
5501
- if (pyFromLock) {
5502
- declared = { version: pyFromLock, source: "Pipfile.lock" };
5503
- (0, import_build_utils12.debug)(`Found Python version ${pyFromLock} in Pipfile.lock`);
5504
- }
5505
- }
5506
- const resolved = getSupportedPythonVersion({
5474
+ if (entrypointNotFound && detected?.baseDir === void 0) {
5475
+ throw entrypointNotFound;
5476
+ }
5477
+ const entryDirectory = detected?.baseDir ?? (0, import_path12.dirname)(entrypoint);
5478
+ const entrypointAbsDir = (0, import_path12.join)(workPath, entryDirectory);
5479
+ const rootDir = repoRootPath ?? workPath;
5480
+ const pythonPackage = await builderSpan.child("vc.builder.python.discover").trace(
5481
+ () => discoverPackage({
5482
+ entrypointDir: entrypointAbsDir,
5483
+ rootDir
5484
+ })
5485
+ );
5486
+ const { pythonVersion, pinVersionFilePath } = await builderSpan.child("vc.builder.python.version").trace((versionSpan) => {
5487
+ const resolution = resolvePythonVersion({
5507
5488
  isDev: meta.isDev,
5508
- declaredPythonVersion: declared
5489
+ pythonPackage,
5490
+ rootDir
5509
5491
  });
5510
5492
  versionSpan.setAttributes({
5511
- "python.version": resolved.version,
5512
- "python.versionSource": declared?.source
5493
+ "python.version": pythonVersionString(resolution.pythonVersion),
5494
+ "python.versionSource": resolution.versionSource
5513
5495
  });
5514
- return { pythonVersion: resolved, declaredPythonVersion: declared };
5496
+ return resolution;
5515
5497
  });
5516
- const selectedVersionTuple = parseVersionTuple(pythonVersion.version);
5517
- const defaultVersionTuple = parseVersionTuple(DEFAULT_PYTHON_VERSION);
5518
- if (!pythonVersionFileDir && pyprojectDir && declaredPythonVersion?.source === "pyproject.toml" && selectedVersionTuple && defaultVersionTuple && compareTuples(selectedVersionTuple, defaultVersionTuple) <= 0) {
5519
- const pythonVersionFilePath = (0, import_path10.join)(pyprojectDir, ".python-version");
5520
- await writeFile(pythonVersionFilePath, `${pythonVersion.version}
5521
- `);
5498
+ if (pinVersionFilePath) {
5522
5499
  console.log(
5523
- `Writing .python-version file with version ${pythonVersion.version}`
5500
+ `Writing .python-version file with version ${pythonVersionString(pythonVersion)}`
5501
+ );
5502
+ await writeFile(
5503
+ pinVersionFilePath,
5504
+ `${pythonVersionString(pythonVersion)}
5505
+ `
5524
5506
  );
5525
5507
  }
5526
- fsFiles = await (0, import_build_utils12.glob)("**", workPath);
5527
- const venvPath = (0, import_path10.join)(workPath, ".vercel", "python", ".venv");
5508
+ fsFiles = await (0, import_build_utils13.glob)("**", workPath);
5509
+ const venvPath = (0, import_path12.join)(workPath, ".vercel", "python", ".venv");
5510
+ const uvCacheDir = getUvCacheDir(workPath);
5528
5511
  await builderSpan.child("vc.builder.python.venv").trace(async () => {
5529
5512
  await ensureVenv({
5530
5513
  pythonPath: pythonVersion.pythonPath,
5531
- venvPath
5514
+ venvPath,
5515
+ uvCacheDir
5532
5516
  });
5533
5517
  });
5534
- if ((0, import_build_utils12.isPythonFramework)(framework)) {
5518
+ if ((0, import_build_utils13.isPythonFramework)(framework)) {
5535
5519
  const {
5536
5520
  cliType,
5537
5521
  lockfileVersion,
5538
5522
  packageJsonPackageManager,
5539
5523
  turboSupportsCorepackHome
5540
- } = await (0, import_build_utils12.scanParentDirs)(workPath, true);
5541
- spawnEnv = (0, import_build_utils12.getEnvForPackageManager)({
5524
+ } = await (0, import_build_utils13.scanParentDirs)(workPath, true);
5525
+ spawnEnv = (0, import_build_utils13.getEnvForPackageManager)({
5542
5526
  cliType,
5543
5527
  lockfileVersion,
5544
5528
  packageJsonPackageManager,
@@ -5557,14 +5541,14 @@ ${pipfileLockContent}`
5557
5541
  }
5558
5542
  }
5559
5543
  const baseEnv = spawnEnv || process.env;
5560
- const pythonEnv = createVenvEnv(venvPath, baseEnv);
5544
+ const pythonEnv = createVenvEnv(venvPath, baseEnv, uvCacheDir);
5561
5545
  pythonEnv.VERCEL_PYTHON_VENV_PATH = venvPath;
5562
5546
  let assumeDepsInstalled = false;
5563
5547
  let uv;
5564
5548
  try {
5565
5549
  const uvPath = await getUvBinaryOrInstall(pythonVersion.pythonPath);
5566
5550
  console.log(`Using uv at "${uvPath}"`);
5567
- uv = new UvRunner(uvPath);
5551
+ uv = new UvRunner(uvPath, uvCacheDir);
5568
5552
  } catch (err) {
5569
5553
  console.log("Failed to install or locate uv");
5570
5554
  throw new Error(
@@ -5575,14 +5559,14 @@ ${pipfileLockContent}`
5575
5559
  let uvProjectDir = null;
5576
5560
  let projectName;
5577
5561
  let noBuildCheckFailed = false;
5578
- await builderSpan.child(import_build_utils12.BUILDER_INSTALLER_STEP, {
5562
+ await builderSpan.child(import_build_utils13.BUILDER_INSTALLER_STEP, {
5579
5563
  installCommand: projectInstallCommand || void 0
5580
5564
  }).trace(async () => {
5581
5565
  if (projectInstallCommand) {
5582
5566
  console.log(
5583
5567
  `Running "install" command: \`${projectInstallCommand}\`...`
5584
5568
  );
5585
- await (0, import_build_utils12.execCommand)(projectInstallCommand, {
5569
+ await (0, import_build_utils13.execCommand)(projectInstallCommand, {
5586
5570
  env: pythonEnv,
5587
5571
  cwd: workPath
5588
5572
  });
@@ -5603,21 +5587,16 @@ ${pipfileLockContent}`
5603
5587
  if (!assumeDepsInstalled) {
5604
5588
  const { projectDir, lockPath, lockFileProvidedByUser } = await ensureUvProject({
5605
5589
  workPath,
5606
- entryDirectory,
5607
- repoRootPath,
5608
- pythonVersion: pythonVersion.version,
5590
+ rootDir,
5591
+ pythonPackage,
5592
+ pythonVersion: pythonVersionString(pythonVersion),
5609
5593
  uv,
5610
5594
  generateLockFile: true,
5611
5595
  requireBinaryWheels: false
5612
5596
  });
5613
5597
  uvLockPath = lockPath;
5614
5598
  uvProjectDir = projectDir;
5615
- const installInfo = await detectInstallSource({
5616
- workPath,
5617
- entryDirectory,
5618
- repoRootPath
5619
- });
5620
- projectName = installInfo.pythonPackage?.manifest?.data?.project?.name;
5599
+ projectName = pythonPackage?.manifest?.data?.project?.name;
5621
5600
  if (lockFileProvidedByUser) {
5622
5601
  try {
5623
5602
  await uv.sync({
@@ -5629,7 +5608,7 @@ ${pipfileLockContent}`
5629
5608
  });
5630
5609
  } catch (err) {
5631
5610
  noBuildCheckFailed = true;
5632
- (0, import_build_utils12.debug)(
5611
+ (0, import_build_utils13.debug)(
5633
5612
  `--no-build check failed: ${err instanceof Error ? err.message : String(err)}`
5634
5613
  );
5635
5614
  }
@@ -5642,15 +5621,15 @@ ${pipfileLockContent}`
5642
5621
  });
5643
5622
  }
5644
5623
  });
5645
- if ((0, import_build_utils12.isPythonFramework)(framework)) {
5624
+ if ((0, import_build_utils13.isPythonFramework)(framework)) {
5646
5625
  const projectBuildCommand = config?.projectSettings?.buildCommand ?? // fallback if provided directly on config (some callers set this)
5647
5626
  config?.buildCommand;
5648
- await builderSpan.child(import_build_utils12.BUILDER_COMPILE_STEP, {
5627
+ await builderSpan.child(import_build_utils13.BUILDER_COMPILE_STEP, {
5649
5628
  buildCommand: projectBuildCommand || void 0
5650
5629
  }).trace(async () => {
5651
5630
  if (projectBuildCommand) {
5652
5631
  console.log(`Running "${projectBuildCommand}"`);
5653
- await (0, import_build_utils12.execCommand)(projectBuildCommand, {
5632
+ await (0, import_build_utils13.execCommand)(projectBuildCommand, {
5654
5633
  env: pythonEnv,
5655
5634
  cwd: workPath
5656
5635
  });
@@ -5663,19 +5642,32 @@ ${pipfileLockContent}`
5663
5642
  }
5664
5643
  });
5665
5644
  }
5645
+ const hookResult = await runFrameworkHook(framework, {
5646
+ pythonEnv,
5647
+ projectDir: (0, import_path12.join)(workPath, entryDirectory),
5648
+ entrypoint,
5649
+ detected
5650
+ });
5651
+ if (entrypointNotFound && hookResult?.entrypoint) {
5652
+ entrypoint = hookResult.entrypoint;
5653
+ entrypointNotFound = void 0;
5654
+ }
5655
+ if (entrypointNotFound) {
5656
+ throw entrypointNotFound;
5657
+ }
5666
5658
  const runtimeDep = baseEnv.VERCEL_RUNTIME_PYTHON || `vercel-runtime==${VERCEL_RUNTIME_VERSION}`;
5667
- (0, import_build_utils12.debug)(`Installing ${runtimeDep}`);
5659
+ (0, import_build_utils13.debug)(`Installing ${runtimeDep}`);
5668
5660
  await uv.pip({
5669
5661
  venvPath,
5670
- projectDir: (0, import_path10.join)(workPath, entryDirectory),
5662
+ projectDir: (0, import_path12.join)(workPath, entryDirectory),
5671
5663
  args: ["install", runtimeDep]
5672
5664
  });
5673
5665
  if (shouldInstallVercelWorkers) {
5674
5666
  const workersDep = baseEnv.VERCEL_WORKERS_PYTHON || `vercel-workers==${VERCEL_WORKERS_VERSION}`;
5675
- (0, import_build_utils12.debug)(`Installing ${workersDep}`);
5667
+ (0, import_build_utils13.debug)(`Installing ${workersDep}`);
5676
5668
  await uv.pip({
5677
5669
  venvPath,
5678
- projectDir: (0, import_path10.join)(workPath, entryDirectory),
5670
+ projectDir: (0, import_path12.join)(workPath, entryDirectory),
5679
5671
  args: ["install", workersDep]
5680
5672
  });
5681
5673
  }
@@ -5683,12 +5675,26 @@ ${pipfileLockContent}`
5683
5675
  if (quirksResult.buildEnv) {
5684
5676
  Object.assign(pythonEnv, quirksResult.buildEnv);
5685
5677
  }
5686
- (0, import_build_utils12.debug)("Entrypoint is", entrypoint);
5678
+ (0, import_build_utils13.debug)("Entrypoint is", entrypoint);
5687
5679
  const moduleName = entrypoint.replace(/\//g, ".").replace(/\.py$/i, "");
5680
+ const handlerFunction = typeof config?.handlerFunction === "string" ? config.handlerFunction : void 0;
5681
+ if (handlerFunction) {
5682
+ const entrypointPath = (0, import_path12.join)(workPath, entrypoint);
5683
+ const source = await import_fs10.default.promises.readFile(entrypointPath, "utf-8");
5684
+ const found = await (0, import_python_analysis7.containsTopLevelCallable)(source, handlerFunction);
5685
+ if (!found) {
5686
+ throw new import_build_utils13.NowBuildError({
5687
+ code: "PYTHON_HANDLER_NOT_FOUND",
5688
+ message: `Handler function "${handlerFunction}" not found in ${entrypoint}. Ensure it is defined at the module's top level.`
5689
+ });
5690
+ }
5691
+ }
5688
5692
  const vendorDir = resolveVendorDir();
5689
5693
  const suffix = meta.isDev && !entrypoint.endsWith(".py") ? ".py" : "";
5690
5694
  const entrypointWithSuffix = `${entrypoint}${suffix}`;
5691
- (0, import_build_utils12.debug)("Entrypoint with suffix is", entrypointWithSuffix);
5695
+ (0, import_build_utils13.debug)("Entrypoint with suffix is", entrypointWithSuffix);
5696
+ const handlerFuncEnvLine = handlerFunction ? `
5697
+ "__VC_HANDLER_FUNC_NAME": "${handlerFunction}",` : "";
5692
5698
  const runtimeTrampoline = `
5693
5699
  import importlib
5694
5700
  import os
@@ -5702,7 +5708,7 @@ os.environ.update({
5702
5708
  "__VC_HANDLER_MODULE_NAME": "${moduleName}",
5703
5709
  "__VC_HANDLER_ENTRYPOINT": "${entrypointWithSuffix}",
5704
5710
  "__VC_HANDLER_ENTRYPOINT_ABS": os.path.join(_here, "${entrypointWithSuffix}"),
5705
- "__VC_HANDLER_VENDOR_DIR": "${vendorDir}",
5711
+ "__VC_HANDLER_VENDOR_DIR": "${vendorDir}",${handlerFuncEnvLine}
5706
5712
  })
5707
5713
 
5708
5714
  _vendor_rel = '${vendorDir}'
@@ -5752,7 +5758,7 @@ from vercel_runtime.vc_init import vc_handler
5752
5758
  cwd: workPath,
5753
5759
  ignore: config && typeof config.excludeFiles === "string" ? [...predefinedExcludes, config.excludeFiles] : predefinedExcludes
5754
5760
  };
5755
- const files = await (0, import_build_utils12.glob)("**", globOptions);
5761
+ const files = await (0, import_build_utils13.glob)("**", globOptions);
5756
5762
  const depExternalizer = new PythonDependencyExternalizer({
5757
5763
  venvPath,
5758
5764
  vendorDir,
@@ -5764,7 +5770,7 @@ from vercel_runtime.vc_init import vc_handler
5764
5770
  pythonPath: pythonVersion.pythonPath,
5765
5771
  hasCustomCommand,
5766
5772
  alwaysBundlePackages: [
5767
- ...quirksResult.alwaysBundlePackages,
5773
+ ...quirksResult.alwaysBundlePackages ?? [],
5768
5774
  ...shouldInstallVercelWorkers ? ["vercel-workers", "vercel_workers"] : []
5769
5775
  ]
5770
5776
  });
@@ -5785,12 +5791,12 @@ from vercel_runtime.vc_init import vc_handler
5785
5791
  }
5786
5792
  });
5787
5793
  const handlerPyFilename = "vc__handler__python";
5788
- files[`${handlerPyFilename}.py`] = new import_build_utils12.FileBlob({ data: runtimeTrampoline });
5794
+ files[`${handlerPyFilename}.py`] = new import_build_utils13.FileBlob({ data: runtimeTrampoline });
5789
5795
  if (config.framework === "fasthtml") {
5790
5796
  const { SESSKEY = "" } = process.env;
5791
- files[".sesskey"] = new import_build_utils12.FileBlob({ data: `"${SESSKEY}"` });
5797
+ files[".sesskey"] = new import_build_utils13.FileBlob({ data: `"${SESSKEY}"` });
5792
5798
  }
5793
- const output = new import_build_utils12.Lambda({
5799
+ const output = new import_build_utils13.Lambda({
5794
5800
  files,
5795
5801
  handler: `${handlerPyFilename}.vc_handler`,
5796
5802
  runtime: pythonVersion.runtime,
@@ -5799,9 +5805,44 @@ from vercel_runtime.vc_init import vc_handler
5799
5805
  });
5800
5806
  return { output };
5801
5807
  };
5808
+ async function readBuildOutputV3Config(workPath) {
5809
+ try {
5810
+ const configPath = (0, import_path12.join)(workPath, ".vercel", "output", "config.json");
5811
+ return JSON.parse(await import_fs10.default.promises.readFile(configPath, "utf8"));
5812
+ } catch (err) {
5813
+ if (err.code !== "ENOENT") {
5814
+ throw err;
5815
+ }
5816
+ }
5817
+ return void 0;
5818
+ }
5819
+ var prepareCache = async ({
5820
+ repoRootPath,
5821
+ workPath
5822
+ }) => {
5823
+ const cacheFiles = {};
5824
+ const root = repoRootPath || workPath;
5825
+ const ignore = ["**/*.pyc", "**/__pycache__/**"];
5826
+ const configV3 = await readBuildOutputV3Config(workPath);
5827
+ if (configV3?.cache && Array.isArray(configV3.cache)) {
5828
+ for (const cacheGlob of configV3.cache) {
5829
+ Object.assign(cacheFiles, await (0, import_build_utils13.glob)(cacheGlob, workPath));
5830
+ }
5831
+ return cacheFiles;
5832
+ }
5833
+ Object.assign(
5834
+ cacheFiles,
5835
+ await (0, import_build_utils13.glob)("**/.vercel/python/.venv/**", { cwd: root, ignore })
5836
+ );
5837
+ Object.assign(
5838
+ cacheFiles,
5839
+ await (0, import_build_utils13.glob)("**/.vercel/python/cache/uv/**", { cwd: root, ignore })
5840
+ );
5841
+ return cacheFiles;
5842
+ };
5802
5843
  var shouldServe = (opts) => {
5803
5844
  const framework = opts.config.framework;
5804
- if ((0, import_build_utils12.isPythonFramework)(framework)) {
5845
+ if ((0, import_build_utils13.isPythonFramework)(framework)) {
5805
5846
  const requestPath = opts.requestPath.replace(/\/$/, "");
5806
5847
  if (requestPath.startsWith("api") && opts.hasMatched) {
5807
5848
  return false;
@@ -5820,7 +5861,7 @@ var defaultShouldServe = ({
5820
5861
  if (entrypoint === requestPath && hasProp(files, entrypoint)) {
5821
5862
  return true;
5822
5863
  }
5823
- const { dir, name } = (0, import_path10.parse)(entrypoint);
5864
+ const { dir, name } = (0, import_path12.parse)(entrypoint);
5824
5865
  if (name === "index" && dir === requestPath && hasProp(files, entrypoint)) {
5825
5866
  return true;
5826
5867
  }
@@ -5829,16 +5870,6 @@ var defaultShouldServe = ({
5829
5870
  function hasProp(obj, key) {
5830
5871
  return Object.hasOwnProperty.call(obj, key);
5831
5872
  }
5832
- function parsePythonVersionFile(content) {
5833
- const lines = content.split("\n");
5834
- for (const line of lines) {
5835
- const trimmed = line.trim();
5836
- if (!trimmed || trimmed.startsWith("#"))
5837
- continue;
5838
- return trimmed;
5839
- }
5840
- return void 0;
5841
- }
5842
5873
  // Annotate the CommonJS export names for ESM import in node:
5843
5874
  0 && (module.exports = {
5844
5875
  build,
@@ -5846,6 +5877,8 @@ function parsePythonVersionFile(content) {
5846
5877
  downloadFilesInWorkPath,
5847
5878
  installRequirement,
5848
5879
  installRequirementsFile,
5880
+ prepareCache,
5881
+ runFrameworkHook,
5849
5882
  shouldServe,
5850
5883
  startDevServer,
5851
5884
  version