@vite-hub/workspace 0.0.4 → 0.3.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 (137) hide show
  1. package/README.md +339 -115
  2. package/dist/abort-BCwpdrN0.js +32 -0
  3. package/dist/{asset-registry-8QI3ML3K.js → asset-registry-DfBV5kmw.js} +3 -2
  4. package/dist/blob-database.d.ts +474 -0
  5. package/dist/blob-database.js +608 -0
  6. package/dist/checkout.d.ts +128 -0
  7. package/dist/checkout.js +849 -0
  8. package/dist/cloudflare.d.ts +6 -7
  9. package/dist/cloudflare.js +1 -1
  10. package/dist/config-B-863EgC.js +15 -0
  11. package/dist/config-BAgL2dtB.js +1076 -0
  12. package/dist/{config-DE9xlaIw.d.ts → config-BQKcPawI.d.ts} +1 -2
  13. package/dist/discard-CNNtCozM.js +8 -0
  14. package/dist/durability.d.ts +22 -0
  15. package/dist/durability.js +70 -0
  16. package/dist/error-diagnostics-CtKjGtGb.js +188 -0
  17. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  18. package/dist/file-2pFYNtsU.js +22 -0
  19. package/dist/{files-Q6xZjDHA.js → files-BOo4SbwE.js} +3 -3
  20. package/dist/files.d.ts +38 -0
  21. package/dist/files.js +6 -0
  22. package/dist/{github-DHnjxQIX.js → github-CrYp4v8k.js} +44 -24
  23. package/dist/glob-B8YGvTrZ.js +21 -0
  24. package/dist/glob-Cjxms1t7.js +30 -0
  25. package/dist/{host-DJH8cuoU.js → host-BFBpXn0N.js} +144 -77
  26. package/dist/{hosted-RPeJOCFz.js → hosted-KcUR_jPv.js} +303 -97
  27. package/dist/hosted-vercel-blob-B3-wRdUm.js +410 -0
  28. package/dist/hosted-vercel-blob.d.ts +6 -7
  29. package/dist/hosted-vercel-blob.js +1 -1
  30. package/dist/hosted.d.ts +10 -9
  31. package/dist/hosted.js +2 -2
  32. package/dist/index.d.ts +26 -47
  33. package/dist/index.js +30 -100
  34. package/dist/internal/path.d.ts +2 -0
  35. package/dist/internal/path.js +2 -0
  36. package/dist/lifecycle-B-enk_4A.js +596 -0
  37. package/dist/lineage.d.ts +26 -0
  38. package/dist/lineage.js +76 -0
  39. package/dist/loader.d.ts +5 -6
  40. package/dist/loader.js +3 -2
  41. package/dist/mcp-resources-DF0F5rcL.js +39 -0
  42. package/dist/memory-BOexthyW.js +247 -0
  43. package/dist/metadata-target-CWz6KHKq.js +1589 -0
  44. package/dist/object-Da1zyPCR.js +11 -0
  45. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  46. package/dist/operations-C6FpR8Rr.js +389 -0
  47. package/dist/operations-CE2drFih.js +1234 -0
  48. package/dist/operations.d.ts +90 -0
  49. package/dist/operations.js +3 -0
  50. package/dist/path--wrT_Azm.js +113 -0
  51. package/dist/path-AxMho1wo.d.ts +7 -0
  52. package/dist/path-DrSIenjj.js +59 -0
  53. package/dist/path-zHxQUbqa.d.ts +9 -0
  54. package/dist/plugins-C8C0auoW.d.ts +10 -0
  55. package/dist/provider-9s4Ufkm5.js +1479 -0
  56. package/dist/providers/github/store.d.ts +3 -5
  57. package/dist/providers/github/store.js +1 -1
  58. package/dist/registry-B3BBm4Ts.d.ts +19 -0
  59. package/dist/{registry-D3yzt8HQ.js → registry-CNphafBx.js} +60 -23
  60. package/dist/registry-CYNN623b.d.ts +9 -0
  61. package/dist/request-scope-Dw5n8bMC.js +83 -0
  62. package/dist/results-DgkZUmTL.js +8 -0
  63. package/dist/{chunk-2rV9d50f.js → rolldown-runtime-rQ84J-ij.js} +3 -4
  64. package/dist/runtime/assets.d.ts +3 -5
  65. package/dist/runtime/assets.js +7 -6
  66. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  67. package/dist/runtime/empty-registry.d.ts +2 -2
  68. package/dist/runtime/registry.d.ts +2 -0
  69. package/dist/runtime/registry.js +23 -0
  70. package/dist/runtime/request.d.ts +4 -0
  71. package/dist/runtime/request.js +8 -0
  72. package/dist/runtime/state.d.ts +5 -4
  73. package/dist/runtime/state.js +8 -18
  74. package/dist/runtime/workspace.d.ts +1 -1
  75. package/dist/runtime/workspace.js +1 -1
  76. package/dist/runtime.d.ts +52 -17
  77. package/dist/runtime.js +324 -67
  78. package/dist/{search-BpiCF2Tw.js → search-C_RfoM2j.js} +10 -9
  79. package/dist/server-8tGltlGz.js +303 -0
  80. package/dist/server.d.ts +36 -39
  81. package/dist/server.js +2 -328
  82. package/dist/shared-B3_EUk89.js +848 -0
  83. package/dist/source-metadata.d.ts +10 -7
  84. package/dist/source-metadata.js +12 -12
  85. package/dist/state-BISnUf1s.d.ts +35 -0
  86. package/dist/{ai-BqCC8BpY.js → state-DbrW-njQ.js} +237 -114
  87. package/dist/store-ybhyD38Z.js +1873 -0
  88. package/dist/{sync-DnTQwt8r.js → sync-CCD_VYC8.js} +61 -41
  89. package/dist/target-jWhTdIuF.js +89 -0
  90. package/dist/test.d.ts +1 -1
  91. package/dist/test.js +1 -1
  92. package/dist/{types-CYuwjJ4V.d.ts → types-BbtwmBZ5.d.ts} +321 -35
  93. package/dist/use-C6lV3-wC.d.ts +321 -0
  94. package/dist/{use-BTNDR5Rd.js → use-CSpT5W87.js} +141 -107
  95. package/dist/utils-CgMZCHsX.js +616 -0
  96. package/dist/vite.d.ts +585 -2
  97. package/dist/vite.js +21369 -2
  98. package/dist/workspace-CYB2xZ1T.d.ts +7 -0
  99. package/dist/{workspace-Dq08Yn72.js → workspace-sPWn2Jxj.js} +441 -225
  100. package/package.json +97 -72
  101. package/dist/ai-CjxvGqM0.d.ts +0 -162
  102. package/dist/ai.d.ts +0 -3
  103. package/dist/ai.js +0 -2
  104. package/dist/collections/client.d.ts +0 -39
  105. package/dist/collections/client.js +0 -137
  106. package/dist/collections.d.ts +0 -59
  107. package/dist/collections.js +0 -159
  108. package/dist/config-Bc3c4Su1.js +0 -7904
  109. package/dist/config-CHLLWklZ.js +0 -36
  110. package/dist/file-Bc1X7pco.js +0 -23
  111. package/dist/glob-CEZKeZFC.js +0 -18
  112. package/dist/hosted-vercel-blob-d6C8ND5j.js +0 -23580
  113. package/dist/lifecycle-LrL3sA4n.js +0 -316
  114. package/dist/metadata-target-B0tOmVW7.js +0 -717
  115. package/dist/mountx.d.ts +0 -10
  116. package/dist/mountx.js +0 -143
  117. package/dist/nitro.d.ts +0 -2
  118. package/dist/nitro.js +0 -2
  119. package/dist/nuxt.d.ts +0 -26
  120. package/dist/nuxt.js +0 -42
  121. package/dist/path-Cp59koVz.js +0 -139
  122. package/dist/provider-B1yLjCJJ.js +0 -746
  123. package/dist/publish.d.ts +0 -35
  124. package/dist/publish.js +0 -112
  125. package/dist/registry-Uj6IVxes.d.ts +0 -11
  126. package/dist/request-execution-B-dSFlGB.js +0 -84
  127. package/dist/runtime-options-BsPSv5O7.js +0 -13
  128. package/dist/runtime-type-iEE6BjQJ.js +0 -34
  129. package/dist/shared-DTR1Hhma.js +0 -331
  130. package/dist/state-tYcRWEh2.d.ts +0 -26
  131. package/dist/store-Dt_Jyys3.js +0 -608
  132. package/dist/target-D4Bqb1eH.js +0 -11
  133. package/dist/token-CVzURBxC.js +0 -61
  134. package/dist/use-BiHzt0xA.d.ts +0 -103
  135. package/dist/vite-BptCrpv2.js +0 -4526
  136. package/dist/vite-CtA9guIM.d.ts +0 -66
  137. package/dist/workspace-Xddf4G1B.d.ts +0 -6
@@ -1,717 +0,0 @@
1
- import { _ as workspaceError, f as sha256, i as decodeFile, l as normalizeWorkspacePath, n as contentStreamToBytes, s as normalizeSafeWorkspacePath, t as contentStreamChunks } from "./path-Cp59koVz.js";
2
- import { a as normalizeWorkspaceSources, c as sourceMountIntersectsPath, n as createSourceContext, s as sourceMountContainsPath, u as prepareWorkspaceSource } from "./config-Bc3c4Su1.js";
3
- import { t as searchText } from "./search-BpiCF2Tw.js";
4
- import { posix } from "node:path";
5
- import { isDeepStrictEqual } from "node:util";
6
- //#region src/sources/source-items.ts
7
- function normalizeWorkspaceSourceItemPath(source, rawSourcePath, options = {}) {
8
- const sourcePath = normalizeSafeWorkspacePath(rawSourcePath, {
9
- allowEmpty: false,
10
- allowReserved: true
11
- });
12
- const label = options.operation ? `${options.operation} item path` : "source item path";
13
- if (sourcePath.split("/").some((part) => part === ".git" || part === ".vitehub")) throw workspaceError(`[vitehub] Workspace ${label} is reserved: ${rawSourcePath}.`);
14
- const path = normalizeSafeWorkspacePath(source.mountPath ? `${source.mountPath}/${sourcePath}` : sourcePath, { allowEmpty: false });
15
- if (source.mountPath && !sourceMountContainsPath(source, path)) throw workspaceError(`[vitehub] Workspace ${label} escapes source mount: ${rawSourcePath}.`);
16
- return {
17
- path,
18
- sourcePath
19
- };
20
- }
21
- function normalizeSourceItemPath(source, item, options = {}) {
22
- return normalizeWorkspaceSourceItemPath(source, item.path || item.key, options);
23
- }
24
- //#endregion
25
- //#region src/sources/materialization.ts
26
- function sourceSnapshotMetaKey(sourceKey) {
27
- return `source:${sourceKey}:snapshot`;
28
- }
29
- function sourceConfigFingerprint(source) {
30
- return {
31
- cache: source.cache,
32
- key: source.key,
33
- materialize: source.materialize,
34
- mountPath: source.mountPath,
35
- source: source.source.fingerprint
36
- };
37
- }
38
- async function sourceConfigHash(source) {
39
- return await sha256(sourceConfigFingerprint(source));
40
- }
41
- function isSnapshotFresh(meta, source, configHash) {
42
- if (!meta || meta.status !== "ready" || meta.configHash !== configHash) return false;
43
- if (!source.cache) return false;
44
- const maxAge = source.cache.maxAge ?? NaN;
45
- if (!Number.isFinite(maxAge)) return false;
46
- if (!meta.materializedAt) return false;
47
- return Date.now() - Date.parse(meta.materializedAt) <= maxAge * 1e3;
48
- }
49
- async function readSourceSnapshotMetadata(store, sourceKey) {
50
- return await store.getMeta?.(sourceSnapshotMetaKey(sourceKey));
51
- }
52
- async function hasCurrentSourceSnapshot(store, source) {
53
- const configHash = await sourceConfigHash(source);
54
- const meta = await readSourceSnapshotMetadata(store, source.key);
55
- return meta?.status === "ready" && meta.configHash === configHash;
56
- }
57
- async function hasFreshSourceSnapshot(store, source) {
58
- const configHash = await sourceConfigHash(source);
59
- return isSnapshotFresh(await readSourceSnapshotMetadata(store, source.key), source, configHash);
60
- }
61
- async function readCurrentSourceSnapshot(store, source) {
62
- const configHash = await sourceConfigHash(source);
63
- const snapshot = await readSourceSnapshotMetadata(store, source.key);
64
- return snapshot?.configHash === configHash ? snapshot : void 0;
65
- }
66
- async function sourceSnapshotOwnsAnyPath(store, sourceKey, paths) {
67
- const meta = await readSourceSnapshotMetadata(store, sourceKey);
68
- if (!meta || meta.status !== "ready") return void 0;
69
- const ownedPaths = new Set(Object.keys(meta.items || {}));
70
- return [...paths].some((path) => ownedPaths.has(normalizeWorkspacePath(path)));
71
- }
72
- async function writeSourceSnapshotMetadata(store, metadata) {
73
- await store.setMeta?.(sourceSnapshotMetaKey(metadata.source), metadata);
74
- }
75
- function materializedItemMeta(snapshot, configHash, path) {
76
- if (!snapshot || snapshot.configHash !== configHash) return void 0;
77
- if (snapshot.status !== "ready" && snapshot.status !== "updating" && snapshot.status !== "error") return void 0;
78
- return snapshot.items?.[path];
79
- }
80
- function checkpointItems(items) {
81
- return Object.keys(items).length ? items : void 0;
82
- }
83
- function contentSize(content) {
84
- return content instanceof Uint8Array ? content.byteLength : new TextEncoder().encode(content).byteLength;
85
- }
86
- function normalizeMetadataValue(value) {
87
- if (Array.isArray(value)) return value.map(normalizeMetadataValue);
88
- if (!value || Object.getPrototypeOf(value) !== Object.prototype) return value;
89
- return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => [key, normalizeMetadataValue(entry)]));
90
- }
91
- function observableFileMetadata(metadata) {
92
- return Object.fromEntries(Object.entries(metadata || {}).filter(([key, value]) => key !== "materializedAt" && key !== "validatedAt" && value !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, value]) => [key, normalizeMetadataValue(value)]));
93
- }
94
- function fileAttributesEqual(previous, previousSnapshot, mediaType, metadata) {
95
- if (previousSnapshot?.materializedAttributes) return previousSnapshot.materializedMediaType === mediaType && isDeepStrictEqual(observableFileMetadata(previousSnapshot.materializedMetadata), observableFileMetadata(metadata));
96
- return (previous.mediaType === void 0 || previous.mediaType === mediaType) && (previous.metadata === void 0 || isDeepStrictEqual(observableFileMetadata(previous.metadata), observableFileMetadata(metadata)));
97
- }
98
- function sourcePathMatches(path, source, options) {
99
- if (options?.sources?.length && !options.sources.includes(source.key)) return false;
100
- const requested = normalizeWorkspacePath(options?.path || "");
101
- if (!requested) return true;
102
- return sourceMountIntersectsPath(source, requested);
103
- }
104
- function pathContains(container, path) {
105
- return !container || path === container || path.startsWith(`${container}/`);
106
- }
107
- function materializationPathMatches(path, options) {
108
- return pathContains(normalizeWorkspacePath(options?.path || ""), path);
109
- }
110
- function materializesCompleteSource(source, options) {
111
- const requested = normalizeWorkspacePath(options?.path || "");
112
- return !requested || Boolean(source.mountPath && pathContains(requested, source.mountPath));
113
- }
114
- function shouldMaterializeSource(source, options) {
115
- if (source.requestOnly || !sourcePathMatches("", source, options)) return false;
116
- if (source.materialize === "lazy" || source.materialize === "startup") return true;
117
- return source.materialize === "build" && Boolean(options?.path);
118
- }
119
- function throwIfAborted(signal) {
120
- if (!signal?.aborted) return;
121
- throw signal.reason instanceof Error ? signal.reason : workspaceError("[vitehub] Workspace source materialization aborted.");
122
- }
123
- async function reportMaterializationProgress(options, source, event) {
124
- await options?.onProgress?.({
125
- ...event,
126
- mountPath: source.mountPath,
127
- path: normalizeWorkspacePath(options?.path || ""),
128
- provider: source.source.name,
129
- source: source.key
130
- });
131
- }
132
- function emptyMaterializationCounts() {
133
- return {
134
- added: 0,
135
- removed: 0,
136
- unchanged: 0,
137
- updated: 0
138
- };
139
- }
140
- function materializationCacheStatus(source, complete, hit) {
141
- if (!complete) return "bypassed";
142
- if (!source.cache) return "disabled";
143
- return hit ? "hit" : "miss";
144
- }
145
- function materializationPaths(options, paths) {
146
- return options?.details === "paths" ? paths.slice().sort((left, right) => left.path.localeCompare(right.path) || left.status.localeCompare(right.status)) : void 0;
147
- }
148
- function contentEquals(left, right) {
149
- const leftBytes = left instanceof Uint8Array ? left : new TextEncoder().encode(left);
150
- const rightBytes = right instanceof Uint8Array ? right : new TextEncoder().encode(right);
151
- return leftBytes.byteLength === rightBytes.byteLength && leftBytes.every((byte, index) => byte === rightBytes[index]);
152
- }
153
- function shouldReportMaterializationUpdate(lastReportedAt, files) {
154
- return files === 1 || files % 25 === 0 || Date.now() - lastReportedAt >= 1e3;
155
- }
156
- function looksLikeConcreteFilePath(path) {
157
- const name = posix.basename(path);
158
- return name.includes(".") || [
159
- "Dockerfile",
160
- "LICENSE",
161
- "Makefile",
162
- "Procfile",
163
- "README"
164
- ].includes(name);
165
- }
166
- function directMaterializationSourceKey(source, options) {
167
- const requested = normalizeWorkspacePath(options?.path || "");
168
- if (!requested || !sourceMountContainsPath(source, requested) || requested === source.mountPath) return;
169
- const sourcePath = source.mountPath ? requested.slice(source.mountPath.length + 1) : requested;
170
- return sourcePath && looksLikeConcreteFilePath(sourcePath) ? sourcePath : void 0;
171
- }
172
- function parentDirectoryPaths(path) {
173
- const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
174
- const paths = [];
175
- for (let index = 1; index < parts.length; index++) paths.push(parts.slice(0, index).join("/"));
176
- return paths;
177
- }
178
- async function removeStaleMaterializedSourceFiles(store, source, sources, nextPaths, scope, control, previousPaths = /* @__PURE__ */ new Set(), onRemoved) {
179
- const entries = await store.list(source.mountPath, { recursive: true });
180
- const nextDirectories = new Set([...nextPaths].flatMap((path) => parentDirectoryPaths(path)));
181
- const staleDirectories = /* @__PURE__ */ new Set();
182
- for (const entry of entries) {
183
- if (!materializationPathMatches(entry.path, scope)) continue;
184
- if (nextPaths.has(entry.path) || entry.type !== "file") continue;
185
- const file = await store.readFile(entry.path);
186
- const currentOwner = file?.metadata?.source;
187
- const overlapsAnotherSource = sources.some((candidate) => candidate.key !== source.key && candidate.mountPath.length >= source.mountPath.length && sourceMountContainsPath(candidate, entry.path));
188
- if (currentOwner === source.key || currentOwner === void 0 && (previousPaths.has(entry.path) || !overlapsAnotherSource)) {
189
- for (const directory of parentDirectoryPaths(entry.path)) staleDirectories.add(directory);
190
- await control.mutate(() => store.rm(entry.path, { force: true }));
191
- onRemoved?.(entry.path, file ? contentSize(file.content) : 0);
192
- }
193
- }
194
- for (const entry of entries.filter((entry) => entry.type === "directory" && staleDirectories.has(entry.path) && !nextDirectories.has(entry.path)).sort((a, b) => b.path.length - a.path.length)) try {
195
- await control.mutate(() => store.rm(entry.path, { force: true }));
196
- } catch {}
197
- }
198
- async function* iterateSourceItems(source, ctx) {
199
- if (source.source.getItems) {
200
- yield* await source.source.getItems(ctx);
201
- return;
202
- }
203
- for (const key of await source.source.getKeys(ctx)) yield await source.source.getItem(key, ctx);
204
- }
205
- function createMaterializationEntry(source, item, upstreamMeta) {
206
- const { path, sourcePath } = normalizeSourceItemPath(source, item, { operation: "source materialization" });
207
- return {
208
- item,
209
- metadata: createLazyMaterializedMetadata({
210
- sourceKey: source.key,
211
- sourcePath,
212
- validate: source.validate
213
- }, item, upstreamMeta),
214
- path,
215
- ...sourceItemContent(item)
216
- };
217
- }
218
- function sourceItemContent(item) {
219
- if (item.contentStream) {
220
- if (item.content !== void 0 || item.data !== void 0) throw workspaceError("[vitehub] Workspace source items cannot define contentStream with content or data.");
221
- return { contentStream: item.contentStream };
222
- }
223
- return { content: item.content ?? (item.data === void 0 ? "" : JSON.stringify(item.data, null, 2)) };
224
- }
225
- async function* iterateMaterializationEntries(source, ctx, store, snapshot, configHash, options) {
226
- const directKey = directMaterializationSourceKey(source, options);
227
- if (directKey) {
228
- const entry = createMaterializationEntry(source, await source.source.getItem(directKey, ctx), void 0);
229
- if (materializationPathMatches(entry.path, options)) yield entry;
230
- return;
231
- }
232
- if (source.source.getItems) {
233
- for await (const item of iterateSourceItems(source, ctx)) {
234
- const entry = createMaterializationEntry(source, item, item.metadata ?? await source.source.getMeta?.(item.key, ctx));
235
- if (materializationPathMatches(entry.path, options)) yield entry;
236
- }
237
- return;
238
- }
239
- for (const key of await source.source.getKeys(ctx)) {
240
- const upstreamMeta = await source.source.getMeta?.(key, ctx);
241
- const { path, sourcePath } = normalizeWorkspaceSourceItemPath(source, key, { operation: "source materialization" });
242
- if (!materializationPathMatches(path, options)) continue;
243
- const previous = materializedItemMeta(snapshot, configHash, path);
244
- if (upstreamMeta && previous?.source === source.key && previous.sourcePath === sourcePath && !hasSourceMetaChanged(previous, upstreamMeta)) {
245
- const stat = await store.stat(path);
246
- if (stat?.type === "file") {
247
- yield {
248
- metadata: previous,
249
- path,
250
- reused: stat
251
- };
252
- continue;
253
- }
254
- }
255
- yield createMaterializationEntry(source, await source.source.getItem(key, ctx), upstreamMeta);
256
- }
257
- }
258
- async function materializeWorkspaceSources(definition, store, options = {}, control = {
259
- isCurrent: () => true,
260
- async mutate(operation) {
261
- return await operation();
262
- },
263
- async checkpoint(operation) {
264
- return await operation();
265
- }
266
- }) {
267
- const assertCurrent = () => {
268
- if (!control.isCurrent()) throw options.abortSignal?.reason ?? workspaceError("[vitehub] Workspace source materialization was superseded.");
269
- };
270
- const started = Date.now();
271
- const configuredSources = normalizeWorkspaceSources(definition.sources);
272
- const sources = configuredSources.filter((source) => shouldMaterializeSource(source, options));
273
- const resultSources = [];
274
- let files = 0;
275
- let directories = 0;
276
- let bytes = 0;
277
- for (const source of sources) {
278
- throwIfAborted(options.abortSignal);
279
- const sourceStarted = Date.now();
280
- await reportMaterializationProgress(options, source, { status: "started" });
281
- let configHash;
282
- let existing;
283
- try {
284
- configHash = await sourceConfigHash(source);
285
- existing = await readSourceSnapshotMetadata(store, source.key);
286
- } catch (error) {
287
- const durationMs = Date.now() - sourceStarted;
288
- const message = error instanceof Error ? error.message : String(error);
289
- const failed = {
290
- counts: emptyMaterializationCounts(),
291
- durationMs,
292
- error: message,
293
- mountPath: source.mountPath,
294
- provider: source.source.name,
295
- source: source.key,
296
- status: "error"
297
- };
298
- resultSources.push(failed);
299
- await reportMaterializationProgress(options, source, {
300
- counts: failed.counts,
301
- durationMs,
302
- error: message,
303
- status: "failed"
304
- });
305
- if (options.abortSignal?.aborted) throw error;
306
- continue;
307
- }
308
- const completeSource = materializesCompleteSource(source, options);
309
- const cacheHit = completeSource && isSnapshotFresh(existing, source, configHash);
310
- const cacheStatus = materializationCacheStatus(source, completeSource, cacheHit);
311
- if (cacheHit) {
312
- const durationMs = Date.now() - sourceStarted;
313
- const cachedPaths = Object.keys(existing?.items || {});
314
- const cachedFiles = cachedPaths.length || existing?.files || 0;
315
- const counts = {
316
- ...emptyMaterializationCounts(),
317
- unchanged: cachedFiles
318
- };
319
- const ready = {
320
- cacheStatus,
321
- counts,
322
- durationMs,
323
- source: source.key,
324
- mountPath: source.mountPath,
325
- provider: source.source.name,
326
- status: "ready",
327
- revision: existing?.revision,
328
- materializedAt: existing?.materializedAt,
329
- files: existing?.files,
330
- bytes: existing?.bytes
331
- };
332
- const paths = materializationPaths(options, cachedPaths.map((path) => ({
333
- path,
334
- status: "unchanged"
335
- })));
336
- if (paths) ready.paths = paths;
337
- resultSources.push(ready);
338
- files += cachedFiles;
339
- bytes += existing?.bytes || 0;
340
- await reportMaterializationProgress(options, source, {
341
- bytes: existing?.bytes || 0,
342
- cacheStatus,
343
- counts,
344
- durationMs,
345
- files: cachedFiles,
346
- revision: existing?.revision,
347
- status: "completed"
348
- });
349
- continue;
350
- }
351
- let revision = existing?.revision;
352
- const itemMetadata = existing?.configHash === configHash ? { ...existing.items } : {};
353
- if (completeSource) {
354
- assertCurrent();
355
- await control.mutate(() => writeSourceSnapshotMetadata(store, {
356
- configHash,
357
- source: source.key,
358
- mountPath: source.mountPath,
359
- status: "updating",
360
- revision,
361
- items: checkpointItems(itemMetadata),
362
- cacheMaxAge: source.cache ? source.cache.maxAge : void 0
363
- }));
364
- }
365
- let sourceFiles = 0;
366
- let sourceBytes = 0;
367
- let persistedBytesDelta = 0;
368
- let lastProgressAt = 0;
369
- const counts = emptyMaterializationCounts();
370
- const paths = [];
371
- try {
372
- const ctx = createSourceContext(definition, source, store, { abortSignal: options.abortSignal });
373
- throwIfAborted(options.abortSignal);
374
- await prepareWorkspaceSource(source.source, ctx);
375
- throwIfAborted(options.abortSignal);
376
- if (source.mountPath) await control.mutate(() => store.mkdir(source.mountPath, { recursive: true }));
377
- revision = ctx.revision;
378
- const directorySet = new Set(source.mountPath ? [source.mountPath] : []);
379
- const nextPaths = /* @__PURE__ */ new Set();
380
- for await (const entry of iterateMaterializationEntries(source, ctx, store, existing, configHash, options)) {
381
- throwIfAborted(options.abortSignal);
382
- const path = entry.path;
383
- nextPaths.add(path);
384
- const parts = path.split("/");
385
- for (let index = 1; index < parts.length; index++) directorySet.add(parts.slice(0, index).join("/"));
386
- if (entry.reused) {
387
- itemMetadata[path] = entry.metadata;
388
- sourceFiles++;
389
- const reusedFile = entry.reused.size === void 0 ? await store.readFile(path) : void 0;
390
- sourceBytes += entry.reused.size ?? (reusedFile ? contentSize(reusedFile.content) : 0);
391
- counts.unchanged++;
392
- paths.push({
393
- path,
394
- status: "unchanged"
395
- });
396
- if (shouldReportMaterializationUpdate(lastProgressAt, sourceFiles)) {
397
- lastProgressAt = Date.now();
398
- await reportMaterializationProgress(options, source, {
399
- bytes: sourceBytes,
400
- cacheStatus,
401
- counts: { ...counts },
402
- files: sourceFiles,
403
- revision,
404
- status: "updating"
405
- });
406
- }
407
- continue;
408
- }
409
- const item = entry.item;
410
- const metadata = item.metadata || {};
411
- const previousStat = await store.stat(path);
412
- const previous = entry.contentStream && store.writeFileStream ? void 0 : await store.readFile(path);
413
- const previousExists = previousStat?.type === "file" || Boolean(previous);
414
- const fileMetadata = {
415
- ...metadata,
416
- ...entry.metadata,
417
- source: source.key
418
- };
419
- const written = await writeMaterializedFile(store, path, {
420
- path,
421
- content: entry.content,
422
- contentStream: entry.contentStream,
423
- mediaType: item.mediaType,
424
- metadata: fileMetadata
425
- }, control, previous?.content);
426
- const tracked = Object.hasOwn(itemMetadata, path);
427
- const previousItemMetadata = itemMetadata[path];
428
- itemMetadata[path] = {
429
- ...entry.metadata,
430
- materializedAttributes: true,
431
- materializedBytes: written.size || 0,
432
- materializedMediaType: item.mediaType,
433
- materializedMetadata: observableFileMetadata(fileMetadata)
434
- };
435
- sourceFiles++;
436
- sourceBytes += written.size || 0;
437
- persistedBytesDelta += (written.size || 0) - (tracked ? previousItemMetadata?.materializedBytes ?? previousStat?.size ?? (previous ? contentSize(previous.content) : 0) : 0);
438
- const status = (entry.contentStream ? store.writeFileStream ? previousStat?.type === "file" && previousStat.digest !== void 0 && previousStat.digest === written.digest : written.contentEqual === true : previous !== void 0 && contentEquals(previous.content, entry.content ?? "")) && fileAttributesEqual(previous ?? previousStat ?? {}, previousItemMetadata, item.mediaType, fileMetadata) ? "unchanged" : previousExists ? "updated" : "added";
439
- counts[status]++;
440
- paths.push({
441
- path,
442
- status
443
- });
444
- if (shouldReportMaterializationUpdate(lastProgressAt, sourceFiles)) {
445
- lastProgressAt = Date.now();
446
- await reportMaterializationProgress(options, source, {
447
- bytes: sourceBytes,
448
- cacheStatus,
449
- counts: { ...counts },
450
- files: sourceFiles,
451
- revision,
452
- status: "updating"
453
- });
454
- }
455
- }
456
- throwIfAborted(options.abortSignal);
457
- await removeStaleMaterializedSourceFiles(store, source, configuredSources, nextPaths, options, control, new Set(Object.keys(existing?.items || {})), (path, removedBytes) => {
458
- counts.removed++;
459
- if (Object.hasOwn(itemMetadata, path)) persistedBytesDelta -= itemMetadata[path]?.materializedBytes ?? removedBytes;
460
- delete itemMetadata[path];
461
- paths.push({
462
- path,
463
- status: "removed"
464
- });
465
- });
466
- const readyItems = Object.fromEntries([...nextPaths].flatMap((path) => {
467
- const metadata = itemMetadata[path];
468
- return metadata ? [[path, metadata]] : [];
469
- }));
470
- const ready = {
471
- configHash,
472
- source: source.key,
473
- mountPath: source.mountPath,
474
- status: "ready",
475
- revision,
476
- materializedAt: (/* @__PURE__ */ new Date()).toISOString(),
477
- files: sourceFiles,
478
- bytes: sourceBytes,
479
- items: readyItems,
480
- cacheMaxAge: source.cache ? source.cache.maxAge : void 0
481
- };
482
- if (completeSource) await control.mutate(() => writeSourceSnapshotMetadata(store, ready));
483
- else if (existing?.configHash === configHash) {
484
- const scopedItems = checkpointItems(itemMetadata);
485
- await control.mutate(() => writeSourceSnapshotMetadata(store, {
486
- ...existing,
487
- bytes: Math.max(0, (existing.bytes || 0) + persistedBytesDelta),
488
- files: scopedItems ? Object.keys(scopedItems).length : 0,
489
- items: scopedItems
490
- }));
491
- }
492
- const durationMs = Date.now() - sourceStarted;
493
- const resultSource = {
494
- ...ready,
495
- cacheStatus,
496
- counts: { ...counts },
497
- durationMs,
498
- provider: source.source.name
499
- };
500
- const reportedPaths = materializationPaths(options, paths);
501
- if (reportedPaths) resultSource.paths = reportedPaths;
502
- resultSources.push(resultSource);
503
- files += sourceFiles;
504
- bytes += sourceBytes;
505
- directories += directorySet.size;
506
- await reportMaterializationProgress(options, source, {
507
- bytes: sourceBytes,
508
- cacheStatus,
509
- counts: { ...counts },
510
- directories: directorySet.size,
511
- durationMs,
512
- files: sourceFiles,
513
- revision,
514
- status: "completed"
515
- });
516
- } catch (error) {
517
- const checkpointItemsMetadata = checkpointItems(itemMetadata);
518
- const resumesExistingSnapshot = existing?.configHash === configHash;
519
- const failed = {
520
- configHash,
521
- source: source.key,
522
- mountPath: source.mountPath,
523
- status: "error",
524
- revision,
525
- error: error instanceof Error ? error.message : String(error),
526
- files: resumesExistingSnapshot && checkpointItemsMetadata ? Object.keys(checkpointItemsMetadata).length : sourceFiles,
527
- bytes: resumesExistingSnapshot ? Math.max(0, (existing?.bytes || 0) + persistedBytesDelta) : sourceBytes,
528
- items: checkpointItemsMetadata,
529
- cacheMaxAge: source.cache ? source.cache.maxAge : void 0
530
- };
531
- const checkpoint = options.abortSignal?.aborted ? completeSource ? {
532
- ...failed,
533
- status: "updating",
534
- error: void 0
535
- } : existing?.configHash === configHash ? {
536
- ...existing,
537
- items: checkpointItemsMetadata
538
- } : void 0 : failed;
539
- if (checkpoint && control.isCurrent()) await control.checkpoint(() => writeSourceSnapshotMetadata(store, checkpoint));
540
- const durationMs = Date.now() - sourceStarted;
541
- const failedSource = {
542
- ...failed,
543
- cacheStatus,
544
- counts: { ...counts },
545
- durationMs,
546
- provider: source.source.name
547
- };
548
- const reportedPaths = materializationPaths(options, paths);
549
- if (reportedPaths) failedSource.paths = reportedPaths;
550
- resultSources.push(failedSource);
551
- await reportMaterializationProgress(options, source, {
552
- bytes: sourceBytes,
553
- cacheStatus,
554
- counts: { ...counts },
555
- durationMs,
556
- error: failed.error,
557
- files: sourceFiles,
558
- revision,
559
- status: "failed"
560
- });
561
- if (options.abortSignal?.aborted) throw error;
562
- }
563
- }
564
- return {
565
- bytes,
566
- directories,
567
- durationMs: Date.now() - started,
568
- files,
569
- path: normalizeWorkspacePath(options.path || ""),
570
- sources: resultSources
571
- };
572
- }
573
- async function readResolvedSourceFile(resolution, store, ctx, options) {
574
- const file = await store.readFile(resolution.workspacePath);
575
- if (!file) throw workspaceError(`[vitehub] Workspace file does not exist: ${resolution.workspacePath}.`);
576
- return decodeFile(file.content, options);
577
- }
578
- async function writeMaterializedFile(store, path, file, control, previousContent) {
579
- if (file.contentStream) {
580
- if (store.writeFileStream) {
581
- let size = 0;
582
- const content = (async function* () {
583
- for await (const chunk of contentStreamChunks(file.contentStream)) {
584
- size += chunk.byteLength;
585
- yield chunk;
586
- }
587
- })();
588
- const write = () => store.writeFileStream(path, {
589
- path: file.path,
590
- content,
591
- mediaType: file.mediaType,
592
- metadata: file.metadata
593
- });
594
- const written = control ? await control.mutate(write) : await write();
595
- if (!written.digest) throw workspaceError("[vitehub] Workspace Store writeFileStream() must return a content digest.");
596
- return {
597
- digest: written.digest,
598
- size
599
- };
600
- }
601
- const content = await contentStreamToBytes(file.contentStream);
602
- if (control) await control.mutate(() => store.writeFile(path, {
603
- path: file.path,
604
- content,
605
- mediaType: file.mediaType,
606
- metadata: file.metadata
607
- }));
608
- else await store.writeFile(path, {
609
- path: file.path,
610
- content,
611
- mediaType: file.mediaType,
612
- metadata: file.metadata
613
- });
614
- return {
615
- contentEqual: previousContent !== void 0 && contentEquals(previousContent, content),
616
- size: content.byteLength
617
- };
618
- }
619
- const content = file.content ?? "";
620
- if (control) await control.mutate(() => store.writeFile(path, {
621
- path: file.path,
622
- content,
623
- mediaType: file.mediaType,
624
- metadata: file.metadata
625
- }));
626
- else await store.writeFile(path, {
627
- path: file.path,
628
- content,
629
- mediaType: file.mediaType,
630
- metadata: file.metadata
631
- });
632
- return { size: contentSize(content) };
633
- }
634
- async function statVirtualSourcePath(source, workspacePath, store, ctx) {
635
- const stored = await store.stat(workspacePath);
636
- if (stored) return stored;
637
- const keys = await source.source.getKeys(ctx);
638
- const sourcePath = normalizeSourcePath(source, workspacePath);
639
- if (!sourcePath && keys.length > 0) return {
640
- path: source.mountPath,
641
- type: "directory"
642
- };
643
- if (keys.includes(sourcePath)) return {
644
- path: workspacePath,
645
- type: "file",
646
- digest: readDigest(await source.source.getMeta?.(sourcePath, ctx))
647
- };
648
- if (keys.some((key) => key.startsWith(`${sourcePath}/`))) return {
649
- path: workspacePath,
650
- type: "directory"
651
- };
652
- }
653
- async function searchMaterializedStore(store, query) {
654
- const limit = query.limit ?? 100;
655
- const result = [];
656
- const entries = query.paths?.length ? (await Promise.all(query.paths.map(async (path) => {
657
- const [stat, nested] = await Promise.all([store.stat(path), store.glob(`${path}/**/*`)]);
658
- return [...stat?.type === "file" ? [stat] : [], ...nested];
659
- }))).flat() : await store.glob("**/*");
660
- for (const entry of entries) {
661
- if (entry.type !== "file") continue;
662
- const file = await store.readFile(entry.path);
663
- if (!file) continue;
664
- const text = file.content instanceof Uint8Array ? new TextDecoder().decode(file.content) : file.content;
665
- result.push(...searchText(entry.path, text, {
666
- ...query,
667
- limit: limit - result.length
668
- }));
669
- if (result.length >= limit) break;
670
- }
671
- return result.slice(0, limit);
672
- }
673
- function createLazyMaterializedMetadata(resolution, item, upstreamMeta) {
674
- const now = (/* @__PURE__ */ new Date()).toISOString();
675
- return {
676
- source: resolution.sourceKey,
677
- sourcePath: resolution.sourcePath,
678
- materializedAt: now,
679
- validatedAt: resolution.validate === "request" ? now : void 0,
680
- etag: readStringMeta(upstreamMeta, "etag"),
681
- sha: readStringMeta(upstreamMeta, "sha"),
682
- digest: readStringMeta(upstreamMeta, "digest") || readStringMeta(item.metadata, "digest"),
683
- ref: readStringMeta(upstreamMeta, "ref")
684
- };
685
- }
686
- function hasSourceMetaChanged(current, upstreamMeta) {
687
- const next = {
688
- etag: readStringMeta(upstreamMeta, "etag"),
689
- sha: readStringMeta(upstreamMeta, "sha"),
690
- digest: readStringMeta(upstreamMeta, "digest"),
691
- ref: readStringMeta(upstreamMeta, "ref")
692
- };
693
- return current.etag !== next.etag || current.sha !== next.sha || current.digest !== next.digest || current.ref !== next.ref;
694
- }
695
- function normalizeSourcePath(source, workspacePath) {
696
- if (workspacePath === source.mountPath) return "";
697
- return source.mountPath && workspacePath.startsWith(`${source.mountPath}/`) ? normalizeWorkspacePath(workspacePath.slice(source.mountPath.length + 1)) : normalizeWorkspacePath(workspacePath);
698
- }
699
- function readStringMeta(meta, key) {
700
- const value = meta?.[key];
701
- return Object.prototype.toString.call(value) === "[object String]" ? String(value) : void 0;
702
- }
703
- function readDigest(meta) {
704
- return readStringMeta(meta, "digest") || readStringMeta(meta, "sha");
705
- }
706
- //#endregion
707
- //#region src/storage/metadata-target.ts
708
- const workspaceMetadataTarget = Symbol.for("vitehub.workspace.metadataTarget");
709
- function forwardWorkspaceMetadataTarget(source, target) {
710
- const resolveTarget = source[workspaceMetadataTarget];
711
- if (resolveTarget) target[workspaceMetadataTarget] = resolveTarget.bind(source);
712
- }
713
- async function resolveWorkspaceMetadataTarget(source) {
714
- return await source[workspaceMetadataTarget]?.();
715
- }
716
- //#endregion
717
- export { hasFreshSourceSnapshot as a, readCurrentSourceSnapshot as c, sourceSnapshotMetaKey as d, sourceSnapshotOwnsAnyPath as f, hasCurrentSourceSnapshot as i, readResolvedSourceFile as l, normalizeSourceItemPath as m, resolveWorkspaceMetadataTarget as n, materializeWorkspaceSources as o, statVirtualSourcePath as p, workspaceMetadataTarget as r, materializesCompleteSource as s, forwardWorkspaceMetadataTarget as t, searchMaterializedStore as u };