@peers-app/peers-sdk 0.27.2 → 0.27.4

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 (260) hide show
  1. package/dist/contracts/contract-proxy.d.ts +7 -0
  2. package/dist/contracts/contract-proxy.js +19 -2
  3. package/dist/contracts/create-local-consumer.js +16 -1
  4. package/dist/contracts/index.d.ts +2 -0
  5. package/dist/contracts/index.js +2 -0
  6. package/dist/contracts/system/index.d.ts +2 -0
  7. package/dist/contracts/system/index.js +2 -0
  8. package/dist/contracts/system/invites-contract.js +2 -1
  9. package/dist/contracts/system/sync-check-contract.d.ts +97 -0
  10. package/dist/contracts/system/sync-check-contract.js +115 -0
  11. package/dist/contracts/tool-arguments.d.ts +15 -0
  12. package/dist/contracts/tool-arguments.js +41 -0
  13. package/dist/contracts/tool-catalog-service.js +2 -12
  14. package/dist/data/change-tracking.d.ts +40 -0
  15. package/dist/data/change-tracking.js +89 -0
  16. package/dist/data/orm/types.d.ts +24 -7
  17. package/dist/data/orm/types.js +97 -24
  18. package/dist/data/persistent-vars.d.ts +5 -0
  19. package/dist/data/persistent-vars.js +24 -6
  20. package/dist/define/manifest.js +6 -34
  21. package/dist/package-loader/package-loader.js +27 -22
  22. package/dist/system-ids.d.ts +5 -0
  23. package/dist/system-ids.js +6 -1
  24. package/package.json +4 -2
  25. package/dist/context/user-context-identity.test.d.ts +0 -1
  26. package/dist/context/user-context-identity.test.js +0 -220
  27. package/dist/contracts/__tests__/action-dispatch.test.d.ts +0 -1
  28. package/dist/contracts/__tests__/action-dispatch.test.js +0 -319
  29. package/dist/contracts/__tests__/also-implements.test.d.ts +0 -1
  30. package/dist/contracts/__tests__/also-implements.test.js +0 -110
  31. package/dist/contracts/__tests__/builder.test.d.ts +0 -1
  32. package/dist/contracts/__tests__/builder.test.js +0 -669
  33. package/dist/contracts/__tests__/contract-events.test.d.ts +0 -1
  34. package/dist/contracts/__tests__/contract-events.test.js +0 -199
  35. package/dist/contracts/__tests__/contract-observables.test.d.ts +0 -1
  36. package/dist/contracts/__tests__/contract-observables.test.js +0 -290
  37. package/dist/contracts/__tests__/contract-provider-router.test.d.ts +0 -1
  38. package/dist/contracts/__tests__/contract-provider-router.test.js +0 -315
  39. package/dist/contracts/__tests__/contract-proxy.test.d.ts +0 -1
  40. package/dist/contracts/__tests__/contract-proxy.test.js +0 -657
  41. package/dist/contracts/__tests__/contract-resolvers.test.d.ts +0 -1
  42. package/dist/contracts/__tests__/contract-resolvers.test.js +0 -758
  43. package/dist/contracts/__tests__/contract-subscription-lifecycle.test.d.ts +0 -1
  44. package/dist/contracts/__tests__/contract-subscription-lifecycle.test.js +0 -353
  45. package/dist/contracts/__tests__/contract-table-events.test.d.ts +0 -1
  46. package/dist/contracts/__tests__/contract-table-events.test.js +0 -209
  47. package/dist/contracts/__tests__/contract-transport.test.d.ts +0 -1
  48. package/dist/contracts/__tests__/contract-transport.test.js +0 -163
  49. package/dist/contracts/__tests__/extract.test.d.ts +0 -1
  50. package/dist/contracts/__tests__/extract.test.js +0 -145
  51. package/dist/contracts/__tests__/frozen-contracts.test.d.ts +0 -1
  52. package/dist/contracts/__tests__/frozen-contracts.test.js +0 -191
  53. package/dist/contracts/__tests__/generic-tool-dispatch.test.d.ts +0 -1
  54. package/dist/contracts/__tests__/generic-tool-dispatch.test.js +0 -130
  55. package/dist/contracts/__tests__/host-contract-client.test.d.ts +0 -1
  56. package/dist/contracts/__tests__/host-contract-client.test.js +0 -793
  57. package/dist/contracts/__tests__/host-contract-consumer.test.d.ts +0 -1
  58. package/dist/contracts/__tests__/host-contract-consumer.test.js +0 -163
  59. package/dist/contracts/__tests__/host-contract-transport.test.d.ts +0 -1
  60. package/dist/contracts/__tests__/host-contract-transport.test.js +0 -66
  61. package/dist/contracts/__tests__/integration.test.d.ts +0 -1
  62. package/dist/contracts/__tests__/integration.test.js +0 -348
  63. package/dist/contracts/__tests__/legacy-removal.test.d.ts +0 -1
  64. package/dist/contracts/__tests__/legacy-removal.test.js +0 -128
  65. package/dist/contracts/__tests__/persistent-registry.test.d.ts +0 -1
  66. package/dist/contracts/__tests__/persistent-registry.test.js +0 -109
  67. package/dist/contracts/__tests__/playground.test.d.ts +0 -1
  68. package/dist/contracts/__tests__/playground.test.js +0 -216
  69. package/dist/contracts/__tests__/registry.test.d.ts +0 -1
  70. package/dist/contracts/__tests__/registry.test.js +0 -238
  71. package/dist/contracts/__tests__/remote-contract-transport.test.d.ts +0 -1
  72. package/dist/contracts/__tests__/remote-contract-transport.test.js +0 -119
  73. package/dist/contracts/__tests__/system-contracts.test.d.ts +0 -1
  74. package/dist/contracts/__tests__/system-contracts.test.js +0 -247
  75. package/dist/contracts/__tests__/target-dispatch.d.ts +0 -11
  76. package/dist/contracts/__tests__/target-dispatch.js +0 -24
  77. package/dist/contracts/__tests__/tool-catalog-inventory.test.d.ts +0 -1
  78. package/dist/contracts/__tests__/tool-catalog-inventory.test.js +0 -44
  79. package/dist/contracts/__tests__/tool-catalog-service.test.d.ts +0 -1
  80. package/dist/contracts/__tests__/tool-catalog-service.test.js +0 -482
  81. package/dist/contracts/__tests__/tool-catalog.test.d.ts +0 -1
  82. package/dist/contracts/__tests__/tool-catalog.test.js +0 -1199
  83. package/dist/contracts/__tests__/validate.test.d.ts +0 -1
  84. package/dist/contracts/__tests__/validate.test.js +0 -991
  85. package/dist/contracts/__tests__/workflow-context.test.d.ts +0 -1
  86. package/dist/contracts/__tests__/workflow-context.test.js +0 -50
  87. package/dist/data/access-level.test.d.ts +0 -1
  88. package/dist/data/access-level.test.js +0 -53
  89. package/dist/data/change-tracking.test.d.ts +0 -1
  90. package/dist/data/change-tracking.test.js +0 -62
  91. package/dist/data/files/files.test.d.ts +0 -1
  92. package/dist/data/files/files.test.js +0 -770
  93. package/dist/data/group-members.test.d.ts +0 -1
  94. package/dist/data/group-members.test.js +0 -336
  95. package/dist/data/group-share.test.d.ts +0 -1
  96. package/dist/data/group-share.test.js +0 -110
  97. package/dist/data/groups.test.d.ts +0 -1
  98. package/dist/data/groups.test.js +0 -153
  99. package/dist/data/orm/cursor.test.d.ts +0 -1
  100. package/dist/data/orm/cursor.test.js +0 -314
  101. package/dist/data/orm/data-query.mongo.test.d.ts +0 -1
  102. package/dist/data/orm/data-query.mongo.test.js +0 -367
  103. package/dist/data/orm/data-query.sqlite.test.d.ts +0 -1
  104. package/dist/data/orm/data-query.sqlite.test.js +0 -365
  105. package/dist/data/orm/data-query.test.d.ts +0 -1
  106. package/dist/data/orm/data-query.test.js +0 -545
  107. package/dist/data/orm/dependency-injection.test.d.ts +0 -1
  108. package/dist/data/orm/dependency-injection.test.js +0 -171
  109. package/dist/data/orm/event-registry.test.d.ts +0 -1
  110. package/dist/data/orm/event-registry.test.js +0 -44
  111. package/dist/data/orm/multi-cursors.test.d.ts +0 -1
  112. package/dist/data/orm/multi-cursors.test.js +0 -463
  113. package/dist/data/orm/sql.data-source.test.d.ts +0 -1
  114. package/dist/data/orm/sql.data-source.test.js +0 -731
  115. package/dist/data/orm/table-container-events.test.d.ts +0 -1
  116. package/dist/data/orm/table-container-events.test.js +0 -101
  117. package/dist/data/orm/table-container.test.d.ts +0 -1
  118. package/dist/data/orm/table-container.test.js +0 -273
  119. package/dist/data/orm/table.event-source.test.d.ts +0 -1
  120. package/dist/data/orm/table.event-source.test.js +0 -331
  121. package/dist/data/orm/types.test.d.ts +0 -1
  122. package/dist/data/orm/types.test.js +0 -409
  123. package/dist/data/package-table-identity.test.d.ts +0 -1
  124. package/dist/data/package-table-identity.test.js +0 -46
  125. package/dist/data/package-version-permissions.test.d.ts +0 -1
  126. package/dist/data/package-version-permissions.test.js +0 -107
  127. package/dist/data/package-version-resolver.test.d.ts +0 -4
  128. package/dist/data/package-version-resolver.test.js +0 -543
  129. package/dist/data/package-versions.test.d.ts +0 -1
  130. package/dist/data/package-versions.test.js +0 -227
  131. package/dist/data/persistent-vars.conflict.test.d.ts +0 -1
  132. package/dist/data/persistent-vars.conflict.test.js +0 -126
  133. package/dist/data/persistent-vars.migration.test.d.ts +0 -1
  134. package/dist/data/persistent-vars.migration.test.js +0 -133
  135. package/dist/data/persistent-vars.package-scope.test.d.ts +0 -1
  136. package/dist/data/persistent-vars.package-scope.test.js +0 -27
  137. package/dist/data/sync-recovery-queue.test.d.ts +0 -1
  138. package/dist/data/sync-recovery-queue.test.js +0 -215
  139. package/dist/data/table-signing.test.d.ts +0 -1
  140. package/dist/data/table-signing.test.js +0 -118
  141. package/dist/data/tool-access.test.d.ts +0 -1
  142. package/dist/data/tool-access.test.js +0 -166
  143. package/dist/data/user-permissions.test.d.ts +0 -1
  144. package/dist/data/user-permissions.test.js +0 -305
  145. package/dist/data/user-trust-levels.test.d.ts +0 -1
  146. package/dist/data/user-trust-levels.test.js +0 -37
  147. package/dist/define/also-implements.test.d.ts +0 -1
  148. package/dist/define/also-implements.test.js +0 -123
  149. package/dist/define/declare-contract.test.d.ts +0 -1
  150. package/dist/define/declare-contract.test.js +0 -573
  151. package/dist/define/define.test.d.ts +0 -1
  152. package/dist/define/define.test.js +0 -1010
  153. package/dist/define/empty-fields.test.d.ts +0 -1
  154. package/dist/define/empty-fields.test.js +0 -55
  155. package/dist/define/events-observables.test.d.ts +0 -1
  156. package/dist/define/events-observables.test.js +0 -1013
  157. package/dist/define/serve-members.test.d.ts +0 -1
  158. package/dist/define/serve-members.test.js +0 -630
  159. package/dist/define/vars.test.d.ts +0 -1
  160. package/dist/define/vars.test.js +0 -39
  161. package/dist/device/binary-peer-connection-v2.test.d.ts +0 -1
  162. package/dist/device/binary-peer-connection-v2.test.js +0 -730
  163. package/dist/device/binary-peer-connection.test.d.ts +0 -1
  164. package/dist/device/binary-peer-connection.test.js +0 -184
  165. package/dist/device/connection.test.d.ts +0 -1
  166. package/dist/device/connection.test.js +0 -613
  167. package/dist/device/device-election.test.d.ts +0 -1
  168. package/dist/device/device-election.test.js +0 -516
  169. package/dist/device/device.test.d.ts +0 -1
  170. package/dist/device/device.test.js +0 -243
  171. package/dist/device/frame-cipher.test.d.ts +0 -1
  172. package/dist/device/frame-cipher.test.js +0 -219
  173. package/dist/device/get-trust-level-fn.test.d.ts +0 -1
  174. package/dist/device/get-trust-level-fn.test.js +0 -685
  175. package/dist/device/streamed-socket.test.d.ts +0 -1
  176. package/dist/device/streamed-socket.test.js +0 -216
  177. package/dist/device/tx-encoding.test.d.ts +0 -1
  178. package/dist/device/tx-encoding.test.js +0 -295
  179. package/dist/device-pairing/cpace.test.d.ts +0 -1
  180. package/dist/device-pairing/cpace.test.js +0 -116
  181. package/dist/device-pairing/device-pairing.test.d.ts +0 -1
  182. package/dist/device-pairing/device-pairing.test.js +0 -211
  183. package/dist/hlc.test.d.ts +0 -1
  184. package/dist/hlc.test.js +0 -45
  185. package/dist/host-credentials.test.d.ts +0 -1
  186. package/dist/host-credentials.test.js +0 -88
  187. package/dist/identity/account-email.test.d.ts +0 -1
  188. package/dist/identity/account-email.test.js +0 -59
  189. package/dist/identity/anchor-document.test.d.ts +0 -1
  190. package/dist/identity/anchor-document.test.js +0 -16
  191. package/dist/identity/anchor-resolution.test.d.ts +0 -1
  192. package/dist/identity/anchor-resolution.test.js +0 -130
  193. package/dist/identity/key-change.test.d.ts +0 -1
  194. package/dist/identity/key-change.test.js +0 -811
  195. package/dist/invites/group-approval.test.d.ts +0 -1
  196. package/dist/invites/group-approval.test.js +0 -223
  197. package/dist/invites/invite-token.test.d.ts +0 -1
  198. package/dist/invites/invite-token.test.js +0 -123
  199. package/dist/keys.test.d.ts +0 -1
  200. package/dist/keys.test.js +0 -336
  201. package/dist/logging/console-logger.test.d.ts +0 -1
  202. package/dist/logging/console-logger.test.js +0 -300
  203. package/dist/logging/console-logs.table.test.d.ts +0 -1
  204. package/dist/logging/console-logs.table.test.js +0 -156
  205. package/dist/observable.test.d.ts +0 -1
  206. package/dist/observable.test.js +0 -309
  207. package/dist/package-build/build-package.test.d.ts +0 -1
  208. package/dist/package-build/build-package.test.js +0 -204
  209. package/dist/package-build/contract-add.test.d.ts +0 -1
  210. package/dist/package-build/contract-add.test.js +0 -467
  211. package/dist/package-build/freeze-contracts.test.d.ts +0 -1
  212. package/dist/package-build/freeze-contracts.test.js +0 -355
  213. package/dist/package-installer/package-author-signing.test.d.ts +0 -1
  214. package/dist/package-installer/package-author-signing.test.js +0 -200
  215. package/dist/package-installer/package-cloner.test.d.ts +0 -1
  216. package/dist/package-installer/package-cloner.test.js +0 -278
  217. package/dist/package-installer/package-creator.test.d.ts +0 -1
  218. package/dist/package-installer/package-creator.test.js +0 -908
  219. package/dist/package-installer/package-dev-tools.test.d.ts +0 -1
  220. package/dist/package-installer/package-dev-tools.test.js +0 -64
  221. package/dist/package-installer/package-installer.test.d.ts +0 -1
  222. package/dist/package-installer/package-installer.test.js +0 -882
  223. package/dist/package-installer/package-propagation.test.d.ts +0 -1
  224. package/dist/package-installer/package-propagation.test.js +0 -1269
  225. package/dist/package-installer/package-publisher.test.d.ts +0 -1
  226. package/dist/package-installer/package-publisher.test.js +0 -153
  227. package/dist/package-installer/package-remote-checker.test.d.ts +0 -1
  228. package/dist/package-installer/package-remote-checker.test.js +0 -334
  229. package/dist/package-installer/package-seed-installer.test.d.ts +0 -1
  230. package/dist/package-installer/package-seed-installer.test.js +0 -123
  231. package/dist/package-installer/package-tarball.test.d.ts +0 -1
  232. package/dist/package-installer/package-tarball.test.js +0 -75
  233. package/dist/package-installer/peers-core-installer.test.d.ts +0 -1
  234. package/dist/package-installer/peers-core-installer.test.js +0 -49
  235. package/dist/package-installer/peers-core-trust-anchor.test.d.ts +0 -1
  236. package/dist/package-installer/peers-core-trust-anchor.test.js +0 -155
  237. package/dist/package-loader/contract-package-loader.test.d.ts +0 -1
  238. package/dist/package-loader/contract-package-loader.test.js +0 -274
  239. package/dist/package-loader/host-authority-loading.test.d.ts +0 -1
  240. package/dist/package-loader/host-authority-loading.test.js +0 -104
  241. package/dist/package-loader/host-dispatch-policy.test.d.ts +0 -1
  242. package/dist/package-loader/host-dispatch-policy.test.js +0 -56
  243. package/dist/package-loader/isolated-artifact.test.d.ts +0 -1
  244. package/dist/package-loader/isolated-artifact.test.js +0 -688
  245. package/dist/package-loader/isolated-persistent-var-gateway.test.d.ts +0 -1
  246. package/dist/package-loader/isolated-persistent-var-gateway.test.js +0 -56
  247. package/dist/package-loader/isolated-table-gateway.test.d.ts +0 -1
  248. package/dist/package-loader/isolated-table-gateway.test.js +0 -633
  249. package/dist/package-loader/package-loader.test.d.ts +0 -1
  250. package/dist/package-loader/package-loader.test.js +0 -1764
  251. package/dist/package-loader/resolve-consumed-contracts.test.d.ts +0 -1
  252. package/dist/package-loader/resolve-consumed-contracts.test.js +0 -166
  253. package/dist/serial-json.compat.test.d.ts +0 -1
  254. package/dist/serial-json.compat.test.js +0 -369
  255. package/dist/serial-json.test.d.ts +0 -1
  256. package/dist/serial-json.test.js +0 -401
  257. package/dist/testing/mock-host-contract.test.d.ts +0 -1
  258. package/dist/testing/mock-host-contract.test.js +0 -782
  259. package/dist/utils.test.d.ts +0 -1
  260. package/dist/utils.test.js +0 -232
@@ -1,782 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const zod_1 = require("zod");
4
- const host_contract_client_1 = require("../contracts/host-contract-client");
5
- const host_contract_transport_1 = require("../contracts/host-contract-transport");
6
- const access_level_1 = require("../data/access-level");
7
- const types_1 = require("../data/orm/types");
8
- const contract_ref_1 = require("../define/contract-ref");
9
- const declare_contract_1 = require("../define/declare-contract");
10
- const define_package_1 = require("../define/define-package");
11
- const events_1 = require("../define/events");
12
- const manifest_1 = require("../define/manifest");
13
- const observables_1 = require("../define/observables");
14
- const table_1 = require("../define/table");
15
- const tool_1 = require("../define/tool");
16
- const vars_1 = require("../define/vars");
17
- const observable_1 = require("../observable");
18
- const peer_id_1 = require("../peer-id");
19
- const field_type_1 = require("../types/field-type");
20
- const zod_types_1 = require("../types/zod-types");
21
- const index_1 = require("./index");
22
- const contractId = "00mvjqva0cduvm6qdq536381m";
23
- const Notes = (0, table_1.defineTable)({
24
- name: "Notes",
25
- description: "Notes.",
26
- primaryKeyName: "noteId",
27
- schema: zod_1.z.object({
28
- noteId: zod_types_1.zodPeerId,
29
- title: zod_1.z.string().trim(),
30
- rank: zod_1.z.number().default(0),
31
- tag: zod_1.z.string().optional(),
32
- }),
33
- });
34
- const summarize = (0, tool_1.defineTool)({
35
- name: "summarize",
36
- usageDescription: "Summarize notes.",
37
- accessLevel: 0,
38
- inputSchema: zod_1.z.object({ count: zod_1.z.number().default(3) }),
39
- outputSchema: zod_1.z.object({ text: zod_1.z.string() }),
40
- handler: () => ({ text: "real handler" }),
41
- });
42
- const archive = (0, tool_1.defineTool)({
43
- name: "archive",
44
- usageDescription: "Archive.",
45
- // Above None: the mock host still runs it (no access checks).
46
- accessLevel: access_level_1.AccessLevel.Writer,
47
- inputSchema: zod_1.z.object({}),
48
- outputSchema: zod_1.z.object({}),
49
- handler: () => ({}),
50
- });
51
- const saved = (0, events_1.defineEvent)({
52
- name: "saved",
53
- description: "Notes were saved.",
54
- payloadSchema: zod_1.z.object({ count: zod_1.z.number() }),
55
- });
56
- const theme = (0, observables_1.defineObservable)({
57
- name: "theme",
58
- description: "Writable theme.",
59
- schema: zod_1.z.string().trim().min(1),
60
- writable: true,
61
- source: (0, observable_1.observable)("light"),
62
- });
63
- const label = (0, observables_1.defineObservable)({
64
- name: "label",
65
- description: "Writable stored label.",
66
- schema: zod_1.z.string().trim(),
67
- writable: true,
68
- source: (0, vars_1.deviceVar)("mockHostLabel", { defaultValue: "notes" }),
69
- });
70
- const status = (0, observables_1.defineObservable)({
71
- name: "status",
72
- description: "Read-only status.",
73
- schema: zod_1.z.string(),
74
- source: (0, observable_1.observable)("idle"),
75
- });
76
- const NotesContract = (0, define_package_1.defineContract)({
77
- contractId,
78
- version: 1,
79
- name: "Notes",
80
- tables: [Notes],
81
- tools: [summarize, archive],
82
- events: [saved],
83
- observables: [theme, status, label],
84
- });
85
- const note = (title, rank = 0, tag) => ({ noteId: (0, peer_id_1.newid)(), title, rank, tag });
86
- /** Let pushes and fire-and-forget requests land. */
87
- const flush = async () => {
88
- for (let i = 0; i < 5; i++)
89
- await new Promise((resolve) => setTimeout(resolve, 0));
90
- };
91
- const cleanups = [];
92
- afterEach(() => {
93
- for (const cleanup of cleanups.splice(0).reverse())
94
- cleanup();
95
- jest.restoreAllMocks();
96
- });
97
- function start(options = {}) {
98
- const host = (0, index_1.mockHostContract)(NotesContract, options);
99
- cleanups.push(() => host.dispose());
100
- return host;
101
- }
102
- function client() {
103
- const made = (0, host_contract_client_1.hostContract)(contractId, 1, { timeoutMs: 500 });
104
- cleanups.push(() => made.dispose());
105
- return made;
106
- }
107
- describe("hostContract(contractId, version)", () => {
108
- test("is the same client as the reference form, typed from the contract", async () => {
109
- const host = start({ tables: { Notes: [note("first")] } });
110
- const shared = (0, host_contract_client_1.hostContract)(contractId, 1);
111
- expect((0, host_contract_client_1.hostContract)(contractId, 1)).toBe(shared);
112
- expect((0, host_contract_client_1.hostContract)((0, contract_ref_1.contractRef)(contractId, 1))).toBe(shared);
113
- const rows = await shared.tables.Notes.list();
114
- expect(rows.map((row) => row.title)).toEqual(["first"]);
115
- expect(host.tables.Notes.rows).toHaveLength(1);
116
- const typeChecks = () => {
117
- // @ts-expect-error the version must be the contract's
118
- (0, host_contract_client_1.hostContract)(contractId, 2);
119
- // @ts-expect-error the id must be the contract's
120
- (0, host_contract_client_1.hostContract)("00mvjqva0xyy1fqyt9pupb16b", 1);
121
- // @ts-expect-error unknown tool
122
- void shared.tools.missing;
123
- // Without a contract type, any member, as with an untyped contractRef.
124
- void (0, host_contract_client_1.hostContract)(contractId, 1).tools.anything;
125
- void (0, host_contract_client_1.hostContract)((0, contract_ref_1.contractRef)(contractId, 1)).tools.anything;
126
- };
127
- void typeChecks;
128
- });
129
- test("validates its arguments", () => {
130
- expect(() => (0, host_contract_client_1.hostContract)("", 1)).toThrow("contractRef requires a contractId");
131
- expect(() => (0, host_contract_client_1.hostContract)(contractId, 0)).toThrow("positive integer");
132
- });
133
- });
134
- describe("mockHostContract", () => {
135
- test("mocks a declared contract: fakes stand in for handlers, start values for sources", async () => {
136
- const Skill = (0, declare_contract_1.declareContract)({
137
- contractId: (0, peer_id_1.newid)(),
138
- version: 1,
139
- name: "Skill",
140
- tools: [
141
- (0, tool_1.declareTool)({
142
- name: "invoke",
143
- usageDescription: "Run one.",
144
- accessLevel: access_level_1.AccessLevel.Reader,
145
- inputSchema: zod_1.z.object({ tool: zod_1.z.string() }),
146
- outputSchema: zod_1.z.object({ speech: zod_1.z.string().optional() }),
147
- }),
148
- ],
149
- observables: [
150
- (0, observables_1.declareObservable)({
151
- name: "skill",
152
- description: "The catalog.",
153
- schema: zod_1.z.object({ slug: zod_1.z.string() }),
154
- }),
155
- ],
156
- events: [
157
- (0, events_1.defineEvent)({
158
- name: "alert",
159
- description: "Attention.",
160
- payloadSchema: zod_1.z.object({ title: zod_1.z.string() }),
161
- }),
162
- ],
163
- });
164
- const host = (0, index_1.mockHostContract)(Skill, {
165
- tools: { invoke: ({ tool }) => ({ speech: `ran ${tool}` }) },
166
- observables: { skill: { slug: "timers" } },
167
- });
168
- cleanups.push(() => host.dispose());
169
- const skill = (0, host_contract_client_1.hostContract)(Skill);
170
- cleanups.push(() => skill.dispose());
171
- // A UI may also import only the declaration's type.
172
- const typedSkill = (0, host_contract_client_1.hostContract)(Skill.contractId, Skill.version);
173
- expect(typedSkill).toBe(skill);
174
- const typedResult = await typedSkill.tools.invoke({ tool: "typed" });
175
- const speech = typedResult.speech;
176
- expect(speech).toBe("ran typed");
177
- await expect(skill.tools.invoke({ tool: "list" })).resolves.toEqual({ speech: "ran list" });
178
- skill.observables.skill.subscribe(() => { });
179
- await flush();
180
- expect(skill.observables.skill()).toEqual({ slug: "timers" });
181
- const alerts = [];
182
- const subscription = skill.events.alert.subscribe((alert) => {
183
- alerts.push(alert.title);
184
- });
185
- await subscription.ready;
186
- await host.events.alert.emit({ title: "Done" });
187
- expect(alerts).toEqual(["Done"]);
188
- });
189
- test("tool fakes see empty optional inputs removed and defaults filled, and clean their results", async () => {
190
- const inputs = [];
191
- const rate = (0, tool_1.defineTool)({
192
- name: "rate",
193
- usageDescription: "Rate.",
194
- accessLevel: 0,
195
- inputSchema: zod_1.z.object({ rating: zod_1.z.number().default(5), note: zod_1.z.string().optional() }),
196
- outputSchema: zod_1.z.object({ note: zod_1.z.string().nullish() }),
197
- handler: () => ({}),
198
- });
199
- const contract = (0, define_package_1.defineContract)({
200
- contractId: (0, peer_id_1.newid)(),
201
- version: 1,
202
- name: "Ratings",
203
- tools: [rate],
204
- });
205
- const host = (0, index_1.mockHostContract)(contract, {
206
- tools: {
207
- rate: (input) => {
208
- inputs.push(input);
209
- return { note: null };
210
- },
211
- },
212
- });
213
- cleanups.push(() => host.dispose());
214
- const ratings = (0, host_contract_client_1.hostContract)(contract.contractId, 1);
215
- cleanups.push(() => ratings.dispose());
216
- await expect(ratings.tools.rate({ rating: null, note: null })).resolves.toStrictEqual({});
217
- expect(inputs).toStrictEqual([{ rating: 5 }]);
218
- });
219
- test("tool fakes get the input as the tool's schema parses it", async () => {
220
- const inputs = [];
221
- start({
222
- tools: {
223
- summarize: (input) => {
224
- const count = input.count;
225
- void count;
226
- inputs.push(input);
227
- return { text: `${input.count} notes` };
228
- },
229
- },
230
- });
231
- const notes = client();
232
- await expect(notes.tools.summarize()).resolves.toEqual({ text: "3 notes" });
233
- await expect(notes.tools.summarize({ count: 5 })).resolves.toEqual({ text: "5 notes" });
234
- expect(inputs).toEqual([{ count: 3 }, { count: 5 }]);
235
- await expect(notes.tools.archive()).rejects.toThrow("no fake for tool 'archive'");
236
- });
237
- test("fake inputs have their parsed types, including schema transforms", async () => {
238
- const convert = (0, tool_1.defineTool)({
239
- name: "convert",
240
- usageDescription: "Parse a count.",
241
- accessLevel: 0,
242
- inputSchema: zod_1.z.object({ count: zod_1.z.string().transform(Number) }),
243
- outputSchema: zod_1.z.object({ count: zod_1.z.number() }),
244
- handler: (input) => input,
245
- });
246
- const Converted = (0, define_package_1.defineContract)({
247
- contractId: (0, peer_id_1.newid)(),
248
- version: 1,
249
- name: "Converted",
250
- tools: [convert],
251
- });
252
- const host = (0, index_1.mockHostContract)(Converted, {
253
- tools: {
254
- convert: (input) => {
255
- const count = input.count;
256
- return { count: count + 1 };
257
- },
258
- },
259
- });
260
- cleanups.push(() => host.dispose());
261
- const converted = (0, host_contract_client_1.hostContract)(Converted.contractId, 1, { timeoutMs: 500 });
262
- cleanups.push(() => converted.dispose());
263
- await expect(converted.tools.convert({ count: "4" })).resolves.toEqual({ count: 5 });
264
- });
265
- test("a private tool refuses UI calls, as the host does, even with a fake", async () => {
266
- const internal = (0, tool_1.defineTool)({
267
- name: "internal",
268
- usageDescription: "Only the package's own dispatcher may call this.",
269
- accessLevel: 0,
270
- private: true,
271
- inputSchema: zod_1.z.object({}),
272
- outputSchema: zod_1.z.object({ ok: zod_1.z.boolean() }),
273
- handler: () => ({ ok: true }),
274
- });
275
- const Internal = (0, define_package_1.defineContract)({
276
- contractId: (0, peer_id_1.newid)(),
277
- version: 1,
278
- name: "Internal",
279
- tools: [internal],
280
- });
281
- const host = (0, index_1.mockHostContract)(Internal, { tools: { internal: () => ({ ok: true }) } });
282
- cleanups.push(() => host.dispose());
283
- const client = (0, host_contract_client_1.hostContract)(Internal.contractId, 1, { timeoutMs: 500 });
284
- cleanups.push(() => client.dispose());
285
- await expect(client.tools.internal()).rejects.toThrow("tool 'internal' is private");
286
- });
287
- test("tables read, filter, sort, and page in memory", async () => {
288
- start({
289
- tables: { Notes: [note("b", 2, "x"), note("a", 1, "y"), note("c", 3, "x")] },
290
- });
291
- const notes = client().tables.Notes;
292
- expect((await notes.list({ tag: "x" })).map((row) => row.title)).toEqual(["b", "c"]);
293
- expect((await notes.list({}, { sortBy: ["-rank"] })).map((row) => row.title)).toEqual([
294
- "c",
295
- "b",
296
- "a",
297
- ]);
298
- expect((await notes.list({}, { sortBy: ["title"], page: 2, pageSize: 2 })).map((row) => row.title)).toEqual(["c"]);
299
- expect(await notes.count({ tag: "x" })).toBe(2);
300
- expect((await notes.findOne({ tag: "y" }))?.title).toBe("a");
301
- expect((await notes.list({ title: { $in: ["a", "c"] } }, { sortBy: ["title"] })).map((row) => row.title)).toEqual(["a", "c"]);
302
- expect(await notes.count({ tag: "x", title: { $in: ["a", "b"] } })).toBe(1);
303
- await expect(notes.list({ $or: [{ tag: "x" }] })).rejects.toThrow("equality and $in filters only");
304
- await expect(notes.list({ title: { $ne: "a" } })).rejects.toThrow("equality and $in filters only");
305
- await expect(notes.list({}, { textSearch: "a" })).rejects.toThrow("does not support query option 'textSearch'");
306
- });
307
- test("UI saves go through the table's schema, and host writes reach subscribers", async () => {
308
- const host = start();
309
- const notes = client().tables.Notes;
310
- const events = [];
311
- const subscription = notes.dataChanged.subscribe((event) => events.push(`${event.op}:${event.dataObject.title}`));
312
- await subscription.ready;
313
- const typeChecks = () => {
314
- // @ts-expect-error `title` has no default
315
- void notes.save({ noteId: (0, peer_id_1.newid)() });
316
- };
317
- void typeChecks;
318
- // The provider's table parses the save, so the schema's default fills `rank`.
319
- const first = await notes.save({ noteId: (0, peer_id_1.newid)(), title: "from UI" });
320
- expect(first.rank).toBe(0);
321
- expect(host.tables.Notes.rows).toEqual([first]);
322
- await expect(notes.save({ noteId: (0, peer_id_1.newid)() })).rejects.toThrow();
323
- await host.tables.Notes.save({ ...first, title: "from host" });
324
- await host.tables.Notes.delete(first.noteId);
325
- await flush();
326
- expect(events).toEqual(["insert:from UI", "update:from host", "delete:from host"]);
327
- expect(await notes.get(first.noteId)).toBeUndefined();
328
- });
329
- test("UI calls and changes go through the table's class", async () => {
330
- const schema = zod_1.z.object({
331
- itemId: zod_types_1.zodPeerId,
332
- title: zod_1.z.string(),
333
- hidden: zod_1.z.boolean().default(false),
334
- });
335
- class ItemsTable extends table_1.PackageTable {
336
- async save(item) {
337
- return super.save({ ...item, title: item.title.trim() });
338
- }
339
- async list(...args) {
340
- return (await super.list(...args)).filter((item) => !item.hidden);
341
- }
342
- dataChanged(event) {
343
- return event.dataObject.hidden ? undefined : event;
344
- }
345
- }
346
- const Items = (0, table_1.defineTable)({
347
- name: "Items",
348
- description: "Items.",
349
- primaryKeyName: "itemId",
350
- schema,
351
- tableClass: ItemsTable,
352
- });
353
- const itemsContractId = (0, peer_id_1.newid)();
354
- const ItemsContract = (0, define_package_1.defineContract)({
355
- contractId: itemsContractId,
356
- version: 1,
357
- name: "Items",
358
- tables: [Items],
359
- });
360
- const host = (0, index_1.mockHostContract)(ItemsContract);
361
- cleanups.push(() => host.dispose());
362
- const items = (0, host_contract_client_1.hostContract)(itemsContractId, 1, { timeoutMs: 500 });
363
- cleanups.push(() => items.dispose());
364
- const changes = [];
365
- await items.tables.Items.dataChanged.subscribe((event) => changes.push(`${event.op}:${event.dataObject.title}`)).ready;
366
- const saved = await items.tables.Items.save({ itemId: (0, peer_id_1.newid)(), title: " shown " });
367
- expect(saved).toMatchObject({ title: "shown", hidden: false });
368
- await host.tables.Items.save({ itemId: (0, peer_id_1.newid)(), title: "secret", hidden: true });
369
- await flush();
370
- expect((await items.tables.Items.list()).map((item) => item.title)).toEqual(["shown"]);
371
- expect(host.tables.Items.rows).toHaveLength(2);
372
- expect(changes).toEqual(["insert:shown"]);
373
- });
374
- test("null equality filters match omitted optional fields, as host storage does", async () => {
375
- start({ tables: { Notes: [note("untagged"), note("tagged", 0, "work")] } });
376
- const notes = client().tables.Notes;
377
- for (const filter of [{ tag: null }, { tag: undefined }]) {
378
- expect((await notes.list(filter)).map((row) => row.title)).toEqual(["untagged"]);
379
- expect(await notes.count(filter)).toBe(1);
380
- expect((await notes.findOne(filter))?.title).toBe("untagged");
381
- }
382
- });
383
- test("table delivery hooks stop when the mock host is disposed", async () => {
384
- const schema = zod_1.z.object({ itemId: zod_types_1.zodPeerId, title: zod_1.z.string() });
385
- let release;
386
- const pending = new Promise((resolve) => {
387
- release = resolve;
388
- });
389
- const seen = [];
390
- class DelayedTable extends table_1.PackageTable {
391
- async dataChanged(event) {
392
- seen.push(event.dataObject.title);
393
- await pending;
394
- return event;
395
- }
396
- }
397
- const Items = (0, table_1.defineTable)({
398
- name: "Items",
399
- description: "Items",
400
- primaryKeyName: "itemId",
401
- schema,
402
- tableClass: DelayedTable,
403
- });
404
- const Contract = (0, define_package_1.defineContract)({
405
- contractId: (0, peer_id_1.newid)(),
406
- version: 1,
407
- name: "Delayed",
408
- tables: [Items],
409
- });
410
- const host = (0, index_1.mockHostContract)(Contract);
411
- cleanups.push(() => host.dispose());
412
- await host.tables.Items.save({ itemId: (0, peer_id_1.newid)(), title: "unobserved" });
413
- await flush();
414
- expect(seen).toEqual([]);
415
- const items = (0, host_contract_client_1.hostContract)(Contract.contractId, 1, { timeoutMs: 500 });
416
- cleanups.push(() => items.dispose());
417
- const pushed = jest.fn();
418
- await items.tables.Items.dataChanged.subscribe(pushed).ready;
419
- await host.tables.Items.save({ itemId: (0, peer_id_1.newid)(), title: "pending" });
420
- await flush();
421
- expect(seen).toEqual(["pending"]);
422
- await host.tables.Items.save({ itemId: (0, peer_id_1.newid)(), title: "queued" });
423
- host.dispose();
424
- release();
425
- await host.tables.Items.save({ itemId: (0, peer_id_1.newid)(), title: "disposed" });
426
- await flush();
427
- expect(seen).toEqual(["pending"]);
428
- expect(pushed).not.toHaveBeenCalled();
429
- });
430
- test("UI saves run the table's schema; stored rows validate the manifest's fields", async () => {
431
- const definition = (0, define_package_1.definePackage)((pkg) => {
432
- pkg.packageId = (0, peer_id_1.newid)();
433
- pkg.version = "1.0.0";
434
- pkg.provides(NotesContract);
435
- });
436
- const fields = (0, manifest_1.buildPackageManifest)(definition).tables?.[0].fields;
437
- if (!fields)
438
- throw new Error("missing table fields");
439
- const storedSchema = (0, types_1.fieldsToSchema)(fields);
440
- const incomplete = { noteId: (0, peer_id_1.newid)(), title: " incomplete " };
441
- // Storage has only the manifest's fields: starting rows must be complete.
442
- expect(() => storedSchema.parse(incomplete)).toThrow();
443
- expect(() => start({ tables: { Notes: [incomplete] } })).toThrow();
444
- // A UI save reaches the package's table, whose schema trims the title and fills `rank`.
445
- const host = start();
446
- const saved = await client().tables.Notes.save(incomplete);
447
- expect(saved).toMatchObject({ title: "incomplete", rank: 0 });
448
- expect(host.tables.Notes.rows).toEqual([saved]);
449
- });
450
- test("stored mock rows match richer manifest fields without enforcing nested shapes", () => {
451
- const Places = (0, table_1.defineTable)({
452
- name: "Places",
453
- description: "Places.",
454
- primaryKeyName: "placeId",
455
- schema: zod_1.z.object({
456
- placeId: zod_types_1.zodPeerId,
457
- mode: zod_1.z.enum(["on", "off"]),
458
- detail: zod_1.z.object({ city: zod_1.z.string() }).optional(),
459
- }),
460
- });
461
- const Contract = (0, define_package_1.defineContract)({
462
- contractId: (0, peer_id_1.newid)(),
463
- version: 1,
464
- name: "Places",
465
- tables: [Places],
466
- });
467
- const rows = [
468
- { placeId: (0, peer_id_1.newid)(), mode: "on" },
469
- { placeId: (0, peer_id_1.newid)(), mode: "on", detail: { city: "Austin", extra: true } },
470
- // Synced stored rows get type-level checks; the package parses consumer saves.
471
- { placeId: (0, peer_id_1.newid)(), mode: "future", detail: { city: 3 } },
472
- ];
473
- const host = (0, index_1.mockHostContract)(Contract, { tables: { Places: rows } });
474
- cleanups.push(() => host.dispose());
475
- expect(host.tables.Places.rows).toEqual(rows);
476
- });
477
- test("an empty optional field is left out, as in host storage", async () => {
478
- const Places = (0, table_1.defineTable)({
479
- name: "Places",
480
- description: "Places.",
481
- primaryKeyName: "placeId",
482
- schema: zod_1.z.object({
483
- placeId: zod_types_1.zodPeerId,
484
- city: zod_1.z.string(),
485
- note: zod_1.z.string().optional(),
486
- where: zod_1.z.object({ zip: zod_1.z.string().optional() }).optional(),
487
- }),
488
- });
489
- const Contract = (0, define_package_1.defineContract)({
490
- contractId: (0, peer_id_1.newid)(),
491
- version: 1,
492
- name: "Places",
493
- tables: [Places],
494
- });
495
- const first = { placeId: (0, peer_id_1.newid)(), city: "Austin", note: null };
496
- const host = (0, index_1.mockHostContract)(Contract, { tables: { Places: [first] } });
497
- cleanups.push(() => host.dispose());
498
- expect(host.tables.Places.rows).toEqual([{ placeId: first.placeId, city: "Austin" }]);
499
- const second = { placeId: (0, peer_id_1.newid)(), city: "Austin", note: null, where: { zip: null } };
500
- const stored = { placeId: second.placeId, city: "Austin", where: {} };
501
- // The save returns the row as stored, so saving it again changes nothing.
502
- expect(await host.tables.Places.save(second)).toEqual(stored);
503
- expect(await host.tables.Places.get(second.placeId)).toEqual(stored);
504
- });
505
- test("a .nullable() table field is refused, as the build refuses it", () => {
506
- const Places = (0, table_1.defineTable)({
507
- name: "Places",
508
- description: "Places.",
509
- primaryKeyName: "placeId",
510
- schema: zod_1.z.object({ placeId: zod_types_1.zodPeerId, city: zod_1.z.string().nullable() }),
511
- });
512
- const Contract = (0, define_package_1.defineContract)({
513
- contractId: (0, peer_id_1.newid)(),
514
- version: 1,
515
- name: "Places",
516
- tables: [Places],
517
- });
518
- expect(() => (0, index_1.mockHostContract)(Contract)).toThrow('Field "city" uses .nullable()');
519
- });
520
- test("the UI holds copies, not the host's rows", async () => {
521
- const host = start({ tables: { Notes: [note("original")] } });
522
- const [row] = await client().tables.Notes.list();
523
- row.title = "changed in the UI";
524
- expect(host.tables.Notes.rows[0].title).toBe("original");
525
- });
526
- test("works without structuredClone, as in Jest's jsdom environment", async () => {
527
- const clone = globalThis.structuredClone;
528
- try {
529
- // @ts-expect-error jsdom does not provide this global
530
- delete globalThis.structuredClone;
531
- const host = start({ tables: { Notes: [note("original")] } });
532
- const notes = client().tables.Notes;
533
- expect(await notes.list()).toEqual(host.tables.Notes.rows);
534
- const saved = await notes.save(note("saved"));
535
- expect(await notes.get(saved.noteId)).toEqual(saved);
536
- }
537
- finally {
538
- globalThis.structuredClone = clone;
539
- }
540
- });
541
- test("a call delayed by onCall rejects if its host is disposed", async () => {
542
- let release;
543
- const gate = new Promise((resolve) => {
544
- release = resolve;
545
- });
546
- const host = start({
547
- tables: { Notes: [note("a")] },
548
- onCall: async () => gate,
549
- });
550
- const notes = client().tables.Notes;
551
- const count = notes.count();
552
- await flush();
553
- host.dispose();
554
- release();
555
- await expect(count).rejects.toThrow("disposed");
556
- });
557
- test("calls that would never be answered reject when the host is disposed", async () => {
558
- const host = start({
559
- tables: { Notes: [note("a")] },
560
- tools: { summarize: () => new Promise(() => { }) },
561
- onCall: (call) => (call.operation === "count" ? new Promise(() => { }) : undefined),
562
- });
563
- const notes = client();
564
- const count = notes.tables.Notes.count();
565
- const summary = notes.tools.summarize();
566
- await flush();
567
- host.dispose();
568
- await expect(count).rejects.toThrow(/Mock host for .* is disposed/);
569
- await expect(summary).rejects.toThrow(/Mock host for .* is disposed/);
570
- });
571
- test("observables follow the host, and a read-only one refuses writes", async () => {
572
- const errors = jest.spyOn(console, "error").mockImplementation(() => { });
573
- const host = start({ observables: { theme: "dark", status: "ready" } });
574
- const notes = client();
575
- const seen = [];
576
- notes.observables.theme.subscribe((value) => seen.push(value));
577
- notes.observables.status.subscribe(() => { });
578
- await flush();
579
- expect(notes.observables.theme()).toBe("dark");
580
- expect(notes.observables.status()).toBe("ready");
581
- notes.observables.theme("blue");
582
- await flush();
583
- expect(host.observables.theme()).toBe("blue");
584
- host.observables.status("busy");
585
- await flush();
586
- expect(notes.observables.status()).toBe("busy");
587
- notes.observables.status("hacked");
588
- await flush();
589
- expect(host.observables.status()).toBe("busy");
590
- expect(notes.observables.status()).toBe("busy");
591
- expect(errors).toHaveBeenCalledWith("Contract observable set failed", expect.anything());
592
- expect(seen).toContain("blue");
593
- });
594
- test("observables start as the host serves them unless given a value", async () => {
595
- const host = start({ observables: { status: "ready" } });
596
- const notes = client();
597
- notes.observables.theme.subscribe(() => { });
598
- notes.observables.status.subscribe(() => { });
599
- notes.observables.label.subscribe(() => { });
600
- await flush();
601
- // In memory: the source's value, which the worker publishes at start.
602
- expect(notes.observables.theme()).toBe("light");
603
- // Given a starting value.
604
- expect(notes.observables.status()).toBe("ready");
605
- // Stored: the variable's default.
606
- expect(notes.observables.label()).toBe("notes");
607
- expect(host.observables.label()).toBe("notes");
608
- });
609
- test("observable reads and pushes leave empty fields out without changing the source", async () => {
610
- const items = (0, observables_1.defineObservable)({
611
- name: "items",
612
- description: "Items.",
613
- schema: zod_1.z.array(zod_1.z.object({ note: zod_1.z.string().optional() })),
614
- source: (0, observable_1.observable)([{ note: null }]),
615
- });
616
- const contract = (0, define_package_1.defineContract)({
617
- contractId: (0, peer_id_1.newid)(),
618
- version: 1,
619
- name: "Items",
620
- observables: [items],
621
- });
622
- const host = (0, index_1.mockHostContract)(contract);
623
- cleanups.push(() => host.dispose());
624
- const client = (0, host_contract_client_1.hostContract)(contract.contractId, 1);
625
- cleanups.push(() => client.dispose());
626
- const seen = [];
627
- client.observables.items.subscribe((value) => seen.push(value));
628
- await flush();
629
- expect(client.observables.items()).toStrictEqual([{}]);
630
- expect(host.observables.items()).toStrictEqual([{ note: null }]);
631
- host.observables.items([{ note: null }, { note: "set" }]);
632
- await flush();
633
- expect(client.observables.items()).toStrictEqual([{}, { note: "set" }]);
634
- expect(seen.at(-1)).toStrictEqual([{}, { note: "set" }]);
635
- });
636
- test("UI observable writes are checked with the schema, as the host checks them", async () => {
637
- const errors = jest.spyOn(console, "error").mockImplementation(() => { });
638
- const host = start({ observables: { theme: "dark", label: "notes" } });
639
- const notes = client();
640
- notes.observables.theme.subscribe(() => { });
641
- notes.observables.label.subscribe(() => { });
642
- await flush();
643
- // An in-memory observable keeps the parsed value, as its write handler does.
644
- notes.observables.theme(" blue ");
645
- await flush();
646
- expect(host.observables.theme()).toBe("blue");
647
- expect(notes.observables.theme()).toBe("blue");
648
- // A value the schema refuses fails, and the UI reads the host's value again.
649
- for (const refused of [undefined, " "]) {
650
- errors.mockClear();
651
- notes.observables.theme(refused);
652
- await flush();
653
- expect(host.observables.theme()).toBe("blue");
654
- expect(notes.observables.theme()).toBe("blue");
655
- expect(errors).toHaveBeenCalledWith("Contract observable set failed", expect.anything());
656
- }
657
- // A stored observable keeps the parsed value, as the package stores it.
658
- notes.observables.label(" todo ");
659
- await flush();
660
- expect(host.observables.label()).toBe("todo");
661
- });
662
- test("observable writes must fit the manifest type before defaults, coercion, or IR writes", async () => {
663
- const Counter = (0, define_package_1.defineContract)({
664
- contractId: (0, peer_id_1.newid)(),
665
- version: 1,
666
- name: "Counter",
667
- observables: [
668
- (0, observables_1.defineObservable)({
669
- name: "defaulted",
670
- description: "A default does not make undefined a valid host write.",
671
- schema: zod_1.z.number().default(1),
672
- writable: true,
673
- source: (0, observable_1.observable)(1),
674
- }),
675
- (0, observables_1.defineObservable)({
676
- name: "coerced",
677
- description: "Coercion runs only after the host checks the incoming value.",
678
- schema: zod_1.z.coerce.number(),
679
- writable: true,
680
- source: (0, observable_1.observable)(1),
681
- }),
682
- (0, observables_1.defineObservable)({
683
- name: "declaredIr",
684
- description: "An IR declaration still has a host value type.",
685
- valueType: field_type_1.FieldType.number,
686
- writable: true,
687
- source: (0, observable_1.observable)(1),
688
- }),
689
- {
690
- name: "rawIr",
691
- description: "A raw IR member has the same host check.",
692
- valueType: field_type_1.FieldType.number,
693
- writable: true,
694
- persistentVar: { scope: "device", name: "rawIr", defaultValue: 1 },
695
- },
696
- ],
697
- });
698
- const host = (0, index_1.mockHostContract)(Counter, {
699
- observables: { defaulted: 2, coerced: 2, declaredIr: 2, rawIr: 2 },
700
- });
701
- cleanups.push(() => host.dispose());
702
- const counter = (0, host_contract_client_1.hostContract)(Counter.contractId, 1, { timeoutMs: 500 });
703
- cleanups.push(() => counter.dispose());
704
- const errors = jest.spyOn(console, "error").mockImplementation(() => { });
705
- const values = counter.observables;
706
- // Access each lazy member before waiting for its initial read.
707
- values.defaulted.subscribe(() => { });
708
- values.coerced.subscribe(() => { });
709
- values.declaredIr.subscribe(() => { });
710
- values.rawIr.subscribe(() => { });
711
- await flush();
712
- values.defaulted(undefined);
713
- values.coerced("3");
714
- values.declaredIr("3");
715
- values.rawIr("3");
716
- await flush();
717
- expect(errors).toHaveBeenCalledTimes(4);
718
- for (const name of ["defaulted", "coerced", "declaredIr", "rawIr"]) {
719
- expect(host.observables[name]()).toBe(2);
720
- expect(values[name]()).toBe(2);
721
- values[name](3);
722
- }
723
- await flush();
724
- for (const name of ["defaulted", "coerced", "declaredIr", "rawIr"]) {
725
- expect(host.observables[name]()).toBe(3);
726
- expect(values[name]()).toBe(3);
727
- }
728
- });
729
- test("events reach subscribers", async () => {
730
- const host = start();
731
- const payloads = [];
732
- const subscription = client().events.saved.subscribe((payload) => payloads.push(payload));
733
- await subscription.ready;
734
- await host.events.saved.emit({ count: 2 });
735
- await flush();
736
- expect(payloads).toEqual([{ count: 2 }]);
737
- });
738
- test("onCall can delay or fail a call", async () => {
739
- const calls = [];
740
- let release;
741
- const gate = new Promise((resolve) => {
742
- release = resolve;
743
- });
744
- start({
745
- tables: { Notes: [note("a")] },
746
- onCall: async (call) => {
747
- calls.push(call);
748
- if (call.operation === "count")
749
- throw new Error("offline");
750
- if (call.operation === "list")
751
- await gate;
752
- },
753
- });
754
- const notes = client().tables.Notes;
755
- await expect(notes.count()).rejects.toThrow("offline");
756
- let listed = false;
757
- const reading = notes.list().then(() => {
758
- listed = true;
759
- });
760
- await flush();
761
- expect(listed).toBe(false);
762
- release();
763
- await reading;
764
- expect(calls.map((call) => `${call.member}.${call.name}.${call.operation}`)).toEqual([
765
- "table.Notes.count",
766
- "table.Notes.list",
767
- ]);
768
- });
769
- test("checks names, runs one at a time, and disconnects on dispose", () => {
770
- expect(() => (0, index_1.mockHostContract)(NotesContract, { tables: { Missing: [] } })).toThrow("has no table 'Missing'");
771
- expect(() => (0, index_1.mockHostContract)(NotesContract, { tools: { missing: () => ({}) } })).toThrow("has no tool 'missing'");
772
- expect(() => (0, index_1.mockHostContract)({})).toThrow("defineContract");
773
- expect(() => (0, index_1.mockHostContract)(NotesContract, { observables: { typo: "dark" } })).toThrow("has no observable 'typo'");
774
- const host = (0, index_1.mockHostContract)(NotesContract);
775
- expect((0, host_contract_transport_1.getHostContractTransport)()).toBeDefined();
776
- expect(() => (0, index_1.mockHostContract)(NotesContract)).toThrow("still running");
777
- host.dispose();
778
- host.dispose();
779
- expect((0, host_contract_transport_1.getHostContractTransport)()).toBeUndefined();
780
- (0, index_1.mockHostContract)(NotesContract).dispose();
781
- });
782
- });