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