ses 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,6 +6,7 @@
6
6
  // module's "imports" with the more specific "resolvedImports" as inferred from
7
7
  // the particular compartment's "resolveHook".
8
8
 
9
+ import { getEnvironmentOption as getenv } from '@endo/env-options';
9
10
  import {
10
11
  ReferenceError,
11
12
  TypeError,
@@ -20,10 +21,11 @@ import {
20
21
  mapHas,
21
22
  mapSet,
22
23
  setAdd,
23
- promiseCatch,
24
24
  promiseThen,
25
25
  values,
26
26
  weakmapGet,
27
+ generatorNext,
28
+ generatorThrow,
27
29
  } from './commons.js';
28
30
  import { assert } from './error/assert.js';
29
31
 
@@ -31,6 +33,33 @@ const { Fail, details: d, quote: q } = assert;
31
33
 
32
34
  const noop = () => {};
33
35
 
36
+ async function asyncTrampoline(generatorFunc, args, errorWrapper) {
37
+ const iterator = generatorFunc(...args);
38
+ let result = generatorNext(iterator);
39
+ while (!result.done) {
40
+ try {
41
+ // eslint-disable-next-line no-await-in-loop
42
+ const val = await result.value;
43
+ result = generatorNext(iterator, val);
44
+ } catch (error) {
45
+ result = generatorThrow(iterator, errorWrapper(error));
46
+ }
47
+ }
48
+ return result.value;
49
+ }
50
+
51
+ function syncTrampoline(generatorFunc, args) {
52
+ const iterator = generatorFunc(...args);
53
+ let result = generatorNext(iterator);
54
+ while (!result.done) {
55
+ try {
56
+ result = generatorNext(iterator, result.value);
57
+ } catch (error) {
58
+ result = generatorThrow(iterator, error);
59
+ }
60
+ }
61
+ return result.value;
62
+ }
34
63
  // `makeAlias` constructs compartment specifier tuples for the `aliases`
35
64
  // private field of compartments.
36
65
  // These aliases allow a compartment to alias an internal module specifier to a
@@ -60,9 +89,9 @@ const loadRecord = (
60
89
  compartment,
61
90
  moduleSpecifier,
62
91
  staticModuleRecord,
63
- pendingJobs,
92
+ enqueueJob,
93
+ selectImplementation,
64
94
  moduleLoads,
65
- errors,
66
95
  importMeta,
67
96
  ) => {
68
97
  const { resolveHook, moduleRecords } = weakmapGet(
@@ -88,21 +117,15 @@ const loadRecord = (
88
117
  for (const fullSpecifier of values(resolvedImports)) {
89
118
  // Behold: recursion.
90
119
  // eslint-disable-next-line no-use-before-define
91
- const dependencyLoaded = memoizedLoadWithErrorAnnotation(
120
+ enqueueJob(memoizedLoadWithErrorAnnotation, [
92
121
  compartmentPrivateFields,
93
122
  moduleAliases,
94
123
  compartment,
95
124
  fullSpecifier,
96
- pendingJobs,
125
+ enqueueJob,
126
+ selectImplementation,
97
127
  moduleLoads,
98
- errors,
99
- );
100
- setAdd(
101
- pendingJobs,
102
- promiseThen(dependencyLoaded, noop, error => {
103
- arrayPush(errors, error);
104
- }),
105
- );
128
+ ]);
106
129
  }
107
130
 
108
131
  // Memoize.
@@ -110,19 +133,17 @@ const loadRecord = (
110
133
  return moduleRecord;
111
134
  };
112
135
 
113
- const loadWithoutErrorAnnotation = async (
136
+ function* loadWithoutErrorAnnotation(
114
137
  compartmentPrivateFields,
115
138
  moduleAliases,
116
139
  compartment,
117
140
  moduleSpecifier,
118
- pendingJobs,
141
+ enqueueJob,
142
+ selectImplementation,
119
143
  moduleLoads,
120
- errors,
121
- ) => {
122
- const { importHook, moduleMap, moduleMapHook, moduleRecords } = weakmapGet(
123
- compartmentPrivateFields,
124
- compartment,
125
- );
144
+ ) {
145
+ const { importHook, importNowHook, moduleMap, moduleMapHook, moduleRecords } =
146
+ weakmapGet(compartmentPrivateFields, compartment);
126
147
 
127
148
  // Follow moduleMap, or moduleMapHook if present.
128
149
  let aliasNamespace = moduleMap[moduleSpecifier];
@@ -150,14 +171,14 @@ const loadWithoutErrorAnnotation = async (
150
171
  }
151
172
  // Behold: recursion.
152
173
  // eslint-disable-next-line no-use-before-define
153
- const aliasRecord = await memoizedLoadWithErrorAnnotation(
174
+ const aliasRecord = yield memoizedLoadWithErrorAnnotation(
154
175
  compartmentPrivateFields,
155
176
  moduleAliases,
156
177
  alias.compartment,
157
178
  alias.specifier,
158
- pendingJobs,
179
+ enqueueJob,
180
+ selectImplementation,
159
181
  moduleLoads,
160
- errors,
161
182
  );
162
183
  mapSet(moduleRecords, moduleSpecifier, aliasRecord);
163
184
  return aliasRecord;
@@ -167,7 +188,10 @@ const loadWithoutErrorAnnotation = async (
167
188
  return mapGet(moduleRecords, moduleSpecifier);
168
189
  }
169
190
 
170
- const staticModuleRecord = await importHook(moduleSpecifier);
191
+ const staticModuleRecord = yield selectImplementation(
192
+ importHook,
193
+ importNowHook,
194
+ )(moduleSpecifier);
171
195
 
172
196
  if (staticModuleRecord === null || typeof staticModuleRecord !== 'object') {
173
197
  Fail`importHook must return a promise for an object, for module ${q(
@@ -198,9 +222,9 @@ const loadWithoutErrorAnnotation = async (
198
222
  aliasCompartment,
199
223
  aliasSpecifier,
200
224
  aliasModuleRecord,
201
- pendingJobs,
225
+ enqueueJob,
226
+ selectImplementation,
202
227
  moduleLoads,
203
- errors,
204
228
  importMeta,
205
229
  );
206
230
  mapSet(moduleRecords, moduleSpecifier, aliasRecord);
@@ -217,14 +241,14 @@ const loadWithoutErrorAnnotation = async (
217
241
  }
218
242
  // Behold: recursion.
219
243
  // eslint-disable-next-line no-use-before-define
220
- const aliasRecord = await memoizedLoadWithErrorAnnotation(
244
+ const aliasRecord = yield memoizedLoadWithErrorAnnotation(
221
245
  compartmentPrivateFields,
222
246
  moduleAliases,
223
247
  staticModuleRecord.compartment,
224
248
  staticModuleRecord.specifier,
225
- pendingJobs,
249
+ enqueueJob,
250
+ selectImplementation,
226
251
  moduleLoads,
227
- errors,
228
252
  );
229
253
  mapSet(moduleRecords, moduleSpecifier, aliasRecord);
230
254
  return aliasRecord;
@@ -239,20 +263,20 @@ const loadWithoutErrorAnnotation = async (
239
263
  compartment,
240
264
  moduleSpecifier,
241
265
  staticModuleRecord,
242
- pendingJobs,
266
+ enqueueJob,
267
+ selectImplementation,
243
268
  moduleLoads,
244
- errors,
245
269
  );
246
- };
270
+ }
247
271
 
248
- const memoizedLoadWithErrorAnnotation = async (
272
+ const memoizedLoadWithErrorAnnotation = (
249
273
  compartmentPrivateFields,
250
274
  moduleAliases,
251
275
  compartment,
252
276
  moduleSpecifier,
253
- pendingJobs,
277
+ enqueueJob,
278
+ selectImplementation,
254
279
  moduleLoads,
255
- errors,
256
280
  ) => {
257
281
  const { name: compartmentName } = weakmapGet(
258
282
  compartmentPrivateFields,
@@ -270,16 +294,17 @@ const memoizedLoadWithErrorAnnotation = async (
270
294
  return moduleLoading;
271
295
  }
272
296
 
273
- moduleLoading = promiseCatch(
274
- loadWithoutErrorAnnotation(
297
+ moduleLoading = selectImplementation(asyncTrampoline, syncTrampoline)(
298
+ loadWithoutErrorAnnotation,
299
+ [
275
300
  compartmentPrivateFields,
276
301
  moduleAliases,
277
302
  compartment,
278
303
  moduleSpecifier,
279
- pendingJobs,
304
+ enqueueJob,
305
+ selectImplementation,
280
306
  moduleLoads,
281
- errors,
282
- ),
307
+ ],
283
308
  error => {
284
309
  // eslint-disable-next-line @endo/no-polymorphic-call
285
310
  assert.note(
@@ -297,6 +322,64 @@ const memoizedLoadWithErrorAnnotation = async (
297
322
  return moduleLoading;
298
323
  };
299
324
 
325
+ function asyncJobQueue() {
326
+ /** @type {Set<Promise<undefined>>} */
327
+ const pendingJobs = new Set();
328
+ /** @type {Array<Error>} */
329
+ const errors = [];
330
+
331
+ /**
332
+ * Enqueues a job that starts immediately but won't be awaited until drainQueue is called.
333
+ *
334
+ * @template {any[]} T
335
+ * @param {(...args: T)=>Promise<*>} func
336
+ * @param {T} args
337
+ */
338
+ const enqueueJob = (func, args) => {
339
+ setAdd(
340
+ pendingJobs,
341
+ promiseThen(func(...args), noop, error => {
342
+ arrayPush(errors, error);
343
+ }),
344
+ );
345
+ };
346
+ /**
347
+ * Sequentially awaits pending jobs and returns an array of errors
348
+ *
349
+ * @returns {Promise<Array<Error>>}
350
+ */
351
+ const drainQueue = async () => {
352
+ for (const job of pendingJobs) {
353
+ // eslint-disable-next-line no-await-in-loop
354
+ await job;
355
+ }
356
+ return errors;
357
+ };
358
+ return { enqueueJob, drainQueue };
359
+ }
360
+
361
+ /**
362
+ * @param {object} options
363
+ * @param {Array<Error>} options.errors
364
+ * @param {string} options.errorPrefix
365
+ */
366
+ function throwAggregateError({ errors, errorPrefix }) {
367
+ // Throw an aggregate error if there were any errors.
368
+ if (errors.length > 0) {
369
+ const verbose =
370
+ getenv('COMPARTMENT_LOAD_ERRORS', '', ['verbose']) === 'verbose';
371
+ throw TypeError(
372
+ `${errorPrefix} (${errors.length} underlying failures: ${arrayJoin(
373
+ arrayMap(errors, error => error.message + (verbose ? error.stack : '')),
374
+ ', ',
375
+ )}`,
376
+ );
377
+ }
378
+ }
379
+
380
+ const preferSync = (_asyncImpl, syncImpl) => syncImpl;
381
+ const preferAsync = (asyncImpl, _syncImpl) => asyncImpl;
382
+
300
383
  /*
301
384
  * `load` asynchronously gathers the `StaticModuleRecord`s for a module and its
302
385
  * transitive dependencies.
@@ -315,47 +398,78 @@ export const load = async (
315
398
  compartment,
316
399
  );
317
400
 
318
- /** @type {Set<Promise<undefined>>} */
319
- const pendingJobs = new Set();
320
401
  /** @type {Map<object, Map<string, Promise<Record<any, any>>>>} */
321
402
  const moduleLoads = new Map();
322
- /** @type {Array<Error>} */
323
- const errors = [];
324
403
 
325
- const dependencyLoaded = memoizedLoadWithErrorAnnotation(
404
+ const { enqueueJob, drainQueue } = asyncJobQueue();
405
+
406
+ enqueueJob(memoizedLoadWithErrorAnnotation, [
326
407
  compartmentPrivateFields,
327
408
  moduleAliases,
328
409
  compartment,
329
410
  moduleSpecifier,
330
- pendingJobs,
411
+ enqueueJob,
412
+ preferAsync,
331
413
  moduleLoads,
414
+ ]);
415
+
416
+ // Drain pending jobs queue and throw an aggregate error
417
+ const errors = await drainQueue();
418
+
419
+ throwAggregateError({
332
420
  errors,
421
+ errorPrefix: `Failed to load module ${q(moduleSpecifier)} in package ${q(
422
+ compartmentName,
423
+ )}`,
424
+ });
425
+ };
426
+
427
+ /*
428
+ * `loadNow` synchronously gathers the `StaticModuleRecord`s for a module and its
429
+ * transitive dependencies.
430
+ * The module records refer to each other by a reference to the dependency's
431
+ * compartment and the specifier of the module within its own compartment.
432
+ * This graph is then ready to be synchronously linked and executed.
433
+ */
434
+ export const loadNow = (
435
+ compartmentPrivateFields,
436
+ moduleAliases,
437
+ compartment,
438
+ moduleSpecifier,
439
+ ) => {
440
+ const { name: compartmentName } = weakmapGet(
441
+ compartmentPrivateFields,
442
+ compartment,
333
443
  );
334
- setAdd(
335
- pendingJobs,
336
- promiseThen(dependencyLoaded, noop, error => {
444
+
445
+ /** @type {Map<object, Map<string, Promise<Record<any, any>>>>} */
446
+ const moduleLoads = new Map();
447
+
448
+ /** @type {Array<Error>} */
449
+ const errors = [];
450
+
451
+ const enqueueJob = (func, args) => {
452
+ try {
453
+ func(...args);
454
+ } catch (error) {
337
455
  arrayPush(errors, error);
338
- }),
339
- );
456
+ }
457
+ };
340
458
 
341
- // Drain pending jobs queue.
342
- // Each job is a promise for undefined, regardless of success or failure.
343
- // Before we add a job to the queue, we catch any error and push it into the
344
- // `errors` accumulator.
345
- for (const job of pendingJobs) {
346
- // eslint-disable-next-line no-await-in-loop
347
- await job;
348
- }
459
+ enqueueJob(memoizedLoadWithErrorAnnotation, [
460
+ compartmentPrivateFields,
461
+ moduleAliases,
462
+ compartment,
463
+ moduleSpecifier,
464
+ enqueueJob,
465
+ preferSync,
466
+ moduleLoads,
467
+ ]);
349
468
 
350
- // Throw an aggregate error if there were any errors.
351
- if (errors.length > 0) {
352
- throw TypeError(
353
- `Failed to load module ${q(moduleSpecifier)} in package ${q(
354
- compartmentName,
355
- )} (${errors.length} underlying failures: ${arrayJoin(
356
- arrayMap(errors, error => error.message),
357
- ', ',
358
- )}`,
359
- );
360
- }
469
+ throwAggregateError({
470
+ errors,
471
+ errorPrefix: `Failed to load module ${q(moduleSpecifier)} in package ${q(
472
+ compartmentName,
473
+ )}`,
474
+ });
361
475
  };
package/src/permits.js CHANGED
@@ -3,6 +3,8 @@
3
3
 
4
4
  import { arrayPush } from './commons.js';
5
5
 
6
+ /** @import {GenericErrorConstructor} from '../types.js' */
7
+
6
8
  /**
7
9
  * @file Exports {@code whitelist}, a recursively defined
8
10
  * JSON record enumerating all intrinsics and their properties
@@ -5,6 +5,7 @@ import {
5
5
  getOwnPropertyDescriptors,
6
6
  defineProperties,
7
7
  arrayMap,
8
+ functionBind,
8
9
  } from './commons.js';
9
10
 
10
11
  /**
@@ -37,11 +38,9 @@ export const tameSymbolConstructor = () => {
37
38
  const OriginalSymbol = Symbol;
38
39
  const SymbolPrototype = OriginalSymbol.prototype;
39
40
 
40
- const SharedSymbol = {
41
- Symbol(description) {
42
- return OriginalSymbol(description);
43
- },
44
- }.Symbol;
41
+ // Bypass Hermes bug, fixed in: https://github.com/facebook/hermes/commit/00f18c89c720e1c34592bb85a1a8d311e6e99599
42
+ // Make a "copy" of the primordial [Symbol "constructor"](https://tc39.es/ecma262/#sec-symbol-description) which maintains all observable behavior. The primordial explicitly throws on `[[Construct]]` and has a `[[Call]]` which ignores the receiver. Binding also maintains the `toString` source as a native function. The `name` is restored below when copying own properties.
43
+ const SharedSymbol = functionBind(Symbol, undefined);
45
44
 
46
45
  defineProperties(SymbolPrototype, {
47
46
  constructor: {