@cortexkit/opencode-antigravity-auth 3.0.41 → 3.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.
Files changed (113) hide show
  1. package/README.md +11 -0
  2. package/dist/cli.js +1316 -1124
  3. package/dist/cli.js.map +4 -4
  4. package/dist/cli.meta.json +116 -106
  5. package/dist/index.js +1257 -720
  6. package/dist/index.js.map +4 -4
  7. package/dist/index.meta.json +187 -169
  8. package/dist/server.js +1310 -773
  9. package/dist/server.js.map +4 -4
  10. package/dist/server.meta.json +1 -1
  11. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +4 -0
  12. package/dist/src/common-auth-embedded/claustrum/custody.js +147 -2
  13. package/dist/src/common-auth-embedded/claustrum/hub.js +47 -1
  14. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  15. package/dist/src/common-auth-embedded/claustrum/index.js +1 -1
  16. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +13 -9
  17. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +65 -12
  18. package/dist/src/common-auth-embedded/routing-accessor/index.js +114 -15
  19. package/dist/src/common-auth-embedded/settings/edit.d.ts +1 -0
  20. package/dist/src/common-auth-embedded/settings/edit.js +48 -2
  21. package/dist/src/common-auth-embedded/settings/handle.d.ts +2 -1
  22. package/dist/src/common-auth-embedded/settings/index.d.ts +1 -0
  23. package/dist/src/common-auth-embedded/settings/update.d.ts +14 -0
  24. package/dist/src/common-auth-embedded/settings/update.js +28 -9
  25. package/dist/src/common-auth-embedded/source-output.json +55 -46
  26. package/dist/src/plugin/__fixtures__/release-model-ids.d.ts.map +1 -1
  27. package/dist/src/plugin/__fixtures__/release-model-ids.js +1 -0
  28. package/dist/src/plugin/__fixtures__/release-model-ids.js.map +1 -1
  29. package/dist/src/plugin/__fixtures__/verified-store.d.ts +1 -1
  30. package/dist/src/plugin/__fixtures__/verified-store.js +4 -4
  31. package/dist/src/plugin/account-access.js +1 -1
  32. package/dist/src/plugin/account-access.js.map +1 -1
  33. package/dist/src/plugin/catalog.d.ts.map +1 -1
  34. package/dist/src/plugin/catalog.js +4 -2
  35. package/dist/src/plugin/catalog.js.map +1 -1
  36. package/dist/src/plugin/config/models.d.ts +9 -0
  37. package/dist/src/plugin/config/models.d.ts.map +1 -1
  38. package/dist/src/plugin/config/models.js +18 -0
  39. package/dist/src/plugin/config/models.js.map +1 -1
  40. package/dist/src/plugin/config/updater.js +2 -2
  41. package/dist/src/plugin/config/updater.js.map +1 -1
  42. package/dist/src/plugin/core/streaming/terminal-event.d.ts +14 -0
  43. package/dist/src/plugin/core/streaming/terminal-event.d.ts.map +1 -0
  44. package/dist/src/plugin/core/streaming/terminal-event.js +39 -0
  45. package/dist/src/plugin/core/streaming/terminal-event.js.map +1 -0
  46. package/dist/src/plugin/core/streaming/transformer.d.ts.map +1 -1
  47. package/dist/src/plugin/core/streaming/transformer.js +1 -13
  48. package/dist/src/plugin/core/streaming/transformer.js.map +1 -1
  49. package/dist/src/plugin/ga-location-services.js +1 -1
  50. package/dist/src/plugin/ga-location-services.js.map +1 -1
  51. package/dist/src/plugin/index.js +1 -1
  52. package/dist/src/plugin/index.js.map +1 -1
  53. package/dist/src/plugin/request-helpers.d.ts +10 -0
  54. package/dist/src/plugin/request-helpers.d.ts.map +1 -1
  55. package/dist/src/plugin/request-helpers.js +6 -0
  56. package/dist/src/plugin/request-helpers.js.map +1 -1
  57. package/dist/src/plugin/request.d.ts.map +1 -1
  58. package/dist/src/plugin/request.js +101 -47
  59. package/dist/src/plugin/request.js.map +1 -1
  60. package/dist/src/plugin/search.d.ts +7 -0
  61. package/dist/src/plugin/search.d.ts.map +1 -1
  62. package/dist/src/plugin/search.js +9 -15
  63. package/dist/src/plugin/search.js.map +1 -1
  64. package/dist/src/plugin/session-context.d.ts +1 -1
  65. package/dist/src/plugin/session-context.d.ts.map +1 -1
  66. package/dist/src/plugin/session-context.js +2 -5
  67. package/dist/src/plugin/session-context.js.map +1 -1
  68. package/dist/src/plugin/shared/request-services.d.ts +8 -1
  69. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  70. package/dist/src/plugin/shared/request-services.js +98 -11
  71. package/dist/src/plugin/shared/request-services.js.map +1 -1
  72. package/dist/src/plugin/shared/vault-routing.d.ts +9 -1
  73. package/dist/src/plugin/shared/vault-routing.d.ts.map +1 -1
  74. package/dist/src/plugin/shared/vault-routing.js +34 -12
  75. package/dist/src/plugin/shared/vault-routing.js.map +1 -1
  76. package/dist/tui-build-map.json +1 -1
  77. package/dist/tui-ga-build-map.json +1 -1
  78. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +4 -0
  79. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  80. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +65 -12
  81. package/dist/types/src/plugin/catalog.d.ts.map +1 -1
  82. package/dist/types/src/plugin/config/models.d.ts +9 -0
  83. package/dist/types/src/plugin/config/models.d.ts.map +1 -1
  84. package/dist/types/src/plugin/core/streaming/terminal-event.d.ts +14 -0
  85. package/dist/types/src/plugin/core/streaming/terminal-event.d.ts.map +1 -0
  86. package/dist/types/src/plugin/core/streaming/transformer.d.ts.map +1 -1
  87. package/dist/types/src/plugin/request-helpers.d.ts +10 -0
  88. package/dist/types/src/plugin/request-helpers.d.ts.map +1 -1
  89. package/dist/types/src/plugin/request.d.ts.map +1 -1
  90. package/dist/types/src/plugin/search.d.ts +7 -0
  91. package/dist/types/src/plugin/search.d.ts.map +1 -1
  92. package/dist/types/src/plugin/session-context.d.ts +1 -1
  93. package/dist/types/src/plugin/session-context.d.ts.map +1 -1
  94. package/dist/types/src/plugin/shared/request-services.d.ts +8 -1
  95. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  96. package/dist/types/src/plugin/shared/vault-routing.d.ts +9 -1
  97. package/dist/types/src/plugin/shared/vault-routing.d.ts.map +1 -1
  98. package/package.json +2 -2
  99. package/src/common-auth-embedded/claustrum/custody.d.ts +4 -0
  100. package/src/common-auth-embedded/claustrum/custody.js +147 -2
  101. package/src/common-auth-embedded/claustrum/hub.js +47 -1
  102. package/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  103. package/src/common-auth-embedded/claustrum/index.js +1 -1
  104. package/src/common-auth-embedded/fs/refresh-file-lock.js +13 -9
  105. package/src/common-auth-embedded/routing-accessor/index.d.ts +65 -12
  106. package/src/common-auth-embedded/routing-accessor/index.js +114 -15
  107. package/src/common-auth-embedded/settings/edit.d.ts +1 -0
  108. package/src/common-auth-embedded/settings/edit.js +48 -2
  109. package/src/common-auth-embedded/settings/handle.d.ts +2 -1
  110. package/src/common-auth-embedded/settings/index.d.ts +1 -0
  111. package/src/common-auth-embedded/settings/update.d.ts +14 -0
  112. package/src/common-auth-embedded/settings/update.js +28 -9
  113. package/src/common-auth-embedded/source-output.json +55 -46
package/dist/cli.js CHANGED
@@ -5825,8 +5825,8 @@ var AGY_CLI_VERSION, AGY_CLI_CHANGE_LIST;
5825
5825
  var init_fingerprint = __esm({
5826
5826
  "../core/dist/fingerprint.js"() {
5827
5827
  "use strict";
5828
- AGY_CLI_VERSION = "1.3.5";
5829
- AGY_CLI_CHANGE_LIST = "998863838";
5828
+ AGY_CLI_VERSION = "1.5.8";
5829
+ AGY_CLI_CHANGE_LIST = "1020628950";
5830
5830
  }
5831
5831
  });
5832
5832
 
@@ -5851,6 +5851,8 @@ function getResolverAliasMap() {
5851
5851
  }
5852
5852
  function getQuotaGroupForModel(modelId, hasArgonPool = false) {
5853
5853
  const normalized = modelId.toLowerCase();
5854
+ if (isGeminiHydrogenModel(normalized))
5855
+ return "gemini";
5854
5856
  if (isGeminiCarbonModel(normalized))
5855
5857
  return "gemini";
5856
5858
  if (isGeminiArgonModel(normalized))
@@ -5868,6 +5870,9 @@ function isGeminiArgonModel(model) {
5868
5870
  function isGeminiCarbonModel(model) {
5869
5871
  return /^(?:antigravity-)?gemini-4-carbon(?:-(?:low|medium|high))?$/.test(model.toLowerCase());
5870
5872
  }
5873
+ function isGeminiHydrogenModel(model) {
5874
+ return /^(?:antigravity-)?gemini-4-hydrogen(?:-(?:low|medium|high|xhigh))?$/.test(model.toLowerCase());
5875
+ }
5871
5876
  var DEFAULT_MODALITIES, MODEL_RELEASE_DATE, DEFAULT_COST, DEFAULT_OPTIONS, ALL_MODEL_DEFINITIONS, RESOLVER_ALIASES, QUOTA_GROUP_BY_MODEL_ID, ANTIGRAVITY_OPENCODE_MODEL_IDS, OPENCODE_MODEL_DEFINITIONS;
5872
5877
  var init_model_registry = __esm({
5873
5878
  "../core/dist/model-registry.js"() {
@@ -5880,6 +5885,18 @@ var init_model_registry = __esm({
5880
5885
  DEFAULT_COST = { input: 0, output: 0 };
5881
5886
  DEFAULT_OPTIONS = {};
5882
5887
  ALL_MODEL_DEFINITIONS = {
5888
+ "antigravity-gemini-4-hydrogen": defineModel("antigravity-gemini-4-hydrogen", {
5889
+ name: "Gemini 4 Hydrogen (Antigravity)",
5890
+ reasoning: true,
5891
+ limit: { context: 1048576, output: 262144 },
5892
+ modalities: DEFAULT_MODALITIES,
5893
+ variants: {
5894
+ low: { thinkingLevel: "low" },
5895
+ medium: { thinkingLevel: "medium" },
5896
+ high: { thinkingLevel: "high" },
5897
+ xhigh: { thinkingLevel: "xhigh" }
5898
+ }
5899
+ }),
5883
5900
  "antigravity-gemini-4-argon": defineModel("antigravity-gemini-4-argon", {
5884
5901
  name: "Gemini 4 Argon (Antigravity)",
5885
5902
  reasoning: true,
@@ -6014,6 +6031,7 @@ var init_model_registry = __esm({
6014
6031
  ANTIGRAVITY_OPENCODE_MODEL_IDS = [
6015
6032
  "antigravity-gemini-4-argon",
6016
6033
  "antigravity-gemini-4-carbon",
6034
+ "antigravity-gemini-4-hydrogen",
6017
6035
  "antigravity-gemini-3.8-flash",
6018
6036
  "antigravity-gemini-3.1-flash-image",
6019
6037
  "antigravity-claude-sonnet-5-5",
@@ -7138,6 +7156,7 @@ Host: ${targetHost}:${targetPort}\r
7138
7156
  const tlsOptions = {
7139
7157
  socket: proxySocket,
7140
7158
  servername: targetHost,
7159
+ ALPNProtocols: ["http/1.1"],
7141
7160
  signal: signal ?? void 0
7142
7161
  };
7143
7162
  const tlsSocket = tls.connect(tlsOptions);
@@ -7163,6 +7182,7 @@ async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
7163
7182
  host: targetUrl.hostname,
7164
7183
  port: Number(targetUrl.port || DEFAULT_HTTPS_PORT),
7165
7184
  servername: targetUrl.hostname,
7185
+ ALPNProtocols: ["http/1.1"],
7166
7186
  signal: signal ?? void 0
7167
7187
  };
7168
7188
  const socket = tls.connect(tlsOptions);
@@ -8770,647 +8790,1070 @@ var init_lock_record = __esm({
8770
8790
  }
8771
8791
  });
8772
8792
 
8773
- // ../core/dist/common-auth-embedded/fs/refresh-file-lock.js
8774
- import { randomUUID as randomUUID7 } from "node:crypto";
8775
- import { link as link2, lstat as lstat3, mkdir as mkdir7, open as open4, readdir, readFile as readFile5, rename as rename6, rm as rm4, stat as stat3, unlink as unlink6 } from "node:fs/promises";
8776
- import { basename as basename3, dirname as dirname7, join as join5 } from "node:path";
8777
- async function createExclusiveText(path2, text2) {
8778
- const tempPath = `${path2}.${randomUUID7()}.tmp`;
8779
- let handle;
8780
- try {
8781
- handle = await open4(tempPath, "wx", 384);
8782
- try {
8783
- if (leaseCreationTestHooks?.beforeWrite)
8784
- await leaseCreationTestHooks.beforeWrite(tempPath);
8785
- await handle.writeFile(text2, "utf8");
8786
- } finally {
8787
- await handle.close();
8793
+ // ../core/dist/common-auth-embedded/logger/capture-sink.js
8794
+ function createCaptureSink() {
8795
+ const records = [];
8796
+ const sink = (record3) => {
8797
+ records.push(record3);
8798
+ };
8799
+ return {
8800
+ records,
8801
+ sink,
8802
+ clear: () => {
8803
+ records.length = 0;
8804
+ }
8805
+ };
8806
+ }
8807
+ var init_capture_sink = __esm({
8808
+ "../core/dist/common-auth-embedded/logger/capture-sink.js"() {
8809
+ "use strict";
8810
+ }
8811
+ });
8812
+
8813
+ // ../core/dist/common-auth-embedded/logger/redact.js
8814
+ function isError(value) {
8815
+ return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
8816
+ }
8817
+ function createRedactor(options = {}) {
8818
+ const patterns = [TOKEN_VALUE, ...options.extraValuePatterns ?? []].map((pattern) => new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
8819
+ function isSecretKey(key) {
8820
+ const normalized = key.toLowerCase().replace(/[-_]/g, "");
8821
+ return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
8822
+ }
8823
+ function errorEntries(error) {
8824
+ const fields2 = error;
8825
+ const entries = [
8826
+ ["name", error.name],
8827
+ ["message", error.message],
8828
+ ["stack", error.stack]
8829
+ ];
8830
+ for (const key of ["code", "status", "cause"])
8831
+ if (fields2[key] !== void 0)
8832
+ entries.push([key, fields2[key]]);
8833
+ const listed = new Set(entries.map(([key]) => key));
8834
+ for (const entry of Object.entries(error))
8835
+ if (!listed.has(entry[0]))
8836
+ entries.push(entry);
8837
+ return entries;
8838
+ }
8839
+ function walk(value, keys, seen, errorDepth = 0) {
8840
+ if (typeof value === "string") {
8841
+ return patterns.reduce((text2, pattern) => text2.replace(pattern, MASK), value);
8788
8842
  }
8843
+ if (!value || typeof value !== "object")
8844
+ return value;
8845
+ if (seen.has(value))
8846
+ return "[Circular]";
8847
+ seen.add(value);
8789
8848
  try {
8790
- if (leaseCreationTestHooks?.beforeLink)
8791
- await leaseCreationTestHooks.beforeLink(tempPath, path2);
8792
- await link2(tempPath, path2);
8793
- } catch (error) {
8794
- const code2 = error.code;
8795
- if (code2 !== "EPERM" && code2 !== "ENOTSUP" && code2 !== "EOPNOTSUPP" && code2 !== "EXDEV")
8796
- throw error;
8797
- await writeExclusiveText(path2, text2);
8849
+ if (Array.isArray(value))
8850
+ return value.map((item) => walk(item, keys, seen, errorDepth));
8851
+ const error = isError(value);
8852
+ if (error && errorDepth >= MAX_ERROR_DEPTH)
8853
+ return "[Truncated]";
8854
+ const childDepth = error ? errorDepth + 1 : errorDepth;
8855
+ return Object.fromEntries((error ? errorEntries(value) : Object.entries(value)).map(([key, item]) => [
8856
+ key,
8857
+ keys && isSecretKey(key) ? MASK : walk(item, keys, seen, childDepth)
8858
+ ]));
8859
+ } finally {
8860
+ seen.delete(value);
8798
8861
  }
8799
- } finally {
8800
- if (handle)
8801
- await rm4(tempPath, { force: true }).catch(() => {
8802
- });
8803
8862
  }
8863
+ return {
8864
+ redact: (value) => walk(value, true, /* @__PURE__ */ new WeakSet()),
8865
+ // Schema keys describe arguments, not credentials; only their string values are scrubbed.
8866
+ redactStrings: (value) => walk(value, false, /* @__PURE__ */ new WeakSet())
8867
+ };
8804
8868
  }
8805
- async function writeExclusiveText(path2, text2) {
8806
- const handle = await open4(path2, "wx", 384);
8807
- let createdStat;
8869
+ var SECRET_KEY_EXACT, TOKEN_VALUE, MASK, MAX_ERROR_DEPTH, defaultRedactor, redact, redactStrings;
8870
+ var init_redact = __esm({
8871
+ "../core/dist/common-auth-embedded/logger/redact.js"() {
8872
+ "use strict";
8873
+ SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
8874
+ TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
8875
+ MASK = "***REDACTED***";
8876
+ MAX_ERROR_DEPTH = 8;
8877
+ defaultRedactor = createRedactor();
8878
+ redact = defaultRedactor.redact;
8879
+ redactStrings = defaultRedactor.redactStrings;
8880
+ }
8881
+ });
8882
+
8883
+ // ../core/dist/common-auth-embedded/logger/engine.js
8884
+ import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
8885
+ import { open as open4 } from "node:fs/promises";
8886
+ import { dirname as dirname7, resolve as resolve4 } from "node:path";
8887
+ function chmodPrivate(path2) {
8808
8888
  try {
8809
- createdStat = await handle.stat();
8889
+ chmodSync(path2, 384);
8810
8890
  } catch {
8811
- createdStat = void 0;
8812
8891
  }
8892
+ }
8893
+ function rotateIfNeeded(f) {
8813
8894
  try {
8814
- if (leaseCreationTestHooks?.beforeWrite)
8815
- await leaseCreationTestHooks.beforeWrite(path2);
8816
- await handle.writeFile(text2, "utf8");
8817
- } catch (error) {
8818
- try {
8819
- const current = await lstat3(path2).catch(() => void 0);
8820
- if (createdStat && current && current.dev === createdStat.dev && current.ino === createdStat.ino) {
8821
- await rm4(path2, { force: true }).catch(() => {
8822
- });
8895
+ if (!(existsSync(f) && statSync(f).size >= MAX_BYTES))
8896
+ return;
8897
+ for (let i = ROTATE_KEEP - 1; i >= 1; i--) {
8898
+ if (existsSync(`${f}.${i}`)) {
8899
+ const rotated2 = `${f}.${i + 1}`;
8900
+ renameSync(`${f}.${i}`, rotated2);
8901
+ chmodPrivate(rotated2);
8823
8902
  }
8824
- } catch {
8825
8903
  }
8826
- throw error;
8827
- } finally {
8828
- await handle.close();
8904
+ const rotated = `${f}.1`;
8905
+ renameSync(f, rotated);
8906
+ chmodPrivate(rotated);
8907
+ } catch {
8829
8908
  }
8830
8909
  }
8831
- function isStagingName(name, lockName) {
8832
- const prefix = `${lockName}.`;
8833
- const suffix = ".tmp";
8834
- if (!name.startsWith(prefix) || !name.endsWith(suffix))
8835
- return false;
8836
- return STAGING_UUID.test(name.slice(prefix.length, -suffix.length));
8910
+ async function closeWindowsFile(sink) {
8911
+ const { file, handle } = sink;
8912
+ sink.file = void 0;
8913
+ sink.handle = void 0;
8914
+ if (file && handle)
8915
+ await privateOperation(file, "log-close", () => handle.close());
8837
8916
  }
8838
- function sameStagingFile(a, b) {
8839
- return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.birthtimeMs === b.birthtimeMs;
8917
+ async function openWindowsFile(sink, file) {
8918
+ await ensurePrivateDirectory(dirname7(file));
8919
+ try {
8920
+ await verifyPrivate(file, "file", true);
8921
+ } catch (error) {
8922
+ if (error.code !== "ENOENT")
8923
+ throw error;
8924
+ try {
8925
+ await createPrivateBytes(file, "");
8926
+ } catch (creationError) {
8927
+ if (creationError.code !== "EEXIST")
8928
+ throw creationError;
8929
+ await verifyPrivate(file, "file", true);
8930
+ }
8931
+ }
8932
+ sink.handle = await privateOperation(file, "log-open", () => open4(file, "a"));
8933
+ sink.file = file;
8934
+ return sink.handle;
8840
8935
  }
8841
- async function readStagedOwner(path2) {
8842
- const before = await lstat3(path2);
8843
- if (!before.isFile() || before.isSymbolicLink())
8844
- return void 0;
8845
- if (before.size > STAGING_SWEEP_MAX_BYTES)
8846
- return void 0;
8847
- const handle = await open4(path2, "r");
8848
- let text2;
8936
+ async function flushWindowsFile(sink, file, text2) {
8937
+ file = resolve4(file);
8849
8938
  try {
8850
- if (!sameStagingFile(before, await handle.stat()))
8851
- return void 0;
8852
- text2 = await handle.readFile("utf8");
8853
- } finally {
8854
- await handle.close();
8939
+ if (sink.file !== file)
8940
+ await closeWindowsFile(sink);
8941
+ let handle = sink.handle ?? await openWindowsFile(sink, file);
8942
+ const info = await privateOperation(file, "log-stat", () => handle.stat());
8943
+ if (info.size >= MAX_BYTES) {
8944
+ await closeWindowsFile(sink);
8945
+ for (let i = ROTATE_KEEP - 1; i >= 0; i--) {
8946
+ const source = i === 0 ? file : `${file}.${i}`;
8947
+ const target = `${file}.${i + 1}`;
8948
+ try {
8949
+ await verifyPrivate(source, "file", true);
8950
+ } catch (error) {
8951
+ if (error.code === "ENOENT")
8952
+ continue;
8953
+ throw error;
8954
+ }
8955
+ try {
8956
+ await verifyPrivate(target, "file", true);
8957
+ } catch (error) {
8958
+ if (error.code !== "ENOENT")
8959
+ throw error;
8960
+ }
8961
+ await replaceWindowsFile(source, target);
8962
+ await verifyPrivate(target, "file");
8963
+ }
8964
+ handle = await openWindowsFile(sink, file);
8965
+ }
8966
+ await privateOperation(file, "log-append", () => handle.appendFile(text2, "utf8"));
8967
+ } catch (error) {
8968
+ await closeWindowsFile(sink).catch(() => {
8969
+ });
8970
+ throw error;
8855
8971
  }
8856
- let record3;
8972
+ }
8973
+ function safeSerialize(data) {
8857
8974
  try {
8858
- record3 = JSON.parse(text2);
8975
+ return ` ${JSON.stringify(data)}`;
8859
8976
  } catch {
8860
- return void 0;
8977
+ return " [unserializable]";
8861
8978
  }
8862
- if (!record3 || typeof record3 !== "object" || Array.isArray(record3))
8863
- return void 0;
8864
- const keys = Object.keys(record3).sort();
8865
- if (keys.length !== 2 || keys[0] !== "expiresAt" || keys[1] !== "ownerId")
8866
- return void 0;
8867
- const { ownerId, expiresAt } = record3;
8868
- if (typeof ownerId !== "string" || !STAGING_UUID.test(ownerId))
8869
- return void 0;
8870
- if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
8871
- return void 0;
8872
- return { identity: before, expiresAt };
8873
8979
  }
8874
- async function sweepAbandonedStaging(lockPath, ttlMs, now) {
8875
- const directory = dirname7(lockPath);
8876
- const lockName = basename3(lockPath);
8877
- const hooks = stagingSweepTestHooks;
8878
- const names = await (hooks?.readdir ?? readdir)(directory);
8879
- const candidates = names.filter((name) => isStagingName(name, lockName)).slice(0, STAGING_SWEEP_MAX_CANDIDATES);
8880
- const marginMs = Math.max(Number.isFinite(ttlMs) ? ttlMs : 0, STAGING_SWEEP_MIN_AGE_MS);
8881
- for (const name of candidates) {
8882
- const path2 = join5(directory, name);
8883
- try {
8884
- if (now() - (await lstat3(path2)).mtimeMs < marginMs)
8885
- continue;
8886
- const staged = await readStagedOwner(path2);
8887
- if (!staged || !(staged.expiresAt < now() - marginMs))
8888
- continue;
8889
- if (hooks?.beforeUnlink)
8890
- await hooks.beforeUnlink(path2);
8891
- const current = await readStagedOwner(path2);
8892
- if (!current || !sameStagingFile(staged.identity, current.identity) || !(current.expiresAt < now() - marginMs))
8893
- continue;
8894
- await (hooks?.unlink ?? unlink6)(path2);
8895
- } catch {
8896
- }
8980
+ function createEngine(options) {
8981
+ let logFileSource;
8982
+ let initLevelSource;
8983
+ let runtimeLevel;
8984
+ let redactor = createRedactor();
8985
+ let captureSink;
8986
+ let buffer = [];
8987
+ let timer;
8988
+ let orderedSink = Promise.resolve();
8989
+ let sinkError;
8990
+ const windowsFile = {};
8991
+ function queueWindows(operation) {
8992
+ const next = orderedSink.then(operation);
8993
+ orderedSink = next.catch((error) => {
8994
+ sinkError = error;
8995
+ });
8996
+ return next;
8897
8997
  }
8898
- }
8899
- function startStagingSweep(lockPath, ttlMs, now) {
8900
- if (sweptLockPaths.has(lockPath))
8901
- return;
8902
- sweptLockPaths.add(lockPath);
8903
- const sweep = Promise.resolve().then(() => sweepAbandonedStaging(lockPath, ttlMs, now)).catch(() => {
8904
- });
8905
- pendingStagingSweeps.add(sweep);
8906
- void sweep.finally(() => pendingStagingSweeps.delete(sweep));
8907
- }
8908
- function isLostMarkerRaceError(error) {
8909
- const code2 = error?.code;
8910
- return code2 === "ENOENT" || !windowsPrivateFiles && (code2 === "EINVAL" || code2 === "ENOTDIR");
8911
- }
8912
- function sameMarkerDirectory(created, current) {
8913
- if (created.dev !== current.dev || created.ino !== current.ino)
8914
- return false;
8915
- if (created.ino === 0 && created.birthtimeMs !== current.birthtimeMs)
8916
- return false;
8917
- return true;
8918
- }
8919
- function acquireRefreshFileLock(options) {
8920
- return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
8921
- }
8922
- async function acquireRefreshFileLockWithClock(options) {
8923
- const lockPath = lockPathFor(options.path, options.name);
8924
- const legacyOwnerPath = join5(lockPath, "owner.json");
8925
- const ownerId = randomUUID7();
8926
- const now = options.now ?? Date.now;
8927
- let renewTimer = null;
8928
- let released = false;
8929
- let releaseConfirmed = false;
8930
- let loss;
8931
- let resolveLoss;
8932
- const lostPromise = new Promise((resolve24) => {
8933
- resolveLoss = resolve24;
8934
- });
8935
- function notifyTimerStep(event) {
8936
- try {
8937
- const result = options.onRenewalTimer?.(event);
8938
- if (result && (typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function") {
8939
- void Promise.resolve(result).catch(() => {
8940
- });
8941
- }
8942
- } catch {
8943
- }
8998
+ function configure(next) {
8999
+ if (windowsPrivateFiles && next.file !== logFileSource)
9000
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
9001
+ });
9002
+ logFileSource = next.file;
9003
+ initLevelSource = next.level;
9004
+ redactor = createRedactor(next);
9005
+ captureSink = next.captureSink;
8944
9006
  }
8945
- function cancelRenewalTimer() {
8946
- if (!renewTimer)
8947
- return;
8948
- clearRefreshLockRenewalTimeout(renewTimer);
8949
- renewTimer = null;
8950
- notifyTimerStep("cancelled");
9007
+ function setLogLevel3(l) {
9008
+ if (l === void 0 || l in ORDER)
9009
+ runtimeLevel = l;
8951
9010
  }
8952
- function recordLoss(reason, owner) {
8953
- if (loss || released)
8954
- return;
8955
- loss = Object.freeze({
8956
- reason,
8957
- expectedOwnerId: ownerId,
8958
- ...typeof owner?.ownerId === "string" ? { observedOwnerId: owner.ownerId } : {},
8959
- ...typeof owner?.expiresAt === "number" ? { observedExpiresAt: owner.expiresAt } : {}
8960
- });
8961
- cancelRenewalTimer();
8962
- resolveLoss(loss);
9011
+ function logFilePath() {
9012
+ if (logFileSource === void 0)
9013
+ return void 0;
9014
+ const resolved = typeof logFileSource === "function" ? logFileSource() : logFileSource;
9015
+ return resolved || void 0;
8963
9016
  }
8964
- let terminalIOError;
8965
- let renewalInFlight = null;
8966
- const evictPath = `${lockPath}.evicting`;
8967
- const evictOwnerPath = join5(evictPath, "owner.json");
8968
- const evictOwnerId = randomUUID7();
8969
- const EVICT_TTL = 5e3;
8970
- const MAX_STEAL_ATTEMPTS = 8;
8971
- function isChangingLockCreate(error) {
8972
- return windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [lockPath], "create") || isWindowsAccessDeniedCreate(error, [evictPath], "directory-create"));
9017
+ function configuredLevel() {
9018
+ if (runtimeLevel)
9019
+ return runtimeLevel;
9020
+ const floor = typeof initLevelSource === "function" ? initLevelSource() : initLevelSource;
9021
+ if (floor && floor in ORDER)
9022
+ return floor;
9023
+ return "info";
8973
9024
  }
8974
- async function readOwner() {
8975
- if (windowsPrivateFiles) {
8976
- try {
8977
- return JSON.parse(await readLockRecord(lockPath, () => readPrivateText(lockPath, true)));
8978
- } catch (error) {
8979
- if (error.code !== "EISDIR" && error.reason !== "wrong-kind")
8980
- throw error;
8981
- await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
8982
- return JSON.parse(await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true)));
8983
- }
9025
+ function flushLogs3(close = true) {
9026
+ if (timer) {
9027
+ clearTimeout(timer);
9028
+ timer = void 0;
9029
+ }
9030
+ if (!buffer.length) {
9031
+ if (windowsPrivateFiles)
9032
+ return queueWindows(async () => {
9033
+ if (close)
9034
+ await closeWindowsFile(windowsFile);
9035
+ if (sinkError)
9036
+ throw sinkError;
9037
+ });
9038
+ return;
8984
9039
  }
9040
+ let file;
8985
9041
  try {
8986
- return JSON.parse(await readFile5(lockPath, "utf8"));
8987
- } catch (error) {
8988
- const code2 = error.code;
8989
- if (code2 !== "EISDIR")
8990
- throw error;
8991
- return JSON.parse(await readFile5(legacyOwnerPath, "utf8"));
9042
+ file = logFilePath();
9043
+ } catch {
9044
+ buffer = [];
9045
+ if (windowsPrivateFiles && close)
9046
+ return queueWindows(() => closeWindowsFile(windowsFile));
9047
+ return;
9048
+ }
9049
+ const text2 = buffer.join("");
9050
+ buffer = [];
9051
+ if (!file) {
9052
+ if (windowsPrivateFiles && close)
9053
+ return queueWindows(() => closeWindowsFile(windowsFile));
9054
+ return;
8992
9055
  }
8993
- }
8994
- async function writeOwner() {
8995
9056
  if (windowsPrivateFiles) {
8996
- const owner = await readOwner();
8997
- const remaining = Number(owner?.expiresAt) - now();
8998
- await writePrivateAtomic(lockPath, `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
8999
- `, {
9000
- deadline: performance.now() + Math.max(0, remaining),
9001
- beforeRename: async () => {
9002
- const current = await readOwner();
9003
- if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
9004
- throw new LockOwnershipError({
9005
- target: options.path,
9006
- name: options.name
9007
- });
9008
- }
9057
+ return queueWindows(async () => {
9058
+ try {
9059
+ await flushWindowsFile(windowsFile, file, text2);
9060
+ } finally {
9061
+ if (close)
9062
+ await closeWindowsFile(windowsFile);
9009
9063
  }
9010
9064
  });
9011
- return;
9012
9065
  }
9013
- const tempPath = `${lockPath}.${randomUUID7()}.tmp`;
9014
- let handle;
9015
- let created = false;
9016
9066
  try {
9017
- handle = await open4(tempPath, "wx", 384);
9018
- created = true;
9019
- await handle.writeFile(`${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
9020
- `, "utf8");
9021
- await handle.chmod(384);
9022
- await handle.close();
9023
- handle = void 0;
9024
- const current = await readOwner();
9025
- if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
9026
- throw new LockOwnershipError({
9027
- target: options.path,
9028
- name: options.name
9029
- });
9030
- }
9031
- await rename6(tempPath, lockPath);
9032
- created = false;
9033
- } finally {
9034
- await handle?.close().catch(() => {
9035
- });
9036
- if (created)
9037
- await rm4(tempPath, { force: true }).catch(() => {
9038
- });
9067
+ rotateIfNeeded(file);
9068
+ if (existsSync(file))
9069
+ chmodPrivate(file);
9070
+ appendFileSync(file, text2, { encoding: "utf8", mode: 384 });
9071
+ } catch {
9039
9072
  }
9040
9073
  }
9041
- async function createLease() {
9042
- const bytes = `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
9043
- `;
9044
- if (windowsPrivateFiles)
9045
- await createPrivateBytes(lockPath, bytes);
9046
- else
9047
- await createExclusiveText(lockPath, bytes);
9074
+ function schedule2() {
9075
+ if (!timer)
9076
+ timer = setTimeout(() => {
9077
+ timer = void 0;
9078
+ const flushed = flushLogs3(false);
9079
+ if (flushed instanceof Promise)
9080
+ void flushed.catch(() => {
9081
+ });
9082
+ }, 500);
9048
9083
  }
9049
- async function leaseContention(error) {
9050
- const code2 = error.code;
9051
- if (code2 !== "EEXIST" && code2 !== "EISDIR")
9052
- return false;
9053
- if (windowsPrivateFiles) {
9054
- if (options.onStep)
9055
- await options.onStep("lease-contention-read-ready");
9084
+ function emit(channel3, level, message, data) {
9085
+ if (logFileSource === void 0 && captureSink === void 0)
9086
+ return;
9087
+ try {
9088
+ if (ORDER[level] > ORDER[configuredLevel()])
9089
+ return;
9090
+ const scrubbedMessage = redactor.redactStrings(message);
9091
+ let scrubbedData;
9056
9092
  try {
9057
- if (code2 === "EISDIR") {
9058
- await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
9059
- await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true));
9060
- } else
9061
- await readOwner();
9062
- } catch (readError) {
9063
- if (readError.code !== "ENOENT")
9064
- throw readError;
9093
+ scrubbedData = redactor.redact(data);
9094
+ } catch {
9095
+ scrubbedData = "[unserializable]";
9096
+ }
9097
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${level.toUpperCase()} [${channel3}] ${scrubbedMessage}` + (data === void 0 ? "" : safeSerialize(scrubbedData)) + "\n";
9098
+ try {
9099
+ captureSink?.({
9100
+ channel: channel3,
9101
+ level,
9102
+ message: scrubbedMessage,
9103
+ data: scrubbedData
9104
+ });
9105
+ } catch {
9065
9106
  }
9107
+ if (logFileSource === void 0)
9108
+ return;
9109
+ buffer.push(line);
9110
+ if (buffer.length >= 50) {
9111
+ const flushed = flushLogs3(false);
9112
+ if (flushed instanceof Promise)
9113
+ void flushed.catch(() => {
9114
+ });
9115
+ } else
9116
+ schedule2();
9117
+ } catch {
9066
9118
  }
9067
- return true;
9068
9119
  }
9069
- async function tryAcquire() {
9120
+ function createLogger5(channel3) {
9121
+ return {
9122
+ error: (m, d) => emit(channel3, "error", m, d),
9123
+ warn: (m, d) => emit(channel3, "warn", m, d),
9124
+ info: (m, d) => emit(channel3, "info", m, d),
9125
+ debug: (m, d) => emit(channel3, "debug", m, d),
9126
+ trace: (m, d) => emit(channel3, "trace", m, d)
9127
+ };
9128
+ }
9129
+ function reset() {
9070
9130
  if (windowsPrivateFiles)
9071
- await ensurePrivateDirectory(dirname7(lockPath));
9072
- try {
9073
- await createLease();
9074
- return true;
9075
- } catch (error) {
9076
- const code2 = error.code;
9077
- if (await leaseContention(error))
9078
- return false;
9079
- if (code2 === "ENOENT") {
9080
- if (windowsPrivateFiles)
9081
- await ensurePrivateDirectory(dirname7(lockPath));
9082
- else
9083
- await mkdir7(dirname7(lockPath), { recursive: true });
9084
- try {
9085
- await createLease();
9086
- return true;
9087
- } catch (retryError) {
9088
- if (await leaseContention(retryError))
9089
- return false;
9090
- throw retryError;
9091
- }
9092
- }
9093
- throw error;
9131
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
9132
+ });
9133
+ sinkError = void 0;
9134
+ buffer = [];
9135
+ if (timer) {
9136
+ clearTimeout(timer);
9137
+ timer = void 0;
9094
9138
  }
9139
+ logFileSource = void 0;
9140
+ initLevelSource = void 0;
9141
+ runtimeLevel = void 0;
9142
+ redactor = createRedactor();
9143
+ captureSink = void 0;
9095
9144
  }
9096
- async function backoff() {
9097
- await new Promise((resolve24) => setTimeout(resolve24, Math.floor(Math.random() * 4)));
9145
+ if (options)
9146
+ configure(options);
9147
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3, reset };
9148
+ }
9149
+ function createLoggerInstance(options) {
9150
+ const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine(options);
9151
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
9152
+ }
9153
+ function initLogger(options) {
9154
+ defaultEngine.configure(options);
9155
+ const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = defaultEngine;
9156
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
9157
+ }
9158
+ function setLogLevel(l) {
9159
+ defaultEngine.setLogLevel(l);
9160
+ }
9161
+ function flushLogs() {
9162
+ return defaultEngine.flushLogs();
9163
+ }
9164
+ function createLogger2(channel3) {
9165
+ return defaultEngine.createLogger(channel3);
9166
+ }
9167
+ async function flushForTest() {
9168
+ return defaultEngine.flushLogs();
9169
+ }
9170
+ function resetLoggerForTest() {
9171
+ defaultEngine.reset();
9172
+ }
9173
+ var ORDER, MAX_BYTES, ROTATE_KEEP, defaultEngine;
9174
+ var init_engine = __esm({
9175
+ "../core/dist/common-auth-embedded/logger/engine.js"() {
9176
+ "use strict";
9177
+ init_private_files();
9178
+ init_redact();
9179
+ ORDER = {
9180
+ error: 0,
9181
+ warn: 1,
9182
+ info: 2,
9183
+ debug: 3,
9184
+ trace: 4
9185
+ };
9186
+ MAX_BYTES = 5 * 1024 * 1024;
9187
+ ROTATE_KEEP = 3;
9188
+ defaultEngine = createEngine();
9098
9189
  }
9099
- async function readLockState(notifyReady = true) {
9100
- if (notifyReady && options.onStep)
9101
- await options.onStep("lock-read-ready");
9102
- let owner;
9190
+ });
9191
+
9192
+ // ../core/dist/common-auth-embedded/logger/index.js
9193
+ var logger_exports = {};
9194
+ __export(logger_exports, {
9195
+ createCaptureSink: () => createCaptureSink,
9196
+ createLogger: () => createLogger2,
9197
+ createLoggerInstance: () => createLoggerInstance,
9198
+ createRedactor: () => createRedactor,
9199
+ flushForTest: () => flushForTest,
9200
+ flushLogs: () => flushLogs,
9201
+ initLogger: () => initLogger,
9202
+ redact: () => redact,
9203
+ redactStrings: () => redactStrings,
9204
+ resetLoggerForTest: () => resetLoggerForTest,
9205
+ setLogLevel: () => setLogLevel
9206
+ });
9207
+ var init_logger2 = __esm({
9208
+ "../core/dist/common-auth-embedded/logger/index.js"() {
9209
+ "use strict";
9210
+ init_capture_sink();
9211
+ init_engine();
9212
+ init_redact();
9213
+ }
9214
+ });
9215
+
9216
+ // ../core/dist/common-auth-embedded/fs/refresh-file-lock.js
9217
+ import { randomUUID as randomUUID7 } from "node:crypto";
9218
+ import { link as link2, lstat as lstat3, mkdir as mkdir7, open as open5, readdir, readFile as readFile5, rename as rename6, rm as rm4, stat as stat3, unlink as unlink6 } from "node:fs/promises";
9219
+ import { basename as basename3, dirname as dirname8, join as join5 } from "node:path";
9220
+ async function createExclusiveText(path2, text2) {
9221
+ const tempPath = `${path2}.${randomUUID7()}.tmp`;
9222
+ let handle;
9223
+ try {
9224
+ handle = await open5(tempPath, "wx", 384);
9103
9225
  try {
9104
- owner = await readOwner();
9105
- } catch (error) {
9106
- if (error instanceof DisappearedLockRecordError)
9107
- return { status: "missing" };
9108
- if (windowsPrivateFiles && error.code !== "ENOENT")
9109
- throw error;
9110
- }
9111
- const expiresAt = Number(owner?.expiresAt);
9112
- if (Number.isFinite(expiresAt) && expiresAt > now())
9113
- return { status: "live" };
9114
- if (typeof owner?.ownerId === "string" && Number.isFinite(expiresAt)) {
9115
- return {
9116
- status: "stale",
9117
- identity: { kind: "owner", ownerId: owner.ownerId, expiresAt }
9118
- };
9226
+ if (leaseCreationTestHooks?.beforeWrite)
9227
+ await leaseCreationTestHooks.beforeWrite(tempPath);
9228
+ await handle.writeFile(text2, "utf8");
9229
+ } finally {
9230
+ await handle.close();
9119
9231
  }
9120
9232
  try {
9121
- const current = await stat3(lockPath);
9122
- const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
9123
- if (legacyExpiry > now())
9124
- return { status: "live" };
9125
- return {
9126
- status: "stale",
9127
- identity: {
9128
- kind: "stat",
9129
- dev: current.dev,
9130
- ino: current.ino,
9131
- mtimeMs: current.mtimeMs,
9132
- expiresAt: legacyExpiry
9133
- }
9134
- };
9233
+ if (leaseCreationTestHooks?.beforeLink)
9234
+ await leaseCreationTestHooks.beforeLink(tempPath, path2);
9235
+ await link2(tempPath, path2);
9135
9236
  } catch (error) {
9136
- if (error.code === "ENOENT") {
9137
- if (options.onStep)
9138
- await options.onStep("lock-missing");
9139
- return { status: "missing" };
9140
- }
9141
- throw error;
9237
+ const code2 = error.code;
9238
+ if (code2 !== "EPERM" && code2 !== "ENOTSUP" && code2 !== "EOPNOTSUPP" && code2 !== "EXDEV")
9239
+ throw error;
9240
+ await writeExclusiveText(path2, text2);
9142
9241
  }
9242
+ } finally {
9243
+ if (handle)
9244
+ await rm4(tempPath, { force: true }).catch(() => {
9245
+ });
9143
9246
  }
9144
- function sameStaleLock(observed, current) {
9145
- if (current.status !== "stale")
9146
- return false;
9147
- const identity3 = current.identity;
9148
- if (observed.kind === "owner" && identity3.kind === "owner") {
9149
- return observed.ownerId === identity3.ownerId && observed.expiresAt === identity3.expiresAt;
9150
- }
9151
- return observed.kind === "stat" && identity3.kind === "stat" && observed.dev === identity3.dev && observed.ino === identity3.ino && observed.mtimeMs === identity3.mtimeMs && observed.expiresAt === identity3.expiresAt;
9247
+ }
9248
+ async function writeExclusiveText(path2, text2) {
9249
+ const handle = await open5(path2, "wx", 384);
9250
+ let createdStat;
9251
+ try {
9252
+ createdStat = await handle.stat();
9253
+ } catch {
9254
+ createdStat = void 0;
9152
9255
  }
9153
- async function ownsEvictionMarker() {
9256
+ try {
9257
+ if (leaseCreationTestHooks?.beforeWrite)
9258
+ await leaseCreationTestHooks.beforeWrite(path2);
9259
+ await handle.writeFile(text2, "utf8");
9260
+ } catch (error) {
9154
9261
  try {
9155
- const owner = JSON.parse(await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, windowsPrivateFiles)));
9156
- return owner?.ownerId === evictOwnerId;
9157
- } catch (error) {
9158
- if (windowsPrivateFiles && error.code !== "ENOENT")
9159
- throw error;
9160
- return false;
9262
+ const current = await lstat3(path2).catch(() => void 0);
9263
+ if (createdStat && current && current.dev === createdStat.dev && current.ino === createdStat.ino) {
9264
+ await rm4(path2, { force: true }).catch(() => {
9265
+ });
9266
+ }
9267
+ } catch {
9161
9268
  }
9269
+ throw error;
9270
+ } finally {
9271
+ await handle.close();
9162
9272
  }
9163
- async function removeLeaseObject(path2) {
9164
- if (windowsPrivateFiles)
9165
- await privateOperation(path2, "remove", () => rm4(path2, { recursive: true, force: true }));
9166
- else
9167
- await rm4(path2, { recursive: true, force: true }).catch(() => {
9168
- });
9169
- }
9170
- function isRetryableRemoval(error, path2) {
9171
- if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.stage !== "remove" || error.path !== path2)
9172
- return false;
9173
- return isWindowsSharingViolation(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
9174
- }
9175
- async function removeOwnedLeaseObject(path2, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
9176
- let original;
9177
- let delayMs = 5;
9178
- while (await stillOwned()) {
9179
- try {
9180
- await removeLeaseObject(path2);
9181
- return;
9182
- } catch (error) {
9183
- if (!isRetryableRemoval(error, path2))
9184
- throw error;
9185
- original ??= error;
9186
- }
9187
- const remainingMs = deadline - performance.now();
9188
- if (remainingMs <= 0)
9189
- throw original;
9190
- await new Promise((resolve24) => setTimeout(resolve24, Math.min(delayMs, remainingMs)));
9191
- if (performance.now() >= deadline)
9192
- throw original;
9193
- delayMs = Math.min(delayMs * 2, 50);
9194
- }
9273
+ }
9274
+ function isStagingName(name, lockName) {
9275
+ const prefix = `${lockName}.`;
9276
+ const suffix = ".tmp";
9277
+ if (!name.startsWith(prefix) || !name.endsWith(suffix))
9278
+ return false;
9279
+ return STAGING_UUID.test(name.slice(prefix.length, -suffix.length));
9280
+ }
9281
+ function sameStagingFile(a, b) {
9282
+ return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.birthtimeMs === b.birthtimeMs;
9283
+ }
9284
+ async function readStagedOwner(path2) {
9285
+ const before = await lstat3(path2);
9286
+ if (!before.isFile() || before.isSymbolicLink())
9287
+ return void 0;
9288
+ if (before.size > STAGING_SWEEP_MAX_BYTES)
9289
+ return void 0;
9290
+ const handle = await open5(path2, "r");
9291
+ let text2;
9292
+ try {
9293
+ if (!sameStagingFile(before, await handle.stat()))
9294
+ return void 0;
9295
+ text2 = await handle.readFile("utf8");
9296
+ } finally {
9297
+ await handle.close();
9195
9298
  }
9196
- async function releaseEvictionMarker(deadline) {
9197
- let ownedDirectory;
9198
- await removeOwnedLeaseObject(evictPath, async () => {
9199
- if (!windowsPrivateFiles)
9200
- return ownsEvictionMarker();
9201
- const current = await lstat3(evictPath).catch((error) => {
9202
- if (error.code !== "ENOENT")
9203
- throw error;
9204
- return void 0;
9205
- });
9206
- if (!current || ownedDirectory && !sameMarkerDirectory(ownedDirectory, current))
9207
- return false;
9208
- if (await ownsEvictionMarker()) {
9209
- ownedDirectory = current;
9210
- return true;
9211
- }
9212
- if (!ownedDirectory)
9213
- return false;
9214
- try {
9215
- await stat3(evictOwnerPath);
9216
- return false;
9217
- } catch (error) {
9218
- if (error.code !== "ENOENT")
9219
- throw error;
9220
- return true;
9221
- }
9222
- }, deadline);
9299
+ let record3;
9300
+ try {
9301
+ record3 = JSON.parse(text2);
9302
+ } catch {
9303
+ return void 0;
9223
9304
  }
9224
- async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
9225
- if (!created)
9226
- return false;
9227
- let stillOurs = false;
9305
+ if (!record3 || typeof record3 !== "object" || Array.isArray(record3))
9306
+ return void 0;
9307
+ const keys = Object.keys(record3).sort();
9308
+ if (keys.length !== 2 || keys[0] !== "expiresAt" || keys[1] !== "ownerId")
9309
+ return void 0;
9310
+ const { ownerId, expiresAt } = record3;
9311
+ if (typeof ownerId !== "string" || !STAGING_UUID.test(ownerId))
9312
+ return void 0;
9313
+ if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
9314
+ return void 0;
9315
+ return { identity: before, expiresAt };
9316
+ }
9317
+ async function sweepAbandonedStaging(lockPath, ttlMs, now) {
9318
+ const directory = dirname8(lockPath);
9319
+ const lockName = basename3(lockPath);
9320
+ const hooks = stagingSweepTestHooks;
9321
+ const names = await (hooks?.readdir ?? readdir)(directory);
9322
+ const candidates = names.filter((name) => isStagingName(name, lockName)).slice(0, STAGING_SWEEP_MAX_CANDIDATES);
9323
+ const marginMs = Math.max(Number.isFinite(ttlMs) ? ttlMs : 0, STAGING_SWEEP_MIN_AGE_MS);
9324
+ for (const name of candidates) {
9325
+ const path2 = join5(directory, name);
9228
9326
  try {
9229
- await removeOwnedLeaseObject(evictPath, async () => {
9230
- stillOurs = false;
9231
- const st = await lstat3(evictPath).catch(() => void 0);
9232
- if (!st || !sameMarkerDirectory(created, st))
9233
- return false;
9234
- stillOurs = true;
9235
- try {
9236
- await stat3(evictOwnerPath);
9237
- return false;
9238
- } catch (error) {
9239
- return error.code === "ENOENT";
9240
- }
9241
- }, deadline);
9327
+ if (now() - (await lstat3(path2)).mtimeMs < marginMs)
9328
+ continue;
9329
+ const staged = await readStagedOwner(path2);
9330
+ if (!staged || !(staged.expiresAt < now() - marginMs))
9331
+ continue;
9332
+ if (hooks?.beforeUnlink)
9333
+ await hooks.beforeUnlink(path2);
9334
+ const current = await readStagedOwner(path2);
9335
+ if (!current || !sameStagingFile(staged.identity, current.identity) || !(current.expiresAt < now() - marginMs))
9336
+ continue;
9337
+ await (hooks?.unlink ?? unlink6)(path2);
9242
9338
  } catch {
9243
9339
  }
9244
- return stillOurs;
9245
9340
  }
9246
- async function tryAcquireEvictionMarker(deadline) {
9247
- if (windowsPrivateFiles)
9248
- await createPrivateDirectoryExclusive(evictPath);
9249
- else
9250
- await mkdir7(evictPath);
9251
- let created;
9341
+ }
9342
+ function startStagingSweep(lockPath, ttlMs, now) {
9343
+ if (sweptLockPaths.has(lockPath))
9344
+ return;
9345
+ sweptLockPaths.add(lockPath);
9346
+ const sweep = Promise.resolve().then(() => sweepAbandonedStaging(lockPath, ttlMs, now)).catch(() => {
9347
+ });
9348
+ pendingStagingSweeps.add(sweep);
9349
+ void sweep.finally(() => pendingStagingSweeps.delete(sweep));
9350
+ }
9351
+ function isLostMarkerRaceError(error) {
9352
+ const code2 = error?.code;
9353
+ return code2 === "ENOENT" || !windowsPrivateFiles && (code2 === "EINVAL" || code2 === "ENOTDIR");
9354
+ }
9355
+ function sameMarkerDirectory(created, current) {
9356
+ if (created.dev !== current.dev || created.ino !== current.ino)
9357
+ return false;
9358
+ if (created.ino === 0 && created.birthtimeMs !== current.birthtimeMs)
9359
+ return false;
9360
+ return true;
9361
+ }
9362
+ function acquireRefreshFileLock(options) {
9363
+ return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
9364
+ }
9365
+ async function acquireRefreshFileLockWithClock(options) {
9366
+ const lockPath = lockPathFor(options.path, options.name);
9367
+ const legacyOwnerPath = join5(lockPath, "owner.json");
9368
+ const ownerId = randomUUID7();
9369
+ const now = options.now ?? Date.now;
9370
+ let renewTimer = null;
9371
+ let released = false;
9372
+ let releaseConfirmed = false;
9373
+ let loss;
9374
+ let resolveLoss;
9375
+ const lostPromise = new Promise((resolve24) => {
9376
+ resolveLoss = resolve24;
9377
+ });
9378
+ function notifyTimerStep(event) {
9252
9379
  try {
9253
- const st = await lstat3(evictPath);
9254
- created = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
9380
+ const result = options.onRenewalTimer?.(event);
9381
+ if (result && (typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function") {
9382
+ void Promise.resolve(result).catch(() => {
9383
+ });
9384
+ }
9255
9385
  } catch {
9256
- created = void 0;
9257
9386
  }
9258
- try {
9259
- await evictionMarkerTestHooks?.beforeOwnerWrite?.(evictPath, evictOwnerPath);
9260
- const injected = await evictionMarkerTestHooks?.failOwnerWrite?.(evictPath, evictOwnerPath);
9261
- if (injected !== void 0)
9262
- throw injected;
9263
- const bytes = `${JSON.stringify({ ownerId: evictOwnerId, createdAt: now() })}
9264
- `;
9265
- if (windowsPrivateFiles)
9266
- await createPrivateBytes(evictOwnerPath, bytes);
9267
- else
9268
- await writeExclusiveText(evictOwnerPath, bytes);
9269
- } catch (error) {
9270
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
9271
- if (isLostMarkerRaceError(error) && !stillOurs)
9272
- return false;
9387
+ }
9388
+ function cancelRenewalTimer() {
9389
+ if (!renewTimer)
9390
+ return;
9391
+ clearRefreshLockRenewalTimeout(renewTimer);
9392
+ renewTimer = null;
9393
+ notifyTimerStep("cancelled");
9394
+ }
9395
+ function recordLoss(reason, owner) {
9396
+ if (loss || released)
9397
+ return;
9398
+ loss = Object.freeze({
9399
+ reason,
9400
+ expectedOwnerId: ownerId,
9401
+ ...typeof owner?.ownerId === "string" ? { observedOwnerId: owner.ownerId } : {},
9402
+ ...typeof owner?.expiresAt === "number" ? { observedExpiresAt: owner.expiresAt } : {}
9403
+ });
9404
+ cancelRenewalTimer();
9405
+ resolveLoss(loss);
9406
+ }
9407
+ let terminalIOError;
9408
+ let renewalInFlight = null;
9409
+ const evictPath = `${lockPath}.evicting`;
9410
+ const evictOwnerPath = join5(evictPath, "owner.json");
9411
+ const evictOwnerId = randomUUID7();
9412
+ const EVICT_TTL = 5e3;
9413
+ const MAX_STEAL_ATTEMPTS = 8;
9414
+ function isChangingLockCreate(error) {
9415
+ return windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [lockPath], "create") || isWindowsAccessDeniedCreate(error, [evictPath], "directory-create"));
9416
+ }
9417
+ async function readOwner() {
9418
+ if (windowsPrivateFiles) {
9273
9419
  try {
9274
- await releaseEvictionMarker(deadline);
9275
- } catch {
9420
+ return JSON.parse(await readLockRecord(lockPath, () => readPrivateText(lockPath, true)));
9421
+ } catch (error) {
9422
+ if (error.code !== "EISDIR" && error.reason !== "wrong-kind")
9423
+ throw error;
9424
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
9425
+ return JSON.parse(await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true)));
9276
9426
  }
9277
- throw error;
9278
9427
  }
9279
- if (options.onStep)
9280
- await options.onStep("eviction-marker-acquired");
9281
- return true;
9282
- }
9283
- async function recoverStaleEvictionMarker(deadline) {
9284
- let evictStat;
9285
9428
  try {
9286
- evictStat = await stat3(evictPath);
9429
+ return JSON.parse(await readFile5(lockPath, "utf8"));
9287
9430
  } catch (error) {
9288
- if (error.code === "ENOENT")
9289
- return "missing";
9290
- throw error;
9291
- }
9292
- if (windowsPrivateFiles) {
9293
- try {
9294
- await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
9295
- } catch (error) {
9296
- if (error.code === "ENOENT")
9297
- return "missing";
9431
+ const code2 = error.code;
9432
+ if (code2 !== "EISDIR")
9298
9433
  throw error;
9299
- }
9434
+ return JSON.parse(await readFile5(legacyOwnerPath, "utf8"));
9300
9435
  }
9301
- if (evictStat.mtimeMs + EVICT_TTL > now()) {
9302
- let hasOwner = true;
9303
- try {
9304
- await stat3(evictOwnerPath);
9305
- } catch (error) {
9306
- if (error.code === "ENOENT")
9307
- hasOwner = false;
9308
- else
9309
- return "fresh";
9310
- }
9311
- if (hasOwner)
9312
- return "fresh";
9313
- if (evictStat.mtimeMs + OWNERLESS_MARKER_GRACE_MS > now())
9314
- return "fresh";
9436
+ }
9437
+ async function writeOwner() {
9438
+ if (windowsPrivateFiles) {
9439
+ const owner = await readOwner();
9440
+ const remaining = Number(owner?.expiresAt) - now();
9441
+ await writePrivateAtomic(lockPath, `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
9442
+ `, {
9443
+ deadline: performance.now() + Math.max(0, remaining),
9444
+ beforeRename: async () => {
9445
+ const current = await readOwner();
9446
+ if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
9447
+ throw new LockOwnershipError({
9448
+ target: options.path,
9449
+ name: options.name
9450
+ });
9451
+ }
9452
+ }
9453
+ });
9454
+ return;
9315
9455
  }
9316
- if (options.onStep)
9317
- await options.onStep("stale-marker-stat");
9318
- const claimedPath = `${evictPath}.${randomUUID7()}`;
9456
+ const tempPath = `${lockPath}.${randomUUID7()}.tmp`;
9457
+ let handle;
9458
+ let created = false;
9319
9459
  try {
9320
- await rename6(evictPath, claimedPath);
9321
- } catch (error) {
9322
- if (error.code === "ENOENT")
9323
- return "missing";
9324
- throw error;
9325
- }
9326
- if (options.onStep)
9327
- await options.onStep("stale-marker-claimed");
9328
- const claimedIdentity = windowsPrivateFiles ? await lstat3(claimedPath) : void 0;
9329
- await removeOwnedLeaseObject(claimedPath, async () => {
9330
- if (!claimedIdentity)
9331
- return true;
9332
- const current = await lstat3(claimedPath).catch((error) => {
9333
- if (error.code !== "ENOENT")
9334
- throw error;
9335
- return void 0;
9460
+ handle = await open5(tempPath, "wx", 384);
9461
+ created = true;
9462
+ await handle.writeFile(`${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
9463
+ `, "utf8");
9464
+ await handle.chmod(384);
9465
+ await handle.close();
9466
+ handle = void 0;
9467
+ const current = await readOwner();
9468
+ if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
9469
+ throw new LockOwnershipError({
9470
+ target: options.path,
9471
+ name: options.name
9472
+ });
9473
+ }
9474
+ await rename6(tempPath, lockPath);
9475
+ created = false;
9476
+ } finally {
9477
+ await handle?.close().catch(() => {
9336
9478
  });
9337
- return !!current && sameMarkerDirectory(claimedIdentity, current);
9338
- }, deadline);
9339
- return "recovered";
9479
+ if (created)
9480
+ await rm4(tempPath, { force: true }).catch(() => {
9481
+ });
9482
+ }
9340
9483
  }
9341
- async function withEvictionMarker(action, deadline) {
9484
+ async function createLease() {
9485
+ const bytes = `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
9486
+ `;
9487
+ if (windowsPrivateFiles)
9488
+ await createPrivateBytes(lockPath, bytes);
9489
+ else
9490
+ await createExclusiveText(lockPath, bytes);
9491
+ }
9492
+ async function leaseContention(error) {
9493
+ const code2 = error.code;
9494
+ if (code2 !== "EEXIST" && code2 !== "EISDIR")
9495
+ return false;
9496
+ if (windowsPrivateFiles) {
9497
+ if (options.onStep)
9498
+ await options.onStep("lease-contention-read-ready");
9499
+ try {
9500
+ if (code2 === "EISDIR") {
9501
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
9502
+ await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true));
9503
+ } else
9504
+ await readOwner();
9505
+ } catch (readError) {
9506
+ if (readError.code !== "ENOENT")
9507
+ throw readError;
9508
+ }
9509
+ }
9510
+ return true;
9511
+ }
9512
+ async function tryAcquire() {
9513
+ if (windowsPrivateFiles)
9514
+ await ensurePrivateDirectory(dirname8(lockPath));
9342
9515
  try {
9343
- if (!await tryAcquireEvictionMarker(deadline))
9344
- return false;
9516
+ await createLease();
9517
+ return true;
9345
9518
  } catch (error) {
9346
- if (error.code === "EEXIST") {
9347
- if (windowsPrivateFiles) {
9348
- try {
9349
- await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
9350
- await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, true));
9351
- } catch (ownerError) {
9352
- if (ownerError.code !== "ENOENT")
9353
- throw ownerError;
9354
- }
9355
- }
9519
+ const code2 = error.code;
9520
+ if (await leaseContention(error))
9356
9521
  return false;
9522
+ if (code2 === "ENOENT") {
9523
+ if (windowsPrivateFiles)
9524
+ await ensurePrivateDirectory(dirname8(lockPath));
9525
+ else
9526
+ await mkdir7(dirname8(lockPath), { recursive: true });
9527
+ try {
9528
+ await createLease();
9529
+ return true;
9530
+ } catch (retryError) {
9531
+ if (await leaseContention(retryError))
9532
+ return false;
9533
+ throw retryError;
9534
+ }
9357
9535
  }
9358
9536
  throw error;
9359
9537
  }
9360
- let actionFailed = false;
9361
- let actionError;
9538
+ }
9539
+ async function backoff() {
9540
+ await new Promise((resolve24) => setTimeout(resolve24, Math.floor(Math.random() * 4)));
9541
+ }
9542
+ async function readLockState(notifyReady = true) {
9543
+ if (notifyReady && options.onStep)
9544
+ await options.onStep("lock-read-ready");
9545
+ let owner;
9362
9546
  try {
9363
- await action();
9547
+ owner = await readOwner();
9364
9548
  } catch (error) {
9365
- actionFailed = true;
9366
- actionError = error;
9549
+ if (error instanceof DisappearedLockRecordError)
9550
+ return { status: "missing" };
9551
+ if (windowsPrivateFiles && error.code !== "ENOENT")
9552
+ throw error;
9553
+ }
9554
+ const expiresAt = Number(owner?.expiresAt);
9555
+ if (Number.isFinite(expiresAt) && expiresAt > now())
9556
+ return { status: "live" };
9557
+ if (typeof owner?.ownerId === "string" && Number.isFinite(expiresAt)) {
9558
+ return {
9559
+ status: "stale",
9560
+ identity: { kind: "owner", ownerId: owner.ownerId, expiresAt }
9561
+ };
9367
9562
  }
9368
9563
  try {
9369
- await releaseEvictionMarker(deadline);
9564
+ const current = await stat3(lockPath);
9565
+ const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
9566
+ if (legacyExpiry > now())
9567
+ return { status: "live" };
9568
+ return {
9569
+ status: "stale",
9570
+ identity: {
9571
+ kind: "stat",
9572
+ dev: current.dev,
9573
+ ino: current.ino,
9574
+ mtimeMs: current.mtimeMs,
9575
+ expiresAt: legacyExpiry
9576
+ }
9577
+ };
9370
9578
  } catch (error) {
9371
- if ((isRetryableRemoval(actionError, lockPath) || isWindowsAccessDeniedRead(actionError, [
9372
- lockPath,
9373
- legacyOwnerPath,
9374
- evictOwnerPath
9375
- ])) && (isRetryableRemoval(error, evictPath) || isWindowsAccessDeniedRead(error, [evictOwnerPath])))
9376
- throw actionError;
9579
+ if (error.code === "ENOENT") {
9580
+ if (options.onStep)
9581
+ await options.onStep("lock-missing");
9582
+ return { status: "missing" };
9583
+ }
9377
9584
  throw error;
9378
9585
  }
9379
- if (actionFailed)
9380
- throw actionError;
9381
- return true;
9382
9586
  }
9383
- async function relinquishLockAfterMarkerLoss() {
9384
- for (let attempt = 0; attempt < MAX_STEAL_ATTEMPTS; attempt++) {
9385
- if (options.onStep)
9386
- await options.onStep("relinquish-read");
9387
- let owner;
9388
- try {
9389
- owner = await readOwner();
9390
- } catch (error) {
9391
- if (windowsPrivateFiles && !(error instanceof DisappearedLockRecordError))
9392
- throw error;
9393
- return;
9394
- }
9395
- if (owner?.ownerId !== ownerId)
9396
- return;
9587
+ function sameStaleLock(observed, current) {
9588
+ if (current.status !== "stale")
9589
+ return false;
9590
+ const identity3 = current.identity;
9591
+ if (observed.kind === "owner" && identity3.kind === "owner") {
9592
+ return observed.ownerId === identity3.ownerId && observed.expiresAt === identity3.expiresAt;
9593
+ }
9594
+ return observed.kind === "stat" && identity3.kind === "stat" && observed.dev === identity3.dev && observed.ino === identity3.ino && observed.mtimeMs === identity3.mtimeMs && observed.expiresAt === identity3.expiresAt;
9595
+ }
9596
+ async function ownsEvictionMarker() {
9597
+ try {
9598
+ const owner = JSON.parse(await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, windowsPrivateFiles)));
9599
+ return owner?.ownerId === evictOwnerId;
9600
+ } catch (error) {
9601
+ if (windowsPrivateFiles && error.code !== "ENOENT")
9602
+ throw error;
9603
+ return false;
9604
+ }
9605
+ }
9606
+ async function removeLeaseObject(path2) {
9607
+ if (windowsPrivateFiles)
9608
+ await privateOperation(path2, "remove", () => rm4(path2, { recursive: true, force: true }));
9609
+ else
9610
+ await rm4(path2, { recursive: true, force: true }).catch(() => {
9611
+ });
9612
+ }
9613
+ function isRetryableRemoval(error, path2) {
9614
+ if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.stage !== "remove" || error.path !== path2)
9615
+ return false;
9616
+ return isWindowsSharingViolation(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
9617
+ }
9618
+ async function removeOwnedLeaseObject(path2, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
9619
+ let original;
9620
+ let delayMs = 5;
9621
+ while (await stillOwned()) {
9397
9622
  try {
9398
- await rm4(lockPath, { recursive: true, force: true });
9623
+ await removeLeaseObject(path2);
9399
9624
  return;
9400
9625
  } catch (error) {
9401
- if (windowsPrivateFiles)
9626
+ if (!isRetryableRemoval(error, path2))
9402
9627
  throw error;
9403
- await backoff();
9628
+ original ??= error;
9404
9629
  }
9630
+ const remainingMs = deadline - performance.now();
9631
+ if (remainingMs <= 0)
9632
+ throw original;
9633
+ await new Promise((resolve24) => setTimeout(resolve24, Math.min(delayMs, remainingMs)));
9634
+ if (performance.now() >= deadline)
9635
+ throw original;
9636
+ delayMs = Math.min(delayMs * 2, 50);
9405
9637
  }
9406
9638
  }
9407
- function scheduleRenewal() {
9408
- if (!options.renew || released || loss)
9409
- return;
9410
- const intervalMs = options.renewIntervalMs ?? Math.max(1e3, Math.floor(options.ttlMs / 3));
9411
- renewTimer = setRefreshLockRenewalTimeout(() => {
9412
- renewTimer = null;
9413
- const renewal = (async () => {
9639
+ async function releaseEvictionMarker(deadline) {
9640
+ let ownedDirectory;
9641
+ await removeOwnedLeaseObject(evictPath, async () => {
9642
+ if (!windowsPrivateFiles)
9643
+ return ownsEvictionMarker();
9644
+ const current = await lstat3(evictPath).catch((error) => {
9645
+ if (error.code !== "ENOENT")
9646
+ throw error;
9647
+ return void 0;
9648
+ });
9649
+ if (!current || ownedDirectory && !sameMarkerDirectory(ownedDirectory, current))
9650
+ return false;
9651
+ if (await ownsEvictionMarker()) {
9652
+ ownedDirectory = current;
9653
+ return true;
9654
+ }
9655
+ if (!ownedDirectory)
9656
+ return false;
9657
+ try {
9658
+ await stat3(evictOwnerPath);
9659
+ return false;
9660
+ } catch (error) {
9661
+ if (error.code !== "ENOENT")
9662
+ throw error;
9663
+ return true;
9664
+ }
9665
+ }, deadline);
9666
+ }
9667
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
9668
+ if (!created)
9669
+ return false;
9670
+ let stillOurs = false;
9671
+ try {
9672
+ await removeOwnedLeaseObject(evictPath, async () => {
9673
+ stillOurs = false;
9674
+ const st = await lstat3(evictPath).catch(() => void 0);
9675
+ if (!st || !sameMarkerDirectory(created, st))
9676
+ return false;
9677
+ stillOurs = true;
9678
+ try {
9679
+ await stat3(evictOwnerPath);
9680
+ return false;
9681
+ } catch (error) {
9682
+ return error.code === "ENOENT";
9683
+ }
9684
+ }, deadline);
9685
+ } catch {
9686
+ }
9687
+ return stillOurs;
9688
+ }
9689
+ async function tryAcquireEvictionMarker(deadline) {
9690
+ if (windowsPrivateFiles)
9691
+ await createPrivateDirectoryExclusive(evictPath);
9692
+ else
9693
+ await mkdir7(evictPath);
9694
+ let created;
9695
+ try {
9696
+ const st = await lstat3(evictPath);
9697
+ created = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
9698
+ } catch {
9699
+ created = void 0;
9700
+ }
9701
+ try {
9702
+ await evictionMarkerTestHooks?.beforeOwnerWrite?.(evictPath, evictOwnerPath);
9703
+ const injected = await evictionMarkerTestHooks?.failOwnerWrite?.(evictPath, evictOwnerPath);
9704
+ if (injected !== void 0)
9705
+ throw injected;
9706
+ const bytes = `${JSON.stringify({ ownerId: evictOwnerId, createdAt: now() })}
9707
+ `;
9708
+ if (windowsPrivateFiles)
9709
+ await createPrivateBytes(evictOwnerPath, bytes);
9710
+ else
9711
+ await writeExclusiveText(evictOwnerPath, bytes);
9712
+ } catch (error) {
9713
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
9714
+ if (isLostMarkerRaceError(error) && !stillOurs)
9715
+ return false;
9716
+ try {
9717
+ await releaseEvictionMarker(deadline);
9718
+ } catch {
9719
+ }
9720
+ throw error;
9721
+ }
9722
+ if (options.onStep)
9723
+ await options.onStep("eviction-marker-acquired");
9724
+ return true;
9725
+ }
9726
+ async function recoverStaleEvictionMarker(deadline) {
9727
+ let evictStat;
9728
+ try {
9729
+ evictStat = await stat3(evictPath);
9730
+ } catch (error) {
9731
+ if (error.code === "ENOENT")
9732
+ return "missing";
9733
+ throw error;
9734
+ }
9735
+ if (windowsPrivateFiles) {
9736
+ try {
9737
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
9738
+ } catch (error) {
9739
+ if (error.code === "ENOENT")
9740
+ return "missing";
9741
+ throw error;
9742
+ }
9743
+ }
9744
+ if (evictStat.mtimeMs + EVICT_TTL > now()) {
9745
+ let hasOwner = true;
9746
+ try {
9747
+ await stat3(evictOwnerPath);
9748
+ } catch (error) {
9749
+ if (error.code === "ENOENT")
9750
+ hasOwner = false;
9751
+ else
9752
+ return "fresh";
9753
+ }
9754
+ if (hasOwner)
9755
+ return "fresh";
9756
+ if (evictStat.mtimeMs + OWNERLESS_MARKER_GRACE_MS > now())
9757
+ return "fresh";
9758
+ }
9759
+ if (options.onStep)
9760
+ await options.onStep("stale-marker-stat");
9761
+ const claimedPath = `${evictPath}.${randomUUID7()}`;
9762
+ try {
9763
+ await rename6(evictPath, claimedPath);
9764
+ } catch (error) {
9765
+ if (error.code === "ENOENT")
9766
+ return "missing";
9767
+ throw error;
9768
+ }
9769
+ if (options.onStep)
9770
+ await options.onStep("stale-marker-claimed");
9771
+ const claimedIdentity = windowsPrivateFiles ? await lstat3(claimedPath) : void 0;
9772
+ await removeOwnedLeaseObject(claimedPath, async () => {
9773
+ if (!claimedIdentity)
9774
+ return true;
9775
+ const current = await lstat3(claimedPath).catch((error) => {
9776
+ if (error.code !== "ENOENT")
9777
+ throw error;
9778
+ return void 0;
9779
+ });
9780
+ return !!current && sameMarkerDirectory(claimedIdentity, current);
9781
+ }, deadline);
9782
+ return "recovered";
9783
+ }
9784
+ async function withEvictionMarker(action, deadline) {
9785
+ try {
9786
+ if (!await tryAcquireEvictionMarker(deadline))
9787
+ return false;
9788
+ } catch (error) {
9789
+ if (error.code === "EEXIST") {
9790
+ if (windowsPrivateFiles) {
9791
+ try {
9792
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
9793
+ await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, true));
9794
+ } catch (ownerError) {
9795
+ if (ownerError.code !== "ENOENT")
9796
+ throw ownerError;
9797
+ }
9798
+ }
9799
+ return false;
9800
+ }
9801
+ throw error;
9802
+ }
9803
+ let actionFailed = false;
9804
+ let actionError;
9805
+ try {
9806
+ await action();
9807
+ } catch (error) {
9808
+ actionFailed = true;
9809
+ actionError = error;
9810
+ }
9811
+ try {
9812
+ await releaseEvictionMarker(deadline);
9813
+ } catch (error) {
9814
+ if ((isRetryableRemoval(actionError, lockPath) || isWindowsAccessDeniedRead(actionError, [
9815
+ lockPath,
9816
+ legacyOwnerPath,
9817
+ evictOwnerPath
9818
+ ])) && (isRetryableRemoval(error, evictPath) || isWindowsAccessDeniedRead(error, [evictOwnerPath])))
9819
+ throw actionError;
9820
+ throw error;
9821
+ }
9822
+ if (actionFailed)
9823
+ throw actionError;
9824
+ return true;
9825
+ }
9826
+ async function relinquishLockAfterMarkerLoss() {
9827
+ for (let attempt = 0; attempt < MAX_STEAL_ATTEMPTS; attempt++) {
9828
+ if (options.onStep)
9829
+ await options.onStep("relinquish-read");
9830
+ let owner;
9831
+ try {
9832
+ owner = await readOwner();
9833
+ } catch (error) {
9834
+ if (windowsPrivateFiles && !(error instanceof DisappearedLockRecordError))
9835
+ throw error;
9836
+ return;
9837
+ }
9838
+ if (owner?.ownerId !== ownerId)
9839
+ return;
9840
+ try {
9841
+ await rm4(lockPath, { recursive: true, force: true });
9842
+ return;
9843
+ } catch (error) {
9844
+ if (windowsPrivateFiles)
9845
+ throw error;
9846
+ await backoff();
9847
+ }
9848
+ }
9849
+ }
9850
+ function scheduleRenewal() {
9851
+ if (!options.renew || released || loss)
9852
+ return;
9853
+ const intervalMs = options.renewIntervalMs ?? Math.max(1e3, Math.floor(options.ttlMs / 3));
9854
+ renewTimer = setRefreshLockRenewalTimeout(() => {
9855
+ renewTimer = null;
9856
+ const renewal = (async () => {
9414
9857
  let shouldReschedule = !released;
9415
9858
  try {
9416
9859
  const markerAcquired = await withEvictionMarker(async () => {
@@ -9661,17 +10104,15 @@ async function acquireRefreshFileLockWithClock(options) {
9661
10104
  removalConfirmed = true;
9662
10105
  }, deadline);
9663
10106
  changingRecordError = void 0;
9664
- if (markerAcquired) {
9665
- if (windowsPrivateFiles && !removalConfirmed)
9666
- throw new PrivateFileError(lockPath, "release-not-confirmed", {
9667
- code: "EIO"
9668
- });
9669
- releaseConfirmed = removalConfirmed;
10107
+ if (markerAcquired && removalConfirmed) {
10108
+ releaseConfirmed = true;
9670
10109
  return;
9671
10110
  }
9672
- if (signal?.aborted)
9673
- return;
9674
- await recoverStaleEvictionMarker(deadline);
10111
+ if (!markerAcquired) {
10112
+ if (signal?.aborted)
10113
+ return;
10114
+ await recoverStaleEvictionMarker(deadline);
10115
+ }
9675
10116
  } catch (error) {
9676
10117
  const changingRecord = windowsPrivateFiles && (isChangingLockCreate(error) || isWindowsAccessDeniedRead(error, [
9677
10118
  lockPath,
@@ -9701,6 +10142,9 @@ async function acquireRefreshFileLockWithClock(options) {
9701
10142
  throw changingRecordError ?? removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
9702
10143
  code: "ETIMEDOUT"
9703
10144
  });
10145
+ createLogger2("fs").warn("File lock release deadline expired", {
10146
+ lockPath
10147
+ });
9704
10148
  }
9705
10149
  };
9706
10150
  }
@@ -9708,6 +10152,7 @@ var leaseCreationTestHooks, STAGING_UUID, STAGING_SWEEP_MIN_AGE_MS, STAGING_SWEE
9708
10152
  var init_refresh_file_lock = __esm({
9709
10153
  "../core/dist/common-auth-embedded/fs/refresh-file-lock.js"() {
9710
10154
  "use strict";
10155
+ init_logger2();
9711
10156
  init_lock_record();
9712
10157
  init_private_files();
9713
10158
  init_with_lock();
@@ -9724,12 +10169,12 @@ var init_refresh_file_lock = __esm({
9724
10169
  });
9725
10170
 
9726
10171
  // ../core/dist/common-auth-embedded/fs/with-lock.js
9727
- import { join as join6, resolve as resolve4 } from "node:path";
10172
+ import { join as join6, resolve as resolve5 } from "node:path";
9728
10173
  function lockPathFor(target, name) {
9729
10174
  return `${target}.${name}.lock`;
9730
10175
  }
9731
10176
  function isChangingLockRecord(error, target, name) {
9732
- const path2 = resolve4(lockPathFor(target, name));
10177
+ const path2 = resolve5(lockPathFor(target, name));
9733
10178
  const paths = [path2, join6(path2, "owner.json")];
9734
10179
  return (isWindowsSharingViolation(error) || isWindowsAccessDeniedRead(error, paths)) && (error.stage === "read" || error.stage === "verify") && paths.includes(error.path) || windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [path2], "create") || isWindowsAccessDeniedCreate(error, [`${path2}.evicting`], "directory-create"));
9735
10180
  }
@@ -12524,566 +12969,143 @@ async function publishRoster(rt, plan, options = {}) {
12524
12969
  return { outcome: "published", receipt: await cleanup(tx, receipt2) };
12525
12970
  }, { completeTorn: false });
12526
12971
  if (result)
12527
- return result;
12528
- await locks.releaseAll();
12529
- if (attempt >= 1)
12530
- throw refusal2("publishRoster", plan.operationId, "row-key-changed", "a named row changed lock key twice during publication", true);
12531
- }
12532
- });
12533
- }
12534
- var init_publication = __esm({
12535
- "../core/dist/common-auth-embedded/store/publication.js"() {
12536
- "use strict";
12537
- init_hooks();
12538
- init_mutate();
12539
- init_rows();
12540
- init_runtime();
12541
- init_schema();
12542
- }
12543
- });
12544
-
12545
- // ../core/dist/common-auth-embedded/store/pull.js
12546
- var PullScheduler;
12547
- var init_pull = __esm({
12548
- "../core/dist/common-auth-embedded/store/pull.js"() {
12549
- "use strict";
12550
- init_attribution();
12551
- init_errors();
12552
- init_mutate();
12553
- init_refresh_lock();
12554
- init_runtime();
12555
- PullScheduler = class {
12556
- rt;
12557
- hook;
12558
- onFailure;
12559
- firedAtLoad;
12560
- logger;
12561
- inflight = /* @__PURE__ */ new Set();
12562
- constructor(rt, hook, onFailure, firedAtLoad, logger2) {
12563
- this.rt = rt;
12564
- this.hook = hook;
12565
- this.onFailure = onFailure;
12566
- this.firedAtLoad = firedAtLoad;
12567
- this.logger = logger2;
12568
- }
12569
- fire(id, reason) {
12570
- if (!this.hook)
12571
- return;
12572
- if (reason === "load") {
12573
- if (this.firedAtLoad.has(id))
12574
- return;
12575
- this.firedAtLoad.add(id);
12576
- }
12577
- const run = this.run(id, reason);
12578
- this.inflight.add(run);
12579
- void run.finally(() => this.inflight.delete(run));
12580
- }
12581
- /** Resolves once every pull fired so far has settled. */
12582
- async settled() {
12583
- while (this.inflight.size > 0)
12584
- await Promise.allSettled([...this.inflight]);
12585
- }
12586
- async run(id, reason) {
12587
- const rt = this.rt();
12588
- const { ctx } = rt;
12589
- const locks = new LockStack(ctx.lockDefaults, ctx.lockEnv);
12590
- const progress = { writes: 0 };
12591
- try {
12592
- const request2 = await withTransaction(ctx, locks, progress, { operation: "pull", rowId: id }, async (tx) => {
12593
- if (tx.reservation(id) !== void 0)
12594
- return void 0;
12595
- await tx.completeTorn();
12596
- const row = tx.row(id);
12597
- if (row?.unbound && row.enabled && row.type === "oauth" && row.credential && !row.invalid)
12598
- requireBound("pull", row);
12599
- if (!row?.candidate || row.type !== "oauth")
12600
- return void 0;
12601
- if (!row.hasEntry) {
12602
- tx.setEntry(id, { credentialEpoch: 1, needsFirstReading: true });
12603
- await tx.commitConfig();
12604
- }
12605
- const current = tx.row(id);
12606
- if (!current?.credential || current.credentialEpoch === void 0)
12607
- return void 0;
12608
- return {
12609
- id,
12610
- credential: current.credential,
12611
- credentialEpoch: current.credentialEpoch,
12612
- ...current.identity !== void 0 ? { identity: current.identity } : {},
12613
- reason
12614
- };
12615
- }, { completeTorn: false });
12616
- await locks.releaseAll();
12617
- if (!request2) {
12618
- this.firedAtLoad.delete(id);
12619
- return;
12620
- }
12621
- await ctx.hold?.("pull-before-request", id);
12622
- let observation;
12623
- try {
12624
- observation = await this.hook?.(request2);
12625
- } catch (cause) {
12626
- throw new PoolOperationError({
12627
- operation: "pull",
12628
- rowId: id,
12629
- phase: "pull",
12630
- retryable: true,
12631
- kind: "pull",
12632
- message: "the quota pull rejected",
12633
- cause
12634
- });
12635
- }
12636
- const publish = rt.publishQuota ?? ((rowId2, attribution, value) => recordQuota(rt, rowId2, attribution, value));
12637
- await publish(id, {
12638
- credentialEpoch: request2.credentialEpoch,
12639
- ...request2.identity !== void 0 ? { identity: request2.identity } : {}
12640
- }, observation);
12641
- } catch (error) {
12642
- this.firedAtLoad.delete(id);
12643
- const failure = toFailure(error, "pull", id, progress);
12644
- if (this.onFailure) {
12645
- try {
12646
- await this.onFailure(id, failure);
12647
- } catch (hookError) {
12648
- this.logger?.warn("pull failure hook threw", {
12649
- rowId: id,
12650
- error: hookError instanceof Error ? hookError.message : String(hookError)
12651
- });
12652
- }
12653
- } else {
12654
- this.logger?.warn("quota pull failed", {
12655
- rowId: id,
12656
- kind: failure.kind
12657
- });
12658
- }
12659
- } finally {
12660
- await locks.releaseAll();
12661
- }
12662
- }
12663
- };
12664
- }
12665
- });
12666
-
12667
- // ../core/dist/common-auth-embedded/logger/capture-sink.js
12668
- function createCaptureSink() {
12669
- const records = [];
12670
- const sink = (record3) => {
12671
- records.push(record3);
12672
- };
12673
- return {
12674
- records,
12675
- sink,
12676
- clear: () => {
12677
- records.length = 0;
12678
- }
12679
- };
12680
- }
12681
- var init_capture_sink = __esm({
12682
- "../core/dist/common-auth-embedded/logger/capture-sink.js"() {
12683
- "use strict";
12684
- }
12685
- });
12686
-
12687
- // ../core/dist/common-auth-embedded/logger/redact.js
12688
- function isError(value) {
12689
- return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
12690
- }
12691
- function createRedactor(options = {}) {
12692
- const patterns = [TOKEN_VALUE, ...options.extraValuePatterns ?? []].map((pattern) => new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
12693
- function isSecretKey(key) {
12694
- const normalized = key.toLowerCase().replace(/[-_]/g, "");
12695
- return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
12696
- }
12697
- function errorEntries(error) {
12698
- const fields2 = error;
12699
- const entries = [
12700
- ["name", error.name],
12701
- ["message", error.message],
12702
- ["stack", error.stack]
12703
- ];
12704
- for (const key of ["code", "status", "cause"])
12705
- if (fields2[key] !== void 0)
12706
- entries.push([key, fields2[key]]);
12707
- const listed = new Set(entries.map(([key]) => key));
12708
- for (const entry of Object.entries(error))
12709
- if (!listed.has(entry[0]))
12710
- entries.push(entry);
12711
- return entries;
12712
- }
12713
- function walk(value, keys, seen, errorDepth = 0) {
12714
- if (typeof value === "string") {
12715
- return patterns.reduce((text2, pattern) => text2.replace(pattern, MASK), value);
12716
- }
12717
- if (!value || typeof value !== "object")
12718
- return value;
12719
- if (seen.has(value))
12720
- return "[Circular]";
12721
- seen.add(value);
12722
- try {
12723
- if (Array.isArray(value))
12724
- return value.map((item) => walk(item, keys, seen, errorDepth));
12725
- const error = isError(value);
12726
- if (error && errorDepth >= MAX_ERROR_DEPTH)
12727
- return "[Truncated]";
12728
- const childDepth = error ? errorDepth + 1 : errorDepth;
12729
- return Object.fromEntries((error ? errorEntries(value) : Object.entries(value)).map(([key, item]) => [
12730
- key,
12731
- keys && isSecretKey(key) ? MASK : walk(item, keys, seen, childDepth)
12732
- ]));
12733
- } finally {
12734
- seen.delete(value);
12735
- }
12736
- }
12737
- return {
12738
- redact: (value) => walk(value, true, /* @__PURE__ */ new WeakSet()),
12739
- // Schema keys describe arguments, not credentials; only their string values are scrubbed.
12740
- redactStrings: (value) => walk(value, false, /* @__PURE__ */ new WeakSet())
12741
- };
12742
- }
12743
- var SECRET_KEY_EXACT, TOKEN_VALUE, MASK, MAX_ERROR_DEPTH, defaultRedactor, redact, redactStrings;
12744
- var init_redact = __esm({
12745
- "../core/dist/common-auth-embedded/logger/redact.js"() {
12746
- "use strict";
12747
- SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
12748
- TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
12749
- MASK = "***REDACTED***";
12750
- MAX_ERROR_DEPTH = 8;
12751
- defaultRedactor = createRedactor();
12752
- redact = defaultRedactor.redact;
12753
- redactStrings = defaultRedactor.redactStrings;
12754
- }
12755
- });
12756
-
12757
- // ../core/dist/common-auth-embedded/logger/engine.js
12758
- import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
12759
- import { open as open5 } from "node:fs/promises";
12760
- import { dirname as dirname8, resolve as resolve5 } from "node:path";
12761
- function chmodPrivate(path2) {
12762
- try {
12763
- chmodSync(path2, 384);
12764
- } catch {
12765
- }
12766
- }
12767
- function rotateIfNeeded(f) {
12768
- try {
12769
- if (!(existsSync(f) && statSync(f).size >= MAX_BYTES))
12770
- return;
12771
- for (let i = ROTATE_KEEP - 1; i >= 1; i--) {
12772
- if (existsSync(`${f}.${i}`)) {
12773
- const rotated2 = `${f}.${i + 1}`;
12774
- renameSync(`${f}.${i}`, rotated2);
12775
- chmodPrivate(rotated2);
12776
- }
12777
- }
12778
- const rotated = `${f}.1`;
12779
- renameSync(f, rotated);
12780
- chmodPrivate(rotated);
12781
- } catch {
12782
- }
12783
- }
12784
- async function closeWindowsFile(sink) {
12785
- const { file, handle } = sink;
12786
- sink.file = void 0;
12787
- sink.handle = void 0;
12788
- if (file && handle)
12789
- await privateOperation(file, "log-close", () => handle.close());
12790
- }
12791
- async function openWindowsFile(sink, file) {
12792
- await ensurePrivateDirectory(dirname8(file));
12793
- try {
12794
- await verifyPrivate(file, "file", true);
12795
- } catch (error) {
12796
- if (error.code !== "ENOENT")
12797
- throw error;
12798
- try {
12799
- await createPrivateBytes(file, "");
12800
- } catch (creationError) {
12801
- if (creationError.code !== "EEXIST")
12802
- throw creationError;
12803
- await verifyPrivate(file, "file", true);
12804
- }
12805
- }
12806
- sink.handle = await privateOperation(file, "log-open", () => open5(file, "a"));
12807
- sink.file = file;
12808
- return sink.handle;
12809
- }
12810
- async function flushWindowsFile(sink, file, text2) {
12811
- file = resolve5(file);
12812
- try {
12813
- if (sink.file !== file)
12814
- await closeWindowsFile(sink);
12815
- let handle = sink.handle ?? await openWindowsFile(sink, file);
12816
- const info = await privateOperation(file, "log-stat", () => handle.stat());
12817
- if (info.size >= MAX_BYTES) {
12818
- await closeWindowsFile(sink);
12819
- for (let i = ROTATE_KEEP - 1; i >= 0; i--) {
12820
- const source = i === 0 ? file : `${file}.${i}`;
12821
- const target = `${file}.${i + 1}`;
12822
- try {
12823
- await verifyPrivate(source, "file", true);
12824
- } catch (error) {
12825
- if (error.code === "ENOENT")
12826
- continue;
12827
- throw error;
12828
- }
12829
- try {
12830
- await verifyPrivate(target, "file", true);
12831
- } catch (error) {
12832
- if (error.code !== "ENOENT")
12833
- throw error;
12834
- }
12835
- await replaceWindowsFile(source, target);
12836
- await verifyPrivate(target, "file");
12837
- }
12838
- handle = await openWindowsFile(sink, file);
12839
- }
12840
- await privateOperation(file, "log-append", () => handle.appendFile(text2, "utf8"));
12841
- } catch (error) {
12842
- await closeWindowsFile(sink).catch(() => {
12843
- });
12844
- throw error;
12845
- }
12846
- }
12847
- function safeSerialize(data) {
12848
- try {
12849
- return ` ${JSON.stringify(data)}`;
12850
- } catch {
12851
- return " [unserializable]";
12852
- }
12853
- }
12854
- function createEngine(options) {
12855
- let logFileSource;
12856
- let initLevelSource;
12857
- let runtimeLevel;
12858
- let redactor = createRedactor();
12859
- let captureSink;
12860
- let buffer = [];
12861
- let timer;
12862
- let orderedSink = Promise.resolve();
12863
- let sinkError;
12864
- const windowsFile = {};
12865
- function queueWindows(operation) {
12866
- const next = orderedSink.then(operation);
12867
- orderedSink = next.catch((error) => {
12868
- sinkError = error;
12869
- });
12870
- return next;
12871
- }
12872
- function configure(next) {
12873
- if (windowsPrivateFiles && next.file !== logFileSource)
12874
- void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
12875
- });
12876
- logFileSource = next.file;
12877
- initLevelSource = next.level;
12878
- redactor = createRedactor(next);
12879
- captureSink = next.captureSink;
12880
- }
12881
- function setLogLevel3(l) {
12882
- if (l === void 0 || l in ORDER)
12883
- runtimeLevel = l;
12884
- }
12885
- function logFilePath() {
12886
- if (logFileSource === void 0)
12887
- return void 0;
12888
- const resolved = typeof logFileSource === "function" ? logFileSource() : logFileSource;
12889
- return resolved || void 0;
12890
- }
12891
- function configuredLevel() {
12892
- if (runtimeLevel)
12893
- return runtimeLevel;
12894
- const floor = typeof initLevelSource === "function" ? initLevelSource() : initLevelSource;
12895
- if (floor && floor in ORDER)
12896
- return floor;
12897
- return "info";
12898
- }
12899
- function flushLogs3(close = true) {
12900
- if (timer) {
12901
- clearTimeout(timer);
12902
- timer = void 0;
12903
- }
12904
- if (!buffer.length) {
12905
- if (windowsPrivateFiles)
12906
- return queueWindows(async () => {
12907
- if (close)
12908
- await closeWindowsFile(windowsFile);
12909
- if (sinkError)
12910
- throw sinkError;
12911
- });
12912
- return;
12913
- }
12914
- let file;
12915
- try {
12916
- file = logFilePath();
12917
- } catch {
12918
- buffer = [];
12919
- if (windowsPrivateFiles && close)
12920
- return queueWindows(() => closeWindowsFile(windowsFile));
12921
- return;
12922
- }
12923
- const text2 = buffer.join("");
12924
- buffer = [];
12925
- if (!file) {
12926
- if (windowsPrivateFiles && close)
12927
- return queueWindows(() => closeWindowsFile(windowsFile));
12928
- return;
12929
- }
12930
- if (windowsPrivateFiles) {
12931
- return queueWindows(async () => {
12932
- try {
12933
- await flushWindowsFile(windowsFile, file, text2);
12934
- } finally {
12935
- if (close)
12936
- await closeWindowsFile(windowsFile);
12937
- }
12938
- });
12939
- }
12940
- try {
12941
- rotateIfNeeded(file);
12942
- if (existsSync(file))
12943
- chmodPrivate(file);
12944
- appendFileSync(file, text2, { encoding: "utf8", mode: 384 });
12945
- } catch {
12946
- }
12947
- }
12948
- function schedule2() {
12949
- if (!timer)
12950
- timer = setTimeout(() => {
12951
- timer = void 0;
12952
- const flushed = flushLogs3(false);
12953
- if (flushed instanceof Promise)
12954
- void flushed.catch(() => {
12955
- });
12956
- }, 500);
12957
- }
12958
- function emit(channel3, level, message, data) {
12959
- if (logFileSource === void 0 && captureSink === void 0)
12960
- return;
12961
- try {
12962
- if (ORDER[level] > ORDER[configuredLevel()])
12963
- return;
12964
- const scrubbedMessage = redactor.redactStrings(message);
12965
- let scrubbedData;
12966
- try {
12967
- scrubbedData = redactor.redact(data);
12968
- } catch {
12969
- scrubbedData = "[unserializable]";
12970
- }
12971
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${level.toUpperCase()} [${channel3}] ${scrubbedMessage}` + (data === void 0 ? "" : safeSerialize(scrubbedData)) + "\n";
12972
- try {
12973
- captureSink?.({
12974
- channel: channel3,
12975
- level,
12976
- message: scrubbedMessage,
12977
- data: scrubbedData
12978
- });
12979
- } catch {
12980
- }
12981
- if (logFileSource === void 0)
12982
- return;
12983
- buffer.push(line);
12984
- if (buffer.length >= 50) {
12985
- const flushed = flushLogs3(false);
12986
- if (flushed instanceof Promise)
12987
- void flushed.catch(() => {
12988
- });
12989
- } else
12990
- schedule2();
12991
- } catch {
12992
- }
12993
- }
12994
- function createLogger5(channel3) {
12995
- return {
12996
- error: (m, d) => emit(channel3, "error", m, d),
12997
- warn: (m, d) => emit(channel3, "warn", m, d),
12998
- info: (m, d) => emit(channel3, "info", m, d),
12999
- debug: (m, d) => emit(channel3, "debug", m, d),
13000
- trace: (m, d) => emit(channel3, "trace", m, d)
13001
- };
13002
- }
13003
- function reset() {
13004
- if (windowsPrivateFiles)
13005
- void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
13006
- });
13007
- sinkError = void 0;
13008
- buffer = [];
13009
- if (timer) {
13010
- clearTimeout(timer);
13011
- timer = void 0;
12972
+ return result;
12973
+ await locks.releaseAll();
12974
+ if (attempt >= 1)
12975
+ throw refusal2("publishRoster", plan.operationId, "row-key-changed", "a named row changed lock key twice during publication", true);
13012
12976
  }
13013
- logFileSource = void 0;
13014
- initLevelSource = void 0;
13015
- runtimeLevel = void 0;
13016
- redactor = createRedactor();
13017
- captureSink = void 0;
13018
- }
13019
- if (options)
13020
- configure(options);
13021
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3, reset };
13022
- }
13023
- function createLoggerInstance(options) {
13024
- const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine(options);
13025
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
13026
- }
13027
- function initLogger(options) {
13028
- defaultEngine.configure(options);
13029
- const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = defaultEngine;
13030
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
13031
- }
13032
- function setLogLevel(l) {
13033
- defaultEngine.setLogLevel(l);
13034
- }
13035
- function flushLogs() {
13036
- return defaultEngine.flushLogs();
13037
- }
13038
- function createLogger2(channel3) {
13039
- return defaultEngine.createLogger(channel3);
13040
- }
13041
- async function flushForTest() {
13042
- return defaultEngine.flushLogs();
13043
- }
13044
- function resetLoggerForTest() {
13045
- defaultEngine.reset();
12977
+ });
13046
12978
  }
13047
- var ORDER, MAX_BYTES, ROTATE_KEEP, defaultEngine;
13048
- var init_engine = __esm({
13049
- "../core/dist/common-auth-embedded/logger/engine.js"() {
12979
+ var init_publication = __esm({
12980
+ "../core/dist/common-auth-embedded/store/publication.js"() {
13050
12981
  "use strict";
13051
- init_private_files();
13052
- init_redact();
13053
- ORDER = {
13054
- error: 0,
13055
- warn: 1,
13056
- info: 2,
13057
- debug: 3,
13058
- trace: 4
13059
- };
13060
- MAX_BYTES = 5 * 1024 * 1024;
13061
- ROTATE_KEEP = 3;
13062
- defaultEngine = createEngine();
12982
+ init_hooks();
12983
+ init_mutate();
12984
+ init_rows();
12985
+ init_runtime();
12986
+ init_schema();
13063
12987
  }
13064
12988
  });
13065
12989
 
13066
- // ../core/dist/common-auth-embedded/logger/index.js
13067
- var logger_exports = {};
13068
- __export(logger_exports, {
13069
- createCaptureSink: () => createCaptureSink,
13070
- createLogger: () => createLogger2,
13071
- createLoggerInstance: () => createLoggerInstance,
13072
- createRedactor: () => createRedactor,
13073
- flushForTest: () => flushForTest,
13074
- flushLogs: () => flushLogs,
13075
- initLogger: () => initLogger,
13076
- redact: () => redact,
13077
- redactStrings: () => redactStrings,
13078
- resetLoggerForTest: () => resetLoggerForTest,
13079
- setLogLevel: () => setLogLevel
13080
- });
13081
- var init_logger2 = __esm({
13082
- "../core/dist/common-auth-embedded/logger/index.js"() {
12990
+ // ../core/dist/common-auth-embedded/store/pull.js
12991
+ var PullScheduler;
12992
+ var init_pull = __esm({
12993
+ "../core/dist/common-auth-embedded/store/pull.js"() {
13083
12994
  "use strict";
13084
- init_capture_sink();
13085
- init_engine();
13086
- init_redact();
12995
+ init_attribution();
12996
+ init_errors();
12997
+ init_mutate();
12998
+ init_refresh_lock();
12999
+ init_runtime();
13000
+ PullScheduler = class {
13001
+ rt;
13002
+ hook;
13003
+ onFailure;
13004
+ firedAtLoad;
13005
+ logger;
13006
+ inflight = /* @__PURE__ */ new Set();
13007
+ constructor(rt, hook, onFailure, firedAtLoad, logger2) {
13008
+ this.rt = rt;
13009
+ this.hook = hook;
13010
+ this.onFailure = onFailure;
13011
+ this.firedAtLoad = firedAtLoad;
13012
+ this.logger = logger2;
13013
+ }
13014
+ fire(id, reason) {
13015
+ if (!this.hook)
13016
+ return;
13017
+ if (reason === "load") {
13018
+ if (this.firedAtLoad.has(id))
13019
+ return;
13020
+ this.firedAtLoad.add(id);
13021
+ }
13022
+ const run = this.run(id, reason);
13023
+ this.inflight.add(run);
13024
+ void run.finally(() => this.inflight.delete(run));
13025
+ }
13026
+ /** Resolves once every pull fired so far has settled. */
13027
+ async settled() {
13028
+ while (this.inflight.size > 0)
13029
+ await Promise.allSettled([...this.inflight]);
13030
+ }
13031
+ async run(id, reason) {
13032
+ const rt = this.rt();
13033
+ const { ctx } = rt;
13034
+ const locks = new LockStack(ctx.lockDefaults, ctx.lockEnv);
13035
+ const progress = { writes: 0 };
13036
+ try {
13037
+ const request2 = await withTransaction(ctx, locks, progress, { operation: "pull", rowId: id }, async (tx) => {
13038
+ if (tx.reservation(id) !== void 0)
13039
+ return void 0;
13040
+ await tx.completeTorn();
13041
+ const row = tx.row(id);
13042
+ if (row?.unbound && row.enabled && row.type === "oauth" && row.credential && !row.invalid)
13043
+ requireBound("pull", row);
13044
+ if (!row?.candidate || row.type !== "oauth")
13045
+ return void 0;
13046
+ if (!row.hasEntry) {
13047
+ tx.setEntry(id, { credentialEpoch: 1, needsFirstReading: true });
13048
+ await tx.commitConfig();
13049
+ }
13050
+ const current = tx.row(id);
13051
+ if (!current?.credential || current.credentialEpoch === void 0)
13052
+ return void 0;
13053
+ return {
13054
+ id,
13055
+ credential: current.credential,
13056
+ credentialEpoch: current.credentialEpoch,
13057
+ ...current.identity !== void 0 ? { identity: current.identity } : {},
13058
+ reason
13059
+ };
13060
+ }, { completeTorn: false });
13061
+ await locks.releaseAll();
13062
+ if (!request2) {
13063
+ this.firedAtLoad.delete(id);
13064
+ return;
13065
+ }
13066
+ await ctx.hold?.("pull-before-request", id);
13067
+ let observation;
13068
+ try {
13069
+ observation = await this.hook?.(request2);
13070
+ } catch (cause) {
13071
+ throw new PoolOperationError({
13072
+ operation: "pull",
13073
+ rowId: id,
13074
+ phase: "pull",
13075
+ retryable: true,
13076
+ kind: "pull",
13077
+ message: "the quota pull rejected",
13078
+ cause
13079
+ });
13080
+ }
13081
+ const publish = rt.publishQuota ?? ((rowId2, attribution, value) => recordQuota(rt, rowId2, attribution, value));
13082
+ await publish(id, {
13083
+ credentialEpoch: request2.credentialEpoch,
13084
+ ...request2.identity !== void 0 ? { identity: request2.identity } : {}
13085
+ }, observation);
13086
+ } catch (error) {
13087
+ this.firedAtLoad.delete(id);
13088
+ const failure = toFailure(error, "pull", id, progress);
13089
+ if (this.onFailure) {
13090
+ try {
13091
+ await this.onFailure(id, failure);
13092
+ } catch (hookError) {
13093
+ this.logger?.warn("pull failure hook threw", {
13094
+ rowId: id,
13095
+ error: hookError instanceof Error ? hookError.message : String(hookError)
13096
+ });
13097
+ }
13098
+ } else {
13099
+ this.logger?.warn("quota pull failed", {
13100
+ rowId: id,
13101
+ kind: failure.kind
13102
+ });
13103
+ }
13104
+ } finally {
13105
+ await locks.releaseAll();
13106
+ }
13107
+ }
13108
+ };
13087
13109
  }
13088
13110
  });
13089
13111
 
@@ -18614,7 +18636,7 @@ function grantReachOf(listed) {
18614
18636
  tuples: Object.freeze(grantTuples.map(({ selectorKind, selector, operation }) => Object.freeze({ selectorKind, selector, operation })))
18615
18637
  });
18616
18638
  }
18617
- var defaultLogger, phaseDiagnostics, SERVING_MARGIN_MS, KEPT_RECEIPT_MARGIN_MS, ClaustrumScopedCustody;
18639
+ var defaultLogger, phaseDiagnostics, SERVING_MARGIN_MS, KEPT_RECEIPT_MARGIN_MS, VAULT_RECEIPT_WAIT_MS, VAULT_YOUNG_OUTAGE_MS, ClaustrumScopedCustody;
18618
18640
  var init_custody = __esm({
18619
18641
  "../core/dist/common-auth-embedded/claustrum/custody.js"() {
18620
18642
  "use strict";
@@ -18631,6 +18653,8 @@ var init_custody = __esm({
18631
18653
  phaseDiagnostics = channel("common-auth.claustrum.phases");
18632
18654
  SERVING_MARGIN_MS = 3e5;
18633
18655
  KEPT_RECEIPT_MARGIN_MS = 6e4;
18656
+ VAULT_RECEIPT_WAIT_MS = 1e4;
18657
+ VAULT_YOUNG_OUTAGE_MS = 6e4;
18634
18658
  ClaustrumScopedCustody = class {
18635
18659
  #client;
18636
18660
  #readToken;
@@ -18648,7 +18672,10 @@ var init_custody = __esm({
18648
18672
  #setTimeout;
18649
18673
  #clearTimeout;
18650
18674
  #outage = false;
18675
+ #outageSince = 0;
18676
+ #outageWaitSpent = false;
18651
18677
  #outageError = new ClaustrumUnreachableError();
18678
+ #receiptWaits = /* @__PURE__ */ new Map();
18652
18679
  #probeTimer;
18653
18680
  #probing = false;
18654
18681
  #lastProbeAt = -Infinity;
@@ -18724,6 +18751,8 @@ var init_custody = __esm({
18724
18751
  if (this.#closed || this.#outage)
18725
18752
  return;
18726
18753
  this.#outage = true;
18754
+ this.#outageSince = this.#now();
18755
+ this.#outageWaitSpent = false;
18727
18756
  this.#outageError = error instanceof ClaustrumCredentialError5 ? error : new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError ? error.reason : void 0);
18728
18757
  this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
18729
18758
  this.#scheduleProbe();
@@ -18998,9 +19027,10 @@ var init_custody = __esm({
18998
19027
  /** Ask the vault while reachable; retain one validated receipt in memory only. */
18999
19028
  async authorize(identity3, signal, routeId = "vault") {
19000
19029
  this.#check(signal);
19030
+ const startedAt = this.#now();
19001
19031
  const { credentialId, credentialType, accountIdentity } = identity3;
19002
19032
  let kept = this.#kept.get(credentialId);
19003
- if (kept && (kept.attempt.credentialType !== credentialType || kept.attempt.expectedAccountIdentity !== accountIdentity)) {
19033
+ if (kept && (kept.attempt.credentialType !== credentialType || kept.attempt.expectedAccountIdentity !== accountIdentity || !this.#usable(kept.attempt))) {
19004
19034
  this.forget(credentialId);
19005
19035
  kept = void 0;
19006
19036
  }
@@ -19017,7 +19047,18 @@ var init_custody = __esm({
19017
19047
  return this.#serveKept(credentialId, kept, token, routeId);
19018
19048
  }
19019
19049
  try {
19020
- const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
19050
+ let attempt;
19051
+ try {
19052
+ const recovering = this.#outage && this.#receiptWaits.has(this.#receiptWaitKey({ credentialId, credentialType, accountIdentity }, token));
19053
+ if (recovering)
19054
+ throw this.#outageError;
19055
+ attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
19056
+ } catch (error) {
19057
+ this.#check(signal);
19058
+ if (classifyVaultFailure(error) !== "unreachable" || kept)
19059
+ throw error;
19060
+ attempt = await this.#waitForReceipt({ credentialId, credentialType, accountIdentity }, token, startedAt, error, signal);
19061
+ }
19021
19062
  this.#kept.set(credentialId, { attempt, routeId, since: null });
19022
19063
  this.#usageServed.set(credentialId, { ...identity3 });
19023
19064
  return attempt;
@@ -19030,6 +19071,109 @@ var init_custody = __esm({
19030
19071
  return this.#serveKept(credentialId, kept, token, routeId, error);
19031
19072
  }
19032
19073
  }
19074
+ #receiptWaitKey(identity3, token) {
19075
+ return JSON.stringify([
19076
+ identity3.credentialId,
19077
+ identity3.credentialType,
19078
+ identity3.accountIdentity,
19079
+ token
19080
+ ]);
19081
+ }
19082
+ async #waitForReceipt(identity3, token, startedAt, error, signal) {
19083
+ const remaining = VAULT_RECEIPT_WAIT_MS - (this.#now() - startedAt);
19084
+ if (remaining <= 0 || this.#outageWaitSpent || this.#now() - this.#outageSince >= VAULT_YOUNG_OUTAGE_MS)
19085
+ throw error;
19086
+ const key = this.#receiptWaitKey(identity3, token);
19087
+ let wait2 = this.#receiptWaits.get(key);
19088
+ if (!wait2) {
19089
+ const controller = new AbortController();
19090
+ const created = {
19091
+ controller,
19092
+ users: 0,
19093
+ error,
19094
+ pending: Promise.resolve().then(async () => {
19095
+ let delay3 = 250;
19096
+ for (; ; ) {
19097
+ await this.#receiptBackoff(delay3, controller.signal);
19098
+ try {
19099
+ return await this.#authorizeFresh(identity3, token, controller.signal);
19100
+ } catch (failure) {
19101
+ this.#check(controller.signal);
19102
+ if (classifyVaultFailure(failure) !== "unreachable")
19103
+ throw failure;
19104
+ created.error = failure;
19105
+ delay3 = Math.min(delay3 * 2, 1e3);
19106
+ }
19107
+ }
19108
+ })
19109
+ };
19110
+ wait2 = created;
19111
+ this.#receiptWaits.set(key, wait2);
19112
+ const remove2 = () => {
19113
+ if (this.#receiptWaits.get(key) === created)
19114
+ this.#receiptWaits.delete(key);
19115
+ };
19116
+ void wait2.pending.then(remove2, remove2);
19117
+ }
19118
+ const shared3 = wait2;
19119
+ shared3.users++;
19120
+ let timer;
19121
+ let abort;
19122
+ try {
19123
+ const attempt = await Promise.race([
19124
+ shared3.pending,
19125
+ new Promise((_resolve, reject) => {
19126
+ timer = this.#setTimeout(() => {
19127
+ if (this.#outage)
19128
+ this.#outageWaitSpent = true;
19129
+ reject(shared3.error);
19130
+ }, remaining);
19131
+ timer.unref?.();
19132
+ if (signal) {
19133
+ abort = () => reject(signal.reason);
19134
+ signal.addEventListener("abort", abort, { once: true });
19135
+ if (signal.aborted)
19136
+ abort();
19137
+ }
19138
+ })
19139
+ ]);
19140
+ this.#check(signal);
19141
+ const receipt2 = Object.freeze(Object.defineProperty({ ...attempt }, "accessToken", {
19142
+ value: attempt.accessToken,
19143
+ enumerable: false
19144
+ }));
19145
+ this.#provenance.set(receipt2, { token });
19146
+ return receipt2;
19147
+ } finally {
19148
+ if (timer)
19149
+ this.#clearTimeout(timer);
19150
+ if (abort)
19151
+ signal?.removeEventListener("abort", abort);
19152
+ if (--shared3.users === 0) {
19153
+ shared3.controller.abort();
19154
+ if (this.#receiptWaits.get(key) === shared3)
19155
+ this.#receiptWaits.delete(key);
19156
+ }
19157
+ }
19158
+ }
19159
+ #receiptBackoff(delay3, signal) {
19160
+ this.#check(signal);
19161
+ return new Promise((resolve24, reject) => {
19162
+ const abort = () => {
19163
+ this.#clearTimeout(timer);
19164
+ signal.removeEventListener("abort", abort);
19165
+ reject(signal.reason);
19166
+ };
19167
+ const timer = this.#setTimeout(() => {
19168
+ signal.removeEventListener("abort", abort);
19169
+ resolve24();
19170
+ }, delay3);
19171
+ timer.unref?.();
19172
+ signal.addEventListener("abort", abort, { once: true });
19173
+ if (signal.aborted)
19174
+ abort();
19175
+ });
19176
+ }
19033
19177
  #serveKept(credentialId, kept, token, routeId, error = this.#outageError) {
19034
19178
  if (!kept || this.#kept.get(credentialId) !== kept || !this.#usable(kept.attempt)) {
19035
19179
  this.forget(credentialId);
@@ -19255,6 +19399,9 @@ var init_custody = __esm({
19255
19399
  if (this.#closed)
19256
19400
  return;
19257
19401
  this.#closed = true;
19402
+ for (const wait2 of this.#receiptWaits.values())
19403
+ wait2.controller.abort();
19404
+ this.#receiptWaits.clear();
19258
19405
  if (this.#probeTimer)
19259
19406
  this.#clearTimeout(this.#probeTimer);
19260
19407
  this.#probeTimer = void 0;
@@ -21128,6 +21275,13 @@ var init_hub = __esm({
21128
21275
  #own;
21129
21276
  #watch;
21130
21277
  #run;
21278
+ /**
21279
+ * Member commit fan-outs still running, each until every one of its
21280
+ * commits has settled. Only a run whose generation ended can leave one
21281
+ * behind while another run starts; `#discover` waits for them before it
21282
+ * reads the files it lists over.
21283
+ */
21284
+ #fanOuts = /* @__PURE__ */ new Set();
21131
21285
  /** The hub's last authority read; undefined before the first one. */
21132
21286
  #active;
21133
21287
  /** Counts inactive transitions, so local work started before one stops. */
@@ -21601,6 +21755,9 @@ var init_hub = __esm({
21601
21755
  if (!this.#live(generation))
21602
21756
  return void 0;
21603
21757
  const folders = await this.#ensureRosterDirectories().then(() => void 0, (error) => error instanceof Error ? error : new Error(String(error)));
21758
+ await this.#settleFanOuts();
21759
+ if (!this.#live(generation))
21760
+ return void 0;
21604
21761
  const bases = new Map(await Promise.all([...this.#members.values()].map(async (entry) => [
21605
21762
  entry,
21606
21763
  await readVaultRoster(entry.path).then((file) => file ? { file } : {}, (error) => error instanceof Error ? error : new Error(String(error)))
@@ -21621,7 +21778,14 @@ var init_hub = __esm({
21621
21778
  if (!this.#live(generation))
21622
21779
  return void 0;
21623
21780
  const members = this.#open();
21624
- const commits = await Promise.all(members.map((entry) => entry.hooks && !entry.closed ? this.#commit(entry, entry.hooks, inventory, folders ?? bases.get(entry), generation) : void 0));
21781
+ const fanOut = Promise.all(members.map((entry) => entry.hooks && !entry.closed ? this.#commit(entry, entry.hooks, inventory, folders ?? bases.get(entry), generation) : void 0));
21782
+ this.#fanOuts.add(fanOut);
21783
+ let commits;
21784
+ try {
21785
+ commits = await fanOut;
21786
+ } finally {
21787
+ this.#fanOuts.delete(fanOut);
21788
+ }
21625
21789
  if (!this.#live(generation))
21626
21790
  return void 0;
21627
21791
  const errors = /* @__PURE__ */ new Map();
@@ -21722,6 +21886,27 @@ var init_hub = __esm({
21722
21886
  return { error };
21723
21887
  }
21724
21888
  }
21889
+ /**
21890
+ * Wait until no member commit fan-out of an earlier run is still running.
21891
+ * Each of them belongs to a generation that ended, so its commits fail or
21892
+ * finish at their next generation check and this wait stays short.
21893
+ */
21894
+ async #settleFanOuts() {
21895
+ if (!this.#fanOuts.size)
21896
+ return;
21897
+ const phaseDiagnostics2 = channel2("common-auth.claustrum.phases");
21898
+ const phase = (name) => {
21899
+ if (phaseDiagnostics2.hasSubscribers)
21900
+ phaseDiagnostics2.publish({ logger: this.#logger, phase: name });
21901
+ };
21902
+ phase("earlier fan-out drain begin");
21903
+ try {
21904
+ while (this.#fanOuts.size)
21905
+ await Promise.allSettled([...this.#fanOuts]);
21906
+ } finally {
21907
+ phase("earlier fan-out drain end");
21908
+ }
21909
+ }
21725
21910
  /**
21726
21911
  * Create the roster folders under the state folder (`rosters`, this host
21727
21912
  * generation and this key) owner-only, as every other Claustrum private
@@ -22034,6 +22219,8 @@ __export(claustrum_exports, {
22034
22219
  VAULT_FAILURE_CLASSES: () => VAULT_FAILURE_CLASSES,
22035
22220
  VAULT_HOST_CONNECT_REFUSAL: () => VAULT_HOST_CONNECT_REFUSAL,
22036
22221
  VAULT_HOST_STATUS: () => VAULT_HOST_STATUS,
22222
+ VAULT_RECEIPT_WAIT_MS: () => VAULT_RECEIPT_WAIT_MS,
22223
+ VAULT_YOUNG_OUTAGE_MS: () => VAULT_YOUNG_OUTAGE_MS,
22037
22224
  WATCH_RETRY_MS: () => WATCH_RETRY_MS,
22038
22225
  acceptAccount: () => acceptAccount,
22039
22226
  acceptVaultRoute: () => acceptVaultRoute,
@@ -24460,6 +24647,9 @@ function createLoggerInstance2(options) {
24460
24647
  const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine2(options);
24461
24648
  return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
24462
24649
  }
24650
+ function createLogger3(channel3) {
24651
+ return defaultEngine2.createLogger(channel3);
24652
+ }
24463
24653
  var ORDER2, MAX_BYTES2, ROTATE_KEEP2, defaultEngine2;
24464
24654
  var init_engine2 = __esm({
24465
24655
  "src/common-auth-embedded/logger/engine.js"() {
@@ -28823,6 +29013,7 @@ var WRITER_LOCK_CONSTANTS2 = Object.freeze({
28823
29013
  init_private_files2();
28824
29014
 
28825
29015
  // src/common-auth-embedded/fs/refresh-file-lock.js
29016
+ init_logger3();
28826
29017
  import { randomUUID as randomUUID14 } from "node:crypto";
28827
29018
  import { link as link3, lstat as lstat8, mkdir as mkdir13, open as open9, readdir as readdir5, readFile as readFile11, rename as rename11, rm as rm6, stat as stat12, unlink as unlink12 } from "node:fs/promises";
28828
29019
  import { basename as basename6, dirname as dirname18, join as join17 } from "node:path";
@@ -29777,17 +29968,15 @@ async function acquireRefreshFileLockWithClock2(options) {
29777
29968
  removalConfirmed = true;
29778
29969
  }, deadline);
29779
29970
  changingRecordError = void 0;
29780
- if (markerAcquired) {
29781
- if (windowsPrivateFiles2 && !removalConfirmed)
29782
- throw new PrivateFileError2(lockPath, "release-not-confirmed", {
29783
- code: "EIO"
29784
- });
29785
- releaseConfirmed = removalConfirmed;
29971
+ if (markerAcquired && removalConfirmed) {
29972
+ releaseConfirmed = true;
29786
29973
  return;
29787
29974
  }
29788
- if (signal?.aborted)
29789
- return;
29790
- await recoverStaleEvictionMarker(deadline);
29975
+ if (!markerAcquired) {
29976
+ if (signal?.aborted)
29977
+ return;
29978
+ await recoverStaleEvictionMarker(deadline);
29979
+ }
29791
29980
  } catch (error) {
29792
29981
  const changingRecord = windowsPrivateFiles2 && (isChangingLockCreate(error) || isWindowsAccessDeniedRead2(error, [
29793
29982
  lockPath,
@@ -29817,6 +30006,9 @@ async function acquireRefreshFileLockWithClock2(options) {
29817
30006
  throw changingRecordError ?? removalError ?? new PrivateFileError2(lockPath, "release-not-confirmed", {
29818
30007
  code: "ETIMEDOUT"
29819
30008
  });
30009
+ createLogger3("fs").warn("File lock release deadline expired", {
30010
+ lockPath
30011
+ });
29820
30012
  }
29821
30013
  };
29822
30014
  }