├── src ├── swc.d.ts ├── utils │ ├── resolve-import.ts │ ├── error.ts │ ├── random-identifier.ts │ ├── resolve-pattern.ts │ └── make-node.ts ├── options.ts ├── swc.js ├── esbuild.ts ├── find.ts ├── find.spec.ts ├── bundle-info.ts ├── bundle-info.spec.ts ├── index.ts ├── transform.ts └── transform.spec.ts ├── .prettierignore ├── .prettierrc ├── exports ├── import.mjs ├── require.cjs └── require.d.cts ├── jest.config.js ├── .gitignore ├── .github └── workflows │ ├── publish.yaml │ └── test.yaml ├── tsconfig.json ├── LICENSE ├── package.json └── README.md /src/swc.d.ts: -------------------------------------------------------------------------------- 1 | export * from "@swc/core"; 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | /dist 2 | /e2e/dist 3 | /coverage 4 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "endOfLine": "lf", 3 | "printWidth": 120, 4 | "arrowParens": "avoid", 5 | "trailingComma": "none" 6 | } 7 | -------------------------------------------------------------------------------- /exports/import.mjs: -------------------------------------------------------------------------------- 1 | import { default as m } from "../dist/index.js"; 2 | export default typeof m === "function" ? m : m.default; 3 | -------------------------------------------------------------------------------- /exports/require.cjs: -------------------------------------------------------------------------------- 1 | module.exports = require("../dist/index").default; 2 | module.exports.default = require("../dist/index").default; 3 | -------------------------------------------------------------------------------- /exports/require.d.cts: -------------------------------------------------------------------------------- 1 | import type _default from "../dist/index.d.ts"; 2 | declare const _export: typeof _default & { default: typeof _default }; 3 | export = _export; 4 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ 2 | module.exports = { 3 | preset: "ts-jest", 4 | testEnvironment: "node", 5 | setupFilesAfterEnv: ["jest-extended/all"], 6 | testPathIgnorePatterns: ["/dist/", "/node_modules/"] 7 | }; 8 | -------------------------------------------------------------------------------- /src/utils/resolve-import.ts: -------------------------------------------------------------------------------- 1 | import { posix as path } from "path"; 2 | 3 | export function resolveImport(base: string, imported: string) { 4 | // Skip external packages 5 | if (!(imported.startsWith("./") || imported.startsWith("../"))) return null; 6 | 7 | return path.join(path.dirname(base), imported); 8 | } 9 | -------------------------------------------------------------------------------- /src/utils/error.ts: -------------------------------------------------------------------------------- 1 | export function raiseUnexpectedNode(nodeType: string, type: string): never { 2 | /* istanbul ignore next */ 3 | throw new Error( 4 | `Unexpected ${nodeType} "${type}" in Rollup's output chunk. Please open an issue at https://github.com/Menci/vite-plugin-top-level-await/issues.` 5 | ); 6 | } 7 | -------------------------------------------------------------------------------- /src/options.ts: -------------------------------------------------------------------------------- 1 | export interface Options { 2 | /** 3 | * @default "__tla" 4 | */ 5 | promiseExportName?: string; 6 | 7 | /** 8 | * @default i => `__tla_${i}` 9 | */ 10 | promiseImportName?: (i: number) => string; 11 | } 12 | 13 | export const DEFAULT_OPTIONS: Options = { 14 | promiseExportName: "__tla", 15 | promiseImportName: i => `__tla_${i}` 16 | }; 17 | -------------------------------------------------------------------------------- /src/swc.js: -------------------------------------------------------------------------------- 1 | /* istanbul ignore file */ 2 | let SWC; 3 | try { 4 | if (process.env.VITE_TLA_FORCE_WASM === "true") { 5 | throw new Error("Force using @swc/wasm"); 6 | } 7 | SWC = require("@swc/core"); 8 | } catch (e) { 9 | if (process.env.VITE_TLA_FORCE_NATIVE === "true") { 10 | throw e; 11 | } 12 | SWC = require("@swc/wasm"); 13 | } 14 | 15 | module.exports = SWC; 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /dist 13 | /e2e/dist 14 | 15 | # misc 16 | .DS_Store 17 | .env.local 18 | .env.development.local 19 | .env.test.local 20 | .env.production.local 21 | 22 | npm-debug.log* 23 | yarn-debug.log* 24 | yarn-error.log* 25 | 26 | .vscode 27 | -------------------------------------------------------------------------------- /src/utils/random-identifier.ts: -------------------------------------------------------------------------------- 1 | import { v5 } from "uuid"; 2 | 3 | export class RandomIdentifierGenerator { 4 | private state: string; 5 | 6 | constructor(seed: string) { 7 | const INITIAL_NAMESPACE = "7976c25e-8279-4241-9a9a-e1831e9feab1"; 8 | this.state = v5(seed, INITIAL_NAMESPACE); 9 | } 10 | 11 | generate() { 12 | this.state = v5(this.state, this.state); 13 | return "var_" + this.state.split("-").join("_"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/esbuild.ts: -------------------------------------------------------------------------------- 1 | // Import the `esbuild` package installed by `vite` 2 | 3 | import path from "path"; 4 | const Module = require("module"); 5 | 6 | function requireFrom(self: any, contextModuleName: string, wantedModuleName: string) { 7 | const contextModulePath = Module._resolveFilename(contextModuleName, self); 8 | const virtualModule = new Module(contextModulePath, module); 9 | virtualModule.filename = contextModulePath; 10 | virtualModule.paths = Module._nodeModulePaths(path.dirname(contextModulePath)); 11 | return virtualModule.require(wantedModuleName); 12 | } 13 | 14 | export default requireFrom(module, "vite", "esbuild") as typeof import("esbuild"); 15 | -------------------------------------------------------------------------------- /.github/workflows/publish.yaml: -------------------------------------------------------------------------------- 1 | name: NPM Publish 2 | 3 | on: 4 | push: 5 | tags: v* 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | name: NPM Publish 11 | steps: 12 | - uses: actions/checkout@v3 13 | - name: Setup node 14 | uses: actions/setup-node@v3 15 | with: 16 | node-version: 22 17 | - name: Install dependencies 18 | run: yarn --frozen-lockfile 19 | - name: Build 20 | run: yarn build 21 | - name: Test 22 | run: yarn test 23 | - name: Publish 24 | uses: JS-DevTools/npm-publish@v2 25 | with: 26 | token: ${{ secrets.NPM_TOKEN }} 27 | tag: ${{ endsWith(github.ref_name, 'next') && 'next' || 'latest' }} 28 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2019", 4 | "lib": [ 5 | "ES2019" 6 | ], 7 | "allowJs": true, 8 | "skipLibCheck": true, 9 | "experimentalDecorators": true, 10 | "esModuleInterop": true, 11 | "allowSyntheticDefaultImports": true, 12 | "forceConsistentCasingInFileNames": true, 13 | "moduleResolution": "node", 14 | "resolveJsonModule": true, 15 | "isolatedModules": true, 16 | "strict": false, 17 | "module": "CommonJS", 18 | "strictBindCallApply": true, 19 | "noFallthroughCasesInSwitch": false, 20 | "baseUrl": "./", 21 | "outDir": "./dist", 22 | "declaration": true 23 | }, 24 | "include": [ 25 | "src" 26 | ], 27 | "exclude": [ 28 | "node_modules", 29 | "dist", 30 | "**/*.test.ts" 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Menci 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/utils/resolve-pattern.ts: -------------------------------------------------------------------------------- 1 | import * as SWC from "../swc"; 2 | import { raiseUnexpectedNode } from "./error"; 3 | 4 | export function resolvePattern(pattern: SWC.Pattern): string | string[] { 5 | switch (pattern.type) { 6 | case "Identifier": 7 | return pattern.value; 8 | case "ObjectPattern": 9 | return pattern.properties.flatMap(prop => { 10 | switch (prop.type) { 11 | case "AssignmentPatternProperty": 12 | return prop.key.value; 13 | case "RestElement": 14 | return resolvePattern(prop.argument); 15 | case "KeyValuePatternProperty": 16 | return resolvePattern(prop.value); 17 | } 18 | }); 19 | case "ArrayPattern": 20 | return pattern.elements 21 | .filter(elem => elem) 22 | .flatMap(elem => { 23 | if (elem.type === "RestElement") { 24 | return resolvePattern(elem.argument); 25 | } 26 | 27 | return resolvePattern(elem); 28 | }); 29 | case "AssignmentPattern": 30 | return resolvePattern(pattern.left); 31 | /* istanbul ignore next */ 32 | default: 33 | raiseUnexpectedNode("pattern in variable declaration", pattern.type); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vite-plugin-top-level-await", 3 | "version": "1.6.0", 4 | "description": "Transform code to support top-level await in normal browsers for Vite.", 5 | "main": "./exports/require.cjs", 6 | "module": "./exports/import.mjs", 7 | "exports": { 8 | "import": { 9 | "types": "./dist/index.d.ts", 10 | "default": "./exports/import.mjs" 11 | }, 12 | "require": { 13 | "types": "./exports/require.d.cts", 14 | "default": "./exports/require.cjs" 15 | } 16 | }, 17 | "repository": "https://github.com/Menci/vite-plugin-top-level-await", 18 | "author": "Menci ", 19 | "license": "MIT", 20 | "keywords": [ 21 | "vite", 22 | "plugin", 23 | "top-level await", 24 | "await" 25 | ], 26 | "scripts": { 27 | "build": "tsc", 28 | "test": "jest --verbose --coverage", 29 | "format": "prettier --write '**/*.{mjs,cjs,js,ts}'" 30 | }, 31 | "devDependencies": { 32 | "@types/jest": "^30.0.0", 33 | "@types/uuid": "^10.0.0", 34 | "cz-conventional-changelog": "^3.3.0", 35 | "esbuild": "^0.25.6", 36 | "jest": "29.7.0", 37 | "jest-extended": "^6.0.0", 38 | "prettier": "^3.6.2", 39 | "ts-jest": "29.2.6", 40 | "typescript": "^5.8.3", 41 | "vite": "^7.0.5" 42 | }, 43 | "dependencies": { 44 | "@rollup/plugin-virtual": "^3.0.2", 45 | "@swc/core": "^1.12.14", 46 | "@swc/wasm": "^1.12.14", 47 | "uuid": "10.0.0" 48 | }, 49 | "peerDependencies": { 50 | "vite": ">=2.8" 51 | }, 52 | "config": { 53 | "commitizen": { 54 | "path": "./node_modules/cz-conventional-changelog" 55 | } 56 | }, 57 | "files": [ 58 | "/dist", 59 | "!/dist/**/*.spec.js", 60 | "!/dist/**/*.spec.d.ts", 61 | "/exports" 62 | ] 63 | } 64 | -------------------------------------------------------------------------------- /.github/workflows/test.yaml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | push: 5 | pull_request: 6 | 7 | jobs: 8 | build: 9 | runs-on: ${{ matrix.os }} 10 | strategy: 11 | fail-fast: false 12 | matrix: 13 | os: [ubuntu-latest, windows-latest] 14 | node: ["14", "16", "18", "20", "22"] 15 | vite: ["2", "3", "4", "5", "6", "7"] 16 | exclude: 17 | # Vite 5 doesn't support Node.js <= 16 18 | - node: "14" 19 | vite: "5" 20 | - node: "16" 21 | vite: "5" 22 | # Vite 5 doesn't support Node.js <= 16 23 | - node: "14" 24 | vite: "6" 25 | - node: "16" 26 | vite: "6" 27 | # Vite 7 doesn't support Node.js <= 18 28 | - node: "14" 29 | vite: "7" 30 | - node: "16" 31 | vite: "7" 32 | - node: "18" 33 | vite: "7" 34 | name: Node.js ${{ matrix.node }} + Vite ${{ matrix.vite }} on ${{ matrix.os }} 35 | steps: 36 | - uses: actions/checkout@v4 37 | - name: Setup node 38 | uses: actions/setup-node@v4 39 | with: 40 | node-version: ${{ matrix.node }} 41 | - name: Set yarn to ignore engines version check 42 | run: yarn config set ignore-engines true 43 | - name: Install dependencies 44 | run: yarn --frozen-lockfile 45 | - name: Install specified version of Vite 46 | run: yarn add vite@^${{ matrix.vite }} 47 | - name: Build 48 | run: yarn build 49 | - name: Test (Native) 50 | run: yarn test 51 | env: 52 | VITE_TLA_FORCE_NATIVE: "true" 53 | - name: Test (WASM) 54 | run: yarn test 55 | env: 56 | VITE_TLA_FORCE_WASM: "true" 57 | - name: Check style 58 | if: ${{ matrix.os != 'windows-latest' }} 59 | run: yarn format --check 60 | -------------------------------------------------------------------------------- /src/find.ts: -------------------------------------------------------------------------------- 1 | import * as SWC from "./swc"; 2 | import { Visitor } from "@swc/core/Visitor"; 3 | 4 | // Throw an exception when found top-level await to exit earlier from AST traversal 5 | class FoundTopLevelAwaitError extends Error {} 6 | 7 | class FindPatternsVisitor extends Visitor { 8 | // Set the flag when a dynamic import is found 9 | public foundDynamicImport = false; 10 | 11 | // Tell if one await is in top-level or not 12 | private currentLevel = 0; 13 | 14 | // Hook class/function visiting functions so we can know the current level 15 | constructor() { 16 | super(); 17 | 18 | const visitor = this; 19 | function hook(methodName: keyof Visitor) { 20 | const originalFunction = visitor[methodName] as Function; 21 | (visitor[methodName] as Function) = function () { 22 | /* istanbul ignore next */ 23 | // A optimize: if we have already found dynamic imports, don't go deeper 24 | if (visitor.foundDynamicImport) return arguments[0]; 25 | 26 | visitor.currentLevel++; 27 | const result = originalFunction.apply(this, arguments); 28 | visitor.currentLevel--; 29 | return result; 30 | }; 31 | } 32 | 33 | hook("visitClass"); 34 | hook("visitArrowFunctionExpression"); 35 | hook("visitFunction"); 36 | hook("visitMethodProperty"); 37 | } 38 | 39 | visitAwaitExpression(expr: SWC.AwaitExpression): SWC.Expression { 40 | if (this.currentLevel === 0) throw new FoundTopLevelAwaitError(); 41 | return super.visitAwaitExpression(expr); 42 | } 43 | 44 | visitForOfStatement(stmt: SWC.ForOfStatement): SWC.Statement { 45 | if (stmt.await && this.currentLevel === 0) { 46 | throw new FoundTopLevelAwaitError(); 47 | } 48 | return super.visitForOfStatement(stmt); 49 | } 50 | 51 | visitCallExpression(expr: SWC.CallExpression): SWC.Expression { 52 | if (expr.callee.type === "Import") this.foundDynamicImport = true; 53 | return super.visitCallExpression(expr); 54 | } 55 | } 56 | 57 | export enum CodePattern { 58 | TopLevelAwait = "TopLevelAwait", 59 | DynamicImport = "DynamicImport" 60 | } 61 | 62 | // Return the "highest" pattern found in the code 63 | // i.e. if we found top-level await, we don't care if there're any dynamic imports then 64 | export function findHighestPattern(ast: SWC.Module): CodePattern { 65 | try { 66 | const visitor = new FindPatternsVisitor(); 67 | visitor.visitModule(ast); 68 | 69 | if (visitor.foundDynamicImport) return CodePattern.DynamicImport; 70 | } catch (e) { 71 | if (e instanceof FoundTopLevelAwaitError) return CodePattern.TopLevelAwait; 72 | 73 | /* istanbul ignore next */ 74 | throw e; 75 | } 76 | 77 | return null; 78 | } 79 | -------------------------------------------------------------------------------- /src/find.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | import * as SWC from "./swc"; 4 | 5 | import { CodePattern, findHighestPattern } from "./find"; 6 | 7 | function test(highestPattern: CodePattern, code: string) { 8 | expect(findHighestPattern(SWC.parseSync(code, { target: "es2022", syntax: "ecmascript" }))).toBe(highestPattern); 9 | } 10 | 11 | describe("Find top-level await usage in module", () => { 12 | it("should work with top-level await", () => { 13 | test( 14 | CodePattern.TopLevelAwait, 15 | ` 16 | await Promise.resolve(0); 17 | ` 18 | ); 19 | }); 20 | 21 | it("should work with top-level await in a complex expression", () => { 22 | test( 23 | CodePattern.TopLevelAwait, 24 | ` 25 | const x = x?.y[fun([await z])]; 26 | ` 27 | ); 28 | }); 29 | 30 | it("should work without top-level await", () => { 31 | test( 32 | null, 33 | ` 34 | console.log("qwq"); 35 | ` 36 | ); 37 | }); 38 | 39 | it("should work with top-level for-await statements", () => { 40 | test( 41 | CodePattern.TopLevelAwait, 42 | ` 43 | for await (const x of y) { 44 | console.log(x); 45 | } 46 | ` 47 | ); 48 | }); 49 | 50 | it("should work with top-level for (non-await) statements", () => { 51 | test( 52 | null, 53 | ` 54 | for (const x of y) { 55 | console.log(x); 56 | } 57 | ` 58 | ); 59 | }); 60 | 61 | it("should work with top-level await in block statements", () => { 62 | test( 63 | CodePattern.TopLevelAwait, 64 | ` 65 | for (const x of y) { 66 | if (x === 1) { 67 | console.log(await x.func()); 68 | } 69 | } 70 | ` 71 | ); 72 | }); 73 | 74 | it("should work with await in functions", () => { 75 | test( 76 | null, 77 | ` 78 | console.log(async () => await x.func()); 79 | async function test() { 80 | for await (const y of x) { 81 | console.log(y); 82 | } 83 | } 84 | ` 85 | ); 86 | }); 87 | 88 | it("should work with await in class methods", () => { 89 | test( 90 | null, 91 | ` 92 | const Class = class Class { 93 | async method() { 94 | await x.func(); 95 | } 96 | } 97 | 98 | class Class2 { 99 | async method2() { 100 | for await (const y of x) { 101 | console.log(y); 102 | } 103 | } 104 | } 105 | ` 106 | ); 107 | }); 108 | 109 | it("should work with dynamic import but without top-level await", () => { 110 | test( 111 | CodePattern.DynamicImport, 112 | ` 113 | function qwqwq() { 114 | return import("qwq"); 115 | } 116 | ` 117 | ); 118 | }); 119 | 120 | it("should work with await in object method property", () => { 121 | test( 122 | null, 123 | ` 124 | const obj = { 125 | async method() { 126 | await x.func(); 127 | } 128 | } 129 | ` 130 | ); 131 | }); 132 | }); 133 | -------------------------------------------------------------------------------- /src/bundle-info.ts: -------------------------------------------------------------------------------- 1 | import * as SWC from "./swc"; 2 | import { CodePattern, findHighestPattern } from "./find"; 3 | 4 | import { resolveImport } from "./utils/resolve-import"; 5 | 6 | export interface ModuleInfo { 7 | imported: string[]; 8 | importedBy: string[]; 9 | withTopLevelAwait: boolean; 10 | transformNeeded: boolean; 11 | } 12 | 13 | export type BundleInfo = Record; 14 | 15 | export async function parseBundleAsts(bundleChunks: Record): Promise> { 16 | return Object.fromEntries( 17 | await Promise.all( 18 | Object.entries(bundleChunks).map( 19 | async ([filename, code]) => 20 | [ 21 | filename, 22 | await SWC.parse(code, { 23 | syntax: "ecmascript", 24 | target: "es2022" 25 | }) 26 | ] as const 27 | ) 28 | ) 29 | ); 30 | } 31 | 32 | export async function parseBundleInfo(bundleAsts: Record): Promise { 33 | const bundleInfo = Object.fromEntries( 34 | Object.keys(bundleAsts).map(moduleName => [ 35 | moduleName, 36 | { 37 | imported: null, 38 | importedBy: [], 39 | transformNeeded: null 40 | } 41 | ]) 42 | ); 43 | 44 | // Pass 1: build dependency graph and its reverse graph 45 | // determine top-level await and dynamic import usage in each module 46 | for (const moduleName in bundleAsts) { 47 | const ast = bundleAsts[moduleName]; 48 | const moduleInfo = bundleInfo[moduleName]; 49 | 50 | // Parse imports 51 | moduleInfo.imported = ast.body 52 | .map(item => { 53 | if (item.type === "ImportDeclaration" || (item.type === "ExportNamedDeclaration" && item.source)) { 54 | return resolveImport(moduleName, item.source.value); 55 | } 56 | }) 57 | .filter(x => x); 58 | 59 | // Add reverse edges for dependency graph traversal 60 | moduleInfo.imported.forEach(importedModuleName => { 61 | if (bundleInfo[importedModuleName]) { 62 | bundleInfo[importedModuleName].importedBy.push(moduleName); 63 | } else { 64 | /* istanbul ignore next */ 65 | console.warn( 66 | `[vite-plugin-top-level-await] Non-existing module ${JSON.stringify( 67 | importedModuleName 68 | )} imported by ${JSON.stringify(moduleName)}, ignoring.` 69 | ); 70 | } 71 | }); 72 | 73 | const highestPattern = findHighestPattern(ast); 74 | moduleInfo.transformNeeded = 75 | highestPattern === CodePattern.TopLevelAwait || highestPattern === CodePattern.DynamicImport; 76 | moduleInfo.withTopLevelAwait = highestPattern === CodePattern.TopLevelAwait; 77 | } 78 | 79 | // Pass 2: transfer each modules's "top-level await usage" property to all successors in reverse graph 80 | const q: string[] = Object.entries(bundleInfo) 81 | .filter(([, module]) => module.withTopLevelAwait) 82 | .map(([moduleName]) => moduleName); 83 | while (q.length > 0) { 84 | const moduleName = q.shift(); 85 | 86 | for (const nextModuleName of bundleInfo[moduleName].importedBy) { 87 | // Skip modules which are already enqueued once 88 | if (bundleInfo[nextModuleName].withTopLevelAwait) continue; 89 | 90 | // Enqueue next module 91 | bundleInfo[nextModuleName].withTopLevelAwait = true; 92 | bundleInfo[nextModuleName].transformNeeded = true; 93 | q.push(nextModuleName); 94 | } 95 | } 96 | 97 | return bundleInfo; 98 | } 99 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vite-plugin-top-level-await 2 | 3 | [![Test Status](https://img.shields.io/github/actions/workflow/status/Menci/vite-plugin-top-level-await/test.yaml?branch=main&style=flat-square)](https://github.com/Menci/vite-plugin-top-level-await/actions?query=workflow%3ATest) 4 | [![npm](https://img.shields.io/npm/v/vite-plugin-top-level-await?style=flat-square)](https://www.npmjs.com/package/vite-plugin-top-level-await) 5 | [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg?style=flat-square)](http://commitizen.github.io/cz-cli/) 6 | [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) 7 | [![License](https://img.shields.io/github/license/Menci/vite-plugin-top-level-await?style=flat-square)](LICENSE) 8 | 9 | Transform code to support top-level await in normal browsers for Vite. Support all modern browsers of Vite's default target without need to set `build.target` to `esnext`. 10 | 11 | ## Installation 12 | 13 | ```bash 14 | yarn add -D vite-plugin-top-level-await 15 | ``` 16 | 17 | ## Usage 18 | 19 | Put this plugin in your plugin list. At most case you don't need to care the order, but if there're any plugin transforming bundle before it, there's a little chance that this plugin fails to parse code since it does only parse Rollup's output `export { ... }` export statement. 20 | 21 | ```typescript 22 | import topLevelAwait from "vite-plugin-top-level-await"; 23 | 24 | export default defineConfig({ 25 | plugins: [ 26 | topLevelAwait({ 27 | // The export name of top-level await promise for each chunk module 28 | promiseExportName: "__tla", 29 | // The function to generate import names of top-level await promise in each chunk module 30 | promiseImportName: i => `__tla_${i}` 31 | }) 32 | ] 33 | }); 34 | ``` 35 | 36 | ## Workers 37 | 38 | You can use this plugin for workers (by putting it in `config.worker.plugins`). 39 | 40 | * If the worker format is ES, the plugin works normally. 41 | * If the worker format is IIFE, the plugin first let Vite build your worker as an ES bundle since IIFE doesn't support top-level awaits, and then build the transformed ES bundle to IIFE. Please use IIFE when targeting Firefox. 42 | ```js 43 | const myWorker = import.meta.env.DEV 44 | // In development mode, `import`s in workers are not transformed, so you 45 | // must use `{ type: "module" }`. 46 | ? new Worker(new URL("./my-worker.js", import.meta.url), { type: "module" }) 47 | // In build mode, let Vite and vite-plugin-top-level-await build a single-file 48 | // bundle of your worker that works on both modern browsers and Firefox. 49 | : new Worker(new URL("./my-worker.js", import.meta.url), { type: "classic" }); 50 | ``` 51 | 52 | ## Note 53 | 54 | This plugin transforms code from: 55 | 56 | ```js 57 | import { a } from "./a.js"; // This module uses top-level await 58 | import { b } from "./b.js"; // This module uses top-level await too 59 | import { c } from "./c.js"; // This module does NOT use top-level await 60 | 61 | const x = 1; 62 | await b.func(); 63 | const { y } = await somePromise; 64 | 65 | export { x, y }; 66 | ``` 67 | 68 | To: 69 | 70 | ```js 71 | import { a, __tla as __tla_0 } from "./a.js"; // This module uses top-level await 72 | import { b, __tla as __tla_1 } from "./b.js"; // This module uses top-level await too 73 | import { c } from "./c.js"; // This module does NOT use top-level await 74 | 75 | // Original exported variables 76 | let x, y; 77 | 78 | // Await imported TLA promises and execute original top-level statements 79 | let __tla = Promise.all([ 80 | (() => { try { return __tla_0; } catch {} })(), 81 | (() => { try { return __tla_1; } catch {} })() 82 | ]).then(async () => { 83 | // Transform exported variables to assignments 84 | x = 1; 85 | 86 | await b.func(); 87 | 88 | // Destructing patterns (and function / class declarations as well) are handled correctly 89 | ({ y } = await somePromise); 90 | }); 91 | 92 | // Export top-level await promise 93 | export { x, y, __tla }; 94 | ``` 95 | 96 | It could handle **correct usage** of circular dependencies with the default behavior of ES standard. But when an TLA dependency is being awaited, an accessing to one of its exports **will NOT raise an exception**. At most time you don't need to care about this. These *could* be supported by doing more transformations of the whole AST but it will make building a lot slower. Open an issue and tell me your scenario if you really need the exception. 97 | -------------------------------------------------------------------------------- /src/bundle-info.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | import { parseBundleAsts, parseBundleInfo } from "./bundle-info"; 4 | 5 | function makeTestcase( 6 | dependencyGraph: Record, 7 | moduleWithTopLevelAwait: string[], 8 | moduleWithDynamicImport: string[] 9 | ): Record { 10 | return Object.fromEntries( 11 | Object.entries(dependencyGraph).map(([moduleName, importedModules]) => [ 12 | moduleName, 13 | importedModules.map(name => `import ${name} from "./${name}";\n`).join("") + 14 | (moduleWithDynamicImport.includes(moduleName) ? "function qwq() { return import(window.someModule); }" : "") + 15 | (moduleWithTopLevelAwait.includes(moduleName) ? "await Promise.resolve(0);\n" : "") + 16 | "export default null;\n" 17 | ]) 18 | ); 19 | } 20 | 21 | describe("Bundle info parser", () => { 22 | it("should parse AST of esnext code with SWC correctly", async () => { 23 | const chunks = { 24 | a: ` 25 | import { x } from "./b"; 26 | const w = await x?.y?.z; 27 | export { w }; 28 | `, 29 | b: ` 30 | import { w } from "./a"; 31 | const x = await w?.x?.y; 32 | export { x }; 33 | ` 34 | }; 35 | 36 | const bundleAsts = await parseBundleAsts(chunks); 37 | 38 | for (const moduleName in chunks) { 39 | expect(bundleAsts[moduleName]).toBeObject(); 40 | expect(bundleAsts[moduleName].type).toBe("Module"); 41 | } 42 | }); 43 | 44 | it("should parse dependencies correctly", async () => { 45 | const chunks = { 46 | a: ` 47 | export { x } from "./b"; 48 | import { s } from "./c"; 49 | const w = await globalThis.y?.z(s); 50 | export { w }; 51 | `, 52 | b: ` 53 | const x = await globalThis.x?.y; 54 | export { x }; 55 | `, 56 | c: ` 57 | const s = await globalThis.p?.q; 58 | export { s }; 59 | ` 60 | }; 61 | 62 | const bundleInfo = await parseBundleInfo(await parseBundleAsts(chunks)); 63 | 64 | expect(bundleInfo["a"]).toBeTruthy(); 65 | expect(bundleInfo["a"].imported).toIncludeSameMembers(["b", "c"]); 66 | expect(bundleInfo["a"].importedBy).toIncludeSameMembers([]); 67 | expect(bundleInfo["b"]).toBeTruthy(); 68 | expect(bundleInfo["b"].imported).toIncludeSameMembers([]); 69 | expect(bundleInfo["b"].importedBy).toIncludeSameMembers(["a"]); 70 | expect(bundleInfo["c"]).toBeTruthy(); 71 | expect(bundleInfo["c"].imported).toIncludeSameMembers([]); 72 | expect(bundleInfo["c"].importedBy).toIncludeSameMembers(["a"]); 73 | }); 74 | 75 | it("should parse side-effect-only imports correctly", async () => { 76 | const chunks = { 77 | a: ` 78 | import "./b"; 79 | const x = 1; 80 | export { x }; 81 | `, 82 | b: ` 83 | const y = await globalThis.x?.y; 84 | export { y }; 85 | ` 86 | }; 87 | 88 | const bundleInfo = await parseBundleInfo(await parseBundleAsts(chunks)); 89 | 90 | expect(bundleInfo["a"]).toBeTruthy(); 91 | expect(bundleInfo["a"].imported).toIncludeSameMembers(["b"]); 92 | expect(bundleInfo["a"].importedBy).toIncludeSameMembers([]); 93 | expect(bundleInfo["a"].withTopLevelAwait).toBeTrue(); 94 | expect(bundleInfo["a"].transformNeeded).toBeTrue(); 95 | expect(bundleInfo["b"]).toBeTruthy(); 96 | expect(bundleInfo["b"].imported).toIncludeSameMembers([]); 97 | expect(bundleInfo["b"].importedBy).toIncludeSameMembers(["a"]); 98 | expect(bundleInfo["b"].withTopLevelAwait).toBeTrue(); 99 | expect(bundleInfo["b"].transformNeeded).toBeTrue(); 100 | }); 101 | 102 | it("should parse dependency graph correctly", async () => { 103 | const dependencyGraph = { 104 | a: ["b", "c", "d"], 105 | b: ["c", "d"], 106 | c: [], 107 | d: ["b", "f"], 108 | e: ["a", "c"], 109 | f: ["g"], 110 | g: ["h"], 111 | h: ["i"], 112 | i: [] 113 | }; 114 | const bundleInfo = await parseBundleInfo(await parseBundleAsts(makeTestcase(dependencyGraph, [], []))); 115 | 116 | for (const moduleName in bundleInfo) { 117 | expect(bundleInfo[moduleName].imported).toIncludeSameMembers(dependencyGraph[moduleName]); 118 | expect(bundleInfo[moduleName].importedBy).toIncludeSameMembers( 119 | Object.entries(dependencyGraph) 120 | .filter(([, imports]) => imports.includes(moduleName)) 121 | .map(([name]) => name) 122 | ); 123 | } 124 | }); 125 | 126 | it("should determine which modules need transform correctly", async () => { 127 | const dependencyGraph = { 128 | a: ["b", "c", "d"], 129 | b: ["c", "d"], 130 | c: ["i"], 131 | d: ["b", "f"], 132 | e: ["a", "c"], 133 | f: ["g"], 134 | g: ["h"], 135 | h: ["i"], 136 | i: [] 137 | }; 138 | const moduleWithTopLevelAwait = ["f", "h"]; 139 | const moduleWithDynamicImport = ["i"]; 140 | const bundleInfo = await parseBundleInfo( 141 | await parseBundleAsts(makeTestcase(dependencyGraph, moduleWithTopLevelAwait, moduleWithDynamicImport)) 142 | ); 143 | 144 | const expectedModulesNeedTransform = ["a", "b", "d", "e", "f", "g", "h", "i"]; 145 | expect( 146 | Object.entries(bundleInfo) 147 | .filter(([, info]) => info.transformNeeded) 148 | .map(([name]) => name) 149 | ).toIncludeSameMembers(expectedModulesNeedTransform); 150 | }); 151 | }); 152 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import { Plugin, ResolvedConfig } from "vite"; 3 | import { rollup, OutputChunk } from "rollup"; 4 | import virtual from "@rollup/plugin-virtual"; 5 | import * as SWC from "./swc"; 6 | import esbuild from "./esbuild"; 7 | 8 | import { DEFAULT_OPTIONS, Options } from "./options"; 9 | import { parseBundleAsts, parseBundleInfo } from "./bundle-info"; 10 | import { transformModule } from "./transform"; 11 | 12 | export type { Options } from "./options"; 13 | 14 | type ViteTarget = ResolvedConfig["build"]["target"]; 15 | 16 | // Use the same default target as Vite. 17 | // https://github.com/vitejs/vite/blob/v6.0.7/packages/vite/src/node/constants.ts#L70-L76 18 | const DEFAULT_VITE_TARGET: ViteTarget = ["es2020", "edge88", "firefox78", "chrome87", "safari14"]; 19 | 20 | export default function topLevelAwait(options?: Options): Plugin { 21 | const resolvedOptions: Options = { 22 | ...DEFAULT_OPTIONS, 23 | ...(options || {}) 24 | }; 25 | 26 | let isWorker = false; 27 | let isWorkerIifeRequested = false; 28 | 29 | let assetsDir = ""; 30 | let buildTarget: ViteTarget; 31 | let minify: boolean; 32 | 33 | const buildRawTarget = async (code: string) => { 34 | return ( 35 | await esbuild.transform(code, { 36 | minify, 37 | target: buildTarget as string | string[], 38 | format: "esm" 39 | }) 40 | ).code as string; 41 | }; 42 | 43 | return { 44 | name: "vite-plugin-top-level-await", 45 | enforce: "post", 46 | outputOptions(options) { 47 | if (isWorker && options.format === "iife") { 48 | // The the worker bundle's output format to ES to allow top-level awaits 49 | // We'll use another rollup build to convert it back to IIFE 50 | options.format = "es"; 51 | isWorkerIifeRequested = true; 52 | } 53 | }, 54 | config(config, env) { 55 | if (env.command === "build") { 56 | if (config.worker) { 57 | isWorker = true; 58 | } 59 | 60 | // By default Vite transforms code with esbuild with target for a browser list with ES modules support 61 | // This cause esbuild to throw an exception when there're top-level awaits in code 62 | // Let's backup the original target and override the esbuild target with "esnext", which allows TLAs. 63 | // If the user doesn't specify a target explicitly, `config.build.target` will be undefined and we'll 64 | // use the default Vite target. 65 | buildTarget = config.build.target ?? DEFAULT_VITE_TARGET; 66 | config.build.target = "esnext"; 67 | 68 | minify = !!config.build.minify; 69 | 70 | assetsDir = config.build.assetsDir; 71 | } 72 | 73 | if (env.command === "serve") { 74 | // Fix errors in NPM packages which are getting pre-processed in development build 75 | if (config.optimizeDeps?.esbuildOptions) { 76 | config.optimizeDeps.esbuildOptions.target = "esnext"; 77 | } 78 | } 79 | }, 80 | async generateBundle(bundleOptions, bundle) { 81 | // Process ES modules (modern) target only since TLAs in legacy builds are handled by SystemJS 82 | if (bundleOptions.format !== "es") return; 83 | 84 | const bundleChunks = Object.fromEntries( 85 | Object.entries(bundle) 86 | .filter(([, item]) => item.type === "chunk") 87 | .map(([key, item]) => [key, (item as OutputChunk).code]) 88 | ); 89 | const bundleAsts = await parseBundleAsts(bundleChunks); 90 | const bundleInfo = await parseBundleInfo(bundleAsts); 91 | 92 | await Promise.all( 93 | Object.keys(bundleChunks).map(async moduleName => { 94 | if (!bundleInfo[moduleName].transformNeeded) { 95 | if (buildTarget !== "esnext") { 96 | (bundle[moduleName] as OutputChunk).code = await buildRawTarget(bundleChunks[moduleName]); 97 | } 98 | return; 99 | } 100 | 101 | const newAst = transformModule( 102 | bundleChunks[moduleName], 103 | bundleAsts[moduleName], 104 | moduleName, 105 | bundleInfo, 106 | resolvedOptions 107 | ); 108 | let code = SWC.printSync(newAst, { minify }).code; 109 | if (buildTarget !== "esnext") { 110 | code = await buildRawTarget(code); 111 | } 112 | (bundle[moduleName] as OutputChunk).code = code; 113 | }) 114 | ); 115 | 116 | if (isWorker && isWorkerIifeRequested) { 117 | // Get the entry chunk 118 | const chunkNames = Object.keys(bundle).filter(key => bundle[key].type === "chunk"); 119 | const entry = chunkNames.find(key => (bundle[key] as OutputChunk).isEntry); 120 | if (!entry) { 121 | throw new Error(`Entry not found in worker bundle! Please submit an issue with a reproducible project.`); 122 | } 123 | 124 | // Build a new bundle to convert ESM to IIFE 125 | // Assets are not touched 126 | const newBuild = await rollup({ 127 | input: entry, 128 | plugins: [virtual(Object.fromEntries(chunkNames.map(key => [key, (bundle[key] as OutputChunk).code])))] 129 | }); 130 | 131 | // IIFE bundle is always a single file 132 | const { 133 | output: [newEntry] 134 | } = await newBuild.generate({ 135 | format: "iife", 136 | entryFileNames: path.posix.join(assetsDir, "[name].js") 137 | }); 138 | 139 | // Postprocess and minify (if requested) with ESBuild 140 | newEntry.code = ( 141 | await esbuild.transform( 142 | // Polyfill `document.currentScript.src` since it's used for `import.meta.url`. 143 | `self.document = { currentScript: { src: self.location.href } };\n${newEntry.code}`, 144 | { 145 | minify, 146 | target: buildTarget as string | string[] 147 | } 148 | ) 149 | ).code; 150 | 151 | // Remove extra chunks and replace ESM entry with IIFE entry 152 | for (const chunkName of chunkNames) { 153 | if (chunkName !== entry) delete bundle[chunkName]; 154 | } 155 | bundle[entry] = newEntry; 156 | } 157 | } 158 | }; 159 | } 160 | -------------------------------------------------------------------------------- /src/utils/make-node.ts: -------------------------------------------------------------------------------- 1 | import * as SWC from "../swc"; 2 | 3 | function span(): SWC.Span { 4 | return { start: 0, end: 0, ctxt: 0 }; 5 | } 6 | 7 | export function makeIdentifier(name: string): SWC.Identifier { 8 | return { 9 | type: "Identifier", 10 | span: span(), 11 | // @ts-ignore SWC is missing the "ctxt" property's 12 | ctxt: 0, 13 | value: name, 14 | optional: false 15 | }; 16 | } 17 | 18 | export function makeVariablesDeclaration(names: string[]): SWC.VariableDeclaration { 19 | if (names.length === 0) return null; 20 | 21 | return { 22 | type: "VariableDeclaration", 23 | span: span(), 24 | // @ts-ignore SWC is missing the "ctxt" property's 25 | ctxt: 0, 26 | kind: "let", 27 | declare: false, 28 | declarations: names.map(name => ({ 29 | type: "VariableDeclarator", 30 | span: span(), 31 | id: makeIdentifier(name), 32 | init: null, 33 | definite: false 34 | })) 35 | }; 36 | } 37 | 38 | export function makeVariableInitDeclaration(name: string, value: SWC.Expression): SWC.VariableDeclaration { 39 | return { 40 | type: "VariableDeclaration", 41 | span: span(), 42 | // @ts-ignore SWC is missing the "ctxt" property's 43 | ctxt: 0, 44 | kind: "let", 45 | declare: false, 46 | declarations: [ 47 | { 48 | type: "VariableDeclarator", 49 | span: span(), 50 | id: makeIdentifier(name), 51 | init: value, 52 | definite: false 53 | } 54 | ] 55 | }; 56 | } 57 | 58 | export function makeStatement(expression: SWC.Expression): SWC.ExpressionStatement { 59 | return { 60 | type: "ExpressionStatement", 61 | span: span(), 62 | expression 63 | }; 64 | } 65 | 66 | export function makeAssignmentExpression(left: SWC.Pattern, right: SWC.Expression): SWC.AssignmentExpression { 67 | return { 68 | type: "AssignmentExpression", 69 | span: span(), 70 | operator: "=", 71 | left, 72 | right 73 | }; 74 | } 75 | 76 | export function makeAssignmentStatement(left: SWC.Pattern, right: SWC.Expression): SWC.ExpressionStatement { 77 | const assignmentExpression = makeAssignmentExpression(left, right); 78 | return makeStatement( 79 | left.type === "ObjectPattern" ? makeParenthesisExpression(assignmentExpression) : assignmentExpression 80 | ); 81 | } 82 | 83 | export function makeImportSpecifier(name: string, as: string): SWC.ImportSpecifier { 84 | return { 85 | type: "ImportSpecifier", 86 | span: span(), 87 | local: makeIdentifier(as), 88 | imported: as === name ? /* istanbul ignore next */ null : makeIdentifier(name), 89 | isTypeOnly: false 90 | }; 91 | } 92 | 93 | export function makeArrayExpression(items: SWC.Expression[]): SWC.ArrayExpression { 94 | return { 95 | type: "ArrayExpression", 96 | span: span(), 97 | elements: items.map(item => ({ 98 | spread: null, 99 | expression: item 100 | })) 101 | }; 102 | } 103 | 104 | export function makeTryCatchStatement( 105 | tryStatements: SWC.Statement[], 106 | catchStatements: SWC.Statement[] 107 | ): SWC.TryStatement { 108 | return { 109 | type: "TryStatement", 110 | span: span(), 111 | block: { 112 | type: "BlockStatement", 113 | span: span(), 114 | // @ts-ignore SWC is missing the "ctxt" property's 115 | ctxt: 0, 116 | stmts: tryStatements 117 | }, 118 | handler: { 119 | type: "CatchClause", 120 | span: span(), 121 | param: null, 122 | body: { 123 | type: "BlockStatement", 124 | span: span(), 125 | // @ts-ignore SWC is missing the "ctxt" property's 126 | ctxt: 0, 127 | stmts: catchStatements 128 | } 129 | }, 130 | finalizer: null 131 | }; 132 | } 133 | 134 | export function makeArrowFunction( 135 | args: string[], 136 | statements: SWC.Statement[], 137 | async?: boolean 138 | ): SWC.ArrowFunctionExpression { 139 | return { 140 | type: "ArrowFunctionExpression", 141 | span: span(), 142 | ctxt: 0, 143 | params: args.map(arg => ({ 144 | type: "Identifier", 145 | span: span(), 146 | ctxt: 0, 147 | value: arg, 148 | optional: false 149 | })), 150 | body: { 151 | type: "BlockStatement", 152 | span: span(), 153 | // @ts-ignore SWC is missing the "ctxt" property's 154 | ctxt: 0, 155 | stmts: statements 156 | }, 157 | async: !!async, 158 | generator: false, 159 | typeParameters: null, 160 | returnType: null 161 | }; 162 | } 163 | 164 | export function makeParenthesisExpression(expression: SWC.Expression): SWC.ParenthesisExpression { 165 | return { 166 | type: "ParenthesisExpression", 167 | span: span(), 168 | expression 169 | }; 170 | } 171 | 172 | export function makeCallExpression(functionExpression: SWC.Expression, args?: SWC.Expression[]): SWC.CallExpression { 173 | return { 174 | type: "CallExpression", 175 | span: span(), 176 | // @ts-ignore SWC is missing the "ctxt" property's 177 | ctxt: 0, 178 | // Put IIFE's function expression in (parenthesis) 179 | callee: 180 | functionExpression.type === "FunctionExpression" || functionExpression.type === "ArrowFunctionExpression" 181 | ? makeParenthesisExpression(functionExpression) 182 | : functionExpression, 183 | arguments: (args ?? []).map(arg => ({ 184 | spread: null, 185 | expression: arg 186 | })), 187 | typeArguments: null 188 | }; 189 | } 190 | 191 | export function makeReturnStatement(expression: SWC.Expression): SWC.ReturnStatement { 192 | return { 193 | type: "ReturnStatement", 194 | span: span(), 195 | argument: expression 196 | }; 197 | } 198 | 199 | export function makeMemberExpression(object: SWC.Expression | string, member: string): SWC.MemberExpression { 200 | return { 201 | type: "MemberExpression", 202 | span: span(), 203 | object: typeof object === "string" ? makeIdentifier(object) : object, 204 | property: makeIdentifier(member) 205 | }; 206 | } 207 | 208 | export function makeExportListDeclaration(map: [exportName: string, identifier: string][]): SWC.ExportNamedDeclaration { 209 | return { 210 | type: "ExportNamedDeclaration", 211 | span: span(), 212 | specifiers: map.map(([exportName, identifier]) => ({ 213 | type: "ExportSpecifier", 214 | span: span(), 215 | orig: makeIdentifier(identifier), 216 | exported: identifier === exportName ? null : makeIdentifier(exportName), 217 | isTypeOnly: false 218 | })), 219 | source: null, 220 | // @ts-ignore 221 | typeOnly: false, 222 | // @ts-ignore 223 | assets: null 224 | }; 225 | } 226 | 227 | export function makeAwaitExpression(expression: SWC.Expression): SWC.AwaitExpression { 228 | return { 229 | type: "AwaitExpression", 230 | span: span(), 231 | argument: expression 232 | }; 233 | } 234 | 235 | export function makeImportDeclaration(source: SWC.StringLiteral): SWC.ImportDeclaration { 236 | const importDeclaration: SWC.ImportDeclaration = { 237 | type: "ImportDeclaration", 238 | specifiers: [], 239 | source, 240 | span: span(), 241 | typeOnly: false 242 | }; 243 | 244 | return importDeclaration; 245 | } 246 | -------------------------------------------------------------------------------- /src/transform.ts: -------------------------------------------------------------------------------- 1 | import * as SWC from "./swc"; 2 | 3 | import { BundleInfo } from "./bundle-info"; 4 | import { Options } from "./options"; 5 | import { raiseUnexpectedNode } from "./utils/error"; 6 | import { 7 | makeIdentifier, 8 | makeAssignmentStatement, 9 | makeVariablesDeclaration, 10 | makeImportSpecifier, 11 | makeArrayExpression, 12 | makeCallExpression, 13 | makeArrowFunction, 14 | makeTryCatchStatement, 15 | makeReturnStatement, 16 | makeMemberExpression, 17 | makeVariableInitDeclaration, 18 | makeExportListDeclaration, 19 | makeStatement, 20 | makeAwaitExpression, 21 | makeImportDeclaration 22 | } from "./utils/make-node"; 23 | import { RandomIdentifierGenerator } from "./utils/random-identifier"; 24 | import { resolveImport } from "./utils/resolve-import"; 25 | import { resolvePattern } from "./utils/resolve-pattern"; 26 | 27 | function transformByType(node: object, type: string, filter: (node: SWC.Node) => SWC.Node) { 28 | for (const key of Array.isArray(node) ? node.keys() : Object.keys(node)) { 29 | if (["span", "type"].includes(key as string)) continue; 30 | if (!node[key]) continue; 31 | if (typeof node[key] === "object") node[key] = transformByType(node[key], type, filter); 32 | } 33 | 34 | if (node["type"] === type) return filter(node as SWC.Node); 35 | return node; 36 | } 37 | 38 | function declarationToExpression( 39 | decl: SWC.FunctionDeclaration | SWC.ClassDeclaration 40 | ): SWC.FunctionExpression | SWC.ClassExpression { 41 | if (decl.type === "FunctionDeclaration") { 42 | return { 43 | ...decl, 44 | identifier: null, 45 | type: "FunctionExpression" 46 | }; 47 | } else if (decl.type === "ClassDeclaration") { 48 | return { 49 | ...decl, 50 | identifier: null, 51 | type: "ClassExpression" 52 | }; 53 | } else { 54 | /* istanbul ignore next */ 55 | raiseUnexpectedNode("declaration", (decl as SWC.Node).type); 56 | } 57 | } 58 | 59 | function expressionToDeclaration( 60 | expr: SWC.FunctionExpression | SWC.ClassExpression 61 | ): SWC.FunctionDeclaration | SWC.ClassDeclaration { 62 | if (expr.type === "FunctionExpression") { 63 | return { 64 | ...expr, 65 | type: "FunctionDeclaration" 66 | }; 67 | } else if (expr.type === "ClassExpression") { 68 | return { 69 | ...expr, 70 | type: "ClassDeclaration" 71 | }; 72 | } else { 73 | /* istanbul ignore next */ 74 | raiseUnexpectedNode("expression", (expr as SWC.Node).type); 75 | } 76 | } 77 | 78 | export function transformModule( 79 | code: string, 80 | ast: SWC.Module, 81 | moduleName: string, 82 | bundleInfo: BundleInfo, 83 | options: Options 84 | ) { 85 | const randomIdentifier = new RandomIdentifierGenerator(code); 86 | 87 | // Extract import declarations 88 | const imports = ast.body.filter((item): item is SWC.ImportDeclaration => item.type === "ImportDeclaration"); 89 | 90 | // Handle `export { named as renamed } from "module";` 91 | const exportFroms = ast.body.filter( 92 | (item): item is SWC.ExportNamedDeclaration => item.type === "ExportNamedDeclaration" && !!item.source 93 | ); 94 | const newImportsByExportFroms: SWC.ImportDeclaration[] = []; 95 | 96 | const exportMap: Record = {}; 97 | 98 | // Extract export declarations 99 | // In Rollup's output, there should be only one, and as the last top-level statement 100 | // But some plugins (e.g. @vitejs/plugin-legacy) may inject others like "export function" 101 | const namedExports = ast.body.filter((item, i): item is SWC.ExportNamedDeclaration => { 102 | switch (item.type) { 103 | /* istanbul ignore next */ 104 | case "ExportAllDeclaration": 105 | raiseUnexpectedNode("top-level statement", item.type); 106 | case "ExportDefaultExpression": 107 | // Convert to a variable 108 | const identifier = randomIdentifier.generate(); 109 | ast.body[i] = makeVariableInitDeclaration(identifier, item.expression); 110 | exportMap["default"] = identifier; 111 | return false; 112 | case "ExportDefaultDeclaration": 113 | if (item.decl.type === "FunctionExpression" || item.decl.type === "ClassExpression") { 114 | // Convert to a declaration or variable 115 | if (item.decl.identifier) { 116 | ast.body[i] = expressionToDeclaration(item.decl); 117 | exportMap["default"] = item.decl.identifier.value; 118 | } else { 119 | const identifier = randomIdentifier.generate(); 120 | ast.body[i] = makeVariableInitDeclaration(identifier, item.decl); 121 | exportMap["default"] = identifier; 122 | } 123 | } else { 124 | /* istanbul ignore next */ 125 | raiseUnexpectedNode("top-level export declaration", item.decl.type); 126 | } 127 | 128 | return false; 129 | case "ExportDeclaration": 130 | if (item.declaration.type === "FunctionDeclaration" || item.declaration.type === "ClassDeclaration") { 131 | // Remove the "export" keyword from this statement 132 | ast.body[i] = item.declaration; 133 | exportMap[item.declaration.identifier.value] = item.declaration.identifier.value; 134 | } else { 135 | /* istanbul ignore next */ 136 | raiseUnexpectedNode("top-level export declaration", item.declaration.type); 137 | } 138 | 139 | return false; 140 | // Handle `export { named as renamed };` without "from" 141 | case "ExportNamedDeclaration": 142 | if (!item.source) { 143 | item.specifiers.forEach(specifier => { 144 | /* istanbul ignore if */ 145 | if (specifier.type !== "ExportSpecifier") { 146 | raiseUnexpectedNode("export specifier", specifier.type); 147 | } 148 | 149 | exportMap[(specifier.exported || specifier.orig).value] = specifier.orig.value; 150 | }); 151 | } 152 | 153 | return true; 154 | } 155 | 156 | return false; 157 | }); 158 | 159 | const exportedNameSet = new Set(Object.values(exportMap)); 160 | const exportedNames = Array.from(exportedNameSet); 161 | 162 | /* 163 | * Move ALL top-level statements to an async IIFE: 164 | * 165 | * ```js 166 | * export let __tla = Promise.all([ 167 | * // imported TLA promises 168 | * ]).then(async () => { 169 | * // original top-level statements here 170 | * }); 171 | * ``` 172 | * 173 | * And add variable declarations for exported names to new top-level, before the IIFE. 174 | * 175 | * ```js 176 | * let x; 177 | * export let __tla = Promise.all([ 178 | * // imported TLA promises 179 | * ]).then(async () => { 180 | * // const x = 1; 181 | * x = 1; 182 | * }); 183 | * export { x as someExport }; 184 | * ``` 185 | */ 186 | 187 | const topLevelStatements = ast.body.filter( 188 | (item): item is SWC.Statement => 189 | !(imports as SWC.ModuleItem[]).includes(item) && !(namedExports as SWC.ModuleItem[]).includes(item) 190 | ); 191 | const importedNames = new Set( 192 | imports.flatMap(importStmt => importStmt.specifiers.map(specifier => specifier.local.value)) 193 | ); 194 | const exportFromedNames = new Set( 195 | exportFroms.flatMap(exportStmt => 196 | exportStmt.specifiers.map(specifier => { 197 | if (specifier.type === "ExportNamespaceSpecifier") { 198 | return specifier.name.value; 199 | } else if (specifier.type === "ExportDefaultSpecifier") { 200 | // When will this happen? 201 | return specifier.exported.value; 202 | } else { 203 | return (specifier.exported || specifier.orig).value; 204 | } 205 | }) 206 | ) 207 | ); 208 | const exportedNamesDeclaration = makeVariablesDeclaration( 209 | exportedNames.filter(name => !importedNames.has(name) && !exportFromedNames.has(name)) 210 | ); 211 | 212 | const warppedStatements = topLevelStatements.flatMap(stmt => { 213 | if (stmt.type === "VariableDeclaration") { 214 | const declaredNames = stmt.declarations.flatMap(decl => resolvePattern(decl.id)); 215 | const exportedDeclaredNames = declaredNames.filter(name => exportedNameSet.has(name)); 216 | const unexportedDeclaredNames = declaredNames.filter(name => !exportedNameSet.has(name)); 217 | 218 | // None is exported in the declared names, no need to transform 219 | if (exportedDeclaredNames.length === 0) return stmt; 220 | 221 | // Generate assignment statements for init-ed declarators 222 | const assignmentStatements = stmt.declarations 223 | .filter(decl => decl.init) 224 | .map(decl => makeAssignmentStatement(decl.id, decl.init)); 225 | 226 | // Generate variable declarations for unexported variables 227 | const unexportedDeclarations = makeVariablesDeclaration(unexportedDeclaredNames); 228 | 229 | return unexportedDeclarations ? [unexportedDeclarations, ...assignmentStatements] : assignmentStatements; 230 | } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") { 231 | const name = stmt.identifier.value; 232 | if (!exportedNameSet.has(name)) return stmt; 233 | return makeAssignmentStatement(makeIdentifier(name), declarationToExpression(stmt)); 234 | } else { 235 | return stmt; 236 | } 237 | }); 238 | 239 | /* 240 | * Process dynamic imports. 241 | * 242 | * ```js 243 | * [ 244 | * import("some-module-with-tla"), 245 | * import("some-module-without-tla"), 246 | * import(dynamicModuleName) 247 | * ] 248 | * ``` 249 | * 250 | * The expression evaluates to a promise, which will resolve after module loaded, but not after 251 | * out `__tla` promise resolved. 252 | * 253 | * We can check the target module. If the argument is string literial and the target module has NO 254 | * top-level await, we won't need to transform it. 255 | * 256 | * ```js 257 | * [ 258 | * import("some-module-with-tla").then(async m => { await m.__tla; return m; }), 259 | * import("some-module-without-tla"), 260 | * import(dynamicModuleName).then(async m => { await m.__tla; return m; }) 261 | * ] 262 | * ``` 263 | */ 264 | 265 | transformByType(warppedStatements, "CallExpression", (call: SWC.CallExpression) => { 266 | if (call.callee.type === "Import") { 267 | const argument = call.arguments[0].expression; 268 | if (argument.type === "StringLiteral") { 269 | const importedModuleName = resolveImport(moduleName, argument.value); 270 | 271 | // Skip transform 272 | if (importedModuleName && !bundleInfo[importedModuleName]?.transformNeeded) return call; 273 | } 274 | 275 | return makeCallExpression(makeMemberExpression(call, "then"), [ 276 | makeArrowFunction( 277 | ["m"], 278 | [ 279 | makeStatement(makeAwaitExpression(makeMemberExpression("m", options.promiseExportName))), 280 | makeReturnStatement(makeIdentifier("m")) 281 | ], 282 | true 283 | ) 284 | ]); 285 | } 286 | 287 | return call; 288 | }); 289 | 290 | /* 291 | * Import and await the promise "__tla" from each imported module with TLA transform enabled. 292 | * 293 | * ```js 294 | * import { ..., __tla as __tla_0 } from "..."; 295 | * import { ..., __tla as __tla_1 } from "..."; 296 | * ``` 297 | * 298 | * To work with circular dependency, wrap each imported promise with try-catch. 299 | * Promises from circular dependencies will not be imported and awaited. 300 | * 301 | * ```js 302 | * export let __tla = Promise.all([ 303 | * (() => { try { return __tla_0; } catch {} })(), 304 | * (() => { try { return __tla_1; } catch {} })() 305 | * ]).then(async () => { 306 | * // original top-level statements here 307 | * }); 308 | * ``` 309 | */ 310 | 311 | // Add import of TLA promises from imported modules 312 | let importedPromiseCount = 0; 313 | for (const declaration of [...imports, ...exportFroms]) { 314 | const importedModuleName = resolveImport(moduleName, declaration.source.value); 315 | if (!importedModuleName || !bundleInfo[importedModuleName]) continue; 316 | 317 | if (bundleInfo[importedModuleName].transformNeeded) { 318 | let targetImportDeclaration: SWC.ImportDeclaration; 319 | if (declaration.type === "ImportDeclaration") { 320 | targetImportDeclaration = declaration; 321 | } else { 322 | targetImportDeclaration = makeImportDeclaration(declaration.source); 323 | newImportsByExportFroms.push(targetImportDeclaration); 324 | } 325 | targetImportDeclaration.specifiers.push( 326 | makeImportSpecifier(options.promiseExportName, options.promiseImportName(importedPromiseCount)) 327 | ); 328 | importedPromiseCount++; 329 | } 330 | } 331 | 332 | const importedPromiseArray = 333 | importedPromiseCount === 0 334 | ? null 335 | : makeArrayExpression( 336 | [...Array(importedPromiseCount).keys()].map(i => 337 | makeCallExpression( 338 | makeArrowFunction( 339 | [], 340 | [makeTryCatchStatement([makeReturnStatement(makeIdentifier(options.promiseImportName(i)))], [])] 341 | ) 342 | ) 343 | ) 344 | ); 345 | 346 | // The `async () => { /* original top-level statements */ }` function 347 | const wrappedTopLevelFunction = makeArrowFunction([], warppedStatements, true); 348 | 349 | // `Promise.all([ /* ... */]).then(async () => { /* ... */ })` or `(async () => {})()` 350 | const promiseExpression = importedPromiseArray 351 | ? makeCallExpression( 352 | makeMemberExpression( 353 | makeCallExpression(makeMemberExpression("Promise", "all"), [importedPromiseArray]), 354 | "then" 355 | ), 356 | [wrappedTopLevelFunction] 357 | ) 358 | : makeCallExpression(wrappedTopLevelFunction); 359 | 360 | /* 361 | * New top-level after transformation: 362 | * 363 | * import { ..., __tla as __tla_0 } from "some-module-with-TLA"; 364 | * import { ... } from "some-module-without-TLA"; 365 | * 366 | * let some, variables, exported, from, original, top, level; 367 | * 368 | * let __tla = Promise.all([ ... ]).then(async () => { 369 | * ... 370 | * }); 371 | * 372 | * export { ..., __tla }; 373 | */ 374 | 375 | const newTopLevel: SWC.ModuleItem[] = [ 376 | ...imports, 377 | ...newImportsByExportFroms, 378 | ...exportFroms, 379 | exportedNamesDeclaration 380 | ]; 381 | 382 | if (exportedNames.length > 0 || bundleInfo[moduleName]?.importedBy?.length > 0) { 383 | // If the chunk is being imported, append export of the TLA promise to export list 384 | const promiseDeclaration = makeVariableInitDeclaration(options.promiseExportName, promiseExpression); 385 | exportMap[options.promiseExportName] = options.promiseExportName; 386 | 387 | newTopLevel.push(promiseDeclaration, makeExportListDeclaration(Object.entries(exportMap))); 388 | } else { 389 | // If the chunk is an entry, just execute the promise expression 390 | newTopLevel.push(makeStatement(promiseExpression)); 391 | } 392 | 393 | ast.body = newTopLevel.filter(x => x); 394 | 395 | return ast; 396 | } 397 | -------------------------------------------------------------------------------- /src/transform.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | import * as SWC from "./swc"; 4 | 5 | import { BundleInfo } from "./bundle-info"; 6 | import { DEFAULT_OPTIONS } from "./options"; 7 | import { transformModule } from "./transform"; 8 | 9 | function test(moduleName: string, bundleInfo: BundleInfo, code: string, expectedResult: string) { 10 | const parse = (code: string) => SWC.parseSync(code, { target: "es2022", syntax: "ecmascript" }); 11 | const print = (ast: SWC.Module) => SWC.printSync(ast).code; 12 | 13 | const originalAst = parse(code); 14 | const transformedAst = transformModule(code, originalAst, moduleName, bundleInfo, DEFAULT_OPTIONS); 15 | 16 | expect(print(transformedAst)).toBe(print(parse(expectedResult))); 17 | } 18 | 19 | describe("Transform top-level await", () => { 20 | it("should work for a module without imports/exports", () => { 21 | test( 22 | "a", 23 | { 24 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 25 | }, 26 | ` 27 | await globalThis.somePromise; 28 | `, 29 | ` 30 | (async () => { 31 | await globalThis.somePromise; 32 | })(); 33 | ` 34 | ); 35 | }); 36 | 37 | it("should work for a module with imports", () => { 38 | test( 39 | "a", 40 | { 41 | a: { imported: ["./b"], importedBy: [], transformNeeded: true, withTopLevelAwait: true }, 42 | b: { imported: [], importedBy: ["./a"], transformNeeded: true, withTopLevelAwait: true } 43 | }, 44 | ` 45 | import { qwq } from "./b"; 46 | await globalThis.somePromise; 47 | `, 48 | ` 49 | import { qwq, __tla as __tla_0 } from "./b"; 50 | Promise.all( 51 | [(() => { try { return __tla_0; } catch {} })()] 52 | ).then(async () => { 53 | await globalThis.somePromise; 54 | }); 55 | ` 56 | ); 57 | }); 58 | 59 | it("should work for a module with exports", () => { 60 | test( 61 | "a", 62 | { 63 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 64 | }, 65 | ` 66 | const w = 0; 67 | const x = await globalThis.somePromise; 68 | const y = w + 1; 69 | export { x, y as z }; 70 | `, 71 | ` 72 | let x, y; 73 | let __tla = (async () => { 74 | const w = 0; 75 | x = await globalThis.somePromise; 76 | y = w + 1; 77 | })(); 78 | export { x, y as z, __tla }; 79 | ` 80 | ); 81 | }); 82 | 83 | it("should work for a module with imports/exports", () => { 84 | test( 85 | "a", 86 | { 87 | a: { imported: ["./b"], importedBy: [], transformNeeded: true, withTopLevelAwait: true }, 88 | b: { imported: [], importedBy: ["./a"], transformNeeded: true, withTopLevelAwait: true } 89 | }, 90 | ` 91 | import { qwq } from "./b"; 92 | const x = await globalThis.somePromise; 93 | const y = 1; 94 | export { x, y as z }; 95 | `, 96 | ` 97 | import { qwq, __tla as __tla_0 } from "./b"; 98 | let x, y; 99 | let __tla = Promise.all( 100 | [(() => { try { return __tla_0; } catch {} })()] 101 | ).then(async () => { 102 | x = await globalThis.somePromise; 103 | y = 1; 104 | }); 105 | export { x, y as z, __tla }; 106 | ` 107 | ); 108 | }); 109 | 110 | it("should work for a module with multiple imports (some with TLA)", () => { 111 | test( 112 | "a", 113 | { 114 | a: { imported: ["./b", "./c", "./d"], importedBy: [], transformNeeded: true, withTopLevelAwait: true }, 115 | b: { imported: [], importedBy: ["./a"], transformNeeded: true, withTopLevelAwait: true }, 116 | c: { imported: [], importedBy: ["./a"], transformNeeded: false, withTopLevelAwait: false }, 117 | d: { imported: [], importedBy: ["./a"], transformNeeded: true, withTopLevelAwait: true } 118 | }, 119 | ` 120 | import { qwq } from "./b"; 121 | import { quq as qvq } from "./c"; 122 | import { default as qaq } from "./d"; 123 | const x = await qvq[qaq].someFunc(globalThis.somePromise); 124 | const y = 1; 125 | export { x, y as default }; 126 | `, 127 | ` 128 | import { qwq, __tla as __tla_0 } from "./b"; 129 | import { quq as qvq } from "./c"; 130 | import { default as qaq, __tla as __tla_1 } from "./d"; 131 | let x, y; 132 | let __tla = Promise.all([ 133 | (() => { try { return __tla_0; } catch {} })(), 134 | (() => { try { return __tla_1; } catch {} })() 135 | ]).then(async () => { 136 | x = await qvq[qaq].someFunc(globalThis.somePromise); 137 | y = 1; 138 | }); 139 | export { x, y as default, __tla }; 140 | ` 141 | ); 142 | }); 143 | 144 | it("should work for a module with export functions", () => { 145 | test( 146 | "a", 147 | { 148 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 149 | }, 150 | ` 151 | const x = await globalThis.somePromise; 152 | function f0(args) { return Math.max(...args); } 153 | function f1(args) { return f1(...args, 0); } 154 | function* f2(args) { yield globalThis.qwq; } 155 | async function f3(args) { await Promise.all(globalThis.promises); } 156 | export { x, f1 as func1, f2 as func2, f3 as func3 }; 157 | `, 158 | ` 159 | let x, f1, f2, f3; 160 | let __tla = (async () => { 161 | x = await globalThis.somePromise; 162 | function f0(args) { return Math.max(...args); } 163 | f1 = function (args) { return f1(...args, 0); }; 164 | f2 = function* (args) { yield globalThis.qwq; }; 165 | f3 = async function (args) { await Promise.all(globalThis.promises); }; 166 | })(); 167 | export { x, f1 as func1, f2 as func2, f3 as func3, __tla }; 168 | ` 169 | ); 170 | }); 171 | 172 | it("should work for a module with export classes", () => { 173 | test( 174 | "a", 175 | { 176 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 177 | }, 178 | ` 179 | const x = await globalThis.somePromise; 180 | class C0 { method0() { return 0; } } 181 | class C1 extends C0 { method1() { return 1; } } 182 | class C2 extends C1 { method2() { return 2; } } 183 | export { x, C0 as Class0, C2 as Class2 }; 184 | `, 185 | ` 186 | let x, C0, C2; 187 | let __tla = (async () => { 188 | x = await globalThis.somePromise; 189 | C0 = class { method0() { return 0; } }; 190 | class C1 extends C0 { method1() { return 1; } } 191 | C2 = class extends C1 { method2() { return 2; } }; 192 | })(); 193 | export { x, C0 as Class0, C2 as Class2, __tla }; 194 | ` 195 | ); 196 | }); 197 | 198 | it("should work for a module with exports of complex object destructuring", () => { 199 | test( 200 | "a", 201 | { 202 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 203 | }, 204 | ` 205 | const { x, _0: { _1: { y, z } } = { _0: { _1: { y: 1, z: "" } } }, ...w } = await globalThis.somePromise; 206 | export { x, z as zzz, w }; 207 | `, 208 | ` 209 | let x, z, w; 210 | let __tla = (async () => { 211 | let y; 212 | ({ x, _0: { _1: { y, z } } = { _0: { _1: { y: 1, z: "" } } }, ...w } = await globalThis.somePromise); 213 | })(); 214 | export { x, z as zzz, w, __tla }; 215 | ` 216 | ); 217 | }); 218 | 219 | it("should work for a module with exports of complex array destructuring", () => { 220 | test( 221 | "a", 222 | { 223 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 224 | }, 225 | ` 226 | const [x, [[[, y, , z] = [0, 1, 2, 3], w], ...u] = globalThis.someArray, ...v] = await globalThis.somePromise; 227 | export { x, y as yyy, w as www, u as uuu }; 228 | `, 229 | ` 230 | let x, y, w, u 231 | let __tla = (async () => { 232 | let z, v; 233 | [x, [[[, y, , z] = [0, 1, 2, 3], w], ...u] = globalThis.someArray, ...v] = await globalThis.somePromise; 234 | })(); 235 | export { x, y as yyy, w as www, u as uuu, __tla }; 236 | ` 237 | ); 238 | }); 239 | 240 | it("should work for a module with plugin-injected function/class exports", () => { 241 | test( 242 | "a", 243 | { 244 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 245 | }, 246 | ` 247 | const x = await globalThis.somePromise; 248 | function f0(args) { return Math.max(...args); } 249 | export function f1(args) { return f1(...args, 0); } 250 | export function* f2(args) { yield globalThis.qwq; } 251 | export async function f3(args) { await Promise.all(globalThis.promises); } 252 | export class c1 { qwq = 1 } 253 | export { x }; 254 | `, 255 | ` 256 | let f1, f2, f3, c1, x; 257 | let __tla = (async () => { 258 | x = await globalThis.somePromise; 259 | function f0(args) { return Math.max(...args); } 260 | f1 = function (args) { return f1(...args, 0); }; 261 | f2 = function* (args) { yield globalThis.qwq; }; 262 | f3 = async function (args) { await Promise.all(globalThis.promises); }; 263 | c1 = class { qwq = 1 }; 264 | })(); 265 | export { f1, f2, f3, c1, x, __tla }; 266 | ` 267 | ); 268 | }); 269 | 270 | it("should work for a module with default export declaration (with function name)", () => { 271 | test( 272 | "a", 273 | { 274 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 275 | }, 276 | ` 277 | const a = await globalThis.somePromise; 278 | export default function A(b, c, d) { return a; } 279 | `, 280 | ` 281 | let A; 282 | let __tla = (async () => { 283 | const a = await globalThis.somePromise; 284 | A = function (b, c, d) { return a; }; 285 | })(); 286 | export { A as default, __tla }; 287 | ` 288 | ); 289 | }); 290 | 291 | it("should work for a module with default export declaration (with class name)", () => { 292 | test( 293 | "a", 294 | { 295 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 296 | }, 297 | ` 298 | const a = await globalThis.somePromise; 299 | export default class A { prop = "qwq"; } 300 | `, 301 | ` 302 | let A; 303 | let __tla = (async () => { 304 | const a = await globalThis.somePromise; 305 | A = class { prop = "qwq"; }; 306 | })(); 307 | export { A as default, __tla }; 308 | ` 309 | ); 310 | }); 311 | 312 | it("should work for a module with default export declaration (without name)", () => { 313 | test( 314 | "a", 315 | { 316 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 317 | }, 318 | ` 319 | const a = await globalThis.somePromise; 320 | export default function (b, c, d) { return a; } 321 | `, 322 | ` 323 | let var_69d2a4fc_d77c_5996_9dda_fc4d543f0a82; 324 | let __tla = (async () => { 325 | const a = await globalThis.somePromise; 326 | var_69d2a4fc_d77c_5996_9dda_fc4d543f0a82 = function (b, c, d) { return a; }; 327 | })(); 328 | export { var_69d2a4fc_d77c_5996_9dda_fc4d543f0a82 as default, __tla }; 329 | ` 330 | ); 331 | }); 332 | 333 | it("should work for a module with default export expression", () => { 334 | test( 335 | "a", 336 | { 337 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 338 | }, 339 | ` 340 | const a = await globalThis.somePromise; 341 | export default globalThis.someFunc().someProp + "qwq"; 342 | `, 343 | ` 344 | let var_b51c2b27_5763_5458_95c3_0273366c9dee; 345 | let __tla = (async () => { 346 | const a = await globalThis.somePromise; 347 | var_b51c2b27_5763_5458_95c3_0273366c9dee = globalThis.someFunc().someProp + "qwq"; 348 | })(); 349 | export { var_b51c2b27_5763_5458_95c3_0273366c9dee as default, __tla }; 350 | ` 351 | ); 352 | }); 353 | 354 | it("should work for a module with default and named export of the same identifier", () => { 355 | test( 356 | "a", 357 | { 358 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 359 | }, 360 | ` 361 | const a = await globalThis.somePromise; 362 | export { a, a as default }; 363 | `, 364 | ` 365 | let a; 366 | let __tla = (async () => { 367 | a = await globalThis.somePromise; 368 | })(); 369 | export { a, a as default, __tla }; 370 | ` 371 | ); 372 | }); 373 | 374 | it("should work for a module with manual re-exports", () => { 375 | test( 376 | "a", 377 | { 378 | a: { imported: ["./b"], importedBy: [], transformNeeded: true, withTopLevelAwait: true }, 379 | b: { imported: [], importedBy: ["./a"], transformNeeded: true, withTopLevelAwait: true } 380 | }, 381 | ` 382 | import { default as qwq } from "./b"; 383 | export { qwq }; 384 | `, 385 | ` 386 | import { default as qwq, __tla as __tla_0 } from "./b"; 387 | let __tla = Promise.all([ 388 | (() => { try { return __tla_0; } catch {} })(), 389 | ]).then(async () => {}); 390 | export { qwq, __tla }; 391 | ` 392 | ); 393 | }); 394 | 395 | it("should work for a module with export-from statements", () => { 396 | test( 397 | "a", 398 | { 399 | a: { imported: ["./b"], importedBy: [], transformNeeded: true, withTopLevelAwait: true }, 400 | b: { imported: [], importedBy: ["./a"], transformNeeded: true, withTopLevelAwait: true } 401 | }, 402 | ` 403 | import { qwq } from "./b"; 404 | export { owo as uwu, default as ovo } from "./b"; 405 | export * as QwQ from "./b"; 406 | const qaq = await globalThis.someFunc(qwq); 407 | export { qaq }; 408 | `, 409 | ` 410 | import { qwq, __tla as __tla_0 } from "./b"; 411 | import { __tla as __tla_1 } from "./b"; 412 | import { __tla as __tla_2 } from "./b"; 413 | export { owo as uwu, default as ovo } from "./b"; 414 | export * as QwQ from "./b"; 415 | let qaq; 416 | let __tla = Promise.all([ 417 | (() => { try { return __tla_0; } catch {} })(), 418 | (() => { try { return __tla_1; } catch {} })(), 419 | (() => { try { return __tla_2; } catch {} })(), 420 | ]).then(async () => { 421 | qaq = await globalThis.someFunc(qwq); 422 | }); 423 | export { qaq, __tla }; 424 | ` 425 | ); 426 | }); 427 | 428 | it("should skip processing imports of external modules", () => { 429 | test( 430 | "a", 431 | { 432 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 433 | }, 434 | ` 435 | import React from "https://esm.run/react"; 436 | import path from "path"; 437 | import MuiMaterial from "@mui/material"; 438 | const x = await globalThis.someFunc(React, path); 439 | export { x as y }; 440 | `, 441 | ` 442 | import React from "https://esm.run/react"; 443 | import path from "path"; 444 | import MuiMaterial from "@mui/material"; 445 | let x; 446 | let __tla = (async () => { 447 | x = await globalThis.someFunc(React, path); 448 | })(); 449 | export { x as y, __tla }; 450 | ` 451 | ); 452 | }); 453 | 454 | it("should handle side-effect-only imports correctly", () => { 455 | test( 456 | "a", 457 | { 458 | a: { imported: ["./b"], importedBy: [], transformNeeded: true, withTopLevelAwait: false }, 459 | b: { imported: [], importedBy: ["./a"], transformNeeded: true, withTopLevelAwait: true } 460 | }, 461 | ` 462 | import "./b"; 463 | const x = 1; 464 | export { x }; 465 | `, 466 | ` 467 | import { __tla as __tla_0 } from "./b"; 468 | let x; 469 | let __tla = Promise.all([ 470 | (() => { try { return __tla_0; } catch {} })(), 471 | ]).then(async () => { 472 | x = 1; 473 | }); 474 | export { x, __tla }; 475 | ` 476 | ); 477 | }); 478 | 479 | it("should transform dynamic imports correctly", () => { 480 | test( 481 | "a", 482 | { 483 | a: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true }, 484 | b: { imported: [], importedBy: [], transformNeeded: false, withTopLevelAwait: false }, 485 | c: { imported: [], importedBy: [], transformNeeded: true, withTopLevelAwait: true } 486 | }, 487 | ` 488 | const x = await Promise.all([ 489 | import("./b"), 490 | import("./c"), 491 | import(globalThis.dynamicModuleName) 492 | ]); 493 | export { x as y }; 494 | `, 495 | ` 496 | let x; 497 | let __tla = (async () => { 498 | x = await Promise.all([ 499 | import("./b"), 500 | import("./c").then(async m => { await m.__tla; return m; }), 501 | import(globalThis.dynamicModuleName).then(async m => { await m.__tla; return m; }) 502 | ]); 503 | })(); 504 | export { x as y, __tla }; 505 | ` 506 | ); 507 | }); 508 | it("should fail gracefully if bundleInfo is undefined", () => { 509 | test( 510 | "css-module.js", 511 | {}, 512 | ` 513 | await globalThis.someFunc(import("./css-module.js")); 514 | `, 515 | ` 516 | (async () => { 517 | await globalThis.someFunc(import("./css-module.js")); 518 | })(); 519 | ` 520 | ); 521 | }); 522 | }); 523 | --------------------------------------------------------------------------------