@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,316 @@
1
+ # Deployment
2
+
3
+ **English** | [العربية](ar/DEPLOYMENT.md)
4
+
5
+ This page covers running Loom as the data producer for a site: the artifacts it
6
+ publishes, the CI job that produces them, the webhook service, and the recovery
7
+ steps for a failed deploy. The wire format itself is in
8
+ [SITE_CONTRACT.md](SITE_CONTRACT.md).
9
+
10
+ ## Artifacts
11
+
12
+ A deployment needs two deterministic files, both derived from the committed
13
+ snapshot:
14
+
15
+ | Artifact | Command | Content |
16
+ | --- | --- | --- |
17
+ | `site.json` | `loom export --out site.json` | canonical JSON, `loom/site@1` |
18
+ | `projects.ts` | `loom export --format ts --package none --out projects.ts` | self-contained TypeScript module |
19
+
20
+ Both files contain no timestamp, run id, or random value. The same snapshot
21
+ always produces the same bytes. A build can publish them to a static host, a
22
+ release asset, a CDN, or a data branch. The consumer only needs a stable URL.
23
+
24
+ `loom export --check` exits `7` when the file on disk is stale. A CI job can use
25
+ that to refuse a redeploy without diffing the JSON itself.
26
+
27
+ The store is the only state that must survive between runs. It holds the
28
+ manifest, content-addressed objects, the ETag cache, the webhook log, and the
29
+ outbox:
30
+
31
+ ```
32
+ .loom/
33
+ manifest.json # schema, snapshot id, createdAt, stats, source
34
+ objects/ab/cdef....json # canonical JSON named by sha256 of those bytes
35
+ cache/http.json # ETag to body, so 304s replay without a payload
36
+ webhook-state.json # processed delivery ids and signed payload hashes
37
+ outbox.json # pending diff whose triggers have not all acknowledged
38
+ loom.lock # single-writer lock
39
+ ```
40
+
41
+ Cache the whole directory in CI, keyed by branch and restored with a prefix
42
+ match. Without the cache a run still works, but every request is cold.
43
+
44
+ ## Build and package
45
+
46
+ ```bash
47
+ bun install --frozen-lockfile
48
+ bun run verify
49
+ bun pm pack
50
+ ```
51
+
52
+ `bun run verify` runs the type check, the full test suite, the build, a fixture
53
+ sync, and the determinism proof. The packed tarball carries `dist`, `schema`,
54
+ the five consumer documents, the licence, and the changelog. It contains no
55
+ source, tests, fixtures, or examples.
56
+
57
+ To install the packed artifact into a clean project:
58
+
59
+ ```bash
60
+ bun add ./sifr-dev-loom-1.0.0.tgz
61
+ ```
62
+
63
+ The registry package name is `@sifr-dev/loom`. The release workflow in
64
+ `.github/workflows/release.yml` runs on a `v*` tag, checks that the tag matches
65
+ `package.json`, runs `bun run verify`, packs, installs the tarball in a clean
66
+ directory, attests the build, publishes with provenance, and attaches the
67
+ tarball and `SHA256SUMS` to the GitHub release. A tag push without `NPM_TOKEN`
68
+ fails instead of pretending a version was published.
69
+
70
+ ## CI that publishes a site
71
+
72
+ A producer job has five steps:
73
+
74
+ 1. restore the `.loom` cache;
75
+ 2. run `loom sync --json` and stop on any non-zero exit;
76
+ 3. export `site.json` and `projects.ts`;
77
+ 4. publish the two files only when their bytes changed;
78
+ 5. dispatch the site once when `status == "created"`.
79
+
80
+ A complete job inside a checkout of Loom, using a data branch as the publish
81
+ target:
82
+
83
+ ```yaml
84
+ name: Site sync
85
+ on:
86
+ schedule:
87
+ - cron: "17,47 * * * *"
88
+ workflow_dispatch:
89
+
90
+ permissions:
91
+ contents: write
92
+
93
+ jobs:
94
+ sync:
95
+ runs-on: ubuntu-latest
96
+ steps:
97
+ - uses: actions/checkout@v7
98
+ with:
99
+ fetch-depth: 0
100
+
101
+ - uses: oven-sh/setup-bun@v2
102
+ with:
103
+ bun-version: "1.4.5"
104
+
105
+ - run: bun install --frozen-lockfile
106
+
107
+ - uses: actions/cache@v6
108
+ with:
109
+ path: .loom
110
+ key: loom-store-${{ github.run_id }}
111
+ restore-keys: loom-store-
112
+
113
+ - name: Poll public state
114
+ id: sync
115
+ env:
116
+ GITHUB_TOKEN: ${{ secrets.LOOM_GITHUB_TOKEN || github.token }}
117
+ run: |
118
+ bun src/cli.ts sync --json > sync.json
119
+ cat sync.json
120
+ echo "status=$(jq -r .status sync.json)" >> "$GITHUB_OUTPUT"
121
+ echo "snapshot=$(jq -r .snapshot sync.json)" >> "$GITHUB_OUTPUT"
122
+
123
+ - name: Export
124
+ run: |
125
+ bun src/cli.ts export --out site.json
126
+ bun src/cli.ts export --format ts --package none --out projects.ts
127
+
128
+ - name: Publish the data branch
129
+ run: |
130
+ worktree="$(mktemp -d)/data"
131
+ if git ls-remote --exit-code --heads origin loom-data >/dev/null 2>&1; then
132
+ git worktree add "$worktree" loom-data
133
+ else
134
+ git worktree add --detach "$worktree"
135
+ git -C "$worktree" checkout --orphan loom-data
136
+ git -C "$worktree" rm -rf . >/dev/null 2>&1 || true
137
+ fi
138
+ cp site.json projects.ts "$worktree/"
139
+ git -C "$worktree" config user.name "Loom"
140
+ git -C "$worktree" config user.email "loom@users.noreply.github.com"
141
+ git -C "$worktree" add site.json projects.ts
142
+ if git -C "$worktree" diff --cached --quiet; then
143
+ echo "site artifacts are byte-identical"
144
+ else
145
+ git -C "$worktree" commit -m "data: site record for ${{ steps.sync.outputs.snapshot }}"
146
+ git -C "$worktree" push origin HEAD:loom-data
147
+ fi
148
+
149
+ - name: Dispatch the site
150
+ if: steps.sync.outputs.status == 'created' && vars.SITE_REPO != ''
151
+ env:
152
+ GH_TOKEN: ${{ secrets.SITE_DISPATCH_TOKEN }}
153
+ SITE_REPO: ${{ vars.SITE_REPO }}
154
+ run: |
155
+ gh api "repos/${SITE_REPO}/dispatches" \
156
+ -f event_type="loom-sync" \
157
+ -f "client_payload[snapshot]=${{ steps.sync.outputs.snapshot }}" \
158
+ -f "client_payload[site_record]=https://raw.githubusercontent.com/${GITHUB_REPOSITORY}/loom-data/site.json"
159
+ ```
160
+
161
+ A data branch is one option. A release asset, an object store, or a static host
162
+ works the same way as long as the consumer has a stable URL and validates
163
+ `complete` before deploying.
164
+
165
+ The deployment event is `repository_dispatch` with `event_type: loom-sync`:
166
+
167
+ ```json
168
+ {
169
+ "snapshot": "sha256:<64 hex>",
170
+ "site_record": "https://example.invalid/site.json",
171
+ "site_module": "https://example.invalid/projects.ts"
172
+ }
173
+ ```
174
+
175
+ A consumer must dedupe by `snapshot`. Loom guarantees at-least-once delivery
176
+ with a stable key; exactly-once requires the receiver to ignore a repeated
177
+ snapshot.
178
+
179
+ ## Webhook service
180
+
181
+ `loom serve` receives GitHub webhooks, verifies the signature, dedupes delivery
182
+ ids, and runs syncs through one bounded queue. It binds `127.0.0.1:8787` by
183
+ default.
184
+
185
+ | Route | Behaviour |
186
+ | --- | --- |
187
+ | `GET /healthz` | liveness, the current snapshot id, and queue depth |
188
+ | `GET /readyz` | `503` while draining or when the store is unreadable |
189
+ | `GET /state` | the manifest, or `null` before the first sync |
190
+ | `GET /metrics` | Prometheus counters and gauges for HTTP, sync, triggers, queue |
191
+ | `POST /webhook` | verify, dedupe, enqueue, serial sync, dispatch |
192
+
193
+ Deploy-relevant events: `push` to a watched branch or the repository's default
194
+ branch, `repository_dispatch`, `release` (`published`, `released`,
195
+ `prereleased`), and `repository` (`renamed`, `deleted`, `archived`,
196
+ `unarchived`). `ping` is acknowledged without a sync. Tag pushes, other
197
+ branches, `workflow_run`, and release edits are acknowledged and ignored.
198
+
199
+ The receiver needs a secret of at least 16 characters in the environment
200
+ variable named by `webhook.secretEnv`, default `LOOM_WEBHOOK_SECRET`. With the
201
+ recorded fixture, the service starts and reports its state:
202
+
203
+ ```console
204
+ $ LOOM_WEBHOOK_SECRET=0123456789abcdef0123456789abcdef \
205
+ bun src/cli.ts serve --config fixtures/demo.config.json \
206
+ --fixture fixtures/github --store .loom-doc --port 8791
207
+ loom serve: listening on http://127.0.0.1:8791
208
+ loom serve: webhook path /webhook, secret from LOOM_WEBHOOK_SECRET
209
+ loom serve: 2 watched repositories, 0 triggers, queue depth 32
210
+
211
+ $ curl -sS localhost:8791/healthz
212
+ {"ok":true,"service":"loom","closing":false,"snapshot":"sha256:8aa70586ead8f545f40b88c1c50edfcda4684ba37cc2080da672a1fad0fd74ad","createdAt":"2026-12-02T04:14:06.706Z","queue":{"depth":0,"active":0,"enqueued":0,"completed":0,"failed":0,"rejectedFull":0,"deduped":0,"closed":false}}
213
+ ```
214
+
215
+ Run one writer. `loom sync`, `loom watch`, and `loom serve` all write the store.
216
+ A second writer is refused with exit `8` while the lock is held; a lock older
217
+ than ten minutes is treated as stale and taken over. The lock is local to one
218
+ host, not distributed.
219
+
220
+ ## Environment
221
+
222
+ | Variable | Used by | Required |
223
+ | --- | --- | --- |
224
+ | `GITHUB_TOKEN` (or `--token-env NAME`) | `sync`, `serve`, `export --source remote` | no; anonymous is 60 requests per hour |
225
+ | `LOOM_WEBHOOK_SECRET` (or `webhook.secretEnv`) | `serve` | yes, at least 16 characters |
226
+ | `VERCEL_DEPLOY_HOOK_URL` | Vercel trigger | when configured |
227
+ | `LOOM_WEBHOOK_URL`, `LOOM_WEBHOOK_SECRET` | generic signed trigger | when configured |
228
+ | `SITE_DISPATCH_TOKEN` | site dispatch job | for automatic dispatch |
229
+ | `SITE_REPO` | site dispatch job | for automatic dispatch |
230
+
231
+ Secrets are named in config, never stored in it. Tokens and credential-shaped
232
+ text are redacted from errors, trigger plans, JSON logs, and the store.
233
+
234
+ ## Exit codes
235
+
236
+ | Code | Meaning | Action |
237
+ | --- | --- | --- |
238
+ | 0 | ok | continue |
239
+ | 1 | failure | read the message; retry only a transient failure |
240
+ | 2 | usage or config | fix the flags or `loom.config.json` |
241
+ | 3 | verification failed | do not deploy; restore or re-sync |
242
+ | 4 | non-public repository | remove it from `repos` |
243
+ | 5 | unauthorized webhook | check the secret and the raw body |
244
+ | 6 | partial snapshot | a repository has no data and no previous copy; fix access |
245
+ | 7 | unchanged | no redeploy needed |
246
+ | 8 | store busy | another writer owns the lock; retry |
247
+
248
+ ## Partial failures
249
+
250
+ - `sync` (default): any repository failure aborts before commit. Nothing is
251
+ deployed and the previous snapshot remains current.
252
+ - `sync --tolerate-errors`: a failed repository with a previous copy is
253
+ retained; `errors[].retained` is set, the diff is empty, and nothing is
254
+ committed.
255
+ - A failed repository with no previous copy fails closed: the sync does not
256
+ commit, does not dispatch, keeps the previous head, and exits `6`. A remote
257
+ export of that state has `complete: false`. Do not deploy it.
258
+
259
+ ## Recovery
260
+
261
+ | Symptom | Recovery |
262
+ | --- | --- |
263
+ | Process killed mid-write | the atomic rename leaves the old or the new file, never a mix; `loom doctor --fix` removes leftover temporary files |
264
+ | Killed after commit, before dispatch | `outbox.json` remains; the next `sync --dispatch` retries the same snapshot and clears it |
265
+ | Trigger returned 5xx | the outbox keeps `attempts` and `nextAttemptAt`; the next poll retries with capped backoff |
266
+ | `cache/http.json` unreadable | quarantined as `*.corrupt-cache-*`; the sync continues with a cold cache |
267
+ | `webhook-state.json` unreadable | quarantined as `*.corrupt-webhook-state-*`; dedupe restarts empty, so a retry may run once more, which is safe because sync is idempotent |
268
+ | `outbox.json` unreadable | quarantined as `*.corrupt-outbox-*`; inspect it, then run `loom sync --dispatch` |
269
+ | manifest points at a missing object | `loom verify` fails `snapshot-present`; restore the object from a backup or re-sync |
270
+
271
+ `loom doctor` is offline and reports config, store verification, cache, webhook
272
+ secret, token, trigger environment variables, and outbox state. `loom doctor
273
+ --fix` also quarantines a corrupt cache, webhook log, or outbox and removes
274
+ temporary debris. It never deletes a content-addressed object.
275
+
276
+ ## Observability
277
+
278
+ `GET /metrics` exposes Prometheus text:
279
+
280
+ | Metric | Meaning |
281
+ | --- | --- |
282
+ | `loom_http_requests_total{route,status}` | HTTP surface, including 401, 413, and 503 |
283
+ | `loom_webhook_total{kind,event}` | accepted, ignored, duplicate, invalid, unauthorized |
284
+ | `loom_sync_total{trigger,status,changed}` | sync outcomes by trigger and status |
285
+ | `loom_deploy_total{changed}` | deploy-relevant completions |
286
+ | `loom_queue_depth`, `loom_queue_active` | backpressure state |
287
+ | `loom_queue_rejected_total` | 503 backpressure events |
288
+ | `loom_sync_duration_milliseconds` | last sync duration |
289
+ | `loom_snapshot_repositories{snapshot}` | size of the current snapshot |
290
+
291
+ `--log-format json` writes one redacted object per line:
292
+ `{"ts","level","component","msg",...detail}`. `--log-format text` is the local
293
+ default. `--quiet` suppresses logs, not command output.
294
+
295
+ ## Backups and migration
296
+
297
+ Back up the whole store directory. `manifest.json` is the only pointer; objects
298
+ are immutable and named by their SHA-256. `loom verify` re-hashes every object,
299
+ re-canonicalises the current payload, re-checks order and stats, and scans for
300
+ credential patterns. A failed verify is a deploy blocker.
301
+
302
+ `loom migrate` upgrades `loom/manifest@0` to `@1` by reading the snapshot it
303
+ points at. Cache and webhook state are validated and rewritten or quarantined.
304
+ An unknown future schema fails with `schema_unsupported`; the tool never guesses
305
+ at a newer layout.
306
+
307
+ ## Limits
308
+
309
+ - Polling, not streaming: GitHub has no push channel for repository metadata.
310
+ - Bearer token, not a GitHub App; public reads only by design.
311
+ - One writer per store; the lock is local to one host.
312
+ - Trigger delivery is at-least-once with an idempotency key, not exactly-once
313
+ across an arbitrary network partition.
314
+ - Secret scanning is pattern-based and is a guardrail, not a proof.
315
+ - `loom export --check` compares bytes; a pretty-printed file is reported as
316
+ stale by design.
package/docs/SDK.md ADDED
@@ -0,0 +1,351 @@
1
+ # Loom SDK (`@sifr-dev/loom`)
2
+
3
+ **English** | [العربية](ar/SDK.md)
4
+
5
+ Loom is a TypeScript SDK that turns public GitHub repositories into
6
+ deterministic snapshots, precise change diffs, and typed website data. The CLI
7
+ is a thin consumer of the same SDK; an application embeds `Loom` directly.
8
+
9
+ ```
10
+ GitHub (public reads, token optional)
11
+ │ ETag / conditional requests, bounded retries
12
+ ▼
13
+ GitHubClient ──► collector ──► canonical snapshot (content addressed)
14
+ │
15
+ ┌─────────────────┼──────────────────┐
16
+ ▼ ▼ ▼
17
+ diff engine site record typed site module
18
+ (entity events) loom/site@1 PROJECTS + enrich()
19
+ │
20
+ ▼
21
+ durable outbox ──► triggers (Vercel / GitHub dispatch / webhook)
22
+ ```
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ bun add @sifr-dev/loom
28
+ # or
29
+ npm install @sifr-dev/loom
30
+ ```
31
+
32
+ | Part | Runtime |
33
+ | --- | --- |
34
+ | `@sifr-dev/loom` | Bun 1.1 or newer, Node 20 or newer |
35
+ | `@sifr-dev/loom/browser` | any runtime with `fetch`: page, worker, edge function, Bun, Node |
36
+ | `@sifr-dev/loom/schema/site@1.json` | any JSON consumer |
37
+ | `loom` command | Bun 1.1 or newer |
38
+
39
+ The package ships `dist/index.js` (ESM), `dist/browser.js`, `dist/cli.js`, and
40
+ declarations in `dist/types`. Reading a config file with
41
+ `Loom.open("loom.config.json")` uses the Bun file API, and `loom serve` uses Bun
42
+ HTTP. In Node, pass a config object to `Loom.open` and run the webhook receiver
43
+ on Bun.
44
+
45
+ ## Entry points
46
+
47
+ | Specifier | Contents |
48
+ | --- | --- |
49
+ | `@sifr-dev/loom` | `Loom`, `runSync`, `SnapshotStore`, config, webhooks, triggers, metrics |
50
+ | `@sifr-dev/loom/browser` | config parsing, `GitHubClient`, caches, collection, diff, site record, module renderer |
51
+ | `@sifr-dev/loom/schema/site@1.json` | the JSON Schema for `loom/site@1` |
52
+
53
+ `@sifr-dev/loom/browser` is safe to import in a page, a worker, or an edge
54
+ function: its module graph contains no `node:` builtin, no Bun global, and no
55
+ `Buffer` or `process` access. It reads with `fetch` and derives the record in
56
+ memory. Persistence, signed webhooks, and deploy triggers stay in the root entry
57
+ because they need a filesystem and an HMAC implementation.
58
+
59
+ ## Quick start
60
+
61
+ ```ts
62
+ import { Loom } from "@sifr-dev/loom";
63
+
64
+ const loom = await Loom.open({ repos: ["Sifr-Dev/Loom"], store: ".loom" });
65
+ const outcome = await loom.sync();
66
+ console.log(outcome.status, outcome.snapshot.id);
67
+ await loom.close();
68
+ ```
69
+
70
+ `Loom.open` accepts a config path, a parsed `LoomConfig`, or a raw config
71
+ object. A raw object is validated with the same schema and defaults as
72
+ `loom.config.json`. Use `Loom.attach(config, store)` to reuse an already-open
73
+ store.
74
+
75
+ The instance reads public state, compares it with the committed snapshot, and
76
+ commits only when the entity diff is not empty. A second run over unchanged
77
+ state prints `unchanged` and writes nothing.
78
+
79
+ ```ts
80
+ const loom = await Loom.open("loom.config.json", {
81
+ token: process.env.GITHUB_TOKEN, // read by name, never stored or logged
82
+ });
83
+
84
+ loom.subscribe((event) => {
85
+ if (event.type === "sync" && event.outcome.diff.changed) {
86
+ console.log("committed", event.outcome.snapshot.id);
87
+ }
88
+ });
89
+
90
+ const outcome = await loom.sync({ dispatch: true });
91
+ console.log(outcome.status, outcome.diff.summary);
92
+
93
+ const record = await loom.siteRecord(); // loom/site@1
94
+ await loom.close(); // abort in-flight work, release the lock
95
+ ```
96
+
97
+ ## In a website
98
+
99
+ ```ts
100
+ import { collectSite, renderSiteModule } from "@sifr-dev/loom/browser";
101
+
102
+ const record = await collectSite({
103
+ repos: ["Ada/portfolio", "Ada/notes"],
104
+ releases: 3,
105
+ collect: { readme: true },
106
+ });
107
+
108
+ for (const project of record.projects) {
109
+ console.log(project.fullName, project.stars, project.release?.tag, project.head?.message);
110
+ }
111
+
112
+ const module = renderSiteModule(record, { packageName: "none" });
113
+ ```
114
+
115
+ `collectSite` validates the config with the CLI rules, reads public GitHub
116
+ state, and returns the `loom/site@1` record. It accepts every `SourceOptions`
117
+ field except `config`: `token`, `fetch`, `cache` (`MemoryCache` by default),
118
+ `now`, `logger`, `tolerateErrors`, `previous`, `concurrency`, and `signal`. Pass
119
+ `fixture: { transport, baseUrl }` from `createFixtureTransport` to run against
120
+ recorded responses with no network.
121
+
122
+ The same entry exports the layers: `GitHubClient`, `computeSnapshot`,
123
+ `buildSiteRecord`, `diffSnapshots`, `renderSiteModule`, `siteDigest`,
124
+ `MemoryCache`, `parseConfig`, `sha256Hex`, and the snapshot types.
125
+
126
+ ## API
127
+
128
+ | Member | Purpose |
129
+ | --- | --- |
130
+ | `Loom.open(input, options)` / `createLoom(...)` | Resolve config and open the store. |
131
+ | `loom.sync(options)` | Read, diff, commit on change, dispatch the outbox. |
132
+ | `loom.snapshot()` | Compute the current snapshot without committing. |
133
+ | `loom.diff({ from, to })` | Entity diff between two snapshots. |
134
+ | `loom.siteRecord(snapshot?)` | Build the `loom/site@1` record. |
135
+ | `loom.siteModule(options?)` | Render the typed TypeScript module. |
136
+ | `loom.siteDigest()` | Content address of the site record. |
137
+ | `loom.discover()` | Public-owner discovery without committing. |
138
+ | `loom.subscribe(listener)` | Sync lifecycle events; returns an unsubscribe function. |
139
+ | `loom.use(plugin)` | Add a plugin after construction. |
140
+ | `loom.verifyWebhook(input, { secret })` | Verify a raw webhook (HMAC). |
141
+ | `loom.receiver()` | Reusable signed-webhook receiver. |
142
+ | `loom.close()` / `loom.drain()` | Abort in-flight work and release the lock. |
143
+
144
+ The root entry also exports the layers below the class: `GitHubClient`,
145
+ `discoverRepositories`, `diffSnapshots`, `buildSiteRecord`, `renderSiteModule`,
146
+ `SnapshotStore`, `WebhookReceiver`, and `runSync`. The environment-free subset
147
+ is available from `@sifr-dev/loom/browser`.
148
+
149
+ ### Website module modes
150
+
151
+ ```ts
152
+ await loom.siteModule(); // imports SiteProject from the SDK
153
+ await loom.siteModule({ packageName: "none" }); // self-contained types
154
+ ```
155
+
156
+ The CLI equivalent is `loom export --format ts --package none`. Self-contained
157
+ mode embeds `SiteProject` and `SiteRecord` in the generated file, so a deployed
158
+ site needs no `@sifr-dev/loom` install. The default package-import mode remains
159
+ for SDK consumers. Both modes are deterministic and work with `--check`.
160
+
161
+ ### Plugins
162
+
163
+ ```ts
164
+ const loom = await Loom.open("loom.config.json", {
165
+ plugins: [
166
+ {
167
+ name: "analytics",
168
+ async onDiff(diff) {
169
+ if (diff.changed) await report(diff.summary);
170
+ },
171
+ onDeploy(results) {
172
+ for (const result of results) if (!result.ok) alert(result.target);
173
+ },
174
+ },
175
+ ],
176
+ });
177
+ ```
178
+
179
+ Hooks run in order and are awaited before `sync()` resolves. A throwing
180
+ `onSnapshot`, `onDiff`, or `onDeploy` aborts the sync; `onError` never throws.
181
+
182
+ ### Lifecycle and shutdown
183
+
184
+ `close()` aborts the instance's `AbortSignal`, waits for in-flight syncs to
185
+ settle, clears subscribers, and is idempotent. In a server:
186
+
187
+ ```ts
188
+ process.on("SIGTERM", () => void loom.close());
189
+ ```
190
+
191
+ The CLI uses the same class: `commands/sync.ts` calls `Loom.attach(...).sync()`
192
+ and closes in a `finally`.
193
+
194
+ ## Configuration
195
+
196
+ `loom.config.json` (schema `loom/config@1`):
197
+
198
+ ```json
199
+ {
200
+ "schema": "loom/config@1",
201
+ "repos": [],
202
+ "discovery": {
203
+ "owners": ["Sifr-Dev"],
204
+ "include": [],
205
+ "exclude": ["acme/legacy-site"],
206
+ "includeArchived": false,
207
+ "includeForks": false
208
+ },
209
+ "branches": ["main"],
210
+ "releases": 5,
211
+ "includeLatestCommit": true,
212
+ "aliases": {},
213
+ "ownerAliases": {},
214
+ "collect": {
215
+ "readme": true,
216
+ "readmeExcerptChars": 600,
217
+ "branches": true,
218
+ "branchLimit": 10,
219
+ "extraBranches": [],
220
+ "commitComments": true,
221
+ "commitCommentLimit": 20,
222
+ "issueComments": true,
223
+ "issueCommentLimit": 20,
224
+ "workflows": true,
225
+ "workflowLimit": 10,
226
+ "ciRuns": 5
227
+ },
228
+ "store": ".loom",
229
+ "triggers": [
230
+ { "kind": "webhook", "urlEnv": "DEPLOY_URL", "secretEnv": "DEPLOY_SECRET" }
231
+ ],
232
+ "webhook": {
233
+ "path": "/webhook",
234
+ "secretEnv": "LOOM_WEBHOOK_SECRET",
235
+ "toleranceSeconds": 300,
236
+ "maxBodyBytes": 1048576
237
+ },
238
+ "serve": {
239
+ "pollIntervalSeconds": 300,
240
+ "queueDepth": 32,
241
+ "shutdownTimeoutSeconds": 30,
242
+ "syncTimeoutSeconds": 120
243
+ }
244
+ }
245
+ ```
246
+
247
+ `collect` is opt-in and every list is bounded, so a busy repository cannot grow
248
+ the snapshot without limit. With every flag false, the snapshot keeps metadata,
249
+ languages, releases, and the latest commit only.
250
+
251
+ `ownerAliases` handles a GitHub account rename: it is applied to every explicit
252
+ repo and discovery owner before any request, so ids, diffs, and the site record
253
+ are canonical and an old owner does not leak into project data. A redirect from
254
+ the old login is recorded automatically; a hard `404` requires an explicit
255
+ alias. `discovery.owners: ["me"]` resolves the authenticated login through
256
+ `GET /user` (PAT required). `loom doctor` fails on alias cycles.
257
+
258
+ Every key and its validation rule is documented in
259
+ [CONFIGURATION.md](CONFIGURATION.md).
260
+
261
+ ## Authentication and PAT scopes
262
+
263
+ Public reads work anonymously at 60 requests per hour. Live sync should use a
264
+ personal access token or a GitHub App installation token in an environment
265
+ variable or CI secret. Loom reads the token by name (`tokenEnv`, default
266
+ `GITHUB_TOKEN`); it never writes it to the config, snapshot, store, or logs, and
267
+ error messages are redacted.
268
+
269
+ | Data | Endpoint | Token scope for public data |
270
+ | --- | --- | --- |
271
+ | repository metadata, languages | `/repos/{o}/{r}` | none (rate limit only) |
272
+ | latest commit, branches | `/commits`, `/branches` | none |
273
+ | releases | `/releases` | none |
274
+ | README, commit and issue comments | `/readme`, `/comments`, `/issues/comments` | none |
275
+ | workflows, CI runs | `/actions/workflows`, `/actions/runs` | none for public Actions |
276
+ | authenticated identity (`owners: ["me"]`) | `/user` | any valid token |
277
+
278
+ A fine-grained PAT with public repository read is enough. Loom accepts only
279
+ repositories whose visibility is `public`; a private or internal response is a
280
+ guard violation. Loom waits for the advertised rate-limit reset when it fits
281
+ inside `maxRateLimitWaitMs`, and reports `rate_limit_exhausted` instead of
282
+ sleeping for an hour.
283
+
284
+ ## Polling and webhooks
285
+
286
+ | Trigger | Path | Notes |
287
+ | --- | --- | --- |
288
+ | `loom sync` / `loom watch` | polling with ETags | unchanged polls are cheap `304`s |
289
+ | `loom serve` reconciliation | `serve.pollIntervalSeconds` | covers missed webhooks |
290
+ | GitHub webhook | `POST /webhook` | signed HMAC, deduped by delivery id |
291
+ | release, push, repository_dispatch | webhook receiver | `release.published`, watched branch push, `repository_dispatch` |
292
+
293
+ The webhook is an accelerator, not a requirement: a missed delivery is repaired
294
+ by the next poll. A deploy happens once per committed snapshot because the
295
+ outbox is keyed by the snapshot id.
296
+
297
+ ## Security and redaction
298
+
299
+ - Secrets are read from the environment by name; plans expose redacted URLs.
300
+ - Snapshot payloads are scanned for credential-shaped values at pack and verify
301
+ time.
302
+ - JSON logs redact `token`, `authorization`, `secret`, and URL userinfo.
303
+ - `loom doctor` reports whether each required environment variable is set, never
304
+ its value.
305
+ - The store is content-addressed; `loom verify` re-hashes every blob.
306
+
307
+ ## Limits
308
+
309
+ - Public repositories only, by design.
310
+ - Comment, branch, and workflow history is bounded by `collect.*Limit`.
311
+ - Trigger delivery is at-least-once with an idempotency key, not exactly-once
312
+ across an arbitrary network partition.
313
+ - The store lock is single-host; there is no distributed lock.
314
+ - The browser entry does not persist. It reads and derives in memory.
315
+
316
+ ## Example: a separate developer repository
317
+
318
+ ```ts
319
+ // app/sync.ts: any Bun service
320
+ import { Loom } from "@sifr-dev/loom";
321
+
322
+ const loom = await Loom.open(
323
+ {
324
+ schema: "loom/config@1",
325
+ repos: [],
326
+ discovery: {
327
+ owners: ["octocat"],
328
+ include: [],
329
+ exclude: [],
330
+ includeArchived: false,
331
+ includeForks: false,
332
+ },
333
+ store: ".loom",
334
+ triggers: [
335
+ {
336
+ kind: "github-dispatch",
337
+ repo: "octocat/site",
338
+ eventType: "loom-sync",
339
+ tokenEnv: "DISPATCH_TOKEN",
340
+ },
341
+ ],
342
+ },
343
+ { token: process.env.GITHUB_TOKEN },
344
+ );
345
+
346
+ const outcome = await loom.sync({ dispatch: true });
347
+ console.log(outcome.status, outcome.diff.summary);
348
+ await loom.close();
349
+ ```
350
+
351
+ See `examples/consumer.ts` for a runnable minimal consumer.