@sifr-dev/loom 0.0.0-stage → 1.0.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 (64) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/LICENSE +21 -0
  3. package/README.ar.md +253 -0
  4. package/README.md +262 -2
  5. package/dist/browser.js +2717 -0
  6. package/dist/cli.js +15 -0
  7. package/dist/index.js +4854 -0
  8. package/dist/types/args.d.ts +14 -0
  9. package/dist/types/base64.d.ts +9 -0
  10. package/dist/types/browser.d.ts +57 -0
  11. package/dist/types/canonical.d.ts +20 -0
  12. package/dist/types/cli.d.ts +12 -0
  13. package/dist/types/commands/context.d.ts +30 -0
  14. package/dist/types/commands/diff.d.ts +18 -0
  15. package/dist/types/commands/doctor.d.ts +19 -0
  16. package/dist/types/commands/export.d.ts +30 -0
  17. package/dist/types/commands/migrate.d.ts +9 -0
  18. package/dist/types/commands/serve.d.ts +18 -0
  19. package/dist/types/commands/snapshot.d.ts +15 -0
  20. package/dist/types/commands/sync.d.ts +17 -0
  21. package/dist/types/commands/verify.d.ts +9 -0
  22. package/dist/types/commands/watch.d.ts +25 -0
  23. package/dist/types/compute.d.ts +49 -0
  24. package/dist/types/concurrency.d.ts +31 -0
  25. package/dist/types/config.d.ts +132 -0
  26. package/dist/types/diff.d.ts +57 -0
  27. package/dist/types/digest.d.ts +11 -0
  28. package/dist/types/entities.d.ts +27 -0
  29. package/dist/types/errors.d.ts +37 -0
  30. package/dist/types/fs.d.ts +23 -0
  31. package/dist/types/github/cache.d.ts +44 -0
  32. package/dist/types/github/client.d.ts +91 -0
  33. package/dist/types/github/collect.d.ts +36 -0
  34. package/dist/types/github/discovery.d.ts +39 -0
  35. package/dist/types/github/fixture.d.ts +26 -0
  36. package/dist/types/github/guard.d.ts +14 -0
  37. package/dist/types/github/memory-cache.d.ts +34 -0
  38. package/dist/types/index.d.ts +44 -0
  39. package/dist/types/log.d.ts +16 -0
  40. package/dist/types/metrics.d.ts +21 -0
  41. package/dist/types/migrate.d.ts +24 -0
  42. package/dist/types/pipeline.d.ts +73 -0
  43. package/dist/types/queue.d.ts +33 -0
  44. package/dist/types/sdk.d.ts +165 -0
  45. package/dist/types/secrets.d.ts +28 -0
  46. package/dist/types/serve-handler.d.ts +46 -0
  47. package/dist/types/sha256.d.ts +13 -0
  48. package/dist/types/site-module.d.ts +23 -0
  49. package/dist/types/site.d.ts +135 -0
  50. package/dist/types/snapshot.d.ts +16 -0
  51. package/dist/types/store.d.ts +119 -0
  52. package/dist/types/triggers.d.ts +67 -0
  53. package/dist/types/types.d.ts +176 -0
  54. package/dist/types/version.d.ts +7 -0
  55. package/dist/types/webhook/delivery.d.ts +45 -0
  56. package/dist/types/webhook/receiver.d.ts +46 -0
  57. package/dist/types/webhook/signature.d.ts +43 -0
  58. package/docs/CONFIGURATION.md +213 -0
  59. package/docs/DEPLOYMENT.md +316 -0
  60. package/docs/SDK.md +351 -0
  61. package/docs/SITE_CONTRACT.md +318 -0
  62. package/docs/VERIFICATION.md +130 -0
  63. package/package.json +83 -4
  64. package/schema/site@1.json +188 -0
@@ -0,0 +1,2717 @@
1
+ // src/secrets.ts
2
+ var SECRET_PATTERNS = [
3
+ { name: "github-token", pattern: /\bgh[pousr]_[A-Za-z0-9]{20,}\b/g },
4
+ { name: "github-pat", pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g },
5
+ { name: "openai-key", pattern: /\bsk-[A-Za-z0-9]{20,}\b/g },
6
+ { name: "slack-token", pattern: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g },
7
+ { name: "aws-access-key", pattern: /\bAKIA[0-9A-Z]{16}\b/g },
8
+ { name: "private-key", pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----/g },
9
+ { name: "jwt", pattern: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g },
10
+ { name: "vercel-hook", pattern: /https:\/\/api\.vercel\.com\/v1\/deploy-hooks\/[A-Za-z0-9]{8,}/g }
11
+ ];
12
+ function redactUrl(raw) {
13
+ try {
14
+ const url = new URL(raw);
15
+ const segments = url.pathname.split("/").filter(Boolean);
16
+ const shape = segments.map((segment) => segment.length > 12 ? "…" : segment).join("/");
17
+ return `${url.origin}/${shape}${url.search ? "?…" : ""}`;
18
+ } catch {
19
+ return "<invalid-url>";
20
+ }
21
+ }
22
+ function redactText(text) {
23
+ let output = text;
24
+ for (const { name, pattern } of SECRET_PATTERNS) {
25
+ pattern.lastIndex = 0;
26
+ output = output.replace(pattern, `<redacted:${name}>`);
27
+ }
28
+ output = output.replace(/(https?:\/\/)[^/@\s]+@/g, "$1<redacted>@");
29
+ return output;
30
+ }
31
+
32
+ // src/errors.ts
33
+ var EXIT = {
34
+ ok: 0,
35
+ failure: 1,
36
+ usage: 2,
37
+ verifyFailed: 3,
38
+ guardViolation: 4,
39
+ unauthorized: 5,
40
+ partial: 6,
41
+ unchanged: 7,
42
+ busy: 8
43
+ };
44
+ var EXIT_FOR_CODE = {
45
+ usage: EXIT.usage,
46
+ config_invalid: EXIT.usage,
47
+ github_error: EXIT.failure,
48
+ rate_limit_exhausted: EXIT.failure,
49
+ repo_not_public: EXIT.guardViolation,
50
+ repo_invalid: EXIT.guardViolation,
51
+ store_corrupt: EXIT.verifyFailed,
52
+ snapshot_missing: EXIT.failure,
53
+ verify_failed: EXIT.verifyFailed,
54
+ signature_invalid: EXIT.unauthorized,
55
+ payload_invalid: EXIT.usage,
56
+ trigger_failed: EXIT.failure,
57
+ secret_missing: EXIT.failure,
58
+ secret_detected: EXIT.failure,
59
+ network_error: EXIT.failure,
60
+ cancelled: EXIT.failure,
61
+ partial_failure: EXIT.partial,
62
+ queue_full: EXIT.busy,
63
+ lock_busy: EXIT.busy,
64
+ schema_unsupported: EXIT.usage
65
+ };
66
+
67
+ class LoomError extends Error {
68
+ name = "LoomError";
69
+ code;
70
+ detail;
71
+ constructor(code, message, detail = {}) {
72
+ super(message);
73
+ this.code = code;
74
+ this.detail = Object.freeze({ ...detail });
75
+ }
76
+ get exitCode() {
77
+ return EXIT_FOR_CODE[this.code] ?? EXIT.failure;
78
+ }
79
+ get hint() {
80
+ return hintFor(this.code);
81
+ }
82
+ toJSON() {
83
+ return {
84
+ ok: false,
85
+ code: this.code,
86
+ message: this.message,
87
+ detail: this.detail,
88
+ ...this.hint ? { hint: this.hint } : {}
89
+ };
90
+ }
91
+ }
92
+ var HINTS = {
93
+ github_error: "Check the repository name and GitHub status; run `loom doctor` for configuration.",
94
+ rate_limit_exhausted: "Set GITHUB_TOKEN (or --token-env) to raise the limit, or retry after the reset time.",
95
+ repo_not_public: "Loom only reads public repositories; remove private/internal entries from `repos`.",
96
+ repo_invalid: "Repository entries must be `owner/name` with no path tricks.",
97
+ store_corrupt: "Run `loom verify`; restore the named object or run `loom doctor --fix` for cache-only corruption.",
98
+ snapshot_missing: "Run `loom sync` before `loom diff`/`loom export`, or pass --from none.",
99
+ verify_failed: "Do not deploy a failed store. Re-sync from the source or restore a known-good object.",
100
+ signature_invalid: "Check the webhook secret and that the raw request body was forwarded unchanged.",
101
+ payload_invalid: "Send the raw GitHub webhook body with its original headers.",
102
+ trigger_failed: "The snapshot is committed; the durable outbox will retry on the next sync.",
103
+ secret_missing: "Export the named environment variable; secrets are never read from config files.",
104
+ secret_detected: "A credential-shaped value reached the public payload. Rotate it and fix the source field.",
105
+ network_error: "Check connectivity and the GitHub status page; transient errors are retried.",
106
+ cancelled: "The operation was cancelled by a signal; it is safe to retry.",
107
+ partial_failure: "Some repositories could not be read and had no previous copy; fix access and re-run.",
108
+ queue_full: "The sync queue is saturated; retry after the Retry-After interval.",
109
+ lock_busy: "Another Loom process owns this store; retry after it exits.",
110
+ schema_unsupported: "Run `loom migrate` or upgrade Loom; this build will not silently reinterpret old data."
111
+ };
112
+ function hintFor(code) {
113
+ return HINTS[code] ?? null;
114
+ }
115
+ function isLoomError(value) {
116
+ return value instanceof LoomError;
117
+ }
118
+ function configError(message, detail = {}) {
119
+ return new LoomError("config_invalid", message, detail);
120
+ }
121
+ function guardError(message, detail = {}) {
122
+ return new LoomError("repo_not_public", message, detail);
123
+ }
124
+ function describeError(error) {
125
+ if (isLoomError(error)) {
126
+ return {
127
+ code: error.code,
128
+ message: redactText(error.message),
129
+ detail: { ...error.detail },
130
+ ...error.hint ? { hint: error.hint } : {}
131
+ };
132
+ }
133
+ if (error instanceof Error) {
134
+ return { code: "unexpected", message: redactText(error.message), detail: {} };
135
+ }
136
+ return { code: "unexpected", message: redactText(String(error)), detail: {} };
137
+ }
138
+
139
+ // src/config.ts
140
+ var CONFIG_SCHEMA = "loom/config@1";
141
+ var DEFAULT_CONFIG = {
142
+ schema: CONFIG_SCHEMA,
143
+ repos: [],
144
+ branches: ["main"],
145
+ releases: 5,
146
+ includeLatestCommit: true,
147
+ aliases: {},
148
+ ownerAliases: {},
149
+ discovery: { owners: [], include: [], exclude: [], includeArchived: false, includeForks: false },
150
+ collect: {
151
+ readme: false,
152
+ readmeExcerptChars: 600,
153
+ branches: false,
154
+ branchLimit: 10,
155
+ extraBranches: [],
156
+ commitComments: false,
157
+ commitCommentLimit: 20,
158
+ issueComments: false,
159
+ issueCommentLimit: 20,
160
+ workflows: false,
161
+ workflowLimit: 10,
162
+ ciRuns: 5
163
+ },
164
+ store: ".loom",
165
+ githubBaseUrl: "https://api.github.com",
166
+ triggers: [],
167
+ webhook: {
168
+ path: "/webhook",
169
+ secretEnv: "LOOM_WEBHOOK_SECRET",
170
+ toleranceSeconds: 300,
171
+ maxBodyBytes: 1048576
172
+ },
173
+ watch: { intervalSeconds: 60 },
174
+ serve: { pollIntervalSeconds: 0, queueDepth: 32, shutdownTimeoutSeconds: 30, syncTimeoutSeconds: 120 }
175
+ };
176
+ var OWNER_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/;
177
+ var REPO_PATTERN = /^[A-Za-z0-9._-]{1,100}$/;
178
+ var GLOB_SEGMENT = /^[A-Za-z0-9._?*-]{1,100}$/;
179
+ function isRepoName(value) {
180
+ if (value.length > 140 || value.includes("..") || value.includes("//"))
181
+ return false;
182
+ const parts = value.split("/");
183
+ if (parts.length !== 2)
184
+ return false;
185
+ const [owner, repo] = parts;
186
+ return OWNER_PATTERN.test(owner) && REPO_PATTERN.test(repo) && repo !== "." && repo !== "..";
187
+ }
188
+ function isRepoGlob(value) {
189
+ if (value.length === 0 || value.length > 140 || value.includes("..") || value.includes("//"))
190
+ return false;
191
+ const parts = value.split("/");
192
+ if (parts.length !== 2)
193
+ return false;
194
+ const [owner, repo] = parts;
195
+ return GLOB_SEGMENT.test(owner) && GLOB_SEGMENT.test(repo) && repo !== "." && repo !== ".." && owner !== "." && owner !== "..";
196
+ }
197
+ function repoGlobMatches(pattern, repo) {
198
+ const source = pattern.toLowerCase().replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
199
+ return new RegExp(`^${source}$`).test(repo.toLowerCase());
200
+ }
201
+ function repoKey(value) {
202
+ return value.toLowerCase();
203
+ }
204
+ function resolveOwnerAlias(owner, aliases) {
205
+ const map = new Map;
206
+ for (const [from, to] of Object.entries(aliases))
207
+ map.set(from.toLowerCase(), to);
208
+ let current = owner;
209
+ const seen = new Set([owner.toLowerCase()]);
210
+ for (let depth = 0;depth < 8; depth += 1) {
211
+ const next = map.get(current.toLowerCase());
212
+ if (!next || seen.has(next.toLowerCase()))
213
+ return current;
214
+ seen.add(next.toLowerCase());
215
+ current = next;
216
+ }
217
+ return current;
218
+ }
219
+ function splitRepoName(fullName) {
220
+ if (!isRepoName(fullName))
221
+ return null;
222
+ const slash = fullName.indexOf("/");
223
+ return { owner: fullName.slice(0, slash), name: fullName.slice(slash + 1) };
224
+ }
225
+ function canonicalRepoKey(fullName, ownerAliases) {
226
+ const parts = splitRepoName(fullName);
227
+ if (!parts)
228
+ return fullName.toLowerCase();
229
+ return `${resolveOwnerAlias(parts.owner, ownerAliases)}/${parts.name}`.toLowerCase();
230
+ }
231
+ function canonicalRepoDisplay(fullName, ownerAliases) {
232
+ const parts = splitRepoName(fullName);
233
+ if (!parts)
234
+ return fullName;
235
+ const owner = resolveOwnerAlias(parts.owner, ownerAliases);
236
+ return owner === parts.owner ? fullName : `${owner}/${parts.name}`;
237
+ }
238
+ function expectObject(value, path) {
239
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
240
+ throw configError(`${path} must be an object`);
241
+ }
242
+ return value;
243
+ }
244
+ function expectString(value, path) {
245
+ if (typeof value !== "string" || value.length === 0) {
246
+ throw configError(`${path} must be a non-empty string`);
247
+ }
248
+ return value;
249
+ }
250
+ function expectBoolean(value, path) {
251
+ if (typeof value !== "boolean")
252
+ throw configError(`${path} must be a boolean`);
253
+ return value;
254
+ }
255
+ function expectInt(value, path, min, max) {
256
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
257
+ throw configError(`${path} must be an integer between ${min} and ${max}`);
258
+ }
259
+ return value;
260
+ }
261
+ function parseTriggers(value) {
262
+ if (value === undefined)
263
+ return [];
264
+ if (!Array.isArray(value))
265
+ throw configError("triggers must be an array");
266
+ return value.map((raw, index) => {
267
+ const path = `triggers[${index}]`;
268
+ const item = expectObject(raw, path);
269
+ const kind = expectString(item["kind"], `${path}.kind`);
270
+ switch (kind) {
271
+ case "vercel":
272
+ return { kind, urlEnv: expectString(item["urlEnv"], `${path}.urlEnv`) };
273
+ case "github-dispatch": {
274
+ const repo = expectString(item["repo"], `${path}.repo`);
275
+ if (!isRepoName(repo))
276
+ throw configError(`${path}.repo must be owner/name`);
277
+ return {
278
+ kind,
279
+ repo,
280
+ eventType: expectString(item["eventType"] ?? "loom-sync", `${path}.eventType`),
281
+ tokenEnv: expectString(item["tokenEnv"] ?? "GITHUB_TOKEN", `${path}.tokenEnv`)
282
+ };
283
+ }
284
+ case "webhook": {
285
+ const secretEnv = item["secretEnv"];
286
+ if (secretEnv !== undefined && secretEnv !== null && typeof secretEnv !== "string") {
287
+ throw configError(`${path}.secretEnv must be a string or null`);
288
+ }
289
+ return {
290
+ kind,
291
+ urlEnv: expectString(item["urlEnv"], `${path}.urlEnv`),
292
+ secretEnv: typeof secretEnv === "string" && secretEnv.length > 0 ? secretEnv : null
293
+ };
294
+ }
295
+ default:
296
+ throw configError(`${path}.kind is unknown: ${kind}`);
297
+ }
298
+ });
299
+ }
300
+ function parseDiscovery(value) {
301
+ if (value === undefined) {
302
+ return { owners: [], include: [], exclude: [], includeArchived: false, includeForks: false };
303
+ }
304
+ const root = expectObject(value, "discovery");
305
+ const owners = [];
306
+ if (root["owners"] !== undefined) {
307
+ if (!Array.isArray(root["owners"]))
308
+ throw configError("discovery.owners must be an array of GitHub logins");
309
+ const seen = new Set;
310
+ for (const [index, entry] of root["owners"].entries()) {
311
+ const owner = expectString(entry, `discovery.owners[${index}]`);
312
+ if (!OWNER_PATTERN.test(owner))
313
+ throw configError(`discovery.owners[${index}] is not a GitHub login: ${owner}`);
314
+ const key = owner.toLowerCase();
315
+ if (seen.has(key))
316
+ continue;
317
+ seen.add(key);
318
+ owners.push(owner);
319
+ }
320
+ }
321
+ const globs = (name) => {
322
+ const raw = root[name];
323
+ if (raw === undefined)
324
+ return [];
325
+ if (!Array.isArray(raw))
326
+ throw configError(`discovery.${name} must be an array of owner/name globs`);
327
+ const out = [];
328
+ for (const [index, entry] of raw.entries()) {
329
+ const pattern = expectString(entry, `discovery.${name}[${index}]`);
330
+ if (!isRepoGlob(pattern))
331
+ throw configError(`discovery.${name}[${index}] is not an owner/name glob: ${pattern}`);
332
+ out.push(pattern);
333
+ }
334
+ return out;
335
+ };
336
+ return {
337
+ owners,
338
+ include: globs("include"),
339
+ exclude: globs("exclude"),
340
+ includeArchived: root["includeArchived"] === undefined ? false : expectBoolean(root["includeArchived"], "discovery.includeArchived"),
341
+ includeForks: root["includeForks"] === undefined ? false : expectBoolean(root["includeForks"], "discovery.includeForks")
342
+ };
343
+ }
344
+ function parseCollect(value) {
345
+ const defaults = structuredClone(DEFAULT_CONFIG.collect);
346
+ if (value === undefined)
347
+ return defaults;
348
+ const root = expectObject(value, "collect");
349
+ const bool = (name) => {
350
+ const raw = root[name];
351
+ if (raw === undefined)
352
+ return defaults[name];
353
+ return expectBoolean(raw, `collect.${String(name)}`);
354
+ };
355
+ const int = (name, min, max) => {
356
+ const raw = root[name];
357
+ if (raw === undefined)
358
+ return defaults[name];
359
+ return expectInt(raw, `collect.${String(name)}`, min, max);
360
+ };
361
+ const extraBranches = [];
362
+ if (root["extraBranches"] !== undefined) {
363
+ if (!Array.isArray(root["extraBranches"]))
364
+ throw configError("collect.extraBranches must be an array");
365
+ const seen = new Set;
366
+ for (const [index, entry] of root["extraBranches"].entries()) {
367
+ const branch = expectString(entry, `collect.extraBranches[${index}]`);
368
+ if (branch.startsWith("refs/") || branch.includes("..") || branch.includes(" ")) {
369
+ throw configError(`collect.extraBranches[${index}] must be a plain branch name`);
370
+ }
371
+ if (seen.has(branch))
372
+ continue;
373
+ seen.add(branch);
374
+ extraBranches.push(branch);
375
+ }
376
+ }
377
+ return {
378
+ readme: bool("readme"),
379
+ readmeExcerptChars: int("readmeExcerptChars", 0, 20000),
380
+ branches: bool("branches"),
381
+ branchLimit: int("branchLimit", 1, 100),
382
+ extraBranches,
383
+ commitComments: bool("commitComments"),
384
+ commitCommentLimit: int("commitCommentLimit", 0, 100),
385
+ issueComments: bool("issueComments"),
386
+ issueCommentLimit: int("issueCommentLimit", 0, 100),
387
+ workflows: bool("workflows"),
388
+ workflowLimit: int("workflowLimit", 0, 100),
389
+ ciRuns: int("ciRuns", 1, 100)
390
+ };
391
+ }
392
+ function parseConfig(raw) {
393
+ const root = expectObject(raw, "config");
394
+ const merged = structuredClone(DEFAULT_CONFIG);
395
+ if (root["schema"] !== undefined && root["schema"] !== CONFIG_SCHEMA) {
396
+ throw configError(`config.schema must be "${CONFIG_SCHEMA}"`, { found: root["schema"] });
397
+ }
398
+ if (root["repos"] !== undefined) {
399
+ if (!Array.isArray(root["repos"]))
400
+ throw configError("repos must be an array of owner/name strings");
401
+ const seen = new Set;
402
+ const repos = [];
403
+ for (const [index, entry] of root["repos"].entries()) {
404
+ const repo = expectString(entry, `repos[${index}]`);
405
+ if (!isRepoName(repo)) {
406
+ throw new LoomError("repo_invalid", `repos[${index}] is not a valid public repository name: ${repo}`);
407
+ }
408
+ const key = repoKey(repo);
409
+ if (seen.has(key))
410
+ continue;
411
+ seen.add(key);
412
+ repos.push(repo);
413
+ }
414
+ merged.repos = repos;
415
+ }
416
+ if (root["branches"] !== undefined) {
417
+ if (!Array.isArray(root["branches"]) || root["branches"].length === 0) {
418
+ throw configError("branches must be a non-empty array");
419
+ }
420
+ merged.branches = root["branches"].map((entry, index) => {
421
+ const branch = expectString(entry, `branches[${index}]`);
422
+ if (branch.startsWith("refs/") || branch.includes("..")) {
423
+ throw configError(`branches[${index}] must be a branch name without refs/ prefix`);
424
+ }
425
+ return branch;
426
+ });
427
+ }
428
+ if (root["releases"] !== undefined)
429
+ merged.releases = expectInt(root["releases"], "releases", 0, 100);
430
+ if (root["includeLatestCommit"] !== undefined) {
431
+ merged.includeLatestCommit = expectBoolean(root["includeLatestCommit"], "includeLatestCommit");
432
+ }
433
+ if (root["store"] !== undefined) {
434
+ const store = expectString(root["store"], "store");
435
+ if (store.startsWith("/") || store.includes("..")) {
436
+ throw configError("store must be a relative path inside the project");
437
+ }
438
+ merged.store = store;
439
+ }
440
+ if (root["githubBaseUrl"] !== undefined) {
441
+ const url = expectString(root["githubBaseUrl"], "githubBaseUrl");
442
+ const parsed = URL.canParse(url) ? new URL(url) : null;
443
+ if (!parsed || parsed.protocol !== "https:" && parsed.protocol !== "http:") {
444
+ throw configError("githubBaseUrl must be an http(s) URL");
445
+ }
446
+ merged.githubBaseUrl = url.replace(/\/$/, "");
447
+ }
448
+ if (root["aliases"] !== undefined) {
449
+ const aliases = expectObject(root["aliases"], "aliases");
450
+ const out = {};
451
+ for (const [from, to] of Object.entries(aliases)) {
452
+ if (!isRepoName(from))
453
+ throw configError(`aliases key is not owner/name: ${from}`);
454
+ const target = expectString(to, `aliases.${from}`);
455
+ if (!isRepoName(target))
456
+ throw configError(`aliases.${from} is not owner/name: ${target}`);
457
+ if (repoKey(from) === repoKey(target))
458
+ throw configError(`aliases.${from} points at itself`);
459
+ out[from] = target;
460
+ }
461
+ merged.aliases = out;
462
+ }
463
+ if (root["ownerAliases"] !== undefined) {
464
+ const ownerAliases = expectObject(root["ownerAliases"], "ownerAliases");
465
+ const out = {};
466
+ for (const [from, to] of Object.entries(ownerAliases)) {
467
+ if (!OWNER_PATTERN.test(from))
468
+ throw configError(`ownerAliases key is not a GitHub login: ${from}`);
469
+ const target = expectString(to, `ownerAliases.${from}`);
470
+ if (!OWNER_PATTERN.test(target))
471
+ throw configError(`ownerAliases.${from} is not a GitHub login: ${target}`);
472
+ if (from.toLowerCase() === target.toLowerCase()) {
473
+ throw configError(`ownerAliases.${from} points at itself`);
474
+ }
475
+ out[from] = target;
476
+ }
477
+ merged.ownerAliases = out;
478
+ }
479
+ merged.discovery = parseDiscovery(root["discovery"]);
480
+ merged.collect = parseCollect(root["collect"]);
481
+ merged.triggers = parseTriggers(root["triggers"]);
482
+ if (root["webhook"] !== undefined) {
483
+ const webhook = expectObject(root["webhook"], "webhook");
484
+ if (webhook["path"] !== undefined) {
485
+ const path = expectString(webhook["path"], "webhook.path");
486
+ if (!path.startsWith("/"))
487
+ throw configError("webhook.path must start with /");
488
+ merged.webhook.path = path;
489
+ }
490
+ if (webhook["secretEnv"] !== undefined) {
491
+ merged.webhook.secretEnv = expectString(webhook["secretEnv"], "webhook.secretEnv");
492
+ }
493
+ if (webhook["toleranceSeconds"] !== undefined) {
494
+ merged.webhook.toleranceSeconds = expectInt(webhook["toleranceSeconds"], "webhook.toleranceSeconds", 0, 3600);
495
+ }
496
+ if (webhook["maxBodyBytes"] !== undefined) {
497
+ merged.webhook.maxBodyBytes = expectInt(webhook["maxBodyBytes"], "webhook.maxBodyBytes", 1024, 10485760);
498
+ }
499
+ }
500
+ if (root["watch"] !== undefined) {
501
+ const watch = expectObject(root["watch"], "watch");
502
+ if (watch["intervalSeconds"] !== undefined) {
503
+ merged.watch.intervalSeconds = expectInt(watch["intervalSeconds"], "watch.intervalSeconds", 1, 86400);
504
+ }
505
+ }
506
+ if (root["serve"] !== undefined) {
507
+ const serve = expectObject(root["serve"], "serve");
508
+ if (serve["pollIntervalSeconds"] !== undefined) {
509
+ merged.serve.pollIntervalSeconds = expectInt(serve["pollIntervalSeconds"], "serve.pollIntervalSeconds", 0, 86400);
510
+ }
511
+ if (serve["queueDepth"] !== undefined) {
512
+ merged.serve.queueDepth = expectInt(serve["queueDepth"], "serve.queueDepth", 1, 1e4);
513
+ }
514
+ if (serve["shutdownTimeoutSeconds"] !== undefined) {
515
+ merged.serve.shutdownTimeoutSeconds = expectInt(serve["shutdownTimeoutSeconds"], "serve.shutdownTimeoutSeconds", 1, 600);
516
+ }
517
+ if (serve["syncTimeoutSeconds"] !== undefined) {
518
+ merged.serve.syncTimeoutSeconds = expectInt(serve["syncTimeoutSeconds"], "serve.syncTimeoutSeconds", 1, 3600);
519
+ }
520
+ }
521
+ return merged;
522
+ }
523
+
524
+ // src/github/guard.ts
525
+ function asRecord(value) {
526
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
527
+ }
528
+ function assertPublicRepo(requested, payload) {
529
+ const record = asRecord(payload);
530
+ if (!record) {
531
+ throw new LoomError("github_error", `repository payload for ${requested} is not an object`, { repo: requested });
532
+ }
533
+ const fullName = record["full_name"];
534
+ if (typeof fullName !== "string" || fullName.length === 0) {
535
+ throw new LoomError("github_error", `repository payload for ${requested} has no full_name`, { repo: requested });
536
+ }
537
+ if (repoKey(fullName) !== repoKey(requested)) {
538
+ const requestedParts = requested.split("/");
539
+ const returnedParts = fullName.split("/");
540
+ const sameName = requestedParts.length === 2 && returnedParts.length === 2 && requestedParts[1]?.toLowerCase() === returnedParts[1]?.toLowerCase();
541
+ if (!sameName) {
542
+ throw new LoomError("github_error", `requested ${requested} but GitHub returned ${fullName}`, {
543
+ repo: requested,
544
+ returned: fullName
545
+ });
546
+ }
547
+ }
548
+ if (record["private"] === true) {
549
+ throw guardError(`refusing to snapshot private repository ${fullName}`, { repo: fullName });
550
+ }
551
+ const visibility = record["visibility"];
552
+ if (typeof visibility === "string" && visibility !== "public") {
553
+ throw guardError(`refusing to snapshot ${visibility} repository ${fullName}`, { repo: fullName });
554
+ }
555
+ const id = record["id"];
556
+ if (typeof id !== "number") {
557
+ throw new LoomError("github_error", `repository payload for ${requested} has no numeric id`, { repo: requested });
558
+ }
559
+ return {
560
+ id,
561
+ fullName,
562
+ private: false,
563
+ ...typeof visibility === "string" ? { visibility } : {},
564
+ archived: record["archived"] === true
565
+ };
566
+ }
567
+ function assertRepoRequest(value) {
568
+ if (!isRepoName(value)) {
569
+ throw new LoomError("repo_invalid", `not a valid owner/name repository: ${value}`, { repo: value });
570
+ }
571
+ return value;
572
+ }
573
+
574
+ // src/base64.ts
575
+ var BASE64_ALPHABET = /[^A-Za-z0-9+/]/g;
576
+ function decodeBase64(value) {
577
+ let clean = value.replace(BASE64_ALPHABET, "");
578
+ const remainder = clean.length % 4;
579
+ if (remainder === 1)
580
+ clean = clean.slice(0, -1);
581
+ else if (remainder === 2)
582
+ clean += "==";
583
+ else if (remainder === 3)
584
+ clean += "=";
585
+ const binary = atob(clean);
586
+ const bytes = new Uint8Array(binary.length);
587
+ for (let index = 0;index < binary.length; index += 1)
588
+ bytes[index] = binary.charCodeAt(index);
589
+ return new TextDecoder("utf-8").decode(bytes);
590
+ }
591
+
592
+ // src/types.ts
593
+ var SNAPSHOT_SCHEMA = "loom/snapshot@1";
594
+ function snapshotStats(payload) {
595
+ let releases = 0;
596
+ let readmes = 0;
597
+ let branches = 0;
598
+ let commitComments = 0;
599
+ let issueComments = 0;
600
+ let workflows = 0;
601
+ const languages = new Set;
602
+ for (const repo of payload.repos) {
603
+ releases += repo.releases.length;
604
+ if (repo.readme)
605
+ readmes += 1;
606
+ branches += repo.branches?.length ?? 0;
607
+ commitComments += repo.commitComments?.length ?? 0;
608
+ issueComments += repo.issueComments?.length ?? 0;
609
+ workflows += repo.workflows?.length ?? 0;
610
+ for (const name of Object.keys(repo.languages))
611
+ languages.add(name);
612
+ }
613
+ return {
614
+ repos: payload.repos.length,
615
+ releases,
616
+ languages: languages.size,
617
+ errors: payload.errors.length,
618
+ readmes,
619
+ branches,
620
+ commitComments,
621
+ issueComments,
622
+ workflows
623
+ };
624
+ }
625
+
626
+ // src/concurrency.ts
627
+ class CancelledError extends Error {
628
+ name = "CancelledError";
629
+ constructor(message = "operation cancelled") {
630
+ super(message);
631
+ }
632
+ }
633
+ function throwIfAborted(signal) {
634
+ if (signal?.aborted) {
635
+ const reason = signal.reason;
636
+ throw new CancelledError(reason instanceof Error ? reason.message : "operation cancelled");
637
+ }
638
+ }
639
+ function combineSignals(signals) {
640
+ const present = signals.filter((signal) => signal !== undefined);
641
+ if (present.length === 0)
642
+ return;
643
+ if (present.length === 1)
644
+ return present[0];
645
+ return AbortSignal.any(present);
646
+ }
647
+ async function mapLimitSettled(items, limit, worker, signal) {
648
+ const results = new Array(items.length);
649
+ if (items.length === 0)
650
+ return results;
651
+ const bound = Math.max(1, Math.min(Math.floor(limit), items.length));
652
+ let cursor = 0;
653
+ const run = async () => {
654
+ for (;; ) {
655
+ throwIfAborted(signal);
656
+ const index = cursor;
657
+ cursor += 1;
658
+ if (index >= items.length)
659
+ return;
660
+ try {
661
+ results[index] = { ok: true, value: await worker(items[index], index) };
662
+ } catch (error) {
663
+ results[index] = { ok: false, error };
664
+ }
665
+ }
666
+ };
667
+ await Promise.all(Array.from({ length: bound }, () => run()));
668
+ throwIfAborted(signal);
669
+ return results;
670
+ }
671
+
672
+ // src/github/collect.ts
673
+ function record(value) {
674
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
675
+ }
676
+ function text(value, fallback = null) {
677
+ return typeof value === "string" && value.length > 0 ? value : fallback;
678
+ }
679
+ function count(value) {
680
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
681
+ }
682
+ function flag(value) {
683
+ return value === true;
684
+ }
685
+ function list(value) {
686
+ return Array.isArray(value) ? value : [];
687
+ }
688
+ function languageMap(value) {
689
+ const raw = record(value) ?? {};
690
+ const out = {};
691
+ for (const [name, bytes] of Object.entries(raw)) {
692
+ if (typeof bytes === "number" && Number.isFinite(bytes) && bytes >= 0)
693
+ out[name] = bytes;
694
+ }
695
+ return out;
696
+ }
697
+ function parseRelease(value) {
698
+ const raw = record(value);
699
+ if (!raw)
700
+ return null;
701
+ const tag = text(raw["tag_name"]);
702
+ if (!tag)
703
+ return null;
704
+ const id = typeof raw["id"] === "number" ? raw["id"] : tag;
705
+ return {
706
+ id,
707
+ tag,
708
+ name: text(raw["name"]),
709
+ publishedAt: text(raw["published_at"] ?? raw["created_at"]),
710
+ prerelease: flag(raw["prerelease"]),
711
+ draft: flag(raw["draft"]),
712
+ url: text(raw["html_url"])
713
+ };
714
+ }
715
+ function parseHead(value) {
716
+ const raw = record(value);
717
+ if (!raw)
718
+ return null;
719
+ const sha = text(raw["sha"]);
720
+ if (!sha)
721
+ return null;
722
+ const commit = record(raw["commit"]) ?? {};
723
+ const author = record(commit["author"]) ?? {};
724
+ return {
725
+ sha,
726
+ message: text(commit["message"]) ?? "",
727
+ author: text(author["name"]),
728
+ committedAt: text(author["date"]),
729
+ url: text(raw["html_url"]) ?? ""
730
+ };
731
+ }
732
+ async function optional(fn) {
733
+ try {
734
+ return await fn();
735
+ } catch (error) {
736
+ if (error instanceof LoomError && (error.detail["status"] === 404 || error.detail["status"] === 410)) {
737
+ return null;
738
+ }
739
+ throw error;
740
+ }
741
+ }
742
+ function parseReadme(value, excerptChars) {
743
+ const raw = record(value);
744
+ if (!raw)
745
+ return null;
746
+ const path = text(raw["path"]) ?? text(raw["name"]);
747
+ const sha = text(raw["sha"]);
748
+ if (!path || !sha)
749
+ return null;
750
+ const encoding = text(raw["encoding"]);
751
+ let excerpt = null;
752
+ const content = text(raw["content"]);
753
+ if (content && excerptChars > 0) {
754
+ const encodedSlice = content.slice(0, Math.ceil(excerptChars * 4 / 3) + 8);
755
+ try {
756
+ const decoded = decodeBase64(encodedSlice);
757
+ excerpt = decoded.slice(0, excerptChars).replace(/\s+$/u, "");
758
+ if (excerpt.length === 0)
759
+ excerpt = null;
760
+ } catch {
761
+ excerpt = null;
762
+ }
763
+ }
764
+ return {
765
+ path,
766
+ sha,
767
+ size: count(raw["size"]),
768
+ encoding,
769
+ htmlUrl: text(raw["html_url"]),
770
+ downloadUrl: text(raw["download_url"]),
771
+ excerpt
772
+ };
773
+ }
774
+ function parseBranch(value, defaultBranch) {
775
+ const raw = record(value);
776
+ if (!raw)
777
+ return null;
778
+ const name = text(raw["name"]);
779
+ const commit = record(raw["commit"]) ?? {};
780
+ const sha = text(commit["sha"]);
781
+ if (!name || !sha)
782
+ return null;
783
+ return { name, sha, protected: flag(raw["protected"]), default: name === defaultBranch };
784
+ }
785
+ function parseCommitComment(value) {
786
+ const raw = record(value);
787
+ if (!raw)
788
+ return null;
789
+ const id = typeof raw["id"] === "number" || typeof raw["id"] === "string" ? raw["id"] : null;
790
+ if (id === null)
791
+ return null;
792
+ const user = record(raw["user"]) ?? {};
793
+ return {
794
+ id,
795
+ body: text(raw["body"]) ?? "",
796
+ author: text(user["login"]),
797
+ createdAt: text(raw["created_at"]),
798
+ url: text(raw["html_url"]),
799
+ commitSha: text(raw["commit_id"])
800
+ };
801
+ }
802
+ function parseIssueComment(value) {
803
+ const raw = record(value);
804
+ if (!raw)
805
+ return null;
806
+ const id = typeof raw["id"] === "number" || typeof raw["id"] === "string" ? raw["id"] : null;
807
+ if (id === null)
808
+ return null;
809
+ const user = record(raw["user"]) ?? {};
810
+ const issueUrl = text(raw["issue_url"]);
811
+ const issueNumber = issueUrl === null ? null : Number.parseInt(issueUrl.slice(issueUrl.lastIndexOf("/") + 1), 10);
812
+ return {
813
+ id,
814
+ body: text(raw["body"]) ?? "",
815
+ author: text(user["login"]),
816
+ createdAt: text(raw["created_at"]),
817
+ url: text(raw["html_url"]),
818
+ issueNumber: Number.isFinite(issueNumber) ? issueNumber : null
819
+ };
820
+ }
821
+ function parseWorkflow(value) {
822
+ const raw = record(value);
823
+ if (!raw)
824
+ return null;
825
+ const id = typeof raw["id"] === "number" || typeof raw["id"] === "string" ? raw["id"] : null;
826
+ const name = text(raw["name"]);
827
+ const path = text(raw["path"]);
828
+ if (id === null || !name || !path)
829
+ return null;
830
+ return { id, name, path, state: text(raw["state"]) ?? "unknown" };
831
+ }
832
+ function parseCi(value) {
833
+ const raw = record(value);
834
+ if (!raw)
835
+ return null;
836
+ const id = typeof raw["id"] === "number" || typeof raw["id"] === "string" ? raw["id"] : null;
837
+ if (id === null)
838
+ return null;
839
+ return {
840
+ workflow: text(raw["name"]),
841
+ runId: id,
842
+ status: text(raw["status"]),
843
+ conclusion: text(raw["conclusion"]),
844
+ branch: text(raw["head_branch"]),
845
+ sha: text(raw["head_sha"]),
846
+ url: text(raw["html_url"]),
847
+ updatedAt: text(raw["updated_at"])
848
+ };
849
+ }
850
+ async function collectRepo(options, requested) {
851
+ const { client } = options;
852
+ const ownerAliases = options.ownerAliases ?? {};
853
+ const target = canonicalRepoDisplay(requested, ownerAliases);
854
+ const metaResponse = await client.get(`/repos/${target}`);
855
+ if (metaResponse.body === null) {
856
+ throw new LoomError("github_error", `no repository metadata for ${target}`, { repo: target });
857
+ }
858
+ const meta = record(metaResponse.body);
859
+ if (!meta) {
860
+ throw new LoomError("github_error", `repository metadata for ${target} is not an object`, {
861
+ repo: target
862
+ });
863
+ }
864
+ const identity = assertPublicRepo(target, meta);
865
+ const fullName = canonicalRepoDisplay(identity.fullName, ownerAliases);
866
+ const defaultBranch = text(meta["default_branch"], "main") ?? "main";
867
+ const languagesResponse = await client.get(`/repos/${fullName}/languages`);
868
+ const languages = languageMap(languagesResponse.body);
869
+ const releases = [];
870
+ const wanted = Math.max(0, Math.min(100, options.releases ?? 0));
871
+ if (wanted > 0) {
872
+ const response = await client.getAll(`/repos/${fullName}/releases?per_page=${wanted}`);
873
+ for (const entry of response.items) {
874
+ const release = parseRelease(entry);
875
+ if (release && !release.draft)
876
+ releases.push(release);
877
+ }
878
+ releases.sort((a, b) => {
879
+ const left = a.publishedAt ?? "";
880
+ const right = b.publishedAt ?? "";
881
+ if (left !== right)
882
+ return left > right ? -1 : 1;
883
+ return a.tag < b.tag ? -1 : a.tag > b.tag ? 1 : 0;
884
+ });
885
+ releases.splice(wanted);
886
+ }
887
+ let head = null;
888
+ if (options.includeLatestCommit !== false) {
889
+ const response = await client.get(`/repos/${fullName}/commits?per_page=1&sha=${encodeURIComponent(defaultBranch)}`);
890
+ head = parseHead(list(response.body)[0]);
891
+ }
892
+ const collect = options.collect;
893
+ const extra = {};
894
+ if (collect?.readme) {
895
+ const response = await optional(() => client.get(`/repos/${fullName}/readme`));
896
+ extra.readme = response?.body ? parseReadme(response.body, collect.readmeExcerptChars) : null;
897
+ }
898
+ if (collect?.branches) {
899
+ const response = await optional(() => client.get(`/repos/${fullName}/branches?per_page=${collect.branchLimit}`));
900
+ const branches = [];
901
+ for (const entry of list(response?.body)) {
902
+ const branch = parseBranch(entry, defaultBranch);
903
+ if (branch)
904
+ branches.push(branch);
905
+ }
906
+ for (const name of collect.extraBranches) {
907
+ if (branches.length >= collect.branchLimit)
908
+ break;
909
+ if (branches.some((branch) => branch.name === name))
910
+ continue;
911
+ const one = await optional(() => client.get(`/repos/${fullName}/branches/${encodeURIComponent(name)}`));
912
+ const branch = one?.body ? parseBranch(one.body, defaultBranch) : null;
913
+ if (branch)
914
+ branches.push(branch);
915
+ }
916
+ if (!branches.some((branch) => branch.default) && branches.length < collect.branchLimit) {
917
+ const one = await optional(() => client.get(`/repos/${fullName}/branches/${encodeURIComponent(defaultBranch)}`));
918
+ const branch = one?.body ? parseBranch(one.body, defaultBranch) : null;
919
+ if (branch)
920
+ branches.push(branch);
921
+ }
922
+ extra.branches = branches.slice(0, collect.branchLimit);
923
+ }
924
+ if (collect?.commitComments && collect.commitCommentLimit > 0) {
925
+ const response = await optional(() => client.get(`/repos/${fullName}/comments?per_page=${collect.commitCommentLimit}`));
926
+ extra.commitComments = list(response?.body).map(parseCommitComment).filter((comment) => comment !== null).slice(0, collect.commitCommentLimit);
927
+ }
928
+ if (collect?.issueComments && collect.issueCommentLimit > 0) {
929
+ const response = await optional(() => client.get(`/repos/${fullName}/issues/comments?per_page=${collect.issueCommentLimit}`));
930
+ extra.issueComments = list(response?.body).map(parseIssueComment).filter((comment) => comment !== null).slice(0, collect.issueCommentLimit);
931
+ }
932
+ if (collect?.workflows) {
933
+ const [definitions, runs] = await Promise.all([
934
+ optional(() => client.get(`/repos/${fullName}/actions/workflows?per_page=${collect.workflowLimit}`)),
935
+ optional(() => client.get(`/repos/${fullName}/actions/runs?branch=${encodeURIComponent(defaultBranch)}&per_page=${collect.ciRuns}`))
936
+ ]);
937
+ const definitionBody = record(definitions?.body) ?? {};
938
+ extra.workflows = list(definitionBody["workflows"]).map(parseWorkflow).filter((workflow) => workflow !== null).slice(0, collect.workflowLimit);
939
+ const runBody = record(runs?.body) ?? {};
940
+ extra.ci = parseCi(list(runBody["workflow_runs"])[0]);
941
+ }
942
+ const licenseRecord = record(meta["license"]);
943
+ const metaHtmlUrl = text(meta["html_url"]);
944
+ const htmlUrlIsCanonical = metaHtmlUrl !== null && metaHtmlUrl.toLowerCase().endsWith(`/${fullName.toLowerCase()}`);
945
+ return {
946
+ id: fullName.toLowerCase(),
947
+ fullName,
948
+ description: text(meta["description"]),
949
+ homepage: text(meta["homepage"]),
950
+ topics: list(meta["topics"]).filter((topic) => typeof topic === "string"),
951
+ language: text(meta["language"]),
952
+ languages,
953
+ license: licenseRecord ? text(licenseRecord["spdx_id"]) : null,
954
+ stars: count(meta["stargazers_count"]),
955
+ forks: count(meta["forks_count"]),
956
+ watchers: count(meta["subscribers_count"] ?? meta["watchers_count"]),
957
+ openIssues: count(meta["open_issues_count"]),
958
+ archived: flag(meta["archived"]),
959
+ fork: flag(meta["fork"]),
960
+ defaultBranch,
961
+ createdAt: text(meta["created_at"]),
962
+ updatedAt: text(meta["updated_at"]),
963
+ pushedAt: text(meta["pushed_at"]),
964
+ htmlUrl: htmlUrlIsCanonical ? metaHtmlUrl : `https://github.com/${fullName}`,
965
+ visibility: "public",
966
+ releases,
967
+ head,
968
+ ...extra
969
+ };
970
+ }
971
+ async function collectSnapshot(options) {
972
+ const requests = options.repos.map((repo) => assertRepoRequest(repo));
973
+ const previous = new Map;
974
+ for (const repo of options.previous?.repos ?? [])
975
+ previous.set(repo.id.toLowerCase(), repo);
976
+ const settled = await mapLimitSettled(requests, options.concurrency ?? 4, (repo) => collectRepo(options, repo), options.signal).catch((error) => {
977
+ if (error instanceof CancelledError) {
978
+ throw new LoomError("cancelled", "repository collection cancelled", { cancelled: true });
979
+ }
980
+ throw error;
981
+ });
982
+ const repos = [];
983
+ const errors = [];
984
+ const detectedAliases = new Map;
985
+ let hardFailure = null;
986
+ settled.forEach((result, index) => {
987
+ const requested = requests[index];
988
+ const key = requested.toLowerCase();
989
+ if (result.ok) {
990
+ const actual = result.value.fullName;
991
+ if (repoKey(requested) !== repoKey(actual)) {
992
+ const before = splitRepoName(requested);
993
+ const after = splitRepoName(actual);
994
+ if (before && after && before.name.toLowerCase() === after.name.toLowerCase()) {
995
+ detectedAliases.set(before.owner, after.owner);
996
+ }
997
+ }
998
+ repos.push(result.value);
999
+ return;
1000
+ }
1001
+ const failure = describeError(result.error);
1002
+ if (!options.tolerateErrors) {
1003
+ hardFailure ??= result.error instanceof LoomError ? result.error : new LoomError("github_error", failure.message);
1004
+ return;
1005
+ }
1006
+ const retained = previous.get(key);
1007
+ if (retained)
1008
+ repos.push(structuredClone(retained));
1009
+ errors.push({
1010
+ repo: key,
1011
+ code: failure.code,
1012
+ message: failure.message,
1013
+ ...retained ? { retained: true } : {}
1014
+ });
1015
+ options.logger?.("repo failed; recorded", {
1016
+ repo: requested,
1017
+ code: failure.code,
1018
+ retained: Boolean(retained)
1019
+ });
1020
+ });
1021
+ if (hardFailure)
1022
+ throw hardFailure;
1023
+ const collect = options.collect;
1024
+ const collectSource = collect && (collect.readme || collect.branches || collect.commitComments || collect.issueComments || collect.workflows) ? {
1025
+ readme: collect.readme,
1026
+ branches: collect.branches,
1027
+ extraBranches: [...collect.extraBranches].sort(),
1028
+ branchLimit: collect.branchLimit,
1029
+ commitComments: collect.commitComments,
1030
+ commitCommentLimit: collect.commitCommentLimit,
1031
+ issueComments: collect.issueComments,
1032
+ issueCommentLimit: collect.issueCommentLimit,
1033
+ workflows: collect.workflows,
1034
+ workflowLimit: collect.workflowLimit,
1035
+ ciRuns: collect.ciRuns
1036
+ } : undefined;
1037
+ const mergedOwnerAliases = { ...options.ownerAliases ?? {} };
1038
+ for (const [from, to] of detectedAliases) {
1039
+ if (!(from.toLowerCase() in mergedOwnerAliases))
1040
+ mergedOwnerAliases[from] = to;
1041
+ }
1042
+ return {
1043
+ schema: SNAPSHOT_SCHEMA,
1044
+ source: {
1045
+ kind: "github",
1046
+ api: options.client.baseUrl,
1047
+ repos: requests,
1048
+ releases: options.releases ?? 0,
1049
+ includeLatestCommit: options.includeLatestCommit !== false,
1050
+ ...Object.keys(mergedOwnerAliases).length > 0 ? {
1051
+ ownerAliases: Object.entries(mergedOwnerAliases).map(([from, to]) => ({ from, to })).sort((a, b) => a.from.toLowerCase() < b.from.toLowerCase() ? -1 : 1)
1052
+ } : {},
1053
+ ...options.identity ? { identity: options.identity } : {},
1054
+ ...collectSource ? { collect: collectSource } : {},
1055
+ ...options.discovery ? { discovery: options.discovery } : {}
1056
+ },
1057
+ repos,
1058
+ errors
1059
+ };
1060
+ }
1061
+
1062
+ // src/github/discovery.ts
1063
+ function record2(value) {
1064
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
1065
+ }
1066
+ function skipReason(value, owner, config) {
1067
+ const raw = record2(value);
1068
+ if (!raw)
1069
+ return { fullName: null, reason: "invalid" };
1070
+ const fullName = raw["full_name"];
1071
+ if (typeof fullName !== "string" || !isRepoName(fullName))
1072
+ return { fullName: null, reason: "invalid" };
1073
+ if (raw["private"] === true)
1074
+ return { fullName, reason: "not-public" };
1075
+ const visibility = raw["visibility"];
1076
+ if (typeof visibility === "string" && visibility !== "public") {
1077
+ return { fullName, reason: "not-public" };
1078
+ }
1079
+ const ownerRecord = record2(raw["owner"]);
1080
+ const login = ownerRecord && typeof ownerRecord["login"] === "string" ? ownerRecord["login"] : null;
1081
+ const listedOwner = fullName.slice(0, fullName.indexOf("/"));
1082
+ if (repoKey(login ?? listedOwner) !== repoKey(owner))
1083
+ return { fullName, reason: "wrong-owner" };
1084
+ if (raw["archived"] === true && !config.includeArchived)
1085
+ return { fullName, reason: "archived" };
1086
+ if (raw["fork"] === true && !config.includeForks)
1087
+ return { fullName, reason: "fork" };
1088
+ if (config.exclude.some((pattern) => repoGlobMatches(pattern, fullName))) {
1089
+ return { fullName, reason: "excluded" };
1090
+ }
1091
+ if (config.include.length > 0 && !config.include.some((pattern) => repoGlobMatches(pattern, fullName))) {
1092
+ return { fullName, reason: "not-included" };
1093
+ }
1094
+ return { fullName, reason: null };
1095
+ }
1096
+ async function ownerIdentity(client, owner, ownerAliases) {
1097
+ let requested = owner;
1098
+ let candidate = owner;
1099
+ if (owner.toLowerCase() === "me") {
1100
+ const self = await client.get("/user");
1101
+ const login = record2(self.body)?.["login"];
1102
+ if (typeof login !== "string" || !login) {
1103
+ throw new LoomError("github_error", "GET /user did not return a login", { owner });
1104
+ }
1105
+ candidate = login;
1106
+ } else {
1107
+ candidate = resolveOwnerAlias(owner, ownerAliases);
1108
+ }
1109
+ let response;
1110
+ try {
1111
+ response = await client.get(`/users/${encodeURIComponent(candidate)}`);
1112
+ } catch (error) {
1113
+ if (error instanceof LoomError && error.detail["status"] === 404) {
1114
+ throw new LoomError("github_error", `owner ${requested} no longer exists; add ownerAliases["${requested}"] = "<current login>"`, { owner: requested, canonical: candidate });
1115
+ }
1116
+ throw error;
1117
+ }
1118
+ const body = record2(response.body);
1119
+ if (!body) {
1120
+ throw new LoomError("github_error", `owner metadata for ${candidate} is not an object`, { owner: candidate });
1121
+ }
1122
+ const login = typeof body["login"] === "string" && body["login"].length > 0 ? body["login"] : candidate;
1123
+ const type = body["type"];
1124
+ const kind = type === "Organization" ? "orgs" : "users";
1125
+ const alias = requested.toLowerCase() !== "me" && requested.toLowerCase() !== login.toLowerCase() ? { from: requested, to: login } : null;
1126
+ return { login, kind, alias };
1127
+ }
1128
+ async function discoverRepositories(options) {
1129
+ const { client, config } = options;
1130
+ const configuredAliases = options.ownerAliases ?? {};
1131
+ const counts = {
1132
+ selected: 0,
1133
+ "not-public": 0,
1134
+ archived: 0,
1135
+ fork: 0,
1136
+ excluded: 0,
1137
+ "not-included": 0,
1138
+ invalid: 0,
1139
+ "wrong-owner": 0
1140
+ };
1141
+ const selected = [];
1142
+ const canonicalOwners = [];
1143
+ const aliases = new Map;
1144
+ let identity = null;
1145
+ for (const owner of config.owners) {
1146
+ const resolved = await ownerIdentity(client, owner, configuredAliases);
1147
+ if (owner.toLowerCase() === "me")
1148
+ identity = resolved.login;
1149
+ if (resolved.alias)
1150
+ aliases.set(resolved.alias.from.toLowerCase(), resolved.alias);
1151
+ canonicalOwners.push(resolved.login);
1152
+ const listing = await client.getAll(`/${resolved.kind}/${encodeURIComponent(resolved.login)}/repos?type=public`);
1153
+ for (const entry of listing.items) {
1154
+ const verdict = skipReason(entry, resolved.login, config);
1155
+ if (verdict.reason !== null || verdict.fullName === null) {
1156
+ counts[verdict.reason ?? "invalid"] += 1;
1157
+ continue;
1158
+ }
1159
+ selected.push(verdict.fullName);
1160
+ }
1161
+ options.logger?.("discovery owner scanned", {
1162
+ owner: resolved.login,
1163
+ kind: resolved.kind,
1164
+ listed: listing.items.length,
1165
+ pages: listing.pages,
1166
+ notModified: listing.notModified
1167
+ });
1168
+ }
1169
+ const unique = new Map;
1170
+ for (const repo of selected) {
1171
+ const key = repoKey(repo);
1172
+ if (!unique.has(key))
1173
+ unique.set(key, repo);
1174
+ }
1175
+ const repos = [...unique.values()].sort((a, b) => {
1176
+ const left = a.toLowerCase();
1177
+ const right = b.toLowerCase();
1178
+ return left < right ? -1 : left > right ? 1 : 0;
1179
+ });
1180
+ counts.selected = repos.length;
1181
+ options.logger?.("discovery complete", { ...counts });
1182
+ return {
1183
+ repos,
1184
+ owners: [...new Set(canonicalOwners.map((owner) => owner.toLowerCase()))].sort(),
1185
+ ownerAliases: [...aliases.values()].sort((a, b) => a.from.toLowerCase() < b.from.toLowerCase() ? -1 : a.from.toLowerCase() > b.from.toLowerCase() ? 1 : 0),
1186
+ identity,
1187
+ counts
1188
+ };
1189
+ }
1190
+
1191
+ // src/version.ts
1192
+ var VERSION = "1.0.0";
1193
+ var USER_AGENT = `loom-sync/${VERSION} (+https://github.com/Sifr-Dev/Loom)`;
1194
+
1195
+ // src/github/client.ts
1196
+ var API_VERSION = "2022-11-28";
1197
+ var DEFAULT_USER_AGENT = USER_AGENT;
1198
+ function integer(value) {
1199
+ if (value === null)
1200
+ return null;
1201
+ const parsed = Number.parseInt(value, 10);
1202
+ return Number.isFinite(parsed) ? parsed : null;
1203
+ }
1204
+ function parseRateLimit(headers, nowMs = Date.now()) {
1205
+ const reset = integer(headers.get("x-ratelimit-reset"));
1206
+ const retryAfterRaw = headers.get("retry-after");
1207
+ let retryAfterSeconds = null;
1208
+ if (retryAfterRaw !== null) {
1209
+ const seconds = Number.parseInt(retryAfterRaw, 10);
1210
+ if (Number.isFinite(seconds) && String(seconds) === retryAfterRaw.trim()) {
1211
+ retryAfterSeconds = Math.max(0, seconds);
1212
+ } else {
1213
+ const dateMs = Date.parse(retryAfterRaw);
1214
+ if (Number.isFinite(dateMs))
1215
+ retryAfterSeconds = Math.max(0, Math.ceil((dateMs - nowMs) / 1000));
1216
+ }
1217
+ }
1218
+ return {
1219
+ limit: integer(headers.get("x-ratelimit-limit")),
1220
+ remaining: integer(headers.get("x-ratelimit-remaining")),
1221
+ used: integer(headers.get("x-ratelimit-used")),
1222
+ resetAt: reset === null ? null : new Date(reset * 1000).toISOString(),
1223
+ retryAfterSeconds
1224
+ };
1225
+ }
1226
+ function nextLink(header, baseUrl) {
1227
+ if (!header)
1228
+ return null;
1229
+ for (const part of header.split(",")) {
1230
+ const match = /<([^>]+)>\s*;\s*rel="?([a-z]+)"?/.exec(part.trim());
1231
+ if (match && match[2] === "next" && match[1]) {
1232
+ try {
1233
+ return new URL(match[1], baseUrl).toString();
1234
+ } catch {
1235
+ return null;
1236
+ }
1237
+ }
1238
+ }
1239
+ return null;
1240
+ }
1241
+
1242
+ class GitHubClient {
1243
+ baseUrl;
1244
+ #token;
1245
+ #userAgent;
1246
+ #cache;
1247
+ #fetch;
1248
+ #sleep;
1249
+ #now;
1250
+ #maxRetries;
1251
+ #retryBaseMs;
1252
+ #retryMaxMs;
1253
+ #jitter;
1254
+ #random;
1255
+ #maxRateLimitWaitMs;
1256
+ #rateLimitReserve;
1257
+ #requestTimeoutMs;
1258
+ #perPage;
1259
+ #maxPages;
1260
+ #signal;
1261
+ #logger;
1262
+ #requests = 0;
1263
+ #notModified = 0;
1264
+ #retries = 0;
1265
+ #rateLimitWaits = 0;
1266
+ #waitMs = 0;
1267
+ #lastRateLimit = null;
1268
+ #statuses = {};
1269
+ constructor(options = {}) {
1270
+ this.baseUrl = (options.baseUrl ?? "https://api.github.com").replace(/\/+$/, "");
1271
+ this.#token = options.token && options.token.length > 0 ? options.token : null;
1272
+ this.#userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
1273
+ this.#cache = options.cache ?? { get: () => {
1274
+ return;
1275
+ }, set: () => {}, save: async () => {}, size: () => 0 };
1276
+ this.#fetch = options.fetch ?? ((input, init) => fetch(input, init));
1277
+ this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1278
+ this.#now = options.now ?? (() => Date.now());
1279
+ this.#maxRetries = Math.max(0, options.maxRetries ?? 4);
1280
+ this.#retryBaseMs = options.retryBaseMs ?? 100;
1281
+ this.#retryMaxMs = options.retryMaxMs ?? 2000;
1282
+ this.#jitter = options.jitter ?? true;
1283
+ this.#random = options.random ?? Math.random;
1284
+ this.#maxRateLimitWaitMs = options.maxRateLimitWaitMs ?? 60000;
1285
+ this.#rateLimitReserve = options.rateLimitReserve ?? 0;
1286
+ this.#requestTimeoutMs = options.requestTimeoutMs ?? 15000;
1287
+ this.#perPage = options.perPage ?? 100;
1288
+ this.#maxPages = options.maxPages ?? 20;
1289
+ this.#signal = options.signal;
1290
+ this.#logger = options.logger ?? (() => {});
1291
+ }
1292
+ get stats() {
1293
+ return {
1294
+ requests: this.#requests,
1295
+ notModified: this.#notModified,
1296
+ retries: this.#retries,
1297
+ rateLimitWaits: this.#rateLimitWaits,
1298
+ waitMs: this.#waitMs,
1299
+ lastRateLimit: this.#lastRateLimit,
1300
+ statuses: { ...this.#statuses }
1301
+ };
1302
+ }
1303
+ url(pathOrUrl) {
1304
+ if (/^https?:\/\//.test(pathOrUrl))
1305
+ return pathOrUrl;
1306
+ const path = pathOrUrl.startsWith("/") ? pathOrUrl : `/${pathOrUrl}`;
1307
+ return `${this.baseUrl}${path}`;
1308
+ }
1309
+ #headers(url) {
1310
+ const headers = new Headers({
1311
+ accept: "application/vnd.github+json",
1312
+ "x-github-api-version": API_VERSION,
1313
+ "user-agent": this.#userAgent
1314
+ });
1315
+ if (this.#token)
1316
+ headers.set("authorization", `Bearer ${this.#token}`);
1317
+ const cached = this.#cache.get(url);
1318
+ if (cached)
1319
+ headers.set("if-none-match", cached.etag);
1320
+ return headers;
1321
+ }
1322
+ #backoff(attempt) {
1323
+ const ceiling = Math.min(this.#retryMaxMs, this.#retryBaseMs * 2 ** attempt);
1324
+ if (!this.#jitter)
1325
+ return ceiling;
1326
+ return Math.max(0, Math.floor(this.#random() * ceiling));
1327
+ }
1328
+ #rateLimitWaitMs(response) {
1329
+ const rate = parseRateLimit(response.headers, this.#now());
1330
+ this.#lastRateLimit = rate;
1331
+ const retryAfterMs = rate.retryAfterSeconds === null ? null : rate.retryAfterSeconds * 1000;
1332
+ const resetMs = rate.resetAt === null ? null : Math.max(0, Date.parse(rate.resetAt) - this.#now());
1333
+ if (response.status === 429) {
1334
+ return retryAfterMs ?? resetMs ?? this.#backoff(0);
1335
+ }
1336
+ if (response.status === 403) {
1337
+ if (rate.remaining === 0)
1338
+ return resetMs ?? retryAfterMs ?? null;
1339
+ if (retryAfterMs !== null)
1340
+ return retryAfterMs;
1341
+ if (rate.remaining === null && resetMs !== null)
1342
+ return resetMs;
1343
+ }
1344
+ return null;
1345
+ }
1346
+ async#wait(ms, signal) {
1347
+ throwIfAborted(signal);
1348
+ if (ms <= 0)
1349
+ return;
1350
+ this.#waitMs += ms;
1351
+ if (!signal) {
1352
+ await this.#sleep(ms);
1353
+ return;
1354
+ }
1355
+ await new Promise((resolve, reject) => {
1356
+ const onAbort = () => {
1357
+ cleanup();
1358
+ reject(new CancelledError("cancelled while waiting"));
1359
+ };
1360
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
1361
+ signal.addEventListener("abort", onAbort, { once: true });
1362
+ this.#sleep(ms).then(() => {
1363
+ cleanup();
1364
+ resolve();
1365
+ }, (error) => {
1366
+ cleanup();
1367
+ reject(error);
1368
+ });
1369
+ });
1370
+ }
1371
+ async#awaitBudget(signal) {
1372
+ const rate = this.#lastRateLimit;
1373
+ if (!rate || rate.remaining === null || rate.remaining > this.#rateLimitReserve)
1374
+ return;
1375
+ if (rate.resetAt === null)
1376
+ return;
1377
+ const waitMs = Math.max(0, Date.parse(rate.resetAt) - this.#now());
1378
+ if (waitMs <= 0)
1379
+ return;
1380
+ if (waitMs > this.#maxRateLimitWaitMs) {
1381
+ throw new LoomError("rate_limit_exhausted", "GitHub rate limit exhausted before the next request", {
1382
+ resetAt: rate.resetAt,
1383
+ waitMs,
1384
+ remaining: rate.remaining
1385
+ });
1386
+ }
1387
+ this.#rateLimitWaits += 1;
1388
+ this.#logger("rate limit: waiting for reset", { waitMs, resetAt: rate.resetAt });
1389
+ await this.#wait(waitMs, signal);
1390
+ }
1391
+ async#http(url, options) {
1392
+ const cached = this.#cache.get(url);
1393
+ let lastError = null;
1394
+ const outer = combineSignals([this.#signal, options.signal]);
1395
+ if (outer?.aborted) {
1396
+ throw new LoomError("cancelled", `GET ${redactUrl(url)} cancelled`, { url: redactUrl(url) });
1397
+ }
1398
+ for (let attempt = 0;attempt <= this.#maxRetries; attempt += 1) {
1399
+ if (outer?.aborted) {
1400
+ throw new LoomError("cancelled", `GET ${redactUrl(url)} cancelled`, { url: redactUrl(url) });
1401
+ }
1402
+ if (attempt > 0)
1403
+ this.#retries += 1;
1404
+ await this.#awaitBudget(outer);
1405
+ let response;
1406
+ try {
1407
+ this.#requests += 1;
1408
+ response = await this.#fetch(url, {
1409
+ method: "GET",
1410
+ headers: this.#headers(url),
1411
+ signal: combineSignals([outer, AbortSignal.timeout(this.#requestTimeoutMs)]),
1412
+ redirect: "follow"
1413
+ });
1414
+ } catch (error) {
1415
+ if (outer?.aborted || error instanceof CancelledError) {
1416
+ throw new LoomError("cancelled", `GET ${redactUrl(url)} cancelled`, { url: redactUrl(url) });
1417
+ }
1418
+ const aborted = error instanceof Error && error.name === "AbortError";
1419
+ lastError = new LoomError("network_error", `GET ${redactUrl(url)} failed${aborted ? " (timeout)" : ""}: ${error.message}`, { url: redactUrl(url), attempt, timeout: aborted });
1420
+ if (attempt < this.#maxRetries) {
1421
+ const wait = this.#backoff(attempt);
1422
+ this.#logger("retry: network error", { url: redactUrl(url), attempt, waitMs: wait });
1423
+ await this.#wait(wait, outer);
1424
+ continue;
1425
+ }
1426
+ throw lastError;
1427
+ }
1428
+ this.#statuses[String(response.status)] = (this.#statuses[String(response.status)] ?? 0) + 1;
1429
+ this.#lastRateLimit = parseRateLimit(response.headers, this.#now());
1430
+ if (response.status === 304) {
1431
+ this.#notModified += 1;
1432
+ const entry = cached;
1433
+ if (!entry && !options.allowUncached304) {
1434
+ throw new LoomError("store_corrupt", "GitHub answered 304 but no cached body exists", {
1435
+ url: redactUrl(url)
1436
+ });
1437
+ }
1438
+ return {
1439
+ status: 304,
1440
+ body: entry?.body ?? null,
1441
+ etag: entry?.etag ?? response.headers.get("etag"),
1442
+ fromCache: true,
1443
+ next: entry?.next ?? null
1444
+ };
1445
+ }
1446
+ if (response.status >= 200 && response.status < 300) {
1447
+ const text = await response.text();
1448
+ let body = null;
1449
+ if (text.length > 0) {
1450
+ try {
1451
+ body = JSON.parse(text);
1452
+ } catch {
1453
+ throw new LoomError("github_error", `GET ${redactUrl(url)} returned non-JSON`, {
1454
+ url: redactUrl(url),
1455
+ status: response.status
1456
+ });
1457
+ }
1458
+ }
1459
+ const etag = response.headers.get("etag");
1460
+ const next = nextLink(response.headers.get("link"), url);
1461
+ if (etag) {
1462
+ this.#cache.set(url, { etag, body, fetchedAt: new Date(this.#now()).toISOString(), next });
1463
+ }
1464
+ return { status: 200, body, etag, fromCache: false, next };
1465
+ }
1466
+ const rateWait = this.#rateLimitWaitMs(response);
1467
+ if (rateWait !== null) {
1468
+ if (rateWait <= this.#maxRateLimitWaitMs && attempt < this.#maxRetries) {
1469
+ this.#rateLimitWaits += 1;
1470
+ this.#logger("retry: rate limited", { url: redactUrl(url), status: response.status, waitMs: rateWait });
1471
+ await this.#wait(rateWait, outer);
1472
+ continue;
1473
+ }
1474
+ throw new LoomError("rate_limit_exhausted", "GitHub rate limit exhausted", {
1475
+ url: redactUrl(url),
1476
+ status: response.status,
1477
+ resetAt: this.#lastRateLimit?.resetAt ?? null,
1478
+ waitMs: rateWait
1479
+ });
1480
+ }
1481
+ const transient = response.status >= 500 || response.status === 408 || response.status === 425;
1482
+ if (transient && attempt < this.#maxRetries) {
1483
+ const retryAfter = this.#lastRateLimit?.retryAfterSeconds;
1484
+ const wait = retryAfter !== null && retryAfter !== undefined ? retryAfter * 1000 : this.#backoff(attempt);
1485
+ this.#logger("retry: server error", { url: redactUrl(url), status: response.status, waitMs: wait });
1486
+ await this.#wait(wait, outer);
1487
+ continue;
1488
+ }
1489
+ const text = await response.text();
1490
+ let message = text.slice(0, 300);
1491
+ let body = null;
1492
+ try {
1493
+ body = JSON.parse(text);
1494
+ if (body && typeof body === "object" && typeof body.message === "string") {
1495
+ message = body.message;
1496
+ }
1497
+ } catch {}
1498
+ throw new LoomError("github_error", `GET ${redactUrl(url)} failed with ${response.status}: ${message}`, {
1499
+ url: redactUrl(url),
1500
+ status: response.status,
1501
+ rateLimit: this.#lastRateLimit
1502
+ });
1503
+ }
1504
+ throw lastError ?? new LoomError("github_error", `GET ${redactUrl(url)} failed`, { url: redactUrl(url) });
1505
+ }
1506
+ async get(pathOrUrl, options = {}) {
1507
+ const url = this.url(pathOrUrl);
1508
+ const result = await this.#http(url, options);
1509
+ return result;
1510
+ }
1511
+ async getAll(pathOrUrl, options = {}) {
1512
+ const first = this.url(pathOrUrl);
1513
+ const start = new URL(first);
1514
+ if (!start.searchParams.has("per_page"))
1515
+ start.searchParams.set("per_page", String(this.#perPage));
1516
+ let cursor = start.toString();
1517
+ const seen = new Set;
1518
+ const items = [];
1519
+ let pages = 0;
1520
+ let allNotModified = true;
1521
+ while (cursor !== null) {
1522
+ if (pages >= this.#maxPages) {
1523
+ throw new LoomError("github_error", `pagination exceeded ${this.#maxPages} pages`, { url: redactUrl(first) });
1524
+ }
1525
+ if (seen.has(cursor)) {
1526
+ throw new LoomError("github_error", `pagination loop at ${redactUrl(cursor)}`, { url: redactUrl(cursor) });
1527
+ }
1528
+ seen.add(cursor);
1529
+ const page = await this.#http(cursor, options);
1530
+ pages += 1;
1531
+ if (page.status === 304) {
1532
+ if (Array.isArray(page.body))
1533
+ items.push(...page.body);
1534
+ else
1535
+ allNotModified = false;
1536
+ } else {
1537
+ allNotModified = false;
1538
+ if (!Array.isArray(page.body)) {
1539
+ throw new LoomError("github_error", `expected an array from ${redactUrl(cursor)}`, {
1540
+ url: redactUrl(cursor)
1541
+ });
1542
+ }
1543
+ items.push(...page.body);
1544
+ }
1545
+ cursor = page.next;
1546
+ }
1547
+ return { items, pages, notModified: allNotModified && pages > 0 };
1548
+ }
1549
+ }
1550
+
1551
+ // src/github/memory-cache.ts
1552
+ class MemoryCache {
1553
+ #entries = new Map;
1554
+ get(key) {
1555
+ return this.#entries.get(key);
1556
+ }
1557
+ set(key, entry) {
1558
+ this.#entries.set(key, entry);
1559
+ }
1560
+ async save() {}
1561
+ size() {
1562
+ return this.#entries.size;
1563
+ }
1564
+ }
1565
+
1566
+ // src/canonical.ts
1567
+ class CanonicalJsonError extends Error {
1568
+ name = "CanonicalJsonError";
1569
+ }
1570
+ function encode(value, path) {
1571
+ if (value === null)
1572
+ return "null";
1573
+ switch (typeof value) {
1574
+ case "boolean":
1575
+ return value ? "true" : "false";
1576
+ case "number": {
1577
+ if (!Number.isFinite(value)) {
1578
+ throw new CanonicalJsonError(`non-finite number at ${path}`);
1579
+ }
1580
+ return JSON.stringify(value === 0 ? 0 : value);
1581
+ }
1582
+ case "string":
1583
+ return JSON.stringify(value);
1584
+ case "object":
1585
+ break;
1586
+ default:
1587
+ throw new CanonicalJsonError(`unsupported ${typeof value} at ${path}`);
1588
+ }
1589
+ if (Array.isArray(value)) {
1590
+ const parts = [];
1591
+ for (let index = 0;index < value.length; index += 1) {
1592
+ const item = value[index];
1593
+ if (item === undefined) {
1594
+ throw new CanonicalJsonError(`undefined array element at ${path}[${index}]`);
1595
+ }
1596
+ parts.push(encode(item, `${path}[${index}]`));
1597
+ }
1598
+ return `[${parts.join(",")}]`;
1599
+ }
1600
+ const record = value;
1601
+ const proto = Object.getPrototypeOf(record);
1602
+ if (proto !== Object.prototype && proto !== null) {
1603
+ throw new CanonicalJsonError(`non-plain object at ${path}`);
1604
+ }
1605
+ const keys = Object.keys(record).sort();
1606
+ const parts = [];
1607
+ for (const key of keys) {
1608
+ const item = record[key];
1609
+ if (item === undefined)
1610
+ continue;
1611
+ parts.push(`${JSON.stringify(key)}:${encode(item, `${path}.${key}`)}`);
1612
+ }
1613
+ return `{${parts.join(",")}}`;
1614
+ }
1615
+ function canonicalize(value) {
1616
+ return encode(value, "$");
1617
+ }
1618
+ function canonicalBytes(value) {
1619
+ return new TextEncoder().encode(canonicalize(value));
1620
+ }
1621
+ function sortKeysDeep(value) {
1622
+ if (Array.isArray(value)) {
1623
+ return value.map((item) => sortKeysDeep(item));
1624
+ }
1625
+ if (value !== null && typeof value === "object") {
1626
+ const record = value;
1627
+ const out = {};
1628
+ for (const key of Object.keys(record).sort()) {
1629
+ const item = record[key];
1630
+ if (item === undefined)
1631
+ continue;
1632
+ out[key] = sortKeysDeep(item);
1633
+ }
1634
+ return out;
1635
+ }
1636
+ return value;
1637
+ }
1638
+
1639
+ // src/sha256.ts
1640
+ var K = new Uint32Array([
1641
+ 1116352408,
1642
+ 1899447441,
1643
+ 3049323471,
1644
+ 3921009573,
1645
+ 961987163,
1646
+ 1508970993,
1647
+ 2453635748,
1648
+ 2870763221,
1649
+ 3624381080,
1650
+ 310598401,
1651
+ 607225278,
1652
+ 1426881987,
1653
+ 1925078388,
1654
+ 2162078206,
1655
+ 2614888103,
1656
+ 3248222580,
1657
+ 3835390401,
1658
+ 4022224774,
1659
+ 264347078,
1660
+ 604807628,
1661
+ 770255983,
1662
+ 1249150122,
1663
+ 1555081692,
1664
+ 1996064986,
1665
+ 2554220882,
1666
+ 2821834349,
1667
+ 2952996808,
1668
+ 3210313671,
1669
+ 3336571891,
1670
+ 3584528711,
1671
+ 113926993,
1672
+ 338241895,
1673
+ 666307205,
1674
+ 773529912,
1675
+ 1294757372,
1676
+ 1396182291,
1677
+ 1695183700,
1678
+ 1986661051,
1679
+ 2177026350,
1680
+ 2456956037,
1681
+ 2730485921,
1682
+ 2820302411,
1683
+ 3259730800,
1684
+ 3345764771,
1685
+ 3516065817,
1686
+ 3600352804,
1687
+ 4094571909,
1688
+ 275423344,
1689
+ 430227734,
1690
+ 506948616,
1691
+ 659060556,
1692
+ 883997877,
1693
+ 958139571,
1694
+ 1322822218,
1695
+ 1537002063,
1696
+ 1747873779,
1697
+ 1955562222,
1698
+ 2024104815,
1699
+ 2227730452,
1700
+ 2361852424,
1701
+ 2428436474,
1702
+ 2756734187,
1703
+ 3204031479,
1704
+ 3329325298
1705
+ ]);
1706
+ function rotr(value, bits) {
1707
+ return value >>> bits | value << 32 - bits;
1708
+ }
1709
+ function sha256Bytes(input) {
1710
+ const length = input.length;
1711
+ const blocks = Math.ceil((length + 9) / 64);
1712
+ const padded = new Uint8Array(blocks * 64);
1713
+ padded.set(input);
1714
+ padded[length] = 128;
1715
+ const view = new DataView(padded.buffer);
1716
+ const bitsHigh = Math.floor(length / 536870912);
1717
+ const bitsLow = length * 8 >>> 0;
1718
+ view.setUint32(padded.length - 8, bitsHigh);
1719
+ view.setUint32(padded.length - 4, bitsLow);
1720
+ const state = new Uint32Array([
1721
+ 1779033703,
1722
+ 3144134277,
1723
+ 1013904242,
1724
+ 2773480762,
1725
+ 1359893119,
1726
+ 2600822924,
1727
+ 528734635,
1728
+ 1541459225
1729
+ ]);
1730
+ const w = new Uint32Array(64);
1731
+ for (let offset = 0;offset < padded.length; offset += 64) {
1732
+ for (let index = 0;index < 16; index += 1)
1733
+ w[index] = view.getUint32(offset + index * 4);
1734
+ for (let index = 16;index < 64; index += 1) {
1735
+ const w15 = w[index - 15];
1736
+ const w2 = w[index - 2];
1737
+ const s0 = rotr(w15, 7) ^ rotr(w15, 18) ^ w15 >>> 3;
1738
+ const s1 = rotr(w2, 17) ^ rotr(w2, 19) ^ w2 >>> 10;
1739
+ w[index] = w[index - 16] + s0 + w[index - 7] + s1 >>> 0;
1740
+ }
1741
+ let a = state[0];
1742
+ let b = state[1];
1743
+ let c = state[2];
1744
+ let d = state[3];
1745
+ let e = state[4];
1746
+ let f = state[5];
1747
+ let g = state[6];
1748
+ let h = state[7];
1749
+ for (let index = 0;index < 64; index += 1) {
1750
+ const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
1751
+ const ch = e & f ^ ~e & g;
1752
+ const temp1 = h + s1 + ch + K[index] + w[index] >>> 0;
1753
+ const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
1754
+ const maj = a & b ^ a & c ^ b & c;
1755
+ const temp2 = s0 + maj >>> 0;
1756
+ h = g;
1757
+ g = f;
1758
+ f = e;
1759
+ e = d + temp1 >>> 0;
1760
+ d = c;
1761
+ c = b;
1762
+ b = a;
1763
+ a = temp1 + temp2 >>> 0;
1764
+ }
1765
+ state[0] = state[0] + a >>> 0;
1766
+ state[1] = state[1] + b >>> 0;
1767
+ state[2] = state[2] + c >>> 0;
1768
+ state[3] = state[3] + d >>> 0;
1769
+ state[4] = state[4] + e >>> 0;
1770
+ state[5] = state[5] + f >>> 0;
1771
+ state[6] = state[6] + g >>> 0;
1772
+ state[7] = state[7] + h >>> 0;
1773
+ }
1774
+ const digest = new Uint8Array(32);
1775
+ const out = new DataView(digest.buffer);
1776
+ for (let index = 0;index < 8; index += 1)
1777
+ out.setUint32(index * 4, state[index]);
1778
+ return digest;
1779
+ }
1780
+ var HEX = "0123456789abcdef";
1781
+ function sha256Hex(input) {
1782
+ const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
1783
+ const digest = sha256Bytes(bytes);
1784
+ let hex = "";
1785
+ for (const byte of digest)
1786
+ hex += `${HEX[byte >>> 4] ?? "0"}${HEX[byte & 15] ?? "0"}`;
1787
+ return hex;
1788
+ }
1789
+
1790
+ // src/digest.ts
1791
+ var DIGEST_PREFIX = "sha256:";
1792
+ function digestOf(value) {
1793
+ return `${DIGEST_PREFIX}${sha256Hex(canonicalize(value))}`;
1794
+ }
1795
+ function isDigest(value) {
1796
+ return /^sha256:[0-9a-f]{64}$/.test(value);
1797
+ }
1798
+ function assertDigest(value) {
1799
+ if (!isDigest(value)) {
1800
+ throw new TypeError(`not a Loom digest: ${value}`);
1801
+ }
1802
+ return value;
1803
+ }
1804
+ function digestHex(digest) {
1805
+ return assertDigest(digest).slice(DIGEST_PREFIX.length);
1806
+ }
1807
+ function shortDigest(digest, length = 8) {
1808
+ return `${DIGEST_PREFIX}${digestHex(digest).slice(0, length)}`;
1809
+ }
1810
+
1811
+ // src/snapshot.ts
1812
+ function byCodeUnit(a, b) {
1813
+ return a < b ? -1 : a > b ? 1 : 0;
1814
+ }
1815
+ function normalizeSnapshot(payload) {
1816
+ const repos = [...payload.repos].map((repo) => ({
1817
+ ...repo,
1818
+ topics: [...new Set(repo.topics)].sort(byCodeUnit),
1819
+ releases: [...repo.releases].filter((release) => !release.draft).sort((a, b) => {
1820
+ const left = a.publishedAt ?? "";
1821
+ const right = b.publishedAt ?? "";
1822
+ if (left !== right)
1823
+ return left > right ? -1 : 1;
1824
+ return byCodeUnit(a.tag, b.tag);
1825
+ }),
1826
+ ...repo.branches ? {
1827
+ branches: [...repo.branches].sort((a, b) => Number(b.default) - Number(a.default) || byCodeUnit(a.name, b.name))
1828
+ } : {},
1829
+ ...repo.commitComments ? {
1830
+ commitComments: [...repo.commitComments].sort((a, b) => byCodeUnit(b.createdAt ?? "", a.createdAt ?? "") || byCodeUnit(String(a.id), String(b.id)))
1831
+ } : {},
1832
+ ...repo.issueComments ? {
1833
+ issueComments: [...repo.issueComments].sort((a, b) => byCodeUnit(b.createdAt ?? "", a.createdAt ?? "") || byCodeUnit(String(a.id), String(b.id)))
1834
+ } : {},
1835
+ ...repo.workflows ? { workflows: [...repo.workflows].sort((a, b) => byCodeUnit(String(a.id), String(b.id))) } : {}
1836
+ })).sort((a, b) => byCodeUnit(a.id, b.id));
1837
+ const seen = new Set;
1838
+ const unique = repos.filter((repo) => {
1839
+ if (seen.has(repo.id))
1840
+ return false;
1841
+ seen.add(repo.id);
1842
+ return true;
1843
+ });
1844
+ const errors = [...payload.errors].sort((a, b) => byCodeUnit(a.repo, b.repo) || byCodeUnit(a.code, b.code));
1845
+ return {
1846
+ schema: SNAPSHOT_SCHEMA,
1847
+ source: {
1848
+ ...payload.source,
1849
+ repos: [...new Set(payload.source.repos.map((repo) => repo.toLowerCase()))].sort(byCodeUnit),
1850
+ ...payload.source.ownerAliases ? {
1851
+ ownerAliases: [...new Map(payload.source.ownerAliases.map((entry) => [entry.from.toLowerCase(), entry])).values()].sort((a, b) => byCodeUnit(a.from.toLowerCase(), b.from.toLowerCase()))
1852
+ } : {},
1853
+ ...payload.source.discovery ? {
1854
+ discovery: {
1855
+ ...payload.source.discovery,
1856
+ owners: [...new Set(payload.source.discovery.owners.map((owner) => owner.toLowerCase()))].sort(byCodeUnit),
1857
+ include: [...new Set(payload.source.discovery.include)].sort(byCodeUnit),
1858
+ exclude: [...new Set(payload.source.discovery.exclude)].sort(byCodeUnit)
1859
+ }
1860
+ } : {}
1861
+ },
1862
+ repos: unique,
1863
+ errors
1864
+ };
1865
+ }
1866
+ function buildSnapshot(payload) {
1867
+ const normalized = normalizeSnapshot(payload);
1868
+ return { payload: normalized, id: digestOf(normalized) };
1869
+ }
1870
+
1871
+ // src/compute.ts
1872
+ function ownerAliasesOf(snapshot) {
1873
+ const out = {};
1874
+ for (const entry of snapshot.payload.source.ownerAliases ?? [])
1875
+ out[entry.from] = entry.to;
1876
+ return out;
1877
+ }
1878
+ function createClient(options, cache, baseUrl, fixture) {
1879
+ return new GitHubClient({
1880
+ baseUrl,
1881
+ token: options.token ?? null,
1882
+ cache,
1883
+ ...fixture ? { fetch: fixture.fetch } : options.fetch ? { fetch: options.fetch } : {},
1884
+ ...options.sleep ? { sleep: options.sleep } : {},
1885
+ ...options.now ? { now: options.now } : {},
1886
+ ...options.logger ? { logger: options.logger } : {},
1887
+ ...options.signal ? { signal: options.signal } : {}
1888
+ });
1889
+ }
1890
+ async function computeSnapshot(options) {
1891
+ const explicit = options.config.repos;
1892
+ const discovery = options.config.discovery;
1893
+ if (explicit.length === 0 && discovery.owners.length === 0) {
1894
+ throw new LoomError("config_invalid", "no repositories configured; add repos or discovery.owners to loom.config.json");
1895
+ }
1896
+ const fixture = options.fixture ?? null;
1897
+ const cache = options.cache === null ? new MemoryCache : options.cache ?? new MemoryCache;
1898
+ const client = createClient(options, cache, fixture?.baseUrl ?? options.config.githubBaseUrl, fixture?.transport ?? null);
1899
+ let discovered = [];
1900
+ let discoverySource;
1901
+ let identity = null;
1902
+ const ownerAliases = { ...options.config.ownerAliases };
1903
+ if (discovery.owners.length > 0) {
1904
+ const result = await discoverRepositories({
1905
+ client,
1906
+ config: discovery,
1907
+ ownerAliases,
1908
+ ...options.signal ? { signal: options.signal } : {},
1909
+ ...options.logger ? { logger: options.logger } : {}
1910
+ });
1911
+ discovered = result.repos;
1912
+ identity = result.identity;
1913
+ for (const alias of result.ownerAliases)
1914
+ ownerAliases[alias.from] = alias.to;
1915
+ discoverySource = {
1916
+ owners: result.owners,
1917
+ include: [...discovery.include].sort(),
1918
+ exclude: [...discovery.exclude].sort(),
1919
+ includeArchived: discovery.includeArchived,
1920
+ includeForks: discovery.includeForks,
1921
+ selected: result.repos.length
1922
+ };
1923
+ }
1924
+ const seen = new Set;
1925
+ const requests = [];
1926
+ const explicitCanonical = explicit.map((repo) => canonicalRepoDisplay(repo, ownerAliases));
1927
+ for (const repo of [...explicitCanonical, ...discovered]) {
1928
+ const key = canonicalRepoKey(repo, ownerAliases);
1929
+ if (seen.has(key))
1930
+ continue;
1931
+ seen.add(key);
1932
+ requests.push(canonicalRepoDisplay(repo, ownerAliases));
1933
+ }
1934
+ if (requests.length === 0) {
1935
+ throw new LoomError("config_invalid", "discovery selected no repositories; refusing an empty snapshot");
1936
+ }
1937
+ const payload = await collectSnapshot({
1938
+ client,
1939
+ repos: requests,
1940
+ releases: options.config.releases,
1941
+ includeLatestCommit: options.config.includeLatestCommit,
1942
+ collect: options.config.collect,
1943
+ ownerAliases,
1944
+ ...identity ? { identity } : {},
1945
+ ...options.tolerateErrors ? { tolerateErrors: true } : {},
1946
+ ...options.previous ? { previous: options.previous } : {},
1947
+ ...options.concurrency ? { concurrency: options.concurrency } : {},
1948
+ ...options.signal ? { signal: options.signal } : {},
1949
+ ...discoverySource ? { discovery: discoverySource } : {},
1950
+ ...options.logger ? { logger: options.logger } : {}
1951
+ });
1952
+ const snapshot = buildSnapshot(payload);
1953
+ return {
1954
+ snapshot,
1955
+ payload: snapshot.payload,
1956
+ client,
1957
+ fixture: fixture?.transport ?? null,
1958
+ cache,
1959
+ stats: snapshotStats(snapshot.payload)
1960
+ };
1961
+ }
1962
+
1963
+ // src/entities.ts
1964
+ function repoFields(repo) {
1965
+ const {
1966
+ releases: _releases,
1967
+ head: _head,
1968
+ readme: _readme,
1969
+ branches: _branches,
1970
+ commitComments: _commitComments,
1971
+ issueComments: _issueComments,
1972
+ workflows: _workflows,
1973
+ ci: _ci,
1974
+ ...fields
1975
+ } = repo;
1976
+ return fields;
1977
+ }
1978
+ function repoEntityId(repo) {
1979
+ return `repo:${repo.toLowerCase()}`;
1980
+ }
1981
+ function releaseEntityId(repo, tag) {
1982
+ return `release:${repo.toLowerCase()}@${tag}`;
1983
+ }
1984
+ function headEntityId(repo) {
1985
+ return `head:${repo.toLowerCase()}`;
1986
+ }
1987
+ function readmeEntityId(repo) {
1988
+ return `readme:${repo.toLowerCase()}`;
1989
+ }
1990
+ function branchEntityId(repo, branch) {
1991
+ return `branch:${repo.toLowerCase()}@${branch}`;
1992
+ }
1993
+ function commitCommentEntityId(repo, id) {
1994
+ return `commit-comment:${repo.toLowerCase()}@${id}`;
1995
+ }
1996
+ function issueCommentEntityId(repo, id) {
1997
+ return `issue-comment:${repo.toLowerCase()}@${id}`;
1998
+ }
1999
+ function workflowEntityId(repo, id) {
2000
+ return `workflow:${repo.toLowerCase()}@${id}`;
2001
+ }
2002
+ function ciEntityId(repo) {
2003
+ return `ci:${repo.toLowerCase()}`;
2004
+ }
2005
+ var KIND_BY_PREFIX = [
2006
+ ["commit-comment:", "commit-comment"],
2007
+ ["issue-comment:", "issue-comment"],
2008
+ ["release:", "release"],
2009
+ ["branch:", "branch"],
2010
+ ["workflow:", "workflow"],
2011
+ ["readme:", "readme"],
2012
+ ["head:", "head"],
2013
+ ["repo:", "repo"],
2014
+ ["ci:", "ci"]
2015
+ ];
2016
+ function entityKindOf(id) {
2017
+ for (const [prefix, kind] of KIND_BY_PREFIX) {
2018
+ if (id.startsWith(prefix))
2019
+ return kind;
2020
+ }
2021
+ return null;
2022
+ }
2023
+ var AT_KINDS = new Set(["release", "branch", "commit-comment", "issue-comment", "workflow"]);
2024
+ function repoOfEntityId(id) {
2025
+ const kind = entityKindOf(id);
2026
+ if (kind === null)
2027
+ return null;
2028
+ const rest = id.slice(id.indexOf(":") + 1);
2029
+ if (AT_KINDS.has(kind)) {
2030
+ const at = rest.lastIndexOf("@");
2031
+ return at === -1 ? rest : rest.slice(0, at);
2032
+ }
2033
+ return rest;
2034
+ }
2035
+ function entity(kind, id, repo, fields) {
2036
+ return { id, kind, repo, fingerprint: digestOf(fields), fields };
2037
+ }
2038
+ function entitiesFromSnapshot(payload) {
2039
+ const out = new Map;
2040
+ for (const repo of payload.repos) {
2041
+ const meta = repoFields(repo);
2042
+ out.set(repoEntityId(repo.id), entity("repo", repoEntityId(repo.id), repo.id, meta));
2043
+ for (const release of repo.releases) {
2044
+ out.set(releaseEntityId(repo.id, release.tag), entity("release", releaseEntityId(repo.id, release.tag), repo.id, {
2045
+ repo: repo.id,
2046
+ ...release
2047
+ }));
2048
+ }
2049
+ if (repo.head) {
2050
+ out.set(headEntityId(repo.id), entity("head", headEntityId(repo.id), repo.id, {
2051
+ repo: repo.id,
2052
+ ...repo.head
2053
+ }));
2054
+ }
2055
+ if (repo.readme) {
2056
+ out.set(readmeEntityId(repo.id), entity("readme", readmeEntityId(repo.id), repo.id, { repo: repo.id, ...repo.readme }));
2057
+ }
2058
+ for (const branch of repo.branches ?? []) {
2059
+ out.set(branchEntityId(repo.id, branch.name), entity("branch", branchEntityId(repo.id, branch.name), repo.id, {
2060
+ repo: repo.id,
2061
+ ...branch
2062
+ }));
2063
+ }
2064
+ for (const comment of repo.commitComments ?? []) {
2065
+ out.set(commitCommentEntityId(repo.id, comment.id), entity("commit-comment", commitCommentEntityId(repo.id, comment.id), repo.id, {
2066
+ repo: repo.id,
2067
+ ...comment
2068
+ }));
2069
+ }
2070
+ for (const comment of repo.issueComments ?? []) {
2071
+ out.set(issueCommentEntityId(repo.id, comment.id), entity("issue-comment", issueCommentEntityId(repo.id, comment.id), repo.id, {
2072
+ repo: repo.id,
2073
+ ...comment
2074
+ }));
2075
+ }
2076
+ for (const workflow of repo.workflows ?? []) {
2077
+ out.set(workflowEntityId(repo.id, workflow.id), entity("workflow", workflowEntityId(repo.id, workflow.id), repo.id, {
2078
+ repo: repo.id,
2079
+ ...workflow
2080
+ }));
2081
+ }
2082
+ if (repo.ci) {
2083
+ out.set(ciEntityId(repo.id), entity("ci", ciEntityId(repo.id), repo.id, { repo: repo.id, ...repo.ci }));
2084
+ }
2085
+ }
2086
+ return out;
2087
+ }
2088
+
2089
+ // src/diff.ts
2090
+ var DIFF_SCHEMA = "loom/diff@1";
2091
+ function normalizeAliases(aliases, ownerAliases) {
2092
+ const map = new Map;
2093
+ for (const [from, to] of Object.entries(aliases)) {
2094
+ map.set(canonicalRepoKey(from, ownerAliases), canonicalRepoKey(to, ownerAliases));
2095
+ }
2096
+ return map;
2097
+ }
2098
+ function resolveRepoAlias(repo, aliases, ownerAliases = {}) {
2099
+ const map = normalizeAliases(aliases, ownerAliases);
2100
+ let current = canonicalRepoKey(repo, ownerAliases);
2101
+ const seen = new Set([current]);
2102
+ for (let depth = 0;depth < 8; depth += 1) {
2103
+ const next = map.get(current);
2104
+ if (!next || seen.has(next))
2105
+ return current;
2106
+ seen.add(next);
2107
+ current = next;
2108
+ }
2109
+ return current;
2110
+ }
2111
+ function rewriteEntityId(id, aliases, ownerAliases = {}) {
2112
+ const repo = repoOfEntityId(id);
2113
+ if (repo === null)
2114
+ return id;
2115
+ const resolved = resolveRepoAlias(repo, aliases, ownerAliases);
2116
+ if (resolved === repo)
2117
+ return id;
2118
+ const colon = id.indexOf(":");
2119
+ const rest = id.slice(colon + 1);
2120
+ const at = rest.lastIndexOf("@");
2121
+ return at === -1 ? `${id.slice(0, colon)}:${resolved}` : `${id.slice(0, colon)}:${resolved}@${rest.slice(at + 1)}`;
2122
+ }
2123
+ function changedFields(before, after) {
2124
+ const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
2125
+ const changed = [];
2126
+ for (const key of keys) {
2127
+ const left = key in before ? canonicalize(before[key]) : "";
2128
+ const right = key in after ? canonicalize(after[key]) : "";
2129
+ if (left !== right)
2130
+ changed.push(key);
2131
+ }
2132
+ return changed.sort(byCodeUnit);
2133
+ }
2134
+ function eventFor(entity, kind, previous) {
2135
+ const base = {
2136
+ id: entity.id,
2137
+ kind,
2138
+ entity: entity.kind,
2139
+ repo: entity.repo,
2140
+ fingerprint: kind === "removed" ? null : entity.fingerprint,
2141
+ previousFingerprint: kind === "added" ? null : kind === "removed" ? entity.fingerprint : previous?.fingerprint ?? null
2142
+ };
2143
+ if (kind === "updated" && previous) {
2144
+ return {
2145
+ ...base,
2146
+ fields: changedFields(previous.fields, entity.fields),
2147
+ ...previous.id !== entity.id ? { previousId: previous.id } : {}
2148
+ };
2149
+ }
2150
+ return { ...base, fields: [] };
2151
+ }
2152
+ function compareEvents(a, b) {
2153
+ return byCodeUnit(a.id, b.id) || byCodeUnit(a.kind, b.kind);
2154
+ }
2155
+ function diffSnapshots(from, to, options = {}) {
2156
+ const aliases = options.aliases ?? {};
2157
+ const ownerAliases = options.ownerAliases ?? {};
2158
+ const before = from === null ? new Map : entitiesFromSnapshot(from.payload);
2159
+ const after = entitiesFromSnapshot(to.payload);
2160
+ const events = [];
2161
+ const renames = [];
2162
+ const pairedOldIds = new Set;
2163
+ const addedIds = [...after.keys()].filter((id) => !before.has(id)).sort(byCodeUnit);
2164
+ const removedIds = [...before.keys()].filter((id) => !after.has(id)).sort(byCodeUnit);
2165
+ const pairedNewIds = new Set;
2166
+ for (const oldId of removedIds) {
2167
+ const rewritten = rewriteEntityId(oldId, aliases, ownerAliases);
2168
+ if (rewritten === oldId || !after.has(rewritten) || before.has(rewritten))
2169
+ continue;
2170
+ if (pairedNewIds.has(rewritten))
2171
+ continue;
2172
+ const previous = before.get(oldId);
2173
+ const next = after.get(rewritten);
2174
+ if (previous.kind !== next.kind)
2175
+ continue;
2176
+ pairedOldIds.add(oldId);
2177
+ pairedNewIds.add(rewritten);
2178
+ events.push(eventFor(next, "updated", previous));
2179
+ renames.push({ from: oldId, to: rewritten });
2180
+ }
2181
+ for (const id of addedIds) {
2182
+ if (pairedNewIds.has(id))
2183
+ continue;
2184
+ events.push(eventFor(after.get(id), "added"));
2185
+ }
2186
+ for (const id of removedIds) {
2187
+ if (pairedOldIds.has(id))
2188
+ continue;
2189
+ events.push(eventFor(before.get(id), "removed"));
2190
+ }
2191
+ const commonIds = [...after.keys()].filter((id) => before.has(id)).sort(byCodeUnit);
2192
+ for (const id of commonIds) {
2193
+ const previous = before.get(id);
2194
+ const next = after.get(id);
2195
+ if (previous.fingerprint !== next.fingerprint) {
2196
+ events.push(eventFor(next, "updated", previous));
2197
+ }
2198
+ }
2199
+ events.sort(compareEvents);
2200
+ const summary = {
2201
+ added: events.filter((event) => event.kind === "added").length,
2202
+ updated: events.filter((event) => event.kind === "updated").length,
2203
+ removed: events.filter((event) => event.kind === "removed").length,
2204
+ renamed: events.filter((event) => event.previousId !== undefined).length,
2205
+ total: events.length
2206
+ };
2207
+ return {
2208
+ schema: DIFF_SCHEMA,
2209
+ from: from?.id ?? null,
2210
+ to: to.id,
2211
+ changed: events.length > 0,
2212
+ summary,
2213
+ renames,
2214
+ events
2215
+ };
2216
+ }
2217
+ function describeEvent(event) {
2218
+ const suffix = event.previousId ? ` (renamed from ${event.previousId})` : "";
2219
+ const fields = event.fields.length > 0 ? ` [${event.fields.join(", ")}]` : "";
2220
+ return `${event.kind.padEnd(7)} ${event.id}${fields}${suffix}`;
2221
+ }
2222
+
2223
+ // src/site.ts
2224
+ var SITE_SCHEMA = "loom/site@1";
2225
+ function splitName(fullName) {
2226
+ const slash = fullName.indexOf("/");
2227
+ if (slash === -1)
2228
+ return { owner: "", name: fullName };
2229
+ return { owner: fullName.slice(0, slash), name: fullName.slice(slash + 1) };
2230
+ }
2231
+ function rewriteOwnerInUrl(url, ownerAliases) {
2232
+ if (url === null)
2233
+ return null;
2234
+ let out = url;
2235
+ for (const [from, to] of Object.entries(ownerAliases)) {
2236
+ const escaped = from.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2237
+ out = out.replace(new RegExp(`/${escaped}/`, "gi"), `/${to}/`);
2238
+ }
2239
+ return out;
2240
+ }
2241
+ function siteRelease(release, ownerAliases) {
2242
+ return {
2243
+ tag: release.tag,
2244
+ name: release.name,
2245
+ publishedAt: release.publishedAt,
2246
+ prerelease: release.prerelease,
2247
+ url: rewriteOwnerInUrl(release.url, ownerAliases)
2248
+ };
2249
+ }
2250
+ function siteHead(head, ownerAliases) {
2251
+ return {
2252
+ sha: head.sha,
2253
+ shortSha: head.sha.slice(0, 12),
2254
+ message: head.message,
2255
+ author: head.author,
2256
+ committedAt: head.committedAt,
2257
+ url: rewriteOwnerInUrl(head.url, ownerAliases) ?? ""
2258
+ };
2259
+ }
2260
+ function languagesOf(repo) {
2261
+ return Object.entries(repo.languages).map(([name, bytes]) => ({ name, bytes })).sort((a, b) => b.bytes - a.bytes || byCodeUnit(a.name, b.name));
2262
+ }
2263
+ function siteBranches(repo) {
2264
+ return (repo.branches ?? []).map((branch) => ({
2265
+ name: branch.name,
2266
+ sha: branch.sha,
2267
+ shortSha: branch.sha.slice(0, 12),
2268
+ protected: branch.protected,
2269
+ default: branch.default
2270
+ })).sort((a, b) => Number(b.default) - Number(a.default) || byCodeUnit(a.name, b.name));
2271
+ }
2272
+ function siteComments(comments) {
2273
+ return comments.map((comment) => ({
2274
+ id: comment.id,
2275
+ body: comment.body,
2276
+ author: comment.author,
2277
+ createdAt: comment.createdAt,
2278
+ url: comment.url
2279
+ })).sort((a, b) => byCodeUnit(b.createdAt ?? "", a.createdAt ?? "") || byCodeUnit(String(a.id), String(b.id)));
2280
+ }
2281
+ function siteCi(repo) {
2282
+ if (!repo.ci)
2283
+ return null;
2284
+ return {
2285
+ workflow: repo.ci.workflow,
2286
+ runId: repo.ci.runId,
2287
+ status: repo.ci.status,
2288
+ conclusion: repo.ci.conclusion,
2289
+ branch: repo.ci.branch,
2290
+ sha: repo.ci.sha,
2291
+ shortSha: repo.ci.sha === null ? null : repo.ci.sha.slice(0, 12),
2292
+ url: repo.ci.url,
2293
+ updatedAt: repo.ci.updatedAt
2294
+ };
2295
+ }
2296
+ function siteProject(repo, ownerAliases = {}) {
2297
+ const split = splitName(repo.fullName);
2298
+ const owner = resolveOwnerAlias(split.owner, ownerAliases);
2299
+ const fullName = owner === split.owner ? repo.fullName : `${owner}/${split.name}`;
2300
+ const htmlUrl = rewriteOwnerInUrl(repo.htmlUrl, ownerAliases) ?? `https://github.com/${fullName}`;
2301
+ const releases = repo.releases.map((release) => siteRelease(release, ownerAliases));
2302
+ return {
2303
+ id: `${owner}/${split.name}`.toLowerCase(),
2304
+ slug: split.name.toLowerCase(),
2305
+ owner,
2306
+ name: split.name,
2307
+ fullName,
2308
+ description: repo.description,
2309
+ homepage: repo.homepage,
2310
+ topics: [...repo.topics],
2311
+ language: repo.language,
2312
+ languages: languagesOf(repo),
2313
+ license: repo.license,
2314
+ stars: repo.stars,
2315
+ forks: repo.forks,
2316
+ watchers: repo.watchers,
2317
+ openIssues: repo.openIssues,
2318
+ archived: repo.archived,
2319
+ fork: repo.fork,
2320
+ defaultBranch: repo.defaultBranch,
2321
+ htmlUrl,
2322
+ createdAt: repo.createdAt,
2323
+ updatedAt: repo.updatedAt,
2324
+ pushedAt: repo.pushedAt,
2325
+ release: releases[0] ?? null,
2326
+ releases,
2327
+ head: repo.head === null ? null : siteHead(repo.head, ownerAliases),
2328
+ ...repo.readme !== undefined ? {
2329
+ readme: repo.readme === null ? null : {
2330
+ path: repo.readme.path,
2331
+ sha: repo.readme.sha,
2332
+ size: repo.readme.size,
2333
+ htmlUrl: repo.readme.htmlUrl,
2334
+ downloadUrl: repo.readme.downloadUrl,
2335
+ excerpt: repo.readme.excerpt
2336
+ }
2337
+ } : {},
2338
+ ...repo.branches ? { branches: siteBranches(repo) } : {},
2339
+ ...repo.commitComments ? { commitComments: siteComments(repo.commitComments) } : {},
2340
+ ...repo.issueComments ? { issueComments: siteComments(repo.issueComments) } : {},
2341
+ ...repo.workflows ? {
2342
+ workflows: [...repo.workflows].map((workflow) => ({
2343
+ id: workflow.id,
2344
+ name: workflow.name,
2345
+ path: workflow.path,
2346
+ state: workflow.state
2347
+ })).sort((a, b) => byCodeUnit(String(a.id), String(b.id)))
2348
+ } : {},
2349
+ ...repo.ci !== undefined ? { ci: siteCi(repo) } : {}
2350
+ };
2351
+ }
2352
+ function buildSiteRecord(snapshot, options = {}) {
2353
+ const ownerAliases = options.ownerAliases ?? {};
2354
+ const repoAliases = options.aliases ?? {};
2355
+ const projects = snapshot.payload.repos.map((repo) => siteProject(repo, ownerAliases)).sort((a, b) => byCodeUnit(a.id, b.id));
2356
+ const errors = [...snapshot.payload.errors].sort((a, b) => byCodeUnit(a.repo, b.repo) || byCodeUnit(a.code, b.code));
2357
+ const ownerAliasList = Object.keys(ownerAliases).map((from) => ({
2358
+ from: from.toLowerCase(),
2359
+ to: resolveOwnerAlias(from, ownerAliases).toLowerCase()
2360
+ })).filter((entry) => entry.from !== entry.to).sort((a, b) => byCodeUnit(a.from, b.from));
2361
+ const aliases = Object.keys(repoAliases).map((from) => ({
2362
+ from: canonicalRepoKey(from, ownerAliases),
2363
+ to: resolveRepoAlias(from, repoAliases, ownerAliases)
2364
+ })).filter((entry) => entry.from !== entry.to).sort((a, b) => byCodeUnit(a.from, b.from));
2365
+ return {
2366
+ schema: SITE_SCHEMA,
2367
+ snapshot: snapshot.id,
2368
+ complete: errors.every((error) => error.retained === true),
2369
+ projects,
2370
+ aliases,
2371
+ ownerAliases: ownerAliasList,
2372
+ errors
2373
+ };
2374
+ }
2375
+ function siteDigest(record) {
2376
+ return digestOf(record);
2377
+ }
2378
+ // src/github/fixture.ts
2379
+ function normaliseKey(key) {
2380
+ const [method, target] = key.split(/\s+/, 2);
2381
+ return `${method?.toUpperCase() ?? "GET"} ${target ?? ""}`;
2382
+ }
2383
+ function searchWithoutPaging(search) {
2384
+ const params = new URLSearchParams(search);
2385
+ params.delete("per_page");
2386
+ params.delete("page");
2387
+ const text = params.toString();
2388
+ return text.length > 0 ? `?${text}` : "";
2389
+ }
2390
+ function createFixtureTransport(file) {
2391
+ const routes = new Map;
2392
+ for (const [key, value] of Object.entries(file.routes)) {
2393
+ routes.set(normaliseKey(key), value);
2394
+ }
2395
+ const requests = [];
2396
+ const missing = [];
2397
+ const cursors = new Map;
2398
+ const byPath = new Map;
2399
+ for (const key of routes.keys()) {
2400
+ const path = key.split(" ")[1]?.split("?")[0] ?? "";
2401
+ const list = byPath.get(path) ?? [];
2402
+ list.push(key);
2403
+ byPath.set(path, list);
2404
+ }
2405
+ const resolve = (method, url) => {
2406
+ const exact = `${method} ${url.pathname}${url.search}`;
2407
+ const direct = routes.get(exact);
2408
+ if (direct !== undefined)
2409
+ return { key: exact, route: direct };
2410
+ const loose = `${method} ${url.pathname}${searchWithoutPaging(url.search)}`;
2411
+ const looseRoute = routes.get(loose);
2412
+ if (looseRoute !== undefined)
2413
+ return { key: loose, route: looseRoute };
2414
+ const candidates = byPath.get(url.pathname) ?? [];
2415
+ if (candidates.length === 1) {
2416
+ const key = candidates[0];
2417
+ return { key, route: routes.get(key) };
2418
+ }
2419
+ return null;
2420
+ };
2421
+ const fetchImpl = async (input, init) => {
2422
+ const method = (init?.method ?? "GET").toUpperCase();
2423
+ const url = new URL(input);
2424
+ requests.push(`${method} ${url.pathname}${url.search}`);
2425
+ const found = resolve(method, url);
2426
+ if (!found) {
2427
+ missing.push(`${method} ${url.pathname}${url.search}`);
2428
+ return new Response(JSON.stringify({ message: "Not Found (fixture)" }), {
2429
+ status: 404,
2430
+ headers: { "content-type": "application/json" }
2431
+ });
2432
+ }
2433
+ let entry;
2434
+ if (Array.isArray(found.route)) {
2435
+ const index = cursors.get(found.key) ?? 0;
2436
+ entry = found.route[Math.min(index, found.route.length - 1)];
2437
+ cursors.set(found.key, index + 1);
2438
+ } else {
2439
+ entry = found.route;
2440
+ }
2441
+ const status = entry.status ?? 200;
2442
+ const headers = new Headers({ "content-type": "application/json", ...entry.headers ?? {} });
2443
+ if (entry.etag)
2444
+ headers.set("etag", entry.etag);
2445
+ if (entry.link)
2446
+ headers.set("link", entry.link);
2447
+ const requestHeaders = new Headers(init?.headers ?? {});
2448
+ const ifNoneMatch = requestHeaders.get("if-none-match");
2449
+ if (status === 200 && entry.etag && ifNoneMatch === entry.etag) {
2450
+ return new Response(null, { status: 304, headers: entry.etag ? { etag: entry.etag } : {} });
2451
+ }
2452
+ if (status === 204 || entry.body === undefined) {
2453
+ return new Response(null, { status, headers });
2454
+ }
2455
+ return new Response(JSON.stringify(entry.body), { status, headers });
2456
+ };
2457
+ return { fetch: fetchImpl, requests, missing };
2458
+ }
2459
+ // src/site-module.ts
2460
+ var CURATED_FIELDS = [
2461
+ "tagline",
2462
+ "category",
2463
+ "maturity",
2464
+ "flagship",
2465
+ "morphology",
2466
+ "narrative",
2467
+ "capabilities",
2468
+ "benchmarks",
2469
+ "links"
2470
+ ];
2471
+ function sorted(value) {
2472
+ if (Array.isArray(value))
2473
+ return value.map(sorted);
2474
+ if (value !== null && typeof value === "object") {
2475
+ const out = {};
2476
+ for (const key of Object.keys(value).sort(byCodeUnit)) {
2477
+ out[key] = sorted(value[key]);
2478
+ }
2479
+ return out;
2480
+ }
2481
+ return value;
2482
+ }
2483
+ function pretty(value) {
2484
+ return JSON.stringify(sorted(value), null, 2);
2485
+ }
2486
+ function projectUnion(projects) {
2487
+ if (projects.length === 0)
2488
+ return "never";
2489
+ return projects.map((project) => JSON.stringify(project.id)).join(" | ");
2490
+ }
2491
+ function selfContainedTypes() {
2492
+ return [
2493
+ "export type SiteRelease = {",
2494
+ " tag: string;",
2495
+ " name: string | null;",
2496
+ " publishedAt: string | null;",
2497
+ " prerelease: boolean;",
2498
+ " url: string | null;",
2499
+ "};",
2500
+ "",
2501
+ "export type SiteHead = {",
2502
+ " sha: string;",
2503
+ " shortSha: string;",
2504
+ " message: string;",
2505
+ " author: string | null;",
2506
+ " committedAt: string | null;",
2507
+ " url: string;",
2508
+ "};",
2509
+ "",
2510
+ "export type SiteReadme = {",
2511
+ " path: string;",
2512
+ " sha: string;",
2513
+ " size: number;",
2514
+ " htmlUrl: string | null;",
2515
+ " downloadUrl: string | null;",
2516
+ " excerpt: string | null;",
2517
+ "};",
2518
+ "",
2519
+ "export type SiteBranch = {",
2520
+ " name: string;",
2521
+ " sha: string;",
2522
+ " shortSha: string;",
2523
+ " protected: boolean;",
2524
+ " default: boolean;",
2525
+ "};",
2526
+ "",
2527
+ "export type SiteComment = {",
2528
+ " id: number | string;",
2529
+ " body: string;",
2530
+ " author: string | null;",
2531
+ " createdAt: string | null;",
2532
+ " url: string | null;",
2533
+ "};",
2534
+ "",
2535
+ "export type SiteWorkflow = {",
2536
+ " id: number | string;",
2537
+ " name: string;",
2538
+ " path: string;",
2539
+ " state: string;",
2540
+ "};",
2541
+ "",
2542
+ "export type SiteCi = {",
2543
+ " workflow: string | null;",
2544
+ " runId: number | string;",
2545
+ " status: string | null;",
2546
+ " conclusion: string | null;",
2547
+ " branch: string | null;",
2548
+ " sha: string | null;",
2549
+ " shortSha: string | null;",
2550
+ " url: string | null;",
2551
+ " updatedAt: string | null;",
2552
+ "};",
2553
+ "",
2554
+ "export type SiteProject = {",
2555
+ " id: string;",
2556
+ " slug: string;",
2557
+ " owner: string;",
2558
+ " name: string;",
2559
+ " fullName: string;",
2560
+ " description: string | null;",
2561
+ " homepage: string | null;",
2562
+ " topics: string[];",
2563
+ " language: string | null;",
2564
+ " languages: { name: string; bytes: number }[];",
2565
+ " license: string | null;",
2566
+ " stars: number;",
2567
+ " forks: number;",
2568
+ " watchers: number;",
2569
+ " openIssues: number;",
2570
+ " archived: boolean;",
2571
+ " fork: boolean;",
2572
+ " defaultBranch: string;",
2573
+ " htmlUrl: string;",
2574
+ " createdAt: string | null;",
2575
+ " updatedAt: string | null;",
2576
+ " pushedAt: string | null;",
2577
+ " release: SiteRelease | null;",
2578
+ " releases: SiteRelease[];",
2579
+ " head: SiteHead | null;",
2580
+ " readme?: SiteReadme | null;",
2581
+ " branches?: SiteBranch[];",
2582
+ " commitComments?: SiteComment[];",
2583
+ " issueComments?: SiteComment[];",
2584
+ " workflows?: SiteWorkflow[];",
2585
+ " ci?: SiteCi | null;",
2586
+ "};",
2587
+ "",
2588
+ "export type SiteRecord = {",
2589
+ ' schema: "loom/site@1";',
2590
+ " snapshot: string;",
2591
+ " complete: boolean;",
2592
+ " projects: SiteProject[];",
2593
+ " aliases: { from: string; to: string }[];",
2594
+ " ownerAliases: { from: string; to: string }[];",
2595
+ " errors: { repo: string; code: string; message: string; retained?: true }[];",
2596
+ "};"
2597
+ ];
2598
+ }
2599
+ function renderSiteModule(record, options = {}) {
2600
+ const requested = options.packageName;
2601
+ const selfContained = requested === null || requested === "" || requested === "none" || requested === "self-contained";
2602
+ const packageName = selfContained ? null : requested ?? "@sifr-dev/loom";
2603
+ const curated = options.curated ?? {};
2604
+ const normalizedCurated = {};
2605
+ for (const [id, entry] of Object.entries(curated))
2606
+ normalizedCurated[id.toLowerCase()] = entry;
2607
+ const curatedIds = Object.keys(normalizedCurated).sort(byCodeUnit);
2608
+ const curatedBlock = curatedIds.length === 0 ? "{}" : pretty(normalizedCurated);
2609
+ const union = projectUnion(record.projects);
2610
+ const lines = [];
2611
+ lines.push("/**");
2612
+ lines.push(" * AUTO-GENERATED by Loom - do not edit by hand.");
2613
+ lines.push(` * Source snapshot: ${record.schema} ${record.snapshot}`);
2614
+ lines.push(selfContained ? " * Regenerate: loom export --format ts --package none --out <this file>" : " * Regenerate: loom export --format ts --out <this file>");
2615
+ lines.push(` * Generated by: ${options.generatedBy ?? "loom export"}`);
2616
+ lines.push(" */");
2617
+ if (packageName !== null) {
2618
+ lines.push(`import type { SiteProject } from ${JSON.stringify(packageName)};`);
2619
+ } else {
2620
+ lines.push(...selfContainedTypes());
2621
+ }
2622
+ lines.push("");
2623
+ lines.push(`export const SNAPSHOT = ${JSON.stringify(record.snapshot)};`);
2624
+ lines.push(`export const COMPLETE = ${record.complete ? "true" : "false"};`);
2625
+ lines.push("");
2626
+ lines.push("export type ProjectId = " + union + ";");
2627
+ lines.push("");
2628
+ lines.push("/** Curated fields a site may overlay; every one is optional. */");
2629
+ lines.push("export type CuratedProject = {");
2630
+ for (const field of CURATED_FIELDS) {
2631
+ const type = field === "flagship" ? "boolean" : field === "capabilities" || field === "benchmarks" || field === "links" ? "string[]" : "string";
2632
+ lines.push(` ${field}?: ${type};`);
2633
+ }
2634
+ lines.push(" [key: string]: unknown;");
2635
+ lines.push("};");
2636
+ lines.push("");
2637
+ lines.push("/** Generic discovered records, sorted by stable project id. */");
2638
+ lines.push(`export const PROJECTS: readonly SiteProject[] = ${pretty(record.projects)};`);
2639
+ lines.push("");
2640
+ lines.push("/** Optional enrichment owned by the site, keyed by project id. */");
2641
+ lines.push(`export const CURATED: Partial<Record<ProjectId, CuratedProject>> = ${curatedBlock};`);
2642
+ lines.push("");
2643
+ lines.push("export type EnrichedProject = SiteProject & { curated?: CuratedProject };");
2644
+ lines.push("");
2645
+ lines.push("export function enrich(curated: Partial<Record<ProjectId, CuratedProject>> = CURATED): EnrichedProject[] {");
2646
+ lines.push(" return PROJECTS.map((project) => {");
2647
+ lines.push(" const extra = curated[project.id as ProjectId];");
2648
+ lines.push(" return extra ? { ...project, curated: extra } : { ...project };");
2649
+ lines.push(" });");
2650
+ lines.push("}");
2651
+ lines.push("");
2652
+ lines.push("export const ALIASES = " + pretty(record.aliases) + ";");
2653
+ lines.push("export const OWNER_ALIASES = " + pretty(record.ownerAliases) + ";");
2654
+ lines.push("export const ERRORS = " + pretty(record.errors) + ";");
2655
+ lines.push("");
2656
+ lines.push("export default PROJECTS;");
2657
+ lines.push("");
2658
+ return lines.join(`
2659
+ `);
2660
+ }
2661
+ function siteModuleDigest(record, options = {}) {
2662
+ return canonicalize(renderSiteModule(record, options));
2663
+ }
2664
+
2665
+ // src/browser.ts
2666
+ async function collectSite(config, options = {}) {
2667
+ const resolved = parseConfig(config);
2668
+ const computed = await computeSnapshot({ ...options, config: resolved });
2669
+ return buildSiteRecord(computed.snapshot, {
2670
+ aliases: resolved.aliases,
2671
+ ownerAliases: { ...resolved.ownerAliases, ...ownerAliasesOf(computed.snapshot) }
2672
+ });
2673
+ }
2674
+ export {
2675
+ CONFIG_SCHEMA,
2676
+ DEFAULT_CONFIG,
2677
+ DIGEST_PREFIX,
2678
+ EXIT,
2679
+ GitHubClient,
2680
+ LoomError,
2681
+ MemoryCache,
2682
+ SITE_SCHEMA,
2683
+ SNAPSHOT_SCHEMA,
2684
+ VERSION,
2685
+ buildSiteRecord,
2686
+ buildSnapshot,
2687
+ canonicalBytes,
2688
+ canonicalize,
2689
+ collectSite,
2690
+ computeSnapshot,
2691
+ createFixtureTransport,
2692
+ decodeBase64,
2693
+ describeEvent,
2694
+ diffSnapshots,
2695
+ digestHex,
2696
+ digestOf,
2697
+ discoverRepositories,
2698
+ isDigest,
2699
+ isRepoGlob,
2700
+ isRepoName,
2701
+ nextLink,
2702
+ normalizeSnapshot,
2703
+ ownerAliasesOf,
2704
+ parseConfig,
2705
+ parseRateLimit,
2706
+ renderSiteModule,
2707
+ repoGlobMatches,
2708
+ repoKey,
2709
+ resolveRepoAlias,
2710
+ sha256Hex,
2711
+ shortDigest,
2712
+ siteDigest,
2713
+ siteModuleDigest,
2714
+ siteProject,
2715
+ snapshotStats,
2716
+ sortKeysDeep
2717
+ };