@vite-hub/workspace 0.0.4 → 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 (127) hide show
  1. package/README.md +225 -58
  2. package/dist/{ai-CjxvGqM0.d.ts → ai-BW2ZhizI.d.ts} +22 -7
  3. package/dist/{ai-BqCC8BpY.js → ai-BZyLwULx.js} +147 -66
  4. package/dist/ai.d.ts +2 -2
  5. package/dist/ai.js +1 -1
  6. package/dist/{asset-registry-8QI3ML3K.js → asset-registry-DfBV5kmw.js} +3 -2
  7. package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +19 -0
  8. package/dist/blob-database.d.ts +521 -0
  9. package/dist/blob-database.js +601 -0
  10. package/dist/cloudflare.d.ts +5 -6
  11. package/dist/cloudflare.js +1 -1
  12. package/dist/config-B7dmzDX3.js +1112 -0
  13. package/dist/{config-DE9xlaIw.d.ts → config-DLKdaFWN.d.ts} +1 -2
  14. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  15. package/dist/error-diagnostics-DY5GP47p.js +96 -0
  16. package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +354 -0
  17. package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +214 -0
  18. package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +527 -0
  19. package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +248 -0
  20. package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +179 -0
  21. package/dist/file-C0_aPWSS.js +26 -0
  22. package/dist/file-metadata-CxDy-E2H.js +58 -0
  23. package/dist/{files-Q6xZjDHA.js → files-C7Px8uaC.js} +3 -3
  24. package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +2278 -0
  25. package/dist/{github-DHnjxQIX.js → github-CPxHtFB7.js} +16 -23
  26. package/dist/github-DtncTfmv-Du2S8lGF.js +4159 -0
  27. package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +2530 -0
  28. package/dist/glob--XcLlcml.js +22 -0
  29. package/dist/glob--kNYDbfU.js +30 -0
  30. package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +489 -0
  31. package/dist/{host-DJH8cuoU.js → host-CFnrTXTK.js} +97 -41
  32. package/dist/{hosted-RPeJOCFz.js → hosted-acMA5XyL.js} +102 -19
  33. package/dist/hosted-vercel-blob-DKntsHaf.js +12603 -0
  34. package/dist/hosted-vercel-blob.d.ts +5 -6
  35. package/dist/hosted-vercel-blob.js +1 -1
  36. package/dist/hosted.d.ts +6 -7
  37. package/dist/hosted.js +1 -1
  38. package/dist/index.d.ts +57 -36
  39. package/dist/index.js +56 -56
  40. package/dist/inspect-BoObD2cJ.js +167 -0
  41. package/dist/internal/path.d.ts +2 -0
  42. package/dist/internal/path.js +2 -0
  43. package/dist/lifecycle-BwZ7c9hb.js +596 -0
  44. package/dist/loader.d.ts +5 -6
  45. package/dist/loader.js +3 -2
  46. package/dist/mcp-resources-BREFCmtn.js +39 -0
  47. package/dist/memory-BbwOqDXl.js +248 -0
  48. package/dist/metadata-target-DZEZQGHA.js +1588 -0
  49. package/dist/mountx.d.ts +4 -6
  50. package/dist/mountx.js +10 -8
  51. package/dist/nitro.d.ts +1 -1
  52. package/dist/nitro.js +1 -1
  53. package/dist/nuxt.d.ts +13 -12
  54. package/dist/nuxt.js +4 -8
  55. package/dist/operations-BcpWr41m.js +159 -0
  56. package/dist/operations-CGqY1XeG.js +965 -0
  57. package/dist/operations-DnOwKsJT.d.ts +136 -0
  58. package/dist/operations.d.ts +53 -0
  59. package/dist/operations.js +2 -0
  60. package/dist/path-CNAwN7pw.js +114 -0
  61. package/dist/path-DrSIenjj.js +59 -0
  62. package/dist/path-zHxQUbqa.d.ts +9 -0
  63. package/dist/plugins-DqQ8b4T5.d.ts +10 -0
  64. package/dist/provider-kXjfli9u.js +1457 -0
  65. package/dist/providers/github/store.d.ts +3 -5
  66. package/dist/providers/github/store.js +1 -1
  67. package/dist/{registry-D3yzt8HQ.js → registry-Bp-8UUfG.js} +9 -7
  68. package/dist/{registry-Uj6IVxes.d.ts → registry-Cg1TJVVZ.d.ts} +1 -2
  69. package/dist/{request-execution-B-dSFlGB.js → request-execution-Dk9rY-Yh.js} +19 -19
  70. package/dist/{chunk-2rV9d50f.js → rolldown-runtime-B4iAMlE-.js} +2 -2
  71. package/dist/runtime/assets.d.ts +3 -5
  72. package/dist/runtime/assets.js +7 -6
  73. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  74. package/dist/runtime/empty-registry.d.ts +1 -2
  75. package/dist/runtime/state.d.ts +3 -3
  76. package/dist/runtime/state.js +6 -6
  77. package/dist/runtime/workspace.d.ts +1 -1
  78. package/dist/runtime/workspace.js +1 -1
  79. package/dist/runtime.d.ts +51 -17
  80. package/dist/runtime.js +320 -60
  81. package/dist/{search-BpiCF2Tw.js → search-CrTmXj5h.js} +10 -9
  82. package/dist/server-BNQ-Nbjj.js +290 -0
  83. package/dist/server.d.ts +22 -34
  84. package/dist/server.js +2 -328
  85. package/dist/shared-DalXdP0i.js +2158 -0
  86. package/dist/source-metadata.d.ts +6 -7
  87. package/dist/source-metadata.js +7 -7
  88. package/dist/{state-tYcRWEh2.d.ts → state-B8zbLi5t.d.ts} +3 -3
  89. package/dist/store-CXgmu-uw.js +1729 -0
  90. package/dist/{sync-DnTQwt8r.js → sync-CN6ec-5M.js} +61 -41
  91. package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +125 -0
  92. package/dist/test.d.ts +1 -1
  93. package/dist/test.js +1 -1
  94. package/dist/{token-CVzURBxC.js → token-CO62GglH.js} +3 -3
  95. package/dist/{types-CYuwjJ4V.d.ts → types-DeK9GIxy.d.ts} +256 -24
  96. package/dist/{use-BTNDR5Rd.js → use-BQj7nSz6.js} +82 -41
  97. package/dist/{use-BiHzt0xA.d.ts → use-DhwhbAVV.d.ts} +16 -11
  98. package/dist/utils-Blrh4N2n.js +545 -0
  99. package/dist/vite-BEvgU2GY.js +20909 -0
  100. package/dist/vite-CcZmMQ7S.d.ts +476 -0
  101. package/dist/vite.d.ts +2 -2
  102. package/dist/vite.js +2 -2
  103. package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +1565 -0
  104. package/dist/{workspace-Dq08Yn72.js → workspace-6pxkOuxr.js} +361 -230
  105. package/dist/{workspace-Xddf4G1B.d.ts → workspace-BWJQBK1u.d.ts} +4 -3
  106. package/package.json +89 -55
  107. package/dist/collections/client.d.ts +0 -39
  108. package/dist/collections/client.js +0 -137
  109. package/dist/collections.d.ts +0 -59
  110. package/dist/collections.js +0 -159
  111. package/dist/config-Bc3c4Su1.js +0 -7904
  112. package/dist/config-CHLLWklZ.js +0 -36
  113. package/dist/file-Bc1X7pco.js +0 -23
  114. package/dist/glob-CEZKeZFC.js +0 -18
  115. package/dist/hosted-vercel-blob-d6C8ND5j.js +0 -23580
  116. package/dist/lifecycle-LrL3sA4n.js +0 -316
  117. package/dist/metadata-target-B0tOmVW7.js +0 -717
  118. package/dist/path-Cp59koVz.js +0 -139
  119. package/dist/provider-B1yLjCJJ.js +0 -746
  120. package/dist/publish.d.ts +0 -35
  121. package/dist/publish.js +0 -112
  122. package/dist/runtime-options-BsPSv5O7.js +0 -13
  123. package/dist/runtime-type-iEE6BjQJ.js +0 -34
  124. package/dist/shared-DTR1Hhma.js +0 -331
  125. package/dist/store-Dt_Jyys3.js +0 -608
  126. package/dist/vite-BptCrpv2.js +0 -4526
  127. package/dist/vite-CtA9guIM.d.ts +0 -66
@@ -0,0 +1,2158 @@
1
+ import { a as workspaceConflict, s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
2
+ import { l as normalizeWorkspacePath } from "./path-CNAwN7pw.js";
3
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-DY5GP47p.js";
4
+ import "node:crypto";
5
+ import { defineDiagnostics } from "nostics";
6
+ import { Buffer } from "node:buffer";
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+ //#region ../forge/dist/utils-CA_4WJhJ-DNgT61X2.js
9
+ /** Whether `support` means the operation cannot be called. Test this rather than `support === false`: `'not_applicable'` is a non-empty string. Accepts the declaration-only levels too, so a declared level can be tested before it resolves. */
10
+ function isUnsupported(support) {
11
+ return support === false || support === "not_applicable";
12
+ }
13
+ /** Every name {@link ReactionContent} covers. */
14
+ const REACTION_CONTENTS = [
15
+ "+1",
16
+ "-1",
17
+ "laugh",
18
+ "confused",
19
+ "heart",
20
+ "hooray",
21
+ "rocket",
22
+ "eyes"
23
+ ];
24
+ /** The normalised name for a forge-native reaction name, or `'other'` where there is none. */
25
+ function reactionContent(raw) {
26
+ return REACTION_CONTENTS.includes(raw) ? raw : "other";
27
+ }
28
+ const CASE_INSENSITIVE = /* @__PURE__ */ new Set([
29
+ "github",
30
+ "gitlab",
31
+ "forgejo",
32
+ "gitea",
33
+ "bitbucket",
34
+ "gitee",
35
+ "azure-devops"
36
+ ]);
37
+ /** Whether `forge` treats owner and repository names case-insensitively. Unknown forges are assumed not to. */
38
+ function namesAreCaseInsensitive(forge) {
39
+ return CASE_INSENSITIVE.has(forge);
40
+ }
41
+ /** `repo` with `owner` and `name` lowercased where the forge ignores case, so equal repositories compare equal. */
42
+ function normaliseRepoName(repo) {
43
+ return namesAreCaseInsensitive(repo.forge) ? {
44
+ ...repo,
45
+ owner: repo.owner.toLowerCase(),
46
+ name: repo.name.toLowerCase()
47
+ } : repo;
48
+ }
49
+ /** Whether `ref` addresses an organisation, group or workspace rather than a repository, by its `kind`. */
50
+ function isNamespaceRef(ref) {
51
+ return ref.kind === "namespace";
52
+ }
53
+ /**
54
+ * The ref of an organisation, group, workspace or project on `origin`, as `orgs`, `repos.byOwner()` and
55
+ * namespace webhooks take it.
56
+ * @param origin The forge and instance, such as a provider.
57
+ * @param owner The namespace path, such as `acme`, `acme/platform` on GitLab or `acme/Widgets` on Azure DevOps.
58
+ * @example
59
+ * ```ts
60
+ * const teams = provider.orgs.teams(namespaceRef(provider, 'acme'))
61
+ * ```
62
+ */
63
+ function namespaceRef(origin, owner) {
64
+ return {
65
+ forge: origin.forge,
66
+ instance: origin.instance,
67
+ owner,
68
+ name: "",
69
+ kind: "namespace"
70
+ };
71
+ }
72
+ /** Whether a thread ref has a number, so that it is a `ResolvedThreadRef`. */
73
+ function isResolvedThread(thread) {
74
+ return typeof thread.number === "string" && thread.number !== "";
75
+ }
76
+ function sameRepo(a, b) {
77
+ if (!b || a.forge !== b.forge || a.instance !== b.instance) return false;
78
+ const [left, right] = [normaliseRepoName(a), normaliseRepoName(b)];
79
+ return left.owner === right.owner && left.name === right.name;
80
+ }
81
+ function lineOf(value) {
82
+ const line = Number.parseInt(value ?? "", 10);
83
+ return line > 0 ? { line } : {};
84
+ }
85
+ /** Reads `base...head` or `base..head`. Git forbids `..` in a ref name, so the first `..` separates the two. */
86
+ function rangeOf(value) {
87
+ const at = value.indexOf("..");
88
+ const base = value.slice(0, at);
89
+ const head = value.slice(value[at + 2] === "." ? at + 3 : at + 2);
90
+ return at > 0 && head ? { compare: {
91
+ base,
92
+ head
93
+ } } : {};
94
+ }
95
+ function encodePath(path) {
96
+ return path.split("/").map(encodeURIComponent).join("/");
97
+ }
98
+ function webUrlFor(web, target) {
99
+ if (("file" in target ? target.file : "raw" in target ? target.raw : "commit" in target ? target.commit : "compare" in target ? target.compare : void 0)?.repo.kind === "namespace") return;
100
+ let path;
101
+ if ("repo" in target) path = "section" in target && target.section ? web.section?.(target.repo, target.section) : web.repo(target.repo);
102
+ else if ("thread" in target) path = isResolvedThread(target.thread) ? web.thread(target.thread) : void 0;
103
+ else if ("comment" in target) {
104
+ const { comment } = target;
105
+ path = isResolvedThread(comment.thread) ? web.comment?.(comment) : void 0;
106
+ } else if ("release" in target) path = web.release?.(target.release);
107
+ else if ("file" in target) path = web.file?.(target.file.repo, target.file.path, target.file.at, target.file.line);
108
+ else if ("raw" in target) path = web.raw?.(target.raw.repo, target.raw.path, target.raw.at);
109
+ else if ("commit" in target) path = target.commit.sha ? web.commit?.(target.commit.repo, target.commit.sha) : void 0;
110
+ else path = web.compare?.(target.compare.repo, target.compare.base, target.compare.head);
111
+ return path === void 0 ? void 0 : path.startsWith("/") ? `${web.baseUrl}${path}` : path;
112
+ }
113
+ /** `ssh://user@host:port/path` or `git://host:port/path` with the host in group 1, or `user@host:path` with it in group 2; the path is group 3. */
114
+ const CLONE_URL_RE = /^(?:(?:ssh|git):\/\/(?:[^@/]+@)?([^:/]+)(?::\d+)?\/|(?:[^@/\s]+@)?([^:/\s]+):(?!\/))(.+)$/i;
115
+ /** The `git+` that npm's `repository` field writes before a transport scheme. */
116
+ const GIT_PLUS_RE = /^git\+(?=[a-z]+:\/\/)/i;
117
+ /** The npm `repository` shorthand, https://docs.npmjs.com/cli/configuring-npm/package-json#repository */
118
+ const SHORTHAND_RE = /^(github|gitlab|bitbucket):(?!\/)/i;
119
+ const SHORTHAND_HOSTS = {
120
+ github: "github.com",
121
+ gitlab: "gitlab.com",
122
+ bitbucket: "bitbucket.org"
123
+ };
124
+ function parseWebUrl(web, input, origin) {
125
+ const base = new URL(web.baseUrl);
126
+ const prefix = base.pathname.replace(/\/$/, "");
127
+ const source = String(input).replace(GIT_PLUS_RE, "").replace(SHORTHAND_RE, (_, forge) => `https://${SHORTHAND_HOSTS[forge.toLowerCase()]}/`);
128
+ const clone = CLONE_URL_RE.exec(source);
129
+ let url;
130
+ try {
131
+ url = new URL(clone && (clone[1] ?? clone[2]).toLowerCase() === base.hostname ? `${base.origin}${prefix}/${clone[3]}` : source);
132
+ } catch {
133
+ return;
134
+ }
135
+ if (url.protocol !== "http:" && url.protocol !== "https:" || url.host !== base.host && !web.hosts?.includes(url.host) || url.username || url.password) return;
136
+ if (prefix && !url.pathname.startsWith(`${prefix}/`)) return;
137
+ let segments;
138
+ try {
139
+ segments = url.pathname.slice(prefix.length).split("/").filter(Boolean).map(decodeURIComponent);
140
+ } catch {
141
+ return;
142
+ }
143
+ return web.parse(segments, url, origin);
144
+ }
145
+ function referenceFor(web, ref, options = {}) {
146
+ if (!web || !("sha" in ref || isResolvedThread(ref))) return;
147
+ return web.reference?.(ref, sameRepo(ref.repo, options.from), options.expand ?? false) ?? webUrlFor(web, "sha" in ref ? { commit: ref } : { thread: ref });
148
+ }
149
+ /** `owner/name`, for forges that nest no deeper. */
150
+ const OWNER_NAME = String.raw`[\w.-]+\/[\w.-]+`;
151
+ /** What cannot come right before a reference, so that a path, an email address or a word does not read as one. */
152
+ const BEFORE = String.raw`(?<![\w/.@#~&!+-])`;
153
+ /** What cannot come right after a reference: a word character, or a dot, slash or `@` that continues a word. */
154
+ const AFTER = String.raw`(?![\w-]|[./@]\w)`;
155
+ const SHA = "[0-9a-f]{7,40}";
156
+ const SCHEME_CHAR = /[\w+.-]/;
157
+ const LETTER = /[a-z]/i;
158
+ const SPACE = /\s/;
159
+ const rules = /* @__PURE__ */ new WeakMap();
160
+ function repoIn(slug, origin) {
161
+ const at = slug.lastIndexOf("/");
162
+ return {
163
+ ...origin,
164
+ owner: slug.slice(0, at),
165
+ name: slug.slice(at + 1)
166
+ };
167
+ }
168
+ /** The spans of URLs in `text`, each from its scheme to the next whitespace. */
169
+ function urlSpans(text) {
170
+ const spans = [];
171
+ for (let at = text.indexOf("://"); at !== -1; at = text.indexOf("://", at + 1)) {
172
+ let start = at;
173
+ while (start > 0 && SCHEME_CHAR.test(text[start - 1])) start--;
174
+ while (start < at && !LETTER.test(text[start])) start++;
175
+ if (start === at || at + 3 >= text.length || SPACE.test(text[at + 3])) continue;
176
+ let end = at + 4;
177
+ while (end < text.length && !SPACE.test(text[end])) end++;
178
+ spans.push([start, end]);
179
+ at = end;
180
+ }
181
+ return spans;
182
+ }
183
+ /** A bare sha needs a letter and a digit, so that neither a number nor a word reads as one. */
184
+ function isBareSha(value) {
185
+ return /[a-f]/.test(value) && /\d/.test(value);
186
+ }
187
+ function rulesFor(syntax) {
188
+ const cached = rules.get(syntax);
189
+ if (cached) return cached;
190
+ const compiled = [];
191
+ const rule = (source, read) => compiled.push({
192
+ pattern: new RegExp(`${BEFORE}${source}${AFTER}`, "g"),
193
+ read
194
+ });
195
+ const suffix = syntax.suffix ? `(?:${syntax.suffix})?` : "";
196
+ for (const { prefix, kind, number = String.raw`[1-9]\d*`, sameRepo: local, namespace } of syntax.threads) {
197
+ const thread = `${prefix.replace(/[$()*+.?[\\\]^{|}]/g, "\\$&")}(?<id>${number})${suffix}`;
198
+ rule(thread, ({ id }, from, origin) => ({
199
+ ...origin,
200
+ repo: namespace ? namespaceRef(origin, from.owner) : from,
201
+ kind,
202
+ number: id
203
+ }));
204
+ if (syntax.repo && !local) rule(`(?<slug>${syntax.repo})${thread}`, ({ slug, id }, _, origin) => ({
205
+ ...origin,
206
+ repo: repoIn(slug, origin),
207
+ kind,
208
+ number: id
209
+ }));
210
+ }
211
+ if (syntax.commits) {
212
+ rule(`(?<sha>${SHA})`, ({ sha }, from, origin) => isBareSha(sha) ? {
213
+ ...origin,
214
+ repo: from,
215
+ sha
216
+ } : void 0);
217
+ if (syntax.repo) rule(`(?<slug>${syntax.repo})@(?<sha>${SHA})`, ({ slug, sha }, _, origin) => ({
218
+ ...origin,
219
+ repo: repoIn(slug, origin),
220
+ sha
221
+ }));
222
+ }
223
+ rules.set(syntax, compiled);
224
+ return compiled;
225
+ }
226
+ function parseReferences(web, text, from, origin) {
227
+ if (!web?.references || from.forge !== origin.forge || from.instance !== origin.instance) return [];
228
+ const urls = urlSpans(text);
229
+ const found = [];
230
+ for (const { pattern, read } of rulesFor(web.references)) for (const match of text.matchAll(pattern)) {
231
+ const ref = urls.some(([start, end]) => match.index >= start && match.index < end) ? void 0 : read(match.groups, from, origin);
232
+ if (ref) found.push({
233
+ start: match.index,
234
+ end: match.index + match[0].length,
235
+ ref
236
+ });
237
+ }
238
+ found.sort((a, b) => a.start - b.start || b.end - a.end);
239
+ let end = 0;
240
+ return found.filter((match) => {
241
+ if (match.start < end) return false;
242
+ end = match.end;
243
+ return true;
244
+ });
245
+ }
246
+ /** Reads GitHub's file route, `blob/{at}/{path}`. */
247
+ function parseGitHubFile([route, at, ...path]) {
248
+ return route === "blob" && at && path.length ? {
249
+ at,
250
+ path: path.join("/")
251
+ } : void 0;
252
+ }
253
+ /** Web links for forges laid out like GitHub: `/{owner}/{name}/issues/{n}` and friends. */
254
+ function githubShapedWeb(baseUrl, shape) {
255
+ const repoPath = (repo) => `/${encodePath(repo.owner)}/${encodeURIComponent(repo.name)}`;
256
+ const kindPath = {
257
+ issue: "issues",
258
+ pull_request: shape.pull,
259
+ ...shape.discussions ? { discussion: "discussions" } : {}
260
+ };
261
+ const commitPath = shape.commit ?? "commit";
262
+ const kindOf = new Map(Object.entries(kindPath).map(([kind, path]) => [path, kind]));
263
+ const reserved = new Set(shape.reserved?.map((segment) => segment.toLowerCase()));
264
+ const parseFile = shape.parseFile ?? parseGitHubFile;
265
+ return {
266
+ baseUrl,
267
+ repo: repoPath,
268
+ section: (repo, section) => {
269
+ if (repo.kind === "namespace") return;
270
+ const path = shape.sections?.[section];
271
+ if (path === null) return;
272
+ return `${repoPath(repo)}/${path ?? (section === "pullRequests" ? "pulls" : section)}`;
273
+ },
274
+ thread: (ref) => kindPath[ref.kind] && `${repoPath(ref.repo)}/${kindPath[ref.kind]}/${encodeURIComponent(ref.number)}`,
275
+ comment: (ref) => kindPath[ref.thread.kind] && `${repoPath(ref.thread.repo)}/${kindPath[ref.thread.kind]}/${encodeURIComponent(ref.thread.number)}#${shape.commentFragment}${ref.id}`,
276
+ commit: (repo, sha) => `${repoPath(repo)}/${commitPath}/${encodeURIComponent(sha)}`,
277
+ release: (ref) => ref.tag ? `${repoPath(ref.repo)}/releases/tag/${encodeURIComponent(ref.tag)}` : void 0,
278
+ file: (repo, path, at, line) => `${repoPath(repo)}${shape.file(at)}/${encodePath(path)}${line ? `#${shape.lineFragment(line)}` : ""}`,
279
+ raw: (repo, path, at) => shape.raw === false ? void 0 : shape.rawOrigin ? `${shape.rawOrigin}${repoPath(repo)}/${encodeURIComponent(at)}/${encodePath(path)}` : `${repoPath(repo)}/raw/${encodeURIComponent(at)}/${encodePath(path)}`,
280
+ compare: (repo, base, head) => `${repoPath(repo)}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`,
281
+ parse: (segments, url, from) => {
282
+ const [owner, name, section, id] = segments;
283
+ if (!owner || !name || reserved.has(owner.toLowerCase())) return;
284
+ const repo = {
285
+ ...from,
286
+ owner,
287
+ name: name.replace(/\.git$/, "")
288
+ };
289
+ const file = parseFile(segments.slice(2));
290
+ if (file) return {
291
+ repo,
292
+ file: {
293
+ ...file,
294
+ ...lineOf(url.hash.replace(/^#L/, ""))
295
+ }
296
+ };
297
+ const kind = section ? kindOf.get(section) : void 0;
298
+ if (section === "releases" && id === "tag" && segments[4]) return {
299
+ repo,
300
+ release: {
301
+ ...from,
302
+ repo,
303
+ id: segments[4],
304
+ tag: segments[4]
305
+ }
306
+ };
307
+ if (section === commitPath && id) return {
308
+ repo,
309
+ commit: {
310
+ ...from,
311
+ repo,
312
+ sha: id
313
+ }
314
+ };
315
+ if (section === "compare" && id) return {
316
+ repo,
317
+ ...rangeOf(segments.slice(3).join("/"))
318
+ };
319
+ if (!kind || !id) return { repo };
320
+ const thread = {
321
+ ...from,
322
+ repo,
323
+ kind,
324
+ number: id
325
+ };
326
+ if (kind === "pull_request" && segments[4] === "commits" && segments[5]) return {
327
+ repo,
328
+ thread,
329
+ commit: {
330
+ ...from,
331
+ repo,
332
+ sha: segments[5]
333
+ }
334
+ };
335
+ const comment = url.hash.startsWith(`#${shape.commentFragment}`) ? url.hash.slice(shape.commentFragment.length + 1) : void 0;
336
+ return {
337
+ repo,
338
+ thread,
339
+ ...comment ? { comment: {
340
+ ...from,
341
+ thread,
342
+ id: comment
343
+ } } : {}
344
+ };
345
+ },
346
+ reference: (ref, same) => {
347
+ if ("sha" in ref) return same ? ref.sha.slice(0, 7) : `${ref.repo.owner}/${ref.repo.name}@${ref.sha.slice(0, 7)}`;
348
+ const prefix = ref.kind === "pull_request" && shape.pullPrefix ? shape.pullPrefix : "#";
349
+ return `${same ? "" : `${ref.repo.owner}/${ref.repo.name}`}${prefix}${ref.number}`;
350
+ },
351
+ references: shape.references ?? {
352
+ threads: [{
353
+ prefix: "#",
354
+ kind: "issue"
355
+ }, ...shape.pullPrefix ? [{
356
+ prefix: shape.pullPrefix,
357
+ kind: "pull_request"
358
+ }] : []],
359
+ repo: OWNER_NAME,
360
+ commits: true
361
+ }
362
+ };
363
+ }
364
+ /** The API base URL and the instance that `options` select. */
365
+ function resolveInstance(definition, options) {
366
+ const root = (options.baseUrl ?? definition.baseUrl).replace(/\/$/, "");
367
+ const baseUrl = definition.apiPath && !root.endsWith(definition.apiPath) ? `${root}${definition.apiPath}` : root;
368
+ let host;
369
+ try {
370
+ host = new URL(baseUrl).host;
371
+ } catch (cause) {
372
+ throw new TypeError(`Invalid baseUrl for ${definition.forge}: ${JSON.stringify(baseUrl)}`, { cause });
373
+ }
374
+ return {
375
+ baseUrl,
376
+ instance: options.instance ?? definition.instance?.(host) ?? host
377
+ };
378
+ }
379
+ /** Base class for every error that forges throws. */
380
+ var ForgeError = class extends Error {
381
+ name = "ForgeError";
382
+ /** The forge that the request went to. */
383
+ forge;
384
+ instance;
385
+ url;
386
+ method;
387
+ constructor(message, context = {}, options) {
388
+ super(message, options);
389
+ this.forge = context.forge;
390
+ this.instance = context.instance;
391
+ this.url = context.url;
392
+ this.method = context.method;
393
+ }
394
+ };
395
+ /** The forge responded with an error. */
396
+ var ForgeApiError = class extends ForgeError {
397
+ name = "ForgeApiError";
398
+ status;
399
+ /** Truncated response body, for diagnostics. */
400
+ body;
401
+ constructor(message, status, body, context, options) {
402
+ super(message, context, options);
403
+ this.status = status;
404
+ this.body = body;
405
+ }
406
+ };
407
+ /** A 404: the resource does not exist, or the credential cannot see it. Many forges respond the same way to both. */
408
+ var NotFoundError = class extends ForgeApiError {
409
+ name = "NotFoundError";
410
+ };
411
+ /**
412
+ * A 401, or a 403 with a request budget of zero (GitHub GraphQL), for a request
413
+ * sent without credentials. A rejected credential is {@link TokenRevokedError}.
414
+ */
415
+ var AuthenticationRequiredError = class extends ForgeApiError {
416
+ name = "AuthenticationRequiredError";
417
+ };
418
+ /** The forge rate limited the request and a retry didn't help. Every rate limit rejects with this class, primary or secondary. */
419
+ var RateLimitedError = class extends ForgeApiError {
420
+ name = "RateLimitedError";
421
+ /** When to send again: after the forge's `retry-after`, or when a used-up budget resets. Absent when the forge names neither. */
422
+ resetAt;
423
+ /**
424
+ * Whether the forge applied a secondary limit, such as a limit on concurrent requests or on content creation,
425
+ * rather than a used-up request budget. No remaining-request counter predicts it.
426
+ */
427
+ secondary;
428
+ constructor(message, status, body, options = {}, errorOptions) {
429
+ super(message, status, body, options, errorOptions);
430
+ this.resetAt = options.resetAt;
431
+ this.secondary = options.secondary ?? false;
432
+ }
433
+ };
434
+ /** The credential was revoked or expired. */
435
+ var TokenRevokedError = class extends ForgeApiError {
436
+ name = "TokenRevokedError";
437
+ };
438
+ /** The credential is valid but lacks the scope or permission for this call. */
439
+ var InsufficientScopeError = class extends ForgeApiError {
440
+ name = "InsufficientScopeError";
441
+ /** Scopes that would allow the request, any one of them, where the forge names them (GitHub's `X-Accepted-OAuth-Scopes`). */
442
+ acceptedScopes;
443
+ /** Scopes the credential holds, where the forge reports them (GitHub's `X-OAuth-Scopes`). */
444
+ grantedScopes;
445
+ /** Fine-grained permissions that would allow the request, verbatim, such as `issues=write` (GitHub's `X-Accepted-GitHub-Permissions`). */
446
+ acceptedPermissionsRaw;
447
+ constructor(message, status, body, context, options) {
448
+ super(message, status, body, context, options);
449
+ this.acceptedScopes = context?.acceptedScopes;
450
+ this.grantedScopes = context?.grantedScopes;
451
+ this.acceptedPermissionsRaw = context?.acceptedPermissionsRaw;
452
+ }
453
+ };
454
+ /**
455
+ * The forge refused the request for a reason other than a missing scope or a
456
+ * rate limit: an organisation policy, an SSO requirement, a protected
457
+ * resource, a release the forge has marked immutable, or a resource that
458
+ * belongs to another app. A missing scope is
459
+ * {@link InsufficientScopeError}, and a rate limit {@link RateLimitedError}.
460
+ */
461
+ var ForbiddenError = class extends ForgeApiError {
462
+ name = "ForbiddenError";
463
+ /** Why the forge refused the request. */
464
+ reason;
465
+ /** The forge's own wording, for diagnostics and for reasons that have no `ForbiddenReason`. */
466
+ reasonRaw;
467
+ /** Where the user authorises the credential for the organisation, when `reason` is `sso_required` and the forge links it (GitHub's `X-GitHub-SSO`). */
468
+ ssoUrl;
469
+ constructor(message, status, body, reason, context, options) {
470
+ super(message, status, body, context, options);
471
+ this.reason = reason;
472
+ this.reasonRaw = context?.reasonRaw;
473
+ this.ssoUrl = context?.ssoUrl;
474
+ }
475
+ };
476
+ /** Body patterns that identify a 403 reason, most specific first. */
477
+ const FORBIDDEN_PATTERNS = [
478
+ ["org_restriction", /third[- ]party application|OAuth App access restrictions|organization has enabled OAuth|not authorized by the organization|blocked by the organization/i],
479
+ ["sso_required", /SAML|single sign[- ]on|\bSSO\b|must be granted .* organization/i],
480
+ ["resource_protected", /archived|read[- ]only|protected branch|repository has been disabled|is disabled/i],
481
+ ["unknown", /contributor list is too large[^".]*/i]
482
+ ];
483
+ /**
484
+ * Classifies a 403 body. Returns `undefined` for a body that names no policy
485
+ * the caller could act on, which stays {@link InsufficientScopeError}.
486
+ */
487
+ function forbiddenReason(body) {
488
+ for (const [reason, pattern] of FORBIDDEN_PATTERNS) {
489
+ const match = body.match(pattern);
490
+ if (match) return {
491
+ reason,
492
+ reasonRaw: match[0]
493
+ };
494
+ }
495
+ }
496
+ const SECONDARY_RATE_LIMIT_RE = /secondary rate limit|abuse detection|submitted too quickly/i;
497
+ /** Whether an error message names a secondary rate limit, such as GitHub's limits on concurrency and content creation. */
498
+ function isSecondaryRateLimit(message) {
499
+ return SECONDARY_RATE_LIMIT_RE.test(message);
500
+ }
501
+ /** The pull request cannot be merged yet, typically because of failing or pending checks or branch protection. */
502
+ var MergeBlockedError = class extends ForgeApiError {
503
+ name = "MergeBlockedError";
504
+ };
505
+ /** The merge conflicts with the base branch, or the head moved since `sha` was read. */
506
+ var MergeConflictError = class extends ForgeApiError {
507
+ name = "MergeConflictError";
508
+ };
509
+ /** `contents.commitFiles()` was given an `expectedHead`, or `threads.updateBranch()` a `sha`, and the branch no longer points at it. */
510
+ var BranchMovedError = class extends ForgeApiError {
511
+ name = "BranchMovedError";
512
+ };
513
+ /** A request or a pending merge exceeded `timeout`. */
514
+ var ForgeTimeoutError = class extends ForgeError {
515
+ name = "ForgeTimeoutError";
516
+ /** The timeout that was exceeded, in milliseconds. */
517
+ timeout;
518
+ constructor(message, timeout, context, options) {
519
+ super(message, context, options);
520
+ this.timeout = timeout;
521
+ }
522
+ };
523
+ /** The request never got a response: DNS, TLS, connection refused or a proxy refusal. */
524
+ var ForgeNetworkError = class extends ForgeError {
525
+ name = "ForgeNetworkError";
526
+ };
527
+ /** A delivery's signature didn't match. */
528
+ var WebhookVerificationError = class extends ForgeError {
529
+ name = "WebhookVerificationError";
530
+ };
531
+ /** The forge doesn't support the operation. */
532
+ var UnsupportedOperationError = class extends ForgeError {
533
+ name = "UnsupportedOperationError";
534
+ };
535
+ /** A write was called on a provider constructed with `readOnly: true`. */
536
+ var ReadOnlyError = class extends UnsupportedOperationError {
537
+ name = "ReadOnlyError";
538
+ };
539
+ /** `contents.getFile` was asked for text and the file's bytes are not valid UTF-8. */
540
+ var ContentNotTextError = class extends ForgeError {
541
+ name = "ContentNotTextError";
542
+ };
543
+ /** Maps a generic merge-endpoint failure onto {@link MergeBlockedError} or {@link MergeConflictError}. */
544
+ function toMergeError(error) {
545
+ if (!(error instanceof ForgeApiError) || error.constructor !== ForgeApiError) return error;
546
+ const context = {
547
+ forge: error.forge,
548
+ instance: error.instance,
549
+ url: error.url,
550
+ method: error.method
551
+ };
552
+ if (error.status === 405) return new MergeBlockedError("Pull request is not mergeable yet", error.status, error.body, context, { cause: error });
553
+ if (error.status === 406 || error.status === 409) return new MergeConflictError("Pull request conflicts with its base or the head has moved", error.status, error.body, context, { cause: error });
554
+ return error;
555
+ }
556
+ /** The thread ref has no number, or is a kind the provider cannot address. */
557
+ var UnresolvedThreadError = class extends ForgeError {
558
+ name = "UnresolvedThreadError";
559
+ };
560
+ /** No merge method was given, and the repository allows several or reports none. */
561
+ var MergeMethodRequiredError = class extends ForgeError {
562
+ name = "MergeMethodRequiredError";
563
+ /** The merge methods that the repository allows. */
564
+ allowed;
565
+ constructor(allowed, context, options) {
566
+ super(allowed.length ? `Repository allows ${allowed.join(", ")}; pass \`method\` to choose one` : "Repository reports no merge method this provider can use; pass `method` explicitly", context, options);
567
+ this.allowed = allowed;
568
+ }
569
+ };
570
+ /** Picks the only allowed merge method, or throws {@link MergeMethodRequiredError}. */
571
+ function soleMergeMethod(allowed, context) {
572
+ const methods = Object.keys(allowed).filter((method) => allowed[method]);
573
+ if (methods.length !== 1) throw new MergeMethodRequiredError(methods, context);
574
+ return methods[0];
575
+ }
576
+ const BODY_EXCERPT_LENGTH = 512;
577
+ const REDIRECT_STATUSES = /* @__PURE__ */ new Set([
578
+ 301,
579
+ 302,
580
+ 303,
581
+ 307,
582
+ 308
583
+ ]);
584
+ /** A forge's plain-text rate limit refusal, such as Gitee's `403 Forbidden (Rate Limit Exceeded)`. */
585
+ const PLAIN_RATE_LIMIT_RE = /^[^{<]{0,80}\brate limit exceeded\b/i;
586
+ const DOT_SEGMENT_RE = /^(?:\.|%2e){1,2}$/i;
587
+ /** Parses an RFC 5988 `Link` header into a map of rel to URL. */
588
+ function parseLinkHeader(header) {
589
+ const links = {};
590
+ if (!header) return links;
591
+ for (const part of header.split(",")) {
592
+ const match = /^<([^>]+)>\s*;\s*(.+)/.exec(part.trim());
593
+ if (!match?.[1] || !match[2]) continue;
594
+ const rel = /rel\s*=\s*"?([^";]+)"?/.exec(match[2])?.[1];
595
+ if (rel) links[rel.trim()] = match[1];
596
+ }
597
+ return links;
598
+ }
599
+ function cursorFrom(response) {
600
+ const next = parseLinkHeader(response.headers.get("link")).next;
601
+ const etag = response.headers.get("etag") ?? void 0;
602
+ if (!next && !etag) return;
603
+ return {
604
+ nextUrl: next,
605
+ etag
606
+ };
607
+ }
608
+ /** The page size a URL carries, under the names forges use for it. */
609
+ function pageSize(url) {
610
+ for (const name of [
611
+ "per_page",
612
+ "limit",
613
+ "perPage",
614
+ "pagelen"
615
+ ]) {
616
+ const value = Number(url.searchParams.get(name));
617
+ if (Number.isInteger(value) && value > 0) return value;
618
+ }
619
+ }
620
+ /**
621
+ * The exact total a response reports in a pagination header. GitLab sends
622
+ * `x-total`, and Forgejo and Gitea send `x-total-count`. A Forgejo or Gitea
623
+ * timeline reports the page's own length there, so a count no larger than the
624
+ * page is ignored for timeline requests; everywhere else it is exact, even
625
+ * when it equals the number of items on a single page.
626
+ */
627
+ function headerTotal(response, itemCount, requestUrl) {
628
+ const total = headerNumber(response, "x-total");
629
+ if (total !== void 0) return total;
630
+ const counted = headerNumber(response, "x-total-count");
631
+ if (counted === void 0) return;
632
+ return counted <= itemCount && /\/timeline(?:\?|$)/.test(requestUrl) ? void 0 : counted;
633
+ }
634
+ /**
635
+ * The total a `Link` header implies: the page number of its `rel="last"`
636
+ * entry times the page size that URL, or the request URL, reports. GitHub,
637
+ * GitLab, Forgejo and Gitea page by number, so their last page times their
638
+ * page size approximates the total. A last page of one means a single page,
639
+ * whose total is the items on it. `undefined` when the header carries no
640
+ * usable last page.
641
+ */
642
+ function linkTotal(header, requestUrl, itemCount) {
643
+ const last = parseLinkHeader(header).last;
644
+ if (!last) return;
645
+ let lastUrl;
646
+ let request;
647
+ try {
648
+ lastUrl = new URL(last);
649
+ request = new URL(requestUrl);
650
+ } catch {
651
+ return;
652
+ }
653
+ const page = Number(lastUrl.searchParams.get("page"));
654
+ if (!Number.isInteger(page) || page < 1) return;
655
+ if (page === 1) return itemCount;
656
+ const size = pageSize(lastUrl) ?? pageSize(request);
657
+ return size === void 0 ? void 0 : page * size;
658
+ }
659
+ function retryAfterMs(response) {
660
+ const header = response.headers.get("retry-after");
661
+ if (!header) return;
662
+ const seconds = Number(header);
663
+ if (Number.isFinite(seconds)) return seconds * 1e3;
664
+ const date = Date.parse(header);
665
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
666
+ }
667
+ /** `x-ratelimit-reset` and `ratelimit-reset` hold a Unix time in seconds on some forges, and seconds from now on others. */
668
+ function resetDate(response, now) {
669
+ const reset = headerNumber(response, "x-ratelimit-reset", "ratelimit-reset");
670
+ if (reset === void 0) return;
671
+ return new Date(reset > 1e9 ? reset * 1e3 : now + reset * 1e3);
672
+ }
673
+ /** A budget with requests left resets on its own schedule, which says nothing about when a secondary limit lifts. */
674
+ function rateLimitReset(response, budget) {
675
+ const after = retryAfterMs(response);
676
+ if (after !== void 0) return new Date(Date.now() + after);
677
+ return budget?.remaining ? void 0 : budget?.resetAt;
678
+ }
679
+ /** The leading number of the first of `names` to hold one, such as `60` of `60, 60;w=3600`. */
680
+ function headerNumber(response, ...names) {
681
+ for (const name of names) {
682
+ const value = response.headers.get(name)?.split(/[,;]/, 1)[0].trim();
683
+ if (value && Number.isFinite(Number(value))) return Number(value);
684
+ }
685
+ }
686
+ /** The members of a structured-field list such as `"burst";r=10;t=5, "day";r=900;t=3600`, by name. */
687
+ function fieldMembers(response, name) {
688
+ const members = /* @__PURE__ */ new Map();
689
+ for (const member of response.headers.get(name)?.split(",") ?? []) {
690
+ const [key = "", ...params] = member.split(";");
691
+ members.set(key.trim().replace(/^"(.*)"$/, "$1"), Object.fromEntries(params.map((param) => {
692
+ const [field = "", value] = param.split("=");
693
+ return [field.trim(), Number(value)];
694
+ })));
695
+ }
696
+ return members;
697
+ }
698
+ /** The IETF `ratelimit` and `ratelimit-policy` fields, for the policy with the fewest requests left. */
699
+ function structuredRateLimit(response, now) {
700
+ const [name, state] = [...fieldMembers(response, "ratelimit")].filter(([, params]) => Number.isFinite(params.r)).sort(([, a], [, b]) => a.r - b.r)[0] ?? [];
701
+ if (!state) return;
702
+ const limit = fieldMembers(response, "ratelimit-policy").get(name)?.q;
703
+ return {
704
+ ...Number.isFinite(limit) ? { limit } : {},
705
+ remaining: state.r,
706
+ ...Number.isFinite(state.t) ? { resetAt: new Date(now + state.t * 1e3) } : {},
707
+ ...name ? { resource: name } : {}
708
+ };
709
+ }
710
+ /** The request budget a response reports, from `x-ratelimit-*` or `ratelimit-*` headers, or the IETF `ratelimit` field. */
711
+ function rateLimitOf(response, now = Date.now()) {
712
+ const limit = headerNumber(response, "x-ratelimit-limit", "ratelimit-limit");
713
+ const remaining = headerNumber(response, "x-ratelimit-remaining", "ratelimit-remaining");
714
+ const reset = resetDate(response, now);
715
+ if (limit === void 0 && remaining === void 0 && reset === void 0) return structuredRateLimit(response, now);
716
+ const resource = response.headers.get("x-ratelimit-resource") || response.headers.get("ratelimit-name") || void 0;
717
+ return {
718
+ ...limit === void 0 ? {} : { limit },
719
+ ...remaining === void 0 ? {} : { remaining },
720
+ ...reset === void 0 ? {} : { resetAt: reset },
721
+ ...resource === void 0 ? {} : { resource }
722
+ };
723
+ }
724
+ /** Whether the `message` or an `errors[].message` of a JSON error body names a secondary rate limit. */
725
+ function scopeList(header) {
726
+ return header === null ? void 0 : header.split(",").map((scope) => scope.trim()).filter(Boolean);
727
+ }
728
+ function namesSecondaryRateLimit(body) {
729
+ let parsed;
730
+ try {
731
+ parsed = JSON.parse(body);
732
+ } catch {
733
+ return false;
734
+ }
735
+ const { message, errors } = parsed ?? {};
736
+ return [message, ...Array.isArray(errors) ? errors.map((error) => error?.message) : []].some((text) => typeof text === "string" && isSecondaryRateLimit(text));
737
+ }
738
+ /** GitHub sends a secondary limit as a 403 or a 429, and its content creation limit can arrive as a 422. */
739
+ function isRateLimited(response, budget, body) {
740
+ if (response.status === 429) return true;
741
+ if ((response.status === 403 || response.status === 422) && namesSecondaryRateLimit(body)) return true;
742
+ if (response.status !== 403 || budget?.limit === 0) return false;
743
+ return budget?.remaining === 0 || response.headers.has("retry-after") || !budget && PLAIN_RATE_LIMIT_RE.test(body.trim());
744
+ }
745
+ /**
746
+ * One signal that aborts when any of `signals` does. `AbortSignal.any` would
747
+ * do this, but StarlingMonkey (the wasm runtime) does not implement it.
748
+ */
749
+ function anySignal(signals) {
750
+ const aborted = signals.find((signal) => signal.aborted);
751
+ if (aborted) return aborted;
752
+ if (signals.length === 1) return signals[0];
753
+ const controller = new AbortController();
754
+ const listeners = [];
755
+ for (const signal of signals) {
756
+ const listener = () => {
757
+ controller.abort(signal.reason);
758
+ for (const [other, removed] of listeners) other.removeEventListener("abort", removed);
759
+ };
760
+ listeners.push([signal, listener]);
761
+ signal.addEventListener("abort", listener, { once: true });
762
+ }
763
+ return controller.signal;
764
+ }
765
+ function assertUrl(url) {
766
+ if (url.protocol !== "https:" && url.protocol !== "http:" || url.username || url.password) throw new TypeError("Invalid request URL");
767
+ return url;
768
+ }
769
+ function assertInput(input) {
770
+ for (const char of input) {
771
+ const code = char.charCodeAt(0);
772
+ if (code <= 32 || code === 127) throw new TypeError("Invalid request URL");
773
+ }
774
+ }
775
+ function assertRelativePath(path) {
776
+ const pathname = path.split("?", 1)[0];
777
+ if (path.includes("#") || pathname.includes("\\") || pathname.split("/").some((segment) => DOT_SEGMENT_RE.test(segment))) throw new TypeError(`Unsafe request path ${JSON.stringify(path)}; check the refs passed to the provider`);
778
+ return path;
779
+ }
780
+ function sleep(ms, signal) {
781
+ return new Promise((resolve, reject) => {
782
+ if (signal?.aborted) {
783
+ reject(signal.reason);
784
+ return;
785
+ }
786
+ const timer = setTimeout(() => {
787
+ signal?.removeEventListener("abort", onAbort);
788
+ resolve();
789
+ }, ms);
790
+ function onAbort() {
791
+ clearTimeout(timer);
792
+ reject(signal.reason);
793
+ }
794
+ signal?.addEventListener("abort", onAbort, { once: true });
795
+ });
796
+ }
797
+ /** Settles as `promise` does, or rejects with the signal's reason once it aborts, leaving `promise` running. */
798
+ function abortable(promise, signal) {
799
+ if (!signal) return promise;
800
+ if (signal.aborted) return Promise.reject(signal.reason);
801
+ return new Promise((resolve, reject) => {
802
+ const onAbort = () => reject(signal.reason);
803
+ signal.addEventListener("abort", onAbort, { once: true });
804
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
805
+ });
806
+ }
807
+ /**
808
+ * Creates a fetcher for one forge API.
809
+ * @param options The base URL and the credentials, timeout and error context of every request.
810
+ */
811
+ function createFetcher(options) {
812
+ const timeout = options.timeout ?? 3e4;
813
+ const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
814
+ assertInput(options.baseUrl);
815
+ const base = assertUrl(new URL(options.baseUrl));
816
+ if (base.search || base.hash) throw new TypeError("Invalid API base URL");
817
+ base.pathname = `${base.pathname.replace(/\/$/, "")}/`;
818
+ const baseOrigin = base.origin;
819
+ function resolve(path, query) {
820
+ assertInput(path);
821
+ let url;
822
+ try {
823
+ url = new URL(path);
824
+ } catch {
825
+ if (path.startsWith("//") || path.split("/", 1)[0].includes(":")) throw new TypeError("Invalid request URL");
826
+ }
827
+ url = assertUrl(url ?? new URL(assertRelativePath(path).replace(/^\//, ""), base));
828
+ for (const [key, value] of Object.entries(query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
829
+ return url.toString();
830
+ }
831
+ function withDefaultQuery(url) {
832
+ if (!options.query) return url;
833
+ const target = new URL(url);
834
+ for (const [key, value] of Object.entries(options.query)) if (!target.searchParams.has(key)) target.searchParams.set(key, value);
835
+ return target.toString();
836
+ }
837
+ async function send(url, options_, attempt, authenticated = true, download = false, redirects = 0, streaming = false, follow = false) {
838
+ const target = assertUrl(new URL(url));
839
+ const trusted = authenticated && target.origin === baseOrigin;
840
+ const controller = streaming ? new AbortController() : void 0;
841
+ const timer = controller ? setTimeout(() => controller.abort(new DOMException("Request timed out", "TimeoutError")), timeout) : void 0;
842
+ const signals = [controller?.signal ?? AbortSignal.timeout(timeout)];
843
+ if (options_.signal) signals.push(options_.signal);
844
+ const headers = new Headers(trusted ? options.headers : void 0);
845
+ for (const [key, value] of Object.entries(trusted ? await (options.authHeaders?.() ?? {}) : {})) headers.set(key, value);
846
+ for (const [key, value] of new Headers(options_.headers)) headers.set(key, value);
847
+ if (options_.etag) headers.set("if-none-match", options_.etag);
848
+ const { json: payload, mapError: _mapError, ...init } = options_;
849
+ if (payload !== void 0) headers.set("content-type", "application/json");
850
+ let response;
851
+ try {
852
+ response = await doFetch(trusted ? withDefaultQuery(url) : url, {
853
+ ...init,
854
+ redirect: follow ? "follow" : "manual",
855
+ credentials: trusted ? init.credentials : "omit",
856
+ headers,
857
+ body: payload === void 0 ? init.body : JSON.stringify(payload),
858
+ signal: anySignal(signals)
859
+ });
860
+ } catch (cause) {
861
+ if (options_.signal?.aborted) throw options_.signal.reason ?? cause;
862
+ if (cause instanceof Error && (cause.name === "TimeoutError" || cause.name === "AbortError")) throw new ForgeTimeoutError(`Request to ${url} timed out after ${timeout}ms`, timeout, {
863
+ ...options.context,
864
+ url,
865
+ method: options_.method ?? "GET"
866
+ }, { cause });
867
+ const inner = cause instanceof Error ? cause.cause : void 0;
868
+ const reason = typeof inner?.code === "string" ? inner.code : inner?.message;
869
+ throw new ForgeNetworkError(`Request to ${url} failed: ${cause instanceof Error ? cause.message : String(cause)}${typeof reason === "string" && reason ? ` (${reason})` : ""}`, {
870
+ ...options.context,
871
+ url,
872
+ method: options_.method ?? "GET"
873
+ }, { cause });
874
+ } finally {
875
+ clearTimeout(timer);
876
+ }
877
+ if (response.type === "opaqueredirect" && options_.redirect !== "manual") {
878
+ const method = (options_.method ?? "GET").toUpperCase();
879
+ if (options_.redirect === "error" || method !== "GET" && method !== "HEAD") throw new TypeError("Hidden redirect refused");
880
+ return send(url, options_, attempt, authenticated, download, redirects, streaming, true);
881
+ }
882
+ if (follow && response.redirected && response.url) {
883
+ const final = assertUrl(new URL(response.url));
884
+ if (final.origin !== target.origin && !download || target.protocol === "https:" && final.protocol !== "https:") {
885
+ await response.body?.cancel();
886
+ throw new TypeError("Unsafe request redirect");
887
+ }
888
+ }
889
+ const budget = rateLimitOf(response);
890
+ if (budget && options.onRateLimit && target.origin === baseOrigin) options.onRateLimit({
891
+ url,
892
+ method: options_.method ?? "GET",
893
+ rateLimit: budget
894
+ });
895
+ const location = REDIRECT_STATUSES.has(response.status) ? response.headers.get("location") : null;
896
+ if (location && options_.redirect !== "manual") {
897
+ await response.body?.cancel();
898
+ if (options_.redirect === "error" || redirects >= 20) throw new TypeError("Request redirect refused");
899
+ assertInput(location);
900
+ const next = assertUrl(new URL(location, target));
901
+ const sameOrigin = next.origin === target.origin;
902
+ if (!sameOrigin && !download || target.protocol === "https:" && next.protocol !== "https:") throw new TypeError("Unsafe request redirect");
903
+ const method = (options_.method ?? "GET").toUpperCase();
904
+ if (!sameOrigin && method !== "GET" && method !== "HEAD") throw new TypeError("Unsafe request redirect");
905
+ let nextOptions = options_;
906
+ if (!sameOrigin) nextOptions = {
907
+ method,
908
+ signal: options_.signal,
909
+ credentials: "omit"
910
+ };
911
+ else if (response.status === 303 && method !== "HEAD" || (response.status === 301 || response.status === 302) && method === "POST") {
912
+ const nextHeaders = new Headers(options_.headers);
913
+ for (const name of [
914
+ "content-type",
915
+ "content-length",
916
+ "content-encoding",
917
+ "content-language",
918
+ "content-location"
919
+ ]) nextHeaders.delete(name);
920
+ nextOptions = {
921
+ ...options_,
922
+ method: "GET",
923
+ body: void 0,
924
+ json: void 0,
925
+ headers: nextHeaders
926
+ };
927
+ }
928
+ return send(next.toString(), nextOptions, attempt, authenticated && sameOrigin, download, redirects + 1, streaming);
929
+ }
930
+ if (response.ok || response.status === 304 || options_.redirect === "manual" && (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400)) return response;
931
+ const text = await response.text();
932
+ const body = text.slice(0, BODY_EXCERPT_LENGTH);
933
+ const context = {
934
+ ...options.context,
935
+ url,
936
+ method: options_.method ?? "GET"
937
+ };
938
+ const credentialed = trusted && options.authenticated || headers.has("authorization");
939
+ if (response.status === 401) throw credentialed ? new TokenRevokedError("Credentials were rejected by the forge", 401, body, context) : new AuthenticationRequiredError("Credentials are required for this request", 401, body, context);
940
+ if (response.status === 403 && !credentialed && budget?.limit === 0) throw new AuthenticationRequiredError("Credentials are required for this request", 403, body, context);
941
+ if (response.status === 404) throw new NotFoundError(`Nothing found at ${options_.method ?? "GET"} ${url}, or the credential cannot see it`, 404, body, context);
942
+ if (isRateLimited(response, budget, text)) {
943
+ const secondary = namesSecondaryRateLimit(text) || budget?.remaining !== 0 && (response.status !== 429 || response.headers.has("retry-after"));
944
+ const wait = retryAfterMs(response);
945
+ if (attempt === 0 && wait !== void 0 && wait <= 6e4) {
946
+ options.onRetry?.({
947
+ url,
948
+ method: options_.method ?? "GET",
949
+ wait
950
+ });
951
+ await sleep(wait, options_.signal);
952
+ return send(url, options_, attempt + 1, authenticated, download, redirects, streaming, follow);
953
+ }
954
+ throw new RateLimitedError("Rate limited by the forge", response.status, body, {
955
+ ...context,
956
+ resetAt: rateLimitReset(response, budget),
957
+ secondary
958
+ });
959
+ }
960
+ if (response.status === 403) {
961
+ const acceptedScopes = scopeList(response.headers.get("x-accepted-oauth-scopes"));
962
+ const grantedScopes = scopeList(response.headers.get("x-oauth-scopes"));
963
+ const missingScope = acceptedScopes?.length && !acceptedScopes.some((scope) => grantedScopes?.includes(scope));
964
+ const ssoUrl = response.headers.get("x-github-sso")?.match(/\burl=(\S+)/)?.[1];
965
+ const forbidden = missingScope ? void 0 : ssoUrl ? {
966
+ reason: "sso_required",
967
+ reasonRaw: forbiddenReason(body)?.reasonRaw
968
+ } : forbiddenReason(body);
969
+ if (!forbidden) {
970
+ const acceptedPermissionsRaw = response.headers.get("x-accepted-github-permissions") || void 0;
971
+ throw new InsufficientScopeError("Credentials lack the scope or permission for this request", 403, body, {
972
+ ...context,
973
+ acceptedScopes,
974
+ grantedScopes,
975
+ acceptedPermissionsRaw
976
+ });
977
+ }
978
+ throw new ForbiddenError(`Forge refused the request (${forbidden.reason})`, 403, body, forbidden.reason, {
979
+ ...context,
980
+ reasonRaw: forbidden.reasonRaw,
981
+ ssoUrl
982
+ });
983
+ }
984
+ throw new ForgeApiError(`Forge responded with ${response.status} for ${options_.method ?? "GET"} ${url}`, response.status, body, context);
985
+ }
986
+ async function raw(path, options_ = {}) {
987
+ try {
988
+ return await send(resolve(path, options_.query), options_, 0);
989
+ } catch (error) {
990
+ throw options_.mapError ? options_.mapError(error) : error;
991
+ }
992
+ }
993
+ async function json(path, options_ = {}) {
994
+ const response = await raw(path, options_);
995
+ if (response.status === 304 || response.status === 204) return {
996
+ data: void 0,
997
+ response,
998
+ notModified: response.status === 304,
999
+ cursor: cursorFrom(response)
1000
+ };
1001
+ const text = await response.text();
1002
+ return {
1003
+ data: text ? parseJson(text) : void 0,
1004
+ response,
1005
+ notModified: false,
1006
+ cursor: cursorFrom(response)
1007
+ };
1008
+ }
1009
+ async function page(path, options_ = {}) {
1010
+ const { select, cursor, conditional = true, ...requestOptions } = options_;
1011
+ const initial = resolve(path, requestOptions.query);
1012
+ const url = cursor?.nextUrl ? resolve(cursor.nextUrl) : initial;
1013
+ if (new URL(url).origin !== new URL(initial).origin) throw new TypeError("Pagination URL must remain on the requested origin");
1014
+ const first = conditional && !cursor?.nextUrl && !cursor?.token;
1015
+ const sent = first ? requestOptions.etag ?? cursor?.etag : void 0;
1016
+ const result = await json(url, {
1017
+ ...requestOptions,
1018
+ etag: sent,
1019
+ query: void 0
1020
+ });
1021
+ const validator = first ? result.response.headers.get("etag") ?? (result.notModified ? sent : void 0) : void 0;
1022
+ const etag = validator ? { etag: validator } : {};
1023
+ if (result.notModified) return {
1024
+ ...result,
1025
+ data: [],
1026
+ cursor: void 0,
1027
+ ...etag
1028
+ };
1029
+ const next = select ? select(result.data, result.cursor?.nextUrl) : void 0;
1030
+ const items = next ? next.items : result.data ?? [];
1031
+ const total = next?.total ?? headerTotal(result.response, items.length, url) ?? linkTotal(result.response.headers.get("link"), url, items.length);
1032
+ if (!next) return {
1033
+ ...result,
1034
+ data: items,
1035
+ cursor: result.cursor?.nextUrl ? result.cursor : void 0,
1036
+ ...total !== void 0 ? { total } : {},
1037
+ ...etag
1038
+ };
1039
+ return {
1040
+ ...result,
1041
+ data: items,
1042
+ cursor: next.next ? {
1043
+ ...result.cursor,
1044
+ nextUrl: next.next
1045
+ } : void 0,
1046
+ ...total !== void 0 ? { total } : {},
1047
+ ...etag
1048
+ };
1049
+ }
1050
+ async function* items(path, options_ = {}) {
1051
+ let cursor;
1052
+ do {
1053
+ const result = await page(path, {
1054
+ ...options_,
1055
+ cursor
1056
+ });
1057
+ yield* result.data ?? [];
1058
+ cursor = result.notModified ? void 0 : result.cursor;
1059
+ } while (cursor?.nextUrl);
1060
+ }
1061
+ async function stream(path, options_ = {}) {
1062
+ try {
1063
+ const response = await send(resolve(path, options_.query), options_, 0, true, true, 0, true);
1064
+ return {
1065
+ status: response.status,
1066
+ headers: response.headers,
1067
+ body: response.body ?? emptyStream()
1068
+ };
1069
+ } catch (error) {
1070
+ throw options_.mapError ? options_.mapError(error) : error;
1071
+ }
1072
+ }
1073
+ return {
1074
+ raw,
1075
+ stream,
1076
+ json,
1077
+ page,
1078
+ items,
1079
+ resolve
1080
+ };
1081
+ }
1082
+ const LONG_NUMBER_RE = /\d{16}/;
1083
+ const INTEGER_RE = /^-?\d+$/;
1084
+ /**
1085
+ * Parses JSON, keeping integers beyond `Number.MAX_SAFE_INTEGER` (such as
1086
+ * GitHub webhook delivery ids) as their exact digits, where the runtime gives
1087
+ * the reviver the source text.
1088
+ */
1089
+ function parseJson(text) {
1090
+ if (!LONG_NUMBER_RE.test(text)) return JSON.parse(text);
1091
+ return JSON.parse(text, (_key, value, context) => typeof value === "number" && !Number.isSafeInteger(value) && context?.source && INTEGER_RE.test(context.source) ? context.source : value);
1092
+ }
1093
+ function emptyStream() {
1094
+ return new Blob([]).stream();
1095
+ }
1096
+ const SAFE_METHODS = /* @__PURE__ */ new Set([
1097
+ "GET",
1098
+ "HEAD",
1099
+ "OPTIONS"
1100
+ ]);
1101
+ /**
1102
+ * Builds a provider's `request()` escape hatch on top of its fetcher.
1103
+ * @param fetcher The fetcher to send requests with.
1104
+ * @param createOptions Where to reject writes, for a read-only provider.
1105
+ */
1106
+ function createRequest(fetcher, createOptions = {}) {
1107
+ const { readOnly } = createOptions;
1108
+ return (async (method, path, options = {}) => {
1109
+ const upperMethod = method.toUpperCase();
1110
+ if (readOnly && (options.mutates ?? !SAFE_METHODS.has(upperMethod))) throw readOnly(upperMethod, path);
1111
+ const json = options.body !== void 0 && isJsonBody(options.body);
1112
+ const init = {
1113
+ method: upperMethod,
1114
+ query: options.query,
1115
+ signal: options.signal,
1116
+ headers: {
1117
+ ...json ? { "content-type": "application/json" } : {},
1118
+ ...options.headers
1119
+ },
1120
+ body: options.body === void 0 ? void 0 : json ? JSON.stringify(options.body) : options.body
1121
+ };
1122
+ if ("raw" in options && options.raw) return fetcher.stream(path, init);
1123
+ const result = await fetcher.json(path, init);
1124
+ const rateLimit = rateLimitOf(result.response);
1125
+ return {
1126
+ status: result.response.status,
1127
+ data: result.data,
1128
+ headers: result.response.headers,
1129
+ ...rateLimit ? { rateLimit } : {}
1130
+ };
1131
+ });
1132
+ }
1133
+ function isJsonBody(value) {
1134
+ return typeof value !== "string" && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && !(typeof Blob !== "undefined" && value instanceof Blob) && !(typeof FormData !== "undefined" && value instanceof FormData) && !(value instanceof URLSearchParams) && !(typeof ReadableStream !== "undefined" && value instanceof ReadableStream);
1135
+ }
1136
+ /**
1137
+ * Wraps a generator so warnings it reports are collected on the returned
1138
+ * iterable rather than interrupting iteration.
1139
+ */
1140
+ function forgeIterable(run) {
1141
+ const warnings = [];
1142
+ return {
1143
+ warnings,
1144
+ [Symbol.asyncIterator]: () => run((warning) => warnings.push(warning))[Symbol.asyncIterator]()
1145
+ };
1146
+ }
1147
+ /** Drives a `page()` function until it reports no further cursor, collecting page warnings. */
1148
+ function iteratePages(page, options = {}) {
1149
+ return forgeIterable(async function* (warn) {
1150
+ let cursor = options.cursor;
1151
+ while (true) {
1152
+ const result = await page({
1153
+ ...options,
1154
+ cursor
1155
+ });
1156
+ result.warnings?.forEach(warn);
1157
+ yield* result.items;
1158
+ if (!result.cursor?.nextUrl && !result.cursor?.token || result.notModified) return;
1159
+ cursor = result.cursor;
1160
+ }
1161
+ });
1162
+ }
1163
+ /** Turns a caught error into a serialisable warning. */
1164
+ function toWarning(code, error, subject) {
1165
+ const err = error instanceof Error ? error : new Error(String(error));
1166
+ return {
1167
+ code,
1168
+ message: err.message,
1169
+ subject,
1170
+ cause: {
1171
+ name: err.name,
1172
+ message: err.message,
1173
+ status: err instanceof ForgeApiError ? err.status : void 0
1174
+ }
1175
+ };
1176
+ }
1177
+ /** Whether a failed side read may become a warning; rate limits, revoked tokens and errors from outside forges still stop the read. */
1178
+ function degradesToWarning(error) {
1179
+ return error instanceof ForgeError && !(error instanceof RateLimitedError) && !(error instanceof TokenRevokedError);
1180
+ }
1181
+ /** Maps with at most `limit` calls in flight, preserving order. Once a call rejects, no further calls start. */
1182
+ async function mapConcurrent(items, limit, fn) {
1183
+ const results = Array.from({ length: items.length });
1184
+ let next = 0;
1185
+ let failed = false;
1186
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
1187
+ while (!failed && next < items.length) {
1188
+ const index = next++;
1189
+ try {
1190
+ results[index] = await fn(items[index]);
1191
+ } catch (error) {
1192
+ failed = true;
1193
+ throw error;
1194
+ }
1195
+ }
1196
+ }));
1197
+ return results;
1198
+ }
1199
+ /** `threads.getMany` for forges without a batch endpoint. A rate limit or a rejected credential rejects the call; other failures become per-item warnings. */
1200
+ function getManyConcurrently(refs, get, options = {}) {
1201
+ return mapConcurrent(refs, 4, (ref) => get(ref, options).then((thread) => ({
1202
+ ok: true,
1203
+ ref,
1204
+ thread
1205
+ }), (error) => {
1206
+ if (options.signal?.aborted) throw options.signal.reason;
1207
+ if (error instanceof ForgeError && !degradesToWarning(error)) throw error;
1208
+ return {
1209
+ ok: false,
1210
+ ref,
1211
+ warning: toWarning(error instanceof UnresolvedThreadError ? "thread_unresolved" : "thread_unreadable", error, ref.number)
1212
+ };
1213
+ }));
1214
+ }
1215
+ /** The comment that a notification's `latest_comment_url` names: an issue comment on a thread subject with a number, or a comment on a commit subject. */
1216
+ function latestCommentOf(subject, url) {
1217
+ if (subject.type === "commit") {
1218
+ const id = /\/repos\/[^/]+\/[^/]+\/comments\/(\d+)$/.exec(url ?? "")?.[1];
1219
+ return id ? {
1220
+ forge: subject.commit.forge,
1221
+ instance: subject.commit.instance,
1222
+ commit: subject.commit,
1223
+ id
1224
+ } : void 0;
1225
+ }
1226
+ const id = /\/issues\/comments\/(\d+)$/.exec(url ?? "")?.[1];
1227
+ if (!id || subject.type !== "thread" || !isResolvedThread(subject.thread)) return;
1228
+ return {
1229
+ forge: subject.thread.forge,
1230
+ instance: subject.thread.instance,
1231
+ thread: subject.thread,
1232
+ id
1233
+ };
1234
+ }
1235
+ /** Compares dotted numeric versions, ignoring any suffix after the numbers. */
1236
+ function versionAtLeast(version, minimum) {
1237
+ if (!version) return false;
1238
+ const parts = (value) => (/^\D*(\d+(?:\.\d+)*)/.exec(value)?.[1] ?? "0").split(".").map(Number);
1239
+ const [a, b] = [parts(version), parts(minimum)];
1240
+ for (let index = 0; index < Math.max(a.length, b.length); index++) {
1241
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
1242
+ if (difference !== 0) return difference > 0;
1243
+ }
1244
+ return true;
1245
+ }
1246
+ /** Reads a timestamp from a forge response, or `undefined` when it is empty or not a date. */
1247
+ function toDate(value) {
1248
+ if (value === null || value === void 0 || value === "") return;
1249
+ const date = new Date(value);
1250
+ return Number.isNaN(date.getTime()) ? void 0 : date;
1251
+ }
1252
+ /** The host of `baseUrl`, including the port when there is one. */
1253
+ function hostOf(baseUrl) {
1254
+ return new URL(baseUrl).host;
1255
+ }
1256
+ /** The namespace ref of `ref`'s owner, for the `org` of a team's ref. */
1257
+ function teamOrg(ref) {
1258
+ return isNamespaceRef(ref) ? ref : namespaceRef(ref, ref.owner);
1259
+ }
1260
+ /** Narrows a ref to one a provider can address, or throws {@link UnresolvedThreadError}. */
1261
+ function requireThread(ref, context) {
1262
+ if (!isResolvedThread(ref)) throw new UnresolvedThreadError("Thread ref has no number; resolve it before calling the forge", context ?? {
1263
+ forge: ref.forge,
1264
+ instance: ref.instance
1265
+ });
1266
+ return ref;
1267
+ }
1268
+ /**
1269
+ * Narrows a ref to an issue or pull request, or throws
1270
+ * {@link UnsupportedOperationError} naming the verb that needs one.
1271
+ */
1272
+ function requireIssueOrPull(ref, context, verb) {
1273
+ const thread = requireThread(ref, context);
1274
+ if (thread.kind !== "issue" && thread.kind !== "pull_request") throw new UnsupportedOperationError(`${context.forge ?? "This forge"} cannot ${verb} a ${thread.kind}`, context);
1275
+ return thread;
1276
+ }
1277
+ /** The token in `auth`, read again on every call when it is a function. */
1278
+ async function resolveToken(auth) {
1279
+ return typeof auth.token === "function" ? await auth.token() : auth.token;
1280
+ }
1281
+ /**
1282
+ * The forge-native id `threads.setMilestone` sends: the milestone's `id`, a
1283
+ * string of digits as it is, or the id of the milestone with that title.
1284
+ */
1285
+ async function milestoneId(milestone, page, context, options = {}) {
1286
+ const value = typeof milestone === "string" ? milestone : milestone.id;
1287
+ if (/^\d+$/.test(value)) return Number(value);
1288
+ for await (const candidate of iteratePages(page, {
1289
+ state: "all",
1290
+ signal: options.signal
1291
+ })) if (candidate.title === value) return Number(candidate.id);
1292
+ throw new UnsupportedOperationError(`No milestone titled ${value}`, context);
1293
+ }
1294
+ /** Joins the merge commit title and message for a forge that takes them as one string. */
1295
+ function mergeCommitMessage({ title, message }) {
1296
+ return title && message ? `${title}\n\n${message}` : title || message;
1297
+ }
1298
+ /** A login from either a login string or an actor. */
1299
+ function actorLogin(actor) {
1300
+ return typeof actor === "string" ? actor : actor.login;
1301
+ }
1302
+ /** Maps one fetched page into a {@link Page}. The cursor is kept only when there is a next page. */
1303
+ function toPage(result, map, warnings) {
1304
+ return {
1305
+ items: (result.data ?? []).flatMap((raw) => {
1306
+ const item = map(raw);
1307
+ return item === void 0 ? [] : [item];
1308
+ }),
1309
+ ...result.total !== void 0 ? { total: result.total } : {},
1310
+ cursor: result.cursor?.nextUrl || result.cursor?.token ? result.cursor : void 0,
1311
+ ...result.etag ? { etag: result.etag } : {},
1312
+ notModified: result.notModified || void 0,
1313
+ ...warnings?.length ? { warnings } : {},
1314
+ ...rateLimitPart(result.response)
1315
+ };
1316
+ }
1317
+ /**
1318
+ * Adds the validator of a listing's first page to `page`: the response's `etag`, or on a `304` the one
1319
+ * `cursor` sent. Later pages are left as they are.
1320
+ */
1321
+ function withEtag(page, result, cursor) {
1322
+ if (!isFirstPage(cursor)) return page;
1323
+ const etag = result.response.headers.get("etag") ?? (result.notModified ? cursor?.etag : void 0);
1324
+ return etag ? {
1325
+ ...page,
1326
+ etag
1327
+ } : page;
1328
+ }
1329
+ /** Whether `cursor` asks for the first page of a listing: it has neither `nextUrl` nor `token`, though it may have an `etag`. */
1330
+ function isFirstPage(cursor) {
1331
+ return !cursor?.nextUrl && !cursor?.token;
1332
+ }
1333
+ /** The `etag` of `cursor` when it asks for the first page, to send as `If-None-Match`. */
1334
+ function firstPageEtag(cursor) {
1335
+ return isFirstPage(cursor) ? cursor?.etag : void 0;
1336
+ }
1337
+ /** Builds a {@link Listing} for a forge that names its page-size parameter `pageParam`. */
1338
+ function createListing(fetcher, pageParam, defaultPerPage) {
1339
+ return async (path, options, map, { warnings, query, ...extras } = {}) => toPage(await fetcher.page(path, {
1340
+ ...extras,
1341
+ query: {
1342
+ ...query,
1343
+ [pageParam]: options.perPage ?? defaultPerPage
1344
+ },
1345
+ cursor: options.cursor,
1346
+ signal: options.signal
1347
+ }), map, warnings);
1348
+ }
1349
+ /** The `rateLimit` of a page built by hand: the budget of the response behind it, or of the page it maps. */
1350
+ function rateLimitPart(source) {
1351
+ const rateLimit = source && ("headers" in source ? rateLimitOf(source) : source.rateLimit);
1352
+ return rateLimit ? { rateLimit } : {};
1353
+ }
1354
+ /**
1355
+ * Chains listings that a forge serves from separate endpoints. The cursor
1356
+ * `token` records which phase is next, ahead of the phase's own token. With
1357
+ * one phase, the first page is conditional as that phase's is; with more,
1358
+ * one validator cannot cover every endpoint, so no page has an `etag`.
1359
+ */
1360
+ async function phased(phases, cursor) {
1361
+ const match = /^(\d+):(.*)$/s.exec(cursor?.token ?? "");
1362
+ const index = match ? Number(match[1]) : 0;
1363
+ const conditional = phases.length === 1;
1364
+ const inner = cursor && (cursor.nextUrl || match?.[2]) ? {
1365
+ ...cursor,
1366
+ token: match?.[2] || void 0
1367
+ } : conditional && cursor?.etag ? { etag: cursor.etag } : void 0;
1368
+ const { etag, ...rest } = await phases[index](inner);
1369
+ const page = conditional && etag ? {
1370
+ ...rest,
1371
+ etag
1372
+ } : rest;
1373
+ if (page.cursor) return {
1374
+ ...page,
1375
+ cursor: {
1376
+ ...page.cursor,
1377
+ token: `${index}:${page.cursor.token ?? ""}`
1378
+ }
1379
+ };
1380
+ return index + 1 < phases.length ? {
1381
+ ...page,
1382
+ cursor: { token: `${index + 1}:` }
1383
+ } : page;
1384
+ }
1385
+ /** Whether `labels` include every name in `wanted`; true when nothing is wanted. */
1386
+ function hasEveryLabel(labels, wanted) {
1387
+ return !wanted?.length || wanted.every((name) => labels?.some((label) => label.name === name));
1388
+ }
1389
+ /** The counts that are numbers, or `undefined` when none are. */
1390
+ function toPullStats(counts) {
1391
+ const known = Object.entries(counts).filter(([, count]) => typeof count === "number");
1392
+ return known.length ? Object.fromEntries(known) : void 0;
1393
+ }
1394
+ /** Any failure fails, else any pending is pending, else any unknown (or none at all) is unknown, else success. */
1395
+ function summariseChecks(states, url) {
1396
+ const failed = states.filter((state) => state === "failure").length;
1397
+ return {
1398
+ state: failed ? "failure" : states.includes("pending") ? "pending" : !states.length || states.includes("unknown") ? "unknown" : "success",
1399
+ total: states.length,
1400
+ failed,
1401
+ ...url ? { url } : {}
1402
+ };
1403
+ }
1404
+ const FAILED_CONCLUSIONS = /* @__PURE__ */ new Set([
1405
+ "failure",
1406
+ "timed_out",
1407
+ "cancelled",
1408
+ "action_required",
1409
+ "startup_failure"
1410
+ ]);
1411
+ /**
1412
+ * State of a check run reported as a status plus a conclusion once completed.
1413
+ * Cancelled, timed-out, action-required and startup failures count as
1414
+ * failures; skipped and neutral runs as neutral.
1415
+ */
1416
+ function checkRunState(status, conclusion) {
1417
+ if (status !== "completed") return "pending";
1418
+ if (conclusion === "success") return "success";
1419
+ if (conclusion && FAILED_CONCLUSIONS.has(conclusion)) return "failure";
1420
+ return conclusion === "neutral" || conclusion === "skipped" ? "neutral" : "unknown";
1421
+ }
1422
+ /** Maps a forge's own file-change word onto {@link FileStatus}; unknown words become `'changed'`. */
1423
+ function toFileStatus(raw) {
1424
+ switch (raw?.toLowerCase()) {
1425
+ case "added":
1426
+ case "new":
1427
+ case "add": return "added";
1428
+ case "removed":
1429
+ case "deleted":
1430
+ case "remove": return "removed";
1431
+ case "renamed":
1432
+ case "rename": return "renamed";
1433
+ case "copied":
1434
+ case "copy": return "copied";
1435
+ case "modified":
1436
+ case "edit":
1437
+ case "change": return "modified";
1438
+ default: return "changed";
1439
+ }
1440
+ }
1441
+ /**
1442
+ * Caches the result of `load` after its first call. A rejected load is
1443
+ * forgotten so the next call retries; with `ttl` (milliseconds) a resolved
1444
+ * value is reloaded once it is older than that.
1445
+ */
1446
+ function memo(load, ttl) {
1447
+ let cached;
1448
+ return () => {
1449
+ if (!cached || ttl !== void 0 && Date.now() - cached.at > ttl) {
1450
+ const promise = load();
1451
+ cached = {
1452
+ promise,
1453
+ at: Date.now()
1454
+ };
1455
+ promise.catch(() => {
1456
+ if (cached?.promise === promise) cached = void 0;
1457
+ });
1458
+ }
1459
+ return cached.promise;
1460
+ };
1461
+ }
1462
+ /** {@link memo} per key. */
1463
+ function memoBy(load) {
1464
+ const cache = /* @__PURE__ */ new Map();
1465
+ return (key) => {
1466
+ let entry = cache.get(key);
1467
+ if (!entry) {
1468
+ entry = memo(() => load(key));
1469
+ cache.set(key, entry);
1470
+ }
1471
+ return entry();
1472
+ };
1473
+ }
1474
+ /**
1475
+ * A review standing in for an approval, vote or participant state on a forge
1476
+ * that has no review objects. `comments` is `false` because there is nothing
1477
+ * to hang inline comments on.
1478
+ */
1479
+ function syntheticReview(thread, id, state, extras) {
1480
+ const { author, stateRaw, submittedAt, raw } = extras;
1481
+ return {
1482
+ ref: {
1483
+ forge: thread.forge,
1484
+ instance: thread.instance,
1485
+ thread,
1486
+ id
1487
+ },
1488
+ author,
1489
+ state,
1490
+ stateRaw,
1491
+ submittedAt,
1492
+ comments: false,
1493
+ raw
1494
+ };
1495
+ }
1496
+ /** A label colour as six hex digits, with the `#` prefix the forge expects. `ededed` when none is given. */
1497
+ function hexColour(colour, prefix = "") {
1498
+ return `${prefix}${(colour ?? "ededed").replace(/^#/, "")}`;
1499
+ }
1500
+ //#endregion
1501
+ //#region ../forge/dist/index.js
1502
+ /**
1503
+ * Server Env of each Forge, keyed by the `env.server.<forge>.<field>` path.
1504
+ * Channels, Capabilities, Workspaces and Sources read the same names.
1505
+ * `FORGES_*` names are the ones that `forgesFromEnv()` in the `forges` library reads.
1506
+ * Fields without a `forges` equivalent have only a `VITEHUB_` name.
1507
+ */
1508
+ const forgeEnv = {
1509
+ github: {
1510
+ appId: { names: ["VITEHUB_GITHUB_APP_ID", "FORGES_GITHUB_APP_ID"] },
1511
+ installationId: { names: ["VITEHUB_GITHUB_INSTALLATION_ID", "FORGES_GITHUB_INSTALLATION_ID"] },
1512
+ appOwner: { names: ["VITEHUB_GITHUB_APP_OWNER"] },
1513
+ appInstallations: { names: ["VITEHUB_GITHUB_APP_INSTALLATIONS"] },
1514
+ privateKey: {
1515
+ names: ["VITEHUB_GITHUB_PRIVATE_KEY", "FORGES_GITHUB_PRIVATE_KEY"],
1516
+ secret: true
1517
+ },
1518
+ privateKeyPath: { names: ["VITEHUB_GITHUB_PRIVATE_KEY_PATH"] },
1519
+ token: {
1520
+ names: ["VITEHUB_GITHUB_TOKEN", "FORGES_GITHUB_TOKEN"],
1521
+ secret: true
1522
+ },
1523
+ webhookSecret: {
1524
+ names: ["VITEHUB_GITHUB_WEBHOOK_SECRET", "FORGES_GITHUB_WEBHOOK_SECRET"],
1525
+ secret: true
1526
+ }
1527
+ },
1528
+ gitlab: {
1529
+ baseUrl: { names: ["VITEHUB_GITLAB_BASE_URL", "FORGES_GITLAB_BASE_URL"] },
1530
+ token: {
1531
+ names: ["VITEHUB_GITLAB_TOKEN", "FORGES_GITLAB_TOKEN"],
1532
+ secret: true
1533
+ },
1534
+ webhookSecret: {
1535
+ names: ["VITEHUB_GITLAB_WEBHOOK_SECRET", "FORGES_GITLAB_WEBHOOK_SECRET"],
1536
+ secret: true
1537
+ }
1538
+ },
1539
+ forgejo: {
1540
+ baseUrl: { names: ["VITEHUB_FORGEJO_BASE_URL", "FORGES_FORGEJO_BASE_URL"] },
1541
+ token: {
1542
+ names: ["VITEHUB_FORGEJO_TOKEN", "FORGES_FORGEJO_TOKEN"],
1543
+ secret: true
1544
+ },
1545
+ webhookSecret: {
1546
+ names: ["VITEHUB_FORGEJO_WEBHOOK_SECRET", "FORGES_FORGEJO_WEBHOOK_SECRET"],
1547
+ secret: true
1548
+ }
1549
+ }
1550
+ };
1551
+ /**
1552
+ * The first value of `field` that is set, in its lookup order.
1553
+ * `env` is a record, such as `process.env`, or a reader, such as a Cloudflare binding lookup. Default: `process.env`.
1554
+ */
1555
+ function readForgeEnv(field, env = globalThis.process?.env ?? {}) {
1556
+ for (const name of field.names) {
1557
+ const value = typeof env === "function" ? env(name) : env[name];
1558
+ if (!isString(value)) continue;
1559
+ const trimmed = value.trim();
1560
+ if (trimmed) return trimmed;
1561
+ }
1562
+ }
1563
+ function isString(value) {
1564
+ return typeof value === "string";
1565
+ }
1566
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
1567
+ const forgeDiagnostics = /*#__PURE__*/ defineDiagnostics({
1568
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
1569
+ codes: {
1570
+ /** The GitHub App installation lookup failed or the App is not installed. */
1571
+ FORGE_R0001: dynamicError,
1572
+ /** `forgeArchive()` was called for a Forge without archive support. */
1573
+ FORGE_R0002: dynamicError,
1574
+ /** `forgeGitCredentials()` received an invalid base URL or repository. */
1575
+ FORGE_R0003: dynamicError,
1576
+ /** `forgeBlob()` was called for a Forge without blob reads. */
1577
+ FORGE_R0004: dynamicError,
1578
+ /** `forgeCommitFiles()` received a file mode for a Forge without file mode writes. */
1579
+ FORGE_R0005: dynamicError,
1580
+ /** A GitHub-only Forge helper received a provider for another Forge. */
1581
+ FORGE_R0006: dynamicError,
1582
+ /** `githubBranchRuleDetails()` got branch rules that are not complete GitHub rulesets or classic protection. */
1583
+ FORGE_R0007: dynamicError,
1584
+ /** GitHub did not return complete review threads. */
1585
+ FORGE_R0008: dynamicError,
1586
+ /** A GitHub-only Forge helper received a reference that is not a numbered pull request, or an empty input. */
1587
+ FORGE_R0009: dynamicError
1588
+ }
1589
+ });
1590
+ /**
1591
+ * The repository tree at `ref` as a gzipped tarball stream.
1592
+ * Gap: `forges` has no `contents.archive()`. Proposed upstream as `provider.contents.archive(repo, options)`.
1593
+ */
1594
+ async function forgeArchive(provider, repo, options) {
1595
+ if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0002({ message: `Repository archives are not supported for ${provider.forge}.` });
1596
+ const owner = encodeURIComponent(repo.owner);
1597
+ const name = encodeURIComponent(repo.name);
1598
+ const ref = options.ref.split("/").map(encodeURIComponent).join("/");
1599
+ const path = provider.authKind === "anonymous" && provider.baseUrl.replace(/\/+$/, "") === "https://api.github.com" ? `https://codeload.github.com/${owner}/${name}/tar.gz/${ref}` : `/repos/${owner}/${name}/tarball/${ref}`;
1600
+ return (await provider.request("GET", path, {
1601
+ raw: true,
1602
+ signal: options.signal
1603
+ })).body;
1604
+ }
1605
+ async function forgeProvider(connection) {
1606
+ const auth = connection.token ? {
1607
+ type: "token",
1608
+ token: connection.token
1609
+ } : { type: "anonymous" };
1610
+ const options = {
1611
+ ...connection.baseUrl ? { baseUrl: connection.baseUrl } : {},
1612
+ ...connection.fetch ? { fetch: connection.fetch } : {},
1613
+ userAgent: connection.userAgent ?? "vitehub",
1614
+ ...connection.timeout === void 0 ? {} : { timeout: connection.timeout },
1615
+ ...connection.readOnly === void 0 ? {} : { readOnly: connection.readOnly },
1616
+ auth
1617
+ };
1618
+ switch (connection.forge) {
1619
+ case "github": {
1620
+ const { github } = await import("./github-DtncTfmv-Du2S8lGF.js");
1621
+ return github(options);
1622
+ }
1623
+ case "gitlab": {
1624
+ const { gitlab } = await import("./gitlab-BoDm8-BC-xzZsW9eW.js");
1625
+ return gitlab(options);
1626
+ }
1627
+ case "forgejo": {
1628
+ const { forgejo } = await import("./forgejo-BN8ItCfl-Bbn4vhDd.js");
1629
+ return forgejo(options);
1630
+ }
1631
+ }
1632
+ throw new Error("Unsupported Forge.");
1633
+ }
1634
+ /** A Forge response that succeeded but did not include the expected data. */
1635
+ var ForgeResponseError = class extends Error {
1636
+ name = "ForgeResponseError";
1637
+ };
1638
+ /** The HTTP status of a failed Forge request, or undefined for other errors. */
1639
+ function forgeErrorStatus(error) {
1640
+ if (!(error instanceof Error) || !("status" in error)) return void 0;
1641
+ return typeof error.status === "number" ? error.status : void 0;
1642
+ }
1643
+ /** The error that a cancelled Forge operation rejects with. */
1644
+ function abortError(signal) {
1645
+ if (signal.reason instanceof Error) return signal.reason;
1646
+ return new DOMException("The operation was aborted.", "AbortError");
1647
+ }
1648
+ /** Reject with the abort reason when `signal` aborts before `promise` settles. */
1649
+ async function withSignal(promise, signal) {
1650
+ if (!signal) return await promise;
1651
+ if (signal.aborted) {
1652
+ promise.catch(() => void 0);
1653
+ throw abortError(signal);
1654
+ }
1655
+ return await new Promise((resolve, reject) => {
1656
+ const abort = () => reject(abortError(signal));
1657
+ signal.addEventListener("abort", abort, { once: true });
1658
+ promise.then((value) => {
1659
+ signal.removeEventListener("abort", abort);
1660
+ resolve(value);
1661
+ }, (error) => {
1662
+ signal.removeEventListener("abort", abort);
1663
+ reject(error);
1664
+ });
1665
+ });
1666
+ }
1667
+ /**
1668
+ * The bytes of one Git blob, by its sha. The blob of a symlink holds the link target.
1669
+ * Gap: `forges` reads files by path only, and GitHub follows a symlink path to its target.
1670
+ * Proposed upstream as `provider.contents.blob(repo, sha, options)`.
1671
+ */
1672
+ async function forgeBlob(provider, repo, sha, options = {}) {
1673
+ if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0004({ message: `Reading a blob by sha is not supported for ${provider.forge}.` });
1674
+ const { data } = await provider.request("GET", `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}/git/blobs/${encodeURIComponent(sha)}`, { signal: options.signal });
1675
+ const bytes = decodeBase64Blob(data);
1676
+ if (!bytes) throw new ForgeResponseError(`GitHub returned a malformed blob ${sha}.`);
1677
+ return new Uint8Array(bytes);
1678
+ }
1679
+ function decodeBase64Blob(value) {
1680
+ if (!(value instanceof Object) || !("content" in value) || !("encoding" in value) || !("sha" in value)) return void 0;
1681
+ if (typeof value.content !== "string" || value.encoding !== "base64" || typeof value.sha !== "string" || value.sha.length === 0) return void 0;
1682
+ const content = value.content.replace(/\s+/g, "");
1683
+ if (content.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(content)) return void 0;
1684
+ try {
1685
+ const bytes = Buffer.from(content, "base64");
1686
+ return bytes.toString("base64") === content ? bytes : void 0;
1687
+ } catch {
1688
+ return;
1689
+ }
1690
+ }
1691
+ /**
1692
+ * `provider.contents.commitFiles()` with Git file modes, and the sha of the new commit.
1693
+ * Without a `mode`, the call goes to `commitFiles()`. When one change has a `mode`, every write without one is `100644`.
1694
+ * Rejects with `BranchMovedError` when the branch no longer points at `expectedHead`, as `commitFiles()` does.
1695
+ * Gap: `FileChange` has no mode, so `commitFiles()` cannot write a symlink or an executable file.
1696
+ * Proposed upstream as `FileChange.mode`.
1697
+ */
1698
+ async function forgeCommitFiles(provider, repo, input, options = {}) {
1699
+ if (input.changes.length > 0 && !input.changes.some((change) => change.mode)) return (await provider.contents.commitFiles(repo, input, options)).sha;
1700
+ if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0005({ message: `Git file modes are not supported for ${provider.forge}.` });
1701
+ const signal = options.signal;
1702
+ const base = `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}/git`;
1703
+ const branchRef = `heads/${input.branch.split("/").map(encodeURIComponent).join("/")}`;
1704
+ const readHead = async () => sha((await provider.request("GET", `${base}/ref/${branchRef}`, { signal })).data, "object", "branch");
1705
+ const parent = input.createFrom === void 0 ? input.expectedHead ?? await readHead() : await provider.contents.resolveRef(repo, input.createFrom, { signal });
1706
+ const baseTree = sha((await provider.request("GET", `${base}/commits/${encodeURIComponent(parent)}`, { signal })).data, "tree", "commit");
1707
+ const tree = await Promise.all(input.changes.map(async (change) => {
1708
+ if (change.content === null) return {
1709
+ mode: change.mode ?? "100644",
1710
+ path: change.path,
1711
+ sha: null,
1712
+ type: "blob"
1713
+ };
1714
+ const content = Buffer.from(change.content).toString("base64");
1715
+ const blob = await provider.request("POST", `${base}/blobs`, {
1716
+ body: {
1717
+ content,
1718
+ encoding: "base64"
1719
+ },
1720
+ signal
1721
+ });
1722
+ return {
1723
+ mode: change.mode ?? "100644",
1724
+ path: change.path,
1725
+ sha: sha(blob.data, void 0, "blob"),
1726
+ type: "blob"
1727
+ };
1728
+ }));
1729
+ const treeSha = sha((await provider.request("POST", `${base}/trees`, {
1730
+ body: {
1731
+ base_tree: baseTree,
1732
+ tree
1733
+ },
1734
+ signal
1735
+ })).data, void 0, "tree");
1736
+ const commit = sha((await provider.request("POST", `${base}/commits`, {
1737
+ body: {
1738
+ message: input.message,
1739
+ parents: [parent],
1740
+ tree: treeSha,
1741
+ ...input.author ? { author: input.author } : {}
1742
+ },
1743
+ signal
1744
+ })).data, void 0, "commit");
1745
+ if (input.createFrom !== void 0) {
1746
+ await provider.request("POST", `${base}/refs`, {
1747
+ body: {
1748
+ ref: `refs/heads/${input.branch}`,
1749
+ sha: commit
1750
+ },
1751
+ signal
1752
+ });
1753
+ return commit;
1754
+ }
1755
+ try {
1756
+ await provider.request("PATCH", `${base}/refs/${branchRef}`, {
1757
+ body: {
1758
+ force: false,
1759
+ sha: commit
1760
+ },
1761
+ signal
1762
+ });
1763
+ } catch (error) {
1764
+ const status = forgeErrorStatus(error);
1765
+ if (status !== 409 && status !== 422) throw error;
1766
+ const head = await readHead();
1767
+ if (head === parent) throw error;
1768
+ throw new BranchMovedError(`${input.branch} is at ${head}, not ${parent}`, status, "", {
1769
+ forge: provider.forge,
1770
+ instance: provider.instance
1771
+ }, { cause: error });
1772
+ }
1773
+ return commit;
1774
+ }
1775
+ /** The `sha` of a GitHub Git database response, or of its `key` object. */
1776
+ function sha(value, key, description) {
1777
+ const target = key && value instanceof Object && key in value ? Reflect.get(value, key) : value;
1778
+ const result = target instanceof Object && "sha" in target ? target.sha : void 0;
1779
+ if (typeof result !== "string" || !result) throw new ForgeResponseError(`GitHub returned a malformed ${description} response.`);
1780
+ return result;
1781
+ }
1782
+ //#endregion
1783
+ //#region ../internal/src/runtime/cloudflare-env.ts
1784
+ let activeEnv;
1785
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
1786
+ const runtimeGlobal = globalThis;
1787
+ const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
1788
+ const globalEnvProbe = Symbol("vitehub.cloudflare.global-env-probe");
1789
+ /**
1790
+ * Under the Nitro Cloudflare dev server, `cloudflare:workers` exports unenv's env proxy, which reads every key from
1791
+ * `globalThis.__env__`. Storing that proxy in `__env__` makes it read itself, and the next read overflows the stack.
1792
+ */
1793
+ function readsGlobalEnv(env) {
1794
+ const scope = globalThis;
1795
+ const owned = Object.hasOwn(scope, "__env__");
1796
+ const previous = scope.__env__;
1797
+ scope.__env__ = { [globalEnvProbe]: true };
1798
+ try {
1799
+ return Reflect.get(env, globalEnvProbe) === true;
1800
+ } catch {
1801
+ return false;
1802
+ } finally {
1803
+ if (owned) scope.__env__ = previous;
1804
+ else delete scope.__env__;
1805
+ }
1806
+ }
1807
+ function setActiveCloudflareEnv(env) {
1808
+ activeEnv = env;
1809
+ if (!env || !readsGlobalEnv(env)) globalThis.__env__ = env;
1810
+ try {
1811
+ activeEnvStorage.enterWith({ env });
1812
+ } catch {}
1813
+ }
1814
+ function getActiveCloudflareEnv() {
1815
+ const scoped = activeEnvStorage.getStore();
1816
+ if (scoped) return scoped.env;
1817
+ const host = globalThis;
1818
+ return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
1819
+ }
1820
+ function getActiveCloudflareBinding(name) {
1821
+ const env = getActiveCloudflareEnv();
1822
+ return env && Object.hasOwn(env, name) ? env[name] : void 0;
1823
+ }
1824
+ //#endregion
1825
+ //#region src/providers/github/shared.ts
1826
+ const githubReadAttempts = 3;
1827
+ function retryDelay(response, attempt) {
1828
+ const retryAfter = response.headers.get("retry-after");
1829
+ if (retryAfter) {
1830
+ const seconds = Number(retryAfter);
1831
+ if (Number.isFinite(seconds)) return Math.min(seconds * 1e3, 2e3);
1832
+ const date = Date.parse(retryAfter);
1833
+ if (Number.isFinite(date)) return Math.min(Math.max(date - Date.now(), 0), 2e3);
1834
+ }
1835
+ return 100 * 2 ** attempt;
1836
+ }
1837
+ async function waitForRetry(delay, signal) {
1838
+ signal?.throwIfAborted();
1839
+ await new Promise((resolve, reject) => {
1840
+ const aborted = () => {
1841
+ clearTimeout(timeout);
1842
+ reject(signal?.reason || new DOMException("The operation was aborted.", "AbortError"));
1843
+ };
1844
+ const timeout = setTimeout(() => {
1845
+ signal?.removeEventListener("abort", aborted);
1846
+ resolve();
1847
+ }, delay);
1848
+ signal?.addEventListener("abort", aborted, { once: true });
1849
+ });
1850
+ }
1851
+ /** `fetch` that retries reads after a network error, a 429 or a 5xx response. The Forge provider sends every request through it. */
1852
+ async function requestGitHub(input, init = {}) {
1853
+ const method = (init.method || "GET").toUpperCase();
1854
+ const retryable = method === "GET" || method === "HEAD";
1855
+ for (let attempt = 0;; attempt++) {
1856
+ init.signal?.throwIfAborted();
1857
+ let response;
1858
+ try {
1859
+ response = await fetch(input, init);
1860
+ } catch (error) {
1861
+ if (!retryable || init.signal?.aborted || attempt + 1 >= githubReadAttempts) throw error;
1862
+ await waitForRetry(100 * 2 ** attempt, init.signal);
1863
+ continue;
1864
+ }
1865
+ if (!retryable || response.status !== 429 && response.status < 500 || attempt + 1 >= githubReadAttempts) return response;
1866
+ await response.body?.cancel().catch(() => void 0);
1867
+ await waitForRetry(retryDelay(response, attempt), init.signal);
1868
+ }
1869
+ }
1870
+ /** A lazy connection: the repository name is checked on the first request. */
1871
+ function connectGitHubRepository(repository, token) {
1872
+ let provider;
1873
+ return {
1874
+ name: repository,
1875
+ blobReadKey: (sha) => JSON.stringify([
1876
+ repository,
1877
+ token,
1878
+ sha
1879
+ ]),
1880
+ provider: async () => {
1881
+ splitGitHubRepository(repository);
1882
+ return await (provider ||= forgeProvider({
1883
+ fetch: requestGitHub,
1884
+ forge: "github",
1885
+ token,
1886
+ userAgent: "vitehub-workspace"
1887
+ }));
1888
+ },
1889
+ ref: (client) => {
1890
+ const { owner, repo } = splitGitHubRepository(repository);
1891
+ return {
1892
+ forge: client.forge,
1893
+ instance: client.instance,
1894
+ name: repo,
1895
+ owner
1896
+ };
1897
+ }
1898
+ };
1899
+ }
1900
+ /**
1901
+ * Run one Forge call. A failed request becomes a Workspace error that keeps the Forge error as its cause.
1902
+ * With `response`, a `TypeError` from the Forge response mapping becomes a malformed `response` error.
1903
+ */
1904
+ async function githubRequest(repository, run, response) {
1905
+ const provider = await repository.provider();
1906
+ try {
1907
+ return await run(provider, repository.ref(provider));
1908
+ } catch (error) {
1909
+ const status = forgeErrorStatus(error);
1910
+ if (status === void 0 && response && error instanceof TypeError) throw workspaceError(`[vitehub] GitHub workspace returned a malformed ${response} response.`, { cause: error });
1911
+ if (status === void 0) throw error;
1912
+ throw workspaceError(`[vitehub] GitHub workspace request failed for ${repository.name}: ${status} ${error instanceof Error ? error.message : ""}`.trim(), { cause: error });
1913
+ }
1914
+ }
1915
+ /** The HTTP status of the GitHub request behind a Workspace error. */
1916
+ function githubRequestStatus(error) {
1917
+ return forgeErrorStatus(error) ?? (error instanceof Error ? forgeErrorStatus(error.cause) : void 0);
1918
+ }
1919
+ function githubBranchMovedConflict(input) {
1920
+ 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: {
1921
+ actualHead: input.actualHead,
1922
+ branch: input.branch,
1923
+ expectedHead: input.expectedHead,
1924
+ repository: input.repository
1925
+ } });
1926
+ }
1927
+ function resolveGitHubOption(value) {
1928
+ const resolved = typeof value === "function" ? value() : value;
1929
+ return typeof resolved === "string" ? resolved.trim() || void 0 : resolved;
1930
+ }
1931
+ function isMaskedGitHubTokenOption(value) {
1932
+ return value === "********" || value === "<redacted>" || value === "[redacted]";
1933
+ }
1934
+ /** The first location value that is set, from the active Cloudflare bindings and then from `env`. */
1935
+ function readLocationEnv(name, env) {
1936
+ const binding = getActiveCloudflareBinding(name);
1937
+ if (typeof binding === "string" && binding.trim()) return binding.trim();
1938
+ return env[name]?.trim() || void 0;
1939
+ }
1940
+ /** The Server Env GitHub token: `VITEHUB_GITHUB_TOKEN`, then `FORGES_GITHUB_TOKEN`, from the active Cloudflare bindings and then from `env`. */
1941
+ function readGitHubEnvToken(env = typeof process !== "undefined" ? process.env : {}) {
1942
+ const binding = readForgeEnv(forgeEnv.github.token, (name) => getActiveCloudflareBinding(name));
1943
+ if (binding && !isMaskedGitHubTokenOption(binding)) return binding;
1944
+ return readForgeEnv(forgeEnv.github.token, env);
1945
+ }
1946
+ function requireGitHubOption(label, value) {
1947
+ if (!value) throw workspaceErrorDiagnostics.WORKSPACE_R0072({ message: `[vitehub] GitHub workspace store requires ${label}.${label === "a token" ? " Set VITEHUB_GITHUB_TOKEN or the token option." : label === "a repository" ? " Set the repository option or VITEHUB_WORKSPACE_GITHUB_REPOSITORY." : ""}` });
1948
+ return value;
1949
+ }
1950
+ function splitGitHubRepository(repository) {
1951
+ const parts = repository.split("/");
1952
+ const owner = parts[0];
1953
+ const repo = parts[1];
1954
+ 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.");
1955
+ return {
1956
+ owner,
1957
+ repo
1958
+ };
1959
+ }
1960
+ function joinGitPath(...parts) {
1961
+ return parts.join("/").replaceAll("\\", "/").split("/").filter(Boolean).join("/");
1962
+ }
1963
+ function resolveGitHubWorkspaceRoot(root, workspaceName) {
1964
+ return normalizeSafeWorkspacePath(joinGitPath(root.replaceAll("<workspace>", workspaceName)), {
1965
+ allowEmpty: true,
1966
+ allowReserved: true
1967
+ });
1968
+ }
1969
+ function workspacePathFromGitPath(path, root) {
1970
+ const normalized = joinGitPath(path);
1971
+ const normalizedRoot = joinGitPath(root);
1972
+ if (!normalizedRoot) return normalizeWorkspacePath(normalized);
1973
+ if (!normalized.startsWith(`${normalizedRoot}/`)) return void 0;
1974
+ return normalizeWorkspacePath(normalized.slice(normalizedRoot.length + 1));
1975
+ }
1976
+ function toHex(bytes) {
1977
+ return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
1978
+ }
1979
+ /** The Git blob sha of `bytes`. Workspace digests are Git blob shas, so local writes compare with the remote tree. */
1980
+ async function gitBlobSha(bytes) {
1981
+ const prefix = new TextEncoder().encode(`blob ${bytes.byteLength}\0`);
1982
+ const input = new Uint8Array(prefix.byteLength + bytes.byteLength);
1983
+ input.set(prefix);
1984
+ input.set(bytes, prefix.byteLength);
1985
+ return toHex(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-1", input)));
1986
+ }
1987
+ function gitFileMode(value) {
1988
+ return value === "120000" || value === "100755" ? value : "100644";
1989
+ }
1990
+ function resolveGitHubRepositoryOption(options, env = typeof process !== "undefined" ? process.env : {}) {
1991
+ return resolveGitHubOption(options.repository) || resolveGitHubOption(options.repo) || readLocationEnv("VITEHUB_WORKSPACE_GITHUB_REPOSITORY", env);
1992
+ }
1993
+ function resolveGitHubBranchOption(options, env = typeof process !== "undefined" ? process.env : {}) {
1994
+ return resolveGitHubOption(options.branch) || readLocationEnv("VITEHUB_WORKSPACE_GITHUB_BRANCH", env) || "main";
1995
+ }
1996
+ function resolveGitHubRootOption(options, workspaceName, env = typeof process !== "undefined" ? process.env : {}) {
1997
+ return resolveGitHubWorkspaceRoot(options.root === "" ? "" : resolveGitHubOption(options.root) || readLocationEnv("VITEHUB_WORKSPACE_GITHUB_ROOT", env) || ".vitehub/workspaces/<workspace>", workspaceName);
1998
+ }
1999
+ /** The branch names for the history refs `published` and `draft`, or undefined when there are none. */
2000
+ function resolveGitHubRefsOption(options) {
2001
+ const refs = options.refs;
2002
+ if (!refs) return void 0;
2003
+ const published = refs.published?.trim() || void 0;
2004
+ const draft = refs.draft?.trim() || void 0;
2005
+ if (published && published === draft) throw workspaceError(`[vitehub] GitHub workspace store refs.published and refs.draft name the same branch: ${published}.`);
2006
+ return published || draft ? {
2007
+ ...published ? { published } : {},
2008
+ ...draft ? { draft } : {}
2009
+ } : void 0;
2010
+ }
2011
+ function resolveGitHubTokenOption(options, env = typeof process !== "undefined" ? process.env : {}) {
2012
+ const token = resolveGitHubOption(options.token);
2013
+ if (token && !isMaskedGitHubTokenOption(token)) return token;
2014
+ return readGitHubEnvToken(env);
2015
+ }
2016
+ const githubBlobs = /* @__PURE__ */ new Map();
2017
+ const githubBlobReads = /* @__PURE__ */ new Map();
2018
+ const githubBlobByteLimit = 33554432;
2019
+ const githubBlobFileLimit = 4194304;
2020
+ let githubBlobBytes = 0;
2021
+ /** 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. */
2022
+ async function readGitHubFile(repository, entry, ref, signal) {
2023
+ signal?.throwIfAborted();
2024
+ const cached = githubBlobs.get(entry.sha);
2025
+ if (cached) return cached.slice();
2026
+ const readKey = repository.blobReadKey(entry.sha);
2027
+ let read = githubBlobReads.get(readKey);
2028
+ if (!read) {
2029
+ read = githubRequest(repository, async (provider, repo) => {
2030
+ return await forgeBlob(provider, repo, entry.sha);
2031
+ }).then(async (bytes) => {
2032
+ if (await gitBlobSha(bytes) !== entry.sha) throw workspaceError("[vitehub] GitHub workspace returned a malformed blob response.");
2033
+ if (bytes.byteLength <= githubBlobFileLimit && !githubBlobs.has(entry.sha)) {
2034
+ for (const [sha, oldest] of githubBlobs) {
2035
+ if (githubBlobBytes + bytes.byteLength <= githubBlobByteLimit) break;
2036
+ githubBlobs.delete(sha);
2037
+ githubBlobBytes -= oldest.byteLength;
2038
+ }
2039
+ githubBlobs.set(entry.sha, bytes);
2040
+ githubBlobBytes += bytes.byteLength;
2041
+ }
2042
+ return bytes;
2043
+ }).finally(() => {
2044
+ githubBlobReads.delete(readKey);
2045
+ });
2046
+ githubBlobReads.set(readKey, read);
2047
+ }
2048
+ return (await withSignal(read, signal)).slice();
2049
+ }
2050
+ async function readGitHubArchive(repository, ref, signal) {
2051
+ return await githubRequest(repository, async (provider, repo) => {
2052
+ const stream = await forgeArchive(provider, repo, {
2053
+ ref,
2054
+ signal
2055
+ });
2056
+ return new Uint8Array(await new Response(stream).arrayBuffer());
2057
+ });
2058
+ }
2059
+ /** The files and symlinks of the tree at `ref`, by their Workspace path under `root`. */
2060
+ async function readGitHubTree(repository, ref, root) {
2061
+ return await githubRequest(repository, async (provider, repo) => {
2062
+ const tree = provider.contents.tree(repo, {
2063
+ recursive: true,
2064
+ ref
2065
+ });
2066
+ const files = /* @__PURE__ */ new Map();
2067
+ for await (const entry of tree) {
2068
+ if (entry.type !== "file" && entry.type !== "symlink") continue;
2069
+ if (!entry.sha) throw workspaceError("[vitehub] GitHub workspace returned a malformed tree response.");
2070
+ const path = workspacePathFromGitPath(entry.path, root);
2071
+ if (path) files.set(path, {
2072
+ mode: gitFileMode(entry.mode),
2073
+ path: entry.path,
2074
+ sha: entry.sha,
2075
+ size: entry.size
2076
+ });
2077
+ }
2078
+ 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.");
2079
+ return files;
2080
+ }, "tree");
2081
+ }
2082
+ function isMissingRef(error) {
2083
+ const status = githubRequestStatus(error);
2084
+ return status === 404 || status === 422;
2085
+ }
2086
+ /** The head of `branch` right now, or null when it does not exist. */
2087
+ async function readCurrentHead(repository, branch) {
2088
+ try {
2089
+ return await githubRequest(repository, async (provider, repo) => await provider.contents.resolveRef(repo, `heads/${branch}`), "commit") || null;
2090
+ } catch (error) {
2091
+ if (isMissingRef(error)) return null;
2092
+ throw error;
2093
+ }
2094
+ }
2095
+ /**
2096
+ * The head of `branch` and the files under `root`. When `branch` does not exist yet, they come from `fork` if it
2097
+ * exists, else from the default branch, and `branchExists` is false.
2098
+ */
2099
+ async function readGitHubBranchState(input) {
2100
+ const resolve = async (branch) => {
2101
+ const sha = await githubRequest(input.repository, async (provider, repo) => await provider.contents.resolveRef(repo, `heads/${branch}`), "commit");
2102
+ if (!sha) throw workspaceError("[vitehub] GitHub workspace returned a malformed commit response.");
2103
+ return sha;
2104
+ };
2105
+ let branchExists = true;
2106
+ let refSha;
2107
+ try {
2108
+ refSha = await resolve(input.branch);
2109
+ } catch (error) {
2110
+ if (!isMissingRef(error)) throw error;
2111
+ branchExists = false;
2112
+ const forked = input.from ?? (input.fork ? await readCurrentHead(input.repository, input.fork) : null);
2113
+ if (forked) refSha = forked;
2114
+ else {
2115
+ const repository = await githubRequest(input.repository, async (provider, repo) => await provider.repos.get(repo), "repository");
2116
+ if (!repository.defaultBranch) throw workspaceError("[vitehub] GitHub workspace returned a malformed repository response.");
2117
+ refSha = await resolve(repository.defaultBranch);
2118
+ }
2119
+ }
2120
+ return {
2121
+ branchExists,
2122
+ files: await readGitHubTree(input.repository, refSha, input.root),
2123
+ refSha
2124
+ };
2125
+ }
2126
+ /**
2127
+ * Write and delete files in one commit on `branch`, and return the commit sha.
2128
+ * A branch that does not exist yet is created from `parentSha`.
2129
+ * Rejects with a Workspace conflict when the branch no longer points at `parentSha`.
2130
+ */
2131
+ async function commitGitHubChanges(input) {
2132
+ const needsModes = input.files.some((file) => file.mode !== "100644" || (input.remoteModes?.get(file.fullPath) ?? "100644") !== "100644");
2133
+ const changes = [...input.files.map((file) => ({
2134
+ content: file.bytes,
2135
+ path: file.fullPath,
2136
+ ...needsModes ? { mode: file.mode } : {}
2137
+ })), ...input.deletePaths.map((path) => ({
2138
+ content: null,
2139
+ path
2140
+ }))];
2141
+ try {
2142
+ return await githubRequest(input.repository, async (provider, repo) => await forgeCommitFiles(provider, repo, {
2143
+ branch: input.branch,
2144
+ changes,
2145
+ message: input.message,
2146
+ ...input.branchExists ? { expectedHead: input.parentSha } : { createFrom: input.parentSha }
2147
+ }));
2148
+ } catch (error) {
2149
+ if (error instanceof BranchMovedError || error instanceof Error && error.cause instanceof BranchMovedError) throw githubBranchMovedConflict({
2150
+ branch: input.branch,
2151
+ expectedHead: input.parentSha,
2152
+ repository: input.repository.name
2153
+ });
2154
+ throw error;
2155
+ }
2156
+ }
2157
+ //#endregion
2158
+ export { forgeIterable as $, ForgeError as A, resolveToken as At, TokenRevokedError as B, toPullStats as Bt, forgeEnv as C, rateLimitPart as Ct, ContentNotTextError as D, requireIssueOrPull as Dt, BranchMovedError as E, referenceFor as Et, NotFoundError as F, teamOrg as Ft, actorLogin as G, UnsupportedOperationError as H, versionAtLeast as Ht, OWNER_NAME as I, toDate as It, createFetcher as J, anySignal as K, REACTION_CONTENTS as L, toFileStatus as Lt, InsufficientScopeError as M, soleMergeMethod as Mt, MergeBlockedError as N, summariseChecks as Nt, ForbiddenError as O, requireThread as Ot, MergeConflictError as P, syntheticReview as Pt, firstPageEtag as Q, RateLimitedError as R, toMergeError as Rt, forgeBlob as S, rateLimitOf as St, AuthenticationRequiredError as T, reactionContent as Tt, WebhookVerificationError as U, webUrlFor as Ut, UnresolvedThreadError as V, toWarning as Vt, abortable as W, withEtag as Wt, createRequest as X, createListing as Y, degradesToWarning as Z, resolveGitHubRepositoryOption as _, milestoneId as _t, githubBranchMovedConflict as a, isFirstPage as at, getActiveCloudflareBinding as b, phased as bt, joinGitPath as c, isSecondaryRateLimit as ct, readGitHubBranchState as d, latestCommentOf as dt, getManyConcurrently as et, readGitHubEnvToken as f, lineOf as ft, resolveGitHubRefsOption as g, mergeCommitMessage as gt, resolveGitHubBranchOption as h, memoBy as ht, gitFileMode as i, hostOf as it, ForgeTimeoutError as j, sleep as jt, ForgeApiError as k, resolveInstance as kt, readCurrentHead as l, isUnsupported as lt, requireGitHubOption as m, memo as mt, connectGitHubRepository as n, hasEveryLabel as nt, githubRequest as o, isNamespaceRef as ot, readGitHubFile as p, mapConcurrent as pt, checkRunState as q, gitBlobSha as r, hexColour as rt, githubRequestStatus as s, isResolvedThread as st, commitGitHubChanges as t, githubShapedWeb as tt, readGitHubArchive as u, iteratePages as ut, resolveGitHubRootOption as v, parseReferences as vt, readForgeEnv as w, rateLimitReset as wt, setActiveCloudflareEnv as x, rangeOf as xt, resolveGitHubTokenOption as y, parseWebUrl as yt, ReadOnlyError as z, toPage as zt };