@xynolog/core 0.0.0-stage → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # @xynolog/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![Tests](https://github.com/xynolog/sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/xynolog/sdk/actions/workflows/ci.yml?query=branch%3Amain+is%3Asuccess+job%3A%22Test+core%22)
4
+ [![codecov](https://codecov.io/gh/xynolog/sdk/graph/badge.svg?component=typescript-core)](https://app.codecov.io/gh/xynolog/sdk/components)
5
+ [![npm version](https://img.shields.io/npm/v/@xynolog/core.svg)](https://www.npmjs.com/package/@xynolog/core)
6
+ [![npm downloads](https://img.shields.io/npm/dm/@xynolog/core.svg)](https://www.npmjs.com/package/@xynolog/core)
7
+ [![License](https://img.shields.io/npm/l/@xynolog/core.svg)](https://github.com/xynolog/sdk/blob/main/LICENSE)
8
+
9
+ What every TypeScript package in Xynolog stands on: the protocol's types, generated from the [spec](https://github.com/xynolog/protocol/blob/main/specs/README.md), and the logic that has to be the same wherever it runs. That is ids, the event bus and its channels, the transport contract, annotations and how they are anchored, and identities.
10
+
11
+ ## Who uses it
12
+
13
+ Every other TypeScript package, the Browser, and the conformance and end-to-end suites. It depends on no other Xynolog package.
14
+
15
+ **Building an application?** Use [`@xynolog/sdk`](../sdk/README.md). It re-exports what an application needs from here, the id constructors and the error types among them, and an application rarely imports this package by name.
16
+
17
+ ## What is in it
18
+
19
+ | Area | What | Where |
20
+ |---|---|---|
21
+ | The protocol's types | `components`, `paths`, `operations`: every request, response and schema | `src/types.ts`, generated when the package is built and not committed |
22
+ | Ids | `ResourceId`, `AnnotationId`, `JobId`, `UserId`, each with a constructor that holds text to its rule and a guard that asks without throwing | [src/identifiers.ts](src/identifiers.ts), generated |
23
+ | The bus | `EventBus`, the `EventMap` of every channel and its payload, and `Bus`, the typed bus over a transport, whose `request` is a request and its reply | [src/event-bus.ts](src/event-bus.ts), [src/bus-protocol.ts](src/bus-protocol.ts), [src/bus.ts](src/bus.ts), [src/bus-request.ts](src/bus-request.ts) |
24
+ | The record's events | `PersistedEvent`, `StoredEvent`, and the list of every event type a knowledge base records | [src/persisted-events.ts](src/persisted-events.ts), [src/event-base.ts](src/event-base.ts) |
25
+ | The transport contract | `ITransport`, `IContentTransport`, `IGatewayOperations`: what a client needs of the wire | [src/transport.ts](src/transport.ts) |
26
+ | Annotations | Building one (`reconcile`, `annotationOfSpan`, `annotationOfResource`), and reading its target, its selectors and its links | [src/annotation-builders.ts](src/annotation-builders.ts), [src/web-annotation-utils.ts](src/web-annotation-utils.ts) |
27
+ | Anchoring | Finding an annotation again after its text changed, and the geometry of text on a PDF page (`locate`, `textUnder`) | [src/anchor-annotation.ts](src/anchor-annotation.ts), [src/pdf-anchoring.ts](src/pdf-anchoring.ts) |
28
+ | Identity | A knowledge base's own did and resource identifier (`kbDid`, `kbResource`). A principal's DID is the gateway's to mint and the record's to read | [src/did-utils.ts](src/did-utils.ts) |
29
+ | Media types | Which types a knowledge base admits, and what can be done with each | [src/media-types.ts](src/media-types.ts) |
30
+ | Shared rules | Error codes, timing, retry, the cache's refresh table, where jobs are kept and the API's limits, the same for every SDK | [src/error-codes.ts](src/error-codes.ts), [src/client-timing.ts](src/client-timing.ts), [src/cache-refresh.ts](src/cache-refresh.ts), [src/job-storage.ts](src/job-storage.ts), [src/protocol-limits.ts](src/protocol-limits.ts), generated; [src/retry.ts](src/retry.ts) |
31
+ | Languages | Every language an interface speaks, by code, with its native and English names | [src/locale-registry.ts](src/locale-registry.ts), generated; [src/locales.ts](src/locales.ts) |
32
+
33
+ The main import runs in a browser. What cannot is on a subpath:
34
+
35
+ | Import | |
36
+ |---|---|
37
+ | `@xynolog/core/openapi` | The spec's limits |
38
+ | `@xynolog/core/testing` | The test doubles every layer shares |
39
+ | `@xynolog/core/testing/axioms` | Property-based harnesses for state units and transports. They need `fast-check` |
40
+ | `@xynolog/core/testing/issuer` | An OIDC issuer in one process, for tests that verify tokens |
41
+
42
+ ## Example
43
+
44
+ ```typescript
45
+ import { resourceId, isResourceId, kbDid, kbResource } from '@xynolog/core';
46
+
47
+ // An id is made by its constructor, which throws for text its rule refuses.
48
+ const id = resourceId('5bcd259ab1464cf68a556bbad21f513f');
49
+
50
+ // A guard asks the same rule without throwing.
51
+ const typed = isResourceId('https://kb.example/resources/5bcd'); // false: a URI is not an id
52
+
53
+ // A knowledge base's did and the audience its tokens carry, from its committed domain.
54
+ const did = kbDid('xynoplex.github.io:xynoplex-caselaw-kb'); // 'did:web:xynoplex.github.io:xynoplex-caselaw-kb'
55
+ const audience = kbResource('xynoplex.github.io:xynoplex-caselaw-kb'); // 'https://xynoplex.github.io/xynoplex-caselaw-kb'
56
+ ```
57
+
58
+ ## What a change must keep
59
+
60
+ - **The spec is the source.** Each module that opens `GENERATED FILE`, `src/types.ts` among them, is generated from [`protocol/specs/src`](https://github.com/xynolog/protocol/tree/main/specs/src), and never edited. Those modules are committed, and `make generate` writes them. Change the spec, then run `make generate`. A type written by hand that restates a schema is a second copy that nothing keeps true: use the spec's type, under the spec's name.
61
+ - **The main import runs in a browser.** It uses no Node builtin. The test issuer is reachable only by its subpath, because of the weight `jose` would add to every bundle, and `npm run lint:core-subpaths` fails a re-export of it from the root.
62
+ - **It depends on no other Xynolog package.** Everything else depends on it.
63
+ - **An id is made only by its constructor or its guard.** One kind is never assignable to another.
64
+ - **Its tests read every package.** Three census tests here walk the source of all of `packages/`, `apps/` and `images/`, tests included, so a change somewhere else can fail this package's suite.
65
+
66
+ ## Documentation
67
+
68
+ - [API tour](docs/API.md): each area, with examples.
69
+ - [Utilities](docs/Utilities.md): the small helpers.
70
+ - [The spec](https://github.com/xynolog/protocol/blob/main/specs/README.md), which this package is generated from.
71
+
72
+ ## License
73
+
74
+ Apache-2.0
@@ -0,0 +1,259 @@
1
+ import { TRACE_FIELD, USER_FIELD, baseUrl, KeptForFirstReader, EventBus, REPLY_NAMES, isResourceScopedChannel, BusRequestError, relayFrames, asDeclared, RESOURCE_SCOPED_CHANNELS, BUS_OPERATIONS } from './chunk-VWT5CTL7.js';
2
+ import { BehaviorSubject } from 'rxjs';
3
+ import { map, filter } from 'rxjs/operators';
4
+
5
+ function refuseUnscriptedOperation(operation) {
6
+ throw new Error(
7
+ `No response scripted for bus operation "${operation}". Script one with transport.queueReply('${operation}', <response>) or pass a makeResponse that handles it.`
8
+ );
9
+ }
10
+ function isOperation(channel) {
11
+ return channel in BUS_OPERATIONS;
12
+ }
13
+ function retryKeyOf(channel, payload) {
14
+ const entries = Object.entries(payload).filter(([k]) => k !== TRACE_FIELD && k !== USER_FIELD).sort(([a], [b]) => a < b ? -1 : 1);
15
+ return `${channel} ${JSON.stringify(entries)}`;
16
+ }
17
+ var FaultyTransport = class {
18
+ baseUrl = baseUrl("faulty://simulator");
19
+ state$ = new BehaviorSubject("open");
20
+ failures = new KeptForFirstReader();
21
+ /**
22
+ * The failures `fail` reports. Of those reported before its first reader,
23
+ * the latest `ERRORS_KEPT_FOR_FIRST_READER_COUNT` are kept for it, in the
24
+ * order reported; what is still kept when the transport is disposed is
25
+ * dropped.
26
+ */
27
+ errors$ = this.failures.said$;
28
+ /** Every request-channel emit, in order — the L2 accounting surface. */
29
+ requestLog = [];
30
+ /** Every frame emitted, a request's echo and its reply included: what a reader is given is gated in `frames`. */
31
+ bus = new EventBus();
32
+ channels;
33
+ /** The resources whose scopes are held, each with how many hold it. */
34
+ scopeRefCounts = /* @__PURE__ */ new Map();
35
+ schedule;
36
+ makeResponse;
37
+ replyQueues = /* @__PURE__ */ new Map();
38
+ requestCount = 0;
39
+ timers = /* @__PURE__ */ new Set();
40
+ disposed = false;
41
+ constructor(cfg) {
42
+ this.channels = new Set(cfg.channels);
43
+ this.schedule = cfg.schedule ?? [];
44
+ this.makeResponse = cfg.makeResponse ?? refuseUnscriptedOperation;
45
+ }
46
+ /**
47
+ * Queue responses for `op`, consumed FIFO — one per request that reaches
48
+ * the simulated gateway — before falling back to `makeResponse`. The queue
49
+ * scripts the GATEWAY; the fault schedule scripts the WIRE. Consequences,
50
+ * deliberately: `duplicate-reply` replays one entry's body twice, and a
51
+ * `drop-reply` still consumes its entry (the gateway answered; the wire ate
52
+ * it) — so "first reply lost, the retry sees the NEXT page" is expressible.
53
+ * `reject-emit` consumes nothing: that request never reached the gateway.
54
+ *
55
+ * Each entry is a `response`. A reply that names what it answers for beside
56
+ * its response (`REPLY_NAMES`: the resource a context was gathered for, the
57
+ * reference a search was for) takes that from its request, as a gateway's
58
+ * does: a test queues the response alone.
59
+ */
60
+ queueReply(op, ...responses) {
61
+ const q = this.replyQueues.get(op) ?? [];
62
+ q.push(...responses);
63
+ this.replyQueues.set(op, q);
64
+ }
65
+ /**
66
+ * Report `error` on `errors$`, as a transport reports a request the
67
+ * gateway refused. A disposed transport reports nothing.
68
+ */
69
+ fail(error) {
70
+ this.failures.say(error);
71
+ }
72
+ // ── Bus primitives ──────────────────────────────────────────────────────
73
+ async emit(channel, payload, envelope) {
74
+ if (this.disposed) return void 0;
75
+ const name = channel;
76
+ if (!isOperation(name)) {
77
+ const target = envelope?.scope === void 0 ? this.bus : this.bus.scope(envelope.scope);
78
+ target.emit(channel, payload, { correlationId: envelope?.correlationId });
79
+ return 1;
80
+ }
81
+ const record = payload;
82
+ const action = this.schedule.length === 0 ? { kind: "deliver" } : this.schedule[this.requestCount % this.schedule.length];
83
+ this.requestCount += 1;
84
+ this.requestLog.push({
85
+ channel: name,
86
+ action,
87
+ correlationId: envelope?.correlationId,
88
+ retryKey: retryKeyOf(name, record),
89
+ // Copied at emit time, so a caller that mutates its own payload
90
+ // afterwards cannot rewrite the log; nested objects are shared.
91
+ payload: { ...record }
92
+ });
93
+ if (action.kind === "reject-emit") {
94
+ throw new Error(
95
+ `FaultyTransport: emit rejected by schedule (reject-emit) on ${name}`
96
+ );
97
+ }
98
+ this.bus.emit(channel, payload, envelope);
99
+ const queue = this.replyQueues.get(name);
100
+ const response = queue && queue.length > 0 ? queue.shift() : this.makeResponse(name, record);
101
+ const named = {};
102
+ for (const property of REPLY_NAMES[name]) {
103
+ if (record[property] === void 0) {
104
+ throw new Error(
105
+ `FaultyTransport: the reply to ${name} names "${property}", which this request does not state`
106
+ );
107
+ }
108
+ named[property] = record[property];
109
+ }
110
+ const reply = () => {
111
+ if (this.disposed) return;
112
+ const replyPayload = response === void 0 ? { ...named } : { ...named, response };
113
+ const resultChannel = BUS_OPERATIONS[name].result;
114
+ this.bus.emit(resultChannel, replyPayload, {
115
+ correlationId: envelope?.correlationId
116
+ });
117
+ };
118
+ switch (action.kind) {
119
+ case "deliver":
120
+ queueMicrotask(reply);
121
+ break;
122
+ case "duplicate-reply":
123
+ queueMicrotask(reply);
124
+ queueMicrotask(reply);
125
+ break;
126
+ case "delay": {
127
+ const t = setTimeout(() => {
128
+ this.timers.delete(t);
129
+ reply();
130
+ }, action.ms);
131
+ this.timers.add(t);
132
+ break;
133
+ }
134
+ }
135
+ return 1;
136
+ }
137
+ on(channel, handler) {
138
+ const sub = this.stream(channel).subscribe(handler);
139
+ return () => sub.unsubscribe();
140
+ }
141
+ stream(channel) {
142
+ return this.frames(channel).pipe(map((frame) => frame.payload));
143
+ }
144
+ /**
145
+ * The frames on the channel that a wire transport's stream would carry: one
146
+ * of no scope on a channel this transport was given, and one of a
147
+ * resource's scope on a resource-scoped channel while that scope is held.
148
+ * Every other frame is dropped. A stream carries every scope it holds on
149
+ * the one channel, so a reader of one resource's keeps that scope's
150
+ * (`Bus.frames(channel, resourceId)`).
151
+ *
152
+ * A resource-scoped channel is read with no scope held, as a wire
153
+ * transport reads it, and carries nothing until one is. Any other channel
154
+ * not given is refused at the call, as `bus.unsubscribed`: a frame on it
155
+ * could never arrive.
156
+ */
157
+ frames(channel) {
158
+ if (!this.channels.has(channel) && !isResourceScopedChannel(channel)) {
159
+ throw new BusRequestError(
160
+ `Transport is not subscribed to ${channel} \u2014 a frame on it can never arrive on this connection. Give the transport the channel.`,
161
+ "bus.unsubscribed",
162
+ { channel }
163
+ );
164
+ }
165
+ return this.bus.channelStream(channel).pipe(
166
+ filter(
167
+ (frame) => frame.scope === void 0 ? this.channels.has(channel) : isResourceScopedChannel(channel) && this.scopeRefCounts.has(frame.scope)
168
+ )
169
+ );
170
+ }
171
+ /**
172
+ * Whether the channels this transport was given name `channel`, as a wire
173
+ * transport answers for its stream's global set: a request whose replies
174
+ * they do not name fails at once, as `bus.unsubscribed`.
175
+ */
176
+ isSubscribed(channel) {
177
+ return this.channels.has(channel);
178
+ }
179
+ /**
180
+ * Hold `resourceId`'s scope until the returned release, as a wire
181
+ * transport holds it: each acquisition counts, distinct resources compose,
182
+ * the scope is let go at its last release, and a release is idempotent.
183
+ */
184
+ subscribeToResource(resourceId) {
185
+ this.scopeRefCounts.set(
186
+ resourceId,
187
+ (this.scopeRefCounts.get(resourceId) ?? 0) + 1
188
+ );
189
+ let released = false;
190
+ return () => {
191
+ if (released) return;
192
+ released = true;
193
+ const holds = this.scopeRefCounts.get(resourceId);
194
+ if (holds === void 0) return;
195
+ if (holds > 1) this.scopeRefCounts.set(resourceId, holds - 1);
196
+ else this.scopeRefCounts.delete(resourceId);
197
+ };
198
+ }
199
+ /**
200
+ * Correlated-reply tracking, exposed for assertions: `Bus.request` registers
201
+ * each cid here before its emit and releases on settle, so a test can pin
202
+ * the tracked set at any point of a request's lifecycle. This double never
203
+ * drops its stream, so it has nothing to replay, and tracking has no
204
+ * behavioral effect.
205
+ */
206
+ pendingReplies = /* @__PURE__ */ new Set();
207
+ trackReply(correlationId) {
208
+ this.pendingReplies.add(correlationId);
209
+ let released = false;
210
+ return () => {
211
+ if (released) return;
212
+ released = true;
213
+ this.pendingReplies.delete(correlationId);
214
+ };
215
+ }
216
+ /**
217
+ * Publish on `bus` what `frames` delivers on the channels this transport
218
+ * was given and on the resource-scoped ones, as a wire transport's bridge
219
+ * does: a resource's frame while its scope is held, with no scope, since
220
+ * the relay carries none.
221
+ */
222
+ bridgeInto(bus) {
223
+ relayFrames(
224
+ this,
225
+ {
226
+ // A payload that is not its channel's is published as its refusal, as a wire transport's bridge does.
227
+ emit: (channel, payload, envelope) => bus.emit(
228
+ channel,
229
+ asDeclared(channel, payload, envelope.correlationId),
230
+ envelope
231
+ )
232
+ },
233
+ [...this.channels, ...RESOURCE_SCOPED_CHANNELS],
234
+ // `EventBus.emit` is synchronous, so this never fires.
235
+ (channel, error) => {
236
+ throw new Error(
237
+ `FaultyTransport: the bridge of ${channel} failed`,
238
+ { cause: error }
239
+ );
240
+ }
241
+ );
242
+ }
243
+ // ── Lifecycle ───────────────────────────────────────────────────────────
244
+ dispose() {
245
+ if (this.disposed) return;
246
+ this.disposed = true;
247
+ this.scopeRefCounts.clear();
248
+ for (const t of this.timers) clearTimeout(t);
249
+ this.timers.clear();
250
+ this.state$.next("closed");
251
+ this.state$.complete();
252
+ this.failures.end();
253
+ this.bus.destroy();
254
+ }
255
+ };
256
+
257
+ export { FaultyTransport, refuseUnscriptedOperation, retryKeyOf };
258
+ //# sourceMappingURL=chunk-JVQYMUSA.js.map
259
+ //# sourceMappingURL=chunk-JVQYMUSA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/faulty-transport.ts"],"names":[],"mappings":";;;;AAmFO,SAAS,0BAA0B,SAAA,EAA0B;AAClE,EAAA,MAAM,IAAI,KAAA;AAAA,IACR,CAAA,wCAAA,EAA2C,SAAS,CAAA,yCAAA,EACT,SAAS,CAAA,sDAAA;AAAA,GAEtD;AACF;AAEA,SAAS,YAAY,OAAA,EAA6C;AAChE,EAAA,OAAO,OAAA,IAAW,cAAA;AACpB;AAKO,SAAS,UAAA,CACd,SACA,OAAA,EACQ;AACR,EAAA,MAAM,OAAA,GA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,OAAO,KAAA,EAAM;AAClB,IAAA,IAAA,CAAK,MAAA,CAAO,KAAK,QAAQ,CAAA;AACzB,IAAA,IAAA,CAAK,OAAO,QAAA,EAAS;AACrB,IAAA,IAAA,CAAK,SAAS,GAAA,EAAI;AAElB,IAAA,IAAA,CAAK,IAAI,OAAA,EAAQ;AAAA,EACnB;AACF","file":"chunk-JVQYMUSA.js","sourcesContent":["/**\n * FaultyTransport — a seeded, scriptable `ITransport` simulator for the\n * liveness axioms. fast-check draws a fault\n * schedule; the transport applies one `FaultAction` per request-channel emit\n * and synthesizes replies from the `BUS_OPERATIONS` registry, so real\n * compositions (`Bus.request`, SWR caches, live queries) run unmodified against\n * generated wire behavior no hand-written test names.\n *\n * Home is core (not sdk/test-utils) for the same reason as\n * `assertStateUnitAxioms`: it needs only core types, and every layer —\n * including `http-transport`, below sdk — can consume it via\n * `@xynolog/core/testing` without a dependency cycle.\n *\n * Deterministic-by-construction: no `Date.now`, no randomness of its own —\n * all variation comes in through the schedule (fast-check owns the seed).\n * Time is real `setTimeout` at millisecond scale; properties pass a small\n * explicit `timeoutMs` to `Bus.request`, so nothing waits 30 s.\n */\n\nimport { BehaviorSubject, type Observable } from 'rxjs';\nimport { filter, map } from 'rxjs/operators';\nimport type { XynologError } from './errors';\nimport { KeptForFirstReader } from './kept-for-first-reader';\nimport type { BaseUrl } from './branded-types';\nimport { baseUrl as makeBaseUrl } from './branded-types';\nimport type { ResourceId } from './identifiers';\nimport { TRACE_FIELD, USER_FIELD, type EventMap } from './bus-protocol';\nimport type { BusEnvelope, BusFrame } from './event-bus';\nimport type { ConnectionState, ITransport } from './transport';\nimport { EventBus } from './event-bus';\nimport {\n BUS_OPERATIONS,\n REPLY_NAMES,\n type BusOperationKey,\n} from './bus-operations';\nimport { asDeclared, type FrameRefusal } from './bus';\nimport { BusRequestError } from './bus-request';\nimport { RESOURCE_SCOPED_CHANNELS } from './bridged-channels';\nimport { isResourceScopedChannel } from './bridging';\nimport { relayFrames } from './relay-frames';\nimport type { FaultAction, RequestLogEntry } from './testing-kit';\n\nexport interface FaultyTransportConfig {\n /**\n * The global channels this transport is given, as a wire transport is\n * given its stream's: a frame of no scope reaches a reader only on one of\n * them, a request's echo and a reply included; it bridges them, beside the\n * resource-scoped channels, into a client's bus, answers `isSubscribed` for\n * them alone, and assumes none of its own. A full client's test gives it `BRIDGED_CHANNELS`; a worker's,\n * the reply channels it awaits and what its claims read\n * (`JOB_CLAIM_CHANNELS`).\n */\n channels: readonly (keyof EventMap)[];\n /**\n * The i-th request-channel emit applies `schedule[i % schedule.length]`.\n * Empty/omitted → every request delivers.\n */\n schedule?: readonly FaultAction[];\n /**\n * Synthesize the `response` value for a delivered reply. Return `undefined`\n * for a void ack (a reply that carries no `response`). Default:\n * `refuseUnscriptedOperation`, which throws naming the operation.\n */\n makeResponse?: (\n operation: BusOperationKey,\n payload: Record<string, unknown>,\n ) => unknown;\n}\n\n/**\n * The default `makeResponse`: refuse, rather than invent.\n *\n * A `() => ({})` default would answer every unscripted operation with a\n * SUCCESS whose every field is `undefined`. That is not a neutral default —\n * it is a fabricated reply, and it surfaces far from its cause (a caller doing\n * `result.engines.find(...)` reports `undefined is not a function`, naming\n * neither the operation nor the missing script). A shape-correct empty default\n * would be worse still: a hand-written mirror of a wire shape the spec owns,\n * carrying a fallback.\n *\n * So the default names the gap. A test that wants an answer scripts one via\n * `queueReply` or its own `makeResponse`.\n */\nexport function refuseUnscriptedOperation(operation: string): never {\n throw new Error(\n `No response scripted for bus operation \"${operation}\". ` +\n `Script one with transport.queueReply('${operation}', <response>) ` +\n `or pass a makeResponse that handles it.`,\n );\n}\n\nfunction isOperation(channel: string): channel is BusOperationKey {\n return channel in BUS_OPERATIONS;\n}\n\n/** Stable request identity: channel + sorted payload minus per-issue fields.\n * The correlation key is not among them — it rides the envelope, so the\n * payload is stable across retries of the same request. */\nexport function retryKeyOf(\n channel: string,\n payload: Record<string, unknown>,\n): string {\n const entries = Object.entries(payload)\n .filter(([k]) => k !== TRACE_FIELD && k !== USER_FIELD)\n .sort(([a], [b]) => (a < b ? -1 : 1));\n return `${channel} ${JSON.stringify(entries)}`;\n}\n\nexport class FaultyTransport implements ITransport {\n readonly baseUrl: BaseUrl = makeBaseUrl('faulty://simulator');\n readonly state$ = new BehaviorSubject<ConnectionState>('open');\n private readonly failures = new KeptForFirstReader<XynologError>();\n /**\n * The failures `fail` reports. Of those reported before its first reader,\n * the latest `ERRORS_KEPT_FOR_FIRST_READER_COUNT` are kept for it, in the\n * order reported; what is still kept when the transport is disposed is\n * dropped.\n */\n readonly errors$: Observable<XynologError> = this.failures.said$;\n\n /** Every request-channel emit, in order — the L2 accounting surface. */\n readonly requestLog: RequestLogEntry[] = [];\n\n /** Every frame emitted, a request's echo and its reply included: what a reader is given is gated in `frames`. */\n private readonly bus = new EventBus();\n private readonly channels: ReadonlySet<keyof EventMap>;\n /** The resources whose scopes are held, each with how many hold it. */\n private readonly scopeRefCounts = new Map<ResourceId, number>();\n private readonly schedule: readonly FaultAction[];\n private readonly makeResponse: (\n op: BusOperationKey,\n payload: Record<string, unknown>,\n ) => unknown;\n private readonly replyQueues = new Map<BusOperationKey, unknown[]>();\n private requestCount = 0;\n private readonly timers = new Set<ReturnType<typeof setTimeout>>();\n private disposed = false;\n\n constructor(cfg: FaultyTransportConfig) {\n this.channels = new Set(cfg.channels);\n this.schedule = cfg.schedule ?? [];\n this.makeResponse = cfg.makeResponse ?? refuseUnscriptedOperation;\n }\n\n /**\n * Queue responses for `op`, consumed FIFO — one per request that reaches\n * the simulated gateway — before falling back to `makeResponse`. The queue\n * scripts the GATEWAY; the fault schedule scripts the WIRE. Consequences,\n * deliberately: `duplicate-reply` replays one entry's body twice, and a\n * `drop-reply` still consumes its entry (the gateway answered; the wire ate\n * it) — so \"first reply lost, the retry sees the NEXT page\" is expressible.\n * `reject-emit` consumes nothing: that request never reached the gateway.\n *\n * Each entry is a `response`. A reply that names what it answers for beside\n * its response (`REPLY_NAMES`: the resource a context was gathered for, the\n * reference a search was for) takes that from its request, as a gateway's\n * does: a test queues the response alone.\n */\n queueReply(op: BusOperationKey, ...responses: unknown[]): void {\n const q = this.replyQueues.get(op) ?? [];\n q.push(...responses);\n this.replyQueues.set(op, q);\n }\n\n /**\n * Report `error` on `errors$`, as a transport reports a request the\n * gateway refused. A disposed transport reports nothing.\n */\n fail(error: XynologError): void {\n this.failures.say(error);\n }\n\n // ── Bus primitives ──────────────────────────────────────────────────────\n\n async emit<K extends keyof EventMap>(\n channel: K,\n payload: EventMap[K],\n envelope?: BusEnvelope,\n ): Promise<number | undefined> {\n // The double models exactly one connected participant, so a delivered\n // emit reports `1`; post-dispose it is inert and reports no count.\n if (this.disposed) return undefined;\n const name = channel as string;\n if (!isOperation(name)) {\n // Non-request channel: forward as-is (scoped or global).\n const target =\n envelope?.scope === undefined\n ? this.bus\n : this.bus.scope(envelope!.scope);\n // `scope` is not repeated — targeting the scoped bus IS how it is set.\n target.emit(channel, payload, { correlationId: envelope?.correlationId });\n return 1;\n }\n\n const record = payload as Record<string, unknown>;\n const action: FaultAction =\n this.schedule.length === 0\n ? { kind: 'deliver' }\n : this.schedule[this.requestCount % this.schedule.length]!;\n this.requestCount += 1;\n this.requestLog.push({\n channel: name,\n action,\n correlationId: envelope?.correlationId,\n retryKey: retryKeyOf(name, record),\n // Copied at emit time, so a caller that mutates its own payload\n // afterwards cannot rewrite the log; nested objects are shared.\n payload: { ...record },\n });\n\n if (action.kind === 'reject-emit') {\n // Models a /bus/emit 4xx: the request never reaches the bus.\n throw new Error(\n `FaultyTransport: emit rejected by schedule (reject-emit) on ${name}`,\n );\n }\n\n // The request itself is observable (handlers-eye view) to a reader of a\n // transport given its channel, then the simulator plays gateway:\n // synthesize the registry reply per the action. The envelope rides along:\n // a handler watching this double must read the same frame it would across\n // a broker.\n this.bus.emit(channel, payload, envelope);\n\n // The gateway's answer is computed ONCE per request that reaches it —\n // the reply QUEUE scripts the gateway, the fault schedule scripts the\n // wire. So `duplicate-reply` replays the same body twice, and a\n // `drop-reply` still consumes its queue entry: the gateway answered, the\n // wire ate it.\n const queue = this.replyQueues.get(name);\n const response =\n queue && queue.length > 0\n ? queue.shift()\n : this.makeResponse(name, record);\n\n // A reply that names what it answers for names what its request did, as a\n // gateway's does. Refused here, where it rejects the emit, rather than in\n // the reply's own microtask, where nobody is awaiting it.\n const named: Record<string, unknown> = {};\n for (const property of REPLY_NAMES[name]) {\n if (record[property] === undefined) {\n throw new Error(\n `FaultyTransport: the reply to ${name} names \"${property}\", which this request does not state`,\n );\n }\n named[property] = record[property];\n }\n\n const reply = (): void => {\n if (this.disposed) return;\n const replyPayload =\n response === undefined ? { ...named } : { ...named, response };\n const resultChannel = BUS_OPERATIONS[name].result as keyof EventMap;\n // The key rides back on the envelope, never inside the reply payload.\n this.bus.emit(resultChannel, replyPayload as EventMap[keyof EventMap], {\n correlationId: envelope?.correlationId,\n });\n };\n\n switch (action.kind) {\n case 'deliver':\n queueMicrotask(reply);\n break;\n case 'duplicate-reply':\n queueMicrotask(reply);\n queueMicrotask(reply);\n break;\n case 'delay': {\n const t = setTimeout(() => {\n this.timers.delete(t);\n reply();\n }, action.ms);\n this.timers.add(t);\n break;\n }\n case 'drop-reply':\n break;\n }\n return 1;\n }\n\n on<K extends keyof EventMap>(\n channel: K,\n handler: (payload: EventMap[K] | FrameRefusal) => void,\n ): () => void {\n const sub = this.stream(channel).subscribe(handler);\n return () => sub.unsubscribe();\n }\n\n stream<K extends keyof EventMap>(\n channel: K,\n ): Observable<EventMap[K] | FrameRefusal> {\n return this.frames(channel).pipe(map((frame) => frame.payload));\n }\n\n /**\n * The frames on the channel that a wire transport's stream would carry: one\n * of no scope on a channel this transport was given, and one of a\n * resource's scope on a resource-scoped channel while that scope is held.\n * Every other frame is dropped. A stream carries every scope it holds on\n * the one channel, so a reader of one resource's keeps that scope's\n * (`Bus.frames(channel, resourceId)`).\n *\n * A resource-scoped channel is read with no scope held, as a wire\n * transport reads it, and carries nothing until one is. Any other channel\n * not given is refused at the call, as `bus.unsubscribed`: a frame on it\n * could never arrive.\n */\n frames<K extends keyof EventMap>(\n channel: K,\n ): Observable<BusFrame<EventMap[K] | FrameRefusal>> {\n if (!this.channels.has(channel) && !isResourceScopedChannel(channel)) {\n throw new BusRequestError(\n `Transport is not subscribed to ${channel as string} — a frame on it can never arrive on this connection. Give the transport the channel.`,\n 'bus.unsubscribed',\n { channel },\n );\n }\n return this.bus\n .channelStream(channel)\n .pipe(\n filter((frame) =>\n frame.scope === undefined\n ? this.channels.has(channel)\n : isResourceScopedChannel(channel) &&\n this.scopeRefCounts.has(frame.scope),\n ),\n );\n }\n\n /**\n * Whether the channels this transport was given name `channel`, as a wire\n * transport answers for its stream's global set: a request whose replies\n * they do not name fails at once, as `bus.unsubscribed`.\n */\n isSubscribed(channel: keyof EventMap): boolean {\n return this.channels.has(channel);\n }\n\n /**\n * Hold `resourceId`'s scope until the returned release, as a wire\n * transport holds it: each acquisition counts, distinct resources compose,\n * the scope is let go at its last release, and a release is idempotent.\n */\n subscribeToResource(resourceId: ResourceId): () => void {\n this.scopeRefCounts.set(\n resourceId,\n (this.scopeRefCounts.get(resourceId) ?? 0) + 1,\n );\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const holds = this.scopeRefCounts.get(resourceId);\n // None once the transport is disposed, which let every scope go.\n if (holds === undefined) return;\n if (holds > 1) this.scopeRefCounts.set(resourceId, holds - 1);\n else this.scopeRefCounts.delete(resourceId);\n };\n }\n\n /**\n * Correlated-reply tracking, exposed for assertions: `Bus.request` registers\n * each cid here before its emit and releases on settle, so a test can pin\n * the tracked set at any point of a request's lifecycle. This double never\n * drops its stream, so it has nothing to replay, and tracking has no\n * behavioral effect.\n */\n readonly pendingReplies = new Set<string>();\n\n trackReply(correlationId: string): () => void {\n this.pendingReplies.add(correlationId);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n this.pendingReplies.delete(correlationId);\n };\n }\n\n /**\n * Publish on `bus` what `frames` delivers on the channels this transport\n * was given and on the resource-scoped ones, as a wire transport's bridge\n * does: a resource's frame while its scope is held, with no scope, since\n * the relay carries none.\n */\n bridgeInto(bus: EventBus): void {\n relayFrames(\n this,\n {\n // A payload that is not its channel's is published as its refusal, as a wire transport's bridge does.\n emit: (channel, payload, envelope) =>\n bus.emit(\n channel,\n asDeclared(channel, payload, envelope.correlationId),\n envelope,\n ),\n },\n [...this.channels, ...RESOURCE_SCOPED_CHANNELS],\n // `EventBus.emit` is synchronous, so this never fires.\n (channel, error) => {\n throw new Error(\n `FaultyTransport: the bridge of ${channel as string} failed`,\n { cause: error },\n );\n },\n );\n }\n\n // ── Lifecycle ───────────────────────────────────────────────────────────\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.scopeRefCounts.clear();\n for (const t of this.timers) clearTimeout(t);\n this.timers.clear();\n this.state$.next('closed');\n this.state$.complete();\n this.failures.end();\n // Completes every subject: in-flight busRequests resolve `bus.closed`.\n this.bus.destroy();\n }\n}\n"]}