-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathheap-classes.test.js
More file actions
541 lines (498 loc) · 15.3 KB
/
heap-classes.test.js
File metadata and controls
541 lines (498 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
// @ts-check
import test from '@endo/ses-ava/test.js';
import harden from '@endo/harden';
import { getInterfaceMethodKeys, M } from '@endo/patterns';
import {
GET_INTERFACE_GUARD,
defineExoClass,
defineExoClassKit,
makeExo,
} from '../index.js';
const NoExtraI = M.interface('NoExtra', {
foo: M.call().returns(),
});
test('what happens with extra arguments', t => {
const exo = makeExo('NoExtraArgs', NoExtraI, {
foo(x) {
t.is(x, undefined);
},
});
// TS sees foo(x: any) from the impl, so this is valid to TS. Runtime guard rejects it.
t.throws(() => exo.foo('an extra arg'), {
message:
'"In \\"foo\\" method of (NoExtraArgs)" accepts at most 0 arguments, not 1: ["an extra arg"]',
});
});
const OptionalArrayI = M.interface('OptionalArray', {
foo: M.callWhen().optional(M.arrayOf(M.any())).returns(),
});
test('callWhen-guarded method called without optional array argument', async t => {
const exo = makeExo('WithNoOption', OptionalArrayI, {
async foo(arr) {
t.is(arr, undefined);
},
});
// @ts-expect-error TS infers foo(arr) as required from the impl, but guard makes it optional at runtime
await t.notThrowsAsync(() => exo.foo());
});
const UpCounterI = M.interface('UpCounter', {
incr: M.call()
// TODO M.number() should not be needed to get a better error message
.optional(M.and(M.number(), M.gte(0)))
.returns(M.number()),
});
const DownCounterI = M.interface('DownCounter', {
decr: M.call()
// TODO M.number() should not be needed to get a better error message
.optional(M.and(M.number(), M.gte(0)))
.returns(M.number()),
});
test('test defineExoClass', t => {
const makeUpCounter = defineExoClass(
'UpCounter',
UpCounterI,
/** @param {number} [x] */
(x = 0) => ({ x }),
{
incr(y = 1) {
const { state } = this;
state.x += y;
return state.x;
},
},
);
const upCounter = makeUpCounter(3);
t.is(upCounter.incr(5), 8);
t.is(upCounter.incr(1), 9);
t.throws(() => upCounter.incr(-3), {
message: 'In "incr" method of (UpCounter): arg 0?: -3 - Must be >= 0',
});
// @ts-expect-error bad arg
t.throws(() => upCounter.incr('foo'), {
message:
'In "incr" method of (UpCounter): arg 0?: string "foo" - Must be a number',
});
t.deepEqual(upCounter[GET_INTERFACE_GUARD]?.(), UpCounterI);
t.deepEqual(getInterfaceMethodKeys(UpCounterI), ['incr']);
const FooI = M.interface('Foo', {
m: M.call().returns(),
m2: M.call(M.boolean()).returns(),
});
t.deepEqual(getInterfaceMethodKeys(FooI), ['m', 'm2']);
const makeFoo = defineExoClass('Foo', FooI, () => ({}), {
m() {},
m2() {},
});
const foo = makeFoo();
t.deepEqual(foo[GET_INTERFACE_GUARD]?.(), FooI);
// @ts-expect-error intentional for test
t.throws(() => foo.m2('invalid arg'), {
message:
'In "m2" method of (Foo): arg 0: string "invalid arg" - Must be a boolean',
});
});
test('test defineExoClassKit', t => {
const makeCounterKit = defineExoClassKit(
'Counter',
{ up: UpCounterI, down: DownCounterI },
/** @param {number} [x] */
(x = 0) => ({ x }),
{
up: {
incr(y = 1) {
// @ts-expect-error methods not on this
this.incr;
// @ts-expect-error facets not on this
this.up;
assert(this.facets.up.incr, 'facets.up.incr exists');
const { state } = this;
state.x += y;
return state.x;
},
},
down: {
decr(y = 1) {
const { state } = this;
state.x -= y;
return state.x;
},
},
},
);
const { up: upCounter, down: downCounter } = makeCounterKit(3);
t.is(upCounter.incr(5), 8);
t.is(downCounter.decr(), 7);
t.is(upCounter.incr(3), 10);
t.throws(() => upCounter.incr(-3), {
message: 'In "incr" method of (Counter up): arg 0?: -3 - Must be >= 0',
});
// @ts-expect-error the type violation is what we're testing
t.throws(() => downCounter.decr('foo'), {
message:
'In "decr" method of (Counter down): arg 0?: string "foo" - Must be a number',
});
// TS limitation: Guarded<M> extends Methods which has an index signature
// (Record<PropertyKey, CallableFunction>), so upCounter.decr is not a
// type error even though 'decr' is only on the down facet.
t.throws(() => /** @type {any} */ (upCounter).decr(3), {
message: 'upCounter.decr is not a function',
});
t.deepEqual(upCounter[GET_INTERFACE_GUARD]?.(), UpCounterI);
t.deepEqual(downCounter[GET_INTERFACE_GUARD]?.(), DownCounterI);
});
test('test makeExo', t => {
let x = 3;
const upCounter = makeExo('upCounter', UpCounterI, {
incr(y = 1) {
x += y;
return x;
},
});
t.is(upCounter.incr(5), 8);
t.is(upCounter.incr(1), 9);
t.throws(() => upCounter.incr(-3), {
message: 'In "incr" method of (upCounter): arg 0?: -3 - Must be >= 0',
});
// @ts-expect-error deliberately bad arg for testing
t.throws(() => upCounter.incr('foo'), {
message:
'In "incr" method of (upCounter): arg 0?: string "foo" - Must be a number',
});
t.deepEqual(upCounter[GET_INTERFACE_GUARD]?.(), UpCounterI);
});
// For code sharing with defineKind which does not support an interface
test('missing interface', t => {
t.notThrows(() =>
makeExo('greeter', undefined, {
sayHello() {
return 'hello';
},
}),
);
const greeterMaker = makeExo('greeterMaker', undefined, {
makeSayHello() {
const helloFunc = () => 'hello';
return harden(helloFunc);
},
});
t.throws(() => greeterMaker.makeSayHello(), {
message:
'In "makeSayHello" method of (greeterMaker): result: Remotables must be explicitly declared: "[Function helloFunc]"',
});
t.is(greeterMaker[GET_INTERFACE_GUARD]?.(), undefined);
});
const SloppyGreeterI = M.interface('greeter', {}, { sloppy: true });
const EmptyGreeterI = M.interface('greeter', {}, { sloppy: false });
test('sloppy option', t => {
const greeter = makeExo('greeter', SloppyGreeterI, {
sayHello() {
return 'hello';
},
});
t.is(greeter.sayHello(), 'hello');
t.deepEqual(greeter[GET_INTERFACE_GUARD]?.(), SloppyGreeterI);
t.throws(
() =>
makeExo(
'greeter',
EmptyGreeterI,
{
sayHello() {
return 'hello';
},
},
),
{ message: 'methods ["sayHello"] not guarded by "greeter"' },
);
});
const makeBehavior = () => ({
behavior() {
return 'something';
},
});
const PassableGreeterI = M.interface(
'greeter',
{},
{ defaultGuards: 'passable' },
);
test('passable guards', t => {
const greeter = makeExo('greeter', PassableGreeterI, {
sayHello(immutabe) {
t.true(Object.isFrozen(immutabe));
return 'hello';
},
});
const mutable = {};
t.is(greeter.sayHello(mutable), 'hello', `passableGreeter can sayHello`);
t.true(Object.isFrozen(mutable), `mutable is frozen`);
t.throws(() => greeter.sayHello(makeBehavior()), {
message:
/In "sayHello" method of \(greeter\): Remotables must be explicitly declared/,
});
});
const RawGreeterI = M.interface('greeter', {}, { defaultGuards: 'raw' });
const testGreeter = (t, greeter, msg) => {
const mutable = {};
t.is(greeter.sayHello(mutable), 'hello', `${msg} can sayHello`);
t.deepEqual(mutable, { x: 3 }, `${msg} mutable is mutated`);
mutable.y = 4;
t.deepEqual(mutable, { x: 3, y: 4 }, `${msg} mutable is mutated again}`);
};
test('raw guards', t => {
const greeter = makeExo('greeter', RawGreeterI, {
sayHello(mutable) {
mutable.x = 3;
return 'hello';
},
});
t.deepEqual(greeter[GET_INTERFACE_GUARD]?.(), RawGreeterI);
testGreeter(t, greeter, 'raw defaultGuards');
const Greeter2I = M.interface('greeter2', {
sayHello: M.call(M.raw()).returns(M.string()),
rawIn: M.call(M.raw()).returns(M.any()),
rawOut: M.call(M.any()).returns(M.raw()),
passthrough: M.call(M.raw()).returns(M.raw()),
tortuous: M.call(M.any(), M.raw(), M.any())
.optional(M.any(), M.raw())
.returns(M.any()),
});
const greeter2 = makeExo('greeter2', Greeter2I, {
sayHello(mutable) {
mutable.x = 3;
return 'hello';
},
rawIn(obj) {
// Object is never actually frozen, but isFrozen will always say true
// when lockdown hardenTaming is unsafe.
t.is(Object.isFrozen({}), Object.isFrozen(obj));
return obj;
},
rawOut(obj) {
// Object is implicitly frozen by harden as a side-effect of passing to
// an M.any guard, or unfrozen because harden is fake, but isFrozen lies.
t.true(Object.isFrozen(obj));
return { .../** @type {Record<string, any>} */ (obj) };
},
passthrough(obj) {
// The object is not frozen, but isFrozen lies when hardenTaming is
// unsafe.
t.is(Object.isFrozen({}), Object.isFrozen(obj));
return obj;
},
tortuous(hardA, softB, hardC, optHardD, optSoftE = {}) {
// Recall that isFrozen lies with hardenTaming: unsafe
// Test that `M.raw()` does not freeze the arguments, unlike `M.any()`.
t.true(Object.isFrozen(hardA));
t.is(Object.isFrozen({}), Object.isFrozen(softB));
softB.b = 2;
t.true(Object.isFrozen(hardC));
t.true(Object.isFrozen(optHardD));
// optSoftE is never frozen. It's either explicitly passed raw, or
// defaults in the argument to an unfrozen object.
// But, in unsafe harden taming, isFrozen misreports that soft objects
// are frozen.
t.is(Object.isFrozen({}), Object.isFrozen(optSoftE));
return {};
},
});
t.deepEqual(greeter2[GET_INTERFACE_GUARD]?.(), Greeter2I);
testGreeter(t, greeter, 'explicit raw');
t.true(Object.isFrozen(greeter2.rawIn({})));
// These both return actually unfrozen objects because of the M.raw return
// guard, but isFrozen says true anyway if hardenTaming is unsafe.
t.is(Object.isFrozen({}), Object.isFrozen(greeter2.rawOut({})));
t.is(Object.isFrozen({}), Object.isFrozen(greeter2.passthrough({})));
t.true(Object.isFrozen(greeter2.tortuous({}, {}, {}, {}, {})));
// @ts-expect-error TS infers 4 required params from impl, guard makes last 2 optional at runtime
t.true(Object.isFrozen(greeter2.tortuous({}, {}, {})));
t.throws(
// @ts-expect-error same: 3 args but impl has 4 required
() => greeter2.tortuous(makeBehavior(), {}, {}),
{
message:
/In "tortuous" method of \(greeter2\): Remotables must be explicitly declared/,
},
'passable behavior not allowed',
);
t.notThrows(
// @ts-expect-error same: 3 args but impl has 4 required
() => greeter2.tortuous({}, makeBehavior(), {}),
'raw behavior allowed',
);
});
const GreeterI = M.interface('greeter', {
sayHello: M.call().returns('hello'),
});
test('naked function call', t => {
const greeter = makeExo('greeter', GreeterI, {
sayHello() {
return 'hello';
},
});
const { sayHello, [GET_INTERFACE_GUARD]: gigm } = greeter;
t.throws(() => sayHello(), {
message:
'Method "In \\"sayHello\\" method of (greeter)" called without \'this\' object',
});
t.is(sayHello.bind(greeter)(), 'hello');
t.throws(() => gigm?.(), {
message:
'Method "In \\"__getInterfaceGuard__\\" method of (greeter)" called without \'this\' object',
});
t.deepEqual(gigm?.bind(greeter)(), GreeterI);
});
// needn't run. we just don't have a better place to write these.
test.skip('types', () => {
// any methods can be defined if there's no interface
const unguarded = makeExo('upCounter', undefined, {
/** @param {number} val */
incr(val) {
return val;
},
notInInterface() {
return 0;
},
});
// @ts-expect-error invalid args
unguarded.incr();
unguarded.notInInterface();
// @ts-expect-error not defined
unguarded.notInBehavior;
const guarded = makeExo('upCounter', UpCounterI, {
/** @param {number} val */
incr(val) {
return val;
},
});
// @ts-expect-error TS infers incr(val: number) as required from JSDoc, guard makes it optional at runtime
guarded.incr();
// @ts-expect-error not defined on the guarded type
guarded.notInBehavior;
// Runtime error: 'notInInterface' not in guard.
// TS limitation: excess property checking does not apply in generic
// contexts, so TS cannot reject extra methods here. If TS gains
// exact-type checking for object literals in generics, this could
// become a compile-time error.
makeExo('upCounter', UpCounterI, {
/** @param {number} val */
incr(val) {
return val;
},
notInInterface() {
return 0;
},
});
const sloppy = makeExo(
'upCounter',
M.interface(
'UpCounter',
{
incr: M.call().optional(M.number()).returns(M.number()),
},
{ sloppy: true },
),
{
/** @param {number} val */
incr(val) {
return val;
},
notInInterface() {
return 0;
},
},
);
sloppy.incr(1);
// @ts-expect-error TS infers incr(val: number) as required from JSDoc, guard makes it optional at runtime
sloppy.incr();
// allowed because sloppy:true
sloppy.notInInterface() === 0;
sloppy.notInInterface() === 1;
});
// ===== defineExoClassKit with typed InterfaceGuardKit =====
const ReaderI = M.interface('Reader', {
read: M.call().returns(M.string()),
});
const WriterI = M.interface('Writer', {
write: M.call(M.string()).returns(M.undefined()),
});
test('defineExoClassKit infers facet types from guard kit', t => {
const makeRW = defineExoClassKit(
'ReadWriter',
{ reader: ReaderI, writer: WriterI },
/** @param {string} initial */
initial => ({ data: initial }),
{
reader: {
read() {
const { state } = this;
return state.data;
},
},
writer: {
write(text) {
const { state } = this;
state.data = text;
},
},
},
);
const rw = makeRW('hello');
// reader facet
t.is(rw.reader.read(), 'hello');
// writer facet
rw.writer.write('world');
t.is(rw.reader.read(), 'world');
});
const SelfRefI = M.interface('SelfRef', {
get: M.call().returns(M.string()),
getViaSelf: M.call().returns(M.string()),
});
test('this.self is typed correctly in exo methods', t => {
const selfRef = makeExo('SelfRef', SelfRefI, {
get() {
return 'direct';
},
getViaSelf() {
// this.self should have the same type as the exo object
return this.self.get();
},
});
t.is(selfRef.get(), 'direct');
t.is(selfRef.getViaSelf(), 'direct');
});
const KitReaderI = M.interface('KitReader', {
read: M.call().returns(M.string()),
readViaFacets: M.call().returns(M.string()),
});
const KitWriterI = M.interface('KitWriter', {
write: M.call(M.string()).returns(M.undefined()),
});
test('this.facets is typed correctly in kit methods', t => {
const makeKit = defineExoClassKit(
'Kit',
{ reader: KitReaderI, writer: KitWriterI },
/** @param {string} data */
data => ({ data }),
{
reader: {
read() {
return this.state.data;
},
readViaFacets() {
// this.facets.reader has the reader facet type
return this.facets.reader.read();
},
},
writer: {
write(text) {
this.state.data = text;
},
},
},
);
const kit = makeKit('hello');
t.is(kit.reader.read(), 'hello');
t.is(kit.reader.readViaFacets(), 'hello');
kit.writer.write('world');
t.is(kit.reader.read(), 'world');
});