@vite-hub/workspace 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +225 -17
  2. package/dist/{ai-Bk3LLnit.js → ai-Ce3PtWFW.js} +160 -29
  3. package/dist/ai-nmHdzjCM.d.ts +162 -0
  4. package/dist/ai.d.ts +2 -85
  5. package/dist/ai.js +1 -1
  6. package/dist/asset-registry-CaG9b7tf.js +19 -0
  7. package/dist/cloudflare.d.ts +18 -0
  8. package/dist/cloudflare.js +2 -0
  9. package/dist/collections/client.d.ts +39 -0
  10. package/dist/collections/client.js +137 -0
  11. package/dist/collections.d.ts +59 -0
  12. package/dist/collections.js +159 -0
  13. package/dist/config-3I1BnsdO.d.ts +28 -0
  14. package/dist/config-CDoyls2X.js +30 -0
  15. package/dist/config-CZLO0m9h.js +7811 -0
  16. package/dist/file-CHfsZpso.js +23 -0
  17. package/dist/{files-DbsIjBya.js → files-QRV55OCx.js} +6 -5
  18. package/dist/github-CfA5vpJ5.js +189 -0
  19. package/dist/glob-D0vD_wRY.js +17 -0
  20. package/dist/host-CAnbugpI.js +370 -0
  21. package/dist/hosted-C1-tTTTf.js +581 -0
  22. package/dist/{providers/vercel/blob-store.js → hosted-vercel-blob-CWBILDVo.js} +100 -19
  23. package/dist/hosted-vercel-blob.d.ts +15 -0
  24. package/dist/hosted-vercel-blob.js +2 -0
  25. package/dist/hosted.d.ts +18 -0
  26. package/dist/hosted.js +2 -0
  27. package/dist/index.d.ts +129 -102
  28. package/dist/index.js +477 -599
  29. package/dist/lifecycle-BYoa9hVb.js +176 -0
  30. package/dist/loader.d.ts +1 -1
  31. package/dist/loader.js +1 -1
  32. package/dist/mountx.d.ts +10 -0
  33. package/dist/mountx.js +143 -0
  34. package/dist/nitro.d.ts +2 -31
  35. package/dist/nitro.js +2 -2
  36. package/dist/nuxt.d.ts +26 -0
  37. package/dist/nuxt.js +36 -0
  38. package/dist/path-CNI6wKIU.js +115 -0
  39. package/dist/{provider-BZuKAV4e.js → provider-C3_elpEh.js} +142 -37
  40. package/dist/providers/github/store.d.ts +6 -0
  41. package/dist/providers/github/store.js +2 -0
  42. package/dist/publish.d.ts +3 -2
  43. package/dist/publish.js +48 -142
  44. package/dist/{registry-D4Qzq26I.d.ts → registry-BIQVCBWI.d.ts} +3 -2
  45. package/dist/registry-CqyDTW9Y.js +74 -0
  46. package/dist/request-execution-u9mgUXKX.js +80 -0
  47. package/dist/runtime/assets.d.ts +2 -1
  48. package/dist/runtime/assets.js +5 -5
  49. package/dist/runtime/empty-assets-registry.d.ts +1 -1
  50. package/dist/runtime/empty-registry.d.ts +1 -1
  51. package/dist/runtime/state.d.ts +4 -21
  52. package/dist/runtime/state.js +7 -4
  53. package/dist/runtime/workspace.d.ts +2 -0
  54. package/dist/runtime/workspace.js +2 -0
  55. package/dist/runtime-options-BsPSv5O7.js +13 -0
  56. package/dist/runtime.d.ts +38 -0
  57. package/dist/runtime.js +626 -0
  58. package/dist/{search-DtaEyjpO.js → search-C4REyHj9.js} +2 -2
  59. package/dist/server.d.ts +65 -0
  60. package/dist/server.js +355 -0
  61. package/dist/shared-jfogBrd5.js +273 -0
  62. package/dist/source-metadata.d.ts +2 -0
  63. package/dist/source-metadata.js +2 -0
  64. package/dist/state-TTqa3x3Y.d.ts +25 -0
  65. package/dist/store-Bs1SLh55.js +414 -0
  66. package/dist/sync-DiuDmSGk.js +269 -0
  67. package/dist/target-D4Bqb1eH.js +11 -0
  68. package/dist/test.d.ts +1 -1
  69. package/dist/test.js +1 -1
  70. package/dist/types-60Yn149G.d.ts +612 -0
  71. package/dist/use-CUFSnFCS.d.ts +86 -0
  72. package/dist/use-CsV3oIxH.js +336 -0
  73. package/dist/vite-tbfDxtlu.js +2191 -0
  74. package/dist/vite.d.ts +33 -5
  75. package/dist/vite.js +2 -131
  76. package/dist/workspace-66SKyiec.d.ts +6 -0
  77. package/dist/workspace-C4k92Ow8.js +1460 -0
  78. package/package.json +143 -62
  79. package/dist/asset-registry-CMuQbyvl.js +0 -14
  80. package/dist/cloudflare-env-DL94Uvpz.js +0 -12
  81. package/dist/config-CvS-7sre.js +0 -49
  82. package/dist/errors-BUL8SoFS.js +0 -21
  83. package/dist/lifecycle-uD82JeGh.js +0 -92
  84. package/dist/module-8LZUMEXC.js +0 -922
  85. package/dist/path-BVv9OXhg.js +0 -63
  86. package/dist/providers/cloudflare/artifacts-store.d.ts +0 -6
  87. package/dist/providers/cloudflare/artifacts-store.js +0 -384
  88. package/dist/providers/vercel/blob-store.d.ts +0 -6
  89. package/dist/registry-Cnr0NoKv.js +0 -932
  90. package/dist/runtime/nitro-plugin.d.ts +0 -6
  91. package/dist/runtime/nitro-plugin.js +0 -14
  92. package/dist/sandbox-DtGXCWRq.js +0 -198
  93. package/dist/types-CwNcWTdt.d.ts +0 -378
  94. package/dist/utils-BtAm_K5P.js +0 -51
  95. /package/dist/{chunk-DrSxFLj_.js → chunk-8H4AJuhK.js} +0 -0
@@ -0,0 +1,581 @@
1
+ import { a as matchesAny, c as normalizeWorkspacePath, d as sha256, o as normalizeSafeWorkspacePath, p as workspaceError, r as contentToBytes, s as normalizeSafeWorkspacePattern } from "./path-CNI6wKIU.js";
2
+ import { c as getWorkspaceHostedStoreLoader, d as setWorkspaceRuntimeConfig, i as resolveGitHubWorkspaceStore, l as setWorkspaceHostedStoreLoader, r as resolveCloudflareArtifactsStore } from "./provider-C3_elpEh.js";
3
+ import { i as diffSnapshots, r as createSnapshotFromEntries, t as createGitHubWorkspaceStore } from "./store-Bs1SLh55.js";
4
+ import { g as getActiveCloudflareBinding } from "./shared-jfogBrd5.js";
5
+ import { resolve } from "node:path";
6
+ //#region src/storage/memory-fs.ts
7
+ var MemoryStats = class {
8
+ entry;
9
+ constructor(entry) {
10
+ this.entry = entry;
11
+ }
12
+ get size() {
13
+ return this.entry.kind === "file" ? this.entry.data.byteLength : 0;
14
+ }
15
+ get mtimeMs() {
16
+ return this.entry.mtimeMs;
17
+ }
18
+ get ctimeMs() {
19
+ return this.entry.mtimeMs;
20
+ }
21
+ get mode() {
22
+ return this.entry.kind === "file" ? 33188 : 16384;
23
+ }
24
+ isFile() {
25
+ return this.entry.kind === "file";
26
+ }
27
+ isDirectory() {
28
+ return this.entry.kind === "dir";
29
+ }
30
+ isSymbolicLink() {
31
+ return false;
32
+ }
33
+ };
34
+ var MemoryFS = class {
35
+ #decoder = new TextDecoder();
36
+ #encoder = new TextEncoder();
37
+ entries = new Map([["/", {
38
+ kind: "dir",
39
+ children: /* @__PURE__ */ new Set(),
40
+ mtimeMs: Date.now()
41
+ }]]);
42
+ promises = {
43
+ lstat: this.lstat.bind(this),
44
+ mkdir: this.mkdir.bind(this),
45
+ readFile: this.readFile.bind(this),
46
+ readlink: this.readlink.bind(this),
47
+ readdir: this.readdir.bind(this),
48
+ rmdir: this.rmdir.bind(this),
49
+ stat: this.stat.bind(this),
50
+ symlink: this.symlink.bind(this),
51
+ unlink: this.unlink.bind(this),
52
+ writeFile: this.writeFile.bind(this)
53
+ };
54
+ normalize(input) {
55
+ const segments = [];
56
+ for (const part of input.split("/")) {
57
+ if (!part || part === ".") continue;
58
+ if (part === "..") segments.pop();
59
+ else segments.push(part);
60
+ }
61
+ return segments.length ? `/${segments.join("/")}` : "/";
62
+ }
63
+ parent(path) {
64
+ const normalized = this.normalize(path);
65
+ if (normalized === "/") return "/";
66
+ const parts = normalized.split("/").filter(Boolean);
67
+ parts.pop();
68
+ return parts.length ? `/${parts.join("/")}` : "/";
69
+ }
70
+ basename(path) {
71
+ return this.normalize(path).split("/").filter(Boolean).pop() || "";
72
+ }
73
+ async mkdir(path, options) {
74
+ const target = this.normalize(path);
75
+ if (target === "/") return;
76
+ const recursive = typeof options === "object" && Boolean(options?.recursive);
77
+ const parent = this.parent(target);
78
+ if (!this.entries.has(parent)) {
79
+ if (!recursive) throw new Error(`ENOENT: ${parent}`);
80
+ await this.mkdir(parent, { recursive: true });
81
+ }
82
+ if (this.entries.has(target)) return;
83
+ this.entries.set(target, {
84
+ kind: "dir",
85
+ children: /* @__PURE__ */ new Set(),
86
+ mtimeMs: Date.now()
87
+ });
88
+ this.#requireDir(parent).children.add(this.basename(target));
89
+ }
90
+ async writeFile(path, data) {
91
+ const target = this.normalize(path);
92
+ await this.mkdir(this.parent(target), { recursive: true });
93
+ const bytes = typeof data === "string" ? this.#encoder.encode(data) : data instanceof Uint8Array ? data : new Uint8Array(data);
94
+ this.entries.set(target, {
95
+ kind: "file",
96
+ data: bytes,
97
+ mtimeMs: Date.now()
98
+ });
99
+ this.#requireDir(this.parent(target)).children.add(this.basename(target));
100
+ }
101
+ async readFile(path, options) {
102
+ const entry = this.#requireEntry(path);
103
+ if (entry.kind !== "file") throw new Error(`EISDIR: ${path}`);
104
+ return (typeof options === "string" ? options : options?.encoding) ? this.#decoder.decode(entry.data) : entry.data;
105
+ }
106
+ async readdir(path) {
107
+ return [...this.#requireDir(path).children].sort();
108
+ }
109
+ async unlink(path) {
110
+ const target = this.normalize(path);
111
+ if (this.#requireEntry(target).kind !== "file") throw new Error(`EISDIR: ${path}`);
112
+ this.entries.delete(target);
113
+ this.#requireDir(this.parent(target)).children.delete(this.basename(target));
114
+ }
115
+ async rmdir(path) {
116
+ const target = this.normalize(path);
117
+ if (this.#requireDir(target).children.size) throw new Error(`ENOTEMPTY: ${path}`);
118
+ this.entries.delete(target);
119
+ this.#requireDir(this.parent(target)).children.delete(this.basename(target));
120
+ }
121
+ async stat(path) {
122
+ return new MemoryStats(this.#requireEntry(path));
123
+ }
124
+ async lstat(path) {
125
+ return this.stat(path);
126
+ }
127
+ async readlink(path) {
128
+ this.#requireEntry(path);
129
+ throw memoryFsError("EINVAL", path);
130
+ }
131
+ async symlink(_target, path) {
132
+ throw memoryFsError("ENOTSUP", path);
133
+ }
134
+ deleteTree(path) {
135
+ const target = this.normalize(path);
136
+ const removed = [...this.entries.keys()].filter((key) => key === target || key.startsWith(`${target}/`));
137
+ for (const key of removed.sort((a, b) => b.length - a.length)) {
138
+ if (key === "/") continue;
139
+ this.entries.delete(key);
140
+ }
141
+ const parent = this.parent(target);
142
+ const parentEntry = this.entries.get(parent);
143
+ if (parentEntry?.kind === "dir") parentEntry.children.delete(this.basename(target));
144
+ return removed.length;
145
+ }
146
+ #requireEntry(path) {
147
+ const entry = this.entries.get(this.normalize(path));
148
+ if (!entry) throw memoryFsError("ENOENT", path);
149
+ return entry;
150
+ }
151
+ #requireDir(path) {
152
+ const entry = this.#requireEntry(path);
153
+ if (entry.kind !== "dir") throw new Error(`ENOTDIR: ${path}`);
154
+ return entry;
155
+ }
156
+ };
157
+ function memoryFsError(code, path) {
158
+ return Object.assign(/* @__PURE__ */ new Error(`${code}: ${path}`), { code });
159
+ }
160
+ //#endregion
161
+ //#region src/providers/cloudflare/artifacts-store.ts
162
+ const dir = "/workspace";
163
+ const fileMetadataPath = ".vitehub/files.json";
164
+ const tokenRefreshWindow = 6e4;
165
+ function tokenSecret(token) {
166
+ return token.split("?expires=")[0] || token;
167
+ }
168
+ function tokenExpiresAt(token) {
169
+ const expires = token.match(/[?&]expires=(\d+)(?:&|$)/)?.[1];
170
+ return expires ? Number(expires) * 1e3 : 0;
171
+ }
172
+ function disposeRpc(value) {
173
+ value?.[Symbol.dispose]?.();
174
+ }
175
+ function encodeWorkspaceRepoName(workspaceName) {
176
+ let encoded = "";
177
+ for (const byte of new TextEncoder().encode(workspaceName)) {
178
+ const character = String.fromCharCode(byte);
179
+ if (/[a-zA-Z0-9.-]/.test(character)) encoded += character;
180
+ else if (character === "_") encoded += "__";
181
+ else encoded += `_${byte.toString(16).padStart(2, "0")}`;
182
+ }
183
+ return encoded;
184
+ }
185
+ function repoName(options, workspaceName) {
186
+ return options.repo || `${options.repoPrefix || "vitehub-workspace-"}${encodeWorkspaceRepoName(workspaceName)}`;
187
+ }
188
+ function hasArtifactsErrorCode(error, code, numericCode) {
189
+ if (typeof error !== "object" || !error) return false;
190
+ const value = error;
191
+ return value.code === code || value.numericCode === numericCode || value.code === numericCode;
192
+ }
193
+ function isNonFastForward(error) {
194
+ if (typeof error !== "object" || !error) return false;
195
+ const value = error;
196
+ if (value.code === "PushRejectedError" && value.data?.reason === "not-fast-forward") return true;
197
+ if (value.code !== "GitPushError") return false;
198
+ return /non-fast-forward|fetch first|stale info/i.test([
199
+ value.message,
200
+ value.data?.prettyDetails,
201
+ JSON.stringify(value.data?.result)
202
+ ].filter(Boolean).join(" "));
203
+ }
204
+ var CloudflareArtifactsWorkspaceStore = class {
205
+ options;
206
+ workspaceName;
207
+ #baseline;
208
+ #branch = "main";
209
+ #files = /* @__PURE__ */ new Map();
210
+ #fs;
211
+ #head;
212
+ #pendingCommit;
213
+ #remote;
214
+ #ready;
215
+ #mutationQueue = Promise.resolve();
216
+ #token;
217
+ constructor(options, workspaceName) {
218
+ this.options = options;
219
+ this.workspaceName = workspaceName;
220
+ }
221
+ async readFile(path) {
222
+ const normalized = normalizeSafeWorkspacePath(path);
223
+ await this.#ensure();
224
+ const filepath = this.#absolute(normalized);
225
+ const content = await this.#fs.promises.readFile(filepath).catch(() => void 0);
226
+ if (!content) return void 0;
227
+ const fileMetadata = this.#files.get(normalized);
228
+ return {
229
+ path: normalized,
230
+ content,
231
+ mediaType: fileMetadata?.mediaType,
232
+ metadata: fileMetadata?.metadata
233
+ };
234
+ }
235
+ async writeFile(path, file) {
236
+ const normalized = normalizeSafeWorkspacePath(path);
237
+ await this.#ensure();
238
+ await this.#mutate(async () => {
239
+ await this.#fs.promises.writeFile(this.#absolute(normalized), contentToBytes(file.content));
240
+ if (file.mediaType !== void 0 || file.metadata !== void 0) this.#files.set(normalized, {
241
+ mediaType: file.mediaType,
242
+ metadata: file.metadata
243
+ });
244
+ else this.#files.delete(normalized);
245
+ await this.#writeFileMetadata();
246
+ });
247
+ }
248
+ async list(prefix = "", options = {}) {
249
+ await this.#ensure();
250
+ return this.#listEntries(prefix, options);
251
+ }
252
+ async #listEntries(prefix = "", options = {}) {
253
+ const normalizedPrefix = normalizeSafeWorkspacePath(prefix, { allowEmpty: true });
254
+ const entries = [];
255
+ for (const [absolute, entry] of this.#fs.entries) {
256
+ if (absolute === dir || !absolute.startsWith(`${dir}/`)) continue;
257
+ const path = normalizeWorkspacePath(absolute.slice(`${dir}/`.length));
258
+ if (!path || path === ".git" || path.startsWith(".git/") || path === ".vitehub" || path.startsWith(".vitehub/")) continue;
259
+ if (normalizedPrefix) {
260
+ if (path === normalizedPrefix) continue;
261
+ if (!path.startsWith(`${normalizedPrefix}/`)) continue;
262
+ }
263
+ if (!options.recursive && path.slice(normalizedPrefix ? normalizedPrefix.length + 1 : 0).includes("/")) continue;
264
+ if (entry.kind === "file") {
265
+ const fileMetadata = this.#files.get(path);
266
+ entries.push({
267
+ digest: await sha256(entry.data),
268
+ mediaType: fileMetadata?.mediaType,
269
+ metadata: fileMetadata?.metadata,
270
+ mtime: entry.mtimeMs,
271
+ path,
272
+ size: entry.data.byteLength,
273
+ type: "file"
274
+ });
275
+ } else entries.push({
276
+ mtime: entry.mtimeMs,
277
+ path,
278
+ type: "directory"
279
+ });
280
+ }
281
+ return entries.sort((a, b) => a.path.localeCompare(b.path));
282
+ }
283
+ async glob(pattern, _options = {}) {
284
+ const patterns = Array.isArray(pattern) ? pattern.map(normalizeSafeWorkspacePattern) : normalizeSafeWorkspacePattern(pattern);
285
+ return (await this.list("", { recursive: true })).filter((entry) => entry.type === "file" && matchesAny(entry.path, patterns));
286
+ }
287
+ async stat(path) {
288
+ const normalized = normalizeSafeWorkspacePath(path);
289
+ await this.#ensure();
290
+ const stat = await this.#fs.promises.stat(this.#absolute(normalized)).catch(() => void 0);
291
+ if (!stat) return void 0;
292
+ const bytes = stat.isFile() ? await this.#fs.promises.readFile(this.#absolute(normalized)) : void 0;
293
+ const fileMetadata = stat.isFile() ? this.#files.get(normalized) : void 0;
294
+ return {
295
+ digest: bytes ? await sha256(bytes) : void 0,
296
+ mediaType: fileMetadata?.mediaType,
297
+ metadata: fileMetadata?.metadata,
298
+ mtime: stat.mtimeMs,
299
+ path: normalized,
300
+ size: stat.isFile() ? stat.size : void 0,
301
+ type: stat.isDirectory() ? "directory" : "file"
302
+ };
303
+ }
304
+ async mkdir(path, options = {}) {
305
+ const normalized = normalizeSafeWorkspacePath(path);
306
+ await this.#ensure();
307
+ await this.#mutate(() => this.#fs.promises.mkdir(this.#absolute(normalized), { recursive: options.recursive ?? true }));
308
+ }
309
+ async rm(path, options = {}) {
310
+ const normalized = normalizeSafeWorkspacePath(path);
311
+ await this.#ensure();
312
+ await this.#mutate(async () => {
313
+ const absolute = this.#absolute(normalized);
314
+ const stat = await this.#fs.promises.stat(absolute).catch(() => void 0);
315
+ if (!stat) {
316
+ if (options.force) return;
317
+ throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
318
+ }
319
+ if (stat.isDirectory() && !options.recursive) {
320
+ if ((await this.#fs.promises.readdir(absolute)).length) throw workspaceError(`[vitehub] Workspace directory is not empty: ${path}.`);
321
+ }
322
+ if (!this.#fs.deleteTree(absolute) && !options.force) throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
323
+ for (const key of this.#files.keys()) if (key === normalized || key.startsWith(`${normalized}/`)) this.#files.delete(key);
324
+ await this.#writeFileMetadata();
325
+ });
326
+ }
327
+ async snapshot(options = {}) {
328
+ await this.#ensure();
329
+ return this.#mutate(() => this.#createSnapshot(options));
330
+ }
331
+ async #createSnapshot(options) {
332
+ const git = await import("isomorphic-git");
333
+ const http = await import("isomorphic-git/http/web");
334
+ const matrix = await git.statusMatrix({
335
+ dir,
336
+ fs: this.#fs,
337
+ ignored: true
338
+ });
339
+ let changed = false;
340
+ for (const [filepath, head, workdir, stage] of matrix) {
341
+ if (filepath.startsWith(".git/")) continue;
342
+ if (workdir === 0 && (head !== 0 || stage !== 0)) {
343
+ await git.remove({
344
+ dir,
345
+ filepath,
346
+ fs: this.#fs
347
+ });
348
+ changed = true;
349
+ } else if (workdir !== stage) {
350
+ await git.add({
351
+ dir,
352
+ filepath,
353
+ force: true,
354
+ fs: this.#fs
355
+ });
356
+ changed = true;
357
+ }
358
+ }
359
+ if (changed || !this.#head && !this.#pendingCommit) this.#pendingCommit = await git.commit({
360
+ author: {
361
+ email: "workspace@vitehub.dev",
362
+ name: "ViteHub Workspace"
363
+ },
364
+ dir,
365
+ fs: this.#fs,
366
+ message: options.name || "Update workspace"
367
+ });
368
+ const id = this.#pendingCommit;
369
+ if (id) {
370
+ const token = await this.#writeToken();
371
+ try {
372
+ await git.push({
373
+ dir,
374
+ fs: this.#fs,
375
+ http,
376
+ onAuth: () => ({
377
+ password: token,
378
+ username: "x"
379
+ }),
380
+ ref: this.#branch,
381
+ url: this.#remote
382
+ });
383
+ } catch (error) {
384
+ if (isNonFastForward(error)) throw workspaceError(`[vitehub] Workspace "${this.workspaceName}" changed remotely while snapshotting branch "${this.#branch}". Reload the Workspace before retrying.`, { cause: error });
385
+ throw error;
386
+ }
387
+ this.#head = id;
388
+ this.#pendingCommit = void 0;
389
+ }
390
+ const snapshot = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }), options.name);
391
+ this.#baseline = {
392
+ ...snapshot,
393
+ id: id || this.#head || snapshot.id
394
+ };
395
+ return this.#baseline;
396
+ }
397
+ async diff(options = {}) {
398
+ await this.#ensure();
399
+ return diffSnapshots(options.from || this.#baseline, await createSnapshotFromEntries(await this.#listEntries("", { recursive: true })));
400
+ }
401
+ async getMeta(key) {
402
+ const path = this.#metaAbsolute(key);
403
+ await this.#ensure();
404
+ const content = await this.#fs.promises.readFile(path).catch(() => void 0);
405
+ if (!content) return void 0;
406
+ return JSON.parse(new TextDecoder().decode(contentToBytes(content)));
407
+ }
408
+ async setMeta(key, value) {
409
+ const path = this.#metaAbsolute(key);
410
+ await this.#ensure();
411
+ await this.#mutate(() => this.#fs.promises.writeFile(path, contentToBytes(JSON.stringify(value))));
412
+ }
413
+ #absolute(path) {
414
+ return `${dir}/${path}`;
415
+ }
416
+ #internalAbsolute(path) {
417
+ return `${dir}/${normalizeWorkspacePath(path)}`;
418
+ }
419
+ #metaAbsolute(key) {
420
+ const normalized = normalizeSafeWorkspacePath(key.endsWith(".json") ? key : `${key}.json`);
421
+ return this.#internalAbsolute(`.vitehub/meta/${normalized}`);
422
+ }
423
+ async #loadFileMetadata() {
424
+ const content = await this.#fs.promises.readFile(this.#internalAbsolute(fileMetadataPath)).catch(() => void 0);
425
+ if (!content) return;
426
+ const files = JSON.parse(new TextDecoder().decode(content));
427
+ this.#files = new Map(Object.entries(files));
428
+ }
429
+ async #writeFileMetadata() {
430
+ const path = this.#internalAbsolute(fileMetadataPath);
431
+ if (!this.#files.size) {
432
+ this.#fs.deleteTree(path);
433
+ return;
434
+ }
435
+ const files = Object.fromEntries([...this.#files.entries()].sort(([a], [b]) => a.localeCompare(b)));
436
+ await this.#fs.promises.writeFile(path, JSON.stringify(files));
437
+ }
438
+ #rememberToken(value, expiresAt) {
439
+ this.#token = {
440
+ expiresAt: (expiresAt ? Date.parse(expiresAt) : 0) || tokenExpiresAt(value),
441
+ value: tokenSecret(value)
442
+ };
443
+ }
444
+ async #writeToken(repo) {
445
+ if (this.#token && this.#token.expiresAt > Date.now() + tokenRefreshWindow) return this.#token.value;
446
+ const tokenRepo = repo || await this.#getBinding().get(repoName(this.options, this.workspaceName));
447
+ let token;
448
+ try {
449
+ token = await tokenRepo.createToken("write", 3600);
450
+ this.#rememberToken(token.plaintext, token.expiresAt);
451
+ return this.#token.value;
452
+ } finally {
453
+ disposeRpc(token);
454
+ if (!repo) disposeRpc(tokenRepo);
455
+ }
456
+ }
457
+ #getBinding() {
458
+ const bindingName = this.options.binding || "WORKSPACE_ARTIFACTS";
459
+ const binding = getActiveCloudflareBinding(bindingName) || globalThis[bindingName];
460
+ if (!binding) throw workspaceError(`[vitehub] Cloudflare Artifacts binding "${bindingName}" not found.`);
461
+ return binding;
462
+ }
463
+ async #ensure() {
464
+ this.#ready ||= this.#load();
465
+ await this.#ready;
466
+ }
467
+ #mutate(operation) {
468
+ const result = this.#mutationQueue.then(operation);
469
+ this.#mutationQueue = result.then(() => void 0, () => void 0);
470
+ return result;
471
+ }
472
+ async #load() {
473
+ const git = await import("isomorphic-git");
474
+ const http = await import("isomorphic-git/http/web");
475
+ const binding = this.#getBinding();
476
+ const name = repoName(this.options, this.workspaceName);
477
+ let created;
478
+ let repo;
479
+ let repoInfo;
480
+ try {
481
+ try {
482
+ repo = await binding.get(name);
483
+ } catch (error) {
484
+ if (!hasArtifactsErrorCode(error, "NOT_FOUND", 10200)) throw error;
485
+ try {
486
+ created = await binding.create(name, {
487
+ description: `ViteHub workspace ${this.workspaceName}`,
488
+ readOnly: false,
489
+ setDefaultBranch: this.options.branch || "main"
490
+ });
491
+ } catch (createError) {
492
+ if (!hasArtifactsErrorCode(createError, "ALREADY_EXISTS", 10201)) throw createError;
493
+ }
494
+ repo = await binding.get(name);
495
+ }
496
+ repoInfo = created || await repo.info();
497
+ this.#remote = repoInfo.remote;
498
+ this.#branch = this.options.branch || repoInfo.defaultBranch || "main";
499
+ if (created) this.#rememberToken(created.token);
500
+ this.#fs = new MemoryFS();
501
+ await this.#fs.promises.mkdir(dir, { recursive: true });
502
+ const token = await this.#writeToken(repo);
503
+ const branchRef = `refs/heads/${this.#branch}`;
504
+ if (!(await git.listServerRefs({
505
+ http,
506
+ onAuth: () => ({
507
+ password: token,
508
+ username: "x"
509
+ }),
510
+ prefix: branchRef,
511
+ url: this.#remote
512
+ })).some((ref) => ref.ref === branchRef)) await git.init({
513
+ defaultBranch: this.#branch,
514
+ dir,
515
+ fs: this.#fs
516
+ });
517
+ else {
518
+ await git.clone({
519
+ depth: 1,
520
+ dir,
521
+ fs: this.#fs,
522
+ http,
523
+ onAuth: () => ({
524
+ password: token,
525
+ username: "x"
526
+ }),
527
+ ref: this.#branch,
528
+ singleBranch: true,
529
+ url: this.#remote
530
+ });
531
+ this.#head = await git.resolveRef({
532
+ dir,
533
+ fs: this.#fs,
534
+ ref: this.#branch
535
+ });
536
+ }
537
+ } finally {
538
+ try {
539
+ disposeRpc(repoInfo);
540
+ if (created !== repoInfo) disposeRpc(created);
541
+ } finally {
542
+ disposeRpc(repo);
543
+ }
544
+ }
545
+ await this.#loadFileMetadata();
546
+ const baseline = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }));
547
+ this.#baseline = this.#head ? {
548
+ ...baseline,
549
+ id: this.#head
550
+ } : baseline;
551
+ }
552
+ };
553
+ function createCloudflareArtifactsWorkspaceStore(options, workspaceName) {
554
+ return new CloudflareArtifactsWorkspaceStore(options, workspaceName);
555
+ }
556
+ //#endregion
557
+ //#region src/hosted.ts
558
+ function installHostedWorkspaceRuntime() {
559
+ const existingWorkspaceHostedStoreLoader = getWorkspaceHostedStoreLoader();
560
+ setWorkspaceHostedStoreLoader((storeOptions, workspaceName) => {
561
+ if (storeOptions.provider === "cloudflare-artifacts") return createCloudflareArtifactsWorkspaceStore(storeOptions, workspaceName);
562
+ if (storeOptions.provider === "github") return createGitHubWorkspaceStore(storeOptions, workspaceName);
563
+ if (existingWorkspaceHostedStoreLoader) return existingWorkspaceHostedStoreLoader(storeOptions, workspaceName);
564
+ throw workspaceError("[vitehub] Hosted workspace runtime cannot load unsupported hosted store.");
565
+ });
566
+ }
567
+ function configureHostedWorkspaceRuntime(options = {}) {
568
+ const root = resolve(process.cwd(), options.root || ".vitehub/workspaces");
569
+ const store = options.store?.provider === "github" ? resolveGitHubWorkspaceStore(options.store, options.env, { runtime: true }) : options.store?.provider === "vercel-blob" ? void 0 : resolveCloudflareArtifactsStore(options.store, options.env);
570
+ if (!store) throw workspaceError("[vitehub] Vercel Blob hosted workspace runtime must use @vite-hub/workspace/internal/runtime/hosted-vercel-blob.");
571
+ const config = {
572
+ assets: options.assets,
573
+ root,
574
+ store
575
+ };
576
+ installHostedWorkspaceRuntime();
577
+ setWorkspaceRuntimeConfig(config);
578
+ return config;
579
+ }
580
+ //#endregion
581
+ export { installHostedWorkspaceRuntime as n, createCloudflareArtifactsWorkspaceStore as r, configureHostedWorkspaceRuntime as t };