shadowrealm-api

ShadowRealm polyfill for browser

Usage no npm install needed!

<script type="module">
  import shadowrealmApi from 'https://cdn.skypack.dev/shadowrealm-api';
</script>

README

ShadowRealm API Polyfill

A implementation of the ShadowRealm API Proposal, a JavaScript sandbox, test with TC39 Test262 cases.

įŽ€äŊ“中文 | English

declare class ShadowRealm {
    constructor();
    evaluate(sourceText: string): Primitive | Function;
    importValue(specifier: string, bindingName: string): Promise<Primitive | Function>;
}

Try it now 🎉

Install

npm i -S shadowrealm-api

Usage

Ponyfill: non-invasive

import ShadowRealm from 'shadowrealm-api'

const realm = new ShadowRealm();

Polyfill: patch up the global object

import 'shadowrealm-api/browser/polyfill.mjs'

const realm = new ShadowRealm();

Debugging

Print internal info for debugging

ShadowRealm.__debug = true;

Limitations

  1. All code evaluated inside a ShadowRealm runs in strict mode;
  2. The ESM statement must not contain redundant comments;
// ❌
import/* */defaultExport from "module-name";
export default/* */'xxx';

// ✅
import defaultExport from "module-name";
export default 'xxx';
  1. Exporting variable declarations is not supported;
// ❌
export const obj = {...}, fn = () => {...};

// ✅
const obj = {...}, fn = () => {...};
export { obj, fn };

Compatibility

IE Edge Firefox Chrome Safari Opera
10[1][2][3] 12[1][2][3] 4[1][2][3][4] 13[1][2][3][4] 6[1][2][3] 12.1[1][2][3][4]
14 19[1][2][3] 19[1][2][3] 8[3] 15[1][2][3]
29[1][3] 32[1][3] 10.1 19[1][3]
41 49 36

Notes:

  1. Don't support destructuring assignment in ESM statement;
  2. Need Promise polyfill in ShadowRealm;
  3. Need fetch polyfill in top window;
  4. Need URL polyfill in top window;

Use fetch or URL polyfill:

import "fetch polyfill";
import "URL polyfill";
import "shadowrealm-api/browser/polyfill.mjs";
// Your codes

Use Promise polyfill:

ShadowRealm.__shims = [
    'path/to/promise-polyfill.js',
    'other polyfills',
];

Contact

  1. WeChat: cai_fanwei
  2. QQ Group: 663286147
  3. E-mail: ambit_tsai@qq.com