@peers-app/peers-sdk 0.26.6 → 0.27.1

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 (189) hide show
  1. package/README.md +3 -1
  2. package/bin/peers-package.js +13 -0
  3. package/define/package.json +4 -0
  4. package/dist/contracts/__tests__/action-dispatch.test.js +56 -76
  5. package/dist/contracts/__tests__/also-implements.test.d.ts +1 -0
  6. package/dist/contracts/__tests__/also-implements.test.js +110 -0
  7. package/dist/contracts/__tests__/builder.test.js +45 -0
  8. package/dist/contracts/__tests__/contract-resolvers.test.js +134 -4
  9. package/dist/contracts/__tests__/frozen-contracts.test.d.ts +1 -0
  10. package/dist/contracts/__tests__/frozen-contracts.test.js +191 -0
  11. package/dist/contracts/__tests__/generic-tool-dispatch.test.js +13 -56
  12. package/dist/contracts/__tests__/host-contract-client.test.d.ts +1 -0
  13. package/dist/contracts/__tests__/host-contract-client.test.js +793 -0
  14. package/dist/contracts/__tests__/host-contract-transport.test.js +15 -0
  15. package/dist/contracts/__tests__/registry.test.js +68 -0
  16. package/dist/contracts/__tests__/target-dispatch.d.ts +11 -0
  17. package/dist/contracts/__tests__/target-dispatch.js +24 -0
  18. package/dist/contracts/__tests__/tool-catalog-service.test.js +37 -1
  19. package/dist/contracts/__tests__/tool-catalog.test.js +12 -3
  20. package/dist/contracts/__tests__/validate.test.js +177 -7
  21. package/dist/contracts/__tests__/workflow-context.test.js +0 -11
  22. package/dist/contracts/builder.d.ts +16 -2
  23. package/dist/contracts/builder.js +44 -3
  24. package/dist/contracts/contract-definition-schema.d.ts +251 -0
  25. package/dist/contracts/contract-definition-schema.js +48 -0
  26. package/dist/contracts/contract-provider-router.d.ts +2 -0
  27. package/dist/contracts/contract-provider-router.js +5 -2
  28. package/dist/contracts/contract-proxy.d.ts +52 -18
  29. package/dist/contracts/contract-proxy.js +144 -203
  30. package/dist/contracts/contract-resolvers.d.ts +6 -4
  31. package/dist/contracts/contract-resolvers.js +32 -9
  32. package/dist/contracts/frozen-contracts.d.ts +59 -0
  33. package/dist/contracts/frozen-contracts.js +86 -0
  34. package/dist/contracts/host-contract-client.d.ts +134 -0
  35. package/dist/contracts/host-contract-client.js +396 -0
  36. package/dist/contracts/host-contract-transport.d.ts +2 -0
  37. package/dist/contracts/host-contract-transport.js +8 -0
  38. package/dist/contracts/index.d.ts +6 -4
  39. package/dist/contracts/index.js +11 -5
  40. package/dist/contracts/registry.d.ts +31 -1
  41. package/dist/contracts/registry.js +100 -6
  42. package/dist/contracts/system/contract-catalog-contract.d.ts +61 -6
  43. package/dist/contracts/system/contract-catalog-contract.js +17 -5
  44. package/dist/contracts/tool-catalog-service.js +26 -6
  45. package/dist/contracts/tool-catalog.d.ts +1 -1
  46. package/dist/contracts/tool-catalog.js +4 -1
  47. package/dist/contracts/types.d.ts +32 -2
  48. package/dist/contracts/validate.d.ts +16 -1
  49. package/dist/contracts/validate.js +139 -25
  50. package/dist/data/change-tracking.d.ts +17 -5
  51. package/dist/data/change-tracking.js +22 -6
  52. package/dist/data/change-tracking.test.d.ts +1 -0
  53. package/dist/data/change-tracking.test.js +62 -0
  54. package/dist/data/create-group.js +1 -1
  55. package/dist/data/group-members.d.ts +14 -0
  56. package/dist/data/group-members.js +36 -0
  57. package/dist/data/group-members.test.js +49 -0
  58. package/dist/data/orm/sql.data-source.d.ts +9 -0
  59. package/dist/data/orm/sql.data-source.js +47 -2
  60. package/dist/data/orm/sql.data-source.test.js +142 -0
  61. package/dist/data/orm/table-container.js +9 -9
  62. package/dist/data/orm/table-container.test.js +44 -0
  63. package/dist/data/orm/types.d.ts +41 -1
  64. package/dist/data/orm/types.js +159 -28
  65. package/dist/data/orm/types.test.js +129 -0
  66. package/dist/data/peer-types.d.ts +8 -62
  67. package/dist/data/persistent-vars.d.ts +4 -1
  68. package/dist/data/persistent-vars.js +7 -2
  69. package/dist/data/tools.d.ts +29 -221
  70. package/dist/define/also-implements.test.d.ts +1 -0
  71. package/dist/define/also-implements.test.js +123 -0
  72. package/dist/define/context.d.ts +77 -0
  73. package/dist/define/context.js +2 -0
  74. package/dist/define/contract-ref.d.ts +177 -0
  75. package/dist/define/contract-ref.js +67 -0
  76. package/dist/define/declare-contract.d.ts +167 -0
  77. package/dist/define/declare-contract.js +220 -0
  78. package/dist/define/declare-contract.test.d.ts +1 -0
  79. package/dist/define/declare-contract.test.js +573 -0
  80. package/dist/define/define-package.d.ts +203 -0
  81. package/dist/define/define-package.js +289 -0
  82. package/dist/define/define.test.d.ts +1 -0
  83. package/dist/define/define.test.js +1010 -0
  84. package/dist/define/empty-fields.d.ts +15 -0
  85. package/dist/define/empty-fields.js +134 -0
  86. package/dist/define/empty-fields.test.d.ts +1 -0
  87. package/dist/define/empty-fields.test.js +55 -0
  88. package/dist/define/events-observables.test.d.ts +1 -0
  89. package/dist/define/events-observables.test.js +1013 -0
  90. package/dist/define/events.d.ts +81 -0
  91. package/dist/define/events.js +81 -0
  92. package/dist/define/generated-field.d.ts +20 -0
  93. package/dist/define/generated-field.js +25 -0
  94. package/dist/define/index.d.ts +28 -0
  95. package/dist/define/index.js +62 -0
  96. package/dist/define/lazy-members.d.ts +8 -0
  97. package/dist/define/lazy-members.js +38 -0
  98. package/dist/define/manifest.d.ts +63 -0
  99. package/dist/define/manifest.js +653 -0
  100. package/dist/define/observables.d.ts +146 -0
  101. package/dist/define/observables.js +187 -0
  102. package/dist/define/serve-members.d.ts +21 -0
  103. package/dist/define/serve-members.js +152 -0
  104. package/dist/define/serve-members.test.d.ts +1 -0
  105. package/dist/define/serve-members.test.js +630 -0
  106. package/dist/define/serve.d.ts +22 -0
  107. package/dist/define/serve.js +58 -0
  108. package/dist/define/system-contracts.d.ts +41 -0
  109. package/dist/define/system-contracts.js +21 -0
  110. package/dist/define/table-handle.d.ts +13 -0
  111. package/dist/define/table-handle.js +36 -0
  112. package/dist/define/table.d.ts +128 -0
  113. package/dist/define/table.js +122 -0
  114. package/dist/define/tool.d.ts +129 -0
  115. package/dist/define/tool.js +91 -0
  116. package/dist/define/vars.d.ts +82 -0
  117. package/dist/define/vars.js +256 -0
  118. package/dist/define/vars.test.d.ts +1 -0
  119. package/dist/define/vars.test.js +39 -0
  120. package/dist/define/wire-value.d.ts +12 -0
  121. package/dist/define/wire-value.js +76 -0
  122. package/dist/define/worker-state.d.ts +15 -0
  123. package/dist/define/worker-state.js +45 -0
  124. package/dist/device/tx-encoding.test.js +10 -0
  125. package/dist/index.d.ts +3 -0
  126. package/dist/index.js +5 -1
  127. package/dist/invites/group-approval.js +4 -2
  128. package/dist/invites/group-approval.test.js +2 -0
  129. package/dist/observable.d.ts +42 -2
  130. package/dist/observable.js +25 -7
  131. package/dist/package-build/build-package.d.ts +60 -0
  132. package/dist/package-build/build-package.js +312 -0
  133. package/dist/package-build/build-package.test.d.ts +1 -0
  134. package/dist/package-build/build-package.test.js +204 -0
  135. package/dist/package-build/cli.d.ts +7 -0
  136. package/dist/package-build/cli.js +218 -0
  137. package/dist/package-build/contract-add.d.ts +35 -0
  138. package/dist/package-build/contract-add.js +97 -0
  139. package/dist/package-build/contract-add.test.d.ts +1 -0
  140. package/dist/package-build/contract-add.test.js +467 -0
  141. package/dist/package-build/contract-source.d.ts +59 -0
  142. package/dist/package-build/contract-source.js +471 -0
  143. package/dist/package-build/freeze-contracts.d.ts +56 -0
  144. package/dist/package-build/freeze-contracts.js +198 -0
  145. package/dist/package-build/freeze-contracts.test.d.ts +1 -0
  146. package/dist/package-build/freeze-contracts.test.js +355 -0
  147. package/dist/package-installer/package-creator.d.ts +4 -0
  148. package/dist/package-installer/package-creator.js +57 -16
  149. package/dist/package-installer/package-creator.test.js +86 -0
  150. package/dist/package-loader/contract-members.d.ts +53 -0
  151. package/dist/package-loader/contract-members.js +31 -0
  152. package/dist/package-loader/contract-package-loader.js +5 -1
  153. package/dist/package-loader/contract-package-loader.test.js +11 -0
  154. package/dist/package-loader/host-authority-loading.test.js +9 -5
  155. package/dist/package-loader/index.d.ts +1 -0
  156. package/dist/package-loader/index.js +1 -0
  157. package/dist/package-loader/isolated-artifact.d.ts +80 -17
  158. package/dist/package-loader/isolated-artifact.js +257 -51
  159. package/dist/package-loader/isolated-artifact.test.js +294 -21
  160. package/dist/package-loader/isolated-runtime.d.ts +22 -7
  161. package/dist/package-loader/isolated-table-gateway.js +30 -11
  162. package/dist/package-loader/isolated-table-gateway.test.js +243 -0
  163. package/dist/package-loader/package-loader.d.ts +8 -1
  164. package/dist/package-loader/package-loader.js +39 -20
  165. package/dist/package-loader/package-loader.test.js +47 -0
  166. package/dist/peer-id.d.ts +25 -0
  167. package/dist/peer-id.js +99 -0
  168. package/dist/serial-json.compat.test.d.ts +1 -0
  169. package/dist/serial-json.compat.test.js +369 -0
  170. package/dist/serial-json.d.ts +41 -5
  171. package/dist/serial-json.js +216 -157
  172. package/dist/serial-json.oracle.d.ts +21 -0
  173. package/dist/serial-json.oracle.js +222 -0
  174. package/dist/serial-json.test.js +315 -0
  175. package/dist/testing/index.d.ts +4 -0
  176. package/dist/testing/index.js +8 -0
  177. package/dist/testing/mock-host-contract.d.ts +123 -0
  178. package/dist/testing/mock-host-contract.js +434 -0
  179. package/dist/testing/mock-host-contract.test.d.ts +1 -0
  180. package/dist/testing/mock-host-contract.test.js +782 -0
  181. package/dist/types/field-type.d.ts +35 -18
  182. package/dist/types/field-type.js +4 -1
  183. package/dist/types/zod-types.d.ts +9 -0
  184. package/dist/types/zod-types.js +8 -2
  185. package/dist/utils.d.ts +22 -25
  186. package/dist/utils.js +45 -92
  187. package/dist/utils.test.js +36 -0
  188. package/package.json +9 -2
  189. package/testing/package.json +4 -0
@@ -62,6 +62,321 @@ describe("serial-json", () => {
62
62
  expect(deserialized.bufferData).toEqual(originalBuffer);
63
63
  });
64
64
  });
65
+ // Signatures sign toJSON output (`canonicalJSONString` in keys.ts), so these strings are frozen.
66
+ describe("encoded form (pinned)", () => {
67
+ it("encodes each extended type as a sentinel string", () => {
68
+ const value = {
69
+ d: new Date("2023-01-01T00:00:00.000Z"),
70
+ u8: new Uint8Array([1, 2, 3]),
71
+ buf: Buffer.from([1, 2, 3]),
72
+ u: undefined,
73
+ nan: NaN,
74
+ inf: Infinity,
75
+ re: /a+b/gi,
76
+ n: null,
77
+ t: true,
78
+ s: "x",
79
+ num: 1.5,
80
+ };
81
+ const encoded = (0, serial_json_1.toJSONString)(value);
82
+ expect(encoded).toBe('{"d":"__DATE 2023-01-01T00:00:00.000Z","u8":"__UINT8ARRAY AQID","buf":"__BUFFER AQID",' +
83
+ '"u":"__UNDEFINED","nan":"__NAN","inf":"__INFINITY","re":"__REGEXP /a+b/gi","n":null,' +
84
+ '"t":true,"s":"x","num":1.5}');
85
+ const decoded = (0, serial_json_1.fromJSONString)(encoded);
86
+ expect(decoded.d).toEqual(value.d);
87
+ expect(decoded.u8).toBeInstanceOf(Uint8Array);
88
+ expect(Buffer.isBuffer(decoded.u8)).toBe(false);
89
+ expect(Buffer.isBuffer(decoded.buf)).toBe(true);
90
+ expect("u" in decoded).toBe(true);
91
+ expect(decoded.u).toBeUndefined();
92
+ expect(decoded.nan).toBeNaN();
93
+ expect(decoded.inf).toBe(Infinity);
94
+ expect(decoded.re).toEqual(/a+b/gi);
95
+ expect(decoded).toMatchObject({ n: null, t: true, s: "x", num: 1.5 });
96
+ });
97
+ it("encodes an Error as its stack and a function as one-way source text", () => {
98
+ const encoded = (0, serial_json_1.toJSON)({
99
+ e: new Error("boom"),
100
+ f: function named() {
101
+ return 1;
102
+ },
103
+ });
104
+ expect(encoded.e).toMatch(/^__ERROR Error: boom\n/);
105
+ expect(encoded.f).toMatch(/^__FUNCTION function named\(\)/);
106
+ const decoded = (0, serial_json_1.fromJSON)(encoded);
107
+ expect(decoded.e).toBeInstanceOf(Error);
108
+ expect(decoded.e.stack).toBe(encoded.e.substring(8));
109
+ expect(decoded.f).toBe(encoded.f);
110
+ });
111
+ it("tags the first copy of a shared object and points the others at it", () => {
112
+ const shared = { s: 1 };
113
+ const encoded = (0, serial_json_1.toJSONString)({ a: shared, b: shared, c: [shared] });
114
+ expect(encoded).toBe('{"a":{"s":1,"__this_ref":"__duplicate_ref_obj_2"},"b":"__duplicate_ref_obj_2",' +
115
+ '"c":["__duplicate_ref_obj_2"]}');
116
+ const decoded = (0, serial_json_1.fromJSONString)(encoded);
117
+ expect(decoded.a).toEqual({ s: 1 });
118
+ expect(decoded.b).toBe(decoded.a);
119
+ expect(decoded.c[0]).toBe(decoded.a);
120
+ });
121
+ it("tags a shared array with an extra first element", () => {
122
+ const shared = ["a", "b"];
123
+ const encoded = (0, serial_json_1.toJSONString)({ x: shared, y: shared });
124
+ expect(encoded).toBe('{"x":["__this_ref:__duplicate_ref_ary_2","a","b"],"y":"__duplicate_ref_ary_2"}');
125
+ const decoded = (0, serial_json_1.fromJSONString)(encoded);
126
+ expect(decoded.x).toEqual(["a", "b"]);
127
+ expect(decoded.y).toBe(decoded.x);
128
+ });
129
+ it("encodes cycles, placing the tag wherever the copy has got to", () => {
130
+ const obj = { n: 1 };
131
+ obj.self = obj;
132
+ const list = [1];
133
+ list.push(list);
134
+ const root = { child: { grand: {} } };
135
+ root.child.grand.up = root;
136
+ expect((0, serial_json_1.toJSONString)(obj)).toBe('{"n":1,"__this_ref":"__duplicate_ref_obj_1","self":"__duplicate_ref_obj_1"}');
137
+ expect((0, serial_json_1.toJSONString)(list)).toBe('["__this_ref:__duplicate_ref_ary_1",1,"__duplicate_ref_ary_1"]');
138
+ expect((0, serial_json_1.toJSONString)(root)).toBe('{"__this_ref":"__duplicate_ref_obj_1","child":{"grand":{"up":"__duplicate_ref_obj_1"}}}');
139
+ const decodedObj = (0, serial_json_1.fromJSONString)((0, serial_json_1.toJSONString)(obj));
140
+ expect(decodedObj.self).toBe(decodedObj);
141
+ expect(decodedObj.n).toBe(1);
142
+ const decodedList = (0, serial_json_1.fromJSONString)((0, serial_json_1.toJSONString)(list));
143
+ expect(decodedList).toHaveLength(2);
144
+ expect(decodedList[1]).toBe(decodedList);
145
+ const decodedRoot = (0, serial_json_1.fromJSONString)((0, serial_json_1.toJSONString)(root));
146
+ expect(decodedRoot.child.grand.up).toBe(decodedRoot);
147
+ });
148
+ it("resolves a reference that appears before its target", () => {
149
+ const decoded = (0, serial_json_1.fromJSONString)('{"b":"__duplicate_ref_obj_2","a":{"k":1,"__this_ref":"__duplicate_ref_obj_2"}}');
150
+ expect(decoded.a).toEqual({ k: 1 });
151
+ expect(decoded.b).toBe(decoded.a);
152
+ });
153
+ it("escapes keys that start with $", () => {
154
+ const encoded = (0, serial_json_1.toJSONString)({ $a: 1, $: 2, plain: { $nested: 3 } });
155
+ expect(encoded).toBe('{"__DOLLAR_a":1,"__DOLLAR_":2,"plain":{"__DOLLAR_nested":3}}');
156
+ expect((0, serial_json_1.fromJSONString)(encoded)).toEqual({ $a: 1, $: 2, plain: { $nested: 3 } });
157
+ });
158
+ it("leaves top-level primitives alone", () => {
159
+ expect((0, serial_json_1.toJSON)(NaN)).toBeNaN();
160
+ expect((0, serial_json_1.toJSONString)(NaN)).toBe("null");
161
+ expect((0, serial_json_1.toJSON)(undefined)).toBeUndefined();
162
+ expect((0, serial_json_1.toJSONString)(undefined)).toBeUndefined();
163
+ expect((0, serial_json_1.toJSON)("__UNDEFINED")).toBe("__UNDEFINED");
164
+ expect((0, serial_json_1.toJSON)(5)).toBe(5);
165
+ expect((0, serial_json_1.toJSON)(new Date(0))).toBe("__DATE 1970-01-01T00:00:00.000Z");
166
+ expect((0, serial_json_1.fromJSON)("__DATE 1970-01-01T00:00:00.000Z")).toEqual(new Date(0));
167
+ });
168
+ });
169
+ // Behavior that is wrong or lossy today. Each test changes when its gap is fixed.
170
+ describe("known gaps (pinned until fixed)", () => {
171
+ it("decodes ordinary strings that look like markers as the marked value", () => {
172
+ // The orphan marker warns; restore so the spy doesn't leak into later tests.
173
+ const warn = jest.spyOn(console, "warn").mockImplementation(() => undefined);
174
+ const decoded = (0, serial_json_1.fromJSON)((0, serial_json_1.toJSON)({
175
+ u: "__UNDEFINED",
176
+ n: "__NAN",
177
+ d: "__DATE tomorrow",
178
+ e: "__ERROR oops",
179
+ r: "__duplicate_ref_obj_9",
180
+ }));
181
+ warn.mockRestore();
182
+ expect(decoded.u).toBeUndefined();
183
+ expect(decoded.n).toBeNaN();
184
+ expect(decoded.d).toBeInstanceOf(Date);
185
+ expect(decoded.d.getTime()).toBeNaN();
186
+ expect(decoded.e).toBeInstanceOf(Error);
187
+ expect(decoded.r).toEqual({});
188
+ });
189
+ it("turns a __DOLLAR_ key into a $ key", () => {
190
+ expect((0, serial_json_1.fromJSONString)((0, serial_json_1.toJSONString)({ __DOLLAR_b: 2 }))).toEqual({ $b: 2 });
191
+ });
192
+ it("treats a __this_ref key as a shared-reference tag unless its value is falsy", () => {
193
+ expect((0, serial_json_1.fromJSONString)((0, serial_json_1.toJSONString)({ __this_ref: "mine", a: 1 }))).toEqual({ a: 1 });
194
+ expect((0, serial_json_1.fromJSONString)((0, serial_json_1.toJSONString)({ __this_ref: "", a: 1 }))).toEqual({
195
+ __this_ref: "",
196
+ a: 1,
197
+ });
198
+ });
199
+ it("loses -Infinity and -0 in JSON text", () => {
200
+ expect((0, serial_json_1.toJSONString)({ a: -Infinity, z: -0 })).toBe('{"a":null,"z":0}');
201
+ });
202
+ it("stores Map, Set and class instances as plain objects", () => {
203
+ class Point {
204
+ x = 1;
205
+ }
206
+ const encoded = (0, serial_json_1.toJSONString)({ m: new Map([[1, 2]]), s: new Set([1]), p: new Point() });
207
+ expect(encoded).toBe('{"m":{},"s":{},"p":{"x":1}}');
208
+ expect(Object.getPrototypeOf((0, serial_json_1.fromJSONString)(encoded).p)).toBe(Object.prototype);
209
+ });
210
+ it("drops symbols and throws on BigInt and invalid dates", () => {
211
+ expect((0, serial_json_1.toJSONString)({ s: Symbol("x"), a: [Symbol("y")] })).toBe('{"a":[null]}');
212
+ expect(() => (0, serial_json_1.toJSONString)({ b: BigInt(1) })).toThrow(TypeError);
213
+ expect(() => (0, serial_json_1.toJSONString)({ d: new Date(Number.NaN) })).toThrow(RangeError);
214
+ });
215
+ it("throws SyntaxError on a malformed regular expression", () => {
216
+ // working/tools/foreman/test/host.test.mjs relies on this error.
217
+ expect(() => (0, serial_json_1.fromJSON)("__REGEXP /[/")).toThrow(SyntaxError);
218
+ });
219
+ });
220
+ // Intended differences from the frozen oracle (serial-json.compat.test.ts covers the rest).
221
+ describe("decoding changes since the oracle", () => {
222
+ let warn;
223
+ beforeEach(() => {
224
+ warn = jest.spyOn(console, "warn").mockImplementation(() => undefined);
225
+ });
226
+ afterEach(() => {
227
+ warn.mockRestore();
228
+ });
229
+ it("returns values that are already decoded as they are", () => {
230
+ const value = {
231
+ bytes: new Uint8Array([1, 2]),
232
+ buffer: Buffer.from([3]),
233
+ error: new Error("boom"),
234
+ pattern: /x/g,
235
+ when: new Date(0),
236
+ };
237
+ const decoded = (0, serial_json_1.fromJSON)({ ...value, encoded: "__DATE 1970-01-01T00:00:00.000Z" });
238
+ for (const key of Object.keys(value)) {
239
+ expect(decoded[key]).toBe(value[key]);
240
+ }
241
+ expect(decoded.encoded).toEqual(new Date(0));
242
+ });
243
+ it("builds new arrays and objects and leaves the input untouched", () => {
244
+ const input = Object.freeze({
245
+ list: Object.freeze(["__this_ref:__duplicate_ref_ary_2", 1]),
246
+ tagged: Object.freeze({ __this_ref: "__duplicate_ref_obj_3", $: Object.freeze({}) }),
247
+ again: "__duplicate_ref_ary_2",
248
+ });
249
+ const decoded = (0, serial_json_1.fromJSON)(input);
250
+ expect(decoded).toEqual({ list: [1], tagged: { $: {} }, again: [1] });
251
+ expect(decoded.again).toBe(decoded.list);
252
+ expect(decoded.list).not.toBe(input.list);
253
+ expect(decoded.tagged).not.toBe(input.tagged);
254
+ expect(decoded.tagged.$).not.toBe(input.tagged.$);
255
+ });
256
+ it("copies untagged nested values instead of sharing live change values", () => {
257
+ const input = { nested: { list: [{ value: 1 }] } };
258
+ const decoded = (0, serial_json_1.fromJSON)(input);
259
+ decoded.nested.list[0].value = 2;
260
+ decoded.nested.list.push({});
261
+ expect(input).toEqual({ nested: { list: [{ value: 1 }] } });
262
+ });
263
+ it("does not let an object fill an array target, or an array an object target", () => {
264
+ // The oracle shared them, so `{"length":4e9}` under an array marker decoded to a huge
265
+ // array that hung whatever re-encoded or cloned it, and `{"length":-1}` threw.
266
+ const decoded = (0, serial_json_1.fromJSONString)('["__duplicate_ref_ary_1",{"__this_ref":"__duplicate_ref_ary_1","length":4000000000,"a":1},' +
267
+ '["__this_ref:__duplicate_ref_ary_1","last"],["__this_ref:__duplicate_ref_obj_1",1],' +
268
+ '{"__this_ref":"__duplicate_ref_obj_1","b":2}]');
269
+ expect(decoded[0]).toBe(decoded[2]);
270
+ expect(decoded[0]).toEqual(["last"]);
271
+ expect(decoded[1]).toEqual({ length: 4000000000, a: 1 });
272
+ expect(decoded[3]).toEqual([1]);
273
+ expect(decoded[4]).toEqual({ b: 2 });
274
+ expect(warn).not.toHaveBeenCalled();
275
+ expect((0, serial_json_1.fromJSONString)('["__duplicate_ref_ary_2",{"__this_ref":"__duplicate_ref_ary_2","length":-1}]')).toEqual([[], { length: -1 }]);
276
+ expect(warn).toHaveBeenCalledTimes(1);
277
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("__duplicate_ref_ary_2"));
278
+ });
279
+ it("warns about an object marker with only a rejected array tag", () => {
280
+ const marker = "__duplicate_ref_obj_rejected_array";
281
+ expect((0, serial_json_1.fromJSON)([marker, [`__this_ref:${marker}`, 1]])).toEqual([{}, [1]]);
282
+ (0, serial_json_1.fromJSON)([marker, [`__this_ref:${marker}`, 2]]);
283
+ expect(warn).toHaveBeenCalledTimes(1);
284
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(marker));
285
+ });
286
+ it("accepts a later matching tag after rejecting a conflicting tag", () => {
287
+ const marker = "__duplicate_ref_obj_later_target";
288
+ const decoded = (0, serial_json_1.fromJSON)([
289
+ marker,
290
+ [`__this_ref:${marker}`, 1],
291
+ { __this_ref: marker, value: 2 },
292
+ ]);
293
+ expect(decoded).toEqual([{ value: 2 }, [1], { value: 2 }]);
294
+ expect(decoded[0]).toBe(decoded[2]);
295
+ expect(warn).not.toHaveBeenCalled();
296
+ });
297
+ it("leaves the browser-only __HTML and __WINDOW sentinels as strings", () => {
298
+ expect((0, serial_json_1.fromJSON)({ html: "__HTML <b>x</b>", win: "__WINDOW" })).toEqual({
299
+ html: "__HTML <b>x</b>",
300
+ win: "__WINDOW",
301
+ });
302
+ });
303
+ it("warns once, in one string, about a marker with no target", () => {
304
+ const marker = "__duplicate_ref_obj_9001";
305
+ expect((0, serial_json_1.fromJSON)({ a: marker, b: { __this_ref: "__duplicate_ref_obj_9002" } })).toEqual({
306
+ a: {},
307
+ b: {},
308
+ });
309
+ (0, serial_json_1.fromJSON)({ again: marker });
310
+ expect(warn).toHaveBeenCalledTimes(1);
311
+ expect(warn.mock.calls[0]).toHaveLength(1);
312
+ expect(warn.mock.calls[0][0]).toContain(marker);
313
+ expect(warn.mock.calls[0][0]).not.toContain("9002");
314
+ });
315
+ it("does not warn about a marker whose target comes later", () => {
316
+ (0, serial_json_1.fromJSON)({ b: "__duplicate_ref_obj_9003", a: { __this_ref: "__duplicate_ref_obj_9003" } });
317
+ expect(warn).not.toHaveBeenCalled();
318
+ });
319
+ it("caps warnings at 100 distinct markers across calls", () => {
320
+ jest.isolateModules(() => {
321
+ const isolated = require("./serial-json");
322
+ for (let i = 0; i < 110; i++) {
323
+ const marker = `__duplicate_ref_obj_cap_${i}`;
324
+ isolated.fromJSON([marker, marker]);
325
+ isolated.fromJSON(marker);
326
+ }
327
+ expect(warn).toHaveBeenCalledTimes(100);
328
+ expect(warn.mock.calls.every((args) => args.length === 1 && typeof args[0] === "string")).toBe(true);
329
+ });
330
+ });
331
+ it("can decode its warning through the log pipeline without warning again", () => {
332
+ warn.mockImplementation((message) => {
333
+ expect((0, serial_json_1.fromJSONString)((0, serial_json_1.toJSONString)({ message }))).toEqual({ message });
334
+ });
335
+ (0, serial_json_1.fromJSON)("__duplicate_ref_obj_log_pipeline");
336
+ expect(warn).toHaveBeenCalledTimes(1);
337
+ });
338
+ });
339
+ describe("untrusted input", () => {
340
+ afterEach(() => {
341
+ // A failing case must not leak a polluted prototype into later tests.
342
+ delete Object.prototype.polluted;
343
+ delete Object.prototype[0];
344
+ delete Object.polluted;
345
+ });
346
+ it("does not resolve an object's shared-reference tag to Object.prototype", () => {
347
+ const decoded = (0, serial_json_1.fromJSONString)('{"__this_ref":"__proto__","polluted":"yes"}');
348
+ expect({}.polluted).toBeUndefined();
349
+ expect(decoded).toEqual({ polluted: "yes" });
350
+ });
351
+ it("does not resolve an array's shared-reference tag to Object.prototype", () => {
352
+ const decoded = (0, serial_json_1.fromJSONString)('["__this_ref:__proto__","yes"]');
353
+ expect({}[0]).toBeUndefined();
354
+ expect(decoded).toEqual(["yes"]);
355
+ });
356
+ it("does not resolve a shared-reference tag to the Object constructor", () => {
357
+ const decoded = (0, serial_json_1.fromJSONString)('{"__this_ref":"constructor","polluted":"yes"}');
358
+ expect(Object.polluted).toBeUndefined();
359
+ expect(decoded).toEqual({ polluted: "yes" });
360
+ });
361
+ it("keeps constructor and prototype properties local to the decoded value", () => {
362
+ const decoded = (0, serial_json_1.fromJSONString)('{"constructor":{"prototype":{"polluted":"yes"}},"prototype":{"polluted":"yes"}}');
363
+ expect({}.polluted).toBeUndefined();
364
+ expect(Object.polluted).toBeUndefined();
365
+ expect(decoded.constructor.prototype.polluted).toBe("yes");
366
+ });
367
+ it("ignores a shared-reference tag that is an object instead of coercing it", () => {
368
+ const decoded = (0, serial_json_1.fromJSONString)('{"a":{"__this_ref":{"toString":"x"},"k":1},"b":{"__this_ref":{},"k":2}}');
369
+ expect(decoded).toEqual({ a: { k: 1 }, b: { k: 2 } });
370
+ expect(decoded.a).not.toBe(decoded.b);
371
+ });
372
+ it("drops __proto__ keys instead of setting the decoded object's prototype", () => {
373
+ const decoded = (0, serial_json_1.fromJSONString)('{"__proto__":{"polluted":"yes"},"b":{"__proto__":[]}}');
374
+ expect(Object.getPrototypeOf(decoded)).toBe(Object.prototype);
375
+ expect(Object.getPrototypeOf(decoded.b)).toBe(Object.prototype);
376
+ expect(decoded.polluted).toBeUndefined();
377
+ expect(Object.keys(decoded)).toEqual(["b"]);
378
+ });
379
+ });
65
380
  describe("existing functionality", () => {
66
381
  it("should still handle other special types", () => {
67
382
  const testObj = {
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Test helpers for package UIs: `@peers-app/peers-sdk/testing`. Not for UI or provider bundles.
3
+ */
4
+ export { type IMockHostCall, type IMockHostContract, type IMockHostContractOptions, type IMockHostTable, mockHostContract, } from "./mock-host-contract";
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mockHostContract = void 0;
4
+ /**
5
+ * Test helpers for package UIs: `@peers-app/peers-sdk/testing`. Not for UI or provider bundles.
6
+ */
7
+ var mock_host_contract_1 = require("./mock-host-contract");
8
+ Object.defineProperty(exports, "mockHostContract", { enumerable: true, get: function () { return mock_host_contract_1.mockHostContract; } });
@@ -0,0 +1,123 @@
1
+ import type { ContractEventPayloadsOf, ContractObservableValuesOf, ContractTableRowsOf } from "../define/contract-ref";
2
+ import { type IContractDeclaration } from "../define/declare-contract";
3
+ import { type IContractMembers, type IPackageContract } from "../define/define-package";
4
+ import type { IPackageTableHandle } from "../define/table";
5
+ import type { IPackageToolDeclaration } from "../define/tool";
6
+ import { type Observable } from "../observable";
7
+ type AnyContract = IPackageContract<any, any, any, any, any, any> | IContractDeclaration<any, any, any, any, any, any>;
8
+ /** A contract's members: the contract itself, or a declaration's. */
9
+ type MembersOf<C> = C extends {
10
+ readonly declaration: infer D;
11
+ } ? D : C;
12
+ type Row = Record<string, any>;
13
+ /** A fake for one tool: it gets the input as the tool's schema parses it. */
14
+ type ToolFake<T> = T extends IPackageToolDeclaration<any, infer O, any, infer P> ? (input: P) => O | Promise<O> : never;
15
+ type ToolFakes<C> = MembersOf<C> extends IContractMembers<any, any, any, infer Tools, any, any> ? {
16
+ readonly [T in Tools[number] as T["definition"]["name"]]?: ToolFake<T>;
17
+ } : never;
18
+ /** One call a UI made to the mock host, as `onCall` sees it. */
19
+ export interface IMockHostCall {
20
+ /** Which kind of member the call is for. */
21
+ readonly member: "tool" | "table" | "event" | "observable";
22
+ /** The member's name. */
23
+ readonly name: string;
24
+ /** `run` for a tool; the method for a table (`list`, `save`, ...); `subscribe` and the rest. */
25
+ readonly operation: string;
26
+ /** The call's arguments. */
27
+ readonly args: readonly unknown[];
28
+ }
29
+ /** What {@link mockHostContract} starts with. */
30
+ export interface IMockHostContractOptions<C> {
31
+ /**
32
+ * Fakes for the contract's tools, by name. Each gets the input parsed with the tool's schema,
33
+ * as the host does. Calling a tool without a fake fails, and so does calling a private one.
34
+ */
35
+ readonly tools?: ToolFakes<C>;
36
+ /** Starting complete rows, validated against the manifest's fields, without package defaults. */
37
+ readonly tables?: {
38
+ readonly [K in keyof ContractTableRowsOf<MembersOf<C>>]?: readonly ContractTableRowsOf<MembersOf<C>>[K][];
39
+ };
40
+ /**
41
+ * Starting values for the contract's observables, by name. Others start as the host serves
42
+ * them: a stored observable's default, or the value an in-memory one's source holds now.
43
+ */
44
+ readonly observables?: {
45
+ readonly [K in keyof ContractObservableValuesOf<MembersOf<C>>]?: ContractObservableValuesOf<MembersOf<C>>[K];
46
+ };
47
+ /** The data context the UI's calls are scoped to. Defaults to a new id. */
48
+ readonly dataContextId?: string;
49
+ /**
50
+ * Runs before the host answers each call (subscriptions included). Return a promise to delay
51
+ * the answer, or throw to fail the call.
52
+ */
53
+ readonly onCall?: (call: IMockHostCall) => void | Promise<void>;
54
+ }
55
+ /** The host's side of one table: its rows, and writes that reach subscribed UIs. */
56
+ export interface IMockHostTable<R extends Row> extends IPackageTableHandle<R> {
57
+ /** A copy of the rows, in the order they were added. */
58
+ readonly rows: R[];
59
+ }
60
+ /** A running mock host. Call `dispose()` when the test ends. */
61
+ export interface IMockHostContract<C> {
62
+ /** The host's tables: change rows as the provider would, and read what the UI saved. */
63
+ readonly tables: {
64
+ readonly [K in keyof ContractTableRowsOf<MembersOf<C>>]: IMockHostTable<ContractTableRowsOf<MembersOf<C>>[K]>;
65
+ };
66
+ /**
67
+ * The host's observables: set one to push a value (as the provider, unchecked), or read what
68
+ * the UI wrote. UI writes must fit the manifest's value type, then any declared schema.
69
+ */
70
+ readonly observables: {
71
+ readonly [K in keyof ContractObservableValuesOf<MembersOf<C>>]: Observable<ContractObservableValuesOf<MembersOf<C>>[K] | undefined>;
72
+ };
73
+ /** The contract's events: emit one to subscribed UIs. */
74
+ readonly events: {
75
+ readonly [K in keyof ContractEventPayloadsOf<MembersOf<C>>]: {
76
+ emit(payload: ContractEventPayloadsOf<MembersOf<C>>[K]): Promise<void>;
77
+ };
78
+ };
79
+ /**
80
+ * Disconnect the host and restore the default data context. Calls still waiting for an answer
81
+ * reject. Idempotent.
82
+ */
83
+ dispose(): void;
84
+ }
85
+ /**
86
+ * Stand in for the local host in a UI test: `hostContract` clients for this contract (including
87
+ * a package's shared `news`-style client) connect to it, with no signed-in user and no
88
+ * provider. Tables hold rows in memory and send `dataChanged`; tools answer with fakes.
89
+ *
90
+ * ```ts
91
+ * const host = mockHostContract(News, {
92
+ * tables: { Headlines: [{ headlineId: newid(), title: "Hello", ... }] },
93
+ * tools: { refresh: async () => ({ errors: [] }) },
94
+ * });
95
+ * // render the UI; it reads and writes through `news` as usual
96
+ * await host.tables.Headlines.save(nextHeadline); // the UI sees the change
97
+ * host.dispose();
98
+ * ```
99
+ *
100
+ * A UI's table calls go through the table's class (`PackageTable` or the package's subclass),
101
+ * as on the host, with a test context: its `callOwnedTable` reaches the mock's rows, and its
102
+ * other calls fail. So a save runs the class's overrides and the schema, defaults included,
103
+ * and each change reaches subscribers through the class's `dataChanged`. Writes through
104
+ * `host.tables` are storage writes, with no class or schema in between; the class still
105
+ * filters the changes they send.
106
+ *
107
+ * Table filters are equality (`{ feedId }`) and `$in` (`{ status: { $in: ["a", "b"] } }`); a
108
+ * filter with other operators (`$or`, `$matchWords`, ...) or a text search fails; test those
109
+ * reads against a real host.
110
+ * `onCall` can delay or fail calls, but cannot replace their answers. Paging and `sortBy` work.
111
+ * Stored rows validate the manifest's fields, as host storage does. UI
112
+ * writes to an observable must fit its manifest value type, then any declared schema. Tool
113
+ * access levels aren't checked (UI calls act as the signed-in user); private tools refuse UI
114
+ * calls, as on the host. Disposing rejects calls still waiting for an answer. One mock host
115
+ * runs at a time.
116
+ *
117
+ * @param contract - The contract value from `defineContract` (tests can import it; UI code
118
+ * imports only its type), or a declaration from `declareContract`, whose observables start
119
+ * empty unless `observables` gives them values.
120
+ * @param options - Tool fakes, starting rows and values, data context, and a call hook.
121
+ */
122
+ export declare function mockHostContract<C extends AnyContract>(contract: C, options?: IMockHostContractOptions<C>): IMockHostContract<C>;
123
+ export {};