@vite-hub/workspace 0.1.0 → 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 +164 -107
- package/dist/abort-BCwpdrN0.js +32 -0
- package/dist/blob-database.d.ts +70 -117
- package/dist/blob-database.js +48 -41
- package/dist/checkout.d.ts +128 -0
- package/dist/checkout.js +849 -0
- package/dist/cloudflare.d.ts +2 -2
- package/dist/cloudflare.js +1 -1
- package/dist/config-B-863EgC.js +15 -0
- package/dist/{config-B7dmzDX3.js → config-BAgL2dtB.js} +48 -84
- package/dist/{config-DLKdaFWN.d.ts → config-BQKcPawI.d.ts} +1 -1
- 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-C7Px8uaC.js → files-BOo4SbwE.js} +2 -2
- package/dist/files.d.ts +38 -0
- package/dist/files.js +6 -0
- package/dist/{github-CPxHtFB7.js → github-CrYp4v8k.js} +32 -5
- package/dist/{glob--XcLlcml.js → glob-B8YGvTrZ.js} +4 -5
- package/dist/{glob--kNYDbfU.js → glob-Cjxms1t7.js} +1 -1
- package/dist/{host-CFnrTXTK.js → host-BFBpXn0N.js} +58 -47
- package/dist/{hosted-acMA5XyL.js → hosted-KcUR_jPv.js} +216 -93
- package/dist/hosted-vercel-blob-B3-wRdUm.js +410 -0
- package/dist/hosted-vercel-blob.d.ts +2 -2
- package/dist/hosted-vercel-blob.js +1 -1
- package/dist/hosted.d.ts +5 -3
- package/dist/hosted.js +2 -2
- package/dist/index.d.ts +9 -51
- package/dist/index.js +21 -91
- package/dist/{lifecycle-BwZ7c9hb.js → lifecycle-B-enk_4A.js} +8 -8
- package/dist/lineage.d.ts +26 -0
- package/dist/lineage.js +76 -0
- package/dist/loader.d.ts +1 -1
- package/dist/loader.js +2 -2
- package/dist/{mcp-resources-BREFCmtn.js → mcp-resources-DF0F5rcL.js} +2 -2
- package/dist/{memory-BbwOqDXl.js → memory-BOexthyW.js} +3 -4
- package/dist/{metadata-target-DZEZQGHA.js → metadata-target-CWz6KHKq.js} +17 -16
- 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 +41 -4
- package/dist/operations.js +3 -2
- package/dist/{path-CNAwN7pw.js → path--wrT_Azm.js} +2 -3
- package/dist/path-AxMho1wo.d.ts +7 -0
- package/dist/{plugins-DqQ8b4T5.d.ts → plugins-C8C0auoW.d.ts} +1 -1
- package/dist/{provider-kXjfli9u.js → provider-9s4Ufkm5.js} +104 -82
- package/dist/providers/github/store.d.ts +1 -1
- package/dist/providers/github/store.js +1 -1
- package/dist/registry-B3BBm4Ts.d.ts +19 -0
- package/dist/{registry-Bp-8UUfG.js → registry-CNphafBx.js} +55 -20
- 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/{rolldown-runtime-B4iAMlE-.js → rolldown-runtime-rQ84J-ij.js} +2 -3
- package/dist/runtime/assets.d.ts +1 -1
- package/dist/runtime/assets.js +3 -3
- package/dist/runtime/empty-assets-registry.d.ts +1 -1
- package/dist/runtime/empty-registry.d.ts +2 -1
- 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 +9 -8
- package/dist/runtime.js +23 -26
- package/dist/{search-CrTmXj5h.js → search-C_RfoM2j.js} +2 -2
- package/dist/{server-BNQ-Nbjj.js → server-8tGltlGz.js} +53 -40
- package/dist/server.d.ts +17 -8
- package/dist/server.js +1 -1
- package/dist/shared-B3_EUk89.js +848 -0
- package/dist/source-metadata.d.ts +6 -2
- package/dist/source-metadata.js +8 -8
- package/dist/state-BISnUf1s.d.ts +35 -0
- package/dist/{ai-BZyLwULx.js → state-DbrW-njQ.js} +96 -54
- package/dist/{store-CXgmu-uw.js → store-ybhyD38Z.js} +250 -106
- package/dist/{sync-CN6ec-5M.js → sync-CCD_VYC8.js} +4 -4
- package/dist/target-jWhTdIuF.js +89 -0
- package/dist/test.d.ts +1 -1
- package/dist/test.js +1 -1
- package/dist/{types-DeK9GIxy.d.ts → types-BbtwmBZ5.d.ts} +68 -14
- package/dist/use-C6lV3-wC.d.ts +321 -0
- package/dist/{use-BQj7nSz6.js → use-CSpT5W87.js} +75 -82
- package/dist/{utils-Blrh4N2n.js → utils-CgMZCHsX.js} +112 -41
- package/dist/vite.d.ts +585 -2
- package/dist/vite.js +21368 -1
- package/dist/{workspace-BWJQBK1u.d.ts → workspace-CYB2xZ1T.d.ts} +1 -1
- package/dist/{workspace-6pxkOuxr.js → workspace-sPWn2Jxj.js} +125 -40
- package/package.json +46 -55
- package/dist/ai-BW2ZhizI.d.ts +0 -177
- package/dist/ai.d.ts +0 -3
- package/dist/ai.js +0 -2
- package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +0 -19
- package/dist/error-diagnostics-A_8Kp-48.js +0 -116
- package/dist/error-diagnostics-DY5GP47p.js +0 -96
- package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +0 -354
- package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +0 -214
- package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +0 -527
- package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +0 -248
- package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +0 -179
- package/dist/file-C0_aPWSS.js +0 -26
- package/dist/file-metadata-CxDy-E2H.js +0 -58
- package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +0 -2278
- package/dist/github-DtncTfmv-Du2S8lGF.js +0 -4159
- package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +0 -2530
- package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +0 -489
- package/dist/hosted-vercel-blob-DKntsHaf.js +0 -12603
- package/dist/inspect-BoObD2cJ.js +0 -167
- package/dist/mountx.d.ts +0 -8
- package/dist/mountx.js +0 -145
- package/dist/nitro.d.ts +0 -2
- package/dist/nitro.js +0 -2
- package/dist/nuxt.d.ts +0 -27
- package/dist/nuxt.js +0 -38
- package/dist/operations-BcpWr41m.js +0 -159
- package/dist/operations-CGqY1XeG.js +0 -965
- package/dist/operations-DnOwKsJT.d.ts +0 -136
- package/dist/registry-Cg1TJVVZ.d.ts +0 -10
- package/dist/request-execution-Dk9rY-Yh.js +0 -84
- package/dist/shared-DalXdP0i.js +0 -2158
- package/dist/state-B8zbLi5t.d.ts +0 -26
- package/dist/target-D4Bqb1eH.js +0 -11
- package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +0 -125
- package/dist/token-CO62GglH.js +0 -61
- package/dist/use-DhwhbAVV.d.ts +0 -108
- package/dist/vite-BEvgU2GY.js +0 -20909
- package/dist/vite-CcZmMQ7S.d.ts +0 -476
- package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +0 -1565
|
@@ -0,0 +1,848 @@
|
|
|
1
|
+
import { a as workspaceConflict, s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
|
|
2
|
+
import { l as normalizeWorkspacePath } from "./path--wrT_Azm.js";
|
|
3
|
+
import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CtKjGtGb.js";
|
|
4
|
+
import { t as internalErrorDiagnostics } from "./error-diagnostics-DSkCJC_L.js";
|
|
5
|
+
import { t as abortable } from "./abort-BCwpdrN0.js";
|
|
6
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
7
|
+
import { gunzipSync } from "node:zlib";
|
|
8
|
+
//#region ../internal/src/forge.ts
|
|
9
|
+
/**
|
|
10
|
+
* Server Env of each Forge, keyed by the `env.server.<forge>.<field>` path.
|
|
11
|
+
* Channels, Capabilities, Workspaces and Sources read the same names.
|
|
12
|
+
* `FORGES_*` names are the ones that `forgesFromEnv()` in the `forges` library reads.
|
|
13
|
+
* Fields without a `forges` equivalent have only a `VITEHUB_` name.
|
|
14
|
+
*/
|
|
15
|
+
const forgeEnv = {
|
|
16
|
+
github: {
|
|
17
|
+
appId: { names: ["VITEHUB_GITHUB_APP_ID", "FORGES_GITHUB_APP_ID"] },
|
|
18
|
+
installationId: { names: ["VITEHUB_GITHUB_INSTALLATION_ID", "FORGES_GITHUB_INSTALLATION_ID"] },
|
|
19
|
+
appOwner: { names: ["VITEHUB_GITHUB_APP_OWNER"] },
|
|
20
|
+
appInstallations: { names: ["VITEHUB_GITHUB_APP_INSTALLATIONS"] },
|
|
21
|
+
privateKey: {
|
|
22
|
+
names: ["VITEHUB_GITHUB_PRIVATE_KEY", "FORGES_GITHUB_PRIVATE_KEY"],
|
|
23
|
+
secret: true
|
|
24
|
+
},
|
|
25
|
+
privateKeyPath: { names: ["VITEHUB_GITHUB_PRIVATE_KEY_PATH"] },
|
|
26
|
+
token: {
|
|
27
|
+
names: ["VITEHUB_GITHUB_TOKEN", "FORGES_GITHUB_TOKEN"],
|
|
28
|
+
secret: true
|
|
29
|
+
},
|
|
30
|
+
webhookSecret: {
|
|
31
|
+
names: ["VITEHUB_GITHUB_WEBHOOK_SECRET", "FORGES_GITHUB_WEBHOOK_SECRET"],
|
|
32
|
+
secret: true
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
gitlab: {
|
|
36
|
+
baseUrl: { names: ["VITEHUB_GITLAB_BASE_URL", "FORGES_GITLAB_BASE_URL"] },
|
|
37
|
+
token: {
|
|
38
|
+
names: ["VITEHUB_GITLAB_TOKEN", "FORGES_GITLAB_TOKEN"],
|
|
39
|
+
secret: true
|
|
40
|
+
},
|
|
41
|
+
webhookSecret: {
|
|
42
|
+
names: ["VITEHUB_GITLAB_WEBHOOK_SECRET", "FORGES_GITLAB_WEBHOOK_SECRET"],
|
|
43
|
+
secret: true
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
forgejo: {
|
|
47
|
+
baseUrl: { names: ["VITEHUB_FORGEJO_BASE_URL", "FORGES_FORGEJO_BASE_URL"] },
|
|
48
|
+
token: {
|
|
49
|
+
names: ["VITEHUB_FORGEJO_TOKEN", "FORGES_FORGEJO_TOKEN"],
|
|
50
|
+
secret: true
|
|
51
|
+
},
|
|
52
|
+
webhookSecret: {
|
|
53
|
+
names: ["VITEHUB_FORGEJO_WEBHOOK_SECRET", "FORGES_FORGEJO_WEBHOOK_SECRET"],
|
|
54
|
+
secret: true
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* The first value of `field` that is set, in its lookup order.
|
|
60
|
+
* `env` is a record, such as `process.env`, or a reader, such as a Cloudflare binding lookup. Default: `process.env`.
|
|
61
|
+
*/
|
|
62
|
+
function readForgeEnv(field, env = globalThis.process?.env ?? {}) {
|
|
63
|
+
for (const name of field.names) {
|
|
64
|
+
const value = typeof env === "function" ? env(name) : env[name];
|
|
65
|
+
if (typeof value !== "string") continue;
|
|
66
|
+
const trimmed = value.trim();
|
|
67
|
+
if (trimmed) return trimmed;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** The HTTP status of a failed Forge request, or undefined for other errors. */
|
|
71
|
+
function forgeErrorStatus(error) {
|
|
72
|
+
if (!(error instanceof Error) || !("status" in error)) return void 0;
|
|
73
|
+
return typeof error.status === "number" ? error.status : void 0;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The error for a failed `import("@vite-hub/forge")`, an optional peer of Channels, Workspaces, and Sources. When the
|
|
77
|
+
* app did not install Forge, it is a coded error that names the install command. Otherwise it is the load error itself.
|
|
78
|
+
* `feature` names what needs Forge, such as `A GitHub Workspace`.
|
|
79
|
+
*
|
|
80
|
+
* Call it in the `catch` of a `try` that holds the import itself, in the calling package. esbuild, and so Wrangler and
|
|
81
|
+
* Netlify, then keep an import that does not resolve for run time instead of failing the build.
|
|
82
|
+
*/
|
|
83
|
+
function forgeImportError(error, feature) {
|
|
84
|
+
if (!isMissingForge(error)) return error;
|
|
85
|
+
return internalErrorDiagnostics.INTERNAL_FORGE_NOT_INSTALLED({
|
|
86
|
+
cause: error,
|
|
87
|
+
feature
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
function isMissingForge(error) {
|
|
91
|
+
return error instanceof Error && /(?:cannot find (?:package|module)|no such module|could not resolve) ['"]@vite-hub\/forge['"]/i.test(error.message);
|
|
92
|
+
}
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region ../internal/src/runtime/cloudflare-env-lookup.ts
|
|
95
|
+
/** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
|
|
96
|
+
const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
|
|
97
|
+
let activeEnv;
|
|
98
|
+
function setInstalledCloudflareEnv(env) {
|
|
99
|
+
activeEnv = env;
|
|
100
|
+
}
|
|
101
|
+
/** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
|
|
102
|
+
function getScopedCloudflareEnv() {
|
|
103
|
+
return globalThis[activeEnvStorageKey]?.getStore();
|
|
104
|
+
}
|
|
105
|
+
function getActiveCloudflareEnv() {
|
|
106
|
+
const scoped = getScopedCloudflareEnv();
|
|
107
|
+
if (scoped) return scoped.env;
|
|
108
|
+
const host = globalThis;
|
|
109
|
+
return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
|
|
110
|
+
}
|
|
111
|
+
//#endregion
|
|
112
|
+
//#region ../internal/src/runtime/cloudflare-env.ts
|
|
113
|
+
const runtimeGlobal = globalThis;
|
|
114
|
+
const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
|
|
115
|
+
const globalEnvProbe = Symbol("vitehub.cloudflare.global-env-probe");
|
|
116
|
+
/**
|
|
117
|
+
* Under the Nitro Cloudflare dev server, `cloudflare:workers` exports unenv's env proxy, which reads every key from
|
|
118
|
+
* `globalThis.__env__`. Storing that proxy in `__env__` makes it read itself, and the next read overflows the stack.
|
|
119
|
+
*/
|
|
120
|
+
function readsGlobalEnv(env) {
|
|
121
|
+
const scope = globalThis;
|
|
122
|
+
const owned = Object.hasOwn(scope, "__env__");
|
|
123
|
+
const previous = scope.__env__;
|
|
124
|
+
scope.__env__ = { [globalEnvProbe]: true };
|
|
125
|
+
try {
|
|
126
|
+
return Reflect.get(env, globalEnvProbe) === true;
|
|
127
|
+
} catch {
|
|
128
|
+
return false;
|
|
129
|
+
} finally {
|
|
130
|
+
if (owned) scope.__env__ = previous;
|
|
131
|
+
else delete scope.__env__;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function setActiveCloudflareEnv(env) {
|
|
135
|
+
setInstalledCloudflareEnv(env);
|
|
136
|
+
if (!env || !readsGlobalEnv(env)) globalThis.__env__ = env;
|
|
137
|
+
try {
|
|
138
|
+
activeEnvStorage.enterWith({ env });
|
|
139
|
+
} catch {}
|
|
140
|
+
}
|
|
141
|
+
function getActiveCloudflareBinding(name) {
|
|
142
|
+
const env = getActiveCloudflareEnv();
|
|
143
|
+
return env && Object.hasOwn(env, name) ? env[name] : void 0;
|
|
144
|
+
}
|
|
145
|
+
//#endregion
|
|
146
|
+
//#region src/providers/github/bounded-map.ts
|
|
147
|
+
/** A Map that keeps the `limit` most recently used entries. */
|
|
148
|
+
var BoundedMap = class extends Map {
|
|
149
|
+
limit;
|
|
150
|
+
constructor(limit) {
|
|
151
|
+
super();
|
|
152
|
+
this.limit = limit;
|
|
153
|
+
}
|
|
154
|
+
get(key) {
|
|
155
|
+
if (!super.has(key)) return void 0;
|
|
156
|
+
const value = super.get(key);
|
|
157
|
+
super.delete(key);
|
|
158
|
+
super.set(key, value);
|
|
159
|
+
return value;
|
|
160
|
+
}
|
|
161
|
+
set(key, value) {
|
|
162
|
+
super.delete(key);
|
|
163
|
+
super.set(key, value);
|
|
164
|
+
for (const oldest of super.keys()) {
|
|
165
|
+
if (this.size <= this.limit) break;
|
|
166
|
+
super.delete(oldest);
|
|
167
|
+
}
|
|
168
|
+
return this;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
//#endregion
|
|
172
|
+
//#region src/providers/github/cache.ts
|
|
173
|
+
/** How long a kept answer stays in KV, in seconds. A commit that nobody reads for a week leaves KV. */
|
|
174
|
+
const kvTTL = 604800;
|
|
175
|
+
const stats = {
|
|
176
|
+
requests: 0,
|
|
177
|
+
notModified: 0,
|
|
178
|
+
memory: 0,
|
|
179
|
+
kv: 0
|
|
180
|
+
};
|
|
181
|
+
let installedKV;
|
|
182
|
+
const maxMemoryBytes = 12582912;
|
|
183
|
+
function createGitHubReadMemory() {
|
|
184
|
+
return {
|
|
185
|
+
conditional: new BoundedMap(256),
|
|
186
|
+
immutable: new BoundedMap(Number.MAX_SAFE_INTEGER),
|
|
187
|
+
immutableBytes: 0
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
const keptHeaders = [
|
|
191
|
+
"content-type",
|
|
192
|
+
"etag",
|
|
193
|
+
"link"
|
|
194
|
+
];
|
|
195
|
+
/** The largest answer that goes to KV. Cloudflare KV takes up to 25 MiB a value. */
|
|
196
|
+
const maxStoredBytes = 16777216;
|
|
197
|
+
const sha = "[0-9a-f]{40}";
|
|
198
|
+
const immutablePaths = [
|
|
199
|
+
new RegExp(`/repos/[^/]+/[^/]+/git/(?:trees|commits)/${sha}$`, "i"),
|
|
200
|
+
new RegExp(`/repos/[^/]+/[^/]+/commits/${sha}$`, "i"),
|
|
201
|
+
new RegExp(`/repos/[^/]+/[^/]+/compare/${sha}\\.\\.\\.${sha}$`, "i")
|
|
202
|
+
];
|
|
203
|
+
const commitList = /\/repos\/[^/]+\/[^/]+\/commits$/;
|
|
204
|
+
const shaPattern = new RegExp(`^${sha}$`, "i");
|
|
205
|
+
/**
|
|
206
|
+
* Give the GitHub Store a shared KV store for the GitHub answers that never change. The Content build calls it with
|
|
207
|
+
* ViteHub KV when the app enables KV; without it, each server instance asks GitHub again after it starts.
|
|
208
|
+
*/
|
|
209
|
+
function registerWorkspaceKV(store) {
|
|
210
|
+
installedKV = store;
|
|
211
|
+
}
|
|
212
|
+
/** The reads of the GitHub Store in this server instance, for tests and inspection. */
|
|
213
|
+
function readGitHubReadStats() {
|
|
214
|
+
return { ...stats };
|
|
215
|
+
}
|
|
216
|
+
/** Whether the answer for `url` can never change: it names a commit or tree sha. */
|
|
217
|
+
function isImmutableGitHubUrl(url) {
|
|
218
|
+
if (immutablePaths.some((pattern) => pattern.test(url.pathname))) return true;
|
|
219
|
+
return commitList.test(url.pathname) && shaPattern.test(url.searchParams.get("sha") ?? "");
|
|
220
|
+
}
|
|
221
|
+
async function hash(text) {
|
|
222
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
223
|
+
return [...new Uint8Array(digest).slice(0, 16)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
224
|
+
}
|
|
225
|
+
/** The KV key of an answer, such as `workspace:github:onmax/repo:3f2a…`. */
|
|
226
|
+
async function githubKVKey(scope, id) {
|
|
227
|
+
return `workspace:github:${scope}:${await hash(id)}`;
|
|
228
|
+
}
|
|
229
|
+
function repositoryOf(url) {
|
|
230
|
+
return /\/repos\/([^/]+\/[^/]+)/.exec(url.pathname)?.[1] ?? url.host;
|
|
231
|
+
}
|
|
232
|
+
function answer(stored) {
|
|
233
|
+
const body = stored.encoding === "base64" ? fromBase64(stored.body) : stored.body;
|
|
234
|
+
return new Response(body, {
|
|
235
|
+
status: 200,
|
|
236
|
+
headers: stored.headers
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
async function store(response) {
|
|
240
|
+
const headers = {};
|
|
241
|
+
for (const name of keptHeaders) {
|
|
242
|
+
const value = response.headers.get(name);
|
|
243
|
+
if (value) headers[name] = value;
|
|
244
|
+
}
|
|
245
|
+
const body = await response.text();
|
|
246
|
+
if (body.length > maxStoredBytes) return void 0;
|
|
247
|
+
return {
|
|
248
|
+
body,
|
|
249
|
+
headers,
|
|
250
|
+
...headers.etag ? { etag: headers.etag } : {}
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
/** Read a value from KV. A KV failure is a miss: the read goes to GitHub. */
|
|
254
|
+
async function readWorkspaceKV(key) {
|
|
255
|
+
if (!installedKV) return void 0;
|
|
256
|
+
try {
|
|
257
|
+
const [error, value] = await installedKV.get(key);
|
|
258
|
+
return error || value === null ? void 0 : value;
|
|
259
|
+
} catch {
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/** Write a value to KV. A failed write only costs a later read. */
|
|
264
|
+
async function writeWorkspaceKV(key, value) {
|
|
265
|
+
if (!installedKV) return;
|
|
266
|
+
try {
|
|
267
|
+
await installedKV.set(key, value, { ttl: kvTTL });
|
|
268
|
+
} catch {}
|
|
269
|
+
}
|
|
270
|
+
/** Whether a shared KV store is registered. */
|
|
271
|
+
function hasWorkspaceKV() {
|
|
272
|
+
return Boolean(installedKV);
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* `fetch` for one GitHub read, with the shared answers of immutable URLs and the ETag of other URLs. Other methods,
|
|
276
|
+
* other headers that change the answer, and non-200 answers pass through.
|
|
277
|
+
*/
|
|
278
|
+
async function fetchGitHubRead(memory, input, init, send) {
|
|
279
|
+
if ((init.method || "GET").toUpperCase() !== "GET" || input instanceof Request) return await counted(send(init));
|
|
280
|
+
const url = new URL(String(input));
|
|
281
|
+
const headers = new Headers(init.headers);
|
|
282
|
+
if (headers.has("range") || headers.has("if-none-match")) return await counted(send(init));
|
|
283
|
+
const id = `${url.href}\n${headers.get("accept") ?? ""}`;
|
|
284
|
+
if (isImmutableGitHubUrl(url)) {
|
|
285
|
+
const kept = memory.immutable.get(id);
|
|
286
|
+
if (kept) {
|
|
287
|
+
stats.memory++;
|
|
288
|
+
return answer(kept);
|
|
289
|
+
}
|
|
290
|
+
const key = installedKV ? await githubKVKey(repositoryOf(url), id) : void 0;
|
|
291
|
+
const shared = key ? await readWorkspaceKV(key) : void 0;
|
|
292
|
+
if (shared) {
|
|
293
|
+
stats.kv++;
|
|
294
|
+
remember(memory, id, shared);
|
|
295
|
+
return answer(shared);
|
|
296
|
+
}
|
|
297
|
+
const response = await counted(send(init));
|
|
298
|
+
if (response.status !== 200 || response.headers.get("content-type")?.includes("json") !== true) return response;
|
|
299
|
+
const stored = await store(response.clone());
|
|
300
|
+
if (stored) {
|
|
301
|
+
remember(memory, id, stored);
|
|
302
|
+
if (key) await writeWorkspaceKV(key, stored);
|
|
303
|
+
}
|
|
304
|
+
return response;
|
|
305
|
+
}
|
|
306
|
+
const previous = memory.conditional.get(id);
|
|
307
|
+
if (previous?.etag) headers.set("if-none-match", previous.etag);
|
|
308
|
+
const response = await counted(send({
|
|
309
|
+
...init,
|
|
310
|
+
headers
|
|
311
|
+
}));
|
|
312
|
+
if (previous && response.status === 304) {
|
|
313
|
+
stats.notModified++;
|
|
314
|
+
await response.body?.cancel().catch(() => void 0);
|
|
315
|
+
return answer(previous);
|
|
316
|
+
}
|
|
317
|
+
if (response.status === 200 && response.headers.get("etag") && response.headers.get("content-type")?.includes("json")) {
|
|
318
|
+
const stored = await store(response.clone());
|
|
319
|
+
if (stored && stored.body.length <= 1048576) memory.conditional.set(id, stored);
|
|
320
|
+
}
|
|
321
|
+
return response;
|
|
322
|
+
}
|
|
323
|
+
/** Keep an immutable answer in memory, the least recently used out first. */
|
|
324
|
+
function remember(memory, id, stored) {
|
|
325
|
+
if (stored.body.length > maxMemoryBytes / 4 || memory.immutable.has(id)) return;
|
|
326
|
+
memory.immutable.set(id, stored);
|
|
327
|
+
memory.immutableBytes += stored.body.length;
|
|
328
|
+
for (const [oldest, entry] of memory.immutable) {
|
|
329
|
+
if (memory.immutableBytes <= maxMemoryBytes) break;
|
|
330
|
+
memory.immutable.delete(oldest);
|
|
331
|
+
memory.immutableBytes -= entry.body.length;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
async function counted(response) {
|
|
335
|
+
stats.requests++;
|
|
336
|
+
return await response;
|
|
337
|
+
}
|
|
338
|
+
function toBase64(bytes) {
|
|
339
|
+
let binary = "";
|
|
340
|
+
for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
|
|
341
|
+
return btoa(binary);
|
|
342
|
+
}
|
|
343
|
+
function fromBase64(text) {
|
|
344
|
+
const binary = atob(text);
|
|
345
|
+
const bytes = new Uint8Array(binary.length);
|
|
346
|
+
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
|
|
347
|
+
return bytes;
|
|
348
|
+
}
|
|
349
|
+
//#endregion
|
|
350
|
+
//#region src/providers/github/tar.ts
|
|
351
|
+
const decoder = new TextDecoder();
|
|
352
|
+
function text(bytes) {
|
|
353
|
+
const end = bytes.indexOf(0);
|
|
354
|
+
return decoder.decode(end === -1 ? bytes : bytes.subarray(0, end));
|
|
355
|
+
}
|
|
356
|
+
/** The `path` record of a PAX header, which GitHub writes for paths longer than the ustar fields. */
|
|
357
|
+
function paxPath(content) {
|
|
358
|
+
let index = 0;
|
|
359
|
+
while (index < content.length) {
|
|
360
|
+
let space = index;
|
|
361
|
+
while (space < content.length && content[space] !== 32) space++;
|
|
362
|
+
const length = Number.parseInt(decoder.decode(content.subarray(index, space)), 10);
|
|
363
|
+
if (!Number.isSafeInteger(length) || length <= 0 || index + length > content.length) return void 0;
|
|
364
|
+
const record = decoder.decode(content.subarray(space + 1, index + length - 1));
|
|
365
|
+
if (record.startsWith("path=")) return record.slice(5);
|
|
366
|
+
index += length;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
/** The regular files of a GitHub `tar.gz` archive. Other entries, such as symlinks and folders, are left out. */
|
|
370
|
+
function readTarGz(archive) {
|
|
371
|
+
const tar = gunzipSync(archive);
|
|
372
|
+
const files = [];
|
|
373
|
+
let offset = 0;
|
|
374
|
+
let longPath;
|
|
375
|
+
while (offset + 512 <= tar.length) {
|
|
376
|
+
const header = tar.subarray(offset, offset + 512);
|
|
377
|
+
if (header.every((byte) => byte === 0)) break;
|
|
378
|
+
const size = Number.parseInt(text(header.subarray(124, 136)).trim() || "0", 8);
|
|
379
|
+
if (!Number.isSafeInteger(size) || size < 0) throw workspaceError("[vitehub] GitHub workspace returned a malformed archive.");
|
|
380
|
+
const start = offset + 512;
|
|
381
|
+
const end = start + Math.ceil(size / 512) * 512;
|
|
382
|
+
if (end > tar.length) throw workspaceError("[vitehub] GitHub workspace returned a malformed archive.");
|
|
383
|
+
const content = tar.subarray(start, start + size);
|
|
384
|
+
const type = String.fromCharCode(header[156] ?? 0);
|
|
385
|
+
if (type === "x") longPath = paxPath(content);
|
|
386
|
+
else {
|
|
387
|
+
if (type === "0" || type === "\0") {
|
|
388
|
+
const prefix = text(header.subarray(345, 500));
|
|
389
|
+
const name = longPath ?? [prefix, text(header.subarray(0, 100))].filter(Boolean).join("/");
|
|
390
|
+
const slash = name.indexOf("/");
|
|
391
|
+
if (slash > 0 && slash < name.length - 1) files.push({
|
|
392
|
+
path: name.slice(slash + 1),
|
|
393
|
+
content: new Uint8Array(content)
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
longPath = void 0;
|
|
397
|
+
}
|
|
398
|
+
offset = end;
|
|
399
|
+
}
|
|
400
|
+
return files;
|
|
401
|
+
}
|
|
402
|
+
//#endregion
|
|
403
|
+
//#region src/providers/github/shared.ts
|
|
404
|
+
const githubReadAttempts = 3;
|
|
405
|
+
function retryDelay(response, attempt) {
|
|
406
|
+
const retryAfter = response.headers.get("retry-after");
|
|
407
|
+
if (retryAfter) {
|
|
408
|
+
const seconds = Number(retryAfter);
|
|
409
|
+
if (Number.isFinite(seconds)) return Math.min(seconds * 1e3, 2e3);
|
|
410
|
+
const date = Date.parse(retryAfter);
|
|
411
|
+
if (Number.isFinite(date)) return Math.min(Math.max(date - Date.now(), 0), 2e3);
|
|
412
|
+
}
|
|
413
|
+
return 100 * 2 ** attempt;
|
|
414
|
+
}
|
|
415
|
+
async function waitForRetry(delay, signal) {
|
|
416
|
+
signal?.throwIfAborted();
|
|
417
|
+
await new Promise((resolve, reject) => {
|
|
418
|
+
const aborted = () => {
|
|
419
|
+
clearTimeout(timeout);
|
|
420
|
+
reject(signal?.reason || new DOMException("The operation was aborted.", "AbortError"));
|
|
421
|
+
};
|
|
422
|
+
const timeout = setTimeout(() => {
|
|
423
|
+
signal?.removeEventListener("abort", aborted);
|
|
424
|
+
resolve();
|
|
425
|
+
}, delay);
|
|
426
|
+
signal?.addEventListener("abort", aborted, { once: true });
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* `fetch` that retries reads after a network error, a 429 or a 5xx response, and reuses answers that did not change
|
|
431
|
+
* (`cache.ts`). The Forge provider sends every request through it.
|
|
432
|
+
*/
|
|
433
|
+
async function requestGitHub(input, init = {}, memory = createGitHubReadMemory()) {
|
|
434
|
+
return await fetchGitHubRead(memory, input, init, async (request) => await sendGitHub(input, request));
|
|
435
|
+
}
|
|
436
|
+
async function sendGitHub(input, init) {
|
|
437
|
+
const method = (init.method || "GET").toUpperCase();
|
|
438
|
+
const retryable = method === "GET" || method === "HEAD";
|
|
439
|
+
for (let attempt = 0;; attempt++) {
|
|
440
|
+
init.signal?.throwIfAborted();
|
|
441
|
+
let response;
|
|
442
|
+
try {
|
|
443
|
+
response = await fetch(input, init);
|
|
444
|
+
} catch (error) {
|
|
445
|
+
if (!retryable || init.signal?.aborted || attempt + 1 >= githubReadAttempts) throw error;
|
|
446
|
+
await waitForRetry(100 * 2 ** attempt, init.signal);
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
if (!retryable || response.status !== 429 && response.status < 500 || attempt + 1 >= githubReadAttempts) return response;
|
|
450
|
+
await response.body?.cancel().catch(() => void 0);
|
|
451
|
+
await waitForRetry(retryDelay(response, attempt), init.signal);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
/** `@vite-hub/forge`, an optional peer. A GitHub Workspace loads it on its first request. */
|
|
455
|
+
async function loadForge() {
|
|
456
|
+
try {
|
|
457
|
+
return await import("@vite-hub/forge");
|
|
458
|
+
} catch (error) {
|
|
459
|
+
throw forgeImportError(error, "A GitHub Workspace");
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* A lazy connection: the repository name is checked on the first request. A GitHub App credential mints an
|
|
464
|
+
* installation token for the repository, keeps it until a minute before it expires, then mints the next one.
|
|
465
|
+
*/
|
|
466
|
+
function connectGitHubRepository(repository, credential) {
|
|
467
|
+
const signIn = typeof credential === "string" ? { token: credential } : credential;
|
|
468
|
+
let provider;
|
|
469
|
+
const memory = createGitHubReadMemory();
|
|
470
|
+
const fetch = async (input, init) => await requestGitHub(input, init, memory);
|
|
471
|
+
const token = async () => {
|
|
472
|
+
if ("token" in signIn) return signIn.token;
|
|
473
|
+
const [error, minted] = await (await signIn.app()).token({ repository });
|
|
474
|
+
if (error) throw workspaceError(`[vitehub] GitHub workspace could not get a GitHub App token for ${repository}: ${error.message}`, { cause: error });
|
|
475
|
+
return minted.token;
|
|
476
|
+
};
|
|
477
|
+
return {
|
|
478
|
+
name: repository,
|
|
479
|
+
blobReadKey: (sha) => JSON.stringify([
|
|
480
|
+
repository,
|
|
481
|
+
"token" in signIn ? signIn.token : "app",
|
|
482
|
+
sha
|
|
483
|
+
]),
|
|
484
|
+
provider: async () => {
|
|
485
|
+
splitGitHubRepository(repository);
|
|
486
|
+
const current = await token();
|
|
487
|
+
if (provider?.token !== current) {
|
|
488
|
+
const next = {
|
|
489
|
+
token: current,
|
|
490
|
+
provider: loadForge().then(async ({ forgeProvider }) => await forgeProvider({
|
|
491
|
+
fetch,
|
|
492
|
+
forge: "github",
|
|
493
|
+
token: current,
|
|
494
|
+
userAgent: "vitehub-workspace",
|
|
495
|
+
conditionalRequests: false
|
|
496
|
+
}))
|
|
497
|
+
};
|
|
498
|
+
next.provider.catch(() => {
|
|
499
|
+
if (provider === next) provider = void 0;
|
|
500
|
+
});
|
|
501
|
+
provider = next;
|
|
502
|
+
}
|
|
503
|
+
return await provider.provider;
|
|
504
|
+
},
|
|
505
|
+
ref: (client) => {
|
|
506
|
+
const { owner, repo } = splitGitHubRepository(repository);
|
|
507
|
+
return {
|
|
508
|
+
forge: client.forge,
|
|
509
|
+
instance: client.instance,
|
|
510
|
+
name: repo,
|
|
511
|
+
owner
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Run one Forge call. A failed request becomes a Workspace error that keeps the Forge error as its cause.
|
|
518
|
+
* With `response`, a `TypeError` from the Forge response mapping becomes a malformed `response` error.
|
|
519
|
+
*/
|
|
520
|
+
async function githubRequest(repository, run, response) {
|
|
521
|
+
const provider = await repository.provider();
|
|
522
|
+
try {
|
|
523
|
+
return await run(provider, repository.ref(provider));
|
|
524
|
+
} catch (error) {
|
|
525
|
+
const status = forgeErrorStatus(error);
|
|
526
|
+
if (status === void 0 && response && error instanceof TypeError) throw workspaceError(`[vitehub] GitHub workspace returned a malformed ${response} response.`, { cause: error });
|
|
527
|
+
if (status === void 0) throw error;
|
|
528
|
+
throw workspaceError(`[vitehub] GitHub workspace request failed for ${repository.name}: ${status} ${error instanceof Error ? error.message : ""}`.trim(), { cause: error });
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
/** The HTTP status of the GitHub request behind a Workspace error. */
|
|
532
|
+
function githubRequestStatus(error) {
|
|
533
|
+
return forgeErrorStatus(error) ?? (error instanceof Error ? forgeErrorStatus(error.cause) : void 0);
|
|
534
|
+
}
|
|
535
|
+
function githubBranchMovedConflict(input) {
|
|
536
|
+
return workspaceConflict(`[vitehub] GitHub Workspace Store conflict for ${input.repository}@${input.branch}: the branch moved after this Workspace Store loaded. Rebase from the current branch head and retry.`, { details: {
|
|
537
|
+
actualHead: input.actualHead,
|
|
538
|
+
branch: input.branch,
|
|
539
|
+
expectedHead: input.expectedHead,
|
|
540
|
+
repository: input.repository
|
|
541
|
+
} });
|
|
542
|
+
}
|
|
543
|
+
function resolveGitHubOption(value) {
|
|
544
|
+
const resolved = typeof value === "function" ? value() : value;
|
|
545
|
+
return typeof resolved === "string" ? resolved.trim() || void 0 : resolved;
|
|
546
|
+
}
|
|
547
|
+
function isMaskedGitHubTokenOption(value) {
|
|
548
|
+
return value === "********" || value === "<redacted>" || value === "[redacted]";
|
|
549
|
+
}
|
|
550
|
+
/** The first location value that is set, from the active Cloudflare bindings and then from `env`. */
|
|
551
|
+
function readLocationEnv(name, env) {
|
|
552
|
+
const binding = getActiveCloudflareBinding(name);
|
|
553
|
+
if (typeof binding === "string" && binding.trim()) return binding.trim();
|
|
554
|
+
return env[name]?.trim() || void 0;
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* The GitHub App of the Server Env, when `VITEHUB_GITHUB_APP_ID` is set: its installation tokens have a rate limit of
|
|
558
|
+
* their own, apart from the personal tokens of the people who share an account. Read from the active Cloudflare bindings,
|
|
559
|
+
* then from `env`. `useForge()` picks the installation of the repository owner, as `VITEHUB_GITHUB_APP_INSTALLATIONS` and
|
|
560
|
+
* `VITEHUB_GITHUB_APP_OWNER` set it.
|
|
561
|
+
*/
|
|
562
|
+
function readGitHubEnvApp(env = typeof process !== "undefined" ? process.env : {}) {
|
|
563
|
+
const lookup = (name) => getActiveCloudflareBinding(name) ?? env[name];
|
|
564
|
+
if (!readForgeEnv(forgeEnv.github.appId, lookup)) return void 0;
|
|
565
|
+
let forge;
|
|
566
|
+
return () => forge ??= loadForge().then(({ useForge }) => useForge({
|
|
567
|
+
env: lookup,
|
|
568
|
+
fetch: requestGitHub,
|
|
569
|
+
userAgent: "vitehub-workspace"
|
|
570
|
+
}));
|
|
571
|
+
}
|
|
572
|
+
/** The Server Env GitHub token: `VITEHUB_GITHUB_TOKEN`, then `FORGES_GITHUB_TOKEN`, from the active Cloudflare bindings and then from `env`. */
|
|
573
|
+
function readGitHubEnvToken(env = typeof process !== "undefined" ? process.env : {}) {
|
|
574
|
+
const binding = readForgeEnv(forgeEnv.github.token, (name) => getActiveCloudflareBinding(name));
|
|
575
|
+
if (binding && !isMaskedGitHubTokenOption(binding)) return binding;
|
|
576
|
+
return readForgeEnv(forgeEnv.github.token, env);
|
|
577
|
+
}
|
|
578
|
+
function requireGitHubOption(label, value) {
|
|
579
|
+
if (!value) throw workspaceErrorDiagnostics.WORKSPACE_R0072({ message: `[vitehub] GitHub workspace store requires ${label}.${label === "a token" ? " Set VITEHUB_GITHUB_TOKEN, the token option, or a GitHub App with VITEHUB_GITHUB_APP_ID and VITEHUB_GITHUB_PRIVATE_KEY." : label === "a repository" ? " Set the repository option or VITEHUB_WORKSPACE_GITHUB_REPOSITORY." : ""}` });
|
|
580
|
+
return value;
|
|
581
|
+
}
|
|
582
|
+
function splitGitHubRepository(repository) {
|
|
583
|
+
const parts = repository.split("/");
|
|
584
|
+
const owner = parts[0];
|
|
585
|
+
const repo = parts[1];
|
|
586
|
+
if (parts.length !== 2 || !owner || /[^A-Za-z0-9-]/.test(owner) || !repo || /[^A-Za-z0-9_.-]/.test(repo) || repo === "." || repo === "..") throw workspaceError("[vitehub] GitHub workspace store requires a repository in owner/repo format.");
|
|
587
|
+
return {
|
|
588
|
+
owner,
|
|
589
|
+
repo
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
function joinGitPath(...parts) {
|
|
593
|
+
return parts.join("/").replaceAll("\\", "/").split("/").filter(Boolean).join("/");
|
|
594
|
+
}
|
|
595
|
+
function resolveGitHubWorkspaceRoot(root, workspaceName) {
|
|
596
|
+
return normalizeSafeWorkspacePath(joinGitPath(root.replaceAll("<workspace>", workspaceName)), {
|
|
597
|
+
allowEmpty: true,
|
|
598
|
+
allowReserved: true
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
function workspacePathFromGitPath(path, root) {
|
|
602
|
+
const normalized = joinGitPath(path);
|
|
603
|
+
const normalizedRoot = joinGitPath(root);
|
|
604
|
+
if (!normalizedRoot) return normalizeWorkspacePath(normalized);
|
|
605
|
+
if (!normalized.startsWith(`${normalizedRoot}/`)) return void 0;
|
|
606
|
+
return normalizeWorkspacePath(normalized.slice(normalizedRoot.length + 1));
|
|
607
|
+
}
|
|
608
|
+
function toHex(bytes) {
|
|
609
|
+
return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
610
|
+
}
|
|
611
|
+
/** The Git blob sha of `bytes`. Workspace digests are Git blob shas, so local writes compare with the remote tree. */
|
|
612
|
+
async function gitBlobSha(bytes) {
|
|
613
|
+
const prefix = new TextEncoder().encode(`blob ${bytes.byteLength}\0`);
|
|
614
|
+
const input = new Uint8Array(prefix.byteLength + bytes.byteLength);
|
|
615
|
+
input.set(prefix);
|
|
616
|
+
input.set(bytes, prefix.byteLength);
|
|
617
|
+
return toHex(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-1", input)));
|
|
618
|
+
}
|
|
619
|
+
function gitFileMode(value) {
|
|
620
|
+
return value === "120000" || value === "100755" ? value : "100644";
|
|
621
|
+
}
|
|
622
|
+
function resolveGitHubRepositoryOption(options, env = typeof process !== "undefined" ? process.env : {}) {
|
|
623
|
+
return resolveGitHubOption(options.repository) || resolveGitHubOption(options.repo) || readLocationEnv("VITEHUB_WORKSPACE_GITHUB_REPOSITORY", env);
|
|
624
|
+
}
|
|
625
|
+
function resolveGitHubBranchOption(options, env = typeof process !== "undefined" ? process.env : {}) {
|
|
626
|
+
return resolveGitHubOption(options.branch) || readLocationEnv("VITEHUB_WORKSPACE_GITHUB_BRANCH", env) || "main";
|
|
627
|
+
}
|
|
628
|
+
function resolveGitHubRootOption(options, workspaceName, env = typeof process !== "undefined" ? process.env : {}) {
|
|
629
|
+
return resolveGitHubWorkspaceRoot(options.root === "" ? "" : resolveGitHubOption(options.root) || readLocationEnv("VITEHUB_WORKSPACE_GITHUB_ROOT", env) || ".vitehub/workspaces/<workspace>", workspaceName);
|
|
630
|
+
}
|
|
631
|
+
/** The branch names for the history refs `published` and `draft`, or undefined when there are none. */
|
|
632
|
+
function resolveGitHubRefsOption(options) {
|
|
633
|
+
const refs = options.refs;
|
|
634
|
+
if (!refs) return void 0;
|
|
635
|
+
const published = refs.published?.trim() || void 0;
|
|
636
|
+
const draft = refs.draft?.trim() || void 0;
|
|
637
|
+
if (published && published === draft) throw workspaceError(`[vitehub] GitHub workspace store refs.published and refs.draft name the same branch: ${published}.`);
|
|
638
|
+
return published || draft ? {
|
|
639
|
+
...published ? { published } : {},
|
|
640
|
+
...draft ? { draft } : {}
|
|
641
|
+
} : void 0;
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* How the Store signs in: the `token` option, else a GitHub App from `VITEHUB_GITHUB_APP_ID`, else
|
|
645
|
+
* `VITEHUB_GITHUB_TOKEN`. The App comes before the env token, the same order as `useForge()`.
|
|
646
|
+
*/
|
|
647
|
+
function resolveGitHubCredential(options, env = typeof process !== "undefined" ? process.env : {}) {
|
|
648
|
+
const token = resolveGitHubOption(options.token);
|
|
649
|
+
if (token && !isMaskedGitHubTokenOption(token)) return { token };
|
|
650
|
+
const app = readGitHubEnvApp(env);
|
|
651
|
+
if (app) return { app };
|
|
652
|
+
return { token: requireGitHubOption("a token", readGitHubEnvToken(env)) };
|
|
653
|
+
}
|
|
654
|
+
const githubBlobs = /* @__PURE__ */ new Map();
|
|
655
|
+
const githubBlobReads = /* @__PURE__ */ new Map();
|
|
656
|
+
const githubBlobByteLimit = 33554432;
|
|
657
|
+
const githubBlobFileLimit = 4194304;
|
|
658
|
+
let githubBlobBytes = 0;
|
|
659
|
+
/** Keep the bytes of a blob, the oldest out first. Different request scopes can finish the same blob; it counts once. */
|
|
660
|
+
function rememberGitHubBlob(sha, bytes) {
|
|
661
|
+
if (bytes.byteLength > githubBlobFileLimit || githubBlobs.has(sha)) return;
|
|
662
|
+
for (const [oldestSha, oldest] of githubBlobs) {
|
|
663
|
+
if (githubBlobBytes + bytes.byteLength <= githubBlobByteLimit) break;
|
|
664
|
+
githubBlobs.delete(oldestSha);
|
|
665
|
+
githubBlobBytes -= oldest.byteLength;
|
|
666
|
+
}
|
|
667
|
+
githubBlobs.set(sha, bytes);
|
|
668
|
+
githubBlobBytes += bytes.byteLength;
|
|
669
|
+
}
|
|
670
|
+
/** The bytes of one remote file. A symlink is read by its blob, so the bytes are the link target and not the file it points at. */
|
|
671
|
+
async function readGitHubFile(repository, entry, ref, signal) {
|
|
672
|
+
signal?.throwIfAborted();
|
|
673
|
+
const cached = githubBlobs.get(entry.sha);
|
|
674
|
+
if (cached) return cached.slice();
|
|
675
|
+
const readKey = repository.blobReadKey(entry.sha);
|
|
676
|
+
let read = githubBlobReads.get(readKey);
|
|
677
|
+
if (!read) {
|
|
678
|
+
read = githubRequest(repository, async (provider, repo) => {
|
|
679
|
+
const { forgeBlob } = await loadForge();
|
|
680
|
+
return await forgeBlob(provider, repo, entry.sha);
|
|
681
|
+
}).then(async (bytes) => {
|
|
682
|
+
if (await gitBlobSha(bytes) !== entry.sha) throw workspaceError("[vitehub] GitHub workspace returned a malformed blob response.");
|
|
683
|
+
rememberGitHubBlob(entry.sha, bytes);
|
|
684
|
+
return bytes;
|
|
685
|
+
}).finally(() => {
|
|
686
|
+
githubBlobReads.delete(readKey);
|
|
687
|
+
});
|
|
688
|
+
githubBlobReads.set(readKey, read);
|
|
689
|
+
}
|
|
690
|
+
return (await abortable(signal, "The GitHub read was aborted.", () => read)).slice();
|
|
691
|
+
}
|
|
692
|
+
/** The last archive that each repository connection read, by commit. */
|
|
693
|
+
const lastArchives = /* @__PURE__ */ new WeakMap();
|
|
694
|
+
/**
|
|
695
|
+
* The gzipped tarball of `ref`. The archive of a commit sha never changes, so the last one stays in memory and goes to
|
|
696
|
+
* the shared KV store, where another server instance reads it without a request.
|
|
697
|
+
*/
|
|
698
|
+
async function readGitHubArchive(repository, ref, signal) {
|
|
699
|
+
const pinned = /^[0-9a-f]{40}$/i.test(ref);
|
|
700
|
+
const last = lastArchives.get(repository);
|
|
701
|
+
if (pinned && last?.ref === ref) return (await abortable(signal, "The GitHub read was aborted.", () => last.bytes)).slice();
|
|
702
|
+
const read = (async () => {
|
|
703
|
+
const kvKey = pinned && hasWorkspaceKV() ? await githubKVKey(repository.name, `archive:${ref}`) : void 0;
|
|
704
|
+
const stored = kvKey ? await readWorkspaceKV(kvKey) : void 0;
|
|
705
|
+
if (stored) return fromBase64(stored);
|
|
706
|
+
const bytes = await githubRequest(repository, async (provider, repo) => {
|
|
707
|
+
const { forgeArchive } = await loadForge();
|
|
708
|
+
const stream = await forgeArchive(provider, repo, {
|
|
709
|
+
ref,
|
|
710
|
+
signal
|
|
711
|
+
});
|
|
712
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
713
|
+
});
|
|
714
|
+
if (kvKey && bytes.byteLength <= maxArchiveKVBytes) await writeWorkspaceKV(kvKey, toBase64(bytes));
|
|
715
|
+
return bytes;
|
|
716
|
+
})();
|
|
717
|
+
if (pinned) {
|
|
718
|
+
const entry = {
|
|
719
|
+
ref,
|
|
720
|
+
bytes: read
|
|
721
|
+
};
|
|
722
|
+
lastArchives.set(repository, entry);
|
|
723
|
+
read.catch(() => {
|
|
724
|
+
if (lastArchives.get(repository) === entry) lastArchives.delete(repository);
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
return (await abortable(signal, "The GitHub read was aborted.", () => read)).slice();
|
|
728
|
+
}
|
|
729
|
+
/** The largest archive that goes to KV, before base64. */
|
|
730
|
+
const maxArchiveKVBytes = 8388608;
|
|
731
|
+
/** Above this many blobs that are not in memory, one archive costs less than a request per blob. */
|
|
732
|
+
const archiveReadThreshold = 8;
|
|
733
|
+
/**
|
|
734
|
+
* Keep the bytes of many files of one commit in memory, so the next `readGitHubFile()` of each needs no request. Few
|
|
735
|
+
* files are read one by one. Many files come from one archive of the commit. A file whose archive bytes do not match its
|
|
736
|
+
* blob sha, such as a symlink, is left for `readGitHubFile()`.
|
|
737
|
+
*/
|
|
738
|
+
async function preloadGitHubFiles(repository, commit, entries, signal) {
|
|
739
|
+
const missing = entries.filter((entry) => !githubBlobs.has(entry.sha) && entry.mode !== "120000");
|
|
740
|
+
if (missing.length <= archiveReadThreshold) return;
|
|
741
|
+
const wanted = new Map(missing.map((entry) => [entry.path, entry]));
|
|
742
|
+
for (const file of readTarGz(await readGitHubArchive(repository, commit, signal))) {
|
|
743
|
+
const entry = wanted.get(file.path);
|
|
744
|
+
if (entry && await gitBlobSha(file.content) === entry.sha) rememberGitHubBlob(entry.sha, file.content);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
/** The files and symlinks of the tree at `ref`, by their Workspace path under `root`. */
|
|
748
|
+
async function readGitHubTree(repository, ref, root) {
|
|
749
|
+
return await githubRequest(repository, async (provider, repo) => {
|
|
750
|
+
const tree = provider.contents.tree(repo, {
|
|
751
|
+
recursive: true,
|
|
752
|
+
ref
|
|
753
|
+
});
|
|
754
|
+
const files = /* @__PURE__ */ new Map();
|
|
755
|
+
for await (const entry of tree) {
|
|
756
|
+
if (entry.type !== "file" && entry.type !== "symlink") continue;
|
|
757
|
+
if (!entry.sha) throw workspaceError("[vitehub] GitHub workspace returned a malformed tree response.");
|
|
758
|
+
const path = workspacePathFromGitPath(entry.path, root);
|
|
759
|
+
if (path) files.set(path, {
|
|
760
|
+
mode: gitFileMode(entry.mode),
|
|
761
|
+
path: entry.path,
|
|
762
|
+
sha: entry.sha,
|
|
763
|
+
size: entry.size
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
if (tree.warnings.some((warning) => warning.code === "tree_truncated")) throw workspaceError("[vitehub] GitHub workspace store could not compare the remote tree because GitHub returned a truncated tree.");
|
|
767
|
+
return files;
|
|
768
|
+
}, "tree");
|
|
769
|
+
}
|
|
770
|
+
function isMissingRef(error) {
|
|
771
|
+
const status = githubRequestStatus(error);
|
|
772
|
+
return status === 404 || status === 422;
|
|
773
|
+
}
|
|
774
|
+
/** The head of `branch` right now, or null when it does not exist. */
|
|
775
|
+
async function readCurrentHead(repository, branch) {
|
|
776
|
+
try {
|
|
777
|
+
return await githubRequest(repository, async (provider, repo) => await provider.contents.resolveRef(repo, `heads/${branch}`), "commit") || null;
|
|
778
|
+
} catch (error) {
|
|
779
|
+
if (isMissingRef(error)) return null;
|
|
780
|
+
throw error;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* The head of `branch` and the files under `root`. When `branch` does not exist yet, they come from `fork` if it
|
|
785
|
+
* exists, else from the default branch, and `branchExists` is false.
|
|
786
|
+
*/
|
|
787
|
+
async function readGitHubBranchState(input) {
|
|
788
|
+
const resolve = async (branch) => {
|
|
789
|
+
const sha = await githubRequest(input.repository, async (provider, repo) => await provider.contents.resolveRef(repo, `heads/${branch}`), "commit");
|
|
790
|
+
if (!sha) throw workspaceError("[vitehub] GitHub workspace returned a malformed commit response.");
|
|
791
|
+
return sha;
|
|
792
|
+
};
|
|
793
|
+
let branchExists = true;
|
|
794
|
+
let refSha;
|
|
795
|
+
try {
|
|
796
|
+
refSha = await resolve(input.branch);
|
|
797
|
+
} catch (error) {
|
|
798
|
+
if (!isMissingRef(error)) throw error;
|
|
799
|
+
branchExists = false;
|
|
800
|
+
const forked = input.from ?? (input.fork ? await readCurrentHead(input.repository, input.fork) : null);
|
|
801
|
+
if (forked) refSha = forked;
|
|
802
|
+
else {
|
|
803
|
+
const repository = await githubRequest(input.repository, async (provider, repo) => await provider.repos.get(repo), "repository");
|
|
804
|
+
if (!repository.defaultBranch) throw workspaceError("[vitehub] GitHub workspace returned a malformed repository response.");
|
|
805
|
+
refSha = await resolve(repository.defaultBranch);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
return {
|
|
809
|
+
branchExists,
|
|
810
|
+
files: await readGitHubTree(input.repository, refSha, input.root),
|
|
811
|
+
refSha
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* Write and delete files in one commit on `branch`, and return the commit sha.
|
|
816
|
+
* A branch that does not exist yet is created from `parentSha`.
|
|
817
|
+
* Rejects with a Workspace conflict when the branch no longer points at `parentSha`.
|
|
818
|
+
*/
|
|
819
|
+
async function commitGitHubChanges(input) {
|
|
820
|
+
const needsModes = input.files.some((file) => file.mode !== "100644" || (input.remoteModes?.get(file.fullPath) ?? "100644") !== "100644");
|
|
821
|
+
const changes = [...input.files.map((file) => ({
|
|
822
|
+
content: file.bytes,
|
|
823
|
+
path: file.fullPath,
|
|
824
|
+
...needsModes ? { mode: file.mode } : {}
|
|
825
|
+
})), ...input.deletePaths.map((path) => ({
|
|
826
|
+
content: null,
|
|
827
|
+
path
|
|
828
|
+
}))];
|
|
829
|
+
const { BranchMovedError, forgeCommitFiles } = await loadForge();
|
|
830
|
+
try {
|
|
831
|
+
return await githubRequest(input.repository, async (provider, repo) => await forgeCommitFiles(provider, repo, {
|
|
832
|
+
branch: input.branch,
|
|
833
|
+
changes,
|
|
834
|
+
message: input.message,
|
|
835
|
+
...input.author ? { author: input.author } : {},
|
|
836
|
+
...input.branchExists ? { expectedHead: input.parentSha } : { createFrom: input.parentSha }
|
|
837
|
+
}));
|
|
838
|
+
} catch (error) {
|
|
839
|
+
if (error instanceof BranchMovedError || error instanceof Error && error.cause instanceof BranchMovedError) throw githubBranchMovedConflict({
|
|
840
|
+
branch: input.branch,
|
|
841
|
+
expectedHead: input.parentSha,
|
|
842
|
+
repository: input.repository.name
|
|
843
|
+
});
|
|
844
|
+
throw error;
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
//#endregion
|
|
848
|
+
export { registerWorkspaceKV as C, forgeEnv as D, setActiveCloudflareEnv as E, readForgeEnv as O, readGitHubReadStats as S, getActiveCloudflareBinding as T, resolveGitHubBranchOption as _, githubBranchMovedConflict as a, resolveGitHubRepositoryOption as b, joinGitPath as c, readCurrentHead as d, readGitHubArchive as f, requireGitHubOption as g, readGitHubFile as h, gitFileMode as i, loadForge as l, readGitHubEnvToken as m, connectGitHubRepository as n, githubRequest as o, readGitHubBranchState as p, gitBlobSha as r, githubRequestStatus as s, commitGitHubChanges as t, preloadGitHubFiles as u, resolveGitHubCredential as v, BoundedMap as w, resolveGitHubRootOption as x, resolveGitHubRefsOption as y };
|