@vite-hub/workspace 0.0.3 → 0.1.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.
Files changed (129) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +236 -58
  3. package/dist/{ai-nmHdzjCM.d.ts → ai-BW2ZhizI.d.ts} +22 -7
  4. package/dist/{ai-Ce3PtWFW.js → ai-BZyLwULx.js} +147 -66
  5. package/dist/ai.d.ts +2 -2
  6. package/dist/ai.js +1 -1
  7. package/dist/{asset-registry-CaG9b7tf.js → asset-registry-DfBV5kmw.js} +3 -2
  8. package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +19 -0
  9. package/dist/blob-database.d.ts +521 -0
  10. package/dist/blob-database.js +601 -0
  11. package/dist/cloudflare.d.ts +5 -6
  12. package/dist/cloudflare.js +1 -1
  13. package/dist/config-B7dmzDX3.js +1112 -0
  14. package/dist/{config-3I1BnsdO.d.ts → config-DLKdaFWN.d.ts} +1 -2
  15. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  16. package/dist/error-diagnostics-DY5GP47p.js +96 -0
  17. package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +354 -0
  18. package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +214 -0
  19. package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +527 -0
  20. package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +248 -0
  21. package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +179 -0
  22. package/dist/file-C0_aPWSS.js +26 -0
  23. package/dist/file-metadata-CxDy-E2H.js +58 -0
  24. package/dist/{files-QRV55OCx.js → files-C7Px8uaC.js} +21 -10
  25. package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +2278 -0
  26. package/dist/{github-CfA5vpJ5.js → github-CPxHtFB7.js} +36 -34
  27. package/dist/github-DtncTfmv-Du2S8lGF.js +4159 -0
  28. package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +2530 -0
  29. package/dist/glob--XcLlcml.js +22 -0
  30. package/dist/glob--kNYDbfU.js +30 -0
  31. package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +489 -0
  32. package/dist/host-CFnrTXTK.js +1086 -0
  33. package/dist/{hosted-C1-tTTTf.js → hosted-acMA5XyL.js} +216 -43
  34. package/dist/hosted-vercel-blob-DKntsHaf.js +12603 -0
  35. package/dist/hosted-vercel-blob.d.ts +5 -6
  36. package/dist/hosted-vercel-blob.js +1 -1
  37. package/dist/hosted.d.ts +6 -7
  38. package/dist/hosted.js +1 -1
  39. package/dist/index.d.ts +76 -64
  40. package/dist/index.js +162 -457
  41. package/dist/inspect-BoObD2cJ.js +167 -0
  42. package/dist/internal/path.d.ts +2 -0
  43. package/dist/internal/path.js +2 -0
  44. package/dist/lifecycle-BwZ7c9hb.js +596 -0
  45. package/dist/loader.d.ts +5 -6
  46. package/dist/loader.js +3 -2
  47. package/dist/mcp-resources-BREFCmtn.js +39 -0
  48. package/dist/memory-BbwOqDXl.js +248 -0
  49. package/dist/metadata-target-DZEZQGHA.js +1588 -0
  50. package/dist/mountx.d.ts +4 -6
  51. package/dist/mountx.js +10 -8
  52. package/dist/nitro.d.ts +1 -1
  53. package/dist/nitro.js +1 -1
  54. package/dist/nuxt.d.ts +13 -12
  55. package/dist/nuxt.js +10 -8
  56. package/dist/operations-BcpWr41m.js +159 -0
  57. package/dist/operations-CGqY1XeG.js +965 -0
  58. package/dist/operations-DnOwKsJT.d.ts +136 -0
  59. package/dist/operations.d.ts +53 -0
  60. package/dist/operations.js +2 -0
  61. package/dist/{path-CNI6wKIU.js → path-CNAwN7pw.js} +34 -35
  62. package/dist/path-DrSIenjj.js +59 -0
  63. package/dist/path-zHxQUbqa.d.ts +9 -0
  64. package/dist/plugins-DqQ8b4T5.d.ts +10 -0
  65. package/dist/provider-kXjfli9u.js +1457 -0
  66. package/dist/providers/github/store.d.ts +3 -5
  67. package/dist/providers/github/store.js +1 -1
  68. package/dist/registry-Bp-8UUfG.js +129 -0
  69. package/dist/{registry-BIQVCBWI.d.ts → registry-Cg1TJVVZ.d.ts} +3 -4
  70. package/dist/{request-execution-u9mgUXKX.js → request-execution-Dk9rY-Yh.js} +24 -20
  71. package/dist/rolldown-runtime-B4iAMlE-.js +35 -0
  72. package/dist/runtime/assets.d.ts +3 -5
  73. package/dist/runtime/assets.js +9 -6
  74. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  75. package/dist/runtime/empty-registry.d.ts +1 -2
  76. package/dist/runtime/state.d.ts +4 -4
  77. package/dist/runtime/state.js +10 -7
  78. package/dist/runtime/workspace.d.ts +1 -1
  79. package/dist/runtime/workspace.js +1 -1
  80. package/dist/runtime.d.ts +84 -15
  81. package/dist/runtime.js +561 -108
  82. package/dist/{search-C4REyHj9.js → search-CrTmXj5h.js} +10 -9
  83. package/dist/server-BNQ-Nbjj.js +290 -0
  84. package/dist/server.d.ts +22 -34
  85. package/dist/server.js +2 -355
  86. package/dist/shared-DalXdP0i.js +2158 -0
  87. package/dist/source-metadata.d.ts +7 -1
  88. package/dist/source-metadata.js +34 -2
  89. package/dist/{state-TTqa3x3Y.d.ts → state-B8zbLi5t.d.ts} +14 -13
  90. package/dist/store-CXgmu-uw.js +1729 -0
  91. package/dist/{sync-DiuDmSGk.js → sync-CN6ec-5M.js} +62 -41
  92. package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +125 -0
  93. package/dist/test.d.ts +1 -1
  94. package/dist/test.js +1 -1
  95. package/dist/token-CO62GglH.js +61 -0
  96. package/dist/{types-60Yn149G.d.ts → types-DeK9GIxy.d.ts} +348 -49
  97. package/dist/{use-CsV3oIxH.js → use-BQj7nSz6.js} +200 -45
  98. package/dist/{use-CUFSnFCS.d.ts → use-DhwhbAVV.d.ts} +34 -12
  99. package/dist/utils-Blrh4N2n.js +545 -0
  100. package/dist/vite-BEvgU2GY.js +20909 -0
  101. package/dist/vite-CcZmMQ7S.d.ts +476 -0
  102. package/dist/vite.d.ts +2 -50
  103. package/dist/vite.js +2 -2
  104. package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +1565 -0
  105. package/dist/workspace-6pxkOuxr.js +1286 -0
  106. package/dist/workspace-BWJQBK1u.d.ts +7 -0
  107. package/package.json +90 -59
  108. package/dist/chunk-8H4AJuhK.js +0 -14
  109. package/dist/collections/client.d.ts +0 -39
  110. package/dist/collections/client.js +0 -137
  111. package/dist/collections.d.ts +0 -59
  112. package/dist/collections.js +0 -159
  113. package/dist/config-CDoyls2X.js +0 -30
  114. package/dist/config-CZLO0m9h.js +0 -7811
  115. package/dist/file-CHfsZpso.js +0 -23
  116. package/dist/glob-D0vD_wRY.js +0 -17
  117. package/dist/host-CAnbugpI.js +0 -370
  118. package/dist/hosted-vercel-blob-CWBILDVo.js +0 -257
  119. package/dist/lifecycle-BYoa9hVb.js +0 -176
  120. package/dist/provider-C3_elpEh.js +0 -599
  121. package/dist/publish.d.ts +0 -35
  122. package/dist/publish.js +0 -112
  123. package/dist/registry-CqyDTW9Y.js +0 -74
  124. package/dist/runtime-options-BsPSv5O7.js +0 -13
  125. package/dist/shared-jfogBrd5.js +0 -273
  126. package/dist/store-Bs1SLh55.js +0 -414
  127. package/dist/vite-tbfDxtlu.js +0 -2191
  128. package/dist/workspace-66SKyiec.d.ts +0 -6
  129. package/dist/workspace-C4k92Ow8.js +0 -1460
package/dist/publish.js DELETED
@@ -1,112 +0,0 @@
1
- import { c as normalizeWorkspacePath, p as workspaceError } from "./path-CNI6wKIU.js";
2
- import { n as resolveWorkspaceStoreTarget } from "./target-D4Bqb1eH.js";
3
- import { a as isWorkspaceFileEntry, d as resolveGitHubBranchOption, f as resolveGitHubOption, h as resolveGitHubTokenOption, l as readGitHubBranchState, m as resolveGitHubRootOption, p as resolveGitHubRepositoryOption, r as createGitHubFileUpdate, t as commitGitHubChanges, u as requireGitHubOption } from "./shared-jfogBrd5.js";
4
- import { dirname, resolve } from "node:path";
5
- import { mkdir, writeFile } from "node:fs/promises";
6
- //#region src/publishers/manifest.ts
7
- function manifest(options = {}) {
8
- return {
9
- name: "manifest",
10
- async publish(ctx) {
11
- const path = resolve(ctx.rootDir, options.path || `.vitehub/workspaces/${ctx.workspace.name}.json`);
12
- const entries = await ctx.store.list("", { recursive: true });
13
- await mkdir(dirname(path), { recursive: true });
14
- await writeFile(path, `${JSON.stringify({
15
- name: ctx.workspace.name,
16
- entries
17
- }, null, 2)}\n`);
18
- }
19
- };
20
- }
21
- //#endregion
22
- //#region src/publishers/github.ts
23
- function resolveMessage(options, ctx) {
24
- return ctx.snapshot?.name || resolveGitHubOption(options.message) || "chore: update workspace snapshot";
25
- }
26
- async function resolveActiveGitHubStoreTarget(ctx) {
27
- const target = await resolveWorkspaceStoreTarget(ctx.store);
28
- if (target) return target.provider === "github" ? target : void 0;
29
- const configuredStore = ctx.workspace.store;
30
- if (configuredStore && "provider" in configuredStore && configuredStore.provider === "github") {
31
- const repository = resolveGitHubRepositoryOption(configuredStore);
32
- if (repository) return {
33
- provider: "github",
34
- branch: resolveGitHubBranchOption(configuredStore),
35
- repository
36
- };
37
- }
38
- }
39
- async function readFiles(ctx, root) {
40
- const entries = await ctx.store.list("", { recursive: true });
41
- return await Promise.all(entries.filter(isWorkspaceFileEntry).map(async (entry) => {
42
- const file = await ctx.store.readFile(entry.path);
43
- if (!file) throw workspaceError(`[vitehub] Workspace file disappeared before GitHub publish: ${entry.path}.`);
44
- const update = await createGitHubFileUpdate(entry.path, root, file.content);
45
- return {
46
- ...file,
47
- path: normalizeWorkspacePath(entry.path),
48
- ...update
49
- };
50
- }));
51
- }
52
- function github(options = {}) {
53
- return {
54
- name: "github",
55
- async publish(ctx) {
56
- const repository = requireGitHubOption("publisher", "a repository", resolveGitHubRepositoryOption(options));
57
- const branch = resolveGitHubBranchOption(options);
58
- const root = resolveGitHubRootOption(options, ctx.workspace.name);
59
- const token = requireGitHubOption("publisher", "a token", resolveGitHubTokenOption(options));
60
- const storeTarget = await resolveActiveGitHubStoreTarget(ctx);
61
- if (!ctx.durable && storeTarget?.repository === repository && storeTarget.branch === branch) throw workspaceError(`[vitehub] GitHub publisher cannot publish to ${repository}@${branch} while it backs the active GitHub Workspace Store. Use workspace.snapshot() for that branch or configure the publisher to use a different repository or branch.`);
62
- const files = await readFiles(ctx, root);
63
- const nextPaths = new Set(files.map((file) => file.path));
64
- const remote = await readGitHubBranchState({
65
- branch,
66
- kind: "publisher",
67
- paths: options.deleteUntracked === false ? files.map((file) => file.path) : void 0,
68
- repository,
69
- root,
70
- token
71
- });
72
- const changedFiles = files.filter((file) => remote.files.get(file.path)?.sha !== file.gitSha);
73
- const deletePaths = options.deleteUntracked === false ? [] : [...remote.files].filter(([path]) => !nextPaths.has(path)).map(([, entry]) => entry.path);
74
- if (!changedFiles.length && !deletePaths.length) return;
75
- await commitGitHubChanges({
76
- baseTreeSha: remote.treeSha,
77
- branch,
78
- branchExists: remote.branchExists,
79
- deletePaths,
80
- files: changedFiles,
81
- kind: "publisher",
82
- message: resolveMessage(options, ctx),
83
- parentSha: remote.refSha,
84
- repository,
85
- token
86
- });
87
- }
88
- };
89
- }
90
- //#endregion
91
- //#region src/publishers/types.ts
92
- function types(options = {}) {
93
- return {
94
- name: "types",
95
- async publish(ctx) {
96
- const path = resolve(ctx.rootDir, options.path || `.vitehub/workspaces/${ctx.workspace.name}.d.ts`);
97
- await mkdir(dirname(path), { recursive: true });
98
- await writeFile(path, `declare module "#vitehub/workspaces/${ctx.workspace.name}" {\n const manifest: { name: ${JSON.stringify(ctx.workspace.name)}, entries: Array<{ path: string, type: "file" | "directory" }> }\n export default manifest\n}\n`);
99
- }
100
- };
101
- }
102
- //#endregion
103
- //#region src/publishers/virtual-module.ts
104
- function virtualModule(options) {
105
- return {
106
- name: `virtual-module:${options.id}`,
107
- clientSafe: options.includeContent === true,
108
- async publish() {}
109
- };
110
- }
111
- //#endregion
112
- export { github, manifest, types, virtualModule };
@@ -1,74 +0,0 @@
1
- import { m as workspaceNotFoundError } from "./path-CNI6wKIU.js";
2
- import { t as createWorkspace } from "./workspace-C4k92Ow8.js";
3
- import runtimeRegistry from "#vitehub-workspace-registry";
4
- //#region src/core/registry.ts
5
- const workspaceRegistryStateKey = Symbol.for("vitehub.workspace.registryState");
6
- function workspaceRegistryState() {
7
- const scope = globalThis;
8
- scope[workspaceRegistryStateKey] ??= {
9
- loadedDefinitions: /* @__PURE__ */ new Map(),
10
- loaders: runtimeRegistry,
11
- registeredDefinitions: /* @__PURE__ */ new Map()
12
- };
13
- return scope[workspaceRegistryStateKey];
14
- }
15
- function pickWorkspaceFields(definition) {
16
- const { __vitehubWorkspaceAgent: _agent, __vitehubWorkspaceAgentOptions: _agentOptions, description: _description, fallback: _fallback, instructions: _instructions, model: _model, name: _agentName, resolve: _resolve, run: _run, stepLimit: _stepLimit, workspace: _workspace, ...workspace } = definition;
17
- return workspace;
18
- }
19
- function normalizeWorkspaceDefinition(name, definition) {
20
- if (!definition) throw workspaceNotFoundError(name);
21
- const workspaceAgentOptions = definition.__vitehubWorkspaceAgentOptions;
22
- if (workspaceAgentOptions?.workspace) {
23
- const injectedWorkspace = pickWorkspaceFields(definition);
24
- const configuredWorkspace = typeof workspaceAgentOptions.workspace === "string" ? {} : workspaceAgentOptions.workspace;
25
- const sources = mergeWorkspaceSources(injectedWorkspace.sources, configuredWorkspace.sources);
26
- return {
27
- ...injectedWorkspace,
28
- ...configuredWorkspace,
29
- ...sources ? { sources } : {},
30
- rootDir: configuredWorkspace.rootDir ?? injectedWorkspace.rootDir,
31
- sourceRootDir: configuredWorkspace.sourceRootDir ?? injectedWorkspace.sourceRootDir,
32
- name
33
- };
34
- }
35
- if ("name" in definition) throw new TypeError(`[vitehub] Workspace definition "${name}" must not declare a name. Workspace names are inferred from filenames.`);
36
- return {
37
- ...pickWorkspaceFields(definition),
38
- name
39
- };
40
- }
41
- function mergeWorkspaceSources(injected, configured) {
42
- if (!injected && !configured) return void 0;
43
- return {
44
- ...injected,
45
- ...configured
46
- };
47
- }
48
- function registerWorkspace(name, definition) {
49
- if (!name || typeof name !== "string") throw new TypeError("[vitehub] registerWorkspace requires a string name.");
50
- workspaceRegistryState().registeredDefinitions.set(name, normalizeWorkspaceDefinition(name, definition));
51
- }
52
- function setWorkspaceRegistry(registry) {
53
- const state = workspaceRegistryState();
54
- state.loaders = registry;
55
- state.loadedDefinitions.clear();
56
- }
57
- async function resolveWorkspaceDefinition(name) {
58
- const state = workspaceRegistryState();
59
- const existing = state.registeredDefinitions.get(name) || state.loadedDefinitions.get(name);
60
- if (existing) return existing;
61
- const load = state.loaders[name];
62
- if (!load) throw workspaceNotFoundError(name);
63
- const definition = normalizeWorkspaceDefinition(name, (await load()).default);
64
- state.loadedDefinitions.set(name, definition);
65
- return definition;
66
- }
67
- async function resolveRegisteredWorkspaceDefinition(name) {
68
- return resolveWorkspaceDefinition(name);
69
- }
70
- async function useRegisteredWorkspace(name) {
71
- return createWorkspace(await resolveWorkspaceDefinition(name));
72
- }
73
- //#endregion
74
- export { useRegisteredWorkspace as a, setWorkspaceRegistry as i, registerWorkspace as n, resolveRegisteredWorkspaceDefinition as r, normalizeWorkspaceDefinition as t };
@@ -1,13 +0,0 @@
1
- //#region src/sources/runtime-options.ts
2
- function withWorkspaceRuntimeOptions(source, options) {
3
- return {
4
- ...source,
5
- cache: options.cache,
6
- materialize: options.materialize,
7
- mount: options.mount,
8
- sync: options.sync,
9
- validate: options.validate
10
- };
11
- }
12
- //#endregion
13
- export { withWorkspaceRuntimeOptions as t };
@@ -1,273 +0,0 @@
1
- import { c as normalizeWorkspacePath, p as workspaceError, r as contentToBytes } from "./path-CNI6wKIU.js";
2
- import { AsyncLocalStorage } from "node:async_hooks";
3
- //#region ../internal/src/runtime/cloudflare-env.ts
4
- let activeEnv;
5
- const activeEnvStorage = new AsyncLocalStorage();
6
- function setActiveCloudflareEnv(env) {
7
- activeEnv = env;
8
- globalThis.__env__ = env;
9
- try {
10
- activeEnvStorage.enterWith({ env });
11
- } catch {}
12
- }
13
- function getActiveCloudflareEnv() {
14
- const scoped = activeEnvStorage.getStore();
15
- return scoped ? scoped.env : activeEnv ?? globalThis.__env__;
16
- }
17
- function getActiveCloudflareBinding(name) {
18
- return getActiveCloudflareEnv()?.[name];
19
- }
20
- //#endregion
21
- //#region src/providers/github/shared.ts
22
- var GitHubRequestError = class extends Error {
23
- status;
24
- constructor(message, status) {
25
- super(message);
26
- this.status = status;
27
- this.name = "GitHubRequestError";
28
- }
29
- };
30
- function githubRequestStatus(error) {
31
- return (error instanceof GitHubRequestError ? error : error instanceof Error && error.cause instanceof GitHubRequestError ? error.cause : void 0)?.status;
32
- }
33
- function processEnv(env, ...keys) {
34
- return keys.map((key) => env[key]).find((value) => typeof value === "string" && value.length > 0);
35
- }
36
- function resolveGitHubOption(value) {
37
- return typeof value === "function" ? value() : value;
38
- }
39
- function isMaskedGitHubTokenOption(value) {
40
- return value === "********" || value === "<redacted>" || value === "[redacted]";
41
- }
42
- function requireGitHubOption(kind, label, value) {
43
- if (!value) throw workspaceError(`[vitehub] GitHub workspace ${kind} requires ${label}.`);
44
- return value;
45
- }
46
- function splitGitHubRepository(repository, kind) {
47
- const [owner, repo] = repository.split("/");
48
- if (!owner || !repo) throw workspaceError(`[vitehub] GitHub workspace ${kind} requires a repository in owner/repo format.`);
49
- return {
50
- owner,
51
- repo
52
- };
53
- }
54
- function joinGitPath(...parts) {
55
- return parts.join("/").replaceAll("\\", "/").split("/").filter(Boolean).join("/");
56
- }
57
- function resolveGitHubWorkspaceRoot(root, workspaceName) {
58
- return joinGitPath(root.replaceAll("<workspace>", workspaceName));
59
- }
60
- function workspacePathFromGitPath(path, root) {
61
- const normalized = joinGitPath(path);
62
- const normalizedRoot = joinGitPath(root);
63
- if (!normalizedRoot) return normalizeWorkspacePath(normalized);
64
- if (!normalized.startsWith(`${normalizedRoot}/`)) return void 0;
65
- return normalizeWorkspacePath(normalized.slice(normalizedRoot.length + 1));
66
- }
67
- function isWorkspaceFileEntry(entry) {
68
- return entry.type === "file";
69
- }
70
- function toHex(bytes) {
71
- return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
72
- }
73
- async function gitBlobSha(bytes) {
74
- const prefix = new TextEncoder().encode(`blob ${bytes.byteLength}\0`);
75
- const input = new Uint8Array(prefix.byteLength + bytes.byteLength);
76
- input.set(prefix);
77
- input.set(bytes, prefix.byteLength);
78
- return toHex(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-1", input)));
79
- }
80
- function toBase64(bytes) {
81
- let binary = "";
82
- for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
83
- const encode = globalThis.btoa;
84
- return encode ? encode(binary) : Buffer.from(bytes).toString("base64");
85
- }
86
- function fromBase64(input) {
87
- const normalized = input.replace(/\s/g, "");
88
- const decode = globalThis.atob;
89
- if (!decode) return new Uint8Array(Buffer.from(normalized, "base64"));
90
- const binary = decode(normalized);
91
- const bytes = new Uint8Array(binary.length);
92
- for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
93
- return bytes;
94
- }
95
- function resolveGitHubRepositoryOption(options, env = typeof process !== "undefined" ? process.env : {}) {
96
- return resolveGitHubOption(options.repository) || resolveGitHubOption(options.repo) || processEnv(env, "WORKSPACE_GITHUB_REPOSITORY", "VITEHUB_WORKSPACE_GITHUB_REPOSITORY", "GITHUB_REPOSITORY");
97
- }
98
- function resolveGitHubBranchOption(options, env = typeof process !== "undefined" ? process.env : {}) {
99
- return resolveGitHubOption(options.branch) || processEnv(env, "WORKSPACE_GITHUB_BRANCH", "VITEHUB_WORKSPACE_GITHUB_BRANCH", "GITHUB_BRANCH") || "main";
100
- }
101
- function resolveGitHubRootOption(options, workspaceName, env = typeof process !== "undefined" ? process.env : {}) {
102
- return resolveGitHubWorkspaceRoot(resolveGitHubOption(options.root) || processEnv(env, "WORKSPACE_GITHUB_ROOT", "VITEHUB_WORKSPACE_GITHUB_ROOT") || ".vitehub/workspaces/<workspace>", workspaceName);
103
- }
104
- function resolveGitHubTokenOption(options, env = typeof process !== "undefined" ? process.env : {}) {
105
- const token = resolveGitHubOption(options.token);
106
- if (token && !isMaskedGitHubTokenOption(token)) return token;
107
- const bindingToken = getActiveCloudflareBinding("GITHUB_TOKEN");
108
- if (bindingToken && !isMaskedGitHubTokenOption(bindingToken)) return bindingToken;
109
- return processEnv(env, "WORKSPACE_GITHUB_TOKEN", "VITEHUB_WORKSPACE_GITHUB_TOKEN", "GITHUB_TOKEN", "GH_TOKEN");
110
- }
111
- async function requestGitHubJson(repository, token, path, init) {
112
- const response = await fetch(`https://api.github.com${path}`, {
113
- ...init,
114
- headers: {
115
- accept: "application/vnd.github+json",
116
- authorization: `Bearer ${token}`,
117
- "content-type": "application/json",
118
- "user-agent": "vitehub-workspace",
119
- "x-github-api-version": "2022-11-28",
120
- ...init?.headers
121
- }
122
- });
123
- if (!response.ok) throw workspaceError("[vitehub] GitHub workspace request failed.", { cause: new GitHubRequestError(`[vitehub] GitHub workspace request failed for ${repository}: ${response.status} ${response.statusText} ${await response.text().catch(() => "")}`, response.status) });
124
- return await response.json();
125
- }
126
- async function requestGitHubBytes(repository, token, path, init) {
127
- const response = await fetch(`https://api.github.com${path}`, {
128
- ...init,
129
- headers: {
130
- accept: "application/vnd.github.raw+json",
131
- authorization: `Bearer ${token}`,
132
- "user-agent": "vitehub-workspace",
133
- "x-github-api-version": "2022-11-28",
134
- ...init?.headers
135
- }
136
- });
137
- if (!response.ok) throw workspaceError("[vitehub] GitHub workspace request failed.", { cause: new GitHubRequestError(`[vitehub] GitHub workspace request failed for ${repository}: ${response.status} ${response.statusText} ${await response.text().catch(() => "")}`, response.status) });
138
- if (response.headers.get("content-type")?.includes("application/json")) {
139
- const blob = await response.json();
140
- if (blob.encoding === "base64" && typeof blob.content === "string") return fromBase64(blob.content);
141
- throw workspaceError(`[vitehub] GitHub workspace request for ${repository} returned unsupported byte response.`);
142
- }
143
- return new Uint8Array(await response.arrayBuffer());
144
- }
145
- function findGitHubRemoteFiles(tree, root, kind) {
146
- if (tree.truncated) throw workspaceError(`[vitehub] GitHub workspace ${kind} could not compare the remote tree because GitHub returned a truncated tree.`);
147
- const files = /* @__PURE__ */ new Map();
148
- for (const entry of tree.tree) {
149
- if (entry.type !== "blob" || !entry.sha) continue;
150
- const path = workspacePathFromGitPath(entry.path, root);
151
- if (path) files.set(path, entry);
152
- }
153
- return files;
154
- }
155
- async function readGitHubBranchState(input) {
156
- const { owner, repo } = splitGitHubRepository(input.repository, input.kind);
157
- let branchExists = true;
158
- let ref;
159
- try {
160
- ref = await requestGitHubJson(input.repository, input.token, `/repos/${owner}/${repo}/git/ref/heads/${input.branch}`);
161
- } catch (error) {
162
- if (githubRequestStatus(error) !== 404) throw error;
163
- const repository = await requestGitHubJson(input.repository, input.token, `/repos/${owner}/${repo}`);
164
- ref = await requestGitHubJson(input.repository, input.token, `/repos/${owner}/${repo}/git/ref/heads/${repository.default_branch}`);
165
- branchExists = false;
166
- }
167
- const current = await requestGitHubJson(input.repository, input.token, `/repos/${owner}/${repo}/git/commits/${ref.object.sha}`);
168
- if (input.paths) {
169
- const entries = await Promise.all(input.paths.map(async (path) => {
170
- const encodedPath = joinGitPath(input.root, path).split("/").map(encodeURIComponent).join("/");
171
- try {
172
- return await requestGitHubJson(input.repository, input.token, `/repos/${owner}/${repo}/contents/${encodedPath}?ref=${encodeURIComponent(ref.object.sha)}`, { headers: { accept: "application/vnd.github.object+json" } });
173
- } catch (error) {
174
- if (githubRequestStatus(error) === 404) return void 0;
175
- throw error;
176
- }
177
- }));
178
- return {
179
- branchExists,
180
- files: new Map(input.paths.flatMap((path, index) => {
181
- const entry = entries[index];
182
- return entry?.type === "file" && entry.sha ? [[path, entry]] : [];
183
- })),
184
- refSha: ref.object.sha,
185
- treeSha: current.tree.sha
186
- };
187
- }
188
- const tree = await requestGitHubJson(input.repository, input.token, `/repos/${owner}/${repo}/git/trees/${current.tree.sha}?recursive=1`);
189
- return {
190
- branchExists,
191
- files: findGitHubRemoteFiles(tree, input.root, input.kind),
192
- refSha: ref.object.sha,
193
- treeSha: current.tree.sha
194
- };
195
- }
196
- async function readGitHubBlob(input) {
197
- const { owner, repo } = splitGitHubRepository(input.repository, input.kind);
198
- return await requestGitHubBytes(input.repository, input.token, `/repos/${owner}/${repo}/git/blobs/${input.sha}`);
199
- }
200
- async function commitGitHubChanges(input) {
201
- const kind = input.kind || "store";
202
- const { owner, repo } = splitGitHubRepository(input.repository, kind);
203
- const blobs = await Promise.all(input.files.map((file) => file.bytes ? createGitHubBlob({
204
- bytes: file.bytes,
205
- kind,
206
- repository: input.repository,
207
- token: input.token
208
- }) : { sha: file.gitSha }));
209
- const tree = await requestGitHubJson(input.repository, input.token, `/repos/${owner}/${repo}/git/trees`, {
210
- body: JSON.stringify({
211
- base_tree: input.baseTreeSha,
212
- tree: [...input.files.map((file, index) => ({
213
- mode: file.mode || "100644",
214
- path: file.fullPath,
215
- sha: blobs[index].sha,
216
- type: "blob"
217
- })), ...input.deletePaths.map((path) => ({
218
- mode: "100644",
219
- path,
220
- sha: null,
221
- type: "blob"
222
- }))]
223
- }),
224
- method: "POST"
225
- });
226
- const commit = await requestGitHubJson(input.repository, input.token, `/repos/${owner}/${repo}/git/commits`, {
227
- body: JSON.stringify({
228
- message: input.message,
229
- parents: [input.parentSha],
230
- tree: tree.sha
231
- }),
232
- method: "POST"
233
- });
234
- if (input.branchExists) await requestGitHubJson(input.repository, input.token, `/repos/${owner}/${repo}/git/refs/heads/${input.branch}`, {
235
- body: JSON.stringify({
236
- force: false,
237
- sha: commit.sha
238
- }),
239
- method: "PATCH"
240
- });
241
- else await requestGitHubJson(input.repository, input.token, `/repos/${owner}/${repo}/git/refs`, {
242
- body: JSON.stringify({
243
- ref: `refs/heads/${input.branch}`,
244
- sha: commit.sha
245
- }),
246
- method: "POST"
247
- });
248
- return {
249
- commitSha: commit.sha,
250
- treeSha: tree.sha
251
- };
252
- }
253
- async function createGitHubBlob(input) {
254
- const kind = input.kind || "store";
255
- const { owner, repo } = splitGitHubRepository(input.repository, kind);
256
- return await requestGitHubJson(input.repository, input.token, `/repos/${owner}/${repo}/git/blobs`, {
257
- body: JSON.stringify({
258
- content: toBase64(input.bytes),
259
- encoding: "base64"
260
- }),
261
- method: "POST"
262
- });
263
- }
264
- async function createGitHubFileUpdate(path, root, content) {
265
- const bytes = contentToBytes(content);
266
- return {
267
- bytes,
268
- fullPath: joinGitPath(root, path),
269
- gitSha: await gitBlobSha(bytes)
270
- };
271
- }
272
- //#endregion
273
- export { setActiveCloudflareEnv as _, isWorkspaceFileEntry as a, readGitHubBlob as c, resolveGitHubBranchOption as d, resolveGitHubOption as f, getActiveCloudflareBinding as g, resolveGitHubTokenOption as h, gitBlobSha as i, readGitHubBranchState as l, resolveGitHubRootOption as m, createGitHubBlob as n, joinGitPath as o, resolveGitHubRepositoryOption as p, createGitHubFileUpdate as r, processEnv as s, commitGitHubChanges as t, requireGitHubOption as u };