@vite-hub/workspace 0.0.2 → 0.0.4

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/LICENSE +201 -0
  2. package/README.md +48 -2
  3. package/dist/{ai-Cztw4eLk.js → ai-BqCC8BpY.js} +15 -4
  4. package/dist/{ai-hFdsvDHC.d.ts → ai-CjxvGqM0.d.ts} +1 -1
  5. package/dist/ai.d.ts +2 -2
  6. package/dist/ai.js +1 -1
  7. package/dist/{asset-registry-CaG9b7tf.js → asset-registry-8QI3ML3K.js} +1 -1
  8. package/dist/chunk-2rV9d50f.js +35 -0
  9. package/dist/cloudflare.d.ts +4 -2
  10. package/dist/cloudflare.js +1 -2
  11. package/dist/collections.d.ts +2 -2
  12. package/dist/collections.js +1 -1
  13. package/dist/{config--r5unwPc.js → config-Bc3c4Su1.js} +213 -120
  14. package/dist/{config-DCQ6y30R.js → config-CHLLWklZ.js} +9 -3
  15. package/dist/{config-Ca5DM8fF.d.ts → config-DE9xlaIw.d.ts} +1 -1
  16. package/dist/{file-B2q9NE18.js → file-Bc1X7pco.js} +9 -10
  17. package/dist/{files-xy0le-_U.js → files-Q6xZjDHA.js} +20 -9
  18. package/dist/{github-lIO6-2sH.js → github-DHnjxQIX.js} +27 -23
  19. package/dist/glob-CEZKeZFC.js +18 -0
  20. package/dist/host-DJH8cuoU.js +1030 -0
  21. package/dist/{artifacts-store-BAV9jZpd.js → hosted-RPeJOCFz.js} +146 -30
  22. package/dist/hosted-vercel-blob-d6C8ND5j.js +23580 -0
  23. package/dist/hosted-vercel-blob.d.ts +1 -1
  24. package/dist/hosted-vercel-blob.js +1 -25
  25. package/dist/hosted.d.ts +1 -1
  26. package/dist/hosted.js +1 -29
  27. package/dist/index.d.ts +61 -78
  28. package/dist/index.js +133 -435
  29. package/dist/lifecycle-LrL3sA4n.js +316 -0
  30. package/dist/loader.d.ts +1 -1
  31. package/dist/loader.js +1 -1
  32. package/dist/metadata-target-B0tOmVW7.js +717 -0
  33. package/dist/mountx.d.ts +10 -0
  34. package/dist/mountx.js +143 -0
  35. package/dist/nitro.d.ts +1 -1
  36. package/dist/nitro.js +1 -1
  37. package/dist/nuxt.d.ts +1 -1
  38. package/dist/nuxt.js +8 -2
  39. package/dist/{path-CNI6wKIU.js → path-Cp59koVz.js} +28 -4
  40. package/dist/{provider-CeQciesl.js → provider-B1yLjCJJ.js} +194 -47
  41. package/dist/providers/github/store.d.ts +1 -1
  42. package/dist/providers/github/store.js +1 -361
  43. package/dist/publish.d.ts +1 -1
  44. package/dist/publish.js +2 -2
  45. package/dist/registry-D3yzt8HQ.js +127 -0
  46. package/dist/{registry-CoC9JxVt.d.ts → registry-Uj6IVxes.d.ts} +3 -3
  47. package/dist/{request-execution-C8qRcReq.js → request-execution-B-dSFlGB.js} +8 -4
  48. package/dist/runtime/assets.d.ts +1 -1
  49. package/dist/runtime/assets.js +4 -2
  50. package/dist/runtime/empty-assets-registry.d.ts +1 -1
  51. package/dist/runtime/empty-registry.d.ts +1 -1
  52. package/dist/runtime/state.d.ts +4 -4
  53. package/dist/runtime/state.js +10 -7
  54. package/dist/runtime/workspace.d.ts +1 -1
  55. package/dist/runtime/workspace.js +1 -1
  56. package/dist/runtime-options-BsPSv5O7.js +13 -0
  57. package/dist/runtime-type-iEE6BjQJ.js +34 -0
  58. package/dist/runtime.d.ts +42 -7
  59. package/dist/runtime.js +276 -100
  60. package/dist/{search-C4REyHj9.js → search-BpiCF2Tw.js} +2 -2
  61. package/dist/server.d.ts +2 -2
  62. package/dist/server.js +24 -51
  63. package/dist/{shared-BRycRSbo.js → shared-DTR1Hhma.js} +115 -39
  64. package/dist/source-metadata.d.ts +9 -2
  65. package/dist/source-metadata.js +34 -2
  66. package/dist/{state-DSAHEsq6.d.ts → state-tYcRWEh2.d.ts} +13 -12
  67. package/dist/store-Dt_Jyys3.js +608 -0
  68. package/dist/{sync-DO42ypji.js → sync-DnTQwt8r.js} +6 -5
  69. package/dist/test.d.ts +1 -1
  70. package/dist/test.js +1 -1
  71. package/dist/token-CVzURBxC.js +61 -0
  72. package/dist/{types-DHkae7Cb.d.ts → types-CYuwjJ4V.d.ts} +94 -43
  73. package/dist/{use-d_PlAdOu.js → use-BTNDR5Rd.js} +147 -50
  74. package/dist/{use-D16tf8Ph.d.ts → use-BiHzt0xA.d.ts} +21 -4
  75. package/dist/vite-BptCrpv2.js +4526 -0
  76. package/dist/vite-CtA9guIM.d.ts +66 -0
  77. package/dist/vite.d.ts +2 -50
  78. package/dist/vite.js +2 -2
  79. package/dist/{workspace-n4wBmdaM.js → workspace-Dq08Yn72.js} +224 -545
  80. package/dist/{workspace-f2DBLmPZ.d.ts → workspace-Xddf4G1B.d.ts} +1 -1
  81. package/package.json +20 -38
  82. package/dist/chunk-8H4AJuhK.js +0 -14
  83. package/dist/cli.d.ts +0 -31
  84. package/dist/cli.js +0 -303
  85. package/dist/cloudflare-env-CKxUs2fa.js +0 -20
  86. package/dist/glob-DeH0dzZX.js +0 -23
  87. package/dist/host-I-_vDs05.js +0 -370
  88. package/dist/lifecycle-Lhk3dAMt.js +0 -176
  89. package/dist/providers/cloudflare/artifacts-store.d.ts +0 -6
  90. package/dist/providers/cloudflare/artifacts-store.js +0 -2
  91. package/dist/providers/vercel/blob-store.d.ts +0 -6
  92. package/dist/providers/vercel/blob-store.js +0 -235
  93. package/dist/registry-C7DMdBXN.js +0 -74
  94. package/dist/utils-BPdaCyI6.js +0 -55
  95. package/dist/vite-NWC9mFjI.js +0 -1882
package/dist/runtime.js CHANGED
@@ -1,13 +1,15 @@
1
- import { c as normalizeWorkspacePath, p as workspaceError } from "./path-CNI6wKIU.js";
2
- import { a as copyWorkspacePath, i as appendWorkspaceFile, n as getWorkspaceDependencyRuntimeLoaders, r as setWorkspaceDependencyRuntimeLoaders, t as createWorkspaceTools } from "./ai-Cztw4eLk.js";
3
- import { a as normalizeWorkspaceSources, f as getWorkspaceSourceRequestDescriptor, g as markLiveWorkspaceSource, h as workspaceSourceRequestDescriptorPath, i as normalizeWorkspaceSourceMetadata, l as workspaceSourceGrantPaths, m as isWorkspaceSourceRequestOnly, o as normalizeWorkspaceSourcesMetadata, r as normalizeWorkspaceSource, t as copyWorkspaceSourceMetadata } from "./config--r5unwPc.js";
4
- import { n as createWorkspaceSourceRequestExecution, r as getWorkspaceSourceRequestExecution, t as attachWorkspaceSourceRequestExecution } from "./request-execution-C8qRcReq.js";
5
- import { c as getWorkspaceHostedStoreLoader, d as setWorkspaceRuntimeConfig, l as setWorkspaceHostedStoreLoader, s as createMemoryWorkspaceStore, u as getWorkspaceRuntimeConfig } from "./provider-CeQciesl.js";
1
+ import { _ as workspaceError, l as normalizeWorkspacePath } from "./path-Cp59koVz.js";
2
+ import { a as copyWorkspacePath, i as appendWorkspaceFile, n as getWorkspaceDependencyRuntimeLoaders, r as setWorkspaceDependencyRuntimeLoaders, t as createWorkspaceTools } from "./ai-BqCC8BpY.js";
3
+ import { _ as workspaceSourceRequestDescriptorPath, a as normalizeWorkspaceSources, g as isWorkspaceSourceRequestOnly, i as normalizeWorkspaceSourceMetadata, l as workspaceSourceGrantPaths, m as getWorkspaceSourceRequestDescriptor, o as normalizeWorkspaceSourcesMetadata, r as normalizeWorkspaceSource, t as copyWorkspaceSourceMetadata, u as prepareWorkspaceSource, v as markLiveWorkspaceSource } from "./config-Bc3c4Su1.js";
4
+ import { n as createWorkspaceSourceRequestExecution, r as getWorkspaceSourceRequestExecution, t as attachWorkspaceSourceRequestExecution } from "./request-execution-B-dSFlGB.js";
5
+ import { c as getWorkspaceHostedStoreLoader, d as setWorkspaceRuntimeConfig, l as setWorkspaceHostedStoreLoader, s as createMemoryWorkspaceStore, u as getWorkspaceRuntimeConfig } from "./provider-B1yLjCJJ.js";
6
6
  import { t as forwardWorkspaceStoreTarget } from "./target-D4Bqb1eH.js";
7
- import { d as createBasicWorkspaceSession, l as createWorkspaceWritePolicy, n as resetWorkspaceStoreCache, r as createWorkspaceSourceView, s as resolveWorkspacePath } from "./workspace-n4wBmdaM.js";
8
- import { n as registerWorkspace, r as resolveRegisteredWorkspaceDefinition } from "./registry-C7DMdBXN.js";
9
- import { t as useWorkspace } from "./use-d_PlAdOu.js";
10
- import { setWorkspaceRuntimeAssetsRegistry, setWorkspaceRuntimeRegistry } from "./runtime/state.js";
7
+ import { t as hasRuntimeType } from "./runtime-type-iEE6BjQJ.js";
8
+ import { f as createBasicWorkspaceSession, i as createWorkspaceSourceView, l as resolveWorkspacePath, r as resetWorkspaceStoreCache, u as createWorkspaceWritePolicy } from "./workspace-Dq08Yn72.js";
9
+ import { n as resolveWorkspaceMetadataTarget, r as workspaceMetadataTarget, t as forwardWorkspaceMetadataTarget } from "./metadata-target-B0tOmVW7.js";
10
+ import { n as registerWorkspace, r as resolveRegisteredWorkspaceDefinition } from "./registry-D3yzt8HQ.js";
11
+ import { t as useWorkspace } from "./use-BTNDR5Rd.js";
12
+ import { invalidateWorkspaceStore, setWorkspaceRuntimeAssetsRegistry, setWorkspaceRuntimeRegistry } from "./runtime/state.js";
11
13
  //#region src/sources/resolution.ts
12
14
  function hasWorkspaceSourceResolvers(definition) {
13
15
  return normalizeWorkspaceSources(definition?.sources).some((source) => typeof source.source.resolve === "function");
@@ -30,33 +32,41 @@ function writeOperations(options) {
30
32
  }
31
33
  function createOverlaySourceStore(workspace, fallback) {
32
34
  const memory = createMemoryWorkspaceStore();
35
+ const tombstones = /* @__PURE__ */ new Set();
36
+ function isTombstoned(path) {
37
+ return [...tombstones].some((tombstone) => path === tombstone || path.startsWith(`${tombstone}/`));
38
+ }
39
+ function restorePath(path) {
40
+ for (const tombstone of tombstones) if (path === tombstone || path.startsWith(`${tombstone}/`)) tombstones.delete(tombstone);
41
+ }
33
42
  async function readBaseFile(path) {
34
- if (!fallback(path)) return;
43
+ if (!fallback(path) || isTombstoned(path)) return;
35
44
  if (!await workspace.fs.exists(path)) return;
36
45
  const stat = await workspace.fs.stat(path).catch(() => void 0);
37
46
  if (stat?.type === "directory") return;
38
47
  return {
39
48
  content: await workspace.fs.readFile(path, { encoding: "binary" }),
40
49
  mediaType: stat?.mediaType,
50
+ metadata: stat?.metadata,
41
51
  path
42
52
  };
43
53
  }
44
54
  async function baseEntries(path = "", options) {
45
55
  try {
46
- return (await workspace.fs.list(path, options)).filter((entry) => fallback(entry.path));
56
+ return (await workspace.fs.list(path, options)).filter((entry) => fallback(entry.path) && !isTombstoned(entry.path));
47
57
  } catch {
48
58
  return [];
49
59
  }
50
60
  }
51
61
  async function baseGlob(pattern, options) {
52
62
  try {
53
- return (await workspace.fs.glob(pattern, options)).filter((entry) => fallback(entry.path));
63
+ return (await workspace.fs.glob(pattern, options)).filter((entry) => fallback(entry.path) && !isTombstoned(entry.path));
54
64
  } catch {
55
65
  return [];
56
66
  }
57
67
  }
58
68
  async function baseStat(path) {
59
- if (!fallback(path)) return;
69
+ if (!fallback(path) || isTombstoned(path)) return;
60
70
  try {
61
71
  return await workspace.fs.stat(path);
62
72
  } catch {
@@ -64,10 +74,12 @@ function createOverlaySourceStore(workspace, fallback) {
64
74
  }
65
75
  }
66
76
  return {
77
+ isTombstoned,
67
78
  async readFile(path) {
68
79
  return await memory.readFile(path) || await readBaseFile(path);
69
80
  },
70
81
  async writeFile(path, file) {
82
+ restorePath(path);
71
83
  await memory.writeFile(path, file);
72
84
  },
73
85
  async list(path, options) {
@@ -80,10 +92,14 @@ function createOverlaySourceStore(workspace, fallback) {
80
92
  return await memory.stat(path) || await baseStat(path);
81
93
  },
82
94
  async mkdir(path, options) {
95
+ restorePath(path);
83
96
  await memory.mkdir(path, options);
84
97
  },
85
98
  async rm(path, options) {
99
+ const removedBaseEntries = options?.recursive ? await baseEntries(path, { recursive: true }) : [];
86
100
  await memory.rm(path, options);
101
+ tombstones.add(path);
102
+ for (const entry of removedBaseEntries) tombstones.add(entry.path);
87
103
  },
88
104
  async snapshot(options) {
89
105
  return await memory.snapshot(options);
@@ -92,7 +108,8 @@ function createOverlaySourceStore(workspace, fallback) {
92
108
  return await memory.diff(options);
93
109
  },
94
110
  async getMeta(key) {
95
- return await memory.getMeta?.(key);
111
+ const internalMetadata = await resolveWorkspaceMetadataTarget(workspace);
112
+ return await memory.getMeta?.(key) ?? await internalMetadata?.getMeta?.(key) ?? await workspace.getMeta?.(key);
96
113
  },
97
114
  async setMeta(key, value) {
98
115
  await memory.setMeta?.(key, value);
@@ -141,6 +158,9 @@ function createWritableFacadeStore(workspace) {
141
158
  async snapshot(options) {
142
159
  return await workspace.snapshot(options);
143
160
  },
161
+ async rebase(options) {
162
+ await workspace.history.rebase(options);
163
+ },
144
164
  async diff(options) {
145
165
  return await workspace.diff(options);
146
166
  },
@@ -162,7 +182,7 @@ function createWritableFacadeStore(workspace) {
162
182
  async function startOverlayWorkspaceSession(_definition, workspace, options) {
163
183
  const host = options?.host;
164
184
  if (host) {
165
- const { createHostedWorkspaceSession } = await import("./host-I-_vDs05.js");
185
+ const { createHostedWorkspaceSession } = await import("./host-DJH8cuoU.js").then((n) => n.n);
166
186
  return await createHostedWorkspaceSession(workspace, {
167
187
  ...options,
168
188
  host
@@ -190,43 +210,48 @@ async function createWorkspaceSourceResolutionFacade(workspace, definition, opti
190
210
  workspace
191
211
  };
192
212
  const selectedWorkspaceScope = options.selectedWorkspaceScope;
193
- const sourceView = createWorkspaceSourceView(createScopedSourceViewDefinition(resolvedDefinition, selectedWorkspaceScope), createOverlaySourceStore(workspace, (path) => !isLazySourcePath(resolvedDefinition, path)));
213
+ const sourceViewDefinition = createScopedSourceViewDefinition(resolvedDefinition, selectedWorkspaceScope);
214
+ const overlayStore = createOverlaySourceStore(workspace, (path) => !isLazySourcePath(resolvedDefinition, path) || selectedScopeCanSee(selectedWorkspaceScope, path) && isUnchangedStartupSourcePath(definition, resolvedDefinition, path));
215
+ const sourceView = createWorkspaceSourceView(sourceViewDefinition, overlayStore, { reuseStartupSnapshots: true });
194
216
  const materializeSources = async (options = {}) => await sourceView.materializeSources(options);
217
+ const canUseBase = (path) => !overlayStore.isTombstoned(normalizeWorkspacePath(path));
195
218
  let readWorkspace;
196
219
  const fs = attachWorkspaceSourceRequestExecution({
197
220
  async readFile(path, options) {
198
221
  if (isSourcePath(resolvedDefinition, path)) return await sourceView.readFile(path, options);
199
222
  if (selectedScopeCanRead(selectedWorkspaceScope, path) && await sourceViewHasPath(resolvedDefinition, sourceView, path)) return await sourceView.readFile(path, options);
200
- return await workspace.fs.readFile(path, options);
223
+ if (selectedScopeCanRead(selectedWorkspaceScope, path) && canUseBase(path)) return await workspace.fs.readFile(path, options);
224
+ return await sourceView.readFile(path, options);
201
225
  },
202
226
  async stat(path) {
203
227
  if (isSourcePath(resolvedDefinition, path)) return await sourceView.stat(path);
204
228
  if (selectedScopeCanSee(selectedWorkspaceScope, path) && await sourceViewHasPath(resolvedDefinition, sourceView, path)) return await sourceView.stat(path);
205
- return await workspace.fs.stat(path);
229
+ if (selectedScopeCanSee(selectedWorkspaceScope, path) && canUseBase(path)) return await workspace.fs.stat(path);
230
+ return await sourceView.stat(path);
206
231
  },
207
232
  async exists(path) {
208
233
  if (isSourcePath(resolvedDefinition, path)) return await sourceView.exists(path);
209
- return selectedScopeCanSee(selectedWorkspaceScope, path) && await sourceViewHasPath(resolvedDefinition, sourceView, path) || await workspace.fs.exists(path);
234
+ return selectedScopeCanSee(selectedWorkspaceScope, path) && (await sourceViewHasPath(resolvedDefinition, sourceView, path) || canUseBase(path) && await workspace.fs.exists(path));
210
235
  },
211
236
  async list(path = "", options = {}) {
212
237
  const normalized = normalizeWorkspacePath(path);
213
238
  if (normalized && isSourcePath(resolvedDefinition, normalized)) return filterScopedEntries(selectedWorkspaceScope, await sourceView.list(normalized, options));
214
239
  const [baseEntries, sourceEntries] = await Promise.all([workspace.fs.list(path, options), selectedScopeCanSee(selectedWorkspaceScope, normalized) && sourcePathIntersects(resolvedDefinition, normalized) ? sourceView.list(normalized, options) : Promise.resolve([])]);
215
- return mergeEntries(filterBaseEntries(resolvedDefinition, baseEntries), filterScopedEntries(selectedWorkspaceScope, sourceEntries));
240
+ return mergeEntries(filterScopedEntries(selectedWorkspaceScope, filterBaseEntries(resolvedDefinition, baseEntries).filter((entry) => canUseBase(entry.path))), filterScopedEntries(selectedWorkspaceScope, sourceEntries));
216
241
  },
217
242
  async glob(pattern, options) {
218
243
  const [baseEntries, sourceEntries] = await Promise.all([workspace.fs.glob(pattern, options), sourceView.glob(pattern, options)]);
219
- return mergeEntries(filterBaseEntries(resolvedDefinition, baseEntries), filterScopedEntries(selectedWorkspaceScope, sourceEntries));
244
+ return mergeEntries(filterScopedEntries(selectedWorkspaceScope, filterBaseEntries(resolvedDefinition, baseEntries).filter((entry) => canUseBase(entry.path))), filterScopedEntries(selectedWorkspaceScope, sourceEntries));
220
245
  },
221
246
  async search(query) {
222
247
  const scopedToSource = searchQueryTargetsSource(resolvedDefinition, query);
223
248
  const [baseHits, sourceHits] = await Promise.all([scopedToSource ? Promise.resolve([]) : workspace.fs.search(query), sourceView.search(query)]);
224
- return mergeHits(filterBaseHits(resolvedDefinition, baseHits), filterScopedHits(selectedWorkspaceScope, sourceHits)).slice(0, query.limit ?? 100);
249
+ return mergeHits(filterScopedHits(selectedWorkspaceScope, filterBaseHits(resolvedDefinition, baseHits).filter((hit) => canUseBase(hit.path))), filterScopedHits(selectedWorkspaceScope, sourceHits)).slice(0, query.limit ?? 100);
225
250
  },
226
251
  materializeSources,
227
252
  startSession: async (options) => {
228
253
  const paths = options?.paths?.length ? options.paths : [""];
229
- await Promise.all(paths.map((path) => materializeSources({ path })));
254
+ if (options?.materializeSources !== false) await Promise.all(paths.map((path) => materializeSources({ path })));
230
255
  return await startOverlayWorkspaceSession(resolvedDefinition, readWorkspace, options);
231
256
  }
232
257
  }, sourceRequestExecution);
@@ -268,7 +293,7 @@ async function createWorkspaceSourceResolutionFacade(workspace, definition, opti
268
293
  return;
269
294
  }
270
295
  }
271
- async function writeWithPolicy(input, write) {
296
+ async function writeWithPolicy(input, write, preservePath = false) {
272
297
  await sourceView.assertWritable(input.path);
273
298
  const next = await writePolicy.before({
274
299
  ...input,
@@ -277,9 +302,14 @@ async function createWorkspaceSourceResolutionFacade(workspace, definition, opti
277
302
  workspace: resolvedDefinition.name
278
303
  });
279
304
  try {
305
+ if (preservePath && next.path !== normalizeWorkspacePath(input.path)) throw workspaceError(`[vitehub] Workspace validator cannot rewrite preserved path: ${normalizeWorkspacePath(input.path)} -> ${next.path}.`);
280
306
  await sourceView.assertWritable(next.path);
281
- await write(next);
307
+ const result = await write(next);
282
308
  await writePolicy.after(next);
309
+ return {
310
+ input: next,
311
+ result
312
+ };
283
313
  } catch (error) {
284
314
  await writePolicy.error(next, error);
285
315
  throw error;
@@ -304,14 +334,19 @@ async function createWorkspaceSourceResolutionFacade(workspace, definition, opti
304
334
  }
305
335
  const writeFs = attachWorkspaceSourceRequestExecution({
306
336
  appendFile: async (path, content) => await appendWorkspaceFile(writeWorkspace, path, content),
307
- copyPath: async (from, to, options) => await copyWorkspacePath(writeWorkspace, from, to, options?.overwrite),
337
+ copyPath: async (from, to, options) => {
338
+ await sourceView.assertWritable(to);
339
+ await copyWorkspacePath(writeWorkspace, from, to, options?.overwrite);
340
+ },
308
341
  exists: fs.exists,
309
342
  glob: fs.glob,
310
343
  list: fs.list,
311
- mkdir: async (path, options) => await writeWithPolicy({
312
- operation: "mkdir",
313
- path
314
- }, async (input) => await workspace.fs.mkdir(input.path, options)),
344
+ mkdir: async (path, options) => {
345
+ await writeWithPolicy({
346
+ operation: "mkdir",
347
+ path
348
+ }, async (input) => await workspace.fs.mkdir(input.path, options));
349
+ },
315
350
  movePath: async (from, to, options) => {
316
351
  await sourceView.assertWritable(from);
317
352
  await sourceView.assertWritable(to);
@@ -322,26 +357,31 @@ async function createWorkspaceSourceResolutionFacade(workspace, definition, opti
322
357
  });
323
358
  },
324
359
  readFile: fs.readFile,
325
- rm: async (path, options) => await writeWithPolicy({
326
- operation: "rm",
327
- path
328
- }, async (input) => await workspace.fs.rm(input.path, options)),
360
+ rm: async (path, options) => {
361
+ await writeWithPolicy({
362
+ operation: "rm",
363
+ path
364
+ }, async (input) => await workspace.fs.rm(input.path, options));
365
+ },
329
366
  search: fs.search,
330
367
  stat: fs.stat,
331
- writeFile: async (path, content, options) => await writeWithPolicy({
332
- content,
333
- mediaType: options?.mediaType,
334
- metadata: options?.metadata,
335
- operation: "writeFile",
336
- path
337
- }, async (input) => {
338
- const writeOptions = options === void 0 && input.mediaType === void 0 && input.metadata === void 0 ? void 0 : {
339
- ...options,
340
- mediaType: input.mediaType,
341
- metadata: input.metadata
342
- };
343
- await workspace.fs.writeFile(input.path, input.content ?? content, writeOptions);
344
- })
368
+ writeFile: async (path, content, options) => {
369
+ const { input, result } = await writeWithPolicy({
370
+ content,
371
+ mediaType: options?.mediaType,
372
+ metadata: options?.metadata,
373
+ operation: "writeFile",
374
+ path
375
+ }, async (next) => {
376
+ const writeOptions = options === void 0 && next.mediaType === void 0 && next.metadata === void 0 ? void 0 : {
377
+ ...options,
378
+ mediaType: next.mediaType,
379
+ metadata: next.metadata
380
+ };
381
+ return await workspace.fs.writeFile(next.path, next.content ?? content, writeOptions);
382
+ }, options?.preservePath);
383
+ return result || input.path;
384
+ }
345
385
  }, sourceRequestExecution);
346
386
  writeWorkspace = attachWorkspaceSourceRequestExecution({
347
387
  name: resolvedDefinition.name,
@@ -352,45 +392,29 @@ async function createWorkspaceSourceResolutionFacade(workspace, definition, opti
352
392
  materializeSources,
353
393
  mkdir: writeFs.mkdir,
354
394
  publish: async (options) => {
355
- const { publishWorkspace } = await import("./lifecycle-Lhk3dAMt.js").then((n) => n.t);
395
+ const { publishWorkspace } = await import("./lifecycle-LrL3sA4n.js").then((n) => n.t);
356
396
  await publishWorkspace(resolvedDefinition, createWritableFacadeStore({
357
397
  ...workspace,
358
398
  fs: writeFs
359
399
  }), options);
360
400
  },
401
+ rebase: workspace.history.rebase,
361
402
  readFile: writeFs.readFile,
362
403
  rm: writeFs.rm,
363
404
  search: writeFs.search,
364
405
  snapshot: workspace.snapshot,
365
406
  startSession: async (options) => {
366
407
  const paths = options?.paths?.length ? options.paths : [""];
367
- await Promise.all(paths.map((path) => materializeSources({ path })));
368
- const startBoxSession = workspace[Symbol.for("vitehub.workspace.start-box-session")];
408
+ if (options?.materializeSources !== false) await Promise.all(paths.map((path) => materializeSources({ path })));
409
+ const startBoxSession = Reflect.get(workspace, Symbol.for("vitehub.workspace.start-box-session"));
369
410
  return withSessionSourceGuards(options?.host ? await startOverlayWorkspaceSession(resolvedDefinition, writeWorkspace, options) : typeof startBoxSession === "function" ? await startBoxSession(writeWorkspace, options) : await startOverlayWorkspaceSession(resolvedDefinition, writeWorkspace, options));
370
411
  },
371
412
  stat: writeFs.stat,
372
413
  sync: async (options) => {
373
- const { syncWorkspaceSources } = await import("./sync-DO42ypji.js");
414
+ const { syncWorkspaceSources } = await import("./sync-DnTQwt8r.js");
374
415
  return await syncWorkspaceSources(resolvedDefinition, syncStore, options);
375
416
  },
376
- writeFile: writeFs.writeFile,
377
- mount(options) {
378
- const mode = options?.mode || "read-only";
379
- return {
380
- workspace: writeWorkspace,
381
- mode,
382
- target: options?.target || "/workspace",
383
- async diff() {
384
- return await writeWorkspace.diff();
385
- },
386
- async commit() {
387
- await writeWorkspace.snapshot({ name: "mount-commit" });
388
- },
389
- async export() {
390
- return await writeWorkspace.snapshot({ name: "mount-export" });
391
- }
392
- };
393
- }
417
+ writeFile: writeFs.writeFile
394
418
  }, sourceRequestExecution);
395
419
  const createWriteTools = (options) => createWorkspaceTools(writeWorkspace, {
396
420
  broadSearchPaths: options?.broadSearchPaths,
@@ -410,25 +434,28 @@ async function createWorkspaceSourceResolutionFacade(workspace, definition, opti
410
434
  writeTools.inspect = createTools;
411
435
  writeTools.none = (() => ({}));
412
436
  writeTools.write = createWriteTools;
437
+ const writableWorkspace = {
438
+ ...workspace,
439
+ diff: writeWorkspace.diff,
440
+ fs: writeFs,
441
+ materializeSources,
442
+ publish: writeWorkspace.publish,
443
+ snapshot: writeWorkspace.snapshot,
444
+ startSession: writeWorkspace.startSession,
445
+ sync: writeWorkspace.sync,
446
+ tools: writeTools
447
+ };
448
+ forwardWorkspaceMetadataTarget({ [workspaceMetadataTarget]: () => overlayStore }, writableWorkspace);
413
449
  return {
414
450
  definition: resolvedDefinition,
415
- workspace: {
416
- ...workspace,
417
- diff: writeWorkspace.diff,
418
- fs: writeFs,
419
- materializeSources,
420
- publish: writeWorkspace.publish,
421
- snapshot: writeWorkspace.snapshot,
422
- startSession: writeWorkspace.startSession,
423
- sync: writeWorkspace.sync,
424
- tools: writeTools
425
- }
451
+ workspace: writableWorkspace
426
452
  };
427
453
  }
428
454
  const readonlyWorkspace = {
429
455
  fs,
430
456
  tools
431
457
  };
458
+ forwardWorkspaceMetadataTarget({ [workspaceMetadataTarget]: () => overlayStore }, readonlyWorkspace);
432
459
  const starter = workspaceSessionStarter(workspace);
433
460
  if (starter) readonlyWorkspace.startSession = async (options) => await starter.startSession(options);
434
461
  return {
@@ -526,7 +553,12 @@ function sourceDescriptorPathIntersects(definition, path) {
526
553
  }
527
554
  function isLazySourcePath(definition, path) {
528
555
  const normalized = normalizeWorkspacePath(path);
529
- return normalizeWorkspaceSources(definition.sources).filter((source) => source.materialize === "lazy").some((source) => pathIntersects(source.mountPath, normalized));
556
+ return normalizeWorkspaceSources(definition.sources).filter((source) => source.materialize === "lazy" || source.materialize === "startup").some((source) => pathIntersects(source.mountPath, normalized));
557
+ }
558
+ function isUnchangedStartupSourcePath(definition, resolvedDefinition, path) {
559
+ const resolved = resolveWorkspacePath(resolvedDefinition, path);
560
+ if (resolved.type === "source") return resolved.materialize === "startup" && resolvedDefinition.sources?.[resolved.sourceKey] === definition.sources?.[resolved.sourceKey];
561
+ return normalizeWorkspaceSources(resolvedDefinition.sources).some((source) => !source.mountPath && source.materialize === "startup" && resolvedDefinition.sources?.[source.key] === definition.sources?.[source.key]);
530
562
  }
531
563
  function searchQueryTargetsSource(definition, query) {
532
564
  return (query.paths?.length ? query.paths : [query.cwd || ""]).every((path) => isSourcePath(definition, path));
@@ -552,7 +584,7 @@ function scopedWorkspaceSource(source, scope) {
552
584
  const scoped = {
553
585
  ...source.source,
554
586
  ...scopedLivePaths ? { async prepare(ctx) {
555
- await source.source.prepare?.(ctx);
587
+ await prepareWorkspaceSource(source.source, ctx);
556
588
  syncScopedLivePaths(scopedLivePaths, source.livePaths, scope);
557
589
  } } : {},
558
590
  ...source.source.getItems ? { getItems: async (ctx) => (await source.source.getItems(ctx)).filter((item) => selectedScopeCanRead(scope, sourceItemWorkspacePath(source, item.path || item.key))) } : {},
@@ -565,14 +597,6 @@ function scopedWorkspaceSource(source, scope) {
565
597
  ...source.source.getMeta ? { getMeta: async (key, ctx) => {
566
598
  if (!selectedScopeCanRead(scope, sourceItemWorkspacePath(source, key))) return void 0;
567
599
  return await source.source.getMeta(key, ctx);
568
- } } : {},
569
- ...source.source.search ? { search: async (query, ctx) => {
570
- const paths = selectedScopeQueryPaths(scope, query).filter((path) => pathIntersects(source.mountPath, path));
571
- if (!paths.length) return [];
572
- return filterScopedHits(scope, await source.source.search({
573
- ...query,
574
- paths
575
- }, ctx));
576
600
  } } : {}
577
601
  };
578
602
  if (!source.requestDescriptor || selectedScopeCanRead(scope, workspaceSourceRequestDescriptorPath(source.key))) copyWorkspaceSourceMetadata(source.source, scoped);
@@ -588,14 +612,6 @@ function sourceItemWorkspacePath(source, sourcePath) {
588
612
  const normalized = normalizeWorkspacePath(sourcePath);
589
613
  return normalizeWorkspacePath(source.mountPath ? `${source.mountPath}/${normalized}` : normalized);
590
614
  }
591
- function selectedScopeQueryPaths(scope, query) {
592
- const requestedPaths = (query.paths?.length ? query.paths : [query.cwd || ""]).map((path) => normalizeWorkspacePath(path));
593
- const scopedPaths = (scope.paths || []).map((path) => normalizeWorkspacePath(path));
594
- const paths = /* @__PURE__ */ new Set();
595
- for (const scopedPath of scopedPaths) for (const requestedPath of requestedPaths) if (pathContains(scopedPath, requestedPath)) paths.add(requestedPath);
596
- else if (pathContains(requestedPath, scopedPath)) paths.add(scopedPath);
597
- return [...paths];
598
- }
599
615
  function selectedScopeCanRead(scope, path) {
600
616
  if (!scope || scope.all) return true;
601
617
  const normalized = normalizeWorkspacePath(path);
@@ -640,4 +656,164 @@ function pathIntersects(left, right) {
640
656
  return pathContains(left, right) || pathContains(right, left);
641
657
  }
642
658
  //#endregion
643
- export { attachWorkspaceSourceRequestExecution, createWorkspaceSourceResolutionFacade, getWorkspaceDependencyRuntimeLoaders, getWorkspaceHostedStoreLoader, getWorkspaceRuntimeConfig, getWorkspaceSourceRequestDescriptor, getWorkspaceSourceRequestExecution, hasWorkspaceSourceResolvers, isWorkspaceSourceRequestOnly, markLiveWorkspaceSource, normalizeWorkspaceSourceMetadata, normalizeWorkspaceSourcesMetadata, registerWorkspace, resetWorkspaceStoreCache, resolveRegisteredWorkspaceDefinition, resolveWorkspaceSources, setWorkspaceDependencyRuntimeLoaders, setWorkspaceHostedStoreLoader, setWorkspaceRuntimeAssetsRegistry, setWorkspaceRuntimeConfig, setWorkspaceRuntimeRegistry, useWorkspace, workspaceSourceGrantPaths, workspaceSourceRequestDescriptorPath };
659
+ //#region src/runtime/preparation.ts
660
+ const MAX_TIMER_DELAY_MS = 2147483647;
661
+ async function waitForAbortable(operation, signal) {
662
+ let removeAbortListener = () => {};
663
+ const aborted = new Promise((_resolve, reject) => {
664
+ const onAbort = () => reject(signal.reason);
665
+ if (signal.aborted) return onAbort();
666
+ signal.addEventListener("abort", onAbort, { once: true });
667
+ removeAbortListener = () => signal.removeEventListener("abort", onAbort);
668
+ });
669
+ try {
670
+ return await Promise.race([operation, aborted]);
671
+ } finally {
672
+ removeAbortListener();
673
+ }
674
+ }
675
+ function createWorkspacePreparation(options) {
676
+ if (!options || !hasRuntimeType(options.workspace, "string") || !options.workspace.trim()) throw new TypeError("[vitehub] Workspace preparation requires a Workspace name.");
677
+ if (options.sources !== void 0 && (!Array.isArray(options.sources) || options.sources.some((source) => !hasRuntimeType(source, "string") || !source.trim()))) throw new TypeError("[vitehub] Workspace preparation sources must be non-empty strings.");
678
+ const retryDelayMs = options.retryDelayMs ?? 1e4;
679
+ if (!Number.isFinite(retryDelayMs) || retryDelayMs < 0 || retryDelayMs > MAX_TIMER_DELAY_MS) throw new TypeError(`[vitehub] Workspace preparation retryDelayMs must be between 0 and ${MAX_TIMER_DELAY_MS}.`);
680
+ const workspaceName = options.workspace.trim();
681
+ const sources = options.sources === void 0 ? void 0 : [...new Set(options.sources.map((source) => source.trim()))];
682
+ let workspace = useWorkspace(workspaceName, { mode: "write" });
683
+ let state = Object.freeze({
684
+ stoppedAt: (/* @__PURE__ */ new Date()).toISOString(),
685
+ status: "stopped"
686
+ });
687
+ let active;
688
+ let starting;
689
+ let abortController;
690
+ let retryTimer;
691
+ let started = false;
692
+ let stopped = true;
693
+ let lifecycle = 0;
694
+ const publish = (next) => {
695
+ state = Object.freeze(next);
696
+ try {
697
+ options.onStateChange?.(state);
698
+ } catch {}
699
+ return state;
700
+ };
701
+ const run = async () => {
702
+ if (stopped) return state;
703
+ if (active) return await active;
704
+ const attemptLifecycle = lifecycle;
705
+ const startedAtMs = Date.now();
706
+ const startedAt = new Date(startedAtMs).toISOString();
707
+ const controller = new AbortController();
708
+ abortController = controller;
709
+ let resolveAttempt;
710
+ let rejectAttempt;
711
+ const attempt = new Promise((resolve, reject) => {
712
+ resolveAttempt = resolve;
713
+ rejectAttempt = reject;
714
+ });
715
+ active = attempt;
716
+ publish({
717
+ startedAt,
718
+ status: "preparing"
719
+ });
720
+ (async () => {
721
+ try {
722
+ const definition = await resolveRegisteredWorkspaceDefinition(workspaceName, controller.signal);
723
+ const selectedSources = sources ?? normalizeWorkspaceSources(definition.sources).filter((source) => source.materialize === "startup").map((source) => source.key);
724
+ if (!selectedSources.length) throw new Error(`[vitehub] Workspace "${workspaceName}" has no startup sources to prepare.`);
725
+ const result = await workspace.materializeSources({
726
+ abortSignal: controller.signal,
727
+ sources: selectedSources
728
+ });
729
+ const sourceResults = new Map(result.sources.map((source) => [source.source, source]));
730
+ const failures = selectedSources.filter((source) => sourceResults.get(source)?.status !== "ready");
731
+ if (failures.length) throw new Error(`[vitehub] Workspace "${workspaceName}" sources failed to prepare: ${failures.join(", ")}.`);
732
+ await waitForAbortable(options.validate?.(result), controller.signal);
733
+ if (stopped || attemptLifecycle !== lifecycle) return state;
734
+ const finishedAtMs = Date.now();
735
+ return publish({
736
+ durationMs: finishedAtMs - startedAtMs,
737
+ finishedAt: new Date(finishedAtMs).toISOString(),
738
+ result,
739
+ startedAt,
740
+ status: "ready"
741
+ });
742
+ } catch (error) {
743
+ if (controller.signal.aborted) workspace = useWorkspace(workspaceName, { mode: "write" });
744
+ if (stopped || attemptLifecycle !== lifecycle) return state;
745
+ const finishedAtMs = Date.now();
746
+ const next = publish({
747
+ durationMs: finishedAtMs - startedAtMs,
748
+ error: error instanceof Error ? error.message : String(error),
749
+ finishedAt: new Date(finishedAtMs).toISOString(),
750
+ startedAt,
751
+ status: "error"
752
+ });
753
+ if (!stopped && attemptLifecycle === lifecycle) retryTimer = setTimeout(() => {
754
+ retryTimer = void 0;
755
+ if (!stopped && attemptLifecycle === lifecycle) run();
756
+ }, retryDelayMs);
757
+ return next;
758
+ } finally {
759
+ if (abortController === controller) abortController = void 0;
760
+ }
761
+ })().then(resolveAttempt, rejectAttempt);
762
+ try {
763
+ return await attempt;
764
+ } finally {
765
+ if (active === attempt) active = void 0;
766
+ }
767
+ };
768
+ return Object.freeze({
769
+ getState() {
770
+ return state;
771
+ },
772
+ response() {
773
+ const ready = state.status === "ready";
774
+ return Response.json({
775
+ ready,
776
+ status: state.status
777
+ }, {
778
+ headers: {
779
+ "cache-control": "no-store",
780
+ "content-type": "application/json; charset=utf-8"
781
+ },
782
+ status: ready ? 200 : 503
783
+ });
784
+ },
785
+ async start() {
786
+ if (started) return starting ? await starting : active ? await active : state;
787
+ started = true;
788
+ stopped = false;
789
+ const startLifecycle = ++lifecycle;
790
+ const transition = (async () => {
791
+ if (active) await active;
792
+ if (!started || stopped || startLifecycle !== lifecycle) return state;
793
+ return await run();
794
+ })();
795
+ starting = transition;
796
+ try {
797
+ return await transition;
798
+ } finally {
799
+ if (starting === transition) starting = void 0;
800
+ }
801
+ },
802
+ async stop() {
803
+ started = false;
804
+ stopped = true;
805
+ lifecycle++;
806
+ publish({
807
+ status: "stopped",
808
+ stoppedAt: (/* @__PURE__ */ new Date()).toISOString()
809
+ });
810
+ if (retryTimer) clearTimeout(retryTimer);
811
+ retryTimer = void 0;
812
+ const current = active;
813
+ abortController?.abort(/* @__PURE__ */ new Error(`[vitehub] Workspace "${workspaceName}" preparation stopped.`));
814
+ await current;
815
+ }
816
+ });
817
+ }
818
+ //#endregion
819
+ export { attachWorkspaceSourceRequestExecution, createWorkspacePreparation, createWorkspaceSourceResolutionFacade, getWorkspaceDependencyRuntimeLoaders, getWorkspaceHostedStoreLoader, getWorkspaceRuntimeConfig, getWorkspaceSourceRequestDescriptor, getWorkspaceSourceRequestExecution, hasWorkspaceSourceResolvers, invalidateWorkspaceStore, isWorkspaceSourceRequestOnly, markLiveWorkspaceSource, normalizeWorkspaceSourceMetadata, normalizeWorkspaceSourcesMetadata, registerWorkspace, resetWorkspaceStoreCache, resolveRegisteredWorkspaceDefinition, resolveWorkspaceSources, setWorkspaceDependencyRuntimeLoaders, setWorkspaceHostedStoreLoader, setWorkspaceRuntimeAssetsRegistry, setWorkspaceRuntimeConfig, setWorkspaceRuntimeRegistry, useWorkspace, workspaceSourceGrantPaths, workspaceSourceRequestDescriptorPath };
@@ -1,5 +1,5 @@
1
- import { t as __exportAll } from "./chunk-8H4AJuhK.js";
2
- import { c as normalizeWorkspacePath } from "./path-CNI6wKIU.js";
1
+ import { n as __exportAll } from "./chunk-2rV9d50f.js";
2
+ import { l as normalizeWorkspacePath } from "./path-Cp59koVz.js";
3
3
  //#region src/core/search.ts
4
4
  var search_exports = /* @__PURE__ */ __exportAll({
5
5
  searchText: () => searchText,
package/dist/server.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { P as WorkspaceDefinition, St as WorkspaceSessionOptions, i as ExecResult, lt as WorkspacePrepareSessionProgressEvent, ot as WorkspaceName, vt as WorkspaceSession, yt as WorkspaceSessionHost } from "./types-DHkae7Cb.js";
2
- import { t as ReadonlyWorkspaceFacade, u as WritableWorkspaceFacade } from "./use-D16tf8Ph.js";
1
+ import { F as WorkspaceDefinition, _t as WorkspaceSession, i as ExecResult, it as WorkspaceName, st as WorkspacePrepareSessionProgressEvent, vt as WorkspaceSessionHost, xt as WorkspaceSessionOptions } from "./types-CYuwjJ4V.js";
2
+ import { i as ReadonlyWorkspaceFacade, m as WritableWorkspaceFacade } from "./use-BiHzt0xA.js";
3
3
  import { WorkspaceCollectionOptions, WorkspaceCollectionSort } from "./collections.js";
4
4
  import { defineEventHandler } from "h3";
5
5