@mdbase-dev/sdk 0.1.0-beta.186 → 0.1.0-beta.188

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/README.md +189 -925
  2. package/dist/app-grant/client.js +7 -3
  3. package/dist/app-grant/client.js.map +1 -1
  4. package/dist/app-grant/setup.js +2 -2
  5. package/dist/app-grant/setup.js.map +1 -1
  6. package/dist/app-host/cloud-copy-host.js +1 -1
  7. package/dist/app-host/cloud-copy-host.js.map +1 -1
  8. package/dist/app-host/collection-readiness.js +10 -12
  9. package/dist/app-host/collection-readiness.js.map +1 -1
  10. package/dist/app-host/handover.js +1 -1
  11. package/dist/app-host/handover.js.map +1 -1
  12. package/dist/app-host/initial-sync.js +4 -4
  13. package/dist/app-host/initial-sync.js.map +1 -1
  14. package/dist/app-host/installation-sign-in.d.ts +3 -0
  15. package/dist/app-host/installation-sign-in.js +11 -2
  16. package/dist/app-host/installation-sign-in.js.map +1 -1
  17. package/dist/app-host/web-sign-in-session.d.ts +2 -0
  18. package/dist/app-host/web-sign-in-session.js +25 -3
  19. package/dist/app-host/web-sign-in-session.js.map +1 -1
  20. package/dist/application/asset-pins.json +4 -4
  21. package/dist/application/browser-capabilities.d.ts +1 -1
  22. package/dist/application/browser-capabilities.js +3 -2
  23. package/dist/application/browser-capabilities.js.map +1 -1
  24. package/dist/application/configuration.js +12 -12
  25. package/dist/application/configuration.js.map +1 -1
  26. package/dist/application/entry.d.ts +69 -108
  27. package/dist/application/entry.js +164 -91
  28. package/dist/application/entry.js.map +1 -1
  29. package/dist/application/front-door.d.ts +30 -12
  30. package/dist/application/front-door.js +2 -89
  31. package/dist/application/front-door.js.map +1 -1
  32. package/dist/application/packaged-assets.d.ts +5 -2
  33. package/dist/application/packaged-assets.js +9 -6
  34. package/dist/application/packaged-assets.js.map +1 -1
  35. package/dist/application/phase.d.ts +4 -1
  36. package/dist/application/phase.js +5 -4
  37. package/dist/application/phase.js.map +1 -1
  38. package/dist/application/private-collections.js +2 -1
  39. package/dist/application/private-collections.js.map +1 -1
  40. package/dist/application/registration-refusal.d.ts +1 -1
  41. package/dist/application/registration-refusal.js +1 -3
  42. package/dist/application/registration-refusal.js.map +1 -1
  43. package/dist/application/registration.js +1 -4
  44. package/dist/application/registration.js.map +1 -1
  45. package/dist/application/setup.d.ts +6 -9
  46. package/dist/application/setup.js +16 -0
  47. package/dist/application/setup.js.map +1 -1
  48. package/dist/application/tabs.d.ts +15 -2
  49. package/dist/application/tabs.js +35 -13
  50. package/dist/application/tabs.js.map +1 -1
  51. package/dist/application/unsynced-transfer.d.ts +1 -1
  52. package/dist/application/unsynced-transfer.js +3 -3
  53. package/dist/application/unsynced-transfer.js.map +1 -1
  54. package/dist/application/worker.js +969 -465
  55. package/dist/application/worker.js.map +1 -1
  56. package/dist/browser/mdbase-sdk.js +21319 -20764
  57. package/dist/browser/mdbase-sdk.min.js +65 -65
  58. package/dist/browser.d.ts +1 -0
  59. package/dist/browser.js +1 -0
  60. package/dist/browser.js.map +1 -1
  61. package/dist/client.d.ts +169 -81
  62. package/dist/client.js +236 -178
  63. package/dist/client.js.map +1 -1
  64. package/dist/codec.d.ts +15 -0
  65. package/dist/codec.js +44 -2
  66. package/dist/codec.js.map +1 -1
  67. package/dist/collection-api.d.ts +44 -0
  68. package/dist/collection-api.js +24 -0
  69. package/dist/collection-api.js.map +1 -0
  70. package/dist/collection-availability.js +1 -1
  71. package/dist/collection-availability.js.map +1 -1
  72. package/dist/contract-query.d.ts +22 -3
  73. package/dist/contract-query.js.map +1 -1
  74. package/dist/contract-records.d.ts +2 -1
  75. package/dist/contract-records.js.map +1 -1
  76. package/dist/describe-error.d.ts +1 -1
  77. package/dist/describe-error.js +7 -6
  78. package/dist/describe-error.js.map +1 -1
  79. package/dist/errors.d.ts +3 -5
  80. package/dist/errors.js +3 -8
  81. package/dist/errors.js.map +1 -1
  82. package/dist/files.d.ts +7 -5
  83. package/dist/files.js +16 -17
  84. package/dist/files.js.map +1 -1
  85. package/dist/holds.d.ts +2 -1
  86. package/dist/holds.js.map +1 -1
  87. package/dist/index.d.ts +7 -11
  88. package/dist/index.js +5 -7
  89. package/dist/index.js.map +1 -1
  90. package/dist/live.d.ts +2 -1
  91. package/dist/live.js.map +1 -1
  92. package/dist/manifest.d.ts +1 -1
  93. package/dist/manifest.js +1 -1
  94. package/dist/native/provenance.json +5 -5
  95. package/dist/native/runtime.wasm +0 -0
  96. package/dist/people.js +3 -7
  97. package/dist/people.js.map +1 -1
  98. package/dist/plain.d.ts +102 -0
  99. package/dist/plain.js +62 -0
  100. package/dist/plain.js.map +1 -0
  101. package/dist/presence.d.ts +2 -1
  102. package/dist/presence.js +3 -3
  103. package/dist/presence.js.map +1 -1
  104. package/dist/read-helpers.d.ts +8 -6
  105. package/dist/read-helpers.js +20 -13
  106. package/dist/read-helpers.js.map +1 -1
  107. package/dist/record-set.d.ts +98 -0
  108. package/dist/record-set.js +347 -0
  109. package/dist/record-set.js.map +1 -0
  110. package/dist/records/session.d.ts +2 -1
  111. package/dist/records/session.js +22 -20
  112. package/dist/records/session.js.map +1 -1
  113. package/dist/records/types.d.ts +5 -3
  114. package/dist/records/witness.d.ts +7 -4
  115. package/dist/records/witness.js +13 -8
  116. package/dist/records/witness.js.map +1 -1
  117. package/dist/records.js +5 -2
  118. package/dist/records.js.map +1 -1
  119. package/dist/saved-views.d.ts +12 -4
  120. package/dist/saved-views.js +51 -43
  121. package/dist/saved-views.js.map +1 -1
  122. package/dist/settle.d.ts +62 -0
  123. package/dist/settle.js +119 -0
  124. package/dist/settle.js.map +1 -0
  125. package/dist/status.d.ts +84 -28
  126. package/dist/status.js +54 -48
  127. package/dist/status.js.map +1 -1
  128. package/dist/testing/application.d.ts +16 -9
  129. package/dist/testing/application.js +48 -45
  130. package/dist/testing/application.js.map +1 -1
  131. package/dist/testing/index.d.ts +2 -2
  132. package/dist/testing/memory-contracts.d.ts +5 -0
  133. package/dist/testing/memory-contracts.js.map +1 -1
  134. package/dist/testing/memory-replica.d.ts +58 -5
  135. package/dist/testing/memory-replica.js +126 -19
  136. package/dist/testing/memory-replica.js.map +1 -1
  137. package/dist/testing/test-app.d.ts +9 -10
  138. package/dist/testing/test-app.js +8 -17
  139. package/dist/testing/test-app.js.map +1 -1
  140. package/dist/thin-client.d.ts +15 -38
  141. package/dist/thin-client.js +11 -20
  142. package/dist/thin-client.js.map +1 -1
  143. package/dist/transport/control-route.js +1 -1
  144. package/dist/transport/control-route.js.map +1 -1
  145. package/dist/transport/relay-close.d.ts +0 -1
  146. package/dist/transport/relay-close.js +4 -2
  147. package/dist/transport/relay-close.js.map +1 -1
  148. package/dist/transport/relay-pipe.js +2 -2
  149. package/dist/transport/relay-pipe.js.map +1 -1
  150. package/dist/type-packs.js +4 -4
  151. package/dist/type-packs.js.map +1 -1
  152. package/dist/validation.d.ts +1 -1
  153. package/dist/validation.js +2 -2
  154. package/dist/validation.js.map +1 -1
  155. package/dist/values.d.ts +4 -20
  156. package/dist/values.js +3 -49
  157. package/dist/values.js.map +1 -1
  158. package/dist/view-sources.d.ts +2 -1
  159. package/dist/view-sources.js +1 -1
  160. package/dist/view-sources.js.map +1 -1
  161. package/dist/wire.d.ts +7 -3
  162. package/dist/wire.js +4 -4
  163. package/dist/wire.js.map +1 -1
  164. package/dist/write-ledger.d.ts +2 -1
  165. package/dist/write-ledger.js +3 -6
  166. package/dist/write-ledger.js.map +1 -1
  167. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- import type { CborValue } from "../cbor.js";
2
1
  import { list } from "../codec.js";
2
+ import { type ClientOptions, type MdbaseClient } from "../client.js";
3
3
  import { Connector } from "../transport/port.js";
4
4
  import { type PlainValue } from "../values.js";
5
5
  import * as w from "../wire.js";
@@ -42,11 +42,42 @@ export interface MemoryReplicaOptions {
42
42
  typing?: (types: string[], path: string) => w.TemporalHint;
43
43
  /** Serve contract-scoped records through these declared implementations (a
44
44
  * subset of Core's mapping; no schema validation). Absent: contract methods
45
- * are unknown, as on an older replica. */
45
+ * are unknown, as on an older replica. `describe` lists them, after what
46
+ * each type file says it implements. */
46
47
  contracts?: MemoryContract[];
47
48
  /** Further `hello` features to grant when asked (default: `presence` and `fence`). */
48
49
  features?: string[];
50
+ /** Read a document's frontmatter and body. Default: one `key: JSON` line per
51
+ * field, which is what `seedType` and the replica itself write. Pass the
52
+ * app's YAML parser when the app writes type files or `document`s. */
53
+ parse?: (document: string) => {
54
+ frontmatter: Record<string, PlainValue>;
55
+ body: string;
56
+ };
49
57
  }
58
+ /** A request `failNextRead` and `pauseReads` can target, by the client
59
+ * methods that send it. Writes have `failNextWrite`. */
60
+ export type MemoryReplicaRead =
61
+ /** `describe` */
62
+ "describe"
63
+ /** `get`, `find`, `readMany` */
64
+ | "get"
65
+ /** `query`, `pages`, and a record set's scan */
66
+ | "query"
67
+ /** `changes`, `watchChanges`, and a record set following changes */
68
+ | "changes"
69
+ /** `resources.get`, `resources.list` */
70
+ | "get_resource" | "list_resources"
71
+ /** `files.get`, `files.list` */
72
+ | "get_file" | "list_files"
73
+ /** `backlinks` */
74
+ | "backlinks"
75
+ /** `receipt`, `awaitReceipt` */
76
+ | "receipt" | "await"
77
+ /** `listHolds`, `listConflicts` */
78
+ | "list_holds" | "list_conflicts"
79
+ /** `getContract`, `queryContract` */
80
+ | "get_contract_v1" | "query_contract_v1";
50
81
  export declare class MemoryReplica {
51
82
  private opts;
52
83
  readonly collection: w.Uuid;
@@ -70,6 +101,8 @@ export declare class MemoryReplica {
70
101
  private stalled;
71
102
  private loseNext;
72
103
  private failWrite;
104
+ private failRead;
105
+ private paused;
73
106
  private holdList;
74
107
  private conflictList;
75
108
  private baseViews;
@@ -78,16 +111,20 @@ export declare class MemoryReplica {
78
111
  constructor(opts?: MemoryReplicaOptions);
79
112
  /** A connector for `MdbaseClient.connect`. Each `open` is a new session. */
80
113
  connector(): Connector;
114
+ /** A client connected to this replica. It does not reconnect by itself
115
+ * unless `reconnect` says so. */
116
+ client(o?: Partial<Omit<ClientOptions, "connector">>): Promise<MdbaseClient>;
81
117
  /** Drop every session (simulates a broken link; clients reconnect). */
82
118
  dropConnections(): void;
83
119
  /** Simulate the log service being unreachable: submits stay pending. */
84
120
  setOnline(online: boolean): void;
85
- /** Seed a confirmed record directly. */
121
+ /** Seed a confirmed record directly. Frontmatter is plain data, or the
122
+ * exact forms where a test wants them (`Float64`, `bigint`, a `Map`). */
86
123
  seed(r: {
87
124
  id?: w.Uuid;
88
125
  path: string;
89
126
  types?: string[];
90
- frontmatter?: Record<string, CborValue>;
127
+ frontmatter?: Record<string, PlainValue>;
91
128
  body?: string;
92
129
  }): MemoryRecord;
93
130
  /** Confirm every pending mutation now. */
@@ -96,7 +133,7 @@ export declare class MemoryReplica {
96
133
  * frontmatter value removes the field. */
97
134
  editElsewhere(ref: string, change: {
98
135
  body?: string;
99
- frontmatter?: Record<string, CborValue | null>;
136
+ frontmatter?: Record<string, PlainValue>;
100
137
  }): void;
101
138
  /** Another device renames (moves) a record. */
102
139
  renameElsewhere(ref: string, to: string): void;
@@ -108,6 +145,11 @@ export declare class MemoryReplica {
108
145
  loseNextResponse(): void;
109
146
  /** The next submit fails with `p` and captures nothing. */
110
147
  failNextWrite(p?: w.Problem): void;
148
+ /** The next `method` request fails with `p` and the one after it is answered. */
149
+ failNextRead(method: MemoryReplicaRead, p?: w.Problem): void;
150
+ /** Hold every `method` request until the returned function is called, as a
151
+ * slow replica would. Requests already answered are not affected. */
152
+ pauseReads(method: MemoryReplicaRead): () => void;
111
153
  /** Stuck pending: while stalled, writes are not confirmed on their own even
112
154
  * though the replica is online (`confirmAll` still confirms). */
113
155
  stallConfirmations(stalled?: boolean): void;
@@ -158,6 +200,10 @@ export declare class MemoryReplica {
158
200
  private view;
159
201
  private evalQuery;
160
202
  private page;
203
+ /** A paging cursor belongs to the view it was issued at (§4): any change in
204
+ * between refuses the next page, and the caller starts again. */
205
+ private pageCursor;
206
+ private pageStart;
161
207
  private dispatch;
162
208
  private pumpStream;
163
209
  private findFile;
@@ -168,6 +214,13 @@ export declare class MemoryReplica {
168
214
  private pendingOps;
169
215
  /** Seed a resource (a type file, mdbase.yaml). */
170
216
  seedResource(path: string, text: string): void;
217
+ /** Frontmatter and body of a document, through `opts.parse` when given. */
218
+ private parse;
219
+ /** What a type implements: the `implements` list of its type file, then the
220
+ * declared contracts the file does not list. */
221
+ private implementations;
222
+ /** One summary per contract version the types implement. */
223
+ private contractSummaries;
171
224
  /** Synthetic type summary: the parsed subset of the type file, never Core's catalog. */
172
225
  private typeSummary;
173
226
  private resourceView;
@@ -15,6 +15,7 @@ import { sha256 } from "@noble/hashes/sha2.js";
15
15
  import { decode, encode, Float64 } from "../cbor.js";
16
16
  import { hash as hashCodec, hashFromBytes, list, uuid as uuidCodec } from "../codec.js";
17
17
  import { ERROR_CODES, isMdbaseError, mdbaseError, MdbaseError } from "../errors.js";
18
+ import { connect } from "../client.js";
18
19
  import { portPair } from "../transport/port.js";
19
20
  import { revisionOf, toPlain, toValue, uuidv7 } from "../values.js";
20
21
  import * as w from "../wire.js";
@@ -106,6 +107,8 @@ export class MemoryReplica {
106
107
  stalled = false;
107
108
  loseNext = false;
108
109
  failWrite = null;
110
+ failRead = new Map();
111
+ paused = new Map();
109
112
  holdList = new Map();
110
113
  conflictList = [];
111
114
  baseViews = new Map();
@@ -151,6 +154,11 @@ export class MemoryReplica {
151
154
  },
152
155
  };
153
156
  }
157
+ /** A client connected to this replica. It does not reconnect by itself
158
+ * unless `reconnect` says so. */
159
+ client(o = {}) {
160
+ return connect({ app: { name: "test", version: "test" }, reconnect: false, ...o, connector: this.connector() });
161
+ }
154
162
  /** Drop every session (simulates a broken link; clients reconnect). */
155
163
  dropConnections() {
156
164
  for (const c of [...this.conns])
@@ -163,13 +171,14 @@ export class MemoryReplica {
163
171
  if (online && this.opts.confirmDelayMs !== null)
164
172
  this.scheduleConfirm();
165
173
  }
166
- /** Seed a confirmed record directly. */
174
+ /** Seed a confirmed record directly. Frontmatter is plain data, or the
175
+ * exact forms where a test wants them (`Float64`, `bigint`, a `Map`). */
167
176
  seed(r) {
168
177
  const rec = {
169
178
  id: r.id ?? uuidv7(),
170
179
  path: r.path,
171
180
  types: r.types ?? [],
172
- frontmatter: new Map(Object.entries(r.frontmatter ?? {})),
181
+ frontmatter: new Map(Object.entries(r.frontmatter ?? {}).map(([k, v]) => [k, toValue(v)])),
173
182
  body: r.body ?? "",
174
183
  confirmedSeq: ++this.seq,
175
184
  pending: false,
@@ -194,7 +203,7 @@ export class MemoryReplica {
194
203
  if (v === null)
195
204
  r.frontmatter.delete(k);
196
205
  else
197
- r.frontmatter.set(k, v);
206
+ r.frontmatter.set(k, toValue(v));
198
207
  }
199
208
  r.confirmedSeq = ++this.seq;
200
209
  this.touch(r.id, r.path, "put");
@@ -227,6 +236,26 @@ export class MemoryReplica {
227
236
  failNextWrite(p = problem("unavailable", "the replica could not take the write", "storage_busy")) {
228
237
  this.failWrite = p;
229
238
  }
239
+ /** The next `method` request fails with `p` and the one after it is answered. */
240
+ failNextRead(method, p = problem("unavailable", "the replica could not answer", "storage_busy")) {
241
+ this.failRead.set(method, p);
242
+ }
243
+ /** Hold every `method` request until the returned function is called, as a
244
+ * slow replica would. Requests already answered are not affected. */
245
+ pauseReads(method) {
246
+ const held = this.paused.get(method);
247
+ if (held)
248
+ return held.release;
249
+ let open;
250
+ const gate = new Promise((resolve) => { open = resolve; });
251
+ const release = () => {
252
+ if (this.paused.get(method)?.release === release)
253
+ this.paused.delete(method);
254
+ open();
255
+ };
256
+ this.paused.set(method, { gate, release });
257
+ return release;
258
+ }
230
259
  /** Stuck pending: while stalled, writes are not confirmed on their own even
231
260
  * though the replica is online (`confirmAll` still confirms). */
232
261
  stallConfirmations(stalled = true) {
@@ -483,6 +512,13 @@ export class MemoryReplica {
483
512
  c.port.close();
484
513
  return;
485
514
  }
515
+ await this.paused.get(f.method)?.gate;
516
+ const failure = this.failRead.get(f.method);
517
+ if (failure) {
518
+ this.failRead.delete(f.method);
519
+ this.send(c, { kind: "response", id: f.id, problem: failure });
520
+ return;
521
+ }
486
522
  try {
487
523
  const result = await this.dispatch(c, f.method, f.params);
488
524
  this.send(c, { kind: "response", id: f.id, result: result ?? null });
@@ -513,12 +549,12 @@ export class MemoryReplica {
513
549
  .filter((x) => !where || this.opts.where(where, { ...r, frontmatter: x.fields })),
514
550
  }))
515
551
  .filter((x) => x.implementations.length);
516
- const start = Number(m.get(4) ?? 0);
552
+ const start = this.pageStart(m.get(4));
517
553
  const limit = m.get(3) ?? 128;
518
554
  const slice = rows.slice(start, start + limit);
519
555
  const page = { records: slice.map((x) => this.view(x.r)), complete: true, asOf: this.viewVersion };
520
556
  if (start + limit < rows.length)
521
- page.cursor = String(start + limit);
557
+ page.cursor = this.pageCursor(start + limit);
522
558
  return contractQueryResult.enc({
523
559
  version: 1, page, contractDigest: contractDigest(impls[0]),
524
560
  records: slice.map((x) => ({ id: x.r.id, implementations: x.implementations })),
@@ -584,7 +620,10 @@ export class MemoryReplica {
584
620
  evalQuery(q) {
585
621
  const types = q.get("types");
586
622
  const where = q.get("where");
587
- let rows = [...this.records.values()].filter((r) => !types?.length || types.some((t) => r.types.includes(t)));
623
+ // Core compares type names without ASCII case.
624
+ const fold = (t) => t.replace(/[A-Z]/g, (c) => c.toLowerCase());
625
+ const wanted = types?.map(fold);
626
+ let rows = [...this.records.values()].filter((r) => !wanted?.length || r.types.some((t) => wanted.includes(fold(t))));
588
627
  if (where) {
589
628
  if (!this.opts.where)
590
629
  throw mdbaseError("invalid_request", "MemoryReplica: pass a `where` evaluator to use where");
@@ -616,11 +655,24 @@ export class MemoryReplica {
616
655
  }
617
656
  page(q) {
618
657
  const all = this.evalQuery(q);
619
- const start = Number(q.get("cursor") ?? 0);
658
+ const start = this.pageStart(q.get("cursor"));
620
659
  const limit = q.get("limit");
621
660
  const rows = limit === undefined ? all.slice(start) : all.slice(start, start + limit);
622
661
  const next = start + rows.length;
623
- return next < all.length && limit !== undefined ? { rows, cursor: String(next) } : { rows };
662
+ return next < all.length && limit !== undefined ? { rows, cursor: this.pageCursor(next) } : { rows };
663
+ }
664
+ /** A paging cursor belongs to the view it was issued at (§4): any change in
665
+ * between refuses the next page, and the caller starts again. */
666
+ pageCursor(next) {
667
+ return `${this.viewVersion}:${next}`;
668
+ }
669
+ pageStart(cursor) {
670
+ if (cursor === undefined || cursor === null)
671
+ return 0;
672
+ const [version, start] = String(cursor).split(":").map(Number);
673
+ if (version !== this.viewVersion)
674
+ throw mdbaseError("invalid_request", "restart from the first query page", "cursor_stale");
675
+ return start;
624
676
  }
625
677
  async dispatch(c, method, p) {
626
678
  const m = (p ?? new Map());
@@ -628,7 +680,7 @@ export class MemoryReplica {
628
680
  case "cancel":
629
681
  return null;
630
682
  case "describe": {
631
- const types = new Set();
683
+ const types = new Set((this.opts.contracts ?? []).map((c) => c.type));
632
684
  for (const r of this.records.values())
633
685
  r.types.forEach((t) => types.add(t));
634
686
  for (const p of this.resources.keys()) {
@@ -636,18 +688,19 @@ export class MemoryReplica {
636
688
  if (m)
637
689
  types.add(m[1]);
638
690
  }
691
+ const summaries = [...types].sort().map((name) => this.typeSummary(name, m.get(0) === true));
639
692
  return w.describeResult.enc({
640
693
  specVersion: "0.3.0-rc.5",
641
- types: [...types].sort().map((name) => this.typeSummary(name, m.get(0) === true)),
694
+ types: summaries,
642
695
  settings: new Map(),
643
696
  inclusion: { include: ["image", "audio", "video", "pdf", "other"] },
644
697
  issues: [],
645
- contracts: [],
698
+ contracts: this.contractSummaries(summaries),
646
699
  });
647
700
  }
648
701
  case "new_type_file": {
649
702
  // Synthetic subset of Core's derivation: frontmatter name, default folder.
650
- const { frontmatter } = parseDocument(m.get(0));
703
+ const { frontmatter } = this.parse(m.get(0));
651
704
  const name = frontmatter.get("name");
652
705
  if (frontmatter.get("kind") !== "mdbase.type" || typeof name !== "string" || name === "" || name.includes("/")) {
653
706
  throw mdbaseError("invalid_record", "the type needs a usable name", "invalid_type_definition");
@@ -801,7 +854,7 @@ export class MemoryReplica {
801
854
  throw mdbaseError("invalid_request", "the account secret is 32 bytes");
802
855
  const refused = (reason) => ({
803
856
  state: "refused",
804
- problem: { code: "forbidden", recovery: "reauthorize", message: `account key refused: ${reason}`, details: new Map([["reason", reason]]) },
857
+ problem: { code: "forbidden", recovery: "reauthorize", message: `account key refused: ${reason}`, details: { reason } },
805
858
  });
806
859
  const enrolled = this.accountKeySecret;
807
860
  this.accountKey = !enrolled ? refused("device_missing")
@@ -1012,14 +1065,68 @@ export class MemoryReplica {
1012
1065
  seedResource(path, text) {
1013
1066
  this.resources.set(path, { text, pending: false });
1014
1067
  }
1068
+ /** Frontmatter and body of a document, through `opts.parse` when given. */
1069
+ parse(doc) {
1070
+ if (!this.opts.parse)
1071
+ return parseDocument(doc);
1072
+ const { frontmatter, body } = this.opts.parse(doc);
1073
+ return { frontmatter: new Map(Object.entries(frontmatter).map(([k, v]) => [k, toValue(v)])), body };
1074
+ }
1075
+ /** What a type implements: the `implements` list of its type file, then the
1076
+ * declared contracts the file does not list. */
1077
+ implementations(name, frontmatter) {
1078
+ const declared = (this.opts.contracts ?? []).filter((c) => c.type === name);
1079
+ const digest = (contract, version) => {
1080
+ const c = declared.find((x) => x.id === contract && x.version === version);
1081
+ return implementationDigest(c ?? { id: contract, version, type: name, fields: {} });
1082
+ };
1083
+ const listed = toPlain(toValue((frontmatter?.get("implements") ?? [])));
1084
+ if (!Array.isArray(listed))
1085
+ throw new Error(`MemoryReplica: _types/${name}.md: implements must be a list`);
1086
+ const out = listed.map((entry) => {
1087
+ const e = entry;
1088
+ if (typeof e.contract !== "string" || typeof e.version !== "string") {
1089
+ throw new Error(`MemoryReplica: _types/${name}.md: an implements entry needs a contract and a version`);
1090
+ }
1091
+ return {
1092
+ contract: e.contract, version: e.version, fields: new Map(Object.entries(e.fields ?? {})),
1093
+ ...(e.binding === undefined ? {} : { binding: toValue(e.binding) }), digest: digest(e.contract, e.version),
1094
+ };
1095
+ });
1096
+ for (const c of declared) {
1097
+ if (out.some((i) => i.contract === c.id && i.version === c.version))
1098
+ continue;
1099
+ out.push({
1100
+ contract: c.id, version: c.version, fields: new Map(Object.entries(c.fields)),
1101
+ ...(c.binding === undefined ? {} : { binding: toValue(c.binding) }), digest: implementationDigest(c),
1102
+ });
1103
+ }
1104
+ return out;
1105
+ }
1106
+ /** One summary per contract version the types implement. */
1107
+ contractSummaries(types) {
1108
+ const out = new Map();
1109
+ for (const type of types)
1110
+ for (const i of type.implements) {
1111
+ const key = `${i.contract}@${i.version}`;
1112
+ const declared = (this.opts.contracts ?? []).find((c) => c.id === i.contract && c.version === i.version);
1113
+ const summary = out.get(key) ?? {
1114
+ id: i.contract, version: i.version, path: declared?.path ?? `_contracts/${i.contract}.md`,
1115
+ digest: contractDigest(declared ?? { id: i.contract, version: i.version }), contractType: "record", implementedBy: [],
1116
+ };
1117
+ summary.implementedBy.push(type.name);
1118
+ out.set(key, summary);
1119
+ }
1120
+ return [...out.values()].sort((a, b) => (`${a.id}@${a.version}` < `${b.id}@${b.version}` ? -1 : 1));
1121
+ }
1015
1122
  /** Synthetic type summary: the parsed subset of the type file, never Core's catalog. */
1016
1123
  typeSummary(name, definitions) {
1017
1124
  const path = `_types/${name}.md`;
1018
- const summary = { name, path, implements: [] };
1019
1125
  const source = this.resources.get(path);
1020
- if (source === undefined)
1126
+ const frontmatter = source === undefined ? undefined : this.parse(source.text).frontmatter;
1127
+ const summary = { name, path, implements: this.implementations(name, frontmatter) };
1128
+ if (source === undefined || frontmatter === undefined)
1021
1129
  return definitions ? { ...summary, definition: new Map(), schema: null } : summary;
1022
- const { frontmatter } = parseDocument(source.text);
1023
1130
  const version = frontmatter.get("version");
1024
1131
  if (typeof version === "number" && Number.isInteger(version))
1025
1132
  summary.version = version;
@@ -1229,7 +1336,7 @@ export class MemoryReplica {
1229
1336
  types: op.type ? [op.type] : [],
1230
1337
  ...(op.document === undefined
1231
1338
  ? { frontmatter: new Map(op.frontmatter ?? []), body: op.body ?? "" }
1232
- : parseDocument(op.document)),
1339
+ : this.parse(op.document)),
1233
1340
  confirmedSeq: 0,
1234
1341
  pending: true,
1235
1342
  });
@@ -1243,7 +1350,7 @@ export class MemoryReplica {
1243
1350
  if (op.ifRevision && op.ifRevision !== revision(r0)) {
1244
1351
  throw new MdbaseError({
1245
1352
  ...problem("conflict", "the record changed since if_revision", "revision"),
1246
- details: new Map([["current", revision(r0)]]),
1353
+ details: { current: revision(r0) },
1247
1354
  });
1248
1355
  }
1249
1356
  const r = { ...r0, frontmatter: new Map(r0.frontmatter), pending: true };
@@ -1292,7 +1399,7 @@ export class MemoryReplica {
1292
1399
  id: op.id,
1293
1400
  path: op.new.path || r0?.path || `${op.id}.md`,
1294
1401
  types: r0?.types ?? [],
1295
- ...parseDocument(op.new.doc),
1402
+ ...this.parse(op.new.doc),
1296
1403
  confirmedSeq: r0?.confirmedSeq ?? 0,
1297
1404
  pending: true,
1298
1405
  });