ses 1.13.1 → 1.15.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.
Files changed (41) hide show
  1. package/README.md +70 -52
  2. package/dist/lockdown.cjs +1346 -948
  3. package/dist/lockdown.mjs +1346 -948
  4. package/dist/lockdown.umd.js +1346 -948
  5. package/dist/lockdown.umd.min.js +1 -1
  6. package/dist/ses-hermes.cjs +1328 -804
  7. package/dist/ses.cjs +1346 -948
  8. package/dist/ses.mjs +1346 -948
  9. package/dist/ses.umd.js +1346 -948
  10. package/dist/ses.umd.min.js +1 -1
  11. package/dist/types.d.cts +115 -141
  12. package/package.json +19 -102
  13. package/src/assert-shim.js +2 -2
  14. package/src/cauterize-property.js +2 -2
  15. package/src/commons.js +111 -50
  16. package/src/compartment.js +25 -8
  17. package/src/enable-property-overrides.js +4 -4
  18. package/src/enablements.js +7 -8
  19. package/src/error/assert.js +126 -101
  20. package/src/error/note-log-args.js +5 -4
  21. package/src/error/stringify-utils.js +2 -2
  22. package/src/error/tame-v8-error-constructor.js +15 -12
  23. package/src/error/types.js +1 -1
  24. package/src/get-anonymous-intrinsics.js +0 -1
  25. package/src/global-object.js +3 -3
  26. package/src/intrinsics.js +8 -8
  27. package/src/lockdown.js +34 -12
  28. package/src/make-hardener.js +4 -4
  29. package/src/module-instance.js +22 -18
  30. package/src/module-link.js +4 -4
  31. package/src/module-load.js +48 -13
  32. package/src/permits-intrinsics.js +8 -8
  33. package/src/permits.js +5 -0
  34. package/src/reporting.js +48 -12
  35. package/src/scope-constants.js +19 -25
  36. package/src/tame-locale-methods.js +2 -2
  37. package/src/tame-regenerator-runtime.js +2 -2
  38. package/src/transforms.js +9 -7
  39. package/types.d.ts +115 -141
  40. package/src/error/README.md +0 -99
  41. package/src/make-lru-cachemap.js +0 -221
package/src/intrinsics.js CHANGED
@@ -11,8 +11,8 @@ import {
11
11
  getOwnPropertyDescriptors,
12
12
  globalThis,
13
13
  is,
14
- isObject,
15
- objectHasOwnProperty,
14
+ isPrimitive,
15
+ hasOwn,
16
16
  values,
17
17
  weaksetHas,
18
18
  } from './commons.js';
@@ -37,7 +37,7 @@ const isFunction = obj => typeof obj === 'function';
37
37
  // get masked as one overwrites the other. Accordingly, the thrown error
38
38
  // complains of a "Conflicting definition".
39
39
  function initProperty(obj, name, desc) {
40
- if (objectHasOwnProperty(obj, name)) {
40
+ if (hasOwn(obj, name)) {
41
41
  const preDesc = getOwnPropertyDescriptor(obj, name);
42
42
  if (
43
43
  !preDesc ||
@@ -69,7 +69,7 @@ function initProperties(obj, descs) {
69
69
  function sampleGlobals(globalObject, newPropertyNames) {
70
70
  const newIntrinsics = { __proto__: null };
71
71
  for (const [globalName, intrinsicName] of entries(newPropertyNames)) {
72
- if (objectHasOwnProperty(globalObject, globalName)) {
72
+ if (hasOwn(globalObject, globalName)) {
73
73
  newIntrinsics[intrinsicName] = globalObject[globalName];
74
74
  }
75
75
  }
@@ -94,11 +94,11 @@ export const makeIntrinsicsCollector = reporter => {
94
94
  // to the intrinsics.
95
95
  const completePrototypes = () => {
96
96
  for (const [name, intrinsic] of entries(intrinsics)) {
97
- if (!isObject(intrinsic)) {
97
+ if (isPrimitive(intrinsic)) {
98
98
  // eslint-disable-next-line no-continue
99
99
  continue;
100
100
  }
101
- if (!objectHasOwnProperty(intrinsic, 'prototype')) {
101
+ if (!hasOwn(intrinsic, 'prototype')) {
102
102
  // eslint-disable-next-line no-continue
103
103
  continue;
104
104
  }
@@ -120,12 +120,12 @@ export const makeIntrinsicsCollector = reporter => {
120
120
  }
121
121
  if (
122
122
  typeof namePrototype !== 'string' ||
123
- !objectHasOwnProperty(permitted, namePrototype)
123
+ !hasOwn(permitted, namePrototype)
124
124
  ) {
125
125
  throw TypeError(`Unrecognized ${name}.prototype permits entry`);
126
126
  }
127
127
  const intrinsicPrototype = intrinsic.prototype;
128
- if (objectHasOwnProperty(intrinsics, namePrototype)) {
128
+ if (hasOwn(intrinsics, namePrototype)) {
129
129
  if (intrinsics[namePrototype] !== intrinsicPrototype) {
130
130
  throw TypeError(`Conflicting bindings of ${namePrototype}`);
131
131
  }
package/src/lockdown.js CHANGED
@@ -25,6 +25,7 @@ import {
25
25
  is,
26
26
  ownKeys,
27
27
  stringSplit,
28
+ symbolFor,
28
29
  noEvalEvaluate,
29
30
  getOwnPropertyNames,
30
31
  getPrototypeOf,
@@ -363,6 +364,30 @@ export const repairIntrinsics = (options = {}) => {
363
364
 
364
365
  const intrinsics = finalIntrinsics();
365
366
 
367
+ // Install Object[@harden] or abort.
368
+ const symbolForHarden = symbolFor('harden');
369
+ const priorHarden = intrinsics.Object[symbolForHarden];
370
+ if (priorHarden) {
371
+ // By convention, if a module like @endo/harden gets used before lockdown,
372
+ // it will install itself as a non-configurable, non-writable property over
373
+ // Object[@harden] so that versions of SES predating the introduction of
374
+ // Object[@harden] will fail to lockdown because they cannot remove an
375
+ // unknown intrinsic.
376
+ // All newer versions explicitly check for Object[@harden] (here).
377
+ // The @endo/harden implementation additionally captures a stack trace
378
+ // where harden was first used to assist developers in tracking down the
379
+ // hardened module that was initialized before lockdown.
380
+ if (priorHarden.lockdownError) {
381
+ throw priorHarden.lockdownError;
382
+ }
383
+ // And in the event a library installs Object[@harden] without leaving a
384
+ // hint, we fall back to a generic lockdown error.
385
+ throw new TypeError(
386
+ 'Cannot lockdown (repairIntrinsics) if a prior harden implementation has been used and installed. Check for libraries using @endo/harden before lockdown.',
387
+ );
388
+ }
389
+ intrinsics.Object[symbolForHarden] = tamedHarden;
390
+
366
391
  const hostIntrinsics = { __proto__: null };
367
392
 
368
393
  // The Node.js Buffer is a derived class of Uint8Array, and as such is often
@@ -404,19 +429,16 @@ export const repairIntrinsics = (options = {}) => {
404
429
  );
405
430
  }
406
431
 
432
+ // The default `assert` installed by `assert-shim.js` does not redact errors,
433
+ // leaving `lockdown` or `repairIntrinsics` with the obligation to replace it
434
+ // with a redacting version, unless the caller opts-out with errorTaming set
435
+ // to `unsafe` or `unsafe-debug`.
436
+ // The inverse was true through version 1.13.0, except the configuration
437
+ // was disregarded and the redacting `assert` left in place if lexical
438
+ // `assert` differed from `globalThis.assert`.
407
439
  // @ts-ignore assert is absent on globalThis type def.
408
- if (
409
- (errorTaming === 'unsafe' || errorTaming === 'unsafe-debug') &&
410
- globalThis.assert === assert
411
- ) {
412
- // If errorTaming is 'unsafe' or 'unsafe-debug' we replace the
413
- // global assert with
414
- // one whose `details` template literal tag does not redact
415
- // unmarked substitution values. IOW, it blabs information that
416
- // was supposed to be secret from callers, as an aid to debugging
417
- // at a further cost in safety.
418
- // @ts-ignore assert is absent on globalThis type def.
419
- globalThis.assert = makeAssert(undefined, true);
440
+ if (errorTaming !== 'unsafe' && errorTaming !== 'unsafe-debug') {
441
+ globalThis.assert = makeAssert();
420
442
  }
421
443
 
422
444
  // Replace *Locale* methods with their non-locale equivalents
@@ -35,8 +35,8 @@ import {
35
35
  getOwnPropertyDescriptors,
36
36
  getPrototypeOf,
37
37
  isInteger,
38
- isObject,
39
- objectHasOwnProperty,
38
+ isPrimitive,
39
+ hasOwn,
40
40
  ownKeys,
41
41
  preventExtensions,
42
42
  setAdd,
@@ -151,7 +151,7 @@ export const makeHardener = () => {
151
151
  * @param {any} val
152
152
  */
153
153
  function enqueue(val) {
154
- if (!isObject(val)) {
154
+ if (isPrimitive(val)) {
155
155
  // ignore primitives
156
156
  return;
157
157
  }
@@ -206,7 +206,7 @@ export const makeHardener = () => {
206
206
  // test could be confused. We use hasOwnProperty to be sure about
207
207
  // whether 'value' is present or not, which tells us for sure that
208
208
  // this is a data property.
209
- if (objectHasOwnProperty(desc, 'value')) {
209
+ if (hasOwn(desc, 'value')) {
210
210
  enqueue(desc.value);
211
211
  } else {
212
212
  enqueue(desc.get);
@@ -354,6 +354,25 @@ export const makeModuleInstance = (
354
354
  };
355
355
  notifiers['*'] = notifyStar;
356
356
 
357
+ const wireUpExportNotifier = (exportName, notify) => {
358
+ if (!notifiers[exportName] && notify !== false) {
359
+ notifiers[exportName] = notify;
360
+
361
+ // exported live binding state
362
+ let value;
363
+ const update = newValue => (value = newValue);
364
+ notify(update);
365
+ exportsProps[exportName] = {
366
+ get() {
367
+ return value;
368
+ },
369
+ set: undefined,
370
+ enumerable: true,
371
+ configurable: false,
372
+ };
373
+ }
374
+ };
375
+
357
376
  // Per the calling convention for the moduleFunctor generated from
358
377
  // an ESM, the `imports` function gets called once up front
359
378
  // to populate or arrange the population of imports and reexports.
@@ -407,30 +426,15 @@ export const makeModuleInstance = (
407
426
  }
408
427
  }
409
428
  if (reexportMap[specifier]) {
410
- // Make named reexports candidates too.
429
+ // Set up reexport notifiers instantly so they are available in cycles.
411
430
  for (const [localName, exportedName] of reexportMap[specifier]) {
412
- candidateAll[exportedName] = importNotifiers[localName];
431
+ wireUpExportNotifier(exportedName, importNotifiers[localName]);
413
432
  }
414
433
  }
415
434
  }
416
435
 
417
436
  for (const [exportName, notify] of entries(candidateAll)) {
418
- if (!notifiers[exportName] && notify !== false) {
419
- notifiers[exportName] = notify;
420
-
421
- // exported live binding state
422
- let value;
423
- const update = newValue => (value = newValue);
424
- notify(update);
425
- exportsProps[exportName] = {
426
- get() {
427
- return value;
428
- },
429
- set: undefined,
430
- enumerable: true,
431
- configurable: false,
432
- };
433
- }
437
+ wireUpExportNotifier(exportName, notify);
434
438
  }
435
439
 
436
440
  // Sort the module exports namespace as per spec.
@@ -11,7 +11,7 @@ import {
11
11
  TypeError,
12
12
  entries,
13
13
  isArray,
14
- isObject,
14
+ isPrimitive,
15
15
  mapGet,
16
16
  mapHas,
17
17
  mapSet,
@@ -59,11 +59,11 @@ function mayBePrecompiledModuleSource(moduleSource) {
59
59
 
60
60
  function validatePrecompiledModuleSource(moduleSource, moduleSpecifier) {
61
61
  const { __fixedExportMap__, __liveExportMap__ } = moduleSource;
62
- isObject(__fixedExportMap__) ||
62
+ !isPrimitive(__fixedExportMap__) ||
63
63
  Fail`Property '__fixedExportMap__' of a precompiled module source must be an object, got ${q(
64
64
  __fixedExportMap__,
65
65
  )}, for module ${q(moduleSpecifier)}`;
66
- isObject(__liveExportMap__) ||
66
+ !isPrimitive(__liveExportMap__) ||
67
67
  Fail`Property '__liveExportMap__' of a precompiled module source must be an object, got ${q(
68
68
  __liveExportMap__,
69
69
  )}, for module ${q(moduleSpecifier)}`;
@@ -82,7 +82,7 @@ function validateVirtualModuleSource(moduleSource, moduleSpecifier) {
82
82
  }
83
83
 
84
84
  function validateModuleSource(moduleSource, moduleSpecifier) {
85
- isObject(moduleSource) ||
85
+ !isPrimitive(moduleSource) ||
86
86
  Fail`Invalid module source: must be of type object, got ${q(
87
87
  moduleSource,
88
88
  )}, for module ${q(moduleSpecifier)}`;
@@ -13,7 +13,7 @@ import {
13
13
  generatorThrow,
14
14
  getOwnPropertyNames,
15
15
  isArray,
16
- isObject,
16
+ isPrimitive,
17
17
  mapGet,
18
18
  mapHas,
19
19
  mapSet,
@@ -186,7 +186,7 @@ function* loadWithoutErrorAnnotation(
186
186
  )} in parent compartment, use {source} module descriptor`,
187
187
  TypeError,
188
188
  );
189
- } else if (isObject(moduleDescriptor)) {
189
+ } else if (!isPrimitive(moduleDescriptor)) {
190
190
  // In this shim (and not in XS, and not in the standard we imagine), we
191
191
  // allow a module namespace object to stand in for a module descriptor that
192
192
  // describes its original {compartment, specifier} so that it can be used
@@ -209,7 +209,7 @@ function* loadWithoutErrorAnnotation(
209
209
  namespace: aliasSpecifier,
210
210
  } = moduleDescriptor;
211
211
  if (
212
- !isObject(aliasCompartment) ||
212
+ isPrimitive(aliasCompartment) ||
213
213
  !weakmapHas(compartmentPrivateFields, aliasCompartment)
214
214
  ) {
215
215
  throw makeError(
@@ -233,7 +233,7 @@ function* loadWithoutErrorAnnotation(
233
233
 
234
234
  // All remaining objects must either be a module namespace, or be
235
235
  // promoted into a module namespace with a virtual module source.
236
- if (isObject(moduleDescriptor.namespace)) {
236
+ if (!isPrimitive(moduleDescriptor.namespace)) {
237
237
  const { namespace } = moduleDescriptor;
238
238
  // Brand-check SES shim module exports namespaces:
239
239
  aliasDescriptor = weakmapGet(moduleAliases, namespace);
@@ -406,7 +406,7 @@ function* loadWithoutErrorAnnotation(
406
406
  moduleDescriptor.specifier !== undefined
407
407
  ) {
408
408
  if (
409
- !isObject(moduleDescriptor.compartment) ||
409
+ isPrimitive(moduleDescriptor.compartment) ||
410
410
  !weakmapHas(compartmentPrivateFields, moduleDescriptor.compartment) ||
411
411
  typeof moduleDescriptor.specifier !== 'string'
412
412
  ) {
@@ -507,7 +507,12 @@ const memoizedLoadWithErrorAnnotation = (
507
507
  return moduleLoading;
508
508
  };
509
509
 
510
- const asyncJobQueue = (errors = []) => {
510
+ /**
511
+ * If `aggregateErrors` is `false`, the `errors` property of the fulfilled object
512
+ * will always be empty.
513
+ * @param {{errors?: Error[], noAggregateErrors?: boolean}} [options]
514
+ */
515
+ const asyncJobQueue = ({ errors = [], noAggregateErrors = false } = {}) => {
511
516
  /** @type {Set<Promise<undefined>>} */
512
517
  const pendingJobs = new Set();
513
518
 
@@ -523,7 +528,11 @@ const asyncJobQueue = (errors = []) => {
523
528
  setAdd(
524
529
  pendingJobs,
525
530
  promiseThen(func(...args), noop, error => {
526
- arrayPush(errors, error);
531
+ if (noAggregateErrors) {
532
+ throw error;
533
+ } else {
534
+ arrayPush(errors, error);
535
+ }
527
536
  }),
528
537
  );
529
538
  };
@@ -540,7 +549,12 @@ const asyncJobQueue = (errors = []) => {
540
549
  return { enqueueJob, drainQueue, errors };
541
550
  };
542
551
 
543
- const syncJobQueue = (errors = []) => {
552
+ /**
553
+ * If `aggregateErrors` is `false`, the `errors` property of the returned object
554
+ * will always be empty.
555
+ * @param {{errors?: Error[], noAggregateErrors?: boolean}} [options]
556
+ */
557
+ const syncJobQueue = ({ errors = [], noAggregateErrors = false } = {}) => {
544
558
  let current = [];
545
559
  let next = [];
546
560
 
@@ -564,7 +578,11 @@ const syncJobQueue = (errors = []) => {
564
578
  try {
565
579
  func(...args);
566
580
  } catch (error) {
567
- arrayPush(errors, error);
581
+ if (noAggregateErrors) {
582
+ throw error;
583
+ } else {
584
+ arrayPush(errors, error);
585
+ }
568
586
  }
569
587
  }
570
588
  current = next;
@@ -597,18 +615,24 @@ const throwAggregateError = ({ errors, errorPrefix }) => {
597
615
  const preferSync = (_asyncImpl, syncImpl) => syncImpl;
598
616
  const preferAsync = (asyncImpl, _syncImpl) => asyncImpl;
599
617
 
600
- /*
618
+ /**
601
619
  * `load` asynchronously gathers the module records for a module and its
602
620
  * transitive dependencies.
603
621
  * The module records refer to each other by a reference to the dependency's
604
622
  * compartment and the specifier of the module within its own compartment.
605
623
  * This graph is then ready to be synchronously linked and executed.
624
+ * @param {WeakMap<Compartment, any>} compartmentPrivateFields
625
+ * @param {WeakMap<object, object>} moduleAliases
626
+ * @param {Compartment} compartment
627
+ * @param {string} moduleSpecifier - The module specifier to load.
628
+ * @param {{ noAggregateErrors?: boolean}} options
606
629
  */
607
630
  export const load = async (
608
631
  compartmentPrivateFields,
609
632
  moduleAliases,
610
633
  compartment,
611
634
  moduleSpecifier,
635
+ { noAggregateErrors = false } = {},
612
636
  ) => {
613
637
  const { name: compartmentName } = weakmapGet(
614
638
  compartmentPrivateFields,
@@ -618,7 +642,9 @@ export const load = async (
618
642
  /** @type {Map<object, Map<string, Promise<Record<any, any>>>>} */
619
643
  const moduleLoads = new Map();
620
644
 
621
- const { enqueueJob, drainQueue, errors } = asyncJobQueue();
645
+ const { enqueueJob, drainQueue, errors } = asyncJobQueue({
646
+ noAggregateErrors,
647
+ });
622
648
 
623
649
  enqueueJob(memoizedLoadWithErrorAnnotation, [
624
650
  compartmentPrivateFields,
@@ -640,18 +666,25 @@ export const load = async (
640
666
  });
641
667
  };
642
668
 
643
- /*
669
+ /**
644
670
  * `loadNow` synchronously gathers the module records for a specified module
645
671
  * and its transitive dependencies.
646
672
  * The module records refer to each other by a reference to the dependency's
647
673
  * compartment and the specifier of the module within its own compartment.
648
674
  * This graph is then ready to be synchronously linked and executed.
675
+ * @param {WeakMap<Compartment, any>} compartmentPrivateFields
676
+ * @param {WeakMap<object, object>} moduleAliases
677
+ * @param {Compartment} compartment
678
+ * @param {string} moduleSpecifier - The module specifier to load.
679
+ * @param {{ noAggregateErrors?: boolean}} options
649
680
  */
681
+
650
682
  export const loadNow = (
651
683
  compartmentPrivateFields,
652
684
  moduleAliases,
653
685
  compartment,
654
686
  moduleSpecifier,
687
+ { noAggregateErrors = false } = {},
655
688
  ) => {
656
689
  const { name: compartmentName } = weakmapGet(
657
690
  compartmentPrivateFields,
@@ -661,7 +694,9 @@ export const loadNow = (
661
694
  /** @type {Map<object, Map<string, Promise<Record<any, any>>>>} */
662
695
  const moduleLoads = new Map();
663
696
 
664
- const { enqueueJob, drainQueue, errors } = syncJobQueue();
697
+ const { enqueueJob, drainQueue, errors } = syncJobQueue({
698
+ noAggregateErrors,
699
+ });
665
700
 
666
701
  enqueueJob(memoizedLoadWithErrorAnnotation, [
667
702
  compartmentPrivateFields,
@@ -55,9 +55,9 @@ import {
55
55
  entries,
56
56
  getOwnPropertyDescriptor,
57
57
  getPrototypeOf,
58
- isObject,
58
+ isPrimitive,
59
59
  mapGet,
60
- objectHasOwnProperty,
60
+ hasOwn,
61
61
  ownKeys,
62
62
  symbolKeyFor,
63
63
  } from './commons.js';
@@ -131,8 +131,8 @@ export default function removeUnpermittedIntrinsics(
131
131
  * Validate the object's [[prototype]] against a permit.
132
132
  */
133
133
  function visitPrototype(path, obj, protoName) {
134
- if (!isObject(obj)) {
135
- throw TypeError(`Object expected: ${path}, ${obj}, ${protoName}`);
134
+ if (isPrimitive(obj)) {
135
+ throw TypeError(`Object expected: ${path}, ${String(obj)}, ${protoName}`);
136
136
  }
137
137
  const proto = getPrototypeOf(obj);
138
138
 
@@ -185,7 +185,7 @@ export default function removeUnpermittedIntrinsics(
185
185
  // Assert: the permit is the name of an intrinsic.
186
186
  // Assert: the property value is equal to that intrinsic.
187
187
 
188
- if (objectHasOwnProperty(intrinsics, permit)) {
188
+ if (hasOwn(intrinsics, permit)) {
189
189
  if (value !== intrinsics[permit]) {
190
190
  throw TypeError(`Does not match permit for ${path}`);
191
191
  }
@@ -225,7 +225,7 @@ export default function removeUnpermittedIntrinsics(
225
225
  }
226
226
 
227
227
  // Is this a value property?
228
- if (objectHasOwnProperty(desc, 'value')) {
228
+ if (hasOwn(desc, 'value')) {
229
229
  if (isAccessorPermit(permit)) {
230
230
  throw TypeError(`Accessor expected at ${path}`);
231
231
  }
@@ -245,12 +245,12 @@ export default function removeUnpermittedIntrinsics(
245
245
  */
246
246
  function getSubPermit(obj, permit, prop) {
247
247
  const permitProp = prop === '__proto__' ? '--proto--' : prop;
248
- if (objectHasOwnProperty(permit, permitProp)) {
248
+ if (hasOwn(permit, permitProp)) {
249
249
  return permit[permitProp];
250
250
  }
251
251
 
252
252
  if (typeof obj === 'function') {
253
- if (objectHasOwnProperty(FunctionInstance, permitProp)) {
253
+ if (hasOwn(FunctionInstance, permitProp)) {
254
254
  return FunctionInstance[permitProp];
255
255
  }
256
256
  }
package/src/permits.js CHANGED
@@ -507,6 +507,11 @@ export const permitted = {
507
507
  seal: fn,
508
508
  setPrototypeOf: fn,
509
509
  values: fn,
510
+ 'RegisteredSymbol(harden)': {
511
+ ...fn,
512
+ // Installed with hardenTaming: 'unsafe'
513
+ isFake: 'boolean',
514
+ },
510
515
  // https://github.com/tc39/proposal-accessible-object-hasownproperty
511
516
  hasOwn: fn,
512
517
  // https://github.com/tc39/proposal-array-grouping
package/src/reporting.js CHANGED
@@ -1,13 +1,45 @@
1
- import { functionBind, globalThis } from './commons.js';
1
+ import { globalThis } from './commons.js';
2
2
  import { assert } from './error/assert.js';
3
3
 
4
4
  /**
5
5
  * @import {Reporter, GroupReporter} from './reporting-types.js'
6
6
  */
7
7
 
8
+ /* eslint-disable @endo/no-polymorphic-call */
9
+ /**
10
+ * To address https://github.com/endojs/endo/issues/2908,
11
+ * the `consoleReporter` uses the current `console` rather
12
+ * than the original one.
13
+ *
14
+ * @type {GroupReporter}
15
+ */
16
+ const consoleReporter = {
17
+ warn(...args) {
18
+ globalThis.console.warn(...args);
19
+ },
20
+ error(...args) {
21
+ globalThis.console.error(...args);
22
+ },
23
+ ...(globalThis.console?.groupCollapsed
24
+ ? {
25
+ groupCollapsed(...args) {
26
+ globalThis.console.groupCollapsed(...args);
27
+ },
28
+ }
29
+ : undefined),
30
+ ...(globalThis.console?.groupEnd
31
+ ? {
32
+ groupEnd() {
33
+ globalThis.console.groupEnd();
34
+ },
35
+ }
36
+ : undefined),
37
+ };
38
+ /* eslint-enable @endo/no-polymorphic-call */
39
+
8
40
  /**
9
41
  * Creates a suitable reporter for internal errors and warnings out of the
10
- * Node.js console.error to ensure all messages to go stderr, including the
42
+ * Node.js console.error to ensure all messages go to stderr, including the
11
43
  * group label.
12
44
  * Accounts for the extra space introduced by console.error as a delimiter
13
45
  * between the indent and subsequent arguments.
@@ -51,18 +83,22 @@ export const chooseReporter = reporting => {
51
83
  if (reporting === 'none') {
52
84
  return makeReportPrinter(mute);
53
85
  }
54
- if (
55
- reporting === 'console' ||
56
- globalThis.window === globalThis ||
57
- globalThis.importScripts !== undefined
58
- ) {
59
- return console;
60
- }
61
86
  if (globalThis.console !== undefined) {
87
+ if (
88
+ reporting === 'console' || // asks for console explicitly
89
+ globalThis.window === globalThis || // likely on browser
90
+ globalThis.importScripts !== undefined // likely on worker
91
+ ) {
92
+ // reporter just delegates directly to the current console
93
+ return consoleReporter;
94
+ }
95
+ assert(reporting === 'platform');
62
96
  // On Node.js, we send all feedback to stderr, regardless of purported level.
63
- const console = globalThis.console;
64
- const error = functionBind(console.error, console);
65
- return makeReportPrinter(error);
97
+ // This uses `consoleReporter.error` instead of `console.error` because we
98
+ // want the constructed reporter to use the `console.error` of the current
99
+ // `console`, not the `console` that was installed when the reporter
100
+ // was created.
101
+ return makeReportPrinter(consoleReporter.error);
66
102
  }
67
103
  if (globalThis.print !== undefined) {
68
104
  return makeReportPrinter(globalThis.print);
@@ -3,16 +3,19 @@ import {
3
3
  arrayIncludes,
4
4
  getOwnPropertyDescriptor,
5
5
  getOwnPropertyNames,
6
- objectHasOwnProperty,
7
- regexpTest,
6
+ hasOwn,
7
+ regexpExec,
8
+ Set,
9
+ setHas,
8
10
  } from './commons.js';
9
11
 
10
12
  /**
11
- * keywords
12
- * In JavaScript you cannot use these reserved words as variables.
13
- * See 11.6.1 Identifier Names
13
+ * reservedNames
14
+ * In JavaScript you cannot use reserved words as variable names (except for
15
+ * "eval", which is specially reserved to prevent shadowing).
16
+ * https://tc39.es/ecma262/multipage/ecmascript-language-lexical-grammar.html#sec-identifier-names
14
17
  */
15
- const keywords = [
18
+ const reservedNames = new Set([
16
19
  // 11.6.2.1 Keywords
17
20
  'await',
18
21
  'break',
@@ -73,7 +76,10 @@ const keywords = [
73
76
 
74
77
  'this',
75
78
  'arguments',
76
- ];
79
+
80
+ // Reserved by us
81
+ 'eval',
82
+ ]);
77
83
 
78
84
  /**
79
85
  * identifierPattern
@@ -89,24 +95,12 @@ const identifierPattern = /^[a-zA-Z_$][\w$]*$/;
89
95
 
90
96
  /**
91
97
  * isValidIdentifierName()
92
- * What variable names might it bring into scope? These include all
93
- * property names which can be variable names, including the names
94
- * of inherited properties. It excludes symbols and names which are
95
- * keywords. We drop symbols safely. Currently, this shim refuses
96
- * service if any of the names are keywords or keyword-like. This is
97
- * safe and only prevent performance optimization.
98
+ * Is a value allowed as an arbitrary identifier name?
98
99
  *
99
100
  * @param {string} name
100
101
  */
101
- export const isValidIdentifierName = name => {
102
- // Ensure we have a valid identifier. We use regexpTest rather than
103
- // /../.test() to guard against the case where RegExp has been poisoned.
104
- return (
105
- name !== 'eval' &&
106
- !arrayIncludes(keywords, name) &&
107
- regexpTest(identifierPattern, name)
108
- );
109
- };
102
+ export const isValidIdentifierName = name =>
103
+ !setHas(reservedNames, name) && !!regexpExec(identifierPattern, name);
110
104
 
111
105
  /*
112
106
  * isImmutableDataProperty
@@ -131,18 +125,18 @@ function isImmutableDataProperty(obj, name) {
131
125
  // can't have accessors and value properties at the same time, therefore
132
126
  // this check is sufficient. Using explicit own property deal with the
133
127
  // case where Object.prototype has been poisoned.
134
- objectHasOwnProperty(desc, 'value')
128
+ hasOwn(desc, 'value')
135
129
  );
136
130
  }
137
131
 
138
132
  /**
139
133
  * getScopeConstants()
140
- * What variable names might it bring into scope? These include all
134
+ * What variable names might be brought into scope? These include all
141
135
  * property names which can be variable names, including the names
142
136
  * of inherited properties. It excludes symbols and names which are
143
137
  * keywords. We drop symbols safely. Currently, this shim refuses
144
138
  * service if any of the names are keywords or keyword-like. This is
145
- * safe and only prevent performance optimization.
139
+ * safe and only affects performance optimization.
146
140
  *
147
141
  * @param {object} globalObject
148
142
  * @param {object} moduleLexicals
@@ -4,7 +4,7 @@ import {
4
4
  TypeError,
5
5
  defineProperty,
6
6
  getOwnPropertyNames,
7
- isObject,
7
+ isPrimitive,
8
8
  regexpExec,
9
9
  } from './commons.js';
10
10
  import { assert } from './error/assert.js';
@@ -54,7 +54,7 @@ export default function tameLocaleMethods(intrinsics, localeTaming = 'safe') {
54
54
 
55
55
  for (const intrinsicName of getOwnPropertyNames(intrinsics)) {
56
56
  const intrinsic = intrinsics[intrinsicName];
57
- if (isObject(intrinsic)) {
57
+ if (!isPrimitive(intrinsic)) {
58
58
  for (const methodName of getOwnPropertyNames(intrinsic)) {
59
59
  const match = regexpExec(localePattern, methodName);
60
60
  if (match) {