@vite-hub/workspace 0.0.0 → 0.0.2
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.
- package/README.md +262 -1
- package/dist/ai-Cztw4eLk.js +472 -0
- package/dist/ai-hFdsvDHC.d.ts +162 -0
- package/dist/ai.d.ts +3 -0
- package/dist/ai.js +2 -0
- package/dist/artifacts-store-BAV9jZpd.js +555 -0
- package/dist/asset-registry-CaG9b7tf.js +19 -0
- package/dist/chunk-8H4AJuhK.js +14 -0
- package/dist/cli.d.ts +31 -0
- package/dist/cli.js +303 -0
- package/dist/cloudflare-env-CKxUs2fa.js +20 -0
- package/dist/cloudflare.d.ts +16 -0
- package/dist/cloudflare.js +3 -0
- package/dist/collections/client.d.ts +39 -0
- package/dist/collections/client.js +137 -0
- package/dist/collections.d.ts +59 -0
- package/dist/collections.js +159 -0
- package/dist/config--r5unwPc.js +7811 -0
- package/dist/config-Ca5DM8fF.d.ts +28 -0
- package/dist/config-DCQ6y30R.js +30 -0
- package/dist/file-B2q9NE18.js +24 -0
- package/dist/files-xy0le-_U.js +51 -0
- package/dist/github-lIO6-2sH.js +194 -0
- package/dist/glob-DeH0dzZX.js +23 -0
- package/dist/host-I-_vDs05.js +370 -0
- package/dist/hosted-vercel-blob.d.ts +15 -0
- package/dist/hosted-vercel-blob.js +26 -0
- package/dist/hosted.d.ts +18 -0
- package/dist/hosted.js +30 -0
- package/dist/index.d.ts +185 -0
- package/dist/index.js +541 -0
- package/dist/lifecycle-Lhk3dAMt.js +176 -0
- package/dist/loader.d.ts +17 -0
- package/dist/loader.js +22 -0
- package/dist/nitro.d.ts +2 -0
- package/dist/nitro.js +2 -0
- package/dist/nuxt.d.ts +26 -0
- package/dist/nuxt.js +36 -0
- package/dist/path-CNI6wKIU.js +115 -0
- package/dist/provider-CeQciesl.js +599 -0
- package/dist/providers/cloudflare/artifacts-store.d.ts +6 -0
- package/dist/providers/cloudflare/artifacts-store.js +2 -0
- package/dist/providers/github/store.d.ts +6 -0
- package/dist/providers/github/store.js +362 -0
- package/dist/providers/vercel/blob-store.d.ts +6 -0
- package/dist/providers/vercel/blob-store.js +235 -0
- package/dist/publish.d.ts +35 -0
- package/dist/publish.js +112 -0
- package/dist/registry-C7DMdBXN.js +74 -0
- package/dist/registry-CoC9JxVt.d.ts +11 -0
- package/dist/request-execution-C8qRcReq.js +80 -0
- package/dist/runtime/assets.d.ts +12 -0
- package/dist/runtime/assets.js +138 -0
- package/dist/runtime/empty-assets-registry.d.ts +6 -0
- package/dist/runtime/empty-assets-registry.js +4 -0
- package/dist/runtime/empty-registry.d.ts +6 -0
- package/dist/runtime/empty-registry.js +4 -0
- package/dist/runtime/state.d.ts +4 -0
- package/dist/runtime/state.js +15 -0
- package/dist/runtime/workspace.d.ts +2 -0
- package/dist/runtime/workspace.js +2 -0
- package/dist/runtime.d.ts +38 -0
- package/dist/runtime.js +643 -0
- package/dist/search-C4REyHj9.js +39 -0
- package/dist/server.d.ts +65 -0
- package/dist/server.js +355 -0
- package/dist/shared-BRycRSbo.js +255 -0
- package/dist/source-metadata.d.ts +2 -0
- package/dist/source-metadata.js +2 -0
- package/dist/state-DSAHEsq6.d.ts +25 -0
- package/dist/sync-DO42ypji.js +269 -0
- package/dist/target-D4Bqb1eH.js +11 -0
- package/dist/test.d.ts +2 -0
- package/dist/test.js +2 -0
- package/dist/types-DHkae7Cb.d.ts +628 -0
- package/dist/use-D16tf8Ph.d.ts +86 -0
- package/dist/use-d_PlAdOu.js +353 -0
- package/dist/utils-BPdaCyI6.js +55 -0
- package/dist/vite-NWC9mFjI.js +1882 -0
- package/dist/vite.d.ts +50 -0
- package/dist/vite.js +2 -0
- package/dist/workspace-f2DBLmPZ.d.ts +6 -0
- package/dist/workspace-n4wBmdaM.js +1476 -0
- package/package.json +197 -5
|
@@ -0,0 +1,1476 @@
|
|
|
1
|
+
import { a as matchesAny, c as normalizeWorkspacePath, d as sha256, i as decodeFile, n as contentStreamToBytes, o as normalizeSafeWorkspacePath, p as workspaceError, r as contentToBytes } from "./path-CNI6wKIU.js";
|
|
2
|
+
import { a as normalizeWorkspaceSources, c as sourceMountIntersectsPath, h as workspaceSourceRequestDescriptorPath, n as createSourceContext, s as sourceMountContainsPath } from "./config--r5unwPc.js";
|
|
3
|
+
import { n as createWorkspaceSourceRequestExecution, t as attachWorkspaceSourceRequestExecution } from "./request-execution-C8qRcReq.js";
|
|
4
|
+
import { s as createMemoryWorkspaceStore, t as createWorkspaceStoreFromProvider } from "./provider-CeQciesl.js";
|
|
5
|
+
import { t as forwardWorkspaceStoreTarget } from "./target-D4Bqb1eH.js";
|
|
6
|
+
import { t as searchText } from "./search-C4REyHj9.js";
|
|
7
|
+
import { posix } from "node:path";
|
|
8
|
+
import { minimatch } from "minimatch";
|
|
9
|
+
import { noExecutionAuthority } from "@vite-hub/runtime";
|
|
10
|
+
//#region src/session/scope.ts
|
|
11
|
+
function isMissingWorkspacePathError(error) {
|
|
12
|
+
return error instanceof Error && error.message.includes("Workspace path does not exist:");
|
|
13
|
+
}
|
|
14
|
+
function pathInSessionScope(path, paths) {
|
|
15
|
+
return !paths || paths.some((scope) => path === scope || path.startsWith(`${scope}/`));
|
|
16
|
+
}
|
|
17
|
+
function pathIntersectsSessionScope(path, paths) {
|
|
18
|
+
return pathInSessionScope(path, paths) || Boolean(paths?.some((scope) => scope.startsWith(`${path}/`)));
|
|
19
|
+
}
|
|
20
|
+
function mkdirPathInSessionScope(path, paths) {
|
|
21
|
+
return pathInSessionScope(path, paths) || Boolean(paths?.some((scope) => scope.startsWith(`${path}/`)));
|
|
22
|
+
}
|
|
23
|
+
function assertPathInSessionScope(path, paths, options = {}) {
|
|
24
|
+
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.`);
|
|
25
|
+
return path;
|
|
26
|
+
}
|
|
27
|
+
function assertDiffInsideSessionPaths(diff, paths) {
|
|
28
|
+
if (!paths) return;
|
|
29
|
+
const entry = diff.entries.find((entry) => !diffEntryInSessionScope(entry, paths));
|
|
30
|
+
if (entry) throw workspaceError(`[vitehub] Workspace session path ${entry.path} is outside the session scope.`);
|
|
31
|
+
}
|
|
32
|
+
function filterSessionEntries(entries, paths) {
|
|
33
|
+
if (!paths) return entries;
|
|
34
|
+
return entries.filter((entry) => pathIntersectsSessionScope(entry.path, paths));
|
|
35
|
+
}
|
|
36
|
+
function filterSessionDiff(diff, paths) {
|
|
37
|
+
if (!paths) return diff;
|
|
38
|
+
return {
|
|
39
|
+
...diff,
|
|
40
|
+
entries: diff.entries.filter((entry) => diffEntryInSessionScope(entry, paths))
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function diffEntryInSessionScope(entry, paths) {
|
|
44
|
+
if (pathInSessionScope(entry.path, paths)) return true;
|
|
45
|
+
return entry.after?.type === "directory" && pathIntersectsSessionScope(entry.path, paths);
|
|
46
|
+
}
|
|
47
|
+
function scopedSearchQuery(query, paths, normalizePath) {
|
|
48
|
+
if (!paths) return query;
|
|
49
|
+
const requested = query.paths?.length ? query.paths : [query.cwd || ""];
|
|
50
|
+
const scoped = /* @__PURE__ */ new Set();
|
|
51
|
+
for (const rawPath of requested) {
|
|
52
|
+
const path = normalizePath(rawPath);
|
|
53
|
+
for (const scope of paths) if (!path || pathInSessionScope(scope, [path])) scoped.add(scope);
|
|
54
|
+
else if (pathInSessionScope(path, [scope])) scoped.add(path);
|
|
55
|
+
}
|
|
56
|
+
if (!scoped.size) return void 0;
|
|
57
|
+
return {
|
|
58
|
+
...query,
|
|
59
|
+
cwd: void 0,
|
|
60
|
+
paths: [...scoped].sort((left, right) => left.localeCompare(right))
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/session/basic.ts
|
|
65
|
+
function unsupportedExec() {
|
|
66
|
+
throw workspaceError("[vitehub] Workspace exec requires a Box session host. Pass the active Box session to workspace.startSession({ host }).");
|
|
67
|
+
}
|
|
68
|
+
function normalizeSessionPaths(options) {
|
|
69
|
+
const paths = [...new Set((options?.paths || []).map((path) => normalizeSafeWorkspacePath(path, {
|
|
70
|
+
allowEmpty: true,
|
|
71
|
+
allowReserved: true
|
|
72
|
+
})))];
|
|
73
|
+
if (!paths.length || paths.includes("")) return void 0;
|
|
74
|
+
return paths.sort((left, right) => left.length - right.length || left.localeCompare(right));
|
|
75
|
+
}
|
|
76
|
+
function normalizeSessionPath(path = "", options = {}) {
|
|
77
|
+
const normalized = path.replace(/\\/g, "/");
|
|
78
|
+
return normalizeSafeWorkspacePath(normalized === "." ? "" : normalized, {
|
|
79
|
+
allowEmpty: options.allowEmpty,
|
|
80
|
+
allowReserved: true
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
async function createBasicWorkspaceSession(workspace, options) {
|
|
84
|
+
const sessionPaths = normalizeSessionPaths(options);
|
|
85
|
+
const overlay = createMemoryWorkspaceStore();
|
|
86
|
+
const initialEntries = filterSessionEntries(await workspace.list("", { recursive: true }), sessionPaths);
|
|
87
|
+
for (const entry of initialEntries.filter((entry) => entry.type === "directory")) await overlay.mkdir(entry.path, { recursive: true });
|
|
88
|
+
for (const entry of initialEntries.filter((entry) => entry.type === "file")) await overlay.writeFile(entry.path, {
|
|
89
|
+
content: await workspace.readFile(entry.path, { encoding: "binary" }),
|
|
90
|
+
mediaType: entry.mediaType,
|
|
91
|
+
metadata: entry.metadata,
|
|
92
|
+
path: entry.path
|
|
93
|
+
});
|
|
94
|
+
await overlay.snapshot({ name: "session-baseline" });
|
|
95
|
+
return {
|
|
96
|
+
executionAuthority: noExecutionAuthority,
|
|
97
|
+
async readFile(path, readOptions) {
|
|
98
|
+
const target = assertPathInSessionScope(normalizeSessionPath(path), sessionPaths, { masked: true });
|
|
99
|
+
const file = await overlay.readFile(target);
|
|
100
|
+
if (!file) throw workspaceError(`[vitehub] Workspace file does not exist: ${path}.`);
|
|
101
|
+
return decodeFile(file.content, readOptions);
|
|
102
|
+
},
|
|
103
|
+
async writeFile(path, content, writeOptions) {
|
|
104
|
+
const target = assertPathInSessionScope(normalizeSessionPath(path), sessionPaths);
|
|
105
|
+
await overlay.writeFile(target, {
|
|
106
|
+
content,
|
|
107
|
+
path: target,
|
|
108
|
+
...writeOptions
|
|
109
|
+
});
|
|
110
|
+
},
|
|
111
|
+
async mkdir(path, mkdirOptions) {
|
|
112
|
+
await overlay.mkdir(assertPathInSessionScope(normalizeSessionPath(path, { allowEmpty: true }), sessionPaths, { mkdir: true }), mkdirOptions);
|
|
113
|
+
},
|
|
114
|
+
async rm(path, rmOptions) {
|
|
115
|
+
await overlay.rm(assertPathInSessionScope(normalizeSessionPath(path), sessionPaths), rmOptions);
|
|
116
|
+
},
|
|
117
|
+
async list(path = "", listOptions = {}) {
|
|
118
|
+
return filterSessionEntries(await overlay.list(normalizeSessionPath(path, { allowEmpty: true }), listOptions), sessionPaths);
|
|
119
|
+
},
|
|
120
|
+
async glob(pattern, globOptions) {
|
|
121
|
+
const patterns = Array.isArray(pattern) ? pattern : [pattern];
|
|
122
|
+
const cwd = normalizeSessionPath(globOptions?.cwd || "", { allowEmpty: true });
|
|
123
|
+
return filterSessionEntries(await overlay.list("", { recursive: true }), sessionPaths).filter((entry) => {
|
|
124
|
+
if (entry.type !== "file") return false;
|
|
125
|
+
if (!cwd) return patterns.some((item) => matchesAny(entry.path, item));
|
|
126
|
+
if (!entry.path.startsWith(`${cwd}/`)) return false;
|
|
127
|
+
return patterns.some((item) => matchesAny(entry.path.slice(cwd.length + 1), item));
|
|
128
|
+
});
|
|
129
|
+
},
|
|
130
|
+
async search(query) {
|
|
131
|
+
const scoped = scopedSearchQuery(query, sessionPaths, (path) => normalizeSessionPath(path, { allowEmpty: true }));
|
|
132
|
+
if (!scoped) return [];
|
|
133
|
+
const roots = (scoped.paths?.length ? scoped.paths : [scoped.cwd || ""]).map((path) => normalizeSessionPath(path, { allowEmpty: true }));
|
|
134
|
+
const hits = [];
|
|
135
|
+
for (const entry of filterSessionEntries(await overlay.list("", { recursive: true }), sessionPaths).filter((entry) => entry.type === "file")) {
|
|
136
|
+
if (!roots.some((root) => !root || entry.path === root || entry.path.startsWith(`${root}/`))) continue;
|
|
137
|
+
const file = await overlay.readFile(entry.path);
|
|
138
|
+
if (!file) continue;
|
|
139
|
+
hits.push(...searchText(entry.path, decodeFile(file.content), {
|
|
140
|
+
...scoped,
|
|
141
|
+
limit: (scoped.limit || 100) - hits.length
|
|
142
|
+
}));
|
|
143
|
+
if (hits.length >= (scoped.limit || 100)) break;
|
|
144
|
+
}
|
|
145
|
+
return hits;
|
|
146
|
+
},
|
|
147
|
+
async diff() {
|
|
148
|
+
return filterSessionDiff(await overlay.diff(), sessionPaths);
|
|
149
|
+
},
|
|
150
|
+
async commit(commitOptions) {
|
|
151
|
+
const diff = await overlay.diff();
|
|
152
|
+
assertDiffInsideSessionPaths(diff, sessionPaths);
|
|
153
|
+
assertDiffInsideSessionPaths(await workspace.diff(), sessionPaths);
|
|
154
|
+
for (const entry of [...diff.entries].sort((left, right) => right.path.length - left.path.length)) if (entry.type === "removed") await workspace.rm(entry.path, {
|
|
155
|
+
force: true,
|
|
156
|
+
recursive: true
|
|
157
|
+
});
|
|
158
|
+
for (const entry of diff.entries) {
|
|
159
|
+
if (!entry.after) continue;
|
|
160
|
+
if (entry.after.type === "directory") {
|
|
161
|
+
if (entry.before?.type === "file") await workspace.rm(entry.path, { force: true });
|
|
162
|
+
await workspace.mkdir(entry.path, { recursive: true });
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (entry.before?.type === "directory") await workspace.rm(entry.path, {
|
|
166
|
+
force: true,
|
|
167
|
+
recursive: true
|
|
168
|
+
});
|
|
169
|
+
const file = await overlay.readFile(entry.path);
|
|
170
|
+
if (file) await workspace.writeFile(entry.path, file.content, {
|
|
171
|
+
mediaType: file.mediaType,
|
|
172
|
+
metadata: file.metadata
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
await workspace.snapshot({ name: commitOptions?.message || "session-commit" });
|
|
176
|
+
await overlay.snapshot({ name: commitOptions?.message || "session-commit" });
|
|
177
|
+
},
|
|
178
|
+
async exec(_command, _args = [], _options) {
|
|
179
|
+
unsupportedExec();
|
|
180
|
+
},
|
|
181
|
+
async close() {}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
//#endregion
|
|
185
|
+
//#region src/core/rules.ts
|
|
186
|
+
function normalizeMaxBytes(value) {
|
|
187
|
+
if (value === void 0) return void 0;
|
|
188
|
+
if (typeof value === "number") return value;
|
|
189
|
+
const match = /^(\d+)(kb|mb)$/.exec(value.toLowerCase());
|
|
190
|
+
if (!match) throw new TypeError(`[vitehub] Invalid workspace rule maxBytes value "${value}".`);
|
|
191
|
+
const count = Number(match[1]);
|
|
192
|
+
return match[2] === "kb" ? count * 1024 : count * 1024 * 1024;
|
|
193
|
+
}
|
|
194
|
+
function toArray(value) {
|
|
195
|
+
if (value === void 0) return [];
|
|
196
|
+
return Array.isArray(value) ? value : [value];
|
|
197
|
+
}
|
|
198
|
+
function mergeHooks(left = {}, right = {}) {
|
|
199
|
+
return {
|
|
200
|
+
"write:after": [...toArray(left["write:after"]), ...toArray(right["write:after"])],
|
|
201
|
+
"write:before": [...toArray(left["write:before"]), ...toArray(right["write:before"])],
|
|
202
|
+
"write:error": [...toArray(left["write:error"]), ...toArray(right["write:error"])],
|
|
203
|
+
"write:validate": [...toArray(left["write:validate"]), ...toArray(right["write:validate"])]
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
function normalizeRules(rules = {}) {
|
|
207
|
+
return Object.entries(rules).map(([pattern, rule]) => {
|
|
208
|
+
const normalizedPattern = normalizeWorkspacePath(pattern);
|
|
209
|
+
return {
|
|
210
|
+
...rule,
|
|
211
|
+
maxBytes: normalizeMaxBytes(rule.maxBytes),
|
|
212
|
+
pattern: normalizedPattern,
|
|
213
|
+
specificity: normalizedPattern.replace(/\*/g, "").length,
|
|
214
|
+
validate: toArray(rule.validate)
|
|
215
|
+
};
|
|
216
|
+
}).sort((left, right) => left.specificity - right.specificity || left.pattern.localeCompare(right.pattern));
|
|
217
|
+
}
|
|
218
|
+
function normalizePolicy(definition) {
|
|
219
|
+
let hooks = {};
|
|
220
|
+
let rules = {};
|
|
221
|
+
for (const plugin of definition.plugins || []) {
|
|
222
|
+
if (!plugin?.id) throw new TypeError("[vitehub] Workspace plugins require an id.");
|
|
223
|
+
rules = {
|
|
224
|
+
...rules,
|
|
225
|
+
...plugin.rules
|
|
226
|
+
};
|
|
227
|
+
hooks = mergeHooks(hooks, plugin.hooks);
|
|
228
|
+
}
|
|
229
|
+
rules = {
|
|
230
|
+
...rules,
|
|
231
|
+
...definition.rules
|
|
232
|
+
};
|
|
233
|
+
hooks = mergeHooks(hooks, definition.hooks);
|
|
234
|
+
return {
|
|
235
|
+
hooks,
|
|
236
|
+
rules: normalizeRules(rules)
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
function matchRule(policy, path) {
|
|
240
|
+
const normalized = normalizeWorkspacePath(path);
|
|
241
|
+
let matched;
|
|
242
|
+
for (const rule of policy.rules) {
|
|
243
|
+
const globstarDirectory = rule.pattern.endsWith("/**") ? rule.pattern.slice(0, -3) : void 0;
|
|
244
|
+
if (minimatch(normalized, rule.pattern, { dot: true }) || normalized === globstarDirectory) matched = rule;
|
|
245
|
+
}
|
|
246
|
+
return matched;
|
|
247
|
+
}
|
|
248
|
+
function writeAllowed(write, operation, exists) {
|
|
249
|
+
if (write === void 0 || write === true) return true;
|
|
250
|
+
if (write === false) return false;
|
|
251
|
+
if (write === "delete") return operation === "rm";
|
|
252
|
+
if (write === "create") return operation !== "rm" && !exists;
|
|
253
|
+
if (write === "update") return operation === "writeFile" && exists;
|
|
254
|
+
return true;
|
|
255
|
+
}
|
|
256
|
+
function sizeOf(content) {
|
|
257
|
+
return content === void 0 ? 0 : contentToBytes(content).byteLength;
|
|
258
|
+
}
|
|
259
|
+
function assertRuleAllows(input) {
|
|
260
|
+
const rule = input.rule;
|
|
261
|
+
if (!rule) return;
|
|
262
|
+
const exists = Boolean(input.previous);
|
|
263
|
+
if (!writeAllowed(rule.write, input.operation, exists)) throw workspaceError(`[vitehub] Workspace rule "${rule.pattern}" does not allow ${input.operation} for ${input.path}.`);
|
|
264
|
+
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}.`);
|
|
265
|
+
if (rule.mediaType && input.mediaType) {
|
|
266
|
+
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}.`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
async function runHooks(hooks, name, input) {
|
|
270
|
+
for (const hook of toArray(hooks[name])) await hook(input);
|
|
271
|
+
}
|
|
272
|
+
async function runValidators(validators, input) {
|
|
273
|
+
let current = input;
|
|
274
|
+
for (const validate of validators) {
|
|
275
|
+
const result = await validate(current);
|
|
276
|
+
if (result === false) throw workspaceError(`[vitehub] Workspace validator rejected ${current.operation} for ${current.path}.`);
|
|
277
|
+
if (typeof result === "object" && result !== null) current = result;
|
|
278
|
+
}
|
|
279
|
+
return current;
|
|
280
|
+
}
|
|
281
|
+
function createWorkspaceWritePolicy(definition) {
|
|
282
|
+
const policy = normalizePolicy(definition);
|
|
283
|
+
return {
|
|
284
|
+
async before(input) {
|
|
285
|
+
let current = {
|
|
286
|
+
...input,
|
|
287
|
+
rule: matchRule(policy, input.path)
|
|
288
|
+
};
|
|
289
|
+
await runHooks(policy.hooks, "write:before", current);
|
|
290
|
+
assertRuleAllows(current);
|
|
291
|
+
if (current.rule?.validate.length) current = await runValidators(current.rule.validate, current);
|
|
292
|
+
await runHooks(policy.hooks, "write:validate", current);
|
|
293
|
+
return current;
|
|
294
|
+
},
|
|
295
|
+
async after(input) {
|
|
296
|
+
await runHooks(policy.hooks, "write:after", input);
|
|
297
|
+
},
|
|
298
|
+
async error(input, error) {
|
|
299
|
+
for (const hook of toArray(policy.hooks["write:error"])) await hook({
|
|
300
|
+
...input,
|
|
301
|
+
error
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
function resolveWorkspaceAutoCommit(definition, diff) {
|
|
307
|
+
if (!diff.entries.length) return;
|
|
308
|
+
if (definition.commit === true || typeof definition.commit === "string") return {
|
|
309
|
+
message: (typeof definition.commit === "string" ? definition.commit.trim() : "") || `chore: update ${definition.name} workspace`,
|
|
310
|
+
paths: diff.entries.map((entry) => normalizeWorkspacePath(entry.path))
|
|
311
|
+
};
|
|
312
|
+
const policy = normalizePolicy(definition);
|
|
313
|
+
const paths = diff.entries.map((entry) => normalizeWorkspacePath(entry.path));
|
|
314
|
+
const rules = paths.map((path) => matchRule(policy, path));
|
|
315
|
+
if (!rules.length || rules.some((rule) => !rule?.commit)) return;
|
|
316
|
+
return {
|
|
317
|
+
message: rules.map((rule) => rule?.commit).find((commit) => typeof commit === "string" && commit.trim().length > 0)?.trim() || `chore: update ${definition.name} workspace`,
|
|
318
|
+
paths
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
//#endregion
|
|
322
|
+
//#region src/sources/source-items.ts
|
|
323
|
+
function normalizeWorkspaceSourceItemPath(source, rawSourcePath, options = {}) {
|
|
324
|
+
const sourcePath = normalizeSafeWorkspacePath(rawSourcePath, {
|
|
325
|
+
allowEmpty: false,
|
|
326
|
+
allowReserved: true
|
|
327
|
+
});
|
|
328
|
+
const label = options.operation ? `${options.operation} item path` : "source item path";
|
|
329
|
+
if (sourcePath.split("/").some((part) => part === ".git" || part === ".vitehub")) throw workspaceError(`[vitehub] Workspace ${label} is reserved: ${rawSourcePath}.`);
|
|
330
|
+
const path = normalizeSafeWorkspacePath(source.mountPath ? `${source.mountPath}/${sourcePath}` : sourcePath, { allowEmpty: false });
|
|
331
|
+
if (source.mountPath && !sourceMountContainsPath(source, path)) throw workspaceError(`[vitehub] Workspace ${label} escapes source mount: ${rawSourcePath}.`);
|
|
332
|
+
return {
|
|
333
|
+
path,
|
|
334
|
+
sourcePath
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
function normalizeSourceItemPath(source, item, options = {}) {
|
|
338
|
+
return normalizeWorkspaceSourceItemPath(source, item.path || item.key, options);
|
|
339
|
+
}
|
|
340
|
+
//#endregion
|
|
341
|
+
//#region src/sources/materialization.ts
|
|
342
|
+
function sourceSnapshotMetaKey(sourceKey) {
|
|
343
|
+
return `source:${sourceKey}:snapshot`;
|
|
344
|
+
}
|
|
345
|
+
function sourceConfigFingerprint(source) {
|
|
346
|
+
return {
|
|
347
|
+
cache: source.cache,
|
|
348
|
+
key: source.key,
|
|
349
|
+
materialize: source.materialize,
|
|
350
|
+
mountPath: source.mountPath,
|
|
351
|
+
source: source.source.fingerprint
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
async function sourceConfigHash(source) {
|
|
355
|
+
return await sha256(sourceConfigFingerprint(source));
|
|
356
|
+
}
|
|
357
|
+
function isSnapshotFresh(meta, source, configHash) {
|
|
358
|
+
if (!meta || meta.status !== "ready" || meta.configHash !== configHash) return false;
|
|
359
|
+
if (!source.cache || typeof source.cache.maxAge !== "number") return false;
|
|
360
|
+
if (!meta.materializedAt) return false;
|
|
361
|
+
return Date.now() - Date.parse(meta.materializedAt) <= source.cache.maxAge * 1e3;
|
|
362
|
+
}
|
|
363
|
+
async function readSourceSnapshotMetadata(store, sourceKey) {
|
|
364
|
+
return await store.getMeta?.(sourceSnapshotMetaKey(sourceKey));
|
|
365
|
+
}
|
|
366
|
+
async function hasCurrentSourceSnapshot(store, source) {
|
|
367
|
+
const configHash = await sourceConfigHash(source);
|
|
368
|
+
const meta = await readSourceSnapshotMetadata(store, source.key);
|
|
369
|
+
return meta?.status === "ready" && meta.configHash === configHash;
|
|
370
|
+
}
|
|
371
|
+
async function writeSourceSnapshotMetadata(store, metadata) {
|
|
372
|
+
await store.setMeta?.(sourceSnapshotMetaKey(metadata.source), metadata);
|
|
373
|
+
}
|
|
374
|
+
function materializedItemMeta(snapshot, configHash, path) {
|
|
375
|
+
if (!snapshot || snapshot.configHash !== configHash) return void 0;
|
|
376
|
+
if (snapshot.status !== "ready" && snapshot.status !== "updating" && snapshot.status !== "error") return void 0;
|
|
377
|
+
return snapshot.items?.[path];
|
|
378
|
+
}
|
|
379
|
+
function checkpointItems(items) {
|
|
380
|
+
return Object.keys(items).length ? items : void 0;
|
|
381
|
+
}
|
|
382
|
+
function contentSize(content) {
|
|
383
|
+
return typeof content === "string" ? new TextEncoder().encode(content).byteLength : content.byteLength;
|
|
384
|
+
}
|
|
385
|
+
function sourcePathMatches(path, source, options) {
|
|
386
|
+
if (options?.sources?.length && !options.sources.includes(source.key)) return false;
|
|
387
|
+
const requested = normalizeWorkspacePath(options?.path || "");
|
|
388
|
+
if (!requested) return true;
|
|
389
|
+
return sourceMountIntersectsPath(source, requested);
|
|
390
|
+
}
|
|
391
|
+
function pathContains(container, path) {
|
|
392
|
+
return !container || path === container || path.startsWith(`${container}/`);
|
|
393
|
+
}
|
|
394
|
+
function materializationPathMatches(path, options) {
|
|
395
|
+
return pathContains(normalizeWorkspacePath(options?.path || ""), path);
|
|
396
|
+
}
|
|
397
|
+
function materializesCompleteSource(source, options) {
|
|
398
|
+
const requested = normalizeWorkspacePath(options?.path || "");
|
|
399
|
+
return !requested || Boolean(source.mountPath && pathContains(requested, source.mountPath));
|
|
400
|
+
}
|
|
401
|
+
function shouldMaterializeSource(source, options) {
|
|
402
|
+
if (source.requestOnly || !sourcePathMatches("", source, options)) return false;
|
|
403
|
+
if (source.materialize === "lazy") return true;
|
|
404
|
+
return source.materialize === "build" && Boolean(options?.path);
|
|
405
|
+
}
|
|
406
|
+
function throwIfAborted(signal) {
|
|
407
|
+
if (!signal?.aborted) return;
|
|
408
|
+
throw signal.reason instanceof Error ? signal.reason : workspaceError("[vitehub] Workspace source materialization aborted.");
|
|
409
|
+
}
|
|
410
|
+
async function reportMaterializationProgress(options, source, event) {
|
|
411
|
+
await options?.onProgress?.({
|
|
412
|
+
...event,
|
|
413
|
+
mountPath: source.mountPath,
|
|
414
|
+
path: normalizeWorkspacePath(options?.path || ""),
|
|
415
|
+
source: source.key
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
function shouldReportMaterializationUpdate(lastReportedAt, files) {
|
|
419
|
+
return files === 1 || files % 25 === 0 || Date.now() - lastReportedAt >= 1e3;
|
|
420
|
+
}
|
|
421
|
+
function looksLikeConcreteFilePath(path) {
|
|
422
|
+
const name = posix.basename(path);
|
|
423
|
+
return name.includes(".") || [
|
|
424
|
+
"Dockerfile",
|
|
425
|
+
"LICENSE",
|
|
426
|
+
"Makefile",
|
|
427
|
+
"Procfile",
|
|
428
|
+
"README"
|
|
429
|
+
].includes(name);
|
|
430
|
+
}
|
|
431
|
+
function directMaterializationSourceKey(source, options) {
|
|
432
|
+
const requested = normalizeWorkspacePath(options?.path || "");
|
|
433
|
+
if (!requested || !sourceMountContainsPath(source, requested) || requested === source.mountPath) return;
|
|
434
|
+
const sourcePath = source.mountPath ? requested.slice(source.mountPath.length + 1) : requested;
|
|
435
|
+
return sourcePath && looksLikeConcreteFilePath(sourcePath) ? sourcePath : void 0;
|
|
436
|
+
}
|
|
437
|
+
function parentDirectoryPaths(path) {
|
|
438
|
+
const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
|
|
439
|
+
const paths = [];
|
|
440
|
+
for (let index = 1; index < parts.length; index++) paths.push(parts.slice(0, index).join("/"));
|
|
441
|
+
return paths;
|
|
442
|
+
}
|
|
443
|
+
async function removeStaleMaterializedSourceFiles(store, source, nextPaths, scope, options = {}) {
|
|
444
|
+
const entries = await store.list(source.mountPath, { recursive: true });
|
|
445
|
+
const nextDirectories = new Set([...nextPaths].flatMap((path) => parentDirectoryPaths(path)));
|
|
446
|
+
const staleDirectories = /* @__PURE__ */ new Set();
|
|
447
|
+
for (const entry of entries) {
|
|
448
|
+
if (!materializationPathMatches(entry.path, scope)) continue;
|
|
449
|
+
if (nextPaths.has(entry.path) || entry.type !== "file") continue;
|
|
450
|
+
const file = await store.readFile(entry.path);
|
|
451
|
+
if (options.removeUntracked || file?.metadata?.source === source.key) {
|
|
452
|
+
for (const directory of parentDirectoryPaths(entry.path)) staleDirectories.add(directory);
|
|
453
|
+
await store.rm(entry.path, { force: true });
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
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 {
|
|
457
|
+
await store.rm(entry.path, { force: true });
|
|
458
|
+
} catch {}
|
|
459
|
+
}
|
|
460
|
+
async function* iterateSourceItems(source, ctx) {
|
|
461
|
+
if (source.source.getItems) {
|
|
462
|
+
yield* await source.source.getItems(ctx);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
for (const key of await source.source.getKeys(ctx)) yield await source.source.getItem(key, ctx);
|
|
466
|
+
}
|
|
467
|
+
function createMaterializationEntry(source, item, upstreamMeta) {
|
|
468
|
+
const { path, sourcePath } = normalizeSourceItemPath(source, item, { operation: "source materialization" });
|
|
469
|
+
return {
|
|
470
|
+
item,
|
|
471
|
+
metadata: createLazyMaterializedMetadata({
|
|
472
|
+
sourceKey: source.key,
|
|
473
|
+
sourcePath,
|
|
474
|
+
validate: source.validate
|
|
475
|
+
}, item, upstreamMeta),
|
|
476
|
+
path,
|
|
477
|
+
...sourceItemContent$1(item)
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
function sourceItemContent$1(item) {
|
|
481
|
+
if (item.contentStream) {
|
|
482
|
+
if (typeof item.content !== "undefined" || typeof item.data !== "undefined") throw workspaceError("[vitehub] Workspace source items cannot define contentStream with content or data.");
|
|
483
|
+
return { contentStream: item.contentStream };
|
|
484
|
+
}
|
|
485
|
+
return { content: item.content ?? (typeof item.data === "undefined" ? "" : JSON.stringify(item.data, null, 2)) };
|
|
486
|
+
}
|
|
487
|
+
async function* iterateMaterializationEntries(source, ctx, store, snapshot, configHash, options) {
|
|
488
|
+
const directKey = directMaterializationSourceKey(source, options);
|
|
489
|
+
if (directKey) {
|
|
490
|
+
const entry = createMaterializationEntry(source, await source.source.getItem(directKey, ctx), void 0);
|
|
491
|
+
if (materializationPathMatches(entry.path, options)) yield entry;
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
if (source.source.getItems) {
|
|
495
|
+
for await (const item of iterateSourceItems(source, ctx)) {
|
|
496
|
+
const entry = createMaterializationEntry(source, item, await source.source.getMeta?.(item.key, ctx));
|
|
497
|
+
if (materializationPathMatches(entry.path, options)) yield entry;
|
|
498
|
+
}
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
for (const key of await source.source.getKeys(ctx)) {
|
|
502
|
+
const upstreamMeta = await source.source.getMeta?.(key, ctx);
|
|
503
|
+
const { path, sourcePath } = normalizeWorkspaceSourceItemPath(source, key, { operation: "source materialization" });
|
|
504
|
+
if (!materializationPathMatches(path, options)) continue;
|
|
505
|
+
const previous = materializedItemMeta(snapshot, configHash, path);
|
|
506
|
+
if (upstreamMeta && previous?.source === source.key && previous.sourcePath === sourcePath && !hasSourceMetaChanged(previous, upstreamMeta)) {
|
|
507
|
+
const stat = await store.stat(path);
|
|
508
|
+
if (stat?.type === "file") {
|
|
509
|
+
yield {
|
|
510
|
+
metadata: previous,
|
|
511
|
+
path,
|
|
512
|
+
reused: stat
|
|
513
|
+
};
|
|
514
|
+
continue;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
yield createMaterializationEntry(source, await source.source.getItem(key, ctx), upstreamMeta);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
async function materializeWorkspaceSources(definition, store, options = {}) {
|
|
521
|
+
const started = Date.now();
|
|
522
|
+
const sources = normalizeWorkspaceSources(definition.sources).filter((source) => shouldMaterializeSource(source, options));
|
|
523
|
+
const resultSources = [];
|
|
524
|
+
let files = 0;
|
|
525
|
+
let directories = 0;
|
|
526
|
+
let bytes = 0;
|
|
527
|
+
for (const source of sources) {
|
|
528
|
+
throwIfAborted(options.abortSignal);
|
|
529
|
+
const sourceStarted = Date.now();
|
|
530
|
+
await reportMaterializationProgress(options, source, { status: "started" });
|
|
531
|
+
const configHash = await sourceConfigHash(source);
|
|
532
|
+
const existing = await readSourceSnapshotMetadata(store, source.key);
|
|
533
|
+
const completeSource = materializesCompleteSource(source, options);
|
|
534
|
+
if (completeSource && isSnapshotFresh(existing, source, configHash)) {
|
|
535
|
+
resultSources.push({
|
|
536
|
+
source: source.key,
|
|
537
|
+
mountPath: source.mountPath,
|
|
538
|
+
status: "ready",
|
|
539
|
+
commit: existing?.commit,
|
|
540
|
+
materializedAt: existing?.materializedAt,
|
|
541
|
+
files: existing?.files,
|
|
542
|
+
bytes: existing?.bytes
|
|
543
|
+
});
|
|
544
|
+
files += existing?.files || 0;
|
|
545
|
+
bytes += existing?.bytes || 0;
|
|
546
|
+
await reportMaterializationProgress(options, source, {
|
|
547
|
+
bytes: existing?.bytes || 0,
|
|
548
|
+
durationMs: Date.now() - sourceStarted,
|
|
549
|
+
files: existing?.files || 0,
|
|
550
|
+
status: "completed"
|
|
551
|
+
});
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
const itemMetadata = existing?.configHash === configHash ? { ...existing.items || {} } : {};
|
|
555
|
+
if (completeSource) await writeSourceSnapshotMetadata(store, {
|
|
556
|
+
configHash,
|
|
557
|
+
source: source.key,
|
|
558
|
+
mountPath: source.mountPath,
|
|
559
|
+
status: "updating",
|
|
560
|
+
items: checkpointItems(itemMetadata),
|
|
561
|
+
cacheMaxAge: source.cache ? source.cache.maxAge : void 0
|
|
562
|
+
});
|
|
563
|
+
let sourceFiles = 0;
|
|
564
|
+
let sourceBytes = 0;
|
|
565
|
+
let lastProgressAt = 0;
|
|
566
|
+
try {
|
|
567
|
+
const ctx = createSourceContext(definition, source, store, { abortSignal: options.abortSignal });
|
|
568
|
+
throwIfAborted(options.abortSignal);
|
|
569
|
+
await source.source.prepare?.(ctx);
|
|
570
|
+
throwIfAborted(options.abortSignal);
|
|
571
|
+
if (source.mountPath) await store.mkdir(source.mountPath, { recursive: true });
|
|
572
|
+
let commit;
|
|
573
|
+
const directorySet = new Set(source.mountPath ? [source.mountPath] : []);
|
|
574
|
+
const nextPaths = /* @__PURE__ */ new Set();
|
|
575
|
+
for await (const entry of iterateMaterializationEntries(source, ctx, store, existing, configHash, options)) {
|
|
576
|
+
throwIfAborted(options.abortSignal);
|
|
577
|
+
const path = entry.path;
|
|
578
|
+
nextPaths.add(path);
|
|
579
|
+
const parts = path.split("/");
|
|
580
|
+
for (let index = 1; index < parts.length; index++) directorySet.add(parts.slice(0, index).join("/"));
|
|
581
|
+
itemMetadata[path] = entry.metadata;
|
|
582
|
+
if (entry.reused) {
|
|
583
|
+
commit ||= entry.metadata.ref || entry.metadata.sha;
|
|
584
|
+
sourceFiles++;
|
|
585
|
+
sourceBytes += entry.reused.size || 0;
|
|
586
|
+
if (completeSource) await writeSourceSnapshotMetadata(store, {
|
|
587
|
+
configHash,
|
|
588
|
+
source: source.key,
|
|
589
|
+
mountPath: source.mountPath,
|
|
590
|
+
status: "updating",
|
|
591
|
+
commit,
|
|
592
|
+
files: sourceFiles,
|
|
593
|
+
bytes: sourceBytes,
|
|
594
|
+
items: checkpointItems(itemMetadata),
|
|
595
|
+
cacheMaxAge: source.cache ? source.cache.maxAge : void 0
|
|
596
|
+
});
|
|
597
|
+
if (shouldReportMaterializationUpdate(lastProgressAt, sourceFiles)) {
|
|
598
|
+
lastProgressAt = Date.now();
|
|
599
|
+
await reportMaterializationProgress(options, source, {
|
|
600
|
+
bytes: sourceBytes,
|
|
601
|
+
files: sourceFiles,
|
|
602
|
+
status: "updating"
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
const item = entry.item;
|
|
608
|
+
const metadata = item.metadata || {};
|
|
609
|
+
commit ||= readStringMeta(metadata, "ref") || readStringMeta(metadata, "sha") || entry.metadata.ref || entry.metadata.sha;
|
|
610
|
+
const written = await writeMaterializedFile(store, path, {
|
|
611
|
+
path,
|
|
612
|
+
content: entry.content,
|
|
613
|
+
contentStream: entry.contentStream,
|
|
614
|
+
mediaType: item.mediaType,
|
|
615
|
+
metadata: {
|
|
616
|
+
...metadata,
|
|
617
|
+
...entry.metadata,
|
|
618
|
+
source: source.key
|
|
619
|
+
}
|
|
620
|
+
});
|
|
621
|
+
sourceFiles++;
|
|
622
|
+
sourceBytes += written.size || 0;
|
|
623
|
+
if (completeSource) await writeSourceSnapshotMetadata(store, {
|
|
624
|
+
configHash,
|
|
625
|
+
source: source.key,
|
|
626
|
+
mountPath: source.mountPath,
|
|
627
|
+
status: "updating",
|
|
628
|
+
commit,
|
|
629
|
+
files: sourceFiles,
|
|
630
|
+
bytes: sourceBytes,
|
|
631
|
+
items: checkpointItems(itemMetadata),
|
|
632
|
+
cacheMaxAge: source.cache ? source.cache.maxAge : void 0
|
|
633
|
+
});
|
|
634
|
+
if (shouldReportMaterializationUpdate(lastProgressAt, sourceFiles)) {
|
|
635
|
+
lastProgressAt = Date.now();
|
|
636
|
+
await reportMaterializationProgress(options, source, {
|
|
637
|
+
bytes: sourceBytes,
|
|
638
|
+
files: sourceFiles,
|
|
639
|
+
status: "updating"
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
throwIfAborted(options.abortSignal);
|
|
644
|
+
await removeStaleMaterializedSourceFiles(store, source, nextPaths, options, { removeUntracked: Boolean(source.mountPath) });
|
|
645
|
+
const readyItems = Object.fromEntries([...nextPaths].flatMap((path) => {
|
|
646
|
+
const metadata = itemMetadata[path];
|
|
647
|
+
return metadata ? [[path, metadata]] : [];
|
|
648
|
+
}));
|
|
649
|
+
const ready = {
|
|
650
|
+
configHash,
|
|
651
|
+
source: source.key,
|
|
652
|
+
mountPath: source.mountPath,
|
|
653
|
+
status: "ready",
|
|
654
|
+
commit,
|
|
655
|
+
materializedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
656
|
+
files: sourceFiles,
|
|
657
|
+
bytes: sourceBytes,
|
|
658
|
+
items: readyItems,
|
|
659
|
+
cacheMaxAge: source.cache ? source.cache.maxAge : void 0
|
|
660
|
+
};
|
|
661
|
+
if (completeSource) await writeSourceSnapshotMetadata(store, ready);
|
|
662
|
+
else if (existing?.configHash === configHash) await writeSourceSnapshotMetadata(store, {
|
|
663
|
+
...existing,
|
|
664
|
+
items: checkpointItems(itemMetadata)
|
|
665
|
+
});
|
|
666
|
+
resultSources.push(ready);
|
|
667
|
+
files += sourceFiles;
|
|
668
|
+
bytes += sourceBytes;
|
|
669
|
+
directories += directorySet.size;
|
|
670
|
+
await reportMaterializationProgress(options, source, {
|
|
671
|
+
bytes: sourceBytes,
|
|
672
|
+
directories: directorySet.size,
|
|
673
|
+
durationMs: Date.now() - sourceStarted,
|
|
674
|
+
files: sourceFiles,
|
|
675
|
+
status: "completed"
|
|
676
|
+
});
|
|
677
|
+
} catch (error) {
|
|
678
|
+
const failed = {
|
|
679
|
+
configHash,
|
|
680
|
+
source: source.key,
|
|
681
|
+
mountPath: source.mountPath,
|
|
682
|
+
status: "error",
|
|
683
|
+
error: error instanceof Error ? error.message : String(error),
|
|
684
|
+
files: sourceFiles,
|
|
685
|
+
bytes: sourceBytes,
|
|
686
|
+
items: checkpointItems(itemMetadata),
|
|
687
|
+
cacheMaxAge: source.cache ? source.cache.maxAge : void 0
|
|
688
|
+
};
|
|
689
|
+
if (!options.abortSignal?.aborted) await writeSourceSnapshotMetadata(store, failed);
|
|
690
|
+
resultSources.push(failed);
|
|
691
|
+
await reportMaterializationProgress(options, source, {
|
|
692
|
+
bytes: sourceBytes,
|
|
693
|
+
durationMs: Date.now() - sourceStarted,
|
|
694
|
+
error: failed.error,
|
|
695
|
+
files: sourceFiles,
|
|
696
|
+
status: "failed"
|
|
697
|
+
});
|
|
698
|
+
if (options.abortSignal?.aborted) throw error;
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
return {
|
|
702
|
+
bytes,
|
|
703
|
+
directories,
|
|
704
|
+
durationMs: Date.now() - started,
|
|
705
|
+
files,
|
|
706
|
+
path: normalizeWorkspacePath(options.path || ""),
|
|
707
|
+
sources: resultSources
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
async function readResolvedSourceFile(resolution, store, ctx, options) {
|
|
711
|
+
const file = await store.readFile(resolution.workspacePath);
|
|
712
|
+
if (!file) throw workspaceError(`[vitehub] Workspace file does not exist: ${resolution.workspacePath}.`);
|
|
713
|
+
return decodeFile(file.content, options);
|
|
714
|
+
}
|
|
715
|
+
async function writeMaterializedFile(store, path, file) {
|
|
716
|
+
if (file.contentStream) {
|
|
717
|
+
if (store.writeFileStream) return await store.writeFileStream(path, {
|
|
718
|
+
path: file.path,
|
|
719
|
+
content: file.contentStream,
|
|
720
|
+
mediaType: file.mediaType,
|
|
721
|
+
metadata: file.metadata
|
|
722
|
+
});
|
|
723
|
+
const content = await contentStreamToBytes(file.contentStream);
|
|
724
|
+
await store.writeFile(path, {
|
|
725
|
+
path: file.path,
|
|
726
|
+
content,
|
|
727
|
+
mediaType: file.mediaType,
|
|
728
|
+
metadata: file.metadata
|
|
729
|
+
});
|
|
730
|
+
return { size: content.byteLength };
|
|
731
|
+
}
|
|
732
|
+
const content = file.content ?? "";
|
|
733
|
+
await store.writeFile(path, {
|
|
734
|
+
path: file.path,
|
|
735
|
+
content,
|
|
736
|
+
mediaType: file.mediaType,
|
|
737
|
+
metadata: file.metadata
|
|
738
|
+
});
|
|
739
|
+
return { size: contentSize(content) };
|
|
740
|
+
}
|
|
741
|
+
async function statVirtualSourcePath(source, workspacePath, store, ctx) {
|
|
742
|
+
const stored = await store.stat(workspacePath);
|
|
743
|
+
if (stored) return stored;
|
|
744
|
+
const keys = await source.source.getKeys(ctx);
|
|
745
|
+
const sourcePath = normalizeSourcePath(source, workspacePath);
|
|
746
|
+
if (!sourcePath && keys.length > 0) return {
|
|
747
|
+
path: source.mountPath,
|
|
748
|
+
type: "directory"
|
|
749
|
+
};
|
|
750
|
+
if (keys.includes(sourcePath)) return {
|
|
751
|
+
path: workspacePath,
|
|
752
|
+
type: "file",
|
|
753
|
+
digest: readDigest(await source.source.getMeta?.(sourcePath, ctx))
|
|
754
|
+
};
|
|
755
|
+
if (keys.some((key) => key.startsWith(`${sourcePath}/`))) return {
|
|
756
|
+
path: workspacePath,
|
|
757
|
+
type: "directory"
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
async function searchMaterializedStore(store, query) {
|
|
761
|
+
const limit = query.limit ?? 100;
|
|
762
|
+
const result = [];
|
|
763
|
+
const entries = query.paths?.length ? (await Promise.all(query.paths.map(async (path) => {
|
|
764
|
+
const [stat, nested] = await Promise.all([store.stat(path), store.glob(`${path}/**/*`)]);
|
|
765
|
+
return [...stat?.type === "file" ? [stat] : [], ...nested];
|
|
766
|
+
}))).flat() : await store.glob("**/*");
|
|
767
|
+
for (const entry of entries) {
|
|
768
|
+
if (entry.type !== "file") continue;
|
|
769
|
+
const file = await store.readFile(entry.path);
|
|
770
|
+
if (!file) continue;
|
|
771
|
+
const text = typeof file.content === "string" ? file.content : new TextDecoder().decode(file.content);
|
|
772
|
+
result.push(...searchText(entry.path, text, {
|
|
773
|
+
...query,
|
|
774
|
+
limit: limit - result.length
|
|
775
|
+
}));
|
|
776
|
+
if (result.length >= limit) break;
|
|
777
|
+
}
|
|
778
|
+
return result.slice(0, limit);
|
|
779
|
+
}
|
|
780
|
+
function createLazyMaterializedMetadata(resolution, item, upstreamMeta) {
|
|
781
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
782
|
+
return {
|
|
783
|
+
source: resolution.sourceKey,
|
|
784
|
+
sourcePath: resolution.sourcePath,
|
|
785
|
+
materializedAt: now,
|
|
786
|
+
validatedAt: resolution.validate === "request" ? now : void 0,
|
|
787
|
+
etag: readStringMeta(upstreamMeta, "etag"),
|
|
788
|
+
sha: readStringMeta(upstreamMeta, "sha"),
|
|
789
|
+
digest: readStringMeta(upstreamMeta, "digest") || readStringMeta(item.metadata, "digest"),
|
|
790
|
+
ref: readStringMeta(upstreamMeta, "ref")
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
function hasSourceMetaChanged(current, upstreamMeta) {
|
|
794
|
+
const next = {
|
|
795
|
+
etag: readStringMeta(upstreamMeta, "etag"),
|
|
796
|
+
sha: readStringMeta(upstreamMeta, "sha"),
|
|
797
|
+
digest: readStringMeta(upstreamMeta, "digest"),
|
|
798
|
+
ref: readStringMeta(upstreamMeta, "ref")
|
|
799
|
+
};
|
|
800
|
+
return current.etag !== next.etag || current.sha !== next.sha || current.digest !== next.digest || current.ref !== next.ref;
|
|
801
|
+
}
|
|
802
|
+
function normalizeSourcePath(source, workspacePath) {
|
|
803
|
+
if (workspacePath === source.mountPath) return "";
|
|
804
|
+
return source.mountPath && workspacePath.startsWith(`${source.mountPath}/`) ? normalizeWorkspacePath(workspacePath.slice(source.mountPath.length + 1)) : normalizeWorkspacePath(workspacePath);
|
|
805
|
+
}
|
|
806
|
+
function readStringMeta(meta, key) {
|
|
807
|
+
return typeof meta?.[key] === "string" ? meta[key] : void 0;
|
|
808
|
+
}
|
|
809
|
+
function readDigest(meta) {
|
|
810
|
+
return readStringMeta(meta, "digest") || readStringMeta(meta, "sha");
|
|
811
|
+
}
|
|
812
|
+
//#endregion
|
|
813
|
+
//#region src/sources/resolver.ts
|
|
814
|
+
function resolveWorkspacePath(definition, path) {
|
|
815
|
+
const workspacePath = normalizeSafeWorkspacePath(path, { allowEmpty: true });
|
|
816
|
+
const sources = normalizeWorkspaceSources(definition.sources).filter((source) => source.materialize !== "none");
|
|
817
|
+
for (const source of sources) {
|
|
818
|
+
if (source.requestOnly) continue;
|
|
819
|
+
const liveSourcePath = source.livePaths?.[workspacePath];
|
|
820
|
+
if (typeof liveSourcePath === "string") return createSourceResolution(source, workspacePath, liveSourcePath);
|
|
821
|
+
if (workspacePath === source.mountPath) return createSourceResolution(source, workspacePath, "");
|
|
822
|
+
if (sourceMountContainsPath(source, workspacePath)) return createSourceResolution(source, workspacePath, source.mountPath ? workspacePath.slice(source.mountPath.length + 1) : workspacePath);
|
|
823
|
+
}
|
|
824
|
+
return {
|
|
825
|
+
type: "store",
|
|
826
|
+
workspacePath,
|
|
827
|
+
readonly: false
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
function createSourceResolution(source, workspacePath, sourcePath) {
|
|
831
|
+
return {
|
|
832
|
+
type: "source",
|
|
833
|
+
sourceKey: source.key,
|
|
834
|
+
source,
|
|
835
|
+
workspacePath,
|
|
836
|
+
sourcePath: normalizeWorkspacePath(sourcePath),
|
|
837
|
+
materialize: source.materialize,
|
|
838
|
+
cache: source.cache,
|
|
839
|
+
validate: source.validate,
|
|
840
|
+
readonly: true
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
//#endregion
|
|
844
|
+
//#region src/sources/sync-state.ts
|
|
845
|
+
function sourceSyncMetaKey(sourceKey) {
|
|
846
|
+
return `source:${sourceKey}:sync`;
|
|
847
|
+
}
|
|
848
|
+
function readWorkspaceSourceSyncState(value) {
|
|
849
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
850
|
+
const state = value;
|
|
851
|
+
if (typeof state.configHash !== "string") return;
|
|
852
|
+
if (typeof state.source !== "string" || typeof state.mountPath !== "string") return;
|
|
853
|
+
if (!state.paths || typeof state.paths !== "object" || Array.isArray(state.paths)) return;
|
|
854
|
+
for (const path of Object.keys(state.paths)) {
|
|
855
|
+
const entry = state.paths[path];
|
|
856
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) return;
|
|
857
|
+
if (typeof entry.digest !== "string" || typeof entry.sourcePath !== "string") return;
|
|
858
|
+
}
|
|
859
|
+
return state;
|
|
860
|
+
}
|
|
861
|
+
function workspaceSourceSyncStateEquals(left, right) {
|
|
862
|
+
if (!left) return false;
|
|
863
|
+
return JSON.stringify(canonicalSourceSyncState(left)) === JSON.stringify(canonicalSourceSyncState(right));
|
|
864
|
+
}
|
|
865
|
+
function canonicalSourceSyncState(state) {
|
|
866
|
+
return {
|
|
867
|
+
configHash: state.configHash,
|
|
868
|
+
mountPath: state.mountPath,
|
|
869
|
+
paths: Object.fromEntries(Object.entries(state.paths).sort(([left], [right]) => left.localeCompare(right))),
|
|
870
|
+
source: state.source
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
//#endregion
|
|
874
|
+
//#region src/sources/view.ts
|
|
875
|
+
function createWorkspaceSourceView(definition, store) {
|
|
876
|
+
const sourceContext = createSourceContext(definition, void 0, store);
|
|
877
|
+
const allSources = normalizeWorkspaceSources(definition.sources);
|
|
878
|
+
const sources = allSources.filter((source) => !source.requestOnly && source.materialize === "lazy");
|
|
879
|
+
const syncSources = allSources.filter((source) => source.sync);
|
|
880
|
+
const descriptorSources = allSources.filter((source) => source.requestDescriptor);
|
|
881
|
+
const writePolicy = createWorkspaceWritePolicy(definition);
|
|
882
|
+
const prepareBySource = /* @__PURE__ */ new Map();
|
|
883
|
+
const materializeBySource = /* @__PURE__ */ new Map();
|
|
884
|
+
function getSourceContext(source) {
|
|
885
|
+
return createSourceContext(definition, source, store);
|
|
886
|
+
}
|
|
887
|
+
function isLazySourcePath(path) {
|
|
888
|
+
return sources.some((source) => sourceMountContainsPath(source, path));
|
|
889
|
+
}
|
|
890
|
+
function isSyncSourceMountPath(path) {
|
|
891
|
+
return syncSources.some((source) => source.mountPath && sourceMountContainsPath(source, path));
|
|
892
|
+
}
|
|
893
|
+
function descriptorSourceForPath(path) {
|
|
894
|
+
return descriptorSources.find((source) => workspaceSourceRequestDescriptorPath(source.key) === path);
|
|
895
|
+
}
|
|
896
|
+
function descriptorPathEntries(path = "", options = {}) {
|
|
897
|
+
if (!descriptorSources.length) return [];
|
|
898
|
+
const normalized = normalizeWorkspacePath(path);
|
|
899
|
+
const descriptors = descriptorSources.map((source) => workspaceSourceRequestDescriptorPath(source.key));
|
|
900
|
+
if (!normalized) return options.recursive ? [
|
|
901
|
+
{
|
|
902
|
+
path: ".vitehub",
|
|
903
|
+
type: "directory"
|
|
904
|
+
},
|
|
905
|
+
{
|
|
906
|
+
path: ".vitehub/sources",
|
|
907
|
+
type: "directory"
|
|
908
|
+
},
|
|
909
|
+
...descriptors.map((descriptor) => ({
|
|
910
|
+
path: descriptor,
|
|
911
|
+
type: "file"
|
|
912
|
+
}))
|
|
913
|
+
] : [{
|
|
914
|
+
path: ".vitehub",
|
|
915
|
+
type: "directory"
|
|
916
|
+
}];
|
|
917
|
+
if (normalized === ".vitehub") return options.recursive ? [{
|
|
918
|
+
path: ".vitehub/sources",
|
|
919
|
+
type: "directory"
|
|
920
|
+
}, ...descriptors.map((descriptor) => ({
|
|
921
|
+
path: descriptor,
|
|
922
|
+
type: "file"
|
|
923
|
+
}))] : [{
|
|
924
|
+
path: ".vitehub/sources",
|
|
925
|
+
type: "directory"
|
|
926
|
+
}];
|
|
927
|
+
if (normalized === ".vitehub/sources") return descriptors.map((descriptor) => ({
|
|
928
|
+
path: descriptor,
|
|
929
|
+
type: "file"
|
|
930
|
+
}));
|
|
931
|
+
if (descriptors.includes(normalized)) return [{
|
|
932
|
+
path: normalized,
|
|
933
|
+
type: "file"
|
|
934
|
+
}];
|
|
935
|
+
return [];
|
|
936
|
+
}
|
|
937
|
+
function descriptorStat(path) {
|
|
938
|
+
if (descriptorSourceForPath(path)) return {
|
|
939
|
+
path,
|
|
940
|
+
type: "file"
|
|
941
|
+
};
|
|
942
|
+
if (descriptorSources.length && (path === ".vitehub" || path === ".vitehub/sources")) return {
|
|
943
|
+
path,
|
|
944
|
+
type: "directory"
|
|
945
|
+
};
|
|
946
|
+
}
|
|
947
|
+
function isDescriptorPath(path) {
|
|
948
|
+
return descriptorSources.length > 0 && (path === ".vitehub" || path === ".vitehub/sources" || path.startsWith(".vitehub/sources/"));
|
|
949
|
+
}
|
|
950
|
+
function descriptorContent(source) {
|
|
951
|
+
return JSON.stringify({
|
|
952
|
+
...source.requestDescriptor,
|
|
953
|
+
sourceKey: source.key
|
|
954
|
+
}, null, 2);
|
|
955
|
+
}
|
|
956
|
+
function isLiveSource(sourceKey) {
|
|
957
|
+
return Boolean(sources.find((item) => item.key === sourceKey)?.livePaths);
|
|
958
|
+
}
|
|
959
|
+
function getLazySourcesForPath(path) {
|
|
960
|
+
return sources.filter((source) => sourceMountIntersectsPath(source, path));
|
|
961
|
+
}
|
|
962
|
+
async function ensurePrepared(sourceKey) {
|
|
963
|
+
const source = sources.find((item) => item.key === sourceKey);
|
|
964
|
+
if (!source?.source.prepare) return;
|
|
965
|
+
let pending = prepareBySource.get(sourceKey);
|
|
966
|
+
if (!pending) {
|
|
967
|
+
pending = source.source.prepare(getSourceContext(source));
|
|
968
|
+
prepareBySource.set(sourceKey, pending);
|
|
969
|
+
}
|
|
970
|
+
await pending;
|
|
971
|
+
}
|
|
972
|
+
async function ensurePreparedSources(items = sources) {
|
|
973
|
+
await Promise.all(items.map(async (source) => await ensurePrepared(source.key)));
|
|
974
|
+
}
|
|
975
|
+
async function ensureMaterialized(sourceKey) {
|
|
976
|
+
let pending = materializeBySource.get(sourceKey);
|
|
977
|
+
if (!pending) {
|
|
978
|
+
pending = materializeWorkspaceSources(definition, store, { sources: [sourceKey] }).then(() => void 0);
|
|
979
|
+
materializeBySource.set(sourceKey, pending);
|
|
980
|
+
}
|
|
981
|
+
await pending;
|
|
982
|
+
}
|
|
983
|
+
async function ensureMaterializedSources(items = sources) {
|
|
984
|
+
await Promise.all(items.map(async (source) => await ensureMaterialized(source.key)));
|
|
985
|
+
}
|
|
986
|
+
async function listSourceAware(path = "", options = {}) {
|
|
987
|
+
const storeEntries = await store.list(path, options);
|
|
988
|
+
const result = new Map(storeEntries.map((entry) => [entry.path, entry]));
|
|
989
|
+
for (const entry of descriptorPathEntries(path, options)) result.set(entry.path, entry);
|
|
990
|
+
for (const source of getLazySourcesForPath(path)) {
|
|
991
|
+
await ensurePrepared(source.key);
|
|
992
|
+
if (source.livePaths) {
|
|
993
|
+
await pruneLiveSourceStoreEntries(result, source);
|
|
994
|
+
continue;
|
|
995
|
+
}
|
|
996
|
+
if (!path && options.recursive && !await hasCurrentSourceSnapshot(store, source)) {
|
|
997
|
+
if ([...result.keys()].some((key) => sourceMountContainsPath(source, key))) {
|
|
998
|
+
const allowed = await currentSourceTreePaths(source, getSourceContext(source));
|
|
999
|
+
for (const key of result.keys()) if (sourceMountContainsPath(source, key) && !allowed.has(key)) result.delete(key);
|
|
1000
|
+
result.set(source.mountPath, {
|
|
1001
|
+
path: source.mountPath,
|
|
1002
|
+
type: "directory"
|
|
1003
|
+
});
|
|
1004
|
+
continue;
|
|
1005
|
+
}
|
|
1006
|
+
for (const key of result.keys()) if (sourceMountContainsPath(source, key)) result.delete(key);
|
|
1007
|
+
result.set(source.mountPath, {
|
|
1008
|
+
path: source.mountPath,
|
|
1009
|
+
type: "directory"
|
|
1010
|
+
});
|
|
1011
|
+
continue;
|
|
1012
|
+
}
|
|
1013
|
+
if (sourceMountContainsPath(source, path) || !source.mountPath && path) {
|
|
1014
|
+
await ensureMaterialized(source.key);
|
|
1015
|
+
for (const entry of await store.list(path, options)) result.set(entry.path, entry);
|
|
1016
|
+
} else if (!path && !result.has(source.mountPath)) result.set(source.mountPath, {
|
|
1017
|
+
path: source.mountPath,
|
|
1018
|
+
type: "directory"
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
addLiveSourceEntries(result, path, options, sources);
|
|
1022
|
+
return [...result.values()].sort((left, right) => left.path.localeCompare(right.path));
|
|
1023
|
+
}
|
|
1024
|
+
async function searchWorkspace(query) {
|
|
1025
|
+
const limit = query.limit ?? 100;
|
|
1026
|
+
const storePaths = [];
|
|
1027
|
+
const sourcePaths = /* @__PURE__ */ new Map();
|
|
1028
|
+
const requestedPaths = query.paths?.length ? query.paths : [query.cwd || ""];
|
|
1029
|
+
for (const requestedPath of requestedPaths) {
|
|
1030
|
+
const resolution = resolveWorkspacePath(definition, normalizeWorkspacePath(requestedPath));
|
|
1031
|
+
if (resolution.type === "store") {
|
|
1032
|
+
storePaths.push(resolution.workspacePath);
|
|
1033
|
+
continue;
|
|
1034
|
+
}
|
|
1035
|
+
const list = sourcePaths.get(resolution.sourceKey) || [];
|
|
1036
|
+
list.push(resolution.workspacePath);
|
|
1037
|
+
sourcePaths.set(resolution.sourceKey, list);
|
|
1038
|
+
}
|
|
1039
|
+
const results = await searchMaterializedStore(store, {
|
|
1040
|
+
...query,
|
|
1041
|
+
paths: storePaths.filter(Boolean).length ? storePaths.filter(Boolean) : void 0,
|
|
1042
|
+
limit
|
|
1043
|
+
});
|
|
1044
|
+
if (query.paths?.length && !storePaths.filter(Boolean).length) results.length = 0;
|
|
1045
|
+
for (const source of descriptorSources) {
|
|
1046
|
+
const entryPath = workspaceSourceRequestDescriptorPath(source.key);
|
|
1047
|
+
if (query.paths?.length && !requestedPaths.some((path) => !normalizeWorkspacePath(path) || sourceMountContainsPath({ mountPath: normalizeWorkspacePath(path) }, entryPath))) continue;
|
|
1048
|
+
results.push(...searchText(entryPath, descriptorContent(source), {
|
|
1049
|
+
...query,
|
|
1050
|
+
limit: limit - results.length
|
|
1051
|
+
}));
|
|
1052
|
+
if (results.length >= limit) return dedupeHits(results).slice(0, limit);
|
|
1053
|
+
}
|
|
1054
|
+
for (const source of sources) {
|
|
1055
|
+
const paths = sourcePaths.get(source.key);
|
|
1056
|
+
if (query.paths?.length && !paths?.length && !query.paths.some((path) => !normalizeWorkspacePath(path))) continue;
|
|
1057
|
+
if (source.livePaths) {
|
|
1058
|
+
await ensurePrepared(source.key);
|
|
1059
|
+
const liveEntries = liveSourceEntries(source).filter((entry) => entry.type === "file").filter((entry) => !paths?.length || paths.some((path) => !path || entry.path === path || entry.path.startsWith(`${path}/`)));
|
|
1060
|
+
for (const entry of liveEntries) {
|
|
1061
|
+
const sourcePath = source.livePaths[entry.path];
|
|
1062
|
+
if (typeof sourcePath !== "string") continue;
|
|
1063
|
+
const content = await sourceItemContent(await source.source.getItem(sourcePath, getSourceContext(source)));
|
|
1064
|
+
const text = typeof content === "string" ? content : new TextDecoder().decode(content);
|
|
1065
|
+
results.push(...searchText(entry.path, text, {
|
|
1066
|
+
...query,
|
|
1067
|
+
limit: limit - results.length
|
|
1068
|
+
}));
|
|
1069
|
+
if (results.length >= limit) break;
|
|
1070
|
+
}
|
|
1071
|
+
if (results.length >= limit) break;
|
|
1072
|
+
continue;
|
|
1073
|
+
}
|
|
1074
|
+
await ensureMaterialized(source.key);
|
|
1075
|
+
results.push(...await searchMaterializedStore(store, {
|
|
1076
|
+
...query,
|
|
1077
|
+
paths,
|
|
1078
|
+
limit: limit - results.length
|
|
1079
|
+
}));
|
|
1080
|
+
if (results.length >= limit) break;
|
|
1081
|
+
}
|
|
1082
|
+
return dedupeHits(results).slice(0, limit);
|
|
1083
|
+
}
|
|
1084
|
+
function assertWritableStorePath(path, workspacePath, type) {
|
|
1085
|
+
if (type === "source" || isLazySourcePath(workspacePath)) throw workspaceError(`[vitehub] Source-backed workspace paths are read-only: ${path}.`);
|
|
1086
|
+
}
|
|
1087
|
+
async function previousStat(path) {
|
|
1088
|
+
return await store.stat(path);
|
|
1089
|
+
}
|
|
1090
|
+
async function materializeRootSourceForPath(path) {
|
|
1091
|
+
for (const source of sources.filter((source) => !source.mountPath)) {
|
|
1092
|
+
await ensurePrepared(source.key);
|
|
1093
|
+
await ensureMaterialized(source.key);
|
|
1094
|
+
if ((await store.readFile(path))?.metadata?.source === source.key) return source;
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
async function isSourceBackedStorePath(path) {
|
|
1098
|
+
const file = await store.readFile(path);
|
|
1099
|
+
if (typeof file?.metadata?.source === "string" && allSources.some((source) => source.key === file.metadata?.source)) return true;
|
|
1100
|
+
if ((await store.stat(path))?.type !== "directory") return false;
|
|
1101
|
+
const entries = await store.list(path, { recursive: true });
|
|
1102
|
+
for (const entry of entries) {
|
|
1103
|
+
if (entry.type !== "file") continue;
|
|
1104
|
+
const child = await store.readFile(entry.path);
|
|
1105
|
+
if (typeof child?.metadata?.source === "string" && allSources.some((source) => source.key === child.metadata?.source)) return true;
|
|
1106
|
+
}
|
|
1107
|
+
return false;
|
|
1108
|
+
}
|
|
1109
|
+
async function isSyncedStatePath(path) {
|
|
1110
|
+
if (!store.getMeta) return false;
|
|
1111
|
+
for (const source of syncSources) {
|
|
1112
|
+
const state = readWorkspaceSourceSyncState(await store.getMeta(sourceSyncMetaKey(source.key)));
|
|
1113
|
+
if (!state) continue;
|
|
1114
|
+
if (state.paths[path]) return true;
|
|
1115
|
+
if (Object.keys(state.paths).some((item) => item.startsWith(`${path}/`))) return true;
|
|
1116
|
+
}
|
|
1117
|
+
return false;
|
|
1118
|
+
}
|
|
1119
|
+
async function assertWritableResolvedStorePath(path, workspacePath, type) {
|
|
1120
|
+
assertWritableStorePath(path, workspacePath, type);
|
|
1121
|
+
await materializeRootSourceForPath(workspacePath);
|
|
1122
|
+
if (isSyncSourceMountPath(workspacePath) || await isSyncedStatePath(workspacePath) || await isSourceBackedStorePath(workspacePath)) throw workspaceError(`[vitehub] Source-backed workspace paths are read-only: ${path}.`);
|
|
1123
|
+
}
|
|
1124
|
+
async function assertWritablePath(path) {
|
|
1125
|
+
if (isDescriptorPath(normalizeWorkspacePath(path))) throw workspaceError(`[vitehub] Source-backed workspace paths are read-only: ${path}.`);
|
|
1126
|
+
const resolution = resolveWorkspacePath(definition, path);
|
|
1127
|
+
if (isDescriptorPath(resolution.workspacePath)) throw workspaceError(`[vitehub] Source-backed workspace paths are read-only: ${path}.`);
|
|
1128
|
+
await assertWritableResolvedStorePath(path, resolution.workspacePath, resolution.type);
|
|
1129
|
+
return resolution;
|
|
1130
|
+
}
|
|
1131
|
+
return {
|
|
1132
|
+
async assertWritable(path) {
|
|
1133
|
+
await assertWritablePath(path);
|
|
1134
|
+
},
|
|
1135
|
+
async readFile(path, options) {
|
|
1136
|
+
const descriptorSource = descriptorSourceForPath(normalizeWorkspacePath(path));
|
|
1137
|
+
if (descriptorSource) return decodeFile(descriptorContent(descriptorSource), options);
|
|
1138
|
+
const resolution = resolveWorkspacePath(definition, path);
|
|
1139
|
+
if (resolution.type === "source") {
|
|
1140
|
+
await ensurePrepared(resolution.sourceKey);
|
|
1141
|
+
if (isLiveSource(resolution.sourceKey)) return decodeFile(await sourceItemContent(await resolution.source.source.getItem(resolution.sourcePath, getSourceContext(resolution.source))), options);
|
|
1142
|
+
const file = await store.readFile(resolution.workspacePath);
|
|
1143
|
+
if (file) return decodeFile(file.content, options);
|
|
1144
|
+
await ensureMaterialized(resolution.sourceKey);
|
|
1145
|
+
return await readResolvedSourceFile(resolution, store, sourceContext, options);
|
|
1146
|
+
}
|
|
1147
|
+
await materializeRootSourceForPath(resolution.workspacePath);
|
|
1148
|
+
const file = await store.readFile(resolution.workspacePath);
|
|
1149
|
+
if (!file) throw workspaceError(`[vitehub] Workspace file does not exist: ${path}.`);
|
|
1150
|
+
return decodeFile(file.content, options);
|
|
1151
|
+
},
|
|
1152
|
+
async writeFile(path, content, options) {
|
|
1153
|
+
const resolution = await assertWritablePath(path);
|
|
1154
|
+
const input = await writePolicy.before({
|
|
1155
|
+
content,
|
|
1156
|
+
mediaType: options?.mediaType,
|
|
1157
|
+
metadata: options?.metadata,
|
|
1158
|
+
operation: "writeFile",
|
|
1159
|
+
path: resolution.workspacePath,
|
|
1160
|
+
previous: await previousStat(resolution.workspacePath),
|
|
1161
|
+
workspace: definition.name
|
|
1162
|
+
});
|
|
1163
|
+
try {
|
|
1164
|
+
await store.writeFile(input.path, {
|
|
1165
|
+
path: input.path,
|
|
1166
|
+
content: input.content ?? content,
|
|
1167
|
+
mediaType: input.mediaType,
|
|
1168
|
+
metadata: input.metadata
|
|
1169
|
+
});
|
|
1170
|
+
await writePolicy.after(input);
|
|
1171
|
+
} catch (error) {
|
|
1172
|
+
await writePolicy.error(input, error);
|
|
1173
|
+
throw error;
|
|
1174
|
+
}
|
|
1175
|
+
},
|
|
1176
|
+
async list(path, options) {
|
|
1177
|
+
return await listSourceAware(path || "", options || {});
|
|
1178
|
+
},
|
|
1179
|
+
async glob(pattern, options) {
|
|
1180
|
+
const patterns = Array.isArray(pattern) ? pattern : [pattern];
|
|
1181
|
+
await ensurePreparedSources();
|
|
1182
|
+
await ensureMaterializedSources(sources.filter((source) => !source.livePaths));
|
|
1183
|
+
const result = /* @__PURE__ */ new Map();
|
|
1184
|
+
for (const entry of await store.glob(patterns, options)) result.set(entry.path, entry);
|
|
1185
|
+
for (const entry of descriptorPathEntries("", { recursive: true })) if (entry.type === "file" && patterns.some((pattern) => matchesAny(entry.path, pattern))) result.set(entry.path, entry);
|
|
1186
|
+
for (const source of sources.filter((source) => source.livePaths)) {
|
|
1187
|
+
await pruneLiveSourceStoreEntries(result, source);
|
|
1188
|
+
for (const entry of liveSourceEntries(source)) if (entry.type === "file" && patterns.some((pattern) => matchesAny(entry.path, pattern))) result.set(entry.path, entry);
|
|
1189
|
+
}
|
|
1190
|
+
return [...result.values()].sort((left, right) => left.path.localeCompare(right.path));
|
|
1191
|
+
},
|
|
1192
|
+
async search(query) {
|
|
1193
|
+
return await searchWorkspace(query);
|
|
1194
|
+
},
|
|
1195
|
+
async stat(path) {
|
|
1196
|
+
const descriptor = descriptorStat(normalizeWorkspacePath(path));
|
|
1197
|
+
if (descriptor) return descriptor;
|
|
1198
|
+
const resolution = resolveWorkspacePath(definition, path);
|
|
1199
|
+
if (resolution.type === "source") {
|
|
1200
|
+
await ensurePrepared(resolution.sourceKey);
|
|
1201
|
+
if (isLiveSource(resolution.sourceKey)) {
|
|
1202
|
+
if (!resolution.workspacePath) return {
|
|
1203
|
+
path: "",
|
|
1204
|
+
type: "directory"
|
|
1205
|
+
};
|
|
1206
|
+
const result = liveSourceStat(resolution.source, resolution.workspacePath);
|
|
1207
|
+
if (!result) throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
|
|
1208
|
+
return result;
|
|
1209
|
+
}
|
|
1210
|
+
const stored = await store.stat(resolution.workspacePath);
|
|
1211
|
+
if (stored) return stored;
|
|
1212
|
+
await ensureMaterialized(resolution.sourceKey);
|
|
1213
|
+
const result = await statVirtualSourcePath(resolution.source, resolution.workspacePath, store, getSourceContext(resolution.source));
|
|
1214
|
+
if (!result) throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
|
|
1215
|
+
return result;
|
|
1216
|
+
}
|
|
1217
|
+
let result = await store.stat(resolution.workspacePath);
|
|
1218
|
+
if (!result) {
|
|
1219
|
+
if (!resolution.workspacePath && sources.some((source) => !source.mountPath && source.livePaths)) return {
|
|
1220
|
+
path: "",
|
|
1221
|
+
type: "directory"
|
|
1222
|
+
};
|
|
1223
|
+
await materializeRootSourceForPath(resolution.workspacePath);
|
|
1224
|
+
result = await store.stat(resolution.workspacePath);
|
|
1225
|
+
}
|
|
1226
|
+
if (!result) throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
|
|
1227
|
+
return result;
|
|
1228
|
+
},
|
|
1229
|
+
async materializeSources(options) {
|
|
1230
|
+
return await materializeWorkspaceSources(definition, store, options);
|
|
1231
|
+
},
|
|
1232
|
+
async exists(path) {
|
|
1233
|
+
if (descriptorStat(normalizeWorkspacePath(path))) return true;
|
|
1234
|
+
const resolution = resolveWorkspacePath(definition, path);
|
|
1235
|
+
if (resolution.type === "source") {
|
|
1236
|
+
await ensurePrepared(resolution.sourceKey);
|
|
1237
|
+
if (isLiveSource(resolution.sourceKey)) {
|
|
1238
|
+
if (!resolution.workspacePath) return true;
|
|
1239
|
+
return Boolean(liveSourceStat(resolution.source, resolution.workspacePath));
|
|
1240
|
+
}
|
|
1241
|
+
if (await store.stat(resolution.workspacePath)) return true;
|
|
1242
|
+
await ensureMaterialized(resolution.sourceKey);
|
|
1243
|
+
return Boolean(await statVirtualSourcePath(resolution.source, resolution.workspacePath, store, getSourceContext(resolution.source)));
|
|
1244
|
+
}
|
|
1245
|
+
if (await store.stat(resolution.workspacePath)) return true;
|
|
1246
|
+
if (!resolution.workspacePath && sources.some((source) => !source.mountPath && source.livePaths)) return true;
|
|
1247
|
+
await materializeRootSourceForPath(resolution.workspacePath);
|
|
1248
|
+
return Boolean(await store.stat(resolution.workspacePath));
|
|
1249
|
+
},
|
|
1250
|
+
async mkdir(path, options) {
|
|
1251
|
+
const resolution = await assertWritablePath(path);
|
|
1252
|
+
const input = await writePolicy.before({
|
|
1253
|
+
operation: "mkdir",
|
|
1254
|
+
path: resolution.workspacePath,
|
|
1255
|
+
previous: await previousStat(resolution.workspacePath),
|
|
1256
|
+
workspace: definition.name
|
|
1257
|
+
});
|
|
1258
|
+
try {
|
|
1259
|
+
await store.mkdir(input.path, options);
|
|
1260
|
+
await writePolicy.after(input);
|
|
1261
|
+
} catch (error) {
|
|
1262
|
+
await writePolicy.error(input, error);
|
|
1263
|
+
throw error;
|
|
1264
|
+
}
|
|
1265
|
+
},
|
|
1266
|
+
async rm(path, options) {
|
|
1267
|
+
const resolution = await assertWritablePath(path);
|
|
1268
|
+
const input = await writePolicy.before({
|
|
1269
|
+
operation: "rm",
|
|
1270
|
+
path: resolution.workspacePath,
|
|
1271
|
+
previous: await previousStat(resolution.workspacePath),
|
|
1272
|
+
workspace: definition.name
|
|
1273
|
+
});
|
|
1274
|
+
try {
|
|
1275
|
+
await store.rm(input.path, options);
|
|
1276
|
+
await writePolicy.after(input);
|
|
1277
|
+
} catch (error) {
|
|
1278
|
+
await writePolicy.error(input, error);
|
|
1279
|
+
throw error;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
};
|
|
1283
|
+
async function pruneLiveSourceStoreEntries(result, source) {
|
|
1284
|
+
const allowed = new Set(liveSourceEntries(source).map((entry) => entry.path));
|
|
1285
|
+
for (const [path, entry] of result) {
|
|
1286
|
+
if (!isWithinLiveSourceMount(source, path) || allowed.has(path)) continue;
|
|
1287
|
+
if (entry.type === "file") {
|
|
1288
|
+
if ((await store.readFile(path))?.metadata?.source === source.key) result.delete(path);
|
|
1289
|
+
continue;
|
|
1290
|
+
}
|
|
1291
|
+
if (!source.mountPath) continue;
|
|
1292
|
+
if (![...allowed].some((allowedPath) => allowedPath.startsWith(`${path}/`))) result.delete(path);
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
function isWithinLiveSourceMount(source, path) {
|
|
1297
|
+
return source.mountPath ? sourceMountContainsPath(source, path) : Boolean(path);
|
|
1298
|
+
}
|
|
1299
|
+
function liveSourceEntries(source) {
|
|
1300
|
+
const paths = Object.keys(source.livePaths || {});
|
|
1301
|
+
const entries = /* @__PURE__ */ new Map();
|
|
1302
|
+
for (const path of paths) {
|
|
1303
|
+
const parts = path.split("/").filter(Boolean);
|
|
1304
|
+
for (let index = 1; index < parts.length; index++) {
|
|
1305
|
+
const directory = parts.slice(0, index).join("/");
|
|
1306
|
+
entries.set(directory, {
|
|
1307
|
+
path: directory,
|
|
1308
|
+
type: "directory"
|
|
1309
|
+
});
|
|
1310
|
+
}
|
|
1311
|
+
entries.set(path, {
|
|
1312
|
+
path,
|
|
1313
|
+
type: "file"
|
|
1314
|
+
});
|
|
1315
|
+
}
|
|
1316
|
+
return [...entries.values()];
|
|
1317
|
+
}
|
|
1318
|
+
async function sourceItemContent(item) {
|
|
1319
|
+
if (item.contentStream) {
|
|
1320
|
+
if (typeof item.content !== "undefined" || typeof item.data !== "undefined") throw workspaceError("[vitehub] Workspace source items cannot define contentStream with content or data.");
|
|
1321
|
+
return await contentStreamToBytes(item.contentStream);
|
|
1322
|
+
}
|
|
1323
|
+
return item.content ?? (typeof item.data === "undefined" ? "" : JSON.stringify(item.data, null, 2));
|
|
1324
|
+
}
|
|
1325
|
+
function addLiveSourceEntries(result, path, options, sources) {
|
|
1326
|
+
const normalized = normalizeWorkspacePath(path);
|
|
1327
|
+
for (const source of sources.filter((source) => source.livePaths)) for (const entry of liveSourceEntries(source)) {
|
|
1328
|
+
if (!isListedLiveEntry(entry, normalized, options)) continue;
|
|
1329
|
+
result.set(entry.path, entry);
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
function isListedLiveEntry(entry, path, options) {
|
|
1333
|
+
if (!path) {
|
|
1334
|
+
if (options.recursive) return true;
|
|
1335
|
+
return !entry.path.includes("/");
|
|
1336
|
+
}
|
|
1337
|
+
if (entry.path === path) return false;
|
|
1338
|
+
if (!entry.path.startsWith(`${path}/`)) return false;
|
|
1339
|
+
if (options.recursive) return true;
|
|
1340
|
+
return !entry.path.slice(path.length + 1).includes("/");
|
|
1341
|
+
}
|
|
1342
|
+
function liveSourceStat(source, workspacePath) {
|
|
1343
|
+
return liveSourceEntries(source).find((entry) => entry.path === workspacePath);
|
|
1344
|
+
}
|
|
1345
|
+
async function currentSourceTreePaths(source, sourceContext) {
|
|
1346
|
+
const allowed = new Set([source.mountPath]);
|
|
1347
|
+
const keys = await source.source.getKeys(sourceContext);
|
|
1348
|
+
for (const key of keys) {
|
|
1349
|
+
const parts = `${source.mountPath}/${key}`.replace(/\/+/g, "/").split("/");
|
|
1350
|
+
for (let index = 1; index <= parts.length; index++) allowed.add(parts.slice(0, index).join("/"));
|
|
1351
|
+
}
|
|
1352
|
+
return allowed;
|
|
1353
|
+
}
|
|
1354
|
+
function dedupeHits(hits) {
|
|
1355
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1356
|
+
return hits.filter((hit) => {
|
|
1357
|
+
const key = `${hit.path}:${hit.line}:${hit.column}:${hit.text}`;
|
|
1358
|
+
if (seen.has(key)) return false;
|
|
1359
|
+
seen.add(key);
|
|
1360
|
+
return true;
|
|
1361
|
+
});
|
|
1362
|
+
}
|
|
1363
|
+
//#endregion
|
|
1364
|
+
//#region src/core/workspace-cache.ts
|
|
1365
|
+
let storeByDefinition = /* @__PURE__ */ new WeakMap();
|
|
1366
|
+
function getCachedWorkspaceStore(definition, create) {
|
|
1367
|
+
let store = storeByDefinition.get(definition);
|
|
1368
|
+
if (!store) {
|
|
1369
|
+
store = create();
|
|
1370
|
+
storeByDefinition.set(definition, store);
|
|
1371
|
+
}
|
|
1372
|
+
return store;
|
|
1373
|
+
}
|
|
1374
|
+
function resetWorkspaceStoreCache() {
|
|
1375
|
+
storeByDefinition = /* @__PURE__ */ new WeakMap();
|
|
1376
|
+
}
|
|
1377
|
+
//#endregion
|
|
1378
|
+
//#region src/core/workspace.ts
|
|
1379
|
+
function getStore(definition) {
|
|
1380
|
+
return getCachedWorkspaceStore(definition, () => createWorkspaceStoreFromProvider(definition));
|
|
1381
|
+
}
|
|
1382
|
+
function createWorkspace(definition) {
|
|
1383
|
+
const store = getStore(definition);
|
|
1384
|
+
const files = createWorkspaceSourceView(definition, store);
|
|
1385
|
+
const workspace = {
|
|
1386
|
+
name: definition.name,
|
|
1387
|
+
async sync(options) {
|
|
1388
|
+
const { syncWorkspaceSources } = await import("./sync-DO42ypji.js");
|
|
1389
|
+
return await syncWorkspaceSources(definition, store, options);
|
|
1390
|
+
},
|
|
1391
|
+
async materializeSources(options) {
|
|
1392
|
+
return await files.materializeSources(options);
|
|
1393
|
+
},
|
|
1394
|
+
async getMeta(key) {
|
|
1395
|
+
return await store.getMeta?.(key);
|
|
1396
|
+
},
|
|
1397
|
+
async setMeta(key, value) {
|
|
1398
|
+
await store.setMeta?.(key, value);
|
|
1399
|
+
},
|
|
1400
|
+
async readFile(path, options) {
|
|
1401
|
+
return await files.readFile(path, options);
|
|
1402
|
+
},
|
|
1403
|
+
async writeFile(path, content, options) {
|
|
1404
|
+
await files.writeFile(path, content, options);
|
|
1405
|
+
},
|
|
1406
|
+
async list(path, options) {
|
|
1407
|
+
return await files.list(path, options);
|
|
1408
|
+
},
|
|
1409
|
+
async glob(pattern, options) {
|
|
1410
|
+
return await files.glob(pattern, options);
|
|
1411
|
+
},
|
|
1412
|
+
async search(query) {
|
|
1413
|
+
return await files.search(query);
|
|
1414
|
+
},
|
|
1415
|
+
async stat(path) {
|
|
1416
|
+
return await files.stat(path);
|
|
1417
|
+
},
|
|
1418
|
+
async exists(path) {
|
|
1419
|
+
return await files.exists(path);
|
|
1420
|
+
},
|
|
1421
|
+
async mkdir(path, options) {
|
|
1422
|
+
await files.mkdir(path, options);
|
|
1423
|
+
},
|
|
1424
|
+
async rm(path, options) {
|
|
1425
|
+
await files.rm(path, options);
|
|
1426
|
+
},
|
|
1427
|
+
async publish(options) {
|
|
1428
|
+
const { publishWorkspace } = await import("./lifecycle-Lhk3dAMt.js").then((n) => n.t);
|
|
1429
|
+
await publishWorkspace(definition, store, options);
|
|
1430
|
+
},
|
|
1431
|
+
async snapshot(options) {
|
|
1432
|
+
const snapshot = await store.snapshot(options);
|
|
1433
|
+
const { publishWorkspaceSnapshot } = await import("./lifecycle-Lhk3dAMt.js").then((n) => n.t);
|
|
1434
|
+
await publishWorkspaceSnapshot(definition, store, snapshot);
|
|
1435
|
+
return snapshot;
|
|
1436
|
+
},
|
|
1437
|
+
async diff(options) {
|
|
1438
|
+
return await store.diff(options);
|
|
1439
|
+
},
|
|
1440
|
+
async startSession(options) {
|
|
1441
|
+
const host = options?.host;
|
|
1442
|
+
if (host) {
|
|
1443
|
+
const { createHostedWorkspaceSession } = await import("./host-I-_vDs05.js");
|
|
1444
|
+
return await createHostedWorkspaceSession(workspace, {
|
|
1445
|
+
...options,
|
|
1446
|
+
host
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1449
|
+
return await createBasicWorkspaceSession(workspace, options);
|
|
1450
|
+
},
|
|
1451
|
+
mount(options) {
|
|
1452
|
+
return {
|
|
1453
|
+
workspace,
|
|
1454
|
+
mode: options?.mode || "read-only",
|
|
1455
|
+
target: options?.target || "/workspace",
|
|
1456
|
+
async diff() {
|
|
1457
|
+
return await workspace.diff();
|
|
1458
|
+
},
|
|
1459
|
+
async commit() {
|
|
1460
|
+
await workspace.snapshot({ name: "mount-commit" });
|
|
1461
|
+
},
|
|
1462
|
+
async export() {
|
|
1463
|
+
return await workspace.snapshot({ name: "mount-export" });
|
|
1464
|
+
}
|
|
1465
|
+
};
|
|
1466
|
+
}
|
|
1467
|
+
};
|
|
1468
|
+
forwardWorkspaceStoreTarget(store, workspace);
|
|
1469
|
+
workspace.__syncWorkspaceDefinition = async () => {
|
|
1470
|
+
const { syncWorkspaceDefinition } = await import("./lifecycle-Lhk3dAMt.js").then((n) => n.t);
|
|
1471
|
+
await syncWorkspaceDefinition(definition, store);
|
|
1472
|
+
};
|
|
1473
|
+
return attachWorkspaceSourceRequestExecution(workspace, createWorkspaceSourceRequestExecution(definition));
|
|
1474
|
+
}
|
|
1475
|
+
//#endregion
|
|
1476
|
+
export { scopedSearchQuery as _, sourceSyncMetaKey as a, normalizeSourceItemPath as c, createBasicWorkspaceSession as d, assertDiffInsideSessionPaths as f, isMissingWorkspacePathError as g, filterSessionEntries as h, readWorkspaceSourceSyncState as i, createWorkspaceWritePolicy as l, filterSessionDiff as m, resetWorkspaceStoreCache as n, workspaceSourceSyncStateEquals as o, assertPathInSessionScope as p, createWorkspaceSourceView as r, resolveWorkspacePath as s, createWorkspace as t, resolveWorkspaceAutoCommit as u };
|