ses 1.9.1 → 1.11.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.
@@ -28,10 +28,24 @@ import {
28
28
  * @import {ErrorInfo, ErrorInfoKind, LogRecord, NoteCallback, LoggedErrorHandler, MakeCausalConsole, MakeLoggingConsoleKit} from "./internal-types.js";
29
29
  */
30
30
 
31
+ /**
32
+ * Explicitly set a function's name, supporting use of arrow functions for which
33
+ * source text doesn't include a name and no initial name is set by
34
+ * NamedEvaluation
35
+ * https://tc39.es/ecma262/multipage/syntax-directed-operations.html#sec-runtime-semantics-namedevaluation
36
+ * Instead, we hope that tooling uses only the explicit `name` property.
37
+ *
38
+ * @template {Function} F
39
+ * @param {string} name
40
+ * @param {F} fn
41
+ * @returns {F}
42
+ */
43
+ const defineName = (name, fn) => defineProperty(fn, 'name', { value: name });
44
+
31
45
  // For our internal debugging purposes, uncomment
32
46
  // const internalDebugConsole = console;
33
47
 
34
- // The whitelists of console methods, from:
48
+ // The permitted console methods, from:
35
49
  // Whatwg "living standard" https://console.spec.whatwg.org/
36
50
  // Node https://nodejs.org/dist/latest-v14.x/docs/api/console.html
37
51
  // MDN https://developer.mozilla.org/en-US/docs/Web/API/Console_API
@@ -110,7 +124,7 @@ export const consoleOtherMethods = freeze([
110
124
  ]);
111
125
 
112
126
  /** @type {readonly [ConsoleProps, LogSeverity | undefined][]} */
113
- const consoleWhitelist = freeze([
127
+ const consoleMethodPermits = freeze([
114
128
  ...consoleLevelMethods,
115
129
  ...consoleOtherMethods,
116
130
  ]);
@@ -118,8 +132,8 @@ const consoleWhitelist = freeze([
118
132
  /**
119
133
  * consoleOmittedProperties is currently unused. I record and maintain it here
120
134
  * with the intention that it be treated like the `false` entries in the main
121
- * SES whitelist: that seeing these on the original console is expected, but
122
- * seeing anything else that's outside the whitelist is surprising and should
135
+ * SES permits: that seeing these on the original console is expected, but
136
+ * seeing anything else that's outside the permits is surprising and should
123
137
  * provide a diagnostic.
124
138
  *
125
139
  * const consoleOmittedProperties = freeze([
@@ -158,17 +172,13 @@ export const makeLoggingConsoleKit = (
158
172
  let logArray = [];
159
173
 
160
174
  const loggingConsole = fromEntries(
161
- arrayMap(consoleWhitelist, ([name, _]) => {
162
- // Use an arrow function so that it doesn't come with its own name in
163
- // its printed form. Instead, we're hoping that tooling uses only
164
- // the `.name` property set below.
175
+ arrayMap(consoleMethodPermits, ([name, _]) => {
165
176
  /**
166
177
  * @param {...any} args
167
178
  */
168
- const method = (...args) => {
179
+ const method = defineName(name, (...args) => {
169
180
  arrayPush(logArray, [name, ...args]);
170
- };
171
- defineProperty(method, 'name', { value: name });
181
+ });
172
182
  return [name, freeze(method)];
173
183
  }),
174
184
  );
@@ -288,8 +298,10 @@ export const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
288
298
  logError(severity, subError);
289
299
  }
290
300
  } finally {
291
- // eslint-disable-next-line @endo/no-polymorphic-call
292
- baseConsole.groupEnd();
301
+ if (baseConsole.groupEnd) {
302
+ // eslint-disable-next-line @endo/no-polymorphic-call
303
+ baseConsole.groupEnd();
304
+ }
293
305
  }
294
306
  };
295
307
 
@@ -368,7 +380,7 @@ export const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
368
380
  /**
369
381
  * @param {...any} logArgs
370
382
  */
371
- const levelMethod = (...logArgs) => {
383
+ const levelMethod = defineName(level, (...logArgs) => {
372
384
  const subErrors = [];
373
385
  const argTags = extractErrorArgs(logArgs, subErrors);
374
386
  if (baseConsole[level]) {
@@ -377,8 +389,7 @@ export const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
377
389
  }
378
390
  // @ts-expect-error ConsoleProp vs LogSeverity mismatch
379
391
  logSubErrors(level, subErrors);
380
- };
381
- defineProperty(levelMethod, 'name', { value: level });
392
+ });
382
393
  return [level, freeze(levelMethod)];
383
394
  });
384
395
  const otherMethodNames = arrayFilter(
@@ -389,13 +400,12 @@ export const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
389
400
  /**
390
401
  * @param {...any} args
391
402
  */
392
- const otherMethod = (...args) => {
403
+ const otherMethod = defineName(name, (...args) => {
393
404
  // @ts-ignore
394
405
  // eslint-disable-next-line @endo/no-polymorphic-call
395
406
  baseConsole[name](...args);
396
407
  return undefined;
397
- };
398
- defineProperty(otherMethod, 'name', { value: name });
408
+ });
399
409
  return [name, freeze(otherMethod)];
400
410
  });
401
411
 
@@ -456,23 +466,21 @@ export const defineCausalConsoleFromLogger = loggedErrorHandler => {
456
466
  }
457
467
  return tlogger(...args);
458
468
  };
459
- const makeNamed = (name, fn) =>
460
- ({ [name]: (...args) => fn(...args) })[name];
461
469
 
462
470
  const baseConsole = fromEntries([
463
471
  ...arrayMap(consoleLevelMethods, ([name]) => [
464
472
  name,
465
- makeNamed(name, logWithIndent),
473
+ defineName(name, (...args) => logWithIndent(...args)),
466
474
  ]),
467
475
  ...arrayMap(consoleOtherMethods, ([name]) => [
468
476
  name,
469
- makeNamed(name, (...args) => logWithIndent(name, ...args)),
477
+ defineName(name, (...args) => logWithIndent(name, ...args)),
470
478
  ]),
471
479
  ]);
472
480
  // https://console.spec.whatwg.org/#grouping
473
481
  for (const name of ['group', 'groupCollapsed']) {
474
482
  if (baseConsole[name]) {
475
- baseConsole[name] = makeNamed(name, (...args) => {
483
+ baseConsole[name] = defineName(name, (...args) => {
476
484
  if (args.length >= 1) {
477
485
  // Prefix the logged data with "group" or "groupCollapsed".
478
486
  logWithIndent(...args);
@@ -482,16 +490,17 @@ export const defineCausalConsoleFromLogger = loggedErrorHandler => {
482
490
  arrayPush(indents, ' ');
483
491
  });
484
492
  } else {
485
- baseConsole[name] = () => {};
493
+ baseConsole[name] = defineName(name, () => {});
486
494
  }
487
495
  }
488
- if (baseConsole.groupEnd) {
489
- baseConsole.groupEnd = makeNamed('groupEnd', (...args) => {
490
- arrayPop(indents);
491
- });
492
- } else {
493
- baseConsole.groupEnd = () => {};
494
- }
496
+ baseConsole.groupEnd = defineName(
497
+ 'groupEnd',
498
+ baseConsole.groupEnd
499
+ ? (...args) => {
500
+ arrayPop(indents);
501
+ }
502
+ : () => {},
503
+ );
495
504
  harden(baseConsole);
496
505
  const causalConsole = makeCausalConsole(
497
506
  /** @type {VirtualConsole} */ (baseConsole),
@@ -508,22 +517,22 @@ freeze(defineCausalConsoleFromLogger);
508
517
  /** @type {FilterConsole} */
509
518
  export const filterConsole = (baseConsole, filter, _topic = undefined) => {
510
519
  // TODO do something with optional topic string
511
- const whitelist = arrayFilter(
512
- consoleWhitelist,
520
+ const methodPermits = arrayFilter(
521
+ consoleMethodPermits,
513
522
  ([name, _]) => name in baseConsole,
514
523
  );
515
- const methods = arrayMap(whitelist, ([name, severity]) => {
524
+ const methods = arrayMap(methodPermits, ([name, severity]) => {
516
525
  /**
517
526
  * @param {...any} args
518
527
  */
519
- const method = (...args) => {
528
+ const method = defineName(name, (...args) => {
520
529
  // eslint-disable-next-line @endo/no-polymorphic-call
521
530
  if (severity === undefined || filter.canLog(severity)) {
522
531
  // @ts-ignore
523
532
  // eslint-disable-next-line @endo/no-polymorphic-call
524
533
  baseConsole[name](...args);
525
534
  }
526
- };
535
+ });
527
536
  return [name, freeze(method)];
528
537
  });
529
538
  const filteringConsole = fromEntries(methods);
@@ -62,7 +62,7 @@
62
62
  /**
63
63
  * @callback MakeLoggingConsoleKit
64
64
  *
65
- * A logging console just accumulates the contents of all whitelisted calls,
65
+ * A logging console just accumulates the contents of all permitted calls,
66
66
  * making them available to callers of `takeLog()`. Calling `takeLog()`
67
67
  * consumes these, so later calls to `takeLog()` will only provide a log of
68
68
  * calls that have happened since then.
@@ -19,8 +19,8 @@ import {
19
19
  TypeError,
20
20
  } from '../commons.js';
21
21
 
22
- // Whitelist names from https://v8.dev/docs/stack-trace-api
23
- // Whitelisting only the names used by error-stack-shim/src/v8StackFrames
22
+ // Permit names from https://v8.dev/docs/stack-trace-api
23
+ // Permiting only the names used by error-stack-shim/src/v8StackFrames
24
24
  // callSiteToFrame to shim the error stack proposal.
25
25
  const safeV8CallSiteMethodNames = [
26
26
  // suppress 'getThis' definitely
@@ -45,7 +45,7 @@ const safeV8CallSiteMethodNames = [
45
45
  'getPosition',
46
46
  'getScriptNameOrSourceURL',
47
47
 
48
- 'toString', // TODO replace to use only whitelisted info
48
+ 'toString', // TODO replace to use only permitted info
49
49
  ];
50
50
 
51
51
  // TODO this is a ridiculously expensive way to attenuate callsites.
@@ -117,11 +117,14 @@ export const setGlobalObjectMutableProperties = (
117
117
  makeCompartmentConstructor,
118
118
  intrinsics,
119
119
  markVirtualizedNativeFunction,
120
- parentCompartment,
120
+ {
121
+ parentCompartment,
122
+ enforceNew: true,
123
+ },
121
124
  ),
122
125
  );
123
126
 
124
- // TODO These should still be tamed according to the whitelist before
127
+ // TODO These should still be tamed according to the permits before
125
128
  // being made available.
126
129
  for (const [name, value] of entries(perCompartmentGlobals)) {
127
130
  defineProperty(globalObject, name, {
package/src/intrinsics.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { cauterizeProperty } from './cauterize-property.js';
1
2
  import {
2
3
  TypeError,
3
4
  WeakSet,
@@ -23,12 +24,16 @@ import {
23
24
  permitted,
24
25
  } from './permits.js';
25
26
 
27
+ /**
28
+ * @import {Reporter} from './reporting-types.js'
29
+ */
30
+
26
31
  const isFunction = obj => typeof obj === 'function';
27
32
 
28
33
  // Like defineProperty, but throws if it would modify an existing property.
29
34
  // We use this to ensure that two conflicting attempts to define the same
30
35
  // property throws, causing SES initialization to fail. Otherwise, a
31
- // conflict between, for example, two of SES's internal whitelists might
36
+ // conflict between, for example, two of SES's internal permits might
32
37
  // get masked as one overwrites the other. Accordingly, the thrown error
33
38
  // complains of a "Conflicting definition".
34
39
  function initProperty(obj, name, desc) {
@@ -71,7 +76,10 @@ function sampleGlobals(globalObject, newPropertyNames) {
71
76
  return newIntrinsics;
72
77
  }
73
78
 
74
- export const makeIntrinsicsCollector = () => {
79
+ /**
80
+ * @param {Reporter} reporter
81
+ */
82
+ export const makeIntrinsicsCollector = reporter => {
75
83
  /** @type {Record<any, any>} */
76
84
  const intrinsics = create(null);
77
85
  let pseudoNatives;
@@ -82,7 +90,7 @@ export const makeIntrinsicsCollector = () => {
82
90
  freeze(addIntrinsics);
83
91
 
84
92
  // For each intrinsic, if it has a `.prototype` property, use the
85
- // whitelist to find out the intrinsic name for that prototype and add it
93
+ // permits to find out the intrinsic name for that prototype and add it
86
94
  // to the intrinsics.
87
95
  const completePrototypes = () => {
88
96
  for (const [name, intrinsic] of entries(intrinsics)) {
@@ -96,17 +104,25 @@ export const makeIntrinsicsCollector = () => {
96
104
  }
97
105
  const permit = permitted[name];
98
106
  if (typeof permit !== 'object') {
99
- throw TypeError(`Expected permit object at whitelist.${name}`);
107
+ throw TypeError(`Expected permit object at permits.${name}`);
100
108
  }
101
109
  const namePrototype = permit.prototype;
102
110
  if (!namePrototype) {
103
- throw TypeError(`${name}.prototype property not whitelisted`);
111
+ cauterizeProperty(
112
+ intrinsic,
113
+ 'prototype',
114
+ false,
115
+ `${name}.prototype`,
116
+ reporter,
117
+ );
118
+ // eslint-disable-next-line no-continue
119
+ continue;
104
120
  }
105
121
  if (
106
122
  typeof namePrototype !== 'string' ||
107
123
  !objectHasOwnProperty(permitted, namePrototype)
108
124
  ) {
109
- throw TypeError(`Unrecognized ${name}.prototype whitelist entry`);
125
+ throw TypeError(`Unrecognized ${name}.prototype permits entry`);
110
126
  }
111
127
  const intrinsicPrototype = intrinsic.prototype;
112
128
  if (objectHasOwnProperty(intrinsics, namePrototype)) {
@@ -155,7 +171,7 @@ export const makeIntrinsicsCollector = () => {
155
171
  /**
156
172
  * getGlobalIntrinsics()
157
173
  * Doesn't tame, delete, or modify anything. Samples globalObject to create an
158
- * intrinsics record containing only the whitelisted global variables, listed
174
+ * intrinsics record containing only the permitted global variables, listed
159
175
  * by the intrinsic names appropriate for new globals, i.e., the globals of
160
176
  * newly constructed compartments.
161
177
  *
@@ -164,9 +180,11 @@ export const makeIntrinsicsCollector = () => {
164
180
  * *original* unsafe (feral, untamed) bindings of these global variables.
165
181
  *
166
182
  * @param {object} globalObject
183
+ * @param {Reporter} reporter
167
184
  */
168
- export const getGlobalIntrinsics = globalObject => {
169
- const { addIntrinsics, finalIntrinsics } = makeIntrinsicsCollector();
185
+ export const getGlobalIntrinsics = (globalObject, reporter) => {
186
+ // TODO pass a proper reporter to `makeIntrinsicsCollector`
187
+ const { addIntrinsics, finalIntrinsics } = makeIntrinsicsCollector(reporter);
170
188
 
171
189
  addIntrinsics(sampleGlobals(globalObject, sharedGlobalPropertyNames));
172
190
 
package/src/lockdown.js CHANGED
@@ -30,7 +30,7 @@ import {
30
30
  } from './commons.js';
31
31
  import { makeHardener } from './make-hardener.js';
32
32
  import { makeIntrinsicsCollector } from './intrinsics.js';
33
- import whitelistIntrinsics from './permits-intrinsics.js';
33
+ import removeUnpermittedIntrinsics from './permits-intrinsics.js';
34
34
  import tameFunctionConstructors from './tame-function-constructors.js';
35
35
  import tameDateConstructor from './tame-date-constructor.js';
36
36
  import tameMathObject from './tame-math-object.js';
@@ -58,6 +58,7 @@ import { tameSymbolConstructor } from './tame-symbol-constructor.js';
58
58
  import { tameFauxDataProperties } from './tame-faux-data-properties.js';
59
59
  import { tameRegeneratorRuntime } from './tame-regenerator-runtime.js';
60
60
  import { shimArrayBufferTransfer } from './shim-arraybuffer-transfer.js';
61
+ import { reportInGroup, chooseReporter } from './reporting.js';
61
62
 
62
63
  /** @import {LockdownOptions} from '../types.js' */
63
64
 
@@ -162,19 +163,24 @@ export const repairIntrinsics = (options = {}) => {
162
163
 
163
164
  const {
164
165
  errorTaming = getenv('LOCKDOWN_ERROR_TAMING', 'safe'),
165
- errorTrapping = /** @type {"platform" | "none" | "report" | "abort" | "exit" | undefined} */ (
166
+ errorTrapping = /** @type {"platform" | "none" | "report" | "abort" | "exit"} */ (
166
167
  getenv('LOCKDOWN_ERROR_TRAPPING', 'platform')
167
168
  ),
168
- unhandledRejectionTrapping = /** @type {"none" | "report" | undefined} */ (
169
+ reporting = /** @type {"platform" | "console" | "none"} */ (
170
+ getenv('LOCKDOWN_REPORTING', 'platform')
171
+ ),
172
+ unhandledRejectionTrapping = /** @type {"none" | "report"} */ (
169
173
  getenv('LOCKDOWN_UNHANDLED_REJECTION_TRAPPING', 'report')
170
174
  ),
171
175
  regExpTaming = getenv('LOCKDOWN_REGEXP_TAMING', 'safe'),
172
176
  localeTaming = getenv('LOCKDOWN_LOCALE_TAMING', 'safe'),
173
177
 
174
- consoleTaming = /** @type {'unsafe' | 'safe' | undefined} */ (
178
+ consoleTaming = /** @type {'unsafe' | 'safe'} */ (
175
179
  getenv('LOCKDOWN_CONSOLE_TAMING', 'safe')
176
180
  ),
177
- overrideTaming = getenv('LOCKDOWN_OVERRIDE_TAMING', 'moderate'),
181
+ overrideTaming = /** @type {'moderate' | 'min' | 'severe'} */ (
182
+ getenv('LOCKDOWN_OVERRIDE_TAMING', 'moderate')
183
+ ),
178
184
  stackFiltering = getenv('LOCKDOWN_STACK_FILTERING', 'concise'),
179
185
  domainTaming = getenv('LOCKDOWN_DOMAIN_TAMING', 'safe'),
180
186
  evalTaming = getenv('LOCKDOWN_EVAL_TAMING', 'safeEval'),
@@ -188,8 +194,8 @@ export const repairIntrinsics = (options = {}) => {
188
194
  'safe',
189
195
  ),
190
196
  __hardenTaming__ = getenv('LOCKDOWN_HARDEN_TAMING', 'safe'),
191
- dateTaming = 'safe', // deprecated
192
- mathTaming = 'safe', // deprecated
197
+ dateTaming, // deprecated
198
+ mathTaming, // deprecated
193
199
  ...extraOptions
194
200
  } = options;
195
201
 
@@ -208,6 +214,22 @@ export const repairIntrinsics = (options = {}) => {
208
214
  extraOptionsNames.length === 0 ||
209
215
  Fail`lockdown(): non supported option ${q(extraOptionsNames)}`;
210
216
 
217
+ const reporter = chooseReporter(reporting);
218
+ const { warn } = reporter;
219
+
220
+ if (dateTaming !== undefined) {
221
+ // eslint-disable-next-line no-console
222
+ warn(
223
+ `SES The 'dateTaming' option is deprecated and does nothing. In the future specifying it will be an error.`,
224
+ );
225
+ }
226
+ if (mathTaming !== undefined) {
227
+ // eslint-disable-next-line no-console
228
+ warn(
229
+ `SES The 'mathTaming' option is deprecated and does nothing. In the future specifying it will be an error.`,
230
+ );
231
+ }
232
+
211
233
  priorRepairIntrinsics === undefined ||
212
234
  // eslint-disable-next-line @endo/no-polymorphic-call
213
235
  assert.fail(
@@ -273,7 +295,7 @@ export const repairIntrinsics = (options = {}) => {
273
295
  const markVirtualizedNativeFunction = tameFunctionToString();
274
296
 
275
297
  const { addIntrinsics, completePrototypes, finalIntrinsics } =
276
- makeIntrinsicsCollector();
298
+ makeIntrinsicsCollector(reporter);
277
299
 
278
300
  // @ts-expect-error __hardenTaming__ could be any string
279
301
  const tamedHarden = tameHarden(safeHarden, __hardenTaming__);
@@ -281,9 +303,9 @@ export const repairIntrinsics = (options = {}) => {
281
303
 
282
304
  addIntrinsics(tameFunctionConstructors());
283
305
 
284
- addIntrinsics(tameDateConstructor(dateTaming));
306
+ addIntrinsics(tameDateConstructor());
285
307
  addIntrinsics(tameErrorConstructor(errorTaming, stackFiltering));
286
- addIntrinsics(tameMathObject(mathTaming));
308
+ addIntrinsics(tameMathObject());
287
309
  addIntrinsics(tameRegExpConstructor(regExpTaming));
288
310
  addIntrinsics(tameSymbolConstructor());
289
311
  addIntrinsics(shimArrayBufferTransfer());
@@ -357,13 +379,22 @@ export const repairIntrinsics = (options = {}) => {
357
379
  tameFauxDataProperties(intrinsics);
358
380
 
359
381
  /**
360
- * 2. WHITELIST to standardize the environment.
382
+ * 2. Enforce PERMITS on shared intrinsics
361
383
  */
362
384
 
363
385
  // Remove non-standard properties.
364
- // All remaining function encountered during whitelisting are
386
+ // All remaining functions encountered during whitelisting are
365
387
  // branded as honorary native functions.
366
- whitelistIntrinsics(intrinsics, markVirtualizedNativeFunction);
388
+ reportInGroup(
389
+ 'SES Removing unpermitted intrinsics',
390
+ reporter,
391
+ groupReporter =>
392
+ removeUnpermittedIntrinsics(
393
+ intrinsics,
394
+ markVirtualizedNativeFunction,
395
+ groupReporter,
396
+ ),
397
+ );
367
398
 
368
399
  // Initialize the powerful initial global, i.e., the global of the
369
400
  // start compartment, from the intrinsics.
@@ -425,7 +456,14 @@ export const repairIntrinsics = (options = {}) => {
425
456
  // therefore before vetted shims rather than afterwards. It is not
426
457
  // clear yet which is better.
427
458
  // @ts-ignore enablePropertyOverrides does its own input validation
428
- enablePropertyOverrides(intrinsics, overrideTaming, overrideDebug);
459
+ reportInGroup('SES Enabling property overrides', reporter, groupReporter =>
460
+ enablePropertyOverrides(
461
+ intrinsics,
462
+ overrideTaming,
463
+ groupReporter,
464
+ overrideDebug,
465
+ ),
466
+ );
429
467
  if (legacyRegeneratorRuntimeTaming === 'unsafe-ignore') {
430
468
  tameRegeneratorRuntime();
431
469
  }
@@ -1,7 +1,7 @@
1
1
  // Portions adapted from V8 - Copyright 2016 the V8 project authors.
2
2
  // https://github.com/v8/v8/blob/master/src/builtins/builtins-function.cc
3
3
 
4
- import { apply, freeze } from './commons.js';
4
+ import { apply, arrayFlatMap, freeze, identity } from './commons.js';
5
5
  import { strictScopeTerminator } from './strict-scope-terminator.js';
6
6
  import { createSloppyGlobalsScopeTerminator } from './sloppy-globals-scope-terminator.js';
7
7
  import { makeEvalScopeKit } from './eval-scope.js';
@@ -62,11 +62,13 @@ export const makeSafeEvaluator = ({
62
62
 
63
63
  // Execute the mandatory transforms last to ensure that any rewritten code
64
64
  // meets those mandatory requirements.
65
- source = applyTransforms(source, [
66
- ...localTransforms,
67
- ...globalTransforms,
68
- mandatoryTransforms,
69
- ]);
65
+ source = applyTransforms(
66
+ source,
67
+ arrayFlatMap(
68
+ [localTransforms, globalTransforms, [mandatoryTransforms]],
69
+ identity,
70
+ ),
71
+ );
70
72
 
71
73
  let err;
72
74
  try {
@@ -1,3 +1,5 @@
1
+ /** @import {ModuleExportsNamespace} from '../types.js' */
2
+
1
3
  import { assert } from './error/assert.js';
2
4
  import { getDeferredExports } from './module-proxy.js';
3
5
  import {
@@ -131,13 +133,15 @@ export const makeModuleInstance = (
131
133
  __fixedExportMap__: fixedExportMap = {},
132
134
  __liveExportMap__: liveExportMap = {},
133
135
  __reexportMap__: reexportMap = {},
136
+ __needsImport__: needsImport = false,
134
137
  __needsImportMeta__: needsImportMeta = false,
135
138
  __syncModuleFunctor__,
136
139
  } = moduleSource;
137
140
 
138
141
  const compartmentFields = weakmapGet(privateFields, compartment);
139
142
 
140
- const { __shimTransforms__, importMetaHook } = compartmentFields;
143
+ const { __shimTransforms__, resolveHook, importMetaHook, compartmentImport } =
144
+ compartmentFields;
141
145
 
142
146
  const { exportsProxy, exportsTarget, activate } = getDeferredExports(
143
147
  compartment,
@@ -171,6 +175,14 @@ export const makeModuleInstance = (
171
175
  importMetaHook(moduleSpecifier, importMeta);
172
176
  }
173
177
 
178
+ /** @type {(fullSpecifier: string) => Promise<ModuleExportsNamespace>} */
179
+ let dynamicImport;
180
+ if (needsImport) {
181
+ /** @param {string} importSpecifier */
182
+ dynamicImport = async importSpecifier =>
183
+ compartmentImport(resolveHook(importSpecifier, moduleSpecifier));
184
+ }
185
+
174
186
  // {_localName_: [{get, set, notify}]} used to merge all the export updaters.
175
187
  const localGetNotify = create(null);
176
188
 
@@ -462,6 +474,7 @@ export const makeModuleInstance = (
462
474
  imports: freeze(imports),
463
475
  onceVar: freeze(onceVar),
464
476
  liveVar: freeze(liveVar),
477
+ import: dynamicImport,
465
478
  importMeta,
466
479
  }),
467
480
  );
@@ -76,27 +76,27 @@ function mayBeVirtualModuleSource(moduleSource) {
76
76
  function validateVirtualModuleSource(moduleSource, moduleSpecifier) {
77
77
  const { exports } = moduleSource;
78
78
  isArray(exports) ||
79
- Fail`Property 'exports' of a third-party module source must be an array, got ${q(
79
+ Fail`Invalid module source: 'exports' of a virtual module source must be an array, got ${q(
80
80
  exports,
81
81
  )}, for module ${q(moduleSpecifier)}`;
82
82
  }
83
83
 
84
84
  function validateModuleSource(moduleSource, moduleSpecifier) {
85
85
  isObject(moduleSource) ||
86
- Fail`Module sources must be of type object, got ${q(
86
+ Fail`Invalid module source: must be of type object, got ${q(
87
87
  moduleSource,
88
88
  )}, for module ${q(moduleSpecifier)}`;
89
89
  const { imports, exports, reexports = [] } = moduleSource;
90
90
  isArray(imports) ||
91
- Fail`Property 'imports' of a module source must be an array, got ${q(
91
+ Fail`Invalid module source: 'imports' must be an array, got ${q(
92
92
  imports,
93
93
  )}, for module ${q(moduleSpecifier)}`;
94
94
  isArray(exports) ||
95
- Fail`Property 'exports' of a precompiled module source must be an array, got ${q(
95
+ Fail`Invalid module source: 'exports' must be an array, got ${q(
96
96
  exports,
97
97
  )}, for module ${q(moduleSpecifier)}`;
98
98
  isArray(reexports) ||
99
- Fail`Property 'reexports' of a precompiled module source must be an array if present, got ${q(
99
+ Fail`Invalid module source: 'reexports' must be an array if present, got ${q(
100
100
  reexports,
101
101
  )}, for module ${q(moduleSpecifier)}`;
102
102
  }
@@ -138,9 +138,7 @@ export const instantiate = (
138
138
  resolvedImports,
139
139
  );
140
140
  } else {
141
- throw TypeError(
142
- `importHook must provide a module source, got ${q(moduleSource)}`,
143
- );
141
+ throw TypeError(`Invalid module source, got ${q(moduleSource)}`);
144
142
  }
145
143
 
146
144
  // Memoize.
@@ -6,11 +6,13 @@ import {
6
6
  arrayJoin,
7
7
  arrayMap,
8
8
  arrayPush,
9
+ arraySome,
9
10
  create,
10
11
  freeze,
11
12
  generatorNext,
12
13
  generatorThrow,
13
14
  getOwnPropertyNames,
15
+ isArray,
14
16
  isObject,
15
17
  mapGet,
16
18
  mapHas,
@@ -85,14 +87,23 @@ const loadModuleSource = (
85
87
  moduleLoads,
86
88
  importMeta,
87
89
  ) => {
88
- const { resolveHook } = weakmapGet(compartmentPrivateFields, compartment);
90
+ const { resolveHook, name: compartmentName } = weakmapGet(
91
+ compartmentPrivateFields,
92
+ compartment,
93
+ );
94
+
95
+ const { imports } = moduleSource;
96
+ if (
97
+ !isArray(imports) ||
98
+ arraySome(imports, specifier => typeof specifier !== 'string')
99
+ ) {
100
+ throw makeError(
101
+ X`Invalid module source: 'imports' must be an array of strings, got ${imports} for module ${q(moduleSpecifier)} of compartment ${q(compartmentName)}`,
102
+ );
103
+ }
89
104
 
90
105
  // resolve all imports relative to this referrer module.
91
- const resolvedImports = resolveAll(
92
- moduleSource.imports,
93
- resolveHook,
94
- moduleSpecifier,
95
- );
106
+ const resolvedImports = resolveAll(imports, resolveHook, moduleSpecifier);
96
107
  const moduleRecord = freeze({
97
108
  compartment,
98
109
  moduleSource,