@milkenjoyer/toolchain 0.14.1 → 0.16.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 (53) hide show
  1. package/README.md +17 -17
  2. package/STARTS.md +11 -0
  3. package/dist/effect-plugin-BsrW5_nI.mjs +79 -0
  4. package/dist/effect-plugin.d.mts +2 -3966
  5. package/dist/effect-plugin.mjs +1 -1
  6. package/dist/fmt-BaECz64m.mjs +8 -0
  7. package/dist/fmt.mjs +1 -8
  8. package/dist/formal.mjs +1 -1
  9. package/dist/guard-Doqk4Fju.mjs +143 -0
  10. package/dist/guard.mjs +1 -96
  11. package/dist/{lint-IhmtnBbx.mjs → lint-CfztB4u8.mjs} +1 -1
  12. package/dist/lint.mjs +1 -1
  13. package/dist/standard.mjs +557 -4
  14. package/dist/starts.d.mts +100 -0
  15. package/dist/starts.mjs +385 -0
  16. package/package.json +11 -9
  17. package/src/arithmetic.ts +60 -0
  18. package/src/compatible.ts +512 -0
  19. package/src/conformance.ts +56 -0
  20. package/src/effect-plugin.ts +24 -0
  21. package/src/effect-tsgo.ts +44 -0
  22. package/src/exceptions.ts +17 -0
  23. package/src/fmt.ts +13 -0
  24. package/src/foldkit-plugin.ts +51 -0
  25. package/src/guard.ts +307 -0
  26. package/src/hooks.ts +205 -0
  27. package/src/index.ts +1 -0
  28. package/src/knip.ts +25 -0
  29. package/src/lint.ts +170 -0
  30. package/src/plugin.ts +21 -0
  31. package/src/rules/no-comments.ts +36 -0
  32. package/src/rules/no-process-env.ts +68 -0
  33. package/src/rules/prefer-accessible-scene-locators.ts +227 -0
  34. package/src/rules/require-command-answer-names.ts +144 -0
  35. package/src/rules/require-past-tense-messages.ts +201 -0
  36. package/src/rules/use-temp-file-scoped.ts +132 -0
  37. package/src/rules.ts +121 -0
  38. package/src/shared/foldkit-api.ts +51 -0
  39. package/src/shared/member-path.ts +106 -0
  40. package/src/shared/syntax.ts +47 -0
  41. package/src/standard/alchemy.ts +70 -0
  42. package/src/standard/checks.ts +10 -1
  43. package/src/standard/config.ts +84 -0
  44. package/src/standard/domain-rules.ts +204 -0
  45. package/src/standard/domain.ts +296 -0
  46. package/src/standard/infra.ts +486 -0
  47. package/src/starts/boat.ts +140 -0
  48. package/src/starts/budget.ts +151 -0
  49. package/src/starts/policy.ts +171 -0
  50. package/src/starts.ts +84 -0
  51. package/src/versions.ts +221 -0
  52. package/dist/effect-plugin-BXUx9PPu.mjs +0 -3561
  53. package/dist/manifest-xQwgnYI1.mjs +0 -53
@@ -0,0 +1,486 @@
1
+ import * as Arr from "effect/Array";
2
+ import * as Effect from "effect/Effect";
3
+ import * as Option from "effect/Option";
4
+ import * as R from "effect/Record";
5
+ import * as Schema from "effect/Schema";
6
+ import {
7
+ type Argument,
8
+ type ArrayExpressionElement,
9
+ type Expression,
10
+ type ModuleExportName,
11
+ parseSync,
12
+ Visitor,
13
+ } from "oxc-parser";
14
+
15
+ import { read, type Finding, type Rule } from "./repo.ts";
16
+
17
+ type Words = ReadonlyArray<Option.Option<string>>;
18
+
19
+ const COMMAND_WORD = /^[a-z][\w-]*$/u;
20
+
21
+ const commandPath = (words: Words): ReadonlyArray<string> =>
22
+ Arr.takeWhile(
23
+ words,
24
+ (word) => Option.isSome(word) && COMMAND_WORD.test(word.value)
25
+ ).flatMap(Option.toArray);
26
+
27
+ const CF_READ_VERB = /^(?:get|list|query|search)$/u;
28
+
29
+ const CF_WRITE_VERB =
30
+ /^(?:ack|add|apply|bind|cancel|create|delete|deploy|disable|edit|enable|import|peek|publish|pull|purge|push|put|remove|rename|reset|retry|rm|rollback|rotate|send|set|start|stop|unbind|update|upload|write)$/u;
31
+
32
+ const cfReads = (words: Words): boolean => {
33
+ const path = commandPath(words);
34
+
35
+ return (
36
+ words.some(
37
+ (word, index) =>
38
+ Option.contains(word, "--dry-run") &&
39
+ !Option.contains(words[index + 1] ?? Option.none(), "=") &&
40
+ !Option.contains(words[index + 1] ?? Option.none(), "false")
41
+ ) ||
42
+ Arr.head(path).pipe(Option.getOrUndefined) === "schema" ||
43
+ (Arr.some(path, (word) => CF_READ_VERB.test(word)) &&
44
+ !Arr.some(path, (word) => CF_WRITE_VERB.test(word)))
45
+ );
46
+ };
47
+
48
+ const PROVIDER_CLIS = {
49
+ wrangler: (): boolean => false,
50
+ pscale: (words: Words): boolean =>
51
+ ["sql", "auth", "org"].includes(
52
+ Arr.head(commandPath(words)).pipe(Option.getOrElse(() => ""))
53
+ ),
54
+ cf: cfReads,
55
+ } satisfies Record<string, (words: Words) => boolean>;
56
+
57
+ type ProviderCli = keyof typeof PROVIDER_CLIS;
58
+
59
+ const reachOf = (cli: ProviderCli, words: Words): ReadonlyArray<string> => {
60
+ const path = commandPath(words);
61
+
62
+ return PROVIDER_CLIS[cli](words)
63
+ ? []
64
+ : [
65
+ `${cli} ${Arr.match(path, {
66
+ onEmpty: () => "<unknown>",
67
+ onNonEmpty: (command) => command.join(" "),
68
+ })}`,
69
+ ];
70
+ };
71
+
72
+ const CLOUDFLARE = "cloudflare";
73
+
74
+ const PROVIDERS = [CLOUDFLARE, "planetscale"];
75
+
76
+ const PROVIDER_HOST = new RegExp(
77
+ String.raw`\bapi\.(?:${PROVIDERS.join("|")})\.com\b`,
78
+ "u"
79
+ );
80
+
81
+ const hexDigits = (code: number, width: number): string =>
82
+ code
83
+ .toString(16)
84
+ .padStart(width, "0")
85
+ .replaceAll(/[a-f]/gu, (digit) => `[${digit}${digit.toUpperCase()}]`);
86
+
87
+ const IDENTITY_ESCAPED = /^[^\dbfnrtuvx]$/u;
88
+
89
+ const LINE_CONTINUATIONS = String.raw`(?:\\(?:\r\n?|[\n\u2028\u2029]))*`;
90
+
91
+ const spelled = (word: string): string =>
92
+ Array.from(word, (char) => {
93
+ const code = char.codePointAt(0) ?? 0;
94
+ const plain = char === "." ? String.raw`\.` : char;
95
+
96
+ const escapes = [
97
+ `x${hexDigits(code, 2)}`,
98
+ `u${hexDigits(code, 4)}`,
99
+ String.raw`u\{0*${hexDigits(code, 1)}\}`,
100
+ `0*${code.toString(8)}`,
101
+ ...(IDENTITY_ESCAPED.test(char) ? [plain] : []),
102
+ ];
103
+
104
+ return String.raw`${LINE_CONTINUATIONS}(?:${plain}|\\(?:${escapes.join("|")}))`;
105
+ }).join("");
106
+
107
+ const IDENTIFIER_PART = String.raw`[\p{ID_Continue}$\u200c\u200d]`;
108
+
109
+ const SHELL_WORD_CHAR = String.raw`[\w./@-]`;
110
+
111
+ const ESCAPE_END = String.raw`\\(?:x[\da-fA-F]{2}|u[\da-fA-F]{4}|u\{[\da-fA-F]+\}|[0-7]{1,3}|[^])`;
112
+
113
+ const SHELL_WORD_BEFORE = String.raw`(?:^|\/|(?!${SHELL_WORD_CHAR})[^]|${ESCAPE_END})`;
114
+
115
+ const SHELL_WORD_AFTER = String.raw`(?!${SHELL_WORD_CHAR})`;
116
+
117
+ const MEMBER_ACCESS_BEFORE = String.raw`(?:(?<!\.)\.|\d\.\.|[[\/\n\r\u2028\u2029])\s*`;
118
+
119
+ const MEMBER_ACCESS_AFTER = String.raw`(?!${IDENTIFIER_PART})(?=\s*\]?\s*(?:\??\.|[[\/]))`;
120
+
121
+ const spelledBetween = (before: string, word: string, after: string): string =>
122
+ String.raw`${spelled(word)}${after}(?<=${before}${spelled(word)})`;
123
+
124
+ const MAY_REACH = new RegExp(
125
+ [
126
+ ...[
127
+ "@distilled.cloud/",
128
+ ...PROVIDERS.map((provider) => `api.${provider}.com`),
129
+ ].map(spelled),
130
+ ...R.keys(PROVIDER_CLIS).map((cli) =>
131
+ spelledBetween(SHELL_WORD_BEFORE, cli, SHELL_WORD_AFTER)
132
+ ),
133
+ `["']${spelled(CLOUDFLARE)}`,
134
+ spelledBetween(MEMBER_ACCESS_BEFORE, "rest", MEMBER_ACCESS_AFTER),
135
+ ].join("|"),
136
+ "u"
137
+ );
138
+
139
+ const MANAGEMENT_CLIENT = new RegExp(
140
+ String.raw`^(?:@distilled\.cloud\/[^/]+(?:\/(?!Credentials$|Errors$|Retry$)[^/]+)?|${CLOUDFLARE}(?:\/.*)?)$`,
141
+ "u"
142
+ );
143
+
144
+ const RUNTIME_CLIENTS = new Set([
145
+ "@distilled.cloud/boat-dev",
146
+ "@distilled.cloud/stripe",
147
+ ]);
148
+
149
+ const RUNTIME_REST = new Map([
150
+ ["git", new Set(["createBlob", "createTree", "createCommit", "createRef"])],
151
+ ["repos", new Set(["createCommitStatus"])],
152
+ [
153
+ "issues",
154
+ new Set([
155
+ "addAssignees",
156
+ "addLabels",
157
+ "create",
158
+ "createComment",
159
+ "deleteComment",
160
+ "lock",
161
+ "removeAllLabels",
162
+ "removeAssignees",
163
+ "removeLabel",
164
+ "setLabels",
165
+ "unlock",
166
+ "update",
167
+ "updateComment",
168
+ ]),
169
+ ],
170
+ [
171
+ "pulls",
172
+ new Set([
173
+ "create",
174
+ "createReplyForReviewComment",
175
+ "createReview",
176
+ "createReviewComment",
177
+ "deletePendingReview",
178
+ "deleteReviewComment",
179
+ "dismissReview",
180
+ "merge",
181
+ "removeRequestedReviewers",
182
+ "requestReviewers",
183
+ "submitReview",
184
+ "update",
185
+ "updateBranch",
186
+ "updateReview",
187
+ "updateReviewComment",
188
+ ]),
189
+ ],
190
+ ]);
191
+
192
+ const packageOf = (source: string): string =>
193
+ source.split("/").slice(0, 2).join("/");
194
+
195
+ const chainOf = (node: Expression): ReadonlyArray<string> | undefined => {
196
+ if (node.type === "Identifier") {
197
+ return [node.name];
198
+ }
199
+ if (node.type !== "MemberExpression" || node.computed) {
200
+ return undefined;
201
+ }
202
+ const head = chainOf(node.object);
203
+ return head === undefined ? undefined : [...head, node.property.name];
204
+ };
205
+
206
+ const READ_METHOD = /^(?:get|list|query|compare)(?:[A-Z_]|$)/iu;
207
+
208
+ type Operand = NonNullable<
209
+ Argument | ArrayExpressionElement | ModuleExportName
210
+ >;
211
+
212
+ const textOf = (node: Option.Option<Operand>): Option.Option<string> => {
213
+ if (Option.isNone(node)) {
214
+ return Option.none();
215
+ }
216
+
217
+ const { value } = node;
218
+
219
+ if (value.type === "Literal") {
220
+ return Schema.is(Schema.String)(value.value)
221
+ ? Option.some(value.value)
222
+ : Option.none();
223
+ }
224
+
225
+ return value.type === "TemplateLiteral"
226
+ ? Option.some(value.quasis.map((quasi) => quasi.value.raw).join(" "))
227
+ : Option.none();
228
+ };
229
+
230
+ const ProviderCli = Schema.Literals(R.keys(PROVIDER_CLIS));
231
+
232
+ const cliOf = (word: string): Option.Option<ProviderCli> => {
233
+ const name = word.slice(word.lastIndexOf("/") + 1);
234
+
235
+ return Schema.is(ProviderCli)(name) ? Option.some(name) : Option.none();
236
+ };
237
+
238
+ const SHELL_TOKEN = new RegExp(
239
+ String.raw`[;&|\n\x60()]|["'$=]|${SHELL_WORD_CHAR}+`,
240
+ "gu"
241
+ );
242
+
243
+ const SEPARATOR = /^[;&|\n`()]$/u;
244
+
245
+ const shellFindings = (text: string): ReadonlyArray<string> => {
246
+ const tokens = text.match(SHELL_TOKEN) ?? [];
247
+
248
+ return tokens.flatMap((token, index) => {
249
+ const cli = cliOf(token);
250
+
251
+ return Option.isNone(cli)
252
+ ? []
253
+ : reachOf(
254
+ cli.value,
255
+ Arr.takeWhile(
256
+ tokens.slice(index + 1),
257
+ (word) => !SEPARATOR.test(word)
258
+ ).map(Option.some)
259
+ );
260
+ });
261
+ };
262
+
263
+ export const providerReaches = (
264
+ file: string,
265
+ source: string
266
+ ): ReadonlyArray<string> => {
267
+ if (!MAY_REACH.test(source)) {
268
+ return [];
269
+ }
270
+
271
+ const found: Array<string> = [];
272
+ const clients = new Set<string>();
273
+ const instances = new Set<string>();
274
+ const commands = new Set<Operand>();
275
+
276
+ const invocation = (
277
+ operands: ReadonlyArray<Option.Option<Operand>>
278
+ ): void => {
279
+ for (const [index, operand] of operands.entries()) {
280
+ const cli = cliOf(
281
+ Option.getOrElse(
282
+ Option.map(textOf(operand), (text) => text.trim()),
283
+ () => ""
284
+ )
285
+ );
286
+
287
+ if (Option.isSome(operand) && Option.isSome(cli)) {
288
+ const after = operands[index + 1] ?? Option.none();
289
+
290
+ const words = (
291
+ Option.isSome(after) && after.value.type === "ArrayExpression"
292
+ ? after.value.elements.map(Option.fromNullishOr)
293
+ : operands.slice(index + 1)
294
+ ).map(textOf);
295
+
296
+ commands.add(operand.value);
297
+ found.push(...reachOf(cli.value, words));
298
+ }
299
+ }
300
+ };
301
+
302
+ const literal = (node: Operand): void => {
303
+ const text = textOf(Option.some(node));
304
+
305
+ if (Option.isNone(text) || commands.has(node)) {
306
+ return;
307
+ }
308
+
309
+ if (PROVIDER_HOST.test(text.value)) {
310
+ found.push(`host ${text.value}`);
311
+ }
312
+
313
+ found.push(
314
+ ...(Option.isNone(cliOf(text.value.trim()))
315
+ ? shellFindings(text.value)
316
+ : [`${text.value.trim()} <unknown>`])
317
+ );
318
+ };
319
+
320
+ new Visitor({
321
+ ImportDeclaration: (node): void => {
322
+ if (
323
+ node.importKind === "type" ||
324
+ !MANAGEMENT_CLIENT.test(node.source.value) ||
325
+ RUNTIME_CLIENTS.has(packageOf(node.source.value))
326
+ ) {
327
+ return;
328
+ }
329
+
330
+ for (const specifier of node.specifiers) {
331
+ if (specifier.type !== "ImportSpecifier") {
332
+ clients.add(specifier.local.name);
333
+ } else if (specifier.importKind !== "type") {
334
+ const imported =
335
+ specifier.imported.type === "Identifier"
336
+ ? specifier.imported.name
337
+ : specifier.imported.value;
338
+
339
+ if (!READ_METHOD.test(imported)) {
340
+ found.push(`imports ${imported}`);
341
+ }
342
+ }
343
+ }
344
+ },
345
+ VariableDeclarator: (node): void => {
346
+ const init =
347
+ node.init?.type === "AwaitExpression" ? node.init.argument : node.init;
348
+ const callee =
349
+ init?.type === "NewExpression" || init?.type === "CallExpression"
350
+ ? init.callee
351
+ : undefined;
352
+ if (
353
+ node.id.type === "Identifier" &&
354
+ callee?.type === "Identifier" &&
355
+ clients.has(callee.name)
356
+ ) {
357
+ instances.add(node.id.name);
358
+ }
359
+ },
360
+ CallExpression: (node): void => {
361
+ invocation(node.arguments.map(Option.some));
362
+ const chain = chainOf(node.callee);
363
+ const [root, ...path] = chain ?? [];
364
+ const method = path.at(-1);
365
+ if (
366
+ root !== undefined &&
367
+ method !== undefined &&
368
+ instances.has(root) &&
369
+ !READ_METHOD.test(method)
370
+ ) {
371
+ found.push(`calls ${[root, ...path].join(".")}`);
372
+ }
373
+ },
374
+ NewExpression: (node): void => invocation(node.arguments.map(Option.some)),
375
+ ArrayExpression: (node): void =>
376
+ invocation(node.elements.map(Option.fromNullishOr)),
377
+ Literal: (node): void => literal(node),
378
+ TemplateLiteral: (node): void => literal(node),
379
+ MemberExpression: (node): void => {
380
+ if (node.computed || node.property.type !== "Identifier") {
381
+ return;
382
+ }
383
+
384
+ const method = node.property.name;
385
+ const { object } = node;
386
+
387
+ const client =
388
+ object.type === "Identifier" && clients.has(object.name)
389
+ ? object.name
390
+ : undefined;
391
+
392
+ const namespace =
393
+ object.type === "MemberExpression" &&
394
+ object.object.type === "MemberExpression" &&
395
+ object.object.property.type === "Identifier" &&
396
+ object.object.property.name === "rest"
397
+ ? !object.computed && object.property.type === "Identifier"
398
+ ? object.property.name
399
+ : "<computed>"
400
+ : undefined;
401
+
402
+ const target =
403
+ client ??
404
+ (namespace === undefined ||
405
+ namespace === "search" ||
406
+ RUNTIME_REST.get(namespace)?.has(method) === true
407
+ ? undefined
408
+ : `rest.${namespace}`);
409
+
410
+ if (target !== undefined && !READ_METHOD.test(method)) {
411
+ found.push(`calls ${target}.${method}`);
412
+ }
413
+ },
414
+ }).visit(parseSync(file, source).program);
415
+
416
+ return found;
417
+ };
418
+
419
+ const PackageScripts = Schema.fromJsonString(
420
+ Schema.Struct({
421
+ scripts: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
422
+ })
423
+ );
424
+ const Workflow = Schema.Struct({
425
+ jobs: Schema.Record(
426
+ Schema.String,
427
+ Schema.Struct({
428
+ steps: Schema.optionalKey(
429
+ Schema.Array(
430
+ Schema.Struct({
431
+ run: Schema.optionalKey(Schema.String),
432
+ })
433
+ )
434
+ ),
435
+ })
436
+ ),
437
+ });
438
+ const SCRIPT = /\.[cm]?[jt]sx?$/u;
439
+ const WORKFLOW = /^\.github\/workflows\/[^/]+\.ya?ml$/u;
440
+
441
+ export const infra: Rule = (repo) =>
442
+ Effect.gen(function* () {
443
+ const findings: Finding[] = [];
444
+ for (const file of repo.tracked) {
445
+ if (/(?:^|\/)wrangler\.(?:jsonc?|toml)$/u.test(file)) {
446
+ findings.push({
447
+ file,
448
+ message:
449
+ "provision infrastructure with native Alchemy resources instead of a Wrangler config",
450
+ });
451
+ continue;
452
+ }
453
+ if (
454
+ !SCRIPT.test(file) &&
455
+ !file.endsWith(".sh") &&
456
+ !/(?:^|\/)package\.json$/u.test(file) &&
457
+ !WORKFLOW.test(file)
458
+ )
459
+ continue;
460
+ const input = yield* read(repo, file, (text) => {
461
+ if (SCRIPT.test(file)) return providerReaches(file, text);
462
+ if (file.endsWith(".sh")) return shellFindings(text);
463
+ const scripts = WORKFLOW.test(file)
464
+ ? Object.values(
465
+ Schema.decodeUnknownSync(Workflow)(Bun.YAML.parse(text)).jobs
466
+ ).flatMap((job) =>
467
+ (job.steps ?? []).flatMap((step) =>
468
+ step.run === undefined ? [] : [step.run]
469
+ )
470
+ )
471
+ : Object.values(
472
+ Schema.decodeSync(PackageScripts)(text).scripts ?? {}
473
+ );
474
+ return scripts.flatMap(shellFindings);
475
+ });
476
+ findings.push(
477
+ ...(input.ok
478
+ ? input.value.map((reach) => ({
479
+ file,
480
+ message: `${reach}; provision infrastructure with native Alchemy resources`,
481
+ }))
482
+ : input.findings)
483
+ );
484
+ }
485
+ return findings;
486
+ });
@@ -0,0 +1,140 @@
1
+ import { BoatApi, CiJobState, Configuration } from "@boatdev/sdk";
2
+ import * as Clock from "effect/Clock";
3
+ import * as Context from "effect/Context";
4
+ import * as Effect from "effect/Effect";
5
+ import * as Layer from "effect/Layer";
6
+ import * as Redacted from "effect/Redacted";
7
+ import * as Schema from "effect/Schema";
8
+
9
+ import {
10
+ type Plan,
11
+ type Repo,
12
+ type RepoStarts,
13
+ windowMillis,
14
+ } from "./budget.ts";
15
+
16
+ export class StartReadError extends Schema.TaggedError<
17
+ StartReadError,
18
+ { readonly brand: unique symbol }
19
+ >()("StartReadError", { reason: Schema.String }) {}
20
+
21
+ const Count = Schema.Number.check(
22
+ Schema.makeFilter((value) => Number.isSafeInteger(value) && value >= 0)
23
+ );
24
+ const Usage = Schema.Struct({ limit: Count, used: Count });
25
+ const Limits = Schema.Struct({
26
+ ok: Schema.Literal(true),
27
+ starts: Schema.Struct({ minute: Usage, hour: Usage, day: Usage }),
28
+ nextStartDollars: Schema.optional(Schema.NullOr(Schema.Finite)),
29
+ });
30
+ const Ci = Schema.Struct({
31
+ ok: Schema.Literal(true),
32
+ jobs: Schema.Array(
33
+ Schema.Struct({
34
+ repo: Schema.String,
35
+ label: Schema.String,
36
+ state: Schema.String.check(Schema.isMinLength(1)),
37
+ queuedAt: Schema.Date,
38
+ runStartedAt: Schema.optional(Schema.NullOr(Schema.Date)),
39
+ })
40
+ ),
41
+ });
42
+ const settled = new Set<string>([
43
+ CiJobState.Success,
44
+ CiJobState.Failure,
45
+ CiJobState.Cancelled,
46
+ CiJobState.Skipped,
47
+ CiJobState.Failed,
48
+ CiJobState.Refused,
49
+ ]);
50
+
51
+ export class BoatStarts extends Context.Service<
52
+ BoatStarts,
53
+ {
54
+ readonly plan: Effect.Effect<Plan, StartReadError>;
55
+ readonly repoStarts: (
56
+ repo: Repo
57
+ ) => Effect.Effect<RepoStarts, StartReadError>;
58
+ }
59
+ >()("toolchain/BoatStarts") {
60
+ static readonly layer = (
61
+ key: Redacted.Redacted<string>,
62
+ options: {
63
+ readonly fetch?: (
64
+ url: string | URL | Request,
65
+ init?: RequestInit
66
+ ) => Promise<Response>;
67
+ } = {}
68
+ ) =>
69
+ Layer.sync(BoatStarts, () => {
70
+ const api = new BoatApi(
71
+ new Configuration({
72
+ accessToken: Redacted.value(key),
73
+ ...(options.fetch === undefined ? {} : { fetchApi: options.fetch }),
74
+ })
75
+ );
76
+ const plan = Effect.gen(function* () {
77
+ const response = yield* Effect.tryPromise({
78
+ try: () => api.limits(),
79
+ catch: () =>
80
+ new StartReadError({ reason: "Boat limits request failed" }),
81
+ });
82
+ const limits = yield* Schema.decodeUnknownEffect(Limits)(response).pipe(
83
+ Effect.mapError(
84
+ () => new StartReadError({ reason: "Boat limits unread" })
85
+ )
86
+ );
87
+ return {
88
+ limits: {
89
+ minute: limits.starts.minute.limit,
90
+ hour: limits.starts.hour.limit,
91
+ day: limits.starts.day.limit,
92
+ },
93
+ used: {
94
+ minute: limits.starts.minute.used,
95
+ hour: limits.starts.hour.used,
96
+ day: limits.starts.day.used,
97
+ },
98
+ nextStartDollars: limits.nextStartDollars ?? undefined,
99
+ };
100
+ });
101
+ const repoStarts = Effect.fn("BoatStarts.repoStarts")(function* (
102
+ repo: Repo
103
+ ) {
104
+ const response = yield* Effect.tryPromise({
105
+ try: () => api.getCiOverview({ repo, limit: 500 }),
106
+ catch: () => new StartReadError({ reason: "Boat CI request failed" }),
107
+ });
108
+ const now = yield* Clock.currentTimeMillis;
109
+ const { jobs } = yield* Schema.decodeUnknownEffect(Ci)(response).pipe(
110
+ Effect.mapError(
111
+ () => new StartReadError({ reason: "Boat CI history unread" })
112
+ )
113
+ );
114
+ if (jobs.some((job) => job.repo !== repo))
115
+ return yield* new StartReadError({
116
+ reason: "Boat CI history differs from request",
117
+ });
118
+ const oldest = Math.min(
119
+ ...jobs.map((job) =>
120
+ Math.max(job.queuedAt.getTime(), job.runStartedAt?.getTime() ?? 0)
121
+ )
122
+ );
123
+ return {
124
+ repo,
125
+ starts: jobs.flatMap((job) => {
126
+ const at =
127
+ job.runStartedAt?.getTime() ??
128
+ (settled.has(job.state) ? undefined : now);
129
+ return job.label.split("/")[0]?.startsWith("boat") === true &&
130
+ at !== undefined &&
131
+ at > now - windowMillis.day
132
+ ? [Math.min(at, now)]
133
+ : [];
134
+ }),
135
+ complete: jobs.length < 500 || oldest <= now - windowMillis.day,
136
+ };
137
+ });
138
+ return BoatStarts.of({ plan, repoStarts });
139
+ });
140
+ }