@vite-hub/workspace 0.6.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/{asset-registry-0CdRAjIV.js → asset-registry-DJyE42kr.js} +1 -1
- package/dist/blob-database.d.ts +1 -1
- package/dist/blob-database.js +6 -6
- package/dist/checkout.js +2 -2
- package/dist/cloudflare.d.ts +1 -1
- package/dist/cloudflare.js +1 -1
- package/dist/{config-jo5QgE1w.js → config--ZzAvhMp.js} +14 -9
- package/dist/{config-DeA287c0.d.ts → config-DF6sqKXB.d.ts} +1 -1
- package/dist/durability.d.ts +1 -1
- package/dist/durability.js +2 -2
- package/dist/{error-diagnostics-B4me-ouV.js → error-diagnostics-CHgE8TQM.js} +16 -0
- package/dist/{error-diagnostics-kKXseq8d.js → error-diagnostics-CsiNo_oI.js} +3 -3
- package/dist/{file-BrNAXQgY.js → file-DQ5-TBTD.js} +1 -1
- package/dist/{file-metadata-Bpsvjw_X.js → file-metadata-Dqpldj0h.js} +7 -2
- package/dist/{files--z2dLC5z.js → files-D1UkSjzX.js} +2 -2
- package/dist/files.d.ts +5 -5
- package/dist/files.js +5 -5
- package/dist/{github-k--_LCrX.js → github-BECfOMaw.js} +4 -4
- package/dist/{glob-BreFjNAV.js → glob-BIg9O4yY.js} +2 -2
- package/dist/{glob-BEutagp1.js → glob-BIsxLusH.js} +1 -1
- package/dist/{host-C8yZizfk.js → host-BYBRcSnh.js} +7 -7
- package/dist/hosted-vercel-blob.d.ts +1 -1
- package/dist/hosted-vercel-blob.js +464 -1
- package/dist/hosted.d.ts +1 -1
- package/dist/hosted.js +917 -1
- package/dist/index.d.ts +6 -7
- package/dist/index.js +13 -13
- package/dist/internal/path.js +108 -1
- package/dist/internal/workspace.d.ts +2 -3
- package/dist/internal/workspace.js +2 -2
- package/dist/{lifecycle-IReZfi0b.js → lifecycle-BK7WNfcP.js} +8 -8
- package/dist/loader.d.ts +1 -1
- package/dist/loader.js +2 -2
- package/dist/{mcp-resources-DeJnbOaw.js → mcp-resources-F4SJF4_P.js} +2 -2
- package/dist/{memory-BlSRrBH1.js → memory-BCZl_ZsJ.js} +26 -4
- package/dist/{metadata-target-CaGLY4ay.js → metadata-target-DPGF6L68.js} +59 -24
- package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-BALFFdKj.d.ts} +1 -0
- package/dist/{operations-BIaK_uYG.js → operations-DJ_7W0gs.js} +8 -7
- package/dist/operations.d.ts +2 -2
- package/dist/operations.js +1327 -2
- package/dist/{path-Bb9OIc_F.js → path-DYHw5KNk.js} +11 -3
- package/dist/plugins-BYxsPDBH.d.ts +12 -0
- package/dist/{provider-CN14ewvx.js → provider-fcI7kJ5k.js} +256 -70
- package/dist/providers/github/store.d.ts +1 -1
- package/dist/providers/github/store.js +1994 -1
- package/dist/{registry-BbUg9vJB.js → registry-CFeUQsja.js} +3 -3
- package/dist/{registry-B0g19sdy.d.ts → registry-h1-cT-cE.d.ts} +1 -1
- package/dist/{registry-s2Ob9PeX.d.ts → registry-hnARUKNF.d.ts} +2 -2
- package/dist/replacement-CVZVsflC.js +76 -0
- package/dist/{request-scope-CXCI_wCb.js → request-scope-jH4H0Sbm.js} +3 -1
- package/dist/{rule-keys-BLEbi1h5.js → rule-keys-xMpiTLq1.js} +1 -1
- package/dist/{rules-BPDXypZV.js → rules-DYQCKYdt.js} +4 -4
- package/dist/runtime/assets.d.ts +1 -1
- package/dist/runtime/assets.js +4 -4
- package/dist/runtime/empty-assets-registry.d.ts +1 -1
- package/dist/runtime/empty-registry.d.ts +2 -2
- package/dist/runtime/registry.d.ts +1 -1
- package/dist/runtime/request.js +1 -1
- package/dist/runtime/state.d.ts +17 -6
- package/dist/runtime/state.js +7 -7
- package/dist/runtime/workspace.d.ts +1 -1
- package/dist/runtime/workspace.js +1 -1
- package/dist/runtime.d.ts +8 -8
- package/dist/runtime.js +38 -23
- package/dist/{search-C_nVorq7.js → search-CG6UNOtn.js} +1 -1
- package/dist/server.d.ts +2 -2
- package/dist/server.js +301 -1
- package/dist/{shared-C20Wh1mp.js → shared-PFnkYidS.js} +59 -21
- package/dist/source-metadata.d.ts +2 -2
- package/dist/source-metadata.js +3 -3
- package/dist/{sync-BBfR4g5y.js → sync-CUkCuP_g.js} +5 -5
- package/dist/test.d.ts +1 -1
- package/dist/test.js +1 -1
- package/dist/{types-Bel5IDmF.d.ts → types-BnSUug2v.d.ts} +13 -1
- package/dist/{use-D0DyTMxM.js → use-BCMkT-kC.js} +15 -51
- package/dist/{use-CpphIBof.d.ts → use-CJ5rdIrW.d.ts} +1 -1
- package/dist/{use-tools-CHduR5k6.js → use-tools-CcXs2hFA.js} +4 -4
- package/dist/{use-tools-CAK10LTc.d.ts → use-tools-DFVqZwgc.d.ts} +2 -2
- package/dist/{utils-DXP9xfXo.js → utils-Bv1NBg8r.js} +5 -5
- package/dist/vite.d.ts +2 -2
- package/dist/vite.js +368 -62
- package/dist/{workspace-BOuxrZrP.d.ts → workspace-B6QreLJd.d.ts} +1 -1
- package/dist/{workspace-CLuPkyZR.js → workspace-D1m00MCM.js} +340 -104
- package/dist/workspace-inspection-scanner-BlJ8bCAB.js +140 -0
- package/package.json +12 -12
- package/dist/errors-CnFDXxeJ.d.ts +0 -4
- package/dist/hosted-8BTKAtMX.js +0 -883
- package/dist/hosted-vercel-blob-B6kygYqn.js +0 -408
- package/dist/operations-DS1C4uXd.js +0 -1308
- package/dist/path-CuYE8-X6.js +0 -57
- package/dist/plugins-CLc32jvL.d.ts +0 -8
- package/dist/server-aa1a4rkV.js +0 -301
- package/dist/state-BdDfBtOR.d.ts +0 -17
- package/dist/store-cx3OqNTi.js +0 -1971
package/dist/hosted.js
CHANGED
|
@@ -1 +1,917 @@
|
|
|
1
|
-
|
|
1
|
+
import { a as resolveGitHubWorkspaceStore, d as setWorkspaceHostedStoreLoader, i as resolveCloudflareArtifactsStore, u as getWorkspaceHostedStoreLoader } from "./provider-fcI7kJ5k.js";
|
|
2
|
+
import { i as workspaceConflict, normalizeSafeWorkspacePath, o as workspaceError, t as assertWorkspaceDigest } from "./internal/path.js";
|
|
3
|
+
import { k as getActiveCloudflareBinding } from "./shared-PFnkYidS.js";
|
|
4
|
+
import { n as copyJsonFileMetadata } from "./file-metadata-Dqpldj0h.js";
|
|
5
|
+
import { a as isExcludedWorkspacePath, c as normalizeSafeWorkspacePattern, f as sha256, l as normalizeWorkspacePath, r as contentToBytes } from "./path-DYHw5KNk.js";
|
|
6
|
+
import { t as createWorkspaceGlobMatcher } from "./glob-BIg9O4yY.js";
|
|
7
|
+
import { t as workspaceStoreDiscard } from "./discard-BkoLmmmN.js";
|
|
8
|
+
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
9
|
+
import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CHgE8TQM.js";
|
|
10
|
+
import { i as replaceStorePath } from "./replacement-CVZVsflC.js";
|
|
11
|
+
import { n as createSnapshotFromEntries, r as diffSnapshots } from "./utils-Bv1NBg8r.js";
|
|
12
|
+
import { createGitHubWorkspaceStore } from "./providers/github/store.js";
|
|
13
|
+
import { n as setWorkspaceRuntimeConfig } from "./config-CsgNNVAI.js";
|
|
14
|
+
import { resolve } from "node:path";
|
|
15
|
+
import { boolean, check, object, optional, parse as parse$1, pipe, record, string, unknown } from "valibot";
|
|
16
|
+
// src/storage/memory-fs.ts
|
|
17
|
+
function copyBinaryData(data) {
|
|
18
|
+
if (ArrayBuffer.isView(data)) return Uint8Array.from(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
|
|
19
|
+
if (Object.prototype.toString.call(data) === "[object ArrayBuffer]") return Uint8Array.from(new Uint8Array(data));
|
|
20
|
+
}
|
|
21
|
+
var MemoryStats = class {
|
|
22
|
+
entry;
|
|
23
|
+
constructor(entry) {
|
|
24
|
+
this.entry = entry;
|
|
25
|
+
}
|
|
26
|
+
get size() {
|
|
27
|
+
return this.entry.kind === "file" ? this.entry.data.byteLength : 0;
|
|
28
|
+
}
|
|
29
|
+
get mtimeMs() {
|
|
30
|
+
return this.entry.mtimeMs;
|
|
31
|
+
}
|
|
32
|
+
get ctimeMs() {
|
|
33
|
+
return this.entry.mtimeMs;
|
|
34
|
+
}
|
|
35
|
+
get mode() {
|
|
36
|
+
return this.entry.kind === "file" ? 33188 : 16384;
|
|
37
|
+
}
|
|
38
|
+
isFile() {
|
|
39
|
+
return this.entry.kind === "file";
|
|
40
|
+
}
|
|
41
|
+
isDirectory() {
|
|
42
|
+
return this.entry.kind === "dir";
|
|
43
|
+
}
|
|
44
|
+
isSymbolicLink() {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
var MemoryFS = class MemoryFS {
|
|
49
|
+
#decoder = new TextDecoder();
|
|
50
|
+
#encoder = new TextEncoder();
|
|
51
|
+
entries = /* @__PURE__ */ new Map([["/", {
|
|
52
|
+
kind: "dir",
|
|
53
|
+
children: /* @__PURE__ */ new Set(),
|
|
54
|
+
mtimeMs: Date.now()
|
|
55
|
+
}]]);
|
|
56
|
+
promises = {
|
|
57
|
+
lstat: this.lstat.bind(this),
|
|
58
|
+
mkdir: this.mkdir.bind(this),
|
|
59
|
+
readFile: this.readFile.bind(this),
|
|
60
|
+
readlink: this.readlink.bind(this),
|
|
61
|
+
readdir: this.readdir.bind(this),
|
|
62
|
+
rmdir: this.rmdir.bind(this),
|
|
63
|
+
stat: this.stat.bind(this),
|
|
64
|
+
symlink: this.symlink.bind(this),
|
|
65
|
+
unlink: this.unlink.bind(this),
|
|
66
|
+
writeFile: this.writeFile.bind(this)
|
|
67
|
+
};
|
|
68
|
+
fork() {
|
|
69
|
+
const fork = new MemoryFS();
|
|
70
|
+
for (const [path, entry] of this.entries) fork.entries.set(path, entry.kind === "dir" ? {
|
|
71
|
+
...entry,
|
|
72
|
+
children: new Set(entry.children)
|
|
73
|
+
} : entry);
|
|
74
|
+
return fork;
|
|
75
|
+
}
|
|
76
|
+
normalize(input) {
|
|
77
|
+
const segments = [];
|
|
78
|
+
for (const part of input.split("/")) {
|
|
79
|
+
if (!part || part === ".") continue;
|
|
80
|
+
if (part === "..") segments.pop();
|
|
81
|
+
else segments.push(part);
|
|
82
|
+
}
|
|
83
|
+
return segments.length ? `/${segments.join("/")}` : "/";
|
|
84
|
+
}
|
|
85
|
+
parent(path) {
|
|
86
|
+
const normalized = this.normalize(path);
|
|
87
|
+
if (normalized === "/") return "/";
|
|
88
|
+
const parts = normalized.split("/").filter(Boolean);
|
|
89
|
+
parts.pop();
|
|
90
|
+
return parts.length ? `/${parts.join("/")}` : "/";
|
|
91
|
+
}
|
|
92
|
+
basename(path) {
|
|
93
|
+
return this.normalize(path).split("/").filter(Boolean).pop() || "";
|
|
94
|
+
}
|
|
95
|
+
async mkdir(path, options) {
|
|
96
|
+
const target = this.normalize(path);
|
|
97
|
+
const recursive = isRecord(options) && options.recursive === true;
|
|
98
|
+
if (target === "/") {
|
|
99
|
+
if (recursive) return;
|
|
100
|
+
throw memoryFsError("EEXIST", path);
|
|
101
|
+
}
|
|
102
|
+
const parent = this.parent(target);
|
|
103
|
+
if (!this.entries.has(parent)) {
|
|
104
|
+
if (!recursive) throw memoryFsError("ENOENT", parent);
|
|
105
|
+
await this.mkdir(parent, { recursive: true });
|
|
106
|
+
}
|
|
107
|
+
const existing = this.entries.get(target);
|
|
108
|
+
if (existing) {
|
|
109
|
+
if (existing.kind === "dir" && recursive) return;
|
|
110
|
+
throw memoryFsError("EEXIST", path);
|
|
111
|
+
}
|
|
112
|
+
const parentEntry = this.#requireDir(parent);
|
|
113
|
+
this.entries.set(target, {
|
|
114
|
+
kind: "dir",
|
|
115
|
+
children: /* @__PURE__ */ new Set(),
|
|
116
|
+
mtimeMs: Date.now()
|
|
117
|
+
});
|
|
118
|
+
parentEntry.children.add(this.basename(target));
|
|
119
|
+
}
|
|
120
|
+
async writeFile(path, data) {
|
|
121
|
+
const target = this.normalize(path);
|
|
122
|
+
if (this.entries.get(target)?.kind === "dir") throw memoryFsError("EISDIR", path);
|
|
123
|
+
const parentPath = this.parent(target);
|
|
124
|
+
if (!this.entries.has(parentPath)) await this.mkdir(parentPath, { recursive: true });
|
|
125
|
+
const parent = this.#requireDir(parentPath);
|
|
126
|
+
const bytes = copyBinaryData(data) ?? this.#encoder.encode(String(data));
|
|
127
|
+
this.entries.set(target, {
|
|
128
|
+
kind: "file",
|
|
129
|
+
data: bytes,
|
|
130
|
+
mtimeMs: Date.now()
|
|
131
|
+
});
|
|
132
|
+
parent.children.add(this.basename(target));
|
|
133
|
+
}
|
|
134
|
+
async readFile(path, options) {
|
|
135
|
+
const entry = this.#requireEntry(path);
|
|
136
|
+
if (entry.kind !== "file") throw memoryFsError("EISDIR", path);
|
|
137
|
+
return (isRecord(options) ? options.encoding : options) ? this.#decoder.decode(entry.data) : Uint8Array.from(entry.data);
|
|
138
|
+
}
|
|
139
|
+
async readdir(path) {
|
|
140
|
+
return [...this.#requireDir(path).children].sort();
|
|
141
|
+
}
|
|
142
|
+
async unlink(path) {
|
|
143
|
+
const target = this.normalize(path);
|
|
144
|
+
if (this.#requireEntry(target).kind !== "file") throw memoryFsError("EISDIR", path);
|
|
145
|
+
this.entries.delete(target);
|
|
146
|
+
this.#requireDir(this.parent(target)).children.delete(this.basename(target));
|
|
147
|
+
}
|
|
148
|
+
async rmdir(path) {
|
|
149
|
+
const target = this.normalize(path);
|
|
150
|
+
if (target === "/") throw memoryFsError("EBUSY", path);
|
|
151
|
+
if (this.#requireDir(target).children.size) throw memoryFsError("ENOTEMPTY", path);
|
|
152
|
+
this.entries.delete(target);
|
|
153
|
+
this.#requireDir(this.parent(target)).children.delete(this.basename(target));
|
|
154
|
+
}
|
|
155
|
+
async stat(path) {
|
|
156
|
+
return new MemoryStats(this.#requireEntry(path));
|
|
157
|
+
}
|
|
158
|
+
async lstat(path) {
|
|
159
|
+
return this.stat(path);
|
|
160
|
+
}
|
|
161
|
+
async readlink(path) {
|
|
162
|
+
this.#requireEntry(path);
|
|
163
|
+
throw memoryFsError("EINVAL", path);
|
|
164
|
+
}
|
|
165
|
+
async symlink(_target, path) {
|
|
166
|
+
throw memoryFsError("ENOTSUP", path);
|
|
167
|
+
}
|
|
168
|
+
deleteTree(path) {
|
|
169
|
+
const target = this.normalize(path);
|
|
170
|
+
const removed = [...this.entries.keys()].filter((key) => key === target || key.startsWith(`${target}/`));
|
|
171
|
+
for (const key of removed.sort((a, b) => b.length - a.length)) {
|
|
172
|
+
if (key === "/") continue;
|
|
173
|
+
this.entries.delete(key);
|
|
174
|
+
}
|
|
175
|
+
const parent = this.parent(target);
|
|
176
|
+
const parentEntry = this.entries.get(parent);
|
|
177
|
+
if (parentEntry?.kind === "dir") parentEntry.children.delete(this.basename(target));
|
|
178
|
+
return removed.length;
|
|
179
|
+
}
|
|
180
|
+
#requireEntry(path) {
|
|
181
|
+
const entry = this.entries.get(this.normalize(path));
|
|
182
|
+
if (!entry) throw memoryFsError("ENOENT", path);
|
|
183
|
+
return entry;
|
|
184
|
+
}
|
|
185
|
+
#requireDir(path) {
|
|
186
|
+
const entry = this.#requireEntry(path);
|
|
187
|
+
if (entry.kind !== "dir") throw memoryFsError("ENOTDIR", path);
|
|
188
|
+
return entry;
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
function memoryFsError(code, path) {
|
|
192
|
+
return Object.assign(workspaceErrorDiagnostics.WORKSPACE_R0065({ message: `${code}: ${path}` }), { code });
|
|
193
|
+
}
|
|
194
|
+
// src/providers/cloudflare/artifacts-store.ts
|
|
195
|
+
const dir = "/workspace";
|
|
196
|
+
const fileMetadataPath = ".vitehub/files.json";
|
|
197
|
+
const fileMetadataJournalPath = ".vitehub/files.pending.json";
|
|
198
|
+
const tokenRefreshWindow = 6e4;
|
|
199
|
+
/** How long a Store without staged writes trusts the branch head that it loaded, in milliseconds. */
|
|
200
|
+
const remoteHeadCacheMs = 5e3;
|
|
201
|
+
const fileMetadataSchema = object({
|
|
202
|
+
mediaType: optional(string()),
|
|
203
|
+
metadata: optional(pipe(record(string(), unknown()), check((value) => value.source === void 0 || typeof value.source === "string", "metadata.source must be a string when provided")))
|
|
204
|
+
});
|
|
205
|
+
const fileMetadataFilesSchema = record(string(), fileMetadataSchema);
|
|
206
|
+
const fileMetadataJournalSchema = object({
|
|
207
|
+
path: string(),
|
|
208
|
+
existed: boolean(),
|
|
209
|
+
digest: string(),
|
|
210
|
+
metadata: fileMetadataSchema
|
|
211
|
+
});
|
|
212
|
+
function parseJson(content) {
|
|
213
|
+
return JSON.parse(new TextDecoder().decode(content));
|
|
214
|
+
}
|
|
215
|
+
function sameSnapshotEntry(left, right) {
|
|
216
|
+
return left?.digest === right?.digest && left?.type === right?.type && left?.size === right?.size && JSON.stringify(left?.metadata) === JSON.stringify(right?.metadata);
|
|
217
|
+
}
|
|
218
|
+
function tokenSecret(token) {
|
|
219
|
+
return token.split("?expires=")[0] || token;
|
|
220
|
+
}
|
|
221
|
+
function tokenExpiresAt(token) {
|
|
222
|
+
const expires = token.match(/[?&]expires=(\d+)(?:&|$)/)?.[1];
|
|
223
|
+
return expires ? Number(expires) * 1e3 : 0;
|
|
224
|
+
}
|
|
225
|
+
function disposeRpc(value) {
|
|
226
|
+
value?.[Symbol.dispose]?.();
|
|
227
|
+
}
|
|
228
|
+
function encodeWorkspaceRepoName(workspaceName) {
|
|
229
|
+
let encoded = "";
|
|
230
|
+
for (const byte of new TextEncoder().encode(workspaceName)) {
|
|
231
|
+
const character = String.fromCharCode(byte);
|
|
232
|
+
if (/[a-zA-Z0-9.-]/.test(character)) encoded += character;
|
|
233
|
+
else if (character === "_") encoded += "__";
|
|
234
|
+
else encoded += `_${byte.toString(16).padStart(2, "0")}`;
|
|
235
|
+
}
|
|
236
|
+
return encoded;
|
|
237
|
+
}
|
|
238
|
+
function repoName(options, workspaceName) {
|
|
239
|
+
return options.repo || `${options.repoPrefix || "vitehub-workspace-"}${encodeWorkspaceRepoName(workspaceName)}`;
|
|
240
|
+
}
|
|
241
|
+
function hasArtifactsErrorCode(error, code, numericCode) {
|
|
242
|
+
if (typeof error !== "object" || !error) return false;
|
|
243
|
+
const value = error;
|
|
244
|
+
return value.code === code || value.numericCode === numericCode || value.code === numericCode;
|
|
245
|
+
}
|
|
246
|
+
function isNonFastForward(error) {
|
|
247
|
+
if (typeof error !== "object" || !error) return false;
|
|
248
|
+
const value = error;
|
|
249
|
+
if (value.code === "PushRejectedError" && value.data?.reason === "not-fast-forward") return true;
|
|
250
|
+
if (value.code !== "GitPushError") return false;
|
|
251
|
+
return /non-fast-forward|fetch first|stale info/i.test([
|
|
252
|
+
value.message,
|
|
253
|
+
value.data?.prettyDetails,
|
|
254
|
+
JSON.stringify(value.data?.result)
|
|
255
|
+
].filter(Boolean).join(" "));
|
|
256
|
+
}
|
|
257
|
+
var CloudflareArtifactsWorkspaceStore = class {
|
|
258
|
+
options;
|
|
259
|
+
workspaceName;
|
|
260
|
+
#baseline;
|
|
261
|
+
#branch = "main";
|
|
262
|
+
#digests = /* @__PURE__ */ new WeakMap();
|
|
263
|
+
#files = /* @__PURE__ */ new Map();
|
|
264
|
+
#fs;
|
|
265
|
+
#head;
|
|
266
|
+
#loadedAt = 0;
|
|
267
|
+
#pendingCommit;
|
|
268
|
+
/** Whether files or metadata changed since the last load or push. */
|
|
269
|
+
#staged = false;
|
|
270
|
+
/** Metadata written since the last load or push, by absolute path. A rebase writes it again on the new head. */
|
|
271
|
+
#stagedMeta = /* @__PURE__ */ new Map();
|
|
272
|
+
#remote;
|
|
273
|
+
#ready;
|
|
274
|
+
#mutationQueue = Promise.resolve();
|
|
275
|
+
#token;
|
|
276
|
+
constructor(options, workspaceName) {
|
|
277
|
+
this.options = options;
|
|
278
|
+
this.workspaceName = workspaceName;
|
|
279
|
+
}
|
|
280
|
+
/** Drops the staged writes. The next call clones the branch again, as the first call does. */
|
|
281
|
+
async [workspaceStoreDiscard]() {
|
|
282
|
+
await this.#mutate(async () => {
|
|
283
|
+
this.#files = /* @__PURE__ */ new Map();
|
|
284
|
+
this.#head = void 0;
|
|
285
|
+
this.#pendingCommit = void 0;
|
|
286
|
+
this.#ready = void 0;
|
|
287
|
+
this.#staged = false;
|
|
288
|
+
this.#stagedMeta = /* @__PURE__ */ new Map();
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
async readFile(path) {
|
|
292
|
+
const normalized = normalizeSafeWorkspacePath(path);
|
|
293
|
+
await this.#ensure();
|
|
294
|
+
return await this.#mutate(() => this.#readFile(normalized));
|
|
295
|
+
}
|
|
296
|
+
async #readFile(normalized) {
|
|
297
|
+
const filepath = this.#absolute(normalized);
|
|
298
|
+
const content = await this.#fs.promises.readFile(filepath).catch(() => void 0);
|
|
299
|
+
if (!content) return void 0;
|
|
300
|
+
const fileMetadata = this.#files.get(normalized);
|
|
301
|
+
return {
|
|
302
|
+
path: normalized,
|
|
303
|
+
content,
|
|
304
|
+
mediaType: fileMetadata?.mediaType,
|
|
305
|
+
metadata: structuredClone(fileMetadata?.metadata)
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
async writeFile(path, file) {
|
|
309
|
+
const normalized = normalizeSafeWorkspacePath(path);
|
|
310
|
+
await this.#ensure();
|
|
311
|
+
await this.#mutate(() => this.#writeFile(normalized, file));
|
|
312
|
+
}
|
|
313
|
+
async writeFileConditional(path, file, ifDigest) {
|
|
314
|
+
const normalized = normalizeSafeWorkspacePath(path);
|
|
315
|
+
await this.#ensure();
|
|
316
|
+
await this.#mutate(async () => {
|
|
317
|
+
const current = await this.#stat(normalized).catch(() => void 0);
|
|
318
|
+
assertWorkspaceDigest(normalized, ifDigest, current?.type === "file" ? current.digest : void 0);
|
|
319
|
+
await this.#writeFile(normalized, file);
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
async list(prefix = "", options = {}) {
|
|
323
|
+
await this.#ensure();
|
|
324
|
+
return await this.#mutate(() => this.#listEntries(prefix, options));
|
|
325
|
+
}
|
|
326
|
+
async #listEntries(prefix = "", options = {}) {
|
|
327
|
+
const normalizedPrefix = normalizeSafeWorkspacePath(prefix, { allowEmpty: true });
|
|
328
|
+
const entries = [];
|
|
329
|
+
for (const [absolute, entry] of this.#fs.entries) {
|
|
330
|
+
if (absolute === dir || !absolute.startsWith(`${dir}/`)) continue;
|
|
331
|
+
const path = normalizeWorkspacePath(absolute.slice(`${dir}/`.length));
|
|
332
|
+
const root = path.split("/")[0]?.toLowerCase();
|
|
333
|
+
if (!path || root === ".git" || root === ".vitehub") continue;
|
|
334
|
+
if (isExcludedWorkspacePath(path, options.exclude)) continue;
|
|
335
|
+
if (normalizedPrefix) {
|
|
336
|
+
if (path === normalizedPrefix) continue;
|
|
337
|
+
if (!path.startsWith(`${normalizedPrefix}/`)) continue;
|
|
338
|
+
}
|
|
339
|
+
if (!options.recursive && path.slice(normalizedPrefix ? normalizedPrefix.length + 1 : 0).includes("/")) continue;
|
|
340
|
+
if (entry.kind === "file") {
|
|
341
|
+
const fileMetadata = this.#files.get(path);
|
|
342
|
+
entries.push({
|
|
343
|
+
digest: await this.#digest(entry.data),
|
|
344
|
+
mediaType: fileMetadata?.mediaType,
|
|
345
|
+
metadata: structuredClone(fileMetadata?.metadata),
|
|
346
|
+
mtime: entry.mtimeMs,
|
|
347
|
+
path,
|
|
348
|
+
size: entry.data.byteLength,
|
|
349
|
+
type: "file"
|
|
350
|
+
});
|
|
351
|
+
} else entries.push({
|
|
352
|
+
mtime: entry.mtimeMs,
|
|
353
|
+
path,
|
|
354
|
+
type: "directory"
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
return entries.sort((a, b) => a.path.localeCompare(b.path));
|
|
358
|
+
}
|
|
359
|
+
async #digest(data) {
|
|
360
|
+
let digest = this.#digests.get(data);
|
|
361
|
+
if (digest === void 0) {
|
|
362
|
+
digest = await sha256(data);
|
|
363
|
+
this.#digests.set(data, digest);
|
|
364
|
+
}
|
|
365
|
+
return digest;
|
|
366
|
+
}
|
|
367
|
+
async glob(pattern, options = {}) {
|
|
368
|
+
const patterns = Array.isArray(pattern) ? pattern.map(normalizeSafeWorkspacePattern) : normalizeSafeWorkspacePattern(pattern);
|
|
369
|
+
const { cwd, matches } = createWorkspaceGlobMatcher(patterns, options);
|
|
370
|
+
return (await this.list(cwd, { recursive: true })).filter((entry) => entry.type === "file" && matches(entry.path));
|
|
371
|
+
}
|
|
372
|
+
async stat(path) {
|
|
373
|
+
const normalized = normalizeSafeWorkspacePath(path);
|
|
374
|
+
await this.#ensure();
|
|
375
|
+
return await this.#mutate(() => this.#stat(normalized));
|
|
376
|
+
}
|
|
377
|
+
async #stat(normalized) {
|
|
378
|
+
const stat = await this.#fs.promises.stat(this.#absolute(normalized)).catch(() => void 0);
|
|
379
|
+
if (!stat) return void 0;
|
|
380
|
+
const entry = this.#fs.entries.get(this.#fs.normalize(this.#absolute(normalized)));
|
|
381
|
+
const fileMetadata = stat.isFile() ? this.#files.get(normalized) : void 0;
|
|
382
|
+
return {
|
|
383
|
+
digest: entry?.kind === "file" ? await this.#digest(entry.data) : void 0,
|
|
384
|
+
mediaType: fileMetadata?.mediaType,
|
|
385
|
+
metadata: structuredClone(fileMetadata?.metadata),
|
|
386
|
+
mtime: stat.mtimeMs,
|
|
387
|
+
path: normalized,
|
|
388
|
+
size: stat.isFile() ? stat.size : void 0,
|
|
389
|
+
type: stat.isDirectory() ? "directory" : "file"
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
async mkdir(path, options = {}) {
|
|
393
|
+
const normalized = normalizeSafeWorkspacePath(path);
|
|
394
|
+
await this.#ensure();
|
|
395
|
+
await this.#mutate(() => this.#fs.promises.mkdir(this.#absolute(normalized), { recursive: options.recursive ?? true }));
|
|
396
|
+
}
|
|
397
|
+
async [replaceStorePath]({ path, directories, files, removeTree }) {
|
|
398
|
+
await this.#ensure();
|
|
399
|
+
await this.#mutate(async () => {
|
|
400
|
+
const previous = this.#fs;
|
|
401
|
+
const metadata = this.#files;
|
|
402
|
+
const staged = this.#staged;
|
|
403
|
+
this.#fs = previous.fork();
|
|
404
|
+
this.#files = new Map(metadata);
|
|
405
|
+
try {
|
|
406
|
+
if (removeTree) {
|
|
407
|
+
this.#fs.deleteTree(this.#absolute(path));
|
|
408
|
+
for (const key of this.#files.keys()) if (key === path || key.startsWith(`${path}/`)) this.#files.delete(key);
|
|
409
|
+
for (const directory of directories) await this.#fs.promises.mkdir(this.#absolute(directory), { recursive: true });
|
|
410
|
+
this.#staged = true;
|
|
411
|
+
}
|
|
412
|
+
for (const file of files) await this.#writeFile(file.path, file);
|
|
413
|
+
if (!files.length) await this.#writeFileMetadata();
|
|
414
|
+
} catch (error) {
|
|
415
|
+
this.#fs = previous;
|
|
416
|
+
this.#files = metadata;
|
|
417
|
+
this.#staged = staged;
|
|
418
|
+
throw error;
|
|
419
|
+
}
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
async removeEmptyDirectory(path) {
|
|
423
|
+
const normalized = normalizeSafeWorkspacePath(path, { allowEmpty: true });
|
|
424
|
+
if (!normalized) return;
|
|
425
|
+
await this.#ensure();
|
|
426
|
+
await this.#mutate(async () => {
|
|
427
|
+
await this.#fs.promises.rmdir(this.#absolute(normalized)).catch((error) => {
|
|
428
|
+
if (error.code !== "ENOENT" && error.code !== "ENOTDIR") throw error;
|
|
429
|
+
});
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
async rm(path, options = {}) {
|
|
433
|
+
const normalized = normalizeSafeWorkspacePath(path);
|
|
434
|
+
await this.#ensure();
|
|
435
|
+
await this.#mutate(async () => {
|
|
436
|
+
if (options.ifDigest !== void 0) assertWorkspaceDigest(path, options.ifDigest, (await this.#stat(normalized))?.digest);
|
|
437
|
+
const absolute = this.#absolute(normalized);
|
|
438
|
+
const stat = await this.#fs.promises.stat(absolute).catch(() => void 0);
|
|
439
|
+
if (!stat) {
|
|
440
|
+
if (options.force) return;
|
|
441
|
+
throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
|
|
442
|
+
}
|
|
443
|
+
if (stat.isDirectory() && !options.recursive) {
|
|
444
|
+
if ((await this.#fs.promises.readdir(absolute)).length) throw workspaceError(`[vitehub] Workspace directory is not empty: ${path}.`);
|
|
445
|
+
}
|
|
446
|
+
const removed = this.#fs.deleteTree(absolute);
|
|
447
|
+
if (!removed && !options.force) throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
|
|
448
|
+
if (removed) this.#staged = true;
|
|
449
|
+
for (const key of this.#files.keys()) if (key === normalized || key.startsWith(`${normalized}/`)) this.#files.delete(key);
|
|
450
|
+
await this.#writeFileMetadata();
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
async snapshot(options = {}) {
|
|
454
|
+
await this.#ensure();
|
|
455
|
+
return this.#mutate(() => this.#createSnapshot(options));
|
|
456
|
+
}
|
|
457
|
+
async rebase(options = {}) {
|
|
458
|
+
await this.#ensure();
|
|
459
|
+
await this.#mutate(async () => await this.#rebase(options));
|
|
460
|
+
}
|
|
461
|
+
/** Load the current branch head and write the staged changes on it again. A path that changed on both sides fails with its name in `details.paths`. */
|
|
462
|
+
async #rebase(options) {
|
|
463
|
+
const baseline = this.#baseline;
|
|
464
|
+
const current = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }));
|
|
465
|
+
const changes = diffSnapshots(baseline, current).entries.filter((change) => change.before?.type === "file" || change.after?.type === "file");
|
|
466
|
+
const local = /* @__PURE__ */ new Map();
|
|
467
|
+
for (const change of changes) local.set(change.path, change.after ? await this.#readFile(change.path) : void 0);
|
|
468
|
+
const previous = {
|
|
469
|
+
baseline: this.#baseline,
|
|
470
|
+
branch: this.#branch,
|
|
471
|
+
files: this.#files,
|
|
472
|
+
fs: this.#fs,
|
|
473
|
+
head: this.#head,
|
|
474
|
+
pendingCommit: this.#pendingCommit,
|
|
475
|
+
remote: this.#remote,
|
|
476
|
+
staged: this.#staged,
|
|
477
|
+
stagedMeta: this.#stagedMeta
|
|
478
|
+
};
|
|
479
|
+
const restore = () => {
|
|
480
|
+
this.#baseline = previous.baseline;
|
|
481
|
+
this.#branch = previous.branch;
|
|
482
|
+
this.#files = previous.files;
|
|
483
|
+
this.#fs = previous.fs;
|
|
484
|
+
this.#head = previous.head;
|
|
485
|
+
this.#pendingCommit = previous.pendingCommit;
|
|
486
|
+
this.#remote = previous.remote;
|
|
487
|
+
this.#staged = previous.staged;
|
|
488
|
+
this.#stagedMeta = previous.stagedMeta;
|
|
489
|
+
};
|
|
490
|
+
try {
|
|
491
|
+
this.#files = /* @__PURE__ */ new Map();
|
|
492
|
+
this.#pendingCommit = void 0;
|
|
493
|
+
await this.#load();
|
|
494
|
+
const remoteChanges = new Map(diffSnapshots(baseline, this.#baseline).entries.map((change) => [change.path, change]));
|
|
495
|
+
const takeRemote = new Set(options.takeRemote || []);
|
|
496
|
+
const conflicts = changes.filter((change) => remoteChanges.has(change.path) && !takeRemote.has(change.path) && !sameSnapshotEntry(current.entries[change.path], this.#baseline?.entries[change.path])).map((change) => change.path).sort();
|
|
497
|
+
if (conflicts.length) throw workspaceConflict(`[vitehub] Cloudflare Artifacts Workspace Store rebase conflict: ${conflicts.join(", ")} changed locally and remotely.`, { details: {
|
|
498
|
+
branch: this.#branch,
|
|
499
|
+
paths: conflicts
|
|
500
|
+
} });
|
|
501
|
+
let replayed = 0;
|
|
502
|
+
for (const change of changes) {
|
|
503
|
+
if (remoteChanges.has(change.path) && takeRemote.has(change.path)) continue;
|
|
504
|
+
replayed++;
|
|
505
|
+
const file = local.get(change.path);
|
|
506
|
+
if (file) await this.#writeFile(change.path, file);
|
|
507
|
+
else {
|
|
508
|
+
this.#fs.deleteTree(this.#absolute(change.path));
|
|
509
|
+
this.#files.delete(change.path);
|
|
510
|
+
await this.#writeFileMetadata();
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
for (const [path, bytes] of previous.stagedMeta) if (bytes.byteLength) await this.#fs.promises.writeFile(path, bytes);
|
|
514
|
+
else this.#fs.deleteTree(path);
|
|
515
|
+
this.#stagedMeta = new Map(previous.stagedMeta);
|
|
516
|
+
this.#staged = replayed > 0 || previous.stagedMeta.size > 0;
|
|
517
|
+
} catch (error) {
|
|
518
|
+
restore();
|
|
519
|
+
throw error;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* Commit and push the staged changes. When the branch moved since the Store loaded, for example because another
|
|
524
|
+
* isolate pushed, the Store loads the new head, writes the staged changes on it again, and pushes once more. A path
|
|
525
|
+
* that changed on both sides, or a second move, fails with `WORKSPACE_CONFLICT`.
|
|
526
|
+
*/
|
|
527
|
+
async #createSnapshot(options, retry = true) {
|
|
528
|
+
const git = await import("isomorphic-git");
|
|
529
|
+
const http = await import("isomorphic-git/http/web");
|
|
530
|
+
const matrix = await git.statusMatrix({
|
|
531
|
+
dir,
|
|
532
|
+
fs: this.#fs,
|
|
533
|
+
ignored: true
|
|
534
|
+
});
|
|
535
|
+
const removed = [];
|
|
536
|
+
const added = [];
|
|
537
|
+
for (const [filepath, head, workdir, stage] of matrix) {
|
|
538
|
+
if (filepath.startsWith(".git/")) continue;
|
|
539
|
+
if (workdir === 0 && (head !== 0 || stage !== 0)) removed.push(filepath);
|
|
540
|
+
else if (workdir !== stage) added.push(filepath);
|
|
541
|
+
}
|
|
542
|
+
if (removed.length) await git.remove({
|
|
543
|
+
dir,
|
|
544
|
+
filepath: removed,
|
|
545
|
+
fs: this.#fs
|
|
546
|
+
});
|
|
547
|
+
if (added.length) await git.add({
|
|
548
|
+
dir,
|
|
549
|
+
filepath: added,
|
|
550
|
+
force: true,
|
|
551
|
+
fs: this.#fs
|
|
552
|
+
});
|
|
553
|
+
if (removed.length > 0 || added.length > 0 || !this.#head && !this.#pendingCommit) this.#pendingCommit = await git.commit({
|
|
554
|
+
author: options.author ?? {
|
|
555
|
+
email: "workspace@vitehub.dev",
|
|
556
|
+
name: "ViteHub Workspace"
|
|
557
|
+
},
|
|
558
|
+
committer: {
|
|
559
|
+
email: "workspace@vitehub.dev",
|
|
560
|
+
name: "ViteHub Workspace"
|
|
561
|
+
},
|
|
562
|
+
dir,
|
|
563
|
+
fs: this.#fs,
|
|
564
|
+
message: options.name || "Update workspace"
|
|
565
|
+
});
|
|
566
|
+
const id = this.#pendingCommit;
|
|
567
|
+
if (id) {
|
|
568
|
+
const token = await this.#writeToken();
|
|
569
|
+
try {
|
|
570
|
+
await git.push({
|
|
571
|
+
dir,
|
|
572
|
+
fs: this.#fs,
|
|
573
|
+
http,
|
|
574
|
+
onAuth: () => ({
|
|
575
|
+
password: token,
|
|
576
|
+
username: "x"
|
|
577
|
+
}),
|
|
578
|
+
ref: this.#branch,
|
|
579
|
+
url: this.#remote
|
|
580
|
+
});
|
|
581
|
+
} catch (error) {
|
|
582
|
+
if (isNonFastForward(error)) {
|
|
583
|
+
if (retry) {
|
|
584
|
+
await this.#rebase({});
|
|
585
|
+
return await this.#createSnapshot(options, false);
|
|
586
|
+
}
|
|
587
|
+
throw workspaceConflict(`[vitehub] Workspace "${this.workspaceName}" changed remotely while snapshotting branch "${this.#branch}". Reload the Workspace before retrying.`, { cause: error });
|
|
588
|
+
}
|
|
589
|
+
throw error;
|
|
590
|
+
}
|
|
591
|
+
this.#head = id;
|
|
592
|
+
this.#pendingCommit = void 0;
|
|
593
|
+
}
|
|
594
|
+
this.#staged = false;
|
|
595
|
+
this.#stagedMeta = /* @__PURE__ */ new Map();
|
|
596
|
+
this.#loadedAt = Date.now();
|
|
597
|
+
const snapshot = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }), options.name);
|
|
598
|
+
this.#baseline = {
|
|
599
|
+
...snapshot,
|
|
600
|
+
id: id || this.#head || snapshot.id
|
|
601
|
+
};
|
|
602
|
+
return this.#baseline;
|
|
603
|
+
}
|
|
604
|
+
async diff(options = {}) {
|
|
605
|
+
await this.#ensure();
|
|
606
|
+
return await this.#mutate(async () => {
|
|
607
|
+
const from = options.from || this.#baseline;
|
|
608
|
+
const to = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }));
|
|
609
|
+
return diffSnapshots(from, to);
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
async getMeta(key) {
|
|
613
|
+
const path = this.#metaAbsolute(key);
|
|
614
|
+
await this.#ensure();
|
|
615
|
+
return await this.#mutate(async () => {
|
|
616
|
+
const content = await this.#fs.promises.readFile(path).catch(() => void 0);
|
|
617
|
+
const bytes = content === void 0 ? void 0 : contentToBytes(content);
|
|
618
|
+
if (!bytes?.byteLength) return void 0;
|
|
619
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
async setMeta(key, value) {
|
|
623
|
+
const path = this.#metaAbsolute(key);
|
|
624
|
+
await this.#ensure();
|
|
625
|
+
await this.#mutate(async () => {
|
|
626
|
+
const bytes = value === void 0 ? /* @__PURE__ */ new Uint8Array() : contentToBytes(JSON.stringify(value));
|
|
627
|
+
if (bytes.byteLength) await this.#fs.promises.writeFile(path, bytes);
|
|
628
|
+
else this.#fs.deleteTree(path);
|
|
629
|
+
this.#stagedMeta.set(path, bytes);
|
|
630
|
+
this.#staged = true;
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
async #writeFile(path, file) {
|
|
634
|
+
file = {
|
|
635
|
+
...file,
|
|
636
|
+
metadata: copyJsonFileMetadata(path, file.metadata)
|
|
637
|
+
};
|
|
638
|
+
const existed = await this.#fs.promises.stat(this.#absolute(path)).then((stat) => stat.isFile()).catch(() => false);
|
|
639
|
+
const content = contentToBytes(file.content);
|
|
640
|
+
const digest = await sha256(content);
|
|
641
|
+
await this.#fs.promises.writeFile(this.#internalAbsolute(fileMetadataJournalPath), JSON.stringify({
|
|
642
|
+
path,
|
|
643
|
+
existed,
|
|
644
|
+
digest,
|
|
645
|
+
metadata: {
|
|
646
|
+
mediaType: file.mediaType,
|
|
647
|
+
metadata: file.metadata
|
|
648
|
+
}
|
|
649
|
+
}));
|
|
650
|
+
await this.#fs.promises.writeFile(this.#absolute(path), content);
|
|
651
|
+
this.#staged = true;
|
|
652
|
+
if (file.mediaType !== void 0 || file.metadata !== void 0) this.#files.set(path, {
|
|
653
|
+
mediaType: file.mediaType,
|
|
654
|
+
metadata: file.metadata
|
|
655
|
+
});
|
|
656
|
+
else this.#files.delete(path);
|
|
657
|
+
await this.#writeFileMetadata();
|
|
658
|
+
this.#fs.deleteTree(this.#internalAbsolute(fileMetadataJournalPath));
|
|
659
|
+
}
|
|
660
|
+
#absolute(path) {
|
|
661
|
+
return `${dir}/${path}`;
|
|
662
|
+
}
|
|
663
|
+
#internalAbsolute(path) {
|
|
664
|
+
return `${dir}/${normalizeWorkspacePath(path)}`;
|
|
665
|
+
}
|
|
666
|
+
#metaAbsolute(key) {
|
|
667
|
+
const normalized = normalizeSafeWorkspacePath(key.endsWith(".json") ? key : `${key}.json`);
|
|
668
|
+
return this.#internalAbsolute(`.vitehub/meta/${normalized}`);
|
|
669
|
+
}
|
|
670
|
+
async #loadFileMetadata() {
|
|
671
|
+
const content = await this.#fs.promises.readFile(this.#internalAbsolute(fileMetadataPath)).catch(() => void 0);
|
|
672
|
+
if (content) {
|
|
673
|
+
const files = parse$1(fileMetadataFilesSchema, parseJson(contentToBytes(content)));
|
|
674
|
+
this.#files = new Map(Object.entries(files).map(([path, file]) => [path, {
|
|
675
|
+
...file,
|
|
676
|
+
metadata: copyJsonFileMetadata(path, file.metadata)
|
|
677
|
+
}]));
|
|
678
|
+
}
|
|
679
|
+
const pending = await this.#fs.promises.readFile(this.#internalAbsolute(fileMetadataJournalPath)).catch(() => void 0);
|
|
680
|
+
if (!pending) return;
|
|
681
|
+
let journal;
|
|
682
|
+
try {
|
|
683
|
+
journal = parse$1(fileMetadataJournalSchema, parseJson(contentToBytes(pending)));
|
|
684
|
+
journal.metadata.metadata = copyJsonFileMetadata(journal.path, journal.metadata.metadata);
|
|
685
|
+
} catch {
|
|
686
|
+
this.#fs.deleteTree(this.#internalAbsolute(fileMetadataJournalPath));
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
try {
|
|
690
|
+
if (journal.path && await this.#fs.promises.stat(this.#absolute(journal.path)).then((stat) => stat.isFile()).catch(() => false)) {
|
|
691
|
+
const content = await this.#fs.promises.readFile(this.#absolute(journal.path));
|
|
692
|
+
if (await sha256(contentToBytes(content)) !== journal.digest) return;
|
|
693
|
+
if (journal.metadata && (journal.metadata.mediaType !== void 0 || journal.metadata.metadata !== void 0)) this.#files.set(journal.path, journal.metadata);
|
|
694
|
+
else this.#files.delete(journal.path);
|
|
695
|
+
await this.#writeFileMetadata();
|
|
696
|
+
}
|
|
697
|
+
} finally {
|
|
698
|
+
this.#fs.deleteTree(this.#internalAbsolute(fileMetadataJournalPath));
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
async #writeFileMetadata() {
|
|
702
|
+
const path = this.#internalAbsolute(fileMetadataPath);
|
|
703
|
+
if (!this.#files.size) {
|
|
704
|
+
this.#fs.deleteTree(path);
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
const files = Object.fromEntries([...this.#files.entries()].sort(([a], [b]) => a.localeCompare(b)));
|
|
708
|
+
await this.#fs.promises.writeFile(path, JSON.stringify(files));
|
|
709
|
+
}
|
|
710
|
+
#rememberToken(value, expiresAt) {
|
|
711
|
+
this.#token = {
|
|
712
|
+
expiresAt: (expiresAt ? Date.parse(expiresAt) : 0) || tokenExpiresAt(value),
|
|
713
|
+
value: tokenSecret(value)
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
async #writeToken(repo) {
|
|
717
|
+
if (this.#token && this.#token.expiresAt > Date.now() + tokenRefreshWindow) return this.#token.value;
|
|
718
|
+
const tokenRepo = repo || await this.#getBinding().get(repoName(this.options, this.workspaceName));
|
|
719
|
+
let token;
|
|
720
|
+
try {
|
|
721
|
+
token = await tokenRepo.createToken("write", 3600);
|
|
722
|
+
this.#rememberToken(token.plaintext, token.expiresAt);
|
|
723
|
+
return this.#token.value;
|
|
724
|
+
} finally {
|
|
725
|
+
disposeRpc(token);
|
|
726
|
+
if (!repo) disposeRpc(tokenRepo);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
#getBinding() {
|
|
730
|
+
const bindingName = this.options.binding || "WORKSPACE_ARTIFACTS";
|
|
731
|
+
const binding = getActiveCloudflareBinding(bindingName) || globalThis[bindingName];
|
|
732
|
+
if (!binding) throw workspaceError(`[vitehub] Cloudflare Artifacts binding "${bindingName}" not found.`);
|
|
733
|
+
return binding;
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Load the branch once. A Store without staged changes that loaded more than `remoteHeadCacheMs` ago asks for the
|
|
737
|
+
* branch head again and loads it when it moved, so a Store that one isolate keeps for many requests sees pushes from
|
|
738
|
+
* other writers before it stages new changes.
|
|
739
|
+
*/
|
|
740
|
+
async #ensure() {
|
|
741
|
+
const wasReady = !!this.#ready;
|
|
742
|
+
this.#ready ||= this.#load().catch((error) => {
|
|
743
|
+
this.#ready = void 0;
|
|
744
|
+
throw error;
|
|
745
|
+
});
|
|
746
|
+
await this.#ready;
|
|
747
|
+
if (!wasReady) return;
|
|
748
|
+
await this.#mutate(async () => {
|
|
749
|
+
if (this.#staged || this.#pendingCommit || Date.now() - this.#loadedAt < remoteHeadCacheMs) return;
|
|
750
|
+
if (await this.#remoteHead() === this.#head) {
|
|
751
|
+
this.#loadedAt = Date.now();
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
const previous = {
|
|
755
|
+
baseline: this.#baseline,
|
|
756
|
+
branch: this.#branch,
|
|
757
|
+
files: this.#files,
|
|
758
|
+
fs: this.#fs,
|
|
759
|
+
head: this.#head,
|
|
760
|
+
remote: this.#remote
|
|
761
|
+
};
|
|
762
|
+
try {
|
|
763
|
+
this.#files = /* @__PURE__ */ new Map();
|
|
764
|
+
this.#head = void 0;
|
|
765
|
+
await this.#load();
|
|
766
|
+
} catch (error) {
|
|
767
|
+
this.#baseline = previous.baseline;
|
|
768
|
+
this.#branch = previous.branch;
|
|
769
|
+
this.#files = previous.files;
|
|
770
|
+
this.#fs = previous.fs;
|
|
771
|
+
this.#head = previous.head;
|
|
772
|
+
this.#remote = previous.remote;
|
|
773
|
+
throw error;
|
|
774
|
+
}
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
async #remoteHead() {
|
|
778
|
+
const git = await import("isomorphic-git");
|
|
779
|
+
const http = await import("isomorphic-git/http/web");
|
|
780
|
+
const token = await this.#writeToken();
|
|
781
|
+
const branchRef = `refs/heads/${this.#branch}`;
|
|
782
|
+
return (await git.listServerRefs({
|
|
783
|
+
http,
|
|
784
|
+
onAuth: () => ({
|
|
785
|
+
password: token,
|
|
786
|
+
username: "x"
|
|
787
|
+
}),
|
|
788
|
+
prefix: branchRef,
|
|
789
|
+
url: this.#remote
|
|
790
|
+
})).find((ref) => ref.ref === branchRef)?.oid;
|
|
791
|
+
}
|
|
792
|
+
#mutate(operation) {
|
|
793
|
+
const result = this.#mutationQueue.then(operation);
|
|
794
|
+
this.#mutationQueue = result.then(() => void 0, () => void 0);
|
|
795
|
+
return result;
|
|
796
|
+
}
|
|
797
|
+
async #load() {
|
|
798
|
+
const git = await import("isomorphic-git");
|
|
799
|
+
const http = await import("isomorphic-git/http/web");
|
|
800
|
+
const binding = this.#getBinding();
|
|
801
|
+
const name = repoName(this.options, this.workspaceName);
|
|
802
|
+
let created;
|
|
803
|
+
let repo;
|
|
804
|
+
let repoInfo;
|
|
805
|
+
try {
|
|
806
|
+
try {
|
|
807
|
+
repo = await binding.get(name);
|
|
808
|
+
} catch (error) {
|
|
809
|
+
if (!hasArtifactsErrorCode(error, "NOT_FOUND", 10200)) throw error;
|
|
810
|
+
try {
|
|
811
|
+
created = await binding.create(name, {
|
|
812
|
+
description: `ViteHub workspace ${this.workspaceName}`,
|
|
813
|
+
readOnly: false,
|
|
814
|
+
setDefaultBranch: this.options.branch || "main"
|
|
815
|
+
});
|
|
816
|
+
} catch (createError) {
|
|
817
|
+
if (!hasArtifactsErrorCode(createError, "ALREADY_EXISTS", 10201)) throw createError;
|
|
818
|
+
}
|
|
819
|
+
repo = await binding.get(name);
|
|
820
|
+
}
|
|
821
|
+
repoInfo = created || await repo.info();
|
|
822
|
+
this.#remote = repoInfo.remote;
|
|
823
|
+
this.#branch = this.options.branch || repoInfo.defaultBranch || "main";
|
|
824
|
+
if (created) this.#rememberToken(created.token);
|
|
825
|
+
this.#fs = new MemoryFS();
|
|
826
|
+
await this.#fs.promises.mkdir(dir, { recursive: true });
|
|
827
|
+
const token = await this.#writeToken(repo);
|
|
828
|
+
const branchRef = `refs/heads/${this.#branch}`;
|
|
829
|
+
if (!(await git.listServerRefs({
|
|
830
|
+
http,
|
|
831
|
+
onAuth: () => ({
|
|
832
|
+
password: token,
|
|
833
|
+
username: "x"
|
|
834
|
+
}),
|
|
835
|
+
prefix: branchRef,
|
|
836
|
+
url: this.#remote
|
|
837
|
+
})).some((ref) => ref.ref === branchRef)) await git.init({
|
|
838
|
+
defaultBranch: this.#branch,
|
|
839
|
+
dir,
|
|
840
|
+
fs: this.#fs
|
|
841
|
+
});
|
|
842
|
+
else {
|
|
843
|
+
await git.clone({
|
|
844
|
+
depth: 1,
|
|
845
|
+
dir,
|
|
846
|
+
fs: this.#fs,
|
|
847
|
+
http,
|
|
848
|
+
onAuth: () => ({
|
|
849
|
+
password: token,
|
|
850
|
+
username: "x"
|
|
851
|
+
}),
|
|
852
|
+
ref: this.#branch,
|
|
853
|
+
singleBranch: true,
|
|
854
|
+
url: this.#remote
|
|
855
|
+
});
|
|
856
|
+
this.#head = await git.resolveRef({
|
|
857
|
+
dir,
|
|
858
|
+
fs: this.#fs,
|
|
859
|
+
ref: this.#branch
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
} finally {
|
|
863
|
+
try {
|
|
864
|
+
disposeRpc(repoInfo);
|
|
865
|
+
if (created !== repoInfo) disposeRpc(created);
|
|
866
|
+
} finally {
|
|
867
|
+
disposeRpc(repo);
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
await this.#loadFileMetadata();
|
|
871
|
+
const baseline = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }));
|
|
872
|
+
this.#baseline = this.#head ? {
|
|
873
|
+
...baseline,
|
|
874
|
+
id: this.#head
|
|
875
|
+
} : baseline;
|
|
876
|
+
this.#loadedAt = Date.now();
|
|
877
|
+
this.#staged = false;
|
|
878
|
+
this.#stagedMeta = /* @__PURE__ */ new Map();
|
|
879
|
+
}
|
|
880
|
+
};
|
|
881
|
+
function createCloudflareArtifactsWorkspaceStore(options, workspaceName) {
|
|
882
|
+
return new CloudflareArtifactsWorkspaceStore(options, workspaceName);
|
|
883
|
+
}
|
|
884
|
+
// src/hosted.ts
|
|
885
|
+
function installHostedGitHubWorkspaceStore() {
|
|
886
|
+
const existingWorkspaceHostedStoreLoader = getWorkspaceHostedStoreLoader();
|
|
887
|
+
setWorkspaceHostedStoreLoader((storeOptions, workspaceName) => {
|
|
888
|
+
if (storeOptions.driver === "github") return createGitHubWorkspaceStore(storeOptions, workspaceName);
|
|
889
|
+
return existingWorkspaceHostedStoreLoader?.(storeOptions, workspaceName);
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
function installHostedCloudflareArtifactsWorkspaceStore() {
|
|
893
|
+
const existingWorkspaceHostedStoreLoader = getWorkspaceHostedStoreLoader();
|
|
894
|
+
setWorkspaceHostedStoreLoader((storeOptions, workspaceName) => {
|
|
895
|
+
if (storeOptions.driver === "cloudflare") return createCloudflareArtifactsWorkspaceStore(storeOptions, workspaceName);
|
|
896
|
+
return existingWorkspaceHostedStoreLoader?.(storeOptions, workspaceName);
|
|
897
|
+
});
|
|
898
|
+
}
|
|
899
|
+
function installHostedWorkspaceRuntime() {
|
|
900
|
+
installHostedGitHubWorkspaceStore();
|
|
901
|
+
installHostedCloudflareArtifactsWorkspaceStore();
|
|
902
|
+
}
|
|
903
|
+
function configureHostedWorkspaceRuntime(options = {}) {
|
|
904
|
+
const root = resolve(process.cwd(), options.root || ".vitehub/workspaces");
|
|
905
|
+
const store = options.store?.driver === "github" ? resolveGitHubWorkspaceStore(options.store, options.env || {}, { runtime: true }) : options.store?.driver === "vercel" ? void 0 : resolveCloudflareArtifactsStore(options.store, options.env);
|
|
906
|
+
if (!store) throw workspaceError("[vitehub] Vercel Blob hosted workspace runtime must use @vite-hub/workspace/internal/runtime/hosted-vercel-blob.");
|
|
907
|
+
const config = {
|
|
908
|
+
assets: options.assets,
|
|
909
|
+
root,
|
|
910
|
+
store
|
|
911
|
+
};
|
|
912
|
+
if (store.driver === "github") installHostedGitHubWorkspaceStore();
|
|
913
|
+
else installHostedCloudflareArtifactsWorkspaceStore();
|
|
914
|
+
setWorkspaceRuntimeConfig(config);
|
|
915
|
+
return config;
|
|
916
|
+
}
|
|
917
|
+
export { configureHostedWorkspaceRuntime, installHostedCloudflareArtifactsWorkspaceStore, installHostedGitHubWorkspaceStore, installHostedWorkspaceRuntime, createCloudflareArtifactsWorkspaceStore as t };
|