@vite-hub/workspace 0.0.4 → 0.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 (127) hide show
  1. package/README.md +225 -58
  2. package/dist/{ai-CjxvGqM0.d.ts → ai-BW2ZhizI.d.ts} +22 -7
  3. package/dist/{ai-BqCC8BpY.js → ai-BZyLwULx.js} +147 -66
  4. package/dist/ai.d.ts +2 -2
  5. package/dist/ai.js +1 -1
  6. package/dist/{asset-registry-8QI3ML3K.js → asset-registry-DfBV5kmw.js} +3 -2
  7. package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +19 -0
  8. package/dist/blob-database.d.ts +521 -0
  9. package/dist/blob-database.js +601 -0
  10. package/dist/cloudflare.d.ts +5 -6
  11. package/dist/cloudflare.js +1 -1
  12. package/dist/config-B7dmzDX3.js +1112 -0
  13. package/dist/{config-DE9xlaIw.d.ts → config-DLKdaFWN.d.ts} +1 -2
  14. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  15. package/dist/error-diagnostics-DY5GP47p.js +96 -0
  16. package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +354 -0
  17. package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +214 -0
  18. package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +527 -0
  19. package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +248 -0
  20. package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +179 -0
  21. package/dist/file-C0_aPWSS.js +26 -0
  22. package/dist/file-metadata-CxDy-E2H.js +58 -0
  23. package/dist/{files-Q6xZjDHA.js → files-C7Px8uaC.js} +3 -3
  24. package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +2278 -0
  25. package/dist/{github-DHnjxQIX.js → github-CPxHtFB7.js} +16 -23
  26. package/dist/github-DtncTfmv-Du2S8lGF.js +4159 -0
  27. package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +2530 -0
  28. package/dist/glob--XcLlcml.js +22 -0
  29. package/dist/glob--kNYDbfU.js +30 -0
  30. package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +489 -0
  31. package/dist/{host-DJH8cuoU.js → host-CFnrTXTK.js} +97 -41
  32. package/dist/{hosted-RPeJOCFz.js → hosted-acMA5XyL.js} +102 -19
  33. package/dist/hosted-vercel-blob-DKntsHaf.js +12603 -0
  34. package/dist/hosted-vercel-blob.d.ts +5 -6
  35. package/dist/hosted-vercel-blob.js +1 -1
  36. package/dist/hosted.d.ts +6 -7
  37. package/dist/hosted.js +1 -1
  38. package/dist/index.d.ts +57 -36
  39. package/dist/index.js +56 -56
  40. package/dist/inspect-BoObD2cJ.js +167 -0
  41. package/dist/internal/path.d.ts +2 -0
  42. package/dist/internal/path.js +2 -0
  43. package/dist/lifecycle-BwZ7c9hb.js +596 -0
  44. package/dist/loader.d.ts +5 -6
  45. package/dist/loader.js +3 -2
  46. package/dist/mcp-resources-BREFCmtn.js +39 -0
  47. package/dist/memory-BbwOqDXl.js +248 -0
  48. package/dist/metadata-target-DZEZQGHA.js +1588 -0
  49. package/dist/mountx.d.ts +4 -6
  50. package/dist/mountx.js +10 -8
  51. package/dist/nitro.d.ts +1 -1
  52. package/dist/nitro.js +1 -1
  53. package/dist/nuxt.d.ts +13 -12
  54. package/dist/nuxt.js +4 -8
  55. package/dist/operations-BcpWr41m.js +159 -0
  56. package/dist/operations-CGqY1XeG.js +965 -0
  57. package/dist/operations-DnOwKsJT.d.ts +136 -0
  58. package/dist/operations.d.ts +53 -0
  59. package/dist/operations.js +2 -0
  60. package/dist/path-CNAwN7pw.js +114 -0
  61. package/dist/path-DrSIenjj.js +59 -0
  62. package/dist/path-zHxQUbqa.d.ts +9 -0
  63. package/dist/plugins-DqQ8b4T5.d.ts +10 -0
  64. package/dist/provider-kXjfli9u.js +1457 -0
  65. package/dist/providers/github/store.d.ts +3 -5
  66. package/dist/providers/github/store.js +1 -1
  67. package/dist/{registry-D3yzt8HQ.js → registry-Bp-8UUfG.js} +9 -7
  68. package/dist/{registry-Uj6IVxes.d.ts → registry-Cg1TJVVZ.d.ts} +1 -2
  69. package/dist/{request-execution-B-dSFlGB.js → request-execution-Dk9rY-Yh.js} +19 -19
  70. package/dist/{chunk-2rV9d50f.js → rolldown-runtime-B4iAMlE-.js} +2 -2
  71. package/dist/runtime/assets.d.ts +3 -5
  72. package/dist/runtime/assets.js +7 -6
  73. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  74. package/dist/runtime/empty-registry.d.ts +1 -2
  75. package/dist/runtime/state.d.ts +3 -3
  76. package/dist/runtime/state.js +6 -6
  77. package/dist/runtime/workspace.d.ts +1 -1
  78. package/dist/runtime/workspace.js +1 -1
  79. package/dist/runtime.d.ts +51 -17
  80. package/dist/runtime.js +320 -60
  81. package/dist/{search-BpiCF2Tw.js → search-CrTmXj5h.js} +10 -9
  82. package/dist/server-BNQ-Nbjj.js +290 -0
  83. package/dist/server.d.ts +22 -34
  84. package/dist/server.js +2 -328
  85. package/dist/shared-DalXdP0i.js +2158 -0
  86. package/dist/source-metadata.d.ts +6 -7
  87. package/dist/source-metadata.js +7 -7
  88. package/dist/{state-tYcRWEh2.d.ts → state-B8zbLi5t.d.ts} +3 -3
  89. package/dist/store-CXgmu-uw.js +1729 -0
  90. package/dist/{sync-DnTQwt8r.js → sync-CN6ec-5M.js} +61 -41
  91. package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +125 -0
  92. package/dist/test.d.ts +1 -1
  93. package/dist/test.js +1 -1
  94. package/dist/{token-CVzURBxC.js → token-CO62GglH.js} +3 -3
  95. package/dist/{types-CYuwjJ4V.d.ts → types-DeK9GIxy.d.ts} +256 -24
  96. package/dist/{use-BTNDR5Rd.js → use-BQj7nSz6.js} +82 -41
  97. package/dist/{use-BiHzt0xA.d.ts → use-DhwhbAVV.d.ts} +16 -11
  98. package/dist/utils-Blrh4N2n.js +545 -0
  99. package/dist/vite-BEvgU2GY.js +20909 -0
  100. package/dist/vite-CcZmMQ7S.d.ts +476 -0
  101. package/dist/vite.d.ts +2 -2
  102. package/dist/vite.js +2 -2
  103. package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +1565 -0
  104. package/dist/{workspace-Dq08Yn72.js → workspace-6pxkOuxr.js} +361 -230
  105. package/dist/{workspace-Xddf4G1B.d.ts → workspace-BWJQBK1u.d.ts} +4 -3
  106. package/package.json +89 -55
  107. package/dist/collections/client.d.ts +0 -39
  108. package/dist/collections/client.js +0 -137
  109. package/dist/collections.d.ts +0 -59
  110. package/dist/collections.js +0 -159
  111. package/dist/config-Bc3c4Su1.js +0 -7904
  112. package/dist/config-CHLLWklZ.js +0 -36
  113. package/dist/file-Bc1X7pco.js +0 -23
  114. package/dist/glob-CEZKeZFC.js +0 -18
  115. package/dist/hosted-vercel-blob-d6C8ND5j.js +0 -23580
  116. package/dist/lifecycle-LrL3sA4n.js +0 -316
  117. package/dist/metadata-target-B0tOmVW7.js +0 -717
  118. package/dist/path-Cp59koVz.js +0 -139
  119. package/dist/provider-B1yLjCJJ.js +0 -746
  120. package/dist/publish.d.ts +0 -35
  121. package/dist/publish.js +0 -112
  122. package/dist/runtime-options-BsPSv5O7.js +0 -13
  123. package/dist/runtime-type-iEE6BjQJ.js +0 -34
  124. package/dist/shared-DTR1Hhma.js +0 -331
  125. package/dist/store-Dt_Jyys3.js +0 -608
  126. package/dist/vite-BptCrpv2.js +0 -4526
  127. package/dist/vite-CtA9guIM.d.ts +0 -66
@@ -1,13 +1,18 @@
1
- import { _ as workspaceError, a as isExcludedWorkspacePath, i as decodeFile, l as normalizeWorkspacePath, n as contentStreamToBytes, o as matchesAny, r as contentToBytes, s as normalizeSafeWorkspacePath } from "./path-Cp59koVz.js";
2
- import { _ as workspaceSourceRequestDescriptorPath, a as normalizeWorkspaceSources, c as sourceMountIntersectsPath, n as createSourceContext, s as sourceMountContainsPath, u as prepareWorkspaceSource } from "./config-Bc3c4Su1.js";
3
- import { n as createWorkspaceSourceRequestExecution, t as attachWorkspaceSourceRequestExecution } from "./request-execution-B-dSFlGB.js";
4
- import { s as createMemoryWorkspaceStore, t as createWorkspaceStoreFromProvider } from "./provider-B1yLjCJJ.js";
5
- import { n as forwardWorkspaceRevisionMaterializer } from "./store-Dt_Jyys3.js";
1
+ import { s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
2
+ import { a as isExcludedWorkspacePath, f as sha256, i as decodeFile, l as normalizeWorkspacePath, n as contentStreamToBytes, r as contentToBytes, s as matchesAny } from "./path-CNAwN7pw.js";
6
3
  import { t as forwardWorkspaceStoreTarget } from "./target-D4Bqb1eH.js";
7
- import { t as hasRuntimeType } from "./runtime-type-iEE6BjQJ.js";
8
- import { t as searchText } from "./search-BpiCF2Tw.js";
9
- import { a as hasFreshSourceSnapshot, c as readCurrentSourceSnapshot, i as hasCurrentSourceSnapshot, l as readResolvedSourceFile, o as materializeWorkspaceSources, p as statVirtualSourcePath, r as workspaceMetadataTarget, s as materializesCompleteSource, u as searchMaterializedStore } from "./metadata-target-B0tOmVW7.js";
10
- import { minimatch } from "minimatch";
4
+ import { a as normalizeWorkspaceSources, c as sourceMountIntersectsPath, f as prepareWorkspaceSource, n as createSourceContext, s as sourceMountContainsPath, v as workspaceSourceRequestDescriptorPath } from "./config-B7dmzDX3.js";
5
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-DY5GP47p.js";
6
+ import { n as createWorkspaceSourceRequestExecution, t as attachWorkspaceSourceRequestExecution } from "./request-execution-Dk9rY-Yh.js";
7
+ import { t as createMemoryWorkspaceStore } from "./memory-BbwOqDXl.js";
8
+ import { t as copyJsonFileMetadata } from "./file-metadata-CxDy-E2H.js";
9
+ import { d as normalizeHistoryRef, i as createWorkspaceHistory, l as historyConflict, m as createWorkspaceWritePolicy } from "./utils-Blrh4N2n.js";
10
+ import { t as createWorkspaceGlobMatcher } from "./glob--kNYDbfU.js";
11
+ import { t as createWorkspaceStoreFromProvider } from "./provider-kXjfli9u.js";
12
+ import { n as forwardWorkspaceRevisionMaterializer } from "./store-CXgmu-uw.js";
13
+ import { t as searchText } from "./search-CrTmXj5h.js";
14
+ import { C as withWorkspaceStoreMutation, D as readWorkspaceFileOwner, _ as reconcileRemovedStartupSources, b as statVirtualSourcePath, c as workspaceInternalMetadataCapability, f as materializeWorkspaceSources, g as readSourceSnapshotPaths, h as readResolvedSourceFile, l as hasCurrentSourceSnapshot, m as readCurrentSourceSnapshot, n as createWorkspaceMetadataTarget, p as materializesCompleteSource, t as attachWorkspaceMetadataTarget, u as hasFreshSourceSnapshot, v as searchMaterializedStore } from "./metadata-target-DZEZQGHA.js";
15
+ import { hasRuntimeType } from "@vite-hub/runtime/internal/runtime-type";
11
16
  import { noExecutionAuthority } from "@vite-hub/runtime";
12
17
  //#region src/session/scope.ts
13
18
  function isMissingWorkspacePathError(error) {
@@ -19,11 +24,8 @@ function pathInSessionScope(path, paths) {
19
24
  function pathIntersectsSessionScope(path, paths) {
20
25
  return pathInSessionScope(path, paths) || Boolean(paths?.some((scope) => scope.startsWith(`${path}/`)));
21
26
  }
22
- function mkdirPathInSessionScope(path, paths) {
23
- return pathInSessionScope(path, paths) || Boolean(paths?.some((scope) => scope.startsWith(`${path}/`)));
24
- }
25
27
  function assertPathInSessionScope(path, paths, options = {}) {
26
- if (!(options.mkdir ? mkdirPathInSessionScope(path, paths) : pathInSessionScope(path, paths))) throw workspaceError(options.masked ? `[vitehub] Workspace file does not exist: ${path}.` : `[vitehub] Workspace session path ${path} is outside the session scope.`);
28
+ if (!(options.mkdir ? pathIntersectsSessionScope(path, paths) : pathInSessionScope(path, paths))) throw workspaceError(options.masked ? `[vitehub] Workspace file does not exist: ${path}.` : `[vitehub] Workspace session path ${path} is outside the session scope.`);
27
29
  return path;
28
30
  }
29
31
  function assertDiffInsideSessionPaths(diff, paths) {
@@ -65,7 +67,7 @@ function scopedSearchQuery(query, paths, normalizePath) {
65
67
  //#endregion
66
68
  //#region src/session/basic.ts
67
69
  function unsupportedExec() {
68
- throw workspaceError("[vitehub] Workspace exec requires a Box session host. Pass the active Box session to workspace.startSession({ host }).");
70
+ throw workspaceError("[vitehub] Workspace exec requires a Sandbox session host. Pass the active Sandbox session to workspace.startSession({ host }).");
69
71
  }
70
72
  function normalizeSessionPaths(options) {
71
73
  const paths = [...new Set((options?.paths || []).map((path) => normalizeSafeWorkspacePath(path, {
@@ -83,6 +85,7 @@ function normalizeSessionPath(path = "", options = {}) {
83
85
  });
84
86
  }
85
87
  async function createBasicWorkspaceSession(workspace, options) {
88
+ const writeBackDisabled = options?.writeBack === false;
86
89
  const sessionPaths = normalizeSessionPaths(options);
87
90
  const overlay = createMemoryWorkspaceStore();
88
91
  const initialEntries = filterSessionEntries(await workspace.list("", { recursive: true }), sessionPaths);
@@ -134,22 +137,25 @@ async function createBasicWorkspaceSession(workspace, options) {
134
137
  if (!scoped) return [];
135
138
  const roots = (scoped.paths?.length ? scoped.paths : [scoped.cwd || ""]).map((path) => normalizeSessionPath(path, { allowEmpty: true }));
136
139
  const hits = [];
140
+ const limit = scoped.limit ?? 100;
137
141
  for (const entry of filterSessionEntries(await overlay.list("", { recursive: true }), sessionPaths).filter((entry) => entry.type === "file")) {
138
142
  if (!roots.some((root) => !root || entry.path === root || entry.path.startsWith(`${root}/`))) continue;
139
143
  const file = await overlay.readFile(entry.path);
140
144
  if (!file) continue;
141
145
  hits.push(...searchText(entry.path, decodeFile(file.content), {
142
146
  ...scoped,
143
- limit: (scoped.limit || 100) - hits.length
147
+ limit: limit - hits.length
144
148
  }));
145
- if (hits.length >= (scoped.limit || 100)) break;
149
+ if (hits.length >= limit) break;
146
150
  }
147
151
  return hits;
148
152
  },
149
153
  async diff() {
154
+ if (writeBackDisabled) throw workspaceError("[vitehub] Workspace Session diff is unavailable when writeBack is false.");
150
155
  return filterSessionDiff(await overlay.diff(), sessionPaths);
151
156
  },
152
157
  async commit(commitOptions) {
158
+ if (writeBackDisabled) throw workspaceError("[vitehub] Workspace Session commit is unavailable when writeBack is false.");
153
159
  const diff = await overlay.diff();
154
160
  assertDiffInsideSessionPaths(diff, sessionPaths);
155
161
  assertDiffInsideSessionPaths(await workspace.diff(), sessionPaths);
@@ -184,143 +190,6 @@ async function createBasicWorkspaceSession(workspace, options) {
184
190
  };
185
191
  }
186
192
  //#endregion
187
- //#region src/core/rules.ts
188
- function normalizeMaxBytes(value) {
189
- if (value === void 0) return void 0;
190
- if (typeof value === "number") return value;
191
- const match = /^(\d+)(kb|mb)$/.exec(value.toLowerCase());
192
- if (!match) throw new TypeError(`[vitehub] Invalid workspace rule maxBytes value "${value}".`);
193
- const count = Number(match[1]);
194
- return match[2] === "kb" ? count * 1024 : count * 1024 * 1024;
195
- }
196
- function toArray(value) {
197
- if (value === void 0) return [];
198
- return Array.isArray(value) ? value : [value];
199
- }
200
- function mergeHooks(left = {}, right = {}) {
201
- return {
202
- "write:after": [...toArray(left["write:after"]), ...toArray(right["write:after"])],
203
- "write:before": [...toArray(left["write:before"]), ...toArray(right["write:before"])],
204
- "write:error": [...toArray(left["write:error"]), ...toArray(right["write:error"])],
205
- "write:validate": [...toArray(left["write:validate"]), ...toArray(right["write:validate"])]
206
- };
207
- }
208
- function normalizeRules(rules = {}) {
209
- return Object.entries(rules).map(([pattern, rule]) => {
210
- const normalizedPattern = normalizeWorkspacePath(pattern);
211
- return {
212
- ...rule,
213
- maxBytes: normalizeMaxBytes(rule.maxBytes),
214
- pattern: normalizedPattern,
215
- specificity: normalizedPattern.replace(/\*/g, "").length,
216
- validate: toArray(rule.validate)
217
- };
218
- }).sort((left, right) => left.specificity - right.specificity || left.pattern.localeCompare(right.pattern));
219
- }
220
- function normalizePolicy(definition) {
221
- let hooks = {};
222
- let rules = {};
223
- for (const plugin of definition.plugins || []) {
224
- if (!plugin?.id) throw new TypeError("[vitehub] Workspace plugins require an id.");
225
- rules = {
226
- ...rules,
227
- ...plugin.rules
228
- };
229
- hooks = mergeHooks(hooks, plugin.hooks);
230
- }
231
- rules = {
232
- ...rules,
233
- ...definition.rules
234
- };
235
- hooks = mergeHooks(hooks, definition.hooks);
236
- return {
237
- hooks,
238
- rules: normalizeRules(rules)
239
- };
240
- }
241
- function matchRule(policy, path) {
242
- const normalized = normalizeWorkspacePath(path);
243
- let matched;
244
- for (const rule of policy.rules) {
245
- const globstarDirectory = rule.pattern.endsWith("/**") ? rule.pattern.slice(0, -3) : void 0;
246
- if (minimatch(normalized, rule.pattern, { dot: true }) || normalized === globstarDirectory) matched = rule;
247
- }
248
- return matched;
249
- }
250
- function writeAllowed(write, operation, exists) {
251
- if (write === void 0 || write === true) return true;
252
- if (write === false) return false;
253
- if (write === "delete") return operation === "rm";
254
- if (write === "create") return operation !== "rm" && !exists;
255
- if (write === "update") return operation === "writeFile" && exists;
256
- return true;
257
- }
258
- function sizeOf(content) {
259
- return content === void 0 ? 0 : contentToBytes(content).byteLength;
260
- }
261
- function assertRuleAllows(input) {
262
- const rule = input.rule;
263
- if (!rule) return;
264
- const exists = Boolean(input.previous);
265
- if (!writeAllowed(rule.write, input.operation, exists)) throw workspaceError(`[vitehub] Workspace rule "${rule.pattern}" does not allow ${input.operation} for ${input.path}.`);
266
- if (rule.maxBytes !== void 0 && sizeOf(input.content) > rule.maxBytes) throw workspaceError(`[vitehub] Workspace rule "${rule.pattern}" limits writes to ${rule.maxBytes} bytes: ${input.path}.`);
267
- if (rule.mediaType && input.mediaType) {
268
- if (!(Array.isArray(rule.mediaType) ? rule.mediaType : [rule.mediaType]).includes(input.mediaType)) throw workspaceError(`[vitehub] Workspace rule "${rule.pattern}" does not allow media type ${input.mediaType}: ${input.path}.`);
269
- }
270
- }
271
- async function runHooks(hooks, name, input) {
272
- for (const hook of toArray(hooks[name])) await hook(input);
273
- }
274
- async function runValidators(validators, input) {
275
- let current = input;
276
- for (const validate of validators) {
277
- const result = await validate(current);
278
- if (result === false) throw workspaceError(`[vitehub] Workspace validator rejected ${current.operation} for ${current.path}.`);
279
- if (typeof result === "object" && result !== null) current = result;
280
- }
281
- return current;
282
- }
283
- function createWorkspaceWritePolicy(definition) {
284
- const policy = normalizePolicy(definition);
285
- return {
286
- async before(input) {
287
- let current = {
288
- ...input,
289
- rule: matchRule(policy, input.path)
290
- };
291
- await runHooks(policy.hooks, "write:before", current);
292
- assertRuleAllows(current);
293
- if (current.rule?.validate.length) current = await runValidators(current.rule.validate, current);
294
- await runHooks(policy.hooks, "write:validate", current);
295
- return current;
296
- },
297
- async after(input) {
298
- await runHooks(policy.hooks, "write:after", input);
299
- },
300
- async error(input, error) {
301
- for (const hook of toArray(policy.hooks["write:error"])) await hook({
302
- ...input,
303
- error
304
- });
305
- }
306
- };
307
- }
308
- function resolveWorkspaceAutoCommit(definition, diff) {
309
- if (!diff.entries.length) return;
310
- if (definition.commit === true || typeof definition.commit === "string") return {
311
- message: (typeof definition.commit === "string" ? definition.commit.trim() : "") || `chore: update ${definition.name} workspace`,
312
- paths: diff.entries.map((entry) => normalizeWorkspacePath(entry.path))
313
- };
314
- const policy = normalizePolicy(definition);
315
- const paths = diff.entries.map((entry) => normalizeWorkspacePath(entry.path));
316
- const rules = paths.map((path) => matchRule(policy, path));
317
- if (!rules.length || rules.some((rule) => !rule?.commit)) return;
318
- return {
319
- message: rules.map((rule) => rule?.commit).find((commit) => typeof commit === "string" && commit.trim().length > 0)?.trim() || `chore: update ${definition.name} workspace`,
320
- paths
321
- };
322
- }
323
- //#endregion
324
193
  //#region src/sources/resolver.ts
325
194
  function resolveWorkspacePath(definition, path) {
326
195
  const workspacePath = normalizeSafeWorkspacePath(path, { allowEmpty: true });
@@ -353,8 +222,12 @@ function createSourceResolution(source, workspacePath, sourcePath) {
353
222
  }
354
223
  //#endregion
355
224
  //#region src/sources/sync-state.ts
356
- function sourceSyncMetaKey(sourceKey) {
357
- return `source:${sourceKey}:sync`;
225
+ function sourceSyncMetaKey(sourceKey, workspace) {
226
+ return workspace ? `workspace:${workspace}:source:${sourceKey}:sync` : `source:${sourceKey}:sync`;
227
+ }
228
+ /** Identifies the durable metadata record owned by Source Sync. */
229
+ function isWorkspaceSourceSyncMetaKey(key) {
230
+ return [key.toLowerCase(), normalizeWorkspacePath(key).toLowerCase()].some((form) => /^(?:workspace:.+:)?source:.*:sync$/.test(form));
358
231
  }
359
232
  function readWorkspaceSourceSyncState(value) {
360
233
  if (!value || typeof value !== "object" || Array.isArray(value)) return;
@@ -366,9 +239,30 @@ function readWorkspaceSourceSyncState(value) {
366
239
  const entry = state.paths[path];
367
240
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) return;
368
241
  if (typeof entry.digest !== "string" || typeof entry.sourcePath !== "string") return;
242
+ if (entry.mountPath !== void 0 && !hasRuntimeType(entry.mountPath, "string")) return;
243
+ }
244
+ if (state.claims !== void 0) {
245
+ if (!state.claims || !hasRuntimeType(state.claims, "object") || Array.isArray(state.claims)) return;
246
+ for (const [path, claims] of Object.entries(state.claims)) {
247
+ if (!state.paths[path] || !Array.isArray(claims) || claims.length === 0) return;
248
+ const mounts = /* @__PURE__ */ new Set();
249
+ for (const claim of claims) {
250
+ if (!claim || !hasRuntimeType(claim, "object") || Array.isArray(claim)) return;
251
+ if (!hasRuntimeType(claim.digest, "string") || !hasRuntimeType(claim.sourcePath, "string") || !hasRuntimeType(claim.mountPath, "string")) return;
252
+ if (mounts.has(claim.mountPath)) return;
253
+ mounts.add(claim.mountPath);
254
+ }
255
+ }
369
256
  }
370
257
  return state;
371
258
  }
259
+ /** Legacy records contain one claim per path; new records retain overlapping mounts. */
260
+ function sourceSyncPathClaims(state, path) {
261
+ return state.claims?.[path] ?? [{
262
+ ...state.paths[path],
263
+ mountPath: state.paths[path].mountPath ?? state.mountPath
264
+ }];
265
+ }
372
266
  function workspaceSourceSyncStateEquals(left, right) {
373
267
  if (!left) return false;
374
268
  return JSON.stringify(canonicalSourceSyncState(left)) === JSON.stringify(canonicalSourceSyncState(right));
@@ -376,6 +270,7 @@ function workspaceSourceSyncStateEquals(left, right) {
376
270
  function canonicalSourceSyncState(state) {
377
271
  return {
378
272
  configHash: state.configHash,
273
+ claims: state.claims,
379
274
  mountPath: state.mountPath,
380
275
  paths: Object.fromEntries(Object.entries(state.paths).sort(([left], [right]) => left.localeCompare(right))),
381
276
  source: state.source
@@ -383,6 +278,25 @@ function canonicalSourceSyncState(state) {
383
278
  }
384
279
  //#endregion
385
280
  //#region src/sources/view.ts
281
+ function assertPublicFileMetadata(path, metadata) {
282
+ metadata = copyJsonFileMetadata(path, metadata);
283
+ if (metadata && Object.hasOwn(metadata, "source")) throw workspaceError(`[vitehub] Invalid Workspace metadata for ${path}. metadata.source is reserved for Source materialization.`);
284
+ return metadata;
285
+ }
286
+ /**
287
+ * Proof that one Source view checked one normalized Workspace path for writes.
288
+ * Only `assertWritable` creates a grant. A grant is request-scoped. Do not persist it.
289
+ */
290
+ var WorkspaceSourceWriteGrant = class {
291
+ #path;
292
+ constructor(path) {
293
+ this.#path = path;
294
+ Object.freeze(this);
295
+ }
296
+ get path() {
297
+ return this.#path;
298
+ }
299
+ };
386
300
  const materializationByStore = /* @__PURE__ */ new WeakMap();
387
301
  async function invalidateWorkspaceSourceMaterialization(definition, store, sourceKeys) {
388
302
  const state = materializationByStore.get(store)?.get(definition);
@@ -421,6 +335,8 @@ function createWorkspaceSourceView(definition, store, options = {}) {
421
335
  const descriptorSources = allSources.filter((source) => source.requestDescriptor);
422
336
  const writePolicy = createWorkspaceWritePolicy(definition);
423
337
  const prepareBySource = /* @__PURE__ */ new Map();
338
+ const priorPathsBySource = /* @__PURE__ */ new Map();
339
+ let removedSourceReconciliation;
424
340
  const sourceContexts = /* @__PURE__ */ new Map();
425
341
  let materializationByDefinition = materializationByStore.get(store);
426
342
  if (!materializationByDefinition) {
@@ -435,8 +351,8 @@ function createWorkspaceSourceView(definition, store, options = {}) {
435
351
  };
436
352
  if (!materializationByDefinition.has(definition)) materializationByDefinition.set(definition, materializationState);
437
353
  const { completedSources, generationBySource, materializedSources, pendingBySource } = materializationState;
354
+ const reusedStartupSources = /* @__PURE__ */ new Set();
438
355
  const uncachedMaterializedSources = /* @__PURE__ */ new Set();
439
- const persistsSourceSnapshots = Boolean(store.getMeta && store.setMeta);
440
356
  function getSourceContext(source) {
441
357
  let context = sourceContexts.get(source.key);
442
358
  if (!context) {
@@ -521,18 +437,45 @@ function createWorkspaceSourceView(definition, store, options = {}) {
521
437
  function usesLiveProvider(source) {
522
438
  return Boolean(source.livePaths && source.materialize !== "startup");
523
439
  }
524
- function getLazySourcesForPath(path) {
525
- return sources.filter((source) => sourceMountIntersectsPath(source, path));
440
+ async function getLazySourcesForPath(path) {
441
+ if (!removedSourceReconciliation && sources.some((source) => !source.mountPath && source.materialize === "startup" && source.source.name === "file" && source.probeKeys?.length)) removedSourceReconciliation = reconcileRemovedStartupSources(definition.name, store, allSources.filter((source) => source.materialize === "startup")).catch((error) => {
442
+ removedSourceReconciliation = void 0;
443
+ throw error;
444
+ });
445
+ await removedSourceReconciliation;
446
+ const normalized = normalizeWorkspacePath(path);
447
+ const intersects = (filePath) => !normalized || normalized === filePath || filePath.startsWith(`${normalized}/`);
448
+ const matched = [];
449
+ for (const source of sources) {
450
+ if (source.mountPath || source.materialize !== "startup" || source.source.name !== "file" || !source.probeKeys?.length) {
451
+ if (sourceMountIntersectsPath(source, normalized)) matched.push(source);
452
+ continue;
453
+ }
454
+ if (source.probeKeys.some((key) => intersects(normalizeWorkspacePath(key)))) {
455
+ matched.push(source);
456
+ continue;
457
+ }
458
+ let priorPaths = priorPathsBySource.get(source.key);
459
+ if (!priorPaths) {
460
+ priorPaths = readSourceSnapshotPaths(store, definition.name, source.key).catch((error) => {
461
+ priorPathsBySource.delete(source.key);
462
+ throw error;
463
+ });
464
+ priorPathsBySource.set(source.key, priorPaths);
465
+ }
466
+ if ((await priorPaths).some(intersects)) matched.push(source);
467
+ }
468
+ return matched;
526
469
  }
527
470
  async function ensurePrepared(sourceKey) {
528
471
  const source = sources.find((item) => item.key === sourceKey);
529
472
  if (!source) return;
530
473
  if (source.materialize === "startup" && completedSources.has(sourceKey)) {
531
- if (!persistsSourceSnapshots || await hasCurrentSourceSnapshot(store, source)) return;
474
+ if (await hasCurrentSourceSnapshot(store, definition.name, source, options.reuseStartupSnapshots, options.reuseStartupSnapshots ? sources : void 0)) return;
532
475
  completedSources.delete(sourceKey);
533
476
  }
534
- if (source.materialize === "startup" && options.reuseStartupSnapshots && await hasCurrentSourceSnapshot(store, source)) {
535
- completedSources.add(sourceKey);
477
+ if (source.materialize === "startup" && options.reuseStartupSnapshots && await hasCurrentSourceSnapshot(store, definition.name, source, true, sources)) {
478
+ reusedStartupSources.add(sourceKey);
536
479
  return;
537
480
  }
538
481
  let pending = prepareBySource.get(sourceKey);
@@ -547,7 +490,7 @@ function createWorkspaceSourceView(definition, store, options = {}) {
547
490
  }
548
491
  async function materializeSerialized(options = {}) {
549
492
  const requestedPath = normalizeWorkspacePath(options.path || "");
550
- const selectedSources = allSources.filter((source) => source.materialize === "lazy" || source.materialize === "startup" || source.materialize === "build" && Boolean(requestedPath)).filter((source) => (!options.sources?.length || options.sources.includes(source.key)) && sourceMountIntersectsPath(source, requestedPath));
493
+ const selectedSources = allSources.filter((source) => source.materialize === "lazy" || source.materialize === "startup" || source.materialize === "build" && Boolean(requestedPath)).filter((source) => (options.sources === void 0 || options.sources.includes(source.key)) && sourceMountIntersectsPath(source, requestedPath));
551
494
  const predecessors = selectedSources.flatMap((source) => {
552
495
  const pending = pendingBySource.get(source.key);
553
496
  return pending ? [pending.tail] : [];
@@ -575,7 +518,10 @@ function createWorkspaceSourceView(definition, store, options = {}) {
575
518
  for (const source of selectedSources) {
576
519
  if (!materializesCompleteSource(source, options)) continue;
577
520
  materializedSources.delete(source.key);
578
- if (source.materialize === "startup") completedSources.delete(source.key);
521
+ if (source.materialize === "startup") {
522
+ completedSources.delete(source.key);
523
+ reusedStartupSources.delete(source.key);
524
+ }
579
525
  }
580
526
  let result;
581
527
  try {
@@ -617,9 +563,10 @@ function createWorkspaceSourceView(definition, store, options = {}) {
617
563
  });
618
564
  return await current;
619
565
  }
620
- async function ensureMaterialized(sourceKey) {
566
+ async function ensureMaterialized(sourceKey, verifyRootOwnership = true) {
621
567
  const source = sources.find((item) => item.key === sourceKey);
622
568
  if (!source) return;
569
+ const verifyOwnership = options.reuseStartupSnapshots ? true : verifyRootOwnership || source.mountPath || !sources.some((item) => !item.mountPath && item.materialize === "lazy") ? "workspace" : false;
623
570
  const isUncachedLazySource = source.materialize === "lazy" && source.cache === false;
624
571
  const pending = pendingBySource.get(sourceKey);
625
572
  if (pending?.fullSource) {
@@ -633,13 +580,16 @@ function createWorkspaceSourceView(definition, store, options = {}) {
633
580
  }
634
581
  if (isUncachedLazySource ? uncachedMaterializedSources.has(sourceKey) : materializedSources.has(sourceKey)) {
635
582
  const maxAge = source.cache && source.cache.maxAge;
636
- if (source.materialize !== "lazy" || !Number.isFinite(maxAge) || await hasFreshSourceSnapshot(store, source)) return;
583
+ if (source.materialize === "startup" ? await hasCurrentSourceSnapshot(store, definition.name, source, verifyOwnership, options.reuseStartupSnapshots ? sources : void 0) : !Number.isFinite(maxAge) || await hasFreshSourceSnapshot(store, definition.name, source)) return;
637
584
  materializedSources.delete(sourceKey);
638
585
  }
639
- if (completedSources.has(sourceKey)) {
640
- if (!persistsSourceSnapshots || await hasCurrentSourceSnapshot(store, source)) return;
586
+ if (completedSources.has(sourceKey) || reusedStartupSources.has(sourceKey)) {
587
+ if (await hasCurrentSourceSnapshot(store, definition.name, source, verifyOwnership, options.reuseStartupSnapshots ? sources : void 0)) return;
641
588
  completedSources.delete(sourceKey);
589
+ reusedStartupSources.delete(sourceKey);
642
590
  }
591
+ const recovery = pendingBySource.get(sourceKey);
592
+ if (recovery && recovery !== pending) return await ensureMaterialized(sourceKey, verifyRootOwnership);
643
593
  await materializeSerialized({ sources: [sourceKey] });
644
594
  }
645
595
  async function ensureMaterializedSources(items = sources) {
@@ -647,18 +597,23 @@ function createWorkspaceSourceView(definition, store, options = {}) {
647
597
  }
648
598
  async function listSourceAware(path = "", options = {}) {
649
599
  const normalized = normalizeWorkspacePath(path);
600
+ if (!isDescriptorPath(normalized)) for (const source of await getLazySourcesForPath(normalized)) {
601
+ if (source.materialize !== "startup" || isExcludedWorkspacePath(source.mountPath, options.exclude)) continue;
602
+ await ensurePrepared(source.key);
603
+ if (!usesLiveProvider(source)) await ensureMaterialized(source.key);
604
+ }
650
605
  const storeEntries = isDescriptorPath(normalized) ? [] : await store.list(path, options);
651
606
  const result = new Map(storeEntries.map((entry) => [entry.path, entry]));
652
607
  for (const entry of descriptorPathEntries(path, options)) if (!isExcludedWorkspacePath(entry.path, options.exclude)) result.set(entry.path, entry);
653
608
  if (isDescriptorPath(normalized)) return [...result.values()].sort((left, right) => left.path.localeCompare(right.path));
654
- for (const source of getLazySourcesForPath(path)) {
609
+ for (const source of await getLazySourcesForPath(path)) {
655
610
  if (isExcludedWorkspacePath(source.mountPath, options.exclude)) continue;
656
611
  await ensurePrepared(source.key);
657
612
  if (usesLiveProvider(source)) {
658
613
  await pruneLiveSourceStoreEntries(result, source);
659
614
  continue;
660
615
  }
661
- if (!path && options.recursive && !await hasCurrentSourceSnapshot(store, source)) {
616
+ if (!normalized && options.recursive && source.materialize !== "startup" && !await hasCurrentSourceSnapshot(store, definition.name, source)) {
662
617
  if ([...result.keys()].some((key) => sourceMountContainsPath(source, key))) {
663
618
  const allowed = await currentSourceTreePaths(source, getSourceContext(source));
664
619
  for (const key of result.keys()) if (sourceMountContainsPath(source, key) && !allowed.has(key)) result.delete(key);
@@ -675,10 +630,11 @@ function createWorkspaceSourceView(definition, store, options = {}) {
675
630
  });
676
631
  continue;
677
632
  }
678
- if (sourceMountContainsPath(source, path) || !source.mountPath && path) {
633
+ if (source.materialize === "startup") continue;
634
+ else if (sourceMountContainsPath(source, path) || !source.mountPath && normalized) {
679
635
  await ensureMaterialized(source.key);
680
636
  for (const entry of await store.list(path, options)) result.set(entry.path, entry);
681
- } else if (!path && !result.has(source.mountPath)) result.set(source.mountPath, {
637
+ } else if (!normalized && !result.has(source.mountPath)) result.set(source.mountPath, {
682
638
  path: source.mountPath,
683
639
  type: "directory"
684
640
  });
@@ -701,6 +657,11 @@ function createWorkspaceSourceView(definition, store, options = {}) {
701
657
  list.push(resolution.workspacePath);
702
658
  sourcePaths.set(resolution.sourceKey, list);
703
659
  }
660
+ for (const source of sources) {
661
+ if (source.materialize !== "startup" || !requestedPaths.some((path) => sourceMountIntersectsPath(source, normalizeWorkspacePath(path)))) continue;
662
+ await ensurePrepared(source.key);
663
+ await ensureMaterialized(source.key);
664
+ }
704
665
  const results = await searchMaterializedStore(store, {
705
666
  ...query,
706
667
  paths: storePaths.filter(Boolean).length ? storePaths.filter(Boolean) : void 0,
@@ -752,14 +713,42 @@ function createWorkspaceSourceView(definition, store, options = {}) {
752
713
  async function previousStat(path) {
753
714
  return await store.stat(path);
754
715
  }
755
- async function materializeRootSourceForPath(path) {
716
+ async function materializeRootStartupSources(verifyRootOwnership = true) {
717
+ for (const source of sources.filter((source) => !source.mountPath && source.materialize === "startup")) {
718
+ await ensurePrepared(source.key);
719
+ await ensureMaterialized(source.key, verifyRootOwnership);
720
+ }
721
+ }
722
+ async function readOwnedRootStartupFile(path, sourceKey) {
723
+ if (!sources.some((source) => !source.mountPath && source.materialize === "startup")) return;
724
+ const owner = await readWorkspaceFileOwner(store, path);
725
+ if (owner?.workspace !== definition.name || !owner.digest) return;
726
+ if (sourceKey && owner.source !== sourceKey) return;
727
+ const source = sources.find((source) => !source.mountPath && source.materialize === "startup" && source.key === owner.source);
728
+ if (!source) return;
729
+ if ((await store.stat(path))?.type !== "file") return;
730
+ const file = await store.readFile(path);
731
+ if (!file) return;
732
+ if (file.metadata?.source && (file.metadata.workspaceSourceOwner !== definition.name || file.metadata.source !== owner.source)) return;
733
+ const snapshot = await readCurrentSourceSnapshot(store, definition.name, source);
734
+ if (snapshot?.status !== "ready" || !Object.hasOwn(snapshot.items || {}, path)) return;
735
+ if (await sha256(file.content) === owner.digest) return file;
736
+ }
737
+ async function materializeRootSourceForPath(path, verifyRootOwnership = true) {
756
738
  for (const source of sources.filter((source) => !source.mountPath)) {
757
739
  await ensurePrepared(source.key);
758
- await ensureMaterialized(source.key);
759
- if ((await store.readFile(path))?.metadata?.source === source.key) return source;
740
+ await ensureMaterialized(source.key, verifyRootOwnership);
741
+ if (source.materialize === "startup") {
742
+ if (await readOwnedRootStartupFile(path, source.key)) return source;
743
+ } else if ((await store.stat(path))?.metadata?.source === source.key) return source;
760
744
  }
761
745
  }
762
746
  async function isSourceBackedStorePath(path) {
747
+ if (!allSources.length) return false;
748
+ for (const source of allSources) {
749
+ const snapshot = await readCurrentSourceSnapshot(store, definition.name, source);
750
+ if (Object.keys(snapshot?.items || {}).some((item) => item === path || !path || item.startsWith(`${path}/`))) return true;
751
+ }
763
752
  const file = await store.readFile(path);
764
753
  if (typeof file?.metadata?.source === "string" && allSources.some((source) => source.key === file.metadata?.source)) return true;
765
754
  if ((await store.stat(path))?.type !== "directory") return false;
@@ -774,13 +763,18 @@ function createWorkspaceSourceView(definition, store, options = {}) {
774
763
  async function isSyncedStatePath(path) {
775
764
  if (!store.getMeta) return false;
776
765
  for (const source of syncSources) {
777
- const state = readWorkspaceSourceSyncState(await store.getMeta(sourceSyncMetaKey(source.key)));
766
+ const state = readWorkspaceSourceSyncState(await store.getMeta(sourceSyncMetaKey(source.key, definition.name)));
778
767
  if (!state) continue;
779
768
  if (state.paths[path]) return true;
780
769
  if (Object.keys(state.paths).some((item) => item.startsWith(`${path}/`))) return true;
781
770
  }
782
771
  return false;
783
772
  }
773
+ async function assertWritableCurrentPath(path) {
774
+ if (isDescriptorPath(path)) throw workspaceError(`[vitehub] Source-backed workspace paths are read-only: ${path}.`);
775
+ const resolution = resolveWorkspacePath(definition, path);
776
+ if (resolution.type === "source" || isLazySourcePath(resolution.workspacePath) || isSyncSourceMountPath(resolution.workspacePath) || await isSyncedStatePath(resolution.workspacePath) || await isSourceBackedStorePath(resolution.workspacePath)) throw workspaceError(`[vitehub] Source-backed workspace paths are read-only: ${path}.`);
777
+ }
784
778
  async function assertWritableResolvedStorePath(path, workspacePath, type) {
785
779
  assertWritableStorePath(path, workspacePath, type);
786
780
  await materializeRootSourceForPath(workspacePath);
@@ -789,61 +783,164 @@ function createWorkspaceSourceView(definition, store, options = {}) {
789
783
  async function assertWritablePath(path) {
790
784
  if (isDescriptorPath(normalizeWorkspacePath(path))) throw workspaceError(`[vitehub] Source-backed workspace paths are read-only: ${path}.`);
791
785
  const resolution = resolveWorkspacePath(definition, path);
792
- if (isDescriptorPath(resolution.workspacePath)) throw workspaceError(`[vitehub] Source-backed workspace paths are read-only: ${path}.`);
786
+ if (isDescriptorPath(resolution.workspacePath) || allSources.some((source) => (source.materialize === "lazy" || source.materialize === "startup") && sourceMountContainsPath(source, resolution.workspacePath))) throw workspaceError(`[vitehub] Source-backed workspace paths are read-only: ${path}.`);
793
787
  await assertWritableResolvedStorePath(path, resolution.workspacePath, resolution.type);
794
788
  return resolution;
795
789
  }
790
+ const writeGrants = /* @__PURE__ */ new WeakMap();
791
+ async function grantWritablePath(path) {
792
+ const { workspacePath } = await assertWritablePath(path);
793
+ const grant = new WorkspaceSourceWriteGrant(workspacePath);
794
+ writeGrants.set(grant, workspacePath);
795
+ return grant;
796
+ }
797
+ async function grantPolicyPath(path) {
798
+ return await grantWritablePath(path);
799
+ }
800
+ function requireWriteGrant(write) {
801
+ return async (grant, path, ...args) => {
802
+ const workspacePath = normalizeWorkspacePath(path);
803
+ if (writeGrants.get(grant) !== workspacePath) throw workspaceError(`[vitehub] Workspace write to ${path} requires a Source write grant for that path.`);
804
+ return await withWorkspaceStoreMutation(store, async () => {
805
+ await assertWritableCurrentPath(workspacePath);
806
+ return await write(workspacePath, ...args);
807
+ });
808
+ };
809
+ }
810
+ function requireRebaseGrants(rebase) {
811
+ return async (grants, options) => {
812
+ const takeRemote = options?.takeRemote ?? [];
813
+ if (!Array.isArray(grants) || grants.length !== takeRemote.length) throw workspaceError("[vitehub] Workspace rebase requires one Source write grant for each takeRemote path.");
814
+ for (const [index, path] of takeRemote.entries()) {
815
+ const grant = grants[index];
816
+ const normalizedPath = normalizeWorkspacePath(path);
817
+ if (!grant || writeGrants.get(grant) !== normalizedPath) throw workspaceError(`[vitehub] Workspace rebase to take remote ${path} requires a Source write grant for that path.`);
818
+ if (allSources.some((source) => (source.materialize === "lazy" || source.materialize === "startup") && sourceMountIntersectsPath(source, normalizedPath))) throw workspaceError(`[vitehub] Source-backed workspace paths are read-only: ${path}.`);
819
+ }
820
+ await withWorkspaceStoreMutation(store, async () => {
821
+ for (const grant of grants) await assertWritableCurrentPath(grant.path);
822
+ await rebase(options?.takeRemote ? {
823
+ ...options,
824
+ takeRemote: grants.map((grant) => grant.path)
825
+ } : options);
826
+ });
827
+ };
828
+ }
829
+ const grantedStore = {
830
+ mkdir: requireWriteGrant(async (path, options) => await store.mkdir(path, options)),
831
+ rm: requireWriteGrant(async (path, options) => await store.rm(path, options)),
832
+ writeFile: requireWriteGrant(async (path, file, ifDigest) => {
833
+ if (ifDigest === void 0) return await store.writeFile(path, {
834
+ ...file,
835
+ path
836
+ });
837
+ if (!store.writeFileConditional) throw workspaceError("[vitehub] This Workspace Store does not support conditional writes.");
838
+ await store.writeFileConditional(path, {
839
+ ...file,
840
+ path
841
+ }, ifDigest);
842
+ })
843
+ };
796
844
  return {
845
+ requireHistoryGrants(history, apply = (options) => history.commit(options)) {
846
+ return async (grants, options) => {
847
+ return await withWorkspaceStoreMutation(store, async () => {
848
+ const ref = normalizeHistoryRef(options.ref);
849
+ const head = await history.head({ ref });
850
+ if ((head?.id ?? null) !== options.ifHead) throw historyConflict(ref, options.ifHead, head?.id ?? null);
851
+ const forkRef = head || options.startFrom ? void 0 : await history.forksFrom?.(ref);
852
+ const startId = head?.id ?? options.startFrom ?? (forkRef ? (await history.head({ ref: forkRef }))?.id : void 0);
853
+ const previous = startId ? await history.open(startId) : void 0;
854
+ const entries = /* @__PURE__ */ new Map();
855
+ for (const entry of previous ? await previous.list("", { recursive: true }) : []) if (entry.type === "file") entries.set(entry.path, entry);
856
+ const historyDigest = async (content) => history.digest ? await history.digest(contentToBytes(content)) : await sha256(content);
857
+ const digestOf = async (path, entry) => entry.digest ?? await historyDigest(await previous.readFile(path, { encoding: "binary" }));
858
+ const sameFile = async (file, digest, entry, compute = historyDigest) => digest === await compute(file.content) && (file.mediaType === void 0 || entry.mediaType === file.mediaType) && (file.metadata === void 0 || JSON.stringify(entry.metadata) === JSON.stringify(file.metadata));
859
+ const next = (path) => {
860
+ if (options.files) return options.files[path];
861
+ if (options.changes.put && Object.hasOwn(options.changes.put, path)) return options.changes.put[path];
862
+ return options.changes.delete?.includes(path) ? void 0 : entries.get(path);
863
+ };
864
+ const candidates = options.files ? /* @__PURE__ */ new Set([...Object.keys(options.files), ...entries.keys()]) : /* @__PURE__ */ new Set([...Object.keys(options.changes.put ?? {}), ...options.changes.delete ?? []]);
865
+ const paths = [];
866
+ for (const path of candidates) {
867
+ const file = next(path);
868
+ const before = entries.get(path);
869
+ if (!file || !before || !("content" in file) || !await sameFile(file, await digestOf(path, before), before)) paths.push(path);
870
+ }
871
+ const authorized = new Set(grants.map((grant) => writeGrants.get(grant)));
872
+ if (authorized.has(void 0) || paths.some((path) => !authorized.has(path))) throw workspaceError("[vitehub] History publication requires a Source write grant for every affected path.");
873
+ for (const path of paths) await assertWritableCurrentPath(path);
874
+ if (history === store.history && ref === "main" && allSources.length) for (const entry of await store.list("", { recursive: true })) {
875
+ if (entry.type !== "file" || !allSources.some((source) => source.key === entry.metadata?.source)) continue;
876
+ const file = next(entry.path);
877
+ const digest = entry.digest ?? await sha256((await store.readFile(entry.path)).content);
878
+ if (!(file && ("content" in file ? await sameFile(file, digest, entry, sha256) : await digestOf(entry.path, file) === digest && file.mediaType === entry.mediaType && JSON.stringify(file.metadata) === JSON.stringify(entry.metadata)))) await assertWritableCurrentPath(entry.path);
879
+ }
880
+ return await apply({
881
+ ...options,
882
+ ref,
883
+ startFrom: head ? options.startFrom : startId
884
+ });
885
+ });
886
+ };
887
+ },
797
888
  async assertWritable(path) {
798
- await assertWritablePath(path);
889
+ return await grantWritablePath(path);
799
890
  },
891
+ assertWritableCurrentPath,
892
+ requireWriteGrant,
893
+ requireRebaseGrants,
800
894
  async readFile(path, options) {
801
895
  const descriptorSource = descriptorSourceForPath(normalizeWorkspacePath(path));
802
896
  if (descriptorSource) return decodeFile(descriptorContent(descriptorSource), options);
803
897
  const resolution = resolveWorkspacePath(definition, path);
804
898
  if (resolution.type === "source") {
805
899
  await ensurePrepared(resolution.sourceKey);
806
- if (isLiveSource(resolution.sourceKey)) return decodeFile(await sourceItemContent(await resolution.source.source.getItem(resolution.sourcePath, getSourceContext(resolution.source))), options);
807
- if (resolution.source.materialize === "startup" && !completedSources.has(resolution.sourceKey) && !materializedSources.has(resolution.sourceKey)) await ensureMaterialized(resolution.sourceKey);
900
+ if (isLiveSource(resolution.sourceKey)) {
901
+ const item = await resolution.source.source.getItem(resolution.sourcePath, getSourceContext(resolution.source));
902
+ return decodeFile(await sourceItemContent(item), options);
903
+ }
904
+ if (resolution.source.materialize === "startup") await ensureMaterialized(resolution.sourceKey);
808
905
  const cacheMaxAge = resolution.source.cache && resolution.source.cache.maxAge;
809
906
  let shouldRefreshCachedLazy = false;
810
- if (resolution.source.materialize === "lazy" && Number.isFinite(cacheMaxAge)) shouldRefreshCachedLazy = materializedSources.has(resolution.sourceKey) || Boolean(await readCurrentSourceSnapshot(store, resolution.source));
907
+ if (resolution.source.materialize === "lazy" && Number.isFinite(cacheMaxAge)) shouldRefreshCachedLazy = materializedSources.has(resolution.sourceKey) || Boolean(await readCurrentSourceSnapshot(store, definition.name, resolution.source));
811
908
  if (shouldRefreshCachedLazy) await ensureMaterialized(resolution.sourceKey);
812
909
  const file = await store.readFile(resolution.workspacePath);
813
910
  if (file) return decodeFile(file.content, options);
814
911
  await ensureMaterialized(resolution.sourceKey);
815
912
  return await readResolvedSourceFile(resolution, store, sourceContext, options);
816
913
  }
817
- await materializeRootSourceForPath(resolution.workspacePath);
914
+ await materializeRootStartupSources(false);
915
+ const startupFile = await readOwnedRootStartupFile(resolution.workspacePath);
916
+ if (startupFile) return decodeFile(startupFile.content, options);
917
+ if (!await materializeRootSourceForPath(resolution.workspacePath, false)) for (const source of sources.filter((source) => !source.mountPath && source.materialize === "startup")) await ensureMaterialized(source.key, true);
818
918
  const file = await store.readFile(resolution.workspacePath);
819
919
  if (!file) throw workspaceError(`[vitehub] Workspace file does not exist: ${path}.`);
820
920
  return decodeFile(file.content, options);
821
921
  },
822
922
  async writeFile(path, content, options) {
823
- const resolution = await assertWritablePath(path);
923
+ const metadata = assertPublicFileMetadata(path, options?.metadata);
924
+ const requested = await grantWritablePath(path);
824
925
  const input = await writePolicy.before({
825
926
  content,
826
927
  mediaType: options?.mediaType,
827
- metadata: options?.metadata,
928
+ metadata,
828
929
  operation: "writeFile",
829
- path: resolution.workspacePath,
830
- previous: await previousStat(resolution.workspacePath),
930
+ path: requested.path,
931
+ previous: await previousStat(requested.path),
831
932
  workspace: definition.name
832
933
  });
833
934
  try {
834
- if (options?.preservePath && input.path !== resolution.workspacePath) throw workspaceError(`[vitehub] Workspace validator cannot rewrite preserved path: ${resolution.workspacePath} -> ${input.path}.`);
835
- const file = {
836
- path: input.path,
935
+ if (options?.preservePath && input.path !== requested.path) throw workspaceError(`[vitehub] Workspace validator cannot rewrite preserved path: ${requested.path} -> ${input.path}.`);
936
+ const grant = await grantPolicyPath(input.path);
937
+ await grantedStore.writeFile(grant, input.path, {
837
938
  content: input.content ?? content,
838
939
  mediaType: input.mediaType,
839
- metadata: input.metadata
840
- };
841
- if (options?.ifDigest !== void 0) {
842
- if (!store.writeFileConditional) throw workspaceError("[vitehub] This Workspace Store does not support conditional writes.");
843
- await store.writeFileConditional(input.path, file, options.ifDigest);
844
- } else await store.writeFile(input.path, file);
940
+ metadata: assertPublicFileMetadata(input.path, input.metadata)
941
+ }, options?.ifDigest);
845
942
  await writePolicy.after(input);
846
- return input.path;
943
+ return grant.path;
847
944
  } catch (error) {
848
945
  await writePolicy.error(input, error);
849
946
  throw error;
@@ -854,14 +951,17 @@ function createWorkspaceSourceView(definition, store, options = {}) {
854
951
  },
855
952
  async glob(pattern, options) {
856
953
  const patterns = Array.isArray(pattern) ? pattern : [pattern];
954
+ const { cwd, matches } = createWorkspaceGlobMatcher(patterns, options);
857
955
  await ensurePreparedSources();
858
956
  await ensureMaterializedSources(sources.filter((source) => !usesLiveProvider(source)));
859
957
  const result = /* @__PURE__ */ new Map();
860
- for (const entry of await store.glob(patterns, options)) result.set(entry.path, entry);
861
- for (const entry of descriptorPathEntries("", { recursive: true })) if (entry.type === "file" && patterns.some((pattern) => matchesAny(entry.path, pattern))) result.set(entry.path, entry);
958
+ if (cwd !== ".vitehub/sources") {
959
+ for (const entry of await store.glob(patterns, options)) if (matches(entry.path)) result.set(entry.path, entry);
960
+ }
961
+ for (const entry of descriptorPathEntries(cwd, { recursive: true })) if (entry.type === "file" && matches(entry.path)) result.set(entry.path, entry);
862
962
  for (const source of sources.filter(usesLiveProvider)) {
863
963
  await pruneLiveSourceStoreEntries(result, source);
864
- for (const entry of liveSourceEntries(source)) if (entry.type === "file" && patterns.some((pattern) => matchesAny(entry.path, pattern))) result.set(entry.path, entry);
964
+ for (const entry of liveSourceEntries(source)) if (entry.type === "file" && matches(entry.path)) result.set(entry.path, entry);
865
965
  }
866
966
  return [...result.values()].sort((left, right) => left.path.localeCompare(right.path));
867
967
  },
@@ -886,12 +986,13 @@ function createWorkspaceSourceView(definition, store, options = {}) {
886
986
  if (resolution.source.materialize === "startup") await ensureMaterialized(resolution.sourceKey);
887
987
  const stored = await store.stat(resolution.workspacePath);
888
988
  if (stored) return stored;
889
- if (resolution.source.materialize === "startup" && completedSources.has(resolution.sourceKey)) throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
989
+ if (resolution.source.materialize === "startup" && (completedSources.has(resolution.sourceKey) || reusedStartupSources.has(resolution.sourceKey))) throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
890
990
  await ensureMaterialized(resolution.sourceKey);
891
991
  const result = await statVirtualSourcePath(resolution.source, resolution.workspacePath, store, getSourceContext(resolution.source));
892
992
  if (!result) throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
893
993
  return result;
894
994
  }
995
+ await materializeRootStartupSources();
895
996
  let result = await store.stat(resolution.workspacePath);
896
997
  if (!result) {
897
998
  if (!resolution.workspacePath && sources.some((source) => !source.mountPath && usesLiveProvider(source))) return {
@@ -918,25 +1019,26 @@ function createWorkspaceSourceView(definition, store, options = {}) {
918
1019
  }
919
1020
  if (resolution.source.materialize === "startup") await ensureMaterialized(resolution.sourceKey);
920
1021
  if (await store.stat(resolution.workspacePath)) return true;
921
- if (resolution.source.materialize === "startup" && completedSources.has(resolution.sourceKey)) return false;
1022
+ if (resolution.source.materialize === "startup" && (completedSources.has(resolution.sourceKey) || reusedStartupSources.has(resolution.sourceKey))) return false;
922
1023
  await ensureMaterialized(resolution.sourceKey);
923
1024
  return Boolean(await statVirtualSourcePath(resolution.source, resolution.workspacePath, store, getSourceContext(resolution.source)));
924
1025
  }
1026
+ await materializeRootStartupSources();
925
1027
  if (await store.stat(resolution.workspacePath)) return true;
926
1028
  if (!resolution.workspacePath && sources.some((source) => !source.mountPath && usesLiveProvider(source))) return true;
927
1029
  await materializeRootSourceForPath(resolution.workspacePath);
928
1030
  return Boolean(await store.stat(resolution.workspacePath));
929
1031
  },
930
1032
  async mkdir(path, options) {
931
- const resolution = await assertWritablePath(path);
1033
+ const requested = await grantWritablePath(path);
932
1034
  const input = await writePolicy.before({
933
1035
  operation: "mkdir",
934
- path: resolution.workspacePath,
935
- previous: await previousStat(resolution.workspacePath),
1036
+ path: requested.path,
1037
+ previous: await previousStat(requested.path),
936
1038
  workspace: definition.name
937
1039
  });
938
1040
  try {
939
- await store.mkdir(input.path, options);
1041
+ await grantedStore.mkdir(await grantPolicyPath(input.path), input.path, options);
940
1042
  await writePolicy.after(input);
941
1043
  } catch (error) {
942
1044
  await writePolicy.error(input, error);
@@ -944,15 +1046,15 @@ function createWorkspaceSourceView(definition, store, options = {}) {
944
1046
  }
945
1047
  },
946
1048
  async rm(path, options) {
947
- const resolution = await assertWritablePath(path);
1049
+ const requested = await grantWritablePath(path);
948
1050
  const input = await writePolicy.before({
949
1051
  operation: "rm",
950
- path: resolution.workspacePath,
951
- previous: await previousStat(resolution.workspacePath),
1052
+ path: requested.path,
1053
+ previous: await previousStat(requested.path),
952
1054
  workspace: definition.name
953
1055
  });
954
1056
  try {
955
- await store.rm(input.path, options);
1057
+ await grantedStore.rm(await grantPolicyPath(input.path), input.path, options);
956
1058
  await writePolicy.after(input);
957
1059
  } catch (error) {
958
1060
  await writePolicy.error(input, error);
@@ -1021,10 +1123,19 @@ function isListedLiveEntry(entry, path, options) {
1021
1123
  return !entry.path.slice(path.length + 1).includes("/");
1022
1124
  }
1023
1125
  function liveSourceStat(source, workspacePath) {
1024
- return liveSourceEntries(source).find((entry) => entry.path === workspacePath);
1126
+ const paths = source.livePaths;
1127
+ if (!paths) return;
1128
+ if (Object.hasOwn(paths, workspacePath)) return {
1129
+ path: workspacePath,
1130
+ type: "file"
1131
+ };
1132
+ if (Object.keys(paths).some((path) => path.startsWith(`${workspacePath}/`))) return {
1133
+ path: workspacePath,
1134
+ type: "directory"
1135
+ };
1025
1136
  }
1026
1137
  async function currentSourceTreePaths(source, sourceContext) {
1027
- const allowed = new Set([source.mountPath]);
1138
+ const allowed = /* @__PURE__ */ new Set([source.mountPath]);
1028
1139
  const keys = await source.source.getKeys(sourceContext);
1029
1140
  for (const key of keys) {
1030
1141
  const parts = `${source.mountPath}/${key}`.replace(/\/+/g, "/").split("/");
@@ -1042,6 +1153,24 @@ function dedupeHits(hits) {
1042
1153
  });
1043
1154
  }
1044
1155
  //#endregion
1156
+ //#region src/storage/metadata-keys.ts
1157
+ const internalMetaKeyPrefixes = [
1158
+ "source:",
1159
+ "workspace:",
1160
+ "workspace-file-",
1161
+ "loader:"
1162
+ ];
1163
+ function isInternalWorkspaceMetaKey(key) {
1164
+ const forms = [key.toLowerCase(), normalizeWorkspacePath(key).toLowerCase()];
1165
+ return internalMetaKeyPrefixes.some((prefix) => forms.some((form) => form.startsWith(prefix)));
1166
+ }
1167
+ /** Rejects keys that Workspace internals own. Public `setMeta` calls this before it writes. */
1168
+ function assertPublicWorkspaceMetaKey(key) {
1169
+ if (!hasRuntimeType(key, "string")) throw workspaceError("[vitehub] Workspace metadata keys must be strings.");
1170
+ if (isInternalWorkspaceMetaKey(key)) throw workspaceError(`[vitehub] Workspace metadata key ${JSON.stringify(key)} is reserved for Workspace internals.`);
1171
+ return key;
1172
+ }
1173
+ //#endregion
1045
1174
  //#region src/core/workspace-cache.ts
1046
1175
  let storeByDefinition = /* @__PURE__ */ new WeakMap();
1047
1176
  function getCachedWorkspaceStore(definition, create) {
@@ -1063,17 +1192,22 @@ function resetWorkspaceStoreCache() {
1063
1192
  function getStore(definition) {
1064
1193
  return getCachedWorkspaceStore(definition, () => createWorkspaceStoreFromProvider(definition));
1065
1194
  }
1066
- function createWorkspace(definition) {
1195
+ function createWorkspace(definition, options = {}) {
1067
1196
  const store = getStore(definition);
1068
- const files = createWorkspaceSourceView(definition, store);
1197
+ const files = createWorkspaceSourceView(definition, store, options);
1198
+ const metadata = createWorkspaceMetadataTarget(store, definition.name);
1199
+ const rebaseStore = files.requireRebaseGrants(async (options) => await store.rebase?.(options));
1069
1200
  const workspace = {
1070
- [workspaceMetadataTarget]: () => store,
1071
1201
  name: definition.name,
1202
+ history: createWorkspaceHistory(definition, store, files),
1072
1203
  async capabilities() {
1073
- return { conditionalWrites: hasRuntimeType(store.writeFileConditional, "function") };
1204
+ return {
1205
+ conditionalWrites: hasRuntimeType(store.writeFileConditional, "function"),
1206
+ retainedHistory: Boolean(store.history)
1207
+ };
1074
1208
  },
1075
1209
  async sync(options) {
1076
- const { syncWorkspaceSources } = await import("./sync-DnTQwt8r.js");
1210
+ const { syncWorkspaceSources } = await import("./sync-CN6ec-5M.js");
1077
1211
  return await syncWorkspaceSources(definition, store, options);
1078
1212
  },
1079
1213
  async materializeSources(options) {
@@ -1082,8 +1216,9 @@ function createWorkspace(definition) {
1082
1216
  async getMeta(key) {
1083
1217
  return await store.getMeta?.(key);
1084
1218
  },
1085
- async setMeta(key, value) {
1086
- await store.setMeta?.(key, value);
1219
+ async setMeta(key, value, capability) {
1220
+ const metadataKey = capability === workspaceInternalMetadataCapability ? key : assertPublicWorkspaceMetaKey(key);
1221
+ await store.setMeta?.(metadataKey, value);
1087
1222
  },
1088
1223
  async readFile(path, options) {
1089
1224
  return await files.readFile(path, options);
@@ -1112,19 +1247,14 @@ function createWorkspace(definition) {
1112
1247
  async rm(path, options) {
1113
1248
  await files.rm(path, options);
1114
1249
  },
1115
- async publish(options) {
1116
- const { publishWorkspace } = await import("./lifecycle-LrL3sA4n.js").then((n) => n.t);
1117
- await publishWorkspace(definition, store, options);
1118
- },
1119
1250
  async snapshot(options) {
1120
- const snapshot = await store.snapshot(options);
1121
- const { publishWorkspaceSnapshot } = await import("./lifecycle-LrL3sA4n.js").then((n) => n.t);
1122
- await publishWorkspaceSnapshot(definition, store, snapshot);
1123
- return snapshot;
1251
+ return await store.snapshot(options);
1124
1252
  },
1125
1253
  async rebase(options) {
1126
- if (!store.rebase) throw new Error("[vitehub] Workspace Store does not support rebasing.");
1127
- await store.rebase(options);
1254
+ if (!store.rebase) throw workspaceErrorDiagnostics.WORKSPACE_R0026({ message: "[vitehub] Workspace Store does not support rebasing." });
1255
+ const grants = [];
1256
+ for (const path of options?.takeRemote ?? []) grants.push(await files.assertWritable(path));
1257
+ await rebaseStore(grants, options);
1128
1258
  },
1129
1259
  async diff(options) {
1130
1260
  return await store.diff(options);
@@ -1132,7 +1262,7 @@ function createWorkspace(definition) {
1132
1262
  async startSession(options) {
1133
1263
  const host = options?.host;
1134
1264
  if (host) {
1135
- const { createHostedWorkspaceSession } = await import("./host-DJH8cuoU.js").then((n) => n.n);
1265
+ const { createHostedWorkspaceSession } = await import("./host-CFnrTXTK.js").then((n) => n.n);
1136
1266
  return await createHostedWorkspaceSession(workspace, {
1137
1267
  ...options,
1138
1268
  host
@@ -1141,15 +1271,16 @@ function createWorkspace(definition) {
1141
1271
  return await createBasicWorkspaceSession(workspace, options);
1142
1272
  }
1143
1273
  };
1274
+ attachWorkspaceMetadataTarget(workspace, () => metadata);
1144
1275
  forwardWorkspaceStoreTarget(store, workspace);
1145
1276
  if (!normalizeWorkspaceSources(definition.sources).some((source) => source.requestDescriptor || source.livePaths)) forwardWorkspaceRevisionMaterializer(store, workspace);
1146
1277
  const synchronizedWorkspace = workspace;
1147
1278
  synchronizedWorkspace.__workspaceDefinitionSyncKey = definition;
1148
1279
  synchronizedWorkspace.__syncWorkspaceDefinition = async (abortSignal) => {
1149
- const { syncWorkspaceDefinition } = await import("./lifecycle-LrL3sA4n.js").then((n) => n.t);
1280
+ const { syncWorkspaceDefinition } = await import("./lifecycle-BwZ7c9hb.js").then((n) => n.t);
1150
1281
  await syncWorkspaceDefinition(definition, store, abortSignal);
1151
1282
  };
1152
1283
  return attachWorkspaceSourceRequestExecution(workspace, createWorkspaceSourceRequestExecution(definition));
1153
1284
  }
1154
1285
  //#endregion
1155
- export { isMissingWorkspacePathError as _, invalidateWorkspaceSourceMaterialization as a, workspaceSourceSyncStateEquals as c, resolveWorkspaceAutoCommit as d, createBasicWorkspaceSession as f, filterSessionEntries as g, filterSessionDiff as h, createWorkspaceSourceView as i, resolveWorkspacePath as l, assertPathInSessionScope as m, invalidateCachedWorkspaceStore as n, readWorkspaceSourceSyncState as o, assertDiffInsideSessionPaths as p, resetWorkspaceStoreCache as r, sourceSyncMetaKey as s, createWorkspace as t, createWorkspaceWritePolicy as u, scopedSearchQuery as v };
1286
+ export { filterSessionDiff as _, isInternalWorkspaceMetaKey as a, scopedSearchQuery as b, isWorkspaceSourceSyncMetaKey as c, sourceSyncPathClaims as d, workspaceSourceSyncStateEquals as f, assertPathInSessionScope as g, assertDiffInsideSessionPaths as h, assertPublicWorkspaceMetaKey as i, readWorkspaceSourceSyncState as l, createBasicWorkspaceSession as m, invalidateCachedWorkspaceStore as n, createWorkspaceSourceView as o, resolveWorkspacePath as p, resetWorkspaceStoreCache as r, invalidateWorkspaceSourceMaterialization as s, createWorkspace as t, sourceSyncMetaKey as u, filterSessionEntries as v, isMissingWorkspacePathError as y };