@vite-hub/workspace 0.0.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +339 -115
- package/dist/abort-BCwpdrN0.js +32 -0
- package/dist/{asset-registry-8QI3ML3K.js → asset-registry-DfBV5kmw.js} +3 -2
- package/dist/blob-database.d.ts +474 -0
- package/dist/blob-database.js +608 -0
- package/dist/checkout.d.ts +128 -0
- package/dist/checkout.js +849 -0
- package/dist/cloudflare.d.ts +6 -7
- package/dist/cloudflare.js +1 -1
- package/dist/config-B-863EgC.js +15 -0
- package/dist/config-BAgL2dtB.js +1076 -0
- package/dist/{config-DE9xlaIw.d.ts → config-BQKcPawI.d.ts} +1 -2
- package/dist/discard-CNNtCozM.js +8 -0
- package/dist/durability.d.ts +22 -0
- package/dist/durability.js +70 -0
- package/dist/error-diagnostics-CtKjGtGb.js +188 -0
- package/dist/error-diagnostics-DSkCJC_L.js +266 -0
- package/dist/file-2pFYNtsU.js +22 -0
- package/dist/{files-Q6xZjDHA.js → files-BOo4SbwE.js} +3 -3
- package/dist/files.d.ts +38 -0
- package/dist/files.js +6 -0
- package/dist/{github-DHnjxQIX.js → github-CrYp4v8k.js} +44 -24
- package/dist/glob-B8YGvTrZ.js +21 -0
- package/dist/glob-Cjxms1t7.js +30 -0
- package/dist/{host-DJH8cuoU.js → host-BFBpXn0N.js} +144 -77
- package/dist/{hosted-RPeJOCFz.js → hosted-KcUR_jPv.js} +303 -97
- package/dist/hosted-vercel-blob-B3-wRdUm.js +410 -0
- package/dist/hosted-vercel-blob.d.ts +6 -7
- package/dist/hosted-vercel-blob.js +1 -1
- package/dist/hosted.d.ts +10 -9
- package/dist/hosted.js +2 -2
- package/dist/index.d.ts +26 -47
- package/dist/index.js +30 -100
- package/dist/internal/path.d.ts +2 -0
- package/dist/internal/path.js +2 -0
- package/dist/lifecycle-B-enk_4A.js +596 -0
- package/dist/lineage.d.ts +26 -0
- package/dist/lineage.js +76 -0
- package/dist/loader.d.ts +5 -6
- package/dist/loader.js +3 -2
- package/dist/mcp-resources-DF0F5rcL.js +39 -0
- package/dist/memory-BOexthyW.js +247 -0
- package/dist/metadata-target-CWz6KHKq.js +1589 -0
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
- package/dist/operations-C6FpR8Rr.js +389 -0
- package/dist/operations-CE2drFih.js +1234 -0
- package/dist/operations.d.ts +90 -0
- package/dist/operations.js +3 -0
- package/dist/path--wrT_Azm.js +113 -0
- package/dist/path-AxMho1wo.d.ts +7 -0
- package/dist/path-DrSIenjj.js +59 -0
- package/dist/path-zHxQUbqa.d.ts +9 -0
- package/dist/plugins-C8C0auoW.d.ts +10 -0
- package/dist/provider-9s4Ufkm5.js +1479 -0
- package/dist/providers/github/store.d.ts +3 -5
- package/dist/providers/github/store.js +1 -1
- package/dist/registry-B3BBm4Ts.d.ts +19 -0
- package/dist/{registry-D3yzt8HQ.js → registry-CNphafBx.js} +60 -23
- package/dist/registry-CYNN623b.d.ts +9 -0
- package/dist/request-scope-Dw5n8bMC.js +83 -0
- package/dist/results-DgkZUmTL.js +8 -0
- package/dist/{chunk-2rV9d50f.js → rolldown-runtime-rQ84J-ij.js} +3 -4
- package/dist/runtime/assets.d.ts +3 -5
- package/dist/runtime/assets.js +7 -6
- package/dist/runtime/empty-assets-registry.d.ts +1 -2
- package/dist/runtime/empty-registry.d.ts +2 -2
- package/dist/runtime/registry.d.ts +2 -0
- package/dist/runtime/registry.js +23 -0
- package/dist/runtime/request.d.ts +4 -0
- package/dist/runtime/request.js +8 -0
- package/dist/runtime/state.d.ts +5 -4
- package/dist/runtime/state.js +8 -18
- package/dist/runtime/workspace.d.ts +1 -1
- package/dist/runtime/workspace.js +1 -1
- package/dist/runtime.d.ts +52 -17
- package/dist/runtime.js +324 -67
- package/dist/{search-BpiCF2Tw.js → search-C_RfoM2j.js} +10 -9
- package/dist/server-8tGltlGz.js +303 -0
- package/dist/server.d.ts +36 -39
- package/dist/server.js +2 -328
- package/dist/shared-B3_EUk89.js +848 -0
- package/dist/source-metadata.d.ts +10 -7
- package/dist/source-metadata.js +12 -12
- package/dist/state-BISnUf1s.d.ts +35 -0
- package/dist/{ai-BqCC8BpY.js → state-DbrW-njQ.js} +237 -114
- package/dist/store-ybhyD38Z.js +1873 -0
- package/dist/{sync-DnTQwt8r.js → sync-CCD_VYC8.js} +61 -41
- package/dist/target-jWhTdIuF.js +89 -0
- package/dist/test.d.ts +1 -1
- package/dist/test.js +1 -1
- package/dist/{types-CYuwjJ4V.d.ts → types-BbtwmBZ5.d.ts} +321 -35
- package/dist/use-C6lV3-wC.d.ts +321 -0
- package/dist/{use-BTNDR5Rd.js → use-CSpT5W87.js} +141 -107
- package/dist/utils-CgMZCHsX.js +616 -0
- package/dist/vite.d.ts +585 -2
- package/dist/vite.js +21369 -2
- package/dist/workspace-CYB2xZ1T.d.ts +7 -0
- package/dist/{workspace-Dq08Yn72.js → workspace-sPWn2Jxj.js} +441 -225
- package/package.json +97 -72
- package/dist/ai-CjxvGqM0.d.ts +0 -162
- package/dist/ai.d.ts +0 -3
- package/dist/ai.js +0 -2
- package/dist/collections/client.d.ts +0 -39
- package/dist/collections/client.js +0 -137
- package/dist/collections.d.ts +0 -59
- package/dist/collections.js +0 -159
- package/dist/config-Bc3c4Su1.js +0 -7904
- package/dist/config-CHLLWklZ.js +0 -36
- package/dist/file-Bc1X7pco.js +0 -23
- package/dist/glob-CEZKeZFC.js +0 -18
- package/dist/hosted-vercel-blob-d6C8ND5j.js +0 -23580
- package/dist/lifecycle-LrL3sA4n.js +0 -316
- package/dist/metadata-target-B0tOmVW7.js +0 -717
- package/dist/mountx.d.ts +0 -10
- package/dist/mountx.js +0 -143
- package/dist/nitro.d.ts +0 -2
- package/dist/nitro.js +0 -2
- package/dist/nuxt.d.ts +0 -26
- package/dist/nuxt.js +0 -42
- package/dist/path-Cp59koVz.js +0 -139
- package/dist/provider-B1yLjCJJ.js +0 -746
- package/dist/publish.d.ts +0 -35
- package/dist/publish.js +0 -112
- package/dist/registry-Uj6IVxes.d.ts +0 -11
- package/dist/request-execution-B-dSFlGB.js +0 -84
- package/dist/runtime-options-BsPSv5O7.js +0 -13
- package/dist/runtime-type-iEE6BjQJ.js +0 -34
- package/dist/shared-DTR1Hhma.js +0 -331
- package/dist/state-tYcRWEh2.d.ts +0 -26
- package/dist/store-Dt_Jyys3.js +0 -608
- package/dist/target-D4Bqb1eH.js +0 -11
- package/dist/token-CVzURBxC.js +0 -61
- package/dist/use-BiHzt0xA.d.ts +0 -103
- package/dist/vite-BptCrpv2.js +0 -4526
- package/dist/vite-CtA9guIM.d.ts +0 -66
- package/dist/workspace-Xddf4G1B.d.ts +0 -6
|
@@ -0,0 +1,1873 @@
|
|
|
1
|
+
import { a as workspaceConflict, n as assertWorkspaceDigest, r as isWorkspaceConflict, s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
|
|
2
|
+
import { r as workspaceStoreTarget } from "./target-jWhTdIuF.js";
|
|
3
|
+
import { a as isExcludedWorkspacePath, c as normalizeSafeWorkspacePattern, i as decodeFile, l as normalizeWorkspacePath, n as contentStreamToBytes, r as contentToBytes } from "./path--wrT_Azm.js";
|
|
4
|
+
import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CtKjGtGb.js";
|
|
5
|
+
import { d as normalizeHistoryRef, l as historyConflict, n as createSnapshotFromEntries, r as diffSnapshots, u as normalizeHistoryPath } from "./utils-CgMZCHsX.js";
|
|
6
|
+
import { t as createWorkspaceGlobMatcher } from "./glob-Cjxms1t7.js";
|
|
7
|
+
import { _ as resolveGitHubBranchOption, a as githubBranchMovedConflict, b as resolveGitHubRepositoryOption, c as joinGitPath, d as readCurrentHead, f as readGitHubArchive, g as requireGitHubOption, h as readGitHubFile, i as gitFileMode, l as loadForge, n as connectGitHubRepository, o as githubRequest, p as readGitHubBranchState, r as gitBlobSha, s as githubRequestStatus, t as commitGitHubChanges, u as preloadGitHubFiles, v as resolveGitHubCredential, w as BoundedMap, x as resolveGitHubRootOption, y as resolveGitHubRefsOption } from "./shared-B3_EUk89.js";
|
|
8
|
+
import { t as workspaceStoreDiscard } from "./discard-CNNtCozM.js";
|
|
9
|
+
import { ViteHubError } from "@vite-hub/runtime";
|
|
10
|
+
import { lookup } from "mrmime";
|
|
11
|
+
import { posix } from "node:path";
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
13
|
+
import * as v from "valibot";
|
|
14
|
+
//#region src/storage/materialization.ts
|
|
15
|
+
const workspaceRevisionMaterializer = Symbol.for("vitehub.workspace.revisionMaterializer");
|
|
16
|
+
function forwardWorkspaceRevisionMaterializer(source, target) {
|
|
17
|
+
const materializer = source[workspaceRevisionMaterializer];
|
|
18
|
+
if (materializer) target[workspaceRevisionMaterializer] = materializer;
|
|
19
|
+
}
|
|
20
|
+
function resolveWorkspaceRevisionMaterializer(workspace) {
|
|
21
|
+
return workspace[workspaceRevisionMaterializer];
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/providers/github/publish-reservation.ts
|
|
25
|
+
const githubPublishReservationMs = 3e5;
|
|
26
|
+
const zeroOid = "0".repeat(40);
|
|
27
|
+
const leaseSchema = v.object({
|
|
28
|
+
vitehubPublishReservation: v.literal(1),
|
|
29
|
+
owner: v.string(),
|
|
30
|
+
expiresAt: v.number(),
|
|
31
|
+
head: v.string(),
|
|
32
|
+
opening: v.optional(v.string())
|
|
33
|
+
});
|
|
34
|
+
const commitSchema = v.object({
|
|
35
|
+
message: v.string(),
|
|
36
|
+
tree: v.object({ sha: v.string() }),
|
|
37
|
+
committer: v.optional(v.object({ date: v.string() }))
|
|
38
|
+
});
|
|
39
|
+
/** Expiring preparation claims become durable before dispatching a mutation whose outcome might be ambiguous. */
|
|
40
|
+
async function acquireGitHubPublishReservation(repository, options) {
|
|
41
|
+
const busy = () => workspaceConflict(`[vitehub] A publish is already opening a pull request for ${options.path}. Retry after it finishes or its reservation expires.`, { details: {
|
|
42
|
+
ref: "pull-request",
|
|
43
|
+
path: options.path
|
|
44
|
+
} });
|
|
45
|
+
const expiresAt = Date.now() + githubPublishReservationMs;
|
|
46
|
+
const route = (repo) => `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
|
|
47
|
+
const readCommit = (sha) => githubRequest(repository, async (provider, repo) => v.parse(commitSchema, (await provider.request("GET", `${route(repo)}/git/commits/${encodeURIComponent(sha)}`)).data));
|
|
48
|
+
const base = await readCommit(options.head);
|
|
49
|
+
const owner = randomUUID();
|
|
50
|
+
const writeClaim = (opening) => githubRequest(repository, async (provider, repo) => v.parse(v.object({ sha: v.string() }), (await provider.request("POST", `${route(repo)}/git/commits`, { body: {
|
|
51
|
+
message: JSON.stringify({
|
|
52
|
+
vitehubPublishReservation: 1,
|
|
53
|
+
owner,
|
|
54
|
+
expiresAt,
|
|
55
|
+
head: options.head,
|
|
56
|
+
...opening ? { opening } : {}
|
|
57
|
+
}),
|
|
58
|
+
parents: [options.head],
|
|
59
|
+
tree: base.tree.sha
|
|
60
|
+
} })).data).sha);
|
|
61
|
+
let owned = await writeClaim();
|
|
62
|
+
async function graphql(query, operationName, variables) {
|
|
63
|
+
return githubRequest(repository, async (provider) => {
|
|
64
|
+
const response = v.parse(v.object({
|
|
65
|
+
data: v.optional(v.unknown()),
|
|
66
|
+
errors: v.optional(v.array(v.object({ message: v.string() })))
|
|
67
|
+
}), (await provider.request("POST", "/graphql", { body: {
|
|
68
|
+
query,
|
|
69
|
+
operationName,
|
|
70
|
+
variables
|
|
71
|
+
} })).data);
|
|
72
|
+
if (response.errors?.length) throw workspaceError(`[vitehub] GitHub publish reservation failed: ${response.errors.map((error) => error.message).join("; ")}`);
|
|
73
|
+
return response.data;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
async function replace(expected, next) {
|
|
77
|
+
const repo = await githubRequest(repository, async (_provider, repo) => repo);
|
|
78
|
+
const { repository: { id } } = v.parse(v.object({ repository: v.object({ id: v.string() }) }), await graphql("query RepositoryId($owner:String!,$name:String!){repository(owner:$owner,name:$name){id}}", "RepositoryId", {
|
|
79
|
+
owner: repo.owner,
|
|
80
|
+
name: repo.name
|
|
81
|
+
}));
|
|
82
|
+
try {
|
|
83
|
+
v.parse(v.object({ updateRefs: v.object({ clientMutationId: v.nullable(v.string()) }) }), await graphql("mutation UpdateRefs($input:UpdateRefsInput!){updateRefs(input:$input){clientMutationId}}", "UpdateRefs", { input: {
|
|
84
|
+
repositoryId: id,
|
|
85
|
+
refUpdates: [{
|
|
86
|
+
name: `refs/heads/${options.branch}`,
|
|
87
|
+
beforeOid: expected,
|
|
88
|
+
afterOid: next,
|
|
89
|
+
force: true
|
|
90
|
+
}]
|
|
91
|
+
} }));
|
|
92
|
+
return true;
|
|
93
|
+
} catch (error) {
|
|
94
|
+
const current = await readCurrentHead(repository, options.branch);
|
|
95
|
+
if (current === next) return true;
|
|
96
|
+
if (current !== expected) return false;
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
await githubRequest(repository, async (provider, repo) => await provider.request("POST", `${route(repo)}/git/refs`, { body: {
|
|
102
|
+
ref: `refs/heads/${options.branch}`,
|
|
103
|
+
sha: owned
|
|
104
|
+
} }));
|
|
105
|
+
} catch (error) {
|
|
106
|
+
if (githubRequestStatus(error) !== 422) throw error;
|
|
107
|
+
const current = await readCurrentHead(repository, options.branch);
|
|
108
|
+
if (!current) throw error;
|
|
109
|
+
const commit = await readCommit(current);
|
|
110
|
+
let expiry;
|
|
111
|
+
let opening;
|
|
112
|
+
try {
|
|
113
|
+
const lease = v.parse(leaseSchema, JSON.parse(commit.message));
|
|
114
|
+
expiry = lease.expiresAt;
|
|
115
|
+
opening = lease.opening;
|
|
116
|
+
} catch {
|
|
117
|
+
expiry = Date.parse(commit.committer?.date ?? "") + githubPublishReservationMs;
|
|
118
|
+
}
|
|
119
|
+
if (!Number.isFinite(expiry) || expiry > Date.now()) throw busy();
|
|
120
|
+
if (opening) {
|
|
121
|
+
if (!await githubRequest(repository, async (provider, repo) => {
|
|
122
|
+
const query = new URLSearchParams({
|
|
123
|
+
state: "all",
|
|
124
|
+
head: `${repo.owner}:${opening}`,
|
|
125
|
+
per_page: "1"
|
|
126
|
+
});
|
|
127
|
+
return v.parse(v.array(v.object({ head: v.object({ ref: v.string() }) })), (await provider.request("GET", `${route(repo)}/pulls?${query}`)).data).some((request) => request.head.ref === opening);
|
|
128
|
+
})) throw workspaceConflict(`[vitehub] GitHub has not confirmed the publish pull request from ${opening} for ${options.path}. Keep its branch and reservation; retry after GitHub reports the result.`, { details: {
|
|
129
|
+
ref: "pull-request",
|
|
130
|
+
path: options.path,
|
|
131
|
+
head: opening
|
|
132
|
+
} });
|
|
133
|
+
}
|
|
134
|
+
if (!await replace(current, owned)) throw busy();
|
|
135
|
+
}
|
|
136
|
+
async function assertOwned() {
|
|
137
|
+
if (await readCurrentHead(repository, options.branch) !== owned || Date.now() >= expiresAt) throw busy();
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
expiresAt,
|
|
141
|
+
assertOwned,
|
|
142
|
+
async begin(opening) {
|
|
143
|
+
await assertOwned();
|
|
144
|
+
const previous = owned;
|
|
145
|
+
owned = await writeClaim(opening);
|
|
146
|
+
if (!await replace(previous, owned)) throw busy();
|
|
147
|
+
},
|
|
148
|
+
async release() {
|
|
149
|
+
await replace(owned, zeroOid);
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
//#endregion
|
|
154
|
+
//#region src/providers/github/history.ts
|
|
155
|
+
/**
|
|
156
|
+
* How long `head()` keeps the head that it read for a branch, in milliseconds. A commit through this history replaces
|
|
157
|
+
* the head at once. A commit by another writer shows after this time at most.
|
|
158
|
+
*/
|
|
159
|
+
const githubHeadCacheMs = 5e3;
|
|
160
|
+
const metadataTrailer = "Vitehub-Metadata: ";
|
|
161
|
+
const metadataTrailerPattern = /(?:^|\n\n)Vitehub-Metadata: ([^\n]*)\s*$/;
|
|
162
|
+
const reservedTrailerPattern = /^Vitehub-Metadata:/m;
|
|
163
|
+
/** The most bytes of commit metadata as JSON, and of a commit message, that the Store writes. */
|
|
164
|
+
const githubMaxMetadataBytes = 65536;
|
|
165
|
+
const githubMaxMessageBytes = 16384;
|
|
166
|
+
function nonEmptyString(value) {
|
|
167
|
+
return typeof value === "string" && value.length > 0;
|
|
168
|
+
}
|
|
169
|
+
function malformed(description) {
|
|
170
|
+
throw workspaceError(`[vitehub] GitHub workspace returned a malformed ${description} response.`);
|
|
171
|
+
}
|
|
172
|
+
function isNoHistoryError(error) {
|
|
173
|
+
const status = githubRequestStatus(error);
|
|
174
|
+
return status === 404 || status === 409;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* GitHub answers a compare of two commits without a merge base with 404 "No common ancestor between <base> and <head>."
|
|
178
|
+
* Any other failure, such as a 422 "Validation failed, or the endpoint has been spammed", proves nothing.
|
|
179
|
+
*/
|
|
180
|
+
function isUnrelatedHistoryError(error) {
|
|
181
|
+
for (let current = error; current instanceof Error; current = current.cause) {
|
|
182
|
+
const body = Reflect.get(current, "body");
|
|
183
|
+
if (/no common ancestor/i.test(`${current.message}\n${typeof body === "string" ? body : ""}`)) return true;
|
|
184
|
+
}
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* GitHub answers a lookup of a commit that the repository does not have with 422 "No commit found for SHA: <sha>." Any
|
|
189
|
+
* other failure, such as a 422 "Validation failed, or the endpoint has been spammed", proves nothing.
|
|
190
|
+
*/
|
|
191
|
+
function isMissingCommitError(error) {
|
|
192
|
+
const status = githubRequestStatus(error);
|
|
193
|
+
if (status !== 404 && status !== 422) return false;
|
|
194
|
+
for (let current = error; current instanceof Error; current = current.cause) {
|
|
195
|
+
const body = Reflect.get(current, "body");
|
|
196
|
+
if (/no commit found for/i.test(`${current.message}\n${typeof body === "string" ? body : ""}`)) return true;
|
|
197
|
+
}
|
|
198
|
+
return false;
|
|
199
|
+
}
|
|
200
|
+
function cursorFor(ref, id) {
|
|
201
|
+
return `${ref}:after:${id}`;
|
|
202
|
+
}
|
|
203
|
+
function pageFromCursor(ref, cursor) {
|
|
204
|
+
if (!cursor) return 1;
|
|
205
|
+
const separator = cursor.lastIndexOf(":");
|
|
206
|
+
const cursorRef = separator < 0 ? "" : cursor.slice(0, separator);
|
|
207
|
+
const page = separator < 0 ? NaN : Number(cursor.slice(separator + 1));
|
|
208
|
+
if (cursorRef !== ref || !Number.isSafeInteger(page) || page < 1) throw workspaceErrorDiagnostics.WORKSPACE_R0070({ message: `[vitehub] History cursor does not belong to ref "${ref}".` });
|
|
209
|
+
return page;
|
|
210
|
+
}
|
|
211
|
+
/** The page number of the next GitHub page, from the Forge cursor. */
|
|
212
|
+
function nextPage(nextUrl) {
|
|
213
|
+
if (!nextUrl) return void 0;
|
|
214
|
+
const page = Number(new URL(nextUrl).searchParams.get("page"));
|
|
215
|
+
return Number.isSafeInteger(page) && page > 1 ? page : void 0;
|
|
216
|
+
}
|
|
217
|
+
function visibleWorkspacePath(path) {
|
|
218
|
+
const parts = path.split("/");
|
|
219
|
+
return !parts.some((part) => part.toLowerCase() === ".git") && parts[0]?.toLowerCase() !== ".vitehub";
|
|
220
|
+
}
|
|
221
|
+
function entryMetadata(entry) {
|
|
222
|
+
return entry.mode === "100644" ? void 0 : { gitMode: entry.mode };
|
|
223
|
+
}
|
|
224
|
+
function mediaType(path) {
|
|
225
|
+
return lookup(path) || "application/octet-stream";
|
|
226
|
+
}
|
|
227
|
+
/** The message of a commit without its metadata trailer, and the metadata that the trailer holds. */
|
|
228
|
+
function readCommitMessage(message) {
|
|
229
|
+
if (!message) return {};
|
|
230
|
+
const match = metadataTrailerPattern.exec(message);
|
|
231
|
+
if (!match) return { message };
|
|
232
|
+
if (new TextEncoder().encode(match[1]).byteLength > 65536) return { message };
|
|
233
|
+
let metadata;
|
|
234
|
+
try {
|
|
235
|
+
const value = JSON.parse(match[1]);
|
|
236
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value)) metadata = Object.fromEntries(Object.entries(value));
|
|
237
|
+
} catch {
|
|
238
|
+
return { message };
|
|
239
|
+
}
|
|
240
|
+
if (!metadata) return { message };
|
|
241
|
+
const text = message.slice(0, match.index).trimEnd();
|
|
242
|
+
return {
|
|
243
|
+
...text ? { message: text } : {},
|
|
244
|
+
metadata
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* The Git author of a history commit: `metadata.author` with a `name` and an `email`, as Content and the
|
|
249
|
+
* `workspace.commit` operation record the signed-in user. Without both, the account of the token is the author.
|
|
250
|
+
*/
|
|
251
|
+
function commitAuthor(metadata) {
|
|
252
|
+
const author = metadata?.author;
|
|
253
|
+
if (!author || typeof author !== "object") return void 0;
|
|
254
|
+
const name = Reflect.get(author, "name");
|
|
255
|
+
const email = Reflect.get(author, "email");
|
|
256
|
+
return typeof name === "string" && name.trim() && typeof email === "string" && email.trim() ? {
|
|
257
|
+
name,
|
|
258
|
+
email
|
|
259
|
+
} : void 0;
|
|
260
|
+
}
|
|
261
|
+
function messageWithMetadata(message, metadata) {
|
|
262
|
+
const limit = (what, size, max) => {
|
|
263
|
+
if (size > max) throw workspaceErrorDiagnostics.WORKSPACE_R0073({ message: `[vitehub] GitHub history commit ${what} is ${size} bytes, over the limit of ${max}. Shorten it.` });
|
|
264
|
+
};
|
|
265
|
+
if (reservedTrailerPattern.test(message)) throw workspaceErrorDiagnostics.WORKSPACE_R0073({ message: `[vitehub] GitHub history commit message cannot contain a line that starts with "${metadataTrailer.trim()}". The Store writes that line from the metadata option. Remove it.` });
|
|
266
|
+
limit("message", new TextEncoder().encode(message).byteLength, githubMaxMessageBytes);
|
|
267
|
+
if (!metadata || !Object.keys(metadata).length) return message;
|
|
268
|
+
const json = JSON.stringify(metadata);
|
|
269
|
+
limit("metadata", new TextEncoder().encode(json).byteLength, githubMaxMetadataBytes);
|
|
270
|
+
return `${message}\n\n${metadataTrailer}${json}`;
|
|
271
|
+
}
|
|
272
|
+
/** A revision from its commit. Without `entries`, the revision leaves out `files` and `bytes`. */
|
|
273
|
+
function publicRevision(commit, ref, entries, url, suppliedMetadata) {
|
|
274
|
+
const stored = readCommitMessage(commit.message);
|
|
275
|
+
suppliedMetadata ??= stored.metadata;
|
|
276
|
+
const author = commit.author;
|
|
277
|
+
const committer = commit.committer;
|
|
278
|
+
const authorName = author?.name || committer?.name;
|
|
279
|
+
const authorEmail = author?.email || committer?.email;
|
|
280
|
+
const authorLogin = author?.actor?.login || committer?.actor?.login;
|
|
281
|
+
const authorMetadata = authorName || authorEmail || authorLogin ? {
|
|
282
|
+
...authorName ? { author: authorName } : {},
|
|
283
|
+
...authorEmail ? { authorEmail } : {},
|
|
284
|
+
...authorLogin ? { authorLogin } : {}
|
|
285
|
+
} : {};
|
|
286
|
+
const metadata = Object.keys(authorMetadata).length || commit.url || url || suppliedMetadata ? {
|
|
287
|
+
...suppliedMetadata,
|
|
288
|
+
...authorMetadata,
|
|
289
|
+
...commit.url || url ? { url: commit.url || url } : {}
|
|
290
|
+
} : void 0;
|
|
291
|
+
const createdAt = author?.date || committer?.date;
|
|
292
|
+
if (!createdAt || Number.isNaN(createdAt.getTime())) malformed("commit");
|
|
293
|
+
return {
|
|
294
|
+
id: commit.sha,
|
|
295
|
+
ref,
|
|
296
|
+
parentId: commit.parents[0] || null,
|
|
297
|
+
createdAt: createdAt.toISOString(),
|
|
298
|
+
...stored.message ? { message: stored.message } : {},
|
|
299
|
+
...metadata ? { metadata } : {},
|
|
300
|
+
...entries ? {
|
|
301
|
+
files: entries.length,
|
|
302
|
+
bytes: entries.reduce((total, entry) => total + entry.size, 0)
|
|
303
|
+
} : {}
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
function viewPath(path) {
|
|
307
|
+
return normalizeSafeWorkspacePath(path, { allowEmpty: true }).split("/").filter(Boolean).join("/");
|
|
308
|
+
}
|
|
309
|
+
function asHistoryEntry(entry, root) {
|
|
310
|
+
if (entry.type !== "file" && entry.type !== "symlink") return void 0;
|
|
311
|
+
if (!entry.sha) malformed("tree");
|
|
312
|
+
const path = entry.path.startsWith(`${root}/`) ? entry.path.slice(root.length + 1) : root ? void 0 : entry.path;
|
|
313
|
+
if (path === void 0 || !path || !visibleWorkspacePath(path)) return void 0;
|
|
314
|
+
return {
|
|
315
|
+
mode: gitFileMode(entry.mode),
|
|
316
|
+
path,
|
|
317
|
+
sha: entry.sha,
|
|
318
|
+
size: entry.size || 0
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
function isHistoryFileInput(file) {
|
|
322
|
+
return typeof file.content === "string" || ArrayBuffer.isView(file.content);
|
|
323
|
+
}
|
|
324
|
+
function isSupportedHistoryRef(name) {
|
|
325
|
+
try {
|
|
326
|
+
normalizeHistoryRef(name);
|
|
327
|
+
return true;
|
|
328
|
+
} catch {
|
|
329
|
+
return false;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
/** A read-through view of GitHub branches and commits using the retained Workspace history contract. */
|
|
333
|
+
function createGitHubWorkspaceHistory(input) {
|
|
334
|
+
let resolved;
|
|
335
|
+
const settings = () => resolved ??= typeof input === "function" ? input() : input;
|
|
336
|
+
const options = {
|
|
337
|
+
get branch() {
|
|
338
|
+
return settings().branch;
|
|
339
|
+
},
|
|
340
|
+
get refs() {
|
|
341
|
+
return settings().refs;
|
|
342
|
+
},
|
|
343
|
+
get repository() {
|
|
344
|
+
return settings().repository;
|
|
345
|
+
},
|
|
346
|
+
get root() {
|
|
347
|
+
return settings().root;
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
const client = () => settings().client;
|
|
351
|
+
const toBranch = (ref) => {
|
|
352
|
+
const refs = options.refs;
|
|
353
|
+
return (ref === "published" ? refs?.published : ref === "draft" ? refs?.draft : void 0) ?? ref;
|
|
354
|
+
};
|
|
355
|
+
/**
|
|
356
|
+
* A given ref name, its branch, and the name that revisions on it report. The branch of an alias is reached only by
|
|
357
|
+
* the alias, so a caller cannot write the published branch under another name and skip the rules that guard `published`.
|
|
358
|
+
* A call without `ref` uses `main`, which is the alias when `refs` points `published` at it.
|
|
359
|
+
*/
|
|
360
|
+
const resolveRef = (given) => {
|
|
361
|
+
const name = normalizeHistoryRef(given);
|
|
362
|
+
const refs = options.refs;
|
|
363
|
+
if (given !== void 0 && name !== "published" && name !== "draft" && (name === refs?.published || name === refs?.draft)) {
|
|
364
|
+
const alias = name === refs?.published ? "published" : "draft";
|
|
365
|
+
throw workspaceErrorDiagnostics.WORKSPACE_R0071({ message: `[vitehub] History ref ${JSON.stringify(name)} is the branch of the ref ${JSON.stringify(alias)} in this Store. Use ${JSON.stringify(alias)}.` });
|
|
366
|
+
}
|
|
367
|
+
const branch = toBranch(name);
|
|
368
|
+
return {
|
|
369
|
+
branch,
|
|
370
|
+
ref: fromBranch(branch)
|
|
371
|
+
};
|
|
372
|
+
};
|
|
373
|
+
const fromBranch = (branch) => {
|
|
374
|
+
const refs = options.refs;
|
|
375
|
+
if (refs?.published === branch) return "published";
|
|
376
|
+
if (refs?.draft === branch) return "draft";
|
|
377
|
+
return branch;
|
|
378
|
+
};
|
|
379
|
+
const hiddenBranch = (branch) => toBranch(fromBranch(branch)) !== branch;
|
|
380
|
+
const heads = /* @__PURE__ */ new Map();
|
|
381
|
+
const commitCache = new BoundedMap(2e3);
|
|
382
|
+
const treeCache = new BoundedMap(32);
|
|
383
|
+
const commitRefs = new BoundedMap(2e3);
|
|
384
|
+
const readCommit = async (id) => {
|
|
385
|
+
const cached = commitCache.get(id);
|
|
386
|
+
if (cached) return cached;
|
|
387
|
+
const commit = await githubRequest(client(), async (provider, repo) => await provider.commits.get({
|
|
388
|
+
forge: provider.forge,
|
|
389
|
+
instance: provider.instance,
|
|
390
|
+
repo,
|
|
391
|
+
sha: encodeURIComponent(id)
|
|
392
|
+
}), "commit");
|
|
393
|
+
if (!nonEmptyString(commit.sha)) malformed("commit");
|
|
394
|
+
commitCache.set(commit.sha, commit);
|
|
395
|
+
return commit;
|
|
396
|
+
};
|
|
397
|
+
const readTreeItems = async (ref, recursive) => await githubRequest(client(), async (provider, repo) => {
|
|
398
|
+
const tree = provider.contents.tree(repo, {
|
|
399
|
+
recursive,
|
|
400
|
+
ref
|
|
401
|
+
});
|
|
402
|
+
const items = [];
|
|
403
|
+
for await (const item of tree) items.push(item);
|
|
404
|
+
return {
|
|
405
|
+
items,
|
|
406
|
+
truncated: tree.warnings.some((warning) => warning.code === "tree_truncated")
|
|
407
|
+
};
|
|
408
|
+
}, "tree");
|
|
409
|
+
const readTree = async (commit) => {
|
|
410
|
+
const cached = treeCache.get(commit.sha);
|
|
411
|
+
if (cached) return cached;
|
|
412
|
+
const tree = await readTreeItems(commit.sha, true);
|
|
413
|
+
const entries = (tree.truncated ? await readTreeWithoutRecursion(commit.sha) : tree.items).flatMap((entry) => {
|
|
414
|
+
const historyEntry = asHistoryEntry(entry, options.root);
|
|
415
|
+
return historyEntry ? [historyEntry] : [];
|
|
416
|
+
}).sort((left, right) => left.path.localeCompare(right.path));
|
|
417
|
+
treeCache.set(commit.sha, entries);
|
|
418
|
+
return entries;
|
|
419
|
+
};
|
|
420
|
+
const readTreeWithoutRecursion = async (ref) => {
|
|
421
|
+
const root = options.root.replace(/^\/+|\/+$/g, "");
|
|
422
|
+
const entries = [];
|
|
423
|
+
const walk = async (sha, prefix) => {
|
|
424
|
+
const tree = await readTreeItems(sha, false);
|
|
425
|
+
if (tree.truncated) throw workspaceError("[vitehub] GitHub workspace tree was truncated while traversing a directory.");
|
|
426
|
+
for (const entry of tree.items) {
|
|
427
|
+
const path = prefix ? `${prefix}/${entry.path}` : entry.path;
|
|
428
|
+
if (!(!root || path === root || path.startsWith(`${root}/`) || root.startsWith(`${path}/`))) continue;
|
|
429
|
+
if (entry.type === "directory") {
|
|
430
|
+
if (!entry.sha) malformed("tree");
|
|
431
|
+
await walk(entry.sha, path);
|
|
432
|
+
} else entries.push({
|
|
433
|
+
...entry,
|
|
434
|
+
path
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
await walk(ref, "");
|
|
439
|
+
return entries;
|
|
440
|
+
};
|
|
441
|
+
const revision = async (ref, id, suppliedMetadata) => {
|
|
442
|
+
const commit = await readCommit(id);
|
|
443
|
+
const entries = await readTree(commit);
|
|
444
|
+
commitRefs.set(commit.sha, ref);
|
|
445
|
+
return publicRevision(commit, ref, entries, `https://github.com/${options.repository}/commit/${commit.sha}`, suppliedMetadata);
|
|
446
|
+
};
|
|
447
|
+
/** A revision from a commit that a list or a head read returned, without the tree request that `files` and `bytes` need. */
|
|
448
|
+
const listedRevision = (ref, commit) => {
|
|
449
|
+
if (!nonEmptyString(commit.sha)) malformed("commit list");
|
|
450
|
+
commitCache.set(commit.sha, commit);
|
|
451
|
+
commitRefs.set(commit.sha, ref);
|
|
452
|
+
return publicRevision(commit, ref, void 0, `https://github.com/${options.repository}/commit/${commit.sha}`);
|
|
453
|
+
};
|
|
454
|
+
const readBranches = async () => {
|
|
455
|
+
try {
|
|
456
|
+
return await githubRequest(client(), async (provider, repo) => {
|
|
457
|
+
const branches = [];
|
|
458
|
+
for await (const branch of provider.contents.branches(repo, { perPage: 100 })) {
|
|
459
|
+
if (!nonEmptyString(branch.name) || !nonEmptyString(branch.sha)) malformed("branch list");
|
|
460
|
+
if (isSupportedHistoryRef(branch.name) && !hiddenBranch(branch.name)) branches.push({
|
|
461
|
+
commit: branch.sha,
|
|
462
|
+
name: branch.name
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
return branches;
|
|
466
|
+
}, "branch list");
|
|
467
|
+
} catch (error) {
|
|
468
|
+
if (isNoHistoryError(error)) return [];
|
|
469
|
+
throw error;
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
const readBranchHead = async (branch) => {
|
|
473
|
+
const cached = heads.get(branch);
|
|
474
|
+
if (cached && cached.expires > Date.now()) return await cached.head;
|
|
475
|
+
const head = (async () => {
|
|
476
|
+
try {
|
|
477
|
+
const commit = await githubRequest(client(), async (provider, repo) => await provider.commits.get({
|
|
478
|
+
forge: provider.forge,
|
|
479
|
+
instance: provider.instance,
|
|
480
|
+
repo,
|
|
481
|
+
sha: encodeURIComponent(`heads/${branch}`)
|
|
482
|
+
}), "commit");
|
|
483
|
+
if (!nonEmptyString(commit.sha)) malformed("commit");
|
|
484
|
+
commitCache.set(commit.sha, commit);
|
|
485
|
+
return commit.sha;
|
|
486
|
+
} catch (error) {
|
|
487
|
+
if (isNoHistoryError(error) || githubRequestStatus(error) === 422) return null;
|
|
488
|
+
throw error;
|
|
489
|
+
}
|
|
490
|
+
})();
|
|
491
|
+
heads.set(branch, {
|
|
492
|
+
expires: Date.now() + githubHeadCacheMs,
|
|
493
|
+
head
|
|
494
|
+
});
|
|
495
|
+
head.catch(() => {
|
|
496
|
+
if (heads.get(branch)?.head === head) heads.delete(branch);
|
|
497
|
+
});
|
|
498
|
+
return await head;
|
|
499
|
+
};
|
|
500
|
+
/** Whether the history of `branch` has the commit `id`: the commit is the merge base of both. */
|
|
501
|
+
async function branchContains(branch, id) {
|
|
502
|
+
if (!/^[0-9a-f]{40}$/i.test(id)) return false;
|
|
503
|
+
const head = await readBranchHead(branch);
|
|
504
|
+
if (!head) return false;
|
|
505
|
+
if (head.toLowerCase() === id.toLowerCase()) return true;
|
|
506
|
+
return await githubRequest(client(), async (provider, repo) => {
|
|
507
|
+
try {
|
|
508
|
+
const compare = (await provider.request("GET", `${repoPath(repo)}/compare/${encodeURIComponent(head)}...${encodeURIComponent(id)}`, { query: { per_page: 1 } })).data;
|
|
509
|
+
return String(Reflect.get(Object(Reflect.get(Object(compare), "merge_base_commit")), "sha")).toLowerCase() === id.toLowerCase();
|
|
510
|
+
} catch (error) {
|
|
511
|
+
if (isUnrelatedHistoryError(error) || githubRequestStatus(error) === 404) return false;
|
|
512
|
+
throw error;
|
|
513
|
+
}
|
|
514
|
+
}, "compare");
|
|
515
|
+
}
|
|
516
|
+
const list = async (listOptions = {}) => {
|
|
517
|
+
const { branch, ref } = resolveRef(listOptions.ref);
|
|
518
|
+
const limit = listOptions.limit ?? 20;
|
|
519
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw workspaceErrorDiagnostics.WORKSPACE_R0070({ message: "[vitehub] History list limit must be an integer from 1 to 100." });
|
|
520
|
+
const separator = listOptions.cursor?.lastIndexOf(":after:") ?? -1;
|
|
521
|
+
const revisionCursor = separator < 0 ? void 0 : listOptions.cursor.slice(separator + 7);
|
|
522
|
+
if (revisionCursor !== void 0 && (listOptions.cursor.slice(0, separator) !== ref || !revisionCursor)) throw workspaceErrorDiagnostics.WORKSPACE_R0070({ message: `[vitehub] History cursor does not belong to ref "${ref}".` });
|
|
523
|
+
const afterId = revisionCursor ?? (listOptions.cursor && /^[0-9a-f]{40}$/i.test(listOptions.cursor) ? listOptions.cursor : void 0);
|
|
524
|
+
if (afterId !== void 0 && !await branchContains(branch, afterId)) throw workspaceErrorDiagnostics.WORKSPACE_R0070({ message: `[vitehub] History cursor does not belong to ref "${ref}".` });
|
|
525
|
+
const page = afterId ? 1 : pageFromCursor(ref, listOptions.cursor);
|
|
526
|
+
const start = afterId ?? (page === 1 ? await readBranchHead(branch) : branch);
|
|
527
|
+
if (!start) return { revisions: [] };
|
|
528
|
+
const gitPath = !listOptions.path ? "" : joinGitPath(options.root, normalizeHistoryPath(listOptions.path));
|
|
529
|
+
let result;
|
|
530
|
+
try {
|
|
531
|
+
result = await githubRequest(client(), async (provider, repo) => {
|
|
532
|
+
const cursor = page === 1 ? void 0 : { nextUrl: `${provider.baseUrl.replace(/\/+$/, "")}/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}/commits?sha=${encodeURIComponent(branch)}&per_page=${limit}&page=${page}${gitPath ? `&path=${encodeURIComponent(gitPath)}` : ""}` };
|
|
533
|
+
return await provider.commits.list(repo, {
|
|
534
|
+
cursor,
|
|
535
|
+
perPage: afterId ? Math.min(limit + 1, 100) : limit,
|
|
536
|
+
ref: start,
|
|
537
|
+
...gitPath ? { path: gitPath } : {}
|
|
538
|
+
}).page();
|
|
539
|
+
}, "commit list");
|
|
540
|
+
} catch (error) {
|
|
541
|
+
if (isNoHistoryError(error)) return { revisions: [] };
|
|
542
|
+
throw error;
|
|
543
|
+
}
|
|
544
|
+
const items = afterId && result.items[0]?.sha === afterId ? result.items.slice(1) : result.items;
|
|
545
|
+
const shown = items.slice(0, limit);
|
|
546
|
+
const revisions = shown.map((commit) => listedRevision(ref, commit));
|
|
547
|
+
const followingPage = nextPage(result.cursor?.nextUrl);
|
|
548
|
+
if (afterId) {
|
|
549
|
+
const last = shown.at(-1)?.sha;
|
|
550
|
+
return {
|
|
551
|
+
revisions,
|
|
552
|
+
...last && (items.length > limit || followingPage !== void 0) ? { cursor: cursorFor(ref, last) } : {}
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
const last = shown.at(-1)?.sha;
|
|
556
|
+
return {
|
|
557
|
+
revisions,
|
|
558
|
+
...last && followingPage !== void 0 ? { cursor: cursorFor(ref, last) } : {}
|
|
559
|
+
};
|
|
560
|
+
};
|
|
561
|
+
const refs = async () => {
|
|
562
|
+
const branches = await readBranches();
|
|
563
|
+
return (await Promise.all(branches.map(async (branch) => ({
|
|
564
|
+
name: fromBranch(branch.name),
|
|
565
|
+
head: await revision(fromBranch(branch.name), branch.commit)
|
|
566
|
+
})))).sort((left, right) => left.name.localeCompare(right.name));
|
|
567
|
+
};
|
|
568
|
+
const refForCommit = async (id) => {
|
|
569
|
+
const cached = commitRefs.get(id);
|
|
570
|
+
if (cached) return cached;
|
|
571
|
+
const branches = await readBranches();
|
|
572
|
+
const heads = branches.filter((branch) => branch.commit === id);
|
|
573
|
+
let branch = heads.find((branch) => branch.name === options.branch) ?? heads[0];
|
|
574
|
+
if (!branch) {
|
|
575
|
+
const ordered = [...branches].sort((left, right) => Number(right.name === options.branch) - Number(left.name === options.branch));
|
|
576
|
+
for (const candidate of ordered) if (await githubRequest(client(), async (provider, repo) => {
|
|
577
|
+
try {
|
|
578
|
+
const compare = (await provider.request("GET", `${repoPath(repo)}/compare/${encodeURIComponent(candidate.commit)}...${encodeURIComponent(id)}`, { query: { per_page: 1 } })).data;
|
|
579
|
+
return Reflect.get(Object(Reflect.get(Object(compare), "merge_base_commit")), "sha") === id;
|
|
580
|
+
} catch (error) {
|
|
581
|
+
if (isUnrelatedHistoryError(error)) return false;
|
|
582
|
+
throw error;
|
|
583
|
+
}
|
|
584
|
+
}, "compare")) {
|
|
585
|
+
branch = candidate;
|
|
586
|
+
break;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
const ref = fromBranch(branch?.name ?? options.branch);
|
|
590
|
+
commitRefs.set(id, ref);
|
|
591
|
+
return ref;
|
|
592
|
+
};
|
|
593
|
+
const open = async (id) => {
|
|
594
|
+
if (!nonEmptyString(id)) throw workspaceError("[vitehub] Workspace revision id must be a non-empty string.");
|
|
595
|
+
let commit;
|
|
596
|
+
try {
|
|
597
|
+
commit = await readCommit(id);
|
|
598
|
+
} catch (error) {
|
|
599
|
+
if (isMissingCommitError(error)) throw new ViteHubError("WORKSPACE_NOT_FOUND", `[vitehub] Workspace revision does not exist: ${id}.`, { cause: error });
|
|
600
|
+
throw error;
|
|
601
|
+
}
|
|
602
|
+
const ref = await refForCommit(commit.sha);
|
|
603
|
+
const entries = await readTree(commit);
|
|
604
|
+
const byPath = new Map(entries.map((entry) => [entry.path, entry]));
|
|
605
|
+
const directories = /* @__PURE__ */ new Map();
|
|
606
|
+
directories.set("", {
|
|
607
|
+
path: "",
|
|
608
|
+
type: "directory"
|
|
609
|
+
});
|
|
610
|
+
for (const entry of entries) {
|
|
611
|
+
const parts = entry.path.split("/");
|
|
612
|
+
for (let index = 1; index < parts.length; index++) {
|
|
613
|
+
const path = parts.slice(0, index).join("/");
|
|
614
|
+
directories.set(path, {
|
|
615
|
+
path,
|
|
616
|
+
type: "directory"
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
const revisionValue = publicRevision(commit, ref, entries, `https://github.com/${options.repository}/commit/${commit.sha}`);
|
|
621
|
+
return Object.freeze({
|
|
622
|
+
revision: revisionValue,
|
|
623
|
+
list: async (path = "", listOptions) => {
|
|
624
|
+
const prefix = viewPath(path);
|
|
625
|
+
return [...directories.values(), ...entries.map((entry) => ({
|
|
626
|
+
path: entry.path,
|
|
627
|
+
type: "file",
|
|
628
|
+
size: entry.size,
|
|
629
|
+
mediaType: mediaType(entry.path),
|
|
630
|
+
digest: entry.sha,
|
|
631
|
+
...entryMetadata(entry) ? { metadata: entryMetadata(entry) } : {}
|
|
632
|
+
}))].filter((entry) => entry.path && entry.path !== prefix && (!prefix || entry.path.startsWith(`${prefix}/`)) && !isExcludedWorkspacePath(entry.path, listOptions?.exclude) && (listOptions?.recursive || !entry.path.slice(prefix ? prefix.length + 1 : 0).includes("/"))).sort((left, right) => left.path.localeCompare(right.path));
|
|
633
|
+
},
|
|
634
|
+
stat: async (path) => {
|
|
635
|
+
const normalized = viewPath(path);
|
|
636
|
+
const directory = directories.get(normalized);
|
|
637
|
+
if (directory) return { ...directory };
|
|
638
|
+
const entry = byPath.get(normalized);
|
|
639
|
+
if (!entry) throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
|
|
640
|
+
return {
|
|
641
|
+
path: normalized,
|
|
642
|
+
type: "file",
|
|
643
|
+
revision: commit.sha,
|
|
644
|
+
size: entry.size,
|
|
645
|
+
mediaType: mediaType(normalized),
|
|
646
|
+
digest: entry.sha,
|
|
647
|
+
...entryMetadata(entry) ? { metadata: entryMetadata(entry) } : {}
|
|
648
|
+
};
|
|
649
|
+
},
|
|
650
|
+
readFile: async (path, readOptions) => {
|
|
651
|
+
const normalized = normalizeHistoryPath(path);
|
|
652
|
+
const entry = byPath.get(normalized);
|
|
653
|
+
if (!entry) throw workspaceError(`[vitehub] Workspace file does not exist: ${path}.`);
|
|
654
|
+
const bytes = await readGitHubFile(client(), {
|
|
655
|
+
...entry,
|
|
656
|
+
path: joinGitPath(options.root, normalized)
|
|
657
|
+
}, commit.sha);
|
|
658
|
+
return decodeFile(bytes, readOptions);
|
|
659
|
+
},
|
|
660
|
+
preload: async (paths) => {
|
|
661
|
+
const entries = paths.flatMap((path) => {
|
|
662
|
+
const entry = byPath.get(normalizeHistoryPath(path));
|
|
663
|
+
return entry ? [{
|
|
664
|
+
...entry,
|
|
665
|
+
path: joinGitPath(options.root, entry.path)
|
|
666
|
+
}] : [];
|
|
667
|
+
});
|
|
668
|
+
await preloadGitHubFiles(client(), commit.sha, entries);
|
|
669
|
+
}
|
|
670
|
+
});
|
|
671
|
+
};
|
|
672
|
+
const usage = async () => {
|
|
673
|
+
const branches = await readBranches();
|
|
674
|
+
const seen = /* @__PURE__ */ new Set();
|
|
675
|
+
let bytes = 0;
|
|
676
|
+
for (const branch of branches) {
|
|
677
|
+
let cursor;
|
|
678
|
+
do {
|
|
679
|
+
const page = await list({
|
|
680
|
+
ref: fromBranch(branch.name),
|
|
681
|
+
cursor,
|
|
682
|
+
limit: 100
|
|
683
|
+
});
|
|
684
|
+
for (const revisionValue of page.revisions) {
|
|
685
|
+
const entries = await readTree(await readCommit(revisionValue.id));
|
|
686
|
+
for (const entry of entries) {
|
|
687
|
+
if (seen.has(entry.sha)) continue;
|
|
688
|
+
seen.add(entry.sha);
|
|
689
|
+
bytes += entry.size;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
cursor = page.cursor;
|
|
693
|
+
} while (cursor);
|
|
694
|
+
}
|
|
695
|
+
return {
|
|
696
|
+
bytes,
|
|
697
|
+
objects: seen.size
|
|
698
|
+
};
|
|
699
|
+
};
|
|
700
|
+
const commit = async (commitOptions) => {
|
|
701
|
+
const { branch, ref } = resolveRef(commitOptions.ref);
|
|
702
|
+
if (commitOptions.ifHead !== null && !nonEmptyString(commitOptions.ifHead)) throw workspaceError("[vitehub] History commit requires ifHead to be a revision id or null.");
|
|
703
|
+
const publishedBranch = options.refs?.published;
|
|
704
|
+
const state = await readGitHubBranchState({
|
|
705
|
+
branch,
|
|
706
|
+
fork: publishedBranch && publishedBranch !== branch ? publishedBranch : void 0,
|
|
707
|
+
from: commitOptions.startFrom,
|
|
708
|
+
repository: client(),
|
|
709
|
+
root: options.root
|
|
710
|
+
});
|
|
711
|
+
const actual = state.branchExists ? state.refSha : null;
|
|
712
|
+
if (actual !== commitOptions.ifHead) {
|
|
713
|
+
heads.delete(branch);
|
|
714
|
+
throw historyConflict(ref, commitOptions.ifHead, actual);
|
|
715
|
+
}
|
|
716
|
+
for (const [expectedRef, expectedHead] of Object.entries(commitOptions.ifHeads ?? {})) {
|
|
717
|
+
const expected = resolveRef(expectedRef);
|
|
718
|
+
const currentHead = await readCurrentHead(client(), expected.branch);
|
|
719
|
+
if (currentHead !== expectedHead) {
|
|
720
|
+
heads.delete(expected.branch);
|
|
721
|
+
throw historyConflict(expected.ref, expectedHead, currentHead);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
const updates = [];
|
|
725
|
+
const deletes = [];
|
|
726
|
+
const desired = /* @__PURE__ */ new Map();
|
|
727
|
+
if (commitOptions.files !== void 0) {
|
|
728
|
+
for (const [path, file] of Object.entries(commitOptions.files)) desired.set(normalizeHistoryPath(path), file);
|
|
729
|
+
for (const [path] of state.files) if (visibleWorkspacePath(path) && !desired.has(path)) deletes.push(joinGitPath(options.root, path));
|
|
730
|
+
} else {
|
|
731
|
+
for (const [path, file] of Object.entries(commitOptions.changes?.put || {})) desired.set(normalizeHistoryPath(path), file);
|
|
732
|
+
for (const path of commitOptions.changes?.delete || []) {
|
|
733
|
+
const normalized = normalizeHistoryPath(path);
|
|
734
|
+
if (!state.files.has(normalized)) throw workspaceError(`[vitehub] Workspace file does not exist: ${path}.`);
|
|
735
|
+
deletes.push(joinGitPath(options.root, normalized));
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
for (const [path, file] of desired) {
|
|
739
|
+
if (!isHistoryFileInput(file)) throw workspaceError(`[vitehub] Invalid history file content: ${path}.`);
|
|
740
|
+
const bytes = new Uint8Array(contentToBytes(file.content));
|
|
741
|
+
const current = state.files.get(path);
|
|
742
|
+
const mode = file.metadata?.gitMode === "120000" || file.metadata?.gitMode === "100755" || file.metadata?.gitMode === "100644" ? file.metadata.gitMode : current?.mode ?? "100644";
|
|
743
|
+
if (current?.sha === await gitBlobSha(bytes) && current.mode === mode) continue;
|
|
744
|
+
updates.push({
|
|
745
|
+
bytes,
|
|
746
|
+
fullPath: joinGitPath(options.root, path),
|
|
747
|
+
mode
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
if (!updates.length && !deletes.length) {
|
|
751
|
+
if (!state.branchExists) throw workspaceError(`[vitehub] GitHub history commit cannot create ref "${ref}" without a file change.`);
|
|
752
|
+
if (commitOptions.metadata === void 0) return await revision(ref, state.refSha);
|
|
753
|
+
}
|
|
754
|
+
const commitSha = await commitGitHubChanges({
|
|
755
|
+
branch,
|
|
756
|
+
branchExists: state.branchExists,
|
|
757
|
+
deletePaths: deletes,
|
|
758
|
+
files: updates,
|
|
759
|
+
message: messageWithMetadata(commitOptions.message || "Update Workspace", commitOptions.metadata),
|
|
760
|
+
author: commitAuthor(commitOptions.metadata),
|
|
761
|
+
parentSha: state.refSha,
|
|
762
|
+
remoteModes: new Map([...state.files.values()].map((entry) => [entry.path, entry.mode])),
|
|
763
|
+
repository: client()
|
|
764
|
+
}).catch((error) => {
|
|
765
|
+
if (isWorkspaceConflict(error)) heads.delete(branch);
|
|
766
|
+
throw error;
|
|
767
|
+
});
|
|
768
|
+
heads.set(branch, {
|
|
769
|
+
expires: Date.now() + githubHeadCacheMs,
|
|
770
|
+
head: Promise.resolve(commitSha)
|
|
771
|
+
});
|
|
772
|
+
return await revision(ref, commitSha, commitOptions.metadata);
|
|
773
|
+
};
|
|
774
|
+
let pullRequestCache;
|
|
775
|
+
const repoPath = (repo) => `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
|
|
776
|
+
const refPath = (branch) => branch.split("/").map(encodeURIComponent).join("/");
|
|
777
|
+
/** Matching refs are returned as one complete array; this endpoint does not support page parameters. */
|
|
778
|
+
const matchingBranches = async (prefix) => await githubRequest(client(), async (provider, repo) => {
|
|
779
|
+
const response = await provider.request("GET", `${repoPath(repo)}/git/matching-refs/heads/${refPath(prefix)}`);
|
|
780
|
+
const names = /* @__PURE__ */ new Set();
|
|
781
|
+
for (const item of Array.isArray(response.data) ? response.data : []) {
|
|
782
|
+
const name = item !== null && typeof item === "object" ? Reflect.get(item, "ref") : void 0;
|
|
783
|
+
if (nonEmptyString(name) && name.startsWith("refs/heads/")) names.add(name.slice(11));
|
|
784
|
+
}
|
|
785
|
+
return [...names];
|
|
786
|
+
}, "branch list");
|
|
787
|
+
/** The open pull request whose head is `branch`, found by the head filter of the pulls endpoint. */
|
|
788
|
+
const openPullRequestOf = async (branch) => await githubRequest(client(), async (provider, repo) => {
|
|
789
|
+
const response = await provider.request("GET", `${repoPath(repo)}/pulls`, { query: {
|
|
790
|
+
state: "open",
|
|
791
|
+
head: `${repo.owner}:${branch}`,
|
|
792
|
+
per_page: 5
|
|
793
|
+
} });
|
|
794
|
+
for (const item of Array.isArray(response.data) ? response.data : []) {
|
|
795
|
+
if (item === null || typeof item !== "object") continue;
|
|
796
|
+
const number = Reflect.get(item, "number");
|
|
797
|
+
const url = Reflect.get(item, "html_url");
|
|
798
|
+
const title = Reflect.get(item, "title");
|
|
799
|
+
const base = Reflect.get(Object(Reflect.get(item, "base")), "ref");
|
|
800
|
+
const headRef = Reflect.get(Object(Reflect.get(item, "head")), "ref");
|
|
801
|
+
if (!Number.isSafeInteger(number) || !nonEmptyString(url) || !nonEmptyString(base) || headRef !== branch) continue;
|
|
802
|
+
if (hiddenBranch(base)) continue;
|
|
803
|
+
const baseSha = Reflect.get(Object(Reflect.get(item, "base")), "sha");
|
|
804
|
+
const headSha = Reflect.get(Object(Reflect.get(item, "head")), "sha");
|
|
805
|
+
if (!nonEmptyString(baseSha) || !nonEmptyString(headSha)) malformed("pull request");
|
|
806
|
+
const compare = (await provider.request("GET", `${repoPath(repo)}/compare/${encodeURIComponent(baseSha)}...${encodeURIComponent(headSha)}`)).data;
|
|
807
|
+
const mergeBase = Reflect.get(Object(Reflect.get(Object(compare), "merge_base_commit")), "sha");
|
|
808
|
+
if (!nonEmptyString(mergeBase)) malformed("compare");
|
|
809
|
+
return {
|
|
810
|
+
number: Number(number),
|
|
811
|
+
url,
|
|
812
|
+
title: String(title ?? ""),
|
|
813
|
+
head: fromBranch(branch),
|
|
814
|
+
base: fromBranch(base),
|
|
815
|
+
mergeBase
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
}, "pull request list");
|
|
819
|
+
const findPullRequests = async (prefix) => {
|
|
820
|
+
return (await Promise.all((await matchingBranches(prefix)).map(async (branch) => await openPullRequestOf(branch)))).filter((entry) => entry !== void 0).sort((left, right) => right.number - left.number);
|
|
821
|
+
};
|
|
822
|
+
const pullRequests = async (listOptions) => {
|
|
823
|
+
const prefix = listOptions?.headPrefix ?? "";
|
|
824
|
+
if (!prefix) throw workspaceError("[vitehub] pullRequests() requires a headPrefix on the GitHub Store.");
|
|
825
|
+
if (!pullRequestCache || pullRequestCache.expires <= Date.now() || pullRequestCache.prefix !== prefix) {
|
|
826
|
+
const value = findPullRequests(prefix);
|
|
827
|
+
pullRequestCache = {
|
|
828
|
+
expires: Date.now() + githubHeadCacheMs,
|
|
829
|
+
prefix,
|
|
830
|
+
value
|
|
831
|
+
};
|
|
832
|
+
value.catch(() => {
|
|
833
|
+
if (pullRequestCache?.value === value) pullRequestCache = void 0;
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
return await pullRequestCache.value;
|
|
837
|
+
};
|
|
838
|
+
const deleteBranch = async (branch) => {
|
|
839
|
+
heads.delete(branch);
|
|
840
|
+
await githubRequest(client(), async (provider, repo) => await provider.request("DELETE", `${repoPath(repo)}/git/refs/heads/${refPath(branch)}`));
|
|
841
|
+
};
|
|
842
|
+
const openPullRequest = async (pullRequest) => {
|
|
843
|
+
const head = resolveRef(pullRequest.head);
|
|
844
|
+
const base = resolveRef(pullRequest.base);
|
|
845
|
+
const locks = [];
|
|
846
|
+
let created;
|
|
847
|
+
let number;
|
|
848
|
+
let dispatched = false;
|
|
849
|
+
let uncertain = false;
|
|
850
|
+
try {
|
|
851
|
+
if (pullRequest.reservation) {
|
|
852
|
+
if (!pullRequest.reservation.headPrefix) throw workspaceError("[vitehub] A pull request reservation requires a headPrefix.");
|
|
853
|
+
const paths = [...new Set(pullRequest.reservation.paths.map(normalizeHistoryPath))].sort();
|
|
854
|
+
const sha = await readCurrentHead(client(), head.branch);
|
|
855
|
+
if (!sha) throw workspaceError(`[vitehub] Pull request branch does not exist: ${head.ref}.`);
|
|
856
|
+
for (const path of paths) {
|
|
857
|
+
const lock = `vitehub/reservations/${await gitBlobSha(new TextEncoder().encode(JSON.stringify([base.branch, joinGitPath(options.root, path)])))}`;
|
|
858
|
+
locks.push(await acquireGitHubPublishReservation(client(), {
|
|
859
|
+
branch: lock,
|
|
860
|
+
head: sha,
|
|
861
|
+
path
|
|
862
|
+
}));
|
|
863
|
+
}
|
|
864
|
+
pullRequestCache = void 0;
|
|
865
|
+
const requests = await findPullRequests(pullRequest.reservation.headPrefix);
|
|
866
|
+
const published = await readCurrentHead(client(), base.branch);
|
|
867
|
+
const main = published ? await readFullTree(published) : /* @__PURE__ */ new Map();
|
|
868
|
+
for (const request of requests) {
|
|
869
|
+
if (request.base !== base.ref || request.head === head.ref || !request.mergeBase) continue;
|
|
870
|
+
const current = await readCurrentHead(client(), resolveRef(request.head).branch);
|
|
871
|
+
if (!current) continue;
|
|
872
|
+
const [branch, parent] = await Promise.all([readFullTree(current), readFullTree(request.mergeBase)]);
|
|
873
|
+
for (const path of paths) {
|
|
874
|
+
const fullPath = joinGitPath(options.root, path);
|
|
875
|
+
const digest = branch.get(fullPath)?.sha;
|
|
876
|
+
if (digest === parent.get(fullPath)?.sha || digest === main.get(fullPath)?.sha) continue;
|
|
877
|
+
throw workspaceConflict(`[vitehub] An open pull request already publishes ${path}: #${request.number} (${request.url}). Merge or close it, then publish again.`, { details: {
|
|
878
|
+
ref: "pull-request",
|
|
879
|
+
path
|
|
880
|
+
} });
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
await Promise.all(locks.map((lock) => lock.assertOwned()));
|
|
885
|
+
for (const lock of locks) await lock.begin(head.branch);
|
|
886
|
+
const deadline = locks.length ? Math.min(...locks.map((lock) => lock.expiresAt)) : void 0;
|
|
887
|
+
dispatched = true;
|
|
888
|
+
created = await githubRequest(client(), async (provider, repo) => await provider.threads.create(repo, {
|
|
889
|
+
kind: "pull_request",
|
|
890
|
+
title: pullRequest.title,
|
|
891
|
+
body: pullRequest.body,
|
|
892
|
+
head: head.branch,
|
|
893
|
+
base: base.branch,
|
|
894
|
+
draft: pullRequest.draft
|
|
895
|
+
}, deadline ? { signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())) } : void 0), "pull request");
|
|
896
|
+
number = Number(created.ref.number);
|
|
897
|
+
if (!Number.isSafeInteger(number) || !created.url) malformed("pull request");
|
|
898
|
+
} catch (error) {
|
|
899
|
+
const status = githubRequestStatus(error);
|
|
900
|
+
uncertain = dispatched && !(status !== void 0 && status >= 400 && status < 500 && status !== 408);
|
|
901
|
+
if (!uncertain && pullRequest.deleteHeadOnFailure) await deleteBranch(head.branch).catch(() => void 0);
|
|
902
|
+
throw error;
|
|
903
|
+
} finally {
|
|
904
|
+
if (!uncertain) await Promise.all(locks.map(async (lock) => await lock.release().catch(() => void 0)));
|
|
905
|
+
}
|
|
906
|
+
pullRequestCache = void 0;
|
|
907
|
+
return {
|
|
908
|
+
number,
|
|
909
|
+
url: created.url,
|
|
910
|
+
title: created.title,
|
|
911
|
+
head: head.ref,
|
|
912
|
+
base: base.ref
|
|
913
|
+
};
|
|
914
|
+
};
|
|
915
|
+
/**
|
|
916
|
+
* GitHub answers 409 to a merge that conflicts, and to one that raced another update of the branch. The body of the
|
|
917
|
+
* response tells them apart: "Merge conflict" against "Head branch was modified".
|
|
918
|
+
*/
|
|
919
|
+
const isMergeConflict = (error) => {
|
|
920
|
+
if (githubRequestStatus(error) !== 409) return false;
|
|
921
|
+
for (const entry of [error, error instanceof Error ? error.cause : void 0]) {
|
|
922
|
+
const body = entry !== null && typeof entry === "object" ? Reflect.get(entry, "body") : void 0;
|
|
923
|
+
if (typeof body === "string" && /merge conflict/i.test(body)) return true;
|
|
924
|
+
}
|
|
925
|
+
return false;
|
|
926
|
+
};
|
|
927
|
+
/** The files of a commit by repository path, with their blob sha and mode. */
|
|
928
|
+
const readFullTree = async (sha) => await githubRequest(client(), async (provider, repo) => {
|
|
929
|
+
const tree = provider.contents.tree(repo, {
|
|
930
|
+
recursive: true,
|
|
931
|
+
ref: sha
|
|
932
|
+
});
|
|
933
|
+
const files = /* @__PURE__ */ new Map();
|
|
934
|
+
for await (const entry of tree) {
|
|
935
|
+
if (entry.type !== "file" && entry.type !== "symlink") continue;
|
|
936
|
+
if (!entry.sha) malformed("tree");
|
|
937
|
+
files.set(entry.path, {
|
|
938
|
+
mode: gitFileMode(entry.mode),
|
|
939
|
+
sha: entry.sha
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
if (tree.warnings.some((warning) => warning.code === "tree_truncated")) throw workspaceError("[vitehub] GitHub workspace store could not merge because GitHub returned a truncated tree.");
|
|
943
|
+
return files;
|
|
944
|
+
}, "tree");
|
|
945
|
+
/**
|
|
946
|
+
* Merge with the Git data API when the Merges API conflicts: files that only one side changed take that side, and
|
|
947
|
+
* files that both changed keep the receiving ref's version. `onConflict` sees the files that stayed.
|
|
948
|
+
*/
|
|
949
|
+
const mergeKeepingOurs = async (from, into, mergeOptions) => {
|
|
950
|
+
let metadata = mergeOptions.metadata;
|
|
951
|
+
const sha = await githubRequest(client(), async (provider, repo) => {
|
|
952
|
+
const oursSha = await provider.contents.resolveRef(repo, `heads/${into.branch}`);
|
|
953
|
+
const theirsSha = await provider.contents.resolveRef(repo, `heads/${from.branch}`);
|
|
954
|
+
if (!oursSha || !theirsSha) malformed("commit");
|
|
955
|
+
const compare = (await provider.request("GET", `${repoPath(repo)}/compare/${encodeURIComponent(oursSha)}...${encodeURIComponent(theirsSha)}`)).data;
|
|
956
|
+
const mergeBase = Reflect.get(Object(Reflect.get(Object(compare), "merge_base_commit")), "sha");
|
|
957
|
+
if (!nonEmptyString(mergeBase)) malformed("compare");
|
|
958
|
+
const [before, ours, theirs] = await Promise.all([
|
|
959
|
+
readFullTree(mergeBase),
|
|
960
|
+
readFullTree(oursSha),
|
|
961
|
+
readFullTree(theirsSha)
|
|
962
|
+
]);
|
|
963
|
+
const same = (left, right) => left?.sha === right?.sha && left?.mode === right?.mode;
|
|
964
|
+
const changes = [];
|
|
965
|
+
const conflicts = [];
|
|
966
|
+
for (const path of /* @__PURE__ */ new Set([
|
|
967
|
+
...before.keys(),
|
|
968
|
+
...ours.keys(),
|
|
969
|
+
...theirs.keys()
|
|
970
|
+
])) {
|
|
971
|
+
const b = before.get(path);
|
|
972
|
+
const o = ours.get(path);
|
|
973
|
+
const t = theirs.get(path);
|
|
974
|
+
if (same(o, t) || same(t, b)) continue;
|
|
975
|
+
if (same(o, b)) {
|
|
976
|
+
changes.push({
|
|
977
|
+
mode: t?.mode ?? "100644",
|
|
978
|
+
path,
|
|
979
|
+
sha: t?.sha ?? null,
|
|
980
|
+
type: "blob"
|
|
981
|
+
});
|
|
982
|
+
continue;
|
|
983
|
+
}
|
|
984
|
+
const workspacePath = options.root ? path.startsWith(`${options.root}/`) ? path.slice(options.root.length + 1) : void 0 : path;
|
|
985
|
+
if (workspacePath !== void 0 && visibleWorkspacePath(workspacePath)) conflicts.push({
|
|
986
|
+
path: workspacePath,
|
|
987
|
+
ours: o?.sha ?? null,
|
|
988
|
+
theirs: t?.sha ?? null,
|
|
989
|
+
base: b?.sha ?? null
|
|
990
|
+
});
|
|
991
|
+
}
|
|
992
|
+
const resolution = await mergeOptions.onConflict(conflicts, { read: async (sha) => await (await loadForge()).forgeBlob(provider, repo, sha) });
|
|
993
|
+
metadata = {
|
|
994
|
+
...mergeOptions.metadata,
|
|
995
|
+
...resolution.metadata
|
|
996
|
+
};
|
|
997
|
+
for (const [path, text] of Object.entries(resolution.files ?? {})) {
|
|
998
|
+
if (!conflicts.some((conflict) => conflict.path === path)) throw workspaceError(`[vitehub] A merge resolved ${path}, which is not one of its conflicting files.`);
|
|
999
|
+
const repositoryPath = options.root ? `${options.root}/${path}` : path;
|
|
1000
|
+
const blob = (await provider.request("POST", `${repoPath(repo)}/git/blobs`, { body: {
|
|
1001
|
+
content: Buffer.from(text, "utf8").toString("base64"),
|
|
1002
|
+
encoding: "base64"
|
|
1003
|
+
} })).data;
|
|
1004
|
+
const blobSha = Reflect.get(Object(blob), "sha");
|
|
1005
|
+
if (!nonEmptyString(blobSha)) malformed("blob");
|
|
1006
|
+
changes.push({
|
|
1007
|
+
mode: ours.get(repositoryPath)?.mode ?? theirs.get(repositoryPath)?.mode ?? "100644",
|
|
1008
|
+
path: repositoryPath,
|
|
1009
|
+
sha: blobSha,
|
|
1010
|
+
type: "blob"
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
const message = messageWithMetadata(mergeOptions.message ?? `Merge ${from.ref} into ${into.ref}`, metadata);
|
|
1014
|
+
const oursTree = (await provider.request("GET", `${repoPath(repo)}/git/commits/${encodeURIComponent(oursSha)}`)).data;
|
|
1015
|
+
const baseTree = Reflect.get(Object(Reflect.get(Object(oursTree), "tree")), "sha");
|
|
1016
|
+
if (!nonEmptyString(baseTree)) malformed("commit");
|
|
1017
|
+
let tree = baseTree;
|
|
1018
|
+
if (changes.length) {
|
|
1019
|
+
const created = (await provider.request("POST", `${repoPath(repo)}/git/trees`, { body: {
|
|
1020
|
+
base_tree: baseTree,
|
|
1021
|
+
tree: changes
|
|
1022
|
+
} })).data;
|
|
1023
|
+
const createdSha = Reflect.get(Object(created), "sha");
|
|
1024
|
+
if (!nonEmptyString(createdSha)) malformed("tree");
|
|
1025
|
+
tree = createdSha;
|
|
1026
|
+
}
|
|
1027
|
+
const commit = (await provider.request("POST", `${repoPath(repo)}/git/commits`, { body: {
|
|
1028
|
+
message,
|
|
1029
|
+
tree,
|
|
1030
|
+
parents: [oursSha, theirsSha]
|
|
1031
|
+
} })).data;
|
|
1032
|
+
const commitSha = Reflect.get(Object(commit), "sha");
|
|
1033
|
+
if (!nonEmptyString(commitSha)) malformed("commit");
|
|
1034
|
+
await provider.request("PATCH", `${repoPath(repo)}/git/refs/heads/${refPath(into.branch)}`, { body: {
|
|
1035
|
+
sha: commitSha,
|
|
1036
|
+
force: false
|
|
1037
|
+
} });
|
|
1038
|
+
return commitSha;
|
|
1039
|
+
}, "merge");
|
|
1040
|
+
heads.set(into.branch, {
|
|
1041
|
+
expires: Date.now() + githubHeadCacheMs,
|
|
1042
|
+
head: Promise.resolve(sha)
|
|
1043
|
+
});
|
|
1044
|
+
return await revision(into.ref, sha, metadata);
|
|
1045
|
+
};
|
|
1046
|
+
const merge = async (mergeOptions) => {
|
|
1047
|
+
const from = resolveRef(mergeOptions.from);
|
|
1048
|
+
const into = resolveRef(mergeOptions.into);
|
|
1049
|
+
const message = messageWithMetadata(mergeOptions.message ?? `Merge ${from.ref} into ${into.ref}`, mergeOptions.metadata);
|
|
1050
|
+
let response;
|
|
1051
|
+
for (let attempt = 1; !response; attempt++) try {
|
|
1052
|
+
response = await githubRequest(client(), async (provider, repo) => await provider.request("POST", `${repoPath(repo)}/merges`, { body: {
|
|
1053
|
+
base: into.branch,
|
|
1054
|
+
head: from.branch,
|
|
1055
|
+
commit_message: message
|
|
1056
|
+
} }), "merge");
|
|
1057
|
+
} catch (error) {
|
|
1058
|
+
heads.delete(into.branch);
|
|
1059
|
+
const status = githubRequestStatus(error);
|
|
1060
|
+
if (isMergeConflict(error)) {
|
|
1061
|
+
if (mergeOptions.onConflict) return await mergeKeepingOurs(from, into, mergeOptions);
|
|
1062
|
+
throw workspaceConflict(`[vitehub] Merging ${from.ref} into ${into.ref} conflicts: the same lines changed on both. Resolve the conflict on the ${into.branch} branch, or make the change again after it.`, {
|
|
1063
|
+
cause: error,
|
|
1064
|
+
details: {
|
|
1065
|
+
from: from.ref,
|
|
1066
|
+
into: into.ref
|
|
1067
|
+
}
|
|
1068
|
+
});
|
|
1069
|
+
}
|
|
1070
|
+
if (status === 409 && attempt === 1) continue;
|
|
1071
|
+
if (status === 404) throw workspaceError(`[vitehub] Cannot merge ${from.ref} into ${into.ref}: a branch does not exist.`, { cause: error });
|
|
1072
|
+
throw error;
|
|
1073
|
+
}
|
|
1074
|
+
if (response.status === 204) return null;
|
|
1075
|
+
const sha = response.data !== null && typeof response.data === "object" ? Reflect.get(response.data, "sha") : void 0;
|
|
1076
|
+
if (!nonEmptyString(sha)) malformed("merge");
|
|
1077
|
+
heads.set(into.branch, {
|
|
1078
|
+
expires: Date.now() + githubHeadCacheMs,
|
|
1079
|
+
head: Promise.resolve(sha)
|
|
1080
|
+
});
|
|
1081
|
+
return await revision(into.ref, sha, mergeOptions.metadata);
|
|
1082
|
+
};
|
|
1083
|
+
/** Prepare on an isolated ref so a denied or invalid merge never changes the destination. */
|
|
1084
|
+
const checkedMerge = async (mergeOptions, check) => {
|
|
1085
|
+
if (!check) return await merge(mergeOptions);
|
|
1086
|
+
const into = resolveRef(mergeOptions.into);
|
|
1087
|
+
const expected = await readCurrentHead(client(), into.branch);
|
|
1088
|
+
if (!expected) throw workspaceError(`[vitehub] Cannot merge into ${into.ref}: the branch does not exist.`);
|
|
1089
|
+
const temporary = `vitehub/merge/${randomUUID()}`;
|
|
1090
|
+
await githubRequest(client(), async (provider, repo) => await provider.request("POST", `${repoPath(repo)}/git/refs`, { body: {
|
|
1091
|
+
ref: `refs/heads/${temporary}`,
|
|
1092
|
+
sha: expected
|
|
1093
|
+
} }));
|
|
1094
|
+
try {
|
|
1095
|
+
const prepared = await merge({
|
|
1096
|
+
...mergeOptions,
|
|
1097
|
+
into: temporary,
|
|
1098
|
+
message: mergeOptions.message ?? `Merge ${mergeOptions.from} into ${into.ref}`
|
|
1099
|
+
});
|
|
1100
|
+
if (!prepared) return null;
|
|
1101
|
+
const [before, after] = await Promise.all([readFullTree(expected), readFullTree(prepared.id)]);
|
|
1102
|
+
for (const path of /* @__PURE__ */ new Set([...before.keys(), ...after.keys()])) {
|
|
1103
|
+
const workspacePath = options.root ? path.startsWith(`${options.root}/`) ? path.slice(options.root.length + 1) : void 0 : path;
|
|
1104
|
+
if (workspacePath !== void 0 && visibleWorkspacePath(workspacePath)) continue;
|
|
1105
|
+
if (before.get(path)?.sha !== after.get(path)?.sha || before.get(path)?.mode !== after.get(path)?.mode) throw workspaceError(`[vitehub] Cannot merge a change outside the Workspace file tree: ${path}.`);
|
|
1106
|
+
}
|
|
1107
|
+
const view = await open(prepared.id);
|
|
1108
|
+
const entries = (await view.list("", { recursive: true })).filter((entry) => entry.type === "file");
|
|
1109
|
+
const files = Object.create(null);
|
|
1110
|
+
for (const entry of entries) files[entry.path] = {
|
|
1111
|
+
path: entry.path,
|
|
1112
|
+
content: await view.readFile(entry.path, { encoding: "binary" }),
|
|
1113
|
+
mediaType: entry.mediaType,
|
|
1114
|
+
metadata: entry.metadata
|
|
1115
|
+
};
|
|
1116
|
+
return await check({
|
|
1117
|
+
ref: into.ref,
|
|
1118
|
+
ifHead: expected,
|
|
1119
|
+
files,
|
|
1120
|
+
message: prepared.message,
|
|
1121
|
+
metadata: prepared.metadata
|
|
1122
|
+
}, async (checked) => {
|
|
1123
|
+
const result = checked.changes !== void 0 || !checked.files || Object.keys(checked.files).length !== entries.length || (await Promise.all(entries.map(async (entry) => {
|
|
1124
|
+
const file = checked.files?.[entry.path];
|
|
1125
|
+
return !file || await gitBlobSha(contentToBytes(file.content)) !== entry.digest || gitFileMode(file.metadata?.gitMode ?? entry.metadata?.gitMode) !== gitFileMode(entry.metadata?.gitMode);
|
|
1126
|
+
}))).some(Boolean) ? await commit({
|
|
1127
|
+
...checked,
|
|
1128
|
+
ref: temporary,
|
|
1129
|
+
ifHead: prepared.id
|
|
1130
|
+
}) : prepared;
|
|
1131
|
+
const actual = await readCurrentHead(client(), into.branch);
|
|
1132
|
+
if (actual !== expected) {
|
|
1133
|
+
heads.delete(into.branch);
|
|
1134
|
+
throw historyConflict(into.ref, expected, actual);
|
|
1135
|
+
}
|
|
1136
|
+
await githubRequest(client(), async (provider, repo) => await provider.request("PATCH", `${repoPath(repo)}/git/refs/heads/${refPath(into.branch)}`, { body: {
|
|
1137
|
+
sha: result.id,
|
|
1138
|
+
force: false
|
|
1139
|
+
} }));
|
|
1140
|
+
heads.set(into.branch, {
|
|
1141
|
+
expires: Date.now() + githubHeadCacheMs,
|
|
1142
|
+
head: Promise.resolve(result.id)
|
|
1143
|
+
});
|
|
1144
|
+
return await revision(into.ref, result.id, result.metadata);
|
|
1145
|
+
});
|
|
1146
|
+
} finally {
|
|
1147
|
+
await deleteBranch(temporary);
|
|
1148
|
+
}
|
|
1149
|
+
};
|
|
1150
|
+
return {
|
|
1151
|
+
pullRequests,
|
|
1152
|
+
openPullRequest,
|
|
1153
|
+
merge: checkedMerge,
|
|
1154
|
+
head: async (headOptions) => {
|
|
1155
|
+
const { branch, ref } = resolveRef(headOptions?.ref);
|
|
1156
|
+
const id = await readBranchHead(branch);
|
|
1157
|
+
return id ? listedRevision(ref, await readCommit(id)) : null;
|
|
1158
|
+
},
|
|
1159
|
+
digest: gitBlobSha,
|
|
1160
|
+
forksFrom: async (ref) => options.refs?.published && ref !== "published" ? "published" : void 0,
|
|
1161
|
+
list,
|
|
1162
|
+
refs,
|
|
1163
|
+
open,
|
|
1164
|
+
usage,
|
|
1165
|
+
commit
|
|
1166
|
+
};
|
|
1167
|
+
}
|
|
1168
|
+
//#endregion
|
|
1169
|
+
//#region src/providers/github/store.ts
|
|
1170
|
+
const fileMetadataPrefix = ".vitehub/file-metadata/";
|
|
1171
|
+
function isFileMetadataPath(path) {
|
|
1172
|
+
return path.startsWith(fileMetadataPrefix) && path.endsWith(".json");
|
|
1173
|
+
}
|
|
1174
|
+
function fileMetadataPath(path) {
|
|
1175
|
+
return `${fileMetadataPrefix}${encodeURIComponent(path)}.json`;
|
|
1176
|
+
}
|
|
1177
|
+
function filePathFromMetadataPath(path) {
|
|
1178
|
+
try {
|
|
1179
|
+
return decodeURIComponent(path.slice(23, -5));
|
|
1180
|
+
} catch {
|
|
1181
|
+
return "";
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
function portableMetadata(metadata) {
|
|
1185
|
+
return Object.fromEntries(Object.entries(metadata).filter(([key]) => key !== "gitMode" && key !== "symlinkTarget"));
|
|
1186
|
+
}
|
|
1187
|
+
function fileAttributesBytes(file) {
|
|
1188
|
+
const metadata = file.metadata && portableMetadata(file.metadata);
|
|
1189
|
+
if (file.mediaType === void 0 && (!metadata || Object.keys(metadata).length === 0)) return void 0;
|
|
1190
|
+
return contentToBytes(JSON.stringify({
|
|
1191
|
+
...file.mediaType === void 0 ? {} : { mediaType: file.mediaType },
|
|
1192
|
+
...metadata && Object.keys(metadata).length > 0 ? { metadata } : {}
|
|
1193
|
+
}));
|
|
1194
|
+
}
|
|
1195
|
+
function parseFileAttributes(bytes) {
|
|
1196
|
+
try {
|
|
1197
|
+
const value = JSON.parse(new TextDecoder().decode(bytes));
|
|
1198
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
1199
|
+
const record = value;
|
|
1200
|
+
const metadata = record.metadata;
|
|
1201
|
+
return {
|
|
1202
|
+
...typeof record.mediaType === "string" ? { mediaType: record.mediaType } : {},
|
|
1203
|
+
...metadata && typeof metadata === "object" && !Array.isArray(metadata) ? { metadata: portableMetadata(metadata) } : {}
|
|
1204
|
+
};
|
|
1205
|
+
} catch {
|
|
1206
|
+
return {};
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
function sameFileAttributes(left, right) {
|
|
1210
|
+
return left?.mediaType === right.mediaType && JSON.stringify(left?.metadata) === JSON.stringify(right.metadata);
|
|
1211
|
+
}
|
|
1212
|
+
function sameGitHubTreeEntry(left, right) {
|
|
1213
|
+
return left?.sha === right?.sha && left?.mode === right?.mode;
|
|
1214
|
+
}
|
|
1215
|
+
function matchesGitHubRemote(file, remote) {
|
|
1216
|
+
return file?.gitSha === remote?.sha && (file ? gitHubFileMode(file.metadata) : void 0) === remote?.mode;
|
|
1217
|
+
}
|
|
1218
|
+
function githubRemoteFile(path, entry, attributes) {
|
|
1219
|
+
const treeMetadata = gitHubFileMetadata(entry);
|
|
1220
|
+
const metadata = treeMetadata || attributes?.metadata ? {
|
|
1221
|
+
...treeMetadata,
|
|
1222
|
+
...attributes?.metadata
|
|
1223
|
+
} : void 0;
|
|
1224
|
+
return {
|
|
1225
|
+
gitSha: entry.sha,
|
|
1226
|
+
...attributes?.mediaType === void 0 ? {} : { mediaType: attributes.mediaType },
|
|
1227
|
+
...metadata ? { metadata } : {},
|
|
1228
|
+
path,
|
|
1229
|
+
size: entry.size
|
|
1230
|
+
};
|
|
1231
|
+
}
|
|
1232
|
+
function isReservedWorkspacePath(path) {
|
|
1233
|
+
const root = normalizeWorkspacePath(path).split("/")[0]?.toLowerCase();
|
|
1234
|
+
return root === ".git" || root === ".vitehub";
|
|
1235
|
+
}
|
|
1236
|
+
function readStringMetadata(metadata, key) {
|
|
1237
|
+
const value = metadata?.[key];
|
|
1238
|
+
return Object.prototype.toString.call(value) === "[object String]" ? String(value) : void 0;
|
|
1239
|
+
}
|
|
1240
|
+
function gitHubFileMetadata(entry) {
|
|
1241
|
+
return entry.mode === "100644" ? void 0 : { gitMode: entry.mode };
|
|
1242
|
+
}
|
|
1243
|
+
function gitHubFileMode(metadata) {
|
|
1244
|
+
return gitFileMode(metadata?.gitMode);
|
|
1245
|
+
}
|
|
1246
|
+
function inheritedGitHubFileMetadata(file, current) {
|
|
1247
|
+
if (file.metadata) return file.metadata;
|
|
1248
|
+
return current?.metadata?.gitMode === "100755" ? current.metadata : void 0;
|
|
1249
|
+
}
|
|
1250
|
+
function parentDirectories(path) {
|
|
1251
|
+
const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
|
|
1252
|
+
const directories = [];
|
|
1253
|
+
for (let index = 1; index < parts.length; index++) directories.push(parts.slice(0, index).join("/"));
|
|
1254
|
+
return directories;
|
|
1255
|
+
}
|
|
1256
|
+
function resolveSymlinkTarget(path, bytes) {
|
|
1257
|
+
const target = gitSymlinkTargetFromBytes(bytes);
|
|
1258
|
+
if (!target || target.startsWith("/")) return;
|
|
1259
|
+
const base = path.split("/").slice(0, -1).join("/");
|
|
1260
|
+
const resolved = posix.normalize(base ? `${base}/${target}` : target);
|
|
1261
|
+
if (!resolved || resolved === "." || resolved === ".." || resolved.startsWith("../")) return;
|
|
1262
|
+
return normalizeSafeWorkspacePath(resolved);
|
|
1263
|
+
}
|
|
1264
|
+
function gitSymlinkTargetFromBytes(bytes) {
|
|
1265
|
+
return new TextDecoder().decode(bytes).replace(/\0/g, "");
|
|
1266
|
+
}
|
|
1267
|
+
async function waitForGitHubOperation(read, signal) {
|
|
1268
|
+
signal?.throwIfAborted();
|
|
1269
|
+
if (!signal) return await read;
|
|
1270
|
+
return await new Promise((resolve, reject) => {
|
|
1271
|
+
const abort = () => reject(signal.reason);
|
|
1272
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
1273
|
+
read.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
1274
|
+
});
|
|
1275
|
+
}
|
|
1276
|
+
var GitHubWorkspaceStore = class {
|
|
1277
|
+
options;
|
|
1278
|
+
workspaceName;
|
|
1279
|
+
#baseline;
|
|
1280
|
+
#archive;
|
|
1281
|
+
#archiveReads = /* @__PURE__ */ new Map();
|
|
1282
|
+
#baselineRefSha;
|
|
1283
|
+
#dirty = false;
|
|
1284
|
+
#files = /* @__PURE__ */ new Map();
|
|
1285
|
+
#loadedAt = 0;
|
|
1286
|
+
#mutationQueue = Promise.resolve();
|
|
1287
|
+
#ready;
|
|
1288
|
+
#remoteFiles = /* @__PURE__ */ new Map();
|
|
1289
|
+
#remoteMetadataFiles = /* @__PURE__ */ new Map();
|
|
1290
|
+
#resolved;
|
|
1291
|
+
#history;
|
|
1292
|
+
constructor(options, workspaceName) {
|
|
1293
|
+
this.options = options;
|
|
1294
|
+
this.workspaceName = workspaceName;
|
|
1295
|
+
}
|
|
1296
|
+
/**
|
|
1297
|
+
* The repository, branch, root, and token resolve on first use. The Store is created when the Workspace Definition
|
|
1298
|
+
* loads, even in a build that has no token, and a missing option fails at the first request.
|
|
1299
|
+
*/
|
|
1300
|
+
get #connection() {
|
|
1301
|
+
return this.#resolved ||= (() => {
|
|
1302
|
+
const repository = requireGitHubOption("a repository", resolveGitHubRepositoryOption(this.options));
|
|
1303
|
+
return {
|
|
1304
|
+
branch: resolveGitHubBranchOption(this.options),
|
|
1305
|
+
client: connectGitHubRepository(repository, resolveGitHubCredential(this.options)),
|
|
1306
|
+
repository,
|
|
1307
|
+
root: resolveGitHubRootOption(this.options, this.workspaceName)
|
|
1308
|
+
};
|
|
1309
|
+
})();
|
|
1310
|
+
}
|
|
1311
|
+
get #branch() {
|
|
1312
|
+
return this.#connection.branch;
|
|
1313
|
+
}
|
|
1314
|
+
get #client() {
|
|
1315
|
+
return this.#connection.client;
|
|
1316
|
+
}
|
|
1317
|
+
get #repository() {
|
|
1318
|
+
return this.#connection.repository;
|
|
1319
|
+
}
|
|
1320
|
+
get #root() {
|
|
1321
|
+
return this.#connection.root;
|
|
1322
|
+
}
|
|
1323
|
+
get history() {
|
|
1324
|
+
return this.#history ||= createGitHubWorkspaceHistory(() => ({
|
|
1325
|
+
branch: this.#branch,
|
|
1326
|
+
client: this.#client,
|
|
1327
|
+
refs: resolveGitHubRefsOption(this.options),
|
|
1328
|
+
repository: this.#repository,
|
|
1329
|
+
root: this.#root
|
|
1330
|
+
}));
|
|
1331
|
+
}
|
|
1332
|
+
/** Drops the staged writes. The next call loads the branch again, as the first call does. */
|
|
1333
|
+
async [workspaceStoreDiscard]() {
|
|
1334
|
+
await this.#mutate(async () => {
|
|
1335
|
+
this.#dirty = false;
|
|
1336
|
+
this.#ready = void 0;
|
|
1337
|
+
});
|
|
1338
|
+
}
|
|
1339
|
+
[workspaceStoreTarget]() {
|
|
1340
|
+
return {
|
|
1341
|
+
provider: "github",
|
|
1342
|
+
branch: this.#branch,
|
|
1343
|
+
repository: this.#repository,
|
|
1344
|
+
...this.options.database === void 0 ? {} : { database: this.options.database }
|
|
1345
|
+
};
|
|
1346
|
+
}
|
|
1347
|
+
[workspaceRevisionMaterializer] = {
|
|
1348
|
+
currentRevision: async (options) => {
|
|
1349
|
+
await waitForGitHubOperation(this.#mutate(async () => await this.#ensure({ refresh: options?.refresh !== false })), options?.abortSignal);
|
|
1350
|
+
return this.#baselineRefSha;
|
|
1351
|
+
},
|
|
1352
|
+
materializeRevision: async (options) => {
|
|
1353
|
+
await waitForGitHubOperation(this.#mutate(async () => await this.#ensure({ refresh: true })), options?.abortSignal);
|
|
1354
|
+
const revision = this.#baselineRefSha;
|
|
1355
|
+
const paths = options?.paths;
|
|
1356
|
+
const files = [...this.#remoteFiles.keys()].filter((path) => !isReservedWorkspacePath(path) && (!paths || paths.some((root) => path === root || path.startsWith(`${root}/`)))).length;
|
|
1357
|
+
if (!this.#dirty && paths === void 0 && this.#archive?.revision !== revision) {
|
|
1358
|
+
let read = this.#archiveReads.get(revision);
|
|
1359
|
+
if (!read) {
|
|
1360
|
+
read = readGitHubArchive(this.#client, revision);
|
|
1361
|
+
this.#archiveReads.set(revision, read);
|
|
1362
|
+
read.finally(() => {
|
|
1363
|
+
if (this.#archiveReads.get(revision) === read) this.#archiveReads.delete(revision);
|
|
1364
|
+
}).catch(() => {});
|
|
1365
|
+
}
|
|
1366
|
+
this.#archive = {
|
|
1367
|
+
bytes: await waitForGitHubOperation(read, options?.abortSignal),
|
|
1368
|
+
revision
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
return {
|
|
1372
|
+
...!this.#dirty && paths === void 0 ? { archive: this.#archive.bytes } : {},
|
|
1373
|
+
files,
|
|
1374
|
+
paths,
|
|
1375
|
+
revision,
|
|
1376
|
+
root: this.#root
|
|
1377
|
+
};
|
|
1378
|
+
}
|
|
1379
|
+
};
|
|
1380
|
+
async readFile(path) {
|
|
1381
|
+
const normalized = normalizeSafeWorkspacePath(path);
|
|
1382
|
+
await this.#mutate(async () => await this.#ensure({ refresh: "expired" }));
|
|
1383
|
+
return await this.#readWorkspaceFile(normalized);
|
|
1384
|
+
}
|
|
1385
|
+
async writeFile(path, file) {
|
|
1386
|
+
await this.#mutate(async () => {
|
|
1387
|
+
const normalized = normalizeSafeWorkspacePath(path);
|
|
1388
|
+
await this.#ensure({ refresh: "expired" });
|
|
1389
|
+
await this.#writeFile(normalized, file);
|
|
1390
|
+
});
|
|
1391
|
+
}
|
|
1392
|
+
async writeFileConditional(path, file, ifDigest) {
|
|
1393
|
+
await this.#mutate(async () => {
|
|
1394
|
+
const normalized = normalizeSafeWorkspacePath(path);
|
|
1395
|
+
await this.#ensure({ refresh: true });
|
|
1396
|
+
assertWorkspaceDigest(normalized, ifDigest, this.#files.get(normalized)?.gitSha);
|
|
1397
|
+
await this.#writeFile(normalized, file);
|
|
1398
|
+
});
|
|
1399
|
+
}
|
|
1400
|
+
async #writeFile(normalized, file) {
|
|
1401
|
+
const current = this.#files.get(normalized);
|
|
1402
|
+
const metadata = inheritedGitHubFileMetadata(file, current);
|
|
1403
|
+
const symlinkTarget = readStringMetadata(metadata, "symlinkTarget");
|
|
1404
|
+
const content = gitHubFileMode(metadata) === "120000" && symlinkTarget !== void 0 ? symlinkTarget : file.content;
|
|
1405
|
+
const bytes = contentToBytes(content);
|
|
1406
|
+
const gitSha = await gitBlobSha(bytes);
|
|
1407
|
+
if (current?.gitSha === gitSha) {
|
|
1408
|
+
if (gitHubFileMode(current.metadata) !== gitHubFileMode(metadata) || !sameFileAttributes(current, {
|
|
1409
|
+
mediaType: file.mediaType,
|
|
1410
|
+
metadata
|
|
1411
|
+
})) this.#dirty = true;
|
|
1412
|
+
this.#files.set(normalized, {
|
|
1413
|
+
...current,
|
|
1414
|
+
bytes,
|
|
1415
|
+
mediaType: file.mediaType,
|
|
1416
|
+
metadata,
|
|
1417
|
+
size: bytes.byteLength
|
|
1418
|
+
});
|
|
1419
|
+
return;
|
|
1420
|
+
}
|
|
1421
|
+
this.#files.set(normalized, {
|
|
1422
|
+
bytes,
|
|
1423
|
+
gitSha,
|
|
1424
|
+
mediaType: file.mediaType,
|
|
1425
|
+
metadata,
|
|
1426
|
+
path: normalized,
|
|
1427
|
+
size: bytes.byteLength
|
|
1428
|
+
});
|
|
1429
|
+
this.#dirty = true;
|
|
1430
|
+
}
|
|
1431
|
+
#mutate(operation) {
|
|
1432
|
+
const result = this.#mutationQueue.then(operation);
|
|
1433
|
+
this.#mutationQueue = result.then(() => void 0, () => void 0);
|
|
1434
|
+
return result;
|
|
1435
|
+
}
|
|
1436
|
+
async writeFileStream(path, file) {
|
|
1437
|
+
const content = await contentStreamToBytes(file.content);
|
|
1438
|
+
await this.writeFile(path, {
|
|
1439
|
+
path: file.path,
|
|
1440
|
+
content,
|
|
1441
|
+
mediaType: file.mediaType,
|
|
1442
|
+
metadata: file.metadata
|
|
1443
|
+
});
|
|
1444
|
+
return {
|
|
1445
|
+
digest: await gitBlobSha(content),
|
|
1446
|
+
mediaType: file.mediaType,
|
|
1447
|
+
path: normalizeSafeWorkspacePath(path),
|
|
1448
|
+
size: content.byteLength,
|
|
1449
|
+
type: "file"
|
|
1450
|
+
};
|
|
1451
|
+
}
|
|
1452
|
+
async list(prefix = "", options = {}) {
|
|
1453
|
+
return await this.#mutate(async () => {
|
|
1454
|
+
const normalizedPrefix = normalizeSafeWorkspacePath(prefix, { allowEmpty: true });
|
|
1455
|
+
await this.#ensure({ refresh: true });
|
|
1456
|
+
return await this.#listEntries(normalizedPrefix, options);
|
|
1457
|
+
});
|
|
1458
|
+
}
|
|
1459
|
+
async glob(pattern, options = {}) {
|
|
1460
|
+
const patterns = Array.isArray(pattern) ? pattern.map(normalizeSafeWorkspacePattern) : normalizeSafeWorkspacePattern(pattern);
|
|
1461
|
+
const { cwd, matches } = createWorkspaceGlobMatcher(patterns, options);
|
|
1462
|
+
return (await this.list(cwd, { recursive: true })).filter((entry) => entry.type === "file" && matches(entry.path));
|
|
1463
|
+
}
|
|
1464
|
+
async stat(path) {
|
|
1465
|
+
return await this.#mutate(async () => {
|
|
1466
|
+
const normalized = normalizeSafeWorkspacePath(path);
|
|
1467
|
+
await this.#ensure({ refresh: true });
|
|
1468
|
+
const file = this.#files.get(normalized);
|
|
1469
|
+
if (file && !isReservedWorkspacePath(normalized)) return this.#fileEntry(file);
|
|
1470
|
+
if (this.#directoryExists(normalized)) return {
|
|
1471
|
+
path: normalized,
|
|
1472
|
+
type: "directory"
|
|
1473
|
+
};
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
async mkdir(path, _options = {}) {
|
|
1477
|
+
normalizeSafeWorkspacePath(path);
|
|
1478
|
+
}
|
|
1479
|
+
async rm(path, options = {}) {
|
|
1480
|
+
await this.#mutate(async () => {
|
|
1481
|
+
const normalized = normalizeSafeWorkspacePath(path);
|
|
1482
|
+
await this.#ensure({ refresh: "expired" });
|
|
1483
|
+
const file = this.#files.get(normalized);
|
|
1484
|
+
if (options.ifDigest !== void 0) assertWorkspaceDigest(path, options.ifDigest, file ? (await this.#fileEntry(file)).digest : void 0);
|
|
1485
|
+
const removedFile = Boolean(file && !isReservedWorkspacePath(normalized));
|
|
1486
|
+
if (removedFile) {
|
|
1487
|
+
this.#files.delete(normalized);
|
|
1488
|
+
this.#dirty = true;
|
|
1489
|
+
if (!options.recursive) return;
|
|
1490
|
+
}
|
|
1491
|
+
const children = this.#publicDescendants(normalized);
|
|
1492
|
+
if (!(children.length > 0)) {
|
|
1493
|
+
if (removedFile || options.force) return;
|
|
1494
|
+
throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
|
|
1495
|
+
}
|
|
1496
|
+
if (children.length && !options.recursive) throw workspaceError(`[vitehub] Workspace directory is not empty: ${path}.`);
|
|
1497
|
+
for (const child of children) this.#files.delete(child);
|
|
1498
|
+
this.#dirty = true;
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1501
|
+
async snapshot(options = {}) {
|
|
1502
|
+
return await this.#mutate(async () => await this.#snapshot(options));
|
|
1503
|
+
}
|
|
1504
|
+
async rebase(options = {}) {
|
|
1505
|
+
await this.#mutate(async () => {
|
|
1506
|
+
await this.#ensure({ refresh: false });
|
|
1507
|
+
await this.#rebase(options);
|
|
1508
|
+
});
|
|
1509
|
+
}
|
|
1510
|
+
/** Move the staged writes onto the current branch head. A path that changed on both sides fails with its name in `details.paths`. */
|
|
1511
|
+
async #rebase(options, loaded) {
|
|
1512
|
+
const remote = loaded ?? await readGitHubBranchState({
|
|
1513
|
+
branch: this.#branch,
|
|
1514
|
+
repository: this.#client,
|
|
1515
|
+
root: this.#root
|
|
1516
|
+
});
|
|
1517
|
+
const remoteFiles = new Map([...remote.files].filter(([path]) => !isFileMetadataPath(path)));
|
|
1518
|
+
const remoteMetadataFiles = new Map([...remote.files].filter(([path]) => isFileMetadataPath(path)));
|
|
1519
|
+
const remoteAttributes = /* @__PURE__ */ new Map();
|
|
1520
|
+
await Promise.all([...remoteMetadataFiles].map(async ([path, entry]) => {
|
|
1521
|
+
const bytes = await readGitHubFile(this.#client, entry, remote.refSha);
|
|
1522
|
+
remoteAttributes.set(filePathFromMetadataPath(path), parseFileAttributes(bytes));
|
|
1523
|
+
}));
|
|
1524
|
+
const takeRemote = options.takeRemote || [];
|
|
1525
|
+
const shouldTakeRemote = (path) => takeRemote.some((root) => path === root || path.startsWith(`${root}/`));
|
|
1526
|
+
const local = new Map(this.#files);
|
|
1527
|
+
const previousRemoteFiles = this.#remoteFiles;
|
|
1528
|
+
const previousRemoteMetadataFiles = this.#remoteMetadataFiles;
|
|
1529
|
+
const changed = /* @__PURE__ */ new Set([...previousRemoteFiles.keys(), ...local.keys()]);
|
|
1530
|
+
if (remote.refSha === this.#baselineRefSha) {
|
|
1531
|
+
for (const path of changed) {
|
|
1532
|
+
if (!shouldTakeRemote(path)) continue;
|
|
1533
|
+
const file = remoteFiles.get(path);
|
|
1534
|
+
if (file) this.#files.set(path, githubRemoteFile(path, file, remoteAttributes.get(path)));
|
|
1535
|
+
else this.#files.delete(path);
|
|
1536
|
+
}
|
|
1537
|
+
this.#dirty = await this.#hasRemoteChanges();
|
|
1538
|
+
return;
|
|
1539
|
+
}
|
|
1540
|
+
const conflicts = [];
|
|
1541
|
+
for (const path of changed) {
|
|
1542
|
+
if (await this.#matchesRemote(local.get(path), previousRemoteFiles.get(path), previousRemoteMetadataFiles.get(fileMetadataPath(path)))) {
|
|
1543
|
+
changed.delete(path);
|
|
1544
|
+
continue;
|
|
1545
|
+
}
|
|
1546
|
+
const previous = previousRemoteFiles.get(path);
|
|
1547
|
+
const current = remoteFiles.get(path);
|
|
1548
|
+
const previousMetadata = previousRemoteMetadataFiles.get(fileMetadataPath(path));
|
|
1549
|
+
const currentMetadata = remoteMetadataFiles.get(fileMetadataPath(path));
|
|
1550
|
+
if ((!sameGitHubTreeEntry(previous, current) || !sameGitHubTreeEntry(previousMetadata, currentMetadata)) && !shouldTakeRemote(path) && !await this.#matchesRemote(local.get(path), current, currentMetadata)) conflicts.push(path);
|
|
1551
|
+
}
|
|
1552
|
+
if (conflicts.length) {
|
|
1553
|
+
conflicts.sort();
|
|
1554
|
+
throw workspaceConflict(`[vitehub] GitHub Workspace Store rebase conflict for ${this.#repository}@${this.#branch}: ${conflicts.join(", ")} changed locally and remotely.`, { details: {
|
|
1555
|
+
branch: this.#branch,
|
|
1556
|
+
paths: conflicts,
|
|
1557
|
+
repository: this.#repository
|
|
1558
|
+
} });
|
|
1559
|
+
}
|
|
1560
|
+
this.#baselineRefSha = remote.refSha;
|
|
1561
|
+
this.#loadedAt = Date.now();
|
|
1562
|
+
this.#remoteFiles = remoteFiles;
|
|
1563
|
+
this.#remoteMetadataFiles = remoteMetadataFiles;
|
|
1564
|
+
this.#files = new Map([...remoteFiles].map(([path, entry]) => [path, githubRemoteFile(path, entry, remoteAttributes.get(path))]));
|
|
1565
|
+
this.#baseline = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }, false), "github-workspace-store-rebase");
|
|
1566
|
+
for (const path of changed) {
|
|
1567
|
+
if (shouldTakeRemote(path)) continue;
|
|
1568
|
+
const file = local.get(path);
|
|
1569
|
+
if (file) this.#files.set(path, file);
|
|
1570
|
+
else this.#files.delete(path);
|
|
1571
|
+
}
|
|
1572
|
+
this.#dirty = await this.#hasRemoteChanges();
|
|
1573
|
+
}
|
|
1574
|
+
/**
|
|
1575
|
+
* Commit the staged writes. When the branch moved since the Store loaded, for example because another isolate
|
|
1576
|
+
* committed, the Store moves the staged writes onto the new head and commits once more. A path that changed on
|
|
1577
|
+
* both sides, or a second move, fails with `WORKSPACE_CONFLICT`.
|
|
1578
|
+
*/
|
|
1579
|
+
async #snapshot(options, retry = true) {
|
|
1580
|
+
await this.#ensure({ refresh: "expired" });
|
|
1581
|
+
const snapshot = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }), options.name);
|
|
1582
|
+
if (!this.#dirty) {
|
|
1583
|
+
this.#baseline = snapshot;
|
|
1584
|
+
return snapshot;
|
|
1585
|
+
}
|
|
1586
|
+
const remote = await readGitHubBranchState({
|
|
1587
|
+
branch: this.#branch,
|
|
1588
|
+
repository: this.#client,
|
|
1589
|
+
root: this.#root
|
|
1590
|
+
});
|
|
1591
|
+
if (this.#baselineRefSha && remote.refSha !== this.#baselineRefSha) {
|
|
1592
|
+
if (retry) {
|
|
1593
|
+
await this.#rebase({}, remote);
|
|
1594
|
+
return await this.#snapshot(options, false);
|
|
1595
|
+
}
|
|
1596
|
+
throw githubBranchMovedConflict({
|
|
1597
|
+
actualHead: remote.refSha,
|
|
1598
|
+
branch: this.#branch,
|
|
1599
|
+
expectedHead: this.#baselineRefSha,
|
|
1600
|
+
repository: this.#repository
|
|
1601
|
+
});
|
|
1602
|
+
}
|
|
1603
|
+
const remoteFiles = new Map([...remote.files].filter(([path]) => !isFileMetadataPath(path)));
|
|
1604
|
+
const remoteMetadataFiles = new Map([...remote.files].filter(([path]) => isFileMetadataPath(path)));
|
|
1605
|
+
this.#remoteFiles = remoteFiles;
|
|
1606
|
+
this.#remoteMetadataFiles = remoteMetadataFiles;
|
|
1607
|
+
this.#baselineRefSha = remote.refSha;
|
|
1608
|
+
const changedFiles = [...this.#files.values()].filter((file) => !matchesGitHubRemote(file, this.#remoteFiles.get(file.path)));
|
|
1609
|
+
const changedMetadataFiles = (await Promise.all([...this.#files.values()].map(async (file) => {
|
|
1610
|
+
const bytes = fileAttributesBytes(file);
|
|
1611
|
+
const remote = this.#remoteMetadataFiles.get(fileMetadataPath(file.path));
|
|
1612
|
+
if (!bytes) return void 0;
|
|
1613
|
+
return remote?.sha === await gitBlobSha(bytes) ? void 0 : file;
|
|
1614
|
+
}))).filter((file) => Boolean(file));
|
|
1615
|
+
const deletePaths = [...this.#remoteFiles].filter(([path]) => !this.#files.has(path)).map(([, entry]) => entry.path).concat([...this.#remoteMetadataFiles].filter(([path]) => !this.#files.has(filePathFromMetadataPath(path)) || !fileAttributesBytes(this.#files.get(filePathFromMetadataPath(path)))).map(([, entry]) => entry.path));
|
|
1616
|
+
if (!changedFiles.length && !changedMetadataFiles.length && !deletePaths.length) {
|
|
1617
|
+
this.#dirty = false;
|
|
1618
|
+
this.#baseline = snapshot;
|
|
1619
|
+
return snapshot;
|
|
1620
|
+
}
|
|
1621
|
+
const files = await Promise.all(changedFiles.map(async (file) => ({
|
|
1622
|
+
bytes: await this.#readFileBytes(file),
|
|
1623
|
+
fullPath: joinGitPath(this.#root, file.path),
|
|
1624
|
+
mode: gitHubFileMode(file.metadata)
|
|
1625
|
+
})));
|
|
1626
|
+
for (const file of changedMetadataFiles) {
|
|
1627
|
+
const bytes = fileAttributesBytes(file);
|
|
1628
|
+
if (bytes) files.push({
|
|
1629
|
+
bytes,
|
|
1630
|
+
fullPath: joinGitPath(this.#root, fileMetadataPath(file.path)),
|
|
1631
|
+
mode: "100644"
|
|
1632
|
+
});
|
|
1633
|
+
}
|
|
1634
|
+
let commitSha;
|
|
1635
|
+
try {
|
|
1636
|
+
commitSha = await commitGitHubChanges({
|
|
1637
|
+
branch: this.#branch,
|
|
1638
|
+
branchExists: remote.branchExists,
|
|
1639
|
+
deletePaths,
|
|
1640
|
+
files,
|
|
1641
|
+
message: options.name || "chore: update workspace snapshot",
|
|
1642
|
+
...options.author ? { author: options.author } : {},
|
|
1643
|
+
parentSha: this.#baselineRefSha,
|
|
1644
|
+
remoteModes: new Map([...this.#remoteFiles.values()].map((entry) => [entry.path, entry.mode])),
|
|
1645
|
+
repository: this.#client
|
|
1646
|
+
});
|
|
1647
|
+
} catch (error) {
|
|
1648
|
+
if (!retry || !isWorkspaceConflict(error)) throw error;
|
|
1649
|
+
await this.#rebase({});
|
|
1650
|
+
return await this.#snapshot(options, false);
|
|
1651
|
+
}
|
|
1652
|
+
this.#dirty = false;
|
|
1653
|
+
this.#baselineRefSha = commitSha;
|
|
1654
|
+
this.#loadedAt = Date.now();
|
|
1655
|
+
this.#remoteFiles = this.#toRemoteFiles();
|
|
1656
|
+
this.#remoteMetadataFiles = await this.#toRemoteMetadataFiles();
|
|
1657
|
+
this.#baseline = {
|
|
1658
|
+
...snapshot,
|
|
1659
|
+
id: commitSha
|
|
1660
|
+
};
|
|
1661
|
+
return this.#baseline;
|
|
1662
|
+
}
|
|
1663
|
+
async diff(options = {}) {
|
|
1664
|
+
return await this.#mutate(async () => {
|
|
1665
|
+
await this.#ensure({ refresh: true });
|
|
1666
|
+
const fromSnapshot = options.from || this.#baseline;
|
|
1667
|
+
const from = fromSnapshot && {
|
|
1668
|
+
...fromSnapshot,
|
|
1669
|
+
entries: Object.fromEntries(Object.entries(fromSnapshot.entries).map(([path, entry]) => [path, {
|
|
1670
|
+
...entry,
|
|
1671
|
+
...entry.metadata?.gitMode === "120000" ? { metadata: {
|
|
1672
|
+
...entry.metadata,
|
|
1673
|
+
symlinkTarget: void 0
|
|
1674
|
+
} } : {}
|
|
1675
|
+
}]))
|
|
1676
|
+
};
|
|
1677
|
+
const to = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }, false));
|
|
1678
|
+
return diffSnapshots(from, to);
|
|
1679
|
+
});
|
|
1680
|
+
}
|
|
1681
|
+
async getMeta(key) {
|
|
1682
|
+
return await this.#mutate(async () => {
|
|
1683
|
+
await this.#ensure({ refresh: true });
|
|
1684
|
+
const file = await this.#readWorkspaceFile(this.#metaPath(key));
|
|
1685
|
+
if (!file?.bytes.byteLength) return void 0;
|
|
1686
|
+
return JSON.parse(new TextDecoder().decode(file.bytes));
|
|
1687
|
+
});
|
|
1688
|
+
}
|
|
1689
|
+
async setMeta(key, value) {
|
|
1690
|
+
await this.#mutate(async () => {
|
|
1691
|
+
const path = this.#metaPath(key);
|
|
1692
|
+
await this.#ensure({ refresh: "expired" });
|
|
1693
|
+
if (value === void 0) {
|
|
1694
|
+
if (this.#files.delete(path)) this.#dirty = true;
|
|
1695
|
+
return;
|
|
1696
|
+
}
|
|
1697
|
+
const bytes = new TextEncoder().encode(JSON.stringify(value));
|
|
1698
|
+
this.#files.set(path, {
|
|
1699
|
+
bytes,
|
|
1700
|
+
gitSha: await gitBlobSha(bytes),
|
|
1701
|
+
path,
|
|
1702
|
+
size: bytes.byteLength
|
|
1703
|
+
});
|
|
1704
|
+
this.#dirty = true;
|
|
1705
|
+
});
|
|
1706
|
+
}
|
|
1707
|
+
/**
|
|
1708
|
+
* Load the branch once. Without staged writes, `refresh: true` reads the head again, and `"expired"` reads it again
|
|
1709
|
+
* when the Store loaded it more than `githubHeadCacheMs` ago. A Store that one isolate keeps for many requests so
|
|
1710
|
+
* sees commits from other writers before it stages new writes.
|
|
1711
|
+
*/
|
|
1712
|
+
async #ensure(options) {
|
|
1713
|
+
const wasReady = !!this.#ready;
|
|
1714
|
+
this.#ready ||= this.#load().catch((error) => {
|
|
1715
|
+
this.#ready = void 0;
|
|
1716
|
+
throw error;
|
|
1717
|
+
});
|
|
1718
|
+
await this.#ready;
|
|
1719
|
+
if (!wasReady || this.#dirty || !options.refresh) return;
|
|
1720
|
+
if (options.refresh === "expired" && Date.now() - this.#loadedAt < 5e3) return;
|
|
1721
|
+
await this.#load();
|
|
1722
|
+
}
|
|
1723
|
+
async #matchesRemote(file, remote, remoteMetadata) {
|
|
1724
|
+
if (!matchesGitHubRemote(file, remote)) return false;
|
|
1725
|
+
const attributes = file && fileAttributesBytes(file);
|
|
1726
|
+
if (!attributes) return !remoteMetadata;
|
|
1727
|
+
return remoteMetadata?.sha === await gitBlobSha(attributes);
|
|
1728
|
+
}
|
|
1729
|
+
async #hasRemoteChanges() {
|
|
1730
|
+
const paths = /* @__PURE__ */ new Set([...this.#remoteFiles.keys(), ...this.#files.keys()]);
|
|
1731
|
+
for (const path of paths) if (!await this.#matchesRemote(this.#files.get(path), this.#remoteFiles.get(path), this.#remoteMetadataFiles.get(fileMetadataPath(path)))) return true;
|
|
1732
|
+
return false;
|
|
1733
|
+
}
|
|
1734
|
+
async #load() {
|
|
1735
|
+
const previousFiles = this.#files;
|
|
1736
|
+
const remote = await readGitHubBranchState({
|
|
1737
|
+
branch: this.#branch,
|
|
1738
|
+
repository: this.#client,
|
|
1739
|
+
root: this.#root
|
|
1740
|
+
});
|
|
1741
|
+
this.#baselineRefSha = remote.refSha;
|
|
1742
|
+
this.#loadedAt = Date.now();
|
|
1743
|
+
const remoteFiles = new Map([...remote.files].filter(([path]) => !isFileMetadataPath(path)));
|
|
1744
|
+
const remoteMetadataFiles = new Map([...remote.files].filter(([path]) => isFileMetadataPath(path)));
|
|
1745
|
+
const attributes = /* @__PURE__ */ new Map();
|
|
1746
|
+
await Promise.all([...remoteMetadataFiles].map(async ([path, entry]) => {
|
|
1747
|
+
const bytes = await readGitHubFile(this.#client, entry, remote.refSha);
|
|
1748
|
+
attributes.set(filePathFromMetadataPath(path), parseFileAttributes(bytes));
|
|
1749
|
+
}));
|
|
1750
|
+
this.#remoteFiles = remoteFiles;
|
|
1751
|
+
this.#remoteMetadataFiles = remoteMetadataFiles;
|
|
1752
|
+
if (!this.#dirty) {
|
|
1753
|
+
this.#files = new Map([...remoteFiles].map(([path, entry]) => {
|
|
1754
|
+
const previous = previousFiles.get(path);
|
|
1755
|
+
return [path, {
|
|
1756
|
+
...githubRemoteFile(path, entry, attributes.get(path)),
|
|
1757
|
+
...previous && previous.gitSha === entry.sha && gitHubFileMode(previous.metadata) === entry.mode ? { bytes: previous.bytes } : {}
|
|
1758
|
+
}];
|
|
1759
|
+
}));
|
|
1760
|
+
this.#baseline = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }, false), "github-workspace-store-load");
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
async #readWorkspaceFile(path, seen = /* @__PURE__ */ new Set()) {
|
|
1764
|
+
const current = this.#files.get(path);
|
|
1765
|
+
if (!current) return void 0;
|
|
1766
|
+
const currentBytes = await this.#readFileBytes(current);
|
|
1767
|
+
if (gitHubFileMode(current.metadata) === "120000" && !seen.has(path)) {
|
|
1768
|
+
const target = resolveSymlinkTarget(path, currentBytes);
|
|
1769
|
+
if (target && this.#files.has(target)) {
|
|
1770
|
+
seen.add(path);
|
|
1771
|
+
const resolved = await this.#readWorkspaceFile(target, seen);
|
|
1772
|
+
if (resolved) return {
|
|
1773
|
+
...resolved,
|
|
1774
|
+
mediaType: current.mediaType ?? resolved.mediaType,
|
|
1775
|
+
metadata: await this.#fileMetadata(current) ?? resolved.metadata,
|
|
1776
|
+
path
|
|
1777
|
+
};
|
|
1778
|
+
}
|
|
1779
|
+
}
|
|
1780
|
+
return {
|
|
1781
|
+
content: currentBytes,
|
|
1782
|
+
bytes: currentBytes,
|
|
1783
|
+
mediaType: current.mediaType,
|
|
1784
|
+
metadata: await this.#fileMetadata(current),
|
|
1785
|
+
path
|
|
1786
|
+
};
|
|
1787
|
+
}
|
|
1788
|
+
async #readFileBytes(file) {
|
|
1789
|
+
if (!file.bytes) {
|
|
1790
|
+
file.bytes = await readGitHubFile(this.#client, {
|
|
1791
|
+
mode: gitHubFileMode(file.metadata),
|
|
1792
|
+
path: joinGitPath(this.#root, file.path),
|
|
1793
|
+
sha: file.gitSha
|
|
1794
|
+
}, this.#baselineRefSha);
|
|
1795
|
+
file.size = file.bytes.byteLength;
|
|
1796
|
+
}
|
|
1797
|
+
return file.bytes;
|
|
1798
|
+
}
|
|
1799
|
+
async #fileMetadata(file) {
|
|
1800
|
+
if (gitHubFileMode(file.metadata) !== "120000" || readStringMetadata(file.metadata, "symlinkTarget") !== void 0) return file.metadata;
|
|
1801
|
+
return {
|
|
1802
|
+
...file.metadata,
|
|
1803
|
+
symlinkTarget: gitSymlinkTargetFromBytes(await this.#readFileBytes(file))
|
|
1804
|
+
};
|
|
1805
|
+
}
|
|
1806
|
+
async #listEntries(prefix, options, resolveSymlinks = true) {
|
|
1807
|
+
const entries = /* @__PURE__ */ new Map();
|
|
1808
|
+
for (const file of this.#files.values()) {
|
|
1809
|
+
if (isReservedWorkspacePath(file.path) || isExcludedWorkspacePath(file.path, options.exclude)) continue;
|
|
1810
|
+
for (const dir of parentDirectories(file.path)) {
|
|
1811
|
+
if (isExcludedWorkspacePath(dir, options.exclude)) continue;
|
|
1812
|
+
if (this.#entryInPrefix(dir, prefix, options)) entries.set(dir, {
|
|
1813
|
+
path: dir,
|
|
1814
|
+
type: "directory"
|
|
1815
|
+
});
|
|
1816
|
+
}
|
|
1817
|
+
if (this.#entryInPrefix(file.path, prefix, options)) entries.set(file.path, await this.#fileEntry(file, resolveSymlinks));
|
|
1818
|
+
}
|
|
1819
|
+
return [...entries.values()].sort((a, b) => a.path.localeCompare(b.path));
|
|
1820
|
+
}
|
|
1821
|
+
#entryInPrefix(path, prefix, options) {
|
|
1822
|
+
if (!prefix) return options.recursive || !path.includes("/");
|
|
1823
|
+
if (path === prefix) return false;
|
|
1824
|
+
if (!path.startsWith(`${prefix}/`)) return false;
|
|
1825
|
+
return options.recursive || !path.slice(prefix.length + 1).includes("/");
|
|
1826
|
+
}
|
|
1827
|
+
async #fileEntry(file, resolveSymlinks = true) {
|
|
1828
|
+
return {
|
|
1829
|
+
digest: file.gitSha,
|
|
1830
|
+
mediaType: file.mediaType,
|
|
1831
|
+
metadata: resolveSymlinks ? await this.#fileMetadata(file) : file.metadata,
|
|
1832
|
+
path: file.path,
|
|
1833
|
+
size: file.size,
|
|
1834
|
+
type: "file"
|
|
1835
|
+
};
|
|
1836
|
+
}
|
|
1837
|
+
#directoryExists(path) {
|
|
1838
|
+
return this.#publicDescendants(path).length > 0;
|
|
1839
|
+
}
|
|
1840
|
+
#publicDescendants(path) {
|
|
1841
|
+
return [...this.#files.keys()].filter((key) => !isReservedWorkspacePath(key) && key.startsWith(`${path}/`));
|
|
1842
|
+
}
|
|
1843
|
+
#metaPath(key) {
|
|
1844
|
+
const normalized = normalizeSafeWorkspacePath(key.endsWith(".json") ? key : `${key}.json`, { allowReserved: true });
|
|
1845
|
+
return normalizeSafeWorkspacePath(`.vitehub/meta/${normalized}`, { allowReserved: true });
|
|
1846
|
+
}
|
|
1847
|
+
#toRemoteFiles() {
|
|
1848
|
+
return new Map([...this.#files.values()].map((file) => [file.path, {
|
|
1849
|
+
mode: gitHubFileMode(file.metadata),
|
|
1850
|
+
path: joinGitPath(this.#root, file.path),
|
|
1851
|
+
sha: file.gitSha,
|
|
1852
|
+
size: file.size
|
|
1853
|
+
}]));
|
|
1854
|
+
}
|
|
1855
|
+
async #toRemoteMetadataFiles() {
|
|
1856
|
+
const entries = await Promise.all([...this.#files.values()].map(async (file) => {
|
|
1857
|
+
const bytes = fileAttributesBytes(file);
|
|
1858
|
+
if (!bytes) return void 0;
|
|
1859
|
+
return [fileMetadataPath(file.path), {
|
|
1860
|
+
mode: "100644",
|
|
1861
|
+
path: joinGitPath(this.#root, fileMetadataPath(file.path)),
|
|
1862
|
+
sha: await gitBlobSha(bytes),
|
|
1863
|
+
size: bytes.byteLength
|
|
1864
|
+
}];
|
|
1865
|
+
}));
|
|
1866
|
+
return new Map(entries.filter((entry) => entry !== void 0));
|
|
1867
|
+
}
|
|
1868
|
+
};
|
|
1869
|
+
function createGitHubWorkspaceStore(options, workspaceName) {
|
|
1870
|
+
return new GitHubWorkspaceStore(options, workspaceName);
|
|
1871
|
+
}
|
|
1872
|
+
//#endregion
|
|
1873
|
+
export { forwardWorkspaceRevisionMaterializer as n, resolveWorkspaceRevisionMaterializer as r, createGitHubWorkspaceStore as t };
|