@varlock/nextjs-integration 1.0.1 → 1.1.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.
@@ -2,7 +2,7 @@
2
2
 
3
3
  var os = require('os');
4
4
  var path3 = require('path');
5
- var fs32 = require('fs');
5
+ var fs5 = require('fs');
6
6
  var util = require('util');
7
7
  var P2 = require('process');
8
8
  var _ = require('readline');
@@ -41,7 +41,7 @@ function _interopNamespace(e) {
41
41
 
42
42
  var os__default = /*#__PURE__*/_interopDefault(os);
43
43
  var path3__namespace = /*#__PURE__*/_interopNamespace(path3);
44
- var fs32__namespace = /*#__PURE__*/_interopNamespace(fs32);
44
+ var fs5__namespace = /*#__PURE__*/_interopNamespace(fs5);
45
45
  var P2__default = /*#__PURE__*/_interopDefault(P2);
46
46
  var ___namespace = /*#__PURE__*/_interopNamespace(_);
47
47
  var fs3__default = /*#__PURE__*/_interopDefault(fs3);
@@ -98,15 +98,31 @@ function getUserVarlockDir() {
98
98
  return path3.join(process.env.XDG_CONFIG_HOME, "varlock");
99
99
  }
100
100
  const legacyDir = path3.join(home, ".varlock");
101
- if (fs32.existsSync(legacyDir)) {
101
+ if (fs5.existsSync(legacyDir)) {
102
102
  return legacyDir;
103
103
  }
104
104
  return path3.join(home, ".config", "varlock");
105
105
  }
106
- var init_chunk_7WB7HK5Z = __esm({
107
- "../../varlock/dist/chunk-7WB7HK5Z.js"() {
106
+ function isWSL() {
107
+ if (_isWSL !== void 0) return _isWSL;
108
+ if (process.env.WSL_DISTRO_NAME) {
109
+ _isWSL = true;
110
+ return true;
111
+ }
112
+ try {
113
+ const version = fs5__namespace.default.readFileSync("/proc/version", "utf-8");
114
+ _isWSL = /microsoft|wsl/i.test(version);
115
+ } catch {
116
+ _isWSL = false;
117
+ }
118
+ return _isWSL;
119
+ }
120
+ var _isWSL;
121
+ var init_chunk_O3WTD6L4 = __esm({
122
+ "../../varlock/dist/chunk-O3WTD6L4.js"() {
108
123
  init_chunk_6PEHRAEP();
109
124
  __name(getUserVarlockDir, "getUserVarlockDir");
125
+ __name(isWSL, "isWSL");
110
126
  }
111
127
  });
112
128
  function wrapAnsi(string, columns, options) {
@@ -1780,10 +1796,10 @@ ${o}
1780
1796
  if (s === "") return [];
1781
1797
  try {
1782
1798
  let r;
1783
- fs32.existsSync(s) ? fs32.lstatSync(s).isDirectory() && (!e.directory || s.endsWith("/")) ? r = s : r = path3.dirname(s) : r = path3.dirname(s);
1799
+ fs5.existsSync(s) ? fs5.lstatSync(s).isDirectory() && (!e.directory || s.endsWith("/")) ? r = s : r = path3.dirname(s) : r = path3.dirname(s);
1784
1800
  const u2 = s.length > 1 && s.endsWith("/") ? s.slice(0, -1) : s;
1785
- return fs32.readdirSync(r).map((n) => {
1786
- const o = path3.join(r, n), c2 = fs32.lstatSync(o);
1801
+ return fs5.readdirSync(r).map((n) => {
1802
+ const o = path3.join(r, n), c2 = fs5.lstatSync(o);
1787
1803
  return { name: n, path: o, isDirectory: c2.isDirectory() };
1788
1804
  }).filter(({ path: n, isDirectory: o }) => n.startsWith(u2) && (o || !e.directory)).map((n) => ({ value: n.path }));
1789
1805
  } catch {
@@ -3162,15 +3178,15 @@ var init_dist_WGIHRGBZ = __esm({
3162
3178
  }
3163
3179
  });
3164
3180
 
3165
- // ../../varlock/dist/config-item-2FQ6I6PO.js
3166
- var config_item_2FQ6I6PO_exports = {};
3167
- __export(config_item_2FQ6I6PO_exports, {
3181
+ // ../../varlock/dist/config-item-6LTV4PNH.js
3182
+ var config_item_6LTV4PNH_exports = {};
3183
+ __export(config_item_6LTV4PNH_exports, {
3168
3184
  ConfigItem: () => ConfigItem
3169
3185
  });
3170
- var init_config_item_2FQ6I6PO = __esm({
3171
- "../../varlock/dist/config-item-2FQ6I6PO.js"() {
3172
- init_chunk_U7RQPX5K();
3173
- init_chunk_7WB7HK5Z();
3186
+ var init_config_item_6LTV4PNH = __esm({
3187
+ "../../varlock/dist/config-item-6LTV4PNH.js"() {
3188
+ init_chunk_XWYFSG46();
3189
+ init_chunk_O3WTD6L4();
3174
3190
  init_chunk_HDKXXS2X();
3175
3191
  init_chunk_2PFIYNFA();
3176
3192
  init_chunk_6PEHRAEP();
@@ -7504,15 +7520,15 @@ function findGraphCycles(graph) {
7504
7520
  }
7505
7521
  async function fetchIconSvg(iconifyName, color = "808080", iconCacheFolder = "/tmp/varlock-icon-cache") {
7506
7522
  if (!iconCacheFolderInit) {
7507
- fs32__namespace.default.mkdirSync(iconCacheFolder, { recursive: true });
7523
+ fs5__namespace.default.mkdirSync(iconCacheFolder, { recursive: true });
7508
7524
  iconCacheFolderInit = true;
7509
7525
  }
7510
7526
  const iconPath = `${iconCacheFolder}/${iconifyName}-${ICON_SIZE}.svg`;
7511
7527
  let svgSrc;
7512
7528
  if (iconInMemoryCache[iconPath]) {
7513
7529
  svgSrc = iconInMemoryCache[iconPath];
7514
- } else if (fs32__namespace.default.existsSync(iconPath)) {
7515
- const svgFileBuffer = await fs32__namespace.default.promises.readFile(iconPath, "utf-8");
7530
+ } else if (fs5__namespace.default.existsSync(iconPath)) {
7531
+ const svgFileBuffer = await fs5__namespace.default.promises.readFile(iconPath, "utf-8");
7516
7532
  svgSrc = svgFileBuffer.toString();
7517
7533
  iconInMemoryCache[iconPath] = svgSrc;
7518
7534
  } else {
@@ -7524,7 +7540,7 @@ async function fetchIconSvg(iconifyName, color = "808080", iconCacheFolder = "/t
7524
7540
  }
7525
7541
  if (!svgSrc) return;
7526
7542
  if (svgSrc) {
7527
- await fs32__namespace.default.promises.writeFile(iconPath, svgSrc, "utf-8");
7543
+ await fs5__namespace.default.promises.writeFile(iconPath, svgSrc, "utf-8");
7528
7544
  iconInMemoryCache[iconPath] = svgSrc;
7529
7545
  }
7530
7546
  }
@@ -7566,6 +7582,10 @@ async function getTsDefinitionForItem(info, indentLevel = 0) {
7566
7582
  jsDocLines.push(`\u{1F4DA} {@link ${docsLink}}`);
7567
7583
  });
7568
7584
  }
7585
+ if (info.isDeprecated) {
7586
+ jsDocLines.push("");
7587
+ jsDocLines.push(info.deprecationMessage ? `@deprecated ${info.deprecationMessage}` : "@deprecated");
7588
+ }
7569
7589
  if (jsDocLines.length === 1) {
7570
7590
  itemSrc.push(`/** ${jsDocLines[0]} */`);
7571
7591
  } else if (jsDocLines.length > 1) {
@@ -7645,7 +7665,7 @@ async function generateTypes(graph, lang, typesPath) {
7645
7665
  items.push(await configItem.getTypeGenInfo());
7646
7666
  }
7647
7667
  const tsSrc = await generateTsTypesSrc(items);
7648
- await fs32__namespace.default.promises.writeFile(typesPath, tsSrc, "utf-8");
7668
+ await fs5__namespace.default.promises.writeFile(typesPath, tsSrc, "utf-8");
7649
7669
  }
7650
7670
  function getErrorLocation(source, parserNode) {
7651
7671
  if (!(source instanceof FileBasedDataSource)) return;
@@ -7905,7 +7925,7 @@ async function pathExists(p2) {
7905
7925
  }
7906
7926
  function pathExistsSync(p2) {
7907
7927
  try {
7908
- fs32.accessSync(p2);
7928
+ fs5.accessSync(p2);
7909
7929
  return true;
7910
7930
  } catch {
7911
7931
  return false;
@@ -7996,7 +8016,7 @@ function detectWorkspaceInfo(opts) {
7996
8016
  const rootPackageJsonPath = path3__namespace.default.join(foundRootPath, "package.json");
7997
8017
  if (pathExistsSync(rootPackageJsonPath)) {
7998
8018
  try {
7999
- const packageJson = JSON.parse(fs32__namespace.default.readFileSync(rootPackageJsonPath, "utf-8"));
8019
+ const packageJson = JSON.parse(fs5__namespace.default.readFileSync(rootPackageJsonPath, "utf-8"));
8000
8020
  if (packageJson.workspaces) isMonorepo = true;
8001
8021
  } catch {
8002
8022
  }
@@ -8053,7 +8073,7 @@ function applyBunCryptoShim() {
8053
8073
  }
8054
8074
  function loadPluginModuleCJS(filePath) {
8055
8075
  applyBunCryptoShim();
8056
- const code = fs32__namespace.default.readFileSync(filePath, "utf-8");
8076
+ const code = fs5__namespace.default.readFileSync(filePath, "utf-8");
8057
8077
  const pluginDir = path3__namespace.default.dirname(filePath);
8058
8078
  const moduleObj = { exports: {} };
8059
8079
  const baseRequire = module$1.createRequire(filePath);
@@ -8184,7 +8204,7 @@ async function downloadPlugin(url) {
8184
8204
  }
8185
8205
  const tmpTgz = path3__namespace.default.join(cacheDir, `tmp-${crypto2__default.default.randomBytes(8).toString("hex")}.tgz`);
8186
8206
  await new Promise((resolve2, reject) => {
8187
- const file = fs32__namespace.default.createWriteStream(tmpTgz);
8207
+ const file = fs5__namespace.default.createWriteStream(tmpTgz);
8188
8208
  https__default.default.get(url, (res) => {
8189
8209
  if (res.statusCode !== 200) {
8190
8210
  reject(new Error(`Failed to download plugin: ${res.statusCode}`));
@@ -8515,9 +8535,9 @@ function coerceToNumber(rawVal) {
8515
8535
  return numVal;
8516
8536
  }
8517
8537
  var require_ansis, require_constants, require_debug, require_re, require_parse_options, require_identifiers, require_semver, require_parse, require_valid, require_clean, require_inc, require_diff, require_major, require_minor, require_patch, require_prerelease, require_compare, require_rcompare, require_compare_loose, require_compare_build, require_sort, require_rsort, require_gt, require_lt, require_eq, require_neq, require_gte, require_lte, require_cmp, require_coerce, require_lrucache, require_range, require_comparator, require_satisfies, require_to_comparators, require_max_satisfying, require_min_satisfying, require_min_version, require_valid2, require_outside, require_gtr, require_ltr, require_intersects, require_simplify, require_subset, require_semver2, __defProp3, __name2, VALID_NUMBER_REGEX, ParsedEnvSpecDivider, ParsedEnvSpecStaticValue, ParsedEnvSpecKeyValuePair, ParsedEnvSpecFunctionArgs, ParsedEnvSpecFunctionCall, ParsedEnvSpecDecorator, ParsedEnvSpecComment, ParsedEnvSpecDecoratorComment, ParsedEnvSpecCommentBlock, ParsedEnvSpecBlankLine, ParsedEnvSpecConfigItem, ParsedEnvSpecFile, EXPAND_VAR_BRACKETED_REGEX, EXPAND_VAR_SIMPLE_REGEX, EXPAND_EXEC_REGEX, peg$SyntaxError, SimpleQueue, AUTOGENERATED_FILE_BANNER, ICON_SIZE, iconCacheFolderInit, iconInMemoryCache, PLATFORMS, VALID_ENVIRONMENTS, ExecError, asyncExec, BUILTIN_VARS, processExists2, originalProcessEnv2, EnvGraph, import_index, ansis_default, Ansis, fg, bg, rgb, bgRgb, hex, bgHex, reset, inverse, hidden, visible, bold, dim, italic, underline, strikethrough, black, red, green, yellow, blue, magenta, cyan, white, gray, redBright, greenBright, yellowBright, blueBright, magentaBright, cyanBright, whiteBright, bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, bgWhite, bgGray, bgRedBright, bgGreenBright, bgYellowBright, bgBlueBright, bgMagentaBright, bgCyanBright, bgWhiteBright, import_semver, unicode, unicodeOr, S_STEP_ACTIVE, S_STEP_CANCEL, S_STEP_ERROR, S_STEP_SUBMIT, S_BAR, S_BAR_END, S_RADIO_ACTIVE, S_RADIO_INACTIVE, S_CHECKBOX_ACTIVE, S_CHECKBOX_SELECTED, S_CHECKBOX_INACTIVE, S_PASSWORD_MASK, symbol, limitOptions, confirm, select, multiselect, password, prompts, prompts_default, debug2, JS_PACKAGE_MANAGERS, workspaceInfoStorage, importedPluginModulePaths, _cryptoShimApplied, isBunRuntime, varlockPluginLibExports, VarlockPlugin, DATA_SOURCE_TYPES, EnvGraphDataSource2, ImportAliasSource, FileBasedDataSource, DotEnvFileDataSource, DirectoryDataSource, MultiplePathsContainerDataSource, DecoratorInstance, ItemDecoratorInstance, RootDecoratorInstance2, builtInRootDecorators, builtInItemDecorators, execAsync, REGEX_LIKE_STRING, Resolver, StaticValueResolver, FunctionArgsResolver, ErrorResolver, ConcatResolver, FallbackResolver, execQueue, ExecResolver, RefResolver, RegexResolver, RemapResolver, ForEnvResolver, EqResolver, IfResolver, IfsResolver, NotResolver, IsEmptyResolver, InferFromPrefixResolver, BaseResolvers, EnvGraphDataType, StringDataType, NumberDataType, BooleanDataType, UrlDataType, SimpleObjectDataType, EnumDataType, EMAIL_REGEX, EmailDataType, IP_V4_ADDRESS_REGEX, IP_V6_ADDRESS_REGEX, IpAddressDataType, PortDataType, SEMVER_REGEX, SemverDataType, ISO_DATE_REGEX, IsoDateDataType, UUID_REGEX, UuidDataType, MD5_REGEX, Md5DataType, BaseDataTypes, ConfigItem;
8518
- var init_chunk_U7RQPX5K = __esm({
8519
- "../../varlock/dist/chunk-U7RQPX5K.js"() {
8520
- init_chunk_7WB7HK5Z();
8538
+ var init_chunk_XWYFSG46 = __esm({
8539
+ "../../varlock/dist/chunk-XWYFSG46.js"() {
8540
+ init_chunk_O3WTD6L4();
8521
8541
  init_chunk_HDKXXS2X();
8522
8542
  init_chunk_2PFIYNFA();
8523
8543
  init_chunk_6PEHRAEP();
@@ -12134,7 +12154,7 @@ ${ansis_default.cyan(S_BAR_END)}
12134
12154
  password = /* @__PURE__ */ __name(async (opts) => {
12135
12155
  return enqueuePasswordPrompt(async () => {
12136
12156
  const mask = opts.mask ?? S_PASSWORD_MASK;
12137
- if (process.platform === "win32") {
12157
+ if (process.platform === "win32" || isWSL()) {
12138
12158
  const { password: clackPassword, isCancel } = await Promise.resolve().then(() => (init_dist_WGIHRGBZ(), dist_WGIHRGBZ_exports));
12139
12159
  const result = await clackPassword({ message: opts.message, mask });
12140
12160
  return isCancel(result) ? /* @__PURE__ */ Symbol("cancel") : result;
@@ -13420,7 +13440,7 @@ ${ansis_default.cyan(S_BAR_END)}
13420
13440
  dataSource._loadingError = err instanceof SchemaError ? err : new SchemaError(err);
13421
13441
  return;
13422
13442
  }
13423
- const { ConfigItem: ConfigItem2 } = await Promise.resolve().then(() => (init_config_item_2FQ6I6PO(), config_item_2FQ6I6PO_exports));
13443
+ const { ConfigItem: ConfigItem2 } = await Promise.resolve().then(() => (init_config_item_6LTV4PNH(), config_item_6LTV4PNH_exports));
13424
13444
  for (const [key, entry] of Object.entries(entries)) {
13425
13445
  const existsInSchema = key in graph.configSchema;
13426
13446
  if (!existsInSchema && !createMissing) {
@@ -13477,6 +13497,9 @@ ${ansis_default.cyan(S_BAR_END)}
13477
13497
  {
13478
13498
  name: "icon"
13479
13499
  },
13500
+ {
13501
+ name: "deprecated"
13502
+ },
13480
13503
  // test-only decorators — dropped in release builds
13481
13504
  ...[]
13482
13505
  ];
@@ -14455,6 +14478,18 @@ ${ansis_default.cyan(S_BAR_END)}
14455
14478
  if (explicitIconDec) return explicitIconDec.resolvedValue;
14456
14479
  return this.dataType?.icon;
14457
14480
  }
14481
+ get isDeprecated() {
14482
+ const deprecatedDec = this.getDec("deprecated");
14483
+ if (!deprecatedDec) return false;
14484
+ const val = deprecatedDec.parsedDecorator.simplifiedValue;
14485
+ return val === true || typeof val === "string";
14486
+ }
14487
+ get deprecationMessage() {
14488
+ const deprecatedDec = this.getDec("deprecated");
14489
+ if (!deprecatedDec) return void 0;
14490
+ const val = deprecatedDec.parsedDecorator.simplifiedValue;
14491
+ return typeof val === "string" ? val : void 0;
14492
+ }
14458
14493
  get docsLinks() {
14459
14494
  const links = [];
14460
14495
  if (this.dataType?.docsEntries) {
@@ -15031,7 +15066,9 @@ ${ansis_default.cyan(S_BAR_END)}
15031
15066
  isRequiredDynamic,
15032
15067
  isSensitive,
15033
15068
  icon,
15034
- docsLinks
15069
+ docsLinks,
15070
+ isDeprecated: this.isDeprecated,
15071
+ deprecationMessage: this.deprecationMessage
15035
15072
  };
15036
15073
  }
15037
15074
  };
@@ -15412,8 +15449,8 @@ function patchGlobalServerResponse(opts) {
15412
15449
  }
15413
15450
  __name(patchGlobalServerResponse, "patchGlobalServerResponse");
15414
15451
 
15415
- // ../../varlock/dist/chunk-FTVXXJMG.js
15416
- init_chunk_U7RQPX5K();
15452
+ // ../../varlock/dist/chunk-CDLU5P62.js
15453
+ init_chunk_XWYFSG46();
15417
15454
  init_chunk_6PEHRAEP();
15418
15455
  var import_semver2 = __toESM(require_semver2(), 1);
15419
15456
  var MIN_BUN_VERSION = "1.3.3";
@@ -15564,8 +15601,8 @@ function gracefulExit(signal) {
15564
15601
  }
15565
15602
  __name(gracefulExit, "gracefulExit");
15566
15603
 
15567
- // ../../varlock/dist/chunk-GBCB7Y3B.js
15568
- init_chunk_U7RQPX5K();
15604
+ // ../../varlock/dist/chunk-QP7TS4SU.js
15605
+ init_chunk_XWYFSG46();
15569
15606
  init_chunk_2PFIYNFA();
15570
15607
  init_chunk_6PEHRAEP();
15571
15608
  async function loadEnvGraph(opts) {
@@ -15583,7 +15620,7 @@ async function loadEnvGraph(opts) {
15583
15620
  } else if (rawPaths?.length === 1) {
15584
15621
  const entryFilePath = rawPaths[0];
15585
15622
  const resolvedPath = path3__namespace.default.resolve(entryFilePath);
15586
- const isDirectory = entryFilePath.endsWith("/") || entryFilePath.endsWith(path3__namespace.default.sep) || fs32__namespace.default.existsSync(resolvedPath) && fs32__namespace.default.statSync(resolvedPath).isDirectory();
15623
+ const isDirectory = entryFilePath.endsWith("/") || entryFilePath.endsWith(path3__namespace.default.sep) || fs5__namespace.default.existsSync(resolvedPath) && fs5__namespace.default.statSync(resolvedPath).isDirectory();
15587
15624
  if (isDirectory) {
15588
15625
  graph.basePath = resolvedPath;
15589
15626
  if (opts?.afterInit) await opts.afterInit(graph);
@@ -15668,9 +15705,10 @@ function getItemSummary(item) {
15668
15705
  const isRequired = item.isRequired;
15669
15706
  summary.push(joinAndCompact([
15670
15707
  icon,
15671
- ansis_default[VALIDATION_STATE_COLORS[item.validationState]](item.key) + (isRequired ? ansis_default.magenta("*") : ""),
15708
+ ansis_default[VALIDATION_STATE_COLORS[item.validationState]](item.isDeprecated ? ansis_default.strikethrough(item.key) : item.key) + (isRequired ? ansis_default.magenta("*") : ""),
15672
15709
  // ansis.gray(`[type = ${item.type.typeLabel}]`),
15673
- isSensitive && ` \u{1F510}${ansis_default.gray.italic("sensitive")}`
15710
+ isSensitive && ` \u{1F510}${ansis_default.gray.italic("sensitive")}`,
15711
+ item.isDeprecated && ` \u{1F635}${ansis_default.yellow.dim.italic("deprecated")}`
15674
15712
  // item.useAt ? ansis.gray.italic(`(${item.useAt?.join(', ')})`) : undefined,
15675
15713
  ]));
15676
15714
  let valAsStr = formattedValue(item.resolvedValue, false);
@@ -15721,8 +15759,8 @@ var CliExitError = class extends Error {
15721
15759
  }
15722
15760
  };
15723
15761
 
15724
- // ../../varlock/dist/chunk-UKFHSMKY.js
15725
- init_chunk_U7RQPX5K();
15762
+ // ../../varlock/dist/chunk-7GFD2ATN.js
15763
+ init_chunk_XWYFSG46();
15726
15764
  init_chunk_2PFIYNFA();
15727
15765
  init_chunk_6PEHRAEP();
15728
15766
  function showErrorLocationDetails(err) {
@@ -15851,25 +15889,9 @@ function checkForConfigErrors(envGraph, opts) {
15851
15889
  }
15852
15890
  __name(checkForConfigErrors, "checkForConfigErrors");
15853
15891
 
15854
- // ../../varlock/dist/chunk-6DXWXIQV.js
15855
- init_chunk_7WB7HK5Z();
15892
+ // ../../varlock/dist/chunk-GURKQO4J.js
15893
+ init_chunk_O3WTD6L4();
15856
15894
  init_chunk_6PEHRAEP();
15857
- var _isWSL;
15858
- function isWSL() {
15859
- if (_isWSL !== void 0) return _isWSL;
15860
- if (process.env.WSL_DISTRO_NAME) {
15861
- _isWSL = true;
15862
- return true;
15863
- }
15864
- try {
15865
- const version = fs32__namespace.default.readFileSync("/proc/version", "utf-8");
15866
- _isWSL = /microsoft|wsl/i.test(version);
15867
- } catch {
15868
- _isWSL = false;
15869
- }
15870
- return _isWSL;
15871
- }
15872
- __name(isWSL, "isWSL");
15873
15895
  var __dirname$1 = path3__namespace.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next-env-compat.js', document.baseURI).href))));
15874
15896
  function debug3(msg) {
15875
15897
  if (process.env.VARLOCK_DEBUG) {
@@ -15884,9 +15906,9 @@ function resolvePackageRoot() {
15884
15906
  let dir = __dirname$1;
15885
15907
  for (let i = 0; i < 10; i++) {
15886
15908
  const pkgJsonPath = path3__namespace.default.join(dir, "package.json");
15887
- if (fs32__namespace.default.existsSync(pkgJsonPath)) {
15909
+ if (fs5__namespace.default.existsSync(pkgJsonPath)) {
15888
15910
  try {
15889
- const pkgJson = JSON.parse(fs32__namespace.default.readFileSync(pkgJsonPath, "utf-8"));
15911
+ const pkgJson = JSON.parse(fs5__namespace.default.readFileSync(pkgJsonPath, "utf-8"));
15890
15912
  if (pkgJson.name === "varlock") return dir;
15891
15913
  } catch {
15892
15914
  }
@@ -15912,15 +15934,15 @@ function getNativeBinSubdir() {
15912
15934
  __name(getNativeBinSubdir, "getNativeBinSubdir");
15913
15935
  function resolveMacOSBinary(dir) {
15914
15936
  const appBundlePath = path3__namespace.default.join(dir, MACOS_APP_BUNDLE, "Contents", "MacOS", BINARY_NAME);
15915
- if (fs32__namespace.default.existsSync(appBundlePath)) return appBundlePath;
15937
+ if (fs5__namespace.default.existsSync(appBundlePath)) return appBundlePath;
15916
15938
  const barePath = path3__namespace.default.join(dir, BINARY_NAME);
15917
- if (fs32__namespace.default.existsSync(barePath)) return barePath;
15939
+ if (fs5__namespace.default.existsSync(barePath)) return barePath;
15918
15940
  return void 0;
15919
15941
  }
15920
15942
  __name(resolveMacOSBinary, "resolveMacOSBinary");
15921
15943
  function resolveStandardBinary(dir) {
15922
15944
  const binaryPath = path3__namespace.default.join(dir, getPlatformBinaryName());
15923
- if (fs32__namespace.default.existsSync(binaryPath)) return binaryPath;
15945
+ if (fs5__namespace.default.existsSync(binaryPath)) return binaryPath;
15924
15946
  return void 0;
15925
15947
  }
15926
15948
  __name(resolveStandardBinary, "resolveStandardBinary");
@@ -15930,7 +15952,7 @@ function resolveBinaryFromDir(dir) {
15930
15952
  }
15931
15953
  __name(resolveBinaryFromDir, "resolveBinaryFromDir");
15932
15954
  function resolveSeaSibling() {
15933
- const execDir = path3__namespace.default.dirname(fs32__namespace.default.realpathSync(process.execPath));
15955
+ const execDir = path3__namespace.default.dirname(fs5__namespace.default.realpathSync(process.execPath));
15934
15956
  const sibling = resolveBinaryFromDir(execDir);
15935
15957
  if (sibling) return sibling;
15936
15958
  const libexecDir = path3__namespace.default.join(execDir, "..", "libexec");
@@ -15940,9 +15962,9 @@ __name(resolveSeaSibling, "resolveSeaSibling");
15940
15962
  function resolveNpmBundled() {
15941
15963
  const packageRoot = resolvePackageRoot();
15942
15964
  const nativeBinsDir = path3__namespace.default.join(packageRoot, "native-bins", getNativeBinSubdir());
15943
- if (fs32__namespace.default.existsSync(nativeBinsDir)) return resolveBinaryFromDir(nativeBinsDir);
15965
+ if (fs5__namespace.default.existsSync(nativeBinsDir)) return resolveBinaryFromDir(nativeBinsDir);
15944
15966
  const adjacentNativeBinsDir = path3__namespace.default.join(path3__namespace.default.dirname(packageRoot), "native-bins", getNativeBinSubdir());
15945
- if (fs32__namespace.default.existsSync(adjacentNativeBinsDir)) return resolveBinaryFromDir(adjacentNativeBinsDir);
15967
+ if (fs5__namespace.default.existsSync(adjacentNativeBinsDir)) return resolveBinaryFromDir(adjacentNativeBinsDir);
15946
15968
  return void 0;
15947
15969
  }
15948
15970
  __name(resolveNpmBundled, "resolveNpmBundled");
@@ -15954,20 +15976,20 @@ function resolveDevFallback() {
15954
15976
  dir = parent;
15955
15977
  if (process.platform === "darwin") {
15956
15978
  const swiftBuild = path3__namespace.default.join(dir, "packages", "encryption-binary-swift", "swift", ".build", "release", "VarlockEnclave");
15957
- if (fs32__namespace.default.existsSync(swiftBuild)) return swiftBuild;
15979
+ if (fs5__namespace.default.existsSync(swiftBuild)) return swiftBuild;
15958
15980
  }
15959
15981
  const rustBuild = path3__namespace.default.join(dir, "packages", "encryption-binary-rust", "target", "release", getPlatformBinaryName());
15960
- if (fs32__namespace.default.existsSync(rustBuild)) return rustBuild;
15982
+ if (fs5__namespace.default.existsSync(rustBuild)) return rustBuild;
15961
15983
  }
15962
15984
  return void 0;
15963
15985
  }
15964
15986
  __name(resolveDevFallback, "resolveDevFallback");
15965
15987
  function ensureExecutable(binaryPath) {
15966
15988
  try {
15967
- fs32__namespace.default.accessSync(binaryPath, fs32__namespace.default.constants.X_OK);
15989
+ fs5__namespace.default.accessSync(binaryPath, fs5__namespace.default.constants.X_OK);
15968
15990
  } catch {
15969
15991
  if (process.platform !== "win32") {
15970
- fs32__namespace.default.chmodSync(binaryPath, 493);
15992
+ fs5__namespace.default.chmodSync(binaryPath, 493);
15971
15993
  }
15972
15994
  }
15973
15995
  return binaryPath;
@@ -16008,6 +16030,10 @@ function resolveNativeBinary() {
16008
16030
  return void 0;
16009
16031
  }
16010
16032
  __name(resolveNativeBinary, "resolveNativeBinary");
16033
+ var SEND_TIMEOUT_MS = 3e4;
16034
+ var BIOMETRIC_TIMEOUT_MS = 9e4;
16035
+ var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
16036
+ var KILL_GRACE_MS = 2e3;
16011
16037
  function debug22(msg) {
16012
16038
  if (process.env.VARLOCK_DEBUG) {
16013
16039
  process.stderr.write(`[varlock:daemon-client] ${msg}
@@ -16015,6 +16041,40 @@ function debug22(msg) {
16015
16041
  }
16016
16042
  }
16017
16043
  __name(debug22, "debug");
16044
+ function killDaemonProcess(pid) {
16045
+ try {
16046
+ process.kill(pid, "SIGTERM");
16047
+ } catch {
16048
+ return true;
16049
+ }
16050
+ const start = Date.now();
16051
+ while (Date.now() - start < KILL_GRACE_MS) {
16052
+ try {
16053
+ process.kill(pid, 0);
16054
+ } catch {
16055
+ return true;
16056
+ }
16057
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
16058
+ }
16059
+ debug22(`daemon pid ${pid} didn't respond to SIGTERM, sending SIGKILL`);
16060
+ try {
16061
+ process.kill(pid, "SIGKILL");
16062
+ } catch {
16063
+ return true;
16064
+ }
16065
+ const killStart = Date.now();
16066
+ while (Date.now() - killStart < 500) {
16067
+ try {
16068
+ process.kill(pid, 0);
16069
+ } catch {
16070
+ return true;
16071
+ }
16072
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
16073
+ }
16074
+ debug22(`daemon pid ${pid} is unkillable (likely in uninterruptible kernel wait) \u2014 proceeding anyway`);
16075
+ return false;
16076
+ }
16077
+ __name(killDaemonProcess, "killDaemonProcess");
16018
16078
  function getSocketDir() {
16019
16079
  return path3__namespace.default.join(getUserVarlockDir(), "local-encrypt");
16020
16080
  }
@@ -16026,6 +16086,10 @@ function getSocketPath() {
16026
16086
  return path3__namespace.default.join(getSocketDir(), "daemon.sock");
16027
16087
  }
16028
16088
  __name(getSocketPath, "getSocketPath");
16089
+ function getLockPath() {
16090
+ return `${getSocketPath()}.lock`;
16091
+ }
16092
+ __name(getLockPath, "getLockPath");
16029
16093
  function getPidPath() {
16030
16094
  return path3__namespace.default.join(getSocketDir(), "daemon.pid");
16031
16095
  }
@@ -16034,12 +16098,29 @@ function getDaemonInfoPath() {
16034
16098
  return path3__namespace.default.join(getSocketDir(), "daemon.info");
16035
16099
  }
16036
16100
  __name(getDaemonInfoPath, "getDaemonInfoPath");
16101
+ function getDaemonStateFiles() {
16102
+ const files = [getPidPath(), getDaemonInfoPath()];
16103
+ if (process.platform !== "win32") {
16104
+ files.push(getSocketPath(), getLockPath());
16105
+ }
16106
+ return files;
16107
+ }
16108
+ __name(getDaemonStateFiles, "getDaemonStateFiles");
16109
+ function cleanupDaemonFiles() {
16110
+ for (const file of getDaemonStateFiles()) {
16111
+ try {
16112
+ fs5__namespace.default.unlinkSync(file);
16113
+ } catch {
16114
+ }
16115
+ }
16116
+ }
16117
+ __name(cleanupDaemonFiles, "cleanupDaemonFiles");
16037
16118
  function checkDaemonBinaryStale() {
16038
16119
  const infoPath = getDaemonInfoPath();
16039
16120
  const pidPath = getPidPath();
16040
16121
  let info;
16041
16122
  try {
16042
- info = JSON.parse(fs32__namespace.default.readFileSync(infoPath, "utf-8"));
16123
+ info = JSON.parse(fs5__namespace.default.readFileSync(infoPath, "utf-8"));
16043
16124
  } catch {
16044
16125
  }
16045
16126
  const currentBinaryPath = resolveNativeBinary();
@@ -16049,7 +16130,7 @@ function checkDaemonBinaryStale() {
16049
16130
  debug22(`daemon binary path changed: ${info.binaryPath} \u2192 ${currentBinaryPath}`);
16050
16131
  } else {
16051
16132
  try {
16052
- const stat = fs32__namespace.default.statSync(currentBinaryPath);
16133
+ const stat = fs5__namespace.default.statSync(currentBinaryPath);
16053
16134
  if (stat.mtimeMs === info.binaryMtimeMs) {
16054
16135
  debug22("daemon binary is current \u2014 no restart needed");
16055
16136
  return void 0;
@@ -16063,18 +16144,20 @@ function checkDaemonBinaryStale() {
16063
16144
  debug22("no daemon.info file \u2014 treating running daemon as stale");
16064
16145
  }
16065
16146
  try {
16066
- const pid = parseInt(fs32__namespace.default.readFileSync(pidPath, "utf-8").trim(), 10);
16147
+ const pid = parseInt(fs5__namespace.default.readFileSync(pidPath, "utf-8").trim(), 10);
16067
16148
  process.kill(pid, 0);
16068
16149
  return pid;
16069
16150
  } catch {
16151
+ debug22("stale PID file points to dead process \u2014 cleaning up");
16152
+ cleanupDaemonFiles();
16070
16153
  return void 0;
16071
16154
  }
16072
16155
  }
16073
16156
  __name(checkDaemonBinaryStale, "checkDaemonBinaryStale");
16074
16157
  function writeDaemonInfo(binaryPath) {
16075
16158
  try {
16076
- const stat = fs32__namespace.default.statSync(binaryPath);
16077
- fs32__namespace.default.writeFileSync(getDaemonInfoPath(), JSON.stringify({
16159
+ const stat = fs5__namespace.default.statSync(binaryPath);
16160
+ fs5__namespace.default.writeFileSync(getDaemonInfoPath(), JSON.stringify({
16078
16161
  binaryPath,
16079
16162
  binaryMtimeMs: stat.mtimeMs
16080
16163
  }));
@@ -16122,22 +16205,8 @@ var DaemonClient = class {
16122
16205
  const stalePid = this.spawnedInThisProcess ? void 0 : checkDaemonBinaryStale();
16123
16206
  if (stalePid) {
16124
16207
  debug22(`killing stale daemon (pid ${stalePid}) \u2014 binary has been updated`);
16125
- try {
16126
- process.kill(stalePid, "SIGTERM");
16127
- } catch {
16128
- }
16129
- for (const file of [getPidPath(), getDaemonInfoPath()]) {
16130
- try {
16131
- fs32__namespace.default.unlinkSync(file);
16132
- } catch {
16133
- }
16134
- }
16135
- if (process.platform !== "win32") {
16136
- try {
16137
- fs32__namespace.default.unlinkSync(socketPath);
16138
- } catch {
16139
- }
16140
- }
16208
+ killDaemonProcess(stalePid);
16209
+ cleanupDaemonFiles();
16141
16210
  } else {
16142
16211
  try {
16143
16212
  await this.connectToSocket(socketPath);
@@ -16147,7 +16216,8 @@ var DaemonClient = class {
16147
16216
  }
16148
16217
  try {
16149
16218
  await this.spawnDaemon();
16150
- } catch {
16219
+ } catch (err) {
16220
+ debug22(`spawnDaemon failed: ${err instanceof Error ? err.message : err}`);
16151
16221
  await new Promise((r) => {
16152
16222
  setTimeout(r, 1e3);
16153
16223
  });
@@ -16155,76 +16225,88 @@ var DaemonClient = class {
16155
16225
  await this.connectToSocket(socketPath);
16156
16226
  }
16157
16227
  async decrypt(ciphertext, keyId = "varlock-default") {
16158
- await this.ensureConnected();
16159
- const result = await this.sendMessage({
16160
- action: "decrypt",
16161
- payload: { ciphertext, keyId }
16228
+ return this.withRetry(async () => {
16229
+ await this.ensureConnected();
16230
+ const result = await this.sendMessage({
16231
+ action: "decrypt",
16232
+ payload: { ciphertext, keyId }
16233
+ }, BIOMETRIC_TIMEOUT_MS);
16234
+ if (typeof result === "string") return result;
16235
+ if (result && typeof result === "object" && "error" in result) {
16236
+ throw new Error(String(result.error));
16237
+ }
16238
+ return String(result);
16162
16239
  });
16163
- if (typeof result === "string") return result;
16164
- if (result && typeof result === "object" && "error" in result) {
16165
- throw new Error(String(result.error));
16166
- }
16167
- return String(result);
16168
16240
  }
16169
16241
  async promptSecret(opts) {
16170
- await this.ensureConnected();
16171
- try {
16172
- const result = await this.sendMessage({
16173
- action: "prompt-secret",
16174
- payload: {
16175
- itemKey: opts?.itemKey,
16176
- message: opts?.message,
16177
- keyId: opts?.keyId
16242
+ return this.withRetry(async () => {
16243
+ await this.ensureConnected();
16244
+ try {
16245
+ const result = await this.sendMessage({
16246
+ action: "prompt-secret",
16247
+ payload: {
16248
+ itemKey: opts?.itemKey,
16249
+ message: opts?.message,
16250
+ keyId: opts?.keyId
16251
+ }
16252
+ }, INTERACTIVE_TIMEOUT_MS);
16253
+ if (result && typeof result === "object" && "ciphertext" in result) {
16254
+ return result.ciphertext;
16178
16255
  }
16179
- });
16180
- if (result && typeof result === "object" && "ciphertext" in result) {
16181
- return result.ciphertext;
16256
+ return void 0;
16257
+ } catch (err) {
16258
+ if (err instanceof Error && err.message === "cancelled") return void 0;
16259
+ throw err;
16182
16260
  }
16183
- return void 0;
16184
- } catch (err) {
16185
- if (err instanceof Error && err.message === "cancelled") return void 0;
16186
- throw err;
16187
- }
16261
+ });
16188
16262
  }
16189
16263
  async invalidateSession() {
16190
- await this.ensureConnected();
16191
- await this.sendMessage({ action: "invalidate-session" });
16264
+ return this.withRetry(async () => {
16265
+ await this.ensureConnected();
16266
+ await this.sendMessage({ action: "invalidate-session" });
16267
+ });
16192
16268
  }
16193
16269
  async keychainGet(opts) {
16194
- await this.ensureConnected();
16195
- const result = await this.sendMessage({
16196
- action: "keychain-get",
16197
- payload: opts
16270
+ return this.withRetry(async () => {
16271
+ await this.ensureConnected();
16272
+ const result = await this.sendMessage({
16273
+ action: "keychain-get",
16274
+ payload: opts
16275
+ }, BIOMETRIC_TIMEOUT_MS);
16276
+ if (typeof result === "string") return result;
16277
+ if (result && typeof result === "object" && "error" in result) {
16278
+ throw new Error(String(result.error));
16279
+ }
16280
+ return String(result);
16198
16281
  });
16199
- if (typeof result === "string") return result;
16200
- if (result && typeof result === "object" && "error" in result) {
16201
- throw new Error(String(result.error));
16202
- }
16203
- return String(result);
16204
16282
  }
16205
16283
  async keychainSearch(opts) {
16206
- await this.ensureConnected();
16207
- const result = await this.sendMessage({
16208
- action: "keychain-search",
16209
- payload: opts ?? {}
16284
+ return this.withRetry(async () => {
16285
+ await this.ensureConnected();
16286
+ const result = await this.sendMessage({
16287
+ action: "keychain-search",
16288
+ payload: opts ?? {}
16289
+ });
16290
+ return result ?? [];
16210
16291
  });
16211
- return result ?? [];
16212
16292
  }
16213
16293
  async keychainPick(opts) {
16214
- await this.ensureConnected();
16215
- try {
16216
- const result = await this.sendMessage({
16217
- action: "keychain-pick",
16218
- payload: { itemKey: opts?.itemKey }
16219
- });
16220
- if (result && typeof result === "object" && "service" in result) {
16221
- return result;
16294
+ return this.withRetry(async () => {
16295
+ await this.ensureConnected();
16296
+ try {
16297
+ const result = await this.sendMessage({
16298
+ action: "keychain-pick",
16299
+ payload: { itemKey: opts?.itemKey }
16300
+ }, INTERACTIVE_TIMEOUT_MS);
16301
+ if (result && typeof result === "object" && "service" in result) {
16302
+ return result;
16303
+ }
16304
+ return void 0;
16305
+ } catch (err) {
16306
+ if (err instanceof Error && err.message === "cancelled") return void 0;
16307
+ throw err;
16222
16308
  }
16223
- return void 0;
16224
- } catch (err) {
16225
- if (err instanceof Error && err.message === "cancelled") return void 0;
16226
- throw err;
16227
- }
16309
+ });
16228
16310
  }
16229
16311
  cleanup() {
16230
16312
  for (const { reject } of this.messageQueue.values()) {
@@ -16237,6 +16319,37 @@ var DaemonClient = class {
16237
16319
  this.buffer = Buffer.alloc(0);
16238
16320
  }
16239
16321
  // -- Private --
16322
+ /**
16323
+ * Run an async operation, and on recoverable failure (timeout, connection
16324
+ * closed) clean up, reconnect to the daemon, and retry once.
16325
+ */
16326
+ async withRetry(fn) {
16327
+ try {
16328
+ return await fn();
16329
+ } catch (err) {
16330
+ const msg = err instanceof Error ? err.message : "";
16331
+ const recoverable = msg.includes("timed out") || msg.includes("connection closed") || msg.includes("Not connected");
16332
+ if (!recoverable) throw err;
16333
+ debug22(`recoverable error, reconnecting: ${msg}`);
16334
+ this.forceCleanup();
16335
+ await this.ensureConnected();
16336
+ return await fn();
16337
+ }
16338
+ }
16339
+ /**
16340
+ * Aggressive cleanup: kill the daemon process if we know its PID,
16341
+ * then reset client state so the next ensureConnected spawns fresh.
16342
+ */
16343
+ forceCleanup() {
16344
+ this.cleanup();
16345
+ this.spawnedInThisProcess = false;
16346
+ try {
16347
+ const pid = parseInt(fs5__namespace.default.readFileSync(getPidPath(), "utf-8").trim(), 10);
16348
+ killDaemonProcess(pid);
16349
+ } catch {
16350
+ }
16351
+ cleanupDaemonFiles();
16352
+ }
16240
16353
  connectToSocket(socketPath) {
16241
16354
  return new Promise((resolve2, reject) => {
16242
16355
  const socket = new net__default.default.Socket();
@@ -16262,6 +16375,11 @@ var DaemonClient = class {
16262
16375
  socket.on("close", () => {
16263
16376
  this.isConnected = false;
16264
16377
  this.socket = null;
16378
+ for (const { reject: rej } of this.messageQueue.values()) {
16379
+ rej(new Error("Daemon connection closed"));
16380
+ }
16381
+ this.messageQueue.clear();
16382
+ this.buffer = Buffer.alloc(0);
16265
16383
  });
16266
16384
  socket.connect(socketPath);
16267
16385
  });
@@ -16288,7 +16406,7 @@ var DaemonClient = class {
16288
16406
  }
16289
16407
  }
16290
16408
  }
16291
- sendMessage(message) {
16409
+ sendMessage(message, timeoutMs = SEND_TIMEOUT_MS) {
16292
16410
  return new Promise((resolve2, reject) => {
16293
16411
  if (!this.isConnected || !this.socket) {
16294
16412
  reject(new Error("Not connected to daemon"));
@@ -16300,7 +16418,20 @@ var DaemonClient = class {
16300
16418
  const messageBytes = Buffer.from(jsonData, "utf-8");
16301
16419
  const lengthBuf = Buffer.alloc(4);
16302
16420
  lengthBuf.writeUInt32LE(messageBytes.length, 0);
16303
- this.messageQueue.set(messageId, { resolve: resolve2, reject });
16421
+ const timeout = setTimeout(() => {
16422
+ this.messageQueue.delete(messageId);
16423
+ reject(new Error(`Daemon message timed out after ${timeoutMs}ms (action: ${message.action})`));
16424
+ }, timeoutMs);
16425
+ this.messageQueue.set(messageId, {
16426
+ resolve: /* @__PURE__ */ __name((value) => {
16427
+ clearTimeout(timeout);
16428
+ resolve2(value);
16429
+ }, "resolve"),
16430
+ reject: /* @__PURE__ */ __name((err) => {
16431
+ clearTimeout(timeout);
16432
+ reject(err);
16433
+ }, "reject")
16434
+ });
16304
16435
  this.socket.write(Buffer.concat([lengthBuf, messageBytes]));
16305
16436
  });
16306
16437
  }
@@ -16313,35 +16444,26 @@ var DaemonClient = class {
16313
16444
  const pidPath = getPidPath();
16314
16445
  const isWindows2 = process.platform === "win32";
16315
16446
  if (!isWindows2) {
16316
- fs32__namespace.default.mkdirSync(path3__namespace.default.dirname(socketPath), { recursive: true });
16447
+ fs5__namespace.default.mkdirSync(path3__namespace.default.dirname(socketPath), { recursive: true });
16317
16448
  }
16318
- fs32__namespace.default.mkdirSync(path3__namespace.default.dirname(pidPath), { recursive: true });
16319
- if (fs32__namespace.default.existsSync(pidPath)) {
16449
+ fs5__namespace.default.mkdirSync(path3__namespace.default.dirname(pidPath), { recursive: true });
16450
+ if (fs5__namespace.default.existsSync(pidPath)) {
16320
16451
  try {
16321
- const pid = parseInt(fs32__namespace.default.readFileSync(pidPath, "utf-8").trim(), 10);
16452
+ const pid = parseInt(fs5__namespace.default.readFileSync(pidPath, "utf-8").trim(), 10);
16322
16453
  process.kill(pid, 0);
16323
- await new Promise((r) => {
16324
- setTimeout(r, 500);
16325
- });
16326
- return;
16454
+ try {
16455
+ await this.connectToSocket(socketPath);
16456
+ return;
16457
+ } catch {
16458
+ debug22(`daemon pid ${pid} alive but socket unresponsive \u2014 killing`);
16459
+ killDaemonProcess(pid);
16460
+ }
16327
16461
  } catch {
16328
16462
  }
16329
16463
  }
16330
- if (!isWindows2) {
16331
- for (const file of [socketPath, pidPath, getDaemonInfoPath()]) {
16332
- if (fs32__namespace.default.existsSync(file)) {
16333
- fs32__namespace.default.unlinkSync(file);
16334
- }
16335
- }
16336
- if (fs32__namespace.default.existsSync(socketPath)) {
16337
- throw new Error(`Failed to clean up stale socket file: ${socketPath}`);
16338
- }
16339
- } else {
16340
- for (const file of [pidPath, getDaemonInfoPath()]) {
16341
- if (fs32__namespace.default.existsSync(file)) {
16342
- fs32__namespace.default.unlinkSync(file);
16343
- }
16344
- }
16464
+ cleanupDaemonFiles();
16465
+ if (!isWindows2 && fs5__namespace.default.existsSync(socketPath)) {
16466
+ throw new Error(`Failed to clean up stale socket file: ${socketPath}`);
16345
16467
  }
16346
16468
  return new Promise((resolve2, reject) => {
16347
16469
  const child = child_process.spawn(binaryPath, [
@@ -16551,7 +16673,7 @@ function getKeyFilePath(keyId) {
16551
16673
  }
16552
16674
  __name(getKeyFilePath, "getKeyFilePath");
16553
16675
  function keyExists(keyId = DEFAULT_KEY_ID) {
16554
- return fs32__namespace.default.existsSync(getKeyFilePath(keyId));
16676
+ return fs5__namespace.default.existsSync(getKeyFilePath(keyId));
16555
16677
  }
16556
16678
  __name(keyExists, "keyExists");
16557
16679
  async function generateKey(keyId = DEFAULT_KEY_ID) {
@@ -16563,18 +16685,18 @@ async function generateKey(keyId = DEFAULT_KEY_ID) {
16563
16685
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
16564
16686
  };
16565
16687
  const keyStorePath = getKeyStorePath();
16566
- fs32__namespace.default.mkdirSync(keyStorePath, { recursive: true });
16688
+ fs5__namespace.default.mkdirSync(keyStorePath, { recursive: true });
16567
16689
  const filePath = getKeyFilePath(keyId);
16568
- fs32__namespace.default.writeFileSync(filePath, JSON.stringify(stored, null, 2), { mode: 384 });
16690
+ fs5__namespace.default.writeFileSync(filePath, JSON.stringify(stored, null, 2), { mode: 384 });
16569
16691
  return { keyId, publicKey: keyPair.publicKey };
16570
16692
  }
16571
16693
  __name(generateKey, "generateKey");
16572
16694
  function loadKeyPair(keyId) {
16573
16695
  const filePath = getKeyFilePath(keyId);
16574
- if (!fs32__namespace.default.existsSync(filePath)) {
16696
+ if (!fs5__namespace.default.existsSync(filePath)) {
16575
16697
  throw new Error(`Key not found: ${keyId}`);
16576
16698
  }
16577
- const data = fs32__namespace.default.readFileSync(filePath, "utf-8");
16699
+ const data = fs5__namespace.default.readFileSync(filePath, "utf-8");
16578
16700
  const parsed = JSON.parse(data);
16579
16701
  const privateKey = parsed.privateKey ?? (parsed.protection === "none" ? parsed.protectedPrivateKey : void 0) ?? parsed.protectedPrivateKey;
16580
16702
  if (!parsed.publicKey || !privateKey) {
@@ -16612,21 +16734,49 @@ function debug32(msg) {
16612
16734
  }
16613
16735
  }
16614
16736
  __name(debug32, "debug");
16615
- var _cachedTtyId;
16616
- function getSelfTtyId() {
16617
- if (_cachedTtyId) return _cachedTtyId;
16737
+ var _cachedSessionId;
16738
+ function getSelfSessionId() {
16739
+ if (_cachedSessionId) return _cachedSessionId;
16618
16740
  try {
16619
- const ttyPath = fs32__namespace.default.readlinkSync("/proc/self/fd/0");
16741
+ const ttyPath = fs5__namespace.default.readlinkSync("/proc/self/fd/0");
16620
16742
  if (ttyPath && ttyPath.startsWith("/dev/")) {
16621
- _cachedTtyId = ttyPath;
16743
+ _cachedSessionId = ttyPath;
16622
16744
  return ttyPath;
16623
16745
  }
16624
16746
  } catch {
16625
16747
  }
16626
- _cachedTtyId = `pid:${process.pid}`;
16627
- return _cachedTtyId;
16748
+ try {
16749
+ const chain = [process.pid];
16750
+ let current = process.pid;
16751
+ for (let i = 0; i < 64; i++) {
16752
+ const stat = fs5__namespace.default.readFileSync(`/proc/${current}/stat`, "utf-8");
16753
+ const fields = stat.split(") ");
16754
+ if (fields.length < 2) break;
16755
+ const ppid = parseInt(fields[1].split(" ")[1], 10);
16756
+ if (!ppid || ppid <= 1) break;
16757
+ chain.push(ppid);
16758
+ current = ppid;
16759
+ }
16760
+ if (chain.length >= 4) {
16761
+ const scopePid = chain[chain.length - 3];
16762
+ let startTime = 0;
16763
+ try {
16764
+ const scopeStat = fs5__namespace.default.readFileSync(`/proc/${scopePid}/stat`, "utf-8");
16765
+ const scopeFields = scopeStat.split(") ");
16766
+ if (scopeFields.length >= 2) {
16767
+ startTime = parseInt(scopeFields[1].split(" ")[19], 10) || 0;
16768
+ }
16769
+ } catch {
16770
+ }
16771
+ _cachedSessionId = `ptree:${scopePid}:${startTime}`;
16772
+ return _cachedSessionId;
16773
+ }
16774
+ } catch {
16775
+ }
16776
+ _cachedSessionId = `pid:${process.pid}`;
16777
+ return _cachedSessionId;
16628
16778
  }
16629
- __name(getSelfTtyId, "getSelfTtyId");
16779
+ __name(getSelfSessionId, "getSelfSessionId");
16630
16780
  var _wslDaemonPrestartAttempted = false;
16631
16781
  function toWindowsPathFromWsl(pathInWsl) {
16632
16782
  if (!isWSL()) return void 0;
@@ -16870,7 +17020,7 @@ async function decryptValue2(ciphertext, keyId = DEFAULT_KEY_ID2) {
16870
17020
  }
16871
17021
  const stdinPayload = JSON.stringify({
16872
17022
  data: ciphertext,
16873
- ttyId: getSelfTtyId()
17023
+ ttyId: getSelfSessionId()
16874
17024
  });
16875
17025
  const runViaDaemon = /* @__PURE__ */ __name((timeout) => child_process.spawnSync(binaryPath, ["decrypt", "--key-id", keyId, "--data-stdin", "--via-daemon"], {
16876
17026
  input: stdinPayload,
@@ -16928,15 +17078,15 @@ async function lockSession() {
16928
17078
  }
16929
17079
  __name(lockSession, "lockSession");
16930
17080
 
16931
- // ../../varlock/dist/chunk-V2MTE4J6.js
16932
- init_chunk_U7RQPX5K();
17081
+ // ../../varlock/dist/chunk-E3F6QKDZ.js
17082
+ init_chunk_XWYFSG46();
16933
17083
  init_chunk_2PFIYNFA();
16934
17084
  init_chunk_6PEHRAEP();
16935
17085
  function writeBackValue(itemKey, newValueStr, sourceFilePath) {
16936
17086
  if (!sourceFilePath) {
16937
17087
  return { updated: false, reason: "missing-source-file" };
16938
17088
  }
16939
- const currentContents = fs32__namespace.default.readFileSync(sourceFilePath, "utf-8");
17089
+ const currentContents = fs5__namespace.default.readFileSync(sourceFilePath, "utf-8");
16940
17090
  const file = parseEnvSpecDotEnvFile(currentContents);
16941
17091
  const item = file.configItems.find((i) => i.key === itemKey);
16942
17092
  if (!item) {
@@ -16949,7 +17099,7 @@ function writeBackValue(itemKey, newValueStr, sourceFilePath) {
16949
17099
  }
16950
17100
  item.data.value = dummyItem.value;
16951
17101
  item.value = dummyItem.value;
16952
- fs32__namespace.default.writeFileSync(sourceFilePath, file.toString());
17102
+ fs5__namespace.default.writeFileSync(sourceFilePath, file.toString());
16953
17103
  return { updated: true };
16954
17104
  }
16955
17105
  __name(writeBackValue, "writeBackValue");
@@ -17269,9 +17419,9 @@ var KeychainResolver = createResolver({
17269
17419
  function readVarlockPackageJsonConfig(opts) {
17270
17420
  const cwd = opts?.cwd ?? process.cwd();
17271
17421
  const pkgPath = path3__namespace.default.join(cwd, "package.json");
17272
- if (!fs32__namespace.default.existsSync(pkgPath)) return void 0;
17422
+ if (!fs5__namespace.default.existsSync(pkgPath)) return void 0;
17273
17423
  try {
17274
- const pkg = JSON.parse(fs32__namespace.default.readFileSync(pkgPath, "utf-8"));
17424
+ const pkg = JSON.parse(fs5__namespace.default.readFileSync(pkgPath, "utf-8"));
17275
17425
  if (pkg.varlock && typeof pkg.varlock === "object") {
17276
17426
  return pkg.varlock;
17277
17427
  }
@@ -17294,7 +17444,7 @@ function loadFromPaths(rawPaths, config) {
17294
17444
  debug4("using %d paths from %s: %s", resolvedPaths.length, config.source, resolvedPaths.join(", "));
17295
17445
  }
17296
17446
  for (const resolvedPath of resolvedPaths) {
17297
- if (!fs32__namespace.default.existsSync(resolvedPath)) {
17447
+ if (!fs5__namespace.default.existsSync(resolvedPath)) {
17298
17448
  throw new CliExitError(`${config.errorPrefix}: ${resolvedPath}`, {
17299
17449
  suggestion: config.errorSuggestion
17300
17450
  });
@@ -17342,8 +17492,8 @@ function loadVarlockEnvGraph(opts) {
17342
17492
  __name(loadVarlockEnvGraph, "loadVarlockEnvGraph");
17343
17493
 
17344
17494
  // ../../varlock/dist/index.js
17345
- init_chunk_U7RQPX5K();
17346
- init_chunk_7WB7HK5Z();
17495
+ init_chunk_XWYFSG46();
17496
+ init_chunk_O3WTD6L4();
17347
17497
  init_chunk_HDKXXS2X();
17348
17498
  init_chunk_2PFIYNFA();
17349
17499
  init_chunk_2PFIYNFA();
@@ -17418,7 +17568,7 @@ init_chunk_6PEHRAEP();
17418
17568
  // ../../varlock/dist/runtime/patch-console.js
17419
17569
  init_chunk_6PEHRAEP();
17420
17570
 
17421
- // ../../varlock/dist/chunk-YHOWSHVH.js
17571
+ // ../../varlock/dist/chunk-F5H5MJ6U.js
17422
17572
  init_chunk_6PEHRAEP();
17423
17573
  var platform = os__default.default.platform();
17424
17574
  var isWindows = platform.match(/^win/i);
@@ -17427,10 +17577,10 @@ function findVarlockBin(startDir) {
17427
17577
  let currentDir = startDir;
17428
17578
  while (currentDir) {
17429
17579
  const possibleBinPath = path3__namespace.default.join(currentDir, "node_modules", ".bin");
17430
- if (fs32__namespace.default.existsSync(possibleBinPath)) {
17580
+ if (fs5__namespace.default.existsSync(possibleBinPath)) {
17431
17581
  for (const binName of binNames) {
17432
17582
  const possibleVarlockPath = path3__namespace.default.join(possibleBinPath, binName);
17433
- if (fs32__namespace.default.existsSync(possibleVarlockPath)) {
17583
+ if (fs5__namespace.default.existsSync(possibleVarlockPath)) {
17434
17584
  return possibleVarlockPath;
17435
17585
  }
17436
17586
  }
@@ -17442,6 +17592,20 @@ function findVarlockBin(startDir) {
17442
17592
  return null;
17443
17593
  }
17444
17594
  __name(findVarlockBin, "findVarlockBin");
17595
+ var VarlockExecError = class extends Error {
17596
+ constructor(message, stdout2, stderr, exitCode) {
17597
+ super(message);
17598
+ this.stdout = stdout2;
17599
+ this.stderr = stderr;
17600
+ this.exitCode = exitCode;
17601
+ }
17602
+ stdout;
17603
+ stderr;
17604
+ exitCode;
17605
+ static {
17606
+ __name(this, "VarlockExecError");
17607
+ }
17608
+ };
17445
17609
  function execSyncVarlock(command, opts) {
17446
17610
  try {
17447
17611
  try {
@@ -17450,7 +17614,7 @@ function execSyncVarlock(command, opts) {
17450
17614
  ...opts?.cwd && { cwd: opts.cwd },
17451
17615
  stdio: "pipe"
17452
17616
  });
17453
- return result.toString();
17617
+ return opts?.fullResult ? { stdout: result.toString(), stderr: "" } : result.toString();
17454
17618
  } catch (err) {
17455
17619
  if (!isWindows && err.status !== 127 && err.code !== "ENOENT") throw err;
17456
17620
  }
@@ -17469,11 +17633,24 @@ function execSyncVarlock(command, opts) {
17469
17633
  stdio: "pipe",
17470
17634
  ...needsShell && { shell: true }
17471
17635
  });
17472
- return result.toString();
17636
+ return opts?.fullResult ? { stdout: result.toString(), stderr: "" } : result.toString();
17473
17637
  }
17474
17638
  }
17475
17639
  throw new Error("Unable to find varlock executable");
17476
17640
  } catch (err) {
17641
+ if (opts?.fullResult) {
17642
+ if (err instanceof VarlockExecError) throw err;
17643
+ const errAny2 = err;
17644
+ if (errAny2.status != null) {
17645
+ throw new VarlockExecError(
17646
+ `varlock ${command} failed (exit code ${errAny2.status})`,
17647
+ errAny2.stdout?.toString() ?? "",
17648
+ errAny2.stderr?.toString() ?? "",
17649
+ errAny2.status ?? 1
17650
+ );
17651
+ }
17652
+ throw err;
17653
+ }
17477
17654
  const errAny = err;
17478
17655
  if (opts?.showLogsOnError) {
17479
17656
  if (errAny.stdout) console.log(errAny.stdout.toString());
@@ -17543,7 +17720,7 @@ function enableExtraFileWatchers(sources, basePath) {
17543
17720
  let triggerFilePath = null;
17544
17721
  for (const envFileName of NEXT_WATCHED_ENV_FILES) {
17545
17722
  const filePath = path3__namespace.join(rootDir, envFileName);
17546
- if (fs32__namespace.existsSync(filePath)) {
17723
+ if (fs5__namespace.existsSync(filePath)) {
17547
17724
  triggerFilePath = filePath;
17548
17725
  break;
17549
17726
  }
@@ -17553,7 +17730,7 @@ function enableExtraFileWatchers(sources, basePath) {
17553
17730
  function triggerNextReload(changedPath) {
17554
17731
  debug5("extra file changed, triggering reload:", changedPath);
17555
17732
  if (mustDestroyTriggerFile) {
17556
- fs32__namespace.writeFileSync(triggerFilePath, [
17733
+ fs5__namespace.writeFileSync(triggerFilePath, [
17557
17734
  "# This file was created by @varlock/nextjs-integration",
17558
17735
  "# It is used to trigger Next.js to reload when non-standard .env files change",
17559
17736
  "# You can safely ignore and delete it",
@@ -17562,19 +17739,19 @@ function enableExtraFileWatchers(sources, basePath) {
17562
17739
  ].join("\n"), "utf-8");
17563
17740
  setTimeout(() => {
17564
17741
  try {
17565
- fs32__namespace.unlinkSync(triggerFilePath);
17742
+ fs5__namespace.unlinkSync(triggerFilePath);
17566
17743
  } catch {
17567
17744
  }
17568
17745
  }, 1e3);
17569
17746
  } else {
17570
- const currentContents = fs32__namespace.readFileSync(triggerFilePath, "utf-8");
17571
- fs32__namespace.writeFileSync(triggerFilePath, currentContents, "utf-8");
17747
+ const currentContents = fs5__namespace.readFileSync(triggerFilePath, "utf-8");
17748
+ fs5__namespace.writeFileSync(triggerFilePath, currentContents, "utf-8");
17572
17749
  }
17573
17750
  }
17574
17751
  debug5("setting up extra file watchers for:", extraFilePaths);
17575
17752
  for (const filePath of extraFilePaths) {
17576
17753
  watchedExtraFiles.add(filePath);
17577
- fs32__namespace.watchFile(filePath, { interval: 500 }, () => {
17754
+ fs5__namespace.watchFile(filePath, { interval: 500 }, () => {
17578
17755
  triggerNextReload(filePath);
17579
17756
  });
17580
17757
  }
@@ -17644,17 +17821,14 @@ function loadEnvConfig(dir, dev, _log = console, forceReload = false, _onReload)
17644
17821
  try {
17645
17822
  const cleanEnv = { ...exports.initialEnv };
17646
17823
  delete cleanEnv.DEBUG_VARLOCK;
17647
- const varlockLoadedEnvStr = execSyncVarlock(`load --format json-full --env ${envFromNextCommand}`, {
17648
- // We handle all error display and exit logic ourselves in the catch block
17649
- // so we can silently defer on serverless platforms where the binary is missing.
17650
- showLogsOnError: false,
17651
- exitOnError: false,
17824
+ const { stdout: stdout2 } = execSyncVarlock(`load --format json-full --env ${envFromNextCommand}`, {
17825
+ fullResult: true,
17652
17826
  env: cleanEnv
17653
17827
  });
17654
17828
  if (loadCount >= 2) {
17655
17829
  console.log("\u2705 env reloaded and validated");
17656
17830
  }
17657
- varlockLoadedEnv = JSON.parse(varlockLoadedEnvStr);
17831
+ varlockLoadedEnv = JSON.parse(stdout2);
17658
17832
  } catch (err) {
17659
17833
  if (err.message.includes("Unable to find varlock executable")) {
17660
17834
  if (!dev) {
@@ -17670,12 +17844,12 @@ function loadEnvConfig(dir, dev, _log = console, forceReload = false, _onReload)
17670
17844
  ].join("\n"));
17671
17845
  process.exit(1);
17672
17846
  }
17673
- const errAny = err;
17674
- if (errAny.stdout) console.log(errAny.stdout.toString());
17675
- if (errAny.stderr) console.error(errAny.stderr.toString());
17676
- console.error("[varlock] \u26A0\uFE0F failed to load env \u2014 see error above");
17847
+ if (err instanceof VarlockExecError) {
17848
+ if (err.stderr) process.stderr.write(err.stderr);
17849
+ console.error("[varlock] \u26A0\uFE0F failed to load env \u2014 see error above");
17850
+ }
17677
17851
  if (!dev) {
17678
- process.exit(err.status ?? 1);
17852
+ process.exit(err.exitCode ?? 1);
17679
17853
  }
17680
17854
  process.env.__VARLOCK_ENV = JSON.stringify({
17681
17855
  sources: [],