@effected/github 0.29.0 → 0.31.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.
@@ -0,0 +1,358 @@
1
+ import { GitHubClient } from "./GitHubClient.js";
2
+ import { GitHubGraphQLError, GraphQLDocument } from "./GraphQL.js";
3
+ import { unstubbed } from "./internal/unstubbed.js";
4
+ import { Repo } from "./Repo.js";
5
+ import { Context, Effect, Exit, Layer, Option, Request, RequestResolver, Schema } from "effect";
6
+
7
+ // src/ChangelogInfo.ts
8
+ /**
9
+ * A changelog lookup was handed a commit sha or pull request number it cannot
10
+ * send.
11
+ *
12
+ * @remarks
13
+ * The batch names each lookup by an alias built from its input
14
+ * (`commit__<sha>`, `pull__<number>`), so the input must be something a
15
+ * GraphQL alias can carry: a hexadecimal sha of 4 to 64 characters, or a
16
+ * positive integer. Nothing is sent when this fails.
17
+ *
18
+ * @public
19
+ */
20
+ var InvalidChangelogRefError = class extends Schema.TaggedError()("InvalidChangelogRefError", {
21
+ /** Which lookup refused it. */
22
+ ref: Schema.Literals(["commit", "pull"]),
23
+ /** What was handed in, as text. */
24
+ input: Schema.String
25
+ }) {
26
+ get message() {
27
+ return this.ref === "commit" ? `not a hexadecimal commit sha of 4 to 64 characters: ${JSON.stringify(this.input)}` : `not a positive pull request number: ${this.input}`;
28
+ }
29
+ };
30
+ /**
31
+ * What a changelog line says about one commit.
32
+ *
33
+ * @remarks
34
+ * The shape `@changesets/get-github-info`'s `getInfo` returns, with every
35
+ * value that can be missing as an `Option`. The links are markdown, in
36
+ * upstream's exact format: the short sha in a code span linked to the commit
37
+ * URL, `[#42](https://github.com/acme/widget/pull/42)` and
38
+ * `[@octocat](https://github.com/octocat)`. Every URL is the one GitHub answered with, so on
39
+ * GitHub Enterprise Server the links name that server; nothing here builds a
40
+ * URL from a configured host.
41
+ *
42
+ * @public
43
+ */
44
+ var CommitChangelogInfo = class extends Schema.Class("CommitChangelogInfo")({
45
+ /**
46
+ * The login to credit: the pull request's author when the commit has one,
47
+ * otherwise the GitHub user the commit's author maps to.
48
+ */
49
+ user: Schema.Option(Schema.String),
50
+ /** The pull request the commit landed through: the earliest-merged one, else the first GitHub lists. */
51
+ pull: Schema.Option(Schema.Int),
52
+ /** Markdown links for the line. */
53
+ links: Schema.Struct({
54
+ /** The first 7 characters of the sha asked for, in a code span, linked to the commit URL. */
55
+ commit: Schema.String,
56
+ /** `#` and the number, linked to the pull request URL, when there is a pull request. */
57
+ pull: Schema.Option(Schema.String),
58
+ /** `@` and the login, linked to the user's URL, when there is a user. */
59
+ user: Schema.Option(Schema.String)
60
+ })
61
+ }) {};
62
+ /**
63
+ * What a changelog line says about one pull request.
64
+ *
65
+ * @remarks
66
+ * The shape `@changesets/get-github-info`'s `getInfoFromPullRequest` returns,
67
+ * for a changeset that names its pull request (`pr: #42`) instead of leaving
68
+ * it to the commit. Links are in the same format as
69
+ * {@link CommitChangelogInfo}'s, from the URLs GitHub answered with.
70
+ *
71
+ * @public
72
+ */
73
+ var PullRequestChangelogInfo = class extends Schema.Class("PullRequestChangelogInfo")({
74
+ /** The pull request author's login. */
75
+ user: Schema.Option(Schema.String),
76
+ /** The merge commit's abbreviated sha, once the pull request has merged. */
77
+ commit: Schema.Option(Schema.String),
78
+ /** Markdown links for the line. */
79
+ links: Schema.Struct({
80
+ /** The first 7 characters of the abbreviated merge sha, in a code span, linked to the commit URL, once merged. */
81
+ commit: Schema.Option(Schema.String),
82
+ /** `#` and the number, linked to the pull request URL. */
83
+ pull: Schema.String,
84
+ /** `@` and the login, linked to the user's URL, when the author still exists. */
85
+ user: Schema.Option(Schema.String)
86
+ })
87
+ }) {};
88
+ /**
89
+ * The commit and pull request facts a changelog line credits, batched into
90
+ * one GraphQL query.
91
+ *
92
+ * @remarks
93
+ * The kit's `@changesets/get-github-info`. The token and the server come from
94
+ * the `GitHubClient` the layer is built over, and the repository from `Repo`;
95
+ * nothing is read from the environment. The query is upstream's, alias for
96
+ * alias, so concurrent lookups cost one round trip per 50.
97
+ *
98
+ * Two answers differ from upstream's, both toward the lookup convention: a
99
+ * pull request number the repository does not have is `Option.none()` (GitHub
100
+ * reports it as an error, which upstream throws for the whole batch), and a
101
+ * sha naming a tree or blob is `Option.none()` (upstream builds links to
102
+ * `undefined`). A missing repository still fails, with `kind: "notFound"`.
103
+ *
104
+ * Batching happens within one built service: each `ChangelogInfo.layer`
105
+ * build owns its own resolver, and nothing is cached across batches.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * import { ChangelogInfo } from "@effected/github";
110
+ * import { Effect, Option } from "effect";
111
+ *
112
+ * const lines = (shas: ReadonlyArray<string>) =>
113
+ * Effect.gen(function* () {
114
+ * const info = yield* ChangelogInfo;
115
+ * const found = yield* Effect.forEach(shas, info.commit, { concurrency: "unbounded" });
116
+ * return found.flatMap((entry) =>
117
+ * Option.match(entry, {
118
+ * onNone: () => [],
119
+ * onSome: ({ links }) => [`${Option.getOrElse(links.pull, () => links.commit)} Thanks ${Option.getOrElse(links.user, () => "")}`],
120
+ * }),
121
+ * );
122
+ * });
123
+ * ```
124
+ *
125
+ * @public
126
+ */
127
+ var ChangelogInfo = class ChangelogInfo extends Context.Service()("@effected/github/ChangelogInfo") {
128
+ /** The live service, built over a `GitHubClient`. */
129
+ static layer = Layer.effect(this, Effect.map(GitHubClient, (client) => make(client)));
130
+ /** An in-memory double; an unstubbed member dies when run, naming itself. */
131
+ static makeTest = (overrides = {}) => ({
132
+ commit: overrides.commit ?? (() => dies("commit")),
133
+ pullRequest: overrides.pullRequest ?? (() => dies("pullRequest"))
134
+ });
135
+ /** {@link ChangelogInfo.makeTest} behind a `Layer`. */
136
+ static layerTest = (overrides = {}) => Layer.succeed(ChangelogInfo, ChangelogInfo.makeTest(overrides));
137
+ };
138
+ const dies = unstubbed("ChangelogInfo.makeTest");
139
+ /** Upstream's batch size (its dataloader's `maxBatchSize`). */
140
+ const BATCH_SIZE = 50;
141
+ /** The one repository alias a batch uses: a batch is always one repository. */
142
+ const REPO_ALIAS = "repo__0";
143
+ const SHA = /^[0-9a-f]{4,64}$/i;
144
+ const CommitLookup = Request.tagged("CommitLookup");
145
+ const PullLookup = Request.tagged("PullLookup");
146
+ const aliasOf = (lookup) => lookup._tag === "CommitLookup" ? `commit__${lookup.sha}` : `pull__${lookup.number}`;
147
+ const Actor = Schema.Struct({
148
+ login: Schema.String,
149
+ url: Schema.String
150
+ });
151
+ const AssociatedPull = Schema.Struct({
152
+ number: Schema.Int,
153
+ url: Schema.String,
154
+ mergedAt: Schema.NullOr(Schema.String),
155
+ author: Schema.NullOr(Actor)
156
+ });
157
+ const CommitNode = Schema.Struct({
158
+ commitUrl: Schema.String,
159
+ associatedPullRequests: Schema.NullOr(Schema.Struct({ nodes: Schema.NullOr(Schema.Array(Schema.NullOr(AssociatedPull))) })),
160
+ author: Schema.NullOr(Schema.Struct({ user: Schema.NullOr(Actor) }))
161
+ });
162
+ /** `object(expression:)` answers `{}` when the sha names a tree or blob: `... on Commit` selects nothing. */
163
+ const NotACommit = Schema.Record(Schema.String, Schema.Never);
164
+ const PullNode = Schema.Struct({
165
+ url: Schema.String,
166
+ author: Schema.NullOr(Actor),
167
+ mergeCommit: Schema.NullOr(Schema.Struct({
168
+ commitUrl: Schema.String,
169
+ abbreviatedOid: Schema.String
170
+ }))
171
+ });
172
+ const COMMIT_FRAGMENT = `\
173
+ fragment CommitFragment on Commit {
174
+ commitUrl
175
+ associatedPullRequests(first: 50) {
176
+ nodes {
177
+ number
178
+ url
179
+ mergedAt
180
+ author {
181
+ login
182
+ url
183
+ }
184
+ }
185
+ }
186
+ author {
187
+ user {
188
+ login
189
+ url
190
+ }
191
+ }
192
+ }
193
+ `;
194
+ const PULL_FRAGMENT = `\
195
+ fragment PullFragment on PullRequest {
196
+ url
197
+ author {
198
+ login
199
+ url
200
+ }
201
+ mergeCommit {
202
+ commitUrl
203
+ abbreviatedOid
204
+ }
205
+ }
206
+ `;
207
+ /**
208
+ * Upstream's `makeQuery` for one repository, character for character.
209
+ *
210
+ * @remarks
211
+ * Values are inlined, as upstream does, and that is safe only because of what
212
+ * reaches here: owner and name through `JSON.stringify` (a JSON string literal
213
+ * is a GraphQL string literal), a sha that matched {@link SHA} and a positive
214
+ * integer. Aliases are built from the same validated values.
215
+ */
216
+ const queryFor = (owner, repo, lookups) => {
217
+ let query = `query {\n ${REPO_ALIAS}: repository(\n owner: ${JSON.stringify(owner)},\n name: ${JSON.stringify(repo)}\n ) {\n`;
218
+ for (const lookup of lookups) query += lookup._tag === "CommitLookup" ? ` ${aliasOf(lookup)}: object(expression: ${JSON.stringify(lookup.sha)}) {\n ... on Commit {\n ...CommitFragment\n }\n }\n` : ` ${aliasOf(lookup)}: pullRequest(number: ${JSON.stringify(lookup.number)}) {\n ...PullFragment\n }\n`;
219
+ query += " }\n}\n";
220
+ if (lookups.some((lookup) => lookup._tag === "CommitLookup")) query += COMMIT_FRAGMENT;
221
+ if (lookups.some((lookup) => lookup._tag === "PullLookup")) query += PULL_FRAGMENT;
222
+ return query;
223
+ };
224
+ /** The whole answer: one repository alias holding one field per lookup alias, each decoded on its own. */
225
+ const BatchResponse = Schema.Struct({ [REPO_ALIAS]: Schema.NullOr(Schema.Record(Schema.String, Schema.Unknown)) });
226
+ const documentFor = (owner, repo, lookups) => GraphQLDocument.make({
227
+ name: "changelogInfo",
228
+ document: queryFor(owner, repo, lookups),
229
+ response: BatchResponse
230
+ })();
231
+ const decodeCommit = Schema.decodeUnknownEffect(Schema.NullOr(Schema.Union([CommitNode, NotACommit])));
232
+ const decodePull = Schema.decodeUnknownEffect(Schema.NullOr(PullNode));
233
+ /**
234
+ * The pull request aliases GitHub reported as not found, when that is all it
235
+ * reported; `undefined` when any entry is something else, such as the
236
+ * repository itself being missing.
237
+ */
238
+ const missingPulls = (error, lookups) => {
239
+ if (error.kind !== "notFound" || error.errors.length === 0) return void 0;
240
+ const pulls = new Set(lookups.filter((lookup) => lookup._tag === "PullLookup").map(aliasOf));
241
+ const missing = /* @__PURE__ */ new Set();
242
+ for (const entry of error.errors) {
243
+ const [repoStep, fieldStep, ...rest] = entry.path ?? [];
244
+ if (entry.type !== "NOT_FOUND" || repoStep !== REPO_ALIAS || rest.length > 0) return void 0;
245
+ if (typeof fieldStep !== "string" || !pulls.has(fieldStep)) return void 0;
246
+ missing.add(fieldStep);
247
+ }
248
+ return missing;
249
+ };
250
+ /** Earliest `mergedAt` first, unmerged last, ties in GitHub's order: upstream's sort. */
251
+ const byMergedAt = (a, b) => {
252
+ if (a.mergedAt === null && b.mergedAt === null) return 0;
253
+ if (a.mergedAt === null) return 1;
254
+ if (b.mergedAt === null) return -1;
255
+ return new Date(a.mergedAt).getTime() - new Date(b.mergedAt).getTime();
256
+ };
257
+ const isCommit = (answer) => "commitUrl" in answer;
258
+ const commitInfo = (sha, answer) => {
259
+ if (answer === null || !isCommit(answer)) return Option.none();
260
+ const node = answer;
261
+ const pulls = (node.associatedPullRequests?.nodes ?? []).filter((pull) => pull !== null);
262
+ const pull = Option.fromNullishOr([...pulls].sort(byMergedAt)[0]);
263
+ const author = Option.orElse(Option.flatMap(pull, (found) => Option.fromNullishOr(found.author)), () => Option.fromNullishOr(node.author?.user));
264
+ return Option.some(CommitChangelogInfo.make({
265
+ user: Option.map(author, (actor) => actor.login),
266
+ pull: Option.map(pull, (found) => found.number),
267
+ links: {
268
+ commit: `[\`${sha.slice(0, 7)}\`](${node.commitUrl})`,
269
+ pull: Option.map(pull, (found) => `[#${found.number}](${found.url})`),
270
+ user: Option.map(author, (actor) => `[@${actor.login}](${actor.url})`)
271
+ }
272
+ }));
273
+ };
274
+ const pullInfo = (number, answer) => {
275
+ if (answer === null) return Option.none();
276
+ const author = Option.fromNullishOr(answer.author);
277
+ const merge = Option.fromNullishOr(answer.mergeCommit);
278
+ return Option.some(PullRequestChangelogInfo.make({
279
+ user: Option.map(author, (actor) => actor.login),
280
+ commit: Option.map(merge, (commit) => commit.abbreviatedOid),
281
+ links: {
282
+ commit: Option.map(merge, (commit) => `[\`${commit.abbreviatedOid.slice(0, 7)}\`](${commit.commitUrl})`),
283
+ pull: `[#${number}](${answer.url})`,
284
+ user: Option.map(author, (actor) => `[@${actor.login}](${actor.url})`)
285
+ }
286
+ }));
287
+ };
288
+ const make = (client) => {
289
+ /**
290
+ * Every alias's answer, `null` for a missing one. A batch whose only errors
291
+ * are missing pull requests is sent again without them, so each round drops
292
+ * at least one lookup and the loop ends.
293
+ */
294
+ const answers = (owner, repo, lookups) => lookups.length === 0 ? Effect.succeed(/* @__PURE__ */ new Map()) : client.graphql(documentFor(owner, repo, lookups), {}).pipe(Effect.map((data) => new Map(Object.entries(data[REPO_ALIAS] ?? {}))), Effect.catchTag("GitHubGraphQLError", (error) => {
295
+ const missing = missingPulls(error, lookups);
296
+ if (missing === void 0) return Effect.fail(error);
297
+ return Effect.map(answers(owner, repo, lookups.filter((lookup) => !missing.has(aliasOf(lookup)))), (found) => new Map([...found, ...[...missing].map((alias) => [alias, null])]));
298
+ }));
299
+ const resolver = RequestResolver.makeGrouped({
300
+ key: ({ request }) => `${request.owner}/${request.repo}`,
301
+ resolver: (entries) => Effect.gen(function* () {
302
+ const { owner, repo } = entries[0].request;
303
+ const distinct = [...new Map(entries.map((entry) => [aliasOf(entry.request), entry.request])).values()];
304
+ yield* Effect.annotateCurrentSpan({
305
+ owner,
306
+ repo,
307
+ lookups: distinct.length
308
+ });
309
+ const found = yield* answers(owner, repo, distinct);
310
+ const decoded = /* @__PURE__ */ new Map();
311
+ for (const lookup of distinct) {
312
+ const alias = aliasOf(lookup);
313
+ const raw = found.get(alias) ?? null;
314
+ const info = lookup._tag === "CommitLookup" ? yield* Effect.map(decodeCommit(raw), (answer) => commitInfo(lookup.sha, answer)) : yield* Effect.map(decodePull(raw), (answer) => pullInfo(lookup.number, answer));
315
+ decoded.set(alias, info);
316
+ }
317
+ for (const entry of entries) entry.completeUnsafe(Exit.succeed(decoded.get(aliasOf(entry.request)) ?? Option.none()));
318
+ }).pipe(Effect.catchTag("SchemaError", (error) => Effect.fail(GitHubGraphQLError.decode("changelogInfo", "response did not match its schema", error))), Effect.withSpan("ChangelogInfo.batch"))
319
+ }).pipe(RequestResolver.batchN(BATCH_SIZE));
320
+ return {
321
+ commit: Effect.fn("ChangelogInfo.commit")(function* (sha) {
322
+ if (!SHA.test(sha)) return yield* new InvalidChangelogRefError({
323
+ ref: "commit",
324
+ input: sha
325
+ });
326
+ const { owner, repo } = yield* Repo;
327
+ yield* Effect.annotateCurrentSpan({
328
+ owner,
329
+ repo,
330
+ sha
331
+ });
332
+ return yield* Effect.request(CommitLookup({
333
+ owner,
334
+ repo,
335
+ sha
336
+ }), resolver);
337
+ }),
338
+ pullRequest: Effect.fn("ChangelogInfo.pullRequest")(function* (number) {
339
+ if (!Number.isSafeInteger(number) || number < 1) return yield* new InvalidChangelogRefError({
340
+ ref: "pull",
341
+ input: String(number)
342
+ });
343
+ const { owner, repo } = yield* Repo;
344
+ yield* Effect.annotateCurrentSpan({
345
+ owner,
346
+ repo,
347
+ number
348
+ });
349
+ return yield* Effect.request(PullLookup({
350
+ owner,
351
+ repo,
352
+ number
353
+ }), resolver);
354
+ })
355
+ };
356
+ };
357
+
358
+ export { ChangelogInfo, CommitChangelogInfo, InvalidChangelogRefError, PullRequestChangelogInfo };
package/GitHubClient.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { GitHubError } from "./GitHubError.js";
2
2
  import { GitHubGraphQLError } from "./GraphQL.js";
3
+ import { API_VERSION_PATTERN, DEFAULT_API_VERSION } from "./internal/apiVersion.js";
3
4
  import { rawRequestRefusal, refusedRequest } from "./internal/confinement.js";
4
- import { DEFAULT_API_VERSION, expandOnDotcom, makeTransport } from "./internal/octokit.js";
5
+ import { expandOnDotcom, makeTransport } from "./internal/octokit.js";
5
6
  import { fromArray, paginate } from "./internal/paginate.js";
6
7
  import { unstubbed } from "./internal/unstubbed.js";
7
8
  import { DOTCOM_API_BASE_URL, originOf, uploadsBaseUrlFor, withUploadChannel } from "./internal/uploads.js";
@@ -233,8 +234,6 @@ var GitHubClient = class GitHubClient extends Context.Service()("@effected/githu
233
234
  */
234
235
  static layerFixture = (fixtures) => Layer.succeed(GitHubClient, confineDouble(makeFixture(fixtures)));
235
236
  };
236
- /** A calendar api-version: `YYYY-MM-DD`. */
237
- const API_VERSION_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
238
237
  /**
239
238
  * The api-version a client pins: the option when it is a calendar version,
240
239
  * the default when it is absent, and a defect naming the option otherwise.