@vite-hub/workspace 0.6.0 → 0.7.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 (95) hide show
  1. package/README.md +5 -5
  2. package/dist/{asset-registry-0CdRAjIV.js → asset-registry-DJyE42kr.js} +1 -1
  3. package/dist/blob-database.d.ts +1 -1
  4. package/dist/blob-database.js +6 -6
  5. package/dist/checkout.js +2 -2
  6. package/dist/cloudflare.d.ts +1 -1
  7. package/dist/cloudflare.js +1 -1
  8. package/dist/{config-jo5QgE1w.js → config--ZzAvhMp.js} +14 -9
  9. package/dist/{config-DeA287c0.d.ts → config-DF6sqKXB.d.ts} +1 -1
  10. package/dist/durability.d.ts +1 -1
  11. package/dist/durability.js +2 -2
  12. package/dist/{error-diagnostics-B4me-ouV.js → error-diagnostics-CHgE8TQM.js} +16 -0
  13. package/dist/{error-diagnostics-kKXseq8d.js → error-diagnostics-CsiNo_oI.js} +3 -3
  14. package/dist/{file-BrNAXQgY.js → file-DQ5-TBTD.js} +1 -1
  15. package/dist/{file-metadata-Bpsvjw_X.js → file-metadata-Dqpldj0h.js} +7 -2
  16. package/dist/{files--z2dLC5z.js → files-D1UkSjzX.js} +2 -2
  17. package/dist/files.d.ts +5 -5
  18. package/dist/files.js +5 -5
  19. package/dist/{github-k--_LCrX.js → github-BECfOMaw.js} +4 -4
  20. package/dist/{glob-BreFjNAV.js → glob-BIg9O4yY.js} +2 -2
  21. package/dist/{glob-BEutagp1.js → glob-BIsxLusH.js} +1 -1
  22. package/dist/{host-C8yZizfk.js → host-BYBRcSnh.js} +7 -7
  23. package/dist/hosted-vercel-blob.d.ts +1 -1
  24. package/dist/hosted-vercel-blob.js +464 -1
  25. package/dist/hosted.d.ts +1 -1
  26. package/dist/hosted.js +917 -1
  27. package/dist/index.d.ts +6 -7
  28. package/dist/index.js +13 -13
  29. package/dist/internal/path.js +108 -1
  30. package/dist/internal/workspace.d.ts +2 -3
  31. package/dist/internal/workspace.js +2 -2
  32. package/dist/{lifecycle-IReZfi0b.js → lifecycle-BK7WNfcP.js} +8 -8
  33. package/dist/loader.d.ts +1 -1
  34. package/dist/loader.js +2 -2
  35. package/dist/{mcp-resources-DeJnbOaw.js → mcp-resources-F4SJF4_P.js} +2 -2
  36. package/dist/{memory-BlSRrBH1.js → memory-BCZl_ZsJ.js} +26 -4
  37. package/dist/{metadata-target-CaGLY4ay.js → metadata-target-DPGF6L68.js} +59 -24
  38. package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-BALFFdKj.d.ts} +1 -0
  39. package/dist/{operations-BIaK_uYG.js → operations-DJ_7W0gs.js} +8 -7
  40. package/dist/operations.d.ts +2 -2
  41. package/dist/operations.js +1327 -2
  42. package/dist/{path-Bb9OIc_F.js → path-DYHw5KNk.js} +11 -3
  43. package/dist/plugins-BYxsPDBH.d.ts +12 -0
  44. package/dist/{provider-CN14ewvx.js → provider-fcI7kJ5k.js} +256 -70
  45. package/dist/providers/github/store.d.ts +1 -1
  46. package/dist/providers/github/store.js +1994 -1
  47. package/dist/{registry-BbUg9vJB.js → registry-CFeUQsja.js} +3 -3
  48. package/dist/{registry-B0g19sdy.d.ts → registry-h1-cT-cE.d.ts} +1 -1
  49. package/dist/{registry-s2Ob9PeX.d.ts → registry-hnARUKNF.d.ts} +2 -2
  50. package/dist/replacement-CVZVsflC.js +76 -0
  51. package/dist/{request-scope-CXCI_wCb.js → request-scope-jH4H0Sbm.js} +3 -1
  52. package/dist/{rule-keys-BLEbi1h5.js → rule-keys-xMpiTLq1.js} +1 -1
  53. package/dist/{rules-BPDXypZV.js → rules-DYQCKYdt.js} +4 -4
  54. package/dist/runtime/assets.d.ts +1 -1
  55. package/dist/runtime/assets.js +4 -4
  56. package/dist/runtime/empty-assets-registry.d.ts +1 -1
  57. package/dist/runtime/empty-registry.d.ts +2 -2
  58. package/dist/runtime/registry.d.ts +1 -1
  59. package/dist/runtime/request.js +1 -1
  60. package/dist/runtime/state.d.ts +17 -6
  61. package/dist/runtime/state.js +7 -7
  62. package/dist/runtime/workspace.d.ts +1 -1
  63. package/dist/runtime/workspace.js +1 -1
  64. package/dist/runtime.d.ts +8 -8
  65. package/dist/runtime.js +38 -23
  66. package/dist/{search-C_nVorq7.js → search-CG6UNOtn.js} +1 -1
  67. package/dist/server.d.ts +2 -2
  68. package/dist/server.js +301 -1
  69. package/dist/{shared-C20Wh1mp.js → shared-PFnkYidS.js} +59 -21
  70. package/dist/source-metadata.d.ts +2 -2
  71. package/dist/source-metadata.js +3 -3
  72. package/dist/{sync-BBfR4g5y.js → sync-CUkCuP_g.js} +5 -5
  73. package/dist/test.d.ts +1 -1
  74. package/dist/test.js +1 -1
  75. package/dist/{types-Bel5IDmF.d.ts → types-BnSUug2v.d.ts} +13 -1
  76. package/dist/{use-D0DyTMxM.js → use-BCMkT-kC.js} +15 -51
  77. package/dist/{use-CpphIBof.d.ts → use-CJ5rdIrW.d.ts} +1 -1
  78. package/dist/{use-tools-CHduR5k6.js → use-tools-CcXs2hFA.js} +4 -4
  79. package/dist/{use-tools-CAK10LTc.d.ts → use-tools-DFVqZwgc.d.ts} +2 -2
  80. package/dist/{utils-DXP9xfXo.js → utils-Bv1NBg8r.js} +5 -5
  81. package/dist/vite.d.ts +2 -2
  82. package/dist/vite.js +368 -62
  83. package/dist/{workspace-BOuxrZrP.d.ts → workspace-B6QreLJd.d.ts} +1 -1
  84. package/dist/{workspace-CLuPkyZR.js → workspace-D1m00MCM.js} +340 -104
  85. package/dist/workspace-inspection-scanner-BlJ8bCAB.js +140 -0
  86. package/package.json +12 -12
  87. package/dist/errors-CnFDXxeJ.d.ts +0 -4
  88. package/dist/hosted-8BTKAtMX.js +0 -883
  89. package/dist/hosted-vercel-blob-B6kygYqn.js +0 -408
  90. package/dist/operations-DS1C4uXd.js +0 -1308
  91. package/dist/path-CuYE8-X6.js +0 -57
  92. package/dist/plugins-CLc32jvL.d.ts +0 -8
  93. package/dist/server-aa1a4rkV.js +0 -301
  94. package/dist/state-BdDfBtOR.d.ts +0 -17
  95. package/dist/store-cx3OqNTi.js +0 -1971
@@ -1,4 +1,4 @@
1
- import { l as workspacePathError, t as normalizeSafeWorkspacePath } from "./path-CuYE8-X6.js";
1
+ import { c as workspacePathError, normalizeSafeWorkspacePath } from "./internal/path.js";
2
2
  import { isAbsolute, relative, resolve, sep } from "node:path";
3
3
  import { createHash } from "node:crypto";
4
4
  import { minimatch } from "minimatch";
@@ -86,12 +86,20 @@ async function contentStreamToBytes(stream) {
86
86
  }
87
87
  return bytes;
88
88
  }
89
+ const storedFileRead = Symbol.for("vitehub.workspace.stored-file-read");
90
+ const storedFileReadOptions = {
91
+ encoding: "binary",
92
+ [storedFileRead]: true
93
+ };
94
+ async function readStoredFile(reader, path) {
95
+ return await reader.readFile(path, storedFileReadOptions);
96
+ }
89
97
  function decodeFile(content, options) {
90
- if (options?.encoding === "binary") return content;
98
+ if (options?.encoding === "binary") return Object.hasOwn(options, storedFileRead) ? content : contentToBytes(content);
91
99
  return typeof content === "string" ? content : new TextDecoder().decode(content);
92
100
  }
93
101
  async function sha256(input) {
94
102
  const bytes = contentToBytes(typeof input === "string" || isWorkspaceBytes(input) ? input : JSON.stringify(input));
95
103
  return createHash("sha256").update(bytes).digest("hex");
96
104
  }
97
- export { isExcludedWorkspacePath as a, normalizeSafeWorkspacePattern as c, sha256 as d, decodeFile as i, normalizeWorkspacePath as l, contentStreamToBytes as n, isWorkspaceBytes as o, contentToBytes as r, matchesAny as s, contentStreamChunks as t, resolveInside as u };
105
+ export { isExcludedWorkspacePath as a, normalizeSafeWorkspacePattern as c, resolveInside as d, sha256 as f, decodeFile as i, normalizeWorkspacePath as l, contentStreamToBytes as n, isWorkspaceBytes as o, contentToBytes as r, matchesAny as s, contentStreamChunks as t, readStoredFile as u };
@@ -0,0 +1,12 @@
1
+ import { jt as WorkspacePlugin } from "./types-BnSUug2v.js";
2
+ import { ViteHubError } from "@vite-hub/runtime";
3
+ import { Diagnostic } from "nostics";
4
+ type WorkspaceErrorCode = "WORKSPACE_CONFLICT" | "WORKSPACE_FAILED" | "WORKSPACE_NOT_FOUND" | "WORKSPACE_PATH_INVALID" | "WORKSPACE_SOURCE_READ_ONLY";
5
+ declare function isWorkspaceConflict(value: unknown): boolean;
6
+ /**
7
+ * Add a plugin's rules and hooks to a Workspace by name, including discovered Workspaces the caller does not define.
8
+ * Registering the same plugin id again replaces the earlier registration. A plugin declared by the Workspace Definition
9
+ * with the same id wins. The returned function removes this registration.
10
+ */
11
+ declare function registerWorkspacePlugin(workspace: string, plugin: WorkspacePlugin): () => void;
12
+ export { WorkspaceErrorCode as n, isWorkspaceConflict as r, registerWorkspacePlugin as t };
@@ -1,20 +1,22 @@
1
- import { M as readForgeEnv, j as forgeEnv, t as assertNoGitHubRepositoryKey } from "./shared-C20Wh1mp.js";
2
- import { n as assertWorkspaceDigest, o as workspaceConflictError, s as workspaceError } from "./path-CuYE8-X6.js";
3
- import { t as createGitHubWorkspaceStore } from "./store-cx3OqNTi.js";
1
+ import { M as readForgeEnv, j as forgeEnv, t as assertNoGitHubRepositoryKey } from "./shared-PFnkYidS.js";
2
+ import { a as workspaceConflictError, o as workspaceError, t as assertWorkspaceDigest } from "./internal/path.js";
3
+ import { createGitHubWorkspaceStore } from "./providers/github/store.js";
4
4
  import { t as getWorkspaceRuntimeConfig } from "./config-CsgNNVAI.js";
5
- import { t as copyJsonFileMetadata } from "./file-metadata-Bpsvjw_X.js";
6
- import { t as createWorkspaceGlobMatcher } from "./glob-BreFjNAV.js";
7
- import { a as isExcludedWorkspacePath, d as sha256, l as normalizeWorkspacePath, r as contentToBytes, t as contentStreamChunks, u as resolveInside } from "./path-Bb9OIc_F.js";
5
+ import { n as copyJsonFileMetadata } from "./file-metadata-Dqpldj0h.js";
6
+ import { t as createWorkspaceGlobMatcher } from "./glob-BIg9O4yY.js";
7
+ import { a as isExcludedWorkspacePath, d as resolveInside, f as sha256, l as normalizeWorkspacePath, r as contentToBytes, t as contentStreamChunks } from "./path-DYHw5KNk.js";
8
8
  import { a as provideWorkspaceStoreTarget } from "./vitehub-grants-Co713QTg.js";
9
- import { r as vitehubOwnedPrefix, t as createMemoryWorkspaceStore } from "./memory-BlSRrBH1.js";
10
- import { t as workspaceErrorDiagnostics } from "./error-diagnostics-B4me-ouV.js";
11
- import { dirname, join, relative, resolve, sep } from "node:path";
9
+ import { a as replacementRecoveryError, i as replaceStorePath } from "./replacement-CVZVsflC.js";
10
+ import { r as vitehubOwnedPrefix, t as createMemoryWorkspaceStore } from "./memory-BCZl_ZsJ.js";
11
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CHgE8TQM.js";
12
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
12
13
  import { createHash, randomUUID } from "node:crypto";
13
- import { constants, createReadStream, createWriteStream } from "node:fs";
14
- import { chmod, chown, copyFile, link, lstat, mkdir, open, readFile, readdir, rename, rm, rmdir, stat, utimes, writeFile } from "node:fs/promises";
14
+ import { constants, createReadStream, createWriteStream, readFileSync, readlinkSync } from "node:fs";
15
+ import { chmod, chown, copyFile, link, lstat, mkdir, mkdtemp, open, readFile, readdir, rename, rm, rmdir, stat, utimes, writeFile } from "node:fs/promises";
15
16
  import { defu } from "defu";
16
17
  import { check, fallback, literal, object, optional, pipe, record, safeParse, string, unknown } from "valibot";
17
18
  import { Readable, Transform } from "node:stream";
19
+ import { hostname } from "node:os";
18
20
  import { pipeline } from "node:stream/promises";
19
21
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
20
22
  // ../internal/src/env.ts
@@ -123,6 +125,7 @@ async function validateLockDirectory(path) {
123
125
  throw error;
124
126
  });
125
127
  if (info && (!info.isDirectory() || info.isSymbolicLink())) throw workspaceError(`[vitehub] Untrusted Workspace lock path: ${path}.`);
128
+ return info !== void 0;
126
129
  }
127
130
  async function ensureLockDirectory(path) {
128
131
  await mkdir(path, { mode: 448 }).catch((error) => {
@@ -130,6 +133,74 @@ async function ensureLockDirectory(path) {
130
133
  });
131
134
  await validateLockDirectory(path);
132
135
  }
136
+ let currentLeaseHost;
137
+ function leaseHost() {
138
+ const read = (read) => {
139
+ try {
140
+ return read().trim();
141
+ } catch {
142
+ return "";
143
+ }
144
+ };
145
+ const digest = (value) => createHash("sha256").update(value).digest("hex").slice(0, 16);
146
+ if (currentLeaseHost) return currentLeaseHost;
147
+ const namespace = process.platform === "linux" ? read(() => readlinkSync("/proc/self/ns/pid")) : "";
148
+ const boot = namespace ? read(() => readFileSync("/proc/sys/kernel/random/boot_id", "utf8")) : "";
149
+ return currentLeaseHost = {
150
+ host: namespace ? digest(`${hostname()}\0${namespace}`) : "",
151
+ boot: boot ? digest(boot) : ""
152
+ };
153
+ }
154
+ function leaseOwner() {
155
+ const { boot, host } = leaseHost();
156
+ return `${randomUUID()}~${process.pid}~${host}~${boot}`;
157
+ }
158
+ function isAbandonedLease(owner) {
159
+ const [, pidText, host, boot] = owner.trim().split("~");
160
+ const pid = Number(pidText);
161
+ const current = leaseHost();
162
+ if (!current.boot || !Number.isSafeInteger(pid) || pid <= 0 || host !== current.host || boot !== current.boot) return false;
163
+ if (pid === process.pid) return false;
164
+ try {
165
+ process.kill(pid, 0);
166
+ return false;
167
+ } catch (error) {
168
+ return Reflect.get(Object(error), "code") === "ESRCH";
169
+ }
170
+ }
171
+ const interruptedRemovals = /* @__PURE__ */ new WeakMap();
172
+ function privateGatePath(gate) {
173
+ return join(dirname(gate), `.recovery-${basename(gate)}-${randomUUID()}`);
174
+ }
175
+ async function reclaimAbandonedGate(gate) {
176
+ const reclaimer = `${gate}.reclaim`;
177
+ if (!await mkdir(reclaimer, { mode: 448 }).then(() => true, (error) => {
178
+ if (error.code === "EEXIST") return false;
179
+ throw error;
180
+ })) return;
181
+ try {
182
+ if (!isAbandonedLease(await readFile(`${gate}/owner`, "utf8").catch(() => ""))) return;
183
+ const quarantine = privateGatePath(gate);
184
+ if (await rename(gate, quarantine).then(() => true, () => false)) await rm(quarantine, {
185
+ force: true,
186
+ recursive: true
187
+ });
188
+ } finally {
189
+ await rmdir(reclaimer);
190
+ }
191
+ }
192
+ async function removeAbandonedMarkers(directory) {
193
+ const names = await readdir(directory).catch(() => []);
194
+ for (const name of names) if (isAbandonedLease(name)) await rm(join(directory, name), {
195
+ force: true,
196
+ recursive: true
197
+ });
198
+ }
199
+ function lockTimeoutError(description, lock) {
200
+ const base = lock.replace(/\.gate$/, "");
201
+ const root = dirname(dirname(dirname(base)));
202
+ return workspaceError(`[vitehub] Timed out waiting to ${description}. Another operation holds a lock marker at ${base}.gate, ${base}.readers, or ${base}.writers, or a process left it when it stopped. If no process uses this Workspace, stop every process that can use it and call recoverLocalWorkspaceLocks({ root: ${JSON.stringify(root)}, offline: true }) from vite-hub/workspace/runtime.`);
203
+ }
133
204
  async function withLeaseHeartbeat(file, operation, onFailure) {
134
205
  let renewal = Promise.resolve();
135
206
  let rejectHeartbeat;
@@ -163,9 +234,9 @@ async function withLeaseHeartbeat(file, operation, onFailure) {
163
234
  }
164
235
  }
165
236
  }
166
- async function removeOwnedGate(lock) {
237
+ async function removePrivateGate(path) {
167
238
  for (let attempt = 0;; attempt++) try {
168
- await rm(lock, {
239
+ await rm(path, {
169
240
  force: true,
170
241
  recursive: true
171
242
  });
@@ -175,49 +246,51 @@ async function removeOwnedGate(lock) {
175
246
  await setTimeout$1(25);
176
247
  }
177
248
  }
178
- async function withFilesystemLock(lock, permissions, description, operation, deadline) {
179
- const expiresAt = Date.now() + 1e4;
180
- const owner = randomUUID();
181
- const ownerPath = `${lock}/owner`;
249
+ async function publishGate(lock, permissions) {
250
+ const staged = privateGatePath(lock);
251
+ await mkdir(staged, { mode: 448 });
182
252
  let lease;
183
- while (true) {
184
- let created = false;
253
+ let published = false;
254
+ try {
255
+ if (process.platform !== "win32") await applyMetadataPermissions(staged, permissions.mode & 504, permissions.gid);
256
+ lease = await open(`${staged}/owner`, "wx");
257
+ await lease.writeFile(leaseOwner());
185
258
  try {
186
- await mkdir(lock, { mode: 448 });
187
- created = true;
188
- if (process.platform !== "win32") await applyMetadataPermissions(lock, permissions.mode & 504, permissions.gid);
189
- const ownerFile = await open(ownerPath, "wx");
190
- try {
191
- await ownerFile.writeFile(owner);
192
- } catch (error) {
193
- await ownerFile.close();
194
- throw error;
195
- }
196
- lease = ownerFile;
197
- break;
259
+ await rename(staged, lock);
198
260
  } catch (error) {
199
- if (created) {
200
- try {
201
- await removeOwnedGate(lock);
202
- } catch (cleanupError) {
203
- throw new AggregateError([error, cleanupError], "Workspace gate acquisition and cleanup failed", { cause: error });
204
- }
205
- throw error;
206
- }
207
- if (Reflect.get(Object(error), "code") !== "EEXIST") throw error;
208
- await validateLockDirectory(lock);
209
- if (Date.now() >= (deadline?.() ?? expiresAt)) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
210
- else await setTimeout$1(25);
261
+ const code = Reflect.get(Object(error), "code");
262
+ if (["EEXIST", "ENOTEMPTY"].includes(code) || process.platform === "win32" && ["EPERM", "EACCES"].includes(code) && await validateLockDirectory(lock)) return;
263
+ throw error;
211
264
  }
212
- }
213
- try {
214
- return await withLeaseHeartbeat(lease, operation);
265
+ published = true;
266
+ return lease;
215
267
  } finally {
216
- await removeOwnedGate(lock);
268
+ if (!published) try {
269
+ await lease?.close();
270
+ } finally {
271
+ await removePrivateGate(staged);
272
+ }
273
+ }
274
+ }
275
+ async function withFilesystemLock(lock, permissions, description, operation, deadline) {
276
+ const expiresAt = Date.now() + 1e4;
277
+ while (true) {
278
+ if (!await validateLockDirectory(lock)) {
279
+ const lease = await publishGate(lock, permissions);
280
+ if (lease) try {
281
+ return await withLeaseHeartbeat(lease, operation);
282
+ } finally {
283
+ const retired = privateGatePath(lock);
284
+ await rename(lock, retired);
285
+ await removePrivateGate(retired);
286
+ }
287
+ } else await reclaimAbandonedGate(lock);
288
+ if (Date.now() >= (deadline?.() ?? expiresAt)) throw lockTimeoutError(description, lock);
289
+ await setTimeout$1(25);
217
290
  }
218
291
  }
219
292
  async function withFilesystemReadLock(lock, permissions, description, operation, onFailure) {
220
- const reader = `${lock}.readers/${randomUUID()}`;
293
+ const reader = `${lock}.readers/${leaseOwner()}`;
221
294
  await ensureLockDirectory(`${lock}.readers`);
222
295
  if (process.platform !== "win32") await applyMetadataPermissions(`${lock}.readers`, permissions.mode & 504, permissions.gid);
223
296
  const lease = await open(reader, "wx");
@@ -242,21 +315,26 @@ async function withFilesystemWriteLock(lock, permissions, description, operation
242
315
  const deadline = Date.now() + 1e4;
243
316
  while (true) {
244
317
  await validateLockDirectory(readers);
245
- if ((await readdir(readers).catch((error) => {
318
+ const active = await readdir(readers).catch((error) => {
246
319
  if (error.code === "ENOENT") return [];
247
320
  throw error;
248
- })).length === 0) {
321
+ });
322
+ if (active.some(isAbandonedLease)) {
323
+ await removeAbandonedMarkers(readers);
324
+ continue;
325
+ }
326
+ if (active.length === 0) {
249
327
  await rmdir(readers).catch(() => {});
250
328
  return await operation();
251
329
  }
252
- if (Date.now() >= deadline) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
330
+ if (Date.now() >= deadline) throw lockTimeoutError(description, lock);
253
331
  await setTimeout$1(25);
254
332
  }
255
333
  });
256
334
  }
257
335
  async function withFilesystemWriterIntent(lock, permissions, operation) {
258
336
  const intents = `${lock}.writers`;
259
- const intent = `${intents}/${randomUUID()}`;
337
+ const intent = `${intents}/${leaseOwner()}`;
260
338
  for (;;) try {
261
339
  await ensureLockDirectory(intents);
262
340
  if (process.platform !== "win32") await applyMetadataPermissions(intents, permissions.mode & 504, permissions.gid);
@@ -275,6 +353,7 @@ async function withFilesystemWriterIntent(lock, permissions, operation) {
275
353
  recursive: true,
276
354
  force: true
277
355
  });
356
+ await removeAbandonedMarkers(intents);
278
357
  await rmdir(intents).catch((error) => {
279
358
  if (![
280
359
  "ENOENT",
@@ -332,7 +411,7 @@ async function admitSharedReader(lock, permissions, description, deadline) {
332
411
  const liveTickets = () => [...batch.tickets].filter((reader) => Date.now() < reader.deadline);
333
412
  batch.admitted = withFilesystemLock(`${lock}.gate`, permissions, description, async () => {
334
413
  readAdmissions.delete(lock);
335
- if (!liveTickets().length) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
414
+ if (!liveTickets().length) throw lockTimeoutError(description, lock);
336
415
  if (pendingWriters.has(lock) || await lstat(`${lock}.writers`).then(() => true).catch((error) => {
337
416
  if (error.code === "ENOENT") return false;
338
417
  throw error;
@@ -346,7 +425,7 @@ async function admitSharedReader(lock, permissions, description, deadline) {
346
425
  chargedCount = tickets.length;
347
426
  if (!chargedCount) {
348
427
  await releaseSharedReaders(lock, lease, 0);
349
- throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
428
+ throw lockTimeoutError(description, lock);
350
429
  }
351
430
  lease.readers += chargedCount;
352
431
  chargedLease = lease;
@@ -372,12 +451,12 @@ async function admitSharedReader(lock, permissions, description, deadline) {
372
451
  if (Date.now() < deadline) return;
373
452
  timedOut = true;
374
453
  batch.tickets.delete(ticket);
375
- reject(workspaceError(`[vitehub] Timed out waiting to ${description}.`));
454
+ reject(lockTimeoutError(description, lock));
376
455
  }, 25);
377
456
  });
378
457
  try {
379
458
  const lease = await Promise.race([batch.admitted, expired]);
380
- if (lease && !ticket.charged) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
459
+ if (lease && !ticket.charged) throw lockTimeoutError(description, lock);
381
460
  return lease;
382
461
  } catch (error) {
383
462
  if (timedOut && ticket.charged) try {
@@ -406,9 +485,9 @@ async function withSharedFilesystemReadLock(lock, permissions, description, oper
406
485
  while (!lease) {
407
486
  for (let writers = pendingWriters.get(lock); writers; writers = pendingWriters.get(lock)) {
408
487
  const remaining = deadline - Date.now();
409
- if (remaining <= 0) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
488
+ if (remaining <= 0) throw lockTimeoutError(description, lock);
410
489
  await new Promise((resolve, reject) => {
411
- const timeout = setTimeout(() => reject(workspaceError(`[vitehub] Timed out waiting to ${description}.`)), remaining);
490
+ const timeout = setTimeout(() => reject(lockTimeoutError(description, lock)), remaining);
412
491
  writers.idle.then(() => {
413
492
  clearTimeout(timeout);
414
493
  resolve();
@@ -427,14 +506,21 @@ async function withSharedFilesystemReadLock(lock, permissions, description, oper
427
506
  lease = await admitSharedReader(lock, permissions, description, deadline);
428
507
  if (lease) break;
429
508
  }
430
- if (writerIntent) await validateLockDirectory(`${lock}.writers`);
431
- if (gate) await validateLockDirectory(`${lock}.gate`);
432
- if (Date.now() >= deadline) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
509
+ if (writerIntent) {
510
+ await validateLockDirectory(`${lock}.writers`);
511
+ await removeAbandonedMarkers(`${lock}.writers`);
512
+ await rmdir(`${lock}.writers`).catch(() => {});
513
+ }
514
+ if (gate) {
515
+ await validateLockDirectory(`${lock}.gate`);
516
+ await reclaimAbandonedGate(`${lock}.gate`);
517
+ }
518
+ if (Date.now() >= deadline) throw lockTimeoutError(description, lock);
433
519
  await setTimeout$1(25);
434
520
  }
435
521
  try {
436
522
  await lease.acquired;
437
- if (Date.now() >= deadline) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
523
+ if (Date.now() >= deadline) throw lockTimeoutError(description, lock);
438
524
  if (lease.failure) throw lease.failure.error;
439
525
  return await operation();
440
526
  } finally {
@@ -722,27 +808,70 @@ var LocalWorkspaceStore = class {
722
808
  provideWorkspaceStoreTarget(this, () => this.#storeTarget());
723
809
  }
724
810
  async #pathLock(root, path, operation, readOnly = false) {
811
+ await this.#completeInterruptedRemovalsAbove(path);
812
+ return await this.#lockPath(root, path, operation, readOnly);
813
+ }
814
+ async #lockPath(root, path, operation, readOnly = false) {
725
815
  return this.#processLocks ? await withProcessPathLock(root, path, operation, readOnly) : await withWorkspacePathLock(root, path, operation, readOnly);
726
816
  }
817
+ async #completeInterruptedRemovalsAbove(path) {
818
+ if (!await this.#hasRemovalDirectory()) return;
819
+ const markers = await readdir(`${this.root}/.vitehub/file-removals`);
820
+ if (!markers.length) return;
821
+ const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
822
+ for (let index = 1; index <= parts.length; index++) {
823
+ const ancestor = parts.slice(0, index).join("/");
824
+ if (markers.includes(basename(this.#removalMarker(ancestor)))) await this.#completeInterruptedRemoval(ancestor);
825
+ }
826
+ }
827
+ async #completeInterruptedRemoval(path) {
828
+ if (!path) return;
829
+ await this.#lockPath(this.root, path, async () => {
830
+ const marker = this.#removalMarker(path);
831
+ if (!await lstat(marker).then(() => true, (error) => {
832
+ if (error.code === "ENOENT") return false;
833
+ throw error;
834
+ })) return;
835
+ const metadata = await this.#prepareMetadataDirectories(path, false);
836
+ for (const key of this.#files.keys()) if (key === path || key.startsWith(`${path}/`)) this.#files.delete(key);
837
+ if (metadata.root) await rm(resolveInside(this.#fileMetadataRoot, path), {
838
+ force: true,
839
+ recursive: true
840
+ });
841
+ await rm(marker, { force: true });
842
+ });
843
+ }
727
844
  #removalMarker(path) {
728
845
  return `${this.root}/.vitehub/file-removals/${createHash("sha256").update(path).digest("hex")}`;
729
846
  }
730
- async #assertNoPendingRemoval(path) {
731
- const directory = `${this.root}/.vitehub/file-removals`;
732
- const info = await lstat(directory).catch((error) => {
847
+ async #hasRemovalDirectory() {
848
+ const lookup = (path) => lstat(path).catch((error) => {
733
849
  if (error.code === "ENOENT") return void 0;
734
850
  throw error;
735
851
  });
736
- if (!info) return;
852
+ const metadata = await lookup(`${this.root}/.vitehub`);
853
+ if (!metadata) return false;
854
+ if (metadata.isSymbolicLink() || !metadata.isDirectory()) throw workspaceError(`[vitehub] Untrusted Workspace metadata path: ${this.root}/.vitehub.`);
855
+ const directory = `${this.root}/.vitehub/file-removals`;
856
+ const info = await lookup(directory);
857
+ if (!info) return false;
737
858
  assertTrustedMetadata(directory, info, await stat(this.root));
738
859
  if (!info.isDirectory()) throw workspaceError(`[vitehub] Invalid Workspace removal directory.`);
860
+ return true;
861
+ }
862
+ async #assertNoPendingRemoval(path) {
863
+ if (!await this.#hasRemovalDirectory()) return;
739
864
  const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
740
865
  for (let index = 0; index <= parts.length; index++) {
741
866
  const ancestor = parts.slice(0, index).join("/");
742
867
  if (await lstat(this.#removalMarker(ancestor)).catch((error) => {
743
868
  if (error.code === "ENOENT") return void 0;
744
869
  throw error;
745
- })) throw workspaceError(`[vitehub] Interrupted Workspace removal at ${ancestor || "/"}; retry removal before accessing ${path}.`);
870
+ })) {
871
+ const error = workspaceError(`[vitehub] Interrupted Workspace removal at ${ancestor || "/"}; retry removal before accessing ${path}. The marker is ${this.#removalMarker(ancestor)}. The Store rolls it back on the next operation; if that fails, fix the error it reports and retry.`);
872
+ interruptedRemovals.set(error, ancestor);
873
+ throw error;
874
+ }
746
875
  }
747
876
  }
748
877
  async #readFileMetadata(path) {
@@ -955,6 +1084,12 @@ var LocalWorkspaceStore = class {
955
1084
  }
956
1085
  }
957
1086
  async #publishFile({ absolute, normalized, temp, backup, hadExisting, file }) {
1087
+ if (hadExisting && process.platform !== "win32") {
1088
+ const original = await stat(absolute);
1089
+ const staged = await stat(temp);
1090
+ if (staged.gid !== original.gid) await chown(temp, staged.uid, original.gid);
1091
+ await chmod(temp, original.mode & 511);
1092
+ }
958
1093
  const foreignUid = hadExisting ? await backupFile(absolute, backup) : void 0;
959
1094
  await rename(temp, absolute).catch(async (error) => {
960
1095
  await rm(backup, { force: true });
@@ -980,7 +1115,7 @@ var LocalWorkspaceStore = class {
980
1115
  for (const part of parts) {
981
1116
  current = join(current, part);
982
1117
  const info = await lstat(current).catch((error) => {
983
- if (error.code === "ENOENT") return void 0;
1118
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return void 0;
984
1119
  throw error;
985
1120
  });
986
1121
  if (!info) return;
@@ -1056,6 +1191,16 @@ var LocalWorkspaceStore = class {
1056
1191
  return await this.#list(prefix, options, false);
1057
1192
  }
1058
1193
  async #list(prefix, options, includeDigest) {
1194
+ for (const completed = /* @__PURE__ */ new Set();;) try {
1195
+ return await this.#listOnce(prefix, options, includeDigest);
1196
+ } catch (error) {
1197
+ const path = typeof error === "object" && error !== null ? interruptedRemovals.get(error) : void 0;
1198
+ if (!path || completed.has(path)) throw error;
1199
+ completed.add(path);
1200
+ await this.#completeInterruptedRemoval(path);
1201
+ }
1202
+ }
1203
+ async #listOnce(prefix, options, includeDigest) {
1059
1204
  await this.#assertPathComponents(prefix);
1060
1205
  const normalizedPrefix = normalizeWorkspacePath(prefix);
1061
1206
  const current = normalizedPrefix ? resolveInside(this.root, normalizedPrefix) : this.root;
@@ -1111,7 +1256,7 @@ var LocalWorkspaceStore = class {
1111
1256
  const absolute = resolveInside(this.root, normalized);
1112
1257
  await this.#assertPathComponents(normalized);
1113
1258
  const info = await stat(absolute, { bigint: true }).catch((error) => {
1114
- if (error.code === "ENOENT") return void 0;
1259
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return void 0;
1115
1260
  throw error;
1116
1261
  });
1117
1262
  if (!info) return void 0;
@@ -1151,6 +1296,47 @@ var LocalWorkspaceStore = class {
1151
1296
  async rm(path, options = {}) {
1152
1297
  await this.#pathLock(this.root, path, () => this.#rm(path, options));
1153
1298
  }
1299
+ async [replaceStorePath]({ path, directories, files, removeTree }) {
1300
+ await this.#pathLock(this.root, path, async () => {
1301
+ if (!removeTree) return await this.#writeFile(path, files[0]);
1302
+ await this.#assertPathComponents(path);
1303
+ await this.#prepareMetadataDirectories(path, true, false);
1304
+ const backup = await mkdtemp(join(this.root, ".vitehub", "replace-"));
1305
+ const original = resolveInside(this.root, path);
1306
+ const attributes = resolveInside(this.#fileMetadataRoot, path);
1307
+ const saved = [];
1308
+ let writing = false;
1309
+ try {
1310
+ for (const [from, to] of [[original, join(backup, "tree")], [attributes, join(backup, "metadata")]]) {
1311
+ await rename(from, to);
1312
+ saved.push({
1313
+ from,
1314
+ to
1315
+ });
1316
+ }
1317
+ writing = true;
1318
+ for (const directory of directories) await mkdir(resolveInside(this.root, directory), { recursive: true });
1319
+ for (const file of files) await this.#writeFile(file.path, file);
1320
+ } catch (error) {
1321
+ const failures = [];
1322
+ if (writing) for (const target of [original, attributes]) await rm(target, {
1323
+ force: true,
1324
+ recursive: true
1325
+ }).catch((failure) => failures.push(failure));
1326
+ for (const { from, to } of saved.reverse()) await rename(to, from).catch((failure) => failures.push(failure));
1327
+ if (failures.length) throw replacementRecoveryError(path, error, failures);
1328
+ await rm(backup, {
1329
+ force: true,
1330
+ recursive: true
1331
+ }).catch(() => void 0);
1332
+ throw error;
1333
+ }
1334
+ await rm(backup, {
1335
+ force: true,
1336
+ recursive: true
1337
+ }).catch(() => void 0);
1338
+ });
1339
+ }
1154
1340
  async #rm(path, options = {}) {
1155
1341
  await this.#assertPathComponents(path, false);
1156
1342
  const normalized = normalizeWorkspacePath(path);
@@ -1445,7 +1631,7 @@ function resolveWorkspaceDefinitionStore(definition, runtimeConfig = getWorkspac
1445
1631
  const runtimeStore = runtimeConfig ? runtimeConfig.store : void 0;
1446
1632
  return normalizeWorkspaceStoreOptions(definition.store || runtimeStore, {
1447
1633
  env: typeof process !== "undefined" ? process.env : {},
1448
- hosting: typeof process !== "undefined" ? process.env.VITEHUB_HOST : void 0,
1634
+ hosting: (typeof process !== "undefined" ? process.env.VITEHUB_HOST : void 0) || (globalThis.navigator?.userAgent === "Cloudflare-Workers" ? "cloudflare" : void 0),
1449
1635
  rootDir,
1450
1636
  runtime: true,
1451
1637
  ...input
@@ -1,2 +1,2 @@
1
- import { En as WorkspaceStore, s as GitHubWorkspaceStoreOptions } from "../../types-Bel5IDmF.js";
1
+ import { En as WorkspaceStore, s as GitHubWorkspaceStoreOptions } from "../../types-BnSUug2v.js";
2
2
  export declare function createGitHubWorkspaceStore(options: GitHubWorkspaceStoreOptions, workspaceName: string): WorkspaceStore;