@xynolog/core 0.8.1 → 0.8.2

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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/job-filter.ts","../src/job-storage.ts","../src/job-subject.ts","../src/persisted-events.ts","../src/event-utils.ts","../src/retry-rules.ts","../src/base64url.ts","../src/sha256.ts","../src/annotation-id.ts","../src/text-offsets.ts","../src/fuzzy-anchor.ts","../src/pdf-anchoring.ts","../src/pdf-coordinates.ts","../src/text-context.ts","../src/annotation-builders.ts","../src/web-annotation-utils.ts","../src/media-type-registry.ts","../src/media-types.ts","../src/refused-encodings.ts","../src/text-encoding.ts","../src/resource-utils.ts","../src/cache-refresh.ts","../src/oauth-clients.ts","../src/gateway-http.ts","../src/sign-in.ts","../src/limits-operations.ts","../src/bus-classification.ts","../src/channel-attrs.ts","../src/anchor-annotation.ts","../src/locale-registry.ts","../src/locales.ts","../src/svg-utils.ts","../src/validation.ts","../src/watched.ts","../src/storage-uri.ts","../src/did-utils.ts","../src/client-assertion.ts","../src/deadline.ts","../src/sign-in-error.ts","../src/unanswered.ts","../src/service-account.ts","../src/knowledge-graph-views.ts","../src/retry.ts","../src/discovery.ts"],"names":["job","right","between","resourceId"],"mappings":";;;;AA0BA,SAAS,MAAA,CAAO,QAAiB,MAAA,EAA0B;AACzD,EAAA,IAAI,CAAC,QAAA,CAAS,MAAM,CAAA,SAAU,MAAA,KAAW,MAAA;AACzC,EAAA,OACE,SAAS,MAAM,CAAA,IACf,OAAO,OAAA,CAAQ,MAAM,EAAE,KAAA,CAAM,CAAC,CAAC,IAAA,EAAM,KAAK,CAAA,KAAM,MAAA,CAAO,OAAO,MAAA,CAAO,IAAI,CAAC,CAAC,CAAA;AAE/E;AAEO,SAAS,gBAAA,CACd,QACAA,IAAAA,EACS;AACT,EAAA,OAAO,MAAA,CAAO,QAAQA,IAAG,CAAA;AAC3B;;;AChCO,IAA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A,IAAS,OAAA,GAAU,KAAK,OAAA,EAAA,EAAW;AACjC,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,EAAA,EAAG;AAAA,IAClB,SAAS,KAAA,EAAO;AAKd,MAAA,IAAI,MAAA,EAAQ,SAAS,MAAM,KAAA;AAC3B,MAAA,IAAI,WAAW,MAAA,CAAO,QAAA,IAAY,CAAC,WAAA,CAAY,KAAK,GAAG,MAAM,KAAA;AAK7D,MAAA,MAAM,SAAU,KAAA,CAAqC,YAAA;AACrD,MAAA,MAAM,UAAU,IAAA,CAAK,GAAA;AAAA,QACnB,YAAY,GAAG,CAAA;AAAA,QACf,OAAO,MAAA,KAAW,QAAA,GAAW,MAAA,GAAS;AAAA,OACxC;AACA,MAAA,OAAA,GAAU,EAAE,OAAA,EAAS,QAAA,EAAU,OAAO,QAAA,EAAU,OAAA,EAAS,OAAO,CAAA;AAChE,MAAA,IAAI,CAAE,MAAM,MAAA,CAAO,OAAA,EAAS,MAAM,GAAI,MAAM,KAAA;AAC5C,MAAA,GAAA,GAAM,IAAA,CAAK,GAAA,CAAI,GAAA,GAAM,CAAA,EAAG,OAAO,UAAU,CAAA;AAAA,IAC3C;AAAA,EACF;AACF;;;AChOO,IAAM,kBAAA,GAAqB","file":"index.js","sourcesContent":["/**\n * Whether a job matches a filter.\n *\n * A filter (`JobFilter`) is a partial job description: it names fields of the\n * description at the description's own paths. A job matches when every field\n * the filter states equals the job's; what the filter leaves out is not\n * compared. So the comparison knows no field by name, and does not change when\n * a filter may state another.\n *\n * It is asked in two places: by the Dispatcher, choosing the next job a claim\n * takes, and by a party checking an announcement against its own claim before\n * it asks. `protocol/specs/src/jobs/filter-cases.json` holds every implementation to\n * one answer.\n */\n\nimport type { components } from './types';\nimport { isObject } from './type-guards';\n\ntype JobFilter = components['schemas']['JobFilter'];\n\n/** A job as a filter is compared with it: announced, or held. */\nexport interface FilterableJob {\n jobType: components['schemas']['JobType'];\n params: object;\n}\n\nfunction states(stated: unknown, actual: unknown): boolean {\n if (!isObject(stated)) return stated === actual;\n return (\n isObject(actual) &&\n Object.entries(stated).every(([name, value]) => states(value, actual[name]))\n );\n}\n\nexport function jobMatchesFilter(\n filter: JobFilter,\n job: FilterableJob,\n): boolean {\n return states(filter, job);\n}\n","// ⚠ GENERATED FILE — do not edit.\n//\n// Authority: protocol/specs/src/jobs/storage.json, protocol/specs/src/components/schemas/JobType.json,\n// protocol/specs/src/components/schemas/MarkJobParams.json\n// Regenerate: make generate (codegen/lib/job_storage/job_storage.ml)\n\n/** The work-queue stream every job is published into. */\nexport const JOBS_STREAM = 'JOBS';\n\n/** The root of every job subject: a job is published on `<root>.<jobType>`. */\nexport const JOBS_SUBJECT_ROOT = 'jobs';\n\n/** The stream's capture filter: every subject under the root. */\nexport const JOBS_STREAM_SUBJECTS = ['jobs.>'] as const;\n\n/** The durable consumer that holds each job's message as its lease. */\nexport const JOBS_CONSUMER = 'dispatcher-leases';\n\n/** The KV bucket holding one JobRecord per job, keyed by the job's id. */\nexport const JOBS_BUCKET = 'jobs';\n\n/** Every job type. */\nexport const JOB_TYPES = ['mark', 'yield'] as const;\n\n/** Every motivation a `mark` job has: the ones MarkJobParams is told apart by. */\nexport const MARK_MOTIVATIONS = [\n 'highlighting',\n 'commenting',\n 'assessing',\n 'linking',\n 'tagging',\n] as const;\n","/** The subject a job is published on, under job-storage.ts's root. */\n\nimport { JOBS_SUBJECT_ROOT } from './job-storage';\n\n/** The subject a job of this type is published on. */\nexport function jobSubject(type: string): string {\n return `${JOBS_SUBJECT_ROOT}.${type}`;\n}\n","// ⚠ GENERATED FILE — do not edit.\n//\n// Authority: protocol/specs/src/bus/registry.json (channels, payloads, operations)\n// Regenerate: make generate (codegen/lib/bus/typescript.ml)\n// Go counterpart: codegen/lib/bus/go.ml → go/bus\n//\n// Payload schemas themselves live in the OpenAPI components; the registry\n// names which one each channel carries, and every payload type here is\n// derived from that. Add or change a channel THERE.\n\n/**\n * Persisted Events\n *\n * The event types that get appended to the JSONL event log, each with the\n * component schema of its payload. The PersistedEvent union derives from this\n * catalog.\n */\n\nimport type { components } from './types';\nimport type { ResourceId } from './identifiers';\nimport type { EventBase } from './event-base';\nimport type { EventPayloadRefinements } from './bus-refinements';\n\n/** Each persisted event type and the payload the registry states it carries. */\nexport type StatedPersistedEventCatalog = {\n 'yield:created': components['schemas']['ResourceCreatedPayload'];\n 'yield:cloned': components['schemas']['ResourceClonedPayload'];\n 'yield:updated': components['schemas']['ResourceUpdatedPayload'];\n 'yield:moved': components['schemas']['ResourceMovedPayload'];\n 'yield:representation-added': components['schemas']['RepresentationAddedPayload'];\n 'yield:representation-removed': components['schemas']['RepresentationRemovedPayload'];\n 'mark:added': components['schemas']['AnnotationAddedPayload'];\n 'mark:removed': components['schemas']['AnnotationRemovedPayload'];\n 'mark:body-updated': components['schemas']['AnnotationBodyUpdatedPayload'];\n 'mark:entity-tag-added': components['schemas']['EntityTagChangedPayload'];\n 'mark:entity-tag-removed': components['schemas']['EntityTagChangedPayload'];\n 'mark:archived': components['schemas']['ResourceArchivedPayload'];\n 'mark:unarchived': components['schemas']['ResourceUnarchivedPayload'];\n 'frame:entity-type-added': components['schemas']['EntityTypeAddedPayload'];\n 'frame:tag-schema-added': components['schemas']['TagSchemaAddedPayload'];\n 'principal:profiled': components['schemas']['PrincipalProfiledPayload'];\n 'job:started': components['schemas']['JobStartedPayload'];\n 'job:assigned': components['schemas']['JobAssignedPayload'];\n 'job:completed': components['schemas']['JobCompletedPayload'];\n 'job:failed': components['schemas']['JobFailedPayload'];\n};\n\n/**\n * Each persisted event type and the payload it carries: the stated one, or\n * its refinement where bus-refinements.ts narrows it to this layer's branded\n * types, so consumers read `payload.annotation.id` as `AnnotationId` without\n * an upcast at every seam.\n */\ntype PersistedEventCatalog = {\n [\n K in keyof StatedPersistedEventCatalog\n ]: K extends keyof EventPayloadRefinements\n ? EventPayloadRefinements[K]\n : StatedPersistedEventCatalog[K];\n};\n\n/** System event types — persisted events that have no resourceId. */\ntype SystemEventType =\n 'frame:entity-type-added' | 'frame:tag-schema-added' | 'principal:profiled';\n\n/** Extract the concrete persisted event type for a given type string. */\nexport type EventOfType<K extends keyof PersistedEventCatalog> =\n K extends SystemEventType\n ? EventBase & { type: K; payload: PersistedEventCatalog[K] }\n : EventBase & {\n type: K;\n resourceId: ResourceId;\n payload: PersistedEventCatalog[K];\n };\n\n/** The union of all persisted event types. Discriminated on `type`. */\nexport type PersistedEvent = {\n [K in keyof PersistedEventCatalog]: EventOfType<K>;\n}[keyof PersistedEventCatalog];\n\nexport type PersistedEventType = PersistedEvent['type'];\n\n/** Every persisted event type, for code that enumerates them at runtime. */\nexport const PERSISTED_EVENT_TYPES = [\n 'yield:created',\n 'yield:cloned',\n 'yield:updated',\n 'yield:moved',\n 'yield:representation-added',\n 'yield:representation-removed',\n 'mark:added',\n 'mark:removed',\n 'mark:body-updated',\n 'mark:entity-tag-added',\n 'mark:entity-tag-removed',\n 'mark:archived',\n 'mark:unarchived',\n 'frame:entity-type-added',\n 'frame:tag-schema-added',\n 'principal:profiled',\n 'job:started',\n 'job:assigned',\n 'job:completed',\n 'job:failed',\n] as const satisfies readonly PersistedEventType[];\n\n/** Input type for appendEvent — PersistedEvent without id/timestamp (assigned at persistence time). */\nexport type EventInput = Omit<PersistedEvent, 'id' | 'timestamp'>;\n","/**\n * Event Type Guards and Extraction Utilities\n *\n * Domain logic for working with resource events.\n * No React dependencies - safe to use in any JavaScript environment.\n */\n\nimport { isAnnotationId, type AnnotationId } from './identifiers';\nimport { isObject, isString } from './type-guards';\nimport type { components } from './types';\n\n// =============================================================================\n// EVENT TYPE GUARDS AND EXTRACTION\n// =============================================================================\n\n/**\n * The annotation a stored event is about, or null when it is about none.\n *\n * A `mark:added` carries the annotation; a `mark:removed` and a\n * `mark:body-updated` name it by id.\n */\nexport function getAnnotationIdFromEvent(\n event: components['schemas']['StoredEventResponse'],\n): AnnotationId | null {\n const payload = event.payload;\n let id: unknown;\n if (event.type === 'mark:added') {\n id = isObject(payload.annotation) ? payload.annotation.id : undefined;\n } else if (\n event.type === 'mark:removed' ||\n event.type === 'mark:body-updated'\n ) {\n id = payload.annotationId;\n }\n return isString(id) && isAnnotationId(id) ? id : null;\n}\n","/**\n * Which failures are worth another attempt — one catalog, several contexts.\n *\n * **Not `RetryPolicy`, which is next door and means something else.** That is a\n * timing budget: how long to keep trying. A `RetryRule` is which failures to try\n * again at all. `STARTUP_FETCH_RETRY: RetryPolicy` and `RETRY_RULES.boot` answer\n * different questions about the same attempt.\n *\n * ## Why one file, when the contexts genuinely differ\n *\n * They do differ, and collapsing them to one answer would break something: a\n * `500` mid-job is worth another attempt, where the same `500` in a boot pass\n * replays whatever broke it. The defect being fixed is not divergence — it is\n * that the divergence was **undeclared**. Four sites decided this question, two\n * with an argument and two with a bare list, and no reader of any file could see\n * that the others existed. Where a list and an argument disagreed, the list won\n * silently.\n *\n * So the rules sit together *because* they disagree. A reader comparing two lines\n * here sees a decision; a reader of one package could only ever see a default.\n *\n * This is the opposite call from `retry.ts`'s \"judgment with its caller\", and\n * deliberately: that rule governs timing budgets, where one number shared across\n * peers that answer differently caused a measured bug. Here the failure mode is\n * invisibility, and co-location is its cure. A context still owns its *choice* —\n * it picks a rule by name — it does not own a private copy of the reasoning.\n *\n * ## The census gate is reachability\n *\n * Rules are exported only through `RETRY_RULES`. A rule missing from that record\n * cannot be consumed, which is a stronger gate than a parallel list a new rule\n * could simply be left out of.\n */\n\n/**\n * What is known about a failure at the moment someone asks.\n *\n * `method` and `keyed` exist because retryability depends on the REQUEST as well\n * as the failure: a `504` on a GET is safe to repeat, a `504` on a POST may\n * already have been processed upstream, unless the POST carries a key the server\n * answers its repeat by. Optional, because only the transport rule has an\n * answer for them — and unstated reads as unsafe rather than as permission.\n *\n * Deliberately not a `ReadonlySet<number>`: a status set cannot say *`5xx` on\n * idempotent methods only*, which is exactly what the transport needs to say.\n */\nexport interface RetryFacts {\n status?: number;\n /** HTTP method, any case. Absent means \"not stated\", which is treated as unsafe. */\n method?: string;\n /**\n * Whether the request carries an `Idempotency-Key`. Absent means it carries\n * none, as a row of protocol/specs/src/retry/cases.json that omits it states.\n */\n keyed?: boolean;\n}\n\nexport interface RetryRule {\n readonly name: string;\n /** Why this context answers the way it does. Not decoration: the two bare\n * lists this taxonomy replaces were bare because nobody had to write one. */\n readonly rationale: string;\n retryable(facts: RetryFacts): boolean;\n}\n\n/** Repeating these cannot cause a second effect upstream (RFC 9110 §9.2.2). */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\n 'GET',\n 'HEAD',\n 'PUT',\n 'DELETE',\n 'OPTIONS',\n 'TRACE',\n]);\n\nconst boot: RetryRule = {\n name: 'boot',\n rationale:\n 'A boot pass or a bus request, where the peer is usually seconds from being ready. ' +\n '429/503/504 are the server saying \"up, but not now\" — retrying is compliance with its ' +\n 'own instruction. 500 is excluded on the record: 503 and 504 are promises to recover, ' +\n 'an unclassified server fault is not, and replaying it inside a boot pass re-runs ' +\n 'whatever broke it. Auth and validation failures stay out for the same reason a 401 ' +\n 'does — the gateway is up and rejected us.',\n retryable: ({ status }) => status === 429 || status === 503 || status === 504,\n};\n\nconst job: RetryRule = {\n name: 'job',\n rationale:\n 'A job retry budget, where the cost of NOT retrying is a discarded long-running ' +\n 'attempt. 5xx is included where the boot rule excludes it, because the alternative is ' +\n 'throwing away paid work over one unclassified fault. 408 joins as an explicit timeout. ' +\n 'The price of a wrong \"transient\" is a re-pay, not a corrupted write — which is what ' +\n 'makes the wider answer affordable here and not at boot. Two facts, both settled ' +\n '2026-09-12, say how affordable: a 5xx arriving at a job has ALREADY failed three ' +\n 'times at the call (the inference client retries twice, a count chosen explicitly ' +\n 'rather than inherited from the vendor SDK), so this is a considered second chance ' +\n 'rather than a hair-trigger; and since a retried job resumes mid-unit from its ' +\n 'checkpointed cursor, the re-pay is about ONE CHUNK, not the whole prefix it used ' +\n 'to be (~26 min on the 1958 document). Both push the same way. ' +\n 'If either changes — the client stops retrying, or resume stops working — this rule ' +\n 'is the line to revisit.',\n retryable: ({ status }) =>\n status === 408 || status === 429 || (status !== undefined && status >= 500),\n};\n\nconst transport: RetryRule = {\n name: 'transport',\n rationale:\n \"An HTTP client's request. A retryable status applies only where a repeat cannot cause a \" +\n 'second effect: on an idempotent method, or on a request that carries an Idempotency-Key, ' +\n 'whose repeat the server answers as it answered the first. A POST with no key that got a ' +\n '502 may already have been processed, so a repeat could do it twice. The method and the ' +\n 'key are enough: no per-endpoint registry. A key makes a repeat harmless, not a refused ' +\n 'request acceptable, so a 400 or 422 stays final. A 401 is not retried: a refused ' +\n 'credential is renewed before any rule is asked, and the same token gets the same answer.',\n retryable: ({ status, method, keyed }) => {\n if (status === undefined) return false;\n const repeatable =\n keyed === true ||\n (method !== undefined && IDEMPOTENT_METHODS.has(method.toUpperCase()));\n if (!repeatable) return false;\n return (\n status === 408 ||\n status === 413 ||\n status === 429 ||\n status === 500 ||\n status === 502 ||\n status === 503 ||\n status === 504\n );\n },\n};\n\n/**\n * Every rule, and the only way to reach one.\n *\n * Frozen and exhaustive on purpose — see the census-gate note above.\n */\nconst refresh: RetryRule = {\n name: 'refresh',\n rationale:\n \"Exchanging a refresh token at its issuer. The issuer's answer is the verdict and its \" +\n 'absence never is: a refused grant (RFC 6749 §5.2 returns 400 `invalid_grant` for a ' +\n 'revoked, expired or already-rotated token) is terminal on the first answer, because ' +\n 'retrying cannot change it and only delays a re-login the user must perform anyway. No ' +\n 'response at all, or one saying \"not now\" (408, 429, 5xx), is transient — the session ' +\n 'survives a lost packet. 5xx is included where the boot rule excludes it, and the two are ' +\n 'not in conflict: a boot pass replays whatever broke it, while this is a single idempotent ' +\n 'exchange with no side effect to replay. Unclassified faults are TERMINAL, which inverts ' +\n 'the usual instinct deliberately — a 404 on the token endpoint is a misconfiguration, not ' +\n 'a promise to recover, and over-retrying here shows the user a hung app instead of the ' +\n 'honest re-login.',\n retryable: ({ status }) => {\n // No status means `fetch` threw before there was a response — the network,\n // not the issuer. That is the case this rule exists to keep alive, so it is\n // the one place absence reads as permission rather than as refusal.\n if (status === undefined) return true;\n return status === 408 || status === 429 || status >= 500;\n },\n};\n\nexport const RETRY_RULES = Object.freeze({ boot, job, refresh, transport });\n","/**\n * Base64url (RFC 4648 section 5), unpadded: what the id of an annotation is\n * cut from. Private to this package.\n */\nexport function base64url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n","/**\n * SHA-256 (FIPS 180-4), for the id of an annotation (`annotation-id.ts`) and\n * the thumbprint a service account's key is named by (`client-assertion.ts`).\n *\n * The platform's own is `crypto.subtle.digest`. It answers later, where an id\n * is worked out at once; and a browser withholds `crypto.subtle` from a page\n * that is not a secure context, one served over plain http from any host but\n * localhost, where this package runs too. This is the one implementation the\n * id uses, in every context: a branch that preferred the platform's where it\n * exists would be a second implementation of one hash, run only where nobody\n * tests.\n *\n * Private to this package: its root exports no hash. Nothing secret is hashed\n * here. An id is a public derivation of what an annotation is, and a\n * thumbprint of a key's public half, so a wrong digest cannot leak anything:\n * it fails where it can be seen, in the id's and the assertion's case tables.\n */\n\n/** The first 32 bits of the fractional parts of the cube roots of the first 64 primes. */\nconst K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,\n 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,\n 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,\n 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,\n 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nconst rotr = (x: number, n: number): number => (x >>> n) | (x << (32 - n));\n\nexport function sha256(message: Uint8Array): Uint8Array {\n // Padding: a 1 bit, zeros, then the message's length in bits as 64 bits,\n // big-endian, ending on a block boundary.\n const padded = new Uint8Array(\n (Math.floor((message.length + 8) / 64) + 1) * 64,\n );\n padded.set(message);\n padded[message.length] = 0x80;\n const blocks = new DataView(padded.buffer);\n const bits = message.length * 8;\n blocks.setUint32(padded.length - 8, Math.floor(bits / 0x1_0000_0000));\n blocks.setUint32(padded.length - 4, bits >>> 0);\n\n // The first 32 bits of the fractional parts of the square roots of the first 8 primes.\n let [h0, h1, h2, h3, h4, h5, h6, h7] = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,\n 0x1f83d9ab, 0x5be0cd19,\n ];\n const w = new Uint32Array(64);\n\n for (let block = 0; block < padded.length; block += 64) {\n for (let t = 0; t < 16; t++) w[t] = blocks.getUint32(block + t * 4);\n for (let t = 16; t < 64; t++) {\n const w15 = w[t - 15]!;\n const w2 = w[t - 2]!;\n const s0 = rotr(w15, 7) ^ rotr(w15, 18) ^ (w15 >>> 3);\n const s1 = rotr(w2, 17) ^ rotr(w2, 19) ^ (w2 >>> 10);\n w[t] = w[t - 16]! + s0 + w[t - 7]! + s1;\n }\n\n let [a, b, c, d, e, f, g, h] = [h0, h1, h2, h3, h4, h5, h6, h7];\n for (let t = 0; t < 64; t++) {\n const t1 =\n (h +\n (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) +\n ((e & f) ^ (~e & g)) +\n K[t]! +\n w[t]!) >>>\n 0;\n const t2 =\n ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) +\n ((a & b) ^ (a & c) ^ (b & c))) >>>\n 0;\n h = g;\n g = f;\n f = e;\n e = (d + t1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) >>> 0;\n }\n\n h0 = (h0 + a) >>> 0;\n h1 = (h1 + b) >>> 0;\n h2 = (h2 + c) >>> 0;\n h3 = (h3 + d) >>> 0;\n h4 = (h4 + e) >>> 0;\n h5 = (h5 + f) >>> 0;\n h6 = (h6 + g) >>> 0;\n h7 = (h7 + h) >>> 0;\n }\n\n const digest = new Uint8Array(32);\n const words = new DataView(digest.buffer);\n [h0, h1, h2, h3, h4, h5, h6, h7].forEach((word, i) =>\n words.setUint32(i * 4, word),\n );\n return digest;\n}\n","/**\n * The id of an annotation a builder makes: worked out from what the\n * annotation is, never minted. protocol/specs/src/annotations/id-cases.json holds the\n * rule, for this and for every other implementation.\n *\n * The builders (`annotation-builders.ts`) are its callers, and no one else\n * is: it is no part of what `@xynolog/core` or `@xynolog/sdk` exports.\n */\n\nimport { base64url } from './base64url';\nimport { byCodePoint } from './by-code-point';\nimport { annotationId, type AnnotationId } from './identifiers';\nimport { sha256 } from './sha256';\n\n/** The identity of an annotation — everything that makes it that annotation\n * and nothing else: the inputs its content-addressed id is hashed from. */\nexport interface AnnotationIdentity {\n /** The resource the annotation is about. */\n resourceId: string;\n /** W3C motivation: two motivations on one span are two annotations. */\n motivation: string;\n /**\n * The span, rendered by the builder that anchored it. Deliberately a\n * caller-supplied STRING rather than a structured span: text anchors by\n * character offset and PDF by page geometry, so there is no shape both\n * share, and inventing one here would be a third home for a fact the\n * builders already own. An annotation of a resource as a whole is anchored\n * nowhere on it, and its anchor is the empty string.\n */\n anchor: string;\n /**\n * The annotation's body, when it has one.\n *\n * Included for EVERY motivation that carries one, which is every\n * motivation except `highlighting`. The body matters beyond `commenting`:\n * the same collision exists for `assessing` and `tagging` (two assessments\n * of one span differ solely by their text), and for `linking`: a detected\n * reference carries its entity\n * type as an unresolved TextualBody, which is exactly the \"type\" in the\n * identity a detected annotation needs (resource, span, type, motivation).\n * So a per-motivation table of hash inputs collapses to one rule — hash the\n * body whenever there is one — and that is better than a table, because a\n * sixth motivation inherits the right behavior instead of an omission.\n */\n body?: unknown;\n}\n\n/**\n * Canonical JSON: an object's members in the order of their names by code\n * point, at every depth, so a body built by one code path hashes the same as\n * an equivalent body built by another, in any language. Array order is\n * preserved — it is meaningful (a tagging body is [category, schema]).\n */\nfunction canonical(value: unknown): string {\n if (value === null || typeof value !== 'object')\n return JSON.stringify(value) ?? 'null';\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => byCodePoint(a, b));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;\n}\n\n/**\n * The annotation's id, derived from what the annotation IS.\n *\n * This is what makes every job-recovery path idempotent: a\n * re-queued job, a resumed unit and a retried failure all re-emit the same\n * annotation, and re-emitting it is a no-op *with no read* — which is the\n * property a read-before-write could not provide, because the thing it would\n * read is exactly what is down when recovery is happening.\n *\n * Note what is NOT an input: `created`, the emitting worker, the job id, any\n * counter. A recovery re-emits at a different time from a different process\n * and must still collide, so anything about the emission rather than the\n * annotation would defeat the whole mechanism.\n *\n * 21 base64url characters of a SHA-256: ~126 bits, which is far more than a\n * per-resource span space needs.\n *\n * ## The no-op guarantee is conditional on `anchor`, and the two kinds of span differ\n *\n * \"Re-emitting is a no-op\" holds exactly as far as `anchor` is stable, and that\n * is the builder's property, not this function's. `annotationOfSpan` does not\n * have it equally for its two kinds of span:\n *\n * - **A span of a text** is anchored as `${start}:${end}:${exact}` and the\n * annotation STORES those offsets in a `TextPositionSelector`. Identity depends\n * only on fields the annotation carries, so the guarantee is unconditional and\n * any reader can verify it after the fact.\n * - **A span of a PDF's anchored text** is anchored the same way, but the offsets\n * come from a text layer *derived* per attempt and are deliberately NOT stored —\n * the annotation carries page geometry and the quoted text instead. There the\n * guarantee holds only while that derivation is stable, and a reader holding two\n * annotations cannot tell whether they disagree because they are different facts\n * or because the text layer moved: every stored field would be identical.\n *\n * The derivation is cached per content checksum, but the entry is gated by a stamp\n * over the Smelter's version, its PDF reader and its OCR engine\n * (`xynolog_smelter.stamp`, in images/smelter), and that stamp is deliberately\n * over-eager — **a release busts it and the same bytes are re-extracted by\n * different code.** So the honest statement is: the PDF path's guarantee holds\n * *per stamp generation*, and a release is the event that could end one.\n */\nexport function annotationIdFor(identity: AnnotationIdentity): AnnotationId {\n const material = canonical({\n resourceId: identity.resourceId,\n motivation: identity.motivation,\n anchor: identity.anchor,\n ...(identity.body !== undefined ? { body: identity.body } : {}),\n });\n const digest = base64url(sha256(new TextEncoder().encode(material)));\n return annotationId(digest.slice(0, 21));\n}\n","/**\n * Where an offset into a text meets a JavaScript string.\n *\n * A text offset, on the wire, in the record and in every store, counts\n * Unicode code points from the start of the text: the W3C Web Annotation\n * rule, and the same count in every language. A JavaScript string is indexed\n * in UTF-16 code units, where a character outside the Basic Multilingual\n * Plane is two. The two counts agree until the first such character and\n * differ by one more after each.\n *\n * So arithmetic is done on offsets, and a length is a difference of two of\n * them: every count a rule states is of code points. A string's own position\n * is only ever the argument or the result of a call on the string (a slice, a\n * search, a regular expression's index), and is converted there.\n * protocol/specs/src/text/offset-cases.json holds the count, for this and for every\n * other implementation.\n */\n\n/** A text's offsets and a string's positions, each given the other. */\nexport interface TextOffsets {\n /** How many code points the text is. An offset may equal it and may not exceed it. */\n readonly length: number;\n /** The offset of a position in the string: how many code points are before it. */\n offsetAt(index: number): number;\n /** The position in the string of an offset. */\n indexAt(offset: number): number;\n}\n\nconst isHigh = (unit: number): boolean => unit >= 0xd800 && unit <= 0xdbff;\nconst isLow = (unit: number): boolean => unit >= 0xdc00 && unit <= 0xdfff;\n\n/** Whether the string has, at `index`, the two units of one character outside the basic plane. */\nconst isPairAt = (text: string, index: number): boolean =>\n isHigh(text.charCodeAt(index)) && isLow(text.charCodeAt(index + 1));\n\n/** How many of `sorted` are less than `value`. */\nfunction countBelow(sorted: readonly number[], value: number): number {\n let low = 0;\n let high = sorted.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (sorted[middle]! < value) low = middle + 1;\n else high = middle;\n }\n return low;\n}\n\n/**\n * The conversions for one text, made once and asked as often as the text has\n * offsets. Making it reads the text once; each conversion after that is a\n * search among the text's characters outside the basic plane, of which most\n * texts have none.\n *\n * Half of a pair on its own counts as a code point, as the string's own\n * iteration counts it: an ill-formed string is still a text with offsets.\n */\nexport function textOffsets(text: string): TextOffsets {\n /** The position of each character outside the basic plane: of the first unit of its pair. */\n const pairs: number[] = [];\n for (let index = 0; index < text.length - 1; index++) {\n if (isPairAt(text, index)) {\n pairs.push(index);\n index++;\n }\n }\n /** The offset of each of those characters: its position, less the pairs before it. */\n const pairOffsets = pairs.map((index, before) => index - before);\n const length = text.length - pairs.length;\n\n return {\n length,\n offsetAt(index: number): number {\n if (!Number.isInteger(index) || index < 0 || index > text.length) {\n throw new RangeError(\n `position ${index} is not in a string of ${text.length} units`,\n );\n }\n // A pair that begins before `index` is wholly before it, or `index` is its second unit.\n const before = countBelow(pairs, index);\n if (before > 0 && pairs[before - 1]! + 1 === index) {\n throw new RangeError(\n `position ${index} is inside a character: it has no offset`,\n );\n }\n return index - before;\n },\n indexAt(offset: number): number {\n if (!Number.isInteger(offset) || offset < 0 || offset > length) {\n throw new RangeError(\n `offset ${offset} is not in a text of ${length} code points`,\n );\n }\n // Each character outside the basic plane before the offset is one more unit of the string.\n return offset + countBelow(pairOffsets, offset);\n },\n };\n}\n\n/**\n * The text from one offset to another. `offsets` is the text's own, and each\n * of the two is an offset of the text, the first no greater than the second:\n * `indexAt` throws at a number that is no offset of the text.\n */\nexport function between(\n text: string,\n offsets: TextOffsets,\n start: number,\n end: number,\n): string {\n return text.slice(offsets.indexAt(start), offsets.indexAt(end));\n}\n\n/**\n * Every place `text` has `words`, as the offset each starts at, in the text's\n * order. Places may overlap. `offsets` is the text's own.\n *\n * A string is searched by its code units, so a search for words that begin or\n * end with half of a pair also finds them inside a character of the text. The\n * text does not have those words there, character for character, and the\n * position has no offset: it is no place.\n */\nexport function occurrencesOf(\n text: string,\n offsets: TextOffsets,\n words: string,\n): number[] {\n const places: number[] = [];\n let index = text.indexOf(words);\n while (index !== -1) {\n const end = index + words.length;\n if (!isPairAt(text, index - 1) && !isPairAt(text, end - 1))\n places.push(offsets.offsetAt(index));\n // Words of no length are found at the end of the text too, and a search\n // from past the end finds them there again.\n index = index < text.length ? text.indexOf(words, index + 1) : -1;\n }\n return places;\n}\n","/**\n * Fuzzy Anchoring for W3C Web Annotation TextQuoteSelector\n *\n * The searches a quote is put through when a text does not have it character\n * for character: without regard to white space and to the form of quotation\n * marks and dashes, without regard to letter case, and by edit distance.\n * protocol/specs/src/annotations/reconcile-cases.json holds the rule.\n *\n * A position in a text is an offset: it counts Unicode code points from the\n * start of the text, and so does every length a rule here states (the\n * stretch a quote is compared with, its allowance, an edit). A string's own\n * positions are converted with `textOffsets`, where the string is called.\n *\n * @see https://www.w3.org/TR/annotation-model/#text-quote-selector\n */\n\nimport { occurrencesOf, textOffsets, type TextOffsets } from './text-offsets';\n\nimport type { MatchQuality } from './payload-types';\n\n/**\n * Normalize text for comparison - handles common document editing changes\n *\n * Collapses whitespace, converts curly quotes to straight quotes,\n * and normalizes common punctuation variations.\n */\nexport function normalizeText(text: string): string {\n return text\n .replace(/\\s+/g, ' ') // collapse whitespace\n .replace(/[\\u2018\\u2019]/g, \"'\") // curly single quotes → straight\n .replace(/[\\u201C\\u201D]/g, '\"') // curly double quotes → straight\n .replace(/\\u2014/g, '--') // em-dash → double hyphen\n .replace(/\\u2013/g, '-') // en-dash → hyphen\n .trim();\n}\n\n/**\n * The edit distance between `wanted` and every stretch of `text` that starts\n * at `from`, up to one of `longest` code points: `distances[n]` is the least\n * number of single code points inserted, deleted or replaced that turns\n * `wanted` into the `n` code points from `from`. `null` when no stretch from\n * there is within `allowance`.\n *\n * Both are code points, one to an element, so an edit is of one code point.\n */\nfunction distancesFrom(\n wanted: readonly string[],\n text: readonly string[],\n from: number,\n longest: number,\n allowance: number,\n): number[] | null {\n // From none of `wanted`, a stretch of `n` code points is `n` insertions away.\n let row = Array.from({ length: longest + 1 }, (_, n) => n);\n let next = new Array<number>(longest + 1);\n\n for (let i = 1; i <= wanted.length; i++) {\n next[0] = i;\n let least = i;\n for (let n = 1; n <= longest; n++) {\n const cost = wanted[i - 1] === text[from + n - 1] ? 0 : 1;\n const distance = Math.min(\n row[n]! + 1,\n next[n - 1]! + 1,\n row[n - 1]! + cost,\n );\n next[n] = distance;\n if (distance < least) least = distance;\n }\n // The least distance of a row never falls as more of `wanted` is taken.\n if (least > allowance) return null;\n [row, next] = [next, row];\n }\n\n return row;\n}\n\n/**\n * Pre-computed content strings for batch fuzzy matching.\n * Avoids recomputing normalizeText(content) and content.toLowerCase()\n * for every annotation when processing many annotations against the same content.\n *\n * `normalizedMap[i]` is the offset, in the original content, of the\n * character that the code point at offset `i` of `normalizedContent` came\n * from, and `lowerMap[i]` the same for `lowerContent`: an entry for each code\n * point of the changed copy. A map is how `findBestTextMatch` answers a match\n * in a copy as a span of the content itself. For the normalized copy,\n * counting char-by-char with `normalizeText(singleChar)` is wrong, because a\n * lone whitespace char trims to `''` (contributing 0) while in a full-string\n * normalize it collapses to a single space (contributing 1). That discrepancy\n * shifts recovered offsets by the number of whitespace runs before the match.\n */\nexport interface ContentCache {\n normalizedContent: string;\n /** The normalized content's own conversions: it is another string. */\n normalizedOffsets: TextOffsets;\n normalizedMap: number[];\n lowerContent: string;\n /** The lower-cased content's own conversions: it is another string, of another length where lower-casing changes one. */\n lowerOffsets: TextOffsets;\n lowerMap: number[];\n}\n\n/**\n * Normalize text and, in the same pass, build a map from each offset of the\n * normalized text back to the offset, in the input, of the character it\n * came from. Both count code points: the map has one entry for each code\n * point of the normalized text.\n * The produced `normalized` string is identical to `normalizeText(input)`\n * — a test pins this equivalence so the two can't drift.\n */\nexport function normalizeTextWithMap(input: string): {\n normalized: string;\n map: number[];\n} {\n let normalized = '';\n const map: number[] = [];\n\n // First pass mirrors normalizeText exactly, char by char, recording the\n // origin offset for every emitted normalized character.\n let pendingWhitespaceStart = -1; // origin offset of an open whitespace run, or -1\n\n const flushWhitespace = () => {\n if (pendingWhitespaceStart !== -1) {\n // A whitespace run collapses to a single space, mapped to the run's\n // first char — but a *leading* run (nothing emitted yet) is dropped,\n // matching normalizeText's trailing `.trim()`.\n if (normalized.length > 0) {\n normalized += ' ';\n map.push(pendingWhitespaceStart);\n }\n pendingWhitespaceStart = -1;\n }\n };\n\n // The offset of `ch`: how many code points of `input` are before it. A\n // string is walked a code point at a time, so it is one more for each.\n let offset = 0;\n for (const ch of input) {\n if (/\\s/.test(ch)) {\n if (pendingWhitespaceStart === -1) pendingWhitespaceStart = offset;\n offset++;\n continue;\n }\n flushWhitespace();\n if (ch === '‘' || ch === '’') {\n normalized += \"'\";\n map.push(offset);\n } else if (ch === '“' || ch === '”') {\n normalized += '\"';\n map.push(offset);\n } else if (ch === '—') {\n normalized += '--';\n map.push(offset);\n map.push(offset);\n } else if (ch === '–') {\n normalized += '-';\n map.push(offset);\n } else {\n normalized += ch;\n map.push(offset);\n }\n offset++;\n }\n // A trailing whitespace run is dropped by trim — do not flush it.\n\n // `normalizeText` applies `.trim()` last. Our run logic already drops a\n // trailing whitespace run; a leading run is dropped because flushWhitespace\n // only runs before a non-space char, so a run at the very start is never\n // emitted. Both ends match trim().\n return { normalized, map };\n}\n\n/**\n * Lower-case text and build a map from each offset of the lower-cased text\n * back to the offset, in the input, of the character it came from. Both\n * count code points.\n *\n * The text is lower-cased whole, by Unicode's rule of no particular language:\n * a capital sigma that ends a word becomes the final one, which lower-casing\n * a character at a time would miss. A character becomes as many code points\n * whole as alone (U+0130, a capital I with a dot, becomes two), which is what\n * the map is counted from.\n */\nexport function lowerCaseWithMap(input: string): {\n lowered: string;\n map: number[];\n} {\n const lowered = input.toLowerCase();\n const map: number[] = [];\n let offset = 0;\n for (const ch of input) {\n const codePoints = Array.from(ch.toLowerCase()).length;\n for (let n = 0; n < codePoints; n++) map.push(offset);\n offset++;\n }\n if (map.length !== textOffsets(lowered).length) {\n throw new Error(\n 'a text lower-cased whole is not as long as its characters lower-cased one at a time',\n );\n }\n return { lowered, map };\n}\n\n/**\n * Build a ContentCache for a given content string.\n * Call once per content, pass to findBestTextMatch for every search of it.\n */\nexport function buildContentCache(content: string): ContentCache {\n const { normalized, map } = normalizeTextWithMap(content);\n const { lowered, map: lowerMap } = lowerCaseWithMap(content);\n return {\n normalizedContent: normalized,\n normalizedOffsets: textOffsets(normalized),\n normalizedMap: map,\n lowerContent: lowered,\n lowerOffsets: textOffsets(lowered),\n lowerMap,\n };\n}\n\n/**\n * The span of the content that a match in a changed copy of it came from:\n * `length` code points of the copy from the offset `at`. It starts at the\n * character the match's first code point came from and ends just after the\n * character its last came from, so a character that became several code\n * points is in the span whole, and white space the content has after the\n * match is not in it.\n */\nfunction spanOf(\n map: readonly number[],\n at: number,\n length: number,\n): { start: number; end: number } {\n return { start: map[at]!, end: map[at + length - 1]! + 1 };\n}\n\n/**\n * Find text that the content does not have character for character, using\n * multi-strategy search: the strictest of the looser searches that finds it\n * at all answers, with every place it finds it.\n *\n * The search `reconcile` (write-time) falls back on, having looked for the\n * text as it is.\n *\n * @param content - Full text content to search within\n * @param searchText - The text to find\n * @param cache - What is made once for the content (from buildContentCache)\n * @returns The places found, each two offsets in code points, in the content's order, and the search that found them; or null if none did\n */\nexport function findBestTextMatch(\n content: string,\n searchText: string,\n cache: ContentCache,\n): {\n places: Array<{ start: number; end: number }>;\n matchQuality: MatchQuality;\n} | null {\n // Nothing, or only white space, is no words to find: it is in no place.\n if (searchText.trim() === '') return null;\n\n // Strategy 1: Normalized match (handles whitespace/quote variations).\n // Each place in the normalized content is answered as the span of the\n // content it came from, through the precomputed offset map.\n const normalizedSearch = normalizeText(searchText);\n const normalizedLength = textOffsets(normalizedSearch).length;\n const normalized = occurrencesOf(\n cache.normalizedContent,\n cache.normalizedOffsets,\n normalizedSearch,\n );\n if (normalized.length > 0) {\n return {\n places: normalized.map((at) =>\n spanOf(cache.normalizedMap, at, normalizedLength),\n ),\n matchQuality: 'normalized',\n };\n }\n\n // Strategy 2: Case-insensitive match. Each place in the lower-cased\n // content is answered as the span of the content it came from: lower-casing\n // changes how many code points some characters are.\n const lowerSearch = searchText.toLowerCase();\n const lowerLength = textOffsets(lowerSearch).length;\n const lowered = occurrencesOf(\n cache.lowerContent,\n cache.lowerOffsets,\n lowerSearch,\n );\n if (lowered.length > 0) {\n return {\n places: lowered.map((at) => spanOf(cache.lowerMap, at, lowerLength)),\n matchQuality: 'case-insensitive',\n };\n }\n\n // Strategy 3: Fuzzy match by edit distance, over every stretch of the\n // content. The search text is a code point to an element: its length is a\n // count of code points, and so is the stretch of content it is compared\n // with. The allowance is a twentieth of that length, with no minimum.\n const wanted = Array.from(searchText);\n const allowance = Math.floor(wanted.length / 20);\n // A stretch at no distance is the search text itself, which the content does not have.\n if (allowance === 0) return null;\n\n const text = Array.from(content);\n // A stretch within the allowance is at most the allowance shorter or longer than the search text.\n const shortest = wanted.length - allowance;\n let best: { start: number; end: number; distance: number } | null = null;\n\n // Of several stretches at the least distance, the one that starts first is\n // taken; of those from one start, the one nearest the search text in\n // length; and of two as near, the shorter. So from each start the stretch as\n // long as the search text is tried first, then the one a code point shorter\n // and the one a code point longer, and so on out.\n for (let start = 0; start + shortest <= text.length; start++) {\n const longest = Math.min(wanted.length + allowance, text.length - start);\n const distances = distancesFrom(wanted, text, start, longest, allowance);\n if (distances === null) continue;\n for (let away = 0; away <= allowance; away++) {\n for (const length of away === 0\n ? [wanted.length]\n : [wanted.length - away, wanted.length + away]) {\n if (length > longest) continue;\n const distance = distances[length]!;\n if (\n distance <= allowance &&\n (best === null || distance < best.distance)\n ) {\n best = { start, end: start + length, distance };\n }\n }\n }\n }\n\n if (best === null) return null;\n return {\n places: [{ start: best.start, end: best.end }],\n matchQuality: 'fuzzy',\n };\n}\n","/**\n * Text ↔ geometry anchoring for PDFs.\n *\n * Two directions over the same pairing of text and the runs that index it:\n * `locate` turns a span of the text into rectangles (an annotation the model\n * produced by quoting text), `textUnder` turns a rectangle into text (an\n * annotation a person produced by dragging a box). They are inverses and live\n * together deliberately.\n *\n * A span, like an item's `start` and `end`, is two offsets: they count\n * Unicode code points from the start of the text.\n *\n * This is pure arithmetic over plain data, so it sits here beside\n * `PdfCoordinate` and the viewrect codec: the browser canvas needs\n * `textUnder` at drag time, over the document's text as it was served.\n * *Producing* an `AnchoredText`, from a text layer or from OCR, is the\n * Smelter's.\n *\n * Coordinates are PDF points with the origin at the bottom-left of the page,\n * Y increasing upward. The Y-flip to canvas pixels lives in the browser.\n */\n\nimport type { PdfCoordinate } from './payload-types';\nimport { textOffsets } from './text-offsets';\nimport type { components } from './types';\n\n/**\n * One positioned text run of a PDF, roughly a word: where it is on its page,\n * and the range of the paired `AnchoredText.text` it stands for, in code\n * points. The spec's shape.\n */\nexport type PdfTextItem = components['schemas']['PdfTextItem'];\n\n/**\n * Text paired with the geometry that indexes it — the minimum needed to turn a\n * range of the text into a Selection, or a rectangle into a quote. The spec's\n * shape.\n *\n * This is the contract `locate`, `textUnder` and the annotation builders\n * actually require; they do not need pages, form fields, or anything else a\n * PDF's reader holds. Naming it separately lets OCR'd content (recovered from\n * pixels, so not a \"text layer\" in the PDF sense) satisfy the same anchoring\n * path.\n */\nexport type AnchoredText = components['schemas']['AnchoredText'];\n\n/**\n * What a READER gets when it asks for a resource's map: the map, a stored\n * decline, or a named absence.\n *\n * Deliberately wider than the spec's `ExtractionOutcome`, which is what the\n * store HOLDS and what an extractor RETURNS — neither of which can ever be\n * \"not yet\". Widening that type instead would have put an impossible state\n * into the store's own.\n */\nexport type AnchoredTextAnswer = components['schemas']['AnchoredTextAnswer'];\n\n/**\n * Items whose baseline Y is within this many PDF points are treated as being on\n * the same line. Tuned for ~12pt body text; revisit for documents with large or\n * variable font sizes (deferred hardening, #738).\n */\nconst SAME_LINE_THRESHOLD_PT = 2;\n\n/**\n * Locates bounding rectangles for a span of text in an AnchoredText\n * (single-line or multi-line).\n *\n * `start` and `end` are offsets into `anchored.text`, in code points, as the\n * items' own are. Nothing here reads the text, so nothing is converted: the\n * arithmetic is on offsets throughout.\n *\n * Finds all overlapping items [start, end), groups them by page and line, and\n * records one bounding rectangle per line as a PdfCoordinate.\n *\n * Returns both the per-line `rects` and the `overlap` items they were computed\n * from — so a caller that also needs the covered text (`annotationOfSpan`,\n * which holds a PDF's span to the text its rectangles cover) reuses this single `items` scan\n * instead of re-filtering. Both arrays are empty if no item overlaps the span:\n * an empty span (`start` equal to `end`) overlaps none, wherever it falls.\n */\nexport function locate(\n anchored: AnchoredText,\n start: number,\n end: number,\n): { rects: PdfCoordinate[]; overlap: PdfTextItem[] } {\n // An empty span has no character for an item to hold, inside one as between two.\n if (start === end) return { rects: [], overlap: [] };\n\n const overlap: PdfTextItem[] = anchored.items.filter(\n (item) => item.start < end && item.end > start,\n );\n if (overlap.length === 0) return { rects: [], overlap };\n\n const pages: Map<number, PdfTextItem[]> = groupItemsByPage(overlap);\n const rects: PdfCoordinate[] = [];\n\n // for each page, group items into lines and compute one rectangle per line\n for (const [page, pageItems] of pages) {\n const lines = groupItemsByLine(pageItems, SAME_LINE_THRESHOLD_PT);\n // Compute one bounding rectangle per line and add it to rects.\n // Boundary items that extend past [start, end) are clipped by the\n // fraction of their code points the span takes: renderers like Typst\n // emit ONE item per line, so without\n // clipping a mid-line phrase would bound the whole line. Proportional\n // interpolation is the measured fallback — exact glyph metrics need\n // the operator-list route, an open refinement, and can replace this\n // arithmetic without changing the shape.\n for (const lineItems of lines) {\n const edges = lineItems.map((i) => {\n const codePoints = i.end - i.start;\n const left =\n i.start < start && codePoints > 0\n ? i.x + i.width * ((start - i.start) / codePoints)\n : i.x;\n const right =\n i.end > end && codePoints > 0\n ? i.x + i.width * ((end - i.start) / codePoints)\n : i.x + i.width;\n return { left, right };\n });\n const x = Math.min(...edges.map((e) => e.left));\n const right = Math.max(...edges.map((e) => e.right));\n const y = Math.min(...lineItems.map((i) => i.y));\n const top = Math.max(...lineItems.map((i) => i.y + i.height));\n rects.push({ page, x, y, width: right - x, height: top - y });\n }\n }\n return { rects, overlap };\n}\n\n/**\n * The inverse of `locate`: given a rectangle, returns the text under it.\n *\n * A hand-drawn PDF rectangle otherwise carries no quoted text at all, so every\n * panel that quotes an annotation shows it blank.\n *\n * `rect` is in the same PDF-point, bottom-left-origin space as `PdfTextItem`,\n * so a canvas drag rectangle passes straight in. A run counts as covered when\n * the rectangle overlaps `RUN_COVERAGE_THRESHOLD` of its area — see there for\n * why any-intersection is not survivable for a hand-drawn box.\n *\n * Covered runs are emitted in reading order (`text` offset order), which\n * inherits the extractor's known column-major ordering on multi-column pages\n * rather than answering it a second, different way.\n *\n * An item's `start` and `end` count code points, so the text of each run is\n * read out of the string through the text's conversions.\n *\n * Returns `''` when nothing is covered — over an image, over whitespace, or\n * over a scanned page with no text layer. Callers must then emit no\n * `TextQuoteSelector` at all: an empty quote would assert the box was drawn\n * around nothing.\n */\nexport function textUnder(anchored: AnchoredText, rect: PdfCoordinate): string {\n const covered = anchored.items\n .filter((item) => item.page === rect.page && covers(item, rect))\n .sort((a, b) => a.start - b.start);\n if (covered.length === 0) return '';\n\n const offsets = textOffsets(anchored.text);\n /** The text between two offsets. */\n const between = (start: number, end: number): string =>\n anchored.text.slice(offsets.indexAt(start), offsets.indexAt(end));\n\n // Join with the document's own separator when the runs are adjacent in\n // `text` — pdf.js splits words at kerning and font changes, so a blanket\n // join(' ') would emit \"aga in\" for a single word. When runs are NOT\n // adjacent the rectangle missed the text between them, so substitute a\n // space rather than splicing in words the box does not cover. (Slicing\n // first-offset..last-offset the way `annotationOfSpan` does is safe there\n // — it only feeds a containment check — but here the result is the stored\n // quote, and on a two-column page it would swallow half of each column.)\n let quoted = between(covered[0].start, covered[0].end);\n for (let i = 1; i < covered.length; i++) {\n const gap = between(covered[i - 1].end, covered[i].start);\n quoted +=\n (gap.trim() === '' ? gap : ' ') +\n between(covered[i].start, covered[i].end);\n }\n return quoted.trim();\n}\n\n/**\n * Fraction of a run's own area a rectangle must overlap for the run to count\n * as covered.\n *\n * Any intersection — the obvious rule, and `locate`'s rule for offsets — is not\n * survivable here, because a hand-drawn box is not a tight box. What decides\n * the threshold is the *headroom* between lines: word boxes run taller than\n * their glyphs, so the gap between one line's box and the next is far smaller\n * than the visible leading. Exact-quote rate measured over every text page of\n * two real scanned books, by how far the box misses:\n *\n * any 0.3 0.4 0.5 0.6\n * -2pt 98/99 98/83 98/49 60/16 2/ 0\n * -1pt 98/99 98/100 98/97 98/94 98/84\n * +2pt 45/ 2 98/97 98/99 98/99 98/100\n * +4pt 11/ 2 98/16 98/58 98/96 98/97\n * +6pt 9/ 0 51/ 8 64/11 98/16 98/38\n * (headroom ~2.0pt / ~0.9pt — the second book is set much tighter,\n * and on some of its pages adjacent word boxes overlap outright)\n *\n * A third book, 100 pages, varies run granularity instead — ~42 chars per run\n * against 25 and 14, i.e. whole lines as single runs — and 0.5 holds 100% from\n * -1pt to +6pt there. Across all three: >=94% from -1pt to +4pt every time.\n *\n * This also carries page skew, which is why it matters beyond hand-drawn boxes.\n * Tilting real runs and taking axis-aligned boxes after rotation, exact-quote\n * rate: 0.5 holds 100% to 0.25deg and 99% at 0.5deg, where `any` is already at\n * 54% and 34% — a tenth of a degree, invisible to the eye, is enough to wreck\n * it. Beyond ~1deg the limit is not this constant but `SAME_LINE_THRESHOLD_PT`,\n * which a drifting baseline exceeds, splitting one line into several rects.\n *\n * Any-intersection is exact only while the box is tight: 2pt of overshoot —\n * less than the height of a comma, and unavoidable with a mouse — and quotes\n * start picking up fragments of the lines above and below.\n *\n * 0.5 is the widest band holding on BOTH books, about 1pt under to 4pt over.\n * Lower thresholds look better on loosely-set pages and fail on tight ones\n * (0.3 drops to 16% at +4pt on the tighter book), which is exactly the way to\n * overfit this constant to one document. A hand drag overshoots far more often\n * than it undershoots, so the asymmetry is spent on the overshoot side.\n *\n * Consequence to know about: a run the box merely clips — a sliver of the\n * first or last word — falls below the threshold and is dropped. That is the\n * intended trade. Raising this admits neighbouring lines; lowering it drops\n * words from a box drawn slightly small.\n */\nexport const RUN_COVERAGE_THRESHOLD = 0.5;\n\nfunction covers(item: PdfTextItem, rect: PdfCoordinate): boolean {\n const overlapX =\n Math.min(item.x + item.width, rect.x + rect.width) -\n Math.max(item.x, rect.x);\n const overlapY =\n Math.min(item.y + item.height, rect.y + rect.height) -\n Math.max(item.y, rect.y);\n if (overlapX <= 0 || overlapY <= 0) return false;\n return (\n overlapX * overlapY >= RUN_COVERAGE_THRESHOLD * item.width * item.height\n );\n}\n\nfunction groupItemsByPage(items: PdfTextItem[]): Map<number, PdfTextItem[]> {\n const map = new Map<number, PdfTextItem[]>();\n for (const item of items) {\n const existing = map.get(item.page);\n if (existing) {\n existing.push(item);\n } else {\n map.set(item.page, [item]);\n }\n }\n return map;\n}\n\n/**\n * Sorts text items into lines when their y coordinates are\n * within `sameLineThreshold` points of each other.\n * Sorted top-to-bottom (descending y in PDF space), then left-to-right.\n *\n * Returns 2D array:\n * Outer array = list of lines\n * Inner array = list of items on that line\n */\nfunction groupItemsByLine(\n items: PdfTextItem[],\n sameLineThreshold: number,\n): PdfTextItem[][] {\n // Sort top-to-bottom by y; if y is equal, sort left-to-right by x\n const sorted = [...items].sort((a, b) => b.y - a.y || a.x - b.x);\n const lines: PdfTextItem[][] = [];\n let currentLine: PdfTextItem[] = [];\n\n for (const item of sorted) {\n if (\n currentLine.length === 0 ||\n Math.abs(item.y - currentLine[0].y) <= sameLineThreshold\n ) {\n currentLine.push(item);\n } else {\n lines.push(currentLine);\n currentLine = [item];\n }\n }\n if (currentLine.length > 0) lines.push(currentLine);\n return lines;\n}\n","/**\n * PDF viewrect FragmentSelector codec.\n *\n * `PdfCoordinate` is a bounding rectangle in PDF point space: origin at the\n * bottom-left of the page, Y increasing upward. The Y-flip to canvas pixels\n * lives in the browser (`react-ui`); the server has no canvas.\n *\n * These functions are the viewrect peer of the W3C `FragmentSelector` wrapper in\n * `web-annotation-utils`: they serialize/parse the RFC 3778\n * `page=N&viewrect=left,top,width,height` value. The annotation builders here\n * (serialization at write time) and the browser canvas both take them from\n * here — no package reaches into the UI.\n *\n * RFC 3778 PDF Fragment Identifiers: https://tools.ietf.org/html/rfc3778\n */\n\nimport type { PdfCoordinate } from './payload-types';\n\n/**\n * Serialize a PdfCoordinate to an RFC 3778 FragmentSelector value.\n * Format: `page=N&viewrect=left,top,width,height` (all in PDF points).\n */\nexport function createFragmentSelector(coord: PdfCoordinate): string {\n return `page=${coord.page}&viewrect=${coord.x},${coord.y},${coord.width},${coord.height}`;\n}\n\n/**\n * Parse an RFC 3778 FragmentSelector value into PDF coordinates.\n * Returns null when the value is not a well-formed page + viewrect fragment.\n */\nexport function parseFragmentSelector(fragment: string): PdfCoordinate | null {\n const pageMatch = fragment.match(/page=(\\d+)/);\n if (!pageMatch) return null;\n\n // Each coordinate: optional sign, integer part, optional fraction — tight enough\n // to round-trip negatives and reject malformed numbers (e.g. \"1.2.3\").\n const viewrectMatch = fragment.match(\n /viewrect=(-?\\d+(?:\\.\\d+)?),(-?\\d+(?:\\.\\d+)?),(-?\\d+(?:\\.\\d+)?),(-?\\d+(?:\\.\\d+)?)/,\n );\n if (!viewrectMatch) return null;\n\n return {\n page: parseInt(pageMatch[1], 10),\n x: parseFloat(viewrectMatch[1]),\n y: parseFloat(viewrectMatch[2]),\n width: parseFloat(viewrectMatch[3]),\n height: parseFloat(viewrectMatch[4]),\n };\n}\n","/**\n * The context of a span of a text: the text just before it and just after\n * it, as a `TextQuoteSelector` states them (`prefix`, `suffix`).\n *\n * `start` and `end` are offsets: they count Unicode code points from the\n * start of the content, and so does every length here (the 64 and the 32).\n * They are a string's own positions only in a text with no character outside\n * the Basic Multilingual Plane; a caller that slices a string converts them\n * with `textOffsets`. protocol/specs/src/annotations/reconcile-cases.json holds the\n * rule, under CONTEXT.\n *\n * @see https://www.w3.org/TR/annotation-model/#text-quote-selector\n */\n\nimport { between, textOffsets, type TextOffsets } from './text-offsets';\n\n// Code points, both.\nconst CONTEXT_LENGTH = 64;\nconst MAX_EXTENSION = 32;\n\n/** What a context is not lengthened past: white space, or one of eighteen marks. */\nconst BOUNDARY = /[\\s.,;:!?'\"()\\[\\]{}<>\\/\\\\]/;\n\n/**\n * Extract prefix and suffix context for a `TextQuoteSelector` from\n * source content: what `reconcile` gives a span it found, and what a caller\n * that makes a span another way (a selection in a viewer, say) gives its own.\n *\n * Extracts up to 64 code points before and after the selected text,\n * extending by up to 32 more to reach a word boundary so the\n * prefix/suffix is meaningful context rather than mid-word fragments.\n *\n * `start` and `end` are offsets: they count code points from the start of\n * `content`.\n */\nexport function extractContext(\n content: string,\n start: number,\n end: number,\n): { prefix?: string; suffix?: string } {\n return contextOf(content, textOffsets(content), start, end);\n}\n\n/** `extractContext`, given the content's conversions: a caller with several spans of one content makes them once. */\nexport function contextOf(\n content: string,\n offsets: TextOffsets,\n start: number,\n end: number,\n): { prefix?: string; suffix?: string } {\n const result: { prefix?: string; suffix?: string } = {};\n\n if (start > 0) {\n let prefixStart = Math.max(0, start - CONTEXT_LENGTH);\n let extensionCount = 0;\n while (prefixStart > 0 && extensionCount < MAX_EXTENSION) {\n if (\n BOUNDARY.test(between(content, offsets, prefixStart - 1, prefixStart))\n )\n break;\n prefixStart--;\n extensionCount++;\n }\n result.prefix = between(content, offsets, prefixStart, start);\n }\n\n if (end < offsets.length) {\n let suffixEnd = Math.min(offsets.length, end + CONTEXT_LENGTH);\n let extensionCount = 0;\n while (suffixEnd < offsets.length && extensionCount < MAX_EXTENSION) {\n if (BOUNDARY.test(between(content, offsets, suffixEnd, suffixEnd + 1)))\n break;\n suffixEnd++;\n extensionCount++;\n }\n result.suffix = between(content, offsets, end, suffixEnd);\n }\n\n return result;\n}\n","/**\n * The annotation builders: what turns the words a model quoted of a text into\n * annotations to commit.\n *\n * - `reconcile` finds the quoted words in the text;\n * - `annotationOfSpan` builds the annotation of a span of a text, or of a\n * PDF's anchored text;\n * - `annotationOfResource` builds an annotation of a resource as a whole.\n *\n * Every SDK has these three, and no other builder:\n * protocol/specs/src/annotations/builder-cases.json names them and holds the two that\n * build, and protocol/specs/src/annotations/reconcile-cases.json holds `reconcile`.\n *\n * A text is a plain string. `start` and `end` are offsets: they count Unicode\n * code points from the start of the text, and so does every length a rule\n * here states. Each function makes the text's conversions for itself\n * (`textOffsets`), so no caller is asked for one.\n *\n * @see https://www.w3.org/TR/annotation-model/#text-quote-selector\n */\n\nimport { annotationIdFor } from './annotation-id';\nimport type { Annotation } from './annotation-types';\nimport type { Motivation } from './branded-types';\nimport { XynologError } from './errors';\nimport { findBestTextMatch, buildContentCache } from './fuzzy-anchor';\nimport type { SpanRefusal } from './error-codes';\nimport type { ResourceId } from './identifiers';\nimport type {\n QuotedText,\n ReconciledSpan,\n Selector,\n TextSpan,\n} from './payload-types';\nimport { locate, type AnchoredText } from './pdf-anchoring';\nimport { createFragmentSelector } from './pdf-coordinates';\nimport { contextOf } from './text-context';\nimport {\n between,\n occurrencesOf,\n textOffsets,\n type TextOffsets,\n} from './text-offsets';\nimport type { components } from './types';\n\ntype Agent = components['schemas']['Agent'];\ntype TextQuoteSelector = components['schemas']['TextQuoteSelector'];\n\n/**\n * A span `annotationOfSpan` refused. `code` names the refusal: one of the\n * `spanRefusal` codes of protocol/specs/src/errors/codes.json, the table every SDK's\n * codes are generated from.\n */\nexport class SpanRefusedError extends XynologError {\n declare code: SpanRefusal;\n\n constructor(message: string, code: SpanRefusal) {\n super(message, code);\n this.name = 'SpanRefusedError';\n }\n}\n\n/** A stretch of the text, as two offsets: from `start` up to but not including `end`. */\ninterface Place {\n start: number;\n end: number;\n}\n\n// Minimum window of the text compared against a quoted prefix or suffix when\n// choosing among several places, in code points. The actual window grows to\n// the length of the quoted prefix or suffix when that is longer: a model is\n// invited to quote up to 64 code points of context, and a fixed window of 32\n// can't `endsWith`/`includes` a string of 64, which would silently defeat the\n// choice for exactly the long, distinctive contexts that choose best.\nconst DISAMBIGUATION_MIN_WINDOW = 32;\n\n/**\n * Find the words a model quoted in a text. The answer is a span whose `start`\n * and `end` bracket `exact` in the text, and whose `exact`, `prefix` and\n * `suffix` are the text's own: nothing the model said is carried into it, so\n * what an annotation built on it states is verifiable against the text.\n *\n * `null` when `quoted.exact` is empty or only white space, or is nowhere in\n * the text, even loosely. A caller drops the proposal, and says so.\n */\nexport function reconcile(\n text: string,\n quoted: QuotedText,\n): ReconciledSpan | null {\n const { exact } = quoted;\n // Nothing, or only white space, is no words to find.\n if (exact.trim() === '') return null;\n\n const offsets = textOffsets(text);\n\n /** What the model said stands beside `exact`, when that is more than white space: a hint of where. */\n const hint = (given: string | undefined): string | undefined =>\n given === undefined || given.trim() === '' ? undefined : given;\n const prefixHint = hint(quoted.prefix);\n const suffixHint = hint(quoted.suffix);\n\n // Size the comparison window to the hint (with a floor), so a prefix of 64\n // code points is matched against at least 64 of the text — a fixed smaller\n // window can't `endsWith`/`includes` a longer string.\n const prefixWindow = Math.max(\n DISAMBIGUATION_MIN_WINDOW,\n prefixHint === undefined ? 0 : textOffsets(prefixHint).length,\n );\n const suffixWindow = Math.max(\n DISAMBIGUATION_MIN_WINDOW,\n suffixHint === undefined ? 0 : textOffsets(suffixHint).length,\n );\n\n /** Whether the text around a place carries every hint given. */\n const fits = ({ start, end }: Place): boolean => {\n const before = between(\n text,\n offsets,\n Math.max(0, start - prefixWindow),\n start,\n );\n const after = between(\n text,\n offsets,\n end,\n Math.min(offsets.length, end + suffixWindow),\n );\n const prefixOk =\n prefixHint === undefined ||\n before.endsWith(prefixHint) ||\n before.includes(prefixHint.trim());\n const suffixOk =\n suffixHint === undefined ||\n after.startsWith(suffixHint) ||\n after.includes(suffixHint.trim());\n return prefixOk && suffixOk;\n };\n\n /** The first of several places that the hints pick: none when no hint was given, or no place fits. */\n const hinted = (places: Place[]): Place | undefined =>\n prefixHint === undefined && suffixHint === undefined\n ? undefined\n : places.find(fits);\n\n /** A place as a span: its words and its context are the text's own. */\n const spanAt = ({ start, end }: Place): TextSpan => {\n const context = contextOf(text, offsets, start, end);\n return {\n start,\n end,\n // The text's words, not the model's version of them — the model may\n // have written slightly different characters (smart or straight\n // quotes, say) and what is stored is what is verifiable.\n exact: between(text, offsets, start, end),\n ...(context.prefix !== undefined ? { prefix: context.prefix } : {}),\n ...(context.suffix !== undefined ? { suffix: context.suffix } : {}),\n };\n };\n\n // Find every place the text has `exact`, character for character: each as long as `exact` is in code points.\n const length = textOffsets(exact).length;\n const occurrences: Place[] = occurrencesOf(text, offsets, exact).map(\n (start) => ({ start, end: start + length }),\n );\n\n if (occurrences.length === 1) {\n return { ...spanAt(occurrences[0]!), anchorMethod: 'unique-match' };\n }\n\n if (occurrences.length > 1) {\n const chosen = hinted(occurrences);\n if (chosen !== undefined)\n return { ...spanAt(chosen), anchorMethod: 'context-recovered' };\n\n // No context chose. Fall back to the first place and flag it for audit:\n // with no hint of where, there is no better signal at this stage, and a\n // caller that sees `first-of-many` should log it loudly so an operator\n // can correct an annotation anchored at the wrong one.\n return { ...spanAt(occurrences[0]!), anchorMethod: 'first-of-many' };\n }\n\n // The text has `exact` nowhere. Try the looser searches (white space and\n // the forms of quotation marks and dashes disregarded, letter case\n // disregarded, edit distance within a twentieth of the length). Of several\n // places one of them finds, the hints choose as they do among the places\n // the text has `exact`, and the first is taken when they choose none.\n const found = findBestTextMatch(text, exact, buildContentCache(text));\n if (!found) return null;\n return {\n ...spanAt(hinted(found.places) ?? found.places[0]!),\n anchorMethod: 'fuzzy-match',\n matchQuality: found.matchQuality,\n };\n}\n\n/** What a refusal is said of: the annotation that was to be built. */\ninterface Refused {\n resourceId: ResourceId;\n motivation: Motivation;\n}\n\nfunction refuse(\n code: SpanRefusal,\n why: string,\n { resourceId, motivation }: Refused,\n): never {\n throw new SpanRefusedError(\n `annotationOfSpan refused a span (${code}): ${why}, for resource ${resourceId}, motivation ${motivation}`,\n code,\n );\n}\n\n/** Whether two numbers are the offsets of a stretch of a text of `length` code points: whole, in order, inside it. */\nconst isStretchOf = (length: number, start: number, end: number): boolean =>\n Number.isInteger(start) &&\n Number.isInteger(end) &&\n 0 <= start &&\n start <= end &&\n end <= length;\n\n/**\n * Refuse a span that is no span of the text: one given backwards, one that\n * runs past the end, one that starts below zero, one stated in fractions.\n * Whatever words lie between its two numbers, it names no stretch of the\n * text, and an annotation built on it would state offsets that anchor nothing.\n */\nfunction holdSpanToText(\n offsets: TextOffsets,\n { start, end }: TextSpan,\n of: Refused,\n): void {\n if (isStretchOf(offsets.length, start, end)) return;\n refuse(\n 'span-out-of-range',\n `offsets ${start} to ${end} are not a span of a text of ${offsets.length} code points`,\n of,\n );\n}\n\n/**\n * Refuse an anchored text one of whose items is no stretch of it. The items\n * are what say where the text is on a page, and a rectangle is made from an\n * item's own offsets: one that is no stretch of the text shows that the items\n * do not index it, and a rectangle made from any of them may be drawn in the\n * wrong place. So every item is held to the text, whether the span touches\n * it or not, and before the span is. A producer that counts offsets another\n * way than the text is counted is what this finds: its last items run past\n * the end, and every item before them is shifted where nothing would show it.\n */\nfunction holdItemsToText(\n anchored: AnchoredText,\n offsets: TextOffsets,\n of: Refused,\n): void {\n const stray = anchored.items.findIndex(\n (item) => !isStretchOf(offsets.length, item.start, item.end),\n );\n if (stray === -1) return;\n const { start, end } = anchored.items[stray]!;\n refuse(\n 'item-out-of-range',\n `item ${stray} of the anchored text is offsets ${start} to ${end}, which is no stretch of a text of ${offsets.length} code points`,\n of,\n );\n}\n\n/**\n * Refuse a prefix or a suffix that is not what the text has on that side of\n * the span: as many code points of it as the prefix or suffix has itself, or\n * all there are if fewer. `span` is a span of the text (`holdSpanToText`).\n */\nfunction holdContextToText(\n text: string,\n offsets: TextOffsets,\n span: TextSpan,\n of: Refused,\n): void {\n if (span.prefix !== undefined) {\n const from = Math.max(0, span.start - textOffsets(span.prefix).length);\n if (between(text, offsets, from, span.start) !== span.prefix) {\n refuse(\n 'prefix-mismatch',\n `the prefix is not the text just before offset ${span.start}`,\n of,\n );\n }\n }\n if (span.suffix !== undefined) {\n const to = Math.min(\n offsets.length,\n span.end + textOffsets(span.suffix).length,\n );\n if (between(text, offsets, span.end, to) !== span.suffix) {\n refuse(\n 'suffix-mismatch',\n `the suffix is not the text just after offset ${span.end}`,\n of,\n );\n }\n }\n}\n\n/**\n * The selectors of a span of a text: its position, and its quote. The span\n * is first held to the text, then its words, then its context.\n */\nfunction selectorsInText(\n text: string,\n span: TextSpan,\n of: Refused,\n): Selector[] {\n const offsets = textOffsets(text);\n holdSpanToText(offsets, span, of);\n if (between(text, offsets, span.start, span.end) !== span.exact) {\n refuse(\n 'exact-mismatch',\n `the text from offset ${span.start} to offset ${span.end}, which count code points, is not exact`,\n of,\n );\n }\n holdContextToText(text, offsets, span, of);\n return [\n { type: 'TextPositionSelector', start: span.start, end: span.end },\n quoteOf(span),\n ];\n}\n\n/**\n * The selectors of a span of a PDF's anchored text: one `FragmentSelector`\n * for each line the span is on (`locate` joins the items it overlaps into a\n * rectangle a line), and its quote. No `TextPositionSelector`: the anchored\n * text is derived from the PDF and is not its stored content, so an offset\n * into it is no durable anchor.\n *\n * The rectangles are of whole items (runs of words), so the text those items\n * cover must *have* `exact` in it, white space apart: containment, not\n * equality. A span that overlaps no item has no rectangle, and is refused\n * under a name of its own: merged with the other, it would send whoever\n * reads the refusal to a comparison of words that never ran.\n *\n * The anchored text is held to itself before anything else (`holdItemsToText`).\n * Then the span is held to it, and its prefix and suffix after, exactly as a\n * span of a text is held to its text: the quote this writes is what\n * re-anchoring reads, on a PDF as on a text.\n */\nfunction selectorsInPdf(\n anchored: AnchoredText,\n span: TextSpan,\n of: Refused,\n): Selector[] {\n const offsets = textOffsets(anchored.text);\n holdItemsToText(anchored, offsets, of);\n holdSpanToText(offsets, span, of);\n\n // `locate` answers both the rectangles and the items they were made from:\n // the covered text is read from those, with no second pass over the items.\n const { rects, overlap } = locate(anchored, span.start, span.end);\n const covered = overlap.length\n ? between(\n anchored.text,\n offsets,\n Math.min(...overlap.map((item) => item.start)),\n Math.max(...overlap.map((item) => item.end)),\n )\n : '';\n const collapsed = (words: string): string =>\n words.replace(/\\s+/g, ' ').trim();\n if (rects.length === 0) {\n refuse(\n 'nothing-located',\n `no rectangle is located for offsets ${span.start} to ${span.end}`,\n of,\n );\n }\n if (!collapsed(covered).includes(collapsed(span.exact))) {\n refuse(\n 'exact-not-covered',\n 'the text the span covers does not have exact in it',\n of,\n );\n }\n holdContextToText(anchored.text, offsets, span, of);\n\n return [\n ...rects.map((rect) => ({\n type: 'FragmentSelector' as const,\n conformsTo: 'http://tools.ietf.org/rfc/rfc3778',\n value: createFragmentSelector(rect),\n })),\n quoteOf(span),\n ];\n}\n\n/** A span's quote: its words, and its context where it has any. */\nfunction quoteOf(span: TextSpan): TextQuoteSelector {\n return {\n type: 'TextQuoteSelector',\n exact: span.exact,\n ...(span.prefix ? { prefix: span.prefix } : {}),\n ...(span.suffix ? { suffix: span.suffix } : {}),\n };\n}\n\n/**\n * Where a span is, for its annotation's id. The words are in it, not just\n * the offsets: after the text changes the same offsets cover other words, and\n * that is another annotation. It is made the same way for a text and for a\n * PDF: a PDF's rectangles are derived from these offsets, so hashing them too\n * would tell no two annotations apart, and would make an id depend on a\n * layout a text cannot reproduce.\n */\nfunction anchorOf(span: TextSpan): string {\n return `${span.start}:${span.end}:${span.exact}`;\n}\n\n/**\n * Build the annotation of a span: of a text when `text` is given, of a PDF\n * when its `anchored` text is. The span is one `reconcile` found, or any\n * other the caller can state.\n *\n * The annotation's selectors are made from the span, and its `id` is derived\n * from what it is (the resource, the motivation, the body and where the span\n * is), so building the same annotation again builds the same id, and\n * committing it again writes nothing new. `generator` says what made it;\n * who asked for it is no member of an annotation a builder makes, and is\n * derived where the annotation is recorded. `created` is the moment it is\n * built.\n *\n * `body` is one body or a list of them, or nothing: an annotation whose\n * motivation alone says what it means (a highlight) has none.\n *\n * Throws `SpanRefusedError` for a span that is not the text's, and for any\n * span of a PDF whose anchored text has an item that is no stretch of it: its\n * `code` is the refusal, and the first check that fails names it.\n */\nexport function annotationOfSpan(\n of: {\n resourceId: ResourceId;\n generator: Agent;\n motivation: Motivation;\n span: TextSpan;\n body?: Annotation['body'];\n } & (\n | { text: string; anchored?: never }\n | { anchored: AnchoredText; text?: never }\n ),\n): Annotation {\n const { resourceId, generator, motivation, span, body } = of;\n const selector =\n of.text !== undefined\n ? selectorsInText(of.text, span, of)\n : selectorsInPdf(of.anchored, span, of);\n return {\n '@context': 'http://www.w3.org/ns/anno.jsonld',\n type: 'Annotation',\n id: annotationIdFor({\n resourceId,\n motivation,\n anchor: anchorOf(span),\n body,\n }),\n motivation,\n generator,\n created: new Date().toISOString(),\n target: { type: 'SpecificResource', source: resourceId, selector },\n ...(body !== undefined ? { body } : {}),\n };\n}\n\n/**\n * Build an annotation of a resource as a whole: its target is the resource,\n * with no selector. The link from a source to what was generated from it is\n * one.\n *\n * Its `id` is derived as a span's annotation's is, from the resource, the\n * motivation and the body: it is anchored nowhere on the resource, and its\n * anchor is the empty string. `generator` says what made it, when something\n * is given; `created` is the moment it is built.\n */\nexport function annotationOfResource(of: {\n resourceId: ResourceId;\n motivation: Motivation;\n generator?: Agent;\n body?: Annotation['body'];\n}): Annotation {\n const { resourceId, motivation, generator, body } = of;\n return {\n '@context': 'http://www.w3.org/ns/anno.jsonld',\n type: 'Annotation',\n id: annotationIdFor({ resourceId, motivation, anchor: '', body }),\n motivation,\n ...(generator !== undefined ? { generator } : {}),\n created: new Date().toISOString(),\n target: { source: resourceId },\n ...(body !== undefined ? { body } : {}),\n };\n}\n","/**\n * Annotation and Selector Utilities\n *\n * Pure TypeScript utilities for working with W3C Web Annotations.\n * No React dependencies - safe to use in any JavaScript environment.\n *\n * Body is either empty array (stub) or single SpecificResource (resolved)\n * Body can be array of TextualBody (tagging) + SpecificResource (linking)\n * Target can be a resource's id or an object with source and optional selector\n */\n\nimport type { components } from './types';\nimport type { Selector } from './payload-types';\nimport type { Annotation } from './annotation-types';\nimport type { ResourceId } from './identifiers';\n\ntype HighlightAnnotation = Annotation;\ntype ReferenceAnnotation = Annotation;\ntype TextPositionSelector = components['schemas']['TextPositionSelector'];\ntype TextQuoteSelector = components['schemas']['TextQuoteSelector'];\ntype SvgSelector = components['schemas']['SvgSelector'];\ntype FragmentSelector = components['schemas']['FragmentSelector'];\n\n// Re-export selector types for convenience\nexport type {\n TextPositionSelector,\n TextQuoteSelector,\n SvgSelector,\n FragmentSelector,\n Selector,\n};\n\n/**\n * Get TextPositionSelector from a selector (single or array)\n */\nexport function getTextPositionSelector(\n selector: Selector | Selector[] | undefined,\n): TextPositionSelector | null {\n if (!selector) return null;\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find((s) => s.type === 'TextPositionSelector');\n if (!found) return null;\n return found.type === 'TextPositionSelector' ? found : null;\n}\n\n/**\n * Get SvgSelector from a selector (single or array)\n */\nexport function getSvgSelector(\n selector: Selector | Selector[] | undefined,\n): SvgSelector | null {\n if (!selector) return null;\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find((s) => s.type === 'SvgSelector');\n if (!found) return null;\n return found.type === 'SvgSelector' ? found : null;\n}\n\n/**\n * Get FragmentSelector from a selector (single or array)\n */\nexport function getFragmentSelector(\n selector: Selector | Selector[] | undefined,\n): FragmentSelector | null {\n if (!selector) return null;\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find((s) => s.type === 'FragmentSelector');\n if (!found) return null;\n return found.type === 'FragmentSelector' ? found : null;\n}\n\n/** A body's items: none when there is no body, the one when it is a single item, each when it is a list. */\nfunction bodyItems(body: Annotation['body']) {\n return body === undefined ? [] : Array.isArray(body) ? body : [body];\n}\n\n/**\n * Get the source from an annotation body (null if stub)\n * Search for SpecificResource in body array\n */\nexport function getBodySource(body: Annotation['body']): ResourceId | null {\n for (const item of bodyItems(body)) {\n if (item.type === 'SpecificResource') return item.source;\n }\n return null;\n}\n\n/**\n * Check if body is resolved (has a source)\n * Check for SpecificResource in body array\n */\nexport function isBodyResolved(body: Annotation['body']): boolean {\n return getBodySource(body) !== null;\n}\n\n/**\n * The resource a target names (handles both string and object forms)\n */\nexport function getTargetSource(target: Annotation['target']): ResourceId {\n if (typeof target === 'string') {\n return target;\n }\n return target.source;\n}\n\n/**\n * Get the selector from target (undefined if string or no selector)\n */\nexport function getTargetSelector(target: Annotation['target']) {\n if (typeof target === 'string') {\n return undefined;\n }\n return target.selector;\n}\n\n/**\n * Type guard to check if an annotation is a highlight\n */\nexport function isHighlight(\n annotation: Annotation,\n): annotation is HighlightAnnotation {\n return annotation.motivation === 'highlighting';\n}\n\n/**\n * Type guard to check if an annotation is a reference (linking)\n */\nexport function isReference(\n annotation: Annotation,\n): annotation is ReferenceAnnotation {\n return annotation.motivation === 'linking';\n}\n\n/**\n * Type guard to check if an annotation is an assessment\n */\nexport function isAssessment(annotation: Annotation): annotation is Annotation {\n return annotation.motivation === 'assessing';\n}\n\n/**\n * Type guard to check if an annotation is a comment\n */\nexport function isComment(annotation: Annotation): annotation is Annotation {\n return annotation.motivation === 'commenting';\n}\n\n/**\n * Type guard to check if an annotation is a tag\n */\nexport function isTag(annotation: Annotation): annotation is Annotation {\n return annotation.motivation === 'tagging';\n}\n\n/**\n * Extract comment text from a comment annotation's body\n * @param annotation - The annotation to extract comment text from\n * @returns The comment text, or undefined if not a comment or no text found\n */\nexport function getCommentText(annotation: Annotation): string | undefined {\n if (!isComment(annotation)) return undefined;\n const body = Array.isArray(annotation.body)\n ? annotation.body[0]\n : annotation.body;\n if (body && 'value' in body) {\n return body.value;\n }\n return undefined;\n}\n\n/**\n * Type guard to check if a reference annotation is a stub (unresolved)\n * Stub if no SpecificResource in body array\n */\nexport function isStubReference(annotation: Annotation): boolean {\n return isReference(annotation) && !isBodyResolved(annotation.body);\n}\n\n/**\n * Type guard to check if a reference annotation is resolved\n * Resolved if SpecificResource exists in body array\n */\nexport function isResolvedReference(\n annotation: Annotation,\n): annotation is ReferenceAnnotation {\n return isReference(annotation) && isBodyResolved(annotation.body);\n}\n\n/**\n * The entity types an annotation states: the text of each body that tags, in\n * the order its body has them. A body with no text states none.\n *\n * Takes anything with an annotation's `body`: one item, a list, or none\n * (a highlight has none).\n */\nexport function getEntityTypes(annotation: {\n body?: Annotation['body'];\n}): string[] {\n const types: string[] = [];\n for (const item of bodyItems(annotation.body)) {\n if (\n item.type === 'TextualBody' &&\n item.purpose === 'tagging' &&\n item.value.length > 0\n ) {\n types.push(item.value);\n }\n }\n return types;\n}\n\n/** The text of the first body that states it for `purpose`. */\nfunction textFor(\n body: Annotation['body'],\n purpose: 'tagging' | 'classifying',\n): string | undefined {\n for (const item of bodyItems(body)) {\n if (item.type === 'TextualBody' && item.purpose === purpose)\n return item.value;\n }\n return undefined;\n}\n\n/**\n * A tag's category (e.g. \"Issue\", \"Rule\"): the text of its body that tags.\n * Nothing for an annotation that is not a tag.\n */\nexport function getTagCategory(annotation: Annotation): string | undefined {\n return isTag(annotation) ? textFor(annotation.body, 'tagging') : undefined;\n}\n\n/**\n * The id of the schema a tag's category is of (e.g. \"legal-irac\"): the text\n * of its body that classifies. Nothing for an annotation that is not a tag.\n */\nexport function getTagSchemaId(annotation: Annotation): string | undefined {\n return isTag(annotation)\n ? textFor(annotation.body, 'classifying')\n : undefined;\n}\n\n// =============================================================================\n// SELECTOR UTILITIES\n// =============================================================================\n\n/**\n * Get the exact text from a selector (single or array)\n *\n * When selector is an array, tries to find a TextQuoteSelector (which has exact text).\n * TextPositionSelector does not have exact text, only offsets, in code points.\n * Handles undefined selector (when target is a string IRI with no selector)\n */\nexport function getExactText(\n selector: Selector | Selector[] | undefined,\n): string {\n if (!selector) {\n return ''; // No selector means entire resource\n }\n const selectors = Array.isArray(selector) ? selector : [selector];\n\n // Try to find TextQuoteSelector (has exact text)\n const quoteSelector = selectors.find(\n (s) => s.type === 'TextQuoteSelector',\n ) as TextQuoteSelector | undefined;\n if (quoteSelector) {\n return quoteSelector.exact;\n }\n\n // No TextQuoteSelector found\n return '';\n}\n\n/**\n * Get the exact text from an annotation's target selector\n * Uses getTargetSelector helper to safely get selector\n */\nexport function getAnnotationExactText(annotation: Annotation): string {\n const selector = getTargetSelector(annotation.target);\n return getExactText(selector as Selector | Selector[] | undefined);\n}\n\n/**\n * Get TextQuoteSelector from a selector (single or array)\n *\n * Returns the first TextQuoteSelector found, or null if none exists.\n */\nexport function getTextQuoteSelector(\n selector: Selector | Selector[],\n): TextQuoteSelector | null {\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find((s) => s.type === 'TextQuoteSelector');\n if (!found) return null;\n return found.type === 'TextQuoteSelector' ? found : null;\n}\n","// ⚠ GENERATED FILE — do not edit.\n//\n// Authority: protocol/specs/src/media-types/registry.json\n// Regenerate: make generate (codegen/lib/media_types/media_types.ml)\n\nexport type RenderMode = 'text' | 'image' | 'pdf' | 'none';\nexport type AnchoringModel = 'text-selector' | 'spatial' | 'none';\nexport type TextSource = 'decode' | 'pdf-text-layer' | 'none';\n\n/** What the system can do with a media type: a row of the registry. */\nexport interface MediaTypeCapabilities {\n /** A file extension, with its dot. */\n extension: string;\n /** The name a person reads. */\n label: string;\n /** The viewer a reader mounts. */\n render: RenderMode;\n /** The annotation model. */\n anchoring: AnchoringModel;\n /** Where its text comes from. */\n textSource: TextSource;\n /** Whether the compose editor offers it. */\n authorable: boolean;\n /** Whether it may be uploaded. */\n uploadable: boolean;\n /**\n * Whether the generation worker can produce it as a yield artifact: the gate\n * for `outputMediaType`, which refuses any other.\n */\n generatable: boolean;\n}\n\n/** A row of the registry, by media type, in the registry's order. */\nexport const MEDIA_TYPE_ROWS = {\n 'text/markdown': {\n extension: '.md',\n label: 'Markdown',\n render: 'text',\n anchoring: 'text-selector',\n textSource: 'decode',\n authorable: true,\n uploadable: true,\n generatable: true,\n },\n 'text/plain': {\n extension: '.txt',\n label: 'Plain Text',\n render: 'text',\n anchoring: 'text-selector',\n textSource: 'decode',\n authorable: true,\n uploadable: true,\n generatable: true,\n },\n 'text/html': {\n extension: '.html',\n label: 'HTML',\n render: 'text',\n anchoring: 'text-selector',\n textSource: 'decode',\n authorable: true,\n uploadable: true,\n generatable: false,\n },\n 'application/json': {\n extension: '.json',\n label: 'JSON',\n render: 'text',\n anchoring: 'text-selector',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/png': {\n extension: '.png',\n label: 'PNG image',\n render: 'image',\n anchoring: 'spatial',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/jpeg': {\n extension: '.jpg',\n label: 'JPEG image',\n render: 'image',\n anchoring: 'spatial',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/pdf': {\n extension: '.pdf',\n label: 'PDF',\n render: 'pdf',\n anchoring: 'spatial',\n textSource: 'pdf-text-layer',\n authorable: false,\n uploadable: true,\n generatable: true,\n },\n 'text/css': {\n extension: '.css',\n label: 'CSS',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/csv': {\n extension: '.csv',\n label: 'CSV',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/xml': {\n extension: '.xml',\n label: 'XML',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/xml': {\n extension: '.xml',\n label: 'XML',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/yaml': {\n extension: '.yaml',\n label: 'YAML',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/x-yaml': {\n extension: '.yaml',\n label: 'YAML',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/javascript': {\n extension: '.js',\n label: 'JavaScript',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/javascript': {\n extension: '.js',\n label: 'JavaScript',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-typescript': {\n extension: '.ts',\n label: 'TypeScript',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/typescript': {\n extension: '.ts',\n label: 'TypeScript',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-python': {\n extension: '.py',\n label: 'Python source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-java': {\n extension: '.java',\n label: 'Java source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-c': {\n extension: '.c',\n label: 'C source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-c++': {\n extension: '.cpp',\n label: 'C++ source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-csharp': {\n extension: '.cs',\n label: 'C# source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-go': {\n extension: '.go',\n label: 'Go source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-rust': {\n extension: '.rs',\n label: 'Rust source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-ruby': {\n extension: '.rb',\n label: 'Ruby source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-php': {\n extension: '.php',\n label: 'PHP source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-swift': {\n extension: '.swift',\n label: 'Swift source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-kotlin': {\n extension: '.kt',\n label: 'Kotlin source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-shell': {\n extension: '.sh',\n label: 'Shell script',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/msword': {\n extension: '.doc',\n label: 'Word document (legacy)',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': {\n extension: '.docx',\n label: 'Word document',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/vnd.ms-excel': {\n extension: '.xls',\n label: 'Excel spreadsheet (legacy)',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': {\n extension: '.xlsx',\n label: 'Excel spreadsheet',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/vnd.ms-powerpoint': {\n extension: '.ppt',\n label: 'PowerPoint presentation (legacy)',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation': {\n extension: '.pptx',\n label: 'PowerPoint presentation',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/zip': {\n extension: '.zip',\n label: 'ZIP archive',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/gzip': {\n extension: '.gz',\n label: 'Gzip archive',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/x-tar': {\n extension: '.tar',\n label: 'TAR archive',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/x-7z-compressed': {\n extension: '.7z',\n label: '7z archive',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/octet-stream': {\n extension: '.bin',\n label: 'Binary',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/wasm': {\n extension: '.wasm',\n label: 'WebAssembly module',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/gif': {\n extension: '.gif',\n label: 'GIF image',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/webp': {\n extension: '.webp',\n label: 'WebP image',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/svg+xml': {\n extension: '.svg',\n label: 'SVG image',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/bmp': {\n extension: '.bmp',\n label: 'BMP image',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/tiff': {\n extension: '.tiff',\n label: 'TIFF image',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/x-icon': {\n extension: '.ico',\n label: 'Icon',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'video/mp4': {\n extension: '.mp4',\n label: 'MP4 video',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'video/mpeg': {\n extension: '.mpeg',\n label: 'MPEG video',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'video/webm': {\n extension: '.webm',\n label: 'WebM video',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'video/ogg': {\n extension: '.ogv',\n label: 'Ogg video',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'video/quicktime': {\n extension: '.mov',\n label: 'QuickTime video',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'video/x-msvideo': {\n extension: '.avi',\n label: 'AVI video',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'audio/mpeg': {\n extension: '.mp3',\n label: 'MP3 audio',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'audio/wav': {\n extension: '.wav',\n label: 'WAV audio',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'audio/ogg': {\n extension: '.ogg',\n label: 'Ogg audio',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'audio/webm': {\n extension: '.webm',\n label: 'WebM audio',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'audio/aac': {\n extension: '.aac',\n label: 'AAC audio',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'audio/flac': {\n extension: '.flac',\n label: 'FLAC audio',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'font/woff': {\n extension: '.woff',\n label: 'WOFF font',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'font/woff2': {\n extension: '.woff2',\n label: 'WOFF2 font',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'font/ttf': {\n extension: '.ttf',\n label: 'TrueType font',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'font/otf': {\n extension: '.otf',\n label: 'OpenType font',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n} as const;\n\n/** Other spellings of an extension, each with the one a row states. */\nexport const EXTENSION_ALIASES: Readonly<Record<string, string>> = {\n '.markdown': '.md',\n '.htm': '.html',\n '.jpeg': '.jpg',\n '.yml': '.yaml',\n};\n","/**\n * Media-type registry for Xynolog\n *\n * One supported-types list, capability-tiered, keyed by the spec's\n * SupportedMediaType enum. The rows are protocol/specs/src/media-types/registry.json's,\n * generated; this module is the questions asked of them. Admission (registry\n * membership) is the create/yield gate: every member is storable, nameable,\n * and uploadable.\n * The curated capabilities say what more the system can do with a type:\n *\n * - `render` — which viewer the UI mounts ('none' → metadata + download)\n * - `anchoring` — which annotation model applies: character-offset text\n * selectors vs spatial geometry (PDFs are spatial)\n * - `textSource` — WHERE a type's text comes from: decoded from its own bytes,\n * or derived by reading them ('none' → skip embedding, never\n * mojibake)\n * - `authorable` — offered in the compose editor's format dropdown\n * - `uploadable` — big tent: true for every registry member\n * - `generatable` — the generation worker can produce it as a yield artifact\n *\n * Capabilities are orthogonal strategies, not a ladder: images render but\n * yield no text; PDFs yield text but aren't authorable. A \"tier\" is a\n * derived reading, not a stored fact.\n *\n * Questions ANSWERABLE from those rows get a helper, never a row of their own —\n * whether a type can carry annotations is read off `anchoring`, and a second stored field would be a fact\n * that can contradict the one it was derived from.\n *\n * Import-leniency invariant: restore/import preserves archive mediaTypes\n * verbatim, so \"every stored mediaType is registry-valid\" holds only for\n * content that entered through the validated create/yield gate. No code\n * reading a stored mediaType may assume `capabilitiesOf()` succeeds — the\n * `undefined` branch is mandatory wherever stored types are read.\n */\n\nimport type { components } from './types';\nimport {\n EXTENSION_ALIASES,\n MEDIA_TYPE_ROWS,\n type AnchoringModel,\n type MediaTypeCapabilities,\n type RenderMode,\n type TextSource,\n} from './media-type-registry';\n\nexport type SupportedMediaType = components['schemas']['SupportedMediaType'];\nexport type { AnchoringModel, MediaTypeCapabilities, RenderMode, TextSource };\n\n/**\n * The registry: protocol/specs/src/media-types/registry.json, which every SDK\n * generates from. `satisfies Record<SupportedMediaType, …>` holds the table to\n * the spec's enum in this language too: a type in one and not the other is a\n * compile error here, as it is a refusal in the generator.\n *\n * Row order matters for `mediaTypeForExtension`: extension collisions\n * (.xml, .yaml, .js, .ts, .webm) resolve to the first row declaring the\n * extension.\n */\nexport const MEDIA_TYPES = MEDIA_TYPE_ROWS satisfies Record<\n SupportedMediaType,\n MediaTypeCapabilities\n>;\n\n// String-indexable view for lookups with runtime strings.\nconst REGISTRY: Readonly<Record<string, MediaTypeCapabilities>> = MEDIA_TYPES;\n\n/**\n * Strip parameters (\"; charset=...\") and normalize case.\n */\nexport function baseMediaType(format: string): string {\n return format.split(';')[0]!.trim().toLowerCase();\n}\n\n/**\n * Registry membership — the admission gate. Exact match: callers pass a\n * base type (see `baseMediaType`); strings carrying parameters are not\n * members.\n */\nexport function isSupportedMediaType(\n format: string,\n): format is SupportedMediaType {\n return Object.hasOwn(MEDIA_TYPES, format);\n}\n\n/** Capabilities for a format (parameters tolerated), or undefined on registry miss. */\nexport function capabilitiesOf(\n format: string,\n): MediaTypeCapabilities | undefined {\n return REGISTRY[baseMediaType(format)];\n}\n\n/**\n * The clone-format gate: a clone opens in the compose editor, so authorable\n * sources keep their base media type and everything else falls back to\n * text/plain. Lives beside the registry it reads; the SDK applies it when\n * deriving a clone upload's format and the CloneTokenManager's tests pin it.\n */\nexport function cloneFormat(\n sourceMediaType: string | undefined,\n): SupportedMediaType {\n const base = baseMediaType(sourceMediaType ?? 'text/plain');\n return isSupportedMediaType(base) && capabilitiesOf(base)?.authorable\n ? base\n : 'text/plain';\n}\n\n/**\n * Lenient extension lookup for naming foreign/imported content: '.dat' on\n * registry miss. Exporters use this — a vocabulary change must never\n * refuse to name restored data.\n */\nexport function extensionForMediaType(format: string): string {\n return capabilitiesOf(format)?.extension ?? '.dat';\n}\n\nconst EXTENSION_TO_MEDIA_TYPE: ReadonlyMap<string, SupportedMediaType> =\n (() => {\n const map = new Map<string, SupportedMediaType>();\n for (const type of Object.keys(MEDIA_TYPES) as SupportedMediaType[]) {\n const ext = MEDIA_TYPES[type].extension;\n if (!map.has(ext)) map.set(ext, type);\n }\n return map;\n })();\n\n/**\n * Inverted registry: extension → media type, for the CLI and the upload\n * detection chain. Accepts 'md' or '.md', any case, and common alternate\n * spellings. Returns undefined for unknown extensions — detection chains\n * fall back to 'application/octet-stream' themselves.\n */\nexport function mediaTypeForExtension(\n ext: string,\n): SupportedMediaType | undefined {\n const lower = ext.trim().toLowerCase();\n const dotted = lower.startsWith('.') ? lower : `.${lower}`;\n return EXTENSION_TO_MEDIA_TYPE.get(EXTENSION_ALIASES[dotted] ?? dotted);\n}\n\n/**\n * WHERE a format's text comes from. Registry rows answer directly; on a registry\n * miss, base types under text/* decode (RFC 2046 guarantees the text top-level\n * type is textual — imported unregistered text subtypes embed too), everything\n * else is 'none'.\n *\n * The three answers are different operations, not degrees of one: `decode` is a\n * pure charset-aware `Buffer → string` anyone holding bytes may run;\n * `pdf-text-layer` parses and, failing that, OCRs — expensive, not deterministic\n * across engine versions, and runnable only by the process that persists its\n * output. Calling both \"extraction\" conflates them.\n */\nexport function textSourceOf(format: string): TextSource {\n const caps = capabilitiesOf(format);\n if (caps) return caps.textSource;\n return baseMediaType(format).startsWith('text/') ? 'decode' : 'none';\n}\n\n/**\n * Whether a text source yields positioned runs (`items`) — the geometry an\n * anchored-text artifact is made of. Only deriving does.\n *\n * Exhaustive over `TextSource` on purpose: a new strategy fails to compile\n * here until someone decides which side it is on, so the next media type cannot\n * default into the wrong answer. Private — `yieldsGeometryOf` is the surface.\n */\nconst GEOMETRY_BY_STRATEGY: Record<TextSource, boolean> = {\n decode: false,\n 'pdf-text-layer': true,\n none: false,\n};\n\n/**\n * WHETHER a type's extracted text carries geometry — page-positioned runs\n * rather than a bare string. Answers \"should an anchored-text artifact exist\n * for this resource?\" (reconcile's check for a lost artifact) and \"does this\n * type anchor spatially or by character offset?\".\n *\n * Derived from `textSource`, not stored: geometry is a property of the\n * STRATEGY. A boolean declared on each extractor implementation would be a\n * second fact that must agree with the strategy vocabulary, gated by nothing,\n * and a consumer asking about a media type would have to resolve an\n * implementation to get an answer.\n *\n * Lenient like `textSourceOf`. An unregistered `text/*` type decodes, and\n * decoding yields no geometry — so `false` here is a real answer rather than\n * a refusal.\n */\nexport function yieldsGeometryOf(format: string): boolean {\n return GEOMETRY_BY_STRATEGY[textSourceOf(format)];\n}\n\n/**\n * Whether a text source's output is DERIVED — produced by the Smelter and\n * persisted as an anchored-text artifact — rather than read by decoding the\n * bytes. Decoding is not deriving.\n *\n * Exhaustive over `TextSource` on purpose, like its geometry sibling: a new\n * strategy fails to compile here until someone declares its category.\n * Private — `derivesTextOf` is the surface.\n */\nconst DERIVED_TEXT_BY_STRATEGY: Record<TextSource, boolean> = {\n decode: false,\n 'pdf-text-layer': true,\n none: false,\n};\n\n/**\n * WHETHER a type's text is the Smelter's derived artifact instead of its own\n * decoded bytes — the read-side dispatch a text READER needs: derived text is\n * answered by the anchored-text read; decoded text by `decodeRepresentation`,\n * which refuses everything else.\n *\n * Deliberately a DISTINCT question from `yieldsGeometryOf`, though the\n * answers coincide for every strategy defined: a transcription strategy would\n * derive text with no geometry. The mechanism literal (`pdf-text-layer`) stays\n * confined to the extraction side, which genuinely dispatches per mechanism.\n */\nexport function derivesTextOf(format: string): boolean {\n return DERIVED_TEXT_BY_STRATEGY[textSourceOf(format)];\n}\n\nconst REGISTRY_KEYS = Object.keys(MEDIA_TYPES) as SupportedMediaType[];\n\n/** Types offered in the compose editor's format dropdown. */\nexport const AUTHORABLE_MEDIA_TYPES: readonly SupportedMediaType[] =\n REGISTRY_KEYS.filter((type) => MEDIA_TYPES[type].authorable);\n\n/** Types the generation worker can produce as a yield artifact — what the\n * Browser offers as a generation's `outputMediaType` reads this, not a local\n * table. */\nexport const GENERATABLE_MEDIA_TYPES: readonly SupportedMediaType[] =\n REGISTRY_KEYS.filter((type) => MEDIA_TYPES[type].generatable);\n","// ⚠ GENERATED FILE — do not edit.\n//\n// Authority: protocol/specs/src/text/encoding-cases.json\n// Regenerate: make generate (codegen/lib/encodings/typescript.ml)\n\n/** The encodings of the Encoding Standard whose labels every reader of a resource's text refuses, by their names in lower case. */\nexport const REFUSED_ENCODINGS: ReadonlySet<string> = new Set([\n 'big5',\n 'euc-jp',\n 'euc-kr',\n 'gb18030',\n 'gbk',\n 'iso-2022-jp',\n 'replacement',\n 'shift_jis',\n]);\n","/**\n * What text a resource's bytes are.\n *\n * The rule is protocol: protocol/contract/W3C-SELECTORS.md states it (\"The text\n * of a resource\"), and the two tables every reader runs hold it,\n * protocol/specs/src/text/decode-cases.json and protocol/specs/src/text/encoding-cases.json. It\n * is the MIME Sniffing Standard's reading of the content type and the\n * Encoding Standard's reading of the bytes, as a browser follows the two. An\n * offset counts the code points of this text, so every reader makes the same\n * text of the same bytes.\n *\n * The decoders are the platform's `TextDecoder`, which has the standard's\n * labels and its encodings. What it does not do is here: the content type's\n * parsing, the byte-order mark's deciding, and the refusal.\n */\n\nimport { XynologError } from './errors';\nimport { REFUSED_ENCODINGS } from './refused-encodings';\nimport type { TransportErrorCode } from './error-codes';\n\n/** HTTP white space: line feed, carriage return, tab and space. */\nconst isHttpWhiteSpace = (character: string): boolean =>\n character === '\\n' ||\n character === '\\r' ||\n character === '\\t' ||\n character === ' ';\n/** ASCII white space: HTTP white space and form feed. */\nconst isAsciiWhiteSpace = (character: string): boolean =>\n isHttpWhiteSpace(character) || character === '\\f';\n\n/** `text` without the characters at its start that `isSpace` holds of. */\nfunction withoutLeading(\n text: string,\n isSpace: (character: string) => boolean,\n): string {\n let start = 0;\n while (start < text.length && isSpace(text.charAt(start))) start += 1;\n return text.slice(start);\n}\n\n/** `text` without the characters at its end that `isSpace` holds of. */\nfunction withoutTrailing(\n text: string,\n isSpace: (character: string) => boolean,\n): string {\n let end = text.length;\n while (end > 0 && isSpace(text.charAt(end - 1))) end -= 1;\n return text.slice(0, end);\n}\n\n/** An HTTP token: what a type, a subtype and a parameter's name are made of. */\nconst HTTP_TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\n/** What a parameter's value may hold: a tab, U+0020 to U+007E, and U+0080 to U+00FF. */\nconst PARAMETER_VALUE = /^[\\t\\x20-\\x7e\\x80-\\xff]*$/;\n\nconst asciiLowerCase = (text: string): string =>\n text.replace(/[A-Z]/g, (letter) => letter.toLowerCase());\n\n/** The quoted string that opens at `start`, without its quotation marks, and where it ends. */\nfunction quotedString(\n input: string,\n start: number,\n): [value: string, end: number] {\n let position = start + 1;\n let value = '';\n for (;;) {\n const from = position;\n while (\n position < input.length &&\n input.charAt(position) !== '\"' &&\n input.charAt(position) !== '\\\\'\n )\n position += 1;\n value += input.slice(from, position);\n if (position >= input.length) break;\n const mark = input.charAt(position);\n position += 1;\n if (mark === '\"') break;\n // A backslash gives the character after it, and at the very end is itself.\n if (position >= input.length) {\n value += '\\\\';\n break;\n }\n value += input.charAt(position);\n position += 1;\n }\n return [value, position];\n}\n\n/**\n * The value of a content type's `charset` parameter, as the MIME Sniffing\n * Standard parses a MIME type: the first parameter of that name that is one.\n * `undefined` where there is none, and where the content type is no MIME\n * type.\n */\nfunction charsetParameter(contentType: string): string | undefined {\n const input = withoutTrailing(\n withoutLeading(contentType, isHttpWhiteSpace),\n isHttpWhiteSpace,\n );\n const slash = input.indexOf('/');\n if (slash === -1 || !HTTP_TOKEN.test(input.slice(0, slash))) return undefined;\n const semicolon = input.indexOf(';', slash);\n let position = semicolon === -1 ? input.length : semicolon;\n if (\n !HTTP_TOKEN.test(\n withoutTrailing(input.slice(slash + 1, position), isHttpWhiteSpace),\n )\n )\n return undefined;\n\n while (position < input.length) {\n position += 1; // past the semicolon\n while (position < input.length && isHttpWhiteSpace(input.charAt(position)))\n position += 1;\n const nameStart = position;\n while (\n position < input.length &&\n input.charAt(position) !== ';' &&\n input.charAt(position) !== '='\n )\n position += 1;\n const name = asciiLowerCase(input.slice(nameStart, position));\n if (position < input.length) {\n if (input.charAt(position) === ';') continue;\n position += 1; // past the equals sign\n }\n if (position >= input.length) break;\n\n let value: string;\n if (input.charAt(position) === '\"') {\n [value, position] = quotedString(input, position);\n while (position < input.length && input.charAt(position) !== ';')\n position += 1;\n } else {\n const valueStart = position;\n while (position < input.length && input.charAt(position) !== ';')\n position += 1;\n value = withoutTrailing(\n input.slice(valueStart, position),\n isHttpWhiteSpace,\n );\n if (value === '') continue;\n }\n if (name === 'charset' && PARAMETER_VALUE.test(value)) return value;\n }\n return undefined;\n}\n\n/**\n * The charset a media type states: its `charset` parameter as the MIME\n * Sniffing Standard parses a MIME type, in ASCII lower case and without the\n * ASCII white space around it. `utf-8` where it states none, or an empty\n * one.\n *\n * @example\n * extractCharset('text/plain; charset=ISO-8859-1') // 'iso-8859-1'\n * extractCharset('text/plain; charset=\"utf-16le\"') // 'utf-16le'\n * extractCharset('text/plain') // 'utf-8'\n */\nexport function extractCharset(mediaType: string): string {\n const stated = charsetParameter(mediaType);\n if (stated === undefined || stated === '') return 'utf-8';\n return asciiLowerCase(\n withoutTrailing(\n withoutLeading(stated, isAsciiWhiteSpace),\n isAsciiWhiteSpace,\n ),\n );\n}\n\n/** The reader's own refusal of a charset, which names it. */\nfunction undecoded(label: string): XynologError {\n return new XynologError(\n `The resource's text is ${label}, which is no charset this reader decodes: read its bytes instead`,\n 'error' satisfies TransportErrorCode,\n );\n}\n\n/**\n * The platform's decoder for a label of the Encoding Standard, or the reader's\n * own refusal, which names the label. The platform decodes the encodings every\n * reader refuses, so those are refused here.\n */\nfunction decoderFor(label: string): TextDecoder {\n let decoder: TextDecoder;\n try {\n decoder = new TextDecoder(label);\n } catch {\n throw undecoded(label);\n }\n if (REFUSED_ENCODINGS.has(decoder.encoding)) throw undecoded(label);\n return decoder;\n}\n\n/** The encoding whose byte-order mark the bytes begin with. */\nfunction encodingOfMark(\n bytes: Uint8Array,\n): 'utf-8' | 'utf-16be' | 'utf-16le' | undefined {\n if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf)\n return 'utf-8';\n if (bytes[0] === 0xfe && bytes[1] === 0xff) return 'utf-16be';\n if (bytes[0] === 0xff && bytes[1] === 0xfe) return 'utf-16le';\n return undefined;\n}\n\n/**\n * A resource's bytes as the text they are: the one place TypeScript makes a\n * text of a resource's bytes.\n *\n * The charset is the one the media type states, UTF-8 when it states none,\n * and is a label of the Encoding Standard: any other is refused, whatever the\n * bytes are. Bytes that begin with the byte-order mark of UTF-8, UTF-16BE or\n * UTF-16LE are in that encoding, whatever was stated, and the mark is not\n * part of the text. What the encoding does not have is U+FFFD.\n *\n * @param buffer - The bytes\n * @param mediaType - The content type they came with (e.g. \"text/plain; charset=iso-8859-1\")\n * @throws A `XynologError` whose code is `error`, naming the charset, for one that is not decoded\n *\n * @example\n * const text = decodeWithCharset(bytes, \"text/plain; charset=iso-8859-1\");\n */\nexport function decodeWithCharset(\n buffer: ArrayBuffer | Uint8Array,\n mediaType: string,\n): string {\n const bytes = ArrayBuffer.isView(buffer) ? buffer : new Uint8Array(buffer);\n // The stated charset is held to the standard before the bytes are looked at.\n const stated = decoderFor(extractCharset(mediaType));\n const marked = encodingOfMark(bytes);\n // A decoder leaves out the mark of its own encoding, and that is the one at the start here.\n return (marked === undefined ? stated : decoderFor(marked)).decode(bytes);\n}\n","/**\n * Helper functions for working with W3C ResourceDescriptor\n */\n\nimport type { components } from './types';\nimport { XynologError } from './errors';\nimport type { TransportErrorCode } from './error-codes';\nimport type { ResourceDescriptor } from './graph';\nimport type { ResourceId } from './identifiers';\nimport { derivesTextOf, textSourceOf } from './media-types';\nimport { decodeWithCharset } from './text-encoding';\n\ntype Representation = components['schemas']['Representation'];\n\n/**\n * Get the resource ID from @id property\n *\n * @id is always a bare ID (UUID), never a full URI.\n */\nexport function getResourceId(\n resource: ResourceDescriptor | undefined,\n): ResourceId | undefined {\n if (!resource) return undefined;\n return resource['@id'] || undefined;\n}\n\n/** Whether `value` is a representation as its schema has one: an object that states its media type as text. */\nfunction isRepresentation(value: unknown): value is Representation {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n 'mediaType' in value &&\n typeof value.mediaType === 'string'\n );\n}\n\n/**\n * The primary representation: the only one, or the first of the list;\n * undefined for an empty list, or for no resource. A resource that states no\n * `representations`, or one that is neither one representation nor a list of\n * them, is no ResourceDescriptor and is refused, as the Rust and Python SDKs\n * refuse it when they decode it (protocol/specs/src/resources/reader-cases.json).\n */\nexport function getPrimaryRepresentation(\n resource: ResourceDescriptor | undefined,\n): Representation | undefined {\n if (resource === undefined) return undefined;\n const stated: unknown = resource.representations;\n if (isRepresentation(stated)) return stated;\n if (Array.isArray(stated) && stated.every(isRepresentation)) return stated[0];\n throw new XynologError(\n `The resource ${resource['@id']} is no ResourceDescriptor: its representations are ${stated === undefined ? 'not stated' : 'neither one representation nor a list of them'}`,\n 'error' satisfies TransportErrorCode,\n );\n}\n\n/**\n * Get the media type from the primary representation. A resource that is no\n * ResourceDescriptor is refused, as getPrimaryRepresentation refuses it.\n */\nexport function getPrimaryMediaType(\n resource: ResourceDescriptor | undefined,\n): string | undefined {\n return getPrimaryRepresentation(resource)?.mediaType;\n}\n\n/**\n * Get the language from the primary representation\n */\nexport function getLanguage(\n resource: ResourceDescriptor | undefined,\n): string | undefined {\n return getPrimaryRepresentation(resource)?.language;\n}\n\n/**\n * Get the storage URI from the primary representation — the field's ONE\n * home: bytes are a fact about a rendition, so their location lives on the\n * Representation, never on the descriptor. This is the accessor every\n * descriptor-holding read goes through; `undefined` means the resource has no\n * stored bytes.\n *\n * @param resource - ResourceDescriptor\n * @returns Storage URI or undefined\n */\nexport function getStorageUri(\n resource: ResourceDescriptor | undefined,\n): string | undefined {\n return getPrimaryRepresentation(resource)?.storageUri;\n}\n\n/**\n * Check if resource is archived (application-specific field)\n *\n * @param resource - ResourceDescriptor\n * @returns True if archived, false otherwise\n */\nexport function isArchived(resource: ResourceDescriptor | undefined): boolean {\n return resource?.archived === true;\n}\n\n/**\n * Get entity types from resource (application-specific field)\n *\n * @param resource - ResourceDescriptor\n * @returns Array of entity types, empty if not set\n */\nexport function getResourceEntityTypes(\n resource: ResourceDescriptor | undefined,\n): string[] {\n return resource?.entityTypes || [];\n}\n\n/**\n * Check if resource is a draft (application-specific field)\n *\n * @param resource - ResourceDescriptor\n * @returns True if draft, false otherwise\n */\nexport function isDraft(resource: ResourceDescriptor | undefined): boolean {\n return resource?.isDraft === true;\n}\n\n/**\n * A representation's bytes as the text they are, for a media type whose bytes\n * are its text. The reading is `decodeWithCharset`'s, which keeps the rule\n * every reader of a resource's text keeps (protocol/contract/W3C-SELECTORS.md,\n * \"The text of a resource\"). An offset counts the code points of this text,\n * so every reader makes the same text of the same bytes.\n *\n * A refusal is the reader's own failure, whichever it is of: a media type\n * whose bytes are not its text, or a charset that is not decoded.\n *\n * @param buffer - The raw representation data\n * @param mediaType - Media type with optional charset (e.g., \"text/plain; charset=iso-8859-1\")\n * @returns Decoded string\n * @throws A `XynologError` whose code is `error`: naming the media type, for one whose bytes are not its text, and naming the charset, for one that is not decoded\n *\n * @example\n * ```typescript\n * const content = decodeRepresentation(buffer, \"text/plain; charset=utf-8\");\n * const legacy = decodeRepresentation(buffer, \"text/plain; charset=windows-1252\");\n * ```\n */\nexport function decodeRepresentation(\n buffer: ArrayBuffer | Uint8Array,\n mediaType: string,\n): string {\n // The chokepoint gate: decoding is only legitimate for media whose bytes\n // ARE its text — not for derived-text media (the anchored-text read answers\n // those) and not for media with no text at all. A PDF decoded here would\n // become megabytes of mojibake; refusing means no caller — present or\n // future — can decode bytes that were never text, which is why this gate\n // supersedes a caller census. Category, not mechanism: a\n // new strategy declares its side in core's exhaustive category maps and\n // this gate follows automatically.\n const source = textSourceOf(mediaType);\n if (derivesTextOf(mediaType) || source === 'none') {\n throw new XynologError(\n `decodeRepresentation refused ${mediaType}: its text source is '${source}' — ` +\n `derived text comes from the anchored-text read, never from decoding bytes`,\n 'error' satisfies TransportErrorCode,\n );\n }\n\n return decodeWithCharset(buffer, mediaType);\n}\n","// ⚠ GENERATED FILE — do not edit.\n//\n// Authority: protocol/specs/src/client/refresh.json\n// Regenerate: make generate (codegen/lib/cache_refresh/typescript.ml)\n\nimport type { components } from './types';\n\n/** The live queries a client's cache answers. */\nexport const CACHE_QUERIES = [\n 'resource',\n 'annotations',\n 'annotation',\n 'events',\n 'referencedBy',\n 'resources',\n 'matchedResources',\n 'entityTypes',\n 'tagSchemas',\n 'engines',\n] as const;\nexport type CacheQuery = (typeof CACHE_QUERIES)[number];\n\n/** The live queries whose answers a client keeps across its lives, for the person signed in. */\nexport const PERSISTED_QUERIES = [\n 'resource',\n 'annotations',\n 'annotation',\n 'entityTypes',\n 'tagSchemas',\n] as const;\nexport type PersistedQuery = (typeof PERSISTED_QUERIES)[number];\n\n/** What each live query is asked for per: a resource, an annotation, or the filters it is asked with; `whole` for one asked for whole, whose one answer is kept under `wholeKey`. */\nexport const CACHE_PER = {\n resource: 'resource',\n annotations: 'resource',\n annotation: 'annotation',\n events: 'resource',\n referencedBy: 'resource',\n resources: 'filters',\n matchedResources: 'filters',\n entityTypes: 'whole',\n tagSchemas: 'whole',\n engines: 'whole',\n} as const satisfies {\n readonly [Q in CacheQuery]: 'resource' | 'annotation' | 'filters' | 'whole';\n};\nexport type CachePer = typeof CACHE_PER;\n\n/** What each live query's cache holds, its `value`: the component, and the members within it the value is, outermost first. */\nexport const CACHE_VALUES = {\n resource: { component: 'ResourceDescriptor', members: [] },\n annotations: { component: 'GetAnnotationsResponse', members: [] },\n annotation: { component: 'Annotation', members: [] },\n events: { component: 'GetEventsResponse', members: ['events'] },\n referencedBy: {\n component: 'GetReferencedByResponse',\n members: ['referencedBy'],\n },\n resources: { component: 'ListResourcesResponse', members: [] },\n matchedResources: { component: 'MatchResourcesResponse', members: [] },\n entityTypes: {\n component: 'GetEntityTypesResponse',\n members: ['entityTypes'],\n },\n tagSchemas: { component: 'GetTagSchemasResponse', members: ['tagSchemas'] },\n engines: {\n component: 'BrowseEnginesResult',\n members: ['response', 'engines'],\n },\n} as const satisfies {\n readonly [Q in CacheQuery]: {\n readonly component: keyof components['schemas'];\n readonly members: readonly string[];\n };\n};\n\n/** The type of what each live query's cache holds: `CACHE_VALUES`'s component, member within member. */\nexport interface CacheValues {\n resource: components['schemas']['ResourceDescriptor'];\n annotations: components['schemas']['GetAnnotationsResponse'];\n annotation: components['schemas']['Annotation'];\n events: components['schemas']['GetEventsResponse']['events'];\n referencedBy: components['schemas']['GetReferencedByResponse']['referencedBy'];\n resources: components['schemas']['ListResourcesResponse'];\n matchedResources: components['schemas']['MatchResourcesResponse'];\n entityTypes: components['schemas']['GetEntityTypesResponse']['entityTypes'];\n tagSchemas: components['schemas']['GetTagSchemasResponse']['tagSchemas'];\n engines: components['schemas']['BrowseEnginesResult']['response']['engines'];\n}\n\n/** Which of a split channel's two kinds of event a row is for. */\nexport type CacheRefreshWhen = 'enriched' | 'unenriched';\n\n/** A way to a member of an event: the names of the members it is within, and its own. */\nexport type CacheRefreshWay = readonly string[];\n\n/** What one trigger does to the cache. */\nexport interface CacheRefresh {\n readonly when?: CacheRefreshWhen;\n /** `subject`: the keys the event names. `held`: every key the client holds. */\n readonly reach: 'subject' | 'held';\n /** Where in the event the keys a `subject` row reaches are: the way to the resource it names (a ResourceId), and to the annotation (an AnnotationId). */\n readonly names: {\n readonly resource?: CacheRefreshWay;\n readonly annotation?: CacheRefreshWay;\n };\n /** The way to the value the row writes (an Annotation). On a split channel, its presence is what makes an event enriched. */\n readonly carries?: CacheRefreshWay;\n /** Asked for again, the value shown meanwhile. */\n readonly refetches: readonly CacheQuery[];\n /** Written with the value the event carries. */\n readonly writes: readonly CacheQuery[];\n /** Gone: the key fails as `bus.not-found`. */\n readonly removes: readonly CacheQuery[];\n}\n\n/** What each trigger does: a channel's events; `reopened`, the stream open again after a drop; or `unreadable`, an event on one of these channels that cannot be read. */\nexport const CACHE_REFRESH = {\n /** The stream is open again after a drop. Events every client hears carry no position, so the ones published meanwhile are lost and nothing replays them: the client asks again for everything they feed. What a resource's own scope feeds needs nothing here: its events are replayed from where the client left off, or `bus:resume-gap` says they could not be. */\n reopened: [\n {\n reach: 'held',\n names: {},\n refetches: [\n 'resources',\n 'matchedResources',\n 'resource',\n 'entityTypes',\n 'tagSchemas',\n 'engines',\n ],\n writes: [],\n removes: [],\n },\n ],\n /** A frame on a channel of this table that its reading refuses, or one a member of which the row names is present and is not what it names: something changed and nothing says what, so every key held is asked for again, as after a gap. */\n unreadable: [\n {\n reach: 'held',\n names: {},\n refetches: [\n 'resource',\n 'annotations',\n 'annotation',\n 'events',\n 'referencedBy',\n 'resources',\n 'matchedResources',\n 'entityTypes',\n 'tagSchemas',\n 'engines',\n ],\n writes: [],\n removes: [],\n },\n ],\n /** The gateway could not replay what a scope missed: everything held of that resource, and of its annotations, is asked for again. */\n 'bus:resume-gap': [\n {\n reach: 'subject',\n names: { resource: ['scope'] },\n refetches: [\n 'annotations',\n 'annotation',\n 'resource',\n 'events',\n 'referencedBy',\n ],\n writes: [],\n removes: [],\n },\n ],\n /** An annotation was added to the resource. */\n 'mark:added': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['annotations', 'events'],\n writes: [],\n removes: [],\n },\n ],\n /** An annotation was removed from the resource. */\n 'mark:removed': [\n {\n reach: 'subject',\n names: {\n resource: ['resourceId'],\n annotation: ['payload', 'annotationId'],\n },\n refetches: ['annotations', 'events'],\n writes: [],\n removes: ['annotation'],\n },\n ],\n /** The reply to this client's own deletion: the annotation is gone whether or not the client holds the scope that would tell it so. */\n 'mark:delete-ok': [\n {\n reach: 'subject',\n names: { annotation: ['response', 'annotationId'] },\n refetches: [],\n writes: [],\n removes: ['annotation'],\n },\n ],\n /** enriched: An annotation's body changed, and the event carries the annotation as it now is. unenriched: An annotation's body changed, and the event could not say what it now is. */\n 'mark:body-updated': [\n {\n when: 'enriched',\n reach: 'subject',\n names: { resource: ['resourceId'], annotation: ['annotation', 'id'] },\n carries: ['annotation'],\n refetches: ['events'],\n writes: ['annotations', 'annotation'],\n removes: [],\n },\n {\n when: 'unenriched',\n reach: 'subject',\n names: {\n resource: ['resourceId'],\n annotation: ['payload', 'annotationId'],\n },\n refetches: ['annotations', 'annotation', 'events'],\n writes: [],\n removes: [],\n },\n ],\n /** An entity tag was added to the resource. */\n 'mark:entity-tag-added': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['annotations', 'resource', 'events'],\n writes: [],\n removes: [],\n },\n ],\n /** An entity tag was removed from the resource. */\n 'mark:entity-tag-removed': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['annotations', 'resource', 'events'],\n writes: [],\n removes: [],\n },\n ],\n /** The resource was archived, which its description states and lists filter on. */\n 'mark:archived': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['resource', 'resources', 'matchedResources'],\n writes: [],\n removes: [],\n },\n ],\n /** The resource was unarchived. */\n 'mark:unarchived': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['resource', 'resources', 'matchedResources'],\n writes: [],\n removes: [],\n },\n ],\n /** A resource was created. */\n 'yield:created': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['resource', 'resources', 'matchedResources'],\n writes: [],\n removes: [],\n },\n ],\n /** A resource was updated. */\n 'yield:updated': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['resource', 'resources', 'matchedResources'],\n writes: [],\n removes: [],\n },\n ],\n /** A resource was created as a clone. */\n 'yield:cloned': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['resource', 'resources', 'matchedResources'],\n writes: [],\n removes: [],\n },\n ],\n /** A resource was renamed or moved. */\n 'yield:moved': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['resource', 'resources', 'matchedResources'],\n writes: [],\n removes: [],\n },\n ],\n /** An entity type was added to the knowledge base. */\n 'frame:entity-type-added': [\n {\n reach: 'subject',\n names: {},\n refetches: ['entityTypes'],\n writes: [],\n removes: [],\n },\n ],\n /** A tag schema was added to the knowledge base. */\n 'frame:tag-schema-added': [\n {\n reach: 'subject',\n names: {},\n refetches: ['tagSchemas'],\n writes: [],\n removes: [],\n },\n ],\n} as const satisfies Record<string, readonly CacheRefresh[]>;\n\nexport type CacheRefreshTrigger = keyof typeof CACHE_REFRESH;\n\n/** The triggers that are channels of the bus. */\nexport const CACHE_REFRESH_CHANNELS = [\n 'bus:resume-gap',\n 'mark:added',\n 'mark:removed',\n 'mark:delete-ok',\n 'mark:body-updated',\n 'mark:entity-tag-added',\n 'mark:entity-tag-removed',\n 'mark:archived',\n 'mark:unarchived',\n 'yield:created',\n 'yield:updated',\n 'yield:cloned',\n 'yield:moved',\n 'frame:entity-type-added',\n 'frame:tag-schema-added',\n] as const;\nexport type CacheRefreshChannel = (typeof CACHE_REFRESH_CHANNELS)[number];\n","// ⚠ GENERATED FILE — do not edit.\n//\n// Authority: protocol/specs/src/session/oauth.json\n// Regenerate: make generate (codegen/lib/oauth_clients/oauth_clients.ml)\n\n/** An application a person uses: the authorization-code grant with PKCE (RFC 7636), at a redirect address the registration lists. */\nexport const BROWSER_CLIENT_ID = 'xynolog-browser';\n\n/** A process with no browser of its own, and the launcher: the device authorization grant (RFC 8628). */\nexport const SCRIPT_CLIENT_ID = 'xynolog-cli';\n\n/** What every sign-in asks for. `offline_access` asks for a refresh token that outlives the issuer's own browser session: a session with a knowledge base is renewed for weeks, not minutes. */\nexport const SIGN_IN_SCOPE = 'openid email profile offline_access';\n","// ⚠ GENERATED FILE — do not edit.\n//\n// Authority: protocol/specs/src/openapi.json and its paths\n// protocol/specs/src/session/ClientSecretForm.json\n// Regenerate: make generate (codegen/lib/gateway_http/typescript.ml)\n\n/** Each operation of the gateway, by its operationId: its method, its path (a `{name}` for each parameter, which the caller fills), and the media types it sends and answers with. */\nexport const gatewayRoutes = {\n getHealth: {\n method: 'GET',\n path: '/api/health',\n answers: 'application/json',\n },\n getHealthAtRoot: { method: 'GET', path: '/', answers: 'application/json' },\n getOpenApiDocument: {\n method: 'GET',\n path: '/api/openapi.json',\n answers: 'application/json',\n },\n getProtectedResourceMetadata: {\n method: 'GET',\n path: '/.well-known/oauth-protected-resource',\n answers: 'application/json',\n },\n createMediaToken: {\n method: 'POST',\n path: '/api/tokens/media',\n sends: 'application/json',\n answers: 'application/json',\n },\n getCurrentUser: {\n method: 'GET',\n path: '/api/users/me',\n answers: 'application/json',\n },\n getStatus: {\n method: 'GET',\n path: '/api/status',\n answers: 'application/json',\n },\n subscribeToBus: {\n method: 'POST',\n path: '/bus/subscribe',\n sends: 'application/json',\n answers: 'text/event-stream',\n },\n emitOnBus: {\n method: 'POST',\n path: '/bus/emit',\n sends: 'application/json',\n answers: 'application/json',\n },\n uploadResource: {\n method: 'POST',\n path: '/resources',\n sends: 'multipart/form-data',\n answers: 'application/json',\n },\n getResourceRepresentation: {\n method: 'GET',\n path: '/resources/{id}',\n answers: '*/*',\n },\n getResourceJsonLd: {\n method: 'GET',\n path: '/resources/{id}/jsonld',\n answers: 'application/ld+json',\n },\n getResourceAnnotations: {\n method: 'GET',\n path: '/resources/{id}/annotations',\n answers: 'application/json',\n },\n getResourceAnchoredText: {\n method: 'GET',\n path: '/resources/{id}/anchored-text',\n answers: 'application/json',\n },\n getResourceRepresentationWithMediaToken: {\n method: 'GET',\n path: '/api/resources/{id}',\n answers: '*/*',\n },\n} as const;\n\n/** Each header the gateway's operations name, asked or answered. */\nexport const gatewayHeaders = {\n cacheControl: 'Cache-Control',\n idempotencyKey: 'Idempotency-Key',\n link: 'Link',\n retryAfter: 'Retry-After',\n wwwAuthenticate: 'WWW-Authenticate',\n} as const;\n\n/** Each credential the gateway takes as a key, by its security scheme: where it goes, and its name there. */\nexport const gatewayApiKeys = {\n mediaToken: { in: 'query', name: 'token' },\n} as const;\n\n/** The form a service account posts with a client secret. */\nexport type ClientSecretForm = {\n grant_type: 'client_credentials';\n client_id: string;\n client_secret: string;\n};\n","// ⚠ GENERATED FILE — do not edit.\n//\n// Authority: protocol/specs/src/sign-in-store (SignIn.json, owner-only.json, README.md)\n// Regenerate: make generate (codegen/lib/sign_in/sign_in.ml)\n\nimport { isObject, isString } from './type-guards';\n\n/** One sign-in to a running stack's knowledge base, as the sign-in store keeps it: the tokens an issuer issued to the script client, and what a renewal and a sign-out need of that issuer, learned once at sign-in. TOKENS, never a password. An entry of <stateDir>/tokens.json (see README.md). */\nexport interface SignIn {\n /** The access token: short-lived, sent as a Bearer token. */\n token: string;\n /** The refresh token: long-lived, and what renews the access token at the issuer without another sign-in. An entry with none cannot be renewed. */\n refreshToken?: string;\n /** Who signed in: the address the access token named when the sign-in was made, which is the one the gateway answers for it. For display. Absent when the token named none. A writer that renews an entry keeps it as it was. */\n email?: string;\n /** When the access token was issued to this machine, RFC 3339 in UTC. */\n obtainedAt: string;\n /** When the access token stops working, RFC 3339 in UTC, so a reader can renew before sending a token it knows is dead. Absent when the issuer named no lifetime: the gateway's refusal is then the signal. */\n expiresAt?: string;\n /** The issuer the sign-in came from: the one the access token named when the sign-in was made. A writer that renews an entry keeps it. */\n issuer: string;\n /** The issuer's token endpoint, where the refresh grant is made. */\n tokenEndpoint: string;\n /** The issuer's revocation endpoint (RFC 7009), where a sign-out tells it to forget the refresh token. Absent when the issuer has none. */\n revocationEndpoint?: string;\n}\n\n/** Whether `value` is a SignIn: what it requires is there, and every member it has is text. */\nexport function isSignIn(value: unknown): value is SignIn {\n return (\n isObject(value) &&\n isString(value['token']) &&\n (value['refreshToken'] === undefined || isString(value['refreshToken'])) &&\n (value['email'] === undefined || isString(value['email'])) &&\n isString(value['obtainedAt']) &&\n (value['expiresAt'] === undefined || isString(value['expiresAt'])) &&\n isString(value['issuer']) &&\n isString(value['tokenEndpoint']) &&\n (value['revocationEndpoint'] === undefined ||\n isString(value['revocationEndpoint']))\n );\n}\n\n/** The directory's mode, in octal, on a system that has modes: its owner reads, writes and enters it, and nobody else does. */\nexport const OWNER_ONLY_DIRECTORY_MODE = 0o700;\n\n/** The mode, in octal, on a system that has modes, that a writer makes tokens.json's temporary file and its lock with, and the launcher its own files in its state home: its owner reads and writes each, and nobody else does. */\nexport const OWNER_ONLY_FILE_MODE = 0o600;\n\n/** The directory's access list on Windows, where a mode keeps nobody out, in SDDL, with `owner` where the SID of the user the writer runs as goes (its process token's user): full access for that user, the system and the administrators, and nobody else. It is handed down to everything made in the directory, and protected, so nothing is inherited from above. */\nexport function ownerOnlyDirectoryAccessList(owner: string): string {\n return 'D:PAI(A;OICI;FA;;;' + owner + ')(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)';\n}\n\n/** A file's access list on Windows, which the launcher gives each file it keeps to its owner, in SDDL, with `owner` where the SID of the user it runs as goes: the directory's list, with nothing handed down, since a file has nothing beneath it. Full access for that user, the system and the administrators, and nobody else, protected, so nothing is inherited from above. */\nexport function ownerOnlyFileAccessList(owner: string): string {\n return 'D:PAI(A;;FA;;;' + owner + ')(A;;FA;;;SY)(A;;FA;;;BA)';\n}\n\n/** The document's name in the state home: one sign-in per stack. */\nexport const SIGN_IN_STORE_FILE = 'tokens.json';\n\n/** The name, beside the document, of the file every writer locks from before its read until after its rename. */\nexport const SIGN_IN_STORE_LOCK = 'tokens.lock';\n\n/** On Windows, the high 32 bits of the offset of the one byte of the lock file that is locked: far past anything the file holds. */\nexport const SIGN_IN_STORE_WINDOWS_OFFSET_HIGH = 0x40000000;\n","/**\n * The operations that report inference limits — one per service that holds\n * inference credentials (the worker: `job:`; the librarian: `gather:`,\n * `match:`), each named `<flow>:limits-requested`. Derived from the bus\n * registry by that name, so a new key holder's operation joins by being\n * registered.\n */\nimport { BUS_OPERATIONS, type BusOperationKey } from './bus-operations';\n\nexport type LimitsOperation = Extract<\n BusOperationKey,\n `${string}:limits-requested`\n>;\n\nexport const LIMITS_OPERATIONS: readonly LimitsOperation[] = (\n Object.keys(BUS_OPERATIONS) as BusOperationKey[]\n).filter((op): op is LimitsOperation => op.endsWith(':limits-requested'));\n","// ⚠ GENERATED FILE — do not edit.\n//\n// Authority: protocol/specs/src/bus/registry.json (channels, payloads, operations)\n// Regenerate: make generate (codegen/lib/bus/typescript.ml)\n// Go counterpart: codegen/lib/bus/go.ml → go/bus\n//\n// Payload schemas themselves live in the OpenAPI components; the registry\n// names which one each channel carries, and every payload type here is\n// derived from that. Add or change a channel THERE.\n\nimport type { EventName } from './bus-protocol';\n\n/**\n * Where a channel sits relative to the hub: emitted toward it, delivered\n * from it (the fan-in set — BRIDGED_CHANNELS, by construction), or never on\n * the wire at all.\n */\nexport type ChannelDirection = 'outbound' | 'inbound' | 'in-process';\n\n/**\n * A channel's delivery class: what a subscriber is promised about a frame on\n * it when its stream drops, or is handed to another. The promise comes from\n * the frame's identity (protocol/contract/TRANSPORT-CONTRACT.md § Delivery).\n *\n * positioned — a recorded event delivered on its resource's scope. Its id\n * is its place in that resource's record: a subscriber that\n * names the last one it holds is sent what it missed.\n * correlated — the reply to a claimed request, routed to the client that\n * asked. Its id is the request's: it is recognised when it\n * arrives twice, and sent again while it is retained.\n * passing — every other frame. Nothing replays it.\n *\n * Derived from the registry's axes, never declared: an operation's replies\n * are correlated; a recorded event whose audience is `scoped` is positioned;\n * everything else that crosses the wire is passing. Who RECEIVES a frame is\n * the audience axis, and a different question.\n */\nexport type ChannelDelivery = 'positioned' | 'correlated' | 'passing';\n\nexport interface ChannelAttrs {\n /** In PERSISTED_EVENT_TYPES — lands in the event log, the system of record. */\n readonly recorded: boolean;\n readonly direction: ChannelDirection;\n /**\n * Does emitting this channel CHANGE the knowledge base, or only ask it\n * something?\n *\n * A WRITE is an act: it appends to the event log, or it enqueues or\n * transitions durable work the log will later cite. A READ answers from state\n * that already exists and leaves nothing behind — every `browse:*` request,\n * and the three lookups that merely resolve a token or a summary.\n *\n * The domain is exactly the EMITTABLE set: an operation's request, or a\n * `kind: command`. Inbound replies, broadcast events and in-process UI\n * signals are absent because nobody emits them at the gateway, so the\n * question does not arise. Every emittable channel names one side or the\n * other and the generator refuses — there is no default.\n *\n * The gateway reads this to decide when the record learns a principal's name:\n * a `_userId` stamp is NOT the test, because a read carries one too. Someone\n * who signs in and only browses is never named, and the profile publish rate\n * is the WRITE rate rather than the emit rate — orders of magnitude apart.\n */\n readonly writes?: boolean;\n /** Absent exactly when the channel never crosses the wire (`in-process`). */\n readonly delivery?: ChannelDelivery;\n}\n\nexport const CHANNEL_ATTRS = {\n 'yield:created': {\n recorded: true,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'yield:cloned': { recorded: true, direction: 'inbound', delivery: 'passing' },\n 'yield:updated': {\n recorded: true,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'yield:moved': { recorded: true, direction: 'inbound', delivery: 'passing' },\n 'yield:representation-added': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'yield:representation-removed': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'yield:create': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'yield:clone-persist': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'yield:update': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'yield:clone': { recorded: false, direction: 'in-process' },\n 'yield:clone-token-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'yield:clone-resource-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'yield:clone-create': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'yield:create-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:create-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-persist-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-persist-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:update-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:update-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-token-generated': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-token-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-resource-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-resource-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-created': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-create-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:added': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:removed': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:body-updated': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:entity-tag-added': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:entity-tag-removed': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:archived': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:unarchived': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:create-request': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:delete': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:update-body': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:archive': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:unarchive': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:update-entity-types': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:create-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:create-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:commit': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:commit-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:commit-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:delete-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:delete-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:archive-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:archive-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:unarchive-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:unarchive-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:update-entity-types-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:update-entity-types-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:body-update-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'mark:requested': { recorded: false, direction: 'in-process' },\n 'mark:submit': { recorded: false, direction: 'in-process' },\n 'mark:delegate-timeout': { recorded: false, direction: 'in-process' },\n 'mark:create-error': { recorded: false, direction: 'in-process' },\n 'mark:delete-error': { recorded: false, direction: 'in-process' },\n 'bind:body-error': { recorded: false, direction: 'in-process' },\n 'frame:entity-type-added': {\n recorded: true,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'frame:tag-schema-added': {\n recorded: true,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'frame:add-entity-type': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'frame:add-tag-schema': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'frame:entity-type-add-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'frame:entity-type-add-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'frame:tag-schema-add-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'frame:tag-schema-add-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'principal:profiled': {\n recorded: true,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'principal:profile': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'bind:initiate': { recorded: false, direction: 'in-process' },\n 'bind:update-body': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'bind:body-updated': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'bind:body-update-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'match:search-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'match:search-results': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'match:search-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'match:resources-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'match:resources-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'match:resources-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'match:limits-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'match:limits-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'match:limits-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'gather:complete': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:resource-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'gather:resource-complete': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:resource-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:summary-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'gather:summary-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:summary-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:referenced-by-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'gather:referenced-by-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:referenced-by-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:limits-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'gather:limits-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:limits-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:resource-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:resource-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:resource-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:resources-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:resources-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:resources-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:annotation-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:annotation-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:annotation-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:events-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:events-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:events-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:annotation-history-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:annotation-history-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:annotation-history-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:entity-types-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:entity-types-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:entity-types-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:tag-schemas-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:tag-schemas-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:tag-schemas-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:engines-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:engines-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:engines-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:profiles-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:profiles-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:profiles-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:kb-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:kb-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:kb-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:directory-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:directory-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:directory-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:click': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'browse:resource-open': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'browse:resource-viewed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'browse:entity-type-clicked': { recorded: false, direction: 'in-process' },\n 'panel:toggle': { recorded: false, direction: 'in-process' },\n 'panel:open': { recorded: false, direction: 'in-process' },\n 'panel:close': { recorded: false, direction: 'in-process' },\n 'shell:sidebar-toggle': { recorded: false, direction: 'in-process' },\n 'tabs:close': { recorded: false, direction: 'in-process' },\n 'tabs:reorder': { recorded: false, direction: 'in-process' },\n 'nav:link-clicked': { recorded: false, direction: 'in-process' },\n 'nav:push': { recorded: false, direction: 'in-process' },\n 'nav:external': { recorded: false, direction: 'in-process' },\n 'beckon:hover': { recorded: false, direction: 'in-process' },\n 'beckon:focus': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'beckon:sparkle': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'job:started': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'job:assigned': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'job:completed': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'job:failed': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'job:start': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:assign': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:report-progress': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'job:complete': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'job:fail': { recorded: false, direction: 'inbound', delivery: 'passing' },\n 'job:checkpoint': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:queued': { recorded: false, direction: 'inbound', delivery: 'passing' },\n 'job:cancel-requested': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:cancel': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:limits-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'job:limits-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:limits-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:status-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'job:create': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:claim': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:status-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:status-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:created': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:create-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:claimed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:claim-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:cancel-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:cancel-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'weave:applied': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'smelt:settled': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'weave:rebuild': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'weave:rebuild-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'weave:rebuild-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'smelt:rebuild-anchors': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'smelt:rebuild-anchors-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'smelt:rebuild-anchors-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'settings:theme-changed': { recorded: false, direction: 'in-process' },\n 'settings:line-numbers-toggled': { recorded: false, direction: 'in-process' },\n 'settings:locale-changed': { recorded: false, direction: 'in-process' },\n 'settings:hover-delay-changed': { recorded: false, direction: 'in-process' },\n 'bus:resume-gap': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'session:joined': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'session:left': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n} as const satisfies Record<EventName, ChannelAttrs>;\n","/**\n * A channel's attributes (`CHANNEL_ATTRS`, bus-classification.ts) read by a\n * name that is not yet known to be a channel's.\n */\n\nimport { CHANNEL_ATTRS, type ChannelAttrs } from './bus-classification';\n\nconst BY_CHANNEL: ReadonlyMap<string, ChannelAttrs> = new Map(\n Object.entries(CHANNEL_ATTRS),\n);\n\n/** String-keyed accessor for boundary code that has not yet narrowed to\n * EventName. Undefined means \"not a channel\", never \"unclassified\" — the\n * `satisfies` on CHANNEL_ATTRS makes unclassified unrepresentable. */\nexport const channelAttrsOf = (channel: string): ChannelAttrs | undefined =>\n BY_CHANNEL.get(channel);\n\n/** Did emitting this channel CHANGE the knowledge base? False for a read, and\n * for anything nobody emits — both are \"no act happened\", which is the\n * question every caller is actually asking. */\nexport const channelWrites = (channel: string): boolean =>\n BY_CHANNEL.get(channel)?.writes === true;\n","/**\n * Anchor a W3C Web Annotation to its rendered text.\n *\n * Render-time cleverness is deliberately limited to **verbatim** quote\n * matching. The annotation's two selectors are written to agree (on the\n * write side `reconcile` finds the span, and `annotationOfSpan` refuses one\n * whose text from `start` to `end` is not `exact`). At render time the\n * only legitimate discrepancy is *positional drift*: the document grew or\n * shrank above the span after the annotation was written, so the offset is\n * stale but the exact text still exists, byte-identical, elsewhere. That is\n * the W3C-intended role of `TextQuoteSelector`, and it is safe because it\n * demands identical text — no normalization, no fuzzy matching, no\n * judgment call.\n *\n * Anything that would require *fuzzy* recovery (smart-quote folding,\n * whitespace collapse, Levenshtein) is out of scope here: a non-verbatim\n * mismatch means the content representation diverged or the stored record\n * is wrong, both of which are deterministic and belong upstream (canonical\n * content, or a corrected annotation event). The renderer does not guess —\n * it renders at the stored offset and flags the anchor low-confidence so\n * the discrepancy surfaces for an upstream fix.\n *\n * Returns `null` only when nothing usable is present; otherwise always\n * returns a position with a `strategy` and `confidence`.\n *\n * A position, given or answered, is two offsets: they count Unicode code\n * points from the start of the content, as a `TextPositionSelector` does.\n * They are a string's own positions only in a text with no character outside\n * the Basic Multilingual Plane; a renderer that slices a string, or hands a\n * position to something that indexes one, converts with `textOffsets`.\n */\n\nimport { occurrencesOf, textOffsets, type TextOffsets } from './text-offsets';\n\nexport type AnchorStrategy =\n /** Position hint pointed exactly at the exact text. Unambiguous. */\n | 'fast-path'\n /** Exact text appears once verbatim in the content. No tiebreak needed. */\n | 'unique-occurrence'\n /** Multiple verbatim occurrences; prefix+suffix uniquely identified one. */\n | 'context-disambiguated'\n /** Multiple verbatim candidates; position closest to hint chosen. */\n | 'position-tiebreaker'\n /** Exact text not found verbatim (or no quote); raw stored offset used,\n * flagged for upstream correction. */\n | 'position-fallback';\n\nexport type AnchorConfidence = 'high' | 'medium' | 'low';\n\nexport interface RenderedAnchor {\n /** The offset the anchor starts at, in code points. */\n start: number;\n /** The offset just after it. */\n end: number;\n strategy: AnchorStrategy;\n confidence: AnchorConfidence;\n}\n\nexport interface AnchorSelectors {\n /** A `TextPositionSelector`'s two offsets, in code points. */\n position?: { start: number; end: number };\n quote?: { exact: string; prefix?: string; suffix?: string };\n}\n\n/**\n * Distance window for the position tiebreaker, in code points. Candidates\n * closer than this to the hint receive a non-zero position score; further\n * candidates fall back to zero. Tuned for typical document sizes;\n * calibration tests pin the boundary behaviour rather than the exact value.\n */\nexport const POSITION_WINDOW = 1024;\n\n/**\n * Score weights — kept as named constants so the calibration tests can\n * import them and pin the *relationships* rather than the magnitudes.\n *\n * Invariant: a full-context match always outranks any position score.\n * (`CONTEXT_FULL_WEIGHT * 2 > POSITION_WEIGHT_MAX`, accounting for\n * prefix+suffix each contributing the full weight.)\n */\nexport const CONTEXT_FULL_WEIGHT = 10;\nexport const CONTEXT_PARTIAL_WEIGHT = 5;\nexport const POSITION_WEIGHT_MAX = 5;\n\n/**\n * Locate the best-effort anchor for an annotation against the content the\n * renderer is about to display. Verbatim-only — see the module doc.\n *\n * `selectors.position` is given as offsets and the anchor is answered as\n * offsets, both in code points. `offsets` is the content's own\n * (`textOffsets(content)`): a renderer with several annotations of one\n * content makes it once.\n */\nexport function anchorAnnotation(\n content: string,\n offsets: TextOffsets,\n selectors: AnchorSelectors,\n): RenderedAnchor | null {\n const { position, quote } = selectors;\n\n // No quote selector. Position is the only signal; use it verbatim if\n // present and in-range, otherwise the annotation has no anchor.\n if (!quote || !quote.exact) {\n if (!position) return null;\n if (\n position.start < 0 ||\n position.end > offsets.length ||\n position.start >= position.end\n ) {\n return null;\n }\n return {\n start: position.start,\n end: position.end,\n strategy: 'position-fallback',\n confidence: 'low',\n };\n }\n\n const { exact, prefix, suffix } = quote;\n // How many code points the quote is: an occurrence of it ends this far on.\n const length = textOffsets(exact).length;\n\n // Fast path: position hint exactly matches the exact text. A stored start\n // that is no offset at all (not a whole number) is between no two\n // characters, and is left to the search below.\n if (position) {\n const probeEnd = position.start + length;\n if (\n Number.isInteger(position.start) &&\n position.start >= 0 &&\n probeEnd <= offsets.length &&\n content.substring(\n offsets.indexAt(position.start),\n offsets.indexAt(probeEnd),\n ) === exact\n ) {\n return {\n start: position.start,\n end: probeEnd,\n strategy: 'fast-path',\n confidence: 'high',\n };\n }\n }\n\n // Find all occurrences via exact indexOf. Cheap; bounded by content\n // size; sufficient for the common case where the renderer's content\n // matches the worker's content character-for-character.\n const occurrences = occurrencesOf(content, offsets, exact);\n\n if (occurrences.length === 1) {\n const start = occurrences[0]!;\n return {\n start,\n end: start + length,\n strategy: 'unique-occurrence',\n confidence: 'high',\n };\n }\n\n if (occurrences.length > 1) {\n const winner = pickByScore(\n content,\n offsets,\n occurrences,\n length,\n prefix,\n suffix,\n position?.start,\n );\n return winner;\n }\n\n // No verbatim occurrence. We do NOT fuzzy-match at render time — a\n // non-verbatim mismatch means the content diverged or the record is\n // wrong, which is an upstream concern. Render at the stored offset so the\n // highlight still appears, flagged low-confidence so the discrepancy is\n // visible and gets corrected at the source.\n if (\n position &&\n position.start >= 0 &&\n position.end <= offsets.length &&\n position.start < position.end\n ) {\n return {\n start: position.start,\n end: position.end,\n strategy: 'position-fallback',\n confidence: 'low',\n };\n }\n\n return null;\n}\n\n/**\n * Context match score at a candidate offset.\n * Returns full / partial / no-match per side (prefix and suffix), then\n * sums each side weighted by `CONTEXT_FULL_WEIGHT` / `CONTEXT_PARTIAL_WEIGHT`.\n *\n * \"Full\" means the stored context aligns exactly with the source text\n * adjacent to the candidate. \"Partial\" is the looser substring check —\n * the stored context appears somewhere in the candidate's surroundings\n * but isn't anchored to the edges. The scorer uses it as one signal among\n * many, not as a hard filter.\n *\n * `pos` is the candidate's offset. The surroundings compared are as many\n * code points of the content, on either side of the candidate, as the stored\n * context has.\n */\nfunction contextScoreAt(\n content: string,\n offsets: TextOffsets,\n pos: number,\n prefix: string | undefined,\n suffix: string | undefined,\n lengths: QuoteLengths,\n): { score: number; full: boolean } {\n let score = 0;\n let prefixFull = true;\n let suffixFull = true;\n\n if (prefix) {\n const adj = content.substring(\n offsets.indexAt(Math.max(0, pos - lengths.prefix)),\n offsets.indexAt(pos),\n );\n if (adj.endsWith(prefix)) {\n score += CONTEXT_FULL_WEIGHT;\n prefixFull = true;\n } else if (adj.includes(prefix.trim()) && prefix.trim().length > 0) {\n score += CONTEXT_PARTIAL_WEIGHT;\n prefixFull = false;\n } else {\n prefixFull = false;\n }\n }\n\n if (suffix) {\n const adj = content.substring(\n offsets.indexAt(pos + lengths.exact),\n offsets.indexAt(\n Math.min(offsets.length, pos + lengths.exact + lengths.suffix),\n ),\n );\n if (adj.startsWith(suffix)) {\n score += CONTEXT_FULL_WEIGHT;\n suffixFull = true;\n } else if (adj.includes(suffix.trim()) && suffix.trim().length > 0) {\n score += CONTEXT_PARTIAL_WEIGHT;\n suffixFull = false;\n } else {\n suffixFull = false;\n }\n }\n\n // \"Full\" overall match means every provided context field aligned\n // exactly — no partial fallbacks. Used to bump confidence to high.\n const full =\n (prefix === undefined || prefixFull) &&\n (suffix === undefined || suffixFull) &&\n (prefix !== undefined || suffix !== undefined);\n\n return { score, full };\n}\n\n/** How many code points the quote and its stored context are. A context that is not given is none. */\ninterface QuoteLengths {\n exact: number;\n prefix: number;\n suffix: number;\n}\n\nfunction positionScoreAt(pos: number, hint: number | undefined): number {\n if (hint === undefined) return 0;\n const distance = Math.abs(pos - hint);\n if (distance >= POSITION_WINDOW) return 0;\n return POSITION_WEIGHT_MAX * (1 - distance / POSITION_WINDOW);\n}\n\nfunction pickByScore(\n content: string,\n offsets: TextOffsets,\n occurrences: number[],\n length: number,\n prefix: string | undefined,\n suffix: string | undefined,\n hint: number | undefined,\n): RenderedAnchor {\n // Measured once, for every candidate.\n const lengths: QuoteLengths = {\n exact: length,\n prefix: prefix === undefined ? 0 : textOffsets(prefix).length,\n suffix: suffix === undefined ? 0 : textOffsets(suffix).length,\n };\n\n let bestPos = occurrences[0]!;\n let bestScore = -1;\n let bestContextFull = false;\n let bestHasAnyContextSignal = false;\n let bestHasAnyPositionSignal = false;\n\n for (const pos of occurrences) {\n const ctx = contextScoreAt(content, offsets, pos, prefix, suffix, lengths);\n const positionScore = positionScoreAt(pos, hint);\n const total = ctx.score + positionScore;\n if (total > bestScore) {\n bestScore = total;\n bestPos = pos;\n bestContextFull = ctx.full;\n bestHasAnyContextSignal = ctx.score > 0;\n bestHasAnyPositionSignal = positionScore > 0;\n }\n }\n\n // Strategy + confidence classification:\n // - both context fields aligned exactly → high-confidence context-disambiguated\n // - some context aligned (full or partial), no position needed → context-disambiguated, medium\n // - position broke the tie (winning candidate has position signal but no context signal,\n // or context was equal across candidates) → position-tiebreaker\n // - no signal at all (all candidates scored zero) → position-tiebreaker, low confidence,\n // deterministic first-of-many fallback\n let strategy: AnchorStrategy;\n let confidence: AnchorConfidence;\n\n if (bestContextFull) {\n strategy = 'context-disambiguated';\n confidence = 'high';\n } else if (bestHasAnyContextSignal && !bestHasAnyPositionSignal) {\n strategy = 'context-disambiguated';\n confidence = 'medium';\n } else if (bestHasAnyContextSignal && bestHasAnyPositionSignal) {\n // Context partially matched and position helped break the tie.\n strategy = 'position-tiebreaker';\n confidence = 'medium';\n } else if (bestHasAnyPositionSignal) {\n strategy = 'position-tiebreaker';\n confidence = 'medium';\n } else {\n strategy = 'position-tiebreaker';\n confidence = 'low';\n }\n\n return {\n start: bestPos,\n end: bestPos + length,\n strategy,\n confidence,\n };\n}\n","// ⚠ GENERATED FILE — do not edit.\n//\n// Authority: protocol/specs/src/locales/registry.json\n// Regenerate: make generate (codegen/lib/locales/locales.ml)\n\n/** The code of every supported language, in the registry's order. */\nexport const LOCALE_CODES = [\n 'ar',\n 'bn',\n 'cs',\n 'da',\n 'de',\n 'el',\n 'en',\n 'es',\n 'fa',\n 'fi',\n 'fr',\n 'he',\n 'hi',\n 'id',\n 'it',\n 'ja',\n 'ko',\n 'ms',\n 'nl',\n 'no',\n 'pl',\n 'pt',\n 'ro',\n 'sv',\n 'th',\n 'tr',\n 'uk',\n 'vi',\n 'zh',\n] as const;\n\n/** The code of a supported language. */\nexport type LocaleCode = (typeof LOCALE_CODES)[number];\n\n/** A supported language: its code, what it calls itself, and its name in English. */\nexport interface LocaleInfo {\n code: LocaleCode;\n nativeName: string;\n englishName: string;\n}\n\n/** A row per supported language, in the registry's order. */\nexport const LOCALES: readonly LocaleInfo[] = [\n { code: 'ar', nativeName: 'العربية', englishName: 'Arabic' },\n { code: 'bn', nativeName: 'বাংলা', englishName: 'Bengali' },\n { code: 'cs', nativeName: 'Čeština', englishName: 'Czech' },\n { code: 'da', nativeName: 'Dansk', englishName: 'Danish' },\n { code: 'de', nativeName: 'Deutsch', englishName: 'German' },\n { code: 'el', nativeName: 'Ελληνικά', englishName: 'Greek' },\n { code: 'en', nativeName: 'English', englishName: 'English' },\n { code: 'es', nativeName: 'Español', englishName: 'Spanish' },\n { code: 'fa', nativeName: 'فارسی', englishName: 'Persian' },\n { code: 'fi', nativeName: 'Suomi', englishName: 'Finnish' },\n { code: 'fr', nativeName: 'Français', englishName: 'French' },\n { code: 'he', nativeName: 'עברית', englishName: 'Hebrew' },\n { code: 'hi', nativeName: 'हिन्दी', englishName: 'Hindi' },\n { code: 'id', nativeName: 'Bahasa Indonesia', englishName: 'Indonesian' },\n { code: 'it', nativeName: 'Italiano', englishName: 'Italian' },\n { code: 'ja', nativeName: '日本語', englishName: 'Japanese' },\n { code: 'ko', nativeName: '한국어', englishName: 'Korean' },\n { code: 'ms', nativeName: 'Bahasa Melayu', englishName: 'Malay' },\n { code: 'nl', nativeName: 'Nederlands', englishName: 'Dutch' },\n { code: 'no', nativeName: 'Norsk', englishName: 'Norwegian' },\n { code: 'pl', nativeName: 'Polski', englishName: 'Polish' },\n { code: 'pt', nativeName: 'Português', englishName: 'Portuguese' },\n { code: 'ro', nativeName: 'Română', englishName: 'Romanian' },\n { code: 'sv', nativeName: 'Svenska', englishName: 'Swedish' },\n { code: 'th', nativeName: 'ไทย', englishName: 'Thai' },\n { code: 'tr', nativeName: 'Türkçe', englishName: 'Turkish' },\n { code: 'uk', nativeName: 'Українська', englishName: 'Ukrainian' },\n { code: 'vi', nativeName: 'Tiếng Việt', englishName: 'Vietnamese' },\n { code: 'zh', nativeName: '中文', englishName: 'Chinese' },\n];\n","/**\n * The languages Xynolog supports, and lookups over them. The table is\n * generated from protocol/specs/src/locales/registry.json.\n */\n\nimport { LOCALES, type LocaleInfo } from './locale-registry';\n\nexport { LOCALES, LOCALE_CODES } from './locale-registry';\nexport type { LocaleCode, LocaleInfo } from './locale-registry';\n\n// Create lookup map for efficient access\nconst localeByCode = new Map<string, LocaleInfo>(\n LOCALES.map((locale) => [locale.code.toLowerCase(), locale]),\n);\n\n/**\n * Get locale information by code\n */\nexport function getLocaleInfo(\n code: string | undefined,\n): LocaleInfo | undefined {\n if (!code) return undefined;\n return localeByCode.get(code.toLowerCase());\n}\n\n/**\n * Format locale code for display as \"Native Name (code)\"\n */\nexport function formatLocaleDisplay(\n code: string | undefined,\n): string | undefined {\n if (!code) return undefined;\n\n const info = getLocaleInfo(code);\n if (!info) return code;\n\n return `${info.nativeName} (${code.toLowerCase()})`;\n}\n","/**\n * SVG Utility Functions\n *\n * Utilities for creating, parsing, and manipulating W3C-compliant SVG selectors\n * for image annotation.\n */\n\nexport interface Point {\n x: number;\n y: number;\n}\n\n/**\n * Create W3C-compliant SVG rectangle selector\n */\nexport function createRectangleSvg(start: Point, end: Point): string {\n const x = Math.min(start.x, end.x);\n const y = Math.min(start.y, end.y);\n const width = Math.abs(end.x - start.x);\n const height = Math.abs(end.y - start.y);\n\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><rect x=\"${x}\" y=\"${y}\" width=\"${width}\" height=\"${height}\"/></svg>`;\n}\n\n/**\n * Create W3C-compliant SVG polygon selector\n */\nexport function createPolygonSvg(points: Point[]): string {\n if (points.length < 3) {\n throw new Error('Polygon requires at least 3 points');\n }\n\n const pointsStr = points.map((p) => `${p.x},${p.y}`).join(' ');\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><polygon points=\"${pointsStr}\"/></svg>`;\n}\n\n/**\n * Create W3C-compliant SVG circle selector\n */\nexport function createCircleSvg(center: Point, radius: number): string {\n if (radius <= 0) {\n throw new Error('Circle radius must be positive');\n }\n\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"${center.x}\" cy=\"${center.y}\" r=\"${radius}\"/></svg>`;\n}\n\n/**\n * The attributes of the first `<name …/>` element in `svg`: white space after\n * the name, at least one more character, and `/>` at the first `>`. Found by\n * index, in one pass, where a regular expression would backtrack quadratically.\n */\nfunction selfClosingElementAttributes(\n svg: string,\n name: string,\n): string | undefined {\n const opener = `<${name}`;\n let close = -1;\n for (\n let start = svg.indexOf(opener);\n start !== -1;\n start = svg.indexOf(opener, start + 1)\n ) {\n const attributesStart = start + opener.length;\n if (close < attributesStart) close = svg.indexOf('>', attributesStart);\n if (close === -1) return undefined;\n const attributes = svg.slice(attributesStart, close - 1);\n if (\n attributes.length >= 2 &&\n /\\s/.test(attributes.charAt(0)) &&\n svg.charAt(close - 1) === '/'\n ) {\n return attributes;\n }\n }\n return undefined;\n}\n\n/**\n * Parse SVG selector to extract shape type and data\n */\nexport function parseSvgSelector(svg: string):\n | {\n type: 'rect';\n data: { x: number; y: number; width: number; height: number };\n }\n | { type: 'polygon'; data: { points: Point[] } }\n | { type: 'circle'; data: { cx: number; cy: number; r: number } }\n | null {\n // Extract rectangle\n const rectAttributes = selfClosingElementAttributes(svg, 'rect');\n if (rectAttributes !== undefined) {\n const attrs = rectAttributes;\n const x = parseFloat(attrs.match(/x=\"([^\"]+)\"/)?.[1] || '0');\n const y = parseFloat(attrs.match(/y=\"([^\"]+)\"/)?.[1] || '0');\n const width = parseFloat(attrs.match(/width=\"([^\"]+)\"/)?.[1] || '0');\n const height = parseFloat(attrs.match(/height=\"([^\"]+)\"/)?.[1] || '0');\n\n return {\n type: 'rect',\n data: { x, y, width, height },\n };\n }\n\n // Extract polygon\n const polygonMatch = svg.match(/<polygon\\s+points=\"([^\"]+)\"/);\n if (polygonMatch && polygonMatch[1]) {\n const pointsStr = polygonMatch[1];\n const points = pointsStr.split(/\\s+/).map((pair) => {\n const [x, y] = pair.split(',').map(parseFloat);\n return { x, y };\n });\n\n return {\n type: 'polygon',\n data: { points },\n };\n }\n\n // Extract circle\n const circleAttributes = selfClosingElementAttributes(svg, 'circle');\n if (circleAttributes !== undefined) {\n const attrs = circleAttributes;\n const cx = parseFloat(attrs.match(/cx=\"([^\"]+)\"/)?.[1] || '0');\n const cy = parseFloat(attrs.match(/cy=\"([^\"]+)\"/)?.[1] || '0');\n const r = parseFloat(attrs.match(/r=\"([^\"]+)\"/)?.[1] || '0');\n\n return {\n type: 'circle',\n data: { cx, cy, r },\n };\n }\n\n return null;\n}\n\n/**\n * Scale entire SVG selector from display space to image native resolution\n */\nexport function scaleSvgToNative(\n svg: string,\n displayWidth: number,\n displayHeight: number,\n imageWidth: number,\n imageHeight: number,\n): string {\n const parsed = parseSvgSelector(svg);\n if (!parsed) return svg;\n\n const scaleX = imageWidth / displayWidth;\n const scaleY = imageHeight / displayHeight;\n\n switch (parsed.type) {\n case 'rect': {\n const { x, y, width, height } = parsed.data;\n return createRectangleSvg(\n { x: x * scaleX, y: y * scaleY },\n { x: (x + width) * scaleX, y: (y + height) * scaleY },\n );\n }\n\n case 'circle': {\n const { cx, cy, r } = parsed.data;\n return createCircleSvg(\n { x: cx * scaleX, y: cy * scaleY },\n r * Math.min(scaleX, scaleY),\n );\n }\n\n case 'polygon': {\n const points = parsed.data.points.map((p: Point) => ({\n x: p.x * scaleX,\n y: p.y * scaleY,\n }));\n return createPolygonSvg(points);\n }\n }\n}\n","/**\n * Generic validation utilities for @xynolog/http-transport\n *\n * Pure TypeScript validation with no external dependencies.\n * Safe to use in any JavaScript environment (Node.js, browser, Deno, etc.)\n */\n\n/**\n * Validation result types\n */\nexport type ValidationSuccess<T> = { success: true; data: T };\nexport type ValidationFailure = {\n success: false;\n error: string;\n details?: string[];\n};\nexport type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure;\n\n/**\n * JWT Token validation\n *\n * Validates JWT token format (header.payload.signature).\n * Does not verify signature - use for format validation only.\n */\nexport const JWTTokenSchema = {\n parse(token: unknown): string {\n if (typeof token !== 'string') {\n throw new Error('Token must be a string');\n }\n if (!token || token.length === 0) {\n throw new Error('Token is required');\n }\n // JWT format: header.payload.signature\n const jwtRegex = /^[A-Za-z0-9\\-_]+\\.[A-Za-z0-9\\-_]+\\.[A-Za-z0-9\\-_]*$/;\n if (!jwtRegex.test(token)) {\n throw new Error('Invalid JWT token format');\n }\n return token;\n },\n\n safeParse(token: unknown): ValidationResult<string> {\n try {\n const validated = this.parse(token);\n return { success: true, data: validated };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Invalid JWT token',\n };\n }\n },\n};\n\n/**\n * Generic validation helper with error formatting\n *\n * Wraps any schema's parse method with try/catch and returns ValidationResult.\n *\n * @example\n * ```typescript\n * const result = validateData(JWTTokenSchema, 'eyJ...');\n * if (result.success) {\n * console.log('Valid token:', result.data);\n * } else {\n * console.error('Invalid:', result.error);\n * }\n * ```\n */\nexport function validateData<T>(\n schema: { parse(data: unknown): T },\n data: unknown,\n): ValidationResult<T> {\n try {\n const validated = schema.parse(data);\n return { success: true, data: validated };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Validation failed',\n };\n }\n}\n\n/**\n * Email validation helper\n *\n * Validates email format using RFC 5322 simplified regex.\n *\n * @param email - Email address to validate\n * @returns true if valid email format\n */\nexport function isValidEmail(email: string): boolean {\n if (email.length < 1 || email.length > 255) {\n return false;\n }\n // RFC 5322 simplified email regex\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(email);\n}\n","import type { BehaviorSubject, Observable } from 'rxjs';\n\n/**\n * A state as its readers are given it: the value now (`getValue`) and each\n * value after it, and nothing that sets it. Whatever writes a state in a\n * `BehaviorSubject` hands out this view of it, so a reader cannot write past\n * what holds it: Python's `Watched`, Rust's `watch::Receiver`.\n */\nexport interface Watched<T> extends Observable<T> {\n getValue(): T;\n}\n\n/** The read-only view of a state held in `held`. */\nexport function watched<T>(held: BehaviorSubject<T>): Watched<T> {\n return Object.assign(held.asObservable(), {\n getValue: () => held.getValue(),\n });\n}\n","/**\n * Storage URI Derivation\n *\n * Builds the name a resource's content lives under in the working tree, from\n * its title and validated media type. Extensions come from the media-type\n * registry; formats are validated upstream at the create/yield boundary, so\n * the lookup is strict — no fallback.\n *\n * Lives in `@xynolog/core` because the generation form proposes a default\n * path, and react-ui depends on no package that needs Node. This module\n * imports only the registry, so it is browser-safe.\n */\n\nimport { MEDIA_TYPES, type SupportedMediaType } from './media-types';\n\n/**\n * The FILENAME a resource's content takes: slug + the registry's extension.\n *\n * The name is lowercased, runs of non-alphanumeric characters collapse to\n * single hyphens, and leading/trailing hyphens are stripped.\n *\n * This is the fragment form, for callers composing a path themselves — the\n * generation form's input sits beside a `file://` prefix chip, so it must not\n * strip a prefix this helper just added.\n *\n * @example\n * storageFileName(\"My Document\", \"text/markdown\") // => \"my-document.md\"\n */\nexport function storageFileName(\n name: string,\n format: SupportedMediaType,\n): string {\n const slug = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '');\n return `${slug}${MEDIA_TYPES[format].extension}`;\n}\n\n/**\n * Derive a full `file://` storage URI from a resource name and media type.\n *\n * @example\n * deriveStorageUri(\"My Document\", \"text/markdown\") // => \"file://my-document.md\"\n */\nexport function deriveStorageUri(\n name: string,\n format: SupportedMediaType,\n): string {\n return `file://${storageFileName(name, format)}`;\n}\n\n/**\n * The folder a resource lives in, WITHOUT a trailing slash — `''` when it sits\n * at the tree root. Accepts a `file://` URI or a bare path.\n */\nexport function folderOf(storageUri: string | undefined): string {\n const path = (storageUri ?? '').replace(/^file:\\/\\//, '');\n const cut = path.lastIndexOf('/');\n return cut === -1 ? '' : path.slice(0, cut);\n}\n\n/**\n * The Save location a form PROPOSES: beside the source resource, named for the\n * title, extended for the chosen format.\n *\n * Deriving the whole filename — extension included — has a happy consequence:\n * while untouched, switching format rewrites the extension too, so the form's\n * refusal of an extension that disagrees with the format becomes unreachable\n * except on hand-edited paths. It guards deliberate edits rather than trapping\n * ordinary use.\n *\n * Returns `''` for an empty title: a bare extension (\".md\") reads as a hidden\n * file and is nobody's intent.\n */\nexport function proposeStoragePath(\n folder: string,\n title: string,\n format: SupportedMediaType,\n): string {\n const name = storageFileName(title, format);\n if (name === MEDIA_TYPES[format].extension) return '';\n return folder ? `${folder}/${name}` : name;\n}\n","/**\n * The knowledge base's own identity, in its two renderings: its did:web and\n * its resource identifier, both from its committed `site.domain`.\n *\n * Nothing here names a person or an agent: the gateway, in Rust, mints every\n * principal's DID, and the record reads them\n * (`protocol/specs/src/principals/cases.json`, `protocol/specs/src/principals/kind-cases.json`).\n */\n\n/**\n * The knowledge base's own did:web identity, from its committed\n * `site.domain`, which the gateway states in the description it serves.\n *\n * Format: `did:web:<domain>` — the domain **verbatim, never encoded**. The\n * project file already stores it in did:web colon-path form\n * (`xynoplex.github.io:xynoplex-caselaw-kb`), so encoding those colons\n * would mint a string nothing else in the system produces. The launcher\n * mints the identical string in Go (`kbconfig.go` `didWeb()`), and the two\n * MUST agree byte-for-byte: the Browser joins discovered KBs to connected\n * ones on this value, and a mismatch fails silently — looking implemented\n * while never matching.\n *\n * A KB has no did when it declares no domain; identity is declared, never\n * defaulted or inferred from an address.\n */\nexport function kbDid(domain: string): string {\n return `did:web:${domain}`;\n}\n\n/**\n * The knowledge base's RESOURCE identifier: its did:web rendered as the https\n * URL that DID method resolves to, and the single value a token's `aud` must\n * carry. `did:web` turns the colon path into a slash path, so\n * `did:web:example.github.io:my-kb` identifies\n * `https://example.github.io/my-kb`.\n *\n * This is an IDENTIFIER, not an address. Nothing dereferences it, and it does\n * not have to equal the origin a request happened to arrive on — a knowledge\n * base reached over http in local development still identifies itself by the\n * https form, because its identity is declared, not observed. That is what\n * makes the value stable across every host, port and proxy it is reached\n * through, which is the whole reason `aud` can be checked at all.\n *\n * Derived from the SAME committed `site.domain` as `kbDid`, so the two\n * cannot drift; the launcher mints the identical string in Go\n * (`kbconfig.go` `kbResource`) and the two MUST agree byte-for-byte.\n */\nexport function kbResource(domain: string): string {\n return `https://${domain.split(':').join('/')}`;\n}\n","/**\n * A service account's assertion of itself, signed with its own key (RFC 7523\n * §2.2, OpenID Connect's `private_key_jwt`).\n *\n * The issuer holds the key's public half, registered on the account's client,\n * and checks the signature with it: the private key never leaves the process,\n * and no secret is sent. The assertion's shape is\n * protocol/specs/src/session/client-assertion-cases.json's.\n *\n * The key is WebCrypto's, which a browser withholds from a page that is not a\n * secure context. A page never holds a service account's key: a worker does,\n * and a worker is a process.\n */\n\nimport { base64url } from './base64url';\nimport { sha256 } from './sha256';\n\n/** The grant's `client_assertion_type` for an assertion that is a JWT. */\nexport const JWT_BEARER =\n 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';\n\n/** How long after it is made an assertion is good for. */\nexport const LIFETIME_SECONDS = 60;\n\n/** An RSA key's public members as a JWK states them: base64url, unpadded, of the unsigned big-endian bytes. */\nexport interface RsaPublicMembers {\n n: string;\n e: string;\n}\n\nconst RS256 = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' } as const;\n\nconst PKCS8_PEM =\n /^-----BEGIN PRIVATE KEY-----([A-Za-z0-9+/=\\s]+)-----END PRIVATE KEY-----$/;\nconst NOT_PKCS8_PEM =\n 'The key is not a PKCS#8 PEM private key: one that begins `-----BEGIN PRIVATE KEY-----`';\nconst NOT_RSA =\n 'The PEM holds no RSA private key: a service account signs its assertions with RS256';\nconst NOT_RS256 =\n 'The key does not sign RS256 (RSASSA-PKCS1-v1_5 with SHA-256): read it with `privateKeyFromPem`';\n\nconst utf8 = new TextEncoder();\nconst segment = (value: object): string =>\n base64url(utf8.encode(JSON.stringify(value)));\n\n/** The key's JWK thumbprint (RFC 7638): the SHA-256 of `e`, `kty` and `n`, in that order, with no whitespace. */\nexport function thumbprint({ n, e }: RsaPublicMembers): string {\n return base64url(sha256(utf8.encode(`{\"e\":\"${e}\",\"kty\":\"RSA\",\"n\":\"${n}\"}`)));\n}\n\n/** An assertion's header: RS256, and the key it is signed with, by its thumbprint. */\nexport function assertionHeader(key: RsaPublicMembers): {\n alg: 'RS256';\n kid: string;\n} {\n return { alg: 'RS256', kid: thumbprint(key) };\n}\n\n/** An assertion's claims: the client is its issuer and its subject, and the token endpoint its audience. */\nexport function assertionClaims(\n clientId: string,\n tokenEndpoint: string,\n { issuedAt, jti }: { issuedAt: number; jti: string },\n): {\n iss: string;\n sub: string;\n aud: string;\n jti: string;\n iat: number;\n exp: number;\n} {\n return {\n iss: clientId,\n sub: clientId,\n aud: tokenEndpoint,\n jti,\n iat: issuedAt,\n exp: issuedAt + LIFETIME_SECONDS,\n };\n}\n\n/**\n * The RSA private key a PKCS#8 PEM holds (`-----BEGIN PRIVATE KEY-----`), as a\n * key that signs RS256. A PEM that is not PKCS#8, or holds a key that is not\n * RSA, is refused, and the refusal never repeats it.\n *\n * The key is extractable: an assertion names it by its thumbprint, and its\n * public members are read by exporting it.\n */\nexport async function privateKeyFromPem(pem: string): Promise<CryptoKey> {\n const armored = PKCS8_PEM.exec(pem.trim());\n if (armored === null) throw new Error(NOT_PKCS8_PEM);\n let der: Uint8Array<ArrayBuffer>;\n try {\n der = Uint8Array.from(atob(armored[1].replace(/\\s/g, '')), (char) =>\n char.charCodeAt(0),\n );\n } catch {\n throw new Error(NOT_PKCS8_PEM);\n }\n try {\n return await crypto.subtle.importKey('pkcs8', der, RS256, true, ['sign']);\n } catch {\n throw new Error(NOT_RSA);\n }\n}\n\n/** The assertion, signed: a compact JWT of `assertionHeader` and `assertionClaims`, RS256 with `privateKey`. */\nexport async function clientAssertion(\n privateKey: CryptoKey,\n clientId: string,\n tokenEndpoint: string,\n made: { issuedAt: number; jti: string },\n): Promise<string> {\n const { kty, alg, n, e } = await crypto.subtle.exportKey('jwk', privateKey);\n if (kty !== 'RSA' || alg !== 'RS256' || n === undefined || e === undefined)\n throw new Error(NOT_RS256);\n const signingInput = `${segment(assertionHeader({ n, e }))}.${segment(assertionClaims(clientId, tokenEndpoint, made))}`;\n const signature = await crypto.subtle.sign(\n RS256,\n privateKey,\n utf8.encode(signingInput),\n );\n return `${signingInput}.${base64url(new Uint8Array(signature))}`;\n}\n","/**\n * An exchange that has `ms` to end. `exchange` is given a signal that is\n * aborted with a `TimeoutError` once `ms` have passed, and the wait is let go\n * when the exchange ends, however it ends. The wait is a timer global, which\n * a test's fake timers move; `AbortSignal.timeout` keeps its wait natively,\n * where no fake reaches it.\n *\n * Whatever reads the answer belongs inside `exchange`: a body read after it\n * has ended has no deadline.\n */\nexport async function withinDeadline<T>(\n ms: number,\n exchange: (signal: AbortSignal) => Promise<T>,\n): Promise<T> {\n const deadline = new AbortController();\n const timer = setTimeout(() => {\n deadline.abort(\n new DOMException(`The deadline of ${ms}ms passed`, 'TimeoutError'),\n );\n }, ms);\n try {\n return await exchange(deadline.signal);\n } finally {\n clearTimeout(timer);\n }\n}\n","/**\n * Why a sign-in at an issuer failed: a person's, over any of the grants the\n * session layer runs, or a service account's, over the client-credentials\n * grant (`ServiceToken`).\n */\n\nimport type { SignInErrorCode } from './error-codes';\n\nexport class SignInError extends Error {\n constructor(\n readonly code: SignInErrorCode,\n message: string,\n /**\n * The HTTP status the issuer answered with, when there was one.\n *\n * Absent means no response existed to read — `fetch` threw. That\n * difference decides whether a session ends or its refresh is retried: an\n * issuer refusing a grant and a network losing a packet are not the same\n * event, and a status that went only into the message would leave the two\n * indistinguishable one layer up.\n */\n readonly status?: number,\n ) {\n super(message);\n this.name = 'SignInError';\n }\n}\n","/**\n * A request that got no answer, and what its failure says of why.\n *\n * `fetch` rejects with what the runtime made of the failure, and the runtime\n * quotes the exchange in it. Node keeps what it could not read of an answer\n * on the error's cause, says a header's value in the message of an error\n * about one, and says a URL in the message of an error about that. Whatever\n * parses a body says where it stopped, and quotes the body there. A request\n * is made with a token and an answer may grant one, and a failure is printed\n * and logged whole.\n *\n * So no failure made here is `fetch`'s own, and none holds it. A failure says\n * the kind of error it was, by the code or the name the runtime gave it, and\n * none of the runtime's words.\n */\n\nimport { XynologError } from './errors';\nimport { isObject } from './type-guards';\n\n/** A code or a name as a runtime writes one: an identifier, and so not words. */\nconst IDENTIFIER = /^[A-Za-z][A-Za-z0-9_]*$/;\n\n/** `value`, when it is a code or a name that says which kind of error it was. `Error` says none. */\nfunction kind(value: unknown): string | undefined {\n return typeof value === 'string' &&\n IDENTIFIER.test(value) &&\n value !== 'Error'\n ? value\n : undefined;\n}\n\n/**\n * Why a request got no answer, as its failure may say it: the code of what\n * caused the rejection (`ECONNREFUSED`), failing that its name\n * (`HTTPParserError`), failing that the rejection's own name (`TimeoutError`).\n */\nexport function whyUnanswered(error: unknown): string {\n if (!isObject(error)) return 'Error';\n const cause = isObject(error['cause']) ? error['cause'] : undefined;\n return (\n kind(cause?.['code']) ??\n kind(cause?.['name']) ??\n kind(error['name']) ??\n 'Error'\n );\n}\n\n/**\n * A request that got no answer: the far end was not reached, what came was\n * not HTTP, or the request's deadline passed.\n *\n * It states no status, since nothing answered with one, and is filed under\n * `unavailable` as every such failure is. Wherever a status that says \"not\n * now\" is worth another attempt, so is this (`isRetryableRequestError`).\n */\nexport class UnansweredError extends XynologError {\n declare code: 'unavailable';\n\n /** `what` names the request. `error` is what `fetch`, or the read of its answer's body, rejected with. */\n constructor(what: string, error: unknown) {\n super(`${what} got no answer: ${whyUnanswered(error)}`, 'unavailable');\n this.name = 'UnansweredError';\n }\n}\n\n/**\n * An answer's body, read as JSON. Nothing, when it is not JSON: what the\n * parser says of such a body quotes it, and is said by no one.\n *\n * A body that stops coming is a request that got no answer, and `unanswered`\n * makes the failure of it.\n */\nexport async function jsonOf(\n response: Response,\n unanswered: (error: unknown) => Error,\n): Promise<unknown> {\n try {\n const body: unknown = await response.json();\n return body;\n } catch (error) {\n if (error instanceof SyntaxError) return undefined;\n throw unanswered(error);\n }\n}\n","/**\n * The client-credentials grant, for a process authenticating as ITSELF.\n *\n * A service or a worker holds its own account at the knowledge base's\n * issuer and exchanges that credential for a short-lived token. That token is\n * its bearer at the gateway, which names it by that account: an agent is an\n * account, as a person is. The account proves itself with its client secret,\n * or with a key: each grant then carries an assertion signed for it alone\n * (`client-assertion.ts`), and no secret is sent.\n *\n * This replaced a single shared secret that every sidecar carried and that the\n * gateway compared by string equality. That secret granted any agent identity\n * to anyone holding it, and could only be rotated by restarting the stack.\n *\n * The token endpoint is discovered rather than constructed. Every issuer\n * publishes it; guessing a vendor's path would put that vendor's layout in\n * code that has no other reason to know it.\n */\n\nimport { JWT_BEARER, clientAssertion } from './client-assertion';\nimport { withinDeadline } from './deadline';\nimport type { ClientSecretForm } from './gateway-http';\nimport { HTTP_REQUEST_TIMEOUT_MS } from './client-timing';\nimport { uuidV4 } from './id-generation';\nimport { SignInError } from './sign-in-error';\nimport { isObject, isString } from './type-guards';\nimport { UnansweredError, jsonOf } from './unanswered';\n\n/** A service account at an issuer, which proves itself with its client secret. */\nexport interface SecretCredential {\n /** The issuer URL, exactly as it appears in tokens' `iss`. */\n issuer: string;\n clientId: string;\n clientSecret: string;\n}\n\n/**\n * A service account at an issuer, which proves itself with a key: each grant\n * carries an assertion signed with `privateKey`, which the issuer checks with\n * the public half registered on the client. The key never leaves the process.\n */\nexport interface KeyCredential {\n /** The issuer URL, exactly as it appears in tokens' `iss`. */\n issuer: string;\n clientId: string;\n /** An RSA key that signs RS256, as `privateKeyFromPem` reads one. */\n privateKey: CryptoKey;\n}\n\n/** A service account at an issuer, by how it proves itself. */\nexport type ServiceAccountCredential = SecretCredential | KeyCredential;\n\n/**\n * The fetch a request is sent with: the one its caller gave, or the runtime's\n * own, looked up as each request is made. Either is called as a plain\n * function, never as a method of something else, which a browser refuses.\n */\nfunction fetchOf(given: typeof fetch | undefined): typeof fetch {\n return (...request: Parameters<typeof fetch>) =>\n (given ?? globalThis.fetch)(...request);\n}\n\n/** Renew this long before expiry, so a token never expires mid-flight. */\nconst RENEW_BEFORE_EXPIRY_MS = 30_000;\n\n/** The client-credentials grant's form: the secret itself, or an assertion signed for this grant alone. */\nasync function proof(\n credential: ServiceAccountCredential,\n endpoint: string,\n): Promise<URLSearchParams> {\n if ('clientSecret' in credential) {\n return new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: credential.clientId,\n client_secret: credential.clientSecret,\n } satisfies ClientSecretForm);\n }\n const assertion = await clientAssertion(\n credential.privateKey,\n credential.clientId,\n endpoint,\n {\n issuedAt: Math.floor(Date.now() / 1000),\n jti: uuidV4(),\n },\n );\n return new URLSearchParams({\n grant_type: 'client_credentials',\n client_assertion_type: JWT_BEARER,\n client_assertion: assertion,\n });\n}\n\n/**\n * A service account's token, fetched on first use and held until it is due\n * for renewal. A process makes one for its account, with the `fetch` its\n * issuer is asked with, and asks it for the token whenever it needs one.\n *\n * The issuer's token endpoint is discovered by the first ask, and kept for as\n * long as the holder is. A discovery that failed, because the issuer was still\n * booting, is not kept: the next ask discovers again.\n *\n * One grant is made at a time: those who ask while one is under way are given\n * what it brings, as they wait their turn.\n *\n * The lifetime comes from `expires_in` on the grant response, which is the\n * protocol's own field rather than a number restated here. Deliberately not\n * the JWT's `exp`: a client-credentials access token is not required to be a\n * JWT, and reading one would be assuming a shape the grant does not promise.\n */\nexport class ServiceToken {\n private endpoint: string | null = null;\n private held: { token: string; expiresAt: number } | null = null;\n /** The ask whose turn it is; the next waits for it to settle, however it does. */\n private asking: Promise<unknown> = Promise.resolve();\n\n constructor(\n private readonly credential: ServiceAccountCredential,\n private readonly fetch?: typeof globalThis.fetch,\n ) {}\n\n private async tokenEndpoint(): Promise<string> {\n if (this.endpoint === null) this.endpoint = await this.discover();\n return this.endpoint;\n }\n\n private async discover(): Promise<string> {\n const { issuer } = this.credential;\n const url = new URL(\n '.well-known/openid-configuration',\n issuer.endsWith('/') ? issuer : `${issuer}/`,\n );\n const unanswered = (error: unknown) =>\n new UnansweredError(`OIDC discovery for ${issuer}`, error);\n const document = await withinDeadline(\n HTTP_REQUEST_TIMEOUT_MS,\n async (signal) => {\n const response = await fetchOf(this.fetch)(url, { signal }).catch(\n (error: unknown) => {\n throw unanswered(error);\n },\n );\n if (!response.ok) {\n throw new SignInError(\n 'discovery',\n `OIDC discovery for ${issuer} failed: HTTP ${response.status} from ${url}`,\n response.status,\n );\n }\n return jsonOf(response, unanswered);\n },\n );\n if (!isObject(document) || !isString(document['token_endpoint'])) {\n throw new SignInError(\n 'discovery',\n `OIDC discovery for ${issuer} returned no \\`token_endpoint\\``,\n );\n }\n return document['token_endpoint'];\n }\n\n /** The `Authorization` header's value: the account's token, renewed when it is due. */\n async authorization(): Promise<string> {\n return `Bearer ${await this.token({ renewed: false })}`;\n }\n\n /**\n * The account's access token: the one held until it is due for renewal,\n * and a new grant after it, or at once when `renewed` (the gateway refused\n * the one held, or it is due by the asker's own schedule).\n *\n * Throws on refusal rather than returning null: a sidecar that cannot prove\n * who it is has nothing useful to do, and the caller's retry policy decides\n * whether this is worth attempting again. A refusal is a `SignInError`\n * carrying the status the issuer answered with; a request that got no\n * answer is an `UnansweredError`.\n *\n * Both requests, the issuer's discovery and the grant, are bounded by\n * `httpRequestTimeoutMs` (protocol/specs/src/client/timing.json): an issuer that\n * accepts a connection and never answers would otherwise hold a process's\n * start, and every renewal after it, for as long as the process lives. Both\n * are sent with the `fetch` this was made with, or the runtime's own.\n */\n token({ renewed }: { renewed: boolean }): Promise<string> {\n const turn = this.asking.then(() => this.granted(renewed));\n // The next ask waits for this one whether it brought a token or failed:\n // its failure is its own asker's, who is handed `turn`.\n this.asking = turn.then(\n () => undefined,\n () => undefined,\n );\n return turn;\n }\n\n /** `token`, in its turn. */\n private async granted(renewed: boolean): Promise<string> {\n const { issuer, clientId } = this.credential;\n\n if (\n !renewed &&\n this.held &&\n this.held.expiresAt - RENEW_BEFORE_EXPIRY_MS > Date.now()\n ) {\n return this.held.token;\n }\n\n const endpoint = await this.tokenEndpoint();\n const form = await proof(this.credential, endpoint);\n\n const unanswered = (error: unknown) =>\n new UnansweredError(\n `Client-credentials grant for ${clientId} at ${issuer}`,\n error,\n );\n const body = await withinDeadline(\n HTTP_REQUEST_TIMEOUT_MS,\n async (signal) => {\n const response = await fetchOf(this.fetch)(endpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: form,\n signal,\n }).catch((error: unknown) => {\n throw unanswered(error);\n });\n\n if (!response.ok) {\n // The status, not the body: a token endpoint's error body can echo the\n // request, and this one carried the secret or the assertion.\n throw new SignInError(\n 'exchange',\n `Client-credentials grant for ${clientId} at ${issuer} failed (HTTP ${response.status})`,\n response.status,\n );\n }\n\n return jsonOf(response, unanswered);\n },\n );\n if (!isObject(body) || !isString(body['access_token'])) {\n throw new SignInError(\n 'exchange',\n `Token endpoint for ${issuer} returned no \\`access_token\\``,\n );\n }\n\n const token = body['access_token'];\n const expiresIn = body['expires_in'];\n // A token whose grant reports no lifetime is not held, and neither is the\n // one it replaces, rather than either living by a guess: serving a token\n // past its expiry fails at the far end, where the cause is hardest to see.\n this.held =\n typeof expiresIn === 'number' && Number.isFinite(expiresIn)\n ? { token, expiresAt: Date.now() + expiresIn * 1000 }\n : null;\n return token;\n }\n}\n","/**\n * Knowledge-graph view derivation: the flattened neighborhood views are derived from the graph,\n * not kept as separately built intermediates.\n *\n * A pure function over the core `KnowledgeGraph` type. `@xynolog/react-ui` (the context summary) runs\n * it, and protocol/specs/src/librarian/derive-views-cases.json holds it to the derivation the Librarian runs. It\n * only transforms a graph the Librarian has already built.\n *\n * Reports the graph as-is: missing-view citers are kept (the citing annotation reflects a\n * real reference event; its resource label falls back to the raw id). A citation is its linking\n * ANNOTATION: an annotation node with `annotation-of` → the citing resource and `cites` → the focal\n * resource — so citedBy resolves through that pair, deduped per citing resource (several citations\n * from one document are one citer). Siblings are annotations ON the focal resource\n * (`annotation-of` → main), excluding the focal annotation — an annotation isn't its own sibling,\n * and a CITING annotation lives on another resource, so it never was one. Peer connections are\n * edges out of `mainResourceId`; derivation is structural (endpoints), never a match on the\n * free-form relationshipType. The graph is a projection of the event log (the system of record),\n * read here because it is the queryable projection at gather time.\n */\nimport type { components } from './types';\n\ntype KnowledgeGraph = components['schemas']['KnowledgeGraph'];\n\nexport interface GraphViews {\n connections: {\n resourceId: string;\n resourceName: string;\n entityTypes: string[];\n bidirectional: boolean;\n }[];\n citedBy: { resourceId: string; resourceName: string }[];\n citedByCount: number;\n siblingEntityTypes: string[];\n}\n\nexport function deriveViews(\n graph: KnowledgeGraph,\n mainResourceId: string,\n focalAnnotationId?: string,\n): GraphViews {\n // An edge names its ends as text, of either kind of node: the nodes are\n // looked up by that text.\n const nodeById = new Map<string, KnowledgeGraph['nodes'][number]>(\n graph.nodes.map((n) => [n.id, n]),\n );\n // annotation id → the resource it lives on. Both derivations resolve through\n // this, which is what keeps them structural: a peer connection whose\n // relationshipType happens to be named 'cites' has no annotation-of entry.\n const annotationOf = new Map<string, string>();\n for (const edge of graph.edges) {\n if (edge.type === 'annotation-of')\n annotationOf.set(edge.source, edge.target);\n }\n\n const connections: GraphViews['connections'] = [];\n const citedBy: GraphViews['citedBy'] = [];\n const citingSeen = new Set<string>();\n for (const edge of graph.edges) {\n const citingResource =\n edge.type === 'cites' && edge.target === mainResourceId\n ? annotationOf.get(edge.source)\n : undefined;\n if (citingResource !== undefined) {\n if (citingSeen.has(citingResource)) continue;\n citingSeen.add(citingResource);\n const node = nodeById.get(citingResource);\n citedBy.push({\n resourceId: citingResource,\n resourceName: node?.label ?? citingResource,\n });\n } else if (edge.source === mainResourceId) {\n const node = nodeById.get(edge.target);\n connections.push({\n resourceId: edge.target,\n resourceName: node?.label ?? edge.target,\n entityTypes: node?.entityTypes ?? [],\n bidirectional: edge.bidirectional ?? false,\n });\n }\n }\n\n const siblingEntityTypes = new Set<string>();\n for (const node of graph.nodes) {\n if (\n node.type === 'annotation' &&\n node.id !== focalAnnotationId &&\n annotationOf.get(node.id) === mainResourceId\n ) {\n for (const et of node.entityTypes ?? []) siblingEntityTypes.add(et);\n }\n }\n\n return {\n connections,\n citedBy,\n citedByCount: citedBy.length,\n siblingEntityTypes: Array.from(siblingEntityTypes),\n };\n}\n","/**\n * Retry: the mechanism, and the classifications core itself owns.\n *\n * At its centre is `retryWithBackoff`, for startup-critical calls in long-running\n * peers — each authenticates the moment its container starts, the gateway may not\n * be reachable for a few seconds, and orchestration runs them with `--rm` and no\n * restart policy, so a process that dies on the first `TypeError: fetch failed` is\n * dead for good.\n *\n * **What lives HERE — the mechanism, because it is one fact each:**\n * - `RetryPolicy` / `retryWithBackoff` — the loop, deadline-aware\n * - `equalJitter` — the backoff curve, shared with the SSE reconnect\n * - the predicates that narrow an error type CORE owns (`isTransientFetchError`\n * over `fetch`'s `TypeError`, `isRetryableRequestError` over `HttpStatusError`)\n *\n * **What deliberately does NOT — the judgment, because each is local knowledge:**\n * - **policies.** `EMIT_RETRY` (http-transport). A policy answers *how long\n * does THIS wait*, and a centralized one gets borrowed: a path waiting out\n * a model download on `STARTUP_FETCH_RETRY` — sized for \"until a peer\n * starts listening\" — sees its ceiling expire just before the thing it is\n * waiting for arrives. Two facts that happen to be measured in seconds are\n * still two facts.\n * - **deadlines.** Each sits with the call it bounds.\n * - **predicates over another package's errors.** Core has no business\n * knowing that a provider's 404 means \"not pulled yet\".\n *\n * `STARTUP_FETCH_RETRY` is the one policy here, and only because every boot\n * path asks the one question it answers.\n *\n * **Deadlines beat budgets.** `retryWithBackoff` takes an optional `AbortSignal`\n * so a caller with its own deadline stops the retry when it falls due, instead\n * of the two numbers having to be kept compatible by hand across packages. That\n * is the `context.Context` / gRPC-deadline move, with the platform's own\n * primitive.\n */\n\nimport { RETRY_RULES } from './retry-rules';\nimport { UnansweredError } from './unanswered';\n\nexport interface RetryPolicy {\n /** Total attempts, including the first one. */\n attempts: number;\n /** Ceiling on the delay before the second attempt; doubles each retry. */\n initialDelayMs: number;\n /** Ceiling for the doubled delay. */\n maxDelayMs: number;\n}\n\n/**\n * Equal jitter: half the computed ceiling, plus a random share of the other\n * half — delay ∈ [cap/2, cap).\n *\n * **One home, because it is one fact.** `retryWithBackoff` and the SSE reconnect\n * loop (`actor-state-unit.ts`) both need it, and a copy in each would be two\n * implementations agreeing by coincidence, free to drift the first time\n * either is tuned. The reconnect computes its own ceiling (`reconnectMs · 2ⁿ`,\n * capped); only the jitter is shared, which is the part that must not diverge.\n *\n * Unconditional in `retryWithBackoff`, not an option. Every caller of\n * `retryWithBackoff` is a container in a fleet that boots together and retries\n * against ONE gateway, which is precisely the lockstep this exists to break: N\n * peers backing off by an identical schedule re-converge on the same instant and\n * re-deliver the burst that caused the failure. A flag would leave that hazard\n * reachable by default-choosing, and nobody would ever pass `false`.\n *\n * The worst case is unchanged — `delay <= cap` still holds, so the patience\n * budget a policy advertises stays true; only the expected wait drops, to ~75%.\n */\nexport function equalJitter(cap: number): number {\n return cap / 2 + Math.random() * (cap / 2);\n}\n\nexport interface RetryAttemptInfo {\n /** 1-based number of the attempt that just failed. */\n attempt: number;\n /** Total attempt budget from the policy. */\n attempts: number;\n /** How long we wait before the next attempt. */\n delayMs: number;\n error: unknown;\n}\n\n/**\n * Default policy for startup connections to the gateway: 8 attempts with delay\n * ceilings 1s, 2s, 4s, then capped at 8s. The equal-jittered backoff means\n * the expected wait is ~75% of the sum of those ceilings.\n */\nexport const STARTUP_FETCH_RETRY: RetryPolicy = {\n attempts: 8,\n initialDelayMs: 1_000,\n maxDelayMs: 8_000,\n};\n\n/**\n * True for the errors `fetch` throws when the connection itself fails —\n * undici's `TypeError: fetch failed` (ECONNREFUSED, ENOTFOUND, reset,\n * timeout — the socket error rides in `cause`). Deliberately false for\n * HTTP-level failures (a 401 means the gateway is UP and rejected us;\n * retrying won't change its mind) and for programming errors.\n */\nexport function isTransientFetchError(error: unknown): boolean {\n if (!(error instanceof TypeError)) return false;\n if (error.message === 'fetch failed') return true;\n const code = (error.cause as { code?: string } | undefined)?.code;\n return typeof code === 'string' && code.length > 0;\n}\n\n/**\n * An error that knows the HTTP status the server answered with.\n *\n * Structural rather than a class, because the class already exists:\n * http-transport's `APIError` carries `status` and cannot be named from here\n * without inverting the package dependency. This interface is the contract\n * between the thrower and `isRetryableRequestError`, stated once — a predicate\n * that recovered the status by parsing it back out of an error MESSAGE would be\n * a second statement of the same fact, in the fragile direction.\n */\nexport interface HttpStatusError extends Error {\n readonly status: number;\n /** The wait the response's `Retry-After` stated, in milliseconds; none when it stated none. */\n readonly retryAfterMs: number | undefined;\n}\n\n/**\n * A `Retry-After` header's wait in milliseconds, when it states one in seconds\n * — the form the gateway sends (`TooManyRequests`, `AtCapacity`); none\n * otherwise.\n */\nexport function retryAfterMs(header: string | null): number | undefined {\n return header !== null && /^[0-9]+$/.test(header.trim())\n ? Number(header.trim()) * 1000\n : undefined;\n}\n\n/**\n * True for failures worth another attempt: the connection never landed\n * (`isTransientFetchError`), the request got no answer (`UnansweredError`),\n * the server answered \"not now\" (`RETRY_RULES.boot`), or our own deadline\n * expired.\n *\n * The status half is DERIVED from `RETRY_RULES.boot` rather than restated here.\n * A private set of the same statuses would make the taxonomy a second opinion\n * instead of the answer — and a second opinion in the same package is the exact\n * defect the `RETRY_RULES` catalog exists to remove. The reasoning for those\n * statuses, and for excluding `500`, lives once, in the rule.\n *\n * The timeout case is the one that is easy to get wrong. A request whose\n * deadline passes (`withinDeadline`) rejects with a **DOMException named\n * `TimeoutError`**, not a `TypeError` — measured, not assumed — so\n * `isTransientFetchError` cannot see it, and without this case a request that\n * bounds itself is unretryable precisely when the bound fires. Matched by\n * `name` rather than `instanceof DOMException` because the constructor is not\n * guaranteed present in every runtime this package builds for, while the name\n * is part of the DOM spec.\n *\n * Auth and validation failures stay excluded, preserving `isTransientFetchError`'s\n * reasoning verbatim: a 401 means the gateway is UP and rejected us, and retrying\n * will not change its mind. A 429 differs — the gateway is up and *asking* us to\n * wait, so the same \"it answered\" fact points the other way.\n */\nexport function isRetryableRequestError(error: unknown): boolean {\n if (isTransientFetchError(error) || error instanceof UnansweredError)\n return true;\n if (typeof error !== 'object' || error === null) return false;\n if ((error as { name?: unknown }).name === 'TimeoutError') return true;\n const status = (error as { status?: unknown }).status;\n return typeof status === 'number' && RETRY_RULES.boot.retryable({ status });\n}\n\n/**\n * Resolves `true` once `ms` have passed, or `false` as soon as `signal`\n * aborts, letting go of the wait it no longer needs.\n */\nfunction waited(ms: number, signal: AbortSignal | undefined): Promise<boolean> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve(false);\n return;\n }\n const cutShort = () => {\n clearTimeout(timer);\n resolve(false);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', cutShort);\n resolve(true);\n }, ms);\n signal?.addEventListener('abort', cutShort, { once: true });\n });\n}\n\n/**\n * Run `fn`, retrying on errors `isRetryable` accepts, with equal-jitter\n * exponential backoff per `policy`. `onRetry` fires before each wait — the\n * caller's hook for logging the attempt, and it reports the actual jittered\n * delay. The final error (retryable budget exhausted, or the first\n * non-retryable one) is rethrown verbatim.\n *\n * `signal` is the caller's deadline. Once it aborts no attempt is made: an\n * aborted signal rejects with its reason before the first, and a wait between\n * attempts ends at once, rethrowing the error that began it. The attempt in\n * flight is the caller's to give up, by giving its own call the signal.\n */\nexport async function retryWithBackoff<T>(\n fn: () => Promise<T>,\n isRetryable: (error: unknown) => boolean,\n policy: RetryPolicy,\n onRetry?: (info: RetryAttemptInfo) => void,\n signal?: AbortSignal,\n): Promise<T> {\n signal?.throwIfAborted();\n let cap = policy.initialDelayMs;\n for (let attempt = 1; ; attempt++) {\n try {\n return await fn();\n } catch (error) {\n // The caller's deadline outranks the budget. Without this, a caller that\n // races its own timeout against work that retries has two numbers it must\n // keep compatible by hand — and the day they stop being compatible, the\n // race kills a retry that was about to succeed.\n if (signal?.aborted) throw error;\n if (attempt >= policy.attempts || !isRetryable(error)) throw error;\n // `delayMs` reported to `onRetry` is the ACTUAL wait, not the ceiling —\n // a log that printed the ceiling would describe a schedule nobody ran.\n // A wait the server stated (`Retry-After`) is a floor under it: a\n // refused caller backs off by the server's clock, not its own.\n const stated = (error as { retryAfterMs?: unknown }).retryAfterMs;\n const delayMs = Math.max(\n equalJitter(cap),\n typeof stated === 'number' ? stated : 0,\n );\n onRetry?.({ attempt, attempts: policy.attempts, delayMs, error });\n if (!(await waited(delayMs, signal))) throw error;\n cap = Math.min(cap * 2, policy.maxDelayMs);\n }\n }\n}\n","/**\n * Browser ↔ launcher KB discovery.\n *\n * The launcher publishes its export view at `<stateDir>/discovery/kbs.json`,\n * mounted read-only into the Browser's container at `/discovery` and served\n * by the Browser image (`images/browser`) at this URL path. One TS-side name for\n * that URL: the Browser server's tests fetch this constant, so\n * prefix/filename drift between the server and consumers is a failing test —\n * mirroring for the URL what the DiscoveryDocument schema does for the\n * payload. (The launcher's Go side keeps its own constant;\n * protocol/specs/src/discovery/README.md is the cross-language record.)\n */\nexport const DISCOVERY_URL_PATH = '/discovery/kbs.json';\n"]}
1
+ {"version":3,"sources":["../src/job-filter.ts","../src/job-storage.ts","../src/job-subject.ts","../src/persisted-events.ts","../src/event-utils.ts","../src/retry-sets.ts","../src/retry-rules.ts","../src/base64url.ts","../src/refuse-non-finite.ts","../src/sha256.ts","../src/annotation-id.ts","../src/text-offsets.ts","../src/fuzzy-anchor.ts","../src/pdf-anchoring.ts","../src/pdf-coordinates.ts","../src/text-context.ts","../src/annotation-builders.ts","../src/web-annotation-utils.ts","../src/media-type-registry.ts","../src/media-types.ts","../src/refused-encodings.ts","../src/text-encoding.ts","../src/resource-utils.ts","../src/byte-source.ts","../src/cache-refresh.ts","../src/control-methods.ts","../src/oauth-clients.ts","../src/stored.ts","../src/gateway-http.ts","../src/archivist-http.ts","../src/service-groups.ts","../src/service-texts.ts","../src/sign-in.ts","../src/limits-operations.ts","../src/bus-classification.ts","../src/channel-attrs.ts","../src/anchor-annotation.ts","../src/locale-registry.ts","../src/locales.ts","../src/svg-utils.ts","../src/validation.ts","../src/watched.ts","../src/storage-uri.ts","../src/did-utils.ts","../src/client-assertion-facts.ts","../src/client-assertion.ts","../src/deadline.ts","../src/sign-in-error.ts","../src/token-renewal.ts","../src/unanswered.ts","../src/service-account.ts","../src/binary-text.ts","../src/knowledge-graph-views.ts","../src/retry.ts","../src/discovery.ts"],"names":["job","RETRY_RULES","right","between","resourceId","segment"],"mappings":";;;;AAwBA,SAAS,MAAA,CAAO,QAAiB,MAAA,EAA0B;AACzD,EAAA,IAAI,CAAC,QAAA,CAAS,MAAM,CAAA,SAAU,MAAA,KAAW,MAAA;AACzC,EAAA,OACE,SAAS,MAAM,CAAA,I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AW;AACjC,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,EAAA,EAAG;AAAA,IAClB,SAAS,KAAA,EAAO;AAKd,MAAA,IAAI,MAAA,EAAQ,SAAS,MAAM,KAAA;AAC3B,MAAA,IAAI,WAAW,MAAA,CAAO,QAAA,IAAY,CAAC,WAAA,CAAY,KAAK,GAAG,MAAM,KAAA;AAG7D,MAAA,MAAM,SAAU,KAAA,CAAqC,YAAA;AACrD,MAAA,MAAM,UAAU,IAAA,CAAK,GAAA;AAAA,QACnB,YAAY,GAAG,CAAA;AAAA,QACf,OAAO,MAAA,KAAW,QAAA,GAAW,MAAA,GAAS;AAAA,OACxC;AACA,MAAA,IAAI,CAAE,MAAM,MAAA,CAAO,OAAA,EAAS,MAAM,GAAI,MAAM,KAAA;AAC5C,MAAA,GAAA,GAAM,IAAA,CAAK,GAAA,CAAI,GAAA,GAAM,CAAA,EAAG,OAAO,UAAU,CAAA;AAAA,IAC3C;AAAA,EACF;AACF;;;AC5LO,IAAM,kBAAA,GAAqB","file":"index.js","sourcesContent":["/**\n * Whether a job matches a filter.\n *\n * A filter (`JobFilter`) is a partial job description: it names fields of the\n * description at the description's own paths. A job matches when every field\n * the filter states equals the job's; what the filter leaves out is not\n * compared. So the comparison knows no field by name, and does not change when\n * a filter may state another.\n *\n * It is asked in two places: by the Dispatcher, choosing the next job a claim\n * takes, and by a party checking an announcement against its own claim before\n * it asks. `protocol/specs/src/jobs/filter-cases.json` holds every implementation to\n * one answer.\n */\n\nimport type { components, JobFilter } from './types';\nimport { isObject } from './type-guards';\n\n/** A job as a filter is compared with it: announced, or held. */\nexport interface FilterableJob {\n jobType: components['schemas']['JobType'];\n params: object;\n}\n\nfunction states(stated: unknown, actual: unknown): boolean {\n if (!isObject(stated)) return stated === actual;\n return (\n isObject(actual) &&\n Object.entries(stated).every(([name, value]) => states(value, actual[name]))\n );\n}\n\nexport function jobMatchesFilter(\n filter: JobFilter,\n job: FilterableJob,\n): boolean {\n return states(filter, job);\n}\n","// Generated from protocol/specs/src/jobs/storage.json, protocol/specs/src/components/schemas/JobType.json and protocol/specs/src/components/schemas/MarkJobParams.json; do not edit.\n// Regenerate: make generate (codegen/lib/job_storage/job_storage.ml)\n\n/** The work-queue stream every job is published into. */\nexport const JOBS_STREAM = 'JOBS';\n\n/** The root of every job subject: a job is published on `<root>.<jobType>`. */\nexport const JOBS_SUBJECT_ROOT = 'jobs';\n\n/** The stream's capture filter: every subject under the root. */\nexport const JOBS_STREAM_SUBJECTS = ['jobs.>'] as const;\n\n/** The durable consumer that holds each job's message as its lease. */\nexport const JOBS_CONSUMER = 'dispatcher-leases';\n\n/** The KV bucket holding one JobRecord per job, keyed by the job's id. */\nexport const JOBS_BUCKET = 'jobs';\n\n/** Every job type. */\nexport const JOB_TYPES = ['mark', 'yield'] as const;\n\n/** Every motivation a `mark` job has: the ones MarkJobParams is told apart by. */\nexport const MARK_MOTIVATIONS = [\n 'highlighting',\n 'commenting',\n 'assessing',\n 'linking',\n 'tagging',\n] as const;\n","/** The subject a job is published on, under job-storage.ts's root. */\n\nimport { JOBS_SUBJECT_ROOT } from './job-storage';\n\n/** The subject a job of this type is published on. */\nexport function jobSubject(type: string): string {\n return `${JOBS_SUBJECT_ROOT}.${type}`;\n}\n","// Generated from protocol/specs/src/bus/registry.json (channels, payloads, operations); do not edit.\n// Regenerate: make generate (codegen/lib/bus/typescript.ml)\n// Go counterpart: codegen/lib/bus/go.ml → go/bus\n//\n// Payload schemas themselves live in the OpenAPI components; the registry\n// names which one each channel carries, and every payload type here is\n// derived from that. Add or change a channel THERE.\n\n/**\n * Persisted Events\n *\n * The event types that get appended to the JSONL event log, each with the\n * component schema of its payload. The PersistedEvent union derives from this\n * catalog.\n */\n\nimport type { components, ResourceId } from './types';\nimport type { EventBase } from './event-base';\n\n/** Each persisted event type and the component schema of the payload the registry states it carries. */\nexport const PERSISTED_EVENT_PAYLOADS = {\n 'yield:created': 'ResourceCreatedPayload',\n 'yield:cloned': 'ResourceClonedPayload',\n 'yield:updated': 'ResourceUpdatedPayload',\n 'yield:moved': 'ResourceMovedPayload',\n 'yield:representation-added': 'RepresentationAddedPayload',\n 'yield:representation-removed': 'RepresentationRemovedPayload',\n 'mark:added': 'AnnotationAddedPayload',\n 'mark:removed': 'AnnotationRemovedPayload',\n 'mark:body-updated': 'AnnotationBodyUpdatedPayload',\n 'mark:entity-tag-added': 'EntityTagChangedPayload',\n 'mark:entity-tag-removed': 'EntityTagChangedPayload',\n 'mark:archived': 'ResourceArchivedPayload',\n 'mark:unarchived': 'ResourceUnarchivedPayload',\n 'frame:entity-type-added': 'EntityTypeAddedPayload',\n 'frame:tag-schema-added': 'TagSchemaAddedPayload',\n 'principal:profiled': 'PrincipalProfiledPayload',\n 'job:started': 'JobStartedPayload',\n 'job:assigned': 'JobAssignedPayload',\n 'job:completed': 'JobCompletedPayload',\n 'job:failed': 'JobFailedPayload',\n} as const satisfies Record<string, keyof components['schemas']>;\n\n/** Each persisted event type and the payload it carries. */\ntype PersistedEventCatalog = {\n [\n K in keyof typeof PERSISTED_EVENT_PAYLOADS\n ]: components['schemas'][(typeof PERSISTED_EVENT_PAYLOADS)[K]];\n};\n\n/** System event types — persisted events that have no resourceId. */\ntype SystemEventType =\n 'frame:entity-type-added' | 'frame:tag-schema-added' | 'principal:profiled';\n\n/** Extract the concrete persisted event type for a given type string. */\nexport type EventOfType<K extends keyof PersistedEventCatalog> =\n K extends SystemEventType\n ? EventBase & { type: K; payload: PersistedEventCatalog[K] }\n : EventBase & {\n type: K;\n resourceId: ResourceId;\n payload: PersistedEventCatalog[K];\n };\n\n/** The union of all persisted event types. Discriminated on `type`. */\nexport type PersistedEvent = {\n [K in keyof PersistedEventCatalog]: EventOfType<K>;\n}[keyof PersistedEventCatalog];\n\nexport type PersistedEventType = PersistedEvent['type'];\n\n/** Every persisted event type, for code that enumerates them at runtime. */\nexport const PERSISTED_EVENT_TYPES = [\n 'yield:created',\n 'yield:cloned',\n 'yield:updated',\n 'yield:moved',\n 'yield:representation-added',\n 'yield:representation-removed',\n 'mark:added',\n 'mark:removed',\n 'mark:body-updated',\n 'mark:entity-tag-added',\n 'mark:entity-tag-removed',\n 'mark:archived',\n 'mark:unarchived',\n 'frame:entity-type-added',\n 'frame:tag-schema-added',\n 'principal:profiled',\n 'job:started',\n 'job:assigned',\n 'job:completed',\n 'job:failed',\n] as const satisfies readonly PersistedEventType[];\n\n/** Input type for appendEvent — PersistedEvent without id/timestamp (assigned at persistence time). */\nexport type EventInput = Omit<PersistedEvent, 'id' | 'timestamp'>;\n","/**\n * Event Type Guards and Extraction Utilities\n *\n * Domain logic for working with resource events.\n * No React dependencies - safe to use in any JavaScript environment.\n */\n\nimport { isAnnotationId } from './identifiers';\nimport { isObject, isString } from './type-guards';\nimport type { components, AnnotationId } from './types';\n\n// =============================================================================\n// EVENT TYPE GUARDS AND EXTRACTION\n// =============================================================================\n\n/**\n * The annotation a stored event is about, or null when it is about none.\n *\n * A `mark:added` carries the annotation; a `mark:removed` and a\n * `mark:body-updated` name it by id.\n */\nexport function getAnnotationIdFromEvent(\n event: components['schemas']['StoredEventResponse'],\n): AnnotationId | null {\n const payload = event.payload;\n let id: unknown;\n if (event.type === 'mark:added') {\n id = isObject(payload.annotation) ? payload.annotation.id : undefined;\n } else if (\n event.type === 'mark:removed' ||\n event.type === 'mark:body-updated'\n ) {\n id = payload.annotationId;\n }\n return isString(id) && isAnnotationId(id) ? id : null;\n}\n","// Generated from protocol/specs/src/retry/rules.json; do not edit.\n// Regenerate: make generate (codegen/lib/typescript_types/table_modules.ml)\n\nimport type { tables } from './types';\n\nimport { HttpStatus } from './held-kinds';\n\n/** protocol/specs/src/retry/rules.json, as `RetryRules` types it. */\nexport const RETRY_RULES: tables['RetryRules'] = {\n $comment:\n \"What each retry rule retries, as sets: retry/cases.json's rows are examples of them, and its `$comment` says what each rule is for. `boot` and `job` are asked only about a status, and retry one of `statuses` or, for `job`, one at or above `statusFrom`. `transport` retries one of `statuses` when the request carries an `Idempotency-Key` or its method is one of `idempotentMethods`, and nothing with no status: a request whose connection failed is the transport's to send again, not this rule's (contract/TRANSPORT-CONTRACT.md). A session's ask of who its token is, which `validate` makes, is no request this rule is asked about: it is sent again only for want of an answer, and never after a status, 503 among them (contract/TRANSPORT-CONTRACT.md § Failures; specs/src/session/cases.json, `startup`). `refresh` retries one of `statuses`, one at or above `statusFrom`, and, as `noResponse` says, an exchange the issuer did not answer. `follow` is asked only about the code a job's follower's ask for the job's status failed with, and asks it again at its next poll when the code is one of `codes`. No rule retries 401: a refused credential is renewed before any rule is asked.\",\n boot: {\n statuses: [HttpStatus(429), HttpStatus(503), HttpStatus(504)],\n },\n job: {\n statuses: [HttpStatus(408), HttpStatus(429)],\n statusFrom: HttpStatus(500),\n },\n transport: {\n statuses: [\n HttpStatus(408),\n HttpStatus(413),\n HttpStatus(429),\n HttpStatus(500),\n HttpStatus(502),\n HttpStatus(503),\n HttpStatus(504),\n ],\n idempotentMethods: ['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS', 'TRACE'],\n },\n refresh: {\n statuses: [HttpStatus(408), HttpStatus(429)],\n statusFrom: HttpStatus(500),\n noResponse: true,\n },\n follow: {\n codes: [\n 'bus.timeout',\n 'bus.peer-unavailable',\n 'rate-limited',\n 'unavailable',\n ],\n },\n};\n","/**\n * Which failures are worth another attempt — one catalog, several contexts.\n *\n * **Not `RetryBudget`, which is next door and means something else.** That is a\n * timing budget: how long to keep trying. A `RetryRule` is which failures to try\n * again at all. A transport's `emitRetry: RetryBudget` and `RETRY_RULES.boot` answer\n * different questions about the same attempt.\n *\n * ## Why one file, when the contexts genuinely differ\n *\n * They do differ, and collapsing them to one answer would break something: a\n * `500` mid-job is worth another attempt, where the same `500` in a boot pass\n * replays whatever broke it. The defect being fixed is not divergence — it is\n * that the divergence was **undeclared**. Four sites decided this question, two\n * with an argument and two with a bare list, and no reader of any file could see\n * that the others existed. Where a list and an argument disagreed, the list won\n * silently.\n *\n * So the rules sit together *because* they disagree. A reader comparing two lines\n * here sees a decision; a reader of one package could only ever see a default.\n *\n * This is the opposite call from `retry.ts`'s \"judgment with its caller\", and\n * deliberately: that rule governs timing budgets, where one number shared across\n * peers that answer differently caused a measured bug. Here the failure mode is\n * invisibility, and co-location is its cure. A context still owns its *choice* —\n * it picks a rule by name — it does not own a private copy of the reasoning.\n *\n * ## The census gate is reachability\n *\n * Rules are exported only through `RETRY_RULES`. A rule missing from that record\n * cannot be consumed, which is a stronger gate than a parallel list a new rule\n * could simply be left out of.\n */\n\nimport { RETRY_RULES as SETS } from './retry-sets';\n\n/**\n * What is known about a failure at the moment someone asks.\n *\n * `method` and `keyed` exist because retryability depends on the REQUEST as well\n * as the failure: a `504` on a GET is safe to repeat, a `504` on a POST may\n * already have been processed upstream, unless the POST carries a key the server\n * answers its repeat by. Optional, because only the transport rule has an\n * answer for them — and unstated reads as unsafe rather than as permission.\n *\n * Deliberately not a `ReadonlySet<number>`: a status set cannot say *`5xx` on\n * idempotent methods only*, which is exactly what the transport needs to say.\n */\nexport interface RetryFacts {\n status?: number;\n /** HTTP method, any case. Absent means \"not stated\", which is treated as unsafe. */\n method?: string;\n /**\n * Whether the request carries an `Idempotency-Key`. Absent means it carries\n * none, as a row of protocol/specs/src/retry/cases.json that omits it states.\n */\n keyed?: boolean;\n /**\n * The code the request failed with, as its error carries it: a\n * `RequestFailureCode` (`requestFailureCode`). Only the follow rule has an\n * answer for it.\n */\n code?: string;\n}\n\nexport interface RetryRule {\n readonly name: string;\n /** Why this context answers the way it does. Not decoration: the two bare\n * lists this taxonomy replaces were bare because nobody had to write one. */\n readonly rationale: string;\n retryable(facts: RetryFacts): boolean;\n}\n\nconst listed = (statuses: readonly number[], status: number): boolean =>\n statuses.includes(status);\n\nconst boot: RetryRule = {\n name: 'boot',\n rationale:\n 'A boot pass or a bus request, where the peer is usually seconds from being ready. ' +\n '429/503/504 are the server saying \"up, but not now\" — retrying is compliance with its ' +\n 'own instruction. 500 is excluded on the record: 503 and 504 are promises to recover, ' +\n 'an unclassified server fault is not, and replaying it inside a boot pass re-runs ' +\n 'whatever broke it. Auth and validation failures stay out for the same reason a 401 ' +\n 'does — the gateway is up and rejected us.',\n retryable: ({ status }) =>\n status !== undefined && listed(SETS.boot.statuses, status),\n};\n\nconst job: RetryRule = {\n name: 'job',\n rationale:\n 'A job retry budget, where the cost of NOT retrying is a discarded long-running ' +\n 'attempt. 5xx is included where the boot rule excludes it, because the alternative is ' +\n 'throwing away paid work over one unclassified fault. 408 joins as an explicit timeout. ' +\n 'The price of a wrong \"transient\" is a re-pay, not a corrupted write — which is what ' +\n 'makes the wider answer affordable here and not at boot. Two facts, both settled ' +\n '2026-09-12, say how affordable: a 5xx arriving at a job has ALREADY failed three ' +\n 'times at the call (the inference client retries twice, a count chosen explicitly ' +\n 'rather than inherited from the vendor SDK), so this is a considered second chance ' +\n 'rather than a hair-trigger; and since a retried job resumes mid-unit from its ' +\n 'checkpointed cursor, the re-pay is about ONE CHUNK, not the whole prefix it used ' +\n 'to be (~26 min on the 1958 document). Both push the same way. ' +\n 'If either changes — the client stops retrying, or resume stops working — this rule ' +\n 'is the line to revisit.',\n retryable: ({ status }) =>\n status !== undefined &&\n (listed(SETS.job.statuses, status) || status >= SETS.job.statusFrom),\n};\n\nconst transport: RetryRule = {\n name: 'transport',\n rationale:\n \"An HTTP client's request. A retryable status applies only where a repeat cannot cause a \" +\n 'second effect: on an idempotent method, or on a request that carries an Idempotency-Key, ' +\n 'whose repeat the server answers as it answered the first. A POST with no key that got a ' +\n '502 may already have been processed, so a repeat could do it twice. The method and the ' +\n 'key are enough: no per-endpoint registry. A key makes a repeat harmless, not a refused ' +\n 'request acceptable, so a 400 or 422 stays final. A 401 is not retried: a refused ' +\n 'credential is renewed before any rule is asked, and the same token gets the same answer.',\n retryable: ({ status, method, keyed }) => {\n if (status === undefined) return false;\n const repeatable =\n keyed === true ||\n (method !== undefined &&\n SETS.transport.idempotentMethods.includes(method.toUpperCase()));\n return repeatable && listed(SETS.transport.statuses, status);\n },\n};\n\nconst refresh: RetryRule = {\n name: 'refresh',\n rationale:\n \"Exchanging a refresh token at its issuer. The issuer's answer is the verdict and its \" +\n 'absence never is: a refused grant (RFC 6749 §5.2 returns 400 `invalid_grant` for a ' +\n 'revoked, expired or already-rotated token) is terminal on the first answer, because ' +\n 'retrying cannot change it and only delays a re-login the user must perform anyway. No ' +\n 'response at all, or one saying \"not now\" (408, 429, 5xx), is transient — the session ' +\n 'survives a lost packet. 5xx is included where the boot rule excludes it, and the two are ' +\n 'not in conflict: a boot pass replays whatever broke it, while this is a single idempotent ' +\n 'exchange with no side effect to replay. Unclassified faults are TERMINAL, which inverts ' +\n 'the usual instinct deliberately — a 404 on the token endpoint is a misconfiguration, not ' +\n 'a promise to recover, and over-retrying here shows the user a hung app instead of the ' +\n 'honest re-login.',\n retryable: ({ status }) => {\n // No status means `fetch` threw before there was a response — the network,\n // not the issuer. That is the case this rule exists to keep alive, so it is\n // the one place absence reads as permission rather than as refusal.\n if (status === undefined) return SETS.refresh.noResponse;\n return (\n listed(SETS.refresh.statuses, status) || status >= SETS.refresh.statusFrom\n );\n },\n};\n\nconst follow: RetryRule = {\n name: 'follow',\n rationale:\n \"A job's follower's ask for the job's status, asked about the code the ask failed \" +\n 'with. Asking again is how a follower that heard nothing learns how its job ended, so ' +\n 'a failure that may pass is asked again at the next poll: a reply that did not come in ' +\n 'time, an answering service not yet connected, a limit, a gateway that could not be ' +\n 'reached. Any other ends the follower with its code, never the job: asking again cannot ' +\n 'mend it, and a follower that asked forever would never say so.',\n retryable: ({ code }) => SETS.follow.codes.some((asked) => asked === code),\n};\n\n/**\n * Every rule, and the only way to reach one.\n *\n * Frozen and exhaustive on purpose — see the census-gate note above.\n */\nexport const RETRY_RULES = Object.freeze({\n boot,\n follow,\n job,\n refresh,\n transport,\n});\n","/**\n * Base64url (RFC 4648 section 5), unpadded: what the id of an annotation is\n * cut from, a JWT's segments are written in, and a person's key and a\n * sign-in's PKCE values are spelled in.\n */\nexport function base64url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n","/**\n * The replacer the JSON the SDK sends and keeps is written with\n * (`JSON.stringify(value, refuseNonFinite)`): it refuses a NaN or an\n * infinity, which JSON has no text for and RFC 8785 refuses to write, where\n * `JSON.stringify` alone would write `null` in its place. The refusal is a\n * `TypeError`, as `JSON.stringify`'s own refusal of what does not encode is.\n */\nexport function refuseNonFinite(key: string, value: unknown): unknown {\n if (typeof value === 'number' && !Number.isFinite(value))\n throw new TypeError(\n `${key === '' ? 'The value' : `The member ${key}`} is ${String(value)}, which is no number JSON writes`,\n );\n return value;\n}\n","/**\n * SHA-256 (FIPS 180-4), for the id of an annotation (`annotation-id.ts`), the\n * thumbprint a service account's key is named by (`client-assertion.ts`), and\n * `@xynolog/sdk`'s PKCE challenge of a sign-in and the person key a client's\n * kept caches are held under.\n *\n * The platform's own is `crypto.subtle.digest`. It answers later, where an id\n * is worked out at once; and a browser withholds `crypto.subtle` from a page\n * that is not a secure context, one served over plain http from any host but\n * localhost, where this package runs too. This is the one implementation the\n * id uses, in every context: a branch that preferred the platform's where it\n * exists would be a second implementation of one hash, run only where nobody\n * tests.\n *\n * Nothing secret is hashed with it. An id is a public derivation of what an\n * annotation is, a thumbprint of a key's public half, and a PKCE challenge a\n * public derivation of a value the client sends anyway, so a wrong digest\n * cannot leak anything: it fails where it can be seen, in the id's, the\n * assertion's and the person key's case tables, and in a refused exchange.\n */\n\n/** The first 32 bits of the fractional parts of the cube roots of the first 64 primes. */\nconst K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,\n 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,\n 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,\n 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,\n 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nconst rotr = (x: number, n: number): number => (x >>> n) | (x << (32 - n));\n\nexport function sha256(message: Uint8Array): Uint8Array {\n // Padding: a 1 bit, zeros, then the message's length in bits as 64 bits,\n // big-endian, ending on a block boundary.\n const padded = new Uint8Array(\n (Math.floor((message.length + 8) / 64) + 1) * 64,\n );\n padded.set(message);\n padded[message.length] = 0x80;\n const blocks = new DataView(padded.buffer);\n const bits = message.length * 8;\n blocks.setUint32(padded.length - 8, Math.floor(bits / 0x1_0000_0000));\n blocks.setUint32(padded.length - 4, bits >>> 0);\n\n // The first 32 bits of the fractional parts of the square roots of the first 8 primes.\n let [h0, h1, h2, h3, h4, h5, h6, h7] = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,\n 0x1f83d9ab, 0x5be0cd19,\n ];\n const w = new Uint32Array(64);\n\n for (let block = 0; block < padded.length; block += 64) {\n for (let t = 0; t < 16; t++) w[t] = blocks.getUint32(block + t * 4);\n for (let t = 16; t < 64; t++) {\n const w15 = w[t - 15]!;\n const w2 = w[t - 2]!;\n const s0 = rotr(w15, 7) ^ rotr(w15, 18) ^ (w15 >>> 3);\n const s1 = rotr(w2, 17) ^ rotr(w2, 19) ^ (w2 >>> 10);\n w[t] = w[t - 16]! + s0 + w[t - 7]! + s1;\n }\n\n let [a, b, c, d, e, f, g, h] = [h0, h1, h2, h3, h4, h5, h6, h7];\n for (let t = 0; t < 64; t++) {\n const t1 =\n (h +\n (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) +\n ((e & f) ^ (~e & g)) +\n K[t]! +\n w[t]!) >>>\n 0;\n const t2 =\n ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) +\n ((a & b) ^ (a & c) ^ (b & c))) >>>\n 0;\n h = g;\n g = f;\n f = e;\n e = (d + t1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) >>> 0;\n }\n\n h0 = (h0 + a) >>> 0;\n h1 = (h1 + b) >>> 0;\n h2 = (h2 + c) >>> 0;\n h3 = (h3 + d) >>> 0;\n h4 = (h4 + e) >>> 0;\n h5 = (h5 + f) >>> 0;\n h6 = (h6 + g) >>> 0;\n h7 = (h7 + h) >>> 0;\n }\n\n const digest = new Uint8Array(32);\n const words = new DataView(digest.buffer);\n [h0, h1, h2, h3, h4, h5, h6, h7].forEach((word, i) =>\n words.setUint32(i * 4, word),\n );\n return digest;\n}\n","/**\n * The id of an annotation a builder makes: worked out from what the\n * annotation is, never minted. protocol/specs/src/annotations/id-cases.json holds the\n * rule, for this and for every other implementation.\n *\n * The builders (`annotation-builders.ts`) are its callers, and no one else\n * is: it is no part of what `@xynolog/core` or `@xynolog/sdk` exports.\n */\n\nimport { base64url } from './base64url';\nimport { byCodePoint } from './by-code-point';\nimport { annotationId } from './identifiers';\nimport { refuseNonFinite } from './refuse-non-finite';\nimport { sha256 } from './sha256';\nimport type { AnnotationId } from './types';\n\n/** The identity of an annotation — everything that makes it that annotation\n * and nothing else: the inputs its content-addressed id is hashed from. */\nexport interface AnnotationIdentity {\n /** The resource the annotation is about. */\n resourceId: string;\n /** W3C motivation: two motivations on one span are two annotations. */\n motivation: string;\n /**\n * The span, rendered by the builder that anchored it. Deliberately a\n * caller-supplied STRING rather than a structured span: text anchors by\n * character offset and PDF by page geometry, so there is no shape both\n * share, and inventing one here would be a third home for a fact the\n * builders already own. An annotation of a resource as a whole is anchored\n * nowhere on it, and its anchor is the empty string.\n */\n anchor: string;\n /**\n * The annotation's body, when it has one.\n *\n * Included for EVERY motivation that carries one, which is every\n * motivation except `highlighting`. The body matters beyond `commenting`:\n * the same collision exists for `assessing` and `tagging` (two assessments\n * of one span differ solely by their text), and for `linking`: a detected\n * reference carries its entity\n * type as an unresolved TextualBody, which is exactly the \"type\" in the\n * identity a detected annotation needs (resource, span, type, motivation).\n * So a per-motivation table of hash inputs collapses to one rule — hash the\n * body whenever there is one — and that is better than a table, because a\n * sixth motivation inherits the right behavior instead of an omission.\n */\n body?: unknown;\n}\n\n/**\n * Canonical JSON: an object's members in the order of their names by code\n * point, at every depth, so a body built by one code path hashes the same as\n * an equivalent body built by another, in any language. Array order is\n * preserved — it is meaningful (a tagging body is [category, schema]).\n */\nfunction canonical(value: unknown): string {\n if (value === null || typeof value !== 'object')\n return JSON.stringify(value, refuseNonFinite) ?? 'null';\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => byCodePoint(a, b));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;\n}\n\n/**\n * The annotation's id, derived from what the annotation IS.\n *\n * This is what makes every job-recovery path idempotent: a\n * re-queued job, a resumed unit and a retried failure all re-emit the same\n * annotation, and re-emitting it is a no-op *with no read* — which is the\n * property a read-before-write could not provide, because the thing it would\n * read is exactly what is down when recovery is happening.\n *\n * Note what is NOT an input: `created`, the emitting worker, the job id, any\n * counter. A recovery re-emits at a different time from a different process\n * and must still collide, so anything about the emission rather than the\n * annotation would defeat the whole mechanism.\n *\n * 21 base64url characters of a SHA-256: ~126 bits, which is far more than a\n * per-resource span space needs.\n *\n * ## The no-op guarantee is conditional on `anchor`, and the two kinds of span differ\n *\n * \"Re-emitting is a no-op\" holds exactly as far as `anchor` is stable, and that\n * is the builder's property, not this function's. `annotationOfSpan` does not\n * have it equally for its two kinds of span:\n *\n * - **A span of a text** is anchored as `${start}:${end}:${exact}` and the\n * annotation STORES those offsets in a `TextPositionSelector`. Identity depends\n * only on fields the annotation carries, so the guarantee is unconditional and\n * any reader can verify it after the fact.\n * - **A span of a PDF's anchored text** is anchored the same way, but the offsets\n * come from a text layer *derived* per attempt and are deliberately NOT stored —\n * the annotation carries page geometry and the quoted text instead. There the\n * guarantee holds only while that derivation is stable, and a reader holding two\n * annotations cannot tell whether they disagree because they are different facts\n * or because the text layer moved: every stored field would be identical.\n *\n * The derivation is cached per content checksum, but the entry is gated by a stamp\n * over the Smelter's version, its PDF reader and its OCR engine\n * (`xynolog_smelter.stamp`, in images/smelter), and that stamp is deliberately\n * over-eager — **a release busts it and the same bytes are re-extracted by\n * different code.** So the honest statement is: the PDF path's guarantee holds\n * *per stamp generation*, and a release is the event that could end one.\n */\nexport function annotationIdFor(identity: AnnotationIdentity): AnnotationId {\n const material = canonical({\n resourceId: identity.resourceId,\n motivation: identity.motivation,\n anchor: identity.anchor,\n ...(identity.body !== undefined ? { body: identity.body } : {}),\n });\n const digest = base64url(sha256(new TextEncoder().encode(material)));\n return annotationId(digest.slice(0, 21));\n}\n","/**\n * Where an offset into a text meets a JavaScript string.\n *\n * A text offset, on the wire, in the record and in every store, counts\n * Unicode code points from the start of the text: the W3C Web Annotation\n * rule, and the same count in every language. A JavaScript string is indexed\n * in UTF-16 code units, where a character outside the Basic Multilingual\n * Plane is two. The two counts agree until the first such character and\n * differ by one more after each.\n *\n * So arithmetic is done on offsets, and a length is a difference of two of\n * them: every count a rule states is of code points. A string's own position\n * is only ever the argument or the result of a call on the string (a slice, a\n * search, a regular expression's index), and is converted there.\n * protocol/specs/src/text/offset-cases.json holds the count, for this and for every\n * other implementation.\n */\n\n/** A text's offsets and a string's positions, each given the other. */\nexport interface TextOffsets {\n /** How many code points the text is. An offset may equal it and may not exceed it. */\n readonly length: number;\n /** The offset of a position in the string: how many code points are before it. */\n offsetAt(index: number): number;\n /** The position in the string of an offset. */\n indexAt(offset: number): number;\n}\n\nconst isHigh = (unit: number): boolean => unit >= 0xd800 && unit <= 0xdbff;\nconst isLow = (unit: number): boolean => unit >= 0xdc00 && unit <= 0xdfff;\n\n/** Whether the string has, at `index`, the two units of one character outside the basic plane. */\nconst isPairAt = (text: string, index: number): boolean =>\n isHigh(text.charCodeAt(index)) && isLow(text.charCodeAt(index + 1));\n\n/** How many of `sorted` are less than `value`. */\nfunction countBelow(sorted: readonly number[], value: number): number {\n let low = 0;\n let high = sorted.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (sorted[middle]! < value) low = middle + 1;\n else high = middle;\n }\n return low;\n}\n\n/**\n * The conversions for one text, made once and asked as often as the text has\n * offsets. Making it reads the text once; each conversion after that is a\n * search among the text's characters outside the basic plane, of which most\n * texts have none.\n *\n * Half of a pair on its own counts as a code point, as the string's own\n * iteration counts it: an ill-formed string is still a text with offsets.\n */\nexport function textOffsets(text: string): TextOffsets {\n /** The position of each character outside the basic plane: of the first unit of its pair. */\n const pairs: number[] = [];\n for (let index = 0; index < text.length - 1; index++) {\n if (isPairAt(text, index)) {\n pairs.push(index);\n index++;\n }\n }\n /** The offset of each of those characters: its position, less the pairs before it. */\n const pairOffsets = pairs.map((index, before) => index - before);\n const length = text.length - pairs.length;\n\n return {\n length,\n offsetAt(index: number): number {\n if (!Number.isInteger(index) || index < 0 || index > text.length) {\n throw new RangeError(\n `position ${index} is not in a string of ${text.length} units`,\n );\n }\n // A pair that begins before `index` is wholly before it, or `index` is its second unit.\n const before = countBelow(pairs, index);\n if (before > 0 && pairs[before - 1]! + 1 === index) {\n throw new RangeError(\n `position ${index} is inside a character: it has no offset`,\n );\n }\n return index - before;\n },\n indexAt(offset: number): number {\n if (!Number.isInteger(offset) || offset < 0 || offset > length) {\n throw new RangeError(\n `offset ${offset} is not in a text of ${length} code points`,\n );\n }\n // Each character outside the basic plane before the offset is one more unit of the string.\n return offset + countBelow(pairOffsets, offset);\n },\n };\n}\n\n/**\n * The text from one offset to another. `offsets` is the text's own, and each\n * of the two is an offset of the text, the first no greater than the second:\n * `indexAt` throws at a number that is no offset of the text.\n */\nexport function between(\n text: string,\n offsets: TextOffsets,\n start: number,\n end: number,\n): string {\n return text.slice(offsets.indexAt(start), offsets.indexAt(end));\n}\n\n/**\n * Every place `text` has `words`, as the offset each starts at, in the text's\n * order. Places may overlap. `offsets` is the text's own.\n *\n * A string is searched by its code units, so a search for words that begin or\n * end with half of a pair also finds them inside a character of the text. The\n * text does not have those words there, character for character, and the\n * position has no offset: it is no place.\n */\nexport function occurrencesOf(\n text: string,\n offsets: TextOffsets,\n words: string,\n): number[] {\n const places: number[] = [];\n let index = text.indexOf(words);\n while (index !== -1) {\n const end = index + words.length;\n if (!isPairAt(text, index - 1) && !isPairAt(text, end - 1))\n places.push(offsets.offsetAt(index));\n // Words of no length are found at the end of the text too, and a search\n // from past the end finds them there again.\n index = index < text.length ? text.indexOf(words, index + 1) : -1;\n }\n return places;\n}\n","/**\n * Fuzzy Anchoring for W3C Web Annotation TextQuoteSelector\n *\n * The searches a quote is put through when a text does not have it character\n * for character: without regard to white space and to the form of quotation\n * marks and dashes, without regard to letter case, and by edit distance.\n * protocol/specs/src/annotations/reconcile-cases.json holds the rule.\n *\n * A position in a text is an offset: it counts Unicode code points from the\n * start of the text, and so does every length a rule here states (the\n * stretch a quote is compared with, its allowance, an edit). A string's own\n * positions are converted with `textOffsets`, where the string is called.\n *\n * @see https://www.w3.org/TR/annotation-model/#text-quote-selector\n */\n\nimport { occurrencesOf, textOffsets, type TextOffsets } from './text-offsets';\n\nimport type { MatchQuality } from './types';\n\n/**\n * Normalize text for comparison - handles common document editing changes\n *\n * Collapses whitespace, converts curly quotes to straight quotes,\n * and normalizes common punctuation variations.\n */\nexport function normalizeText(text: string): string {\n return text\n .replace(/\\s+/g, ' ') // collapse whitespace\n .replace(/[\\u2018\\u2019]/g, \"'\") // curly single quotes → straight\n .replace(/[\\u201C\\u201D]/g, '\"') // curly double quotes → straight\n .replace(/\\u2014/g, '--') // em-dash → double hyphen\n .replace(/\\u2013/g, '-') // en-dash → hyphen\n .trim();\n}\n\n/**\n * The edit distance between `wanted` and every stretch of `text` that starts\n * at `from`, up to one of `longest` code points: `distances[n]` is the least\n * number of single code points inserted, deleted or replaced that turns\n * `wanted` into the `n` code points from `from`. `null` when no stretch from\n * there is within `allowance`.\n *\n * Both are code points, one to an element, so an edit is of one code point.\n */\nfunction distancesFrom(\n wanted: readonly string[],\n text: readonly string[],\n from: number,\n longest: number,\n allowance: number,\n): number[] | null {\n // From none of `wanted`, a stretch of `n` code points is `n` insertions away.\n let row = Array.from({ length: longest + 1 }, (_, n) => n);\n let next = new Array<number>(longest + 1);\n\n for (let i = 1; i <= wanted.length; i++) {\n next[0] = i;\n let least = i;\n for (let n = 1; n <= longest; n++) {\n const cost = wanted[i - 1] === text[from + n - 1] ? 0 : 1;\n const distance = Math.min(\n row[n]! + 1,\n next[n - 1]! + 1,\n row[n - 1]! + cost,\n );\n next[n] = distance;\n if (distance < least) least = distance;\n }\n // The least distance of a row never falls as more of `wanted` is taken.\n if (least > allowance) return null;\n [row, next] = [next, row];\n }\n\n return row;\n}\n\n/**\n * Pre-computed content strings for batch fuzzy matching.\n * Avoids recomputing normalizeText(content) and content.toLowerCase()\n * for every annotation when processing many annotations against the same content.\n *\n * `normalizedMap[i]` is the offset, in the original content, of the\n * character that the code point at offset `i` of `normalizedContent` came\n * from, and `lowerMap[i]` the same for `lowerContent`: an entry for each code\n * point of the changed copy. A map is how `findBestTextMatch` answers a match\n * in a copy as a span of the content itself. For the normalized copy,\n * counting char-by-char with `normalizeText(singleChar)` is wrong, because a\n * lone whitespace char trims to `''` (contributing 0) while in a full-string\n * normalize it collapses to a single space (contributing 1). That discrepancy\n * shifts recovered offsets by the number of whitespace runs before the match.\n */\nexport interface ContentCache {\n normalizedContent: string;\n /** The normalized content's own conversions: it is another string. */\n normalizedOffsets: TextOffsets;\n normalizedMap: number[];\n lowerContent: string;\n /** The lower-cased content's own conversions: it is another string, of another length where lower-casing changes one. */\n lowerOffsets: TextOffsets;\n lowerMap: number[];\n}\n\n/**\n * Normalize text and, in the same pass, build a map from each offset of the\n * normalized text back to the offset, in the input, of the character it\n * came from. Both count code points: the map has one entry for each code\n * point of the normalized text.\n * The produced `normalized` string is identical to `normalizeText(input)`\n * — a test pins this equivalence so the two can't drift.\n */\nexport function normalizeTextWithMap(input: string): {\n normalized: string;\n map: number[];\n} {\n let normalized = '';\n const map: number[] = [];\n\n // First pass mirrors normalizeText exactly, char by char, recording the\n // origin offset for every emitted normalized character.\n let pendingWhitespaceStart = -1; // origin offset of an open whitespace run, or -1\n\n const flushWhitespace = () => {\n if (pendingWhitespaceStart !== -1) {\n // A whitespace run collapses to a single space, mapped to the run's\n // first char — but a *leading* run (nothing emitted yet) is dropped,\n // matching normalizeText's trailing `.trim()`.\n if (normalized.length > 0) {\n normalized += ' ';\n map.push(pendingWhitespaceStart);\n }\n pendingWhitespaceStart = -1;\n }\n };\n\n // The offset of `ch`: how many code points of `input` are before it. A\n // string is walked a code point at a time, so it is one more for each.\n let offset = 0;\n for (const ch of input) {\n if (/\\s/.test(ch)) {\n if (pendingWhitespaceStart === -1) pendingWhitespaceStart = offset;\n offset++;\n continue;\n }\n flushWhitespace();\n if (ch === '‘' || ch === '’') {\n normalized += \"'\";\n map.push(offset);\n } else if (ch === '“' || ch === '”') {\n normalized += '\"';\n map.push(offset);\n } else if (ch === '—') {\n normalized += '--';\n map.push(offset);\n map.push(offset);\n } else if (ch === '–') {\n normalized += '-';\n map.push(offset);\n } else {\n normalized += ch;\n map.push(offset);\n }\n offset++;\n }\n // A trailing whitespace run is dropped by trim — do not flush it.\n\n // `normalizeText` applies `.trim()` last. Our run logic already drops a\n // trailing whitespace run; a leading run is dropped because flushWhitespace\n // only runs before a non-space char, so a run at the very start is never\n // emitted. Both ends match trim().\n return { normalized, map };\n}\n\n/**\n * Lower-case text and build a map from each offset of the lower-cased text\n * back to the offset, in the input, of the character it came from. Both\n * count code points.\n *\n * The text is lower-cased whole, by Unicode's rule of no particular language:\n * a capital sigma that ends a word becomes the final one, which lower-casing\n * a character at a time would miss. A character becomes as many code points\n * whole as alone (U+0130, a capital I with a dot, becomes two), which is what\n * the map is counted from.\n */\nexport function lowerCaseWithMap(input: string): {\n lowered: string;\n map: number[];\n} {\n const lowered = input.toLowerCase();\n const map: number[] = [];\n let offset = 0;\n for (const ch of input) {\n const codePoints = Array.from(ch.toLowerCase()).length;\n for (let n = 0; n < codePoints; n++) map.push(offset);\n offset++;\n }\n if (map.length !== textOffsets(lowered).length) {\n throw new Error(\n 'a text lower-cased whole is not as long as its characters lower-cased one at a time',\n );\n }\n return { lowered, map };\n}\n\n/**\n * Build a ContentCache for a given content string.\n * Call once per content, pass to findBestTextMatch for every search of it.\n */\nexport function buildContentCache(content: string): ContentCache {\n const { normalized, map } = normalizeTextWithMap(content);\n const { lowered, map: lowerMap } = lowerCaseWithMap(content);\n return {\n normalizedContent: normalized,\n normalizedOffsets: textOffsets(normalized),\n normalizedMap: map,\n lowerContent: lowered,\n lowerOffsets: textOffsets(lowered),\n lowerMap,\n };\n}\n\n/**\n * The span of the content that a match in a changed copy of it came from:\n * `length` code points of the copy from the offset `at`. It starts at the\n * character the match's first code point came from and ends just after the\n * character its last came from, so a character that became several code\n * points is in the span whole, and white space the content has after the\n * match is not in it.\n */\nfunction spanOf(\n map: readonly number[],\n at: number,\n length: number,\n): { start: number; end: number } {\n return { start: map[at]!, end: map[at + length - 1]! + 1 };\n}\n\n/**\n * Find text that the content does not have character for character, using\n * multi-strategy search: the strictest of the looser searches that finds it\n * at all answers, with every place it finds it.\n *\n * The search `reconcile` (write-time) falls back on, having looked for the\n * text as it is.\n *\n * @param content - Full text content to search within\n * @param searchText - The text to find\n * @param cache - What is made once for the content (from buildContentCache)\n * @returns The places found, each two offsets in code points, in the content's order, and the search that found them; or null if none did\n */\nexport function findBestTextMatch(\n content: string,\n searchText: string,\n cache: ContentCache,\n): {\n places: Array<{ start: number; end: number }>;\n matchQuality: MatchQuality;\n} | null {\n // Nothing, or only white space, is no words to find: it is in no place.\n if (searchText.trim() === '') return null;\n\n // Strategy 1: Normalized match (handles whitespace/quote variations).\n // Each place in the normalized content is answered as the span of the\n // content it came from, through the precomputed offset map.\n const normalizedSearch = normalizeText(searchText);\n const normalizedLength = textOffsets(normalizedSearch).length;\n const normalized = occurrencesOf(\n cache.normalizedContent,\n cache.normalizedOffsets,\n normalizedSearch,\n );\n if (normalized.length > 0) {\n return {\n places: normalized.map((at) =>\n spanOf(cache.normalizedMap, at, normalizedLength),\n ),\n matchQuality: 'normalized',\n };\n }\n\n // Strategy 2: Case-insensitive match. Each place in the lower-cased\n // content is answered as the span of the content it came from: lower-casing\n // changes how many code points some characters are.\n const lowerSearch = searchText.toLowerCase();\n const lowerLength = textOffsets(lowerSearch).length;\n const lowered = occurrencesOf(\n cache.lowerContent,\n cache.lowerOffsets,\n lowerSearch,\n );\n if (lowered.length > 0) {\n return {\n places: lowered.map((at) => spanOf(cache.lowerMap, at, lowerLength)),\n matchQuality: 'case-insensitive',\n };\n }\n\n // Strategy 3: Fuzzy match by edit distance, over every stretch of the\n // content. The search text is a code point to an element: its length is a\n // count of code points, and so is the stretch of content it is compared\n // with. The allowance is a twentieth of that length, with no minimum.\n const wanted = Array.from(searchText);\n const allowance = Math.floor(wanted.length / 20);\n // A stretch at no distance is the search text itself, which the content does not have.\n if (allowance === 0) return null;\n\n const text = Array.from(content);\n // A stretch within the allowance is at most the allowance shorter or longer than the search text.\n const shortest = wanted.length - allowance;\n let best: { start: number; end: number; distance: number } | null = null;\n\n // Of several stretches at the least distance, the one that starts first is\n // taken; of those from one start, the one nearest the search text in\n // length; and of two as near, the shorter. So from each start the stretch as\n // long as the search text is tried first, then the one a code point shorter\n // and the one a code point longer, and so on out.\n for (let start = 0; start + shortest <= text.length; start++) {\n const longest = Math.min(wanted.length + allowance, text.length - start);\n const distances = distancesFrom(wanted, text, start, longest, allowance);\n if (distances === null) continue;\n for (let away = 0; away <= allowance; away++) {\n for (const length of away === 0\n ? [wanted.length]\n : [wanted.length - away, wanted.length + away]) {\n if (length > longest) continue;\n const distance = distances[length]!;\n if (\n distance <= allowance &&\n (best === null || distance < best.distance)\n ) {\n best = { start, end: start + length, distance };\n }\n }\n }\n }\n\n if (best === null) return null;\n return {\n places: [{ start: best.start, end: best.end }],\n matchQuality: 'fuzzy',\n };\n}\n","/**\n * Text ↔ geometry anchoring for PDFs.\n *\n * Two directions over the same pairing of text and the runs that index it:\n * `locate` turns a span of the text into rectangles (an annotation the model\n * produced by quoting text), `textUnder` turns a rectangle into text (an\n * annotation a person produced by dragging a box). They are inverses and live\n * together deliberately.\n *\n * A span, like an item's `start` and `end`, is two offsets: they count\n * Unicode code points from the start of the text.\n *\n * This is pure arithmetic over plain data, so it sits here beside\n * `PdfCoordinate` and the viewrect codec: the browser canvas needs\n * `textUnder` at drag time, over the document's text as it was served.\n * *Producing* an `AnchoredText`, from a text layer or from OCR, is the\n * Smelter's.\n *\n * Coordinates are PDF points with the origin at the bottom-left of the page,\n * Y increasing upward. The Y-flip to canvas pixels lives in the browser.\n */\n\nimport { textOffsets } from './text-offsets';\nimport type { PdfTextItem, AnchoredText, PdfCoordinate } from './types';\n\n/**\n * Items whose baseline Y is within this many PDF points are treated as being on\n * the same line. Tuned for ~12pt body text; revisit for documents with large or\n * variable font sizes (deferred hardening, #738).\n */\nconst SAME_LINE_THRESHOLD_PT = 2;\n\n/**\n * Locates bounding rectangles for a span of text in an AnchoredText\n * (single-line or multi-line).\n *\n * `start` and `end` are offsets into `anchored.text`, in code points, as the\n * items' own are. Nothing here reads the text, so nothing is converted: the\n * arithmetic is on offsets throughout.\n *\n * Finds all overlapping items [start, end), groups them by page and line, and\n * records one bounding rectangle per line as a PdfCoordinate.\n *\n * Returns both the per-line `rects` and the `overlap` items they were computed\n * from — so a caller that also needs the covered text (`annotationOfSpan`,\n * which holds a PDF's span to the text its rectangles cover) reuses this single `items` scan\n * instead of re-filtering. Both arrays are empty if no item overlaps the span:\n * an empty span (`start` equal to `end`) overlaps none, wherever it falls.\n */\nexport function locate(\n anchored: AnchoredText,\n start: number,\n end: number,\n): { rects: PdfCoordinate[]; overlap: PdfTextItem[] } {\n // An empty span has no character for an item to hold, inside one as between two.\n if (start === end) return { rects: [], overlap: [] };\n\n const overlap: PdfTextItem[] = anchored.items.filter(\n (item) => item.start < end && item.end > start,\n );\n if (overlap.length === 0) return { rects: [], overlap };\n\n const pages: Map<number, PdfTextItem[]> = groupItemsByPage(overlap);\n const rects: PdfCoordinate[] = [];\n\n // for each page, group items into lines and compute one rectangle per line\n for (const [page, pageItems] of pages) {\n const lines = groupItemsByLine(pageItems, SAME_LINE_THRESHOLD_PT);\n // Compute one bounding rectangle per line and add it to rects.\n // Boundary items that extend past [start, end) are clipped by the\n // fraction of their code points the span takes: renderers like Typst\n // emit ONE item per line, so without\n // clipping a mid-line phrase would bound the whole line. Proportional\n // interpolation is the measured fallback — exact glyph metrics need\n // the operator-list route, an open refinement, and can replace this\n // arithmetic without changing the shape.\n for (const lineItems of lines) {\n const edges = lineItems.map((i) => {\n const codePoints = i.end - i.start;\n const left =\n i.start < start && codePoints > 0\n ? i.x + i.width * ((start - i.start) / codePoints)\n : i.x;\n const right =\n i.end > end && codePoints > 0\n ? i.x + i.width * ((end - i.start) / codePoints)\n : i.x + i.width;\n return { left, right };\n });\n const x = Math.min(...edges.map((e) => e.left));\n const right = Math.max(...edges.map((e) => e.right));\n const y = Math.min(...lineItems.map((i) => i.y));\n const top = Math.max(...lineItems.map((i) => i.y + i.height));\n rects.push({ page, x, y, width: right - x, height: top - y });\n }\n }\n return { rects, overlap };\n}\n\n/**\n * The inverse of `locate`: given a rectangle, returns the text under it.\n *\n * A hand-drawn PDF rectangle otherwise carries no quoted text at all, so every\n * panel that quotes an annotation shows it blank.\n *\n * `rect` is in the same PDF-point, bottom-left-origin space as `PdfTextItem`,\n * so a canvas drag rectangle passes straight in. A run counts as covered when\n * the rectangle overlaps `RUN_COVERAGE_THRESHOLD` of its area — see there for\n * why any-intersection is not survivable for a hand-drawn box.\n *\n * Covered runs are emitted in reading order (`text` offset order), which\n * inherits the extractor's known column-major ordering on multi-column pages\n * rather than answering it a second, different way.\n *\n * An item's `start` and `end` count code points, so the text of each run is\n * read out of the string through the text's conversions.\n *\n * Returns `''` when nothing is covered — over an image, over whitespace, or\n * over a scanned page with no text layer. Callers must then emit no\n * `TextQuoteSelector` at all: an empty quote would assert the box was drawn\n * around nothing.\n */\nexport function textUnder(anchored: AnchoredText, rect: PdfCoordinate): string {\n const covered = anchored.items\n .filter((item) => item.page === rect.page && covers(item, rect))\n .sort((a, b) => a.start - b.start);\n if (covered.length === 0) return '';\n\n const offsets = textOffsets(anchored.text);\n /** The text between two offsets. */\n const between = (start: number, end: number): string =>\n anchored.text.slice(offsets.indexAt(start), offsets.indexAt(end));\n\n // Join with the document's own separator when the runs are adjacent in\n // `text` — pdf.js splits words at kerning and font changes, so a blanket\n // join(' ') would emit \"aga in\" for a single word. When runs are NOT\n // adjacent the rectangle missed the text between them, so substitute a\n // space rather than splicing in words the box does not cover. (Slicing\n // first-offset..last-offset the way `annotationOfSpan` does is safe there\n // — it only feeds a containment check — but here the result is the stored\n // quote, and on a two-column page it would swallow half of each column.)\n let quoted = between(covered[0].start, covered[0].end);\n for (let i = 1; i < covered.length; i++) {\n const gap = between(covered[i - 1].end, covered[i].start);\n quoted +=\n (gap.trim() === '' ? gap : ' ') +\n between(covered[i].start, covered[i].end);\n }\n return quoted.trim();\n}\n\n/**\n * Fraction of a run's own area a rectangle must overlap for the run to count\n * as covered.\n *\n * Any intersection — the obvious rule, and `locate`'s rule for offsets — is not\n * survivable here, because a hand-drawn box is not a tight box. What decides\n * the threshold is the *headroom* between lines: word boxes run taller than\n * their glyphs, so the gap between one line's box and the next is far smaller\n * than the visible leading. Exact-quote rate measured over every text page of\n * two real scanned books, by how far the box misses:\n *\n * any 0.3 0.4 0.5 0.6\n * -2pt 98/99 98/83 98/49 60/16 2/ 0\n * -1pt 98/99 98/100 98/97 98/94 98/84\n * +2pt 45/ 2 98/97 98/99 98/99 98/100\n * +4pt 11/ 2 98/16 98/58 98/96 98/97\n * +6pt 9/ 0 51/ 8 64/11 98/16 98/38\n * (headroom ~2.0pt / ~0.9pt — the second book is set much tighter,\n * and on some of its pages adjacent word boxes overlap outright)\n *\n * A third book, 100 pages, varies run granularity instead — ~42 chars per run\n * against 25 and 14, i.e. whole lines as single runs — and 0.5 holds 100% from\n * -1pt to +6pt there. Across all three: >=94% from -1pt to +4pt every time.\n *\n * This also carries page skew, which is why it matters beyond hand-drawn boxes.\n * Tilting real runs and taking axis-aligned boxes after rotation, exact-quote\n * rate: 0.5 holds 100% to 0.25deg and 99% at 0.5deg, where `any` is already at\n * 54% and 34% — a tenth of a degree, invisible to the eye, is enough to wreck\n * it. Beyond ~1deg the limit is not this constant but `SAME_LINE_THRESHOLD_PT`,\n * which a drifting baseline exceeds, splitting one line into several rects.\n *\n * Any-intersection is exact only while the box is tight: 2pt of overshoot —\n * less than the height of a comma, and unavoidable with a mouse — and quotes\n * start picking up fragments of the lines above and below.\n *\n * 0.5 is the widest band holding on BOTH books, about 1pt under to 4pt over.\n * Lower thresholds look better on loosely-set pages and fail on tight ones\n * (0.3 drops to 16% at +4pt on the tighter book), which is exactly the way to\n * overfit this constant to one document. A hand drag overshoots far more often\n * than it undershoots, so the asymmetry is spent on the overshoot side.\n *\n * Consequence to know about: a run the box merely clips — a sliver of the\n * first or last word — falls below the threshold and is dropped. That is the\n * intended trade. Raising this admits neighbouring lines; lowering it drops\n * words from a box drawn slightly small.\n */\nexport const RUN_COVERAGE_THRESHOLD = 0.5;\n\nfunction covers(item: PdfTextItem, rect: PdfCoordinate): boolean {\n const overlapX =\n Math.min(item.x + item.width, rect.x + rect.width) -\n Math.max(item.x, rect.x);\n const overlapY =\n Math.min(item.y + item.height, rect.y + rect.height) -\n Math.max(item.y, rect.y);\n if (overlapX <= 0 || overlapY <= 0) return false;\n return (\n overlapX * overlapY >= RUN_COVERAGE_THRESHOLD * item.width * item.height\n );\n}\n\nfunction groupItemsByPage(items: PdfTextItem[]): Map<number, PdfTextItem[]> {\n const map = new Map<number, PdfTextItem[]>();\n for (const item of items) {\n const existing = map.get(item.page);\n if (existing) {\n existing.push(item);\n } else {\n map.set(item.page, [item]);\n }\n }\n return map;\n}\n\n/**\n * Sorts text items into lines when their y coordinates are\n * within `sameLineThreshold` points of each other.\n * Sorted top-to-bottom (descending y in PDF space), then left-to-right.\n *\n * Returns 2D array:\n * Outer array = list of lines\n * Inner array = list of items on that line\n */\nfunction groupItemsByLine(\n items: PdfTextItem[],\n sameLineThreshold: number,\n): PdfTextItem[][] {\n // Sort top-to-bottom by y; if y is equal, sort left-to-right by x\n const sorted = [...items].sort((a, b) => b.y - a.y || a.x - b.x);\n const lines: PdfTextItem[][] = [];\n let currentLine: PdfTextItem[] = [];\n\n for (const item of sorted) {\n if (\n currentLine.length === 0 ||\n Math.abs(item.y - currentLine[0].y) <= sameLineThreshold\n ) {\n currentLine.push(item);\n } else {\n lines.push(currentLine);\n currentLine = [item];\n }\n }\n if (currentLine.length > 0) lines.push(currentLine);\n return lines;\n}\n","/**\n * PDF viewrect FragmentSelector codec.\n *\n * `PdfCoordinate` is a bounding rectangle in PDF point space: origin at the\n * bottom-left of the page, Y increasing upward. The Y-flip to canvas pixels\n * lives in the browser (`react-ui`); the server has no canvas.\n *\n * These functions are the viewrect peer of the W3C `FragmentSelector` wrapper in\n * `web-annotation-utils`: they serialize/parse the RFC 3778\n * `page=N&viewrect=left,top,width,height` value. The annotation builders here\n * (serialization at write time) and the browser canvas both take them from\n * here — no package reaches into the UI.\n *\n * RFC 3778 PDF Fragment Identifiers: https://tools.ietf.org/html/rfc3778\n */\n\nimport type { PdfCoordinate } from './types';\n\n/**\n * Serialize a PdfCoordinate to an RFC 3778 FragmentSelector value.\n * Format: `page=N&viewrect=left,top,width,height` (all in PDF points).\n */\nexport function createFragmentSelector(coord: PdfCoordinate): string {\n return `page=${coord.page}&viewrect=${coord.x},${coord.y},${coord.width},${coord.height}`;\n}\n\n/**\n * Parse an RFC 3778 FragmentSelector value into PDF coordinates.\n * Returns null when the value is not a well-formed page + viewrect fragment.\n */\nexport function parseFragmentSelector(fragment: string): PdfCoordinate | null {\n const pageMatch = fragment.match(/page=(\\d+)/);\n if (!pageMatch) return null;\n\n // Each coordinate: optional sign, integer part, optional fraction — tight enough\n // to round-trip negatives and reject malformed numbers (e.g. \"1.2.3\").\n const viewrectMatch = fragment.match(\n /viewrect=(-?\\d+(?:\\.\\d+)?),(-?\\d+(?:\\.\\d+)?),(-?\\d+(?:\\.\\d+)?),(-?\\d+(?:\\.\\d+)?)/,\n );\n if (!viewrectMatch) return null;\n\n return {\n page: parseInt(pageMatch[1], 10),\n x: parseFloat(viewrectMatch[1]),\n y: parseFloat(viewrectMatch[2]),\n width: parseFloat(viewrectMatch[3]),\n height: parseFloat(viewrectMatch[4]),\n };\n}\n","/**\n * The context of a span of a text: the text just before it and just after\n * it, as a `TextQuoteSelector` states them (`prefix`, `suffix`).\n *\n * `start` and `end` are offsets: they count Unicode code points from the\n * start of the content, and so does every length here (the 64 and the 32).\n * They are a string's own positions only in a text with no character outside\n * the Basic Multilingual Plane; a caller that slices a string converts them\n * with `textOffsets`. protocol/specs/src/annotations/reconcile-cases.json holds the\n * rule, under CONTEXT.\n *\n * @see https://www.w3.org/TR/annotation-model/#text-quote-selector\n */\n\nimport { between, textOffsets, type TextOffsets } from './text-offsets';\n\n// Code points, both.\nconst CONTEXT_LENGTH = 64;\nconst MAX_EXTENSION = 32;\n\n/** What a context is not lengthened past: white space, or one of eighteen marks. */\nconst BOUNDARY = /[\\s.,;:!?'\"()[\\]{}<>/\\\\]/;\n\n/**\n * Extract prefix and suffix context for a `TextQuoteSelector` from\n * source content: what `reconcile` gives a span it found, and what a caller\n * that makes a span another way (a selection in a viewer, say) gives its own.\n *\n * Extracts up to 64 code points before and after the selected text,\n * extending by up to 32 more to reach a word boundary so the\n * prefix/suffix is meaningful context rather than mid-word fragments.\n *\n * `start` and `end` are offsets: they count code points from the start of\n * `content`.\n */\nexport function extractContext(\n content: string,\n start: number,\n end: number,\n): { prefix?: string; suffix?: string } {\n return contextOf(content, textOffsets(content), start, end);\n}\n\n/** `extractContext`, given the content's conversions: a caller with several spans of one content makes them once. */\nexport function contextOf(\n content: string,\n offsets: TextOffsets,\n start: number,\n end: number,\n): { prefix?: string; suffix?: string } {\n const result: { prefix?: string; suffix?: string } = {};\n\n if (start > 0) {\n let prefixStart = Math.max(0, start - CONTEXT_LENGTH);\n let extensionCount = 0;\n while (prefixStart > 0 && extensionCount < MAX_EXTENSION) {\n if (\n BOUNDARY.test(between(content, offsets, prefixStart - 1, prefixStart))\n )\n break;\n prefixStart--;\n extensionCount++;\n }\n result.prefix = between(content, offsets, prefixStart, start);\n }\n\n if (end < offsets.length) {\n let suffixEnd = Math.min(offsets.length, end + CONTEXT_LENGTH);\n let extensionCount = 0;\n while (suffixEnd < offsets.length && extensionCount < MAX_EXTENSION) {\n if (BOUNDARY.test(between(content, offsets, suffixEnd, suffixEnd + 1)))\n break;\n suffixEnd++;\n extensionCount++;\n }\n result.suffix = between(content, offsets, end, suffixEnd);\n }\n\n return result;\n}\n","/**\n * The annotation builders: what turns the words a model quoted of a text into\n * annotations to commit.\n *\n * - `reconcile` finds the quoted words in the text;\n * - `annotationOfSpan` builds the annotation of a span of a text, or of a\n * PDF's anchored text;\n * - `annotationOfResource` builds an annotation of a resource as a whole.\n *\n * Every SDK has these three, and no other builder:\n * protocol/specs/src/annotations/builder-cases.json names them and holds the two that\n * build, and protocol/specs/src/annotations/reconcile-cases.json holds `reconcile`.\n *\n * A text is a plain string. `start` and `end` are offsets: they count Unicode\n * code points from the start of the text, and so does every length a rule\n * here states. Each function makes the text's conversions for itself\n * (`textOffsets`), so no caller is asked for one.\n *\n * @see https://www.w3.org/TR/annotation-model/#text-quote-selector\n */\n\nimport { annotationIdFor } from './annotation-id';\nimport { XynologError } from './errors';\nimport { findBestTextMatch, buildContentCache } from './fuzzy-anchor';\nimport type { SpanRefusal } from './error-codes';\nimport { locate } from './pdf-anchoring';\nimport { createFragmentSelector } from './pdf-coordinates';\nimport { contextOf } from './text-context';\nimport {\n between,\n occurrencesOf,\n textOffsets,\n type TextOffsets,\n} from './text-offsets';\nimport type {\n Agent,\n TextQuoteSelector,\n Annotation,\n Motivation,\n Selector,\n AnchoredText,\n ResourceId,\n QuotedText,\n ReconciledSpan,\n TextSpan,\n} from './types';\n\n/**\n * A span `annotationOfSpan` refused. `code` names the refusal: one of the\n * `spanRefusal` codes of protocol/specs/src/errors/codes.json, the table every SDK's\n * codes are generated from.\n */\nexport class SpanRefusedError extends XynologError {\n constructor(\n message: string,\n public readonly code: SpanRefusal,\n ) {\n super(message);\n this.name = 'SpanRefusedError';\n }\n}\n\n/** A stretch of the text, as two offsets: from `start` up to but not including `end`. */\ninterface Place {\n start: number;\n end: number;\n}\n\n// Minimum window of the text compared against a quoted prefix or suffix when\n// choosing among several places, in code points. The actual window grows to\n// the length of the quoted prefix or suffix when that is longer: a model is\n// invited to quote up to 64 code points of context, and a fixed window of 32\n// can't `endsWith`/`includes` a string of 64, which would silently defeat the\n// choice for exactly the long, distinctive contexts that choose best.\nconst DISAMBIGUATION_MIN_WINDOW = 32;\n\n/**\n * Find the words a model quoted in a text. The answer is a span whose `start`\n * and `end` bracket `exact` in the text, and whose `exact`, `prefix` and\n * `suffix` are the text's own: nothing the model said is carried into it, so\n * what an annotation built on it states is verifiable against the text.\n *\n * `null` when `quoted.exact` is empty or only white space, or is nowhere in\n * the text, even loosely. A caller drops the proposal, and says so.\n */\nexport function reconcile(\n text: string,\n quoted: QuotedText,\n): ReconciledSpan | null {\n const { exact } = quoted;\n // Nothing, or only white space, is no words to find.\n if (exact.trim() === '') return null;\n\n const offsets = textOffsets(text);\n\n /** What the model said stands beside `exact`, when that is more than white space: a hint of where. */\n const hint = (given: string | undefined): string | undefined =>\n given === undefined || given.trim() === '' ? undefined : given;\n const prefixHint = hint(quoted.prefix);\n const suffixHint = hint(quoted.suffix);\n\n // Size the comparison window to the hint (with a floor), so a prefix of 64\n // code points is matched against at least 64 of the text — a fixed smaller\n // window can't `endsWith`/`includes` a longer string.\n const prefixWindow = Math.max(\n DISAMBIGUATION_MIN_WINDOW,\n prefixHint === undefined ? 0 : textOffsets(prefixHint).length,\n );\n const suffixWindow = Math.max(\n DISAMBIGUATION_MIN_WINDOW,\n suffixHint === undefined ? 0 : textOffsets(suffixHint).length,\n );\n\n /** Whether the text around a place carries every hint given. */\n const fits = ({ start, end }: Place): boolean => {\n const before = between(\n text,\n offsets,\n Math.max(0, start - prefixWindow),\n start,\n );\n const after = between(\n text,\n offsets,\n end,\n Math.min(offsets.length, end + suffixWindow),\n );\n const prefixOk =\n prefixHint === undefined ||\n before.endsWith(prefixHint) ||\n before.includes(prefixHint.trim());\n const suffixOk =\n suffixHint === undefined ||\n after.startsWith(suffixHint) ||\n after.includes(suffixHint.trim());\n return prefixOk && suffixOk;\n };\n\n /** The first of several places that the hints pick: none when no hint was given, or no place fits. */\n const hinted = (places: Place[]): Place | undefined =>\n prefixHint === undefined && suffixHint === undefined\n ? undefined\n : places.find(fits);\n\n /** A place as a span: its words and its context are the text's own. */\n const spanAt = ({ start, end }: Place): TextSpan => {\n const context = contextOf(text, offsets, start, end);\n return {\n start,\n end,\n // The text's words, not the model's version of them — the model may\n // have written slightly different characters (smart or straight\n // quotes, say) and what is stored is what is verifiable.\n exact: between(text, offsets, start, end),\n ...(context.prefix !== undefined ? { prefix: context.prefix } : {}),\n ...(context.suffix !== undefined ? { suffix: context.suffix } : {}),\n };\n };\n\n // Find every place the text has `exact`, character for character: each as long as `exact` is in code points.\n const length = textOffsets(exact).length;\n const occurrences: Place[] = occurrencesOf(text, offsets, exact).map(\n (start) => ({ start, end: start + length }),\n );\n\n if (occurrences.length === 1) {\n return { ...spanAt(occurrences[0]!), anchorMethod: 'unique-match' };\n }\n\n if (occurrences.length > 1) {\n const chosen = hinted(occurrences);\n if (chosen !== undefined)\n return { ...spanAt(chosen), anchorMethod: 'context-recovered' };\n\n // No context chose. Fall back to the first place and flag it for audit:\n // with no hint of where, there is no better signal at this stage, and a\n // caller that sees `first-of-many` should log it loudly so an operator\n // can correct an annotation anchored at the wrong one.\n return { ...spanAt(occurrences[0]!), anchorMethod: 'first-of-many' };\n }\n\n // The text has `exact` nowhere. Try the looser searches (white space and\n // the forms of quotation marks and dashes disregarded, letter case\n // disregarded, edit distance within a twentieth of the length). Of several\n // places one of them finds, the hints choose as they do among the places\n // the text has `exact`, and the first is taken when they choose none.\n const found = findBestTextMatch(text, exact, buildContentCache(text));\n if (!found) return null;\n return {\n ...spanAt(hinted(found.places) ?? found.places[0]!),\n anchorMethod: 'fuzzy-match',\n matchQuality: found.matchQuality,\n };\n}\n\n/** What a refusal is said of: the annotation that was to be built. */\ninterface Refused {\n resourceId: ResourceId;\n motivation: Motivation;\n}\n\nfunction refuse(\n code: SpanRefusal,\n why: string,\n { resourceId, motivation }: Refused,\n): never {\n throw new SpanRefusedError(\n `annotationOfSpan refused a span (${code}): ${why}, for resource ${resourceId}, motivation ${motivation}`,\n code,\n );\n}\n\n/** Whether two numbers are the offsets of a stretch of a text of `length` code points: whole, in order, inside it. */\nconst isStretchOf = (length: number, start: number, end: number): boolean =>\n Number.isInteger(start) &&\n Number.isInteger(end) &&\n 0 <= start &&\n start <= end &&\n end <= length;\n\n/**\n * Refuse a span that is no span of the text: one given backwards, one that\n * runs past the end, one that starts below zero, one stated in fractions.\n * Whatever words lie between its two numbers, it names no stretch of the\n * text, and an annotation built on it would state offsets that anchor nothing.\n */\nfunction holdSpanToText(\n offsets: TextOffsets,\n { start, end }: TextSpan,\n of: Refused,\n): void {\n if (isStretchOf(offsets.length, start, end)) return;\n refuse(\n 'span-out-of-range',\n `offsets ${start} to ${end} are not a span of a text of ${offsets.length} code points`,\n of,\n );\n}\n\n/**\n * Refuse an anchored text one of whose items is no stretch of it. The items\n * are what say where the text is on a page, and a rectangle is made from an\n * item's own offsets: one that is no stretch of the text shows that the items\n * do not index it, and a rectangle made from any of them may be drawn in the\n * wrong place. So every item is held to the text, whether the span touches\n * it or not, and before the span is. A producer that counts offsets another\n * way than the text is counted is what this finds: its last items run past\n * the end, and every item before them is shifted where nothing would show it.\n */\nfunction holdItemsToText(\n anchored: AnchoredText,\n offsets: TextOffsets,\n of: Refused,\n): void {\n const stray = anchored.items.findIndex(\n (item) => !isStretchOf(offsets.length, item.start, item.end),\n );\n if (stray === -1) return;\n const { start, end } = anchored.items[stray]!;\n refuse(\n 'item-out-of-range',\n `item ${stray} of the anchored text is offsets ${start} to ${end}, which is no stretch of a text of ${offsets.length} code points`,\n of,\n );\n}\n\n/**\n * Refuse a prefix or a suffix that is not what the text has on that side of\n * the span: as many code points of it as the prefix or suffix has itself, or\n * all there are if fewer. `span` is a span of the text (`holdSpanToText`).\n */\nfunction holdContextToText(\n text: string,\n offsets: TextOffsets,\n span: TextSpan,\n of: Refused,\n): void {\n if (span.prefix !== undefined) {\n const from = Math.max(0, span.start - textOffsets(span.prefix).length);\n if (between(text, offsets, from, span.start) !== span.prefix) {\n refuse(\n 'prefix-mismatch',\n `the prefix is not the text just before offset ${span.start}`,\n of,\n );\n }\n }\n if (span.suffix !== undefined) {\n const to = Math.min(\n offsets.length,\n span.end + textOffsets(span.suffix).length,\n );\n if (between(text, offsets, span.end, to) !== span.suffix) {\n refuse(\n 'suffix-mismatch',\n `the suffix is not the text just after offset ${span.end}`,\n of,\n );\n }\n }\n}\n\n/**\n * The selectors of a span of a text: its position, and its quote. The span\n * is first held to the text, then its words, then its context.\n */\nfunction selectorsInText(\n text: string,\n span: TextSpan,\n of: Refused,\n): Selector[] {\n const offsets = textOffsets(text);\n holdSpanToText(offsets, span, of);\n if (between(text, offsets, span.start, span.end) !== span.exact) {\n refuse(\n 'exact-mismatch',\n `the text from offset ${span.start} to offset ${span.end}, which count code points, is not exact`,\n of,\n );\n }\n holdContextToText(text, offsets, span, of);\n return [\n { type: 'TextPositionSelector', start: span.start, end: span.end },\n quoteOf(span),\n ];\n}\n\n/**\n * The selectors of a span of a PDF's anchored text: one `FragmentSelector`\n * for each line the span is on (`locate` joins the items it overlaps into a\n * rectangle a line), and its quote. No `TextPositionSelector`: the anchored\n * text is derived from the PDF and is not its stored content, so an offset\n * into it is no durable anchor.\n *\n * The rectangles are of whole items (runs of words), so the text those items\n * cover must *have* `exact` in it, white space apart: containment, not\n * equality. A span that overlaps no item has no rectangle, and is refused\n * under a name of its own: merged with the other, it would send whoever\n * reads the refusal to a comparison of words that never ran.\n *\n * The anchored text is held to itself before anything else (`holdItemsToText`).\n * Then the span is held to it, and its prefix and suffix after, exactly as a\n * span of a text is held to its text: the quote this writes is what\n * re-anchoring reads, on a PDF as on a text.\n */\nfunction selectorsInPdf(\n anchored: AnchoredText,\n span: TextSpan,\n of: Refused,\n): Selector[] {\n const offsets = textOffsets(anchored.text);\n holdItemsToText(anchored, offsets, of);\n holdSpanToText(offsets, span, of);\n\n // `locate` answers both the rectangles and the items they were made from:\n // the covered text is read from those, with no second pass over the items.\n const { rects, overlap } = locate(anchored, span.start, span.end);\n const covered = overlap.length\n ? between(\n anchored.text,\n offsets,\n Math.min(...overlap.map((item) => item.start)),\n Math.max(...overlap.map((item) => item.end)),\n )\n : '';\n const collapsed = (words: string): string =>\n words.replace(/\\s+/g, ' ').trim();\n if (rects.length === 0) {\n refuse(\n 'nothing-located',\n `no rectangle is located for offsets ${span.start} to ${span.end}`,\n of,\n );\n }\n if (!collapsed(covered).includes(collapsed(span.exact))) {\n refuse(\n 'exact-not-covered',\n 'the text the span covers does not have exact in it',\n of,\n );\n }\n holdContextToText(anchored.text, offsets, span, of);\n\n return [\n ...rects.map((rect) => ({\n type: 'FragmentSelector' as const,\n conformsTo: 'http://tools.ietf.org/rfc/rfc3778',\n value: createFragmentSelector(rect),\n })),\n quoteOf(span),\n ];\n}\n\n/** A span's quote: its words, and its context where it has any. */\nfunction quoteOf(span: TextSpan): TextQuoteSelector {\n return {\n type: 'TextQuoteSelector',\n exact: span.exact,\n ...(span.prefix ? { prefix: span.prefix } : {}),\n ...(span.suffix ? { suffix: span.suffix } : {}),\n };\n}\n\n/**\n * Where a span is, for its annotation's id. The words are in it, not just\n * the offsets: after the text changes the same offsets cover other words, and\n * that is another annotation. It is made the same way for a text and for a\n * PDF: a PDF's rectangles are derived from these offsets, so hashing them too\n * would tell no two annotations apart, and would make an id depend on a\n * layout a text cannot reproduce.\n */\nfunction anchorOf(span: TextSpan): string {\n return `${span.start}:${span.end}:${span.exact}`;\n}\n\n/**\n * Build the annotation of a span: of a text when `text` is given, of a PDF\n * when its `anchored` text is. The span is one `reconcile` found, or any\n * other the caller can state.\n *\n * The annotation's selectors are made from the span, and its `id` is derived\n * from what it is (the resource, the motivation, the body and where the span\n * is), so building the same annotation again builds the same id, and\n * committing it again writes nothing new. `generator` says what made it;\n * who asked for it is no member of an annotation a builder makes, and is\n * derived where the annotation is recorded. `created` is the moment it is\n * built.\n *\n * `body` is one body or a list of them, or nothing: an annotation whose\n * motivation alone says what it means (a highlight) has none.\n *\n * Throws `SpanRefusedError` for a span that is not the text's, and for any\n * span of a PDF whose anchored text has an item that is no stretch of it: its\n * `code` is the refusal, and the first check that fails names it.\n */\nexport function annotationOfSpan(\n of: {\n resourceId: ResourceId;\n generator: Agent;\n motivation: Motivation;\n span: TextSpan;\n body?: Annotation['body'];\n } & (\n | { text: string; anchored?: never }\n | { anchored: AnchoredText; text?: never }\n ),\n): Annotation {\n const { resourceId, generator, motivation, span, body } = of;\n const selector =\n of.text !== undefined\n ? selectorsInText(of.text, span, of)\n : selectorsInPdf(of.anchored, span, of);\n return {\n '@context': 'http://www.w3.org/ns/anno.jsonld',\n type: 'Annotation',\n id: annotationIdFor({\n resourceId,\n motivation,\n anchor: anchorOf(span),\n body,\n }),\n motivation,\n generator,\n created: new Date().toISOString(),\n target: { type: 'SpecificResource', source: resourceId, selector },\n ...(body !== undefined ? { body } : {}),\n };\n}\n\n/**\n * Build an annotation of a resource as a whole: its target is the resource,\n * with no selector. The link from a source to what was generated from it is\n * one.\n *\n * Its `id` is derived as a span's annotation's is, from the resource, the\n * motivation and the body: it is anchored nowhere on the resource, and its\n * anchor is the empty string. `generator` says what made it, when something\n * is given; `created` is the moment it is built.\n */\nexport function annotationOfResource(of: {\n resourceId: ResourceId;\n motivation: Motivation;\n generator?: Agent;\n body?: Annotation['body'];\n}): Annotation {\n const { resourceId, motivation, generator, body } = of;\n return {\n '@context': 'http://www.w3.org/ns/anno.jsonld',\n type: 'Annotation',\n id: annotationIdFor({ resourceId, motivation, anchor: '', body }),\n motivation,\n ...(generator !== undefined ? { generator } : {}),\n created: new Date().toISOString(),\n target: { source: resourceId },\n ...(body !== undefined ? { body } : {}),\n };\n}\n","/**\n * Annotation and Selector Utilities\n *\n * Pure TypeScript utilities for working with W3C Web Annotations.\n * No React dependencies - safe to use in any JavaScript environment.\n *\n * Body is either empty array (stub) or single SpecificResource (resolved)\n * Body can be array of TextualBody (tagging) + SpecificResource (linking)\n * Target can be a resource's id or an object with source and optional selector\n */\n\nimport type {\n TextPositionSelector,\n TextQuoteSelector,\n SvgSelector,\n FragmentSelector,\n Annotation,\n Selector,\n ResourceId,\n} from './types';\n\ntype HighlightAnnotation = Annotation;\ntype ReferenceAnnotation = Annotation;\n\n// Re-export selector types for convenience\nexport type {\n TextPositionSelector,\n TextQuoteSelector,\n SvgSelector,\n FragmentSelector,\n Selector,\n};\n\n/**\n * Get TextPositionSelector from a selector (single or array)\n */\nexport function getTextPositionSelector(\n selector: Selector | Selector[] | undefined,\n): TextPositionSelector | null {\n if (!selector) return null;\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find((s) => s.type === 'TextPositionSelector');\n if (!found) return null;\n return found.type === 'TextPositionSelector' ? found : null;\n}\n\n/**\n * Get SvgSelector from a selector (single or array)\n */\nexport function getSvgSelector(\n selector: Selector | Selector[] | undefined,\n): SvgSelector | null {\n if (!selector) return null;\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find((s) => s.type === 'SvgSelector');\n if (!found) return null;\n return found.type === 'SvgSelector' ? found : null;\n}\n\n/**\n * Get FragmentSelector from a selector (single or array)\n */\nexport function getFragmentSelector(\n selector: Selector | Selector[] | undefined,\n): FragmentSelector | null {\n if (!selector) return null;\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find((s) => s.type === 'FragmentSelector');\n if (!found) return null;\n return found.type === 'FragmentSelector' ? found : null;\n}\n\n/** A body's items: none when there is no body, the one when it is a single item, each when it is a list. */\nfunction bodyItems(body: Annotation['body']) {\n return body === undefined ? [] : Array.isArray(body) ? body : [body];\n}\n\n/**\n * Get the source from an annotation body (null if stub)\n * Search for SpecificResource in body array\n */\nexport function getBodySource(body: Annotation['body']): ResourceId | null {\n for (const item of bodyItems(body)) {\n if (item.type === 'SpecificResource') return item.source;\n }\n return null;\n}\n\n/**\n * Check if body is resolved (has a source)\n * Check for SpecificResource in body array\n */\nexport function isBodyResolved(body: Annotation['body']): boolean {\n return getBodySource(body) !== null;\n}\n\n/**\n * The resource a target names (handles both string and object forms)\n */\nexport function getTargetSource(target: Annotation['target']): ResourceId {\n if (typeof target === 'string') {\n return target;\n }\n return target.source;\n}\n\n/**\n * Get the selector from target (undefined if string or no selector)\n */\nexport function getTargetSelector(target: Annotation['target']) {\n if (typeof target === 'string') {\n return undefined;\n }\n return target.selector;\n}\n\n/**\n * Type guard to check if an annotation is a highlight\n */\nexport function isHighlight(\n annotation: Annotation,\n): annotation is HighlightAnnotation {\n return annotation.motivation === 'highlighting';\n}\n\n/**\n * Type guard to check if an annotation is a reference (linking)\n */\nexport function isReference(\n annotation: Annotation,\n): annotation is ReferenceAnnotation {\n return annotation.motivation === 'linking';\n}\n\n/**\n * Type guard to check if an annotation is an assessment\n */\nexport function isAssessment(annotation: Annotation): annotation is Annotation {\n return annotation.motivation === 'assessing';\n}\n\n/**\n * Type guard to check if an annotation is a comment\n */\nexport function isComment(annotation: Annotation): annotation is Annotation {\n return annotation.motivation === 'commenting';\n}\n\n/**\n * Type guard to check if an annotation is a tag\n */\nexport function isTag(annotation: Annotation): annotation is Annotation {\n return annotation.motivation === 'tagging';\n}\n\n/**\n * Extract comment text from a comment annotation's body\n * @param annotation - The annotation to extract comment text from\n * @returns The comment text, or undefined if not a comment or no text found\n */\nexport function getCommentText(annotation: Annotation): string | undefined {\n if (!isComment(annotation)) return undefined;\n const body = Array.isArray(annotation.body)\n ? annotation.body[0]\n : annotation.body;\n if (body && 'value' in body) {\n return body.value;\n }\n return undefined;\n}\n\n/**\n * Type guard to check if a reference annotation is a stub (unresolved)\n * Stub if no SpecificResource in body array\n */\nexport function isStubReference(annotation: Annotation): boolean {\n return isReference(annotation) && !isBodyResolved(annotation.body);\n}\n\n/**\n * Type guard to check if a reference annotation is resolved\n * Resolved if SpecificResource exists in body array\n */\nexport function isResolvedReference(\n annotation: Annotation,\n): annotation is ReferenceAnnotation {\n return isReference(annotation) && isBodyResolved(annotation.body);\n}\n\n/**\n * The entity types an annotation states: the text of each body that tags, in\n * the order its body has them. A body with no text states none.\n *\n * Takes anything with an annotation's `body`: one item, a list, or none\n * (a highlight has none).\n */\nexport function getEntityTypes(annotation: {\n body?: Annotation['body'];\n}): string[] {\n const types: string[] = [];\n for (const item of bodyItems(annotation.body)) {\n if (\n item.type === 'TextualBody' &&\n item.purpose === 'tagging' &&\n item.value.length > 0\n ) {\n types.push(item.value);\n }\n }\n return types;\n}\n\n/** The text of the first body that states it for `purpose`. */\nfunction textFor(\n body: Annotation['body'],\n purpose: 'tagging' | 'classifying',\n): string | undefined {\n for (const item of bodyItems(body)) {\n if (item.type === 'TextualBody' && item.purpose === purpose)\n return item.value;\n }\n return undefined;\n}\n\n/**\n * A tag's category (e.g. \"Issue\", \"Rule\"): the text of its body that tags.\n * Nothing for an annotation that is not a tag.\n */\nexport function getTagCategory(annotation: Annotation): string | undefined {\n return isTag(annotation) ? textFor(annotation.body, 'tagging') : undefined;\n}\n\n/**\n * The id of the schema a tag's category is of (e.g. \"legal-irac\"): the text\n * of its body that classifies. Nothing for an annotation that is not a tag.\n */\nexport function getTagSchemaId(annotation: Annotation): string | undefined {\n return isTag(annotation)\n ? textFor(annotation.body, 'classifying')\n : undefined;\n}\n\n// =============================================================================\n// SELECTOR UTILITIES\n// =============================================================================\n\n/**\n * Get the exact text from a selector (single or array)\n *\n * When selector is an array, tries to find a TextQuoteSelector (which has exact text).\n * TextPositionSelector does not have exact text, only offsets, in code points.\n * Handles undefined selector (when target is a string IRI with no selector)\n */\nexport function getExactText(\n selector: Selector | Selector[] | undefined,\n): string {\n if (!selector) {\n return ''; // No selector means entire resource\n }\n const selectors = Array.isArray(selector) ? selector : [selector];\n\n // Try to find TextQuoteSelector (has exact text)\n const quoteSelector = selectors.find(\n (s) => s.type === 'TextQuoteSelector',\n ) as TextQuoteSelector | undefined;\n if (quoteSelector) {\n return quoteSelector.exact;\n }\n\n // No TextQuoteSelector found\n return '';\n}\n\n/**\n * Get the exact text from an annotation's target selector\n * Uses getTargetSelector helper to safely get selector\n */\nexport function getAnnotationExactText(annotation: Annotation): string {\n const selector = getTargetSelector(annotation.target);\n return getExactText(selector as Selector | Selector[] | undefined);\n}\n\n/**\n * Get TextQuoteSelector from a selector (single or array)\n *\n * Returns the first TextQuoteSelector found, or null if none exists.\n */\nexport function getTextQuoteSelector(\n selector: Selector | Selector[],\n): TextQuoteSelector | null {\n const selectors = Array.isArray(selector) ? selector : [selector];\n const found = selectors.find((s) => s.type === 'TextQuoteSelector');\n if (!found) return null;\n return found.type === 'TextQuoteSelector' ? found : null;\n}\n","// Generated from protocol/specs/src/media-types/registry.json; do not edit.\n// Regenerate: make generate (codegen/lib/media_types/media_types.ml)\n\nexport type RenderMode = 'text' | 'image' | 'pdf' | 'none';\nexport type AnchoringModel = 'text-selector' | 'spatial' | 'none';\nexport type TextSource = 'decode' | 'pdf-text-layer' | 'none';\n\n/** What the system can do with a media type: a row of the registry. */\nexport interface MediaTypeCapabilities {\n /** A file extension, with its dot. */\n extension: string;\n /** The name a person reads. */\n label: string;\n /** The viewer a reader mounts. */\n render: RenderMode;\n /** The annotation model. */\n anchoring: AnchoringModel;\n /** Where its text comes from. */\n textSource: TextSource;\n /** Whether the compose editor offers it. */\n authorable: boolean;\n /** Whether it may be uploaded. */\n uploadable: boolean;\n /**\n * Whether the generation worker can produce it as a yield artifact: the gate\n * for `outputMediaType`, which refuses any other.\n */\n generatable: boolean;\n}\n\n/** A row of the registry, by media type, in the registry's order. */\nexport const MEDIA_TYPE_ROWS = {\n 'text/markdown': {\n extension: '.md',\n label: 'Markdown',\n render: 'text',\n anchoring: 'text-selector',\n textSource: 'decode',\n authorable: true,\n uploadable: true,\n generatable: true,\n },\n 'text/plain': {\n extension: '.txt',\n label: 'Plain Text',\n render: 'text',\n anchoring: 'text-selector',\n textSource: 'decode',\n authorable: true,\n uploadable: true,\n generatable: true,\n },\n 'text/html': {\n extension: '.html',\n label: 'HTML',\n render: 'text',\n anchoring: 'text-selector',\n textSource: 'decode',\n authorable: true,\n uploadable: true,\n generatable: false,\n },\n 'application/json': {\n extension: '.json',\n label: 'JSON',\n render: 'text',\n anchoring: 'text-selector',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/png': {\n extension: '.png',\n label: 'PNG image',\n render: 'image',\n anchoring: 'spatial',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/jpeg': {\n extension: '.jpg',\n label: 'JPEG image',\n render: 'image',\n anchoring: 'spatial',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/pdf': {\n extension: '.pdf',\n label: 'PDF',\n render: 'pdf',\n anchoring: 'spatial',\n textSource: 'pdf-text-layer',\n authorable: false,\n uploadable: true,\n generatable: true,\n },\n 'text/css': {\n extension: '.css',\n label: 'CSS',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/csv': {\n extension: '.csv',\n label: 'CSV',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/xml': {\n extension: '.xml',\n label: 'XML',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/xml': {\n extension: '.xml',\n label: 'XML',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/yaml': {\n extension: '.yaml',\n label: 'YAML',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/x-yaml': {\n extension: '.yaml',\n label: 'YAML',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/javascript': {\n extension: '.js',\n label: 'JavaScript',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/javascript': {\n extension: '.js',\n label: 'JavaScript',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-typescript': {\n extension: '.ts',\n label: 'TypeScript',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/typescript': {\n extension: '.ts',\n label: 'TypeScript',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-python': {\n extension: '.py',\n label: 'Python source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-java': {\n extension: '.java',\n label: 'Java source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-c': {\n extension: '.c',\n label: 'C source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-c++': {\n extension: '.cpp',\n label: 'C++ source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-csharp': {\n extension: '.cs',\n label: 'C# source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-go': {\n extension: '.go',\n label: 'Go source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-rust': {\n extension: '.rs',\n label: 'Rust source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-ruby': {\n extension: '.rb',\n label: 'Ruby source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-php': {\n extension: '.php',\n label: 'PHP source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-swift': {\n extension: '.swift',\n label: 'Swift source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-kotlin': {\n extension: '.kt',\n label: 'Kotlin source',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'text/x-shell': {\n extension: '.sh',\n label: 'Shell script',\n render: 'none',\n anchoring: 'none',\n textSource: 'decode',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/msword': {\n extension: '.doc',\n label: 'Word document (legacy)',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': {\n extension: '.docx',\n label: 'Word document',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/vnd.ms-excel': {\n extension: '.xls',\n label: 'Excel spreadsheet (legacy)',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': {\n extension: '.xlsx',\n label: 'Excel spreadsheet',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/vnd.ms-powerpoint': {\n extension: '.ppt',\n label: 'PowerPoint presentation (legacy)',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation': {\n extension: '.pptx',\n label: 'PowerPoint presentation',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/zip': {\n extension: '.zip',\n label: 'ZIP archive',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/gzip': {\n extension: '.gz',\n label: 'Gzip archive',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/x-tar': {\n extension: '.tar',\n label: 'TAR archive',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/x-7z-compressed': {\n extension: '.7z',\n label: '7z archive',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/octet-stream': {\n extension: '.bin',\n label: 'Binary',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'application/wasm': {\n extension: '.wasm',\n label: 'WebAssembly module',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/gif': {\n extension: '.gif',\n label: 'GIF image',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/webp': {\n extension: '.webp',\n label: 'WebP image',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/svg+xml': {\n extension: '.svg',\n label: 'SVG image',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/bmp': {\n extension: '.bmp',\n label: 'BMP image',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/tiff': {\n extension: '.tiff',\n label: 'TIFF image',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'image/x-icon': {\n extension: '.ico',\n label: 'Icon',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'video/mp4': {\n extension: '.mp4',\n label: 'MP4 video',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'video/mpeg': {\n extension: '.mpeg',\n label: 'MPEG video',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'video/webm': {\n extension: '.webm',\n label: 'WebM video',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'video/ogg': {\n extension: '.ogv',\n label: 'Ogg video',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'video/quicktime': {\n extension: '.mov',\n label: 'QuickTime video',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'video/x-msvideo': {\n extension: '.avi',\n label: 'AVI video',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'audio/mpeg': {\n extension: '.mp3',\n label: 'MP3 audio',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'audio/wav': {\n extension: '.wav',\n label: 'WAV audio',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'audio/ogg': {\n extension: '.ogg',\n label: 'Ogg audio',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'audio/webm': {\n extension: '.webm',\n label: 'WebM audio',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'audio/aac': {\n extension: '.aac',\n label: 'AAC audio',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'audio/flac': {\n extension: '.flac',\n label: 'FLAC audio',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'font/woff': {\n extension: '.woff',\n label: 'WOFF font',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'font/woff2': {\n extension: '.woff2',\n label: 'WOFF2 font',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'font/ttf': {\n extension: '.ttf',\n label: 'TrueType font',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n 'font/otf': {\n extension: '.otf',\n label: 'OpenType font',\n render: 'none',\n anchoring: 'none',\n textSource: 'none',\n authorable: false,\n uploadable: true,\n generatable: false,\n },\n} as const;\n\n/** Other spellings of an extension, each with the one a row states. */\nexport const EXTENSION_ALIASES: Readonly<Record<string, string>> = {\n '.markdown': '.md',\n '.htm': '.html',\n '.jpeg': '.jpg',\n '.yml': '.yaml',\n};\n","/**\n * Media-type registry for Xynolog\n *\n * One supported-types list, capability-tiered, keyed by the spec's\n * SupportedMediaType enum. The rows are protocol/specs/src/media-types/registry.json's,\n * generated; this module is the questions asked of them. Admission (registry\n * membership) is the create/yield gate: every member is storable, nameable,\n * and uploadable.\n * The curated capabilities say what more the system can do with a type:\n *\n * - `render` — which viewer the UI mounts ('none' → metadata + download)\n * - `anchoring` — which annotation model applies: character-offset text\n * selectors vs spatial geometry (PDFs are spatial)\n * - `textSource` — WHERE a type's text comes from: decoded from its own bytes,\n * or derived by reading them ('none' → skip embedding, never\n * mojibake)\n * - `authorable` — offered in the compose editor's format dropdown\n * - `uploadable` — big tent: true for every registry member\n * - `generatable` — the generation worker can produce it as a yield artifact\n *\n * Capabilities are orthogonal strategies, not a ladder: images render but\n * yield no text; PDFs yield text but aren't authorable. A \"tier\" is a\n * derived reading, not a stored fact.\n *\n * Questions ANSWERABLE from those rows get a helper, never a row of their own —\n * whether a type can carry annotations is read off `anchoring`, and a second stored field would be a fact\n * that can contradict the one it was derived from.\n *\n * Import-leniency invariant: restore/import preserves archive mediaTypes\n * verbatim, so \"every stored mediaType is registry-valid\" holds only for\n * content that entered through the validated create/yield gate. No code\n * reading a stored mediaType may assume `capabilitiesOf()` succeeds — the\n * `undefined` branch is mandatory wherever stored types are read.\n */\n\nimport type { SupportedMediaType } from './types';\nimport {\n EXTENSION_ALIASES,\n MEDIA_TYPE_ROWS,\n type AnchoringModel,\n type MediaTypeCapabilities,\n type RenderMode,\n type TextSource,\n} from './media-type-registry';\n\nexport type { AnchoringModel, MediaTypeCapabilities, RenderMode, TextSource };\n\n/**\n * The registry: protocol/specs/src/media-types/registry.json, which every SDK\n * generates from. `satisfies Record<SupportedMediaType, …>` holds the table to\n * the spec's enum in this language too: a type in one and not the other is a\n * compile error here, as it is a refusal in the generator.\n *\n * Row order matters for `mediaTypeForExtension`: extension collisions\n * (.xml, .yaml, .js, .ts, .webm) resolve to the first row declaring the\n * extension.\n */\nexport const MEDIA_TYPES = MEDIA_TYPE_ROWS satisfies Record<\n SupportedMediaType,\n MediaTypeCapabilities\n>;\n\n// String-indexable view for lookups with runtime strings.\nconst REGISTRY: Readonly<Record<string, MediaTypeCapabilities>> = MEDIA_TYPES;\n\n/**\n * Strip parameters (\"; charset=...\") and normalize case.\n */\nexport function baseMediaType(format: string): string {\n return format.split(';')[0]!.trim().toLowerCase();\n}\n\n/**\n * Registry membership — the admission gate. Exact match: callers pass a\n * base type (see `baseMediaType`); strings carrying parameters are not\n * members.\n */\nexport function isSupportedMediaType(\n format: string,\n): format is SupportedMediaType {\n return Object.hasOwn(MEDIA_TYPES, format);\n}\n\n/** Capabilities for a format (parameters tolerated), or undefined on registry miss. */\nexport function capabilitiesOf(\n format: string,\n): MediaTypeCapabilities | undefined {\n return REGISTRY[baseMediaType(format)];\n}\n\n/**\n * The clone-format gate: a clone opens in the compose editor, so authorable\n * sources keep their base media type and everything else falls back to\n * text/plain. Lives beside the registry it reads; the SDK applies it when\n * deriving a clone upload's format and the CloneTokenManager's tests pin it.\n */\nexport function cloneFormat(\n sourceMediaType: string | undefined,\n): SupportedMediaType {\n const base = baseMediaType(sourceMediaType ?? 'text/plain');\n return isSupportedMediaType(base) && capabilitiesOf(base)?.authorable\n ? base\n : 'text/plain';\n}\n\n/**\n * Lenient extension lookup for naming foreign/imported content: '.dat' on\n * registry miss. Exporters use this — a vocabulary change must never\n * refuse to name restored data.\n */\nexport function extensionForMediaType(format: string): string {\n return capabilitiesOf(format)?.extension ?? '.dat';\n}\n\nconst EXTENSION_TO_MEDIA_TYPE: ReadonlyMap<string, SupportedMediaType> =\n (() => {\n const map = new Map<string, SupportedMediaType>();\n for (const type of Object.keys(MEDIA_TYPES) as SupportedMediaType[]) {\n const ext = MEDIA_TYPES[type].extension;\n if (!map.has(ext)) map.set(ext, type);\n }\n return map;\n })();\n\n/**\n * Inverted registry: extension → media type, for the CLI and the upload\n * detection chain. Accepts 'md' or '.md', any case, and common alternate\n * spellings. Returns undefined for unknown extensions — detection chains\n * fall back to 'application/octet-stream' themselves.\n */\nexport function mediaTypeForExtension(\n ext: string,\n): SupportedMediaType | undefined {\n const lower = ext.trim().toLowerCase();\n const dotted = lower.startsWith('.') ? lower : `.${lower}`;\n return EXTENSION_TO_MEDIA_TYPE.get(EXTENSION_ALIASES[dotted] ?? dotted);\n}\n\n/**\n * WHERE a format's text comes from. Registry rows answer directly; on a registry\n * miss, base types under text/* decode (RFC 2046 guarantees the text top-level\n * type is textual — imported unregistered text subtypes embed too), everything\n * else is 'none'.\n *\n * The three answers are different operations, not degrees of one: `decode` is a\n * pure charset-aware `Buffer → string` anyone holding bytes may run;\n * `pdf-text-layer` parses and, failing that, OCRs — expensive, not deterministic\n * across engine versions, and runnable only by the process that persists its\n * output. Calling both \"extraction\" conflates them.\n */\nexport function textSourceOf(format: string): TextSource {\n const caps = capabilitiesOf(format);\n if (caps) return caps.textSource;\n return baseMediaType(format).startsWith('text/') ? 'decode' : 'none';\n}\n\n/**\n * Whether a text source yields positioned runs (`items`) — the geometry an\n * anchored-text artifact is made of. Only deriving does.\n *\n * Exhaustive over `TextSource` on purpose: a new strategy fails to compile\n * here until someone decides which side it is on, so the next media type cannot\n * default into the wrong answer. Private — `yieldsGeometryOf` is the surface.\n */\nconst GEOMETRY_BY_STRATEGY: Record<TextSource, boolean> = {\n decode: false,\n 'pdf-text-layer': true,\n none: false,\n};\n\n/**\n * WHETHER a type's extracted text carries geometry — page-positioned runs\n * rather than a bare string. Answers \"should an anchored-text artifact exist\n * for this resource?\" (reconcile's check for a lost artifact) and \"does this\n * type anchor spatially or by character offset?\".\n *\n * Derived from `textSource`, not stored: geometry is a property of the\n * STRATEGY. A boolean declared on each extractor implementation would be a\n * second fact that must agree with the strategy vocabulary, gated by nothing,\n * and a consumer asking about a media type would have to resolve an\n * implementation to get an answer.\n *\n * Lenient like `textSourceOf`. An unregistered `text/*` type decodes, and\n * decoding yields no geometry — so `false` here is a real answer rather than\n * a refusal.\n */\nexport function yieldsGeometryOf(format: string): boolean {\n return GEOMETRY_BY_STRATEGY[textSourceOf(format)];\n}\n\n/**\n * Whether a text source's output is DERIVED — produced by the Smelter and\n * persisted as an anchored-text artifact — rather than read by decoding the\n * bytes. Decoding is not deriving.\n *\n * Exhaustive over `TextSource` on purpose, like its geometry sibling: a new\n * strategy fails to compile here until someone declares its category.\n * Private — `derivesTextOf` is the surface.\n */\nconst DERIVED_TEXT_BY_STRATEGY: Record<TextSource, boolean> = {\n decode: false,\n 'pdf-text-layer': true,\n none: false,\n};\n\n/**\n * WHETHER a type's text is the Smelter's derived artifact instead of its own\n * decoded bytes — the read-side dispatch a text READER needs: derived text is\n * answered by the anchored-text read; decoded text by `decodeRepresentation`,\n * which refuses everything else.\n *\n * Deliberately a DISTINCT question from `yieldsGeometryOf`, though the\n * answers coincide for every strategy defined: a transcription strategy would\n * derive text with no geometry. The mechanism literal (`pdf-text-layer`) stays\n * confined to the extraction side, which genuinely dispatches per mechanism.\n */\nexport function derivesTextOf(format: string): boolean {\n return DERIVED_TEXT_BY_STRATEGY[textSourceOf(format)];\n}\n\nconst REGISTRY_KEYS = Object.keys(MEDIA_TYPES) as SupportedMediaType[];\n\n/** Types offered in the compose editor's format dropdown. */\nexport const AUTHORABLE_MEDIA_TYPES: readonly SupportedMediaType[] =\n REGISTRY_KEYS.filter((type) => MEDIA_TYPES[type].authorable);\n\n/** Types the generation worker can produce as a yield artifact — what the\n * Browser offers as a generation's `outputMediaType` reads this, not a local\n * table. */\nexport const GENERATABLE_MEDIA_TYPES: readonly SupportedMediaType[] =\n REGISTRY_KEYS.filter((type) => MEDIA_TYPES[type].generatable);\n","// Generated from protocol/specs/src/text/encoding-cases.json; do not edit.\n// Regenerate: make generate (codegen/lib/encodings/typescript.ml)\n\n/** The encodings of the Encoding Standard whose labels every reader of a resource's text refuses, by their names in lower case. */\nexport const REFUSED_ENCODINGS: ReadonlySet<string> = new Set([\n 'big5',\n 'euc-jp',\n 'euc-kr',\n 'gb18030',\n 'gbk',\n 'iso-2022-jp',\n 'replacement',\n 'shift_jis',\n]);\n","/**\n * What text a resource's bytes are.\n *\n * The rule is protocol: protocol/contract/W3C-SELECTORS.md states it (\"The text\n * of a resource\"), and the two tables every reader runs hold it,\n * protocol/specs/src/text/decode-cases.json and protocol/specs/src/text/encoding-cases.json. It\n * is the MIME Sniffing Standard's reading of the content type and the\n * Encoding Standard's reading of the bytes, as a browser follows the two. An\n * offset counts the code points of this text, so every reader makes the same\n * text of the same bytes.\n *\n * The decoders are the platform's `TextDecoder`, which has the standard's\n * labels and its encodings. What it does not do is here: the content type's\n * parsing, the byte-order mark's deciding, and the refusal.\n */\n\nimport { TransportError } from './errors';\nimport { REFUSED_ENCODINGS } from './refused-encodings';\nimport type { TransportErrorCode } from './error-codes';\n\n/** HTTP white space: line feed, carriage return, tab and space. */\nconst isHttpWhiteSpace = (character: string): boolean =>\n character === '\\n' ||\n character === '\\r' ||\n character === '\\t' ||\n character === ' ';\n/** ASCII white space: HTTP white space and form feed. */\nconst isAsciiWhiteSpace = (character: string): boolean =>\n isHttpWhiteSpace(character) || character === '\\f';\n\n/** `text` without the characters at its start that `isSpace` holds of. */\nfunction withoutLeading(\n text: string,\n isSpace: (character: string) => boolean,\n): string {\n let start = 0;\n while (start < text.length && isSpace(text.charAt(start))) start += 1;\n return text.slice(start);\n}\n\n/** `text` without the characters at its end that `isSpace` holds of. */\nfunction withoutTrailing(\n text: string,\n isSpace: (character: string) => boolean,\n): string {\n let end = text.length;\n while (end > 0 && isSpace(text.charAt(end - 1))) end -= 1;\n return text.slice(0, end);\n}\n\n/** An HTTP token: what a type, a subtype and a parameter's name are made of. */\nconst HTTP_TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\n/** What a parameter's value may hold: a tab, U+0020 to U+007E, and U+0080 to U+00FF. */\nconst PARAMETER_VALUE = /^[\\t\\x20-\\x7e\\x80-\\xff]*$/;\n\nconst asciiLowerCase = (text: string): string =>\n text.replace(/[A-Z]/g, (letter) => letter.toLowerCase());\n\n/** The quoted string that opens at `start`, without its quotation marks, and where it ends. */\nfunction quotedString(\n input: string,\n start: number,\n): [value: string, end: number] {\n let position = start + 1;\n let value = '';\n for (;;) {\n const from = position;\n while (\n position < input.length &&\n input.charAt(position) !== '\"' &&\n input.charAt(position) !== '\\\\'\n )\n position += 1;\n value += input.slice(from, position);\n if (position >= input.length) break;\n const mark = input.charAt(position);\n position += 1;\n if (mark === '\"') break;\n // A backslash gives the character after it, and at the very end is itself.\n if (position >= input.length) {\n value += '\\\\';\n break;\n }\n value += input.charAt(position);\n position += 1;\n }\n return [value, position];\n}\n\n/**\n * The value of a content type's `charset` parameter, as the MIME Sniffing\n * Standard parses a MIME type: the first parameter of that name that is one.\n * `undefined` where there is none, and where the content type is no MIME\n * type.\n */\nfunction charsetParameter(contentType: string): string | undefined {\n const input = withoutTrailing(\n withoutLeading(contentType, isHttpWhiteSpace),\n isHttpWhiteSpace,\n );\n const slash = input.indexOf('/');\n if (slash === -1 || !HTTP_TOKEN.test(input.slice(0, slash))) return undefined;\n const semicolon = input.indexOf(';', slash);\n let position = semicolon === -1 ? input.length : semicolon;\n if (\n !HTTP_TOKEN.test(\n withoutTrailing(input.slice(slash + 1, position), isHttpWhiteSpace),\n )\n )\n return undefined;\n\n while (position < input.length) {\n position += 1; // past the semicolon\n while (position < input.length && isHttpWhiteSpace(input.charAt(position)))\n position += 1;\n const nameStart = position;\n while (\n position < input.length &&\n input.charAt(position) !== ';' &&\n input.charAt(position) !== '='\n )\n position += 1;\n const name = asciiLowerCase(input.slice(nameStart, position));\n if (position < input.length) {\n if (input.charAt(position) === ';') continue;\n position += 1; // past the equals sign\n }\n if (position >= input.length) break;\n\n let value: string;\n if (input.charAt(position) === '\"') {\n [value, position] = quotedString(input, position);\n while (position < input.length && input.charAt(position) !== ';')\n position += 1;\n } else {\n const valueStart = position;\n while (position < input.length && input.charAt(position) !== ';')\n position += 1;\n value = withoutTrailing(\n input.slice(valueStart, position),\n isHttpWhiteSpace,\n );\n if (value === '') continue;\n }\n if (name === 'charset' && PARAMETER_VALUE.test(value)) return value;\n }\n return undefined;\n}\n\n/**\n * The charset a media type states: its `charset` parameter as the MIME\n * Sniffing Standard parses a MIME type, in ASCII lower case and without the\n * ASCII white space around it. `utf-8` where it states none, or an empty\n * one.\n *\n * @example\n * extractCharset('text/plain; charset=ISO-8859-1') // 'iso-8859-1'\n * extractCharset('text/plain; charset=\"utf-16le\"') // 'utf-16le'\n * extractCharset('text/plain') // 'utf-8'\n */\nexport function extractCharset(mediaType: string): string {\n const stated = charsetParameter(mediaType);\n if (stated === undefined || stated === '') return 'utf-8';\n return asciiLowerCase(\n withoutTrailing(\n withoutLeading(stated, isAsciiWhiteSpace),\n isAsciiWhiteSpace,\n ),\n );\n}\n\n/** The reader's own refusal of a charset, which names it. */\nfunction undecoded(label: string): TransportError {\n return new TransportError(\n `The resource's text is ${label}, which is no charset this reader decodes: read its bytes instead`,\n 'error' satisfies TransportErrorCode,\n );\n}\n\n/**\n * The platform's decoder for a label of the Encoding Standard, or the reader's\n * own refusal, which names the label. The platform decodes the encodings every\n * reader refuses, so those are refused here.\n */\nfunction decoderFor(label: string): TextDecoder {\n let decoder: TextDecoder;\n try {\n decoder = new TextDecoder(label);\n } catch {\n throw undecoded(label);\n }\n if (REFUSED_ENCODINGS.has(decoder.encoding)) throw undecoded(label);\n return decoder;\n}\n\n/** The encoding whose byte-order mark the bytes begin with. */\nfunction encodingOfMark(\n bytes: Uint8Array,\n): 'utf-8' | 'utf-16be' | 'utf-16le' | undefined {\n if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf)\n return 'utf-8';\n if (bytes[0] === 0xfe && bytes[1] === 0xff) return 'utf-16be';\n if (bytes[0] === 0xff && bytes[1] === 0xfe) return 'utf-16le';\n return undefined;\n}\n\n/**\n * A resource's bytes as the text they are: the one place TypeScript makes a\n * text of a resource's bytes.\n *\n * The charset is the one the media type states, UTF-8 when it states none,\n * and is a label of the Encoding Standard: any other is refused, whatever the\n * bytes are. Bytes that begin with the byte-order mark of UTF-8, UTF-16BE or\n * UTF-16LE are in that encoding, whatever was stated, and the mark is not\n * part of the text. What the encoding does not have is U+FFFD.\n *\n * @param buffer - The bytes\n * @param mediaType - The content type they came with (e.g. \"text/plain; charset=iso-8859-1\")\n * @throws A `TransportError` whose code is `error`, naming the charset, for one that is not decoded\n *\n * @example\n * const text = decodeWithCharset(bytes, \"text/plain; charset=iso-8859-1\");\n */\nexport function decodeWithCharset(\n buffer: ArrayBuffer | Uint8Array,\n mediaType: string,\n): string {\n const bytes = ArrayBuffer.isView(buffer) ? buffer : new Uint8Array(buffer);\n // The stated charset is held to the standard before the bytes are looked at.\n const stated = decoderFor(extractCharset(mediaType));\n const marked = encodingOfMark(bytes);\n // A decoder leaves out the mark of its own encoding, and that is the one at the start here.\n return (marked === undefined ? stated : decoderFor(marked)).decode(bytes);\n}\n","/**\n * Helper functions for working with W3C ResourceDescriptor\n */\n\nimport type { Representation, ResourceDescriptor, ResourceId } from './types';\nimport { TransportError } from './errors';\nimport type { TransportErrorCode } from './error-codes';\nimport { derivesTextOf, textSourceOf } from './media-types';\nimport { decodeWithCharset } from './text-encoding';\n\n/**\n * Get the resource ID from @id property\n *\n * @id is always a bare ID (UUID), never a full URI.\n */\nexport function getResourceId(\n resource: ResourceDescriptor | undefined,\n): ResourceId | undefined {\n if (!resource) return undefined;\n return resource['@id'] || undefined;\n}\n\n/** Whether `value` is a representation as its schema has one: an object that states its media type as text. */\nfunction isRepresentation(value: unknown): value is Representation {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n 'mediaType' in value &&\n typeof value.mediaType === 'string'\n );\n}\n\n/**\n * The primary representation: the only one, or the first of the list;\n * undefined for an empty list, or for no resource. A resource that states no\n * `representations`, or one that is neither one representation nor a list of\n * them, is no ResourceDescriptor and is refused, as the Rust and Python SDKs\n * refuse it when they decode it (protocol/specs/src/resources/reader-cases.json).\n */\nexport function getPrimaryRepresentation(\n resource: ResourceDescriptor | undefined,\n): Representation | undefined {\n if (resource === undefined) return undefined;\n const stated: unknown = resource.representations;\n if (isRepresentation(stated)) return stated;\n if (Array.isArray(stated) && stated.every(isRepresentation)) return stated[0];\n throw new TransportError(\n `The resource ${resource['@id']} is no ResourceDescriptor: its representations are ${stated === undefined ? 'not stated' : 'neither one representation nor a list of them'}`,\n 'error' satisfies TransportErrorCode,\n );\n}\n\n/**\n * Get the media type from the primary representation. A resource that is no\n * ResourceDescriptor is refused, as getPrimaryRepresentation refuses it.\n */\nexport function getPrimaryMediaType(\n resource: ResourceDescriptor | undefined,\n): string | undefined {\n return getPrimaryRepresentation(resource)?.mediaType;\n}\n\n/**\n * Get the language from the primary representation\n */\nexport function getLanguage(\n resource: ResourceDescriptor | undefined,\n): string | undefined {\n return getPrimaryRepresentation(resource)?.language;\n}\n\n/**\n * Get the storage URI from the primary representation — the field's ONE\n * home: bytes are a fact about a rendition, so their location lives on the\n * Representation, never on the descriptor. This is the accessor every\n * descriptor-holding read goes through; `undefined` means the resource has no\n * stored bytes.\n *\n * @param resource - ResourceDescriptor\n * @returns Storage URI or undefined\n */\nexport function getStorageUri(\n resource: ResourceDescriptor | undefined,\n): string | undefined {\n return getPrimaryRepresentation(resource)?.storageUri;\n}\n\n/**\n * Check if resource is archived (application-specific field)\n *\n * @param resource - ResourceDescriptor\n * @returns True if archived, false otherwise\n */\nexport function isArchived(resource: ResourceDescriptor | undefined): boolean {\n return resource?.archived === true;\n}\n\n/**\n * Get entity types from resource (application-specific field)\n *\n * @param resource - ResourceDescriptor\n * @returns Array of entity types, empty if not set\n */\nexport function getResourceEntityTypes(\n resource: ResourceDescriptor | undefined,\n): string[] {\n return resource?.entityTypes || [];\n}\n\n/**\n * Check if resource is a draft (application-specific field)\n *\n * @param resource - ResourceDescriptor\n * @returns True if draft, false otherwise\n */\nexport function isDraft(resource: ResourceDescriptor | undefined): boolean {\n return resource?.isDraft === true;\n}\n\n/**\n * A representation's bytes as the text they are, for a media type whose bytes\n * are its text. The reading is `decodeWithCharset`'s, which keeps the rule\n * every reader of a resource's text keeps (protocol/contract/W3C-SELECTORS.md,\n * \"The text of a resource\"). An offset counts the code points of this text,\n * so every reader makes the same text of the same bytes.\n *\n * A refusal is the reader's own failure, whichever it is of: a media type\n * whose bytes are not its text, or a charset that is not decoded.\n *\n * @param buffer - The raw representation data\n * @param mediaType - Media type with optional charset (e.g., \"text/plain; charset=iso-8859-1\")\n * @returns Decoded string\n * @throws A `TransportError` whose code is `error`: naming the media type, for one whose bytes are not its text, and naming the charset, for one that is not decoded\n *\n * @example\n * ```typescript\n * const content = decodeRepresentation(buffer, \"text/plain; charset=utf-8\");\n * const legacy = decodeRepresentation(buffer, \"text/plain; charset=windows-1252\");\n * ```\n */\nexport function decodeRepresentation(\n buffer: ArrayBuffer | Uint8Array,\n mediaType: string,\n): string {\n // The chokepoint gate: decoding is only legitimate for media whose bytes\n // ARE its text — not for derived-text media (the anchored-text read answers\n // those) and not for media with no text at all. A PDF decoded here would\n // become megabytes of mojibake; refusing means no caller — present or\n // future — can decode bytes that were never text, which is why this gate\n // supersedes a caller census. Category, not mechanism: a\n // new strategy declares its side in core's exhaustive category maps and\n // this gate follows automatically.\n const source = textSourceOf(mediaType);\n if (derivesTextOf(mediaType) || source === 'none') {\n throw new TransportError(\n `decodeRepresentation refused ${mediaType}: its text source is '${source}' — ` +\n `derived text comes from the anchored-text read, never from decoding bytes`,\n 'error' satisfies TransportErrorCode,\n );\n }\n\n return decodeWithCharset(buffer, mediaType);\n}\n","/**\n * What an upload's bytes are made from by hand: a source of whole bytes, how\n * long any source says it is, and an opening of any source. And how a source\n * the SDK opens is read whole, held to the length it states, and what its\n * failures are.\n */\n\nimport { TransportError } from './errors';\nimport type { ByteSource } from './types';\n\n/**\n * A source of `bytes`, held whole, of their length: each opening reads them\n * from the first byte, in one piece. It is one the SDK opens, not a `Blob`.\n */\nexport function byteSourceOf(bytes: Uint8Array): Exclude<ByteSource, Blob> {\n return {\n open: () =>\n new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(bytes);\n controller.close();\n },\n }),\n length: bytes.byteLength,\n };\n}\n\n/**\n * How many bytes `source` states it is: a `Blob`'s size, or the length a\n * source the SDK opens states, which may be none.\n */\nexport function lengthOf(source: ByteSource): number | undefined {\n return source instanceof Blob ? source.size : source.length;\n}\n\n/**\n * A fresh opening of `source`, from its first byte: a `Blob`'s own stream, or\n * what a source the SDK opens opens. Whoever opens it releases it.\n */\nexport function openSource(source: ByteSource): ReadableStream<Uint8Array> {\n return source instanceof Blob ? source.stream() : source.open();\n}\n\n/**\n * What an upload's source failed with: it could not be opened, a read of it\n * failed, or it gave other than the length it states. Its own failure, not\n * the network's, so the upload ends with it and is sent no more. It carries\n * what the source failed with as its cause.\n */\nexport function sourceFailure(cause: unknown): TransportError {\n return new TransportError(\n `the upload's source could not be read: ${cause instanceof Error ? cause.message : String(cause)}`,\n 'error',\n undefined,\n { cause },\n );\n}\n\n/**\n * What releasing an opening of an upload's source failed with, carried as its\n * cause. Reported, and never the upload's outcome.\n */\nexport function releaseFailure(cause: unknown): TransportError {\n return new TransportError(\n `the upload's source could not be released: ${cause instanceof Error ? cause.message : String(cause)}`,\n 'error',\n undefined,\n { cause },\n );\n}\n\n/**\n * A source the SDK opens, as a `Blob`: opened afresh and read whole. One that\n * cannot be opened, fails as it is read, or gives other than the length it\n * states rejects with its `sourceFailure`. The opening is released however\n * the reading ends: read through, failed, or cancelled by `signal`, which\n * rejects with its reason. A release that fails is told to\n * `onReleaseFailure`, and the reading ends as it would have.\n */\nexport async function heldOf(\n source: Exclude<ByteSource, Blob>,\n signal: AbortSignal | undefined,\n onReleaseFailure: (failure: TransportError) => void,\n): Promise<Blob> {\n if (signal?.aborted) throw signal.reason;\n const { length } = source;\n let reader: ReadableStreamDefaultReader<Uint8Array>;\n try {\n reader = source.open().getReader();\n } catch (error) {\n throw sourceFailure(error);\n }\n let released: Promise<void> | undefined;\n const release = (reason: unknown): Promise<void> =>\n (released ??= reader.cancel(reason).catch((error: unknown) => {\n onReleaseFailure(releaseFailure(error));\n }));\n const cancelled = (): void => void release(signal?.reason);\n signal?.addEventListener('abort', cancelled, { once: true });\n const pieces: Uint8Array<ArrayBuffer>[] = [];\n let given = 0;\n try {\n for (;;) {\n const read = await reader.read().catch((error: unknown) => {\n // Its stream failed: nothing of it is left to release.\n released ??= Promise.resolve();\n throw signal?.aborted ? signal.reason : sourceFailure(error);\n });\n if (signal?.aborted) throw signal.reason;\n if (read.done) {\n const file = new Blob(pieces);\n if (length !== undefined && file.size !== length)\n throw sourceFailure(\n new Error(`it gave ${file.size} bytes, and states ${length}`),\n );\n return file;\n }\n given += read.value.byteLength;\n if (length !== undefined && given > length)\n throw sourceFailure(\n new Error(`it gave more bytes than the ${length} it states`),\n );\n // A `Blob` takes bytes of an `ArrayBuffer` of their own.\n pieces.push(new Uint8Array(read.value));\n }\n } catch (error) {\n await release(error);\n throw error;\n } finally {\n signal?.removeEventListener('abort', cancelled);\n }\n}\n","// Generated from protocol/specs/src/client/refresh.json; do not edit.\n// Regenerate: make generate (codegen/lib/cache_refresh/typescript.ml)\n\nimport type { components } from './types';\n\n/** The live queries a client's cache answers. */\nexport const CACHE_QUERIES = [\n 'resource',\n 'annotations',\n 'annotation',\n 'events',\n 'referencedBy',\n 'resources',\n 'matchedResources',\n 'entityTypes',\n 'tagSchemas',\n 'engines',\n] as const;\nexport type CacheQuery = (typeof CACHE_QUERIES)[number];\n\n/** The live queries whose answers a client keeps across its lives, for the person signed in. */\nexport const PERSISTED_QUERIES = [\n 'resource',\n 'annotations',\n 'annotation',\n 'entityTypes',\n 'tagSchemas',\n] as const;\nexport type PersistedQuery = (typeof PERSISTED_QUERIES)[number];\n\n/** What each live query is asked for per: a resource, an annotation, or the filters it is asked with; `whole` for one asked for whole, whose one answer is kept under `wholeKey`. */\nexport const CACHE_PER = {\n resource: 'resource',\n annotations: 'resource',\n annotation: 'annotation',\n events: 'resource',\n referencedBy: 'resource',\n resources: 'filters',\n matchedResources: 'filters',\n entityTypes: 'whole',\n tagSchemas: 'whole',\n engines: 'whole',\n} as const satisfies {\n readonly [Q in CacheQuery]: 'resource' | 'annotation' | 'filters' | 'whole';\n};\nexport type CachePer = typeof CACHE_PER;\n\n/** What each live query's cache holds, its `value`: the component, and the members within it the value is, outermost first. */\nexport const CACHE_VALUES = {\n resource: { component: 'ResourceDescriptor', members: [] },\n annotations: { component: 'GetAnnotationsResponse', members: [] },\n annotation: { component: 'Annotation', members: [] },\n events: { component: 'GetEventsResponse', members: ['events'] },\n referencedBy: {\n component: 'GetReferencedByResponse',\n members: ['referencedBy'],\n },\n resources: { component: 'ListResourcesResponse', members: [] },\n matchedResources: { component: 'MatchResourcesResponse', members: [] },\n entityTypes: {\n component: 'GetEntityTypesResponse',\n members: ['entityTypes'],\n },\n tagSchemas: { component: 'GetTagSchemasResponse', members: ['tagSchemas'] },\n engines: {\n component: 'BrowseEnginesResult',\n members: ['response', 'engines'],\n },\n} as const satisfies {\n readonly [Q in CacheQuery]: {\n readonly component: keyof components['schemas'];\n readonly members: readonly string[];\n };\n};\n\n/** The type of what each live query's cache holds: `CACHE_VALUES`'s component, member within member. */\nexport interface CacheValues {\n resource: components['schemas']['ResourceDescriptor'];\n annotations: components['schemas']['GetAnnotationsResponse'];\n annotation: components['schemas']['Annotation'];\n events: components['schemas']['GetEventsResponse']['events'];\n referencedBy: components['schemas']['GetReferencedByResponse']['referencedBy'];\n resources: components['schemas']['ListResourcesResponse'];\n matchedResources: components['schemas']['MatchResourcesResponse'];\n entityTypes: components['schemas']['GetEntityTypesResponse']['entityTypes'];\n tagSchemas: components['schemas']['GetTagSchemasResponse']['tagSchemas'];\n engines: components['schemas']['BrowseEnginesResult']['response']['engines'];\n}\n\n/** Which of a split channel's two kinds of event a row is for. */\nexport type CacheRefreshWhen = 'enriched' | 'unenriched';\n\n/** A way to a member of an event: the names of the members it is within, and its own. */\nexport type CacheRefreshWay = readonly string[];\n\n/** What one trigger does to the cache. */\nexport interface CacheRefresh {\n readonly when?: CacheRefreshWhen;\n /** `subject`: the keys the event names. `held`: every key the client holds. */\n readonly reach: 'subject' | 'held';\n /** Where in the event the keys a `subject` row reaches are: the way to the resource it names (a ResourceId), and to the annotation (an AnnotationId). */\n readonly names: {\n readonly resource?: CacheRefreshWay;\n readonly annotation?: CacheRefreshWay;\n };\n /** The way to the value the row writes (an Annotation). On a split channel, its presence is what makes an event enriched. */\n readonly carries?: CacheRefreshWay;\n /** Asked for again, the value shown meanwhile. */\n readonly refetches: readonly CacheQuery[];\n /** Written with the value the event carries. */\n readonly writes: readonly CacheQuery[];\n /** Gone: the key fails as `bus.not-found`. */\n readonly removes: readonly CacheQuery[];\n}\n\n/** What each trigger does: a channel's events; `reopened`, the stream open again after a drop; or `unreadable`, an event on one of these channels that cannot be read. */\nexport const CACHE_REFRESH = {\n /** The stream is open again after a drop. Events every client hears carry no position, so the ones published meanwhile are lost and nothing replays them: the client asks again for everything they feed. What a resource's own scope feeds needs nothing here: its events are replayed from where the client left off, or `bus:resume-gap` says they could not be. */\n reopened: [\n {\n reach: 'held',\n names: {},\n refetches: [\n 'resources',\n 'matchedResources',\n 'resource',\n 'entityTypes',\n 'tagSchemas',\n 'engines',\n ],\n writes: [],\n removes: [],\n },\n ],\n /** A frame on a channel of this table that its reading refuses, or one a member of which the row names is present and is not what it names: something changed and nothing says what, so every key held is asked for again, as after a gap. */\n unreadable: [\n {\n reach: 'held',\n names: {},\n refetches: [\n 'resource',\n 'annotations',\n 'annotation',\n 'events',\n 'referencedBy',\n 'resources',\n 'matchedResources',\n 'entityTypes',\n 'tagSchemas',\n 'engines',\n ],\n writes: [],\n removes: [],\n },\n ],\n /** The gateway could not replay what a scope missed: everything held of that resource, and of its annotations, is asked for again. */\n 'bus:resume-gap': [\n {\n reach: 'subject',\n names: { resource: ['scope'] },\n refetches: [\n 'annotations',\n 'annotation',\n 'resource',\n 'events',\n 'referencedBy',\n ],\n writes: [],\n removes: [],\n },\n ],\n /** An annotation was added to the resource. */\n 'mark:added': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['annotations', 'events'],\n writes: [],\n removes: [],\n },\n ],\n /** An annotation was removed from the resource. */\n 'mark:removed': [\n {\n reach: 'subject',\n names: {\n resource: ['resourceId'],\n annotation: ['payload', 'annotationId'],\n },\n refetches: ['annotations', 'events'],\n writes: [],\n removes: ['annotation'],\n },\n ],\n /** The reply to this client's own deletion: the annotation is gone whether or not the client holds the scope that would tell it so. */\n 'mark:delete-ok': [\n {\n reach: 'subject',\n names: { annotation: ['response', 'annotationId'] },\n refetches: [],\n writes: [],\n removes: ['annotation'],\n },\n ],\n /** enriched: An annotation's body changed, and the event carries the annotation as it now is. unenriched: An annotation's body changed, and the event could not say what it now is. */\n 'mark:body-updated': [\n {\n when: 'enriched',\n reach: 'subject',\n names: { resource: ['resourceId'], annotation: ['annotation', 'id'] },\n carries: ['annotation'],\n refetches: ['events'],\n writes: ['annotations', 'annotation'],\n removes: [],\n },\n {\n when: 'unenriched',\n reach: 'subject',\n names: {\n resource: ['resourceId'],\n annotation: ['payload', 'annotationId'],\n },\n refetches: ['annotations', 'annotation', 'events'],\n writes: [],\n removes: [],\n },\n ],\n /** An entity tag was added to the resource. */\n 'mark:entity-tag-added': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['annotations', 'resource', 'events'],\n writes: [],\n removes: [],\n },\n ],\n /** An entity tag was removed from the resource. */\n 'mark:entity-tag-removed': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['annotations', 'resource', 'events'],\n writes: [],\n removes: [],\n },\n ],\n /** The resource was archived, which its description states and lists filter on. */\n 'mark:archived': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['resource', 'resources', 'matchedResources'],\n writes: [],\n removes: [],\n },\n ],\n /** The resource was unarchived. */\n 'mark:unarchived': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['resource', 'resources', 'matchedResources'],\n writes: [],\n removes: [],\n },\n ],\n /** A resource was created. */\n 'yield:created': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['resource', 'resources', 'matchedResources'],\n writes: [],\n removes: [],\n },\n ],\n /** A resource was updated. */\n 'yield:updated': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['resource', 'resources', 'matchedResources'],\n writes: [],\n removes: [],\n },\n ],\n /** A resource was created as a clone. */\n 'yield:cloned': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['resource', 'resources', 'matchedResources'],\n writes: [],\n removes: [],\n },\n ],\n /** A resource was renamed or moved. */\n 'yield:moved': [\n {\n reach: 'subject',\n names: { resource: ['resourceId'] },\n refetches: ['resource', 'resources', 'matchedResources'],\n writes: [],\n removes: [],\n },\n ],\n /** An entity type was added to the knowledge base. */\n 'frame:entity-type-added': [\n {\n reach: 'subject',\n names: {},\n refetches: ['entityTypes'],\n writes: [],\n removes: [],\n },\n ],\n /** A tag schema was added to the knowledge base. */\n 'frame:tag-schema-added': [\n {\n reach: 'subject',\n names: {},\n refetches: ['tagSchemas'],\n writes: [],\n removes: [],\n },\n ],\n} as const satisfies Record<string, readonly CacheRefresh[]>;\n\nexport type CacheRefreshTrigger = keyof typeof CACHE_REFRESH;\n\n/** The triggers that are channels of the bus. */\nexport const CACHE_REFRESH_CHANNELS = [\n 'bus:resume-gap',\n 'mark:added',\n 'mark:removed',\n 'mark:delete-ok',\n 'mark:body-updated',\n 'mark:entity-tag-added',\n 'mark:entity-tag-removed',\n 'mark:archived',\n 'mark:unarchived',\n 'yield:created',\n 'yield:updated',\n 'yield:cloned',\n 'yield:moved',\n 'frame:entity-type-added',\n 'frame:tag-schema-added',\n] as const;\nexport type CacheRefreshChannel = (typeof CACHE_REFRESH_CHANNELS)[number];\n","// Generated from protocol/specs/src/control/methods.json; do not edit.\n// Regenerate: make generate (codegen/lib/typescript_types/typescript_types.ml)\n\nimport type { components } from './types';\n\n/** The version of the control API these tables state. */\nexport const CONTROL_API_VERSION = 'control.xynolog.org/v1alpha1' as const;\n\n/** Each notification of the control API: who sends it, and the schema of its params. */\nexport const CONTROL_NOTIFICATIONS = {\n /** A line of what a request is doing. */\n 'notifications/progress': { from: 'launcher', params: 'Progress' },\n /** A sign-in waits for a person to enter a code. */\n 'notifications/userAction': { from: 'launcher', params: 'UserAction' },\n /** A line a followed service wrote. */\n 'notifications/log': { from: 'launcher', params: 'LogRecord' },\n /** A run's instance is running. */\n 'notifications/serviceStarted': {\n from: 'launcher',\n params: 'ServiceStarted',\n },\n /** A line a run's instance wrote. */\n 'notifications/serviceOutput': { from: 'launcher', params: 'ServiceOutput' },\n /** The client gives up on a request. */\n 'notifications/cancelled': { from: 'client', params: 'Cancelled' },\n} as const satisfies {\n [key: string]: {\n readonly from: components['schemas']['ControlSender'];\n readonly params: keyof components['schemas'];\n };\n};\n\n/** A notification of the control API, by its name. */\nexport type ControlNotification = keyof typeof CONTROL_NOTIFICATIONS;\n\n/** Each method of the control API: the schemas of its params and its result, whether it runs alone, and the notifications it sends while it runs. */\nexport const CONTROL_METHODS = {\n /**\n * What the launcher is: its version, the API versions it speaks, the runtimes\n * it detects. It reads none of the machine's state.\n */\n 'launcher.about': {\n params: 'AboutParams',\n result: 'AboutResult',\n exclusive: false,\n sends: [],\n },\n /** Every knowledge base this machine knows: xynolog roots. */\n 'roots.list': {\n params: 'RootsListParams',\n result: 'RootsListResult',\n exclusive: true,\n sends: [],\n },\n /** Create and register a new local knowledge base: xynolog init. */\n 'roots.init': {\n params: 'RootsInitParams',\n result: 'RootsInitResult',\n exclusive: true,\n sends: ['notifications/progress'],\n },\n /** Remove one registry row, and no file: xynolog forget. */\n 'roots.forget': {\n params: 'RootsForgetParams',\n result: 'RootsForgetResult',\n exclusive: true,\n sends: [],\n },\n /**\n * Each knowledge base's stack, and the services they share: xynolog status.\n */\n 'status.snapshot': {\n params: 'StatusSnapshotParams',\n result: 'StatusSnapshotResult',\n exclusive: true,\n sends: [],\n },\n /** Start a stack, or some of its services: xynolog start. */\n 'stack.start': {\n params: 'StackStartParams',\n result: 'StackStartResult',\n exclusive: true,\n sends: [],\n },\n /** Stop a stack, or some of its services: xynolog stop. */\n 'stack.stop': {\n params: 'StackStopParams',\n result: 'StackStopResult',\n exclusive: true,\n sends: [],\n },\n /**\n * Sign in at the issuer a stack's knowledge base trusts, by the device grant,\n * and keep the session in the launcher's store: xynolog login. Exclusive\n * while it finds the stack; the wait for the person is not.\n */\n 'auth.login': {\n params: 'AuthLoginParams',\n result: 'AuthLoginResult',\n exclusive: true,\n sends: ['notifications/userAction'],\n },\n /** End the launcher's session for a stack: xynolog logout. */\n 'auth.logout': {\n params: 'AuthLogoutParams',\n result: 'AuthLogoutResult',\n exclusive: true,\n sends: [],\n },\n /**\n * Create an account in a local knowledge base's launcher-managed Keycloak\n * realm: xynolog useradd. A supplied password is secret request data and is\n * never narrated or persisted; a generated password is returned once in the\n * result.\n */\n 'identity.useradd': {\n params: 'IdentityUseraddParams',\n result: 'IdentityUseraddResult',\n exclusive: true,\n sends: [],\n },\n /**\n * List accounts in one local knowledge base's launcher-managed Keycloak\n * realm. Passwords and tokens are never returned.\n */\n 'identity.users.list': {\n params: 'IdentityUsersListParams',\n result: 'IdentityUsersListResult',\n exclusive: true,\n sends: [],\n },\n /**\n * Follow a stack's service logs until the client cancels or every source\n * ends: xynolog logs. Exclusive while it finds the containers; the follow is\n * not.\n */\n 'logs.follow': {\n params: 'LogsFollowParams',\n result: 'LogsFollowResult',\n exclusive: true,\n sends: ['notifications/log'],\n },\n /** Every setting the launcher keeps: xynolog settings. */\n 'settings.list': {\n params: 'SettingsListParams',\n result: 'SettingsListResult',\n exclusive: true,\n sends: [],\n },\n /** One setting: xynolog settings <name>. */\n 'settings.get': {\n params: 'SettingsGetParams',\n result: 'Setting',\n exclusive: true,\n sends: [],\n },\n /**\n * Set a setting, checked as a start would check it: xynolog settings <name>\n * <value>.\n */\n 'settings.set': {\n params: 'SettingsSetParams',\n result: 'Setting',\n exclusive: true,\n sends: [],\n },\n /** Return a setting to its default: xynolog settings <name> --unset. */\n 'settings.unset': {\n params: 'SettingsUnsetParams',\n result: 'Setting',\n exclusive: true,\n sends: [],\n },\n /** Where a machine document is: xynolog settings <document> --path. */\n 'settings.path': {\n params: 'SettingsPathParams',\n result: 'SettingsPathResult',\n exclusive: true,\n sends: [],\n },\n /**\n * Where this machine and a run's instance meet under a runtime: the host\n * address an instance's ports are published on and its dials of this machine\n * go to. A caller asks it before it writes an instance's document.\n */\n 'service.host': {\n params: 'ServiceHostParams',\n result: 'ServiceHostResult',\n exclusive: false,\n sends: [],\n },\n /**\n * Run one instance of a knowledge base's own service once, from the image its\n * stack documents name, unsupervised, on the caller's document, arguments,\n * environment and mounts, and answer when it exits: xynolog run. Exclusive\n * until its container runs; the wait for its exit is not.\n */\n 'service.run': {\n params: 'ServiceRunParams',\n result: 'ServiceRunResult',\n exclusive: true,\n sends: ['notifications/serviceStarted', 'notifications/serviceOutput'],\n },\n /**\n * Send a run's instance SIGTERM, then SIGKILL if it outlives 15 seconds, or\n * SIGKILL at once: xynolog signal.\n */\n 'service.signal': {\n params: 'ServiceSignalParams',\n result: 'ServiceSignalResult',\n exclusive: false,\n sends: [],\n },\n} as const satisfies {\n [key: string]: {\n readonly params: keyof components['schemas'];\n readonly result: keyof components['schemas'];\n readonly exclusive: boolean;\n readonly sends: readonly ControlNotification[];\n };\n};\n\n/** A method of the control API, by its name. */\nexport type ControlMethod = keyof typeof CONTROL_METHODS;\n\n/** What a method of the control API is asked with. */\nexport type ControlParams<M extends keyof typeof CONTROL_METHODS> =\n components['schemas'][(typeof CONTROL_METHODS)[M]['params']];\n\n/** What a method of the control API answers. */\nexport type ControlResult<M extends keyof typeof CONTROL_METHODS> =\n components['schemas'][(typeof CONTROL_METHODS)[M]['result']];\n\n/** What a notification of the control API carries. */\nexport type ControlNotificationParams<\n N extends keyof typeof CONTROL_NOTIFICATIONS,\n> = components['schemas'][(typeof CONTROL_NOTIFICATIONS)[N]['params']];\n","// Generated from protocol/specs/src/session/oauth.json; do not edit.\n// Regenerate: make generate (codegen/lib/oauth_clients/oauth_clients.ml)\n\n/** An application a person uses: the authorization-code grant with PKCE (RFC 7636), at a redirect address the registration lists. */\nexport const BROWSER_CLIENT_ID = 'xynolog-browser';\n\n/** A process with no browser of its own, and the launcher: the device authorization grant (RFC 8628). */\nexport const SCRIPT_CLIENT_ID = 'xynolog-cli';\n\n/** What every sign-in asks for. `offline_access` asks for a refresh token that outlives the issuer's own browser session: a session with a knowledge base is renewed for weeks, not minutes. */\nexport const SIGN_IN_SCOPE = 'openid email profile offline_access';\n","// Generated from protocol/specs/src/session/stored.json; do not edit.\n// Regenerate: make generate (codegen/lib/stored/stored.ml)\n\n/** The registered knowledge bases: a JSON list of KnowledgeBase (components/schemas/KnowledgeBase.json). */\nexport const STORAGE_KEY = 'xynolog.knowledgeBases';\n\n/** The id of the active knowledge base. Nothing is kept under it while none is active. */\nexport const ACTIVE_KEY = 'xynolog.activeKnowledgeBaseId';\n\n/** What is open in each knowledge base: a JSON object from a knowledge base's id to the list of its open resources, each an `openResource`. */\nexport const OPEN_RESOURCES_BY_KB_KEY = 'xynolog.openResourcesByKb';\n\n/** Where the person was in each knowledge base: a JSON object from a knowledge base's id to the id of the resource last viewed in it. */\nexport const LAST_VIEWED_RESOURCE_BY_KB_KEY = 'xynolog.lastViewedResourceByKb';\n\n/** A sign-in by a page redirect that is under way: what it remembers across the trip to the issuer and back. It is taken when the sign-in completes, so a callback that is replayed finds nothing to complete. */\nexport const PENDING_AUTHORIZATION_KEY = 'xynolog.pendingAuthorization';\n\n/** A knowledge base's stored session is kept under this followed by the knowledge base's id. */\nexport const SESSION_KEY_PREFIX = 'xynolog.session.';\n\n/** Where a knowledge base's stream was, for one person, is kept under this followed by the knowledge base's id, a dot and the person's key: the unpadded base64url SHA-256 of the UTF-8 of the did the gateway answers for the person's token (components/schemas/UserResponse.json), never the did itself. What is kept is `lastEventIds`. It is written in the same call as a write of one of the caches kept beside it, and only while every kept cache has no fetch in flight and owes no save, and the refresher owes no refetch (a window of B19, contract/CACHE-SEMANTICS.md, that holds an invalidation it has not yet run); so it never leads them. Its own write is never a reason to write a cache. At disposal this is read once, before any kept cache or the refresher is disposed. Nothing is kept for a token whose person the gateway has not named, and forgetting the knowledge base's stored sign-in, however it is forgotten, deletes it. */\nexport const LAST_EVENT_ID_KEY_PREFIX = 'xynolog.lastEventId.';\n\n/** What a client keeps of a query, for one person, is kept under this followed by the knowledge base's id, a dot, the person's key as `lastEventIdKeyPrefix` makes it, a dot and the query's name: one `cacheDocument` for each query specs/src/client/refresh.json marks `persisted`. Nothing is kept for a token whose person the gateway has not named, and forgetting the knowledge base's stored sign-in, however it is forgotten, deletes the key of every kept query. */\nexport const CACHE_KEY_PREFIX = 'xynolog.cache.';\n\n/** The key a kept query that is per nothing (a `queries` row of specs/src/client/refresh.json with no `per`) keeps its one entry under. */\nexport const WHOLE_KEY = '_';\n\n/** The form of the document. A document of another version is read as none. */\nexport const CACHE_DOCUMENT_VERSION = 1;\n","// Generated from protocol/specs/src/openapi.json and its paths; do not edit.\n// Regenerate: make generate (codegen/lib/gateway_http/typescript.ml)\n\n/** Each operation of the gateway, by its operationId: its method, its path (a `{name}` for each parameter, which the caller fills), and the media types it sends and answers with. */\nexport const gatewayRoutes = {\n getHealth: {\n method: 'GET',\n path: '/api/health',\n answers: 'application/json',\n },\n getHealthAtRoot: { method: 'GET', path: '/', answers: 'application/json' },\n getOpenApiDocument: {\n method: 'GET',\n path: '/api/openapi.json',\n answers: 'application/json',\n },\n getProtectedResourceMetadata: {\n method: 'GET',\n path: '/.well-known/oauth-protected-resource',\n answers: 'application/json',\n },\n createMediaToken: {\n method: 'POST',\n path: '/api/tokens/media',\n sends: 'application/json',\n answers: 'application/json',\n },\n getCurrentUser: {\n method: 'GET',\n path: '/api/users/me',\n answers: 'application/json',\n },\n getStatus: {\n method: 'GET',\n path: '/api/status',\n answers: 'application/json',\n },\n subscribeToBus: {\n method: 'POST',\n path: '/bus/subscribe',\n sends: 'application/json',\n answers: 'text/event-stream',\n },\n emitOnBus: {\n method: 'POST',\n path: '/bus/emit',\n sends: 'application/json',\n answers: 'application/json',\n },\n uploadResource: {\n method: 'POST',\n path: '/resources',\n sends: 'multipart/form-data',\n answers: 'application/json',\n },\n getResourceRepresentation: {\n method: 'GET',\n path: '/resources/{id}',\n answers: '*/*',\n },\n getResourceJsonLd: {\n method: 'GET',\n path: '/resources/{id}/jsonld',\n answers: 'application/ld+json',\n },\n getResourceAnnotations: {\n method: 'GET',\n path: '/resources/{id}/annotations',\n answers: 'application/json',\n },\n getResourceAnchoredText: {\n method: 'GET',\n path: '/resources/{id}/anchored-text',\n answers: 'application/json',\n },\n getResourceRepresentationWithMediaToken: {\n method: 'GET',\n path: '/api/resources/{id}',\n answers: '*/*',\n },\n} as const;\n\n/** Each header the gateway's operations are asked with. */\nexport const gatewayRequestHeaders = {\n idempotencyKey: 'Idempotency-Key',\n traceparent: 'traceparent',\n tracestate: 'tracestate',\n} as const;\n\n/** Each header the gateway's operations answer with. */\nexport const gatewayResponseHeaders = {\n cacheControl: 'Cache-Control',\n link: 'Link',\n retryAfter: 'Retry-After',\n wwwAuthenticate: 'WWW-Authenticate',\n} as const;\n\n/** Each credential the gateway takes as a key, by its security scheme: where it goes, and its name there. */\nexport const gatewayApiKeys = {\n mediaToken: { in: 'query', name: 'token' },\n} as const;\n","// Generated from protocol/specs/src/archivist/openapi.json and its paths; do not edit.\n// Regenerate: make generate (codegen/lib/typescript_types/table_modules.ml)\n\n/** Each operation of the Archivist, by its operationId: its method, and its path (a `{name}` for each parameter, which the caller fills). */\nexport const archivistRoutes = {\n getHealth: { method: 'GET', path: '/health' },\n listStreams: { method: 'GET', path: '/events' },\n getResourceEvents: { method: 'GET', path: '/events/{resourceId}' },\n storeResource: { method: 'POST', path: '/resources' },\n getResourceContent: { method: 'GET', path: '/resources/{id}/content' },\n getResourceJsonLd: { method: 'GET', path: '/resources/{id}/jsonld' },\n getResourceAnnotations: {\n method: 'GET',\n path: '/resources/{id}/annotations',\n },\n getResourceAnchoredText: {\n method: 'GET',\n path: '/resources/{id}/anchored-text',\n },\n putResourceAnchoredText: {\n method: 'PUT',\n path: '/resources/{id}/anchored-text',\n },\n listAnchoredTextEntries: { method: 'GET', path: '/anchored-text/entries' },\n getStoredResourceAnchoredText: {\n method: 'GET',\n path: '/resources/{id}/anchored-text/stored',\n },\n putAnchoredTextStamp: { method: 'PUT', path: '/anchored-text/stamp' },\n} as const;\n","// Generated from protocol/specs/src/control/service-groups.json; do not edit.\n// Regenerate: make generate (codegen/lib/typescript_types/table_modules.ml)\n\nimport type { tables } from './types';\n\n/** protocol/specs/src/control/service-groups.json, as `ControlServiceGroups` types it. */\nexport const CONTROL_SERVICE_GROUPS: tables['ControlServiceGroups'] = {\n $comment:\n \"AUTHORITY for the group each service role is in (ServiceRole, ServiceGroup): what xynolog status shows together, and what --group starts or stops. Each group once, in ServiceGroup's order, and each role in exactly one group, in the order status reads them; read in order, the roles are ServiceRole's. A knowledge base is its record and its index. The issuer signs every knowledge base's accounts in. The knowledge workers are where people and agents work on it. The providers serve its models, and the telemetry watches them all.\",\n groups: [\n {\n group: 'record',\n roles: ['gateway', 'archivist', 'dispatcher', 'messaging'],\n },\n {\n group: 'index',\n roles: ['librarian', 'smelter', 'weaver', 'graph', 'vectors'],\n },\n {\n group: 'issuer',\n roles: ['identity', 'identity-store'],\n },\n {\n group: 'knowledge-workers',\n roles: ['browser', 'worker'],\n },\n {\n group: 'providers',\n roles: ['inference', 'embedding'],\n },\n {\n group: 'telemetry',\n roles: ['collector', 'traces', 'metrics'],\n },\n ],\n};\n","// Generated from the services' tables of protocol/specs/src; do not edit.\n// Regenerate: make generate (codegen/lib/service_texts/typescript.ml)\n\n/**\n * A resource's event stream: a directory of event files. Its path in its tree,\n * `/`-separated.\n *\n * protocol/specs/src/archivist/layout.json, /eventStream/path.\n */\nexport function archivistLayoutEventStreamPath(placeholders: {\n readonly shard: string;\n readonly resourceId: string;\n}): string {\n return `.xynolog/events/${placeholders.shard}/${placeholders.resourceId}`;\n}\n\n/**\n * The files of a stream. A file's name, `{number}` its number in `digits`\n * decimal digits.\n *\n * protocol/specs/src/archivist/layout.json, /eventFile/name.\n */\nexport function archivistLayoutEventFileName(placeholders: {\n readonly number: number;\n}): string {\n return `events-${String(placeholders.number).padStart(6, '0')}.jsonl`;\n}\n\n/**\n * A resource's view, in the state directory. Its path in its tree,\n * `/`-separated.\n *\n * protocol/specs/src/archivist/layout.json, /view/path.\n */\nexport function archivistLayoutViewPath(placeholders: {\n readonly shard: string;\n readonly resourceId: string;\n}): string {\n return `resources/${placeholders.shard}/${placeholders.resourceId}.json`;\n}\n\n/**\n * An entry of the storage-uri index, which names the resource whose content is\n * at a storage URI. Its path in its tree, `/`-separated.\n *\n * protocol/specs/src/archivist/layout.json, /storageUriIndex/path.\n */\nexport function archivistLayoutStorageUriIndexPath(placeholders: {\n readonly shard: string;\n readonly uriHash: string;\n}): string {\n return `projections/storage-uri/${placeholders.shard}/${placeholders.uriHash}.json`;\n}\n\n/**\n * An entry of the anchored-text store, keyed by the checksum of the content it\n * was extracted from. Its path in its tree, `/`-separated.\n *\n * protocol/specs/src/archivist/layout.json, /anchoredTextEntry/path.\n */\nexport function archivistLayoutAnchoredTextEntryPath(placeholders: {\n readonly shard: string;\n readonly contentChecksum: string;\n}): string {\n return `${placeholders.shard}/${placeholders.contentChecksum}.json`;\n}\n\n/**\n * The working tree commits no `.xynolog/config.yaml`, so it declares no\n * `site.domain` (step 3).\n *\n * protocol/specs/src/archivist/messages.json, /boot/0/refusal.\n */\nexport function archivistMessagesBootNoProjectFile(): string {\n return 'The knowledge base commits no .xynolog/config.yaml, so declares no site.domain: it is the identity this knowledge base acts under, and the audience it accepts tokens for';\n}\n\n/**\n * The project file says `git.sync` is true, and git cannot be run in the root\n * or says it is not inside a work tree (step 6): `{root}` is the document's\n * `root`, and `{why}` git's or the system's reason, which varies.\n *\n * protocol/specs/src/archivist/messages.json, /boot/1/refusal.\n */\nexport function archivistMessagesBootNotACheckout(placeholders: {\n readonly root: string;\n readonly why: string;\n}): string {\n return `The knowledge base's project file says git.sync is true, and ${placeholders.root} is not a git checkout (${placeholders.why}). Make it one (git init), or set git.sync to false.`;\n}\n\n/**\n * The gateway does not answer its protected-resource metadata (step 5):\n * `{gateway}` is the document's `gatewayUrl`, and `{reason}` why, which varies.\n *\n * protocol/specs/src/archivist/messages.json, /boot/2/refusal.\n */\nexport function archivistMessagesBootGatewaySilent(placeholders: {\n readonly gateway: string;\n readonly reason: string;\n}): string {\n return `The gateway at ${placeholders.gateway} did not say which knowledge base it serves (/.well-known/oauth-protected-resource): ${placeholders.reason}`;\n}\n\n/**\n * The gateway serves another knowledge base than the tree (step 5): `{gateway}`\n * is the document's `gatewayUrl`, `{served}` the `resource` its metadata names,\n * `{root}` the document's `root`, `{tree}` the tree's audience\n * (`https://<domain>`, each `:` written `/`), and `{did}` the tree's DID.\n *\n * protocol/specs/src/archivist/messages.json, /boot/3/refusal.\n */\nexport function archivistMessagesBootGatewayElsewhere(placeholders: {\n readonly gateway: string;\n readonly served: string;\n readonly root: string;\n readonly tree: string;\n readonly did: string;\n}): string {\n return `The gateway at ${placeholders.gateway} serves ${placeholders.served}, and the tree at ${placeholders.root} is ${placeholders.tree} (${placeholders.did})`;\n}\n\n/**\n * A reply whose JSON is larger than a bus message may be: `{bytes}` is its size\n * in bytes, and `{maxBodyBytes}` `POST /bus/emit`'s\n * `x-xynolog-limits.maxBodyBytes` in the gateway's API.\n *\n * protocol/specs/src/archivist/messages.json, /unsent/0/message.\n */\nexport function archivistMessagesUnsentTooLarge(placeholders: {\n readonly bytes: string;\n readonly maxBodyBytes: string;\n}): string {\n return `The answer could not be sent: it is ${placeholders.bytes} bytes, and a bus message may be ${placeholders.maxBodyBytes}`;\n}\n\n/**\n * Any other reply that cannot be sent, once the transport gives up: `{why}` is\n * why, which varies.\n *\n * protocol/specs/src/archivist/messages.json, /unsent/1/message.\n */\nexport function archivistMessagesUnsentNotSent(placeholders: {\n readonly why: string;\n}): string {\n return `The answer could not be sent: ${placeholders.why}`;\n}\n\n/**\n * A sender holding the worker role whose command cites no `jobId`.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/0/message.\n */\nexport function archivistMessagesRefusalsUncitedWorker(placeholders: {\n readonly channel: string;\n}): string {\n return `${placeholders.channel} refused: a worker-role emitter must cite the job it fulfils in \\`jobId\\``;\n}\n\n/**\n * A command citing a job that the log of the resource it is checked against\n * holds no `job:assigned` of, and that did not make the resource: `{jobId}` is\n * the cited job, and `{resourceId}` that resource.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/1/message.\n */\nexport function archivistMessagesRefusalsUnassignedJob(placeholders: {\n readonly channel: string;\n readonly jobId: string;\n readonly resourceId: string;\n}): string {\n return `${placeholders.channel} refused: cites job ${placeholders.jobId}, but the log of ${placeholders.resourceId} holds no assignment of it, and the job did not make it`;\n}\n\n/**\n * A command citing a job whose recorded holder is not its sender: `{jobId}` is\n * the cited job, `{holder}` the assignment's `holder` or the sender of the\n * `yield:created` the job made, and `{writer}` the command's sender.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/2/message.\n */\nexport function archivistMessagesRefusalsNotTheHolder(placeholders: {\n readonly channel: string;\n readonly jobId: string;\n readonly holder: string;\n readonly writer: string;\n}): string {\n return `${placeholders.channel} refused: job ${placeholders.jobId}'s recorded holder is ${placeholders.holder}, not the writer ${placeholders.writer}`;\n}\n\n/**\n * A `yield:create` that cites a job and names no `generatedFrom.resourceId`.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/3/message.\n */\nexport function archivistMessagesRefusalsSourcelessCreate(): string {\n return 'yield:create refused: a create citing a job must name the source resource its job was assigned on (generatedFrom.resourceId)';\n}\n\n/**\n * A `yield:create` whose `generator` is a list.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/4/message.\n */\nexport function archivistMessagesRefusalsMultiAgentCreate(): string {\n return 'yield:create refused: a multi-agent generator is not supported; derivation binds one generator to the executor';\n}\n\n/**\n * A supplied generator that is not the command's sender: `{generator}` is the\n * generator's `@id`, and `{executor}` the sender.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/5/message.\n */\nexport function archivistMessagesRefusalsGeneratorNotExecutor(placeholders: {\n readonly channel: string;\n readonly generator: string;\n readonly executor: string;\n}): string {\n return `${placeholders.channel} refused: generator ${placeholders.generator} is not the executor ${placeholders.executor}`;\n}\n\n/**\n * A supplied generator from a sender that is not software: `{executor}` is the\n * sender.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/6/message.\n */\nexport function archivistMessagesRefusalsExecutorNotSoftware(placeholders: {\n readonly channel: string;\n readonly executor: string;\n}): string {\n return `${placeholders.channel} refused: a generator was supplied, but the executor ${placeholders.executor} is not software`;\n}\n\n/**\n * An annotation that arrives with a `creator`: `{annotationId}` is its `id`.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/7/message.\n */\nexport function archivistMessagesRefusalsAnnotationWithCreator(placeholders: {\n readonly channel: string;\n readonly annotationId: string;\n}): string {\n return `${placeholders.channel} refused: \\`creator\\` on annotation ${placeholders.annotationId} is derived by the knowledge base, never sent`;\n}\n\n/**\n * An annotation whose `generator` is a list: `{annotationId}` is its `id`.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/8/message.\n */\nexport function archivistMessagesRefusalsMultiAgentAnnotation(placeholders: {\n readonly channel: string;\n readonly annotationId: string;\n}): string {\n return `${placeholders.channel} refused: annotation ${placeholders.annotationId} carries a multi-agent generator; derivation binds one generator to the executor`;\n}\n\n/**\n * A target whose resource's content cannot be annotated: `{mediaType}` is its\n * media type.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/9/message.\n */\nexport function archivistMessagesRefusalsNotAnnotatable(placeholders: {\n readonly mediaType: string;\n}): string {\n return `\"${placeholders.mediaType}\" cannot be annotated`;\n}\n\n/**\n * A storage URI that does not begin `file://`: `{uri}` is the URI.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/10/message.\n */\nexport function archivistMessagesRefusalsStorageUriScheme(placeholders: {\n readonly uri: string;\n}): string {\n return `Invalid storage URI (must start with file://): ${placeholders.uri}`;\n}\n\n/**\n * A storage URI naming a place outside the working tree: `{uri}` is the URI.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/11/message.\n */\nexport function archivistMessagesRefusalsStorageUriOutside(placeholders: {\n readonly uri: string;\n}): string {\n return `Invalid storage URI (must name a file inside the working tree): ${placeholders.uri}`;\n}\n\n/**\n * Content registered whose file is not the checksum expected: `{uri}` is the\n * URI, `{expected}` the first 8 characters of the checksum expected, and\n * `{actual}` the first 8 of the file's.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/12/message.\n */\nexport function archivistMessagesRefusalsChecksumMismatch(placeholders: {\n readonly uri: string;\n readonly expected: string;\n readonly actual: string;\n}): string {\n return `Checksum mismatch for ${placeholders.uri}: expected ${placeholders.expected}... but got ${placeholders.actual}...\nThe file on disk differs from the recorded checksum. Has it been modified since staging?`;\n}\n\n/**\n * A `mark:unarchive` naming a storage URI with no file at it: `{uri}` is the\n * URI.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/13/message.\n */\nexport function archivistMessagesRefusalsUnarchiveWithoutFile(placeholders: {\n readonly uri: string;\n}): string {\n return `Cannot unarchive: file not found at ${placeholders.uri}`;\n}\n\n/**\n * Types to add that are not in the vocabulary: `{types}` is each that is not,\n * in the order the command names them, joined by `, `.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/14/message.\n */\nexport function archivistMessagesRefusalsEntityTypeNotRegistered(placeholders: {\n readonly types: string;\n}): string {\n return `Entity type not registered: ${placeholders.types}`;\n}\n\n/**\n * A resource the Archivist holds no view of, one with no events; and, for\n * `mark:create-request`, a target whose resource's view holds no\n * representation, so names no media type to annotate.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/15/message.\n */\nexport function archivistMessagesRefusalsResourceNotFound(): string {\n return 'Resource not found';\n}\n\n/**\n * An annotation the resource's view does not hold.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/16/message.\n */\nexport function archivistMessagesRefusalsAnnotationNotFound(): string {\n return 'Annotation not found';\n}\n\n/**\n * A path outside the working tree.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/17/message.\n */\nexport function archivistMessagesRefusalsPathEscapes(): string {\n return 'path escapes project root';\n}\n\n/**\n * A path of the working tree that is not there.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/18/message.\n */\nexport function archivistMessagesRefusalsPathNotFound(): string {\n return 'path not found';\n}\n\n/**\n * A token asked for a resource with no view.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/19/message.\n */\nexport function archivistMessagesRefusalsCloneSourceNotFound(): string {\n return 'Resource not found';\n}\n\n/**\n * A token asked for a resource whose content is not in the working tree.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/20/message.\n */\nexport function archivistMessagesRefusalsCloneContentNotFound(): string {\n return 'Resource content not found';\n}\n\n/**\n * A token the Archivist did not issue, or has forgotten or spent.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/21/message.\n */\nexport function archivistMessagesRefusalsInvalidToken(): string {\n return 'Invalid or expired token';\n}\n\n/**\n * A token issued more than fifteen minutes before.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/22/message.\n */\nexport function archivistMessagesRefusalsTokenExpired(): string {\n return 'Token expired';\n}\n\n/**\n * A token whose resource is no longer held.\n *\n * protocol/specs/src/archivist/messages.json, /refusals/23/message.\n */\nexport function archivistMessagesRefusalsTokenSourceNotFound(): string {\n return 'Source resource not found';\n}\n\n/**\n * A listing of the log's streams that failed.\n *\n * protocol/specs/src/archivist/messages.json, /http/0/error.\n */\nexport function archivistMessagesHttpStreamListingFailed(): string {\n return 'stream listing failed';\n}\n\n/**\n * A `fromSequence` that is not an integer of at least 1 in decimal digits, or\n * an id that is not one.\n *\n * protocol/specs/src/archivist/messages.json, /http/1/error.\n */\nexport function archivistMessagesHttpEventsBadRequest(): string {\n return 'resourceId path segment and integer fromSequence >= 1 are required';\n}\n\n/**\n * A read of the stream that failed.\n *\n * protocol/specs/src/archivist/messages.json, /http/2/error.\n */\nexport function archivistMessagesHttpEventReadFailed(): string {\n return 'event read failed';\n}\n\n/**\n * A file missing from the working tree.\n *\n * protocol/specs/src/archivist/messages.json, /http/3/error.\n */\nexport function archivistMessagesHttpContentReadFailed(): string {\n return 'content read failed';\n}\n\n/**\n * No view of the resource: `{id}` is the path's id.\n *\n * protocol/specs/src/archivist/messages.json, /http/4/error.\n */\nexport function archivistMessagesHttpContentNoResource(placeholders: {\n readonly id: string;\n}): string {\n return `Resource not found: ${placeholders.id}`;\n}\n\n/**\n * A view with no storage URI: `{id}` is the path's id.\n *\n * protocol/specs/src/archivist/messages.json, /http/5/error.\n */\nexport function archivistMessagesHttpContentNoRepresentation(placeholders: {\n readonly id: string;\n}): string {\n return `Resource representation not found: no storageUri for ${placeholders.id}`;\n}\n\n/**\n * A resource with no events.\n *\n * protocol/specs/src/archivist/messages.json, /http/6/error.\n */\nexport function archivistMessagesHttpJsonldNotFound(): string {\n return 'Resource not found';\n}\n\n/**\n * No view of the resource, or an id that is not one.\n *\n * protocol/specs/src/archivist/messages.json, /http/7/error.\n */\nexport function archivistMessagesHttpAnnotationsNotFound(): string {\n return 'Resource not found';\n}\n\n/**\n * A read of the store that failed.\n *\n * protocol/specs/src/archivist/messages.json, /http/8/error.\n */\nexport function archivistMessagesHttpAnchoredTextReadFailed(): string {\n return 'anchored-text read failed';\n}\n\n/**\n * A body that is not an AnchoredTextWrite: `{why}` is why, which varies.\n *\n * protocol/specs/src/archivist/messages.json, /http/9/error.\n */\nexport function archivistMessagesHttpAnchoredTextNotAWrite(placeholders: {\n readonly why: string;\n}): string {\n return `The body is no AnchoredTextWrite: ${placeholders.why}`;\n}\n\n/**\n * No view of the resource, or an id that is not one.\n *\n * protocol/specs/src/archivist/messages.json, /http/10/error.\n */\nexport function archivistMessagesHttpAnchoredTextWriteNotFound(): string {\n return 'Resource not found';\n}\n\n/**\n * No view of the resource, or an id that is not one.\n *\n * protocol/specs/src/archivist/messages.json, /http/11/error.\n */\nexport function archivistMessagesHttpAnchoredTextStoredNotFound(): string {\n return 'Resource not found';\n}\n\n/**\n * No entry stored for the resource's content under the stamp stated.\n *\n * protocol/specs/src/archivist/messages.json, /http/12/error.\n */\nexport function archivistMessagesHttpAnchoredTextNoEntry(): string {\n return 'No entry is stored for this content';\n}\n\n/**\n * An upload without `Xynolog-Principal`.\n *\n * protocol/specs/src/archivist/messages.json, /http/13/error.\n */\nexport function archivistMessagesHttpUploadUnattributed(): string {\n return 'Xynolog-Principal is required: the record attributes every resource to someone';\n}\n\n/**\n * A body that is not `multipart/form-data`.\n *\n * protocol/specs/src/archivist/messages.json, /http/14/error.\n */\nexport function archivistMessagesHttpUploadNotMultipart(): string {\n return 'The body is not multipart/form-data';\n}\n\n/**\n * A `format` whose media type is not one Xynolog knows: `{type}` is the media\n * type.\n *\n * protocol/specs/src/archivist/messages.json, /http/15/error.\n */\nexport function archivistMessagesHttpUploadUnsupportedMedia(placeholders: {\n readonly type: string;\n}): string {\n return `Unsupported media type: ${placeholders.type}`;\n}\n\n/**\n * An `Idempotency-Key` whose resource was recorded from other fields or other\n * bytes, a copy's key sent with no clone token, or a new resource's sent with\n * one.\n *\n * protocol/specs/src/archivist/messages.json, /http/16/error.\n */\nexport function archivistMessagesHttpUploadKeyReused(): string {\n return 'This Idempotency-Key names a resource recorded from other fields or other bytes';\n}\n\n/**\n * A record that is refused: `{refusal}` is the refusal's message, as `refusals`\n * states it for `yield:create`, or `yield:clone-create` with a clone token.\n *\n * protocol/specs/src/archivist/messages.json, /http/17/error.\n */\nexport function archivistMessagesHttpUploadRefused(placeholders: {\n readonly refusal: string;\n}): string {\n return `${placeholders.refusal}`;\n}\n\n/**\n * A line of the log that is not an event, found when the views are rebuilt:\n * `{path}` is its event file's path, and `{line}` its line number, counted from\n * 1.\n *\n * protocol/specs/src/archivist/messages.json, /logged/0/fields/what.\n */\nexport function archivistMessagesLoggedNotAnEventFieldsWhat(placeholders: {\n readonly path: string;\n readonly line: string;\n}): string {\n return `${placeholders.path} line ${placeholders.line} is not an event`;\n}\n\n/**\n * A `job:create` with no `_userId` (check 1). The gateway stamps `_userId` on\n * every frame it accepts, so only a frame that reached the bus around it is\n * refused so.\n *\n * protocol/specs/src/dispatcher/messages.json, /refusals/0/message.\n */\nexport function dispatcherMessagesRefusalsCreateWithoutUser(): string {\n return '_userId is required (injected by bus gateway)';\n}\n\n/**\n * A `mark` linking job, or a `yield` job, naming entity types that are not\n * registered (checks 2 and 5): `{types}` is each that is not, in the order the\n * job names them, joined by `, `.\n *\n * protocol/specs/src/dispatcher/messages.json, /refusals/1/message.\n */\nexport function dispatcherMessagesRefusalsEntityTypeNotRegistered(placeholders: {\n readonly types: string;\n}): string {\n return `Entity type not registered: ${placeholders.types}`;\n}\n\n/**\n * A `mark` tagging job whose `schemaId` names no registered tag schema (check\n * 3): `{schemaId}` is the `schemaId`.\n *\n * protocol/specs/src/dispatcher/messages.json, /refusals/2/message.\n */\nexport function dispatcherMessagesRefusalsTagSchemaNotRegistered(placeholders: {\n readonly schemaId: string;\n}): string {\n return `Tag schema not registered: ${placeholders.schemaId}`;\n}\n\n/**\n * A `yield` job given parameters GenerationJobParams does not name (check 4):\n * `{params}` is each, in the order the job gives them, joined by `, `.\n *\n * protocol/specs/src/dispatcher/messages.json, /refusals/3/message.\n */\nexport function dispatcherMessagesRefusalsYieldParameter(placeholders: {\n readonly params: string;\n}): string {\n return `a yield job takes no parameter ${placeholders.params}`;\n}\n\n/**\n * A `job:claim` whose `_roles` does not hold the worker role, checked before\n * the queue is consulted.\n *\n * protocol/specs/src/dispatcher/messages.json, /refusals/4/message.\n */\nexport function dispatcherMessagesRefusalsNotAWorker(): string {\n return 'job:claim refused: the caller is not a worker for this knowledge base';\n}\n\n/**\n * A `job:claim` from a worker that no pending job matches: a decline, not an\n * error.\n *\n * protocol/specs/src/dispatcher/messages.json, /refusals/5/message.\n */\nexport function dispatcherMessagesRefusalsNonePending(): string {\n return 'No pending job matches the claim';\n}\n\n/**\n * A `job:claim` from a worker with no `_userId`, checked after the transition,\n * which leaves the job `running`. The gateway stamps `_userId` on every frame\n * it accepts, so only a frame that reached the bus around it is refused so.\n *\n * protocol/specs/src/dispatcher/messages.json, /refusals/6/message.\n */\nexport function dispatcherMessagesRefusalsClaimWithoutUser(): string {\n return 'job:claim missing _userId (gateway injection)';\n}\n\n/**\n * A `job:status-requested` naming a job the queue holds no record of: never\n * created, or deleted by retention.\n *\n * protocol/specs/src/dispatcher/messages.json, /refusals/7/message.\n */\nexport function dispatcherMessagesRefusalsJobNotFound(): string {\n return 'Job not found';\n}\n\n/**\n * The dead-worker sweep's, for a running job with no write for\n * `staleRunningMs`: `{minutes}` is `staleRunningMs` divided by 60000, as the\n * shortest decimal that reads back as that number, with no `.0` when it is\n * whole.\n *\n * protocol/specs/src/dispatcher/messages.json, /errors/0/error.\n */\nexport function dispatcherMessagesErrorsPresumedDead(placeholders: {\n readonly minutes: string;\n}): string {\n return `worker presumed dead — no progress within ${placeholders.minutes} minutes`;\n}\n\n/**\n * Its claims beside `iat` and `exp`, each filled as the table says.\n *\n * protocol/specs/src/gateway/media-token.json, /claims/iss.\n */\nexport function gatewayMediaTokenClaimsIss(placeholders: {\n readonly domain: string;\n}): string {\n return `${placeholders.domain}`;\n}\n\n/**\n * Its claims beside `iat` and `exp`, each filled as the table says.\n *\n * protocol/specs/src/gateway/media-token.json, /claims/sub.\n */\nexport function gatewayMediaTokenClaimsSub(placeholders: {\n readonly resourceId: string;\n}): string {\n return `${placeholders.resourceId}`;\n}\n\n/**\n * A protected operation, asked with no credential: no `Authorization` header, a\n * scheme that is not `Bearer`, a `Bearer` with no token, or a media token\n * anywhere it is not accepted.\n *\n * protocol/specs/src/gateway/messages.json, /messages/0/error.\n */\nexport function gatewayMessagesMessagesNoCredential(): string {\n return 'Unauthorized';\n}\n\n/**\n * A bearer token the gateway does not accept.\n *\n * protocol/specs/src/gateway/messages.json, /messages/1/error.\n */\nexport function gatewayMessagesMessagesRefusedToken(): string {\n return 'Invalid token';\n}\n\n/**\n * A media token `GET /api/resources/{id}` does not accept: expired, of another\n * knowledge base, of another resource, or not one.\n *\n * protocol/specs/src/gateway/messages.json, /messages/2/error.\n */\nexport function gatewayMessagesMessagesRefusedMediaToken(): string {\n return 'Invalid media token';\n}\n\n/**\n * Any of the 401s above, once the refusals its holder has had have used their\n * allowance.\n *\n * protocol/specs/src/gateway/messages.json, /messages/3/error.\n */\nexport function gatewayMessagesMessagesRefusalRate(): string {\n return \"The credential was refused, and its holder's refused requests have used their allowance\";\n}\n\n/**\n * An operation whose body is JSON, given one that is not.\n *\n * protocol/specs/src/gateway/messages.json, /messages/4/error.\n */\nexport function gatewayMessagesMessagesNotJson(): string {\n return 'The body is not JSON';\n}\n\n/**\n * An operation that requires an `Idempotency-Key`, asked without one.\n *\n * protocol/specs/src/gateway/messages.json, /messages/5/error.\n */\nexport function gatewayMessagesMessagesNoIdempotencyKey(): string {\n return 'The request carries no Idempotency-Key';\n}\n\n/**\n * An `Idempotency-Key` with a character that is not visible ASCII.\n *\n * protocol/specs/src/gateway/messages.json, /messages/6/error.\n */\nexport function gatewayMessagesMessagesIdempotencyKeyNotText(): string {\n return 'The Idempotency-Key is not text: only visible ASCII characters';\n}\n\n/**\n * An `Idempotency-Key` shorter or longer than its parameter allows:\n * `{minLength}` and `{maxLength}` are its schema's.\n *\n * protocol/specs/src/gateway/messages.json, /messages/7/error.\n */\nexport function gatewayMessagesMessagesIdempotencyKeyLength(placeholders: {\n readonly minLength: string;\n readonly maxLength: string;\n}): string {\n return `The Idempotency-Key must be ${placeholders.minLength} to ${placeholders.maxLength} characters`;\n}\n\n/**\n * An emit on a channel the bus registry does not register: `{channel}` is the\n * one it named.\n *\n * protocol/specs/src/gateway/messages.json, /messages/8/error.\n */\nexport function gatewayMessagesMessagesUnknownChannel(placeholders: {\n readonly channel: string;\n}): string {\n return `Unknown channel: ${placeholders.channel}`;\n}\n\n/**\n * An emit whose payload its channel's schema refuses: `{channel}` is the\n * channel, and `{problems}` each refusal, as `<the member's JSON Pointer, or\n * root>: <the refusal>`, joined by `; `.\n *\n * protocol/specs/src/gateway/messages.json, /messages/9/error.\n */\nexport function gatewayMessagesMessagesInvalidPayload(placeholders: {\n readonly channel: string;\n readonly problems: string;\n}): string {\n return `Invalid payload for ${placeholders.channel}: ${placeholders.problems}`;\n}\n\n/**\n * An emit that carries a `correlationId` and no `clientId`: `{channel}` is its\n * channel.\n *\n * protocol/specs/src/gateway/messages.json, /messages/10/error.\n */\nexport function gatewayMessagesMessagesCorrelationWithoutClient(placeholders: {\n readonly channel: string;\n}): string {\n return `clientId is required to emit ${placeholders.channel} with a correlationId`;\n}\n\n/**\n * A subscription with no global channel and no scoped entry.\n *\n * protocol/specs/src/gateway/messages.json, /messages/11/error.\n */\nexport function gatewayMessagesMessagesNoSubscription(): string {\n return 'At least one global channel or scoped entry is required';\n}\n\n/**\n * A subscription whose `scoped` names one scope twice: `{scope}` is that scope.\n *\n * protocol/specs/src/gateway/messages.json, /messages/12/error.\n */\nexport function gatewayMessagesMessagesDuplicateScope(placeholders: {\n readonly scope: string;\n}): string {\n return `duplicate scope \"${placeholders.scope}\" in matrix`;\n}\n\n/**\n * A path the gateway does not serve, or a method a path it serves does not\n * take.\n *\n * protocol/specs/src/gateway/messages.json, /messages/13/error.\n */\nexport function gatewayMessagesMessagesNotFound(): string {\n return 'Not found';\n}\n\n/**\n * A resource the knowledge base does not hold: an `{id}` that is no ResourceId,\n * one the Archivist holds no view of, or one whose bytes the Archivist answers\n * it does not hold the resource of.\n *\n * protocol/specs/src/gateway/messages.json, /messages/14/error.\n */\nexport function gatewayMessagesMessagesResourceNotFound(): string {\n return 'Resource not found';\n}\n\n/**\n * A resource the knowledge base holds, whose bytes the Archivist answers it\n * does not hold.\n *\n * protocol/specs/src/gateway/messages.json, /messages/15/error.\n */\nexport function gatewayMessagesMessagesRepresentationNotFound(): string {\n return 'Resource representation not found';\n}\n\n/**\n * An emit whose `correlationId` another client has claimed: `{correlationId}`\n * is it.\n *\n * protocol/specs/src/gateway/messages.json, /messages/16/error.\n */\nexport function gatewayMessagesMessagesCorrelationClaimed(placeholders: {\n readonly correlationId: string;\n}): string {\n return `correlationId ${placeholders.correlationId} is already claimed`;\n}\n\n/**\n * A body larger than its operation's `maxBodyBytes`, which `{maxBodyBytes}` is.\n *\n * protocol/specs/src/gateway/messages.json, /messages/17/error.\n */\nexport function gatewayMessagesMessagesTooLarge(placeholders: {\n readonly maxBodyBytes: string;\n}): string {\n return `The body is larger than ${placeholders.maxBodyBytes} bytes, this operation's maxBodyBytes`;\n}\n\n/**\n * An emit sent again under its `Idempotency-Key` with another body.\n *\n * protocol/specs/src/gateway/messages.json, /messages/18/error.\n */\nexport function gatewayMessagesMessagesIdempotencyKeyReused(): string {\n return 'This Idempotency-Key was first sent with another body';\n}\n\n/**\n * An emit past its principal's emit-rate bucket.\n *\n * protocol/specs/src/gateway/messages.json, /messages/19/error.\n */\nexport function gatewayMessagesMessagesEmitRate(): string {\n return \"This principal's emits have used its bucket\";\n}\n\n/**\n * A request on the bus past its client's unanswered requests: `{max}` is the\n * most it may hold.\n *\n * protocol/specs/src/gateway/messages.json, /messages/20/error.\n */\nexport function gatewayMessagesMessagesUnansweredRequests(placeholders: {\n readonly max: string;\n}): string {\n return `client has ${placeholders.max} unanswered requests; retry when one settles`;\n}\n\n/**\n * A subscription past the streams its principal may hold.\n *\n * protocol/specs/src/gateway/messages.json, /messages/21/error.\n */\nexport function gatewayMessagesMessagesStreams(): string {\n return 'This principal holds as many streams as it may';\n}\n\n/**\n * A fault of the gateway's own; its log says what.\n *\n * protocol/specs/src/gateway/messages.json, /messages/22/error.\n */\nexport function gatewayMessagesMessagesInternal(): string {\n return 'Internal server error';\n}\n\n/**\n * A read or an upload the Archivist did not answer as its API states: it could\n * not be reached, it did not answer in time, it refused the gateway, or it\n * answered what its API does not; or the gateway could not get its own service\n * token to ask it with.\n *\n * protocol/specs/src/gateway/messages.json, /messages/23/error.\n */\nexport function gatewayMessagesMessagesContentStoreUnavailable(): string {\n return 'Content store unavailable';\n}\n\n/**\n * An emit, or anything that reads or writes a table the replicas share, while\n * the signal plane's broker is not connected.\n *\n * protocol/specs/src/gateway/messages.json, /messages/24/error.\n */\nexport function gatewayMessagesMessagesPlaneUnavailable(): string {\n return 'The signal plane is unavailable: its broker is not connected';\n}\n\n/**\n * A subscription past the queued bytes the gateway can hold.\n *\n * protocol/specs/src/gateway/messages.json, /messages/25/error.\n */\nexport function gatewayMessagesMessagesCapacity(): string {\n return 'The gateway holds as many queued bytes as it can';\n}\n\n/**\n * A request on the bus that no subscriber answers: `{channel}` is the request's\n * channel. Its payload carries no stamp.\n *\n * protocol/specs/src/gateway/messages.json, /failures/0/message.\n */\nexport function gatewayMessagesFailuresPeerUnavailable(placeholders: {\n readonly channel: string;\n}): string {\n return `No subscriber for ${placeholders.channel}: the service that answers it is not connected`;\n}\n\n/**\n * The `WWW-Authenticate` of a 401. For a request that presents no credential.\n * The challenge. `{origin}` is the origin the Unauthorized response names:\n * `http://` and the request's `Host`, or, for a request that names none, the\n * gateway's `publicUrl`.\n *\n * protocol/specs/src/gateway/messages.json, /challenges/noCredential.\n */\nexport function gatewayMessagesChallengesNoCredential(placeholders: {\n readonly origin: string;\n}): string {\n return `Bearer resource_metadata=\"${placeholders.origin}/.well-known/oauth-protected-resource\"`;\n}\n\n/**\n * The `WWW-Authenticate` of a 401. For a request whose credential, a bearer\n * token or a media token, is refused. The challenge. `{origin}` is the origin\n * the Unauthorized response names: `http://` and the request's `Host`, or, for\n * a request that names none, the gateway's `publicUrl`.\n *\n * protocol/specs/src/gateway/messages.json, /challenges/refused.\n */\nexport function gatewayMessagesChallengesRefused(placeholders: {\n readonly origin: string;\n}): string {\n return `Bearer error=\"invalid_token\", resource_metadata=\"${placeholders.origin}/.well-known/oauth-protected-resource\"`;\n}\n\n/**\n * The one line the service writes to stderr, its refusal in place of\n * `{refusal}`, before it exits.\n *\n * protocol/specs/src/service-environment/boot-refusals.json, /line.\n */\nexport function serviceEnvironmentBootRefusalsLine(placeholders: {\n readonly refusal: string;\n}): string {\n return `[fatal] ${placeholders.refusal}`;\n}\n\n/**\n * Started without `--config <path>` or `--config=<path>` naming a path.\n *\n * protocol/specs/src/service-environment/boot-refusals.json,\n * /refusals/0/refusal.\n */\nexport function serviceEnvironmentBootRefusalsRefusalsUnnamed(placeholders: {\n readonly service: string;\n}): string {\n return `The ${placeholders.service}'s configuration document is not named: start it with --config <path>`;\n}\n\n/**\n * The path names no file the service can read: `{path}` is the path as it was\n * given, and `{reason}` the system's reason, which varies.\n *\n * protocol/specs/src/service-environment/boot-refusals.json,\n * /refusals/1/refusal.\n */\nexport function serviceEnvironmentBootRefusalsRefusalsUnreadable(placeholders: {\n readonly service: string;\n readonly path: string;\n readonly reason: string;\n readonly schema: string;\n}): string {\n return `Cannot read the ${placeholders.service}'s configuration document at ${placeholders.path} (${placeholders.reason}). The launcher writes it; a ${placeholders.service} started another way is given one (${placeholders.schema} in protocol/specs/).`;\n}\n\n/**\n * The file is not JSON: `{path}` is the path as it was given, and `{reason}`\n * the parser's reason, which varies.\n *\n * protocol/specs/src/service-environment/boot-refusals.json,\n * /refusals/2/refusal.\n */\nexport function serviceEnvironmentBootRefusalsRefusalsNotJson(placeholders: {\n readonly path: string;\n readonly reason: string;\n}): string {\n return `${placeholders.path} is not JSON: ${placeholders.reason}`;\n}\n\n/**\n * The document is not its schema's: `{path}` is the path as it was given, and\n * `{members}` is one line of `members` for each way it is not, each on a line\n * of its own.\n *\n * protocol/specs/src/service-environment/boot-refusals.json,\n * /refusals/3/refusal.\n */\nexport function serviceEnvironmentBootRefusalsRefusalsInvalid(placeholders: {\n readonly path: string;\n readonly service: string;\n readonly schema: string;\n readonly members: string;\n}): string {\n return `${placeholders.path} is not a ${placeholders.service} configuration document (${placeholders.schema}):\n${placeholders.members}`;\n}\n\n/**\n * `XYNOLOG_OIDC_CLIENT_ID` or `XYNOLOG_OIDC_CLIENT_SECRET` is unset or empty:\n * `{missing}` is each that is, in that order, joined by ` and `.\n *\n * protocol/specs/src/service-environment/boot-refusals.json,\n * /refusals/4/refusal.\n */\nexport function serviceEnvironmentBootRefusalsRefusalsNoServiceAccount(placeholders: {\n readonly missing: string;\n readonly service: string;\n}): string {\n return `${placeholders.missing} not set — this ${placeholders.service} has no service account to sign in with.\nThe launcher passes both for each service it starts; a ${placeholders.service} started another way needs the client its realm registers for it (XYNOLOG_OIDC_CLIENT_ID=xynolog-${placeholders.service}).`;\n}\n\n/**\n * A member of the document names an environment variable that is unset or\n * empty: `{field}` is the member's JSON pointer, and `{name}` the variable.\n *\n * protocol/specs/src/service-environment/boot-refusals.json,\n * /refusals/5/refusal.\n */\nexport function serviceEnvironmentBootRefusalsRefusalsUnset(placeholders: {\n readonly field: string;\n readonly name: string;\n}): string {\n return `${placeholders.field} names the environment variable ${placeholders.name}, which is not set`;\n}\n\n/**\n * An object without a member its schema requires: `{pointer}` is the object's\n * JSON pointer, `/` for the document itself, and `{member}` the member.\n *\n * protocol/specs/src/service-environment/boot-refusals.json, /members/0/line.\n */\nexport function serviceEnvironmentBootRefusalsMembersMissing(placeholders: {\n readonly pointer: string;\n readonly member: string;\n}): string {\n return ` ${placeholders.pointer} is missing ${placeholders.member}`;\n}\n\n/**\n * An object with members its schema does not declare: `{pointer}` is the\n * object's JSON pointer, `/` for the document itself, and `{members}` the\n * members, joined by `, `.\n *\n * protocol/specs/src/service-environment/boot-refusals.json, /members/1/line.\n */\nexport function serviceEnvironmentBootRefusalsMembersUndeclared(placeholders: {\n readonly pointer: string;\n readonly members: string;\n}): string {\n return ` ${placeholders.pointer} does not declare ${placeholders.members}`;\n}\n\n/**\n * Any other way a member is not its schema's: `{pointer}` is the member's JSON\n * pointer, and `{why}` the validator's words, which vary and never carry the\n * member's value.\n *\n * protocol/specs/src/service-environment/boot-refusals.json, /members/2/line.\n */\nexport function serviceEnvironmentBootRefusalsMembersOther(placeholders: {\n readonly pointer: string;\n readonly why: string;\n}): string {\n return ` ${placeholders.pointer} ${placeholders.why}`;\n}\n\n/**\n * The lines of a service's logger. A line of the `simple` format.\n *\n * protocol/specs/src/service-telemetry/log-lines.json, /logger/simple.\n */\nexport function serviceTelemetryLogLinesLoggerSimple(placeholders: {\n readonly timestamp: string;\n readonly level: string;\n readonly message: string;\n}): string {\n return `${placeholders.timestamp} [${placeholders.level}] ${placeholders.message}`;\n}\n\n/**\n * The line the supervisor writes when it starts a service. The line.\n *\n * protocol/specs/src/service-telemetry/log-lines.json, /supervisor/line.\n */\nexport function serviceTelemetryLogLinesSupervisorLine(placeholders: {\n readonly time: string;\n readonly name: string;\n readonly count: string;\n}): string {\n return `[supervise ${placeholders.time}] starting ${placeholders.name} (rapid failures so far: ${placeholders.count})`;\n}\n\n/**\n * The line the supervisor writes when it starts a service. What a service\n * counts the lines that hold of, for each of its lives.\n *\n * protocol/specs/src/service-telemetry/log-lines.json, /supervisor/counted.\n */\nexport function serviceTelemetryLogLinesSupervisorCounted(placeholders: {\n readonly name: string;\n}): string {\n return `starting ${placeholders.name}`;\n}\n\n/**\n * A knowledge base that answered `browse:kb-requested` with the domain the\n * service's document names for it, which the service then serves (LIBRARIAN.md\n * § Boot, SMELTER.md § Boot, WEAVER.md § Boot, WORKER-SERVICE.md R1):\n * `{domain}` is that domain, and `{did}` the DID the knowledge base names the\n * service's agent by.\n *\n * protocol/specs/src/service-telemetry/messages.json, /logged/0/fields/domain.\n */\nexport function serviceTelemetryMessagesLoggedConfirmedFieldsDomain(placeholders: {\n readonly domain: string;\n}): string {\n return `${placeholders.domain}`;\n}\n\n/**\n * A knowledge base that answered `browse:kb-requested` with the domain the\n * service's document names for it, which the service then serves (LIBRARIAN.md\n * § Boot, SMELTER.md § Boot, WEAVER.md § Boot, WORKER-SERVICE.md R1):\n * `{domain}` is that domain, and `{did}` the DID the knowledge base names the\n * service's agent by.\n *\n * protocol/specs/src/service-telemetry/messages.json, /logged/0/fields/did.\n */\nexport function serviceTelemetryMessagesLoggedConfirmedFieldsDid(placeholders: {\n readonly did: string;\n}): string {\n return `${placeholders.did}`;\n}\n\n/**\n * An attribute of the resource the services' spans and metrics are exported\n * under. Its value when nothing says another, with `{service}` the service's\n * name.\n *\n * protocol/specs/src/service-telemetry/telemetry.json, /resource/0/default.\n */\nexport function serviceTelemetryTelemetryResourceServiceName(placeholders: {\n readonly service: string;\n}): string {\n return `xynolog-${placeholders.service}`;\n}\n\n/**\n * A rebuild of anchored text that could not do every resource it set out to\n * (SMELTER.md § Rebuild): `{failed}` is how many it could not do, and `{total}`\n * how many it set out to do, each in decimal digits.\n *\n * protocol/specs/src/smelter/messages.json, /refusals/0/message.\n */\nexport function smelterMessagesRefusalsRebuildIncomplete(placeholders: {\n readonly failed: string;\n readonly total: string;\n}): string {\n return `${placeholders.failed} of ${placeholders.total} resources failed to re-anchor: see the Smelter's log`;\n}\n\n/**\n * A resource the Smelter decided not to index (SMELTER.md § What it decides):\n * `{resourceId}` is the resource, `{reason}` the `reason` its `smelt:settled`\n * carries, `{mediaType}` the media type its bytes were read as, and\n * `{checksum}` the checksum of those bytes.\n *\n * protocol/specs/src/smelter/messages.json, /logged/0/fields/resourceId.\n */\nexport function smelterMessagesLoggedNotIndexedFieldsResourceId(placeholders: {\n readonly resourceId: string;\n}): string {\n return `${placeholders.resourceId}`;\n}\n\n/**\n * A resource the Smelter decided not to index (SMELTER.md § What it decides):\n * `{resourceId}` is the resource, `{reason}` the `reason` its `smelt:settled`\n * carries, `{mediaType}` the media type its bytes were read as, and\n * `{checksum}` the checksum of those bytes.\n *\n * protocol/specs/src/smelter/messages.json, /logged/0/fields/reason.\n */\nexport function smelterMessagesLoggedNotIndexedFieldsReason(placeholders: {\n readonly reason: string;\n}): string {\n return `${placeholders.reason}`;\n}\n\n/**\n * A resource the Smelter decided not to index (SMELTER.md § What it decides):\n * `{resourceId}` is the resource, `{reason}` the `reason` its `smelt:settled`\n * carries, `{mediaType}` the media type its bytes were read as, and\n * `{checksum}` the checksum of those bytes.\n *\n * protocol/specs/src/smelter/messages.json, /logged/0/fields/contentType.\n */\nexport function smelterMessagesLoggedNotIndexedFieldsContentType(placeholders: {\n readonly mediaType: string;\n}): string {\n return `${placeholders.mediaType}`;\n}\n\n/**\n * A resource the Smelter decided not to index (SMELTER.md § What it decides):\n * `{resourceId}` is the resource, `{reason}` the `reason` its `smelt:settled`\n * carries, `{mediaType}` the media type its bytes were read as, and\n * `{checksum}` the checksum of those bytes.\n *\n * protocol/specs/src/smelter/messages.json, /logged/0/fields/contentChecksum.\n */\nexport function smelterMessagesLoggedNotIndexedFieldsContentChecksum(placeholders: {\n readonly checksum: string;\n}): string {\n return `${placeholders.checksum}`;\n}\n\n/**\n * A resource whose bytes the Smelter could not read (SMELTER.md § What it\n * decides): `{resourceId}` is the resource. `error` says why.\n *\n * protocol/specs/src/smelter/messages.json, /logged/1/fields/resourceId.\n */\nexport function smelterMessagesLoggedContentUnreadFieldsResourceId(placeholders: {\n readonly resourceId: string;\n}): string {\n return `${placeholders.resourceId}`;\n}\n\n/**\n * An event the Smelter could not apply because its embedding provider failed a\n * request (SMELTER.md § The embedding provider): `{resourceId}` is the event's\n * resource, `{provider}` the provider's `type` (EmbeddingConfig), `{model}` the\n * model it was asked for, and `{status}` the status it answered with. `slice`\n * is which request of the batch it was, and `error` says why.\n *\n * protocol/specs/src/smelter/messages.json, /logged/2/fields/resourceId.\n */\nexport function smelterMessagesLoggedEventFailedFieldsResourceId(placeholders: {\n readonly resourceId: string;\n}): string {\n return `${placeholders.resourceId}`;\n}\n\n/**\n * An event the Smelter could not apply because its embedding provider failed a\n * request (SMELTER.md § The embedding provider): `{resourceId}` is the event's\n * resource, `{provider}` the provider's `type` (EmbeddingConfig), `{model}` the\n * model it was asked for, and `{status}` the status it answered with. `slice`\n * is which request of the batch it was, and `error` says why.\n *\n * protocol/specs/src/smelter/messages.json, /logged/2/fields/provider.\n */\nexport function smelterMessagesLoggedEventFailedFieldsProvider(placeholders: {\n readonly provider: string;\n}): string {\n return `${placeholders.provider}`;\n}\n\n/**\n * An event the Smelter could not apply because its embedding provider failed a\n * request (SMELTER.md § The embedding provider): `{resourceId}` is the event's\n * resource, `{provider}` the provider's `type` (EmbeddingConfig), `{model}` the\n * model it was asked for, and `{status}` the status it answered with. `slice`\n * is which request of the batch it was, and `error` says why.\n *\n * protocol/specs/src/smelter/messages.json, /logged/2/fields/model.\n */\nexport function smelterMessagesLoggedEventFailedFieldsModel(placeholders: {\n readonly model: string;\n}): string {\n return `${placeholders.model}`;\n}\n\n/**\n * An event the Smelter could not apply because its embedding provider failed a\n * request (SMELTER.md § The embedding provider): `{resourceId}` is the event's\n * resource, `{provider}` the provider's `type` (EmbeddingConfig), `{model}` the\n * model it was asked for, and `{status}` the status it answered with. `slice`\n * is which request of the batch it was, and `error` says why.\n *\n * protocol/specs/src/smelter/messages.json, /logged/2/fields/status.\n */\nexport function smelterMessagesLoggedEventFailedFieldsStatus(placeholders: {\n readonly status: string;\n}): string {\n return `${placeholders.status}`;\n}\n\n/**\n * The document is not a WorkerConfig: `{path}` is the path as it was given, and\n * `{reasons}` one line of `reasons`, for the first way it is not.\n *\n * protocol/specs/src/worker/messages.json, /boot/3/refusal.\n */\nexport function workerMessagesBootInvalid(placeholders: {\n readonly path: string;\n readonly reasons: string;\n}): string {\n return `${placeholders.path} is not a worker configuration document (WorkerConfig):\n${placeholders.reasons}`;\n}\n\n/**\n * `XYNOLOG_OIDC_CLIENT_KEY` is unset or empty.\n *\n * protocol/specs/src/worker/messages.json, /boot/4/refusal.\n */\nexport function workerMessagesBootKeyUnset(): string {\n return \"XYNOLOG_OIDC_CLIENT_KEY is not set in the worker's environment: a worker signs in as a service account\";\n}\n\n/**\n * `XYNOLOG_OIDC_CLIENT_KEY` is not a PEM private key the service can read\n * without a passphrase.\n *\n * protocol/specs/src/worker/messages.json, /boot/5/refusal.\n */\nexport function workerMessagesBootKeyUnreadable(): string {\n return \"XYNOLOG_OIDC_CLIENT_KEY in the worker's environment is not an unencrypted PEM private key\";\n}\n\n/**\n * `XYNOLOG_OIDC_CLIENT_KEY` is a private key that is not RSA.\n *\n * protocol/specs/src/worker/messages.json, /boot/6/refusal.\n */\nexport function workerMessagesBootKeyNotRsa(): string {\n return \"XYNOLOG_OIDC_CLIENT_KEY in the worker's environment is not an RSA key: a worker signs its assertions with RS256\";\n}\n\n/**\n * An engine names, by its `apiKeyEnv`, a variable that is unset or empty:\n * `{knowledgeBase}` is the index of its knowledge base in `knowledgeBases`, and\n * `{engine}` its index in that one's `engines`, each in decimal digits.\n *\n * protocol/specs/src/worker/messages.json, /boot/7/refusal.\n */\nexport function workerMessagesBootApiKeyUnset(placeholders: {\n readonly knowledgeBase: string;\n readonly engine: string;\n}): string {\n return `knowledgeBases[${placeholders.knowledgeBase}].engines[${placeholders.engine}].apiKeyEnv names a variable that is not set in the worker's environment`;\n}\n\n/**\n * Two of `knowledgeBases` name one `domain`: `{later}` is the index of the\n * later, and `{earlier}` of the earlier, each in decimal digits.\n *\n * protocol/specs/src/worker/messages.json, /boot/8/refusal.\n */\nexport function workerMessagesBootDomainTwice(placeholders: {\n readonly later: string;\n readonly earlier: string;\n}): string {\n return `knowledgeBases[${placeholders.later}].domain is the domain of knowledgeBases[${placeholders.earlier}]: a worker serves a knowledge base once`;\n}\n\n/**\n * Every knowledge base refused the service before any was confirmed.\n *\n * protocol/specs/src/worker/messages.json, /boot/9/refusal.\n */\nexport function workerMessagesBootNoneAdmits(): string {\n return 'No knowledge base admits this worker: each of its knowledgeBases refused it';\n}\n\n/**\n * The service cannot listen on its `port`: `{port}` is the port, in decimal\n * digits, and `{why}` the system's reason, which varies.\n *\n * protocol/specs/src/worker/messages.json, /boot/10/refusal.\n */\nexport function workerMessagesBootCannotListen(placeholders: {\n readonly port: string;\n readonly why: string;\n}): string {\n return `Cannot listen on port ${placeholders.port}: ${placeholders.why}`;\n}\n\n/**\n * An object without a member its schema requires: `{member}` is the member's\n * name.\n *\n * protocol/specs/src/worker/messages.json, /reasons/0/line.\n */\nexport function workerMessagesReasonsMissing(placeholders: {\n readonly member: string;\n}): string {\n return ` Missing required property: ${placeholders.member}`;\n}\n\n/**\n * Any other way the document is not its schema's: `{member}` is the names on\n * the way from the document to the member, joined by `.`, with no index of an\n * array.\n *\n * protocol/specs/src/worker/messages.json, /reasons/1/line.\n */\nexport function workerMessagesReasonsOther(placeholders: {\n readonly member: string;\n}): string {\n return ` ${placeholders.member}: is not what the schema states`;\n}\n\n/**\n * How an error names the job, by its type, as `{job}`: `{motivation}` is a mark\n * job's motivation.\n *\n * protocol/specs/src/worker/messages.json, /job/mark.\n */\nexport function workerMessagesJobMark(placeholders: {\n readonly motivation: string;\n}): string {\n return `mark (${placeholders.motivation})`;\n}\n\n/**\n * A job on a resource whose media type has no text the worker can read:\n * `{resourceId}` is the resource, and `{mediaType}` its media type.\n *\n * protocol/specs/src/worker/messages.json, /errors/0/error.\n */\nexport function workerMessagesErrorsUnextractable(placeholders: {\n readonly job: string;\n readonly resourceId: string;\n readonly mediaType: string;\n}): string {\n return `Cannot run ${placeholders.job} on resource ${placeholders.resourceId}: media type '${placeholders.mediaType}' has no extractable text to analyze`;\n}\n\n/**\n * A job on a resource whose anchored text the Smelter has not yet settled:\n * `{resourceId}` is the resource.\n *\n * protocol/specs/src/worker/messages.json, /errors/1/error.\n */\nexport function workerMessagesErrorsNotSettled(placeholders: {\n readonly resourceId: string;\n}): string {\n return `Anchored text not yet derived for resource ${placeholders.resourceId} — Smelter has not settled; retrying`;\n}\n\n/**\n * A job on a resource the anchored-text consult declines: `{resourceId}` is the\n * resource, and `{declined}` what the consult answered, `no-map` or `unknown`.\n *\n * protocol/specs/src/worker/messages.json, /errors/2/error.\n */\nexport function workerMessagesErrorsAnchoredDeclined(placeholders: {\n readonly job: string;\n readonly resourceId: string;\n readonly declined: string;\n}): string {\n return `Cannot run ${placeholders.job} on resource ${placeholders.resourceId}: anchored-text consult returned '${placeholders.declined}'`;\n}\n\n/**\n * A job of a motivation the engine that took it does not serve.\n *\n * protocol/specs/src/worker/messages.json, /errors/3/error.\n */\nexport function workerMessagesErrorsNotServed(placeholders: {\n readonly job: string;\n}): string {\n return `Worker not configured for job: ${placeholders.job}`;\n}\n\n/**\n * A tagging job handed over without the schema it names.\n *\n * protocol/specs/src/worker/messages.json, /errors/4/error.\n */\nexport function workerMessagesErrorsNoProcessor(placeholders: {\n readonly job: string;\n}): string {\n return `No processor for job: ${placeholders.job}`;\n}\n\n/**\n * A model whose window leaves a piece 64 tokens or fewer: `{contextTokens}` is\n * the window, `{scaffoldTokens}` the tokens of the prompt without its piece,\n * and `{inputBudget}` what is left, each in decimal digits.\n *\n * protocol/specs/src/worker/messages.json, /errors/5/error.\n */\nexport function workerMessagesErrorsWindowTooSmall(placeholders: {\n readonly contextTokens: string;\n readonly scaffoldTokens: string;\n readonly inputBudget: string;\n}): string {\n return `Inference window too small for detection: context ${placeholders.contextTokens} tokens minus scaffold ${placeholders.scaffoldTokens} leaves an input budget of ${placeholders.inputBudget} (need > 64). Use a model with a larger context window or reduce the prompt scaffold.`;\n}\n\n/**\n * An Ollama engine's generation refused: `{status}` is the status, and `{body}`\n * the body, as it was sent.\n *\n * protocol/specs/src/worker/messages.json, /errors/6/error.\n */\nexport function workerMessagesErrorsOllamaRefused(placeholders: {\n readonly status: string;\n readonly body: string;\n}): string {\n return `Ollama API error (${placeholders.status}): ${placeholders.body}`;\n}\n\n/**\n * An Anthropic engine's request refused: `{said}` is what its client says of\n * the refusal, which varies, and carries the refusal's status and the words of\n * its body's `error.message`.\n *\n * protocol/specs/src/worker/messages.json, /errors/7/error.\n */\nexport function workerMessagesErrorsAnthropicRefused(placeholders: {\n readonly said: string;\n}): string {\n return `${placeholders.said}`;\n}\n\n/**\n * An answer that cannot be read: `{detail}` is one of `details`, and\n * `{stopReason}` why the model stopped, `end_turn` where an Ollama engine's\n * says `stop`.\n *\n * protocol/specs/src/worker/messages.json, /errors/8/error.\n */\nexport function workerMessagesErrorsUnreadable(placeholders: {\n readonly detail: string;\n readonly stopReason: string;\n}): string {\n return `Structured response could not be read: ${placeholders.detail} (stop_reason: ${placeholders.stopReason})`;\n}\n\n/**\n * A refusal whose stated wait is over 120 seconds: `{failure}` is the refusal's\n * error, `anthropic-refused` or `anthropic-limits-refused`, and `{said}` one of\n * `waits`.\n *\n * protocol/specs/src/worker/messages.json, /errors/9/error.\n */\nexport function workerMessagesErrorsWaitStated(placeholders: {\n readonly failure: string;\n readonly said: string;\n}): string {\n return `${placeholders.failure}; the provider said to wait (${placeholders.said}), which is longer than the 120 seconds this driver waits`;\n}\n\n/**\n * An answer the provider withheld: `{why}` is ` ({category})` where it states a\n * category and `: {explanation}` where it states an explanation, in that order,\n * each left out where it states none.\n *\n * protocol/specs/src/worker/messages.json, /errors/10/error.\n */\nexport function workerMessagesErrorsWithheld(placeholders: {\n readonly why: string;\n}): string {\n return `The provider withheld its answer: refusal${placeholders.why}`;\n}\n\n/**\n * A mark job on an Anthropic model the Models API does not report strict\n * structured outputs for: `{model}` is the model.\n *\n * protocol/specs/src/worker/messages.json, /errors/11/error.\n */\nexport function workerMessagesErrorsNoStructuredOutputs(placeholders: {\n readonly model: string;\n}): string {\n return `Model '${placeholders.model}' does not report support for strict structured outputs (Models API capabilities.structured_outputs). It is refused: a generation the provider does not hold to the schema can come back unreadable. Give the agent that does this work a model that reports supported: true.`;\n}\n\n/**\n * `/api/show` refused: `{model}` is the model, `{status}` the status, and\n * `{said}` the body, as it was sent.\n *\n * protocol/specs/src/worker/messages.json, /errors/12/error.\n */\nexport function workerMessagesErrorsOllamaLimitsRefused(placeholders: {\n readonly model: string;\n readonly status: string;\n readonly said: string;\n}): string {\n return `Failed to discover model limits for '${placeholders.model}' from Ollama's /api/show: refused with status ${placeholders.status}: ${placeholders.said}`;\n}\n\n/**\n * The Models API refused: `{model}` is the model, `{status}` the status, and\n * `{said}` what `anthropic-refused` says of the refusal.\n *\n * protocol/specs/src/worker/messages.json, /errors/13/error.\n */\nexport function workerMessagesErrorsAnthropicLimitsRefused(placeholders: {\n readonly model: string;\n readonly status: string;\n readonly said: string;\n}): string {\n return `Failed to discover model limits for '${placeholders.model}' from the Models API: refused with status ${placeholders.status}: ${placeholders.said}`;\n}\n\n/**\n * `/api/show` answered with no context length: `{model}` is the model.\n *\n * protocol/specs/src/worker/messages.json, /errors/14/error.\n */\nexport function workerMessagesErrorsNoContextLength(placeholders: {\n readonly model: string;\n}): string {\n return `/api/show reports no context length for '${placeholders.model}'`;\n}\n\n/**\n * A yield job for a media type the worker does not generate: `{mediaType}` is\n * the job's `outputMediaType`, and `{generatable}` each media type\n * media-types/registry.json says is generatable, in its order, joined by ` or\n * `.\n *\n * protocol/specs/src/worker/messages.json, /errors/15/error.\n */\nexport function workerMessagesErrorsUnsupportedOutput(placeholders: {\n readonly mediaType: string;\n readonly generatable: string;\n}): string {\n return `Unsupported outputMediaType for generation: ${placeholders.mediaType}. Generation produces ${placeholders.generatable}.`;\n}\n\n/**\n * A yield job whose prompt and length are together over its model's window:\n * `{promptTokens}` is the tokens of the prompt, `{maxTokens}` the job's\n * `maxTokens`, `{model}` the model, and `{contextTokens}` its window, each\n * number in decimal digits.\n *\n * protocol/specs/src/worker/messages.json, /errors/16/error.\n */\nexport function workerMessagesErrorsOverWindow(placeholders: {\n readonly promptTokens: string;\n readonly maxTokens: string;\n readonly model: string;\n readonly contextTokens: string;\n}): string {\n return `The prompt (~${placeholders.promptTokens} tokens) and the ${placeholders.maxTokens} tokens asked for are together over the context window of '${placeholders.model}' (${placeholders.contextTokens} tokens)`;\n}\n\n/**\n * An answer that is not JSON.\n *\n * protocol/specs/src/worker/messages.json, /details/0/detail.\n */\nexport function workerMessagesDetailsNotJson(): string {\n return 'response is not valid JSON';\n}\n\n/**\n * An answer that is JSON and not an array: `{kind}` is what it is, `object`,\n * `string`, `number`, `boolean` or `null`.\n *\n * protocol/specs/src/worker/messages.json, /details/1/detail.\n */\nexport function workerMessagesDetailsNotArray(placeholders: {\n readonly kind: string;\n}): string {\n return `parsed to ${placeholders.kind}, not an array`;\n}\n\n/**\n * An answer with no text.\n *\n * protocol/specs/src/worker/messages.json, /details/2/detail.\n */\nexport function workerMessagesDetailsEmpty(): string {\n return 'response is empty';\n}\n\n/**\n * A `retry-after` of `{seconds}`, as it was sent.\n *\n * protocol/specs/src/worker/messages.json, /waits/0/said.\n */\nexport function workerMessagesWaitsSeconds(placeholders: {\n readonly seconds: string;\n}): string {\n return `retry-after: ${placeholders.seconds}`;\n}\n\n/**\n * A `retry-after-ms` of `{milliseconds}`, as it was sent.\n *\n * protocol/specs/src/worker/messages.json, /waits/1/said.\n */\nexport function workerMessagesWaitsMilliseconds(placeholders: {\n readonly milliseconds: string;\n}): string {\n return `retry-after-ms: ${placeholders.milliseconds}`;\n}\n\n/**\n * A knowledge base that refused the worker: `{domain}` is its domain. `reason`\n * says why.\n *\n * protocol/specs/src/worker/messages.json, /logged/0/fields/domain.\n */\nexport function workerMessagesLoggedRefusedFieldsDomain(placeholders: {\n readonly domain: string;\n}): string {\n return `${placeholders.domain}`;\n}\n\n/**\n * A knowledge base in trouble, which the worker starts again: `{domain}` is its\n * domain. `error` says what the trouble was, and `waitMs` how long it waits, in\n * milliseconds.\n *\n * protocol/specs/src/worker/messages.json, /logged/1/fields/domain.\n */\nexport function workerMessagesLoggedTroubleFieldsDomain(placeholders: {\n readonly domain: string;\n}): string {\n return `${placeholders.domain}`;\n}\n","// Generated from protocol/specs/src/sign-in-store (SignIn.json, owner-only.json, README.md); do not edit.\n// Regenerate: make generate (codegen/lib/sign_in/sign_in.ml)\n\n/** One sign-in to a running stack's knowledge base, as the sign-in store keeps it: the tokens an issuer issued to the script client, and what a renewal and a sign-out need of that issuer, learned once at sign-in. TOKENS, never a password. An entry of <stateDir>/tokens.json (see README.md). */\nexport interface SignIn {\n /** The access token: short-lived, sent as a Bearer token. */\n token: string;\n /** The refresh token: long-lived, and what renews the access token at the issuer without another sign-in. An entry with none cannot be renewed. */\n refreshToken?: string;\n /** Who signed in: the address the access token named when the sign-in was made, which is the one the gateway answers for it. For display. Absent when the token named none. A writer that renews an entry keeps it as it was. */\n email?: string;\n /** When the access token was issued to this machine, RFC 3339 in UTC. */\n obtainedAt: string;\n /** When the access token stops working, RFC 3339 in UTC, so a reader can renew before sending a token it knows is dead. Absent when the issuer named no lifetime: the gateway's refusal is then the signal. */\n expiresAt?: string;\n /** The issuer the sign-in came from: the one the access token named when the sign-in was made. A writer that renews an entry keeps it. */\n issuer: string;\n /** The issuer's token endpoint, where the refresh grant is made. */\n tokenEndpoint: string;\n /** The issuer's revocation endpoint (RFC 7009), where a sign-out tells it to forget the refresh token. Absent when the issuer has none. */\n revocationEndpoint?: string;\n}\n\n/** The directory's mode, in octal, on a system that has modes: its owner reads, writes and enters it, and nobody else does. */\nexport const OWNER_ONLY_DIRECTORY_MODE = 0o700;\n\n/** The mode, in octal, on a system that has modes, that a writer makes tokens.json's temporary file and its lock with, and the launcher its own files in its state home: its owner reads and writes each, and nobody else does. */\nexport const OWNER_ONLY_FILE_MODE = 0o600;\n\n/** The directory's access list on Windows, where a mode keeps nobody out, in SDDL, with `owner` where the SID of the user the writer runs as goes (its process token's user): full access for that user, the system and the administrators, and nobody else. It is handed down to everything made in the directory, and protected, so nothing is inherited from above. */\nexport function ownerOnlyDirectoryAccessList(owner: string): string {\n return 'D:PAI(A;OICI;FA;;;' + owner + ')(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)';\n}\n\n/** A file's access list on Windows, which the launcher gives each file it keeps to its owner, in SDDL, with `owner` where the SID of the user it runs as goes: the directory's list, with nothing handed down, since a file has nothing beneath it. Full access for that user, the system and the administrators, and nobody else, protected, so nothing is inherited from above. */\nexport function ownerOnlyFileAccessList(owner: string): string {\n return 'D:PAI(A;;FA;;;' + owner + ')(A;;FA;;;SY)(A;;FA;;;BA)';\n}\n\n/** The document's name in the state home: one sign-in per stack. */\nexport const SIGN_IN_STORE_FILE = 'tokens.json';\n\n/** The name, beside the document, of the file every writer locks from before its read until after its rename. */\nexport const SIGN_IN_STORE_LOCK = 'tokens.lock';\n\n/** On Windows, the high 32 bits of the offset of the one byte of the lock file that is locked: far past anything the file holds. */\nexport const SIGN_IN_STORE_WINDOWS_OFFSET_HIGH = 0x40000000;\n","/**\n * The operations that report inference limits — one per service that holds\n * inference credentials (the worker: `job:`; the librarian: `gather:`,\n * `match:`), each named `<flow>:limits-requested`. Derived from the bus\n * registry by that name, so a new key holder's operation joins by being\n * registered.\n */\nimport { BUS_OPERATIONS, type BusOperationKey } from './bus-operations';\n\nexport type LimitsOperation = Extract<\n BusOperationKey,\n `${string}:limits-requested`\n>;\n\nexport const LIMITS_OPERATIONS: readonly LimitsOperation[] = (\n Object.keys(BUS_OPERATIONS) as BusOperationKey[]\n).filter((op): op is LimitsOperation => op.endsWith(':limits-requested'));\n","// Generated from protocol/specs/src/bus/registry.json (channels, payloads, operations); do not edit.\n// Regenerate: make generate (codegen/lib/bus/typescript.ml)\n// Go counterpart: codegen/lib/bus/go.ml → go/bus\n//\n// Payload schemas themselves live in the OpenAPI components; the registry\n// names which one each channel carries, and every payload type here is\n// derived from that. Add or change a channel THERE.\n\nimport type { EventName } from './bus-protocol';\n\n/**\n * Where a channel sits relative to the hub: emitted toward it, delivered\n * from it (the fan-in set — BRIDGED_CHANNELS, by construction), or never on\n * the wire at all.\n */\nexport type ChannelDirection = 'outbound' | 'inbound' | 'in-process';\n\n/**\n * A channel's delivery class: what a subscriber is promised about a frame on\n * it when its stream drops, or is handed to another. The promise comes from\n * the frame's identity (protocol/contract/TRANSPORT-CONTRACT.md § Delivery).\n *\n * positioned — a recorded event delivered on its resource's scope. Its id\n * is its place in that resource's record: a subscriber that\n * names the last one it holds is sent what it missed.\n * correlated — the reply to a claimed request, routed to the client that\n * asked. Its id is the request's: it is recognised when it\n * arrives twice, and sent again while it is retained.\n * passing — every other frame. Nothing replays it.\n *\n * Derived from the registry's axes, never declared: an operation's replies\n * are correlated; a recorded event whose audience is `scoped` is positioned;\n * everything else that crosses the wire is passing. Who RECEIVES a frame is\n * the audience axis, and a different question.\n */\nexport type ChannelDelivery = 'positioned' | 'correlated' | 'passing';\n\nexport interface ChannelAttrs {\n /** In PERSISTED_EVENT_TYPES — lands in the event log, the system of record. */\n readonly recorded: boolean;\n readonly direction: ChannelDirection;\n /**\n * Does emitting this channel CHANGE the knowledge base, or only ask it\n * something?\n *\n * A WRITE is an act: it appends to the event log, or it enqueues or\n * transitions durable work the log will later cite. A READ answers from state\n * that already exists and leaves nothing behind — every `browse:*` request,\n * and the three lookups that merely resolve a token or a summary.\n *\n * The domain is exactly the EMITTABLE set: an operation's request, or a\n * `kind: command`. Inbound replies, broadcast events and in-process UI\n * signals are absent because nobody emits them at the gateway, so the\n * question does not arise. Every emittable channel names one side or the\n * other and the generator refuses — there is no default.\n *\n * The gateway reads this to decide when the record learns a principal's name:\n * a `_userId` stamp is NOT the test, because a read carries one too. Someone\n * who signs in and only browses is never named, and the profile publish rate\n * is the WRITE rate rather than the emit rate — orders of magnitude apart.\n */\n readonly writes?: boolean;\n /** Absent exactly when the channel never crosses the wire (`in-process`). */\n readonly delivery?: ChannelDelivery;\n}\n\nexport const CHANNEL_ATTRS = {\n 'yield:created': {\n recorded: true,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'yield:cloned': { recorded: true, direction: 'inbound', delivery: 'passing' },\n 'yield:updated': {\n recorded: true,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'yield:moved': { recorded: true, direction: 'inbound', delivery: 'passing' },\n 'yield:representation-added': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'yield:representation-removed': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'yield:create': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'yield:clone-persist': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'yield:update': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'yield:clone': { recorded: false, direction: 'in-process' },\n 'yield:clone-token-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'yield:clone-resource-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'yield:clone-create': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'yield:create-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:create-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-persist-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-persist-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:update-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:update-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-token-generated': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-token-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-resource-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-resource-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-created': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'yield:clone-create-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:added': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:removed': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:body-updated': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:entity-tag-added': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:entity-tag-removed': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:archived': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:unarchived': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'mark:create-request': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:delete': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:update-body': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:archive': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:unarchive': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:update-entity-types': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:create-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:create-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:commit': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'mark:commit-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:commit-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:delete-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:delete-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:archive-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:archive-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:unarchive-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:unarchive-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:update-entity-types-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:update-entity-types-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'mark:body-update-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'mark:requested': { recorded: false, direction: 'in-process' },\n 'mark:submit': { recorded: false, direction: 'in-process' },\n 'mark:delegate-timeout': { recorded: false, direction: 'in-process' },\n 'mark:create-error': { recorded: false, direction: 'in-process' },\n 'mark:delete-error': { recorded: false, direction: 'in-process' },\n 'bind:body-error': { recorded: false, direction: 'in-process' },\n 'frame:entity-type-added': {\n recorded: true,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'frame:tag-schema-added': {\n recorded: true,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'frame:add-entity-type': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'frame:add-tag-schema': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'frame:entity-type-add-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'frame:entity-type-add-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'frame:tag-schema-add-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'frame:tag-schema-add-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'principal:profiled': {\n recorded: true,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'principal:profile': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'bind:initiate': { recorded: false, direction: 'in-process' },\n 'bind:update-body': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'bind:body-updated': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'bind:body-update-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'match:search-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'match:search-results': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'match:search-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'match:resources-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'match:resources-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'match:resources-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'match:limits-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'match:limits-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'match:limits-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'gather:complete': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:resource-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'gather:resource-complete': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:resource-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:summary-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'gather:summary-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:summary-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:referenced-by-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'gather:referenced-by-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:referenced-by-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:limits-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'gather:limits-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'gather:limits-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:resource-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:resource-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:resource-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:resources-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:resources-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:resources-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:annotation-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:annotation-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:annotation-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:events-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:events-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:events-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:annotation-history-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:annotation-history-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:annotation-history-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:entity-types-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:entity-types-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:entity-types-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:tag-schemas-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:tag-schemas-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:tag-schemas-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:engines-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:engines-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:engines-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:profiles-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:profiles-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:profiles-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:kb-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:kb-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:kb-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:directory-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'browse:directory-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:directory-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'browse:click': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'browse:resource-open': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'browse:resource-viewed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'browse:entity-type-clicked': { recorded: false, direction: 'in-process' },\n 'panel:toggle': { recorded: false, direction: 'in-process' },\n 'panel:open': { recorded: false, direction: 'in-process' },\n 'panel:close': { recorded: false, direction: 'in-process' },\n 'shell:sidebar-toggle': { recorded: false, direction: 'in-process' },\n 'tabs:close': { recorded: false, direction: 'in-process' },\n 'tabs:reorder': { recorded: false, direction: 'in-process' },\n 'nav:link-clicked': { recorded: false, direction: 'in-process' },\n 'nav:push': { recorded: false, direction: 'in-process' },\n 'nav:external': { recorded: false, direction: 'in-process' },\n 'beckon:hover': { recorded: false, direction: 'in-process' },\n 'beckon:focus': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'beckon:sparkle': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'job:started': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'job:assigned': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'job:completed': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'job:failed': {\n recorded: true,\n direction: 'inbound',\n delivery: 'positioned',\n },\n 'job:start': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:assign': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:report-progress': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'job:complete': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'job:fail': { recorded: false, direction: 'inbound', delivery: 'passing' },\n 'job:checkpoint': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:queued': { recorded: false, direction: 'inbound', delivery: 'passing' },\n 'job:cancel-requested': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:cancel': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:limits-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'job:limits-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:limits-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:status-requested': {\n recorded: false,\n direction: 'outbound',\n writes: false,\n delivery: 'passing',\n },\n 'job:create': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:claim': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'job:status-result': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:status-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:created': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:create-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:claimed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:claim-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:cancel-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'job:cancel-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'weave:applied': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'smelt:settled': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'weave:rebuild': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'weave:rebuild-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'weave:rebuild-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'smelt:rebuild-anchors': {\n recorded: false,\n direction: 'outbound',\n writes: true,\n delivery: 'passing',\n },\n 'smelt:rebuild-anchors-ok': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'smelt:rebuild-anchors-failed': {\n recorded: false,\n direction: 'inbound',\n delivery: 'correlated',\n },\n 'settings:theme-changed': { recorded: false, direction: 'in-process' },\n 'settings:line-numbers-toggled': { recorded: false, direction: 'in-process' },\n 'settings:locale-changed': { recorded: false, direction: 'in-process' },\n 'settings:hover-delay-changed': { recorded: false, direction: 'in-process' },\n 'bus:resume-gap': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'session:joined': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n 'session:left': {\n recorded: false,\n direction: 'inbound',\n delivery: 'passing',\n },\n} as const satisfies Record<EventName, ChannelAttrs>;\n","/**\n * A channel's attributes (`CHANNEL_ATTRS`, bus-classification.ts) read by a\n * name that is not yet known to be a channel's.\n */\n\nimport { CHANNEL_ATTRS, type ChannelAttrs } from './bus-classification';\n\nconst BY_CHANNEL: ReadonlyMap<string, ChannelAttrs> = new Map(\n Object.entries(CHANNEL_ATTRS),\n);\n\n/** String-keyed accessor for boundary code that has not yet narrowed to\n * EventName. Undefined means \"not a channel\", never \"unclassified\" — the\n * `satisfies` on CHANNEL_ATTRS makes unclassified unrepresentable. */\nexport const channelAttrsOf = (channel: string): ChannelAttrs | undefined =>\n BY_CHANNEL.get(channel);\n\n/** Did emitting this channel CHANGE the knowledge base? False for a read, and\n * for anything nobody emits — both are \"no act happened\", which is the\n * question every caller is actually asking. */\nexport const channelWrites = (channel: string): boolean =>\n BY_CHANNEL.get(channel)?.writes === true;\n","/**\n * Anchor a W3C Web Annotation to its rendered text.\n *\n * Render-time cleverness is deliberately limited to **verbatim** quote\n * matching. The annotation's two selectors are written to agree (on the\n * write side `reconcile` finds the span, and `annotationOfSpan` refuses one\n * whose text from `start` to `end` is not `exact`). At render time the\n * only legitimate discrepancy is *positional drift*: the document grew or\n * shrank above the span after the annotation was written, so the offset is\n * stale but the exact text still exists, byte-identical, elsewhere. That is\n * the W3C-intended role of `TextQuoteSelector`, and it is safe because it\n * demands identical text — no normalization, no fuzzy matching, no\n * judgment call.\n *\n * Anything that would require *fuzzy* recovery (smart-quote folding,\n * whitespace collapse, Levenshtein) is out of scope here: a non-verbatim\n * mismatch means the content representation diverged or the stored record\n * is wrong, both of which are deterministic and belong upstream (canonical\n * content, or a corrected annotation event). The renderer does not guess —\n * it renders at the stored offset and flags the anchor low-confidence so\n * the discrepancy surfaces for an upstream fix.\n *\n * Returns `null` only when nothing usable is present; otherwise always\n * returns a position with a `strategy` and `confidence`.\n *\n * A position, given or answered, is two offsets: they count Unicode code\n * points from the start of the content, as a `TextPositionSelector` does.\n * They are a string's own positions only in a text with no character outside\n * the Basic Multilingual Plane; a renderer that slices a string, or hands a\n * position to something that indexes one, converts with `textOffsets`.\n */\n\nimport { occurrencesOf, textOffsets, type TextOffsets } from './text-offsets';\n\nexport type AnchorStrategy =\n /** Position hint pointed exactly at the exact text. Unambiguous. */\n | 'fast-path'\n /** Exact text appears once verbatim in the content. No tiebreak needed. */\n | 'unique-occurrence'\n /** Multiple verbatim occurrences; prefix+suffix uniquely identified one. */\n | 'context-disambiguated'\n /** Multiple verbatim candidates; position closest to hint chosen. */\n | 'position-tiebreaker'\n /** Exact text not found verbatim (or no quote); raw stored offset used,\n * flagged for upstream correction. */\n | 'position-fallback';\n\nexport type AnchorConfidence = 'high' | 'medium' | 'low';\n\nexport interface RenderedAnchor {\n /** The offset the anchor starts at, in code points. */\n start: number;\n /** The offset just after it. */\n end: number;\n strategy: AnchorStrategy;\n confidence: AnchorConfidence;\n}\n\nexport interface AnchorSelectors {\n /** A `TextPositionSelector`'s two offsets, in code points. */\n position?: { start: number; end: number };\n quote?: { exact: string; prefix?: string; suffix?: string };\n}\n\n/**\n * Distance window for the position tiebreaker, in code points. Candidates\n * closer than this to the hint receive a non-zero position score; further\n * candidates fall back to zero. Tuned for typical document sizes;\n * calibration tests pin the boundary behaviour rather than the exact value.\n */\nexport const POSITION_WINDOW = 1024;\n\n/**\n * Score weights — kept as named constants so the calibration tests can\n * import them and pin the *relationships* rather than the magnitudes.\n *\n * Invariant: a full-context match always outranks any position score.\n * (`CONTEXT_FULL_WEIGHT * 2 > POSITION_WEIGHT_MAX`, accounting for\n * prefix+suffix each contributing the full weight.)\n */\nexport const CONTEXT_FULL_WEIGHT = 10;\nexport const CONTEXT_PARTIAL_WEIGHT = 5;\nexport const POSITION_WEIGHT_MAX = 5;\n\n/**\n * Locate the best-effort anchor for an annotation against the content the\n * renderer is about to display. Verbatim-only — see the module doc.\n *\n * `selectors.position` is given as offsets and the anchor is answered as\n * offsets, both in code points. `offsets` is the content's own\n * (`textOffsets(content)`): a renderer with several annotations of one\n * content makes it once.\n */\nexport function anchorAnnotation(\n content: string,\n offsets: TextOffsets,\n selectors: AnchorSelectors,\n): RenderedAnchor | null {\n const { position, quote } = selectors;\n\n // No quote selector. Position is the only signal; use it verbatim if\n // present and in-range, otherwise the annotation has no anchor.\n if (!quote || !quote.exact) {\n if (!position) return null;\n if (\n position.start < 0 ||\n position.end > offsets.length ||\n position.start >= position.end\n ) {\n return null;\n }\n return {\n start: position.start,\n end: position.end,\n strategy: 'position-fallback',\n confidence: 'low',\n };\n }\n\n const { exact, prefix, suffix } = quote;\n // How many code points the quote is: an occurrence of it ends this far on.\n const length = textOffsets(exact).length;\n\n // Fast path: position hint exactly matches the exact text. A stored start\n // that is no offset at all (not a whole number) is between no two\n // characters, and is left to the search below.\n if (position) {\n const probeEnd = position.start + length;\n if (\n Number.isInteger(position.start) &&\n position.start >= 0 &&\n probeEnd <= offsets.length &&\n content.substring(\n offsets.indexAt(position.start),\n offsets.indexAt(probeEnd),\n ) === exact\n ) {\n return {\n start: position.start,\n end: probeEnd,\n strategy: 'fast-path',\n confidence: 'high',\n };\n }\n }\n\n // Find all occurrences via exact indexOf. Cheap; bounded by content\n // size; sufficient for the common case where the renderer's content\n // matches the worker's content character-for-character.\n const occurrences = occurrencesOf(content, offsets, exact);\n\n if (occurrences.length === 1) {\n const start = occurrences[0]!;\n return {\n start,\n end: start + length,\n strategy: 'unique-occurrence',\n confidence: 'high',\n };\n }\n\n if (occurrences.length > 1) {\n const winner = pickByScore(\n content,\n offsets,\n occurrences,\n length,\n prefix,\n suffix,\n position?.start,\n );\n return winner;\n }\n\n // No verbatim occurrence. We do NOT fuzzy-match at render time — a\n // non-verbatim mismatch means the content diverged or the record is\n // wrong, which is an upstream concern. Render at the stored offset so the\n // highlight still appears, flagged low-confidence so the discrepancy is\n // visible and gets corrected at the source.\n if (\n position &&\n position.start >= 0 &&\n position.end <= offsets.length &&\n position.start < position.end\n ) {\n return {\n start: position.start,\n end: position.end,\n strategy: 'position-fallback',\n confidence: 'low',\n };\n }\n\n return null;\n}\n\n/**\n * Context match score at a candidate offset.\n * Returns full / partial / no-match per side (prefix and suffix), then\n * sums each side weighted by `CONTEXT_FULL_WEIGHT` / `CONTEXT_PARTIAL_WEIGHT`.\n *\n * \"Full\" means the stored context aligns exactly with the source text\n * adjacent to the candidate. \"Partial\" is the looser substring check —\n * the stored context appears somewhere in the candidate's surroundings\n * but isn't anchored to the edges. The scorer uses it as one signal among\n * many, not as a hard filter.\n *\n * `pos` is the candidate's offset. The surroundings compared are as many\n * code points of the content, on either side of the candidate, as the stored\n * context has.\n */\nfunction contextScoreAt(\n content: string,\n offsets: TextOffsets,\n pos: number,\n prefix: string | undefined,\n suffix: string | undefined,\n lengths: QuoteLengths,\n): { score: number; full: boolean } {\n let score = 0;\n let prefixFull = true;\n let suffixFull = true;\n\n if (prefix) {\n const adj = content.substring(\n offsets.indexAt(Math.max(0, pos - lengths.prefix)),\n offsets.indexAt(pos),\n );\n if (adj.endsWith(prefix)) {\n score += CONTEXT_FULL_WEIGHT;\n prefixFull = true;\n } else if (adj.includes(prefix.trim()) && prefix.trim().length > 0) {\n score += CONTEXT_PARTIAL_WEIGHT;\n prefixFull = false;\n } else {\n prefixFull = false;\n }\n }\n\n if (suffix) {\n const adj = content.substring(\n offsets.indexAt(pos + lengths.exact),\n offsets.indexAt(\n Math.min(offsets.length, pos + lengths.exact + lengths.suffix),\n ),\n );\n if (adj.startsWith(suffix)) {\n score += CONTEXT_FULL_WEIGHT;\n suffixFull = true;\n } else if (adj.includes(suffix.trim()) && suffix.trim().length > 0) {\n score += CONTEXT_PARTIAL_WEIGHT;\n suffixFull = false;\n } else {\n suffixFull = false;\n }\n }\n\n // \"Full\" overall match means every provided context field aligned\n // exactly — no partial fallbacks. Used to bump confidence to high.\n const full =\n (prefix === undefined || prefixFull) &&\n (suffix === undefined || suffixFull) &&\n (prefix !== undefined || suffix !== undefined);\n\n return { score, full };\n}\n\n/** How many code points the quote and its stored context are. A context that is not given is none. */\ninterface QuoteLengths {\n exact: number;\n prefix: number;\n suffix: number;\n}\n\nfunction positionScoreAt(pos: number, hint: number | undefined): number {\n if (hint === undefined) return 0;\n const distance = Math.abs(pos - hint);\n if (distance >= POSITION_WINDOW) return 0;\n return POSITION_WEIGHT_MAX * (1 - distance / POSITION_WINDOW);\n}\n\nfunction pickByScore(\n content: string,\n offsets: TextOffsets,\n occurrences: number[],\n length: number,\n prefix: string | undefined,\n suffix: string | undefined,\n hint: number | undefined,\n): RenderedAnchor {\n // Measured once, for every candidate.\n const lengths: QuoteLengths = {\n exact: length,\n prefix: prefix === undefined ? 0 : textOffsets(prefix).length,\n suffix: suffix === undefined ? 0 : textOffsets(suffix).length,\n };\n\n let bestPos = occurrences[0]!;\n let bestScore = -1;\n let bestContextFull = false;\n let bestHasAnyContextSignal = false;\n let bestHasAnyPositionSignal = false;\n\n for (const pos of occurrences) {\n const ctx = contextScoreAt(content, offsets, pos, prefix, suffix, lengths);\n const positionScore = positionScoreAt(pos, hint);\n const total = ctx.score + positionScore;\n if (total > bestScore) {\n bestScore = total;\n bestPos = pos;\n bestContextFull = ctx.full;\n bestHasAnyContextSignal = ctx.score > 0;\n bestHasAnyPositionSignal = positionScore > 0;\n }\n }\n\n // Strategy + confidence classification:\n // - both context fields aligned exactly → high-confidence context-disambiguated\n // - some context aligned (full or partial), no position needed → context-disambiguated, medium\n // - position broke the tie (winning candidate has position signal but no context signal,\n // or context was equal across candidates) → position-tiebreaker\n // - no signal at all (all candidates scored zero) → position-tiebreaker, low confidence,\n // deterministic first-of-many fallback\n let strategy: AnchorStrategy;\n let confidence: AnchorConfidence;\n\n if (bestContextFull) {\n strategy = 'context-disambiguated';\n confidence = 'high';\n } else if (bestHasAnyContextSignal && !bestHasAnyPositionSignal) {\n strategy = 'context-disambiguated';\n confidence = 'medium';\n } else if (bestHasAnyContextSignal && bestHasAnyPositionSignal) {\n // Context partially matched and position helped break the tie.\n strategy = 'position-tiebreaker';\n confidence = 'medium';\n } else if (bestHasAnyPositionSignal) {\n strategy = 'position-tiebreaker';\n confidence = 'medium';\n } else {\n strategy = 'position-tiebreaker';\n confidence = 'low';\n }\n\n return {\n start: bestPos,\n end: bestPos + length,\n strategy,\n confidence,\n };\n}\n","// Generated from protocol/specs/src/locales/registry.json; do not edit.\n// Regenerate: make generate (codegen/lib/locales/locales.ml)\n\n/** The code of every supported language, in the registry's order. */\nexport const LOCALE_CODES = [\n 'ar',\n 'bn',\n 'cs',\n 'da',\n 'de',\n 'el',\n 'en',\n 'es',\n 'fa',\n 'fi',\n 'fr',\n 'he',\n 'hi',\n 'id',\n 'it',\n 'ja',\n 'ko',\n 'ms',\n 'nl',\n 'no',\n 'pl',\n 'pt',\n 'ro',\n 'sv',\n 'th',\n 'tr',\n 'uk',\n 'vi',\n 'zh',\n] as const;\n\n/** The code of a supported language. */\nexport type LocaleCode = (typeof LOCALE_CODES)[number];\n\n/** A supported language: its code, what it calls itself, and its name in English. */\nexport interface LocaleInfo {\n code: LocaleCode;\n nativeName: string;\n englishName: string;\n}\n\n/** A row per supported language, in the registry's order. */\nexport const LOCALES: readonly LocaleInfo[] = [\n { code: 'ar', nativeName: 'العربية', englishName: 'Arabic' },\n { code: 'bn', nativeName: 'বাংলা', englishName: 'Bengali' },\n { code: 'cs', nativeName: 'Čeština', englishName: 'Czech' },\n { code: 'da', nativeName: 'Dansk', englishName: 'Danish' },\n { code: 'de', nativeName: 'Deutsch', englishName: 'German' },\n { code: 'el', nativeName: 'Ελληνικά', englishName: 'Greek' },\n { code: 'en', nativeName: 'English', englishName: 'English' },\n { code: 'es', nativeName: 'Español', englishName: 'Spanish' },\n { code: 'fa', nativeName: 'فارسی', englishName: 'Persian' },\n { code: 'fi', nativeName: 'Suomi', englishName: 'Finnish' },\n { code: 'fr', nativeName: 'Français', englishName: 'French' },\n { code: 'he', nativeName: 'עברית', englishName: 'Hebrew' },\n { code: 'hi', nativeName: 'हिन्दी', englishName: 'Hindi' },\n { code: 'id', nativeName: 'Bahasa Indonesia', englishName: 'Indonesian' },\n { code: 'it', nativeName: 'Italiano', englishName: 'Italian' },\n { code: 'ja', nativeName: '日本語', englishName: 'Japanese' },\n { code: 'ko', nativeName: '한국어', englishName: 'Korean' },\n { code: 'ms', nativeName: 'Bahasa Melayu', englishName: 'Malay' },\n { code: 'nl', nativeName: 'Nederlands', englishName: 'Dutch' },\n { code: 'no', nativeName: 'Norsk', englishName: 'Norwegian' },\n { code: 'pl', nativeName: 'Polski', englishName: 'Polish' },\n { code: 'pt', nativeName: 'Português', englishName: 'Portuguese' },\n { code: 'ro', nativeName: 'Română', englishName: 'Romanian' },\n { code: 'sv', nativeName: 'Svenska', englishName: 'Swedish' },\n { code: 'th', nativeName: 'ไทย', englishName: 'Thai' },\n { code: 'tr', nativeName: 'Türkçe', englishName: 'Turkish' },\n { code: 'uk', nativeName: 'Українська', englishName: 'Ukrainian' },\n { code: 'vi', nativeName: 'Tiếng Việt', englishName: 'Vietnamese' },\n { code: 'zh', nativeName: '中文', englishName: 'Chinese' },\n];\n","/**\n * The languages Xynolog supports, and lookups over them. The table is\n * generated from protocol/specs/src/locales/registry.json.\n */\n\nimport { LOCALES, type LocaleInfo } from './locale-registry';\n\nexport { LOCALES, LOCALE_CODES } from './locale-registry';\nexport type { LocaleCode, LocaleInfo } from './locale-registry';\n\n// Create lookup map for efficient access\nconst localeByCode = new Map<string, LocaleInfo>(\n LOCALES.map((locale) => [locale.code.toLowerCase(), locale]),\n);\n\n/**\n * Get locale information by code\n */\nexport function getLocaleInfo(\n code: string | undefined,\n): LocaleInfo | undefined {\n if (!code) return undefined;\n return localeByCode.get(code.toLowerCase());\n}\n\n/**\n * Format locale code for display as \"Native Name (code)\"\n */\nexport function formatLocaleDisplay(\n code: string | undefined,\n): string | undefined {\n if (!code) return undefined;\n\n const info = getLocaleInfo(code);\n if (!info) return code;\n\n return `${info.nativeName} (${code.toLowerCase()})`;\n}\n","/**\n * SVG Utility Functions\n *\n * Utilities for creating, parsing, and manipulating W3C-compliant SVG selectors\n * for image annotation.\n */\n\nexport interface Point {\n x: number;\n y: number;\n}\n\n/**\n * Create W3C-compliant SVG rectangle selector\n */\nexport function createRectangleSvg(start: Point, end: Point): string {\n const x = Math.min(start.x, end.x);\n const y = Math.min(start.y, end.y);\n const width = Math.abs(end.x - start.x);\n const height = Math.abs(end.y - start.y);\n\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><rect x=\"${x}\" y=\"${y}\" width=\"${width}\" height=\"${height}\"/></svg>`;\n}\n\n/**\n * Create W3C-compliant SVG polygon selector\n */\nexport function createPolygonSvg(points: Point[]): string {\n if (points.length < 3) {\n throw new Error('Polygon requires at least 3 points');\n }\n\n const pointsStr = points.map((p) => `${p.x},${p.y}`).join(' ');\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><polygon points=\"${pointsStr}\"/></svg>`;\n}\n\n/**\n * Create W3C-compliant SVG circle selector\n */\nexport function createCircleSvg(center: Point, radius: number): string {\n if (radius <= 0) {\n throw new Error('Circle radius must be positive');\n }\n\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"${center.x}\" cy=\"${center.y}\" r=\"${radius}\"/></svg>`;\n}\n\n/**\n * The attributes of the first `<name …/>` element in `svg`: white space after\n * the name, at least one more character, and `/>` at the first `>`. Found by\n * index, in one pass, where a regular expression would backtrack quadratically.\n */\nfunction selfClosingElementAttributes(\n svg: string,\n name: string,\n): string | undefined {\n const opener = `<${name}`;\n let close = -1;\n for (\n let start = svg.indexOf(opener);\n start !== -1;\n start = svg.indexOf(opener, start + 1)\n ) {\n const attributesStart = start + opener.length;\n if (close < attributesStart) close = svg.indexOf('>', attributesStart);\n if (close === -1) return undefined;\n const attributes = svg.slice(attributesStart, close - 1);\n if (\n attributes.length >= 2 &&\n /\\s/.test(attributes.charAt(0)) &&\n svg.charAt(close - 1) === '/'\n ) {\n return attributes;\n }\n }\n return undefined;\n}\n\n/**\n * Parse SVG selector to extract shape type and data\n */\nexport function parseSvgSelector(svg: string):\n | {\n type: 'rect';\n data: { x: number; y: number; width: number; height: number };\n }\n | { type: 'polygon'; data: { points: Point[] } }\n | { type: 'circle'; data: { cx: number; cy: number; r: number } }\n | null {\n // Extract rectangle\n const rectAttributes = selfClosingElementAttributes(svg, 'rect');\n if (rectAttributes !== undefined) {\n const attrs = rectAttributes;\n const x = parseFloat(attrs.match(/x=\"([^\"]+)\"/)?.[1] || '0');\n const y = parseFloat(attrs.match(/y=\"([^\"]+)\"/)?.[1] || '0');\n const width = parseFloat(attrs.match(/width=\"([^\"]+)\"/)?.[1] || '0');\n const height = parseFloat(attrs.match(/height=\"([^\"]+)\"/)?.[1] || '0');\n\n return {\n type: 'rect',\n data: { x, y, width, height },\n };\n }\n\n // Extract polygon\n const polygonMatch = svg.match(/<polygon\\s+points=\"([^\"]+)\"/);\n if (polygonMatch && polygonMatch[1]) {\n const pointsStr = polygonMatch[1];\n const points = pointsStr.split(/\\s+/).map((pair) => {\n const [x, y] = pair.split(',').map(parseFloat);\n return { x, y };\n });\n\n return {\n type: 'polygon',\n data: { points },\n };\n }\n\n // Extract circle\n const circleAttributes = selfClosingElementAttributes(svg, 'circle');\n if (circleAttributes !== undefined) {\n const attrs = circleAttributes;\n const cx = parseFloat(attrs.match(/cx=\"([^\"]+)\"/)?.[1] || '0');\n const cy = parseFloat(attrs.match(/cy=\"([^\"]+)\"/)?.[1] || '0');\n const r = parseFloat(attrs.match(/r=\"([^\"]+)\"/)?.[1] || '0');\n\n return {\n type: 'circle',\n data: { cx, cy, r },\n };\n }\n\n return null;\n}\n\n/**\n * Scale entire SVG selector from display space to image native resolution\n */\nexport function scaleSvgToNative(\n svg: string,\n displayWidth: number,\n displayHeight: number,\n imageWidth: number,\n imageHeight: number,\n): string {\n const parsed = parseSvgSelector(svg);\n if (!parsed) return svg;\n\n const scaleX = imageWidth / displayWidth;\n const scaleY = imageHeight / displayHeight;\n\n switch (parsed.type) {\n case 'rect': {\n const { x, y, width, height } = parsed.data;\n return createRectangleSvg(\n { x: x * scaleX, y: y * scaleY },\n { x: (x + width) * scaleX, y: (y + height) * scaleY },\n );\n }\n\n case 'circle': {\n const { cx, cy, r } = parsed.data;\n return createCircleSvg(\n { x: cx * scaleX, y: cy * scaleY },\n r * Math.min(scaleX, scaleY),\n );\n }\n\n case 'polygon': {\n const points = parsed.data.points.map((p: Point) => ({\n x: p.x * scaleX,\n y: p.y * scaleY,\n }));\n return createPolygonSvg(points);\n }\n }\n}\n","/**\n * Generic validation utilities for @xynolog/http-transport\n *\n * Pure TypeScript validation with no external dependencies.\n * Safe to use in any JavaScript environment (Node.js, browser, Deno, etc.)\n */\n\n/**\n * Validation result types\n */\nexport type ValidationSuccess<T> = { success: true; data: T };\nexport type ValidationFailure = {\n success: false;\n error: string;\n details?: string[];\n};\nexport type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure;\n\n/**\n * JWT Token validation\n *\n * Validates JWT token format (header.payload.signature).\n * Does not verify signature - use for format validation only.\n */\nexport const JWTTokenSchema = {\n parse(token: unknown): string {\n if (typeof token !== 'string') {\n throw new Error('Token must be a string');\n }\n if (!token || token.length === 0) {\n throw new Error('Token is required');\n }\n // JWT format: header.payload.signature\n const jwtRegex = /^[A-Za-z0-9\\-_]+\\.[A-Za-z0-9\\-_]+\\.[A-Za-z0-9\\-_]*$/;\n if (!jwtRegex.test(token)) {\n throw new Error('Invalid JWT token format');\n }\n return token;\n },\n\n safeParse(token: unknown): ValidationResult<string> {\n try {\n const validated = this.parse(token);\n return { success: true, data: validated };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Invalid JWT token',\n };\n }\n },\n};\n\n/**\n * Generic validation helper with error formatting\n *\n * Wraps any schema's parse method with try/catch and returns ValidationResult.\n *\n * @example\n * ```typescript\n * const result = validateData(JWTTokenSchema, 'eyJ...');\n * if (result.success) {\n * console.log('Valid token:', result.data);\n * } else {\n * console.error('Invalid:', result.error);\n * }\n * ```\n */\nexport function validateData<T>(\n schema: { parse(data: unknown): T },\n data: unknown,\n): ValidationResult<T> {\n try {\n const validated = schema.parse(data);\n return { success: true, data: validated };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Validation failed',\n };\n }\n}\n\n/**\n * Email validation helper\n *\n * Validates email format using RFC 5322 simplified regex.\n *\n * @param email - Email address to validate\n * @returns true if valid email format\n */\nexport function isValidEmail(email: string): boolean {\n if (email.length < 1 || email.length > 255) {\n return false;\n }\n // RFC 5322 simplified email regex\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(email);\n}\n","import type { BehaviorSubject, Observable } from 'rxjs';\n\n/**\n * A state as its readers are given it: the value now (`getValue`) and each\n * value after it, and nothing that sets it. Whatever writes a state in a\n * `BehaviorSubject` hands out this view of it, so a reader cannot write past\n * what holds it: Python's `Watched`, Rust's `watch::Receiver`.\n */\nexport interface Watched<T> extends Observable<T> {\n getValue(): T;\n}\n\n/** The read-only view of a state held in `held`. */\nexport function watched<T>(held: BehaviorSubject<T>): Watched<T> {\n return Object.assign(held.asObservable(), {\n getValue: () => held.getValue(),\n });\n}\n","/**\n * Storage URI Derivation\n *\n * Builds the name a resource's content lives under in the working tree, from\n * its title and validated media type. Extensions come from the media-type\n * registry; formats are validated upstream at the create/yield boundary, so\n * the lookup is strict — no fallback.\n *\n * Lives in `@xynolog/core` because the generation form proposes a default\n * path, and react-ui depends on no package that needs Node. This module\n * imports only the registry, so it is browser-safe.\n */\n\nimport { MEDIA_TYPES } from './media-types';\nimport type { SupportedMediaType } from './types';\n\n/**\n * The FILENAME a resource's content takes: slug + the registry's extension.\n *\n * The name is lowercased, runs of non-alphanumeric characters collapse to\n * single hyphens, and leading/trailing hyphens are stripped.\n *\n * This is the fragment form, for callers composing a path themselves — the\n * generation form's input sits beside a `file://` prefix chip, so it must not\n * strip a prefix this helper just added.\n *\n * @example\n * storageFileName(\"My Document\", \"text/markdown\") // => \"my-document.md\"\n */\nexport function storageFileName(\n name: string,\n format: SupportedMediaType,\n): string {\n const slug = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '');\n return `${slug}${MEDIA_TYPES[format].extension}`;\n}\n\n/**\n * Derive a full `file://` storage URI from a resource name and media type.\n *\n * @example\n * deriveStorageUri(\"My Document\", \"text/markdown\") // => \"file://my-document.md\"\n */\nexport function deriveStorageUri(\n name: string,\n format: SupportedMediaType,\n): string {\n return `file://${storageFileName(name, format)}`;\n}\n\n/**\n * The folder a resource lives in, WITHOUT a trailing slash — `''` when it sits\n * at the tree root. Accepts a `file://` URI or a bare path.\n */\nexport function folderOf(storageUri: string | undefined): string {\n const path = (storageUri ?? '').replace(/^file:\\/\\//, '');\n const cut = path.lastIndexOf('/');\n return cut === -1 ? '' : path.slice(0, cut);\n}\n\n/**\n * The Save location a form PROPOSES: beside the source resource, named for the\n * title, extended for the chosen format.\n *\n * Deriving the whole filename — extension included — has a happy consequence:\n * while untouched, switching format rewrites the extension too, so the form's\n * refusal of an extension that disagrees with the format becomes unreachable\n * except on hand-edited paths. It guards deliberate edits rather than trapping\n * ordinary use.\n *\n * Returns `''` for an empty title: a bare extension (\".md\") reads as a hidden\n * file and is nobody's intent.\n */\nexport function proposeStoragePath(\n folder: string,\n title: string,\n format: SupportedMediaType,\n): string {\n const name = storageFileName(title, format);\n if (name === MEDIA_TYPES[format].extension) return '';\n return folder ? `${folder}/${name}` : name;\n}\n","/**\n * The knowledge base's own identity, in its two renderings: its did:web and\n * its resource identifier, both from its committed `site.domain`.\n *\n * Nothing here names a person or an agent: the gateway, in Rust, mints every\n * principal's DID, and the record reads them\n * (`protocol/specs/src/principals/cases.json`, `protocol/specs/src/principals/kind-cases.json`).\n */\n\n/**\n * The knowledge base's own did:web identity, from its committed\n * `site.domain`, which the gateway states in the description it serves.\n *\n * Format: `did:web:<domain>` — the domain **verbatim, never encoded**. The\n * project file already stores it in did:web colon-path form\n * (`xynoplex.github.io:xynoplex-caselaw-kb`), so encoding those colons\n * would mint a string nothing else in the system produces. The launcher\n * mints the identical string in Go (`kbconfig.go` `didWeb()`), and the two\n * MUST agree byte-for-byte: the Browser joins discovered KBs to connected\n * ones on this value, and a mismatch fails silently — looking implemented\n * while never matching.\n *\n * A KB has no did when it declares no domain; identity is declared, never\n * defaulted or inferred from an address.\n */\nexport function kbDid(domain: string): string {\n return `did:web:${domain}`;\n}\n\n/**\n * The knowledge base's RESOURCE identifier: its did:web rendered as the https\n * URL that DID method resolves to, and the single value a token's `aud` must\n * carry. `did:web` turns the colon path into a slash path, so\n * `did:web:example.github.io:my-kb` identifies\n * `https://example.github.io/my-kb`.\n *\n * This is an IDENTIFIER, not an address. Nothing dereferences it, and it does\n * not have to equal the origin a request happened to arrive on — a knowledge\n * base reached over http in local development still identifies itself by the\n * https form, because its identity is declared, not observed. That is what\n * makes the value stable across every host, port and proxy it is reached\n * through, which is the whole reason `aud` can be checked at all.\n *\n * Derived from the SAME committed `site.domain` as `kbDid`, so the two\n * cannot drift; the launcher mints the identical string in Go\n * (`kbconfig.go` `kbResource`) and the two MUST agree byte-for-byte.\n */\nexport function kbResource(domain: string): string {\n return `https://${domain.split(':').join('/')}`;\n}\n","// Generated from protocol/specs/src/session/client-assertion-cases.json; do not edit.\n// Regenerate: make generate (codegen/lib/client_assertion.ml)\n\n/** The grant's client_assertion_type for an assertion that is a JWT. */\nexport const JWT_BEARER =\n 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';\n\n/** How long after it is made an assertion is good for, in seconds. */\nexport const LIFETIME_SECONDS = 60;\n","/**\n * A service account's assertion of itself, signed with its own key (RFC 7523\n * §2.2, OpenID Connect's `private_key_jwt`).\n *\n * The issuer holds the key's public half, registered on the account's client,\n * and checks the signature with it: the private key never leaves the process,\n * and no secret is sent. The assertion's shape is\n * protocol/specs/src/session/client-assertion-cases.json's.\n *\n * The key is WebCrypto's, which a browser withholds from a page that is not a\n * secure context. A page never holds a service account's key: a worker does,\n * and a worker is a process.\n */\n\nimport { base64url } from './base64url';\nimport { LIFETIME_SECONDS } from './client-assertion-facts';\nimport { refuseNonFinite } from './refuse-non-finite';\nimport { sha256 } from './sha256';\n\n/** An RSA key's public members as a JWK states them: base64url, unpadded, of the unsigned big-endian bytes. */\nexport interface RsaPublicMembers {\n n: string;\n e: string;\n}\n\nconst RS256 = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' } as const;\n\nconst PKCS8_PEM =\n /^-----BEGIN PRIVATE KEY-----([A-Za-z0-9+/=\\s]+)-----END PRIVATE KEY-----$/;\nconst NOT_PKCS8_PEM =\n 'The key is not a PKCS#8 PEM private key: one that begins `-----BEGIN PRIVATE KEY-----`';\nconst NOT_RSA =\n 'The PEM holds no RSA private key: a service account signs its assertions with RS256';\nconst NOT_RS256 =\n 'The key does not sign RS256 (RSASSA-PKCS1-v1_5 with SHA-256): read it with `privateKeyFromPem`';\n\nconst utf8 = new TextEncoder();\nconst segment = (value: object): string =>\n base64url(utf8.encode(JSON.stringify(value, refuseNonFinite)));\n\n/** The key's JWK thumbprint (RFC 7638): the SHA-256 of `e`, `kty` and `n`, in that order, with no whitespace. */\nexport function thumbprint({ n, e }: RsaPublicMembers): string {\n return base64url(sha256(utf8.encode(`{\"e\":\"${e}\",\"kty\":\"RSA\",\"n\":\"${n}\"}`)));\n}\n\n/** An assertion's header: RS256, and the key it is signed with, by its thumbprint. */\nexport function assertionHeader(key: RsaPublicMembers): {\n alg: 'RS256';\n kid: string;\n} {\n return { alg: 'RS256', kid: thumbprint(key) };\n}\n\n/** An assertion's claims: the client is its issuer and its subject, and the token endpoint its audience. */\nexport function assertionClaims(\n clientId: string,\n tokenEndpoint: string,\n { issuedAt, jti }: { issuedAt: number; jti: string },\n): {\n iss: string;\n sub: string;\n aud: string;\n jti: string;\n iat: number;\n exp: number;\n} {\n return {\n iss: clientId,\n sub: clientId,\n aud: tokenEndpoint,\n jti,\n iat: issuedAt,\n exp: issuedAt + LIFETIME_SECONDS,\n };\n}\n\n/**\n * The RSA private key a PKCS#8 PEM holds (`-----BEGIN PRIVATE KEY-----`), as a\n * key that signs RS256. A PEM that is not PKCS#8, or holds a key that is not\n * RSA, is refused, and the refusal never repeats it.\n *\n * The key is extractable: an assertion names it by its thumbprint, and its\n * public members are read by exporting it.\n */\nexport async function privateKeyFromPem(pem: string): Promise<CryptoKey> {\n const armored = PKCS8_PEM.exec(pem.trim());\n if (armored === null) throw new Error(NOT_PKCS8_PEM);\n let der: Uint8Array<ArrayBuffer>;\n try {\n der = Uint8Array.from(atob(armored[1].replace(/\\s/g, '')), (char) =>\n char.charCodeAt(0),\n );\n } catch {\n throw new Error(NOT_PKCS8_PEM);\n }\n try {\n return await crypto.subtle.importKey('pkcs8', der, RS256, true, ['sign']);\n } catch {\n throw new Error(NOT_RSA);\n }\n}\n\n/** The assertion, signed: a compact JWT of `assertionHeader` and `assertionClaims`, RS256 with `privateKey`. */\nexport async function clientAssertion(\n privateKey: CryptoKey,\n clientId: string,\n tokenEndpoint: string,\n made: { issuedAt: number; jti: string },\n): Promise<string> {\n const { kty, alg, n, e } = await crypto.subtle.exportKey('jwk', privateKey);\n if (kty !== 'RSA' || alg !== 'RS256' || n === undefined || e === undefined)\n throw new Error(NOT_RS256);\n const signingInput = `${segment(assertionHeader({ n, e }))}.${segment(assertionClaims(clientId, tokenEndpoint, made))}`;\n const signature = await crypto.subtle.sign(\n RS256,\n privateKey,\n utf8.encode(signingInput),\n );\n return `${signingInput}.${base64url(new Uint8Array(signature))}`;\n}\n","/**\n * An exchange that has `ms` to end. `exchange` is given a signal that is\n * aborted with a `TimeoutError` once `ms` have passed, and the wait is let go\n * when the exchange ends, however it ends. The wait is a timer global, which\n * a test's fake timers move; `AbortSignal.timeout` keeps its wait natively,\n * where no fake reaches it.\n *\n * Whatever reads the answer belongs inside `exchange`: a body read after it\n * has ended has no deadline.\n */\nexport async function withinDeadline<T>(\n ms: number,\n exchange: (signal: AbortSignal) => Promise<T>,\n): Promise<T> {\n const deadline = new AbortController();\n const timer = setTimeout(() => {\n deadline.abort(\n new DOMException(`The deadline of ${ms}ms passed`, 'TimeoutError'),\n );\n }, ms);\n try {\n return await exchange(deadline.signal);\n } finally {\n clearTimeout(timer);\n }\n}\n","/**\n * Why a sign-in at an issuer failed: a person's, over any of the grants the\n * session layer runs, or a service account's, over the client-credentials\n * grant (`ServiceToken`).\n */\n\nimport type { SignInErrorCode } from './error-codes';\n\nexport class SignInError extends Error {\n constructor(\n readonly code: SignInErrorCode,\n message: string,\n /**\n * The HTTP status the issuer answered with, when there was one.\n *\n * Absent means no response existed to read — `fetch` threw. That\n * difference decides whether a session ends or its refresh is retried: an\n * issuer refusing a grant and a network losing a packet are not the same\n * event, and a status that went only into the message would leave the two\n * indistinguishable one layer up.\n */\n readonly status?: number,\n ) {\n super(message);\n this.name = 'SignInError';\n }\n}\n","/**\n * When a token is renewed: the one schedule every holder of a token keeps, a\n * session's and a service account's alike.\n */\n\nimport { MIN_REFRESH_DELAY_MS, REFRESH_BEFORE_EXP_MS } from './client-timing';\nimport { isObject } from './type-guards';\n\n/**\n * JWT segments are base64**url**, and `atob` is strict base64: it throws\n * `InvalidCharacterError` on `-` and `_`, the two characters base64url\n * substitutes for `+` and `/`, and it wants the `=` padding JWTs omit.\n *\n * Pure-ASCII payloads seldom produce those characters, so a bare `atob`\n * appears to work. A non-ASCII `name` claim produces them often — 2 of 8\n * sample names, \"Zoë Fauré\" among them — and it is deterministic per\n * account, so an affected user hits it on every token they are ever issued.\n *\n * The consequence is not a missing refresh. `isJwtExpired` answers `true`\n * when the payload will not parse, and it gates both startup and the KB\n * panel's status — so under a bare `atob` those users' perfectly valid\n * sessions read as expired, every time. `TextDecoder` rather than a\n * charCode loop because the payload is UTF-8 by definition, and that is the\n * whole reason those bytes are there.\n */\nfunction decodeBase64Url(segment: string): string {\n const base64 = segment.replace(/-/g, '+').replace(/_/g, '/');\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n '=',\n );\n const binary = atob(padded);\n const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));\n return new TextDecoder().decode(bytes);\n}\n\n/** A JWT's payload; null when the token is no JWT, or its payload no JSON. */\nexport function jwtPayload(token: string): unknown {\n try {\n const parts = token.split('.');\n if (parts.length !== 3 || !parts[1]) return null;\n return JSON.parse(decodeBase64Url(parts[1]));\n } catch {\n return null;\n }\n}\n\n/** A claim of `token`'s that is a count of seconds; undefined when it states none. */\nexport function secondsClaim(token: string, name: string): number | undefined {\n const payload = jwtPayload(token);\n if (!isObject(payload)) return undefined;\n const claim = payload[name];\n return typeof claim === 'number' && Number.isFinite(claim)\n ? claim\n : undefined;\n}\n\n/**\n * How long to wait before renewing a token that lives `lifetimeMs` in all and\n * has `remainingMs` of it left.\n *\n * **The margin is a fraction of the token's OWN lifetime**, capped at\n * {@link REFRESH_BEFORE_EXP_MS}. That is the whole point: a constant margin can\n * equal — or exceed — the lifetime of a token some issuer mints, and when it\n * does, the subtraction yields a moment already past. Half the lifetime cannot,\n * for any lifetime, so no issuer's configuration can produce a refresh loop. This\n * matters beyond the realm Xynolog runs: for `type = \"oidc\"` the launcher\n * deliberately refuses to set a lifespan at all, so an external issuer's\n * lifetime is not ours to correct and the client is the only place that can be\n * right for every issuer.\n */\nexport function renewalDelayMs(\n lifetimeMs: number,\n remainingMs: number,\n): number {\n const marginMs = Math.min(REFRESH_BEFORE_EXP_MS, Math.max(0, lifetimeMs) / 2);\n return Math.max(MIN_REFRESH_DELAY_MS, remainingMs - marginMs);\n}\n\n/**\n * How long to wait before proactively refreshing `token`, or `null` when it\n * carries no `exp` to schedule against (the caller then schedules nothing):\n * {@link renewalDelayMs} of the lifetime its claims state.\n */\nexport function refreshDelayMs(\n token: string,\n now: number = Date.now(),\n): number | null {\n const exp = secondsClaim(token, 'exp');\n if (!exp) return null;\n\n const expMs = exp * 1000;\n const iat = secondsClaim(token, 'iat');\n // `exp - iat` is the lifetime the issuer chose. Without `iat` — not every\n // issuer sends one — the remaining life is the only lifetime observable,\n // and halving that is bounded too, which is the property that matters.\n const lifetimeMs = iat ? (exp - iat) * 1000 : expMs - now;\n return renewalDelayMs(lifetimeMs, expMs - now);\n}\n","/**\n * A request that got no answer, and what its failure says of why.\n *\n * `fetch` rejects with what the runtime made of the failure, and the runtime\n * quotes the exchange in it. Node keeps what it could not read of an answer\n * on the error's cause, says a header's value in the message of an error\n * about one, and says a URL in the message of an error about that. Whatever\n * parses a body says where it stopped, and quotes the body there. A request\n * is made with a token and an answer may grant one, and a failure is printed\n * and logged whole.\n *\n * So no failure made here is `fetch`'s own, and none holds it. A failure says\n * the kind of error it was, by the code or the name the runtime gave it, and\n * none of the runtime's words.\n */\n\nimport { TransportError } from './errors';\nimport { isObject } from './type-guards';\n\n/** A code or a name as a runtime writes one: an identifier, and so not words. */\nconst IDENTIFIER = /^[A-Za-z][A-Za-z0-9_]*$/;\n\n/** `value`, when it is a code or a name that says which kind of error it was. `Error` says none. */\nfunction kind(value: unknown): string | undefined {\n return typeof value === 'string' &&\n IDENTIFIER.test(value) &&\n value !== 'Error'\n ? value\n : undefined;\n}\n\n/**\n * Why a request got no answer, as its failure may say it: the code of what\n * caused the rejection (`ECONNREFUSED`), failing that its name\n * (`HTTPParserError`), failing that the rejection's own name (`TimeoutError`).\n */\nexport function whyUnanswered(error: unknown): string {\n if (!isObject(error)) return 'Error';\n const cause = isObject(error['cause']) ? error['cause'] : undefined;\n return (\n kind(cause?.['code']) ??\n kind(cause?.['name']) ??\n kind(error['name']) ??\n 'Error'\n );\n}\n\n/**\n * A request that got no answer: the far end was not reached, what came was\n * not HTTP, or the request's deadline passed.\n *\n * It states no status, since nothing answered with one, and is filed under\n * `unavailable` as every such failure is. Wherever a status that says \"not\n * now\" is worth another attempt, so is this (`isRetryableRequestError`).\n */\nexport class UnansweredError extends TransportError {\n declare readonly code: 'unavailable';\n\n /** `what` names the request. `error` is what `fetch`, or the read of its answer's body, rejected with. */\n constructor(what: string, error: unknown) {\n super(`${what} got no answer: ${whyUnanswered(error)}`, 'unavailable');\n this.name = 'UnansweredError';\n }\n}\n\n/**\n * An answer's body, read as JSON. Nothing, when it is not JSON: what the\n * parser says of such a body quotes it, and is said by no one.\n *\n * A body that stops coming is a request that got no answer, and `unanswered`\n * makes the failure of it.\n */\nexport async function jsonOf(\n response: Response,\n unanswered: (error: unknown) => Error,\n): Promise<unknown> {\n try {\n const body: unknown = await response.json();\n return body;\n } catch (error) {\n if (error instanceof SyntaxError) return undefined;\n throw unanswered(error);\n }\n}\n","/**\n * The client-credentials grant, for a process authenticating as ITSELF.\n *\n * A service or a worker holds its own account at the knowledge base's\n * issuer and exchanges that credential for a short-lived token. That token is\n * its bearer at the gateway, which names it by that account: an agent is an\n * account, as a person is. The account proves itself with its client secret,\n * or with a key: each grant then carries an assertion signed for it alone\n * (`client-assertion.ts`), and no secret is sent.\n *\n * This replaced a single shared secret that every sidecar carried and that the\n * gateway compared by string equality. That secret granted any agent identity\n * to anyone holding it, and could only be rotated by restarting the stack.\n *\n * The token endpoint is discovered rather than constructed. Every issuer\n * publishes it; guessing a vendor's path would put that vendor's layout in\n * code that has no other reason to know it.\n */\n\nimport { clientAssertion } from './client-assertion';\nimport { JWT_BEARER } from './client-assertion-facts';\nimport { withinDeadline } from './deadline';\nimport type { TransportTiming } from './client-timing';\nimport { uuidV4 } from './id-generation';\nimport { SignInError } from './sign-in-error';\nimport { refreshDelayMs, renewalDelayMs } from './token-renewal';\nimport { isObject, isString } from './type-guards';\nimport type { ClientSecretForm } from './types';\nimport { UnansweredError, jsonOf } from './unanswered';\n\n/** A service account at an issuer, which proves itself with its client secret. */\nexport interface SecretCredential {\n /** The issuer URL, exactly as it appears in tokens' `iss`. */\n issuer: string;\n clientId: string;\n clientSecret: string;\n}\n\n/**\n * A service account at an issuer, which proves itself with a key: each grant\n * carries an assertion signed with `privateKey`, which the issuer checks with\n * the public half registered on the client. The key never leaves the process.\n */\nexport interface KeyCredential {\n /** The issuer URL, exactly as it appears in tokens' `iss`. */\n issuer: string;\n clientId: string;\n /** An RSA key that signs RS256, as `privateKeyFromPem` reads one. */\n privateKey: CryptoKey;\n}\n\n/** A service account at an issuer, by how it proves itself. */\nexport type ServiceAccountCredential = SecretCredential | KeyCredential;\n\n/**\n * The fetch a request is sent with: the one its caller gave, or the runtime's\n * own, looked up as each request is made. Either is called as a plain\n * function, never as a method of something else, which a browser refuses.\n */\nfunction fetchOf(given: typeof fetch | undefined): typeof fetch {\n return (...request: Parameters<typeof fetch>) =>\n (given ?? globalThis.fetch)(...request);\n}\n\n/** The client-credentials grant's form: the secret itself, or an assertion signed for this grant alone. */\nasync function proof(\n credential: ServiceAccountCredential,\n endpoint: string,\n): Promise<URLSearchParams> {\n if ('clientSecret' in credential) {\n return new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: credential.clientId,\n client_secret: credential.clientSecret,\n } satisfies ClientSecretForm);\n }\n const assertion = await clientAssertion(\n credential.privateKey,\n credential.clientId,\n endpoint,\n {\n issuedAt: Math.floor(Date.now() / 1000),\n jti: uuidV4(),\n },\n );\n return new URLSearchParams({\n grant_type: 'client_credentials' satisfies ClientSecretForm['grant_type'],\n client_assertion_type: JWT_BEARER,\n client_assertion: assertion,\n });\n}\n\n/**\n * A service account's token, fetched on first use and held until it is due\n * for renewal. A process makes one for its account, with its transport's\n * `timing` and the `fetch` its issuer is asked with, and asks it for the\n * token whenever it needs one.\n *\n * The issuer's token endpoint is discovered by the first ask, and kept for as\n * long as the holder is. A discovery that failed, because the issuer was still\n * booting, is not kept: the next ask discovers again.\n *\n * One grant is made at a time: those who ask while one is under way are given\n * what it brings, as they wait their turn.\n *\n * It is due for renewal by the schedule a session keeps (`refreshDelayMs`):\n * half its lifetime before it expires, at most `REFRESH_BEFORE_EXP_MS`. Its\n * own `exp` and `iat` say how long it lives, or failing those the grant's\n * `expires_in`, since a client-credentials access token need not be a JWT;\n * a token that says neither is not held.\n */\nexport class ServiceToken {\n private endpoint: string | null = null;\n private held: { token: string; renewAt: number } | null = null;\n /** The ask whose turn it is; the next waits for it to settle, however it does. */\n private asking: Promise<unknown> = Promise.resolve();\n\n constructor(\n private readonly credential: ServiceAccountCredential,\n private readonly timing: TransportTiming,\n private readonly fetch?: typeof globalThis.fetch,\n ) {}\n\n private async tokenEndpoint(): Promise<string> {\n if (this.endpoint === null) this.endpoint = await this.discover();\n return this.endpoint;\n }\n\n private async discover(): Promise<string> {\n const { issuer } = this.credential;\n const url = new URL(\n '.well-known/openid-configuration',\n issuer.endsWith('/') ? issuer : `${issuer}/`,\n );\n const unanswered = (error: unknown) =>\n new UnansweredError(`OIDC discovery for ${issuer}`, error);\n const document = await withinDeadline(\n this.timing.httpRequestTimeoutMs,\n async (signal) => {\n const response = await fetchOf(this.fetch)(url, { signal }).catch(\n (error: unknown) => {\n throw unanswered(error);\n },\n );\n if (!response.ok) {\n throw new SignInError(\n 'discovery',\n `OIDC discovery for ${issuer} failed: HTTP ${response.status} from ${url}`,\n response.status,\n );\n }\n return jsonOf(response, unanswered);\n },\n );\n if (!isObject(document) || !isString(document['token_endpoint'])) {\n throw new SignInError(\n 'discovery',\n `OIDC discovery for ${issuer} returned no \\`token_endpoint\\``,\n );\n }\n return document['token_endpoint'];\n }\n\n /** The `Authorization` header's value: the account's token, renewed when it is due. */\n async authorization(): Promise<string> {\n return `Bearer ${await this.token({ renewed: false })}`;\n }\n\n /**\n * The account's access token: the one held until it is due for renewal,\n * and a new grant after it, or at once when `renewed` (the gateway refused\n * the one held, or it is due by the asker's own schedule).\n *\n * Throws on refusal rather than returning null: a sidecar that cannot prove\n * who it is has nothing useful to do, and the caller's retry policy decides\n * whether this is worth attempting again. A refusal is a `SignInError`\n * carrying the status the issuer answered with; a request that got no\n * answer is an `UnansweredError`.\n *\n * Both requests, the issuer's discovery and the grant, are bounded by the\n * `httpRequestTimeoutMs` of the timing this was made with\n * (protocol/specs/src/client/timing.json): an issuer that\n * accepts a connection and never answers would otherwise hold a process's\n * start, and every renewal after it, for as long as the process lives. Both\n * are sent with the `fetch` this was made with, or the runtime's own.\n */\n token({ renewed }: { renewed: boolean }): Promise<string> {\n const turn = this.asking.then(() => this.granted(renewed));\n // The next ask waits for this one whether it brought a token or failed:\n // its failure is its own asker's, who is handed `turn`.\n this.asking = turn.then(\n () => undefined,\n () => undefined,\n );\n return turn;\n }\n\n /** `token`, in its turn. */\n private async granted(renewed: boolean): Promise<string> {\n const { issuer, clientId } = this.credential;\n\n if (!renewed && this.held && this.held.renewAt > Date.now()) {\n return this.held.token;\n }\n\n const endpoint = await this.tokenEndpoint();\n const form = await proof(this.credential, endpoint);\n\n const unanswered = (error: unknown) =>\n new UnansweredError(\n `Client-credentials grant for ${clientId} at ${issuer}`,\n error,\n );\n const body = await withinDeadline(\n this.timing.httpRequestTimeoutMs,\n async (signal) => {\n const response = await fetchOf(this.fetch)(endpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: form,\n signal,\n }).catch((error: unknown) => {\n throw unanswered(error);\n });\n\n if (!response.ok) {\n // The status, not the body: a token endpoint's error body can echo the\n // request, and this one carried the secret or the assertion.\n throw new SignInError(\n 'exchange',\n `Client-credentials grant for ${clientId} at ${issuer} failed (HTTP ${response.status})`,\n response.status,\n );\n }\n\n return jsonOf(response, unanswered);\n },\n );\n if (!isObject(body) || !isString(body['access_token'])) {\n throw new SignInError(\n 'exchange',\n `Token endpoint for ${issuer} returned no \\`access_token\\``,\n );\n }\n\n const token = body['access_token'];\n const expiresIn = body['expires_in'];\n const now = Date.now();\n const lifetimeMs =\n typeof expiresIn === 'number' &&\n Number.isFinite(expiresIn) &&\n expiresIn >= 0\n ? expiresIn * 1000\n : undefined;\n const renewInMs =\n refreshDelayMs(token, now) ??\n (lifetimeMs === undefined\n ? null\n : renewalDelayMs(lifetimeMs, lifetimeMs));\n // A token that states no lifetime is not held, and neither is the one it\n // replaces, rather than either living by a guess: serving a token past\n // its expiry fails at the far end, where the cause is hardest to see. One\n // is used until it is due, and never past its expiry: the schedule's\n // floor is for a timer, which a token already expired must not turn into\n // a loop, and nothing here loops.\n this.held =\n renewInMs === null\n ? null\n : {\n token,\n renewAt:\n now +\n (lifetimeMs === undefined\n ? renewInMs\n : Math.min(renewInMs, lifetimeMs)),\n };\n return token;\n }\n}\n","/**\n * The text a `Binary` is held as in JSON, as protocol/specs/src/json/binary-cases.json\n * states it: the standard base64 of its bytes, padded (RFC 4648 section 4).\n */\n\n/** `bytes` as their text: each run of bytes has one. */\nexport function binaryText(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\n/**\n * The bytes `text` is, or undefined for a text no bytes are written as: one\n * not of the standard alphabet, not a whole four, padded short, with white\n * space, or whose padded last four leaves bits that are not zero. `atob`\n * forgives all but the first, so a text is read only when its bytes are\n * written as it.\n */\nexport function binaryOf(text: string): Uint8Array | undefined {\n let binary: string;\n try {\n binary = atob(text);\n } catch {\n return undefined;\n }\n const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));\n return binaryText(bytes) === text ? bytes : undefined;\n}\n","/**\n * Knowledge-graph view derivation: the flattened neighborhood views are derived from the graph,\n * not kept as separately built intermediates.\n *\n * A pure function over the core `KnowledgeGraph` type. `@xynolog/react-ui` (the context summary) runs\n * it, and protocol/specs/src/librarian/derive-views-cases.json holds it to the derivation the Librarian runs. It\n * only transforms a graph the Librarian has already built.\n *\n * Reports the graph as-is: missing-view citers are kept (the citing annotation reflects a\n * real reference event; its resource label falls back to the raw id). A citation is its linking\n * ANNOTATION: an annotation node with `annotation-of` → the citing resource and `cites` → the focal\n * resource — so citedBy resolves through that pair, deduped per citing resource (several citations\n * from one document are one citer). Siblings are annotations ON the focal resource\n * (`annotation-of` → main), excluding the focal annotation — an annotation isn't its own sibling,\n * and a CITING annotation lives on another resource, so it never was one. Peer connections are\n * edges out of `mainResourceId`; derivation is structural (endpoints), never a match on the\n * free-form relationshipType. The graph is a projection of the event log (the system of record),\n * read here because it is the queryable projection at gather time.\n */\nimport type { KnowledgeGraphNodesItem, KnowledgeGraph } from './types';\n\nexport interface GraphViews {\n connections: {\n resourceId: string;\n resourceName: string;\n entityTypes: string[];\n bidirectional: boolean;\n }[];\n citedBy: { resourceId: string; resourceName: string }[];\n citedByCount: number;\n siblingEntityTypes: string[];\n}\n\nexport function deriveViews(\n graph: KnowledgeGraph,\n mainResourceId: string,\n focalAnnotationId?: string,\n): GraphViews {\n // An edge names its ends as text, of either kind of node: the nodes are\n // looked up by that text.\n const nodeById = new Map<string, KnowledgeGraphNodesItem>(\n graph.nodes.map((n) => [n.id, n]),\n );\n // annotation id → the resource it lives on. Both derivations resolve through\n // this, which is what keeps them structural: a peer connection whose\n // relationshipType happens to be named 'cites' has no annotation-of entry.\n const annotationOf = new Map<string, string>();\n for (const edge of graph.edges) {\n if (edge.type === 'annotation-of')\n annotationOf.set(edge.source, edge.target);\n }\n\n const connections: GraphViews['connections'] = [];\n const citedBy: GraphViews['citedBy'] = [];\n const citingSeen = new Set<string>();\n for (const edge of graph.edges) {\n const citingResource =\n edge.type === 'cites' && edge.target === mainResourceId\n ? annotationOf.get(edge.source)\n : undefined;\n if (citingResource !== undefined) {\n if (citingSeen.has(citingResource)) continue;\n citingSeen.add(citingResource);\n const node = nodeById.get(citingResource);\n citedBy.push({\n resourceId: citingResource,\n resourceName: node?.label ?? citingResource,\n });\n } else if (edge.source === mainResourceId) {\n const node = nodeById.get(edge.target);\n connections.push({\n resourceId: edge.target,\n resourceName: node?.label ?? edge.target,\n entityTypes: node?.entityTypes ?? [],\n bidirectional: edge.bidirectional ?? false,\n });\n }\n }\n\n const siblingEntityTypes = new Set<string>();\n for (const node of graph.nodes) {\n if (\n node.type === 'annotation' &&\n node.id !== focalAnnotationId &&\n annotationOf.get(node.id) === mainResourceId\n ) {\n for (const et of node.entityTypes ?? []) siblingEntityTypes.add(et);\n }\n }\n\n return {\n connections,\n citedBy,\n citedByCount: citedBy.length,\n siblingEntityTypes: Array.from(siblingEntityTypes),\n };\n}\n","/**\n * Retry: the mechanism, and the classifications core itself owns.\n *\n * At its centre is `retryWithBackoff`, which makes a request again inside a\n * budget `protocol/specs/src/client/timing.json` states: one emit inside\n * `emitRetry` (http-transport), one renewal inside `refreshRetry` (sdk).\n *\n * **What lives HERE — the mechanism, because it is one fact each:**\n * - `RetryBudget` / `retryWithBackoff` — the loop, deadline-aware\n * - `equalJitter` — the backoff curve, shared with the SSE reconnect\n * - the predicates that narrow an error type CORE owns (`isTransientFetchError`\n * over `fetch`'s `TypeError`, `isRetryableRequestError` over `HttpStatusError`)\n *\n * **What deliberately does NOT — the judgment, because each is local knowledge:**\n * - **budgets.** Each is client timing, generated into `client-timing.ts`,\n * and taken by the call it bounds.\n * - **deadlines.** Each sits with the call it bounds.\n * - **predicates over another package's errors.** Core has no business\n * knowing that a provider's 404 means \"not pulled yet\".\n *\n * **Deadlines beat budgets.** `retryWithBackoff` takes an optional `AbortSignal`\n * so a caller with its own deadline stops the retry when it falls due, instead\n * of the two numbers having to be kept compatible by hand across packages. That\n * is the `context.Context` / gRPC-deadline move, with the platform's own\n * primitive.\n */\n\nimport { RETRY_RULES } from './retry-rules';\nimport type { RetryBudget } from './types';\nimport { UnansweredError } from './unanswered';\n\n/**\n * Equal jitter: half the computed ceiling, plus a random share of the other\n * half — delay ∈ [cap/2, cap).\n *\n * **One home, because it is one fact.** `retryWithBackoff` and the SSE reconnect\n * loop (`actor-state-unit.ts`) both need it, and a copy in each would be two\n * implementations agreeing by coincidence, free to drift the first time\n * either is tuned. The reconnect computes its own ceiling (`reconnectMs · 2ⁿ`,\n * capped); only the jitter is shared, which is the part that must not diverge.\n *\n * Unconditional in `retryWithBackoff`, not an option. Every caller of\n * `retryWithBackoff` may be one of many clients retrying against ONE gateway,\n * which is precisely the lockstep this exists to break: N peers backing off by\n * an identical schedule re-converge on the same instant and re-deliver the\n * burst that caused the failure. A flag would leave that hazard\n * reachable by default-choosing, and nobody would ever pass `false`.\n *\n * The worst case is unchanged — `delay <= cap` still holds, so the patience\n * budget a policy advertises stays true; only the expected wait drops, to ~75%.\n */\nexport function equalJitter(cap: number): number {\n return cap / 2 + Math.random() * (cap / 2);\n}\n\n/**\n * True for the errors `fetch` throws when the connection itself fails —\n * undici's `TypeError: fetch failed` (ECONNREFUSED, ENOTFOUND, reset,\n * timeout — the socket error rides in `cause`). Deliberately false for\n * HTTP-level failures (a 401 means the gateway is UP and rejected us;\n * retrying won't change its mind) and for programming errors.\n */\nexport function isTransientFetchError(error: unknown): boolean {\n if (!(error instanceof TypeError)) return false;\n if (error.message === 'fetch failed') return true;\n const code = (error.cause as { code?: string } | undefined)?.code;\n return typeof code === 'string' && code.length > 0;\n}\n\n/**\n * An error that knows the HTTP status the server answered with.\n *\n * Structural rather than a class, because the class already exists:\n * http-transport's `APIError` carries `status` and cannot be named from here\n * without inverting the package dependency. This interface is the contract\n * between the thrower and `isRetryableRequestError`, stated once — a predicate\n * that recovered the status by parsing it back out of an error MESSAGE would be\n * a second statement of the same fact, in the fragile direction.\n */\nexport interface HttpStatusError extends Error {\n readonly status: number;\n /** The wait the response's `Retry-After` stated, in milliseconds; none when it stated none. */\n readonly retryAfterMs: number | undefined;\n}\n\n/**\n * A `Retry-After` header's wait in milliseconds, when it states one in seconds\n * — the form the gateway sends (`TooManyRequests`, `AtCapacity`); none\n * otherwise.\n */\nexport function retryAfterMs(header: string | null): number | undefined {\n return header !== null && /^[0-9]+$/.test(header.trim())\n ? Number(header.trim()) * 1000\n : undefined;\n}\n\n/**\n * True for failures worth another attempt: the connection never landed\n * (`isTransientFetchError`), the request got no answer (`UnansweredError`),\n * the server answered \"not now\" (`RETRY_RULES.boot`), or our own deadline\n * expired.\n *\n * The status half is DERIVED from `RETRY_RULES.boot` rather than restated here.\n * A private set of the same statuses would make the taxonomy a second opinion\n * instead of the answer — and a second opinion in the same package is the exact\n * defect the `RETRY_RULES` catalog exists to remove. The reasoning for those\n * statuses, and for excluding `500`, lives once, in the rule.\n *\n * The timeout case is the one that is easy to get wrong. A request whose\n * deadline passes (`withinDeadline`) rejects with a **DOMException named\n * `TimeoutError`**, not a `TypeError` — measured, not assumed — so\n * `isTransientFetchError` cannot see it, and without this case a request that\n * bounds itself is unretryable precisely when the bound fires. Matched by\n * `name` rather than `instanceof DOMException` because the constructor is not\n * guaranteed present in every runtime this package builds for, while the name\n * is part of the DOM spec.\n *\n * Auth and validation failures stay excluded, preserving `isTransientFetchError`'s\n * reasoning verbatim: a 401 means the gateway is UP and rejected us, and retrying\n * will not change its mind. A 429 differs — the gateway is up and *asking* us to\n * wait, so the same \"it answered\" fact points the other way.\n */\nexport function isRetryableRequestError(error: unknown): boolean {\n if (isTransientFetchError(error) || error instanceof UnansweredError)\n return true;\n if (typeof error !== 'object' || error === null) return false;\n if ((error as { name?: unknown }).name === 'TimeoutError') return true;\n const status = (error as { status?: unknown }).status;\n return typeof status === 'number' && RETRY_RULES.boot.retryable({ status });\n}\n\n/**\n * Resolves `true` once `ms` have passed, or `false` as soon as `signal`\n * aborts, letting go of the wait it no longer needs.\n */\nfunction waited(ms: number, signal: AbortSignal | undefined): Promise<boolean> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve(false);\n return;\n }\n const cutShort = () => {\n clearTimeout(timer);\n resolve(false);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', cutShort);\n resolve(true);\n }, ms);\n signal?.addEventListener('abort', cutShort, { once: true });\n });\n}\n\n/**\n * Run `fn`, retrying on errors `isRetryable` accepts, with equal-jitter\n * exponential backoff per `policy`. The final error (retryable budget\n * exhausted, or the first non-retryable one) is rethrown verbatim.\n *\n * `signal` is the caller's deadline. Once it aborts no attempt is made: an\n * aborted signal rejects with its reason before the first, and a wait between\n * attempts ends at once, rethrowing the error that began it. The attempt in\n * flight is the caller's to give up, by giving its own call the signal.\n */\nexport async function retryWithBackoff<T>(\n fn: () => Promise<T>,\n isRetryable: (error: unknown) => boolean,\n policy: RetryBudget,\n signal?: AbortSignal,\n): Promise<T> {\n signal?.throwIfAborted();\n let cap = policy.initialDelayMs;\n for (let attempt = 1; ; attempt++) {\n try {\n return await fn();\n } catch (error) {\n // The caller's deadline outranks the budget. Without this, a caller that\n // races its own timeout against work that retries has two numbers it must\n // keep compatible by hand — and the day they stop being compatible, the\n // race kills a retry that was about to succeed.\n if (signal?.aborted) throw error;\n if (attempt >= policy.attempts || !isRetryable(error)) throw error;\n // A wait the server stated (`Retry-After`) is a floor under the jittered\n // one: a refused caller backs off by the server's clock, not its own.\n const stated = (error as { retryAfterMs?: unknown }).retryAfterMs;\n const delayMs = Math.max(\n equalJitter(cap),\n typeof stated === 'number' ? stated : 0,\n );\n if (!(await waited(delayMs, signal))) throw error;\n cap = Math.min(cap * 2, policy.maxDelayMs);\n }\n }\n}\n","// Generated from protocol/specs/src/client/surface.json; do not edit.\n// Regenerate: make generate (codegen/lib/discovery_url_path.ml)\n\n/** Where a launcher's discovery document is: its path under the state home, and the URL path a browser fetches it at. */\nexport const DISCOVERY_URL_PATH = '/discovery/kbs.json';\n"]}