diff --git a/.changeset/clever-wasps-battle.md b/.changeset/clever-wasps-battle.md new file mode 100644 index 000000000..a3bd725c2 --- /dev/null +++ b/.changeset/clever-wasps-battle.md @@ -0,0 +1,5 @@ +--- +"@farmfe/core": major +--- + +export loadenv api diff --git a/.changeset/happy-mice-visit.md b/.changeset/happy-mice-visit.md deleted file mode 100644 index 633c7c761..000000000 --- a/.changeset/happy-mice-visit.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"@farmfe/core": patch ---- - -fix plugin circle call between Runtime & LazyCompilation, fix runtime & lazyCompilation conflict diff --git a/.changeset/shiny-guests-deliver.md b/.changeset/shiny-guests-deliver.md new file mode 100644 index 000000000..347ef30e4 --- /dev/null +++ b/.changeset/shiny-guests-deliver.md @@ -0,0 +1,5 @@ +--- +"@farmfe/core": major +--- + +build cjs script diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index e9fe348e8..1df2bf3a8 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -131,6 +131,11 @@ jobs: - uses: actions/setup-node@v3 with: node-version: 18 + - uses: actions/download-artifact@v4 + id: download-plugin-replace-dirname + with: + name: ${{ github.sha }}-${{ matrix.settings.abi }}-plugin-replace-dirname + path: ./rust-plugins/replace-dirname/npm/${{ matrix.settings.abi }} - name: Install Dependencies run: npm install -g pnpm@9.1.0 && pnpm i --frozen-lockfile - name: Build CLI and Core @@ -189,6 +194,7 @@ jobs: settings: - name: plugin-sass - name: plugin-react + - name: plugin-replace-dirname steps: - uses: actions/download-artifact@v4 with: @@ -199,34 +205,3 @@ jobs: do test -f /tmp/artifacts/${{ github.sha }}-${abi}-${{ matrix.settings.name }}/index.farm done - - benchmarks: - needs: [call-rust-build] - runs-on: ${{ matrix.settings.os }} - strategy: - fail-fast: false - matrix: - settings: - - os: ubuntu-latest - abi: linux-x64-gnu - steps: - - uses: "actions/checkout@v3" - - uses: actions/setup-node@v3 - with: - node-version: 18 - - name: Install Dependencies - run: npm install -g pnpm@9.1.0 && pnpm i --frozen-lockfile - - name: Build CLI and Core - run: pnpm --filter @farmfe/cli run build - - uses: actions/download-artifact@v4 - id: download - with: - name: ${{ github.sha }}-${{ matrix.settings.abi }} - path: ./packages/core/binding - - name: Build Core CJS - run: cd packages/core && pnpm run build:cjs - # - name: Run benchmarks - # uses: CodSpeedHQ/action@v3 - # with: - # run: npm exec vitest bench - # token: ${{ secrets.CODSPEED_TOKEN }} diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index cb8f0f44b..9b0fa3bbb 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -35,12 +35,14 @@ jobs: do mv /tmp/artifacts/${{ github.sha }}-${abi}/* ./packages/core/npm/${abi} mv /tmp/artifacts/${{ github.sha }}-${abi}-plugin-react/* ./rust-plugins/react/npm/${abi} + mv /tmp/artifacts/${{ github.sha }}-${abi}-plugin-replace-dirname/* ./rust-plugins/replace-dirname/npm/${abi} mv /tmp/artifacts/${{ github.sha }}-${abi}-plugin-sass/* ./rust-plugins/sass/npm/${abi} mv /tmp/artifacts/${{ github.sha }}-${abi}-create-farm/* ./packages/create-farm/npm/${abi} test -f ./packages/core/npm/${abi}/farm.${abi}.node test -f ./packages/create-farm/npm/${abi}/create-farm.${abi}.node test -f ./rust-plugins/react/npm/${abi}/index.farm + test -f ./rust-plugins/replace-dirname/npm/${abi}/index.farm test -f ./rust-plugins/sass/npm/${abi}/index.farm done for abi in android-arm-eabi linux-arm-gnueabihf android-arm64 diff --git a/Cargo.lock b/Cargo.lock index ebc087b8f..578ed8f5b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1856,6 +1856,7 @@ name = "farmfe_plugin_runtime" version = "0.0.12" dependencies = [ "farmfe_core", + "farmfe_plugin_bundle", "farmfe_testing_helpers", "farmfe_toolkit", "farmfe_utils 0.1.6", @@ -1956,6 +1957,7 @@ dependencies = [ "farmfe_testing_helpers", "farmfe_toolkit_plugin_types", "farmfe_utils 0.1.6", + "itertools 0.13.0", "lazy_static", "preset_env_base", "sourcemap", diff --git a/README.md b/README.md index e577c56cb..f302afba6 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,9 @@ license + + Gurubase +


diff --git a/crates/compiler/src/build/mod.rs b/crates/compiler/src/build/mod.rs index 0f0aaf266..a27cdbd3e 100644 --- a/crates/compiler/src/build/mod.rs +++ b/crates/compiler/src/build/mod.rs @@ -488,6 +488,14 @@ impl Compiler { return; } + if let ResolveKind::Entry(ref name) = resolve_param.kind { + context + .module_graph + .write() + .entries + .insert(module.id.clone(), name.to_string()); + } + match Self::build_module( resolve_module_id_result.resolve_result, &mut module, diff --git a/crates/compiler/src/generate/render_resource_pots.rs b/crates/compiler/src/generate/render_resource_pots.rs index 2ae30b9d8..dcfbfd02e 100644 --- a/crates/compiler/src/generate/render_resource_pots.rs +++ b/crates/compiler/src/generate/render_resource_pots.rs @@ -84,8 +84,9 @@ pub fn render_resource_pots_and_generate_resources( &mut resource_pot_info, )?; - let r = &mut res.resource; let resource_pot_info: ResourcePotInfo = resource_pot_info.unwrap(); + res.resource.info = Some(resource_pot_info); + let r = &mut res.resource; // ignore runtime resource if !matches!(r.resource_type, ResourceType::Runtime) { @@ -149,7 +150,6 @@ pub fn render_resource_pots_and_generate_resources( resource_pot.add_resource(res.resource.name.clone()); - res.resource.info = Some(resource_pot_info); resources.lock().push(res.resource); Ok::<(), CompilationError>(()) diff --git a/crates/compiler/src/generate/snapshots/generate_resource_pot_map-2.snap b/crates/compiler/src/generate/snapshots/generate_resource_pot_map-2.snap index 2d7fdedfc..e3b870fc0 100644 --- a/crates/compiler/src/generate/snapshots/generate_resource_pot_map-2.snap +++ b/crates/compiler/src/generate/snapshots/generate_resource_pot_map-2.snap @@ -1,59 +1,65 @@ --- source: crates/compiler/src/generate/partial_bundling.rs -input_file: crates/compiler/src/generate/partial_bundling.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "E", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_2f5d", - ), - ( - "id", - "B_2f5d", - ), - ( - "entry", - Some( - ModuleId { - relative_path: "B", - query_string: "", - }, - ), - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "F", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "B", + query_string: "", + }, +) +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/generate/snapshots/generate_resource_pot_map-3.snap b/crates/compiler/src/generate/snapshots/generate_resource_pot_map-3.snap index 0f4dee256..17c211f26 100644 --- a/crates/compiler/src/generate/snapshots/generate_resource_pot_map-3.snap +++ b/crates/compiler/src/generate/snapshots/generate_resource_pot_map-3.snap @@ -1,54 +1,90 @@ --- source: crates/compiler/src/generate/partial_bundling.rs -input_file: crates/compiler/src/generate/partial_bundling.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "D", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_3f39", - ), - ( - "id", - "B_3f39", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "D", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "F", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "B", + query_string: "", + }, +) +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: B_3f39 +id: B_3f39 +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "D", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/generate/snapshots/generate_resource_pot_map-4.snap b/crates/compiler/src/generate/snapshots/generate_resource_pot_map-4.snap index fadc33416..4534cfb5b 100644 --- a/crates/compiler/src/generate/snapshots/generate_resource_pot_map-4.snap +++ b/crates/compiler/src/generate/snapshots/generate_resource_pot_map-4.snap @@ -1,50 +1,111 @@ --- source: crates/compiler/src/generate/partial_bundling.rs -input_file: crates/compiler/src/generate/partial_bundling.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "G", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "G_333e", - ), - ( - "id", - "G_333e", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "G", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "F", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "B", + query_string: "", + }, +) +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: B_3f39 +id: B_3f39 +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "D", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: G_333e +id: G_333e +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "G", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "G", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/generate/snapshots/generate_resource_pot_map-5.snap b/crates/compiler/src/generate/snapshots/generate_resource_pot_map-5.snap index 52473273b..6f4597436 100644 --- a/crates/compiler/src/generate/snapshots/generate_resource_pot_map-5.snap +++ b/crates/compiler/src/generate/snapshots/generate_resource_pot_map-5.snap @@ -1,66 +1,148 @@ --- source: crates/compiler/src/generate/partial_bundling.rs -input_file: crates/compiler/src/generate/partial_bundling.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "F", - query_string: "", - }, - ModuleId { - relative_path: "H", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "test", - ), - ( - "id", - "test_custom(\"__farm_unknown\")", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "D", - query_string: "", - }, - ModuleId { - relative_path: "F", - query_string: "", - }, - ModuleId { - relative_path: "G", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "F", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "B", + query_string: "", + }, +) +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: B_3f39 +id: B_3f39 +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "D", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: G_333e +id: G_333e +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "G", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "G", + query_string: "", + }, +] +resources: [] + +------- + +name: test +id: test_js +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "D", + query_string: "", + }, + ModuleId { + relative_path: "F", + query_string: "", + }, + ModuleId { + relative_path: "G", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "F", + query_string: "", + }, + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/generate/snapshots/generate_resource_pot_map.snap b/crates/compiler/src/generate/snapshots/generate_resource_pot_map.snap index 48258406c..6ba9809bf 100644 --- a/crates/compiler/src/generate/snapshots/generate_resource_pot_map.snap +++ b/crates/compiler/src/generate/snapshots/generate_resource_pot_map.snap @@ -1,63 +1,35 @@ --- source: crates/compiler/src/generate/partial_bundling.rs -input_file: crates/compiler/src/generate/partial_bundling.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "A", - query_string: "", - }, - ModuleId { - relative_path: "C", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "A_66be", - ), - ( - "id", - "A_66be", - ), - ( - "entry", - Some( - ModuleId { - relative_path: "A", - query_string: "", - }, - ), - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "A", - query_string: "", - }, - ModuleId { - relative_path: "F", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "F", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-2.snap b/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-2.snap index 2d7fdedfc..e3b870fc0 100644 --- a/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-2.snap +++ b/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-2.snap @@ -1,59 +1,65 @@ --- source: crates/compiler/src/generate/partial_bundling.rs -input_file: crates/compiler/src/generate/partial_bundling.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "E", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_2f5d", - ), - ( - "id", - "B_2f5d", - ), - ( - "entry", - Some( - ModuleId { - relative_path: "B", - query_string: "", - }, - ), - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "F", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "B", + query_string: "", + }, +) +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-3.snap b/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-3.snap index 0f4dee256..17c211f26 100644 --- a/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-3.snap +++ b/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-3.snap @@ -1,54 +1,90 @@ --- source: crates/compiler/src/generate/partial_bundling.rs -input_file: crates/compiler/src/generate/partial_bundling.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "D", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_3f39", - ), - ( - "id", - "B_3f39", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "D", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "F", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "B", + query_string: "", + }, +) +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: B_3f39 +id: B_3f39 +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "D", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-4.snap b/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-4.snap index 02b861b4a..0a98b81b3 100644 --- a/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-4.snap +++ b/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-4.snap @@ -1,50 +1,111 @@ --- source: crates/compiler/src/generate/partial_bundling.rs -input_file: crates/compiler/src/generate/partial_bundling.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "F", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "F_f67a", - ), - ( - "id", - "F_f67a", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "F", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "F", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "B", + query_string: "", + }, +) +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: B_3f39 +id: B_3f39 +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "D", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: F_f67a +id: F_f67a +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "F", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "F", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-5.snap b/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-5.snap index fadc33416..d085692de 100644 --- a/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-5.snap +++ b/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external-5.snap @@ -1,50 +1,132 @@ --- source: crates/compiler/src/generate/partial_bundling.rs -input_file: crates/compiler/src/generate/partial_bundling.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "G", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "G_333e", - ), - ( - "id", - "G_333e", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "G", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "F", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "B", + query_string: "", + }, +) +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: B_3f39 +id: B_3f39 +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "D", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: F_f67a +id: F_f67a +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "F", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "F", + query_string: "", + }, +] +resources: [] + +------- + +name: G_333e +id: G_333e +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "G", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "G", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external.snap b/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external.snap index 48258406c..6ba9809bf 100644 --- a/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external.snap +++ b/crates/compiler/src/generate/snapshots/generate_resource_pot_map_external.snap @@ -1,63 +1,35 @@ --- source: crates/compiler/src/generate/partial_bundling.rs -input_file: crates/compiler/src/generate/partial_bundling.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "A", - query_string: "", - }, - ModuleId { - relative_path: "C", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "A_66be", - ), - ( - "id", - "A_66be", - ), - ( - "entry", - Some( - ModuleId { - relative_path: "A", - query_string: "", - }, - ), - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "A", - query_string: "", - }, - ModuleId { - relative_path: "F", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "F", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-10.snap b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-10.snap index 729599936..fac352c38 100644 --- a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-10.snap +++ b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-10.snap @@ -1,59 +1,31 @@ --- source: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs -input_file: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "A", - query_string: "", - }, - ModuleId { - relative_path: "C", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "A_66be", - ), - ( - "id", - "A_66be", - ), - ( - "entry", - Some( - ModuleId { - relative_path: "A", - query_string: "", - }, - ), - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "A", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-11.snap b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-11.snap index 99b0ee8c5..8ae01fea3 100644 --- a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-11.snap +++ b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-11.snap @@ -1,59 +1,61 @@ --- source: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs -input_file: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "E", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_2f5d", - ), - ( - "id", - "B_2f5d", - ), - ( - "entry", - Some( - ModuleId { - relative_path: "B", - query_string: "", - }, - ), - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "B", + query_string: "", + }, +) +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-12.snap b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-12.snap index b83015b73..2e0d39f3b 100644 --- a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-12.snap +++ b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-12.snap @@ -1,54 +1,86 @@ --- source: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs -input_file: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "D", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_3f39", - ), - ( - "id", - "B_3f39", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "D", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "B", + query_string: "", + }, +) +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: B_3f39 +id: B_3f39 +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "D", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-13.snap b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-13.snap index 63f02ffbb..70890a654 100644 --- a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-13.snap +++ b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-13.snap @@ -1,58 +1,107 @@ --- source: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs -input_file: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "F", - query_string: "", - }, - ModuleId { - relative_path: "H", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "test", - ), - ( - "id", - "test_custom(\"__farm_unknown\")", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "F", - query_string: "", - }, - ], - ), +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, ) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "B", + query_string: "", + }, +) +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: B_3f39 +id: B_3f39 +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "D", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: test +id: test_custom("__farm_unknown") +immutable: false +resource_pot_type: Custom("__farm_unknown") +entry: None +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-14.snap b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-14.snap new file mode 100644 index 000000000..b05dbf147 --- /dev/null +++ b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-14.snap @@ -0,0 +1,132 @@ +--- +source: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs +input_file: crates/testing_helpers/src/lib.rs +--- +name: A_66be +id: A_66be +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "A", + query_string: "", + }, +) +module_groups: [ + ModuleId { + relative_path: "A", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "A", + query_string: "", + }, + ModuleId { + relative_path: "C", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: Some( + ModuleId { + relative_path: "B", + query_string: "", + }, +) +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: B_3f39 +id: B_3f39 +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "D", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: test +id: test_custom("__farm_unknown") +immutable: false +resource_pot_type: Custom("__farm_unknown") +entry: None +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] + +------- + +name: test +id: test_js +immutable: false +resource_pot_type: Js +entry: None +module_groups: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "F", + query_string: "", + }, +] +modules: [ + ModuleId { + relative_path: "F", + query_string: "", + }, +] +resources: [] diff --git a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-3.snap b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-3.snap index f757f9607..11e21b036 100644 --- a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-3.snap +++ b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-3.snap @@ -1,9 +1,10 @@ --- source: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs -input_file: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs +input_file: crates/testing_helpers/src/lib.rs --- [ "B_2f5d", "B_3f39", "test_custom(\"__farm_unknown\")", + "test_js", ] diff --git a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-5.snap b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-5.snap index b706ee71c..c04ee311d 100644 --- a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-5.snap +++ b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-5.snap @@ -1,7 +1,7 @@ --- source: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs -input_file: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs +input_file: crates/testing_helpers/src/lib.rs --- [ - "test_custom(\"__farm_unknown\")", + "test_js", ] diff --git a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-6.snap b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-6.snap index 200d659e7..674b2da51 100644 --- a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-6.snap +++ b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots-6.snap @@ -1,5 +1,5 @@ --- source: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs -input_file: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs +input_file: crates/testing_helpers/src/lib.rs --- -"test_custom(\"__farm_unknown\")" +"test_js" diff --git a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots.snap b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots.snap index b706ee71c..f88bfb4f2 100644 --- a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots.snap +++ b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/snapshots/generate_and_diff_resource_pots.snap @@ -1,7 +1,9 @@ --- source: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs +assertion_line: 105 input_file: crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs --- [ "test_custom(\"__farm_unknown\")", + "test_js", ] diff --git a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_handle_enforce_resource_pots.rs b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_handle_enforce_resource_pots.rs index 9a143735f..101057d10 100644 --- a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_handle_enforce_resource_pots.rs +++ b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_handle_enforce_resource_pots.rs @@ -6,7 +6,7 @@ use farmfe_core::{ config_regex::ConfigRegex, partial_bundling::PartialBundlingEnforceResourceConfig, Config, }, context::CompilationContext, farm_profile_function, module::{ module_graph::{ModuleGraphEdge, ModuleGraphEdgeDataItem}, - Module, + Module, ModuleType, }, plugin::{Plugin, PluginHookContext, ResolveKind} }; use farmfe_plugin_partial_bundling::module_group_graph_from_entries; @@ -30,7 +30,13 @@ fn test_handle_enforce_resource_pots() { update_module_graph .remove_edge(&"F".into(), &"A".into()) .unwrap(); - update_module_graph.add_module(Module::new("H".into())); + update_module_graph.add_module({ + let mut m = Module::new("H".into()); + + m.module_type = ModuleType::Js; + + m + }); update_module_graph .add_edge(&"B".into(), &"H".into(), Default::default()) .unwrap(); @@ -124,7 +130,7 @@ fn test_handle_enforce_resource_pots() { assert_eq!( enforce_resource_pots, - vec!["test_custom(\"__farm_unknown\")".to_string()] + vec!["test_js".to_string()] ); un_enforce_resource_pots.sort(); assert_eq!( diff --git a/crates/compiler/tests/bundle.rs b/crates/compiler/tests/bundle.rs index 5ec5b8149..93d9eb4e4 100644 --- a/crates/compiler/tests/bundle.rs +++ b/crates/compiler/tests/bundle.rs @@ -1,21 +1,21 @@ use std::{collections::HashMap, path::PathBuf}; -use farmfe_core::config::{bool_or_obj::BoolOrObj, config_regex::ConfigRegex, Mode, TargetEnv}; +use farmfe_core::config::{ + bool_or_obj::BoolOrObj, config_regex::ConfigRegex, + partial_bundling::PartialBundlingEnforceResourceConfig, Mode, TargetEnv, +}; mod common; use crate::common::{ assert_compiler_result_with_config, create_compiler_with_args, AssertCompilerResultConfig, }; +use farmfe_core::config::Config; #[allow(dead_code)] #[cfg(test)] -fn test(file: String, crate_path: String) { - use std::fs; - - use common::get_config_field; +fn test(file: String, crate_path: String, f: Option) { + use common::{format_output_name, get_dir_config_files, try_merge_config_file}; use farmfe_core::config::partial_bundling::PartialBundlingEnforceResourceConfig; - use crate::common::try_read_config_from_json; - let file_path_buf = PathBuf::from(file.clone()); let create_path_buf = PathBuf::from(crate_path); let cwd = file_path_buf.parent().unwrap(); @@ -23,42 +23,15 @@ fn test(file: String, crate_path: String) { let entry_name = "index".to_string(); + let files = get_dir_config_files(cwd); let runtime_entry = cwd.to_path_buf().join("runtime.ts"); - let files = fs::read_dir(cwd) - .unwrap() - .filter_map(|item| item.map(|item| Some(item)).unwrap_or(None)) - .filter_map(|item| { - let filename = item - .path() - .file_name() - .unwrap_or_default() - .to_string_lossy() - .to_string(); - - if filename.starts_with("config") || filename.ends_with(".json") { - Some(( - item.path(), - filename - .trim_start_matches("config") - .trim_start_matches(".") - .trim_end_matches("json") - .trim_end_matches(".") - .to_string(), - )) - } else { - None - } - }) - .collect::>(); - - for (config_entry, config_named) in files { - let config_from_file = try_read_config_from_json(config_entry); + for (name, config_entry) in files { let compiler = create_compiler_with_args( cwd.to_path_buf(), create_path_buf.clone(), |mut config, plugins| { - config.mode = Mode::Production; + config.mode = Mode::Development; if runtime_entry.is_file() { let runtime_entry = runtime_entry.to_string_lossy().to_string(); @@ -71,7 +44,8 @@ fn test(file: String, crate_path: String) { config.tree_shaking = Box::new(BoolOrObj::Bool(false)); config.external = vec![ConfigRegex::new("(^node:.*)"), ConfigRegex::new("^fs$")]; - config.output.target_env = TargetEnv::Node; + config.output.target_env = TargetEnv::Custom("library-node".to_string()); + config.resolve.auto_external_failed_resolve = true; // config.output.format = ModuleFormat::CommonJs; // TODO: multiple bundle @@ -80,18 +54,10 @@ fn test(file: String, crate_path: String) { name: "index".to_string(), }]; - if let Some(config_from_file) = config_from_file { - if let Some(mode) = get_config_field(&config_from_file, &["mode"]) { - config.mode = mode; - } + config = try_merge_config_file(config, config_entry); - if let Some(format) = get_config_field(&config_from_file, &["output", "format"]) { - config.output.format = format; - } - - if let Some(target_env) = get_config_field(&config_from_file, &["output", "targetEnv"]) { - config.output.target_env = target_env; - } + if let Some(f) = f.as_ref() { + f(&mut config); } (config, plugins) @@ -104,21 +70,37 @@ fn test(file: String, crate_path: String) { &compiler, AssertCompilerResultConfig { entry_name: Some(entry_name.clone()), + output_file: Some(format_output_name(name)), ignore_emitted_field: false, - output_file: Some(format!( - "output.{}js", - if config_named.is_empty() { - "".into() - } else { - format!("{config_named}.") - } - )), ..Default::default() }, ); } } -farmfe_testing::testing! {"tests/fixtures/bundle/library/**/index.ts", test} -// farmfe_testing::testing! {"tests/fixtures/runtime/bundle/cjs/export/entryExportStar/**/index.ts", test} -// farmfe_testing::testing! {"tests/fixtures/runtime/bundle/external/import/namespace/**/index.ts", test} +fn single_bundle_test(file: String, crate_path: String) { + test(file, crate_path, None::); +} + +fn multiple_bundle_test(file: String, crate_path: String) { + test( + file, + crate_path, + Some(|config: &mut Config| { + config.partial_bundling.enforce_resources = vec![PartialBundlingEnforceResourceConfig { + name: "bundle1".to_string(), + test: vec![ConfigRegex::new("^bundle2.+")], + }]; + }), + ); +} + +// farmfe_testing::testing! {"tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/namespace/**/index.ts", single_bundle_test} + +farmfe_testing::testing! { + "tests/fixtures/bundle/**/index.ts", + // "tests/fixtures/bundle/library/reexport/use_external_reexport/**/index.ts", + // "tests/fixtures/bundle/library/reexport/reexport/**/index.ts", + // "tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/**/index.ts", + multiple_bundle_test +} diff --git a/crates/compiler/tests/common/mod.rs b/crates/compiler/tests/common/mod.rs index 2c5c43cf2..5e8fd91c7 100644 --- a/crates/compiler/tests/common/mod.rs +++ b/crates/compiler/tests/common/mod.rs @@ -1,4 +1,9 @@ -use std::{collections::HashMap, path::PathBuf, sync::Arc}; +use std::{ + collections::HashMap, + fs, + path::{Path, PathBuf}, + sync::Arc, +}; use farmfe_compiler::Compiler; use farmfe_core::{ @@ -107,6 +112,48 @@ pub fn try_read_config_from_json(path: PathBuf) -> Option { farmfe_core::serde_json::from_str(&content).unwrap() } +#[allow(dead_code)] +pub fn merge_config(v1: Value, v2: Value) -> Value { + match (v1, v2) { + (Value::Array(mut a1), Value::Array(a2)) => { + for item in a2 { + a1.push(item); + } + + Value::Array(a1) + } + + (Value::Object(mut o1), Value::Object(o2)) => { + for (key, val) in o2 { + if let Some(left_value) = o1.remove(&key) { + o1.insert(key, merge_config(left_value, val)); + } else { + o1.insert(key, val); + } + } + + Value::Object(o1) + } + + (_, v2) => v2, + } +} + +#[allow(dead_code)] +pub fn try_merge_config_file(origin: Config, file: PathBuf) -> Config { + let config_from_file = try_read_config_from_json(file); + + if let Some(config_from_file) = config_from_file { + let origin: Value = serde_json::from_str(&serde_json::to_string(&origin).unwrap()).unwrap(); + + let origin = merge_config(origin, config_from_file); + + return serde_json::from_value(origin).unwrap(); + } + + return origin; +} + #[allow(dead_code)] pub fn create_compiler_with_args(cwd: PathBuf, crate_path: PathBuf, handle: F) -> Compiler where @@ -309,15 +356,50 @@ pub fn assert_compiler_result(compiler: &Compiler, entry_name: Option<&String>) } #[allow(dead_code)] -pub fn get_config_field(value: &Value, keys: &[&str]) -> Option { - let mut v: &Value = value; +pub fn get_dir_config_files(cwd: &Path) -> Vec<(String, PathBuf)> { + // println!("fs::read_dir(cwd): {:#?}", fs::read(format!("{}/", cwd.to_string_lossy().to_string()))); + let mut files = fs::read_dir(cwd.to_path_buf()) + .map(|item| { + item + .into_iter() + .filter_map(|file| match file { + Ok(v) => Some(v), + Err(_) => None, + }) + .map(|v| v.path()) + .filter(|v| v.is_file()) + .filter(|v| { + let m = v.file_name().unwrap().to_string_lossy().to_string(); + m.starts_with("config") && m.ends_with(".json") + }) + .map(|v| { + let m = v.file_name().unwrap().to_string_lossy().to_string(); + + ( + m.trim_start_matches("config") + .trim_start_matches(".") + .trim_end_matches("json") + .trim_end_matches(".") + .to_string(), + v, + ) + }) + .collect::>() + }) + .unwrap_or_default(); - for key in keys.iter() { - v = v.get(key)?; + if !files.iter().any(|(name, _)| name.is_empty()) { + files.push(("".to_string(), cwd.to_path_buf().join("config.json"))); } - Some( - serde_json::from_value(v.clone()) - .expect(format!("{} type is not correct", keys.join(".")).as_str()), - ) + files +} + +#[allow(dead_code)] +pub fn format_output_name(name: String) -> String { + if name.is_empty() { + return "output.js".to_string(); + } + + format!("output.{}.js", name) } diff --git a/crates/compiler/tests/fixtures/bundle/library/execute/bundle2.ts b/crates/compiler/tests/fixtures/bundle/library/execute/bundle2.ts new file mode 100644 index 000000000..8f6945224 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/execute/bundle2.ts @@ -0,0 +1,3 @@ +console.log('hello world'); + +export default {} \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/execute/index.ts b/crates/compiler/tests/fixtures/bundle/library/execute/index.ts new file mode 100644 index 000000000..05885d4eb --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/execute/index.ts @@ -0,0 +1 @@ +import './bundle2'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/execute/output.js b/crates/compiler/tests/fixtures/bundle/library/execute/output.js new file mode 100644 index 000000000..21f3edd32 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/execute/output.js @@ -0,0 +1,14 @@ +//bundle1.js: + // module_id: bundle2.ts +console.log('hello world'); +var bundle2_default = {}; +export { bundle2_default }; + + +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + +//index.js: + // module_id: index.ts +import "./bundle1.js"; diff --git a/crates/compiler/tests/fixtures/bundle/library/external/importNamed/index.ts b/crates/compiler/tests/fixtures/bundle/library/external/importNamed/index.ts new file mode 100644 index 000000000..1492523a8 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/external/importNamed/index.ts @@ -0,0 +1,7 @@ +import { readFile as r1, readFileSync as r2 } from 'node:fs'; + + +const readFile = 1; +const readFileSync = 2; + +console.log({ readFile, readFileSync, r1, r2 }); \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/external/importNamed/output.js b/crates/compiler/tests/fixtures/bundle/library/external/importNamed/output.js new file mode 100644 index 000000000..0f8892197 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/external/importNamed/output.js @@ -0,0 +1,15 @@ +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + +//index.js: + // module_id: index.ts +import { readFile as r1, readFileSync as r2 } from "node:fs"; +const readFile = 1; +const readFileSync = 2; +console.log({ + readFile: readFile, + readFileSync: readFileSync, + r1: r1, + r2: r2 +}); diff --git a/crates/compiler/tests/fixtures/bundle/library/external/importNamespace/output.cjs.js b/crates/compiler/tests/fixtures/bundle/library/external/importNamespace/output.cjs.js index 582bbe45a..9ecaeea13 100644 --- a/crates/compiler/tests/fixtures/bundle/library/external/importNamespace/output.cjs.js +++ b/crates/compiler/tests/fixtures/bundle/library/external/importNamespace/output.cjs.js @@ -1,21 +1,14 @@ -//index.js: - function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) return obj; if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { default: obj @@ -36,19 +29,32 @@ newObj.default = obj; if (cache) cache.set(obj, newObj); return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}var node_fs_ns = _interop_require_wildcard(require("node:fs")); +} +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +module.exports._interop_require_default = _interop_require_default; +module.exports._interop_require_wildcard = _interop_require_wildcard; +Object.defineProperty(exports, "__esModule", { + value: true +}); + + +//index.js: + // module_id: a.ts +var farm_runtime_js_ns = require("./farm_runtime.js"); +var _interop_require_default = farm_runtime_js_ns._interop_require_default, _interop_require_wildcard = farm_runtime_js_ns._interop_require_wildcard; +var node_fs_ns = _interop_require_wildcard(require("node:fs")); +var node_fs_ns = require("node:fs"); var fs$1 = _interop_require_default(node_fs_ns).default; const fs = 'a.ts'; console.log(fs); var a_default = 'a.ts'; +// module_id: b.ts console.log('b.ts', node_fs_ns); +// module_id: index.ts console.log('index.ts', fs$1); diff --git a/crates/compiler/tests/fixtures/bundle/library/external/importNamespace/output.js b/crates/compiler/tests/fixtures/bundle/library/external/importNamespace/output.js index 35b6de91b..3f3db2e96 100644 --- a/crates/compiler/tests/fixtures/bundle/library/external/importNamespace/output.js +++ b/crates/compiler/tests/fixtures/bundle/library/external/importNamespace/output.js @@ -1,54 +1,17 @@ +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + //index.js: - function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}import * as node_fs_ns from "node:fs"; + // module_id: a.ts +import * as node_fs_ns from "node:fs"; import fs$1 from "node:fs"; const fs = 'a.ts'; console.log(fs); var a_default = 'a.ts'; +// module_id: b.ts console.log('b.ts', node_fs_ns); +// module_id: index.ts console.log('index.ts', fs$1); diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/defaultParams/bundle2-foo.ts b/crates/compiler/tests/fixtures/bundle/library/hybrid/defaultParams/bundle2-foo.ts new file mode 100644 index 000000000..8eaf3cd75 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/defaultParams/bundle2-foo.ts @@ -0,0 +1,7 @@ +const foo = { + Provider: 'bundle2-foo', +}; + +export { + foo as ReactProvider +}; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/defaultParams/foo.ts b/crates/compiler/tests/fixtures/bundle/library/hybrid/defaultParams/foo.ts new file mode 100644 index 000000000..f4596d540 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/defaultParams/foo.ts @@ -0,0 +1 @@ +export const foo = 'foo'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/defaultParams/index.ts b/crates/compiler/tests/fixtures/bundle/library/hybrid/defaultParams/index.ts new file mode 100644 index 000000000..6ab0301ab --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/defaultParams/index.ts @@ -0,0 +1,35 @@ +import { foo as defaultFoo } from './foo'; +import { ReactProvider } from './bundle2-foo'; + + +function loadFoo(foo = defaultFoo) { + return +} + +const loadFooArrowExpr = () => { + return (foo: string) => { + console.log(foo, ReactProvider.Provider); + } +} + +class LoadFoo { + constructor(public foo = defaultFoo) {} + + getFoo() { + return this.foo; + } +} + +loadFoo(); + +new LoadFoo(); + +const bar = 2; + +function computed(bar = 1) { + return { + [bar]: 123, + [defaultFoo]: 234, + } +} +computed(); \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/defaultParams/output.js b/crates/compiler/tests/fixtures/bundle/library/hybrid/defaultParams/output.js new file mode 100644 index 000000000..e930df08e --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/defaultParams/output.js @@ -0,0 +1,45 @@ +//bundle1.js: + // module_id: bundle2-foo.ts +const foo$5 = { + Provider: 'bundle2-foo' +}; +export { foo$5 }; + + +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + +//index.js: + // module_id: foo.ts +import { foo$5 } from "./bundle1.js"; +const foo$1 = 'foo'; + +// module_id: index.ts +function loadFoo(foo = foo$1) { + return; +} +const loadFooArrowExpr = ()=>{ + return (foo)=>{ + console.log(foo, foo$5.Provider); + }; +}; +class LoadFoo { + foo; + constructor(foo = foo$1){ + this.foo = foo; + } + getFoo() { + return this.foo; + } +} +loadFoo(); +new LoadFoo(); +const bar$1 = 2; +function computed(bar = 1) { + return { + [bar]: 123, + [foo$1]: 234 + }; +} +computed(); diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/importCjsNamespace/a.ts b/crates/compiler/tests/fixtures/bundle/library/hybrid/importCjsNamespace/a.ts index 769d5241a..d25772398 100644 --- a/crates/compiler/tests/fixtures/bundle/library/hybrid/importCjsNamespace/a.ts +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/importCjsNamespace/a.ts @@ -1,5 +1,5 @@ const lodash = 'a.ts'; -console.log(lodash); +console.log(lodash, 'a.ts'); export default 'a.ts'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/importCjsNamespace/output.cjs.js b/crates/compiler/tests/fixtures/bundle/library/hybrid/importCjsNamespace/output.cjs.js index f38d44cc6..62a6f1e6e 100644 --- a/crates/compiler/tests/fixtures/bundle/library/hybrid/importCjsNamespace/output.cjs.js +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/importCjsNamespace/output.cjs.js @@ -1,21 +1,31 @@ -//index.js: - function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); + } + return module.exports; + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) return obj; if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { default: obj @@ -36,39 +46,39 @@ newObj.default = obj; if (cache) cache.set(obj, newObj); return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, +} +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); +} +module.exports.__commonJs = __commonJs; +module.exports._interop_require_default = _interop_require_default; +module.exports._interop_require_wildcard = _interop_require_wildcard; +Object.defineProperty(exports, "__esModule", { + value: true +}); + + +//index.js: + // module_id: lodash.ts +var farm_runtime_js_ns = require("./farm_runtime.js"); +var __commonJs = farm_runtime_js_ns.__commonJs, _interop_require_default = farm_runtime_js_ns._interop_require_default, _interop_require_wildcard = farm_runtime_js_ns._interop_require_wildcard; +var lodash_cjs = __commonJs({ + "lodash.ts": (module, exports)=>{ + module.exports.name = 'lodash'; + module.exports.default = 'foo'; } - return module.exports; - }; -}var lodash_cjs = __commonJs((module, exports)=>{ - module.exports.name = 'lodash'; - module.exports.default = 'foo'; }); var lodash$1 = _interop_require_default(lodash_cjs()).default, lodash_ns = _interop_require_wildcard(lodash_cjs()); +// module_id: a.ts const lodash = 'a.ts'; -console.log(lodash); +console.log(lodash, 'a.ts'); var a_default = 'a.ts'; +// module_id: b.ts console.log('b.ts', lodash_ns); +// module_id: index.ts console.log('index.ts', lodash$1); diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/importCjsNamespace/output.js b/crates/compiler/tests/fixtures/bundle/library/hybrid/importCjsNamespace/output.js new file mode 100644 index 000000000..7777ea74c --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/importCjsNamespace/output.js @@ -0,0 +1,78 @@ +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; + } + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); + } + return module.exports; + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) return obj; + if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { + default: obj + }; + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) return cache.get(obj); + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); + else newObj[key] = obj[key]; + } + } + newObj.default = obj; + if (cache) cache.set(obj, newObj); + return newObj; +} +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +export { __commonJs, _interop_require_default, _interop_require_wildcard }; + + +//index.js: + // module_id: lodash.ts +import { __commonJs, _interop_require_default, _interop_require_wildcard } from "./farm_runtime.js"; +var lodash_cjs = __commonJs({ + "lodash.ts": (module, exports)=>{ + module.exports.name = 'lodash'; + module.exports.default = 'foo'; + } +}); +var lodash$1 = _interop_require_default(lodash_cjs()).default, lodash_ns = _interop_require_wildcard(lodash_cjs()); + +// module_id: a.ts +const lodash = 'a.ts'; +console.log(lodash, 'a.ts'); +var a_default = 'a.ts'; + +// module_id: b.ts +console.log('b.ts', lodash_ns); + +// module_id: index.ts +console.log('index.ts', lodash$1); diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/bar.ts b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/bar.ts new file mode 100644 index 000000000..c69d49c0d --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/bar.ts @@ -0,0 +1,6 @@ +import cjs, { cjsName } from './cjs'; +import esm, { esmName } from './esm'; +import bundle2, { bundle2Name } from './bundle2'; +import { readFile } from 'node:fs'; + +console.log({ cjs: { cjs, cjsName }, readFile, esm: { esm, esmName }, bundle2: { bundle2, bundle2Name } }, 'bar.ts'); \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/bundle2.ts b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/bundle2.ts new file mode 100644 index 000000000..a05cf35e2 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/bundle2.ts @@ -0,0 +1,6 @@ +export const bundle2Name = 'bundle2'; +export const bundle2Age = 18; + +export default function bundle2() { + +} \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/cjs.ts b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/cjs.ts new file mode 100644 index 000000000..5e509d98b --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/cjs.ts @@ -0,0 +1,4 @@ +module.exports.cjsName = 'foo'; +module.exports.cjsAge = 18; + +export default function cjs() {} \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/esm.ts b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/esm.ts new file mode 100644 index 000000000..8808c9ed5 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/esm.ts @@ -0,0 +1,4 @@ +export const esmName = 'esm'; +export const esmAge = 19 + +export default function esm() {} \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/foo.ts b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/foo.ts new file mode 100644 index 000000000..60cb7377e --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/foo.ts @@ -0,0 +1,7 @@ +import cjs, { cjsAge } from './cjs'; +import { readFile } from 'node:fs'; +import esm, { esmAge } from './esm'; +import bundle2, { bundle2Age } from './bundle2'; + + +console.log({ cjs: { cjs, cjsAge }, esm: { esm, esmAge }, bundle2: { bundle2, bundle2Age }, readFile }, 'foo.ts'); \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/index.ts b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/index.ts new file mode 100644 index 000000000..a7fb77d09 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/index.ts @@ -0,0 +1,2 @@ +import './bar'; +import './foo'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/output.js b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/output.js new file mode 100644 index 000000000..8cbe5705d --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/importZip/output.js @@ -0,0 +1,99 @@ +//bundle1.js: + // module_id: bundle2.ts +const bundle2Name = 'bundle2'; +const bundle2Age = 18; +function bundle2() {} +export { bundle2, bundle2Age, bundle2Name }; + + +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; + } + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); + } + return module.exports; + }; +} +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +export { __commonJs, _interop_require_default }; + + +//index.js: + // module_id: cjs.ts +import { __commonJs, _interop_require_default } from "./farm_runtime.js"; +import { bundle2, bundle2Age, bundle2Name } from "./bundle1.js"; +import { readFile } from "node:fs"; +var cjs_cjs = __commonJs({ + "cjs.ts": (module, exports)=>{ + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return cjs; + } + }); + module.exports.cjsName = 'foo'; + module.exports.cjsAge = 18; + function cjs() {} + } +}); +var cjs = _interop_require_default(cjs_cjs()).default, cjsAge = cjs_cjs()["cjsAge"], cjsName = cjs_cjs()["cjsName"]; + +// module_id: esm.ts +const esmName = 'esm'; +const esmAge = 19; +function esm() {} + +// module_id: bar.ts +console.log({ + cjs: { + cjs: cjs, + cjsName: cjsName + }, + readFile: readFile, + esm: { + esm: esm, + esmName: esmName + }, + bundle2: { + bundle2: bundle2, + bundle2Name: bundle2Name + } +}, 'bar.ts'); + +// module_id: foo.ts +console.log({ + cjs: { + cjs: cjs, + cjsAge: cjsAge + }, + esm: { + esm: esm, + esmAge: esmAge + }, + bundle2: { + bundle2: bundle2, + bundle2Age: bundle2Age + }, + readFile: readFile +}, 'foo.ts'); + +// module_id: index.ts diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/noexport/output.js b/crates/compiler/tests/fixtures/bundle/library/hybrid/noexport/output.js index af94bfa3d..265b3173e 100644 --- a/crates/compiler/tests/fixtures/bundle/library/hybrid/noexport/output.js +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/noexport/output.js @@ -1,69 +1,39 @@ -//index.js: - import __farmNodeModule from 'module'; -global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); +} +import __farmNodeModule from 'module'; +var __nodeRequireInstance = __farmNodeModule.createRequire(import.meta.url); +function _nodeRequire() { + return __nodeRequireInstance.apply(null, arguments); +} +export { __commonJs, _nodeRequire }; + + +//index.js: + // module_id: index.ts +import { __commonJs, _nodeRequire } from "./farm_runtime.js"; +import fs from "node:fs"; +var index_cjs = __commonJs({ + "index.ts": (module, exports)=>{ + "use strict"; + const os = _nodeRequire('node:os'); + console.log(fs.read, os.cpus); } - return module.exports; - }; -}import fs from "node:fs"; -var index_cjs = __commonJs((module, exports)=>{ - "use strict"; - const os = global.nodeRequire('node:os'); - console.log(fs.read, os.cpus); }); index_cjs(); diff --git a/crates/compiler/tests/fixtures/bundle/library/hybrid/normal/output.js b/crates/compiler/tests/fixtures/bundle/library/hybrid/normal/output.js index d5e79b13a..5b8a4b2c9 100644 --- a/crates/compiler/tests/fixtures/bundle/library/hybrid/normal/output.js +++ b/crates/compiler/tests/fixtures/bundle/library/hybrid/normal/output.js @@ -1,97 +1,71 @@ -//index.js: - import __farmNodeModule from 'module'; -global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);function _interop_require_default(obj) { +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; + } + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); + } + return module.exports; + }; +} +function _interop_require_default(obj) { return obj && obj.__esModule ? obj : { default: obj }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { +} +import __farmNodeModule from 'module'; +var __nodeRequireInstance = __farmNodeModule.createRequire(import.meta.url); +function _nodeRequire() { + return __nodeRequireInstance.apply(null, arguments); +} +export { __commonJs, _interop_require_default, _nodeRequire }; + + +//index.js: + // module_id: index.ts +import { __commonJs, _interop_require_default, _nodeRequire } from "./farm_runtime.js"; +import fs from "node:fs"; +var index_cjs = __commonJs({ + "index.ts": (module, exports)=>{ + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { enumerable: true, - get: function() { - return from[k]; - } + get: all[name] }); } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, - }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}import fs from "node:fs"; -var index_cjs = __commonJs((module, exports)=>{ - "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); - function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] + _export(exports, { + bar: function() { + return bar; + }, + default: function() { + return _default; + }, + foo: function() { + return foo; + } }); + const os = _nodeRequire('node:os'); + console.log(fs.read, os.cpus); + var _default = { + read: fs.read, + c: 1 + }; + const foo = 'foo'; + const bar = 'bar'; } - _export(exports, { - bar: function() { - return bar; - }, - default: function() { - return _default; - }, - foo: function() { - return foo; - } - }); - const os = global.nodeRequire('node:os'); - console.log(fs.read, os.cpus); - var _default = { - read: fs.read, - c: 1 - }; - const foo = 'foo'; - const bar = 'bar'; }); var index_default = _interop_require_default(index_cjs()).default, bar = index_cjs()["bar"], foo = index_cjs()["foo"]; -export { bar, foo }; -export default index_default; +export { bar, foo, index_default as default }; diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/esm/default/output.js b/crates/compiler/tests/fixtures/bundle/library/reexport/esm/default/output.js index 9cf3a7632..a2e8f323b 100644 --- a/crates/compiler/tests/fixtures/bundle/library/reexport/esm/default/output.js +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/esm/default/output.js @@ -1,48 +1,10 @@ +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + //index.js: - function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}var foo_default = 'foo'; + // module_id: foo.ts +var foo_default = 'foo'; +// module_id: index.ts export { foo_default as default }; diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/esm/named/output.js b/crates/compiler/tests/fixtures/bundle/library/reexport/esm/named/output.js index c4feebfd5..be43adb9a 100644 --- a/crates/compiler/tests/fixtures/bundle/library/reexport/esm/named/output.js +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/esm/named/output.js @@ -1,49 +1,11 @@ +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + //index.js: - function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const foo = 'foo'; + // module_id: foo.ts +const foo = 'foo'; const bar = 'bar'; +// module_id: index.ts export { bar, foo }; diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/esm/namespace/output.js b/crates/compiler/tests/fixtures/bundle/library/reexport/esm/namespace/output.js index 4cb7c1d6b..ef05d3b9b 100644 --- a/crates/compiler/tests/fixtures/bundle/library/reexport/esm/namespace/output.js +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/esm/namespace/output.js @@ -1,58 +1,20 @@ +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + //index.js: - function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}var foo_default = 'foo'; -const foo$1 = 'foo'; + // module_id: foo.ts +var foo_default = 'foo'; +const foo = 'foo'; const bar = 'bar'; var foo_ns = { bar: bar, - foo: foo$1, + foo: foo, "default": foo_default, __esModule: true }; -const foo = 123; -console.log(foo_ns.default, foo_ns.foo, foo); +// module_id: index.ts +const foo$1 = 123; +console.log(foo_ns.default, foo_ns.foo, foo$1); export { foo_ns as ns }; diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/esm/star/output.js b/crates/compiler/tests/fixtures/bundle/library/reexport/esm/star/output.js index d33ca68f7..2906dc539 100644 --- a/crates/compiler/tests/fixtures/bundle/library/reexport/esm/star/output.js +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/esm/star/output.js @@ -1,49 +1,10 @@ +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + //index.js: - function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}var foo_default = 'foo'; + // module_id: foo.ts +var foo_default = 'foo'; const foo = 'foo'; const bar = 'bar'; var foo_ns = { @@ -53,5 +14,5 @@ var foo_ns = { __esModule: true }; -export { bar, foo }; -export default foo_default; +// module_id: index.ts +export { bar, foo, foo_default as default }; diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport/index.ts b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport/index.ts new file mode 100644 index 000000000..194ef63e6 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport/index.ts @@ -0,0 +1,4 @@ +export * from './reexport'; +// TODO: external +// TODO: improve reexport external +const Foo1 = '123'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport/output.js b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport/output.js new file mode 100644 index 000000000..22a4e6214 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport/output.js @@ -0,0 +1,18 @@ +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + +//index.js: + // module_id: reexport.ts +import { default as Foo1 } from "foo1"; +import { default as Foo2 } from "foo2"; +var reexport_ns = { + Foo2: Foo2, + Foo1: Foo1, + __esModule: true +}; + +// module_id: index.ts +const Foo1 = '123'; +export { default as Foo1 } from "foo1"; +export { default as Foo2 } from "foo2"; diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport/reexport.ts b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport/reexport.ts new file mode 100644 index 000000000..1ae4fa357 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport/reexport.ts @@ -0,0 +1,3 @@ +// @ts-nocheck +export { default as Foo1 } from 'foo1' +export { default as Foo2 } from 'foo2' \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/circle.ts b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/circle.ts new file mode 100644 index 000000000..20d6a2b6f --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/circle.ts @@ -0,0 +1,3 @@ +import * as ns from './reexport'; + +console.log({ ns }); \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/foo.ts b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/foo.ts index 8af2ad9ac..f618a4771 100644 --- a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/foo.ts +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/foo.ts @@ -1,2 +1,3 @@ module.exports.cjs = true; -export default 'foo'; \ No newline at end of file +var a = 'foo'; +export default a; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/index.ts b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/index.ts index 2f816c828..061b1c23c 100644 --- a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/index.ts +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/index.ts @@ -1 +1,4 @@ -export { default } from './foo.ts'; +import _default_import from './reexport'; + +export default _default_import; +export * from './reexport'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/output.js b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/output.js index e29a879d7..1fee85dc9 100644 --- a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/output.js +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/output.js @@ -1,78 +1,20 @@ +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + //index.js: - function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, - }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); + // module_id: reexport.ts +class foo { + constructor(){ + console.log(this.constructor === foo); } - return module.exports; - }; -}var foo_cjs = __commonJs((module, exports)=>{ - "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); - Object.defineProperty(exports, "default", { - enumerable: true, - get: function() { - return _default; - } - }); - module.exports.cjs = true; - var _default = 'foo'; -}); -var foo_default = foo_cjs()["default"]; +} +const bar = 'foo'; +var reexport_ns = { + bar: bar, + default: foo, + __esModule: true +}; -export { foo_default as default }; +// module_id: index.ts +export { bar, foo as default }; diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/reexport.ts b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/reexport.ts new file mode 100644 index 000000000..50b615610 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/default/reexport.ts @@ -0,0 +1,12 @@ +// export { default } from './foo.ts'; +// import './circle'; + +class foo { + constructor() { + console.log(this.constructor === foo); + } +}; + +export const bar = 'foo'; + +export { foo as default }; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/named/output.js b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/named/output.js index f1996fe32..646fc6068 100644 --- a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/named/output.js +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/named/output.js @@ -1,87 +1,54 @@ -//index.js: - function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; + } + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); + } + return module.exports; }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { +} +export { __commonJs }; + + +//index.js: + // module_id: foo.ts +import { __commonJs } from "./farm_runtime.js"; +var foo_cjs = __commonJs({ + "foo.ts": (module, exports)=>{ + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { enumerable: true, - get: function() { - return from[k]; - } + get: all[name] }); } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, - }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var foo_cjs = __commonJs((module, exports)=>{ - "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); - function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] + _export(exports, { + bar: function() { + return bar; + }, + foo: function() { + return foo; + } }); + const foo = 'foo'; + const bar = 'bar'; + module.exports.cjs = true; } - _export(exports, { - bar: function() { - return bar; - }, - foo: function() { - return foo; - } - }); - const foo = 'foo'; - const bar = 'bar'; - module.exports.cjs = true; }); var bar = foo_cjs()["bar"], foo = foo_cjs()["foo"]; +// module_id: index.ts export { bar, foo }; diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/namespace/output.js b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/namespace/output.js index 46366be2b..319073cfe 100644 --- a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/namespace/output.js +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/namespace/output.js @@ -1,21 +1,31 @@ -//index.js: - function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; + } + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { + return module.exports; + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) return obj; if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { default: obj @@ -36,56 +46,43 @@ newObj.default = obj; if (cache) cache.set(obj, newObj); return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, - }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var foo_cjs = __commonJs((module, exports)=>{ - "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); - function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] +} +export { __commonJs, _interop_require_wildcard }; + + +//index.js: + // module_id: foo.ts +import { __commonJs, _interop_require_wildcard } from "./farm_runtime.js"; +var foo_cjs = __commonJs({ + "foo.ts": (module, exports)=>{ + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true }); - } - _export(exports, { - bar: function() { - return bar; - }, - default: function() { - return _default; - }, - foo: function() { - return foo; + function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); } - }); - var _default = 'foo'; - const foo = 'foo'; - const bar = 'bar'; - module.exports.cjs = true; + _export(exports, { + bar: function() { + return bar; + }, + default: function() { + return _default; + }, + foo: function() { + return foo; + } + }); + var _default = 'foo'; + const foo = 'foo'; + const bar = 'bar'; + module.exports.cjs = true; + } }); var foo_ns = _interop_require_wildcard(foo_cjs()); +// module_id: index.ts export { foo_ns as ns }; diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/output.js b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/output.js new file mode 100644 index 000000000..b484195ee --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/output.js @@ -0,0 +1,20 @@ +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + +//index.js: + // module_id: default/reexport.ts +class foo { + constructor(){ + console.log(this.constructor === foo); + } +} +const bar = 'foo'; +var reexport_ns = { + bar: bar, + default: foo, + __esModule: true +}; + +// module_id: default/index.ts +export { bar, foo as default }; diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/star/output.js b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/star/output.js index f2320e3c3..ca84b2381 100644 --- a/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/star/output.js +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/reexport_hybrid_cjs/star/output.js @@ -1,92 +1,63 @@ -//index.js: - function _interop_require_default(obj) { +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; + } + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); + } + return module.exports; + }; +} +function _interop_require_default(obj) { return obj && obj.__esModule ? obj : { default: obj }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { +} +export { __commonJs, _interop_require_default }; + + +//index.js: + // module_id: foo.ts +import { __commonJs, _interop_require_default } from "./farm_runtime.js"; +var foo_cjs = __commonJs({ + "foo.ts": (module, exports)=>{ + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { enumerable: true, - get: function() { - return from[k]; - } + get: all[name] }); } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, - }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var foo_cjs = __commonJs((module, exports)=>{ - "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); - function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] + _export(exports, { + bar: function() { + return bar; + }, + default: function() { + return _default; + }, + foo: function() { + return foo; + } }); + var _default = 'foo'; + const foo = 'foo'; + const bar = 'bar'; + module.exports.cjs = true; } - _export(exports, { - bar: function() { - return bar; - }, - default: function() { - return _default; - }, - foo: function() { - return foo; - } - }); - var _default = 'foo'; - const foo = 'foo'; - const bar = 'bar'; - module.exports.cjs = true; }); var foo_default = _interop_require_default(foo_cjs()).default, bar = foo_cjs()["bar"], foo = foo_cjs()["foo"]; -export { bar, foo }; -export default foo_default; +// module_id: index.ts +export { bar, foo, foo_default as default }; diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/use_external_reexport/index.ts b/crates/compiler/tests/fixtures/bundle/library/reexport/use_external_reexport/index.ts new file mode 100644 index 000000000..b65de0054 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/use_external_reexport/index.ts @@ -0,0 +1,6 @@ +import r1, { foo, unstable_batchedUpdates as batch } from './reexport'; + +const unstable_batchedUpdates = 123; +console.log({ unstable_batchedUpdates }); + +console.log({ r1, foo, batch }); \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/use_external_reexport/output.js b/crates/compiler/tests/fixtures/bundle/library/reexport/use_external_reexport/output.js new file mode 100644 index 000000000..6d63e5d7f --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/use_external_reexport/output.js @@ -0,0 +1,20 @@ +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + +//index.js: + // module_id: reexport.ts +import { foo } from "foo"; +import { readFile } from "node:fs"; +import { unstable_batchedUpdates as unstable_batchedUpdates$1 } from "react-dom"; + +// module_id: index.ts +const unstable_batchedUpdates = 123; +console.log({ + unstable_batchedUpdates: unstable_batchedUpdates +}); +console.log({ + r1: readFile, + foo: foo, + batch: unstable_batchedUpdates$1 +}); diff --git a/crates/compiler/tests/fixtures/bundle/library/reexport/use_external_reexport/reexport.ts b/crates/compiler/tests/fixtures/bundle/library/reexport/use_external_reexport/reexport.ts new file mode 100644 index 000000000..44f74ada8 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/library/reexport/use_external_reexport/reexport.ts @@ -0,0 +1,5 @@ +// @ts-nocheck +export { readFile as default } from 'node:fs'; +export { foo } from 'foo'; + +export { unstable_batchedUpdates } from 'react-dom'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/bundle2.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/bundle2.ts new file mode 100644 index 000000000..1ae84b933 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/bundle2.ts @@ -0,0 +1,9 @@ +// @ts-nocheck + +function lodash() {} + +lodash.merge = function() {} + +const _ = lodash; + +(module.exports = _)._ = _; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/config.cjs.json b/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/config.cjs.json new file mode 100644 index 000000000..932c1085f --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/config.cjs.json @@ -0,0 +1,6 @@ +{ + "output": { + "targetEnv": "library-node", + "format": "cjs" + } +} \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/index.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/index.ts new file mode 100644 index 000000000..d7441d779 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/index.ts @@ -0,0 +1,3 @@ +import lodash, { merge } from './bundle2'; + +console.log(lodash, merge); diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/output.cjs.js b/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/output.cjs.js new file mode 100644 index 000000000..387e51689 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/output.cjs.js @@ -0,0 +1,54 @@ +//bundle1.js: + // module_id: bundle2.ts +var farm_runtime_js_ns = require("./farm_runtime.js"); +var __commonJs = farm_runtime_js_ns.__commonJs; +var bundle2_cjs = __commonJs({ + "bundle2.ts": (module, exports)=>{ + function lodash() {} + lodash.merge = function() {}; + const _ = lodash; + (module.exports = _)._ = _; + } +}); +module.exports.bundle2_cjs = bundle2_cjs; + + +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; + } + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); + } + return module.exports; + }; +} +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +module.exports.__commonJs = __commonJs; +module.exports._interop_require_default = _interop_require_default; +Object.defineProperty(exports, "__esModule", { + value: true +}); + + +//index.js: + // module_id: index.ts +var farm_runtime_js_ns = require("./farm_runtime.js"); +var _interop_require_default = farm_runtime_js_ns._interop_require_default; +var bundle1_js_ns = require("./bundle1.js"); +var bundle2_cjs = bundle1_js_ns.bundle2_cjs; +var lodash = _interop_require_default(bundle2_cjs()).default, merge = bundle2_cjs()["merge"]; +console.log(lodash, merge); diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/output.js b/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/output.js new file mode 100644 index 000000000..9f67ed91c --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/lodash_export/output.js @@ -0,0 +1,47 @@ +//bundle1.js: + // module_id: bundle2.ts +import { __commonJs } from "./farm_runtime.js"; +var bundle2_cjs = __commonJs({ + "bundle2.ts": (module, exports)=>{ + function lodash() {} + lodash.merge = function() {}; + const _ = lodash; + (module.exports = _)._ = _; + } +}); +export { bundle2_cjs }; + + +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; + } + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); + } + return module.exports; + }; +} +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +export { __commonJs, _interop_require_default }; + + +//index.js: + // module_id: index.ts +import { _interop_require_default } from "./farm_runtime.js"; +import { bundle2_cjs } from "./bundle1.js"; +var lodash = _interop_require_default(bundle2_cjs()).default, merge = bundle2_cjs()["merge"]; +console.log(lodash, merge); diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/bundle2.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/bundle2.ts new file mode 100644 index 000000000..c96c4108f --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/bundle2.ts @@ -0,0 +1,2 @@ +export * as ns from './namespace'; +export { default } from './default'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/config.cjs.json b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/config.cjs.json new file mode 100644 index 000000000..a54e6cace --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/config.cjs.json @@ -0,0 +1,5 @@ +{ + "output": { + "format": "cjs" + } +} \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/default.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/default.ts new file mode 100644 index 000000000..517359f06 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/default.ts @@ -0,0 +1,3 @@ +const d = 'default'; + +export default d; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/index.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/index.ts new file mode 100644 index 000000000..80a6223b5 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/index.ts @@ -0,0 +1,3 @@ +import bundle2, { ns } from './bundle2'; + +console.log({ ns, bundle2 }); \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/namespace.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/namespace.ts new file mode 100644 index 000000000..3bf7f28e5 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/namespace.ts @@ -0,0 +1,4 @@ +export const ns_named = 'ns named'; +export const ns_default = 'ns default'; + +module.exports.name = '123'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/output.cjs.js b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/output.cjs.js new file mode 100644 index 000000000..bd25a3713 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/output.cjs.js @@ -0,0 +1,118 @@ +//bundle1.js: + // module_id: bundle2.ts +var farm_runtime_js_ns = require("./farm_runtime.js"); +var _interop_require_wildcard = farm_runtime_js_ns._interop_require_wildcard; +var index_1175_ns = require("./index.js"); +var d = index_1175_ns.d, namespace_cjs = index_1175_ns.namespace_cjs; +var ns = _interop_require_wildcard(namespace_cjs()); +module.exports.d = d; +module.exports.ns = ns; +Object.defineProperty(exports, "__esModule", { + value: true +}); + + +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; + } + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); + } + return module.exports; + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) return obj; + if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { + default: obj + }; + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) return cache.get(obj); + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); + else newObj[key] = obj[key]; + } + } + newObj.default = obj; + if (cache) cache.set(obj, newObj); + return newObj; +} +module.exports.__commonJs = __commonJs; +module.exports._interop_require_wildcard = _interop_require_wildcard; +Object.defineProperty(exports, "__esModule", { + value: true +}); + + +//index.js: + // module_id: namespace.ts +var farm_runtime_js_ns = require("./farm_runtime.js"); +var __commonJs = farm_runtime_js_ns.__commonJs; +var bundle1_js_ns = require("./bundle1.js"); +var ns = bundle1_js_ns.ns; +var namespace_cjs = __commonJs({ + "namespace.ts": (module, exports)=>{ + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); + } + _export(exports, { + ns_default: function() { + return ns_default; + }, + ns_named: function() { + return ns_named; + } + }); + const ns_named = 'ns named'; + const ns_default = 'ns default'; + module.exports.name = '123'; + } +}); +var ns_default = namespace_cjs()["ns_default"], ns_named = namespace_cjs()["ns_named"]; + +// module_id: default.ts +const d = 'default'; + +// module_id: index.ts +console.log({ + ns: ns, + bundle2: d +}); +module.exports.d = d; +module.exports.namespace_cjs = namespace_cjs; +module.exports.ns_default = ns_default; +module.exports.ns_named = ns_named; +Object.defineProperty(exports, "__esModule", { + value: true +}); diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/output.js b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/output.js new file mode 100644 index 000000000..11bc8ca0c --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/cross_bundle/namespace/output.js @@ -0,0 +1,100 @@ +//bundle1.js: + // module_id: bundle2.ts +import { _interop_require_wildcard } from "./farm_runtime.js"; +import { d, namespace_cjs } from "./index.js"; +var ns = _interop_require_wildcard(namespace_cjs()); +export { d, ns }; + + +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; + } + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); + } + return module.exports; + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) return obj; + if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { + default: obj + }; + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) return cache.get(obj); + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); + else newObj[key] = obj[key]; + } + } + newObj.default = obj; + if (cache) cache.set(obj, newObj); + return newObj; +} +export { __commonJs, _interop_require_wildcard }; + + +//index.js: + // module_id: namespace.ts +import { __commonJs } from "./farm_runtime.js"; +import { ns } from "./bundle1.js"; +var namespace_cjs = __commonJs({ + "namespace.ts": (module, exports)=>{ + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); + } + _export(exports, { + ns_default: function() { + return ns_default; + }, + ns_named: function() { + return ns_named; + } + }); + const ns_named = 'ns named'; + const ns_default = 'ns default'; + module.exports.name = '123'; + } +}); +var ns_default = namespace_cjs()["ns_default"], ns_named = namespace_cjs()["ns_named"]; + +// module_id: default.ts +const d = 'default'; + +// module_id: index.ts +console.log({ + ns: ns, + bundle2: d +}); +export { d, namespace_cjs, ns_default, ns_named }; diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/entry_export/bundle2.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/entry_export/bundle2.ts new file mode 100644 index 000000000..3291b0ab2 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/entry_export/bundle2.ts @@ -0,0 +1,2 @@ +export const named = 'bundle2 named'; +export default 'bundle2 default' \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/entry_export/index.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/entry_export/index.ts new file mode 100644 index 000000000..b4dd6e9ef --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/entry_export/index.ts @@ -0,0 +1,4 @@ +export { named, default } from './bundle2'; + +// TODO: fix it +// export * as ns from './bundle2'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/entry_export/output.js b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/entry_export/output.js new file mode 100644 index 000000000..f630c8a37 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/entry_export/output.js @@ -0,0 +1,15 @@ +//bundle1.js: + // module_id: bundle2.ts +const named = 'bundle2 named'; +var bundle2_default = 'bundle2 default'; +export { bundle2_default, named }; + + +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + +//index.js: + // module_id: index.ts +import { bundle2_default, named } from "./bundle1.js"; +export { bundle2_default as default, named }; diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/namespace/bundle2.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/namespace/bundle2.ts new file mode 100644 index 000000000..5d870bd6a --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/namespace/bundle2.ts @@ -0,0 +1 @@ +export * as ns from './bundle2_namespace'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/namespace/bundle2_namespace.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/namespace/bundle2_namespace.ts new file mode 100644 index 000000000..4e6fb1206 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/namespace/bundle2_namespace.ts @@ -0,0 +1,2 @@ +export const ns_named = 'ns named'; +export const ns_default = 'ns default'; diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/namespace/index.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/namespace/index.ts new file mode 100644 index 000000000..01711ceb8 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/namespace/index.ts @@ -0,0 +1,3 @@ +import { ns } from './bundle2'; + +console.log({ ns }); \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/namespace/output.js b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/namespace/output.js new file mode 100644 index 000000000..16c9eee9c --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/namespace/output.js @@ -0,0 +1,24 @@ +//bundle1.js: + // module_id: bundle2_namespace.ts +const ns_named = 'ns named'; +const ns_default = 'ns default'; +var bundle2_namespace_ns = { + ns_default: ns_default, + ns_named: ns_named, + __esModule: true +}; + +// module_id: bundle2.ts +export { bundle2_namespace_ns }; + + +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + +//index.js: + // module_id: index.ts +import { bundle2_namespace_ns } from "./bundle1.js"; +console.log({ + ns: bundle2_namespace_ns +}); diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/bundle2-foo.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/bundle2-foo.ts new file mode 100644 index 000000000..d1c6b14bb --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/bundle2-foo.ts @@ -0,0 +1,5 @@ +const bundle_str1 = 'bundle2 str1'; + +console.log(bundle_str1); + +export default 'bundle2 foo'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/bundle2.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/bundle2.ts new file mode 100644 index 000000000..822733fdf --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/bundle2.ts @@ -0,0 +1,7 @@ +import { foo_str1, foo_str2 } from './foo'; +import './bundle2-foo'; + +console.log({ foo_str1, foo_str2 }); + +export const bundle_str1 = 'bundle str1'; +export const bundle_str2 = 'bundle str2'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/foo.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/foo.ts new file mode 100644 index 000000000..2d6a02f3f --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/foo.ts @@ -0,0 +1,11 @@ + +export const foo_str1 = 'foo str1'; +export const foo_str2 = 'foo str2'; + +const foo_str3 = 'foo str3'; + +const index_foo = 234; + +console.log(foo_str1, index_foo, foo_str3); + +export default 'foo default'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/index.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/index.ts new file mode 100644 index 000000000..45cf5fffb --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/index.ts @@ -0,0 +1,14 @@ +import { bundle_str1 } from './bundle2'; + +console.log(bundle_str1); + +export const index_foo = 'index foo'; +export const index_bar = 'index bar'; + +const foo_str1 = 123; +const foo_str3 = 'index-foo_str3'; +console.log(foo_str1, foo_str3); + +export default 'index default'; + +// export * from './bundle2'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/output.js b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/output.js new file mode 100644 index 000000000..13cc90bba --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle/output.js @@ -0,0 +1,41 @@ +//bundle1.js: + // module_id: bundle2-foo.ts +import { foo_str1, foo_str2 } from "./index.js"; +const bundle_str1 = 'bundle2 str1'; +console.log(bundle_str1); +var bundle2_foo_default = 'bundle2 foo'; + +// module_id: bundle2.ts +console.log({ + foo_str1: foo_str1, + foo_str2: foo_str2 +}); +const bundle_str1$1 = 'bundle str1'; +const bundle_str2 = 'bundle str2'; +export { bundle_str1$1, bundle_str2 }; + + +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + +//index.js: + // module_id: foo.ts +import { bundle_str1$1 } from "./bundle1.js"; +const foo_str1 = 'foo str1'; +const foo_str2 = 'foo str2'; +const foo_str3 = 'foo str3'; +const index_foo = 234; +console.log(foo_str1, index_foo, foo_str3); +var foo_default = 'foo default'; + +// module_id: index.ts +console.log(bundle_str1$1); +const index_foo$1 = 'index foo'; +const index_bar = 'index bar'; +const foo_str1$1 = 123; +const foo_str3$1 = 'index-foo_str3'; +console.log(foo_str1$1, foo_str3$1); +var index_default = 'index default'; +export { index_bar, index_foo$1 as index_foo, index_default as default }; +export { foo_default, foo_str1, foo_str2 }; diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/bundle2.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/bundle2.ts new file mode 100644 index 000000000..5afe39162 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/bundle2.ts @@ -0,0 +1,7 @@ +import bundle2_default from './default'; +import * as bundle2_namespace from './namespace'; +import { foo_named as bundle2_named } from './named'; + +console.log({ bundle2_default, bundle2_namespace, bundle2_named }); + +export { bundle2_default, bundle2_namespace, bundle2_named } \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/config.cjs.json b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/config.cjs.json new file mode 100644 index 000000000..a54e6cace --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/config.cjs.json @@ -0,0 +1,5 @@ +{ + "output": { + "format": "cjs" + } +} \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/default.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/default.ts new file mode 100644 index 000000000..7df88d728 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/default.ts @@ -0,0 +1 @@ +export default '123'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/index.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/index.ts new file mode 100644 index 000000000..94a8d33ca --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/index.ts @@ -0,0 +1,5 @@ +import { bundle2_default, bundle2_named, bundle2_namespace } from './bundle2'; + +console.log(bundle2_default, bundle2_named, bundle2_namespace); + +export default 'index'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/named.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/named.ts new file mode 100644 index 000000000..911b22928 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/named.ts @@ -0,0 +1 @@ +export const foo_named = '123'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/namespace.ts b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/namespace.ts new file mode 100644 index 000000000..d7a5dde9b --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/namespace.ts @@ -0,0 +1,2 @@ +export const foo_ns = 'ns_foo'; +export default 'ns_default'; \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/output.cjs.js b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/output.cjs.js new file mode 100644 index 000000000..aba014a29 --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/output.cjs.js @@ -0,0 +1,49 @@ +//bundle1.js: + // module_id: bundle2.ts +var index_c86a_ns = require("./index.js"); +var default_default$1 = index_c86a_ns.default_default$1, foo_named = index_c86a_ns.foo_named, namespace_ns = index_c86a_ns.namespace_ns; +console.log({ + bundle2_default: default_default$1, + bundle2_namespace: namespace_ns, + bundle2_named: foo_named +}); +module.exports.default_default$1 = default_default$1; +module.exports.foo_named = foo_named; +module.exports.namespace_ns = namespace_ns; +Object.defineProperty(exports, "__esModule", { + value: true +}); + + +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + +//index.js: + // module_id: default.ts +var default_default$1 = '123'; + +// module_id: namespace.ts +const foo_ns = 'ns_foo'; +var namespace_default = 'ns_default'; +var namespace_ns = { + foo_ns: foo_ns, + "default": namespace_default, + __esModule: true +}; + +// module_id: named.ts +const foo_named = '123'; + +// module_id: index.ts +console.log(default_default$1, foo_named, namespace_ns); +var index_default = 'index'; +module.exports.default = index_default; +Object.defineProperty(exports, "__esModule", { + value: true +}); +module.exports.default_default$1 = default_default$1; +module.exports.foo_named = foo_named; +module.exports.foo_ns = foo_ns; +module.exports.namespace_default = namespace_default; +module.exports.namespace_ns = namespace_ns; diff --git a/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/output.js b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/output.js new file mode 100644 index 000000000..117f69def --- /dev/null +++ b/crates/compiler/tests/fixtures/bundle/multiple_bundle/reexport/reexport_cross_bundle_1/output.js @@ -0,0 +1,36 @@ +//bundle1.js: + // module_id: bundle2.ts +import { default_default$1, foo_named, namespace_ns } from "./index.js"; +console.log({ + bundle2_default: default_default$1, + bundle2_namespace: namespace_ns, + bundle2_named: foo_named +}); +export { default_default$1, foo_named, namespace_ns }; + + +//farm_runtime.js: + // module_id: __FARM_BUNDLE_POLYFILL_SLOT__ + + +//index.js: + // module_id: default.ts +var default_default$1 = '123'; + +// module_id: namespace.ts +const foo_ns = 'ns_foo'; +var namespace_default = 'ns_default'; +var namespace_ns = { + foo_ns: foo_ns, + "default": namespace_default, + __esModule: true +}; + +// module_id: named.ts +const foo_named = '123'; + +// module_id: index.ts +console.log(default_default$1, foo_named, namespace_ns); +var index_default = 'index'; +export { index_default as default }; +export { default_default$1, foo_named, foo_ns, namespace_default, namespace_ns }; diff --git a/crates/compiler/tests/fixtures/css/modules/composes/external_import/output.js b/crates/compiler/tests/fixtures/css/modules/composes/external_import/output.js index 6625fca3a..606065d0d 100644 --- a/crates/compiler/tests/fixtures/css/modules/composes/external_import/output.js +++ b/crates/compiler/tests/fixtures/css/modules/composes/external_import/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_0467.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"8b6840d6":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); ""; diff --git a/crates/compiler/tests/fixtures/css/modules/composes/global_import/output.js b/crates/compiler/tests/fixtures/css/modules/composes/global_import/output.js index ad80cca5c..176684dd5 100644 --- a/crates/compiler/tests/fixtures/css/modules/composes/global_import/output.js +++ b/crates/compiler/tests/fixtures/css/modules/composes/global_import/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_2544.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"95fe6ac5":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); ""; diff --git a/crates/compiler/tests/fixtures/css/modules/composes/local_import/output.js b/crates/compiler/tests/fixtures/css/modules/composes/local_import/output.js index a7b5c01be..a5efdba77 100644 --- a/crates/compiler/tests/fixtures/css/modules/composes/local_import/output.js +++ b/crates/compiler/tests/fixtures/css/modules/composes/local_import/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_2544.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"95fe6ac5":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); ""; diff --git a/crates/compiler/tests/fixtures/css/modules/global/output.js b/crates/compiler/tests/fixtures/css/modules/global/output.js index 269e4e6e3..1c8aa9a3c 100644 --- a/crates/compiler/tests/fixtures/css/modules/global/output.js +++ b/crates/compiler/tests/fixtures/css/modules/global/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_2544.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"95fe6ac5":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); ""; diff --git a/crates/compiler/tests/fixtures/css/modules/local/output.js b/crates/compiler/tests/fixtures/css/modules/local/output.js index 7edd2e0d0..7548fec04 100644 --- a/crates/compiler/tests/fixtures/css/modules/local/output.js +++ b/crates/compiler/tests/fixtures/css/modules/local/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_2544.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"95fe6ac5":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); ""; diff --git a/crates/compiler/tests/fixtures/css/modules/normal/output.js b/crates/compiler/tests/fixtures/css/modules/normal/output.js index 6fd40ed07..d5e639e2b 100644 --- a/crates/compiler/tests/fixtures/css/modules/normal/output.js +++ b/crates/compiler/tests/fixtures/css/modules/normal/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_2544.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"95fe6ac5":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); ""; diff --git a/crates/compiler/tests/fixtures/css/prefixer/normal/output.js b/crates/compiler/tests/fixtures/css/prefixer/normal/output.js index 504a5152f..845eca938 100644 --- a/crates/compiler/tests/fixtures/css/prefixer/normal/output.js +++ b/crates/compiler/tests/fixtures/css/prefixer/normal/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); ""; diff --git a/crates/compiler/tests/fixtures/css/url_replacer/absolute/output.js b/crates/compiler/tests/fixtures/css/url_replacer/absolute/output.js index 6bc33eb99..6e9b6081f 100644 --- a/crates/compiler/tests/fixtures/css/url_replacer/absolute/output.js +++ b/crates/compiler/tests/fixtures/css/url_replacer/absolute/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); ""; diff --git a/crates/compiler/tests/fixtures/css/url_replacer/ignored/output.js b/crates/compiler/tests/fixtures/css/url_replacer/ignored/output.js index a8d91a1fc..78dc24acc 100644 --- a/crates/compiler/tests/fixtures/css/url_replacer/ignored/output.js +++ b/crates/compiler/tests/fixtures/css/url_replacer/ignored/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); ""; diff --git a/crates/compiler/tests/fixtures/external/browser/normal/cjs/output.js b/crates/compiler/tests/fixtures/external/browser/normal/cjs/output.js index 85332e7ab..16d563d19 100644 --- a/crates/compiler/tests/fixtures/external/browser/normal/cjs/output.js +++ b/crates/compiler/tests/fixtures/external/browser/normal/cjs/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());window['__farm_default_namespace__'].__farm_module_system__.setExternalModules({"jquery": window['jquery']||{}});(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_jquery = module.i(farmRequire('jquery')); diff --git a/crates/compiler/tests/fixtures/external/browser/normal/esm/output.js b/crates/compiler/tests/fixtures/external/browser/normal/esm/output.js index 07bba9d11..40218a309 100644 --- a/crates/compiler/tests/fixtures/external/browser/normal/esm/output.js +++ b/crates/compiler/tests/fixtures/external/browser/normal/esm/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());window['__farm_default_namespace__'].__farm_module_system__.setExternalModules({"jquery": (window['jquery']||{}).default && !(window['jquery']||{}).__esModule ? {...(window['jquery']||{}),__esModule:true} : ({...window['jquery']||{}})});(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_jquery = module.i(farmRequire('jquery')); diff --git a/crates/compiler/tests/fixtures/external/browser/object/cjs/output.js b/crates/compiler/tests/fixtures/external/browser/object/cjs/output.js index 0b9c5b37b..338e69a81 100644 --- a/crates/compiler/tests/fixtures/external/browser/object/cjs/output.js +++ b/crates/compiler/tests/fixtures/external/browser/object/cjs/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());window['__farm_default_namespace__'].__farm_module_system__.setExternalModules({"jquery": window['$']||{}});(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_jquery = module.i(farmRequire('jquery')); diff --git a/crates/compiler/tests/fixtures/external/browser/object/esm/output.js b/crates/compiler/tests/fixtures/external/browser/object/esm/output.js index b93573402..f203198a6 100644 --- a/crates/compiler/tests/fixtures/external/browser/object/esm/output.js +++ b/crates/compiler/tests/fixtures/external/browser/object/esm/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());window['__farm_default_namespace__'].__farm_module_system__.setExternalModules({"jquery": (window['$']||{}).default && !(window['$']||{}).__esModule ? {...(window['$']||{}),__esModule:true} : ({...window['$']||{}})});(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_jquery = module.i(farmRequire('jquery')); diff --git a/crates/compiler/tests/fixtures/external/node/hosting/import/output.js b/crates/compiler/tests/fixtures/external/node/hosting/import/output.js index 0a276bda9..c1c9e7f2e 100644 --- a/crates/compiler/tests/fixtures/external/node/hosting/import/output.js +++ b/crates/compiler/tests/fixtures/external/node/hosting/import/output.js @@ -1,69 +1,27 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); global['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); import * as __farm_external_module_jquery from "jquery";global['__farm_default_namespace__'].__farm_module_system__.setExternalModules({"jquery": __farm_external_module_jquery && __farm_external_module_jquery.default && !__farm_external_module_jquery.__esModule ? {...__farm_external_module_jquery,__esModule:true} : {...__farm_external_module_jquery}});(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';global['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_jquery = module.i(farmRequire('jquery')); diff --git a/crates/compiler/tests/fixtures/external/node/hosting/require/output.js b/crates/compiler/tests/fixtures/external/node/hosting/require/output.js index 74191645b..559c574d0 100644 --- a/crates/compiler/tests/fixtures/external/node/hosting/require/output.js +++ b/crates/compiler/tests/fixtures/external/node/hosting/require/output.js @@ -1,69 +1,27 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); global['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); (function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';global['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { const xxx = global.nodeRequire('jquery', true); console.log({ diff --git a/crates/compiler/tests/fixtures/external/node/normala/cjs/output.js b/crates/compiler/tests/fixtures/external/node/normala/cjs/output.js index 31a071647..d65131aee 100644 --- a/crates/compiler/tests/fixtures/external/node/normala/cjs/output.js +++ b/crates/compiler/tests/fixtures/external/node/normala/cjs/output.js @@ -1,69 +1,27 @@ //index.js: - global.nodeRequire = require;global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + global.nodeRequire = require;global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); global['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); var __farm_external_module_jquery = require("jquery");global['__farm_default_namespace__'].__farm_module_system__.setExternalModules({"jquery": __farm_external_module_jquery});(function(_){for(var r in _){_[r].__farm_resource_pot__='file://'+__filename;global['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_jquery = module.i(farmRequire('jquery')); diff --git a/crates/compiler/tests/fixtures/external/node/normala/esm/output.js b/crates/compiler/tests/fixtures/external/node/normala/esm/output.js index d5f3e2bbb..c0d6c52a3 100644 --- a/crates/compiler/tests/fixtures/external/node/normala/esm/output.js +++ b/crates/compiler/tests/fixtures/external/node/normala/esm/output.js @@ -1,69 +1,27 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); global['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); import * as __farm_external_module_jquery from "jquery";global['__farm_default_namespace__'].__farm_module_system__.setExternalModules({"jquery": __farm_external_module_jquery && __farm_external_module_jquery.default && !__farm_external_module_jquery.__esModule ? {...__farm_external_module_jquery,__esModule:true} : {...__farm_external_module_jquery}});(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';global['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_jquery = module.i(farmRequire('jquery')); diff --git a/crates/compiler/tests/fixtures/minify/css/basic/output.js b/crates/compiler/tests/fixtures/minify/css/basic/output.js index a81c8090b..087eacdcc 100644 --- a/crates/compiler/tests/fixtures/minify/css/basic/output.js +++ b/crates/compiler/tests/fixtures/minify/css/basic/output.js @@ -1,5 +1,5 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};var e,s;e=(e,s)=>{"use strict";console.log("runtime/index.js"),window.__farm_default_namespace__.__farm_module_system__.setPlugins([]);},()=>(s||(s={exports:{}},"function"==typeof e?e(s,s.exports):e[Object.keys(e)[0]](s,s.exports)),s.exports);(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function n(n,c,f,i){n._m(c);},});window['__farm_default_namespace__'].__farm_module_system__.setInitialLoadedResources([]);window['__farm_default_namespace__'].__farm_module_system__.setDynamicModuleResourcesMap([],{ });var farmModuleSystem = window['__farm_default_namespace__'].__farm_module_system__;farmModuleSystem.bootstrap();var entry = farmModuleSystem.require("b5d64806"); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};var e,s;(e=(e,s)=>{"use strict";console.log("runtime/index.js"),window.__farm_default_namespace__.__farm_module_system__.setPlugins([]);},()=>(s||(s={exports:{}},"function"==typeof e?e(s,s.exports):e[Object.keys(e)[0]](s,s.exports)),s.exports))();(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function n(n,c,f,i){n._m(c);},});window['__farm_default_namespace__'].__farm_module_system__.setInitialLoadedResources([]);window['__farm_default_namespace__'].__farm_module_system__.setDynamicModuleResourcesMap([],{ });var farmModuleSystem = window['__farm_default_namespace__'].__farm_module_system__;farmModuleSystem.bootstrap();var entry = farmModuleSystem.require("b5d64806"); //index_6dd2.css: #root{color:green} diff --git a/crates/compiler/tests/fixtures/minify/html/output.js b/crates/compiler/tests/fixtures/minify/html/output.js index 4b775816e..25abc6e01 100644 --- a/crates/compiler/tests/fixtures/minify/html/output.js +++ b/crates/compiler/tests/fixtures/minify/html/output.js @@ -1,2 +1,2 @@ //index.html: - Document \ No newline at end of file + Document \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/minify/script/basic/output.js b/crates/compiler/tests/fixtures/minify/script/basic/output.js index dfa83e788..dbdeff0b3 100644 --- a/crates/compiler/tests/fixtures/minify/script/basic/output.js +++ b/crates/compiler/tests/fixtures/minify/script/basic/output.js @@ -1,2 +1,2 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};var e,s;e=(e,s)=>{"use strict";console.log("runtime/index.js"),window.__farm_default_namespace__.__farm_module_system__.setPlugins([]);},()=>(s||(s={exports:{}},"function"==typeof e?e(s,s.exports):e[Object.keys(e)[0]](s,s.exports)),s.exports);(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function n(n,t,e,o){n._m(t),n.o(t,"dep_a",function(){return u;});let u=1;},"b5d64806":function e(e,n,a,c){e._m(n);var d=a("05ee5ec7");document.body.innerHTML="a = "+d.dep_a;},});window['__farm_default_namespace__'].__farm_module_system__.setInitialLoadedResources([]);window['__farm_default_namespace__'].__farm_module_system__.setDynamicModuleResourcesMap([],{ });var farmModuleSystem = window['__farm_default_namespace__'].__farm_module_system__;farmModuleSystem.bootstrap();var entry = farmModuleSystem.require("b5d64806"); \ No newline at end of file + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};var e,s;(e=(e,s)=>{"use strict";console.log("runtime/index.js"),window.__farm_default_namespace__.__farm_module_system__.setPlugins([]);},()=>(s||(s={exports:{}},"function"==typeof e?e(s,s.exports):e[Object.keys(e)[0]](s,s.exports)),s.exports))();(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function n(n,t,e,o){n._m(t),n.o(t,"dep_a",function(){return u;});let u=1;},"b5d64806":function e(e,n,a,c){e._m(n);var d=a("05ee5ec7");document.body.innerHTML="a = "+d.dep_a;},});window['__farm_default_namespace__'].__farm_module_system__.setInitialLoadedResources([]);window['__farm_default_namespace__'].__farm_module_system__.setDynamicModuleResourcesMap([],{ });var farmModuleSystem = window['__farm_default_namespace__'].__farm_module_system__;farmModuleSystem.bootstrap();var entry = farmModuleSystem.require("b5d64806"); \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/minify/script/function/output.js b/crates/compiler/tests/fixtures/minify/script/function/output.js index f6137e2d0..b1a245771 100644 --- a/crates/compiler/tests/fixtures/minify/script/function/output.js +++ b/crates/compiler/tests/fixtures/minify/script/function/output.js @@ -1,2 +1,2 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};var e,s;e=(e,s)=>{"use strict";console.log("runtime/index.js"),window.__farm_default_namespace__.__farm_module_system__.setPlugins([]);},()=>(s||(s={exports:{}},"function"==typeof e?e(s,s.exports):e[Object.keys(e)[0]](s,s.exports)),s.exports);(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function t(t,e,n,i){function h(t){return"number"==typeof t&&!isNaN(t);}function r(t,e,n,i){var r=n,a=i;if(e){var d,o=(d=getComputedStyle(t),{width:(t.clientWidth||parseInt(d.width,10))-parseInt(d.paddingLeft,10)-parseInt(d.paddingRight,10),height:(t.clientHeight||parseInt(d.height,10))-parseInt(d.paddingTop,10)-parseInt(d.paddingBottom,10)});r=o.width?o.width:r,a=o.height?o.height:a;}return{width:Math.max(h(r)?r:1,1),height:Math.max(h(a)?a:1,1)};}function a(t){var e=t.parentNode;e&&e.removeChild(t);}t._m(e),t.o(e,"getChartSize",function(){return r;}),t.o(e,"removeDom",function(){return a;});},"b5d64806":function e(e,o,c,m){e._m(o);var n=c("05ee5ec7");console.log(n.getChartSize,n.removeDom);},});window['__farm_default_namespace__'].__farm_module_system__.setInitialLoadedResources([]);window['__farm_default_namespace__'].__farm_module_system__.setDynamicModuleResourcesMap([],{ });var farmModuleSystem = window['__farm_default_namespace__'].__farm_module_system__;farmModuleSystem.bootstrap();var entry = farmModuleSystem.require("b5d64806"); \ No newline at end of file + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};var e,s;(e=(e,s)=>{"use strict";console.log("runtime/index.js"),window.__farm_default_namespace__.__farm_module_system__.setPlugins([]);},()=>(s||(s={exports:{}},"function"==typeof e?e(s,s.exports):e[Object.keys(e)[0]](s,s.exports)),s.exports))();(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function t(t,e,n,i){function h(t){return"number"==typeof t&&!isNaN(t);}function r(t,e,n,i){var r=n,a=i;if(e){var d,o=(d=getComputedStyle(t),{width:(t.clientWidth||parseInt(d.width,10))-parseInt(d.paddingLeft,10)-parseInt(d.paddingRight,10),height:(t.clientHeight||parseInt(d.height,10))-parseInt(d.paddingTop,10)-parseInt(d.paddingBottom,10)});r=o.width?o.width:r,a=o.height?o.height:a;}return{width:Math.max(h(r)?r:1,1),height:Math.max(h(a)?a:1,1)};}function a(t){var e=t.parentNode;e&&e.removeChild(t);}t._m(e),t.o(e,"getChartSize",function(){return r;}),t.o(e,"removeDom",function(){return a;});},"b5d64806":function e(e,o,c,m){e._m(o);var n=c("05ee5ec7");console.log(n.getChartSize,n.removeDom);},});window['__farm_default_namespace__'].__farm_module_system__.setInitialLoadedResources([]);window['__farm_default_namespace__'].__farm_module_system__.setDynamicModuleResourcesMap([],{ });var farmModuleSystem = window['__farm_default_namespace__'].__farm_module_system__;farmModuleSystem.bootstrap();var entry = farmModuleSystem.require("b5d64806"); \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/partial_bundling/basic/output.js b/crates/compiler/tests/fixtures/partial_bundling/basic/output.js index dfc875e09..42fac550e 100644 --- a/crates/compiler/tests/fixtures/partial_bundling/basic/output.js +++ b/crates/compiler/tests/fixtures/partial_bundling/basic/output.js @@ -1,69 +1,27 @@ //__farm_runtime.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })()); //debounce_6f74.js: diff --git a/crates/compiler/tests/fixtures/runtime/bundle/browser/external/output.js b/crates/compiler/tests/fixtures/runtime/bundle/browser/external/output.js index ae97ee835..906b59387 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/browser/external/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/browser/external/output.js @@ -1,49 +1,5 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}((function(){import fs from "node:fs.farm-runtime"; + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){import fs from "node:fs.farm-runtime"; console.log(fs); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) {} diff --git a/crates/compiler/tests/fixtures/runtime/bundle/browser/normal/output.js b/crates/compiler/tests/fixtures/runtime/bundle/browser/normal/output.js index 0e10cc9f3..f9badff4a 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/browser/normal/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/browser/normal/output.js @@ -1,68 +1,26 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var runtime_ts_cjs = __commonJs((module, exports)=>{ +} +var runtime_ts_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('hello world'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +runtime_ts_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) {} ,});window['__farm_default_namespace__'].__farm_module_system__.setInitialLoadedResources([]);window['__farm_default_namespace__'].__farm_module_system__.setDynamicModuleResourcesMap([],{ });var farmModuleSystem = window['__farm_default_namespace__'].__farm_module_system__;farmModuleSystem.bootstrap();var entry = farmModuleSystem.require("b5d64806"); \ No newline at end of file diff --git a/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/circlesImportCjs/output.js b/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/circlesImportCjs/output.js index 965ca4ffa..7b65d49b5 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/circlesImportCjs/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/circlesImportCjs/output.js @@ -1,65 +1,22 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var cjs_ts_cjs = __commonJs((module, exports)=>{ +} +var cjs_ts_cjs = __commonJs((module, exports)=>{ const foo = export_ts_cjs(); module.exports.name = "foo"; module.exports.age = 18; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/entryExportStar/output.js b/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/entryExportStar/output.js index 11d6d57ce..f9c13cbea 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/entryExportStar/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/entryExportStar/output.js @@ -1,21 +1,30 @@ //index.js: - global.nodeRequire = require;global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + global.nodeRequire = require;global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); + } + return module.exports; + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) return obj; if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { default: obj @@ -36,30 +45,8 @@ newObj.default = obj; if (cache) cache.set(obj, newObj); return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, - }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var node_fs_ns = _interop_require_wildcard(require("node:fs.farm-runtime")); +} +var node_fs_ns = _interop_require_wildcard(require("node:fs.farm-runtime")); var cjsExport_ts_cjs = __commonJs((module, exports)=>{ "use strict"; Object.defineProperty(exports, "__esModule", { diff --git a/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/exportNamed/output.js b/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/exportNamed/output.js index 82c89068a..3f85b37c0 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/exportNamed/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/exportNamed/output.js @@ -1,65 +1,22 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};// module_id: dep.ts.farm-runtime +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}// module_id: dep.ts.farm-runtime +} var dep_ts_cjs = __commonJs({ "dep.ts.farm-runtime": (module, exports)=>{ module.exports.name = 'shulan'; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/exportNamespace/output.js b/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/exportNamespace/output.js index 760b155a4..b9f7f8381 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/exportNamespace/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/exportNamespace/output.js @@ -1,21 +1,30 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; + } + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { + return module.exports; + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) return obj; if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { default: obj @@ -36,30 +45,8 @@ newObj.default = obj; if (cache) cache.set(obj, newObj); return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, - }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var dep_ts_cjs = __commonJs((module, exports)=>{ +} +var dep_ts_cjs = __commonJs((module, exports)=>{ module.exports.name = 'shulan'; module.exports.age = 18; module.exports.default = 'default'; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/exportStar/output.js b/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/exportStar/output.js index 2e0bcb65e..62524c70f 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/exportStar/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/exportStar/output.js @@ -1,78 +1,38 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function _mergeNamespaces(n, m) { - m.forEach(function (e) { - e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + return module.exports; + }; +} +function _mergeNamespaces(n, m) { + m.forEach(function(e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function(k) { if (k !== 'default' && !(k in n)) { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, - get: function () { return e[k]; } + get: function() { + return e[k]; + } }); } }); }); return Object.freeze(n); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, - }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var cjsExport_ts_cjs = __commonJs((module, exports)=>{ +} +var cjsExport_ts_cjs = __commonJs((module, exports)=>{ module.exports.name = 'shulan'; module.exports.age = 18; module.exports.default = 'default'; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/repeatUsingCjs/output.js b/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/repeatUsingCjs/output.js index c07d01b81..f89a30ad2 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/repeatUsingCjs/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/cjs/export/repeatUsingCjs/output.js @@ -1,21 +1,30 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); + } + return module.exports; + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) return obj; if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { default: obj @@ -36,30 +45,13 @@ newObj.default = obj; if (cache) cache.set(obj, newObj); return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, +} +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var cjs_ts_cjs = __commonJs((module, exports)=>{ +} +var cjs_ts_cjs = __commonJs((module, exports)=>{ module.exports.name = "foo"; module.exports.age = 18; }); diff --git a/crates/compiler/tests/fixtures/runtime/bundle/cjs/hybrid/exportStar/output.js b/crates/compiler/tests/fixtures/runtime/bundle/cjs/hybrid/exportStar/output.js index 2c4c2a61d..ffcfe7567 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/cjs/hybrid/exportStar/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/cjs/hybrid/exportStar/output.js @@ -1,78 +1,38 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};// module_id: cjsExport.ts.farm-runtime +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function _mergeNamespaces(n, m) { - m.forEach(function (e) { - e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + return module.exports; + }; +} +function _mergeNamespaces(n, m) { + m.forEach(function(e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function(k) { if (k !== 'default' && !(k in n)) { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, - get: function () { return e[k]; } + get: function() { + return e[k]; + } }); } }); }); return Object.freeze(n); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, - }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}// module_id: cjsExport.ts.farm-runtime +} import * as node_fs_ns from "node:fs.farm-runtime"; var cjsExport_ts_cjs = __commonJs({ "cjsExport.ts.farm-runtime": (module, exports)=>{ diff --git a/crates/compiler/tests/fixtures/runtime/bundle/cjs/hybrid/nested_require/output.js b/crates/compiler/tests/fixtures/runtime/bundle/cjs/hybrid/nested_require/output.js index 2ff61e1c9..06cc34f1a 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/cjs/hybrid/nested_require/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/cjs/hybrid/nested_require/output.js @@ -1,65 +1,22 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}function cjs_ts_default() { +} +function cjs_ts_default() { console.log('foo'); } var cjs_ts_ns = { diff --git a/crates/compiler/tests/fixtures/runtime/bundle/cjs/hybrid/unresolved_variables/output.js b/crates/compiler/tests/fixtures/runtime/bundle/cjs/hybrid/unresolved_variables/output.js index 9286e786e..0c3c0d4f5 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/cjs/hybrid/unresolved_variables/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/cjs/hybrid/unresolved_variables/output.js @@ -1,65 +1,22 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var cjs_ts_cjs = __commonJs((module, exports)=>{ +} +var cjs_ts_cjs = __commonJs((module, exports)=>{ module.exports.name = "shulan"; module.exports.age = 18; foo = "unresolved_variable"; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/cjs/normal/output.js b/crates/compiler/tests/fixtures/runtime/bundle/cjs/normal/output.js index cf1d39cc8..ec1021473 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/cjs/normal/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/cjs/normal/output.js @@ -1,21 +1,31 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};// module_id: esmExport.ts.farm-runtime +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); + } + return module.exports; + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) return obj; if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { default: obj @@ -36,30 +46,12 @@ newObj.default = obj; if (cache) cache.set(obj, newObj); return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, +} +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}// module_id: esmExport.ts.farm-runtime +} const name = 'name'; const age = 18; var esmExport_ts_default = { diff --git a/crates/compiler/tests/fixtures/runtime/bundle/decl/export_default_decl/no_ident/output.js b/crates/compiler/tests/fixtures/runtime/bundle/decl/export_default_decl/no_ident/output.js index 04d12e6a0..93545f445 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/decl/export_default_decl/no_ident/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/decl/export_default_decl/no_ident/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}class export_class_ts_default { + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};class export_class_ts_default { constructor(){ console.log('class foo'); } diff --git a/crates/compiler/tests/fixtures/runtime/bundle/decl/forward_export/output.js b/crates/compiler/tests/fixtures/runtime/bundle/decl/forward_export/output.js index acb8dc156..a9966dd93 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/decl/forward_export/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/decl/forward_export/output.js @@ -1,65 +1,22 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}function Layout() {} +} +function Layout() {} function wrap(fn) { return ()=>{ return fn(); diff --git a/crates/compiler/tests/fixtures/runtime/bundle/decl/normal/output.js b/crates/compiler/tests/fixtures/runtime/bundle/decl/normal/output.js index 3459764c4..36b87102c 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/decl/normal/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/decl/normal/output.js @@ -1,65 +1,22 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var runtime_2_ts_cjs = __commonJs((module, exports)=>{ +} +var runtime_2_ts_cjs = __commonJs((module, exports)=>{ "use strict"; const a = 3; const b = 4; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/decl/self_ref/output.js b/crates/compiler/tests/fixtures/runtime/bundle/decl/self_ref/output.js index a95747a0e..bf6354fe5 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/decl/self_ref/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/decl/self_ref/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function addClass() { + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function addClass() { console.log('addClass'); } diff --git a/crates/compiler/tests/fixtures/runtime/bundle/decl/spread/output.js b/crates/compiler/tests/fixtures/runtime/bundle/decl/spread/output.js index c3731dfbb..ab668dae2 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/decl/spread/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/decl/spread/output.js @@ -1,65 +1,22 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}const Row = ()=>{}; +} +const Row = ()=>{}; const Col = ()=>{}; const Grid = { Row: Row, diff --git a/crates/compiler/tests/fixtures/runtime/bundle/decl/unresolved_variable/output.js b/crates/compiler/tests/fixtures/runtime/bundle/decl/unresolved_variable/output.js index c5a26cdba..394ccccc1 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/decl/unresolved_variable/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/decl/unresolved_variable/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const name = 100; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const name = 100; foo = "bar"; let foo$1 = 200; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/decl/var/output.js b/crates/compiler/tests/fixtures/runtime/bundle/decl/var/output.js index 86f1742a1..9ed765324 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/decl/var/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/decl/var/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const foo = 'foo', arrowFn = ()=>{}, fn = function() {}, obj = { + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const foo = 'foo', arrowFn = ()=>{}, fn = function() {}, obj = { key: 'value' }, arr = []; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/dynamic/normal/output.js b/crates/compiler/tests/fixtures/runtime/bundle/dynamic/normal/output.js index fda4fee3d..35125c9ad 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/dynamic/normal/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/dynamic/normal/output.js @@ -1,58 +1,14 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function foo$1() { + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function foo() { console.log('foo'); } var dynamic_ts_ns = { - "default": foo$1, + "default": foo, __esModule: true }; Promise.resolve(dynamic_ts_ns).then((res)=>res.default()); -const foo = ()=>Promise.resolve(dynamic_ts_ns); +const foo$1 = ()=>Promise.resolve(dynamic_ts_ns); function loader(m) {} loader(Promise.resolve(dynamic_ts_ns)); Promise.resolve(dynamic_ts_ns); diff --git a/crates/compiler/tests/fixtures/runtime/bundle/export/emptyExport/output.js b/crates/compiler/tests/fixtures/runtime/bundle/export/emptyExport/output.js index 30f683795..20bdf7104 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/export/emptyExport/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/export/emptyExport/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -} + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'}; console.log(fs); global['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); (function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';global['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) {} diff --git a/crates/compiler/tests/fixtures/runtime/bundle/export/entryExport1/output.js b/crates/compiler/tests/fixtures/runtime/bundle/export/entryExport1/output.js index 8740330ad..b9acc1ce4 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/export/entryExport1/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/export/entryExport1/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const a = 10; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const a = 10; function b() { return 20; } diff --git a/crates/compiler/tests/fixtures/runtime/bundle/export/entryExport2/output.js b/crates/compiler/tests/fixtures/runtime/bundle/export/entryExport2/output.js index 8740330ad..b9acc1ce4 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/export/entryExport2/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/export/entryExport2/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const a = 10; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const a = 10; function b() { return 20; } diff --git a/crates/compiler/tests/fixtures/runtime/bundle/export/entryExport3/output.js b/crates/compiler/tests/fixtures/runtime/bundle/export/entryExport3/output.js index 02c08672f..98aefc650 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/export/entryExport3/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/export/entryExport3/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const a = 3; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const a = 3; const b = 4; const c = 5; function BB() { diff --git a/crates/compiler/tests/fixtures/runtime/bundle/export/exportDefault1/output.js b/crates/compiler/tests/fixtures/runtime/bundle/export/exportDefault1/output.js index 738870765..0660fdbdb 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/export/exportDefault1/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/export/exportDefault1/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const a = 3; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const a = 3; const a$1 = 3 + a; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/export/exportDefaultDecl/output.js b/crates/compiler/tests/fixtures/runtime/bundle/export/exportDefaultDecl/output.js index b5e68733f..f3a4c9fcf 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/export/exportDefaultDecl/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/export/exportDefaultDecl/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const a = 3; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const a = 3; class getA { constructor(){} getA() { diff --git a/crates/compiler/tests/fixtures/runtime/bundle/export/exportDefaultExpr/output.js b/crates/compiler/tests/fixtures/runtime/bundle/export/exportDefaultExpr/output.js index eebd281fd..f67eeb7d4 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/export/exportDefaultExpr/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/export/exportDefaultExpr/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const a = 3; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const a = 3; var runtime_2_ts_default = a + 10; var runtime_1_ts_default = runtime_2_ts_default + 20; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/export/exportNamed1/output.js b/crates/compiler/tests/fixtures/runtime/bundle/export/exportNamed1/output.js index 8bcc8e56a..108362bdd 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/export/exportNamed1/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/export/exportNamed1/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const a = 'a-runtime.2.ts'; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const a = 'a-runtime.2.ts'; const b = 'b-runtime.2.ts'; function BB() { const a$1 = 5; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/export/exportNamed2/output.js b/crates/compiler/tests/fixtures/runtime/bundle/export/exportNamed2/output.js index a6e11e141..8711ae877 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/export/exportNamed2/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/export/exportNamed2/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const a = 'a-runtime2-a.ts'; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const a = 'a-runtime2-a.ts'; const b = 'b-runtime2-b.ts'; function BB() { const a$1 = 5; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/export/exportNamed3/output.js b/crates/compiler/tests/fixtures/runtime/bundle/export/exportNamed3/output.js index c3794c706..d63de9687 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/export/exportNamed3/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/export/exportNamed3/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const isString = (v)=>{ + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const isString = (v)=>{ console.log('isString1'); return typeof v === 'string'; }; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_all/output.js b/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_all/output.js index 18d279600..981c50be7 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_all/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_all/output.js @@ -1,62 +1,21 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function _mergeNamespaces(n, m) { - m.forEach(function (e) { - e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _mergeNamespaces(n, m) { + m.forEach(function(e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function(k) { if (k !== 'default' && !(k in n)) { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, - get: function () { return e[k]; } + get: function() { + return e[k]; + } }); } }); }); return Object.freeze(n); -}import * as node_fs_ns from "node:fs.farm-runtime"; +} +import * as node_fs_ns from "node:fs.farm-runtime"; var exportAll_ts_ns = _mergeNamespaces({ __esModule: true }, [ diff --git a/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_as_namespace/output.js b/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_as_namespace/output.js index bcede061e..5fbebb06e 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_as_namespace/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_as_namespace/output.js @@ -1,78 +1,39 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function _mergeNamespaces(n, m) { - m.forEach(function (e) { - e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + return module.exports; + }; +} +function _mergeNamespaces(n, m) { + m.forEach(function(e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function(k) { if (k !== 'default' && !(k in n)) { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, - get: function () { return e[k]; } + get: function() { + return e[k]; + } }); } }); }); return Object.freeze(n); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, - }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var exportCjs_ts_cjs = __commonJs((module, exports)=>{ +} +import { readFile, readFileSync } from "node:fs.farm-runtime"; +var exportCjs_ts_cjs = __commonJs((module, exports)=>{ module.exports.name = "shulan"; module.exports.age = 18; }); diff --git a/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_named/output.js b/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_named/output.js index ab6be1157..637d0ea95 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_named/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_named/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}import { readFileSync, readSync } from "node:fs.farm-runtime"; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};import { readFileSync, readSync } from "node:fs.farm-runtime"; const bundle2A = 'bundle2A'; const bundle2B = 'bundle2B'; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_namespace/output.js b/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_namespace/output.js index 2c561f212..e4afd3104 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_namespace/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/external/export/from_source/export_namespace/output.js @@ -1,21 +1,14 @@ //index.js: - global.nodeRequire = require;global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { + global.nodeRequire = require;global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};// module_id: exportNamespace.ts.farm-runtime +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) return obj; if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { default: obj @@ -36,14 +29,7 @@ newObj.default = obj; if (cache) cache.set(obj, newObj); return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}// module_id: exportNamespace.ts.farm-runtime +} var node_fs_ns = _interop_require_wildcard(require("node:fs.farm-runtime")); console.log('export namespace'); var exportNamespace_ts_ns = { diff --git a/crates/compiler/tests/fixtures/runtime/bundle/external/import/default/output.js b/crates/compiler/tests/fixtures/runtime/bundle/external/import/default/output.js index 62975266b..c6384ab79 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/external/import/default/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/external/import/default/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}import fs$1 from "fs.farm-runtime"; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};import fs$1 from "fs.farm-runtime"; import fs from "node:fs.farm-runtime"; console.log('external 1', fs); diff --git a/crates/compiler/tests/fixtures/runtime/bundle/external/import/named/output.js b/crates/compiler/tests/fixtures/runtime/bundle/external/import/named/output.js index 64f4d02dd..56e28a812 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/external/import/named/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/external/import/named/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}import { read } from "node:fs.farm-runtime"; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};import { read } from "node:fs.farm-runtime"; console.log('external 1', read); console.log('external 2', read); diff --git a/crates/compiler/tests/fixtures/runtime/bundle/external/import/namespace/output.js b/crates/compiler/tests/fixtures/runtime/bundle/external/import/namespace/output.js index 318a6f168..a3a0204ba 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/external/import/namespace/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/external/import/namespace/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}import * as node_fs_ns from "node:fs.farm-runtime"; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};import * as node_fs_ns from "node:fs.farm-runtime"; console.log('external 1', node_fs_ns); console.log('external 1', node_fs_ns); diff --git a/crates/compiler/tests/fixtures/runtime/bundle/function/output.js b/crates/compiler/tests/fixtures/runtime/bundle/function/output.js index f0c71b49f..71363875b 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/function/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/function/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const MIN_CHART_WIDTH = 1; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const MIN_CHART_WIDTH = 1; const MIN_CHART_HEIGHT = 1; function getElementSize(ele) { var style = getComputedStyle(ele); diff --git a/crates/compiler/tests/fixtures/runtime/bundle/import/importDefault/output.js b/crates/compiler/tests/fixtures/runtime/bundle/import/importDefault/output.js index 908edd27a..47915dbd3 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/import/importDefault/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/import/importDefault/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}class DC { + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};class DC { constructor(){} } diff --git a/crates/compiler/tests/fixtures/runtime/bundle/import/importNamed/output.js b/crates/compiler/tests/fixtures/runtime/bundle/import/importNamed/output.js index 3accdfe32..2204e7e89 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/import/importNamed/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/import/importNamed/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const a = 3; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const a = 3; const b = 4; function BB() { const a$1 = 5; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/import/importNamespace/output.js b/crates/compiler/tests/fixtures/runtime/bundle/import/importNamespace/output.js index 3d7b19ad7..5cfe12ded 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/import/importNamespace/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/import/importNamespace/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const a = 3; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const a = 3; const b = 4; const c = 5; function BB() { diff --git a/crates/compiler/tests/fixtures/runtime/bundle/import/importedInScope/output.js b/crates/compiler/tests/fixtures/runtime/bundle/import/importedInScope/output.js index a23d9bbb1..b9d8bb83a 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/import/importedInScope/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/import/importedInScope/output.js @@ -1,65 +1,21 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const hello$5 = 'hello1'; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const hello = 'hello1'; const hello$1 = 'hello'; -console.log(hello$5, hello$1); +console.log(hello, hello$1); function export_nested() { - const hello = 'hello'; - console.log(hello); + const hello$2 = 'hello'; + console.log(hello$2); } -var hello$2 = hello$5; +var hello$3 = hello; function say() { - var hello$3 = hello$5; - var hello$1$1 = hello$5; - console.log(hello$3); + var hello$4 = hello; + var hello$1$1 = hello; + console.log(hello$4); function nested_say() { - var hello$4 = hello$5; - var hello$2$1 = hello$5; - console.log(hello$4); + var hello$5 = hello; + var hello$2$1 = hello; + console.log(hello$5); } } say(); diff --git a/crates/compiler/tests/fixtures/runtime/bundle/import/sameImport/output.js b/crates/compiler/tests/fixtures/runtime/bundle/import/sameImport/output.js index 8e7e44bf3..0397ddb8f 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/import/sameImport/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/import/sameImport/output.js @@ -1,65 +1,27 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; + }; +} +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}var export_ts_cjs = __commonJs((module, exports)=>{ +} +var export_ts_cjs = __commonJs((module, exports)=>{ module.exports = function() { console.log('safe import'); }; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/interface/output.js b/crates/compiler/tests/fixtures/runtime/bundle/interface/output.js index e34ab8459..1504171d5 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/interface/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/interface/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -} + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'}; const foo = 10; console.log(1, 10, foo); global['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); diff --git a/crates/compiler/tests/fixtures/runtime/bundle/issues/merge_props/output.js b/crates/compiler/tests/fixtures/runtime/bundle/issues/merge_props/output.js index 1b562e83c..3c7309cb4 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/issues/merge_props/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/issues/merge_props/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}var __assign = this && this.__assign || function() { + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};var __assign = this && this.__assign || function() { __assign = Object.assign || function(t) { for(var s, i = 1, n = arguments.length; i < n; i++){ s = arguments[i]; @@ -53,15 +9,15 @@ }; return __assign.apply(this, arguments); }; -function mergeProps$1(componentProps, defaultProps, globalComponentConfig) { +function mergeProps(componentProps, defaultProps, globalComponentConfig) { var _defaultProps = __assign(__assign({}, defaultProps), globalComponentConfig); - var props = __assign({}, componentProps); + var props$1 = __assign({}, componentProps); for(var propName in _defaultProps){ - if (props[propName] === undefined) { - props[propName] = _defaultProps[propName]; + if (props$1[propName] === undefined) { + props$1[propName] = _defaultProps[propName]; } } - return props; + return props$1; } var Trigger = function(_super) { @@ -70,8 +26,8 @@ var Trigger = function(_super) { var _this = _super.call(this, props, context) || this; _this.getMergedProps = function(baseProps) { var componentConfig = _this.context.componentConfig; - var props$1 = mergeProps$1(baseProps || _this.props, defaultProps, componentConfig === null || componentConfig === void 0 ? void 0 : componentConfig.Trigger); - return props$1; + var props$3 = mergeProps(baseProps || _this.props, defaultProps, componentConfig === null || componentConfig === void 0 ? void 0 : componentConfig.Trigger); + return props$3; }; return _this; } @@ -86,59 +42,59 @@ var Trigger = function(_super) { if (!popup) { return null; } - var mergeProps = {}; + var mergeProps$1 = {}; var popupEventProps = { onMouseDown: this.onPopupMouseDown }; if (this.isHoverTrigger() && !disabled) { - mergeProps.onMouseEnter = this.onMouseEnter; - mergeProps.onMouseLeave = this.onMouseLeave; + mergeProps$1.onMouseEnter = this.onMouseEnter; + mergeProps$1.onMouseLeave = this.onMouseLeave; if (alignPoint) { - mergeProps.onMouseMove = this.onMouseMove; + mergeProps$1.onMouseMove = this.onMouseMove; } if (!this.isPopupHoverHide()) { popupEventProps.onMouseEnter = this.onPopupMouseEnter; popupEventProps.onMouseLeave = this.onPopupMouseLeave; } } else { - mergeProps.onMouseEnter = this.triggerOriginEvent('onMouseEnter'); - mergeProps.onMouseLeave = this.triggerOriginEvent('onMouseLeave'); + mergeProps$1.onMouseEnter = this.triggerOriginEvent('onMouseEnter'); + mergeProps$1.onMouseLeave = this.triggerOriginEvent('onMouseLeave'); } if (this.isContextMenuTrigger() && !disabled) { - mergeProps.onContextMenu = this.onContextMenu; - mergeProps.onClick = this.hideContextMenu; + mergeProps$1.onContextMenu = this.onContextMenu; + mergeProps$1.onClick = this.hideContextMenu; } else { - mergeProps.onContextMenu = this.triggerOriginEvent('onContextMenu'); + mergeProps$1.onContextMenu = this.triggerOriginEvent('onContextMenu'); } if (this.isClickTrigger() && !disabled) { - mergeProps.onClick = this.onClick; + mergeProps$1.onClick = this.onClick; } else { - mergeProps.onClick = mergeProps.onClick || this.triggerOriginEvent('onClick'); + mergeProps$1.onClick = mergeProps$1.onClick || this.triggerOriginEvent('onClick'); } if (this.isFocusTrigger() && !disabled) { - mergeProps.onFocus = this.onFocus; + mergeProps$1.onFocus = this.onFocus; if (this.isBlurToHide()) { - mergeProps.onBlur = this.onBlur; + mergeProps$1.onBlur = this.onBlur; } } else { - mergeProps.onFocus = this.triggerOriginEvent('onFocus'); - mergeProps.onBlur = this.triggerOriginEvent('onBlur'); + mergeProps$1.onFocus = this.triggerOriginEvent('onFocus'); + mergeProps$1.onBlur = this.triggerOriginEvent('onBlur'); } if (!disabled) { - mergeProps.onKeyDown = this.onKeyDown; + mergeProps$1.onKeyDown = this.onKeyDown; } else { - mergeProps.onKeyDown = this.triggerOriginEvent('onKeyDown'); + mergeProps$1.onKeyDown = this.triggerOriginEvent('onKeyDown'); } var child = this.getChild(); var popupChildren = React.Children.only(popup()); if (child.props.className) { - mergeProps.className = child.props.className; + mergeProps$1.className = child.props.className; } if (childrenPrefix && popupVisible) { - mergeProps.className = mergeProps.className ? mergeProps.className + " " + childrenPrefix + "-open" : childrenPrefix + "-open"; + mergeProps$1.className = mergeProps$1.className ? mergeProps$1.className + " " + childrenPrefix + "-open" : childrenPrefix + "-open"; } if (this.isFocusTrigger()) { - mergeProps.tabIndex = disabled ? -1 : 0; + mergeProps$1.tabIndex = disabled ? -1 : 0; } }; return Trigger$1; diff --git a/crates/compiler/tests/fixtures/runtime/bundle/lazy_compilation/output.js b/crates/compiler/tests/fixtures/runtime/bundle/lazy_compilation/output.js index 544898b7d..650e0aad8 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/lazy_compilation/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/lazy_compilation/output.js @@ -1,49 +1,5 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}((function(){const name = 'foo'; + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){const name = 'foo'; var foo_ts_ns = { name: name, __esModule: true diff --git a/crates/compiler/tests/fixtures/runtime/bundle/polyfill/reserved_word/cjs/output.js b/crates/compiler/tests/fixtures/runtime/bundle/polyfill/reserved_word/cjs/output.js index fa370b982..84cf5cbd1 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/polyfill/reserved_word/cjs/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/polyfill/reserved_word/cjs/output.js @@ -1,65 +1,22 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}function foo() {} +} +function foo() {} var dep_ts_ns = { "default": foo, __esModule: true diff --git a/crates/compiler/tests/fixtures/runtime/bundle/polyfill/reserved_word/esm/output.js b/crates/compiler/tests/fixtures/runtime/bundle/polyfill/reserved_word/esm/output.js index b32df6748..48a087ac7 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/polyfill/reserved_word/esm/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/polyfill/reserved_word/esm/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const a = 10; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const a = 10; function foo() {} var dep_ts_ns = { a: a, diff --git a/crates/compiler/tests/fixtures/runtime/bundle/rename/output.js b/crates/compiler/tests/fixtures/runtime/bundle/rename/output.js index 2338bbed8..f5d40e69f 100644 --- a/crates/compiler/tests/fixtures/runtime/bundle/rename/output.js +++ b/crates/compiler/tests/fixtures/runtime/bundle/rename/output.js @@ -1,49 +1,5 @@ //index.js: - import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); - } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}const namedA = 10; + import __farmNodeModule from 'node:module';global.nodeRequire = __farmNodeModule.createRequire(import.meta.url);global['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'node'};const namedA = 10; const namedB = 20; const namedC = 30; const sameNameWithFile_ts = 1; diff --git a/crates/compiler/tests/fixtures/script/accept_deps/output.js b/crates/compiler/tests/fixtures/script/accept_deps/output.js index 0effa7790..e20bb0be0 100644 --- a/crates/compiler/tests/fixtures/script/accept_deps/output.js +++ b/crates/compiler/tests/fixtures/script/accept_deps/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_fb79.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_foo = farmRequire("59ebf907"); diff --git a/crates/compiler/tests/fixtures/script/comments/output.js b/crates/compiler/tests/fixtures/script/comments/output.js index 93f02d3a8..a0e5ad297 100644 --- a/crates/compiler/tests/fixtures/script/comments/output.js +++ b/crates/compiler/tests/fixtures/script/comments/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":/** * @license MIT this comments should be preserved */ function (module, exports, farmRequire, farmDynamicRequire) { diff --git a/crates/compiler/tests/fixtures/script/import_equals/output.js b/crates/compiler/tests/fixtures/script/import_equals/output.js index ffc5f21bd..cec2ebc20 100644 --- a/crates/compiler/tests/fixtures/script/import_equals/output.js +++ b/crates/compiler/tests/fixtures/script/import_equals/output.js @@ -1,69 +1,27 @@ //__farm_runtime.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })()); //index.js: diff --git a/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/absolute_public_path/lit_str/output.js b/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/absolute_public_path/lit_str/output.js index 35846f8cf..a2ae3e08d 100644 --- a/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/absolute_public_path/lit_str/output.js +++ b/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/absolute_public_path/lit_str/output.js @@ -2,71 +2,29 @@ foo //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_2f83.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_foo = module.i(farmRequire("e6cee430")); diff --git a/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/relative_public_path/tip/complate/output.js b/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/relative_public_path/tip/complate/output.js index 6b650d84c..1a5a1f717 100644 --- a/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/relative_public_path/tip/complate/output.js +++ b/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/relative_public_path/tip/complate/output.js @@ -2,71 +2,29 @@ foo_bar //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dff7.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b334ec2f":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); exports.default = "/foo_bar-47689c.txt?url"; diff --git a/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/relative_public_path/tip/normal/output.js b/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/relative_public_path/tip/normal/output.js index 22c85ee01..88dd9d6a7 100644 --- a/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/relative_public_path/tip/normal/output.js +++ b/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/relative_public_path/tip/normal/output.js @@ -5,71 +5,29 @@ foo //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_5425.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"27eb6d1d":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); exports.default = "./foo-8bdf4c.txt?url"; diff --git a/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/relative_public_path/tip/tip_star_star/output.js b/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/relative_public_path/tip/tip_star_star/output.js index 91c4c9517..803b3662d 100644 --- a/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/relative_public_path/tip/tip_star_star/output.js +++ b/crates/compiler/tests/fixtures/script/import_meta_url_with_URL/relative_public_path/tip/tip_star_star/output.js @@ -2,71 +2,29 @@ foo //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_daf2.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"27eb6d1d":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); exports.default = "./foo-8bdf4c.txt?url"; diff --git a/crates/compiler/tests/fixtures/script/native_top_level_await/output.js b/crates/compiler/tests/fixtures/script/native_top_level_await/output.js index bd8d2f520..0fc65fdae 100644 --- a/crates/compiler/tests/fixtures/script/native_top_level_await/output.js +++ b/crates/compiler/tests/fixtures/script/native_top_level_await/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":async function (module, exports, farmRequire, farmDynamicRequire) { const delay = (ms)=>new Promise((resolve)=>setTimeout(resolve, ms)); await delay(3000); diff --git a/crates/compiler/tests/fixtures/tree_shake/basic/output.js b/crates/compiler/tests/fixtures/tree_shake/basic/output.js index 3be34cf0c..931443614 100644 --- a/crates/compiler/tests/fixtures/tree_shake/basic/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/basic/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "a", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/changed_ast/output.js b/crates/compiler/tests/fixtures/tree_shake/changed_ast/output.js index fba29b7ca..f6de1183f 100644 --- a/crates/compiler/tests/fixtures/tree_shake/changed_ast/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/changed_ast/output.js @@ -1,65 +1,22 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){// module_id: ../../_internal/runtime/index.js.farm-runtime +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){// module_id: ../../_internal/runtime/index.js.farm-runtime +} var index_js_cjs = __commonJs({ "../../_internal/runtime/index.js.farm-runtime": (module, exports)=>{ "use strict"; @@ -67,6 +24,7 @@ var index_js_cjs = __commonJs({ window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); } }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_4924.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"comp.tsx":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "Description", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/cjs/output.js b/crates/compiler/tests/fixtures/tree_shake/cjs/output.js index 63992de59..42ccfacf5 100644 --- a/crates/compiler/tests/fixtures/tree_shake/cjs/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/cjs/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_6889.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"3da733a3":function (module, exports, farmRequire, farmDynamicRequire) { module.exports = function() { return 'b'; diff --git a/crates/compiler/tests/fixtures/tree_shake/compiled-vue-comp/output.js b/crates/compiler/tests/fixtures/tree_shake/compiled-vue-comp/output.js index 258d32f39..085759ca2 100644 --- a/crates/compiler/tests/fixtures/tree_shake/compiled-vue-comp/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/compiled-vue-comp/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());window['__farm_default_namespace__'].__farm_module_system__.setExternalModules({"vue": (window['vue']||{}).default && !(window['vue']||{}).__esModule ? {...(window['vue']||{}),__esModule:true} : ({...window['vue']||{}})});(function(_){for(var r in _){_[r].__farm_resource_pot__='index_236f.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"8cea7e1d":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); exports.default = (a)=>a; diff --git a/crates/compiler/tests/fixtures/tree_shake/css/output.js b/crates/compiler/tests/fixtures/tree_shake/css/output.js index 883d8e9aa..32e648584 100644 --- a/crates/compiler/tests/fixtures/tree_shake/css/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/css/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_cb11.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"44a34200":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "c", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/cyclic_deps/output.js b/crates/compiler/tests/fixtures/tree_shake/cyclic_deps/output.js index dfd1c01ec..c76253af6 100644 --- a/crates/compiler/tests/fixtures/tree_shake/cyclic_deps/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/cyclic_deps/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "a", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/cyclic_export_all/output.js b/crates/compiler/tests/fixtures/tree_shake/cyclic_export_all/output.js index 333f6e9fe..a22b44713 100644 --- a/crates/compiler/tests/fixtures/tree_shake/cyclic_export_all/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/cyclic_export_all/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dd58.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"569704c1":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_b = farmRequire("f380ea31"); diff --git a/crates/compiler/tests/fixtures/tree_shake/decl/self-ref/output.js b/crates/compiler/tests/fixtures/tree_shake/decl/self-ref/output.js index aff53128c..7dd66c8f4 100644 --- a/crates/compiler/tests/fixtures/tree_shake/decl/self-ref/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/decl/self-ref/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_d7d4.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"3e3af5b6":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = '\\ufe0e\\ufe0f'; diff --git a/crates/compiler/tests/fixtures/tree_shake/deep_dynamic_import/output.js b/crates/compiler/tests/fixtures/tree_shake/deep_dynamic_import/output.js index 1b8d533b4..524c9ae5e 100644 --- a/crates/compiler/tests/fixtures/tree_shake/deep_dynamic_import/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/deep_dynamic_import/output.js @@ -21,71 +21,29 @@ ,}); //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_5d9b.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"7c4a34c2":async function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); exports.default = await farmDynamicRequire("05ee5ec7"); diff --git a/crates/compiler/tests/fixtures/tree_shake/dynamic-import/output.js b/crates/compiler/tests/fixtures/tree_shake/dynamic-import/output.js index fce01295c..c1af2eb05 100644 --- a/crates/compiler/tests/fixtures/tree_shake/dynamic-import/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/dynamic-import/output.js @@ -21,71 +21,29 @@ ,}); //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { farmDynamicRequire("05ee5ec7").then((dep)=>{ console.log(dep); diff --git a/crates/compiler/tests/fixtures/tree_shake/empty_module/output.js b/crates/compiler/tests/fixtures/tree_shake/empty_module/output.js index b498ca445..9a8c9d628 100644 --- a/crates/compiler/tests/fixtures/tree_shake/empty_module/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/empty_module/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_6b9f.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"569704c1":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_b = farmRequire("f380ea31"); diff --git a/crates/compiler/tests/fixtures/tree_shake/empty_specifier_export_all/output.js b/crates/compiler/tests/fixtures/tree_shake/empty_specifier_export_all/output.js index e6d376261..83f0c0fae 100644 --- a/crates/compiler/tests/fixtures/tree_shake/empty_specifier_export_all/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/empty_specifier_export_all/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_b85a.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_dep1 = farmRequire("ef0c4c9d"); diff --git a/crates/compiler/tests/fixtures/tree_shake/empty_specifiers/output.js b/crates/compiler/tests/fixtures/tree_shake/empty_specifiers/output.js index e38a67d83..d38d69f5b 100644 --- a/crates/compiler/tests/fixtures/tree_shake/empty_specifiers/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/empty_specifiers/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_5de5.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"6f462555":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); ""; diff --git a/crates/compiler/tests/fixtures/tree_shake/export_all/output.js b/crates/compiler/tests/fixtures/tree_shake/export_all/output.js index 6919bef9e..54a474ff4 100644 --- a/crates/compiler/tests/fixtures/tree_shake/export_all/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/export_all/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_6b9f.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"569704c1":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_b = farmRequire("f380ea31"); diff --git a/crates/compiler/tests/fixtures/tree_shake/farm_config/output.js b/crates/compiler/tests/fixtures/tree_shake/farm_config/output.js index 15a465793..d0c455424 100644 --- a/crates/compiler/tests/fixtures/tree_shake/farm_config/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/farm_config/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());window['__farm_default_namespace__'].__farm_module_system__.setExternalModules({"module": (window['module']||{}).default && !(window['module']||{}).__esModule ? {...(window['module']||{}),__esModule:true} : ({...window['module']||{}})});(function(_){for(var r in _){_[r].__farm_resource_pot__='index_7f1c.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"052dab48":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); exports.default = { diff --git a/crates/compiler/tests/fixtures/tree_shake/html_entry/basic/output.js b/crates/compiler/tests/fixtures/tree_shake/html_entry/basic/output.js index e8cd033b2..f6b0c818a 100644 --- a/crates/compiler/tests/fixtures/tree_shake/html_entry/basic/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/html_entry/basic/output.js @@ -10,71 +10,29 @@ window['__farm_default_namespace__'] = {}; window['__farm_default_namespace__'] = { __FARM_TARGET_ENV__: 'browser', -}; diff --git a/crates/compiler/tests/fixtures/tree_shake/import-glob-eager/output.js b/crates/compiler/tests/fixtures/tree_shake/import-glob-eager/output.js index fc0ee1806..ee2776eae 100644 --- a/crates/compiler/tests/fixtures/tree_shake/import-glob-eager/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/import-glob-eager/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_de21.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "routes", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/import_meta_hot/output.js b/crates/compiler/tests/fixtures/tree_shake/import_meta_hot/output.js index 7e5591f32..20657e462 100644 --- a/crates/compiler/tests/fixtures/tree_shake/import_meta_hot/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/import_meta_hot/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "a", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/import_namespace/output.js b/crates/compiler/tests/fixtures/tree_shake/import_namespace/output.js index 0047ba52f..47b0349f2 100644 --- a/crates/compiler/tests/fixtures/tree_shake/import_namespace/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/import_namespace/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_7104.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_b = module.w(farmRequire("f380ea31")); diff --git a/crates/compiler/tests/fixtures/tree_shake/issue_1424/output.js b/crates/compiler/tests/fixtures/tree_shake/issue_1424/output.js index 210986c22..4ce6ca698 100644 --- a/crates/compiler/tests/fixtures/tree_shake/issue_1424/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/issue_1424/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "Holder", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/issue_337/output.js b/crates/compiler/tests/fixtures/tree_shake/issue_337/output.js index dc2161827..609d3d926 100644 --- a/crates/compiler/tests/fixtures/tree_shake/issue_337/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/issue_337/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_a93b.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"066a321b":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "default", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/issue_344/output.js b/crates/compiler/tests/fixtures/tree_shake/issue_344/output.js index e3a4ca977..5304c99e6 100644 --- a/crates/compiler/tests/fixtures/tree_shake/issue_344/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/issue_344/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_51e4.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"4ef5be87":function (module, exports, farmRequire, farmDynamicRequire) { module.exports = { program: function() {} diff --git a/crates/compiler/tests/fixtures/tree_shake/issue_625/output.js b/crates/compiler/tests/fixtures/tree_shake/issue_625/output.js index 11329e1ed..ba9108b2f 100644 --- a/crates/compiler/tests/fixtures/tree_shake/issue_625/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/issue_625/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_2c69.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"10c43cb2":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "registerTickMethod", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/non_script/output.js b/crates/compiler/tests/fixtures/tree_shake/non_script/output.js index d9e19948a..5fb1f53b2 100644 --- a/crates/compiler/tests/fixtures/tree_shake/non_script/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/non_script/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_dcdc.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); ""; diff --git a/crates/compiler/tests/fixtures/tree_shake/partial_cyclic_deps/output.js b/crates/compiler/tests/fixtures/tree_shake/partial_cyclic_deps/output.js index 1c1747b4b..11351420a 100644 --- a/crates/compiler/tests/fixtures/tree_shake/partial_cyclic_deps/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/partial_cyclic_deps/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_6d6c.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"25593d80":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_b = module.i(farmRequire("f380ea31")); diff --git a/crates/compiler/tests/fixtures/tree_shake/remove_module/output.js b/crates/compiler/tests/fixtures/tree_shake/remove_module/output.js index 574378aea..5116c7a48 100644 --- a/crates/compiler/tests/fixtures/tree_shake/remove_module/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/remove_module/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ecb7.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"569704c1":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "appendA", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/assign/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/assign/output.js index 785dda96a..c7649868d 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/assign/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/assign/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_6b9f.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"569704c1":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_b = module.i(farmRequire("f380ea31")); diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/axios/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/axios/output.js index 5567165fb..b2cad2d59 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/axios/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/axios/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "AxiosURLSearchParams2", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/class/static/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/class/static/output.js index 4ad572f1e..acdd88dd3 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/class/static/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/class/static/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_e094.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"6d686e48":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "Foo", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/basis/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/basis/output.js index 9348e3196..1cb23d297 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/basis/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/basis/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ecb7.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"569704c1":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var a1 = 11; diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/class/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/class/output.js index fae34232a..b24b05456 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/class/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/class/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "Foo", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/function/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/function/output.js index eb88a5809..97d00e74e 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/function/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/function/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); function foo() {} diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/var_side_effect/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/var_side_effect/output.js index 49f18d6d2..8f0769202 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/var_side_effect/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/var_side_effect/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_5314.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"b5d64806":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); var _f_a = module.i(farmRequire("fa8c9120")); diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/vars/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/vars/output.js index 4cc753f78..77f736ab7 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/vars/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/vars/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "foo1", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/vars_reverse_read/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/vars_reverse_read/output.js index a63518370..ec209cbdc 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/vars_reverse_read/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/decl/vars_reverse_read/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"05ee5ec7":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "a1", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/deep_side_effect/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/deep_side_effect/output.js index ab0f1f741..f807ca266 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/deep_side_effect/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/deep_side_effect/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_d7f6.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"446ec84b":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "result", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/enum/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/enum/output.js index f7756695b..44b438c7d 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/enum/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/enum/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ecb7.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"569704c1":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "resolveValue", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/iife/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/iife/output.js index 89e018f10..4d6f222f8 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/iife/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/iife/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ecb7.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"569704c1":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); (function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/import/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/import/output.js index 093398982..59f8feae7 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/import/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/import/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_6b9f.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"569704c1":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); farmRequire("f380ea31"); diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/new-call/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/new-call/output.js index 26bb6d71b..0deee71ae 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/new-call/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/new-call/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_f1d9.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"4312d062":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "default", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/set/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/set/output.js index 3808c2fb4..0114658ec 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/set/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/set/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ecb7.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"569704c1":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); exports.default = function() { diff --git a/crates/compiler/tests/fixtures/tree_shake/self-executed/side_effect/output.js b/crates/compiler/tests/fixtures/tree_shake/self-executed/side_effect/output.js index 252d2f9ac..8f4ef748e 100644 --- a/crates/compiler/tests/fixtures/tree_shake/self-executed/side_effect/output.js +++ b/crates/compiler/tests/fixtures/tree_shake/self-executed/side_effect/output.js @@ -1,69 +1,27 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){var index_js_cjs = __commonJs((module, exports)=>{ +} +var index_js_cjs = __commonJs((module, exports)=>{ "use strict"; console.log('runtime/index.js'); window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_98b2.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"070fbe2d":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); let foo = 0; diff --git a/crates/compiler/tests/fixtures/tree_shake_development/css/output.js b/crates/compiler/tests/fixtures/tree_shake_development/css/output.js index 4fd1a34e3..10f914bc4 100644 --- a/crates/compiler/tests/fixtures/tree_shake_development/css/output.js +++ b/crates/compiler/tests/fixtures/tree_shake_development/css/output.js @@ -1,65 +1,22 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){// module_id: ../../_internal/runtime/index.js.farm-runtime +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){// module_id: ../../_internal/runtime/index.js.farm-runtime +} var index_js_cjs = __commonJs({ "../../_internal/runtime/index.js.farm-runtime": (module, exports)=>{ "use strict"; @@ -67,6 +24,7 @@ var index_js_cjs = __commonJs({ window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); } }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_4246.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"index.ts":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "c", function() { diff --git a/crates/compiler/tests/fixtures/tree_shake_development/import_meta_hot/output.js b/crates/compiler/tests/fixtures/tree_shake_development/import_meta_hot/output.js index f827ce332..42051f0c4 100644 --- a/crates/compiler/tests/fixtures/tree_shake_development/import_meta_hot/output.js +++ b/crates/compiler/tests/fixtures/tree_shake_development/import_meta_hot/output.js @@ -1,65 +1,22 @@ //index.js: - window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}function _export_star(from, to) { - Object.keys(from).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { - Object.defineProperty(to, k, { - enumerable: true, - get: function() { - return from[k]; - } - }); + window['__farm_default_namespace__'] = {__FARM_TARGET_ENV__: 'browser'};;((function(){// module_id: ../../_internal/runtime/index.js.farm-runtime +function __commonJs(mod) { + var module; + return ()=>{ + if (module) { + return module.exports; } - }); - return from; -}function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { - default: obj - }; - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) return cache.get(obj); - var newObj = { - __proto__: null - }; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; + module = { + exports: {} + }; + if (typeof mod === "function") { + mod(module, module.exports); + } else { + mod[Object.keys(mod)[0]](module, module.exports); } - } - newObj.default = obj; - if (cache) cache.set(obj, newObj); - return newObj; -}function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -}function __commonJs(mod) { - var module; - return () => { - if (module) { - return module.exports; - } - module = { - exports: {}, + return module.exports; }; - if(typeof mod === "function") { - mod(module, module.exports); - }else { - mod[Object.keys(mod)[0]](module, module.exports); - } - return module.exports; - }; -}((function(){// module_id: ../../_internal/runtime/index.js.farm-runtime +} var index_js_cjs = __commonJs({ "../../_internal/runtime/index.js.farm-runtime": (module, exports)=>{ "use strict"; @@ -67,6 +24,7 @@ var index_js_cjs = __commonJs({ window['__farm_default_namespace__'].__farm_module_system__.setPlugins([]); } }); +index_js_cjs(); })());(function(_){for(var r in _){_[r].__farm_resource_pot__='index_ddf1.js';window['__farm_default_namespace__'].__farm_module_system__.register(r,_[r])}})({"dep.ts":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); module.o(exports, "a", function() { diff --git a/crates/compiler/tests/fixtures/update/lazy-compilation/update0.output.js b/crates/compiler/tests/fixtures/update/lazy-compilation/update0.output.js index e2c3479cf..f2ff42168 100644 --- a/crates/compiler/tests/fixtures/update/lazy-compilation/update0.output.js +++ b/crates/compiler/tests/fixtures/update/lazy-compilation/update0.output.js @@ -5,10 +5,9 @@ , "dep.ts.farm_dynamic_import_virtual_module":function (module, exports, farmRequire, farmDynamicRequire) { module._m(exports); - var _f_dep = module.i(farmRequire("dep.ts")); - exports.default = module.f(_f_dep); - var _f_dep1 = farmRequire("dep.ts"); - module._e(exports, _f_dep1); + var _f_dep = module.w(farmRequire("dep.ts")); + var ns = _f_dep; + module.exports = ns; } ,}) {} \ No newline at end of file diff --git a/crates/compiler/tests/runtime.rs b/crates/compiler/tests/runtime.rs index 23442bc3c..2ff46f187 100644 --- a/crates/compiler/tests/runtime.rs +++ b/crates/compiler/tests/runtime.rs @@ -12,9 +12,7 @@ use crate::common::{ #[allow(dead_code)] #[cfg(test)] fn test(file: String, crate_path: String) { - use common::get_config_field; - - use crate::common::try_read_config_from_json; + use common::{format_output_name, get_dir_config_files, try_merge_config_file}; let file_path_buf = PathBuf::from(file.clone()); let create_path_buf = PathBuf::from(crate_path); @@ -23,67 +21,48 @@ fn test(file: String, crate_path: String) { let entry_name = "index".to_string(); - let config_entry = cwd.to_path_buf().join("config.json"); - let runtime_entry = cwd.to_path_buf().join("runtime.ts"); - - let config_from_file = try_read_config_from_json(config_entry); - - let compiler = - create_compiler_with_args(cwd.to_path_buf(), create_path_buf, |mut config, plugins| { - config.mode = Mode::Production; - - if runtime_entry.is_file() { - let runtime_entry = runtime_entry.to_string_lossy().to_string(); - config.runtime.path = runtime_entry; - } - - config.input = HashMap::from_iter(vec![(entry_name.clone(), file)]); + let files = get_dir_config_files(cwd); - config.minify = Box::new(BoolOrObj::Bool(false)); - config.tree_shaking = Box::new(BoolOrObj::Bool(false)); + for (name, config_entry) in files { + let runtime_entry = cwd.to_path_buf().join("runtime.ts"); - config.external = vec![ConfigRegex::new("(^node:.*)"), ConfigRegex::new("^fs$")]; - config.output.target_env = TargetEnv::Node; - // config.output.format = ModuleFormat::CommonJs; + let compiler = create_compiler_with_args( + cwd.to_path_buf(), + create_path_buf.clone(), + |mut config, plugins| { + config.mode = Mode::Production; - // TODO: multiple bundle - config.partial_bundling.enforce_resources = vec![PartialBundlingEnforceResourceConfig { - test: vec![ConfigRegex::new("^bundle2.*")], - name: "bundle2".to_string(), - }]; - - if let Some(config_from_file) = config_from_file { - // TODO: macro - if let Some(mode) = get_config_field(&config_from_file, &["mode"]) { - config.mode = mode; + if runtime_entry.is_file() { + let runtime_entry = runtime_entry.to_string_lossy().to_string(); + config.runtime.path = runtime_entry; } - if let Some(format) = get_config_field(&config_from_file, &["output", "format"]) { - config.output.format = format; - } + config.input = HashMap::from_iter(vec![(entry_name.clone(), file.clone())]); - if let Some(target_env) = get_config_field(&config_from_file, &["output", "targetEnv"]) { - config.output.target_env = target_env; - } + config.minify = Box::new(BoolOrObj::Bool(false)); + config.tree_shaking = Box::new(BoolOrObj::Bool(false)); - if let Some(lazy_compilation) = get_config_field(&config_from_file, &["lazyCompilation"]) { - config.lazy_compilation = lazy_compilation; - } - } + config.external = vec![ConfigRegex::new("(^node:.*)"), ConfigRegex::new("^fs$")]; + config.output.target_env = TargetEnv::Node; + + config = try_merge_config_file(config, config_entry); - (config, plugins) - }); + (config, plugins) + }, + ); - compiler.compile().unwrap(); + compiler.compile().unwrap(); - assert_compiler_result_with_config( - &compiler, - AssertCompilerResultConfig { - entry_name: Some(entry_name), - ignore_emitted_field: false, - ..Default::default() - }, - ); + assert_compiler_result_with_config( + &compiler, + AssertCompilerResultConfig { + entry_name: Some(entry_name.clone()), + output_file: Some(format_output_name(name)), + ignore_emitted_field: false, + ..Default::default() + }, + ); + } } farmfe_testing::testing! {"tests/fixtures/runtime/bundle/**/index.ts", test} diff --git a/crates/compiler/tests/script.rs b/crates/compiler/tests/script.rs index cdfc0ad95..4016331e9 100644 --- a/crates/compiler/tests/script.rs +++ b/crates/compiler/tests/script.rs @@ -1,8 +1,8 @@ use std::{collections::HashMap, path::PathBuf}; use common::{ - assert_compiler_result_with_config, create_compiler_with_args, get_config_field, - try_read_config_from_json, AssertCompilerResultConfig, + assert_compiler_result_with_config, create_compiler_with_args, + try_merge_config_file, AssertCompilerResultConfig, }; mod common; @@ -17,23 +17,11 @@ fn script_test(file: String, crate_path: String) { let config_entry = cwd.to_path_buf().join("config.json"); - let config_from_file = try_read_config_from_json(config_entry); - let compiler = create_compiler_with_args(cwd.to_path_buf(), create_path_buf, |mut config, plugins| { - config.input = HashMap::from_iter(vec![(entry_name.clone(), file)]); - - if let Some(config_form_file) = config_from_file { - if let Some(str) = get_config_field(&config_form_file, &["output", "publicPath"]) { - config.output.public_path = str; - } - - if let Some(enable) = - get_config_field(&config_form_file, &["script", "nativeTopLevelAwait"]) - { - config.script.native_top_level_await = enable; - } - } + config.input = HashMap::from_iter(vec![(entry_name.clone(), file.clone())]); + + config = try_merge_config_file(config, config_entry); (config, plugins) }); diff --git a/crates/core/src/module/mod.rs b/crates/core/src/module/mod.rs index 0f8272514..431740d29 100644 --- a/crates/core/src/module/mod.rs +++ b/crates/core/src/module/mod.rs @@ -402,6 +402,18 @@ impl ScriptModuleMetaData { pub fn set_comments(&mut self, comments: CommentsMetaData) { self.comments = comments; } + + pub fn is_cjs(&self) -> bool { + matches!(self.module_system, ModuleSystem::CommonJs) + } + + pub fn is_esm(&self) -> bool { + matches!(self.module_system, ModuleSystem::EsModule) + } + + pub fn is_hybrid(&self) -> bool { + matches!(self.module_system, ModuleSystem::Hybrid) + } } #[cache_item] diff --git a/crates/core/src/resource/resource_pot.rs b/crates/core/src/resource/resource_pot.rs index abc101a6b..1f5ae40e0 100644 --- a/crates/core/src/resource/resource_pot.rs +++ b/crates/core/src/resource/resource_pot.rs @@ -82,6 +82,10 @@ impl ResourcePot { std::mem::take(&mut self.meta) } + pub fn has_module(&self, module_id: &ModuleId) -> bool { + self.modules.contains(module_id) + } + pub fn remove_module(&mut self, module_id: &ModuleId) { self.modules.remove(module_id); } diff --git a/crates/plugin_bundle/src/lib.rs b/crates/plugin_bundle/src/lib.rs index dccc11ffe..a8586a87b 100644 --- a/crates/plugin_bundle/src/lib.rs +++ b/crates/plugin_bundle/src/lib.rs @@ -1,27 +1,43 @@ #![feature(box_patterns)] -use std::{collections::HashMap, sync::Arc}; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; use farmfe_core::{ + config::{ + config_regex::ConfigRegex, partial_bundling::PartialBundlingEnforceResourceConfig, Config, + }, + context::CompilationContext, enhanced_magic_string::bundle::Bundle, + module::ModuleType, parking_lot::Mutex, - plugin::Plugin, - resource::resource_pot::{ResourcePotMetaData, ResourcePotType}, + plugin::{ + Plugin, PluginAnalyzeDepsHookResultEntry, PluginFinalizeResourcesHookParams, + PluginGenerateResourcesHookResult, PluginHookContext, PluginLoadHookParam, + PluginLoadHookResult, PluginResolveHookParam, PluginResolveHookResult, ResolveKind, + }, + regex::Regex, + relative_path::RelativePath, + resource::{ + resource_pot::{ResourcePot, ResourcePotMetaData, ResourcePotType}, + ResourceType, + }, +}; +use farmfe_toolkit::constant::RUNTIME_SUFFIX; +use resource_pot_to_bundle::{ + BundleGroup, ShareBundleOptions, SharedBundle, FARM_BUNDLE_POLYFILL_SLOT, + FARM_BUNDLE_REFERENCE_SLOT_PREFIX, }; -use resource_pot_to_bundle::{Polyfill, SharedBundle}; pub mod resource_pot_to_bundle; -const MODULE_NEED_POLYFILLS: [Polyfill; 3] = [ - Polyfill::Wildcard, - Polyfill::InteropRequireDefault, - Polyfill::ExportStar, -]; - #[derive(Default)] pub struct FarmPluginBundle { runtime_code: Mutex>, bundle_map: Mutex>, + resource_pot_id_resource_map: Mutex>, } impl FarmPluginBundle { @@ -30,15 +46,94 @@ impl FarmPluginBundle { } } +impl FarmPluginBundle { + fn should_bundle(config: &Config) -> bool { + config.output.target_env.is_library() + } +} + impl Plugin for FarmPluginBundle { fn name(&self) -> &str { "farm-plugin-bundle" } + fn config(&self, config: &mut Config) -> farmfe_core::error::Result> { + if Self::should_bundle(&config) { + // push it last + config + .partial_bundling + .enforce_resources + .push(PartialBundlingEnforceResourceConfig { + name: "farm_runtime".to_string(), + test: vec![ConfigRegex::new(FARM_BUNDLE_POLYFILL_SLOT)], + }); + } + + Ok(None) + } + + fn resolve( + &self, + param: &PluginResolveHookParam, + _context: &Arc, + _hook_context: &PluginHookContext, + ) -> farmfe_core::error::Result> { + if param.source.starts_with(FARM_BUNDLE_POLYFILL_SLOT) { + return Ok(Some(PluginResolveHookResult { + resolved_path: FARM_BUNDLE_POLYFILL_SLOT.to_string(), + external: false, + side_effects: true, + query: vec![], + meta: Default::default(), + })); + } + + Ok(None) + } + + fn load( + &self, + param: &PluginLoadHookParam, + _context: &Arc, + _hook_context: &PluginHookContext, + ) -> farmfe_core::error::Result> { + if param.resolved_path.starts_with(FARM_BUNDLE_POLYFILL_SLOT) { + return Ok(Some(PluginLoadHookResult { + // TODO: disable tree-shaking it + content: format!(r#"export {{}}"#), + module_type: ModuleType::Js, + source_map: None, + })); + } + + Ok(None) + } + + fn analyze_deps( + &self, + param: &mut farmfe_core::plugin::PluginAnalyzeDepsHookParam, + context: &Arc, + ) -> farmfe_core::error::Result> { + let module_graph = context.module_graph.read(); + + if Self::should_bundle(&context.config) + && module_graph.entries.contains_key(¶m.module.id) + && param.module.module_type.is_script() + && !param.module.id.to_string().ends_with(RUNTIME_SUFFIX) + { + param.deps.push(PluginAnalyzeDepsHookResultEntry { + source: FARM_BUNDLE_POLYFILL_SLOT.to_string(), + kind: ResolveKind::Import, + }); + } + + Ok(None) + } + fn process_resource_pots( &self, - resource_pots: &mut Vec<&mut farmfe_core::resource::resource_pot::ResourcePot>, - context: &std::sync::Arc, + resource_pots: &mut Vec<&mut ResourcePot>, + context: &Arc, ) -> farmfe_core::error::Result> { if !self.runtime_code.lock().is_empty() { return Ok(None); @@ -53,29 +148,17 @@ impl Plugin for FarmPluginBundle { context.config.output.target_env.is_library() || matches!(item.resource_pot_type, ResourcePotType::Runtime) }) - .map(|item| &**item) + .map(|item| BundleGroup::from(&**item)) .collect::>(); - let mut shared_bundle = SharedBundle::new(r, &module_graph, context)?; - - let inject_resource_pot_id = resource_pots - .iter() - .find(|item| { - (context.config.output.target_env.is_library() && item.entry_module.is_some()) - || matches!(item.resource_pot_type, ResourcePotType::Runtime) - }) - .map(|i| i.id.clone()); - - if let Some(resource_pot_id) = inject_resource_pot_id { - let polyfill = &mut shared_bundle - .bundle_map - .get_mut(&resource_pot_id) - .unwrap() - .polyfill; - - MODULE_NEED_POLYFILLS - .iter() - .for_each(|item| polyfill.add(item.clone())); - } + let mut shared_bundle = SharedBundle::new( + r, + &module_graph, + context, + Some(ShareBundleOptions { + format: context.config.output.format.clone(), + ..Default::default() + }), + )?; shared_bundle.render()?; @@ -83,7 +166,7 @@ impl Plugin for FarmPluginBundle { for resource_pot in resource_pots.iter() { if matches!(resource_pot.resource_pot_type, ResourcePotType::Runtime) || (context.config.output.target_env.is_library() - && resource_pot.resource_pot_type == ResourcePotType::Js) + && matches!(resource_pot.resource_pot_type, ResourcePotType::Js)) { let resource_pot_id = resource_pot.id.clone(); @@ -110,11 +193,10 @@ impl Plugin for FarmPluginBundle { fn render_resource_pot_modules( &self, - resource_pot: &farmfe_core::resource::resource_pot::ResourcePot, - _context: &Arc, - _hook_context: &farmfe_core::plugin::PluginHookContext, - ) -> farmfe_core::error::Result> - { + resource_pot: &ResourcePot, + _context: &Arc, + _hook_context: &PluginHookContext, + ) -> farmfe_core::error::Result> { if matches!(resource_pot.resource_pot_type, ResourcePotType::Runtime) { return Ok(Some(ResourcePotMetaData { rendered_modules: HashMap::new(), @@ -134,4 +216,109 @@ impl Plugin for FarmPluginBundle { Ok(None) } + + fn process_generated_resources( + &self, + resources: &mut PluginGenerateResourcesHookResult, + _context: &Arc, + ) -> farmfe_core::error::Result> { + if let Some(resource_pot_id) = resources.resource.info.as_ref().map(|i| i.id.clone()) { + self + .resource_pot_id_resource_map + .lock() + .insert(resource_pot_id, resources.resource.name.clone()); + } + + Ok(None) + } + + fn finalize_resources( + &self, + param: &mut PluginFinalizeResourcesHookParams, + context: &Arc, + ) -> farmfe_core::error::Result> { + if !context.config.output.target_env.is_library() { + return Ok(None); + } + + let mut map = HashMap::new(); + + for (name, resource) in param.resources_map.iter() { + if let Some(ref info) = resource.info { + map.insert(info.id.clone(), name.clone()); + } + } + + for (name, resource) in param.resources_map.iter_mut() { + if !matches!( + resource.resource_type, + ResourceType::Js | ResourceType::Runtime + ) { + continue; + } + let before = std::time::Instant::now(); + + let r = format!("/{}", name); + let relative_path = RelativePath::new(&r); + + let mut content = String::from_utf8_lossy(&resource.bytes).to_string(); + + let reg = + Regex::new(format!("{}\\(\\(.+?\\)\\)", FARM_BUNDLE_REFERENCE_SLOT_PREFIX).as_str()) + .unwrap(); + + let items = reg + .captures_iter(&content) + .into_iter() + .flat_map(|i| { + i.iter() + .filter_map(|i| i) + .map(|i| i.as_str().to_string()) + .collect::>() + }) + .map(|i| i.as_str().to_string()) + .collect::>(); + + if items.is_empty() { + continue; + } + + for item in items { + let resource_pot_id = item + .trim_start_matches(FARM_BUNDLE_REFERENCE_SLOT_PREFIX) + .trim_start_matches("((") + .trim_end_matches("))"); + let resource_name = map + .get(resource_pot_id) + .expect("cannot find bundle reference, please ensure your resource cornet"); + + let r1 = format!("/{}", resource_name); + + println!("resource pot id {} to {} ", resource_pot_id, r1); + + let relative_resource_path = RelativePath::new(&r1); + content = content.replace( + &item, + &format!( + "./{}", + relative_path + .parent() + .map(|i| i.relative(relative_resource_path).to_string()) + .unwrap() + .trim_start_matches("/") + ), + ); + } + + resource.bytes = content.into_bytes(); + + println!( + "resource_name {} time: {}", + name, + before.elapsed().as_secs_f32() + ); + } + + Ok(None) + } } diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_analyzer.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_analyzer.rs index 66b3246fc..b3afe0219 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_analyzer.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_analyzer.rs @@ -15,8 +15,8 @@ use farmfe_core::{ }, error::{CompilationError, Result}, farm_profile_function, farm_profile_scope, - module::{module_graph::ModuleGraph, ModuleId, ModuleSystem, ModuleType}, - resource::resource_pot::{ResourcePot, ResourcePotType}, + module::{module_graph::ModuleGraph, ModuleId, ModuleSystem}, + resource::resource_pot::{ResourcePotId, ResourcePotType}, swc_common::{comments::SingleThreadedComments, util::take::Take}, }; use farmfe_toolkit::{ @@ -27,19 +27,24 @@ use farmfe_toolkit::{ }; use crate::resource_pot_to_bundle::{ - bundle::bundle_external::ReferenceKind, + bundle::bundle_reference::{CommonJsImportMap, ReferenceBuilder, ReferenceKind}, common::OptionToResult, modules_analyzer::module_analyzer::{ ExportSpecifierInfo, ImportSpecifierInfo, StmtAction, Variable, }, polyfill::SimplePolyfill, - targets::generate::{ - generate_bundle_import_by_bundle_reference, generate_export_by_reference_export, + targets::{ + cjs::CjsModuleAnalyzer, + generate::{generate_bundle_import_by_bundle_reference, generate_export_by_reference_export}, }, uniq_name::{BundleVariable, FindModuleExportResult}, + BundleGroup, ShareBundleContext, FARM_BUNDLE_POLYFILL_SLOT, }; -use super::{BundleReference, ModuleAnalyzerManager}; +use super::{ + bundle_reference::{BundleReference, BundleReferenceManager}, + ModuleAnalyzerManager, +}; #[derive(Debug)] #[allow(dead_code)] @@ -50,47 +55,46 @@ enum NamespaceExportType { } pub struct BundleAnalyzer<'a> { - pub resource_pot: &'a ResourcePot, + pub group: BundleGroup<'a>, pub ordered_modules: Vec<&'a ModuleId>, pub bundle_variable: Rc>, module_graph: &'a ModuleGraph, context: Arc, - pub bundle_reference: BundleReference, pub polyfill: SimplePolyfill, } impl<'a> BundleAnalyzer<'a> { pub fn new( - resource_pot: &'a ResourcePot, + resource_pot: BundleGroup<'a>, module_graph: &'a ModuleGraph, context: &Arc, bundle_variable: Rc>, ) -> Self { Self { bundle_variable, - resource_pot, + group: resource_pot, ordered_modules: vec![], module_graph, context: context.clone(), - bundle_reference: BundleReference::new(), + // bundle_reference: BundleReference::new(), // bundle level polyfill polyfill: SimplePolyfill::default(), } } - pub fn set_namespace(&mut self, resource_pot_id: &str) { + pub fn set_namespace(&mut self, group_id: &str) { self .bundle_variable .borrow_mut() - .set_namespace(resource_pot_id.to_string()); + .set_namespace(group_id.to_string()); } // step: 1 toposort fetch modules pub fn build_module_order(&mut self, order_index_map: &HashMap) { farm_profile_function!(); - let mut resource_pot_modules = self.resource_pot.modules(); + let mut resource_pot_modules = self.group.modules.clone(); resource_pot_modules.sort_by(|a, b| { if !order_index_map.contains_key(a) || !order_index_map.contains_key(b) { @@ -106,6 +110,7 @@ impl<'a> BundleAnalyzer<'a> { // 3-1. uniq declare variable name pub fn module_conflict_name(&mut self, module_analyzer_manager: &mut ModuleAnalyzerManager) { farm_profile_function!(""); + for module_id in &self.ordered_modules { farm_profile_scope!(format!( "bundle module conflict name: {}", @@ -116,14 +121,15 @@ impl<'a> BundleAnalyzer<'a> { let mut variables = module_analyzer.variables().into_iter().collect::>(); variables.sort(); + let mut bundle_variable = self.bundle_variable.borrow_mut(); for index in variables { // used_name is global variable, we need rename same used_name in cjs - if is_commonjs && !(self.bundle_variable.borrow().is_in_used_name(index)) { + if is_commonjs && !(bundle_variable.is_in_used_name(index)) { continue; } - self.bundle_variable.borrow_mut().set_var_uniq_rename(index); + bundle_variable.set_var_uniq_rename(index); } }; } @@ -203,674 +209,846 @@ impl<'a> BundleAnalyzer<'a> { } // 3-3 find module relation and link local variable - // TODO: refactor bundle_reference logic + // TODO: + // 1. refactor bundle_reference import/export logic + // 2. split BundleReference collection and reuse it pub fn link_module_relation( &mut self, + module_id: &ModuleId, module_analyzer_manager: &mut ModuleAnalyzerManager, + bundle_reference_manager: &mut BundleReferenceManager, + options: &ShareBundleContext, ) -> Result<()> { - farm_profile_function!(""); + let is_format_to_commonjs = matches!(options.options.format, ModuleFormat::CommonJs); - let is_format_to_commonjs = self.context.config.output.format == ModuleFormat::CommonJs; + farm_profile_scope!(format!( + "bundle analyzer module relation: {}", + module_id.to_string() + )); - for module_id in &self.ordered_modules { - farm_profile_scope!(format!( - "bundle analyzer module relation: {}", - module_id.to_string() - )); + if let Some(module_analyzer) = module_analyzer_manager.module_analyzer(module_id) { + let group_id = module_analyzer.bundle_group_id.clone(); + let module_system = module_analyzer.module_system.clone(); + let is_entry = module_analyzer.entry; - if let Some(module_analyzer) = module_analyzer_manager.module_analyzer(module_id) { - let resource_pot_id = module_analyzer.resource_pot_id.clone(); - let module_system = module_analyzer.module_system.clone(); - let is_reference_by_another = module_analyzer.entry || { + let is_reference_by_another = is_entry + || module_analyzer.is_reference_by_another(|| { let importer = self.module_graph.dependents_ids(module_id); - importer.iter().any(|importer| { - module_analyzer_manager - .module_analyzer(importer) - .is_some_and(|i| i.resource_pot_id != resource_pot_id) + if module_analyzer_manager.contain(importer) { + module_analyzer_manager + .group_id(importer) + .is_some_and(|i| i != &group_id) + } else { + // partial ShareBundle should reexport raw + true + } }) - }; - let mut is_contain_export = false; + }); - for statement in &module_analyzer.statements { - if let Some(import) = &statement.import { - for specify in &import.specifiers { - match specify { - // import * as fs from "person" - ImportSpecifierInfo::Namespace(ns) => { - let target = self.bundle_variable.borrow().find_ident_by_index( - *ns, - &import.source, - module_analyzer_manager, - resource_pot_id.clone(), - false, - true, - ); + let bundle_reference1 = bundle_reference_manager.reference_mut(&group_id); + let mut bundle_reference_1 = bundle_reference1.borrow_mut(); + let bundle_reference1 = bundle_reference_1.fetch_mut(module_id, module_analyzer_manager); - if let Some(target) = target { - let is_common_js = target.is_common_js(); + // reexport as namespace + if module_analyzer_manager + .namespace_modules + .contains(module_id) + && !module_analyzer_manager.is_commonjs(module_id) + { + let ns = module_analyzer_manager + .module_global_uniq_name + .namespace_name_result(module_id)?; - match target { - FindModuleExportResult::Local(_, target_module_id, _) => { - if let Some(mut uniq_ns) = module_analyzer_manager - .module_global_uniq_name - .namespace_name(&target_module_id) - { - if is_common_js { - uniq_ns = self.bundle_reference.add_declare_commonjs_import( - &ImportSpecifierInfo::Namespace(uniq_ns), - target_module_id.into(), - &self.bundle_variable.borrow(), - )?; - } + bundle_reference1 + .add_local_export(&ExportSpecifierInfo::Namespace(ns), module_system.clone()); + } - self - .bundle_variable - .borrow_mut() - .set_rename_from_other_render_name(*ns, uniq_ns); - } - } + let mut is_contain_export = false; - FindModuleExportResult::External(_, _) => { - self.bundle_reference.add_import( - specify, - import.source.clone().into(), - &self.bundle_variable.borrow(), - )?; + for statement in &module_analyzer.statements { + if let Some(import) = &statement.import { + if import.specifiers.is_empty() { + if module_analyzer_manager.is_same_bundle(module_id, &import.source) { + continue; + } - let rename = module_analyzer_manager - .module_global_uniq_name - .namespace_name(&import.source) - .to_result(format!( - "not found module {:?} namespace named", - import.source - ))?; + let reference_kind = ReferenceKind::Module(import.source.clone()); + + // import 'module'; + if module_analyzer_manager.is_commonjs(&import.source) + && !module_analyzer_manager.is_external(module_id) + { + if let Some(name) = module_analyzer_manager + .module_global_uniq_name + .commonjs_name(&import.source) + { + bundle_reference1.add_import( + &ImportSpecifierInfo::Named { + local: name, + imported: None, + }, + import.source.clone().into(), + &self.bundle_variable.borrow_mut(), + )?; + } + } else { + bundle_reference1.add_execute_module(reference_kind); + } - self - .bundle_variable - .borrow_mut() - .set_rename_from_other_render_name(*ns, rename); - } + continue; + } - // TODO: bundle - FindModuleExportResult::Bundle(_, bundle_name, _) => { - let import_rename = self.bundle_reference.add_import( - specify, - bundle_name.into(), - &self.bundle_variable.borrow(), - )?; + for specify in &import.specifiers { + match specify { + // import * as person from "person" + ImportSpecifierInfo::Namespace(ns) => { + let target = self.bundle_variable.borrow().find_ident_by_index( + *ns, + &import.source, + module_analyzer_manager, + group_id.clone(), + false, + true, + ); + + if let Some(target) = target { + let is_common_js = target.is_common_js(); + + match target { + FindModuleExportResult::Local(_, target_module_id, _) => { + if let Some(mut local) = module_analyzer_manager + .module_global_uniq_name + .namespace_name(&target_module_id) + { + if is_common_js { + bundle_reference1.add_declare_commonjs_import( + &ImportSpecifierInfo::Namespace(local), + target_module_id.into(), + &self.bundle_variable.borrow(), + )?; + } self .bundle_variable .borrow_mut() - .set_rename_from_other_render_name(*ns, import_rename); + .set_rename_from_other_render_name(*ns, local); } } - } - } - // import { name, age } from "person"; - ImportSpecifierInfo::Named { local, imported } => { - let imported = imported.unwrap_or(*local); - let target = self.bundle_variable.borrow().find_ident_by_index( - imported, - &import.source, - module_analyzer_manager, - resource_pot_id.clone(), - self.bundle_variable.borrow().name(imported) == "default", - false, - ); + FindModuleExportResult::External(_, _, _) => { + bundle_reference1.add_import( + specify, + import.source.clone().into(), + &self.bundle_variable.borrow(), + )?; - if let Some(target) = target { - let is_common_js = target.is_common_js(); - match target { - FindModuleExportResult::Local(mut index, target_source, _) => { - if is_common_js { - index = self.bundle_reference.add_declare_commonjs_import( - specify, - target_source.clone().into(), - &self.bundle_variable.borrow(), - )?; - } + let rename = module_analyzer_manager + .module_global_uniq_name + .namespace_name(&import.source) + .to_result(format!( + "not found module {:?} namespace named", + import.source + ))?; - self - .bundle_variable - .borrow_mut() - .set_uniq_name_both(index, *local); + self + .bundle_variable + .borrow_mut() + .set_rename_from_other_name(*ns, rename); + } + + // TODO: bundle + FindModuleExportResult::Bundle(_, target_id, _, _) => { + let namespace = module_analyzer_manager + .module_global_uniq_name + .namespace_name_result(&target_id)?; + + let mut bundle_variable = self.bundle_variable.borrow_mut(); + bundle_variable.set_var_root(*ns, namespace); + + let is_same_bundle = bundle_variable.is_same_bundle_by_root( + *ns, + &group_id, + module_analyzer_manager, + ); + + let mut import_rename = namespace; + + if !is_same_bundle { + // let other_bundle_reference = + // bundle_reference_manager.reference1_mut(&target_id); + let other_bundle_reference = bundle_reference_manager + .reference_mut_by_module(&target_id, &module_analyzer_manager); + let mut other_bundle_reference = other_bundle_reference.borrow_mut(); + let other_bundle_reference = + other_bundle_reference.fetch_mut(&target_id, module_analyzer_manager); + + other_bundle_reference.add_local_export( + &ExportSpecifierInfo::Named((namespace).into()), + module_system.clone(), + ); + + import_rename = bundle_reference1.add_import( + &ImportSpecifierInfo::Named { + local: namespace, + imported: None, + }, + target_id.into(), + &bundle_variable, + )?; } - FindModuleExportResult::External(_, target) => { - let rename = self.bundle_reference.add_import( + bundle_variable.set_rename_from_other_render_name(*ns, import_rename); + } + } + } + } + + // import { name, age } from "person"; + ImportSpecifierInfo::Named { local, imported } => { + let imported = imported.unwrap_or(*local); + + let target = self.bundle_variable.borrow().find_ident_by_index( + imported, + &import.source, + module_analyzer_manager, + group_id.clone(), + self.bundle_variable.borrow().name(imported) == "default", + false, + ); + + if let Some(target) = target { + let is_common_js = target.is_common_js(); + match target { + FindModuleExportResult::Local(mut index, target_source, _) => { + if is_common_js { + index = bundle_reference1.add_declare_commonjs_import( specify, - target.into(), + target_source.clone().into(), &self.bundle_variable.borrow(), )?; - - self - .bundle_variable - .borrow_mut() - .set_uniq_name_both(rename, *local); } - FindModuleExportResult::Bundle(_, target, _) => { - let rename = self.bundle_reference.add_import( + self + .bundle_variable + .borrow_mut() + .set_uniq_name_both(index, *local); + } + + FindModuleExportResult::External(index, target, _) => { + let mut rename = index; + + // not reexport external + if target == import.source { + rename = bundle_reference1.add_import( specify, target.into(), &self.bundle_variable.borrow(), )?; - - self - .bundle_variable - .borrow_mut() - .set_uniq_name_both(rename, *local); } + + self + .bundle_variable + .borrow_mut() + .set_uniq_name_both(rename, *local); } - } - } - // import fs from "person" - ImportSpecifierInfo::Default(default) => { - let target = self.bundle_variable.borrow().find_ident_by_index( - *default, - &import.source, - module_analyzer_manager, - resource_pot_id.clone(), - true, - false, - ); + FindModuleExportResult::Bundle(index, target_id, _, _) => { + let mut bundle_variable = self.bundle_variable.borrow_mut(); + let is_same_bundle = if is_common_js { + module_analyzer_manager.is_same_bundle(&module_id, &target_id) + } else { + bundle_variable.set_var_root(*local, index); + bundle_variable.is_same_bundle_by_root( + *local, + &group_id, + module_analyzer_manager, + ) + }; + let mut rename = index; - if let Some(target) = target { - let is_common_js = target.is_common_js(); - match target { - FindModuleExportResult::Local(mut index, target_source, _) => { + if !is_same_bundle { if is_common_js { - index = self.bundle_reference.add_declare_commonjs_import( - specify, - target_source.into(), - &self.bundle_variable.borrow(), + bundle_reference1.add_import( + &ImportSpecifierInfo::Named { + local: module_analyzer_manager + .module_global_uniq_name + .commonjs_name_result(&target_id)?, + imported: None, + }, + target_id.clone().into(), + &bundle_variable, + )?; + } else { + rename = bundle_reference1.add_import( + &ImportSpecifierInfo::Named { + local: index, + imported: None, + }, + bundle_variable + .module_id_by_var_index(index) + .unwrap() + .into(), + &bundle_variable, )?; } - - self - .bundle_variable - .borrow_mut() - .set_uniq_name_both(index, *default); } - - FindModuleExportResult::External(_, target) => { - let rename = self.bundle_reference.add_import( - specify, - target.into(), - &self.bundle_variable.borrow(), + if is_common_js { + bundle_reference1.add_declare_commonjs_import( + &ImportSpecifierInfo::Named { + local: *local, + imported: None, + }, + target_id.clone().into(), + &bundle_variable, )?; - - self - .bundle_variable - .borrow_mut() - .set_uniq_name_both(rename, *default); } + bundle_variable.set_uniq_name_for_cross_bundle( + rename, + *local, + &target_id, + &module_id, + module_analyzer_manager, + ); + } + } + } + } - FindModuleExportResult::Bundle(_, target, _) => { - let rename = self.bundle_reference.add_import( + // import person from "person" + ImportSpecifierInfo::Default(default) => { + let target = self.bundle_variable.borrow().find_ident_by_index( + *default, + &import.source, + module_analyzer_manager, + group_id.clone(), + true, + false, + ); + + if let Some(target) = target { + let is_common_js = target.is_common_js(); + match target { + FindModuleExportResult::Local(mut index, target_source, _) => { + let mut bundle_variable = self.bundle_variable.borrow_mut(); + + if is_common_js { + index = bundle_reference1.add_declare_commonjs_import( specify, - target.into(), - &self.bundle_variable.borrow(), + target_source.into(), + &bundle_variable, )?; - - self - .bundle_variable - .borrow_mut() - .set_uniq_name_both(rename, *default); } + bundle_variable.set_uniq_name_both(index, *default); } - }; - } - } - } - } - - if let Some(export) = &statement.export { - is_contain_export = true; - if module_analyzer_manager.is_commonjs(module_id) && !is_reference_by_another { - continue; - } - for specify in &export.specifiers { - match specify { - // export * from 'person' - ExportSpecifierInfo::All(_) => { - let Some(source) = &export.source else { - unreachable!("export all should have source") - }; + FindModuleExportResult::External(_, target, _) => { + let rename = bundle_reference1.add_import( + specify, + target.into(), + &self.bundle_variable.borrow(), + )?; - // entry | other bundle - if is_reference_by_another { - let reexport_commonjs = - |module_id: &ModuleId, bundle_reference: &mut BundleReference| { - bundle_reference.change_to_hybrid_dynamic(module_id.clone().into()); + self + .bundle_variable + .borrow_mut() + .set_uniq_name_both(rename, *default); + } - bundle_reference.add_declare_commonjs_import( - &ImportSpecifierInfo::Namespace( - module_analyzer_manager - .module_global_uniq_name - .namespace_name(module_id) - .unwrap(), - ), - module_id.clone().into(), - &self.bundle_variable.borrow(), - )?; + FindModuleExportResult::Bundle(target_default_index, target_id, _, _) => { + let mut bundle_variable = self.bundle_variable.borrow_mut(); + let mut name = target_default_index; - bundle_reference.add_reference_export( - &ExportSpecifierInfo::All(None), - module_id.clone().into(), - ModuleSystem::CommonJs, - ); + if is_common_js { + name = module_analyzer_manager + .module_global_uniq_name + .commonjs_name_result(&target_id)?; + } else if bundle_variable.name(target_default_index) == "default" { + name = module_analyzer_manager + .module_global_uniq_name + .default_name_result(&target_id)?; + } - Result::<()>::Ok(()) + let is_same_bundle = if is_common_js { + module_analyzer_manager.is_same_bundle(module_id, &target_id) + } else { + bundle_variable.set_var_root(*default, name); + bundle_variable.is_same_bundle_by_root( + *default, + &group_id, + module_analyzer_manager, + ) }; - if module_analyzer_manager.is_external(source) { - // export * from "node:fs" - // => commonjs - // const node_fs = require("node:fs") - // _export_star(node_fs, module.exports); + if !is_same_bundle { + if is_common_js { + bundle_reference1.add_import( + &ImportSpecifierInfo::Named { + local: module_analyzer_manager + .module_global_uniq_name + .commonjs_name_result(&target_id)? + .into(), + imported: None, + }, + target_id.clone().into(), + &bundle_variable, + )?; + } else { + bundle_reference1.add_import( + &ImportSpecifierInfo::Default(*default), + target_id.clone().into(), + &bundle_variable, + )?; + } + }; - if is_format_to_commonjs { - self.bundle_reference.add_import( - &ImportSpecifierInfo::Namespace( - module_analyzer_manager - .module_global_uniq_name - .namespace_name(source) - .unwrap(), - ), - source.clone().into(), - &self.bundle_variable.borrow(), + if is_common_js { + bundle_reference1.add_declare_commonjs_import( + &ImportSpecifierInfo::Default(*default), + target_id.clone().into(), + &bundle_variable, )?; + bundle_variable.set_var_uniq_rename(*default); + } else { + bundle_variable.set_uniq_name_for_cross_bundle( + name, + *default, + &target_id, + module_id, + module_analyzer_manager, + ); } + } + } + }; + } + } + } + } - self.bundle_reference.add_reference_export( - &ExportSpecifierInfo::All(None), - source.clone().into(), - module_system.clone(), - ); - } else if module_analyzer_manager.is_commonjs(source) - && (!module_analyzer.entry - || matches!(module_analyzer.module_type, ModuleType::Runtime)) - { - reexport_commonjs(source, &mut self.bundle_reference)?; - } else { - let export_names = &*module_analyzer_manager.get_export_names(source); - let export_type = export_names.export_type.merge(module_system.clone()); - - let is_hybrid_dynamic = matches!(export_type, ModuleSystem::Hybrid); - let is_commonjs = module_analyzer_manager.is_commonjs(source); - - { - for (from, export_as) in &export_names.export.named { - self.bundle_reference.add_local_export( - &ExportSpecifierInfo::Named((*from, Some(*export_as)).into()), - export_type.clone(), - ); + if let Some(export) = &statement.export { + is_contain_export = true; + if module_analyzer_manager.is_commonjs(module_id) && !is_reference_by_another { + continue; + } - if is_commonjs { - let is_default_key = - self.bundle_variable.borrow().is_default_key(*from); + if module_analyzer.is_dynamic && is_reference_by_another { + if let Some(x) = module_analyzer_manager + .module_global_uniq_name + .namespace_name(module_id) + { + bundle_reference1 + .add_local_export(&ExportSpecifierInfo::Named(x.into()), module_system.clone()); + } + } - let imported = if is_default_key { - module_analyzer_manager - .module_global_uniq_name - .default_name_result(module_id)? - } else { - *from - }; - - self.bundle_reference.add_declare_commonjs_import( - &ImportSpecifierInfo::Named { - local: *export_as, - imported: Some(imported), - }, - export.source.clone().unwrap().into(), - &self.bundle_variable.borrow(), - )?; - } - } + for specify in &export.specifiers { + match specify { + // export * from 'person' + ExportSpecifierInfo::All(_) => { + let Some(source) = &export.source else { + unreachable!("export all should have source") + }; + + bundle_reference1.add_reexport_all(ReferenceBuilder { + is_reference_by_another_bundle: is_reference_by_another, + module_analyzer_manager, + module_analyzer, + bundle_variable: &mut self.bundle_variable.borrow_mut(), + source, + module_system: module_system.clone(), + config: &options, + module_id: &module_id, + })?; + } - if let Some(item) = &export_names.export.default { - let is_default_key = self.bundle_variable.borrow().is_default_key(*item); + // export { name as personName } + // export { name as personName } from './person'; + ExportSpecifierInfo::Named(variable) => { + if let Some(source) = &export.source { + let is_find_default = + self.bundle_variable.borrow().name(variable.local()) == "default"; + let target = self.bundle_variable.borrow_mut().find_ident_by_index( + variable.local(), + source, + module_analyzer_manager, + group_id.clone(), + is_find_default, + false, + ); - self.bundle_reference.add_local_export( - &ExportSpecifierInfo::Default(if is_default_key { - module_analyzer_manager - .module_global_uniq_name - .default_name_result(source)? - } else { - *item - }), - export_type.clone(), - ); + if let Some(target) = target { + let is_common_js = target.is_common_js(); + let mut is_confirmed_import = false; + let target_source = target.target_source(); + let module_system = + module_system.merge(target.module_system().unwrap_or(module_system.clone())); - if is_commonjs { - self.bundle_reference.add_declare_commonjs_import( - &ImportSpecifierInfo::Default(if is_default_key { - module_analyzer_manager - .module_global_uniq_name - .default_name_result(source)? - } else { - *item - }), - source.clone().into(), - &self.bundle_variable.borrow(), - )?; - } - } - } + match target { + FindModuleExportResult::Local(local, target_source, _) => { + is_confirmed_import = true; + let is_default_key = self.bundle_variable.borrow().is_default_key(local); - { - for (module_id, reference) in &export_names.reference_map { - if module_analyzer_manager.is_external(module_id) { - for (from, export_as) in &reference.named { - self.bundle_reference.add_reference_export( - &ExportSpecifierInfo::Named((*from, Some(*export_as)).into()), - module_id.clone().into(), - export_type.clone(), - ); - } + let name = if is_default_key { + module_analyzer_manager + .module_global_uniq_name + .default_name_result(&target_source)? + } else { + local + }; - if let Some(item) = &reference.default { - self.bundle_reference.add_reference_export( - &ExportSpecifierInfo::Default(*item), - module_id.clone().into(), - export_type.clone(), - ); - } + if is_common_js { + self.bundle_variable.borrow_mut().set_var_uniq_rename(local); - if reference.all { - if is_hybrid_dynamic - && self.context.config.output.format == ModuleFormat::CommonJs - { - self.bundle_reference.add_import( - &ImportSpecifierInfo::Namespace( - module_analyzer_manager - .module_global_uniq_name - .namespace_name(module_id) - .unwrap(), - ), - module_id.clone().into(), - &self.bundle_variable.borrow(), - )?; + bundle_reference1.add_declare_commonjs_import( + &if is_default_key { + ImportSpecifierInfo::Named { + local: name, + imported: Some(local), } + } else { + ImportSpecifierInfo::Named { + local, + imported: None, + } + }, + target_source.into(), + &self.bundle_variable.borrow(), + )?; + } - self.bundle_reference.add_reference_export( - &ExportSpecifierInfo::All(None), - module_id.clone().into(), - export_type.clone(), - ); - } - } else if module_analyzer_manager.is_commonjs(module_id) { - reexport_commonjs(module_id, &mut self.bundle_reference)? - } + if is_reference_by_another { + bundle_reference1.add_local_export( + &ExportSpecifierInfo::Named(Variable(name, Some(variable.export_as()))), + module_system, + ); } } - } - } - } - - // export { name as personName } - // export { name as personName } from './person'; - ExportSpecifierInfo::Named(variable) => { - if let Some(source) = &export.source { - let is_find_default = - self.bundle_variable.borrow().name(variable.local()) == "default"; - let target = self.bundle_variable.borrow_mut().find_ident_by_index( - variable.local(), - source, - module_analyzer_manager, - resource_pot_id.clone(), - is_find_default, - false, - ); - - if let Some(target) = target { - let is_common_js = target.is_common_js(); - let mut is_confirmed_import = false; - let target_source = target.target_source(); - let module_system = module_system - .merge(target.module_system().unwrap_or(module_system.clone())); - - match target { - FindModuleExportResult::Local(local, target_source, _) => { - is_confirmed_import = true; - let is_default_key = self.bundle_variable.borrow().is_default_key(local); - let name = if is_default_key { - module_analyzer_manager - .module_global_uniq_name - .default_name_result(&target_source)? - } else { - local - }; - - if is_common_js { - self.bundle_variable.borrow_mut().set_var_uniq_rename(local); - - self.bundle_reference.add_declare_commonjs_import( - &if is_default_key { - ImportSpecifierInfo::Named { - local: name, - imported: Some(local), - } - } else { - ImportSpecifierInfo::Named { - local, - imported: None, - } - }, - target_source.into(), - &self.bundle_variable.borrow(), - )?; - } + FindModuleExportResult::External(_, target_source, _) => { + let mut bundle_variable = self.bundle_variable.borrow_mut(); + is_confirmed_import = true; + if is_reference_by_another { + bundle_reference1.add_reference_export( + specify, + target_source.into(), + module_system, + ); + } else { + let is_default = bundle_variable.is_default_key(variable.export_as()); - if is_reference_by_another { - self.bundle_reference.add_local_export( - &ExportSpecifierInfo::Named(Variable( - name, - Some(variable.export_as()), - )), - module_system, - ); + if is_default { + bundle_variable + .set_uniq_name_both(variable.export_from(), variable.export_as()); } - } - FindModuleExportResult::External(_, target_source) => { - if is_reference_by_another { - self.bundle_reference.add_reference_export( - specify, - target_source.into(), - module_system, - ); - is_confirmed_import = true; - } - } - FindModuleExportResult::Bundle(_, _, _) => { - is_confirmed_import = true; - // TODO: bundle impl + bundle_reference1.add_import( + &ImportSpecifierInfo::Named { + local: variable.export_as(), + imported: Some(variable.export_from()), + }, + target_source.into(), + &bundle_variable, + )?; } } - if !is_confirmed_import { - self.bundle_reference.add_empty_import(target_source) - } - } - } else { - self - .bundle_variable - .borrow_mut() - .set_var_uniq_rename(variable.local()); - - if is_reference_by_another { - if module_analyzer_manager.is_commonjs(module_id) { - let is_default_key = self - .bundle_variable - .borrow() - .is_default_key(variable.local()); - - self.bundle_reference.add_declare_commonjs_import( - &ImportSpecifierInfo::Named { - local: if is_default_key { - module_analyzer_manager - .module_global_uniq_name - .default_name_result(module_id)? - } else { - variable.local() + FindModuleExportResult::Bundle(index, target_id, _, _) => { + let bundle_variable = self.bundle_variable.borrow_mut(); + is_confirmed_import = true; + let is_same_bundle = if is_common_js { + module_analyzer_manager.is_same_bundle(module_id, &target_id) + } else { + bundle_variable.set_var_root(variable.local(), index); + bundle_variable.is_same_bundle_by_root( + index, + &group_id, + module_analyzer_manager, + ) + }; + + if is_same_bundle { + bundle_reference1.add_local_export( + &ExportSpecifierInfo::Named((variable.local()).into()), + module_system, + ); + } else { + bundle_reference1.add_import( + &ImportSpecifierInfo::Named { + local: index, + imported: None, }, - imported: Some(variable.export_as()), - }, - ReferenceKind::Module((*module_id).clone()), - &self.bundle_variable.borrow(), - )?; - } + target_id.clone().into(), + &bundle_variable, + )?; - self - .bundle_reference - .add_local_export(specify, module_system.clone()); + bundle_reference1.add_local_export( + &ExportSpecifierInfo::Named((variable.local()).into()), + module_system, + ); + } + } } - } - } - // export default n, Default(n) - // export default 1 + 1, Default("default") - ExportSpecifierInfo::Default(var) => { - let default_name = || { - module_analyzer_manager - .module_global_uniq_name - .default_name_result(module_id) - }; - - if self.bundle_variable.borrow().name(*var) == "default" { - let rendered_name = self.bundle_variable.borrow().render_name(default_name()?); - - self - .bundle_variable - .borrow_mut() - .set_rename(*var, rendered_name); - } else { - self.bundle_variable.borrow_mut().set_var_uniq_rename(*var); + if !is_confirmed_import { + bundle_reference1.add_empty_import(target_source) + } } + } else { + self + .bundle_variable + .borrow_mut() + .set_var_uniq_rename(variable.local()); if is_reference_by_another { if module_analyzer_manager.is_commonjs(module_id) { - self.bundle_reference.add_declare_commonjs_import( - &ImportSpecifierInfo::Default(default_name()?), + let is_default_key = self + .bundle_variable + .borrow() + .is_default_key(variable.local()); + + bundle_reference1.add_declare_commonjs_import( + &ImportSpecifierInfo::Named { + local: if is_default_key { + module_analyzer_manager + .module_global_uniq_name + .default_name_result(module_id)? + } else { + variable.local() + }, + imported: Some(variable.export_as()), + }, ReferenceKind::Module((*module_id).clone()), &self.bundle_variable.borrow(), )?; } - self - .bundle_reference - .add_local_export(specify, module_system.clone()); + bundle_reference1.add_local_export(specify, module_system.clone()); } } + } - // export * as ns from 'person' - ExportSpecifierInfo::Namespace(ns) => { - let source = export - .source - .as_ref() - .to_result("namespace should have source, but not found")?; - - let local_var = module_analyzer_manager + // export default n, Default(n) + // export default 1 + 1, Default("default") + ExportSpecifierInfo::Default(var) => { + let default_name = || { + module_analyzer_manager .module_global_uniq_name - .namespace_name(source) - .to_result(format!("not found module {source:?} namespace named"))?; + .default_name_result(module_id) + }; + let mut bundle_variable = self.bundle_variable.borrow_mut(); + let is_default_key = bundle_variable.is_default_key(*var); - let local_name = self.bundle_variable.borrow().render_name(local_var); + if is_default_key { + let default_name = default_name()?; + let rendered_name = bundle_variable.render_name(default_name); - self - .bundle_variable - .borrow_mut() - .set_rename(*ns, local_name); + bundle_variable.set_var_root(*var, default_name); + bundle_variable.set_rename(*var, rendered_name); + } else { + bundle_variable.set_var_uniq_rename(*var); + } - let target = self.bundle_variable.borrow().find_ident_by_index( - local_var, - source, - module_analyzer_manager, - resource_pot_id.clone(), - false, - true, - ); + if is_reference_by_another { + if module_analyzer_manager.is_commonjs(module_id) { + bundle_reference1.add_declare_commonjs_import( + &ImportSpecifierInfo::Default(default_name()?), + ReferenceKind::Module((*module_id).clone()), + &bundle_variable, + )?; + } - if let Some(target) = target { - let mut is_confirmed_import = false; - let target_source = target.target_source(); - let module_system = - module_system.merge(target.module_system().unwrap_or(module_system.clone())); - match target { - FindModuleExportResult::Local(_, _, _) => { + if is_entry { + bundle_reference1.add_local_export(specify, module_system.clone()); + } else { + bundle_reference1.add_local_export( + &ExportSpecifierInfo::Named((*var).into()), + module_system.clone(), + ); + } + } + } + + // export * as ns from 'person' + ExportSpecifierInfo::Namespace(ns) => { + let bundle_variable = self.bundle_variable.borrow_mut(); + let source = export + .source + .as_ref() + .to_result("namespace should have source, but not found")?; + + let local_var = module_analyzer_manager + .module_global_uniq_name + .namespace_name(source) + .to_result(format!("not found module {:?} namespace named", source))?; + + let target = bundle_variable.find_ident_by_index( + local_var, + source, + module_analyzer_manager, + group_id.clone(), + false, + true, + ); + + if let Some(target) = target { + let mut is_confirmed_import = false; + let target_source = target.target_source(); + let module_system = + module_system.merge(target.module_system().unwrap_or(module_system.clone())); + match target { + FindModuleExportResult::Local(_, _, _) => { + let local_name = bundle_variable.render_name(local_var); + + bundle_variable.set_rename(*ns, local_name); + + is_confirmed_import = true; + if module_analyzer_manager.is_commonjs(source) { + bundle_reference1.add_declare_commonjs_import( + &ImportSpecifierInfo::Namespace(local_var), + source.clone().into(), + &bundle_variable, + )?; + } + + if is_reference_by_another { + bundle_reference1.add_local_export( + &ExportSpecifierInfo::Named((local_var, Some(*ns)).into()), + module_system, + ); + } + } + + FindModuleExportResult::External(_, _, _) => { + let local_name = bundle_variable.render_name(local_var); + + bundle_variable.set_rename(*ns, local_name); + + if is_format_to_commonjs { is_confirmed_import = true; - if module_analyzer_manager.is_commonjs(source) { - self.bundle_reference.add_declare_commonjs_import( - &ImportSpecifierInfo::Namespace(local_var), - source.clone().into(), - &self.bundle_variable.borrow(), - )?; - } + bundle_reference1.add_import( + &ImportSpecifierInfo::Namespace(*ns), + source.clone().into(), + &bundle_variable, + )?; + } - if is_reference_by_another { - self.bundle_reference.add_local_export( - &ExportSpecifierInfo::Named((local_var, Some(*ns)).into()), - module_system, - ); - } + if is_reference_by_another { + is_confirmed_import = true; + bundle_reference1.add_reference_export( + specify, + source.clone().into(), + module_system, + ); } + } + + FindModuleExportResult::Bundle(index, target_id, _, _) => { + is_confirmed_import = true; + + let is_commonjs = module_analyzer_manager.is_commonjs(&target_id); + + let is_same_bundle = if is_commonjs { + module_analyzer_manager.is_same_bundle(module_id, &target_id) + } else { + bundle_variable.set_var_root( + *ns, + module_analyzer_manager + .module_global_uniq_name + .namespace_name_result(&target_id)?, + ); + + bundle_variable.is_same_bundle_by_root( + index, + &group_id, + module_analyzer_manager, + ) + }; - FindModuleExportResult::External(_, _) => { - if is_format_to_commonjs { - is_confirmed_import = true; - self.bundle_reference.add_import( + if !is_same_bundle { + bundle_reference1.add_import( + &ImportSpecifierInfo::Named { + local: if is_commonjs { + module_analyzer_manager + .module_global_uniq_name + .commonjs_name_result(&target_id)? + } else { + module_analyzer_manager + .module_global_uniq_name + .namespace_name_result(&target_id)? + } + .into(), + imported: None, + }, + target_id.clone().into(), + &bundle_variable, + )?; + + if is_commonjs { + bundle_reference1.add_declare_commonjs_import( &ImportSpecifierInfo::Namespace(*ns), - source.clone().into(), - &self.bundle_variable.borrow(), + target_id.clone().into(), + &bundle_variable, )?; } if is_reference_by_another { - is_confirmed_import = true; - self.bundle_reference.add_reference_export( - specify, - source.clone().into(), - module_system, + // let target_reference = + // bundle_reference_manager.reference1_mut(&target_id); + // let mut target_reference = target_reference.borrow_mut(); + let target_reference = bundle_reference_manager + .reference_mut_by_module(&target_id, &module_analyzer_manager); + let mut target_reference = target_reference.borrow_mut(); + let target_reference = + target_reference.fetch_mut(&target_id, module_analyzer_manager); + + target_reference.add_local_export( + &ExportSpecifierInfo::Named( + if is_commonjs { + module_analyzer_manager + .module_global_uniq_name + .commonjs_name_result(target_id)? + } else { + module_analyzer_manager + .module_global_uniq_name + .namespace_name_result(target_id)? + } + .into(), + ), + module_system.clone(), ); } } - FindModuleExportResult::Bundle(_, _, _) => { - // bundle - // export * as ns from './other_bundle_module' - // self.bundle_reference.sync_export( - // &ExportSpecifierInfo::Named((*ns).into()), - // Some(module_analyzer.resource_pot_id.clone().into()), - // false, - // ); - } + bundle_reference1 + .add_local_export(&ExportSpecifierInfo::Named((*ns).into()), module_system); } + } - if !is_confirmed_import { - self.bundle_reference.add_empty_import(target_source); - } + if !is_confirmed_import { + bundle_reference1.add_empty_import(target_source); } } } } } + } + } - if !is_contain_export - && module_analyzer_manager.is_commonjs(module_id) - && module_analyzer.entry - { - let reference_kind = ReferenceKind::Module((*module_id).clone()); - self.bundle_reference.execute_module_for_cjs(reference_kind); - } + if !is_contain_export && module_analyzer_manager.is_commonjs(module_id) { + if module_analyzer.entry { + let reference_kind = ReferenceKind::Module((*module_id).clone()); + bundle_reference1.execute_module_for_cjs(reference_kind); + } else if is_reference_by_another { + bundle_reference1.add_local_export( + &ExportSpecifierInfo::Named( + module_analyzer_manager + .module_global_uniq_name + .commonjs_name_result(module_id)? + .into(), + ), + ModuleSystem::CommonJs, + ); } } } @@ -879,19 +1057,8 @@ impl<'a> BundleAnalyzer<'a> { } // 3. start process bundle - pub fn render( - &mut self, - module_analyzer_manager: &mut ModuleAnalyzerManager, - order_index_map: &HashMap, - ) -> Result<()> { - self.module_conflict_name(module_analyzer_manager); - + pub fn render(&mut self, module_analyzer_manager: &mut ModuleAnalyzerManager) -> Result<()> { self.strip_module(module_analyzer_manager)?; - - self.link_module_relation(module_analyzer_manager)?; - - self.patch_ast(module_analyzer_manager, order_index_map)?; - Ok(()) } @@ -902,59 +1069,140 @@ impl<'a> BundleAnalyzer<'a> { &mut self, module_analyzer_manager: &mut ModuleAnalyzerManager, order_index_map: &HashMap, + bundle_reference_manager: &mut BundleReferenceManager, + ctx: &ShareBundleContext, ) -> Result<()> { farm_profile_function!(""); + let mut commonjs_import_executed: HashSet = HashSet::new(); let external_config = ExternalConfig::from(self.context.config.as_ref()); - for module_id in &self.ordered_modules { - farm_profile_scope!(format!( - "bundle patch ast module: {}", - module_id.to_string() - )); + let mut patch_export_to_module = vec![]; + let mut patch_import_to_module = vec![]; + let mut patch_after_import_to_module = vec![]; + + let mut is_polyfilled_es_module_flag = false; + let mut already_redeclare: HashSet = HashSet::new(); + + // sort by order + // 1. sort commonjs declaration to top + // 2. commonjs import declaration should use after declaration or first module use + for module_id in self.ordered_modules.iter() { + // let bundle_reference = bundle_reference_manager.reference1_mut(&module_id); + // let mut bundle_reference = bundle_reference.borrow_mut(); + let bundle_reference = + bundle_reference_manager.reference_mut_by_module(&module_id, &module_analyzer_manager); + let mut bundle_reference = bundle_reference.borrow_mut(); + let module_of_bundle_reference = + bundle_reference.fetch_mut(module_id, module_analyzer_manager); + module_analyzer_manager.patch_module_analyzer_ast( module_id, &self.context, - self.module_graph, &mut self.bundle_variable.borrow_mut(), - &mut self.bundle_reference, + module_of_bundle_reference, &mut commonjs_import_executed, order_index_map, &mut self.polyfill, &external_config, + ctx, )?; + + if let Some(f) = bundle_reference.query_redeclare_both(&module_id) { + already_redeclare.insert(module_id.clone().into()); + let result = CjsModuleAnalyzer::redeclare_commonjs_export( + &self.bundle_variable.borrow(), + &f.redeclare_commonjs_import, + &module_analyzer_manager.module_global_uniq_name, + &mut self.polyfill, + ctx, + )?; + + let module_analyzer = module_analyzer_manager.module_analyzer_mut_unchecked(&module_id); + + module_analyzer.ast.body.extend(result); + } } - let is_runtime_bundle = matches!( - self.resource_pot.resource_pot_type, - ResourcePotType::Runtime - ); + let bundle_commonjs_declare_map: CommonJsImportMap = CommonJsImportMap::new(); - let mut patch_export_to_module = vec![]; - let mut patch_import_to_module = vec![]; + let bundle_reference = bundle_reference_manager.reference_mut(&self.group.id); + let mut bundle_reference = bundle_reference.borrow_mut(); + + let mut map = bundle_reference.query_all_redeclare(); + + for item in already_redeclare { + map.remove(&item); + } + + patch_after_import_to_module.extend(CjsModuleAnalyzer::redeclare_commonjs_export( + &self.bundle_variable.borrow(), + &map, + &module_analyzer_manager.module_global_uniq_name, + &mut self.polyfill, + ctx, + )?); + + for module_id in &self.ordered_modules { + module_analyzer_manager.patch_rename( + module_id, + &self.context, + &mut self.bundle_variable.borrow_mut(), + &bundle_commonjs_declare_map, + ); + } + + let is_runtime_bundle = matches!(self.group.group_type, ResourcePotType::Runtime); - // runtime bundle cannot export - // 1. if import by other bundle or entry export, should reexport some variable if !is_runtime_bundle { patch_export_to_module.extend(generate_export_by_reference_export( - &self.resource_pot.id, + &self.group.id, + true, &self.bundle_variable.borrow(), - &mut self.bundle_reference, + &mut bundle_reference.reexport_raw, module_analyzer_manager, &self.context, &mut self.polyfill, + &mut is_polyfilled_es_module_flag, + ctx, + )?); + + patch_export_to_module.extend(generate_export_by_reference_export( + &self.group.id, + false, + &self.bundle_variable.borrow(), + &mut bundle_reference.bundle_reference1, + module_analyzer_manager, + &self.context, + &mut self.polyfill, + &mut is_polyfilled_es_module_flag, + ctx, )?); } // 2. maybe import external、other bundle, should generate import patch_import_to_module.extend(generate_bundle_import_by_bundle_reference( - &self.context.config.output.format, + &ctx.options.format, + &self.bundle_variable.borrow(), + &bundle_reference.bundle_reference1, + module_analyzer_manager, + &mut self.polyfill, + &self.group.id, + ctx, + )?); + + patch_import_to_module.extend(generate_bundle_import_by_bundle_reference( + &ctx.options.format, &self.bundle_variable.borrow(), - &self.bundle_reference, + &bundle_reference.reexport_raw, module_analyzer_manager, &mut self.polyfill, + &self.group.id, + ctx, )?); + patch_import_to_module.extend(patch_after_import_to_module); + if !patch_import_to_module.is_empty() { if let Some(module_analyzer) = self .ordered_modules @@ -990,6 +1238,125 @@ impl<'a> BundleAnalyzer<'a> { Ok(()) } + pub fn patch_polyfill_for_bundle( + &mut self, + module_analyzer_manager: &mut ModuleAnalyzerManager, + context: &ShareBundleContext, + ) -> Result<()> { + if let Some(module_id) = self.ordered_modules.first() { + let module_analyzer = module_analyzer_manager.module_analyzer_mut_unchecked(module_id); + + let mut bundle_reference = BundleReference::new(); + + let bundle_variable = self.bundle_variable.borrow_mut(); + + for name in self.polyfill.to_export() { + if let Some(index) = &bundle_variable.polyfill_index_map.get(&name) { + bundle_reference.add_import( + &ImportSpecifierInfo::Named { + local: **index, + imported: None, + }, + ModuleId::from(FARM_BUNDLE_POLYFILL_SLOT).into(), + &bundle_variable, + )?; + } + } + + let mut ast = module_analyzer.ast.body.take(); + + let stmts = generate_bundle_import_by_bundle_reference( + &context.options.format, + &bundle_variable, + &bundle_reference, + &module_analyzer_manager, + &mut self.polyfill, + &self.group.id, + context, + )?; + + ast = stmts.into_iter().chain(ast.take()).collect(); + + module_analyzer_manager.set_ast_body(&module_id, ast); + } + + Ok(()) + } + + // TODO: for partial ShareBundle + pub fn patch_polyfill_inline( + &mut self, + module_analyzer_manager: &mut ModuleAnalyzerManager, + ) -> Result<()> { + if let Some(module_id) = self.ordered_modules.first() { + let module_analyzer = module_analyzer_manager.module_analyzer_mut_unchecked(module_id); + + let mut ast = module_analyzer.ast.body.take(); + + ast = self + .polyfill + .to_ast()? + .into_iter() + .chain(ast.take()) + .collect(); + + module_analyzer_manager.set_ast_body(&module_id, ast); + } + + Ok(()) + } + + pub fn patch_polyfill( + &mut self, + module_analyzer_manager: &mut ModuleAnalyzerManager, + polyfill: SimplePolyfill, + context: &ShareBundleContext, + ) -> Result<()> { + let module_id = ModuleId::from(FARM_BUNDLE_POLYFILL_SLOT); + let module_analyzer = module_analyzer_manager + .module_analyzer_mut(&module_id) + .to_result(format!("cannot found module {:?}", module_id))?; + + let mut ast = module_analyzer.ast.body.take(); + + ast = [ + polyfill.to_ast().into_iter().flatten().collect::>(), + ast, + ] + .concat(); + + let mut bundle_reference = BundleReference::new(); + + for name in polyfill.to_export() { + if let Some(index) = &self.bundle_variable.borrow().polyfill_index_map.get(&name) { + bundle_reference.add_local_export( + &ExportSpecifierInfo::Named((**index).into()), + module_analyzer.module_system.clone(), + ); + } + } + + let group_id = module_analyzer.bundle_group_id.clone(); + + let stmts = generate_export_by_reference_export( + &group_id, + false, + &self.bundle_variable.borrow(), + &mut bundle_reference, + &module_analyzer_manager, + &self.context, + &mut SimplePolyfill::default(), + &mut false, + context, + )?; + + ast = ast.into_iter().chain(stmts).collect(); + + module_analyzer_manager.set_ast_body(&module_id, ast); + + Ok(()) + } + // step: 4 generate bundle code pub fn codegen( &mut self, @@ -1002,6 +1369,10 @@ impl<'a> BundleAnalyzer<'a> { trace_source_map_chain: Some(false), }); + let mut ordered_modules = self.ordered_modules.clone(); + + ordered_modules.sort_by_key(|v| module_analyzer_manager.is_commonjs(v)); + for module_id in &self.ordered_modules { let module = self .module_graph @@ -1086,28 +1457,12 @@ impl<'a> BundleAnalyzer<'a> { // in browser, should avoid naming pollution if matches!(self.context.config.output.target_env, TargetEnv::Browser) - && matches!( - self.resource_pot.resource_pot_type, - ResourcePotType::Runtime - ) + && matches!(self.group.group_type, ResourcePotType::Runtime) { - bundle.prepend("((function(){"); + bundle.prepend(";((function(){"); bundle.append("})());", None); }; - let injectable_resource_pot = (config.output.target_env.is_library() - && self.resource_pot.entry_module.is_some()) - || matches!( - self.resource_pot.resource_pot_type, - ResourcePotType::Runtime - ); - - if !self.polyfill.is_empty() && injectable_resource_pot { - for item in self.polyfill.to_str() { - bundle.prepend(&item); - } - } - Ok(bundle) } } diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_external.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_external.rs deleted file mode 100644 index a67660299..000000000 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_external.rs +++ /dev/null @@ -1,279 +0,0 @@ -use std::collections::HashMap; - -use farmfe_core::{ - error::{CompilationError, Result}, - module::{ModuleId, ModuleSystem}, -}; - -use crate::resource_pot_to_bundle::{ - modules_analyzer::module_analyzer::{ExportSpecifierInfo, ImportSpecifierInfo}, - uniq_name::BundleVariable, -}; - -#[derive(Debug)] -pub struct ExternalReferenceImport { - pub named: HashMap, - pub namespace: Option, - pub default: Option, -} - -impl ExternalReferenceImport { - fn new() -> Self { - Self { - named: HashMap::new(), - namespace: None, - default: None, - } - } - - fn fetch( - &self, - import_type: &ImportSpecifierInfo, - bundle_variable: &BundleVariable, - ) -> Option { - match import_type { - ImportSpecifierInfo::Named { local, imported } => self - .named - .get(&bundle_variable.name(imported.unwrap_or(*local))) - .cloned(), - ImportSpecifierInfo::Namespace(_) => self.namespace, - ImportSpecifierInfo::Default(_) => self.default, - } - } - - fn insert(&mut self, import_type: ImportSpecifierInfo, bundle_variable: &BundleVariable) { - match import_type { - ImportSpecifierInfo::Named { local, imported } => { - let imported = imported.unwrap_or(local); - let name = bundle_variable.name(imported); - - self.named.entry(name).or_insert(local); - } - ImportSpecifierInfo::Namespace(name) => { - self.namespace = Some(name); - } - ImportSpecifierInfo::Default(name) => { - self.default = Some(name); - } - } - } - - pub fn is_empty(&self) -> bool { - self.named.is_empty() && self.namespace.is_none() && self.default.is_none() - } -} - -#[derive(Debug)] -pub struct ExternalReferenceExport { - pub named: HashMap, - pub default: Option, - // TODO: `export * from "cjs"`; in cjs need transform to _export_star(cjs, module.exports) - pub all: (bool, Option), - pub namespace: Option, - pub module_system: ModuleSystem, -} - -impl ExternalReferenceExport { - pub fn new(module_system: ModuleSystem) -> Self { - Self { - named: HashMap::new(), - default: None, - all: (false, None), - namespace: None, - module_system, - } - } - - #[allow(dead_code)] - fn contains(&self, export: &ExportSpecifierInfo) -> bool { - match export { - ExportSpecifierInfo::Named(named) => self.named.contains_key(&named.local()), - ExportSpecifierInfo::Default(_) => self.default.is_some(), - ExportSpecifierInfo::All(_) => self.all.0, - ExportSpecifierInfo::Namespace(_) => self.namespace.is_some(), - } - } - - fn insert(&mut self, export: ExportSpecifierInfo) { - match export { - ExportSpecifierInfo::Named(named) => { - self.named.insert(named.export_as(), named.local()); - } - ExportSpecifierInfo::Default(local) => { - self.default = Some(local); - } - ExportSpecifierInfo::All(_) => { - self.all = (true, None); - } - ExportSpecifierInfo::Namespace(name) => { - self.namespace = Some(name); - } - } - } -} - -#[derive(Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord)] -pub enum ReferenceKind { - Bundle(String), - Module(ModuleId), -} - -impl ReferenceKind { - pub fn to_module_id(&self) -> ModuleId { - match self { - ReferenceKind::Bundle(name) => ModuleId::from(name.as_str()), - ReferenceKind::Module(id) => id.clone(), - } - } -} - -impl ToString for ReferenceKind { - fn to_string(&self) -> String { - match self { - ReferenceKind::Bundle(name) => name.clone(), - ReferenceKind::Module(id) => id.to_string(), - } - } -} - -impl From for ReferenceKind { - fn from(id: ModuleId) -> Self { - ReferenceKind::Module(id) - } -} - -impl From for ReferenceKind { - fn from(name: String) -> Self { - ReferenceKind::Bundle(name) - } -} - -#[derive(Debug, Default)] -pub struct BundleReference { - /// import { xxx } from './external_bundle_module' | './other_bundle_module' - pub import_map: HashMap, - - /// - /// ```ts - /// export { } from "./cjs_module"; - /// export * as ns from "./cjs_module"; - /// export { default } ns from "./cjs_module"; - /// // => - /// const cjs_module_cjs = cjs_module()["default"]; - /// ``` - /// - pub redeclare_commonjs_import: HashMap, - - // pub declare_commonjs_export: HashMap, - /// export xxx from './external_bundle_module' - /// export * as ns from './external_bundle_module' - pub external_export_map: HashMap, - - /// export { local } - /// export default local - pub export: Option, -} - -impl BundleReference { - pub fn new() -> Self { - Self::default() - } - - /// import "./cjs" - pub fn execute_module_for_cjs(&mut self, import_kind: ReferenceKind) { - self - .redeclare_commonjs_import - .entry(import_kind) - .or_insert_with(ExternalReferenceImport::new); - } - - pub fn add_local_export(&mut self, specify: &ExportSpecifierInfo, module_system: ModuleSystem) { - if self.export.is_none() { - self.export = Some(ExternalReferenceExport::new(module_system)); - } - if let Some(ref mut export) = self.export { - export.insert(specify.clone()) - }; - } - - pub fn add_reference_export( - &mut self, - specify: &ExportSpecifierInfo, - source: ReferenceKind, - module_system: ModuleSystem, - ) { - if self.external_export_map.contains_key(&source) { - let map = self.external_export_map.get_mut(&source).unwrap(); - map.insert(specify.clone()); - } else { - let mut map = ExternalReferenceExport::new(module_system); - map.insert(specify.clone()); - self.external_export_map.insert(source, map); - } - } - - pub fn change_to_hybrid_dynamic(&mut self, source: ReferenceKind) { - if let Some(map) = self.external_export_map.get_mut(&source) { - map.module_system.merge(ModuleSystem::Hybrid); - } - } - - fn add_import_helper( - map: &mut HashMap, - import: &ImportSpecifierInfo, - source: ReferenceKind, - bundle_variable: &BundleVariable, - ) -> Result { - if !map.contains_key(&source) { - map.insert(source.clone(), ExternalReferenceImport::new()); - } - - let module_import_map = map.get_mut(&source).unwrap(); - - if let Some(options) = module_import_map.fetch(import, bundle_variable) { - Ok(options) - } else { - module_import_map.insert(import.clone(), bundle_variable); - module_import_map - .fetch(import, bundle_variable) - .map(Ok) - .unwrap_or(Err(CompilationError::GenericError( - "failed fetch import".to_string(), - ))) - } - } - - pub fn add_declare_commonjs_import( - &mut self, - import: &ImportSpecifierInfo, - source: ReferenceKind, - bundle_variable: &BundleVariable, - ) -> Result { - Self::add_import_helper( - &mut self.redeclare_commonjs_import, - import, - source, - bundle_variable, - ) - } - - pub fn add_empty_import(&mut self, source: ReferenceKind) { - self - .import_map - .entry(source) - .or_insert_with(ExternalReferenceImport::new); - } - - pub fn add_import( - &mut self, - import: &ImportSpecifierInfo, - source: ReferenceKind, - bundle_variable: &BundleVariable, - ) -> Result { - Self::add_import_helper(&mut self.import_map, import, source, bundle_variable) - } - - pub fn import(&self, import_kind: &ReferenceKind) -> Option<&ExternalReferenceImport> { - self.import_map.get(import_kind) - } -} diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_reference.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_reference.rs new file mode 100644 index 000000000..2062685d9 --- /dev/null +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_reference.rs @@ -0,0 +1,812 @@ +use std::{cell::RefCell, collections::HashMap, rc::Rc}; + +use farmfe_core::{ + config::{Config, ModuleFormat}, + error::{CompilationError, Result}, + module::{ModuleId, ModuleSystem, ModuleType}, + resource::resource_pot::ResourcePotId, +}; + +use crate::resource_pot_to_bundle::{ + common::with_bundle_reference_slot_name, + modules_analyzer::module_analyzer::{ExportSpecifierInfo, ImportSpecifierInfo, ModuleAnalyzer}, + uniq_name::BundleVariable, + ShareBundleContext, +}; + +use super::ModuleAnalyzerManager; + +#[derive(Debug, Clone)] +pub struct ExternalReferenceImport { + pub named: HashMap, + pub namespace: Option, + pub default: Option, + pub source: Option, +} + +impl ExternalReferenceImport { + pub fn new() -> Self { + Self { + named: HashMap::new(), + namespace: None, + default: None, + source: None, + } + } + + fn fetch( + &self, + import_type: &ImportSpecifierInfo, + bundle_variable: &BundleVariable, + ) -> Option { + match import_type { + ImportSpecifierInfo::Named { local, imported } => self + .named + .get(&bundle_variable.name(imported.unwrap_or(*local))) + .cloned(), + ImportSpecifierInfo::Namespace(_) => self.namespace, + ImportSpecifierInfo::Default(_) => self.default, + } + } + + fn insert(&mut self, import_type: ImportSpecifierInfo, bundle_variable: &BundleVariable) { + match import_type { + ImportSpecifierInfo::Named { local, imported } => { + let imported = imported.unwrap_or(local); + let name = bundle_variable.name(imported); + // TODO: use index + self.named.entry(name).or_insert(local); + } + ImportSpecifierInfo::Namespace(name) => { + self.namespace = Some(name); + } + ImportSpecifierInfo::Default(name) => { + self.default = Some(name); + } + } + } + + pub fn is_empty(&self) -> bool { + self.named.is_empty() && self.namespace.is_none() && self.default.is_none() + } + + pub fn extend(&mut self, other: &Self) { + self + .named + .extend(other.named.iter().map(|(k, v)| (k.clone(), *v))); + + if self.namespace.is_none() { + self.namespace = other.namespace; + } + + if self.default.is_none() { + self.default = other.default; + } + } +} + +#[derive(Debug, Clone)] +pub struct ExternalReferenceExport { + pub named: HashMap, + pub default: Option, + // TODO: `export * from "cjs"`; in cjs need transform to _export_star(cjs, module.exports) + pub all: (bool, Option), + pub namespace: Option, + pub module_system: ModuleSystem, +} + +impl ExternalReferenceExport { + pub fn new(module_system: ModuleSystem) -> Self { + Self { + named: HashMap::new(), + default: None, + all: (false, None), + namespace: None, + module_system, + } + } + + #[allow(dead_code)] + fn contains(&self, export: &ExportSpecifierInfo) -> bool { + match export { + ExportSpecifierInfo::Named(named) => self.named.contains_key(&named.local()), + ExportSpecifierInfo::Default(_) => self.default.is_some(), + ExportSpecifierInfo::All(_) => self.all.0, + ExportSpecifierInfo::Namespace(_) => self.namespace.is_some(), + } + } + + fn insert(&mut self, export: ExportSpecifierInfo) { + match export { + ExportSpecifierInfo::Named(named) => { + self.named.insert(named.export_as(), named.local()); + } + ExportSpecifierInfo::Default(local) => { + self.default = Some(local); + } + ExportSpecifierInfo::All(_) => { + self.all = (true, None); + } + ExportSpecifierInfo::Namespace(name) => { + self.namespace = Some(name); + } + } + } + + pub fn extend(&mut self, other: &Self) { + self.named.extend(other.named.clone()); + + if self.default.is_none() { + self.default = other.default; + } + + self.all.0 = self.all.0 || other.all.0; + + if self.namespace.is_none() { + self.namespace = other.namespace; + } + } +} + +// TODO: remove it +#[derive(Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord)] +pub enum ReferenceKind { + Bundle(String), + Module(ModuleId), +} + +impl ReferenceKind { + pub fn is_module_id(&self) -> bool { + matches!(self, ReferenceKind::Module(_)) + } + + /// remove it + pub fn to_module_id(&self) -> ModuleId { + match self { + ReferenceKind::Bundle(name) => ModuleId::from(with_bundle_reference_slot_name(name, true)), + ReferenceKind::Module(id) => id.clone(), + } + } +} + +impl ToString for ReferenceKind { + fn to_string(&self) -> String { + match self { + ReferenceKind::Bundle(m) => m.to_string(), + ReferenceKind::Module(m) => m.to_string(), + } + } +} + +impl From for ReferenceKind { + fn from(id: ModuleId) -> Self { + ReferenceKind::Module(id) + } +} + +impl From<&ModuleId> for ReferenceKind { + fn from(id: &ModuleId) -> Self { + ReferenceKind::Module(id.clone()) + } +} + +impl From for ReferenceKind { + fn from(name: String) -> Self { + ReferenceKind::Bundle(name) + } +} +impl From<&String> for ReferenceKind { + fn from(name: &String) -> Self { + ReferenceKind::Bundle(name.clone()) + } +} + +/// +/// { +/// import: { +/// source: xxx +/// }, +/// commonjs: { +/// source: xxx +/// }, +/// external: { +/// source: xxx +/// }, +/// local_export: { +/// aa: bb +/// } +/// } +/// + +pub type CommonJsImportMap = HashMap; + +#[derive(Debug, Default)] +pub struct BundleReference { + /// import { xxx } from './external_bundle_module' | './other_bundle_module' + pub import_map: HashMap, + + /// + /// ```ts + /// export { } from "./cjs_module"; + /// export * as ns from "./cjs_module"; + /// export { default } ns from "./cjs_module"; + /// // => + /// const cjs_module_cjs = cjs_module()["default"]; + /// + /// { + /// "cjs_module": { + /// default: None, + /// named: {} + /// } + /// } + /// ``` + /// + pub redeclare_commonjs_import: CommonJsImportMap, + + // pub declare_commonjs_export: HashMap, + /// export xxx from './external_bundle_module' + /// export * as ns from './external_bundle_module' + pub external_export_map: HashMap, + + /// export { local } + /// export default local + pub export: Option, +} + +impl BundleReference { + pub fn new() -> Self { + Self::default() + } + + pub fn is_empty(&self) -> bool { + self.import_map.is_empty() + && self.redeclare_commonjs_import.is_empty() + && self.external_export_map.is_empty() + && self.export.is_none() + } + + /// import "./cjs" + pub fn execute_module_for_cjs(&mut self, import_kind: ReferenceKind) { + self + .redeclare_commonjs_import + .entry(import_kind) + .or_insert_with(ExternalReferenceImport::new); + } + + pub fn add_execute_module(&mut self, import_kind: ReferenceKind) { + self + .import_map + .entry(import_kind) + .or_insert_with(ExternalReferenceImport::new); + } + + pub fn add_local_export(&mut self, specify: &ExportSpecifierInfo, module_system: ModuleSystem) { + if self.export.is_none() { + self.export = Some(ExternalReferenceExport::new(module_system)); + } + + if let Some(ref mut export) = self.export { + export.insert(specify.clone()) + }; + } + + pub fn add_reference_export( + &mut self, + specify: &ExportSpecifierInfo, + source: ReferenceKind, + module_system: ModuleSystem, + ) { + if self.external_export_map.contains_key(&source) { + let map = self.external_export_map.get_mut(&source).unwrap(); + map.insert(specify.clone()); + } else { + let mut map = ExternalReferenceExport::new(module_system); + map.insert(specify.clone()); + self.external_export_map.insert(source, map); + } + } + + pub fn change_to_hybrid_dynamic(&mut self, source: ReferenceKind) { + if let Some(map) = self.external_export_map.get_mut(&source) { + map.module_system.merge(ModuleSystem::Hybrid); + } + } + + fn add_import_helper( + map: &mut HashMap, + import: &ImportSpecifierInfo, + source: ReferenceKind, + bundle_variable: &BundleVariable, + ) -> Result { + if !map.contains_key(&source) { + map.insert(source.clone(), ExternalReferenceImport::new()); + } + + let module_import_map = map.get_mut(&source).unwrap(); + + if let Some(options) = module_import_map.fetch(import, bundle_variable) { + Ok(options) + } else { + module_import_map.insert(import.clone(), bundle_variable); + module_import_map + .fetch(import, bundle_variable) + .map(Ok) + .unwrap_or(Err(CompilationError::GenericError( + "failed fetch import".to_string(), + ))) + } + } + + pub fn add_declare_commonjs_import( + &mut self, + import: &ImportSpecifierInfo, + source: ReferenceKind, + bundle_variable: &BundleVariable, + ) -> Result { + Self::add_import_helper( + &mut self.redeclare_commonjs_import, + import, + source, + bundle_variable, + ) + } + + pub fn add_empty_import(&mut self, source: ReferenceKind) { + self + .import_map + .entry(source) + .or_insert_with(ExternalReferenceImport::new); + } + + pub fn add_import( + &mut self, + import: &ImportSpecifierInfo, + source: ReferenceKind, + bundle_variable: &BundleVariable, + ) -> Result { + Self::add_import_helper(&mut self.import_map, import, source, bundle_variable) + } + + pub fn reexport_commonjs( + &mut self, + module_id: &ModuleId, + module_analyzer_manager: &ModuleAnalyzerManager, + bundle_variable: &BundleVariable, + ) -> Result<()> { + self.change_to_hybrid_dynamic(module_id.clone().into()); + + self.add_declare_commonjs_import( + &ImportSpecifierInfo::Namespace( + module_analyzer_manager + .module_global_uniq_name + .namespace_name(module_id) + .unwrap(), + ), + module_id.clone().into(), + bundle_variable, + )?; + + self.add_reference_export( + &ExportSpecifierInfo::All(None), + module_id.clone().into(), + ModuleSystem::CommonJs, + ); + + Result::<()>::Ok(()) + } + + pub fn add_reexport_all(&mut self, reference_builder: ReferenceBuilder) -> Result<()> { + if !reference_builder.is_reference_by_another_bundle { + return Ok(()); + } + + let reexport_commonjs = |module_id: &ModuleId, bundle_reference: &mut BundleReference| { + bundle_reference.change_to_hybrid_dynamic(module_id.clone().into()); + + bundle_reference.add_declare_commonjs_import( + &ImportSpecifierInfo::Namespace( + reference_builder + .module_analyzer_manager + .module_global_uniq_name + .namespace_name(module_id) + .unwrap(), + ), + module_id.clone().into(), + reference_builder.bundle_variable, + )?; + + bundle_reference.add_reference_export( + &ExportSpecifierInfo::All(None), + module_id.clone().into(), + ModuleSystem::CommonJs, + ); + + Result::<()>::Ok(()) + }; + let is_external = reference_builder.is_external(reference_builder.source); + + let is_commonjs = reference_builder + .module_analyzer_manager + .is_commonjs(reference_builder.source); + let is_format_to_cjs = matches!( + reference_builder.config.options.format, + ModuleFormat::CommonJs + ); + let redeclare_commonjs = !reference_builder.module_analyzer.entry + || matches!( + reference_builder.module_analyzer.module_type, + ModuleType::Runtime + ); + + if is_external { + // export * from "node:fs" + // => commonjs + // const node_fs = require("node:fs") + // _export_star(node_fs, module.exports); + + if is_format_to_cjs { + if let Some(ns) = reference_builder + .module_analyzer_manager + .module_global_uniq_name + .namespace_name(reference_builder.source) + { + self.add_import( + &ImportSpecifierInfo::Namespace(ns), + reference_builder.source.clone().into(), + &reference_builder.bundle_variable, + )?; + } + } + + self.add_reference_export( + &ExportSpecifierInfo::All(None), + reference_builder.source.clone().into(), + reference_builder.module_system.clone(), + ); + } else if is_commonjs && redeclare_commonjs { + reexport_commonjs(reference_builder.source, self)?; + } else { + let export_names = &*reference_builder + .module_analyzer_manager + .get_export_names(reference_builder.source); + let export_type = export_names + .export_type + .merge(reference_builder.module_system.clone()); + + let is_hybrid_dynamic = matches!(export_type, ModuleSystem::Hybrid); + + // local export + { + // export named + for (export_as, local) in &export_names.export.named { + let is_default_key = reference_builder.bundle_variable.is_default_key(*export_as); + // reference_builder.bundle_variable.name(from) + + self.add_local_export( + &if is_default_key { + ExportSpecifierInfo::Default((*local).into()) + } else { + ExportSpecifierInfo::Named((*local, Some(*export_as)).into()) + }, + export_type.clone(), + ); + + if is_commonjs { + let imported = if is_default_key { + reference_builder + .module_analyzer_manager + .module_global_uniq_name + .default_name_result(reference_builder.module_id.to_string())? + } else { + *export_as + }; + + self.add_declare_commonjs_import( + &ImportSpecifierInfo::Named { + local: *local, + imported: Some(imported), + }, + reference_builder.source.clone().into(), + &reference_builder.bundle_variable, + )?; + } + } + + // export default + if let Some(item) = &export_names.export.default { + let is_default_key = reference_builder.bundle_variable.is_default_key(*item); + + self.add_local_export( + &ExportSpecifierInfo::Default(if is_default_key { + reference_builder + .module_analyzer_manager + .module_global_uniq_name + .default_name_result(reference_builder.source)? + } else { + *item + }), + export_type.clone(), + ); + + if is_commonjs { + self.add_declare_commonjs_import( + &ImportSpecifierInfo::Default(if is_default_key { + reference_builder + .module_analyzer_manager + .module_global_uniq_name + .default_name_result(reference_builder.source)? + } else { + *item + }), + reference_builder.source.clone().into(), + &reference_builder.bundle_variable, + )?; + } + } + } + + // reexport external | bundle + { + for (module_id, reference) in &export_names.reexport_map { + let is_external_source = reference_builder.is_external(module_id); + let is_commonjs_source = reference_builder.is_commonjs(module_id); + + if is_external_source { + // export named + for (from, export_as) in &reference.named { + self.add_reference_export( + &ExportSpecifierInfo::Named((*export_as, Some(*from)).into()), + module_id.clone().into(), + export_type.clone(), + ); + } + + // export default + if let Some(item) = &reference.default { + self.add_reference_export( + &ExportSpecifierInfo::Default(*item), + module_id.clone().into(), + export_type.clone(), + ); + } + + // reexport all + if reference.all { + if is_hybrid_dynamic && is_format_to_cjs { + self.add_import( + &ImportSpecifierInfo::Namespace( + reference_builder + .module_analyzer_manager + .module_global_uniq_name + .namespace_name(module_id) + .unwrap(), + ), + module_id.clone().into(), + &reference_builder.bundle_variable, + )?; + } + + self.add_reference_export( + &ExportSpecifierInfo::All(None), + module_id.clone().into(), + export_type.clone(), + ); + } + } else if is_commonjs_source { + reexport_commonjs(module_id, self)? + } + } + } + } + + Ok(()) + } + + // TODO: refactor module relation analyze + pub fn add_export_named(&mut self) {} + + pub fn add_reexport_named(&mut self) {} + + pub fn add_export_namespace(&mut self) {} + + pub fn add_reexport_namespace(&mut self) {} + + pub fn add_export_default(&mut self) {} + + pub fn add_reexport_default(&mut self) {} + + pub fn add_import_default(&mut self) {} + + pub fn add_import_named(&mut self) {} + + pub fn add_import_namespace(&mut self) {} +} + +#[derive(Debug, Default)] +pub struct BundleReferenceManager { + /// why use [ResourcePotId] as key? + /// + /// because use [ResourcePotId] as key can zip same export or import at Bundle + /// + /// but there is one place to be careful that entry module/bundle, it should export raw named + bundle_reference: HashMap>>, + bundle_reference1: HashMap>>, +} + +#[derive(Debug, Default)] +pub struct CombineBundleReference { + pub reexport_raw: BundleReference, + pub bundle_reference1: BundleReference, +} + +// TODO: improve logic +impl CombineBundleReference { + pub fn fetch( + &self, + module_id: &ModuleId, + module_analyzer_manager: &ModuleAnalyzerManager, + ) -> &BundleReference { + if module_analyzer_manager.is_entry(module_id) { + &self.reexport_raw + } else { + &self.bundle_reference1 + } + } + + pub fn fetch_mut( + &mut self, + module_id: &ModuleId, + module_analyzer_manager: &ModuleAnalyzerManager, + ) -> &mut BundleReference { + if module_analyzer_manager.is_entry(module_id) { + &mut self.reexport_raw + } else { + &mut self.bundle_reference1 + } + } + + pub fn query_redeclare_both(&mut self, module_id: &ModuleId) -> Option { + let mut bundle_reference = BundleReference::new(); + let reference_kind: ReferenceKind = module_id.clone().into(); + + let mut is_empty = true; + for item in [ + &self.bundle_reference1.redeclare_commonjs_import, + &self.reexport_raw.redeclare_commonjs_import, + ] { + if let Some(m) = item.get(&reference_kind) { + is_empty = false; + bundle_reference + .redeclare_commonjs_import + .entry(reference_kind.clone()) + .or_insert_with(|| ExternalReferenceImport::new()) + .extend(m); + }; + } + + // for item in [ + // &self.bundle_reference1.import_map, + // &self.reexport_raw.import_map, + // ] { + // if let Some(m) = item.get(&reference_kind) { + // is_empty = false; + // bundle_reference + // .import_map + // .entry(reference_kind.clone()) + // .or_insert_with(|| ExternalReferenceImport::new()) + // .extend(m); + // } + // } + + if is_empty { + None + } else { + Some(bundle_reference) + } + } + + pub fn query_all_redeclare(&self) -> CommonJsImportMap { + let mut bundle_reference = CommonJsImportMap::new(); + + for map in [ + &self.bundle_reference1.redeclare_commonjs_import, + &self.reexport_raw.redeclare_commonjs_import, + ] { + for (key, item) in map { + bundle_reference + .entry(key.clone()) + .or_insert_with(|| ExternalReferenceImport::new()) + .extend(item); + } + } + + bundle_reference + } +} + +impl BundleReferenceManager { + // import compress + pub fn reference_mut(&mut self, group_id: &ResourcePotId) -> Rc> { + Rc::clone(if self.bundle_reference.contains_key(group_id) { + self.bundle_reference.get(group_id).unwrap() + } else { + self + .bundle_reference + .entry(group_id.clone()) + .or_insert_with(|| Rc::new(RefCell::new(CombineBundleReference::default()))) + }) + } + + pub fn reference_mut_by_module( + &mut self, + module_id: &ModuleId, + module_analyzer_manager: &ModuleAnalyzerManager, + ) -> Rc> { + let group_id = module_analyzer_manager.group_id(module_id).unwrap(); + self.reference_mut(group_id) + } + + pub fn reference1_mut(&mut self, module_id: &ModuleId) -> Rc> { + Rc::clone(if self.bundle_reference1.contains_key(module_id) { + self.bundle_reference1.get(module_id).unwrap() + } else { + self + .bundle_reference1 + .entry(module_id.clone()) + .or_insert_with(|| Rc::new(RefCell::new(BundleReference::new()))) + }) + } +} + +pub struct ReferenceBuilder<'a> { + pub is_reference_by_another_bundle: bool, + pub module_analyzer_manager: &'a ModuleAnalyzerManager<'a>, + pub module_analyzer: &'a ModuleAnalyzer, + pub bundle_variable: &'a mut BundleVariable, + pub source: &'a ModuleId, + pub module_system: ModuleSystem, + pub config: &'a ShareBundleContext, + pub module_id: &'a ModuleId, +} + +impl<'a> ReferenceBuilder<'a> { + fn is_external(&self, module_id: &ModuleId) -> bool { + self.module_analyzer_manager.is_external(module_id) + || !self.module_analyzer_manager.contain(module_id) + } + + fn is_commonjs(&self, module_id: &ModuleId) -> bool { + self.module_analyzer_manager.is_commonjs(module_id) + } + + /// + /// ```ts + /// // moduleA.ts + /// export default 'a'; + /// ``` + /// + /// ```ts + /// // moduleB.ts + /// export default 'b'; + /// ``` + /// --- + /// + /// ```ts + /// + /// // entry bundle (entry module moduleA.ts) + /// export default module_a_default; + /// + /// // normal_bundle + /// export { module_a_default, module_b_default } + /// + /// // import bundle + /// import { module_a_default, module_b_default } from './normal_bundle' + /// ``` + pub fn reexport_name(&self, raw_export: usize, export_as: usize) -> usize { + if self.module_analyzer.entry { + raw_export + } else { + export_as + } + } +} diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_variable.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_variable.rs index edbeb779e..cff7b99db 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_variable.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_variable.rs @@ -1,16 +1,93 @@ +use std::mem; + +use farmfe_core::module::ModuleId; + use crate::resource_pot_to_bundle::uniq_name::BundleVariable; +use super::ModuleAnalyzerManager; + impl BundleVariable { - pub fn set_uniq_name_both(&mut self, v1: usize, v2: usize) { - self.set_var_uniq_rename(v1); - self.set_rename(v2, self.render_name(v1)); + pub fn set_uniq_name_both(&mut self, root: usize, local: usize) { + self.set_var_root(local, root); + self.set_var_uniq_rename(root); + self.set_rename(local, self.render_name(root)); } - pub fn set_rename_from_other_render_name(&mut self, target: usize, from: usize) { - self.set_rename(target, self.render_name(from)); + pub fn set_rename_from_other_render_name(&mut self, local: usize, root: usize) { + self.set_var_root(local, root); + let rendered_name = self.render_name(root); + self.set_rename(local, rendered_name); } pub fn set_rename_from_other_name(&mut self, target: usize, from: usize) { - self.set_rename(target, self.name(from)); + self.set_var_root(target, from); + let name = self.name(from); + self.set_rename(target, name); + } + + pub fn set_uniq_name_for_cross_bundle( + &mut self, + target: usize, + local: usize, + target_id: &ModuleId, + local_id: &ModuleId, + module_analyzer_manager: &ModuleAnalyzerManager, + ) { + if module_analyzer_manager.is_same_bundle(target_id, local_id) { + self.set_rename_from_other_name(target, local); + } else { + let m = module_analyzer_manager + .module_analyzer(target_id) + .map(|i| i.bundle_group_id.to_string()) + .unwrap(); + let prev_namespace = mem::replace(&mut self.namespace, m); + + self.set_var_uniq_rename(target); + + self.set_var_root(local, target); + + self.set_namespace(prev_namespace); + + self.set_var_uniq_rename(local); + } + } + + /// modules: + /// index.js a.js b.js + /// + /// relation: + /// index.js -> b.js + /// b.js -> a.js + /// + /// bundle: + /// index: index.js, a.js + /// b: b.js + /// + /// ```js + /// // b.js + /// import { named } from "./a"; + /// export { named as bundleBNamed } + /// + /// // index.js + /// import { bundleBNamed } from "./b"; + /// ``` + /// + /// 1. index(index.js) import bundleBNamed from b(b.js) + /// 2. b(b.js) import named from index(a.js) + /// + /// step1 should use index bundle var "named", rather than import from b reexport + /// + pub fn is_same_bundle_by_root( + &self, + index: usize, + group_id: &str, + module_analyzer_manager: &ModuleAnalyzerManager, + ) -> bool { + let root = self.var_or_root(index); + self.module_id_by_var_index(root.index).is_some_and(|m| { + module_analyzer_manager + .group_id(m) + .is_some_and(|r| r == &group_id) + }) } } diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/mod.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/mod.rs index 165a687df..7b6486dba 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/mod.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/mod.rs @@ -1,28 +1,29 @@ use std::{ collections::{HashMap, HashSet}, + fmt::Debug, mem::{self, replace}, sync::{Arc, Mutex, RwLock}, }; -use bundle_external::BundleReference; +use bundle_reference::{BundleReference, CommonJsImportMap, ReferenceKind}; use farmfe_core::{ config::external::ExternalConfig, context::CompilationContext, error::{CompilationError, MapCompletionError, Result}, farm_profile_function, farm_profile_scope, - module::{module_graph::ModuleGraph, ModuleId, ModuleSystem}, - plugin::ResolveKind, + module::{module_graph::ModuleGraph, ModuleId, ModuleMetaData, ModuleSystem}, rayon::iter::{IntoParallelIterator, ParallelIterator}, + resource::resource_pot::ResourcePotId, swc_common::{util::take::Take, SyntaxContext, DUMMY_SP}, swc_ecma_ast::{ self, BindingIdent, CallExpr, ClassDecl, Decl, EmptyStmt, Expr, ExprStmt, FnDecl, Ident, - Module, ModuleDecl, ModuleItem, Stmt, VarDecl, VarDeclarator, + Module as ModuleAst, ModuleDecl, ModuleItem, Stmt, VarDecl, VarDeclarator, }, }; -use farmfe_toolkit::{script::swc_try_with::try_with, swc_ecma_visit::VisitMutWith}; +use farmfe_toolkit::{itertools::Itertools, script::swc_try_with::try_with, swc_ecma_visit::VisitMutWith}; pub mod bundle_analyzer; -pub mod bundle_external; +pub mod bundle_reference; pub mod bundle_variable; pub mod reference; use crate::resource_pot_to_bundle::targets::{ @@ -40,9 +41,13 @@ use super::{ polyfill::SimplePolyfill, targets::generate::generate_namespace_by_reference_map, uniq_name::BundleVariable, + ShareBundleContext, ShareBundleOptions, FARM_BUNDLE_POLYFILL_SLOT, }; + +pub type ModuleMap = HashMap; + pub struct ModuleAnalyzerManager<'a> { - pub module_map: HashMap, + pub module_map: ModuleMap, pub namespace_modules: HashSet, /// @@ -71,7 +76,7 @@ pub struct ModuleAnalyzerManager<'a> { /// /// pub module_global_uniq_name: ModuleGlobalUniqName, - module_graph: &'a ModuleGraph, + pub module_graph: &'a ModuleGraph, } #[derive(Debug)] @@ -93,7 +98,7 @@ impl ModuleGlobalName { #[derive(Debug, Default)] pub struct ModuleGlobalUniqName { - module_map: HashMap, + module_map: HashMap, } impl ModuleGlobalUniqName { @@ -103,41 +108,71 @@ impl ModuleGlobalUniqName { } } - pub fn namespace_name(&self, module_id: &ModuleId) -> Option { + pub fn namespace_name>(&self, module_id: R) -> Option { self .module_map - .get(module_id) + .get(&module_id.into()) .and_then(|item| item.namespace) } - pub fn default_name(&self, module_id: &ModuleId) -> Option { - self.module_map.get(module_id).and_then(|item| item.default) + pub fn default_name>(&self, module_id: R) -> Option { + self + .module_map + .get(&module_id.into()) + .and_then(|item| item.default) } - pub fn commonjs_name(&self, module_id: &ModuleId) -> Option { + pub fn commonjs_name>(&self, module_id: R) -> Option { self .module_map - .get(module_id) + .get(&module_id.into()) .and_then(|item| item.commonjs) } - pub fn default_name_result(&self, module_id: &ModuleId) -> Result { + pub fn namespace_name_result + Debug + Clone>( + &self, + module_id: R, + ) -> Result { + Ok(self.namespace_name(module_id.clone()).unwrap()) + } + + pub fn commonjs_name_result + Debug + Clone>( + &self, + module_id: R, + ) -> Result { self - .default_name(module_id) - .to_result("not found module {:?} default name") + .commonjs_name(module_id.clone()) + .to_result(format!("not found module commonjs name by {:?}", module_id)) } - fn entry_module(&mut self, module_id: &ModuleId) -> &mut ModuleGlobalName { - if !self.module_map.contains_key(module_id) { + pub fn default_name_result + Debug + Clone>( + &self, + module_id: R, + ) -> Result { + Ok( + self + .default_name(module_id.clone()) + .expect(format!("not found module default name by {:?}", module_id).as_str()), + ) + // .to_result(format!("not found module default name by {:?}", module_id)) + } + + fn entry_module>(&mut self, module_id: R) -> &mut ModuleGlobalName { + let reference_kind = module_id.into(); + if !self.module_map.contains_key(&reference_kind) { self .module_map - .insert(module_id.clone(), ModuleGlobalName::new()); + .insert(reference_kind.clone(), ModuleGlobalName::new()); } - self.module_map.get_mut(module_id).unwrap() + self.module_map.get_mut(&reference_kind).unwrap() } - fn add_namespace usize>(&mut self, module_id: &ModuleId, v: F) { + fn add_namespace usize, R: Into>( + &mut self, + module_id: R, + v: F, + ) { let m = self.entry_module(module_id); if m.namespace.is_none() { @@ -145,7 +180,7 @@ impl ModuleGlobalUniqName { } } - fn add_default usize>(&mut self, module_id: &ModuleId, v: F) { + fn add_default usize, R: Into>(&mut self, module_id: R, v: F) { let m = self.entry_module(module_id); if m.default.is_none() { @@ -153,7 +188,7 @@ impl ModuleGlobalUniqName { } } - fn add_commonjs usize>(&mut self, module_id: &ModuleId, v: F) { + fn add_commonjs usize, R: Into>(&mut self, module_id: R, v: F) { let m = self.entry_module(module_id); if m.commonjs.is_none() { @@ -178,6 +213,12 @@ impl<'a> ModuleAnalyzerManager<'a> { } } + pub fn polyfill_resource_pot(&self) -> Option { + self + .module_analyzer(&ModuleId::from(FARM_BUNDLE_POLYFILL_SLOT)) + .and_then(|m| Some(m.bundle_group_id.clone())) + } + pub fn extract_modules_statements( &mut self, modules: &Vec<&ModuleId>, @@ -195,13 +236,20 @@ impl<'a> ModuleAnalyzerManager<'a> { .collect::>>>() }; + let index = bundle_variable.index.clone(); + let module_order_map = bundle_variable.module_order_map.clone(); + let module_order_index_set = bundle_variable.module_order_index_set.clone(); + modules.into_par_iter().try_for_each(|module_id| { let mut module_analyzer = module_map .get(module_id) .map(|item| item.write().unwrap()) .unwrap(); - let mut new_bundle_variable = bundle_variable.branch(); - new_bundle_variable.set_namespace(module_analyzer.resource_pot_id.clone()); + let mut new_bundle_variable = + BundleVariable::branch(&index, &module_order_map, &module_order_index_set); + + new_bundle_variable.set_namespace(module_analyzer.bundle_group_id.clone()); + farm_profile_scope!(format!( "extract module statement: {:?}", module_id.to_string() @@ -241,8 +289,18 @@ impl<'a> ModuleAnalyzerManager<'a> { self .module_map .get(module_id) - .map(|item| item.is_commonjs()) - .unwrap_or(false) + .is_some_and(|item| item.is_commonjs()) + || self.module_graph.module(module_id).is_some_and(|m| { + if matches!(m.meta.as_ref(), ModuleMetaData::Script(_)) { + let s = m.meta.as_script(); + matches!( + s.module_system, + ModuleSystem::CommonJs | ModuleSystem::Hybrid + ) + } else { + false + } + }) } #[inline] @@ -251,15 +309,29 @@ impl<'a> ModuleAnalyzerManager<'a> { .module_map .get(module_id) .map(|item| item.entry) - .unwrap_or(false) + .is_some_and(|v| v) + || self.module_graph.entries.contains_key(module_id) } pub fn module_system(&self, module_id: &ModuleId) -> ModuleSystem { self .module_map .get(module_id) - .map(|item| item.module_system.clone()) - .unwrap() + .map(|item| Some(item.module_system.clone())) + .unwrap_or_else(|| { + self.module_graph.module(module_id).map(|m| { + let script = m.meta.as_script(); + + script.module_system.clone() + }) + }) + .expect( + format!( + "expect ModuleSystem of module \"{}\", but not found.", + module_id.to_string() + ) + .as_str(), + ) } pub fn is_hybrid_or_esm(&self, module_id: &ModuleId) -> bool { @@ -284,6 +356,16 @@ impl<'a> ModuleAnalyzerManager<'a> { self.module_map.get(module_id) } + #[inline] + pub fn contain(&self, module_id: &ModuleId) -> bool { + self.module_map.contains_key(module_id) + } + + #[inline] + pub fn group_id(&self, module_id: &ModuleId) -> Option<&ResourcePotId> { + self.module_map.get(module_id).map(|m| &m.bundle_group_id) + } + #[inline] pub fn module_analyzer_unchecked(&self, module_id: &ModuleId) -> &ModuleAnalyzer { &self.module_map[module_id] @@ -313,33 +395,23 @@ impl<'a> ModuleAnalyzerManager<'a> { } #[inline] - pub fn set_ast(&mut self, module_id: &ModuleId, ast_body: Module) { + pub fn set_ast(&mut self, module_id: &ModuleId, ast_body: ModuleAst) { self.module_analyzer_mut_unchecked(module_id).ast = ast_body; } - pub fn module_analyzer_by_source( - &self, - module_id: &ModuleId, - source: &str, - ) -> Option<&ModuleAnalyzer> { - if let Some(m) = self.module_graph.get_dep_by_source_optional( - module_id, - source, - Some(ResolveKind::DynamicImport), - ) { - return self.module_map.get(&m); - } - - None - } - pub fn is_same_bundle(&self, a: &ModuleId, b: &ModuleId) -> bool { match (self.module_analyzer(a), self.module_analyzer(b)) { - (Some(a), Some(b)) => a.resource_pot_id == b.resource_pot_id, + (Some(a), Some(b)) => a.bundle_group_id == b.bundle_group_id, _ => false, } } + pub fn is_same_bundle_by_bundle(&self, source: &ModuleId, name: &str) -> bool { + self + .module_analyzer(source) + .is_some_and(|m| m.bundle_group_id == name) + } + #[inline] pub fn is_contain_namespace(&self, module_id: &ModuleId) -> bool { self @@ -386,7 +458,7 @@ impl<'a> ModuleAnalyzerManager<'a> { for export in exports_stmts { for specify in export.specifiers.iter() { if let Some(ref source) = export.source { - if self.is_external(source) { + if self.is_external(source) || !self.contain(source) { map.add_reference(source, specify); continue; } @@ -405,6 +477,8 @@ impl<'a> ModuleAnalyzerManager<'a> { ExportSpecifierInfo::Named(export) => { let export_map = self.build_export_names(source, bundle_variable); if let Some(i) = export_map.query(export.export_from(), bundle_variable) { + // bundle_variable.set_var_root(export.export_as(), i); + map.add_local(&ExportSpecifierInfo::Named( (i, Some(export.export_as())).into(), )) @@ -433,10 +507,6 @@ impl<'a> ModuleAnalyzerManager<'a> { } } - if self.is_commonjs(module_id) && self.module_analyzer(module_id).is_some_and(|m| m.entry) { - // map - } - if let Some(m) = self.module_analyzer_mut(module_id) { m.export_names = Some(Arc::new(map)); } @@ -448,13 +518,13 @@ impl<'a> ModuleAnalyzerManager<'a> { &mut self, module_id: &ModuleId, context: &Arc, - module_graph: &ModuleGraph, bundle_variable: &mut BundleVariable, bundle_reference: &mut BundleReference, commonjs_import_executed: &mut HashSet, order_index_map: &HashMap, polyfill: &mut SimplePolyfill, external_config: &ExternalConfig, + options: &ShareBundleContext, ) -> Result<()> { farm_profile_function!(format!( "patch module analyzer ast: {}", @@ -467,16 +537,14 @@ impl<'a> ModuleAnalyzerManager<'a> { module_id, context, bundle_variable, - module_graph, namespace, bundle_reference, commonjs_import_executed, order_index_map, polyfill, external_config, - )?; - - Ok(()) + options, + ) } fn patch_namespace( @@ -514,6 +582,7 @@ impl<'a> ModuleAnalyzerManager<'a> { module_id: &ModuleId, bundle_variable: &BundleVariable, commonjs_import_executed: &mut HashSet, + ctx: &ShareBundleContext, ) { let module_analyzer = self.module_analyzer_mut_unchecked(module_id); let mut stmt_actions = module_analyzer @@ -524,120 +593,132 @@ impl<'a> ModuleAnalyzerManager<'a> { stmt_actions.sort_by_key(|a| std::cmp::Reverse(a.index())); let mut ast = module_analyzer.ast.take(); - stmt_actions.iter().for_each(|action| { - let mut replace_ast_item = |index: usize| { - replace(&mut ast.body[index], ModuleItem::Stmt(Stmt::Empty(EmptyStmt { span: DUMMY_SP }))) - }; + for action in &stmt_actions { + let mut replace_ast_item = |index: usize| { + replace( + &mut ast.body[index], + ModuleItem::Stmt(Stmt::Empty(EmptyStmt { span: DUMMY_SP })), + ) + }; - match action { - StmtAction::StripExport(index) => { - if let ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export_decl)) = replace_ast_item(*index) { - ast.body[*index] = ModuleItem::Stmt(Stmt::Decl(export_decl.decl)) - } - }, - - StmtAction::StripDefaultExport(index, rename) => { - if let ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(export_decl)) = replace_ast_item(*index) { - let rendered_name = bundle_variable.render_name(*rename); - ast.body[*index] = ModuleItem::Stmt(Stmt::Decl(match export_decl.decl { - swc_ecma_ast::DefaultDecl::Class(class) => { - Decl::Class( - ClassDecl { - ident: Ident::from(rendered_name.as_str()), - declare: false, - class: class.class, - }, - ) - }, - swc_ecma_ast::DefaultDecl::Fn(f) => { - Decl::Fn(FnDecl { - ident: Ident::from(rendered_name.as_str()), - declare: false, - function: f.function, - }) - }, - _ => { - unreachable!( - "export_default_decl.decl should not be anything clone() other than a class, function" - ) - }, - })); - } - } + match action { + StmtAction::StripExport(index) => { + if let ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export_decl)) = + replace_ast_item(*index) + { + ast.body[*index] = ModuleItem::Stmt(Stmt::Decl(export_decl.decl)) + } + } - StmtAction::DeclDefaultExpr(index, var) => { - match replace_ast_item(*index) { - ModuleItem::ModuleDecl(decl) => { - match decl { - ModuleDecl::ExportDefaultDecl(export) => { - let default_name = bundle_variable.render_name(self.module_global_uniq_name.default_name(module_id).unwrap()); - match export.decl { - swc_ecma_ast::DefaultDecl::Class(class) => { - ast.body[*index] = ModuleItem::Stmt(Stmt::Decl(Decl::Class(ClassDecl { - ident: Ident::from(default_name.as_str()), - declare: false, - class: class.class, - }))); - }, - swc_ecma_ast::DefaultDecl::Fn(f) => { - ast.body[*index] = ModuleItem::Stmt(Stmt::Decl(Decl::Fn(FnDecl { - ident: Ident::from(default_name.as_str()), - declare: false, - function: f.function, - }))); - }, - _ => { - unreachable!("ExportDefault should not be anything other than a class, function") - } - } - }, - ModuleDecl::ExportDefaultExpr(export_default_decl) => { - ast.body[*index] = - ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { - span: DUMMY_SP, - kind: swc_ecma_ast::VarDeclKind::Var, - declare: false, - decls: vec![VarDeclarator { - span: DUMMY_SP, - name: swc_ecma_ast::Pat::Ident(BindingIdent { - id: Ident::from(bundle_variable.render_name(*var).as_str()), - type_ann: None, - }), - init: Some(export_default_decl.expr), - definite: false, - }], - ctxt: SyntaxContext::empty() - })))); - }, - _ => {} - } - }, - _ => { - unreachable!("ExportDefault should not be anything other than a class, function"); - } - } + StmtAction::StripDefaultExport(index, rename) => { + if let ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(export_decl)) = + replace_ast_item(*index) + { + let rendered_name = bundle_variable.render_name(*rename); + ast.body[*index] = ModuleItem::Stmt(Stmt::Decl(match export_decl.decl { + swc_ecma_ast::DefaultDecl::Class(class) => Decl::Class(ClassDecl { + ident: Ident::from(rendered_name.as_str()), + declare: false, + class: class.class, + }), + swc_ecma_ast::DefaultDecl::Fn(f) => Decl::Fn(FnDecl { + ident: Ident::from(rendered_name.as_str()), + declare: false, + function: f.function, + }), + _ => { + unreachable!( + "export_default_decl.decl should not be anything clone() other than a class, function" + ) } + })); + } + } - StmtAction::StripCjsImport(index, import_execute_module) => { - replace_ast_item(*index); - if let Some(source) = import_execute_module { - if !commonjs_import_executed.contains(source) { - ast.body[*index] = ModuleItem::Stmt(Stmt::Expr( - ExprStmt { span: DUMMY_SP, expr: Box::new(Expr::Call( - CallExpr { span: DUMMY_SP, callee: swc_ecma_ast::Callee::Expr(Box::new(Expr::Ident(bundle_variable.name(self.module_global_uniq_name.commonjs_name(source).unwrap()).as_str().into()))), args: vec![], type_args: None, ctxt: SyntaxContext::empty() } - )) } - )); - commonjs_import_executed.insert(source.clone()); - } + StmtAction::DeclDefaultExpr(index, var) => match replace_ast_item(*index) { + ModuleItem::ModuleDecl(decl) => match decl { + ModuleDecl::ExportDefaultDecl(export) => { + let default_name = bundle_variable.render_name( + self + .module_global_uniq_name + .default_name(module_id) + .unwrap(), + ); + match export.decl { + swc_ecma_ast::DefaultDecl::Class(class) => { + ast.body[*index] = ModuleItem::Stmt(Stmt::Decl(Decl::Class(ClassDecl { + ident: Ident::from(default_name.as_str()), + declare: false, + class: class.class, + }))); + } + swc_ecma_ast::DefaultDecl::Fn(f) => { + ast.body[*index] = ModuleItem::Stmt(Stmt::Decl(Decl::Fn(FnDecl { + ident: Ident::from(default_name.as_str()), + declare: false, + function: f.function, + }))); + } + _ => { + unreachable!("ExportDefault should not be anything other than a class, function") } } - - StmtAction::RemoveImport(index) => { - replace_ast_item(*index); + } + ModuleDecl::ExportDefaultExpr(export_default_decl) => { + ast.body[*index] = ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { + ctxt: SyntaxContext::empty(), + span: DUMMY_SP, + kind: swc_ecma_ast::VarDeclKind::Var, + declare: false, + decls: vec![VarDeclarator { + span: DUMMY_SP, + name: swc_ecma_ast::Pat::Ident(BindingIdent { + id: Ident::from(bundle_variable.render_name(*var).as_str()), + type_ann: None, + }), + init: Some(export_default_decl.expr), + definite: false, + }], + })))); + } + _ => {} + }, + _ => { + unreachable!("ExportDefault should not be anything other than a class, function"); + } + }, + + StmtAction::StripCjsImport(index, import_execute_module) => { + replace_ast_item(*index); + if let Some(source) = import_execute_module { + if !commonjs_import_executed.contains(source) { + if self.contain(source) { + ast.body[*index] = ModuleItem::Stmt(Stmt::Expr(ExprStmt { + span: DUMMY_SP, + expr: Box::new(Expr::Call(CallExpr { + ctxt: SyntaxContext::empty(), + span: DUMMY_SP, + callee: swc_ecma_ast::Callee::Expr(Box::new(Expr::Ident( + bundle_variable + .name(self.module_global_uniq_name.commonjs_name(source).unwrap()) + .as_str() + .into(), + ))), + args: vec![], + type_args: None, + })), + })); + commonjs_import_executed.insert(source.clone()); } } + } + } - }); + StmtAction::RemoveImport(index) => { + replace_ast_item(*index); + } + } + } let module_analyzer = self.module_analyzer_mut_unchecked(module_id); module_analyzer.ast = ast; @@ -648,13 +729,13 @@ impl<'a> ModuleAnalyzerManager<'a> { module_id: &ModuleId, context: &Arc, bundle_variable: &mut BundleVariable, - module_graph: &ModuleGraph, namespace: Option, bundle_reference: &mut BundleReference, commonjs_import_executed: &mut HashSet, order_index_map: &HashMap, polyfill: &mut SimplePolyfill, external_config: &ExternalConfig, + ctx: &ShareBundleContext, ) -> Result<()> { farm_profile_function!(""); @@ -667,8 +748,8 @@ impl<'a> ModuleAnalyzerManager<'a> { let cm = module_analyzer.cm.clone(); try_with(cm, &context.meta.script.globals, || { - // 1. strip/remove export - self.strip_module_decl(module_id, bundle_variable, commonjs_import_executed); + // 1. strip/remove export/import + self.strip_module_decl(module_id, bundle_variable, commonjs_import_executed, ctx); let mut patch_asts = vec![]; @@ -687,26 +768,25 @@ impl<'a> ModuleAnalyzerManager<'a> { .unwrap(); // 3. process hybrid module or commonjs - CjsPatch::patch_cjs_module( + CjsPatch::transform_hybrid_or_commonjs_to_esm( self, module_id, - module_graph, context, - &mut patch_asts, bundle_variable, bundle_reference, polyfill, - ); + ctx, + ) + .unwrap(); // 1. append ast // 2. replace commonjs require // 3. rename { let module_analyzer = self.module_analyzer_mut_unchecked(module_id); + let mark = module_analyzer.mark.clone(); let mut ast = module_analyzer.ast.take(); - let rename_map = module_analyzer.build_rename_map(bundle_variable); - ast.body.extend(patch_asts); if matches!( @@ -714,16 +794,19 @@ impl<'a> ModuleAnalyzerManager<'a> { ModuleSystem::CommonJs | ModuleSystem::Hybrid ) { CjsPatch::replace_cjs_require( - module_analyzer.mark, + mark, &mut ast, module_id, - module_graph, - &self.module_global_uniq_name, bundle_variable, &context.config, polyfill, external_config, - ) + bundle_reference, + &self.module_graph, + &self.module_global_uniq_name, + &self.module_map, + ctx, + ); } ast.body = mem::take(&mut ast.body) @@ -738,10 +821,9 @@ impl<'a> ModuleAnalyzerManager<'a> { self, module_id, bundle_variable, + ctx, )); - ast.visit_mut_with(&mut RenameIdent::new(rename_map)); - self.set_ast(module_id, ast); } }) @@ -750,17 +832,48 @@ impl<'a> ModuleAnalyzerManager<'a> { Ok(()) } + pub fn patch_rename( + &mut self, + module_id: &ModuleId, + context: &Arc, + bundle_variable: &mut BundleVariable, + commonjs_import_map: &CommonJsImportMap, + ) { + let module_analyzer = self.module_analyzer_mut_unchecked(module_id); + + let cm = module_analyzer.cm.clone(); + let mut ast = module_analyzer.ast.take(); + + try_with(cm, &context.meta.script.globals, || { + let module_analyzer = self.module_analyzer_unchecked(module_id); + + let rename_map = module_analyzer.build_rename_map(bundle_variable, commonjs_import_map); + ast.visit_mut_with(&mut RenameIdent::new(rename_map, &bundle_variable, self)); + + self.set_ast(module_id, ast); + }) + .unwrap(); + } + pub fn link( &mut self, bundle_variable: &mut BundleVariable, order_index_map: &HashMap, context: &Arc, + ordered_groups_id: &Vec, ) { farm_profile_scope!("link module analyzer"); let root = &context.config.root; - let mut ordered_module_ids = order_index_map.keys().collect::>(); + let ordered_module_ids = order_index_map + .keys() + .sorted_by_key(|a| order_index_map[a]) + .collect::>(); - ordered_module_ids.sort_by(|a, b| order_index_map[b].cmp(&order_index_map[a])); + for group_id in ordered_groups_id { + self.module_global_uniq_name.add_namespace(group_id, |v| { + bundle_variable.register_common_used_name(v, &group_id) + }); + } for module_id in ordered_module_ids { if self.module_map.contains_key(module_id) { @@ -776,12 +889,17 @@ impl<'a> ModuleAnalyzerManager<'a> { module_analyzer.module_id.to_string() )); - bundle_variable.set_namespace(module_analyzer.resource_pot_id.clone()); + bundle_variable.set_namespace(module_analyzer.bundle_group_id.clone()); // in this time, it import by cjs require if self.namespace_modules.contains(&module_analyzer.module_id) || self.is_external(&module_analyzer.module_id) - || self.module_graph.is_dynamic(module_id) + || (module_analyzer.is_dynamic + && self + .module_graph + .dependents_ids(&module_analyzer.module_id) + .iter() + .any(|importer| self.is_same_bundle(module_id, importer))) { self .module_global_uniq_name @@ -845,13 +963,12 @@ impl<'a> ModuleAnalyzerManager<'a> { for specify in &s.specifiers { match specify { ExportSpecifierInfo::Default(n) => { - if bundle_variable.name(*n) == "default" { - self - .module_global_uniq_name - .add_default(&module_analyzer.module_id, |s| { - bundle_variable.register_used_name_by_module_id(&module_analyzer.module_id, s, root) - }); - } + // TODO: only add default when it is export default expression e.g: export default 1 + 1 + self + .module_global_uniq_name + .add_default(&module_analyzer.module_id, |s| { + bundle_variable.register_used_name_by_module_id(&module_analyzer.module_id, s, root) + }); } ExportSpecifierInfo::Namespace(_) | diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/reference.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/reference.rs index 29b4ff212..08cd6de35 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/reference.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/reference.rs @@ -81,7 +81,7 @@ impl ReferenceExport { self.named.is_empty() && self.default.is_none() && !self.all && self.namespace.is_none() } - pub fn query(&self, export_from: &String, bundle_variable: &BundleVariable) -> Option { + pub fn query(&self, export_from: &str, bundle_variable: &BundleVariable) -> Option { if let Some(index) = self.namespace { if &bundle_variable.name(index) == export_from { return Some(index); @@ -99,11 +99,11 @@ impl ReferenceExport { pub fn raw_query( &self, - export_from: &String, + export_from: &str, bundle_variable: &BundleVariable, find_default: bool, ) -> Option { - if find_default { + if find_default && self.default.is_some() { return self.default; } @@ -125,28 +125,33 @@ impl ReferenceExport { #[derive(Debug, Clone)] pub struct ReferenceMap { - pub reference_map: HashMap, + pub reexport_map: HashMap, pub export: ReferenceExport, pub export_type: ModuleSystem, } +pub struct ReferenceQueryResult { + pub index: usize, + pub is_reexport: bool, +} + impl ReferenceMap { pub fn new(module_system: ModuleSystem) -> Self { Self { export: ReferenceExport::default(), - reference_map: Default::default(), + reexport_map: Default::default(), export_type: module_system, } } pub fn add_reference(&mut self, module_id: &ModuleId, export: &ExportSpecifierInfo) { - if !self.reference_map.contains_key(module_id) { + if !self.reexport_map.contains_key(module_id) { self - .reference_map + .reexport_map .insert(module_id.clone(), ReferenceExport::new()); } - let reference = self.reference_map.get_mut(module_id).unwrap(); + let reference = self.reexport_map.get_mut(module_id).unwrap(); reference.insert(export); } @@ -159,24 +164,29 @@ impl ReferenceMap { self.export.insert(export); } - pub fn query_by_var_str( + pub fn query_by_var_str_and_meta( &self, export_from: &String, bundle_variable: &BundleVariable, - ) -> Option { + ) -> Option { if let Some(r) = self.export.query(export_from, bundle_variable) { - Some(r) + Some(ReferenceQueryResult { + index: r, + is_reexport: false, + }) } else { self - .reference_map + .reexport_map .values() .find_map(|item| item.query(export_from, bundle_variable)) + .map(|r| ReferenceQueryResult { + index: r, + is_reexport: true, + }) } } - pub fn query(&self, index: usize, bundle_variable: &BundleVariable) -> Option { - let export_from = bundle_variable.name(index); - + pub fn query_by_str(&self, export_from: &str, bundle_variable: &BundleVariable) -> Option { let find_default = export_from == "default"; if let Some(r) = self @@ -186,21 +196,27 @@ impl ReferenceMap { Some(r) } else { self - .reference_map + .reexport_map .values() .find_map(|item| item.query(&export_from, bundle_variable)) } } + pub fn query(&self, index: usize, bundle_variable: &BundleVariable) -> Option { + let export_from = bundle_variable.name(index); + + self.query_by_str(&export_from, bundle_variable) + } + pub fn extends(&mut self, other: &ReferenceMap) { - for item in &other.reference_map { - if !self.reference_map.contains_key(item.0) { + for item in &other.reexport_map { + if !self.reexport_map.contains_key(item.0) { self - .reference_map + .reexport_map .insert(item.0.clone(), ReferenceExport::new()); } - if let Some(map) = self.reference_map.get_mut(item.0) { + if let Some(map) = self.reexport_map.get_mut(item.0) { map.merge_by_export_all(item.1); } } @@ -243,7 +259,7 @@ impl ReferenceMap { }; print_export(&self.export, None); - for (module_id, reference) in &self.reference_map { + for (module_id, reference) in &self.reexport_map { print_export(reference, Some(module_id)); } } diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/common.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/common.rs index 923bbb212..4f09fe8d6 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/common.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/common.rs @@ -29,7 +29,7 @@ pub fn get_module_mark( } } -pub fn parse_module_item(string: &str) -> Result { +pub fn parse_module_item(string: &str) -> Result> { let (_, source_file) = create_swc_source_map(Source { path: PathBuf::from("unknown"), content: Arc::new(string.to_string()), @@ -47,11 +47,12 @@ pub fn parse_module_item(string: &str) -> Result { let mut parser = Parser::new_from(lexer); parser - .parse_module_item() + .parse_module() .map_err(|msg| CompilationError::ParseError { resolved_path: "unknown temp parser".to_string(), msg: format!("failed parse content, cause: {msg:#?}"), }) + .map(|i| i.body) } pub trait OptionToResult { @@ -66,3 +67,14 @@ impl OptionToResult for std::option::Option { } } } + +pub const FARM_BUNDLE_REFERENCE_SLOT_PREFIX: &str = "__FARM_BUNDLE_REFERENCE_SLOT__:"; +pub const FARM_BUNDLE_POLYFILL_SLOT: &str = "__FARM_BUNDLE_POLYFILL_SLOT__"; + +// TODO: replace bundle reference slot +pub fn with_bundle_reference_slot_name(reference_id: &String, contain_slot: bool) -> String { + if !contain_slot { + return reference_id.clone(); + } + format!("{}(({}))", FARM_BUNDLE_REFERENCE_SLOT_PREFIX, reference_id) +} diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/config.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/config.rs new file mode 100644 index 000000000..937972588 --- /dev/null +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/config.rs @@ -0,0 +1,102 @@ +use std::sync::Arc; + +use farmfe_core::{ + config::{Mode, ModuleFormat}, + context::CompilationContext, + module::ModuleId, +}; +use farmfe_toolkit::script::module2cjs::RuntimeCalleeAllocator; + +use super::targets::util::ShareBundleRuntimeCalleeAllocator; + +/// +/// +/// ```js +/// // farm.config.js +/// { +/// alias: { +/// "react": "node_modules/react/index.js" +/// } +/// } +/// ``` +/// +/// ```js +/// // index.js +/// import React from "react"; +/// ``` +/// +/// after ShareBundle import generate +/// ```js +/// import React from "node_modules/react/index.js"; +/// ``` +/// +/// but in non-full ShareBundle render, cannot find it +/// + +pub struct ShareBundleOptions { + /// whether to use reference slot + /// + /// `true`: + /// ```js + /// require("__FARM_BUNDLE_REFERENCE_SLOT__(({bundle_group_id}))") + /// ``` + /// + /// `false`: + /// ```js + /// require("{bundle_group_id}") + /// ``` + pub reference_slot: bool, + + /// require("external") + pub ignore_external_polyfill: bool, + + /// in non-full ShareBundle render, maybe not that transform by config.output.format + pub format: ModuleFormat, + /// hash paths other than external + pub hash_path: bool, + + pub concatenation_module: bool, + pub allocator: Option>, +} + +impl Default for ShareBundleOptions { + fn default() -> Self { + Self { + reference_slot: true, + ignore_external_polyfill: false, + hash_path: false, + format: ModuleFormat::EsModule, + concatenation_module: false, + allocator: None, + } + } +} + +pub struct ShareBundleContext { + pub options: ShareBundleOptions, + pub context: Arc, + pub allocator: Box, +} + +impl ShareBundleContext { + pub fn format(&self, module_id: &ModuleId) -> String { + if self.options.hash_path { + module_id.id(self.context.config.mode.clone()) + } else { + module_id.to_string() + } + } + + pub fn new(mut options: ShareBundleOptions, context: &Arc) -> Self { + let allocator = options + .allocator + .take() + .unwrap_or_else(|| Box::new(ShareBundleRuntimeCalleeAllocator::new())); + + Self { + options, + context: Arc::clone(context), + allocator, + } + } +} diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/defined_idents_collector.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/defined_idents_collector.rs index b9198a43c..fd5c62409 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/defined_idents_collector.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/defined_idents_collector.rs @@ -1,11 +1,12 @@ -use std::collections::{HashMap, HashSet}; +use std::{ + cell::RefCell, + collections::{HashMap, HashSet}, +}; use farmfe_core::{ swc_common::DUMMY_SP, swc_ecma_ast::{ - AssignExpr, AssignOp, AssignTarget, BindingIdent, Expr, Id, IdentName, KeyValuePatProp, - KeyValueProp, MemberProp, ObjectPat, ObjectPatProp, Pat, Prop, PropName, PropOrSpread, - SimpleAssignTarget, + AssignExpr, AssignOp, AssignTarget, BindingIdent, Expr, Id, IdentName, KeyValuePatProp, KeyValueProp, MemberProp, ObjectPat, ObjectPatProp, Pat, Prop, PropName, PropOrSpread, SimpleAssignTarget }, }; use farmfe_toolkit::{ @@ -70,20 +71,39 @@ impl Visit for DefinedIdentsCollector { use farmfe_core::swc_ecma_ast::Ident; -use super::Var; +use super::{ + bundle::ModuleAnalyzerManager, modules_analyzer::module_analyzer::VarRefKey, + uniq_name::BundleVariable, +}; + +type RenameMap<'a> = HashMap, usize>; -#[derive(Debug, Default)] +// #[derive(Debug)] pub struct RenameIdent<'a> { - map: HashMap<&'a Id, &'a Var>, + map: RenameMap<'a>, + bundle_variable: &'a BundleVariable, + module_analyzer_manager: &'a ModuleAnalyzerManager<'a>, } impl<'a> RenameIdent<'a> { - pub fn new(map: HashMap<&'a Id, &'a Var>) -> Self { - Self { map } + pub fn new( + map: RenameMap<'a>, + bundle_variable: &'a BundleVariable, + module_analyzer_manager: &'a ModuleAnalyzerManager<'a>, + ) -> Self { + Self { + map, + bundle_variable, + module_analyzer_manager, + } } fn rename(&self, ident: &Ident) -> Option { - self.map.get(&ident.to_id()).map(|var| var.render_name()) + let r = RefCell::new(ident.to_id()); + let v = self.map.get(&(r.borrow().into())).map(|var| { + return self.bundle_variable.render_name(*var); + }); + v } } diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/mod.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/mod.rs index 8b28ae0ea..07f21476a 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/mod.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/mod.rs @@ -6,6 +6,7 @@ use std::{ sync::{Arc, Mutex}, }; +use bundle::bundle_reference::BundleReferenceManager; use farmfe_core::{ context::CompilationContext, enhanced_magic_string::bundle::Bundle, @@ -27,15 +28,23 @@ use self::{ mod bundle; mod common; +mod config; mod defined_idents_collector; mod modules_analyzer; mod targets; +pub use common::{FARM_BUNDLE_POLYFILL_SLOT, FARM_BUNDLE_REFERENCE_SLOT_PREFIX}; +pub use config::*; #[derive(Debug, Default, PartialEq, Eq)] pub struct Var { var: Id, rename: Option, removed: bool, + root: Option, + module_id: Option, + index: usize, + // only for uniq name + placeholder: bool, } impl Var { @@ -72,77 +81,104 @@ pub type BundleMap<'a> = HashMap>; pub struct SharedBundle<'a> { pub bundle_map: BundleMap<'a>, + bundle_reference: BundleReferenceManager, module_analyzer_manager: ModuleAnalyzerManager<'a>, module_graph: &'a ModuleGraph, - context: &'a Arc, pub bundle_variables: Rc>, - order_index_map: HashMap, - order_resource_pot: Vec, + // TODO: try use moduleId ref instead of clone + ordered_module_index: Arc>, + ordered_groups_id: Vec, + context: ShareBundleContext, +} + +// TODO: use ref instead of clone +pub struct BundleGroup<'a> { + /// unique id + pub id: String, + /// module_id array + pub modules: Vec<&'a ModuleId>, + /// entry module + pub entry_module: Option, + /// bundle type + pub group_type: ResourcePotType, +} + +impl<'a> From<&'a ResourcePot> for BundleGroup<'a> { + fn from(value: &'a ResourcePot) -> Self { + Self { + id: value.id.clone(), + modules: value.modules(), + entry_module: value.entry_module.clone(), + group_type: value.resource_pot_type.clone(), + } + } } /// /// TODO: -/// 1. multiple bundle -/// 2. dynamic bundle -/// 3. multiple environment process +/// 1. multiple environment process +/// - browser polyfill /// impl<'a> SharedBundle<'a> { pub fn new( - resource_pots: Vec<&'a ResourcePot>, + bundle_groups: Vec>, module_graph: &'a ModuleGraph, context: &'a Arc, + options: Option, ) -> Result { farm_profile_function!("shared bundle initial"); + let options = options.unwrap_or_default(); + + let context = ShareBundleContext::new(options, &context); + let module_analyzer_map: Mutex> = Mutex::new(HashMap::new()); let mut bundle_map: HashMap = HashMap::new(); let bundle_variables = Rc::new(RefCell::new(BundleVariable::new())); let (toposort_modules, _) = module_graph.toposort(); - let mut order_resource_pot = vec![]; - let order_map: HashMap = toposort_modules - .into_iter() - .enumerate() - .map(|item| (item.1, item.0)) - .collect(); + let mut ordered_bundle_group_ids = vec![]; + let order_map: Arc> = Arc::new( + toposort_modules + .iter() + .enumerate() + .map(|item| (item.1.clone(), item.0.clone())) + .collect(), + ); + + bundle_variables.borrow_mut().module_order_map = order_map.clone(); + bundle_variables.borrow_mut().module_order_index_set = Arc::new(toposort_modules); // 1. analyze resource pot - for resource_pot in resource_pots.iter() { + for bundle_group in bundle_groups.into_iter() { if !(matches!( - resource_pot.resource_pot_type, + bundle_group.group_type, ResourcePotType::Js | ResourcePotType::Runtime )) { continue; } - farm_profile_scope!(format!("analyze resource pot: {:?}", resource_pot.id)); + farm_profile_scope!(format!("analyze resource pot: {:?}", bundle_group.id)); - order_resource_pot.push(resource_pot.id.clone()); + ordered_bundle_group_ids.push(bundle_group.id.clone()); - // 1-1. analyze bundle - let mut bundle_analyzer = BundleAnalyzer::new( - resource_pot, - module_graph, - context, - bundle_variables.clone(), - ); + let bundle_group_id = bundle_group.id.clone(); - resource_pot - .modules() + (&bundle_group.modules) .into_par_iter() .try_for_each(|module_id| { let is_dynamic = module_graph.is_dynamic(module_id); - let is_entry = resource_pot + let is_entry = bundle_group .entry_module .as_ref() - .is_some_and(|item| item == module_id); + .is_some_and(|item| item == *module_id); let module = module_graph.module(module_id).unwrap(); let is_runtime = matches!(module.module_type, ModuleType::Runtime); // 1-2. analyze bundle module let module_analyzer = ModuleAnalyzer::new( module, - context, - resource_pot.id.clone(), + &context.context, + bundle_group.id.clone(), is_entry, is_dynamic, is_runtime, @@ -151,29 +187,40 @@ impl<'a> SharedBundle<'a> { module_analyzer_map .lock() .map_c_error()? - .insert(module_id.clone(), module_analyzer); + .insert((*module_id).clone(), module_analyzer); Ok::<(), CompilationError>(()) })?; + // 1-1. analyze bundle + let mut bundle_analyzer = BundleAnalyzer::new( + bundle_group, + module_graph, + &context.context, + bundle_variables.clone(), + ); + // 1-3. order bundle module bundle_analyzer.build_module_order(&order_map); - bundle_map.insert(resource_pot.id.clone(), bundle_analyzer); + bundle_map.insert(bundle_group_id, bundle_analyzer); } // modules manager let module_analyzer_manager = ModuleAnalyzerManager::new(module_analyzer_map.into_inner().unwrap(), module_graph); + let bundle_reference_manager = BundleReferenceManager::default(); + Ok(Self { module_analyzer_manager, bundle_map, module_graph, context, bundle_variables, - order_index_map: order_map, - order_resource_pot, + ordered_module_index: order_map, + ordered_groups_id: ordered_bundle_group_ids, + bundle_reference: bundle_reference_manager, }) } @@ -181,25 +228,23 @@ impl<'a> SharedBundle<'a> { fn extract_modules(&mut self) -> Result<()> { farm_profile_function!(""); - for resource_pot_id in &self.order_resource_pot { - farm_profile_scope!(format!( - "extract module resource pot: {:?}", - resource_pot_id - )); + for group_id in &self.ordered_groups_id { + farm_profile_scope!(format!("extract module resource pot: {:?}", group_id)); let bundle = self .bundle_map - .get_mut(resource_pot_id) + .get_mut(group_id) .map(Ok) .unwrap_or_else(|| { Err(CompilationError::GenericError(format!( - "get resource pot {resource_pot_id:?} failed" + "get resource pot {:?} failed", + group_id ))) })?; self.module_analyzer_manager.extract_modules_statements( &bundle.ordered_modules, - self.context, + &self.context.context, self.module_graph, &mut bundle.bundle_variable.borrow_mut(), )?; @@ -209,68 +254,158 @@ impl<'a> SharedBundle<'a> { } // 2-2 process common module data - fn link_modules(&mut self) -> Result<()> { - farm_profile_function!(""); - + fn link_resource_polyfill_to_variables(&mut self) { let bundle_variable = &mut self.bundle_variables.borrow_mut(); - for resource_pot_id in &self.order_resource_pot { - bundle_variable.set_namespace(resource_pot_id.clone()); + let polyfill_module_id = ModuleId::from(FARM_BUNDLE_POLYFILL_SLOT); + + let mut reserved_word = SimplePolyfill::reserved_word(); + + reserved_word.push("module".to_string()); + + if let Some(bundle_analyzer) = self + .module_analyzer_manager + .module_analyzer(&polyfill_module_id) + .and_then(|r| self.bundle_map.get_mut(&r.bundle_group_id)) + { + bundle_variable.set_namespace(bundle_analyzer.group.id.clone()); + + for name in &reserved_word { + let var = bundle_variable.register_var(&polyfill_module_id, &name.as_str().into(), false); + bundle_variable.polyfill_index_map.insert(name.clone(), var); + } + }; + + for group_id in &self.ordered_groups_id { + bundle_variable.set_namespace(group_id.clone()); // polyfill name should make sure it doesn't conflict. // tip: but it cannot be rename unresolved mark - for name in SimplePolyfill::reserved_word() { - bundle_variable.add_used_name(name); + for name in &reserved_word { + bundle_variable.add_used_name(name.clone()); } } + } - self - .module_analyzer_manager - .link(bundle_variable, &self.order_index_map, self.context); + // 2-3 + fn link_modules_meta(&mut self) -> Result<()> { + farm_profile_function!(""); + + self.module_analyzer_manager.link( + &mut self.bundle_variables.borrow_mut(), + &self.ordered_module_index, + &self.context.context, + &self.ordered_groups_id, + ); Ok(()) } - // 2-3 start process bundle + // 2-4 fn render_bundle(&mut self) -> Result<()> { farm_profile_function!(""); - // TODO: multiple bundle should merge polyfill to runtime bundle, and reexport to other bundle - for resource_pot_id in &self.order_resource_pot { - farm_profile_scope!(format!("render bundle: {}", resource_pot_id)); + self.each_render()?; + + self.each_patch_ast()?; - let bundle_analyzer = self.bundle_map.get_mut(resource_pot_id).unwrap(); + self.patch_polyfill()?; - bundle_analyzer.set_namespace(&bundle_analyzer.resource_pot.id); + Ok(()) + } + + fn each_render(&mut self) -> Result<()> { + // let mut defer_bundle_relation = vec![]; + + let mut ordered_modules = self.ordered_module_index.iter().collect::>(); + + ordered_modules.sort_by(|a, b| a.1.cmp(b.1).reverse()); + + for group_id in &self.ordered_groups_id { + farm_profile_scope!(format!("render bundle: {}", group_id)); + + let bundle_analyzer = self.bundle_map.get_mut(group_id).unwrap(); + bundle_analyzer.set_namespace(&group_id); + + bundle_analyzer.render(&mut self.module_analyzer_manager)?; + } + + for (module_id, _) in &ordered_modules { + farm_profile_scope!(format!("render module: {}", module_id)); + + let Some(module_analyzer) = self.module_analyzer_manager.module_analyzer(module_id) else { + continue; + }; + + let group_id = module_analyzer.bundle_group_id.clone(); + + let bundle_analyzer = self.bundle_map.get_mut(&group_id).unwrap(); + + bundle_analyzer.set_namespace(&group_id); + + bundle_analyzer.link_module_relation( + module_id, + &mut self.module_analyzer_manager, + &mut self.bundle_reference, + &self.context, + )?; - bundle_analyzer.render(&mut self.module_analyzer_manager, &self.order_index_map)?; + bundle_analyzer.module_conflict_name(&mut self.module_analyzer_manager); } + Ok(()) + } + + fn each_patch_ast(&mut self) -> Result<()> { + for group_id in &self.ordered_groups_id { + let bundle_analyzer = self.bundle_map.get_mut(group_id).unwrap(); + let bundle_group_id = bundle_analyzer.group.id.clone(); + + bundle_analyzer.set_namespace(&bundle_group_id); + + bundle_analyzer.patch_ast( + &mut self.module_analyzer_manager, + &self.ordered_module_index, + &mut self.bundle_reference, + &self.context, + )?; + } + + Ok(()) + } + + fn patch_polyfill(&mut self) -> Result<()> { + if self.context.options.concatenation_module { + return Ok(()); + } + + // multiple bundle should merge polyfill to runtime or entry bundle, and reexport to other bundle let mut polyfill = SimplePolyfill::new(vec![]); - for resource_pot_id in &self.order_resource_pot { - let bundle_analyzer = self.bundle_map.get(resource_pot_id).unwrap(); + let polyfill_resource_pot = self.module_analyzer_manager.polyfill_resource_pot(); - if matches!( - bundle_analyzer.resource_pot.resource_pot_type, - ResourcePotType::Js - ) { + for group_id in &self.ordered_groups_id { + let bundle_analyzer = self.bundle_map.get_mut(group_id).unwrap(); + + if let Some(ref polyfill_group_id) = polyfill_resource_pot { + if polyfill_group_id != group_id { + bundle_analyzer + .patch_polyfill_for_bundle(&mut self.module_analyzer_manager, &self.context)?; + } + } else { + bundle_analyzer.patch_polyfill_inline(&mut self.module_analyzer_manager)?; + } + + if matches!(bundle_analyzer.group.group_type, ResourcePotType::Js) { polyfill.extends(&bundle_analyzer.polyfill); } } - let runtime_resource_pot_id = self.order_resource_pot.iter().find(|item| { - self.bundle_map.get_mut(*item).is_some_and(|item| { - matches!( - item.resource_pot.resource_pot_type, - ResourcePotType::Runtime - ) - }) - }); - - if let Some(runtime_resource_pot_id) = runtime_resource_pot_id { - let bundle_analyzer = self.bundle_map.get_mut(runtime_resource_pot_id).unwrap(); - bundle_analyzer.polyfill.extends(&polyfill); + if let Some(bundle_analyzer) = polyfill_resource_pot + .map(|group_id| self.bundle_map.get_mut(&group_id)) + .flatten() + { + bundle_analyzer.patch_polyfill(&mut self.module_analyzer_manager, polyfill, &self.context)?; }; Ok(()) @@ -280,22 +415,27 @@ impl<'a> SharedBundle<'a> { pub fn render(&mut self) -> Result<()> { farm_profile_function!(""); + self.link_resource_polyfill_to_variables(); + self.extract_modules()?; // TODO: try async foreach - self.link_modules()?; + self.link_modules_meta()?; self.render_bundle()?; Ok(()) } - pub fn codegen(&mut self, resource_pot_id: &String) -> Result { + pub fn codegen(&mut self, group_id: &String) -> Result { farm_profile_function!(""); - let bundle = self.bundle_map.get_mut(resource_pot_id).unwrap(); + let bundle = self.bundle_map.get_mut(group_id).unwrap(); - let bundle = bundle.codegen(&mut self.module_analyzer_manager, &self.context.config)?; + let bundle = bundle.codegen( + &mut self.module_analyzer_manager, + &self.context.context.config, + )?; Ok(bundle) } diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/modules_analyzer/analyze.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/modules_analyzer/analyze.rs index 49b33e64a..abaa2d847 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/modules_analyzer/analyze.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/modules_analyzer/analyze.rs @@ -7,7 +7,7 @@ use farmfe_core::{ swc_common::Mark, swc_ecma_ast::{ self, DefaultDecl, ExportDecl, Expr, Ident, ImportSpecifier, ModuleDecl, ModuleExportName, - ModuleItem, + ModuleItem, Pat, }, }; use farmfe_toolkit::swc_ecma_visit::{Visit, VisitWith}; @@ -41,7 +41,7 @@ impl Visit for CollectUnresolvedIdent { } } -type RegisterVarHandle<'a> = Box<&'a mut dyn FnMut(&Ident, bool) -> usize>; +type RegisterVarHandle<'a> = Box<&'a mut dyn FnMut(&Ident, bool, bool) -> usize>; struct AnalyzeModuleItem<'a> { id: StatementId, @@ -52,11 +52,12 @@ struct AnalyzeModuleItem<'a> { module_graph: &'a ModuleGraph, _register_var: RegisterVarHandle<'a>, is_in_export: bool, + is_collect_ident: bool, top_level_mark: Mark, } impl<'a> AnalyzeModuleItem<'a> { - fn new usize>( + fn new usize>( id: StatementId, module_graph: &'a ModuleGraph, module_id: &'a ModuleId, @@ -73,6 +74,7 @@ impl<'a> AnalyzeModuleItem<'a> { _register_var: Box::new(register_var), is_in_export: false, top_level_mark, + is_collect_ident: false, } } @@ -112,8 +114,25 @@ impl<'a> AnalyzeModuleItem<'a> { self.is_in_export = is_in_export; } + fn with_collect_ident(&mut self, v: bool, f: F) { + let is_collect_ident = self.is_collect_ident; + self.is_collect_ident = v; + f(self); + self.is_collect_ident = is_collect_ident; + } + + fn is_strict(&self, ident: &Ident, default_strict: bool) -> bool { + default_strict || ident.ctxt.outer() != self.top_level_mark + } + fn register_var(&mut self, ident: &Ident, strict: bool) -> usize { - self._register_var.as_mut()(ident, strict || ident.ctxt.outer() != self.top_level_mark) + let strict = self.is_strict(ident, strict); + self._register_var.as_mut()(ident, strict, false) + } + + fn register_placeholder(&mut self, ident: &Ident) -> usize { + let strict = self.is_strict(ident, false); + self._register_var.as_mut()(ident, strict, true) } } @@ -240,18 +259,19 @@ impl<'a> Visit for AnalyzeModuleItem<'a> { for specifier in &export_named.specifiers { match specifier { swc_ecma_ast::ExportSpecifier::Named(named) => { - let local = match &named.orig { + let org = match &named.orig { ModuleExportName::Ident(i) => i.clone(), ModuleExportName::Str(_) => unimplemented!("exporting a string is not supported"), }; + let exported = named.exported.as_ref().map(|i| match i { + ModuleExportName::Ident(i) => i.clone(), + ModuleExportName::Str(_) => unimplemented!("exporting a string is not supported"), + }); specifiers.push(ExportSpecifierInfo::Named( ( - self.register_var(&local, false), - named.exported.as_ref().map(|i| match i { - ModuleExportName::Ident(i) => self.register_var(i, false), - _ => panic!("non-ident exported is not supported when tree shaking"), - }), + self.register_var(&org, false), + exported.as_ref().map(|i| self.register_var(i, false)), ) .into(), )); @@ -374,9 +394,34 @@ impl<'a> Visit for AnalyzeModuleItem<'a> { n.class.visit_with(self); } + + // fn visit_arrow_expr(&mut self, n: &swc_ecma_ast::ArrowExpr) {} + + fn visit_ident(&mut self, n: &Ident) { + if self.is_collect_ident { + let index = self.register_placeholder(n); + self.defined_idents.insert(index); + } + } + + fn visit_pat(&mut self, n: &swc_ecma_ast::Pat) { + match n { + Pat::Assign(assign) => { + self.with_collect_ident(true, |this| assign.left.visit_with(this)); + } + + Pat::Ident(ident) => { + self.with_collect_ident(true, |this| ident.visit_with(this)); + } + + _ => { + n.visit_children_with(self); + } + } + } } -pub fn analyze_imports_and_exports usize>( +pub fn analyze_imports_and_exports usize>( id: StatementId, stmt: &ModuleItem, module_id: &ModuleId, diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/modules_analyzer/module_analyzer.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/modules_analyzer/module_analyzer.rs index d498362f5..2577c7f52 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/modules_analyzer/module_analyzer.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/modules_analyzer/module_analyzer.rs @@ -1,6 +1,8 @@ use std::{ + cell::Ref, collections::{HashMap, HashSet}, fmt::Debug, + hash::Hash, path::PathBuf, sync::Arc, }; @@ -11,7 +13,7 @@ use farmfe_core::{ farm_profile_function, module::{module_graph::ModuleGraph, Module, ModuleId, ModuleSystem, ModuleType}, resource::resource_pot::ResourcePotId, - swc_common::{Mark, SourceMap}, + swc_common::{sync::OnceCell, Mark, SourceMap}, swc_ecma_ast::{Id, Module as EcmaAstModule}, }; use farmfe_toolkit::{ @@ -21,8 +23,10 @@ use farmfe_toolkit::{ }; use crate::resource_pot_to_bundle::{ - bundle::reference::ReferenceMap, common::get_module_mark, targets::cjs::CjsModuleAnalyzer, - uniq_name::BundleVariable, Var, + bundle::{bundle_reference::CommonJsImportMap, reference::ReferenceMap}, + common::get_module_mark, + targets::cjs::CjsModuleAnalyzer, + uniq_name::BundleVariable, }; use super::analyze::{self, CollectUnresolvedIdent}; @@ -81,19 +85,9 @@ pub enum StmtAction { /// import cjs from './cjs_module'; /// // => /// remove - /// // or /// /// ``` StripCjsImport(usize, Option), - // - // ```ts - // export { name as cjsName } from "./cjs"; - // export { age as cjsAge } from "./cjs"; - // // => - // const { name, age } = require_cjs(); - // ``` - // - // ReplaceCjsExport(ModuleId), } impl StmtAction { @@ -104,7 +98,6 @@ impl StmtAction { StmtAction::DeclDefaultExpr(index, _) => Some(*index), StmtAction::RemoveImport(index) => Some(*index), StmtAction::StripCjsImport(index, _) => Some(*index), - // StmtAction::ReplaceCjsExport(_) => None, } } } @@ -233,16 +226,17 @@ pub struct ModuleAnalyzer { pub cm: Arc, pub ast: EcmaAstModule, pub module_id: ModuleId, - pub resource_pot_id: ResourcePotId, + pub bundle_group_id: ResourcePotId, pub export_names: Option>, pub entry: bool, pub external: bool, - pub dynamic: bool, + pub is_dynamic: bool, pub is_runtime: bool, pub cjs_module_analyzer: CjsModuleAnalyzer, pub mark: (Mark, Mark), pub module_system: ModuleSystem, pub module_type: ModuleType, + pub is_reference_by_another: OnceCell, } impl Debug for ModuleAnalyzer { @@ -253,15 +247,16 @@ impl Debug for ModuleAnalyzer { .field("cm", &"[skip]") .field("ast", &self.ast) .field("module_id", &self.module_id) - .field("resource_pot_id", &self.resource_pot_id) + .field("bundle_group_id", &self.bundle_group_id) .field("export_names", &self.export_names) .field("entry", &self.entry) .field("external", &self.external) - .field("dynamic", &self.dynamic) + .field("dynamic", &self.is_dynamic) .field("is_runtime", &self.is_runtime) .field("cjs_module_analyzer", &"[skip]") .field("mark", &self.mark) .field("module_system", &self.module_system) + .field("is_reference_by_other", &self.is_reference_by_another) .finish() } } @@ -270,7 +265,7 @@ impl ModuleAnalyzer { pub fn new( module: &Module, context: &Arc, - resource_pot_id: ResourcePotId, + group_id: ResourcePotId, is_entry: bool, is_dynamic: bool, is_runtime: bool, @@ -295,15 +290,16 @@ impl ModuleAnalyzer { ast, module_id: module.id.clone(), export_names: None, - resource_pot_id, + bundle_group_id: group_id, external: module.external, entry: is_entry, - dynamic: is_dynamic, + is_dynamic, is_runtime, cjs_module_analyzer: CjsModuleAnalyzer::new(), mark: mark.unwrap(), module_system: module.meta.as_script().module_system.clone(), module_type: module.module_type.clone(), + is_reference_by_another: OnceCell::new(), }) } @@ -321,6 +317,10 @@ impl ModuleAnalyzer { ) } + pub fn is_reference_by_another bool>(&self, f: F) -> bool { + *self.is_reference_by_another.get_or_init(f) + } + fn collect_unresolved_ident(&self, bundle_variable: &mut BundleVariable) { farm_profile_function!(); let mut collection = CollectUnresolvedIdent::new(self.mark.0); @@ -352,7 +352,13 @@ impl ModuleAnalyzer { &self.module_id, module_graph, self.mark.1, - &mut |ident, strict| bundle_variable.register_var(&self.module_id, ident, strict), + &mut |ident, strict, is_placeholder| { + if is_placeholder { + bundle_variable.register_placeholder(&self.module_id, ident) + } else { + bundle_variable.register_var(&self.module_id, ident, strict) + } + }, ) .unwrap(); @@ -409,7 +415,8 @@ impl ModuleAnalyzer { pub fn build_rename_map<'a>( &self, bundle_variable: &'a BundleVariable, - ) -> HashMap<&'a Id, &'a Var> { + commonjs_import_map: &'a CommonJsImportMap, + ) -> HashMap, usize> { self .statements .iter() @@ -444,27 +451,68 @@ impl ModuleAnalyzer { .as_ref() .map(|item| { let mut idents = vec![]; + let commonjs = commonjs_import_map.get(&item.source.clone().into()); + for specify in &item.specifiers { match specify { ImportSpecifierInfo::Namespace(local) => { - idents.push(*local); + if let Some(i) = commonjs.and_then(|i| i.namespace) { + idents.push(i); + } else { + idents.push(*local); + } } ImportSpecifierInfo::Named { local, imported: _ } => { idents.push(*local); } ImportSpecifierInfo::Default(local) => { - idents.push(*local); + if let Some(i) = commonjs.and_then(|i| i.default) { + idents.push(i); + } else { + idents.push(*local); + } } } } + idents }) .unwrap_or_default(), ) .map(|item| bundle_variable.var_by_index(item)) - .filter(|item| item.rename.is_some()) - .map(|item| (&item.var, item)) + .filter(|item| item.rename.is_some() && !item.placeholder) + .map(|item| { + ( + Ref::map(Ref::clone(&item), |item| &item.var).into(), + item.index, + ) + }) }) .collect::>() } } + +#[derive(Debug)] +pub struct VarRefKey<'a> { + inner: Ref<'a, Id>, +} + +impl<'a> PartialEq for VarRefKey<'a> { + fn eq(&self, other: &Self) -> bool { + *self.inner == *other.inner + } +} + +impl<'a> Eq for VarRefKey<'a> {} + +impl<'a> Hash for VarRefKey<'a> { + fn hash(&self, state: &mut H) { + self.inner.hash(state); + } +} + +impl<'a> From> for VarRefKey<'a> { + fn from(value: Ref<'a, Id>) -> Self { + Self { inner: value } + } +} diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/polyfill/cjs.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/polyfill/cjs.rs deleted file mode 100644 index d400009b6..000000000 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/polyfill/cjs.rs +++ /dev/null @@ -1,54 +0,0 @@ -use farmfe_core::{ - swc_common::{SyntaxContext, DUMMY_SP}, - swc_ecma_ast::{CallExpr, Callee, Expr, ExprOrSpread}, -}; - -use super::{Polyfill, SimplePolyfill}; - -pub fn wrap_require_default(expr: Box, polyfill: &mut SimplePolyfill) -> Box { - polyfill.add(Polyfill::InteropRequireDefault); - Box::new(Expr::Call(farmfe_core::swc_ecma_ast::CallExpr { - span: DUMMY_SP, - callee: farmfe_core::swc_ecma_ast::Callee::Expr(Box::new(Expr::Ident( - "_interop_require_default".into(), - ))), - args: vec![farmfe_core::swc_ecma_ast::ExprOrSpread { spread: None, expr }], - type_args: None, - ctxt: SyntaxContext::empty(), - })) -} - -pub fn wrap_require_wildcard(expr: Box, polyfill: &mut SimplePolyfill) -> Box { - polyfill.add(Polyfill::Wildcard); - Box::new(Expr::Call(farmfe_core::swc_ecma_ast::CallExpr { - span: DUMMY_SP, - callee: farmfe_core::swc_ecma_ast::Callee::Expr(Box::new(Expr::Ident( - "_interop_require_wildcard".into(), - ))), - args: vec![farmfe_core::swc_ecma_ast::ExprOrSpread { spread: None, expr }], - type_args: None, - ctxt: SyntaxContext::empty(), - })) -} - -pub fn wrap_export_star(args: Vec, polyfill: &mut SimplePolyfill) -> Box { - polyfill.add(Polyfill::ExportStar); - Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: Callee::Expr(Box::new(Expr::Ident("_export_star".into()))), - args, - type_args: None, - ctxt: SyntaxContext::empty(), - })) -} - -pub fn wrap_commonjs(args: Vec, polyfill: &mut SimplePolyfill) -> Box { - polyfill.add(Polyfill::WrapCommonJs); - Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: Callee::Expr(Box::new(Expr::Ident(("__commonJs").into()))), - args, - type_args: None, - ctxt: SyntaxContext::empty(), - })) -} diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/polyfill/mod.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/polyfill/mod.rs index aa1609ae2..5122f347b 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/polyfill/mod.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/polyfill/mod.rs @@ -3,7 +3,6 @@ use std::collections::HashSet; use farmfe_core::{error::Result, farm_profile_scope, swc_ecma_ast::ModuleItem}; use super::common::parse_module_item; -pub mod cjs; // TODO: global polyfill #[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone)] @@ -77,6 +76,30 @@ pub enum Polyfill { BrowserExternalRequire, } +pub enum NamedType { + Export(String), + Inner(String), +} + +impl NamedType { + pub fn to_name(&self) -> String { + match self { + NamedType::Export(name) => name.to_string(), + NamedType::Inner(name) => name.to_string(), + } + } + + pub fn exportable(&self) -> bool { + matches!(self, NamedType::Export(_)) + } +} + +impl From<&str> for NamedType { + fn from(name: &str) -> Self { + NamedType::Inner(name.to_string()) + } +} + impl Polyfill { fn to_str(&self) -> Vec { match self { @@ -184,7 +207,11 @@ function _interop_require_default(obj) { Polyfill::NodeEsmGlobalRequireHelper => vec![ r#" import __farmNodeModule from 'module'; -global.nodeRequire = __farmNodeModule.createRequire(import.meta.url); +var __nodeRequireInstance = __farmNodeModule.createRequire(import.meta.url); + +function _nodeRequire() { + return __nodeRequireInstance.apply(null, arguments); +} "#, ], Polyfill::BrowserExternalRequire => vec![ @@ -219,7 +246,8 @@ function loadExternalRequire(name) { let mut result = vec![]; for item in self.to_str() { - result.push(parse_module_item(&item)?); + let items = parse_module_item(&item)?; + result.extend(items); } Ok(result) @@ -229,20 +257,40 @@ function loadExternalRequire(name) { vec![] } - fn name(&self) -> Vec { + fn name(&self) -> Vec { (match self { - Polyfill::WrapCommonJs => vec!["__commonJs"], - Polyfill::MergeNamespace => vec!["_mergeNamespaces"], - Polyfill::Wildcard => vec!["_getRequireWildcardCache", "_interop_require_wildcard"], - Polyfill::ExportStar => vec!["_export_star"], - Polyfill::InteropRequireDefault => vec!["_interop_require_default"], - Polyfill::NodeEsmGlobalRequireHelper => vec!["__farmNodeModule"], - Polyfill::BrowserExternalRequire => vec!["loadExternalRequire"], + Polyfill::WrapCommonJs => vec![NamedType::Export("__commonJs".into())], + Polyfill::MergeNamespace => vec![NamedType::Export("_mergeNamespaces".into())], + Polyfill::Wildcard => vec![ + "_getRequireWildcardCache".into(), + NamedType::Export("_interop_require_wildcard".into()), + ], + Polyfill::ExportStar => vec![NamedType::Export("_export_star".into())], + Polyfill::InteropRequireDefault => vec![NamedType::Export("_interop_require_default".into())], + Polyfill::NodeEsmGlobalRequireHelper => vec![ + "__farmNodeModule".into(), + NamedType::Export("_nodeRequire".into()), + ], + Polyfill::BrowserExternalRequire => vec![NamedType::Export("loadExternalRequire".into())], }) .into_iter() .map(|item| item.into()) .collect() } + + // fn export(&self) -> Vec { + // match self { + // Polyfill::WrapCommonJs => vec![create_export_named(vec!["__commonJs"])], + // Polyfill::MergeNamespace => vec![create_export_named(vec!["_mergeNamespaces"])], + // Polyfill::Wildcard => vec![create_export_named(vec!["_interop_require_wildcard"])], + // Polyfill::ExportStar => vec![create_export_named(vec!["_export_star"])], + // Polyfill::InteropRequireDefault => { + // vec![create_export_named(vec!["_interop_require_default"])] + // } + // Polyfill::NodeEsmGlobalRequireHelper => vec![], + // Polyfill::BrowserExternalRequire => vec![create_export_named(vec!["loadExternalRequire"])], + // } + // } } #[derive(Debug, Default, Clone)] @@ -290,6 +338,49 @@ impl SimplePolyfill { Ok(asts) } + pub fn to_names(&self) -> Vec { + farm_profile_scope!("polyfill to names"); + let mut names = vec![]; + + let mut polyfills = self.polyfills.iter().collect::>(); + + polyfills.sort(); + + for polyfill in &polyfills { + names.extend( + polyfill + .name() + .into_iter() + .map(|i| i.to_name()) + .collect::>(), + ) + } + + names + } + + pub fn to_export(&self) -> Vec { + farm_profile_scope!("polyfill to export"); + let mut exports = vec![]; + + let mut polyfills = self.polyfills.iter().collect::>(); + + polyfills.sort(); + + for polyfill in &polyfills { + exports.extend( + polyfill + .name() + .into_iter() + .filter(|i| i.exportable()) + .map(|i| i.to_name()) + .collect::>(), + ) + } + + exports + } + pub fn to_str(&self) -> Vec { farm_profile_scope!("polyfill to str"); let mut str_list = vec![]; @@ -319,7 +410,7 @@ impl SimplePolyfill { Polyfill::NodeEsmGlobalRequireHelper, ] .into_iter() - .flat_map(|polyfill| polyfill.name()) + .flat_map(|polyfill| polyfill.name().into_iter().map(|i| i.to_name())) .collect() } diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/generate.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/generate.rs index 037990f51..d824a5c9f 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/generate.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/generate.rs @@ -1,29 +1,31 @@ -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use farmfe_core::{ error::Result, - module::{ModuleId, ModuleSystem}, + module::ModuleSystem, swc_common::{SyntaxContext, DUMMY_SP}, swc_ecma_ast::{ AssignExpr, AssignOp, AssignTarget, BindingIdent, CallExpr, Callee, Decl, Expr, ExprOrSpread, - ExprStmt, KeyValueProp, Lit, MemberExpr, MemberProp, ModuleItem, ObjectLit, Pat, Prop, - PropName, PropOrSpread, SimpleAssignTarget, Stmt, VarDecl, VarDeclKind, VarDeclarator, + ExprStmt, Lit, MemberExpr, MemberProp, ModuleItem, Pat, SimpleAssignTarget, Stmt, VarDecl, + VarDeclKind, VarDeclarator, }, }; +use farmfe_toolkit::itertools::Itertools; use crate::resource_pot_to_bundle::{ bundle::{ - bundle_external::{ExternalReferenceExport, ExternalReferenceImport, ReferenceKind}, + bundle_reference::{ExternalReferenceExport, ExternalReferenceImport, ReferenceKind}, ModuleAnalyzerManager, }, - common::OptionToResult, - polyfill::{ - cjs::{wrap_export_star, wrap_require_default, wrap_require_wildcard}, - SimplePolyfill, - }, + common::{with_bundle_reference_slot_name, OptionToResult}, + polyfill::SimplePolyfill, + targets::util::{wrap_export_star, wrap_require_default, wrap_require_wildcard}, uniq_name::BundleVariable, + ShareBundleContext, }; +use super::util::create_esm_flag; + // export * from "./moduleA"; // esm => export * from "./moduleA"; // cjs => @@ -34,16 +36,20 @@ pub struct CjsGenerate {} impl CjsGenerate { pub fn generate_export( - source: Option<&ModuleId>, + source: Option<&ReferenceKind>, export: &ExternalReferenceExport, bundle_variable: &BundleVariable, module_analyzer_manager: &ModuleAnalyzerManager, polyfill: &mut SimplePolyfill, + is_already_polyfilled: &mut bool, + ctx: &ShareBundleContext, ) -> Result> { let mut stmts = vec![]; - let mut ordered_keys = export.named.keys().collect::>(); - - ordered_keys.sort_by_key(|a| bundle_variable.name(**a)); + let index_is_entry = |i: usize| { + bundle_variable + .module_id_by_var_index(i) + .is_some_and(|m| !module_analyzer_manager.is_entry(m)) + }; let module_export = |exported_name: &String, named_render_name: &String| { ModuleItem::Stmt(Stmt::Expr(ExprStmt { @@ -65,16 +71,33 @@ impl CjsGenerate { })) }; - for exported in ordered_keys { - let local = &export.named[exported]; - if bundle_variable.var_by_index(*local).removed { - continue; - } + for (exported, local) in export + .named + .iter() + .filter_map(|(exported, local)| { + if bundle_variable.var_by_index(*local).removed { + return None; + } - let named_render_name = bundle_variable.render_name(*local); - let exported_name = bundle_variable.name(*exported); + let should_reexport_uniq = index_is_entry(*local); - stmts.push(module_export(&exported_name, &named_render_name)); + let named_render_name = bundle_variable.render_name(*local); + let exported_name = bundle_variable.name(*exported); + + let exported_name = if should_reexport_uniq || named_render_name == exported_name { + None + } else { + Some(exported_name.as_str().into()) + }; + + let exported_name = exported_name.unwrap_or(named_render_name.clone()); + + Some((exported_name, named_render_name)) + }) + .unique_by(|(a, _)| a.to_string()) + .sorted_by_key(|(a, _)| a.to_string()) + { + stmts.push(module_export(&exported, &local)); } if let Some(namespace) = export.namespace.as_ref() { @@ -83,10 +106,11 @@ impl CjsGenerate { stmts.push(module_export(&exported_name, &named_render_name)); } - if let Some(source) = source { + if let Some(ReferenceKind::Module(source)) = source { if export.all.0 { let is_external = module_analyzer_manager.is_external(source); - if is_external || module_analyzer_manager.is_commonjs(source) { + let is_commonjs = module_analyzer_manager.is_commonjs(source); + if is_external || is_commonjs { let ns = module_analyzer_manager .module_global_uniq_name .namespace_name(source) @@ -111,6 +135,7 @@ impl CjsGenerate { }, ], polyfill, + ctx, ), }))); } @@ -126,47 +151,14 @@ impl CjsGenerate { )); }; - if matches!( - export.module_system, - ModuleSystem::EsModule | ModuleSystem::Hybrid - ) { - // Object.defineProperty(exports, '__esModule', { - // value: true, - // }); - - stmts.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: Callee::Expr(Box::new(Expr::Member(MemberExpr { - span: DUMMY_SP, - obj: Box::new(Expr::Ident("Object".into())), - prop: MemberProp::Ident("defineProperty".into()), - }))), - args: vec![ - ExprOrSpread { - spread: None, - expr: Box::new(Expr::Ident("exports".into())), - }, - ExprOrSpread { - spread: None, - expr: Box::new(Expr::Lit("__esModule".into())), - }, - ExprOrSpread { - spread: None, - expr: Box::new(Expr::Object(ObjectLit { - span: DUMMY_SP, - props: vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { - key: PropName::Ident("value".into()), - value: Box::new(Expr::Lit(Lit::Bool(true.into()))), - })))], - })), - }, - ], - type_args: None, - ctxt: SyntaxContext::empty(), - })), - }))); + if !*is_already_polyfilled + && matches!( + export.module_system, + ModuleSystem::EsModule | ModuleSystem::Hybrid + ) + { + stmts.push(create_esm_flag()); + *is_already_polyfilled = true; } Ok(stmts) @@ -195,84 +187,105 @@ impl CjsGenerate { import_map: &HashMap, module_analyzer_manager: &ModuleAnalyzerManager, polyfill: &mut SimplePolyfill, + group_id: &str, + ctx: &ShareBundleContext, ) -> Result> { let mut stmts = vec![]; let mut ordered_import = import_map.keys().collect::>(); ordered_import.sort(); + let mut generate_import_specifies: HashMap = HashMap::new(); + for source in ordered_import { - let module_id = match source { + let import = &import_map[source]; + + let mut is_import_uniq_name = false; + + let (module_id, url) = match source { ReferenceKind::Bundle(_) => continue, - ReferenceKind::Module(m) => m, + ReferenceKind::Module(m) => ( + m, + if module_analyzer_manager.is_external(m) { + m.to_string() + } else { + if !module_analyzer_manager.is_entry(m) { + is_import_uniq_name = true; + } + + with_bundle_reference_slot_name( + &module_analyzer_manager + .module_analyzer(m) + .map(|m| m.bundle_group_id.clone()) + .unwrap(), + ctx.options.reference_slot, + ) + }, + ), }; - let import = &import_map[source]; - - if import.named.is_empty() && import.namespace.is_none() && import.default.is_none() { - continue; - } + let source_bundle_id = module_analyzer_manager + .module_analyzer(module_id) + .map(|m| m.bundle_group_id.clone()) + // maybe external + .unwrap_or(group_id.to_string()); + let is_same_bundle = source_bundle_id == group_id; - let namespace_name = bundle_variable.name( + let namespace_name = bundle_variable.name(if !is_same_bundle { + module_analyzer_manager + .module_global_uniq_name + .namespace_name(source_bundle_id.to_string()) + .unwrap() + } else { module_analyzer_manager .module_global_uniq_name .namespace_name(module_id) - .unwrap(), - ); + .unwrap() + }); + + let merged_import = + generate_import_specifies + .entry(url) + .or_insert_with(|| MergedImportGenerate { + specifies: vec![], + namespace_name: namespace_name.clone(), + is_contain_namespace: import.namespace.is_some(), + }); + + if import.named.is_empty() && import.namespace.is_none() && import.default.is_none() { + continue; + } // import * as foo_ns from "foo"; // import foo from "foo"; // => // var foo_ns = _interop_require_wildcard(require("foo")); - // var foo_default = foo_ns.default; - let try_wrap_namespace = |expr: Box, polyfill: &mut SimplePolyfill| { - if import.namespace.is_some() { - return wrap_require_wildcard(expr, polyfill); - } - expr - }; let try_wrap_require_default = |expr: Box, polyfill: &mut SimplePolyfill| { if import.default.is_some() { - return wrap_require_default(expr, polyfill); + return wrap_require_default(expr, polyfill, ctx); } expr }; - // if both namespace and default are imported, we need to import the namespace first - stmts.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { - span: DUMMY_SP, - kind: farmfe_core::swc_ecma_ast::VarDeclKind::Var, - declare: false, - decls: vec![VarDeclarator { - span: DUMMY_SP, - name: Pat::Ident(BindingIdent { - id: namespace_name.as_str().into(), - type_ann: None, - }), - init: Some(try_wrap_namespace( - Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: Callee::Expr(Box::new(Expr::Ident("require".into()))), - args: vec![ExprOrSpread { - spread: None, - expr: Box::new(Expr::Lit(Lit::Str(module_id.to_string().as_str().into()))), - }], - type_args: None, - ctxt: SyntaxContext::empty(), - })), - polyfill, - )), - definite: false, - }], - ctxt: SyntaxContext::empty(), - }))))); - let mut decls: Vec = vec![]; + let namespace_expr = Expr::Ident(namespace_name.as_str().into()); let mut add_decl = |name: &str, property: &str| { let is_default = property == "default"; - let init_expr = Box::new(Expr::Ident(namespace_name.as_str().into())); + let init_expr = Box::new(namespace_expr.clone()); + + let init_expr = Expr::Member(MemberExpr { + span: DUMMY_SP, + obj: if is_default { + try_wrap_require_default(init_expr, polyfill) + } else { + init_expr + }, + prop: MemberProp::Ident(property.into()), + }); + + let t = Box::new(init_expr); decls.push(VarDeclarator { span: DUMMY_SP, @@ -280,15 +293,7 @@ impl CjsGenerate { id: name.into(), type_ann: None, }), - init: Some(Box::new(Expr::Member(MemberExpr { - span: DUMMY_SP, - obj: if is_default { - try_wrap_require_default(init_expr, polyfill) - } else { - init_expr - }, - prop: MemberProp::Ident(property.into()), - }))), + init: Some(t), definite: false, }); }; @@ -300,24 +305,117 @@ impl CjsGenerate { let local = &import.named[imported]; let local_named = bundle_variable.render_name(*local); - add_decl(&local_named, imported); + if is_import_uniq_name { + add_decl(&local_named, &local_named); + } else { + add_decl(&local_named, &imported); + } } if let Some(default) = import.default.as_ref() { - add_decl(&bundle_variable.render_name(*default), "default"); + let name = bundle_variable.render_name(*default); + if is_import_uniq_name { + add_decl(&name, &name); + } else { + add_decl(&name, "default"); + } } - if !decls.is_empty() { + merged_import.merge(MergedImportGenerate { + specifies: decls, + namespace_name, + is_contain_namespace: import.namespace.is_some(), + }); + } + + for (url, merged_import_generate) in generate_import_specifies + .into_iter() + .sorted_by_key(|(key, _)| key.to_string()) + { + let execute_require = Box::new(Expr::Call(CallExpr { + ctxt: SyntaxContext::empty(), + span: DUMMY_SP, + callee: Callee::Expr(Box::new(Expr::Ident("require".into()))), + args: vec![ExprOrSpread { + spread: None, + expr: Box::new(Expr::Lit(Lit::Str(url.as_str().into()))), + }], + type_args: None, + })); + + // import * as ns + // import { name } + if !merged_import_generate.specifies.is_empty() || merged_import_generate.is_contain_namespace + { + // if both namespace and default are imported, we need to import the namespace first + // const node_fs = require("node:fs") + // const readFile = node_fs.readFile; stmts.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { + ctxt: SyntaxContext::empty(), span: DUMMY_SP, - kind: VarDeclKind::Var, + kind: farmfe_core::swc_ecma_ast::VarDeclKind::Var, declare: false, - decls, - ctxt: SyntaxContext::empty(), + decls: vec![VarDeclarator { + span: DUMMY_SP, + name: Pat::Ident(BindingIdent { + id: merged_import_generate.namespace_name.as_str().into(), + type_ann: None, + }), + init: Some(try_wrap_namespace( + execute_require, + polyfill, + merged_import_generate.is_contain_namespace, + ctx, + )), + definite: false, + }], }))))); + + if !merged_import_generate.specifies.is_empty() { + stmts.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { + ctxt: SyntaxContext::empty(), + span: DUMMY_SP, + kind: VarDeclKind::Var, + declare: false, + decls: merged_import_generate.specifies, + }))))); + } + } else { + // import "node:fs" + stmts.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt { + span: DUMMY_SP, + expr: execute_require, + }))); } } Ok(stmts) } } + +// var foo_default = foo_ns.default; +fn try_wrap_namespace( + expr: Box, + polyfill: &mut SimplePolyfill, + is_contain_namespace: bool, + ctx: &ShareBundleContext, +) -> Box { + if is_contain_namespace { + return wrap_require_wildcard(expr, polyfill, ctx); + } + + expr +} + +pub struct MergedImportGenerate { + specifies: Vec, + namespace_name: String, + is_contain_namespace: bool, +} + +impl MergedImportGenerate { + fn merge(&mut self, other: MergedImportGenerate) { + self.specifies.extend(other.specifies); + self.is_contain_namespace = self.is_contain_namespace || other.is_contain_namespace; + } +} diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/mod.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/mod.rs index fa4a9cbda..38248e0ae 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/mod.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/mod.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; use farmfe_core::{ + error::Result, farm_profile_function, module::{module_graph::ModuleGraph, ModuleId}, swc_common::{Mark, SyntaxContext, DUMMY_SP}, @@ -10,20 +11,22 @@ use farmfe_core::{ }, }; use farmfe_toolkit::{ + itertools::Itertools, script::is_commonjs_require, swc_ecma_visit::{Visit, VisitWith}, }; use crate::resource_pot_to_bundle::{ bundle::{ - bundle_external::{ExternalReferenceExport, ExternalReferenceImport, ReferenceKind}, + bundle_reference::{ + CommonJsImportMap, ExternalReferenceExport, ExternalReferenceImport, ReferenceKind, + }, ModuleGlobalUniqName, }, - polyfill::{ - cjs::{wrap_require_default, wrap_require_wildcard}, - SimplePolyfill, - }, + polyfill::SimplePolyfill, + targets::util::{wrap_require_default, wrap_require_wildcard}, uniq_name::BundleVariable, + ShareBundleContext, }; pub mod generate; @@ -96,6 +99,7 @@ impl CjsModuleAnalyzer { module_graph: &ModuleGraph, ) -> Vec { farm_profile_function!("cjs module analyzer:analyzer modules"); + let mut collector = CjsCollector { unresolved_mark, top_level_mark, @@ -111,36 +115,101 @@ impl CjsModuleAnalyzer { /** when use esm export commonjs module */ pub fn redeclare_commonjs_export( - module_id: &ModuleId, bundle_variable: &BundleVariable, + import_map: &CommonJsImportMap, module_global_uniq_name: &ModuleGlobalUniqName, - reference_import: &ExternalReferenceImport, polyfill: &mut SimplePolyfill, - ) -> Vec { + ctx: &ShareBundleContext, + ) -> Result> { let mut result = vec![]; - let cjs_name = - bundle_variable.render_name(module_global_uniq_name.commonjs_name(module_id).unwrap()); + let mut generate_import_specifies: HashMap = HashMap::new(); - let mut decls = vec![]; + for source in import_map.keys().sorted() { + let import = &import_map[source]; + let Some((name, r)) = Self::redeclare_commonjs_export_item( + bundle_variable, + (source, &import), + module_global_uniq_name, + polyfill, + ctx, + )? + else { + continue; + }; + + generate_import_specifies.insert(name, r); + } - let cjs_caller = CallExpr { - span: DUMMY_SP, - callee: swc_ecma_ast::Callee::Expr(Box::new(Expr::Ident(cjs_name.as_str().into()))), - args: vec![], - type_args: None, - ctxt: SyntaxContext::empty(), + let mut generate_import_ordered = generate_import_specifies + .keys() + .cloned() + .collect::>(); + generate_import_ordered.sort(); + + for name in generate_import_ordered { + let decls = generate_import_specifies.remove(&name).unwrap(); + + match decls { + CommonJsDeclareResult::VarDecl(decls) => result.push(ModuleItem::Stmt(Stmt::Decl( + swc_ecma_ast::Decl::Var(Box::new(VarDecl { + ctxt: SyntaxContext::empty(), + span: DUMMY_SP, + kind: swc_ecma_ast::VarDeclKind::Var, + declare: false, + decls: decls.clone(), + })), + ))), + CommonJsDeclareResult::Execute(expr) => { + result.push(expr); + } + } + } + + Ok(result) + } + + pub fn redeclare_commonjs_export_item( + bundle_variable: &BundleVariable, + (source, import_map): (&ReferenceKind, &ExternalReferenceImport), + module_global_uniq_name: &ModuleGlobalUniqName, + polyfill: &mut SimplePolyfill, + ctx: &ShareBundleContext, + ) -> Result> { + let module_id = match source { + ReferenceKind::Bundle(_) => return Ok(None), + ReferenceKind::Module(m) => m, }; - if reference_import.is_empty() { - result.push(ModuleItem::Stmt(Stmt::Expr(ExprStmt { - span: DUMMY_SP, - expr: Box::new(Expr::Call(cjs_caller)), - }))); - return result; + let (cjs_name, cjs_caller) = if let Some(m) = module_global_uniq_name.commonjs_name(module_id) { + let name = bundle_variable.render_name(m); + ( + name.clone(), + Box::new(Expr::Call(CallExpr { + ctxt: SyntaxContext::empty(), + span: DUMMY_SP, + callee: swc_ecma_ast::Callee::Expr(Box::new(Expr::Ident(name.as_str().into()))), + args: vec![], + type_args: None, + })), + ) + } else { + return Ok(None); + }; + + if import_map.is_empty() { + return Ok(Some(( + cjs_name, + CommonJsDeclareResult::Execute(ModuleItem::Stmt(Stmt::Expr(ExprStmt { + span: DUMMY_SP, + expr: cjs_caller, + }))), + ))); } - if let Some(default) = reference_import.default { + let mut decls = vec![]; + + if let Some(default) = import_map.default { decls.push(VarDeclarator { span: DUMMY_SP, name: Pat::Ident(BindingIdent { @@ -149,37 +218,30 @@ impl CjsModuleAnalyzer { }), init: Some(Box::new(Expr::Member(MemberExpr { span: DUMMY_SP, - obj: wrap_require_default(Box::new(Expr::Call(cjs_caller.clone())), polyfill), + obj: wrap_require_default(cjs_caller.clone(), polyfill, ctx), prop: MemberProp::Ident("default".into()), }))), definite: false, }); } - if let Some(ns) = reference_import.namespace { + if let Some(ns) = import_map.namespace { decls.push(VarDeclarator { span: DUMMY_SP, name: Pat::Ident(BindingIdent { id: Ident::from(bundle_variable.render_name(ns).as_str()), type_ann: None, }), - init: Some(wrap_require_wildcard( - Box::new(Expr::Call(cjs_caller.clone())), - polyfill, - )), + init: Some(wrap_require_wildcard(cjs_caller.clone(), polyfill, ctx)), definite: false, }); } - let mut ordered_keys = reference_import.named.keys().collect::>(); - ordered_keys.sort(); - - for imported in ordered_keys { - let named_index = &reference_import.named[imported]; + for imported in import_map.named.keys().sorted() { + let named_index = &import_map.named[imported]; let require_name = bundle_variable.name(*named_index); let is_require_default = require_name == "default"; - let init_expr = Box::new(Expr::Call(cjs_caller.clone())); decls.push(VarDeclarator { span: DUMMY_SP, @@ -190,9 +252,9 @@ impl CjsModuleAnalyzer { init: Some(Box::new(Expr::Member(MemberExpr { span: DUMMY_SP, obj: if is_require_default { - wrap_require_default(init_expr, polyfill) + wrap_require_default(cjs_caller.clone(), polyfill, ctx) } else { - init_expr + cjs_caller.clone() }, prop: swc_ecma_ast::MemberProp::Computed(ComputedPropName { span: DUMMY_SP, @@ -203,18 +265,44 @@ impl CjsModuleAnalyzer { }); } - if !decls.is_empty() { - result.push(ModuleItem::Stmt(Stmt::Decl(swc_ecma_ast::Decl::Var( - Box::new(VarDecl { + Ok(Some((cjs_name, CommonJsDeclareResult::VarDecl(decls)))) + } +} + +#[derive(Debug)] +pub enum CommonJsDeclareResult { + VarDecl(Vec), + Execute(ModuleItem), +} + +impl CommonJsDeclareResult { + fn merge(&mut self, other: CommonJsDeclareResult) { + match self { + CommonJsDeclareResult::VarDecl(ref mut decls) => { + if let CommonJsDeclareResult::VarDecl(other_decls) = other { + decls.extend(other_decls); + } + } + CommonJsDeclareResult::Execute(_) => { + if matches!(other, CommonJsDeclareResult::VarDecl(_)) { + *self = other; + } + } + } + } + + pub fn to_module_item(self) -> ModuleItem { + match self { + CommonJsDeclareResult::VarDecl(decls) => { + ModuleItem::Stmt(Stmt::Decl(swc_ecma_ast::Decl::Var(Box::new(VarDecl { + ctxt: SyntaxContext::empty(), span: DUMMY_SP, kind: swc_ecma_ast::VarDeclKind::Var, declare: false, - decls, - ctxt: SyntaxContext::empty(), - }), - )))); + decls: decls.clone(), + })))) + } + CommonJsDeclareResult::Execute(expr) => expr, } - - result } } diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/patch.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/patch.rs index e617c9678..29f108037 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/patch.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/patch.rs @@ -1,4 +1,4 @@ -use std::sync::Arc; +use std::{collections::HashMap, sync::Arc}; use farmfe_core::{ config::{external::ExternalConfig, Config, Mode}, @@ -7,17 +7,19 @@ use farmfe_core::{ module::{module_graph::ModuleGraph, ModuleId, ModuleSystem}, swc_common::{util::take::Take, Mark, SyntaxContext, DUMMY_SP}, swc_ecma_ast::{ - ArrowExpr, BindingIdent, BlockStmt, BlockStmtOrExpr, Decl, EsVersion, Expr, ExprOrSpread, - Ident, KeyValueProp, Module as EcmaAstModule, ModuleItem, ObjectLit, Pat, Program, Prop, + ArrowExpr, BindingIdent, BlockStmt, BlockStmtOrExpr, Decl, Expr, ExprOrSpread, Ident, + KeyValueProp, Module as EcmaAstModule, ModuleItem, ObjectLit, Pass, Pat, Program, Prop, PropName, PropOrSpread, Stmt, VarDecl, VarDeclKind, VarDeclarator, }, }; use farmfe_toolkit::{ + script::module2cjs::{self, TransformModuleDeclsOptions}, swc_ecma_transforms::{ feature::enable_available_feature_from_es_version, modules::{ common_js, import_analysis::import_analyzer, + path::Resolver, util::{Config as SwcConfig, ImportInterop}, }, }, @@ -25,17 +27,20 @@ use farmfe_toolkit::{ }; use crate::resource_pot_to_bundle::{ - bundle::{bundle_external::BundleReference, ModuleAnalyzerManager, ModuleGlobalUniqName}, - polyfill::{cjs::wrap_commonjs, Polyfill, SimplePolyfill}, + bundle::{bundle_reference::BundleReference, ModuleAnalyzerManager, ModuleGlobalUniqName}, + modules_analyzer::module_analyzer::ModuleAnalyzer, + polyfill::{Polyfill, SimplePolyfill}, + targets::util::wrap_commonjs, uniq_name::BundleVariable, + ShareBundleContext, }; -use super::{util::CJSReplace, CjsModuleAnalyzer}; +use super::util::CJSReplace; pub struct CjsPatch {} impl CjsPatch { - pub fn wrap_commonjs( + fn wrap_commonjs( module_id: &ModuleId, bundle_variable: &BundleVariable, module_global_uniq_name: &ModuleGlobalUniqName, @@ -113,47 +118,60 @@ impl CjsPatch { Ok(patch_ast_items) } - pub fn to_cjs( + fn to_cjs( module_id: &ModuleId, ast: &mut EcmaAstModule, module_graph: &ModuleGraph, unresolved_mark: Mark, - es_version: EsVersion, + context: &Arc, + options: &ShareBundleContext, ) { - // let module = module_graph.module(module_id).unwrap(); - - // let comments = module.meta.as_script().comments.clone().into(); - let take_ast = std::mem::take(ast); - let mut program = Program::Module(take_ast); - program.mutate(&mut import_analyzer(ImportInterop::Swc, true)); - - program.mutate(&mut common_js( - Default::default(), - unresolved_mark, - SwcConfig { - ignore_dynamic: true, - preserve_import_meta: true, - ..Default::default() - }, - enable_available_feature_from_es_version(es_version), - // Some(&comments), - )); - let take_ast = program.expect_module(); - *ast = take_ast; + if options.options.concatenation_module { + module2cjs::transform_module_decls( + ast, + unresolved_mark, + &module2cjs::OriginalRuntimeCallee { unresolved_mark }, + TransformModuleDeclsOptions { + is_target_legacy: context.config.script.is_target_legacy(), + }, + ); + } else { + let mut program = Program::Module(ast.take()); + import_analyzer(ImportInterop::Swc, true).process(&mut program); + + common_js( + Resolver::Default, + unresolved_mark, + SwcConfig { + ignore_dynamic: true, + preserve_import_meta: true, + ..Default::default() + }, + enable_available_feature_from_es_version(context.config.script.target), + ) + .process(&mut program); + + let Program::Module(module) = program else { + unreachable!("cannot found module from program") + }; + *ast = module; + } } /// transform hybrid and commonjs module to esm - pub fn patch_cjs_module( + pub fn transform_hybrid_or_commonjs_to_esm( module_analyzer_manager: &mut ModuleAnalyzerManager, module_id: &ModuleId, - module_graph: &ModuleGraph, context: &Arc, - patch_ast: &mut Vec, bundle_variable: &BundleVariable, - bundle_reference: &BundleReference, + bundle_reference: &mut BundleReference, polyfill: &mut SimplePolyfill, - ) { - let module_analyzer = module_analyzer_manager.module_analyzer_mut_unchecked(module_id); + options: &ShareBundleContext, + ) -> Result<()> { + let module_analyzer = module_analyzer_manager + .module_map + .get_mut(module_id) + .unwrap(); let unresolved_mark = module_analyzer.mark.0; // if hybrid module, should transform to cjs @@ -161,66 +179,59 @@ impl CjsPatch { CjsPatch::to_cjs( module_id, &mut module_analyzer.ast, - module_graph, + module_analyzer_manager.module_graph, unresolved_mark, - context.config.script.target, + context, + options, ); } + let mut ast = module_analyzer.ast.body.take(); // if commonjs module, should wrap function // see [Polyfill::WrapCommonJs] if module_analyzer.is_commonjs() { - let ast = module_analyzer.ast.body.take(); - - module_analyzer_manager.set_ast_body( - module_id, - CjsPatch::wrap_commonjs( - module_id, - bundle_variable, - &module_analyzer_manager.module_global_uniq_name, - ast, - context.config.mode.clone(), - polyfill, - ) - .unwrap(), - ); - } - - if let Some(import) = bundle_reference - .redeclare_commonjs_import - .get(&module_id.clone().into()) - { - patch_ast.extend(CjsModuleAnalyzer::redeclare_commonjs_export( + ast = CjsPatch::wrap_commonjs( module_id, bundle_variable, &module_analyzer_manager.module_global_uniq_name, - import, + ast, + context.config.mode.clone(), polyfill, - )); + )?; } + + module_analyzer_manager.set_ast_body(module_id, ast); + + Ok(()) } - pub fn replace_cjs_require( + pub fn replace_cjs_require<'a>( mark: (Mark, Mark), ast: &mut EcmaAstModule, - module_id: &ModuleId, + module_id: &'a ModuleId, + bundle_variable: &'a BundleVariable, + config: &'a Config, + polyfill: &'a mut SimplePolyfill, + external_config: &'a ExternalConfig, + bundle_reference: &'a mut BundleReference, module_graph: &ModuleGraph, module_global_uniq_name: &ModuleGlobalUniqName, - bundle_variable: &BundleVariable, - config: &Config, - polyfill: &mut SimplePolyfill, - external_config: &ExternalConfig, + module_map: &HashMap, + options: &'a ShareBundleContext, ) { let mut replacer: CJSReplace = CJSReplace { unresolved_mark: mark.0, top_level_mark: mark.1, - module_graph, module_id: module_id.clone(), - module_global_uniq_name, bundle_variable, config, polyfill, external_config, + module_global_uniq_name, + module_graph, + bundle_reference, + module_map, + context: options, }; ast.visit_mut_with(&mut replacer); diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/util.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/util.rs index 7443be676..3218a28e3 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/util.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/cjs/util.rs @@ -1,8 +1,13 @@ +use std::collections::HashMap; + use farmfe_core::{ config::{external::ExternalConfig, Config, ModuleFormat}, module::{module_graph::ModuleGraph, ModuleId}, swc_common::{Mark, SyntaxContext, DUMMY_SP}, - swc_ecma_ast::{CallExpr, Callee, Expr, ExprOrSpread, Lit, MemberExpr, MemberProp}, + swc_ecma_ast::{ + CallExpr, Callee, Expr, ExprOrSpread, ExprStmt, KeyValueProp, Lit, MemberExpr, MemberProp, + ModuleItem, ObjectLit, Prop, PropName, PropOrSpread, Stmt, + }, }; use farmfe_toolkit::{ script::is_commonjs_require, @@ -10,7 +15,7 @@ use farmfe_toolkit::{ }; use crate::resource_pot_to_bundle::{ - bundle::ModuleGlobalUniqName, uniq_name::BundleVariable, Polyfill, SimplePolyfill, + bundle::{bundle_reference::BundleReference, ModuleGlobalUniqName}, modules_analyzer::module_analyzer::{ImportSpecifierInfo, ModuleAnalyzer}, uniq_name::BundleVariable, Polyfill, ShareBundleContext, ShareBundleOptions, SimplePolyfill }; enum ReplaceType { @@ -56,8 +61,22 @@ pub struct CJSReplace<'a> { pub module_global_uniq_name: &'a ModuleGlobalUniqName, pub bundle_variable: &'a BundleVariable, pub config: &'a Config, + pub context: &'a ShareBundleContext, pub polyfill: &'a mut SimplePolyfill, pub external_config: &'a ExternalConfig, + pub bundle_reference: &'a mut BundleReference, + pub module_map: &'a HashMap, +} + +impl<'a> CJSReplace<'a> { + fn is_same_bundle(&self, a: &ModuleId, b: &ModuleId) -> bool { + match (self.module_map.get(a), self.module_map.get(b)) { + (Some(a), Some(b)) => a.bundle_group_id == b.bundle_group_id, + // maybe external + (Some(_), None) | (None, Some(_)) => true, + _ => false, + } + } } impl<'a> VisitMut for CJSReplace<'a> { @@ -78,23 +97,26 @@ impl<'a> VisitMut for CJSReplace<'a> { { let source = str.value.to_string(); - if let Some(id) = + let reference_id = self .module_graph - .get_dep_by_source_optional(&self.module_id, &source, None) - { - if self.module_graph.module(&id).is_some_and(|m| m.external) { - if self.config.output.target_env.is_library() - && self.config.output.target_env.is_node() - { + .get_dep_by_source_optional(&self.module_id, &source, None); + + if let Some(id) = reference_id { + let is_external = self.module_graph.module(&id).is_some_and(|m| m.external); + let is_library_node = + self.config.output.target_env.is_library() && self.config.output.target_env.is_node(); + + if is_external { + if self.context.options.ignore_external_polyfill { + return; + } + + if is_library_node { // node esm - if matches!(self.config.output.format, ModuleFormat::EsModule) { + if matches!(self.context.options.format, ModuleFormat::EsModule) { self.polyfill.add(Polyfill::NodeEsmGlobalRequireHelper); - call_expr.callee = Callee::Expr(Box::new(Expr::Member(MemberExpr { - span: DUMMY_SP, - obj: Box::new(Expr::Ident("global".into())), - prop: MemberProp::Ident("nodeRequire".into()), - }))); + call_expr.callee = Callee::Expr(Box::new(Expr::Ident("_nodeRequire".into()))); } } else { // browser @@ -115,26 +137,59 @@ impl<'a> VisitMut for CJSReplace<'a> { }]; call_expr.span = DUMMY_SP; } - } else if let Some(commonjs_name) = self.module_global_uniq_name.commonjs_name(&id) { - *call_expr = CallExpr { - span: DUMMY_SP, - callee: Callee::Expr(Box::new(Expr::Ident( + } else { + let is_same_bundle = self.is_same_bundle(&self.module_id, &id); + let commonjs_name = self.module_global_uniq_name.commonjs_name(&id); + + // require('./moduleA') => moduleA_cjs() + if let Some(commonjs_name) = commonjs_name { + *call_expr = CallExpr { + ctxt: SyntaxContext::empty(), + span: DUMMY_SP, + callee: Callee::Expr(Box::new(Expr::Ident( + self + .bundle_variable + .render_name(commonjs_name) + .as_str() + .into(), + ))), + args: vec![], + type_args: None, + }; + replaced = ReplaceType::Call; + + if !is_same_bundle { + self + .bundle_reference + .add_import( + &ImportSpecifierInfo::Named { + local: commonjs_name, + imported: None, + }, + id.clone().into(), + &self.bundle_variable, + ) + .unwrap(); + } + } else if let Some(ns) = self.module_global_uniq_name.namespace_name(&id) { + if !is_same_bundle { self - .bundle_variable - .render_name(commonjs_name) - .as_str() - .into(), - ))), - args: vec![], - type_args: None, - ctxt: SyntaxContext::empty(), - }; - replaced = ReplaceType::Call; - } else if let Some(ns) = self.module_global_uniq_name.namespace_name(&id) { - replaced = ReplaceType::Ident(ns); + .bundle_reference + .add_import( + &ImportSpecifierInfo::Named { + local: ns, + imported: None, + }, + id.clone().into(), + &self.bundle_variable, + ) + .unwrap(); + } + + replaced = ReplaceType::Ident(ns); + } } } - // TODO: other bundle } } @@ -148,3 +203,46 @@ impl<'a> VisitMut for CJSReplace<'a> { } } } + +/// +/// ```js +/// Object.defineProperty(exports, '__esModule', { +/// value: true, +/// }); +/// ``` +/// +pub fn create_esm_flag() -> ModuleItem { + ModuleItem::Stmt(Stmt::Expr(ExprStmt { + span: DUMMY_SP, + expr: Box::new(Expr::Call(CallExpr { + ctxt: SyntaxContext::empty(), + span: DUMMY_SP, + callee: Callee::Expr(Box::new(Expr::Member(MemberExpr { + span: DUMMY_SP, + obj: Box::new(Expr::Ident("Object".into())), + prop: MemberProp::Ident("defineProperty".into()), + }))), + args: vec![ + ExprOrSpread { + spread: None, + expr: Box::new(Expr::Ident("exports".into())), + }, + ExprOrSpread { + spread: None, + expr: Box::new(Expr::Lit("__esModule".into())), + }, + ExprOrSpread { + spread: None, + expr: Box::new(Expr::Object(ObjectLit { + span: DUMMY_SP, + props: vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { + key: PropName::Ident("value".into()), + value: Box::new(Expr::Lit(Lit::Bool(true.into()))), + })))], + })), + }, + ], + type_args: None, + })), + })) +} diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/dynamic_import.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/dynamic_import.rs index 9b79d5921..3be5f9340 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/dynamic_import.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/dynamic_import.rs @@ -1,18 +1,19 @@ +use std::mem; + use farmfe_core::{ - module::ModuleId, + module::{Module, ModuleId}, + plugin::ResolveKind, swc_common::{SyntaxContext, DUMMY_SP}, - swc_ecma_ast::{CallExpr, Callee, Expr, ExprOrSpread, Ident, Lit, MemberExpr, MemberProp}, + swc_ecma_ast::{ + BindingIdent, BlockStmt, CallExpr, Callee, Expr, ExprOrSpread, FnExpr, Function, Ident, Lit, + MemberExpr, MemberProp, Param, Pat, ReturnStmt, Stmt, + }, }; use farmfe_toolkit::swc_ecma_visit::{VisitMut, VisitMutWith}; -use crate::resource_pot_to_bundle::{bundle::ModuleAnalyzerManager, uniq_name::BundleVariable}; - -const FARM_BUNDLE_REFERENCE_SLOT_PREFIX: &str = "__FARM_BUNDLE_REFERENCE_SLOT__:"; - -// TODO: replace bundle reference slot -fn with_bundle_reference_slot_name(bundle_id: &String) -> String { - format!("{FARM_BUNDLE_REFERENCE_SLOT_PREFIX}{bundle_id}") -} +use crate::resource_pot_to_bundle::{ + bundle::ModuleAnalyzerManager, common::with_bundle_reference_slot_name, modules_analyzer::module_analyzer::ModuleAnalyzer, uniq_name::BundleVariable, ShareBundleContext, ShareBundleOptions +}; /// /// ```ts @@ -37,19 +38,53 @@ fn with_bundle_reference_slot_name(bundle_id: &String) -> String { /// ``` /// /// -pub struct ReplaceDynamicVisit<'a> { - module_manager: &'a ModuleAnalyzerManager<'a>, +pub struct ReplaceDynamicVisit<'a, 'b> { + module_manager: &'b ModuleAnalyzerManager<'b>, module_id: &'a ModuleId, bundle_variable: &'a BundleVariable, + context: &'a ShareBundleContext, } -impl<'a> ReplaceDynamicVisit<'a> { - pub fn replace_expr(&self, call_expr: &mut CallExpr) -> Option> { - if !matches!(call_expr.callee, Callee::Import(_)) { - return None; +enum FromType<'a> { + Module(&'a Module), + ModuleAnalyzer(&'a ModuleAnalyzer), +} + +impl<'a, 'b> ReplaceDynamicVisit<'a, 'b> { + pub fn is_matched_dynamic_import(&self, expr: &CallExpr) -> bool { + matches!(expr.callee, Callee::Import(_)) + } + + fn try_find_module(&self, source: &str) -> Option { + if let Some(m) = self.module_manager.module_graph.get_dep_by_source_optional( + self.module_id, + source, + Some(ResolveKind::DynamicImport), + ) { + let v = self + .module_manager + .module_analyzer(&m) + .map(FromType::ModuleAnalyzer); + + if v.is_some() { + return v; + } + + let v = self + .module_manager + .module_graph + .module(&m) + .filter(|m| !m.external) + .map(FromType::Module); + + return v; } - let arg = &mut call_expr.args[0]; + None + } + + fn dynamic_import_source_str(&self, expr: &CallExpr) -> Option { + let arg = &expr.args[0]; if arg.spread.is_some() { return None; @@ -59,40 +94,42 @@ impl<'a> ReplaceDynamicVisit<'a> { return None; }; - let Some(value) = self - .module_manager - .module_analyzer_by_source(self.module_id, str.value.as_ref()) - else { - // external - return None; - }; + self.try_find_module(str.value.as_ref()) + } + + pub fn replace_expr_by_module_analyzer( + &self, + call_expr: &mut CallExpr, + module_analyzer: &ModuleAnalyzer, + ) -> Option> { + let arg = &mut call_expr.args[0]; // same bundle if self .module_manager - .is_same_bundle(self.module_id, &value.module_id) + .is_same_bundle(self.module_id, &module_analyzer.module_id) { - let is_commonjs = value.is_commonjs(); + let is_commonjs = module_analyzer.is_commonjs(); let name = self.bundle_variable.name(if is_commonjs { self .module_manager .module_global_uniq_name - .commonjs_name(&value.module_id) + .commonjs_name(&module_analyzer.module_id) .unwrap_or_else(|| { panic!( "not found module {:?} commonjs name as import() arg", - value.module_id + module_analyzer.module_id ) }) } else { self .module_manager .module_global_uniq_name - .namespace_name(&value.module_id) + .namespace_name(&module_analyzer.module_id) .unwrap_or_else(|| { panic!( "not found module {:?} namespace name as import() arg", - value.module_id + module_analyzer.module_id ) }) }); @@ -127,24 +164,157 @@ impl<'a> ReplaceDynamicVisit<'a> { *arg = ExprOrSpread { spread: None, expr: Box::new(Expr::Lit(Lit::Str( - with_bundle_reference_slot_name(&value.resource_pot_id) - .as_str() - .into(), + with_bundle_reference_slot_name( + &module_analyzer.bundle_group_id, + self.context.options.reference_slot, + ) + .as_str() + .into(), ))), }; } None } + + pub fn replace_expr_by_module( + &self, + call_expr: &mut CallExpr, + module: &Module, + ) -> Option> { + let arg = &mut call_expr.args[0]; + + *arg = ExprOrSpread { + spread: None, + // TODO: id hash + expr: Box::new(Expr::Lit(Lit::Str(self.context.format(&module.id).into()))), + }; + + None + } + + /// + /// + /// ```js + /// // foo.js + /// export default "foo"; + /// + /// // index.js (other bundle) + /// import("./foo").then(res => console.log(res.default)); + /// // => + /// import("./foo").then(function(r){ return r.foo_ns }).then(res => console.log(res.default)); + /// ``` + /// + pub fn map_promise_name_for_other_bundle( + &self, + expr: &mut Expr, + module_analyzer: &ModuleAnalyzer, + ) { + let is_commonjs = module_analyzer.is_commonjs(); + + let name = if is_commonjs { + self + .module_manager + .module_global_uniq_name + .commonjs_name(&module_analyzer.module_id) + } else { + self + .module_manager + .module_global_uniq_name + .namespace_name(&module_analyzer.module_id) + }; + + if let Some(ns) = name { + let namespace_name = self.bundle_variable.render_name(ns); + let e: Expr = mem::replace(expr, Expr::Lit(Lit::Bool(false.into()))); + + let return_expr = Expr::Member(MemberExpr { + span: DUMMY_SP, + obj: Box::new(Expr::Ident("r".into())), + prop: MemberProp::Ident(namespace_name.as_str().into()), + }); + + *expr = Expr::Call(CallExpr { + ctxt: SyntaxContext::empty(), + span: DUMMY_SP, + callee: Callee::Expr(Box::new(Expr::Member(MemberExpr { + span: DUMMY_SP, + obj: Box::new(e), + prop: MemberProp::Ident("then".into()), + }))), + args: vec![ExprOrSpread { + spread: None, + expr: Box::new(Expr::Fn(FnExpr { + ident: None, + function: Box::new(Function { + ctxt: SyntaxContext::empty(), + params: vec![Param { + span: DUMMY_SP, + decorators: vec![], + pat: Pat::Ident(BindingIdent { + id: "r".into(), + type_ann: None, + }), + }], + decorators: vec![], + span: DUMMY_SP, + body: Some(BlockStmt { + ctxt: SyntaxContext::empty(), + span: DUMMY_SP, + stmts: vec![Stmt::Return(ReturnStmt { + span: DUMMY_SP, + arg: Some(Box::new(if is_commonjs { + Expr::Call(CallExpr { + ctxt: SyntaxContext::empty(), + span: DUMMY_SP, + callee: Callee::Expr(Box::new(return_expr)), + args: vec![], + type_args: None, + }) + } else { + return_expr + })), + })], + }), + is_generator: false, + is_async: false, + type_params: None, + return_type: None, + }), + })), + }], + type_args: None, + }); + } + } } -impl<'a> VisitMut for ReplaceDynamicVisit<'a> { +impl<'a, 'b> VisitMut for ReplaceDynamicVisit<'a, 'b> { fn visit_mut_expr(&mut self, n: &mut Expr) { let mut visited = false; + if let Expr::Call(ref mut call_expr) = n { - if let Some(expr) = self.replace_expr(call_expr) { - visited = true; - *n = *expr; + if self.is_matched_dynamic_import(&call_expr) { + if let Some(from_type) = self.dynamic_import_source_str(&call_expr) { + match from_type { + FromType::Module(module) => { + self.replace_expr_by_module(call_expr, module); + } + FromType::ModuleAnalyzer(module_analyzer) => { + if let Some(expr) = self.replace_expr_by_module_analyzer(call_expr, module_analyzer) { + visited = true; + *n = *expr; + } + + if !self + .module_manager + .is_same_bundle(&self.module_id, &module_analyzer.module_id) + { + self.map_promise_name_for_other_bundle(n, module_analyzer); + } + } + } + } } } @@ -154,14 +324,16 @@ impl<'a> VisitMut for ReplaceDynamicVisit<'a> { } } -pub fn replace_dynamic_import<'a>( - module_manager: &'a ModuleAnalyzerManager<'a>, +pub fn replace_dynamic_import<'a, 'b>( + module_analyzer_manager: &'b ModuleAnalyzerManager<'b>, module_id: &'a ModuleId, bundle_variable: &'a BundleVariable, -) -> ReplaceDynamicVisit<'a> { + options: &'a ShareBundleContext, +) -> ReplaceDynamicVisit<'a, 'b> { ReplaceDynamicVisit { - module_manager, + module_manager: module_analyzer_manager, module_id, bundle_variable, + context: options, } } diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/esm/generate.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/esm/generate.rs index dea6a65d0..ffcb23aa3 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/esm/generate.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/esm/generate.rs @@ -1,40 +1,64 @@ -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use farmfe_core::{ error::Result, - module::ModuleId, swc_common::DUMMY_SP, swc_ecma_ast::{ - ExportAll, ExportDefaultExpr, ExportNamedSpecifier, ExportNamespaceSpecifier, Expr, ImportDecl, - ImportDefaultSpecifier, ImportNamedSpecifier, ImportStarAsSpecifier, ModuleDecl, ModuleItem, - NamedExport, Str, + ExportAll, ExportNamedSpecifier, ExportNamespaceSpecifier, ExportSpecifier, ImportDecl, + ImportDefaultSpecifier, ImportNamedSpecifier, ImportSpecifier, ImportStarAsSpecifier, + ModuleDecl, ModuleExportName, ModuleItem, NamedExport, Str, }, }; +use farmfe_toolkit::itertools::Itertools; use crate::resource_pot_to_bundle::{ bundle::{ - bundle_external::{ExternalReferenceExport, ExternalReferenceImport, ReferenceKind}, + bundle_reference::{ExternalReferenceExport, ExternalReferenceImport, ReferenceKind}, ModuleAnalyzerManager, }, + common::with_bundle_reference_slot_name, uniq_name::BundleVariable, + ShareBundleContext, }; pub struct EsmGenerate {} impl EsmGenerate { pub fn generate_export( - source: Option<&ModuleId>, + should_reexport_raw: bool, + source: Option<&ReferenceKind>, export: &ExternalReferenceExport, bundle_variable: &BundleVariable, module_analyzer_manager: &ModuleAnalyzerManager, + context: &ShareBundleContext, ) -> Result> { let mut stmts = vec![]; let mut specifiers = vec![]; - let mut ordered_keys = export.named.keys().collect::>(); - ordered_keys.sort_by_key(|a| bundle_variable.name(**a)); + let source_url = source.map(|target_id| { + if let ReferenceKind::Module(target_id) = target_id { + return if let Some(target_module_analyzer) = + module_analyzer_manager.module_analyzer(target_id) + { + with_bundle_reference_slot_name( + &target_module_analyzer.bundle_group_id, + context.options.reference_slot, + ) + } else { + context.format(target_id) + }; + } + + target_id.to_module_id().to_string() + }); + + let mut uniq_sets = HashSet::new(); - for exported in ordered_keys { + for exported in export + .named + .keys() + .sorted_by_key(|a| bundle_variable.render_name(**a)) + { let local = &export.named[exported]; if bundle_variable.var_by_index(*local).removed { continue; @@ -43,22 +67,24 @@ impl EsmGenerate { let named_render_name = bundle_variable.render_name(*local); let exported_name = bundle_variable.name(*exported); - let exported_name = if named_render_name == exported_name { + if uniq_sets.contains(&named_render_name) { + continue; + } + + uniq_sets.insert(named_render_name.clone()); + + let exported_name = if !should_reexport_raw || named_render_name == exported_name { None } else { Some(exported_name.as_str().into()) }; - specifiers.push(farmfe_core::swc_ecma_ast::ExportSpecifier::Named( - ExportNamedSpecifier { - span: DUMMY_SP, - orig: farmfe_core::swc_ecma_ast::ModuleExportName::Ident( - named_render_name.as_str().into(), - ), - exported: exported_name.map(farmfe_core::swc_ecma_ast::ModuleExportName::Ident), - is_type_only: false, - }, - )); + specifiers.push(ExportSpecifier::Named(ExportNamedSpecifier { + span: DUMMY_SP, + orig: ModuleExportName::Ident(named_render_name.as_str().into()), + exported: exported_name.map(ModuleExportName::Ident), + is_type_only: false, + })); } if let Some(namespace) = export.namespace.as_ref() { @@ -72,120 +98,210 @@ impl EsmGenerate { )); } - if let Some(source) = source { + if let Some(ReferenceKind::Module(source)) = source { if export.all.0 && !module_analyzer_manager.is_commonjs(source) { stmts.push(ModuleItem::ModuleDecl(ModuleDecl::ExportAll(ExportAll { span: DUMMY_SP, - src: Box::new(source.to_string().as_str().into()), + src: Box::new(source_url.as_ref().unwrap().as_str().into()), type_only: false, with: None, }))); } } + if let Some(default) = export.default.as_ref() { + let name = bundle_variable.render_name(*default).as_str().into(); + + specifiers.push(ExportSpecifier::Named(ExportNamedSpecifier { + span: DUMMY_SP, + orig: ModuleExportName::Ident(name), + exported: should_reexport_raw.then(|| ModuleExportName::Ident("default".into())), + is_type_only: false, + })); + } + if !specifiers.is_empty() { stmts.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed( NamedExport { span: DUMMY_SP, specifiers, - src: source.map(|source| Box::new(source.to_string().as_str().into())), + src: source_url.map(|source| Box::new(source.as_str().into())), type_only: false, with: None, }, ))); } - if let Some(default) = export.default.as_ref() { - stmts.push(ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr( - ExportDefaultExpr { - span: DUMMY_SP, - expr: Box::new(Expr::Ident( - bundle_variable.render_name(*default).as_str().into(), - )), - }, - ))); - } - Ok(stmts) } pub fn generate_import( bundle_variable: &BundleVariable, import_map: &HashMap, + module_analyzer_manager: &ModuleAnalyzerManager, + resource_pot_name: &str, + options: &ShareBundleContext, ) -> Result> { let mut stmts = vec![]; - let mut ordered_import = import_map.keys().collect::>(); - ordered_import.sort(); + let mut generate_import_specifies: HashMap = HashMap::new(); + + for source in import_map.keys().sorted() { + let mut is_import_uniq_name = false; + + let (_, url) = match source { + ReferenceKind::Bundle(_) => continue, + ReferenceKind::Module(m) => { + if module_analyzer_manager.is_external(m) { + (m.clone(), m.to_string()) + } else { + if module_analyzer_manager.contain(m) && !module_analyzer_manager.is_entry(m) { + is_import_uniq_name = true; + } + + ( + m.clone(), + with_bundle_reference_slot_name( + &module_analyzer_manager + .group_id(m) + .map(|id| id.to_string()) + // maybe using group + .unwrap_or_else(|| options.format(m)), + options.options.reference_slot, + ), + ) + } + } + }; - for source in ordered_import { let import = &import_map[source]; - if import.named.is_empty() && import.namespace.is_none() && import.default.is_none() { + let import_item = init_import_specify(&mut generate_import_specifies, &url); + + if import.is_empty() { continue; } - let create_import = |specifiers: Vec| { - ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl { - span: DUMMY_SP, - specifiers, - src: Box::new(Str { - span: DUMMY_SP, - value: source.to_string().as_str().into(), - raw: None, - }), - type_only: false, - with: None, - phase: farmfe_core::swc_ecma_ast::ImportPhase::Evaluation, - })) - }; + for imported in import.named.keys().sorted() { + let local = import.named[imported]; + let local_named = bundle_variable.render_name(local); - let mut specifiers = vec![]; + let imported = if is_import_uniq_name || imported == &local_named { + None + } else { + Some(imported.as_str()) + }; - let mut ordered_named_keys = import.named.keys().collect::>(); - ordered_named_keys.sort(); - for imported in ordered_named_keys { - let local = &import.named[imported]; - let local_named = bundle_variable.render_name(*local); + let used_name = imported.unwrap_or(&local_named).to_string(); - specifiers.push(farmfe_core::swc_ecma_ast::ImportSpecifier::Named( - ImportNamedSpecifier { + if import_item.contains_key(&used_name) { + continue; + } + + import_item.insert( + used_name, + ImportSpecifier::Named(ImportNamedSpecifier { span: DUMMY_SP, local: local_named.as_str().into(), - imported: if imported == &local_named { - None - } else { - Some(farmfe_core::swc_ecma_ast::ModuleExportName::Ident( - imported.as_str().into(), - )) - }, + imported: imported.map(|s| ModuleExportName::Ident(s.into())), is_type_only: false, + }), + ); + } + + if let Some(default) = import.default.as_ref() { + let name = bundle_variable.render_name(*default); + if import_item.contains_key(&name) { + continue; + } + + import_item.insert( + name.clone(), + if is_import_uniq_name { + ImportSpecifier::Named(ImportNamedSpecifier { + span: DUMMY_SP, + local: name.as_str().into(), + imported: None, + is_type_only: false, + }) + } else { + ImportSpecifier::Default(ImportDefaultSpecifier { + span: DUMMY_SP, + local: name.as_str().into(), + }) }, - )); + ); } if let Some(namespace) = import.namespace.as_ref() { - stmts.push(create_import(vec![ - farmfe_core::swc_ecma_ast::ImportSpecifier::Namespace(ImportStarAsSpecifier { + let namespace_name = bundle_variable.render_name(*namespace).as_str().into(); + if import_item.is_empty() {} + import_item.insert( + namespace_name, + ImportSpecifier::Namespace(ImportStarAsSpecifier { span: DUMMY_SP, local: bundle_variable.render_name(*namespace).as_str().into(), }), - ])); + ); } + } - if let Some(default) = import.default.as_ref() { - specifiers.push(farmfe_core::swc_ecma_ast::ImportSpecifier::Default( - ImportDefaultSpecifier { - span: DUMMY_SP, - local: bundle_variable.render_name(*default).as_str().into(), - }, - )); + for (url, import_item) in generate_import_specifies + .into_iter() + .sorted_by(|a, b| a.0.cmp(&b.0)) + { + let partial_specifiers = import_item + .into_iter() + .sorted_by(|a, b| a.0.cmp(&b.0)) + .fold([vec![], vec![]], |mut res, (_, specifier)| { + match specifier { + ImportSpecifier::Namespace(_) => { + res[1] = vec![specifier]; + } + + _ => res[0].push(specifier), + } + + res + }); + + let mut partial_specifiers = partial_specifiers + .into_iter() + .filter(|v| !v.is_empty()) + .collect::>(); + + if partial_specifiers.is_empty() { + partial_specifiers.push(vec![]); } - if !specifiers.is_empty() { - stmts.push(create_import(specifiers)); + for item in partial_specifiers { + stmts.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl { + span: DUMMY_SP, + specifiers: item, + src: Box::new(Str { + span: DUMMY_SP, + value: url.clone().into(), + raw: None, + }), + type_only: false, + with: None, + phase: farmfe_core::swc_ecma_ast::ImportPhase::Evaluation, + }))); } } Ok(stmts) } } + +fn init_import_specify<'a>( + generate_import_specifies: &'a mut HashMap>, + url: &String, +) -> &'a mut ImportItem { + if !generate_import_specifies.contains_key(url) { + generate_import_specifies.insert(url.clone(), Default::default()); + } + + generate_import_specifies.get_mut(url).unwrap() +} + +type ImportItem = HashMap; diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/generate.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/generate.rs index d8c94b355..77d2fc1f4 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/generate.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/generate.rs @@ -7,24 +7,25 @@ use farmfe_core::{ module::{ModuleId, ModuleSystem}, swc_common::{SyntaxContext, DUMMY_SP}, swc_ecma_ast::{ - self, ArrayLit, BindingIdent, Bool, CallExpr, Decl, Expr, ExprOrSpread, Ident, IdentName, - KeyValueProp, ModuleItem, ObjectLit, Pat, Prop, PropName, PropOrSpread, Stmt, Str, VarDecl, - VarDeclKind, VarDeclarator, + self, BindingIdent, Bool, Decl, Expr, Ident, IdentName, KeyValueProp, ModuleItem, ObjectLit, + Pat, Prop, PropName, PropOrSpread, Stmt, Str, VarDecl, VarDeclKind, VarDeclarator, }, }; +use farmfe_toolkit::itertools::Itertools; use crate::resource_pot_to_bundle::{ bundle::{ - bundle_external::{BundleReference, ExternalReferenceExport}, + bundle_reference::{BundleReference, ExternalReferenceExport, ReferenceKind}, reference::{ReferenceExport, ReferenceMap}, ModuleAnalyzerManager, }, modules_analyzer::module_analyzer::ImportSpecifierInfo, - polyfill::{Polyfill, SimplePolyfill}, + polyfill::SimplePolyfill, uniq_name::BundleVariable, + ShareBundleContext, }; -use super::{cjs::generate::CjsGenerate, esm::generate::EsmGenerate}; +use super::{cjs::generate::CjsGenerate, esm::generate::EsmGenerate, util::create_merge_namespace}; /// namespace pub fn generate_namespace_by_reference_map( @@ -45,17 +46,18 @@ pub fn generate_namespace_by_reference_map( let mut reexport_namespace: Vec = vec![]; { - generate_export_as_object_prop(&mut props, &map.export, bundle_variable); + generate_export_as_object_prop(&mut props, &map.export, bundle_variable, false); } - let mut module_ids = map.reference_map.keys().collect::>(); - - module_ids.sort_by_key(|a| &order_index_map[a]); - - for module_id in module_ids { - let reference_export = &map.reference_map[module_id]; + for module_id in map + .reexport_map + .keys() + .sorted_by_key(|a| order_index_map[a]) + { + let reference_export = &map.reexport_map[module_id]; - if module_analyzer_manager.is_external(module_id) { + if module_analyzer_manager.is_external(module_id) || !module_analyzer_manager.contain(module_id) + { if reference_export.is_empty() || reference_export.all { let ns_index = module_analyzer_manager .module_global_uniq_name @@ -73,7 +75,7 @@ pub fn generate_namespace_by_reference_map( } // TODO: export import from external - generate_export_as_object_prop(&mut props, reference_export, bundle_variable); + generate_export_as_object_prop(&mut props, reference_export, bundle_variable, true); } else if module_analyzer_manager.is_commonjs(module_id) { if reference_export.is_empty() || reference_export.all { commonjs_fns.push( @@ -90,7 +92,7 @@ pub fn generate_namespace_by_reference_map( continue; } - generate_export_as_object_prop(&mut props, reference_export, bundle_variable) + generate_export_as_object_prop(&mut props, reference_export, bundle_variable, false) } } @@ -113,52 +115,13 @@ pub fn generate_namespace_by_reference_map( props, }))) } else { - polyfill.add(Polyfill::MergeNamespace); - // dynamic - Some(Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: swc_ecma_ast::Callee::Expr(Box::new(Expr::Ident(Ident::from("_mergeNamespaces")))), - args: vec![ - // static - ExprOrSpread { - spread: None, - expr: Box::new(Expr::Object(ObjectLit { - span: DUMMY_SP, - props, - })), - }, - ExprOrSpread { - spread: None, - expr: Box::new(Expr::Array(ArrayLit { - span: DUMMY_SP, - elems: commonjs_fns - .into_iter() - .map(|ident| { - Some(ExprOrSpread { - spread: None, - expr: Box::new(Expr::Call(CallExpr { - span: DUMMY_SP, - callee: swc_ecma_ast::Callee::Expr(Box::new(Expr::Ident(ident))), - args: vec![], - type_args: None, - ctxt: SyntaxContext::empty(), - })), - }) - }) - .chain(reexport_namespace.into_iter().map(|ns| { - Some(ExprOrSpread { - spread: None, - expr: Box::new(Expr::Ident(ns)), - }) - })) - .collect(), - })), - }, - ], - type_args: None, - ctxt: SyntaxContext::empty(), - }))) + Some(create_merge_namespace( + props, + commonjs_fns, + reexport_namespace, + polyfill, + )) }; patch_ast_items.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { @@ -183,25 +146,33 @@ pub fn generate_export_as_object_prop( props: &mut Vec, reference_export: &ReferenceExport, bundle_variable: &BundleVariable, + is_external: bool, ) { - let mut exported_ordered_names = reference_export + let exported_ordered_names = reference_export .named - .keys() - .map(|i| (bundle_variable.name(*i), i)) + .iter() + .sorted_by_key(|(a, _)| bundle_variable.name(**a)) .collect::>(); - exported_ordered_names.sort_by(|(a, _), (b, _)| a.cmp(b)); - - for (exported_name, exported_index) in &exported_ordered_names { - let local = &reference_export.named[*exported_index]; - - let local_ident = bundle_variable.render_name(*local); - - // maybe as short, but need legacy - props.push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { - key: PropName::Ident(exported_name.as_str().into()), - value: Box::new(Expr::Ident(Ident::from(local_ident.as_str()))), - })))); + for (export_as, export_local) in &exported_ordered_names { + let export_as_name = bundle_variable.name(**export_as); + let export_local_name = bundle_variable.render_name(**export_local); + + props.push(PropOrSpread::Prop(Box::new(Prop::KeyValue( + if is_external { + KeyValueProp { + key: PropName::Ident((bundle_variable.name(**export_as).as_str()).into()), + value: Box::new(Expr::Ident( + bundle_variable.render_name(**export_as).as_str().into(), + )), + } + } else { + KeyValueProp { + key: PropName::Ident(export_as_name.as_str().into()), + value: Box::new(Expr::Ident(Ident::from(export_local_name.as_str()))), + } + }, + )))); } if let Some(default) = reference_export.default { @@ -227,45 +198,48 @@ pub fn generate_export_as_object_prop( /// generate bundle export pub fn generate_export_by_reference_export( - resource_pot_id: &str, + _group_id: &str, + should_reexport_raw: bool, bundle_variable: &BundleVariable, bundle_reference: &mut BundleReference, module_analyzer_manager: &ModuleAnalyzerManager, - context: &Arc, + _context: &Arc, polyfill: &mut SimplePolyfill, + is_already_polyfilled: &mut bool, + options: &ShareBundleContext, ) -> Result> { - let mut patch_export_to_module = vec![]; - + let mut patch_export_to_module: Vec = vec![]; if let Some(export) = bundle_reference.export.as_ref() { patch_export_to_module.extend(generate_export_as_module_export( - resource_pot_id, + should_reexport_raw, None, export, bundle_variable, module_analyzer_manager, - context, polyfill, + is_already_polyfilled, + options, )?); } - let mut ordered_external_export = bundle_reference + let ordered_external_export = bundle_reference .external_export_map .keys() + .sorted_by_key(|a| a.to_string()) .collect::>(); - ordered_external_export.sort_by_key(|a| a.to_string()); - for source in ordered_external_export { let export = &bundle_reference.external_export_map[source]; patch_export_to_module.extend(generate_export_as_module_export( - resource_pot_id, - Some(&source.to_module_id()), + should_reexport_raw, + Some(&source), export, bundle_variable, module_analyzer_manager, - context, polyfill, + is_already_polyfilled, + options, )?); } @@ -273,23 +247,25 @@ pub fn generate_export_by_reference_export( } pub fn generate_export_as_module_export( - _resource_pot_name: &str, - source: Option<&ModuleId>, + should_reexport_raw: bool, + source: Option<&ReferenceKind>, export: &ExternalReferenceExport, bundle_variable: &BundleVariable, module_analyzer_manager: &ModuleAnalyzerManager, - context: &Arc, polyfill: &mut SimplePolyfill, + is_already_polyfilled: &mut bool, + ctx: &ShareBundleContext, ) -> Result> { - let mut ordered_keys = export.named.keys().collect::>(); - - ordered_keys.sort_by_key(|a| bundle_variable.name(**a)); - - match (&export.module_system, context.config.output.format) { + match (&export.module_system, ctx.options.format) { // hybrid dynamic es module cannot support, if hybrid, only export static export - (_, ModuleFormat::EsModule) => { - EsmGenerate::generate_export(source, export, bundle_variable, module_analyzer_manager) - } + (_, ModuleFormat::EsModule) => EsmGenerate::generate_export( + should_reexport_raw, + source, + export, + bundle_variable, + module_analyzer_manager, + ctx, + ), (_, ModuleFormat::CommonJs) => CjsGenerate::generate_export( source, @@ -297,38 +273,39 @@ pub fn generate_export_as_module_export( bundle_variable, module_analyzer_manager, polyfill, + is_already_polyfilled, + ctx, ), } } /// generate bundle import - pub fn generate_bundle_import_by_bundle_reference( format: &ModuleFormat, bundle_variable: &BundleVariable, bundle_reference: &BundleReference, module_analyzer_manager: &ModuleAnalyzerManager, polyfill: &mut SimplePolyfill, + group_id: &str, + options: &ShareBundleContext, ) -> Result> { - let mut patch_import_to_module = vec![]; - + // TODO: sort import by order match format { - ModuleFormat::CommonJs => { - patch_import_to_module.extend(CjsGenerate::generate_import( - bundle_variable, - &bundle_reference.import_map, - module_analyzer_manager, - polyfill, - )?); - } + ModuleFormat::EsModule => EsmGenerate::generate_import( + bundle_variable, + &bundle_reference.import_map, + module_analyzer_manager, + group_id, + options, + ), - ModuleFormat::EsModule => { - patch_import_to_module.extend(EsmGenerate::generate_import( - bundle_variable, - &bundle_reference.import_map, - )?); - } + ModuleFormat::CommonJs => CjsGenerate::generate_import( + bundle_variable, + &bundle_reference.import_map, + module_analyzer_manager, + polyfill, + group_id, + options, + ), } - - Ok(patch_import_to_module) } diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/mod.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/mod.rs index c92a6c553..762dbb9bf 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/mod.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/mod.rs @@ -1,4 +1,6 @@ +pub mod util; pub mod cjs; + pub mod dynamic_import; pub mod esm; pub mod generate; diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/util.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/util.rs new file mode 100644 index 000000000..f0649c630 --- /dev/null +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/util.rs @@ -0,0 +1,149 @@ +use std::{cell::RefCell, rc::Rc}; + +use farmfe_core::{ + swc_common::{SyntaxContext, DUMMY_SP}, + swc_ecma_ast::{ArrayLit, CallExpr, Callee, Expr, ExprOrSpread, Ident, ObjectLit, PropOrSpread}, +}; +use farmfe_toolkit::script::module2cjs::RuntimeCalleeAllocator; + +use crate::resource_pot_to_bundle::{Polyfill, ShareBundleContext, SimplePolyfill}; + +pub fn wrap_require_default( + expr: Box, + polyfill: &mut SimplePolyfill, + ctx: &ShareBundleContext, +) -> Box { + polyfill.add(Polyfill::InteropRequireDefault); + Box::new(Expr::Call(farmfe_core::swc_ecma_ast::CallExpr { + span: DUMMY_SP, + callee: farmfe_core::swc_ecma_ast::Callee::Expr(ctx.allocator.import_default_callee()), + args: vec![farmfe_core::swc_ecma_ast::ExprOrSpread { spread: None, expr }], + type_args: None, + ctxt: SyntaxContext::empty(), + })) +} + +/// +/// ```ts +/// import * as bar from "foo"; +/// ``` +/// +pub fn wrap_require_wildcard( + expr: Box, + polyfill: &mut SimplePolyfill, + ctx: &ShareBundleContext, +) -> Box { + polyfill.add(Polyfill::Wildcard); + Box::new(Expr::Call(farmfe_core::swc_ecma_ast::CallExpr { + span: DUMMY_SP, + callee: farmfe_core::swc_ecma_ast::Callee::Expr(ctx.allocator.import_namespace_callee()), + args: vec![farmfe_core::swc_ecma_ast::ExprOrSpread { spread: None, expr }], + type_args: None, + ctxt: SyntaxContext::empty(), + })) +} + +/// +/// ```ts +/// export * from "x"; +/// ``` +/// +pub fn wrap_export_star( + args: Vec, + polyfill: &mut SimplePolyfill, + ctx: &ShareBundleContext, +) -> Box { + polyfill.add(Polyfill::ExportStar); + Box::new(Expr::Call(CallExpr { + span: DUMMY_SP, + callee: Callee::Expr(ctx.allocator.export_star_callee()), + args, + type_args: None, + ctxt: SyntaxContext::empty(), + })) +} + +pub fn wrap_commonjs(args: Vec, polyfill: &mut SimplePolyfill) -> Box { + polyfill.add(Polyfill::WrapCommonJs); + Box::new(Expr::Call(CallExpr { + span: DUMMY_SP, + callee: Callee::Expr(Box::new(Expr::Ident(("__commonJs").into()))), + args, + type_args: None, + ctxt: SyntaxContext::empty(), + })) +} + +pub fn create_merge_namespace( + props: Vec, + commonjs_fns: Vec, + reexport_namespace: Vec, + polyfill: &mut SimplePolyfill, +) -> Box { + polyfill.add(Polyfill::MergeNamespace); + Box::new(Expr::Call(CallExpr { + ctxt: SyntaxContext::empty(), + span: DUMMY_SP, + callee: Callee::Expr(Box::new(Expr::Ident(Ident::from("_mergeNamespaces")))), + args: vec![ + // static + ExprOrSpread { + spread: None, + expr: Box::new(Expr::Object(ObjectLit { + span: DUMMY_SP, + props, + })), + }, + ExprOrSpread { + spread: None, + expr: Box::new(Expr::Array(ArrayLit { + span: DUMMY_SP, + elems: commonjs_fns + .into_iter() + .map(|ident| { + Some(ExprOrSpread { + spread: None, + expr: Box::new(Expr::Call(CallExpr { + ctxt: SyntaxContext::empty(), + span: DUMMY_SP, + callee: Callee::Expr(Box::new(Expr::Ident(ident))), + args: vec![], + type_args: None, + })), + }) + }) + .chain(reexport_namespace.into_iter().map(|ns| { + Some(ExprOrSpread { + spread: None, + expr: Box::new(Expr::Ident(ns)), + }) + })) + .collect(), + })), + }, + ], + type_args: None, + })) +} + +pub struct ShareBundleRuntimeCalleeAllocator {} + +impl ShareBundleRuntimeCalleeAllocator { + pub fn new() -> Self { + Self {} + } +} + +impl RuntimeCalleeAllocator for ShareBundleRuntimeCalleeAllocator { + fn import_default_callee(&self) -> Box { + Box::new(Expr::Ident("_interop_require_default".into())) + } + + fn import_namespace_callee(&self) -> Box { + Box::new(Expr::Ident("_interop_require_wildcard".into())) + } + + fn export_star_callee(&self) -> Box { + Box::new(Expr::Ident("_export_star".into())) + } +} diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/uniq_name.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/uniq_name.rs index 0bd4c3923..e6c6b8004 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/uniq_name.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/uniq_name.rs @@ -1,5 +1,6 @@ use std::{ borrow::Cow, + cell::{Ref, RefCell, RefMut}, collections::{HashMap, HashSet}, path::PathBuf, str::FromStr, @@ -17,8 +18,10 @@ use farmfe_core::{ }; use farmfe_toolkit::fs::normalize_file_name_as_variable; +use crate::resource_pot_to_bundle::bundle::reference::ReferenceQueryResult; + use super::{ - bundle::{bundle_external::ReferenceKind, ModuleAnalyzerManager}, + bundle::{bundle_reference::ReferenceKind, ModuleAnalyzerManager}, Var, }; @@ -74,12 +77,15 @@ impl UniqName { pub struct BundleVariable { pub index: Arc, // TODO(improve) diff vec and hashmap - pub variables: HashMap, + pub variables: HashMap>, // TODO(improve): maybe record top_level var, and only register same top_level var pub module_defined_vars: HashMap>, pub uniq_name_hash_map: HashMap, pub namespace: String, pub used_names: HashSet, + pub module_order_map: Arc>, + pub module_order_index_set: Arc>, + pub polyfill_index_map: HashMap, } pub fn safe_name_from_module_id(module_id: &ModuleId, root: &str) -> String { @@ -100,51 +106,42 @@ pub fn safe_name_from_module_id(module_id: &ModuleId, root: &str) -> String { impl BundleVariable { pub fn new() -> Self { Self { + index: Arc::new(AtomicUsize::new(1)), ..Default::default() } } - fn push(&mut self, var: Var, index: usize) { - self.variables.insert(index, var); + fn push(&mut self, mut var: Var, index: usize) { + var.index = index; + self.variables.insert(index, RefCell::new(var)); } pub fn is_in_used_name(&self, index: usize) -> bool { self.used_names.contains(&self.name(index)) } + // TODO: remove split by resource_pot_id pub fn uniq_name_mut(&mut self) -> &mut UniqName { - self.uniq_name_hash_map.get_mut(&self.namespace).unwrap() + self.uniq_name_hash_map.get_mut("default").unwrap() } pub fn uniq_name(&mut self) -> &UniqName { - self.uniq_name_hash_map.get(&self.namespace).unwrap() - } - - pub fn with_namespace T>(&mut self, namespace: String, f: F) -> T { - let prev = self.namespace.clone(); - - if self.uniq_name_hash_map.contains_key(&namespace) { - self - .uniq_name_hash_map - .insert(namespace.clone(), UniqName::new()); - } - self.namespace = namespace; - - let r = f(self); - - self.namespace = prev; - - r + self.uniq_name_hash_map.get("default").unwrap() } - pub fn set_namespace(&mut self, namespace: String) { - if !self.uniq_name_hash_map.contains_key(&namespace) { - self - .uniq_name_hash_map - .insert(namespace.clone(), UniqName::new()); - } + // TODO: assess the necessity of its existence + pub fn set_namespace(&mut self, _namespace: String) { + // if !self.uniq_name_hash_map.contains_key(&namespace) { + // self + // .uniq_name_hash_map + // .insert(namespace.clone(), UniqName::new()); + // } - self.namespace = namespace; + // self.namespace = namespace; + self + .uniq_name_hash_map + .entry("default".to_string()) + .or_insert_with(|| UniqName::new()); } pub fn add_used_name(&mut self, used_name: String) { @@ -153,11 +150,22 @@ impl BundleVariable { self.used_names.insert(used_name); } + pub fn register_placeholder(&mut self, module_id: &ModuleId, ident: &Ident) -> usize { + let index = self.register_var(module_id, ident, true); + + self.uniq_name_mut().insert(ident.sym.as_str()); + + self.var_mut_by_index(index).placeholder = true; + + index + } + pub fn register_var(&mut self, module_id: &ModuleId, ident: &Ident, strict: bool) -> usize { farm_profile_scope!("register var"); let var = Var { var: ident.to_id(), rename: None, + module_id: self.module_order_map.get(module_id).cloned(), ..Default::default() }; @@ -168,6 +176,8 @@ impl BundleVariable { v }; + // TODO: maybe top-level var should register, other var should as placeholder + // TODO: should use ident.id as key let var_ident = if strict { // a#1 ident.to_string() @@ -177,6 +187,7 @@ impl BundleVariable { }; if let Some(map) = self.module_defined_vars.get_mut(module_id) { + // TODO: used name should effect to uniq if !self.used_names.contains(&var_ident) { if let Some(exists_index) = map.get(&var_ident) { return *exists_index; @@ -195,9 +206,15 @@ impl BundleVariable { index.unwrap() } - pub fn branch(&self) -> Self { + pub fn branch( + index: &Arc, + module_order_map: &Arc>, + module_order_index_set: &Arc>, + ) -> Self { Self { - index: Arc::clone(&self.index), + index: Arc::clone(&index), + module_order_map: Arc::clone(module_order_map), + module_order_index_set: Arc::clone(module_order_index_set), ..Default::default() } } @@ -235,19 +252,117 @@ impl BundleVariable { self.add_used_name(uniq_name_safe_name.clone()); - self.register_var(module_id, &uniq_name_safe_name.as_str().into(), false) + self.register_var(&module_id, &uniq_name_safe_name.as_str().into(), false) + } + + pub fn register_common_used_name(&mut self, suffix: &str, name: &str) -> usize { + let uniq_name = self.uniq_name_mut().uniq_name( + format!( + "{}{}", + normalize_file_name_as_variable(name.to_string()), + suffix + ) + .as_str(), + ); + + self.add_used_name(uniq_name.clone()); + + self.register_var( + &ModuleId::from("__FARM_BUNDLE_COMMON_USED_NAME__"), + &uniq_name.as_str().into(), + false, + ) + } + + // ---------- var ------------ + + pub fn var(&self, index: usize) -> (Ref, Option>) { + let v = self.var_by_index(index); + + if let Some(root) = v.root { + return (v, Some(self.var_by_index(root))); + } + + (v, None) + } + + pub fn module_id_by_var_index(&self, index: usize) -> Option<&ModuleId> { + let v = self.var_by_index(index); + + v.module_id.map(|i| &self.module_order_index_set[i]) + } + + pub fn module_id_by_var(&self, var: &Var) -> Option<&ModuleId> { + var.module_id.map(|i| &self.module_order_index_set[i]) + } + + pub fn var_mut(&self, index: usize) -> (RefMut, Option>) { + let v = self.var_mut_by_index(index); + + if let Some(root) = v.root { + return (v, Some(self.var_mut_by_index(root))); + } + + (v, None) + } + + pub fn set_var_root(&self, index: usize, root: usize) { + if index == root { + return; + } + let mut var = self.var_mut_by_index(index); + var.root = Some(self.var_or_root(root).index); + } + + pub fn var_or_root(&self, index: usize) -> Ref { + let mut v = self.var_by_index(index); + + let mut paths = vec![index]; + loop { + if let Some(root) = v.root.map(|root| self.var_by_index(root)) { + if paths.contains(&root.index) { + break; + } + + v = root; + paths.push(v.index); + } else { + break; + } + } + + for path in paths.into_iter().rev().skip(1) { + if path == index { + continue; + } + + self.set_var_root(path, v.index); + } + + v } - pub fn var_by_index(&self, index: usize) -> &Var { - &self.variables[&index] + pub fn var_root_mut(&self, index: usize) -> RefMut { + let v = self.var_mut_by_index(index); + + if let Some(root) = v.root { + return self.var_mut_by_index(root); + } + + v } - pub fn var_mut_by_index(&mut self, index: usize) -> &mut Var { - self.variables.get_mut(&index).unwrap() + pub fn var_by_index(&self, index: usize) -> Ref { + self.variables[&index].borrow() } - pub fn set_rename(&mut self, index: usize, rename: String) { - let var = self.var_mut_by_index(index); + pub fn var_mut_by_index(&self, index: usize) -> RefMut { + self.variables[&index].borrow_mut() + } + + pub fn set_rename(&self, index: usize, rename: String) { + let mut var = self.var_mut_by_index(index); + if var.rename.is_none() { var.rename = Some(rename); } @@ -257,34 +372,39 @@ impl BundleVariable { self.var_mut_by_index(index).rename = Some(rename); } - pub fn rename(&self, index: usize) -> Option<&String> { - self.var_by_index(index).rename.as_ref() + pub fn rename(&self, index: usize) -> Option> { + let v = self.var_or_root(index); + + if v.rename.is_some() { + return Some(Ref::map(v, |item| item.rename.as_ref().unwrap())); + } + + None } pub fn name(&self, index: usize) -> String { self.var_by_index(index).var.0.to_string() } + pub fn render_name(&self, index: usize) -> String { + let var = self.var_or_root(index); + + var.render_name() + } + #[inline] pub fn is_default_key(&self, index: usize) -> bool { self.name(index) == "default" } - pub fn render_name(&self, index: usize) -> String { - let var = self.var_by_index(index); - if let Some(rename) = var.rename.as_ref() { - return rename.clone(); - } - - var.var.0.to_string() - } - pub fn set_var_uniq_rename_string(&mut self, index: usize, var_ident: String) { let var = self.var_by_index(index); if var.rename.is_some() { return; } + drop(var); + let uniq_name = if self.uniq_name().contain(&var_ident) { self.uniq_name_mut().uniq_name(&var_ident) } else { @@ -309,55 +429,83 @@ impl BundleVariable { index: usize, source: &ModuleId, module_analyzers: &ModuleAnalyzerManager, - resource_pot_id: ResourcePotId, + group_id: ResourcePotId, find_default: bool, find_namespace: bool, ) -> Option { let var_ident = self.name(index); - - if module_analyzers.is_external(source) { - return Some(FindModuleExportResult::External(index, source.clone())); + if module_analyzers.is_external(source) || !module_analyzers.contain(source) { + return Some(FindModuleExportResult::External( + index, + source.clone(), + false, + )); } if let Some(module_analyzer) = module_analyzers.module_analyzer(source) { let module_system = module_analyzer.module_system.clone(); - if find_namespace || module_analyzers.is_commonjs(source) { - return Some(FindModuleExportResult::Local( - index, - source.clone(), - module_system, - )); - } - let reference_map = module_analyzer.export_names(); - if module_analyzer.resource_pot_id != resource_pot_id { - if let Some(index) = reference_map.query_by_var_str(&var_ident, self) { + if module_analyzer.bundle_group_id != group_id { + if find_namespace || find_default || module_analyzers.is_commonjs(source) { + let Some(res) = self.find_ident_by_index( + index, + source, + module_analyzers, + module_analyzer.bundle_group_id.clone(), + find_default, + find_namespace, + ) else { + return None; + }; + + match res { + FindModuleExportResult::Local(i, target, _) + | FindModuleExportResult::External(i, target, _) => { + let is_reexport = module_analyzers + .module_analyzer(&target) + .is_some_and(|m| m.bundle_group_id == module_analyzer.bundle_group_id); + + return Some(FindModuleExportResult::Bundle( + i, + module_analyzer.module_id.clone(), + module_system, + is_reexport, + )); + } + _ => return Some(res), + } + } + + if let Some(ReferenceQueryResult { index, is_reexport }) = + reference_map.query_by_var_str_and_meta(&var_ident, self) + { return Some(FindModuleExportResult::Bundle( index, - module_analyzer.resource_pot_id.clone(), + module_analyzer.module_id.clone(), // support cjs module_system, + is_reexport, )); - // TODO: error? } } + if find_namespace || module_analyzers.is_commonjs(source) { + return Some(FindModuleExportResult::Local( + index, + source.clone(), + module_system, + )); + } + if find_default { - if let Some(d) = reference_map + return reference_map .export .default - .or_else(|| reference_map.export.query(&"default".to_string(), self)) - { - return Some(FindModuleExportResult::Local( - d, - source.clone(), - module_system, - )); - } - - return None; + .or_else(|| reference_map.query_by_str("default", self)) + // .or_else(|| reference_map.export.query(&"default".to_string(), self)) + .map(|i| FindModuleExportResult::Local(i, source.clone(), module_system)); } // find from local @@ -370,10 +518,10 @@ impl BundleVariable { } // find from reference external or bundle - for (module_id, export) in &reference_map.reference_map { + for (module_id, export) in &reference_map.reexport_map { if let Some(d) = export.query(&var_ident, self) { - if module_analyzers.is_external(module_id) { - return Some(FindModuleExportResult::External(d, module_id.clone())); + if module_analyzers.is_external(module_id) || !module_analyzers.contain(module_id) { + return Some(FindModuleExportResult::External(d, module_id.clone(), true)); } else { return Some(FindModuleExportResult::Local( d, @@ -383,6 +531,12 @@ impl BundleVariable { } } } + } else { + return Some(FindModuleExportResult::External( + index, + source.clone(), + false, + )); } None @@ -392,15 +546,15 @@ impl BundleVariable { #[derive(Debug)] pub enum FindModuleExportResult { Local(usize, ModuleId, ModuleSystem), - External(usize, ModuleId), - Bundle(usize, ResourcePotId, ModuleSystem), + External(usize, ModuleId, bool), + Bundle(usize, ModuleId, ModuleSystem, bool), } impl FindModuleExportResult { pub fn is_common_js(&self) -> bool { match self { FindModuleExportResult::Local(_, _, module_system) - | FindModuleExportResult::Bundle(_, _, module_system) => { + | FindModuleExportResult::Bundle(_, _, module_system, _) => { matches!(module_system, ModuleSystem::CommonJs | ModuleSystem::Hybrid) } @@ -411,16 +565,24 @@ impl FindModuleExportResult { pub fn module_system(&self) -> Option { match self { FindModuleExportResult::Local(_, _, module_system) - | FindModuleExportResult::Bundle(_, _, module_system) => Some(module_system.clone()), - FindModuleExportResult::External(_, _) => None, + | FindModuleExportResult::Bundle(_, _, module_system, _) => Some(module_system.clone()), + FindModuleExportResult::External(_, _, _) => None, } } pub fn target_source(&self) -> ReferenceKind { match self { FindModuleExportResult::Local(_, target_source, _) => target_source.clone().into(), - FindModuleExportResult::External(_, target_source) => target_source.clone().into(), - FindModuleExportResult::Bundle(_, target_bundle, _) => target_bundle.clone().into(), + FindModuleExportResult::External(_, target_source, _) => target_source.clone().into(), + FindModuleExportResult::Bundle(_, target_bundle, _, _) => target_bundle.clone().into(), + } + } + + pub fn is_reexport(&self) -> bool { + match self { + FindModuleExportResult::Local(_, _, _) => false, + FindModuleExportResult::External(_, _, reexport) => *reexport, + FindModuleExportResult::Bundle(_, _, _, reexport) => *reexport, } } } @@ -569,7 +731,7 @@ mod tests { assert!(matches!( result, - Some(FindModuleExportResult::External(_, _)) + Some(FindModuleExportResult::External(_, _, _)) )); if let FindModuleExportResult::External(index, ..) = result.unwrap() { @@ -692,7 +854,7 @@ mod tests { assert!(matches!( result, - Some(FindModuleExportResult::Bundle(_, _, _)) + Some(FindModuleExportResult::Bundle(_, _, _, _)) )); if let FindModuleExportResult::Bundle(index, ..) = result.unwrap() { diff --git a/crates/plugin_lazy_compilation/src/lib.rs b/crates/plugin_lazy_compilation/src/lib.rs index 8b83c2b44..773aae83a 100644 --- a/crates/plugin_lazy_compilation/src/lib.rs +++ b/crates/plugin_lazy_compilation/src/lib.rs @@ -196,10 +196,10 @@ impl Plugin for FarmPluginLazyCompilation { let relative_source = relative(&dir, &resolved_path); let content = format!( r#" - import _default_import from "./{relative_source}"; - export default _default_import; - export * from "./{relative_source}"; - "# + import * as ns from "./{0}" + module.exports = ns; + "#, + relative_source ); Ok(Some(PluginLoadHookResult { content, diff --git a/crates/plugin_partial_bundling/src/generate_module_buckets.rs b/crates/plugin_partial_bundling/src/generate_module_buckets.rs index abd448721..38f19b024 100644 --- a/crates/plugin_partial_bundling/src/generate_module_buckets.rs +++ b/crates/plugin_partial_bundling/src/generate_module_buckets.rs @@ -234,9 +234,9 @@ mod tests { assert_eq!( HashSet::::from_iter(module_group_buckets[0].buckets.clone().into_iter()), HashSet::from([ - "__farm_unknown_false_B".to_string(), - "__farm_unknown_false_B_D".to_string(), - "__farm_unknown_false_B_D_F_G".to_string() + "js_false_B".to_string(), + "js_false_B_D".to_string(), + "js_false_B_D_F_G".to_string() ]) ); @@ -246,8 +246,8 @@ mod tests { assert_eq!( HashSet::::from_iter(module_group_buckets[1].buckets.clone().into_iter()), HashSet::from([ - "__farm_unknown_false_G".to_string(), - "__farm_unknown_false_B_D_F_G".to_string() + "js_false_G".to_string(), + "js_false_B_D_F_G".to_string() ]) ); @@ -256,7 +256,7 @@ mod tests { assert_eq!(module_group_buckets[2].buckets.len(), 1); assert_eq!( HashSet::::from_iter(module_group_buckets[2].buckets.clone().into_iter()), - HashSet::from(["__farm_unknown_false_A_F".to_string()]) + HashSet::from(["js_false_A_F".to_string()]) ); assert_eq!(module_group_buckets[3].module_group_id, "F".into()); @@ -265,9 +265,9 @@ mod tests { assert_eq!( HashSet::::from_iter(module_group_buckets[3].buckets.clone().into_iter()), HashSet::from([ - "__farm_unknown_false_F".to_string(), - "__farm_unknown_false_A_F".to_string(), - "__farm_unknown_false_B_D_F_G".to_string() + "js_false_F".to_string(), + "js_false_A_F".to_string(), + "js_false_B_D_F_G".to_string() ]) ); @@ -277,8 +277,8 @@ mod tests { assert_eq!( HashSet::::from_iter(module_group_buckets[4].buckets.clone().into_iter()), HashSet::from([ - "__farm_unknown_false_B_D_F_G".to_string(), - "__farm_unknown_false_B_D".to_string() + "js_false_B_D_F_G".to_string(), + "js_false_B_D".to_string() ]) ); } diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-2.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-2.snap index ffd0f81ab..61b6de0f4 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-2.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-2.snap @@ -1,45 +1,33 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - true, - ), - ( - "modules", - [ - ModuleId { - relative_path: "H", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "H_44bd", - ), - ( - "id", - "B_44bd", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: H_44bd +id: B_44bd +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-3.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-3.snap index a67d19cf7..7e2f4b93e 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-3.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-3.snap @@ -1,45 +1,49 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "E", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "E_a9f5", - ), - ( - "id", - "B_a9f5", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: H_44bd +id: B_44bd +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] + +------- + +name: E_a9f5 +id: B_a9f5 +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-4.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-4.snap index b687c25c6..2d494d4ef 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-4.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-4.snap @@ -1,45 +1,65 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_df7e", - ), - ( - "id", - "B_df7e", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: H_44bd +id: B_44bd +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] + +------- + +name: E_a9f5 +id: B_a9f5 +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: B_df7e +id: B_df7e +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-5.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-5.snap index e6625bc0f..5e5975448 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-5.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-5.snap @@ -1,49 +1,21 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "E", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_2f5d", - ), - ( - "id", - "B_2f5d", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-6.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-6.snap index c5ae54b7c..d4abb383a 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-6.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-6.snap @@ -1,45 +1,37 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - true, - ), - ( - "modules", - [ - ModuleId { - relative_path: "D", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "D_3f39", - ), - ( - "id", - "B_3f39", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-7.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-7.snap index ffd0f81ab..79c5e9fe3 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-7.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0-7.snap @@ -1,45 +1,53 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - true, - ), - ( - "modules", - [ - ModuleId { - relative_path: "H", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "H_44bd", - ), - ( - "id", - "B_44bd", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: H_44bd +id: B_44bd +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0.snap index c5ae54b7c..fb74caea6 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_concurrent_requests_0.snap @@ -1,45 +1,17 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - true, - ), - ( - "modules", - [ - ModuleId { - relative_path: "D", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "D_3f39", - ), - ( - "id", - "B_3f39", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-2.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-2.snap index c5ae54b7c..d4abb383a 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-2.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-2.snap @@ -1,45 +1,37 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - true, - ), - ( - "modules", - [ - ModuleId { - relative_path: "D", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "D_3f39", - ), - ( - "id", - "B_3f39", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-3.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-3.snap index ffd0f81ab..79c5e9fe3 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-3.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-3.snap @@ -1,45 +1,53 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - true, - ), - ( - "modules", - [ - ModuleId { - relative_path: "H", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "H_44bd", - ), - ( - "id", - "B_44bd", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: H_44bd +id: B_44bd +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-4.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-4.snap index c5ae54b7c..fb74caea6 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-4.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-4.snap @@ -1,45 +1,17 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - true, - ), - ( - "modules", - [ - ModuleId { - relative_path: "D", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "D_3f39", - ), - ( - "id", - "B_3f39", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-5.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-5.snap index ffd0f81ab..61b6de0f4 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-5.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-5.snap @@ -1,45 +1,33 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - true, - ), - ( - "modules", - [ - ModuleId { - relative_path: "H", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "H_44bd", - ), - ( - "id", - "B_44bd", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: H_44bd +id: B_44bd +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-6.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-6.snap index a67d19cf7..7e2f4b93e 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-6.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-6.snap @@ -1,45 +1,49 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "E", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "E_a9f5", - ), - ( - "id", - "B_a9f5", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: H_44bd +id: B_44bd +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] + +------- + +name: E_a9f5 +id: B_a9f5 +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-7.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-7.snap index b687c25c6..2d494d4ef 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-7.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0-7.snap @@ -1,45 +1,65 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_df7e", - ), - ( - "id", - "B_df7e", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: H_44bd +id: B_44bd +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] + +------- + +name: E_a9f5 +id: B_a9f5 +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: B_df7e +id: B_df7e +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0.snap index e6625bc0f..5e5975448 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_0.snap @@ -1,49 +1,21 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "E", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_2f5d", - ), - ( - "id", - "B_2f5d", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_not_enough_size-2.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_not_enough_size-2.snap index 51511dd94..6742f129a 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_not_enough_size-2.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_not_enough_size-2.snap @@ -1,49 +1,41 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "E", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_2f5d_2f5d", - ), - ( - "id", - "B_2f5d_2f5d", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: H_44bd_2328 +id: B_2328_2328 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d_2f5d +id: B_2f5d_2f5d +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_not_enough_size.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_not_enough_size.snap index b2bb0ca09..2a067acee 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_not_enough_size.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/boundaries_enforce_min_size_not_enough_size.snap @@ -1,49 +1,21 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_boundaries.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - true, - ), - ( - "modules", - [ - ModuleId { - relative_path: "D", - query_string: "", - }, - ModuleId { - relative_path: "H", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "H_44bd_2328", - ), - ( - "id", - "B_2328_2328", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: H_44bd_2328 +id: B_2328_2328 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/default-2.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/default-2.snap index 9a2e85b47..a31df1eb7 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/default-2.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/default-2.snap @@ -1,45 +1,37 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_default.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_default.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - true, - ), - ( - "modules", - [ - ModuleId { - relative_path: "D", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "D_3f39", - ), - ( - "id", - "B_3f39", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/default-3.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/default-3.snap index a0155d717..e07a7a0f5 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/default-3.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/default-3.snap @@ -1,45 +1,53 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_default.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_default.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - true, - ), - ( - "modules", - [ - ModuleId { - relative_path: "H", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "H_44bd", - ), - ( - "id", - "B_44bd", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, +] +resources: [] + +------- + +name: H_44bd +id: B_44bd +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/default.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/default.snap index ad885c204..b78b8816a 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/default.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/default.snap @@ -1,49 +1,21 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_default.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_default.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "E", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_2f5d", - ), - ( - "id", - "B_2f5d", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_concurrent_requests-2.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_concurrent_requests-2.snap index e97306a02..be413d560 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_concurrent_requests-2.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_concurrent_requests-2.snap @@ -1,49 +1,41 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_enforce_configs.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_enforce_configs.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "E", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_2f5d", - ), - ( - "id", - "B_2f5d", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: H_44bd_2328 +id: B_2328_2328 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] + +------- + +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_concurrent_requests.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_concurrent_requests.snap index 9a550bd7a..7da3763e2 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_concurrent_requests.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_concurrent_requests.snap @@ -1,49 +1,21 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_enforce_configs.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_enforce_configs.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - true, - ), - ( - "modules", - [ - ModuleId { - relative_path: "D", - query_string: "", - }, - ModuleId { - relative_path: "H", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "H_44bd_2328", - ), - ( - "id", - "B_2328_2328", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: H_44bd_2328 +id: B_2328_2328 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_min_size-2.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_min_size-2.snap index 71a10d89b..f2c357352 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_min_size-2.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_min_size-2.snap @@ -1,49 +1,41 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_enforce_configs.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_enforce_configs.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - true, - ), - ( - "modules", - [ - ModuleId { - relative_path: "D", - query_string: "", - }, - ModuleId { - relative_path: "H", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "D_3f39", - ), - ( - "id", - "B_3f39", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] + +------- + +name: D_3f39 +id: B_3f39 +immutable: true +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "D", + query_string: "", + }, + ModuleId { + relative_path: "H", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_min_size.snap b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_min_size.snap index e97306a02..8cc42575d 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_min_size.snap +++ b/crates/plugin_partial_bundling/src/merge_module_pots/snapshots/enforce_configs_min_size.snap @@ -1,49 +1,21 @@ --- source: crates/plugin_partial_bundling/src/merge_module_pots/test_enforce_configs.rs -input_file: crates/plugin_partial_bundling/src/merge_module_pots/test_enforce_configs.rs +input_file: crates/testing_helpers/src/lib.rs --- -( - ( - "immutable", - false, - ), - ( - "modules", - [ - ModuleId { - relative_path: "B", - query_string: "", - }, - ModuleId { - relative_path: "E", - query_string: "", - }, - ], - ), - ( - "resource_pot_type", - Custom( - "__farm_unknown", - ), - ), - ( - "name", - "B_2f5d", - ), - ( - "id", - "B_2f5d", - ), - ( - "entry", - None, - ), - ( - "resources", - [], - ), - ( - "module_groups", - [], - ), -) +name: B_2f5d +id: B_2f5d +immutable: false +resource_pot_type: Js +entry: None +module_groups: [] +modules: [ + ModuleId { + relative_path: "B", + query_string: "", + }, + ModuleId { + relative_path: "E", + query_string: "", + }, +] +resources: [] diff --git a/crates/plugin_progress/src/lib.rs b/crates/plugin_progress/src/lib.rs index 27ef851e8..f311824ea 100644 --- a/crates/plugin_progress/src/lib.rs +++ b/crates/plugin_progress/src/lib.rs @@ -194,8 +194,9 @@ impl Plugin for FarmPluginProgress { if *first_build { self.progress_bar.set_message(format!( - "generate resources for resource pot {}", - resource_pot.name + "generate resources for resource pot {} by {}", + resource_pot.name, + self.name() )); self.progress_bar.inc(1); } diff --git a/crates/plugin_runtime/Cargo.toml b/crates/plugin_runtime/Cargo.toml index e35f851d2..724d19d83 100644 --- a/crates/plugin_runtime/Cargo.toml +++ b/crates/plugin_runtime/Cargo.toml @@ -14,6 +14,7 @@ farmfe_core = { path = "../core", version = "0.7.0" } farmfe_toolkit = { path = "../toolkit", version = "0.0.14" } farmfe_testing_helpers = { path = "../testing_helpers", version = "0.0.14" } farmfe_utils = { path = "../utils", version = "0.1.6" } +farmfe_plugin_bundle = { path = "../plugin_bundle/" } rkyv = { version = "0.7.42" } [features] diff --git a/crates/plugin_runtime/src/lib.rs b/crates/plugin_runtime/src/lib.rs index 393113083..835be3704 100644 --- a/crates/plugin_runtime/src/lib.rs +++ b/crates/plugin_runtime/src/lib.rs @@ -219,7 +219,7 @@ impl Plugin for FarmPluginRuntime { context: &Arc, ) -> farmfe_core::error::Result> { // detect async module like top level await when module graph updated - // module graph updated is called when the module graph is updated + // module graph updated is called during compiler.update let mut async_modules = context.custom.get_mut(ASYNC_MODULES).unwrap(); let async_modules = async_modules.downcast_mut::>().unwrap(); diff --git a/crates/plugin_runtime/src/render_resource_pot/mod.rs b/crates/plugin_runtime/src/render_resource_pot/mod.rs index 76574487a..4c0f55180 100644 --- a/crates/plugin_runtime/src/render_resource_pot/mod.rs +++ b/crates/plugin_runtime/src/render_resource_pot/mod.rs @@ -16,22 +16,23 @@ use farmfe_core::{ error::{CompilationError, Result}, module::{module_graph::ModuleGraph, ModuleId}, parking_lot::Mutex, + plugin::PluginParseHookParam, rayon::iter::{IntoParallelIterator, ParallelIterator}, resource::resource_pot::{RenderedModule, ResourcePot}, serialize, }; use farmfe_toolkit::common::MinifyBuilder; -use farmfe_utils::hash::sha256; +use farmfe_utils::{hash::sha256, parse_query}; use render_module::RenderModuleOptions; +use scope_hoisting::build_scope_hoisted_module_groups; use self::render_module::{render_module, RenderModuleResult}; mod render_module; -// mod farm_module_system; +mod scope_hoisting; mod source_replacer; mod transform_async_module; -mod transform_module_decls; /// Merge all modules' ast in a [ResourcePot] to Farm's runtime [ObjectLit]. The [ObjectLit] looks like: /// ```js @@ -68,13 +69,47 @@ pub fn resource_pot_to_runtime_object( minify_builder.is_enabled(&module_id.resolved_path(&context.config.root)) }; - resource_pot - .modules() + // group modules in the same group that can perform scope hoisting + let scope_hoisting_module_groups = + build_scope_hoisted_module_groups(resource_pot, module_graph, context); + + scope_hoisting_module_groups .into_par_iter() - .try_for_each(|m_id| { + .try_for_each(|hoisted_group| { let module = module_graph - .module(m_id) - .unwrap_or_else(|| panic!("Module not found: {m_id:?}")); + .module(&hoisted_group.target_hoisted_module_id) + .unwrap_or_else(|| { + panic!( + "Module not found: {:?}", + &hoisted_group.target_hoisted_module_id + ) + }); + + let (hoisted_ast, comments) = if hoisted_group.hoisted_module_ids.len() > 1 { + let hoisted_code_bundle = hoisted_group.render(module_graph, context)?; + let code = hoisted_code_bundle.to_string(); + + let mut meta = context + .plugin_driver + .parse( + &PluginParseHookParam { + module_id: module.id.clone(), + resolved_path: module.id.resolved_path(&context.config.root), + query: parse_query(&module.id.query_string()), + module_type: module.module_type.clone(), + content: Arc::new(code), + }, + context, + &Default::default(), + )? + .unwrap(); + ( + Some(meta.as_script_mut().take_ast()), + Some(meta.as_script_mut().take_comments().into()), + ) + } else { + (None, None) + }; let mut cache_store_key = None; @@ -82,12 +117,12 @@ pub fn resource_pot_to_runtime_object( if context.config.persistent_cache.enabled() { let content_hash = module.content_hash.clone(); let store_key = CacheStoreKey { - name: m_id.to_string() + "-resource_pot_to_runtime_object", + name: module.id.to_string() + "-resource_pot_to_runtime_object", key: sha256( format!( "resource_pot_to_runtime_object_{}_{}_{}", content_hash, - m_id.to_string(), + module.id.to_string(), module.used_exports.join(",") ) .as_bytes(), @@ -115,25 +150,29 @@ pub fn resource_pot_to_runtime_object( } } - let is_async_module = async_modules.contains(m_id); + let is_async_module = async_modules.contains(&module.id); let RenderModuleResult { rendered_module, external_modules, source_map_chain, - } = render_module(RenderModuleOptions { - module, - module_graph, - is_enabled_minify, - minify_builder: &minify_builder, - is_async_module, - context, - })?; + } = render_module( + RenderModuleOptions { + module, + hoisted_ast, + module_graph, + is_enabled_minify, + minify_builder: &minify_builder, + is_async_module, + context, + }, + comments, + )?; let code = rendered_module.rendered_content.clone(); // cache the code and sourcemap if context.config.persistent_cache.enabled() { let cache_rendered_script_module = CacheRenderedScriptModule::new( - m_id.clone(), + module.id.clone(), code.clone(), rendered_module.clone(), external_modules.clone(), @@ -147,21 +186,21 @@ pub fn resource_pot_to_runtime_object( .expect("failed to write resource pot to runtime object cache"); } - let mut module = MagicString::new( + let mut magic_string = MagicString::new( &code, Some(MagicStringOptions { - filename: Some(m_id.resolved_path_with_query(&context.config.root)), + filename: Some(module.id.resolved_path_with_query(&context.config.root)), source_map_chain, ..Default::default() }), ); - module.prepend(&format!("{:?}:", m_id.id(context.config.mode.clone()))); - module.append(","); + magic_string.prepend(&format!("{:?}:", module.id.id(context.config.mode.clone()))); + magic_string.append(","); modules.lock().push(RenderedScriptModule { - id: m_id.clone(), - module, + id: module.id.clone(), + module: magic_string, rendered_module, external_modules, }); diff --git a/crates/plugin_runtime/src/render_resource_pot/render_module.rs b/crates/plugin_runtime/src/render_resource_pot/render_module.rs index b5f1e4c86..702c150e4 100644 --- a/crates/plugin_runtime/src/render_resource_pot/render_module.rs +++ b/crates/plugin_runtime/src/render_resource_pot/render_module.rs @@ -13,6 +13,7 @@ use farmfe_toolkit::{ minify::minify_js_module, script::{ codegen_module, + module2cjs::{transform_module_decls, OriginalRuntimeCallee, TransformModuleDeclsOptions}, swc_try_with::{resolve_module_mark, try_with}, CodeGenCommentsConfig, }, @@ -36,7 +37,6 @@ use farmfe_core::{ use super::{ source_replacer::{ExistingCommonJsRequireVisitor, SourceReplacer, SourceReplacerOptions}, transform_async_module, - transform_module_decls::{transform_module_decls, TransformModuleDeclsOptions}, }; pub struct RenderModuleResult { @@ -47,6 +47,7 @@ pub struct RenderModuleResult { pub struct RenderModuleOptions<'a, F: Fn(&ModuleId) -> bool> { pub module: &'a Module, + pub hoisted_ast: Option, pub module_graph: &'a ModuleGraph, pub is_enabled_minify: F, pub minify_builder: &'a MinifyBuilder, @@ -56,22 +57,25 @@ pub struct RenderModuleOptions<'a, F: Fn(&ModuleId) -> bool> { pub fn render_module<'a, F: Fn(&ModuleId) -> bool>( options: RenderModuleOptions<'a, F>, + comments: Option, ) -> farmfe_core::error::Result { let RenderModuleOptions { module, + hoisted_ast, module_graph, is_enabled_minify, minify_builder, is_async_module, context, } = options; - let mut cloned_module = module.meta.as_script().ast.clone(); + let is_use_hoisted = hoisted_ast.is_some(); + let mut cloned_module = hoisted_ast.unwrap_or(module.meta.as_script().ast.clone()); let (cm, _) = create_swc_source_map(Source { path: PathBuf::from(module.id.resolved_path_with_query(&context.config.root)), content: module.content.clone(), }); let mut external_modules = vec![]; - let comments: SingleThreadedComments = module.meta.as_script().comments.clone().into(); + let comments: SingleThreadedComments = comments.unwrap_or_else(|| module.meta.as_script().comments.clone().into()) ; let minify_enabled = is_enabled_minify(&module.id); try_with(cm.clone(), &context.meta.script.globals, || { @@ -110,6 +114,7 @@ pub fn render_module<'a, F: Fn(&ModuleId) -> bool>( transform_module_decls( &mut cloned_module, unresolved_mark, + &OriginalRuntimeCallee { unresolved_mark }, TransformModuleDeclsOptions { is_target_legacy: context.config.script.is_target_legacy(), }, @@ -124,6 +129,7 @@ pub fn render_module<'a, F: Fn(&ModuleId) -> bool>( module_id: module.id.clone(), mode: context.config.mode.clone(), target_env: context.config.output.target_env.clone(), + is_strict_find_source: !is_use_hoisted, }); cloned_module.visit_mut_with(&mut source_replacer); cloned_module.visit_mut_with(&mut hygiene_with_config(HygieneConfig { diff --git a/crates/plugin_runtime/src/render_resource_pot/scope_hoisting.rs b/crates/plugin_runtime/src/render_resource_pot/scope_hoisting.rs new file mode 100644 index 000000000..75ee53e86 --- /dev/null +++ b/crates/plugin_runtime/src/render_resource_pot/scope_hoisting.rs @@ -0,0 +1,277 @@ +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; + +use farmfe_core::{ + config::ModuleFormat, + context::CompilationContext, + enhanced_magic_string::bundle::Bundle, + module::{module_graph::ModuleGraph, ModuleId}, + resource::resource_pot::{ResourcePot, ResourcePotType}, +}; + +use farmfe_plugin_bundle::resource_pot_to_bundle::{BundleGroup, ShareBundleOptions, SharedBundle}; + +/// Note: Scope Hoisting is enabled only `config.concatenate_modules` is true. Otherwise, it A module is a [ScopeHoistedModuleGroup] +/// +/// The [ModuleId]s that can be hoisted into the same Module. For example: +/// ```md +/// A F +/// / \ / +/// B C +/// / \ +/// D E +/// ``` +/// The [ModuleId]s of `A`, `B`, `D`, `E` can be hoisted into the same Module `A`. But `C` cannot cause C has 2 independencies. + +#[derive(Debug, PartialEq, Eq)] +pub struct ScopeHoistedModuleGroup { + /// The [ModuleId] that other modules hoisted to, it's the entry of this [ScopeHoistedModuleGroup]. + pub target_hoisted_module_id: ModuleId, + /// The [ModuleId]s that this [ScopeHoistedModuleGroup] hoisted to. Include the [target_hoisted_module_id]. + pub hoisted_module_ids: HashSet, +} + +impl ScopeHoistedModuleGroup { + pub fn new(target_hoisted_module_id: ModuleId) -> Self { + Self { + hoisted_module_ids: HashSet::from([target_hoisted_module_id.clone()]), + target_hoisted_module_id, + } + } + + pub fn extend_hoisted_module_ids(&mut self, hoisted_module_ids: HashSet) { + self.hoisted_module_ids.extend(hoisted_module_ids); + } + + /// Render this [ScopeHoistedModuleGroup] to a Farm runtime module. For example: + /// ```js + /// function(module, exports, farmRequire, farmDynamicRequire) { + /// const xxx = farmDynamicRequire('./xxx'); + /// + /// const module_D = 'D'; // hoisted code of module D + /// const module_C = 'C'; // hoisted code of module C + /// const module_B = 'B'; // hoisted code of module B + /// console.log(module_D, module_C, module_B, xxx); // code of module A + /// + /// module.o(exports, 'b', module_B); + /// } + /// ``` + pub fn render( + &self, + module_graph: &ModuleGraph, + context: &Arc, + ) -> farmfe_core::error::Result { + let bundle_id = self.target_hoisted_module_id.to_string(); + + let mut share_bundle = SharedBundle::new( + vec![BundleGroup { + id: bundle_id.clone(), + modules: self.hoisted_module_ids.iter().collect(), + entry_module: Some(self.target_hoisted_module_id.clone()), + group_type: ResourcePotType::Js, + }], + module_graph, + context, + Some(ShareBundleOptions { + reference_slot: false, + ignore_external_polyfill: true, + // should ignore + format: ModuleFormat::EsModule, + hash_path: true, + concatenation_module: true, + ..Default::default() + }), + )?; + + share_bundle.render()?; + share_bundle.codegen(&bundle_id) + } +} + +/// Handle the modules of a resource pot in topological order. +/// Merge the modules into a [ScopeHoistedModuleGroup] if all of the dependents of that module are in the same [ScopeHoistedModuleGroup]. +/// +/// Note: A module is a [ScopeHoistedModuleGroup] if config.concatenate_modules is false. +pub fn build_scope_hoisted_module_groups( + resource_pot: &ResourcePot, + module_graph: &ModuleGraph, + context: &Arc, +) -> Vec { + let mut scope_hoisted_module_groups_map = HashMap::new(); + let mut reverse_module_hoisted_group_map = HashMap::new(); + + for module_id in resource_pot.modules() { + scope_hoisted_module_groups_map.insert( + module_id.clone(), + ScopeHoistedModuleGroup::new(module_id.clone()), + ); + reverse_module_hoisted_group_map.insert(module_id.clone(), module_id.clone()); + } + // println!( + // "scope_hoisted_module_groups_map: {:?}", + // scope_hoisted_module_groups_map + // ); + // Merge ScopeHoistedModuleGroup when concatenate_modules enabled + if context.config.concatenate_modules { + let mut scope_hoisted_module_groups = scope_hoisted_module_groups_map + .values() + .collect::>(); + // 1. topological sort + scope_hoisted_module_groups.sort_by(|a, b| { + let ma = module_graph.module(&a.target_hoisted_module_id).unwrap(); + let mb = module_graph.module(&b.target_hoisted_module_id).unwrap(); + // larger execution_order means it's the importer + mb.execution_order.cmp(&ma.execution_order) + }); + + let mut merged_scope_hoisted_module_groups_map: HashMap> = + HashMap::new(); + + for group in scope_hoisted_module_groups { + let module = module_graph + .module(&group.target_hoisted_module_id) + .unwrap(); + // if this module is not an esm module, skip it + if !module.meta.as_script().is_esm() { + continue; + } + + let dependents = module_graph.dependents_ids(&group.target_hoisted_module_id); + // there dependents of this module are not in this resource pot + if dependents.iter().any(|id| { + !resource_pot.has_module(id) + || !module_graph + .module(id) + .is_some_and(|m| m.meta.as_script().is_esm()) + }) { + continue; + } + + let dependents_hoisted_group_ids = dependents + .into_iter() + .map(|id| reverse_module_hoisted_group_map.get(&id).unwrap().clone()) + .collect::>(); + + // all of the dependents of this module are in the same [ScopeHoistedModuleGroup] + if dependents_hoisted_group_ids.len() == 1 { + let dependents_hoisted_group_id = dependents_hoisted_group_ids.into_iter().next().unwrap(); + + // if execution_order of dependents_hoisted_group_id is smaller than this module, means there is a cycle, skip it + let dependents_hoisted_group_module = + module_graph.module(&dependents_hoisted_group_id).unwrap(); + + if dependents_hoisted_group_module.execution_order + < module_graph + .module(&group.target_hoisted_module_id) + .unwrap() + .execution_order + { + continue; + } + + let merged_map = merged_scope_hoisted_module_groups_map + .entry(dependents_hoisted_group_id.clone()) + .or_default(); + merged_map.insert(group.target_hoisted_module_id.clone()); + + for hoisted_module_id in &group.hoisted_module_ids { + reverse_module_hoisted_group_map.insert( + hoisted_module_id.clone(), + dependents_hoisted_group_id.clone(), + ); + } + } + } + + for (target_hoisted_module_id, hoisted_module_ids) in + merged_scope_hoisted_module_groups_map.into_iter() + { + let mut all_hoisted_module_ids = HashSet::new(); + + for hoisted_module_id in hoisted_module_ids { + let hoisted_module_group = scope_hoisted_module_groups_map + .remove(&hoisted_module_id) + .unwrap(); + all_hoisted_module_ids.extend(hoisted_module_group.hoisted_module_ids); + } + + let target_hoisted_module_group = scope_hoisted_module_groups_map + .get_mut(&target_hoisted_module_id) + .unwrap(); + + target_hoisted_module_group.extend_hoisted_module_ids(all_hoisted_module_ids); + } + } + + let mut res = scope_hoisted_module_groups_map + .into_values() + .collect::>(); + res.sort_by_key(|group| group.target_hoisted_module_id.to_string()); + + res +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + + use farmfe_core::{ + config::Config, + context::CompilationContext, + resource::resource_pot::{ResourcePot, ResourcePotType}, + }; + use farmfe_testing_helpers::construct_test_module_graph; + + #[test] + fn test_build_scope_hoisted_module_groups() { + let mut module_graph = construct_test_module_graph(); + module_graph.update_execution_order_for_modules(); + + let mut resource_pot = ResourcePot::new("test".to_string(), ResourcePotType::Js); + + for module in module_graph.modules() { + resource_pot.add_module(module.id.clone()); + } + + let context = CompilationContext::new( + Config { + concatenate_modules: true, + ..Default::default() + }, + vec![], + ) + .unwrap(); + + let scope_hoisted_module_groups = super::build_scope_hoisted_module_groups( + &resource_pot, + &module_graph, + &std::sync::Arc::new(context), + ); + + println!("{:#?}", scope_hoisted_module_groups); + // groups: (A, C), (B, E, G), (F), (D) + assert_eq!( + scope_hoisted_module_groups, + vec![ + super::ScopeHoistedModuleGroup { + target_hoisted_module_id: "A".into(), + hoisted_module_ids: HashSet::from(["A".into(), "C".into(),]), + }, + super::ScopeHoistedModuleGroup { + target_hoisted_module_id: "B".into(), + hoisted_module_ids: HashSet::from(["B".into(), "E".into(), "G".into(),]), + }, + super::ScopeHoistedModuleGroup { + target_hoisted_module_id: "D".into(), + hoisted_module_ids: HashSet::from(["D".into(),]), + }, + super::ScopeHoistedModuleGroup { + target_hoisted_module_id: "F".into(), + hoisted_module_ids: HashSet::from(["F".into(),]), + }, + ] + ); + } +} diff --git a/crates/plugin_runtime/src/render_resource_pot/source_replacer.rs b/crates/plugin_runtime/src/render_resource_pot/source_replacer.rs index ddd3b3601..f8e77775b 100644 --- a/crates/plugin_runtime/src/render_resource_pot/source_replacer.rs +++ b/crates/plugin_runtime/src/render_resource_pot/source_replacer.rs @@ -36,6 +36,7 @@ pub struct SourceReplacer<'a> { mode: Mode, pub external_modules: Vec, target_env: TargetEnv, + is_strict_find_source: bool, } pub struct SourceReplacerOptions<'a> { @@ -45,6 +46,7 @@ pub struct SourceReplacerOptions<'a> { pub module_id: ModuleId, pub mode: Mode, pub target_env: TargetEnv, + pub is_strict_find_source: bool, } impl<'a> SourceReplacer<'a> { @@ -56,6 +58,7 @@ impl<'a> SourceReplacer<'a> { module_id, mode, target_env, + is_strict_find_source, } = options; Self { @@ -66,6 +69,7 @@ impl<'a> SourceReplacer<'a> { mode, external_modules: vec![], target_env, + is_strict_find_source, } } } @@ -136,13 +140,17 @@ impl SourceReplacer<'_> { ctxt: SyntaxContext::empty(), }))); - let (id, resolve_kind) = - (self.find_real_module_meta_by_source(&source)).unwrap_or_else(|| { + let Some((id, resolve_kind)) = self.find_real_module_meta_by_source(&source) else { + if self.is_strict_find_source { panic!( "Cannot find module id for source {:?} from {:?}", source, self.module_id ) - }); + } + + return SourceReplaceResult::NotReplaced; + }; + // only execute script module let dep_module = self.module_graph.module(&id).unwrap(); @@ -150,7 +158,7 @@ impl SourceReplacer<'_> { if matches!(resolve_kind, ResolveKind::Require) && matches!(self.target_env, TargetEnv::Node) { - // transform require("external") to global.nodeRequire("external") + // transform require("external") to globalThis.nodeRequire("external") call_expr.callee = Callee::Expr(Box::new(Expr::Member(MemberExpr { span: DUMMY_SP, obj: Box::new(Expr::Ident("global".into())), @@ -183,20 +191,33 @@ impl SourceReplacer<'_> { { let source = str.value.to_string(); - let id = self.module_graph.get_dep_by_source( + if let Some(id) = self.module_graph.get_dep_by_source_optional( &self.module_id, &source, Some(ResolveKind::DynamicImport), - ); - // only execute script module - let dep_module = self.module_graph.module(&id).unwrap(); + ) { + // only execute script module + let dep_module = self.module_graph.module(&id).unwrap(); - if dep_module.external { - self.external_modules.push(id.to_string()); + if dep_module.external { + self.external_modules.push(id.to_string()); - return SourceReplaceResult::NotReplaced; + return SourceReplaceResult::NotReplaced; + } + + str.value = id.id(self.mode.clone()).into(); + str.span = DUMMY_SP; + str.raw = None; + } else if self.is_strict_find_source { + panic!( + "cannot found {} of DynamicImport from {}", + source, + self.module_id.to_string() + ); } + // in partial ShareBundle, `module source` already rewrite at DynamicImportReplacer stage + // so, even not found module by source, still replace `require` call_expr.callee = Callee::Expr(Box::new(Expr::Ident(Ident { span: DUMMY_SP, sym: FARM_DYNAMIC_REQUIRE.into(), @@ -204,9 +225,6 @@ impl SourceReplacer<'_> { ctxt: SyntaxContext::empty(), }))); - str.value = id.id(self.mode.clone()).into(); - str.span = DUMMY_SP; - str.raw = None; return SourceReplaceResult::Replaced; } } diff --git a/crates/testing_helpers/src/assert.rs b/crates/testing_helpers/src/assert.rs index d92f5c74b..8f7a7e156 100644 --- a/crates/testing_helpers/src/assert.rs +++ b/crates/testing_helpers/src/assert.rs @@ -1,6 +1,7 @@ #[macro_export] macro_rules! assert_resource_pots { - ($resource_pots:expr) => { + ($resource_pots:expr) => {{ + let mut output: Vec = Vec::new(); for resource_pot in $resource_pots { let mut resources = resource_pot.resources(); let mut module_groups = resource_pot.module_groups.iter().collect::>(); @@ -8,27 +9,39 @@ macro_rules! assert_resource_pots { resources.sort(); module_groups.sort_by_key(|a| a.to_string()); - farmfe_testing_helpers::assert_debug_snapshot!(( - ("immutable", resource_pot.immutable), - ("modules", resource_pot.modules()), - ("resource_pot_type", &resource_pot.resource_pot_type), - ("name", &resource_pot.name), - ("id", &resource_pot.id), - ("entry", &resource_pot.entry_module), - ("resources", resources), - ("module_groups", module_groups), - )); + output.push( + format!( + "name: {} +id: {} +immutable: {} +resource_pot_type: {:?} +entry: {:#?} +module_groups: {:#?} +modules: {:#?} +resources: {:#?}", + &resource_pot.name, + &resource_pot.id, + resource_pot.immutable, + &resource_pot.resource_pot_type, + &resource_pot.entry_module, + module_groups, + resource_pot.modules(), + resources, + ), + ); + + farmfe_testing_helpers::assert_snapshot!(output.join("\n\n-------\n\n")); } - }; + }}; } #[macro_export] macro_rules! assert_sorted_iter_eq { - ($v:expr) => { + ($v:expr) => {{ let mut left = ($v).iter().cloned().collect::>(); left.sort(); farmfe_testing_helpers::assert_debug_snapshot!(left); - }; + }}; } diff --git a/crates/testing_helpers/src/lib.rs b/crates/testing_helpers/src/lib.rs index 034115efe..e5527e020 100644 --- a/crates/testing_helpers/src/lib.rs +++ b/crates/testing_helpers/src/lib.rs @@ -5,7 +5,7 @@ use farmfe_core::{ module::{ module_graph::{ModuleGraph, ModuleGraphEdgeDataItem}, module_group::{ModuleGroup, ModuleGroupGraph}, - Module, + Module, ModuleMetaData, ModuleType, ScriptModuleMetaData, }, plugin::ResolveKind, relative_path::RelativePath, @@ -14,17 +14,35 @@ use farmfe_core::{ pub mod assert; pub use insta; +use insta::Settings; -#[macro_export] -macro_rules! assert_debug_snapshot { - ($ex:expr) => { - let mut setting = farmfe_testing_helpers::insta::Settings::clone_current(); +pub struct InstaHelper {} + +impl InstaHelper { + pub fn create_setting() -> Settings { + let mut setting = Settings::clone_current(); setting.set_sort_maps(true); setting.set_omit_expression(true); setting.set_input_file(file!()); setting.set_prepend_module_to_snapshot(false); - setting.bind(|| { - farmfe_testing_helpers::insta::assert_debug_snapshot!($ex); + setting + } +} + +#[macro_export] +macro_rules! assert_debug_snapshot { + ($ex:expr) => { + farmfe_testing_helpers::InstaHelper::create_setting().bind(|| { + farmfe_testing_helpers::insta::assert_debug_snapshot!($ex) + }); + }; +} + +#[macro_export] +macro_rules! assert_snapshot { + ($ex:expr) => { + farmfe_testing_helpers::InstaHelper::create_setting().bind(|| { + farmfe_testing_helpers::insta::assert_snapshot!($ex) }); }; } @@ -51,7 +69,9 @@ pub fn construct_test_module_graph() -> ModuleGraph { let mut graph = ModuleGraph::new(); for id in module_ids { - let m = Module::new(id); + let mut m = Module::new(id); + m.module_type = ModuleType::Js; + m.meta = Box::new(ModuleMetaData::Script(ScriptModuleMetaData::default())); graph.add_module(m); } @@ -176,7 +196,8 @@ pub fn construct_test_module_group_graph() -> ModuleGroupGraph { /// * others are static dependencies pub fn construct_test_module_graph_complex() -> ModuleGraph { let mut test_module_graph = construct_test_module_graph(); - let module_h = Module::new("H".into()); + let mut module_h = Module::new("H".into()); + module_h.module_type = ModuleType::Js; test_module_graph.add_module(module_h); let static_edges = vec![("D", "H", 1), ("F", "H", 0), ("G", "H", 0)]; diff --git a/crates/toolkit/Cargo.toml b/crates/toolkit/Cargo.toml index 012ee2c4a..881fb4990 100644 --- a/crates/toolkit/Cargo.toml +++ b/crates/toolkit/Cargo.toml @@ -51,3 +51,4 @@ swc_ecma_utils = "4.0.0" lazy_static = "1.4.0" sourcemap = "9.0.0" anyhow = { version = "1.0.90", features = ["backtrace"] } +itertools = "0.13.0" diff --git a/crates/toolkit/src/constant.rs b/crates/toolkit/src/constant.rs new file mode 100644 index 000000000..0b065d3d5 --- /dev/null +++ b/crates/toolkit/src/constant.rs @@ -0,0 +1 @@ +pub const RUNTIME_SUFFIX: &str = ".farm-runtime"; \ No newline at end of file diff --git a/crates/toolkit/src/lib.rs b/crates/toolkit/src/lib.rs index 5e0c720d9..aef57ec8c 100644 --- a/crates/toolkit/src/lib.rs +++ b/crates/toolkit/src/lib.rs @@ -37,9 +37,11 @@ pub use anyhow; pub use farmfe_core::regex; pub use lazy_static; pub use sourcemap; +pub use itertools; pub mod get_dynamic_resources_map; pub mod minify; // pluginutils pub mod pluginutils; +pub mod constant; diff --git a/crates/toolkit/src/script/mod.rs b/crates/toolkit/src/script/mod.rs index 43b42318d..654abc525 100644 --- a/crates/toolkit/src/script/mod.rs +++ b/crates/toolkit/src/script/mod.rs @@ -33,6 +33,7 @@ use self::swc_try_with::try_with; pub mod defined_idents_collector; pub mod swc_try_with; pub mod constant; +pub mod module2cjs; /// parse the content of a module to [SwcModule] ast. pub fn parse_module( diff --git a/crates/plugin_runtime/src/render_resource_pot/transform_module_decls.rs b/crates/toolkit/src/script/module2cjs.rs similarity index 83% rename from crates/plugin_runtime/src/render_resource_pot/transform_module_decls.rs rename to crates/toolkit/src/script/module2cjs.rs index 35d63c48f..87e7a126e 100644 --- a/crates/plugin_runtime/src/render_resource_pot/transform_module_decls.rs +++ b/crates/toolkit/src/script/module2cjs.rs @@ -1,5 +1,9 @@ use std::{collections::HashMap, ffi::OsStr}; +use crate::{ + script::defined_idents_collector::DefinedIdentsCollector, + swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith}, +}; use farmfe_core::{ regex::Regex, swc_common::{util::take::Take, Mark, SyntaxContext, DUMMY_SP}, @@ -12,10 +16,162 @@ use farmfe_core::{ ReturnStmt, SimpleAssignTarget, Stmt, Str, VarDecl, VarDeclKind, VarDeclarator, }, }; -use farmfe_toolkit::{ - script::defined_idents_collector::DefinedIdentsCollector, - swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith}, -}; + +/// +/// only return fn name +/// +pub trait RuntimeCalleeAllocator { + /// + /// ```js + /// Object.defineProperty(to, to_k, { + /// enumerable: true, + /// get + /// }); + /// + /// ``` + /// ```ts + /// #fn(target: object, to_k: string, get: () => any); + /// ``` + /// + fn define_property_callee(&self) -> Box { + unimplemented!() + } + + /// + /// ```js + /// exports.xx = xx + /// ``` + /// + /// ```ts + /// #fn(to: object, to_k: string, val: any) + /// ``` + /// + fn cjs_export_named_callee(&self) -> Box { + unimplemented!() + } + + /// + /// ```js + /// Object.defineProperty(target, "__esModule", { + /// value: true, + /// }) + /// ``` + /// + /// ```js + /// #fn(target: Object) + /// ``` + /// + fn es_module_flag_callee(&self) -> Box { + unimplemented!() + } + + /// + /// ```js + /// `export * from` + /// ``` + /// + /// ```ts + /// #fn(to: object, from: object) + /// ``` + /// + fn export_star_callee(&self) -> Box { + unimplemented!() + } + + /// + /// ```js + /// `import default from` + /// ``` + /// + /// ```ts + /// #fn(obj: object).default + /// ``` + /// + fn import_default_callee(&self) -> Box { + unimplemented!() + } + + /// + /// ```js + /// `import * as ns from` + /// ``` + /// + /// ```ts + /// #fn(obj: object, nodeInterop: any); + /// ``` + /// + fn import_namespace_callee(&self) -> Box { + unimplemented!() + } + + /// + /// ```js + /// export { xx } from "helper" + /// ``` + /// + /// ```ts + /// #fn(target: object, to_k: string, from_k: string); + /// ``` + /// + fn esm_export_named_callee(&self) -> Box { + unimplemented!() + } + + /// xxx.default + fn interop_default(&self) -> Box { + unimplemented!() + } +} + +pub struct OriginalRuntimeCallee { + pub unresolved_mark: Mark, +} + +fn create_module_member_expr(ident: &str, unresolved_mark: Mark) -> Expr { + Expr::Member(MemberExpr { + span: DUMMY_SP, + obj: Box::new(Expr::Ident(Ident::new( + FARM_MODULE_SYSTEM_MODULE.into(), + DUMMY_SP, + SyntaxContext::empty().apply_mark(unresolved_mark), + ))), + prop: MemberProp::Ident(ident.into()), + }) +} + +impl RuntimeCalleeAllocator for OriginalRuntimeCallee { + fn define_property_callee(&self) -> Box { + Box::new(create_module_member_expr("o", self.unresolved_mark)) + } + + fn es_module_flag_callee(&self) -> Box { + Box::new(create_module_member_expr("_m", self.unresolved_mark)) + } + + fn export_star_callee(&self) -> Box { + Box::new(create_module_member_expr("_e", self.unresolved_mark)) + } + + fn esm_export_named_callee(&self) -> Box { + Box::new(create_module_member_expr("_", self.unresolved_mark)) + } + + fn import_namespace_callee(&self) -> Box { + Box::new(create_module_member_expr("w", self.unresolved_mark)) + } + + fn cjs_export_named_callee(&self) -> Box { + Box::new(create_module_member_expr("d", self.unresolved_mark)) + } + + fn interop_default(&self) -> Box { + Box::new(create_module_member_expr("f", self.unresolved_mark)) + } + + fn import_default_callee(&self) -> Box { + Box::new(create_module_member_expr("i", self.unresolved_mark)) + } +} const FARM_MODULE_SYSTEM_MODULE: &str = "module"; const FARM_MODULE_SYSTEM_REQUIRE: &str = "require"; @@ -61,9 +217,10 @@ pub struct TransformModuleDeclsOptions { /// module._e(exports, require("./d")); /// /// ``` -pub fn transform_module_decls( +pub fn transform_module_decls( ast: &mut SwcModule, unresolved_mark: Mark, + callee_allocator: &F, options: TransformModuleDeclsOptions, ) { let mut items = vec![]; @@ -83,22 +240,30 @@ pub fn transform_module_decls( import_items.extend(transform_import_decl( import_decl, unresolved_mark, + callee_allocator, &mut import_bindings_map, )); } ModuleDecl::ExportDecl(export_decl) => { - let export = transform_export_decl(export_decl, unresolved_mark, &options); + let export = + transform_export_decl(export_decl, callee_allocator, unresolved_mark, &options); items.extend(export.declare_items); export_items.extend(export.export_items); } ModuleDecl::ExportNamed(export_named) => { - let export = transform_export_named(export_named, unresolved_mark, &options); + let export = + transform_export_named(export_named, unresolved_mark, callee_allocator, &options); items.extend(export.declare_items); export_items.extend(export.export_items); } ModuleDecl::ExportDefaultDecl(default_decl) => { - let export = transform_export_default_decl(default_decl, unresolved_mark, &options); + let export = transform_export_default_decl( + default_decl, + callee_allocator, + unresolved_mark, + &options, + ); items.extend(export.declare_items); export_items.extend(export.export_items); } @@ -106,13 +271,18 @@ pub fn transform_module_decls( items.extend(transform_export_default_expr(export_expr, unresolved_mark)); } ModuleDecl::ExportAll(export_all) => { - items.extend(transform_export_all(export_all, unresolved_mark)); + items.extend(transform_export_all( + export_all, + callee_allocator, + unresolved_mark, + )); } ModuleDecl::TsImportEquals(_) | ModuleDecl::TsExportAssignment(_) | ModuleDecl::TsNamespaceExport(_) => unreachable!(), } } + ModuleItem::Stmt(stmt) => items.push(ModuleItem::Stmt(stmt)), } } @@ -136,7 +306,7 @@ pub fn transform_module_decls( span: DUMMY_SP, expr: Box::new(Expr::Call(CallExpr { span: DUMMY_SP, - callee: create_module_helper_callee("_m", unresolved_mark), + callee: Callee::Expr(callee_allocator.es_module_flag_callee()), args: vec![ExprOrSpread { spread: None, expr: Box::new(Expr::Ident(create_exports_ident(unresolved_mark))), @@ -154,6 +324,7 @@ pub fn transform_module_decls( fn transform_import_decl( import_decl: ImportDecl, unresolved_mark: Mark, + callee_allocator: &dyn RuntimeCalleeAllocator, import_bindings_map: &mut HashMap, ) -> Vec { let mut items = vec![]; @@ -198,19 +369,18 @@ fn transform_import_decl( contains_default = true; // module.f(val_name_ident) let init = create_module_helper_call_expr( - "f", + callee_allocator.interop_default(), vec![ExprOrSpread { spread: None, expr: Box::new(Expr::Ident(val_name_ident.clone())), }], - unresolved_mark, ); import_bindings_map.insert(specifier.local.to_id(), Expr::Call(init)); } ImportSpecifier::Namespace(specifier) => { items.push(create_module_helper_item( - "w", + callee_allocator.import_namespace_callee(), val_name_ident.clone(), *import_decl.src.clone(), unresolved_mark, @@ -225,14 +395,14 @@ fn transform_import_decl( if contains_named && contains_default { items.push(create_module_helper_item( - "w", + callee_allocator.import_namespace_callee(), val_name_ident.clone(), *import_decl.src.clone(), unresolved_mark, )); } else if contains_default { items.push(create_module_helper_item( - "i", + callee_allocator.import_default_callee(), val_name_ident.clone(), *import_decl.src.clone(), unresolved_mark, @@ -250,6 +420,7 @@ fn transform_import_decl( fn transform_export_decl( export_decl: ExportDecl, + callee_allocator: &dyn RuntimeCalleeAllocator, unresolved_mark: Mark, options: &TransformModuleDeclsOptions, ) -> ExportModuleItem { @@ -264,6 +435,7 @@ fn transform_export_decl( Some(class_decl.ident.clone()), class_decl.ident, class_decl.class, + callee_allocator, unresolved_mark, options.is_target_legacy, ) @@ -273,6 +445,7 @@ fn transform_export_decl( Some(fn_decl.ident.clone()), fn_decl.ident, fn_decl.function, + callee_allocator, unresolved_mark, options.is_target_legacy, ) @@ -293,6 +466,7 @@ fn transform_export_decl( let call_expr = create_define_export_property_ident_call_expr( None, ident, + callee_allocator, unresolved_mark, options.is_target_legacy, ); @@ -317,6 +491,7 @@ fn transform_export_decl( fn transform_export_named( named_export: NamedExport, unresolved_mark: Mark, + callee_allocator: &dyn RuntimeCalleeAllocator, options: &TransformModuleDeclsOptions, ) -> ExportModuleItem { let mut items = vec![]; @@ -335,13 +510,14 @@ fn transform_export_named( let call_expr = create_define_export_property_ident_call_expr( Some(ident.to_id()), ident.to_id(), + callee_allocator, unresolved_mark, options.is_target_legacy, ); export_items.push(create_module_item_from_call_expr(call_expr)); // var ident = module.w(require(src)) items.push(create_module_helper_item( - "w", + callee_allocator.import_namespace_callee(), ident, *named_export.src.clone().unwrap(), unresolved_mark, @@ -399,13 +575,15 @@ fn transform_export_named( cached_export_from_item = Some(export_from_ident); // module._(exports, exported_ident, export_from_ident, local_ident) - let call_expr = create_module_helper_call_expr("_", args, unresolved_mark); + let call_expr = + create_module_helper_call_expr(callee_allocator.esm_export_named_callee(), args); extra_items.push(create_module_item_from_call_expr(call_expr)); } else { let call_expr = create_define_export_property_ident_call_expr( Some(exported_ident.to_id()), local_ident.to_id(), + callee_allocator, unresolved_mark, options.is_target_legacy, ); @@ -421,14 +599,14 @@ fn transform_export_named( if let Some(export_from_ident) = cached_export_from_item { if contains_named && contains_default { items.push(create_module_helper_item( - "w", + callee_allocator.import_namespace_callee(), export_from_ident.clone(), *named_export.src.clone().unwrap(), unresolved_mark, )); } else if contains_default { items.push(create_module_helper_item( - "i", + callee_allocator.import_default_callee(), export_from_ident.clone(), *named_export.src.clone().unwrap(), unresolved_mark, @@ -452,6 +630,7 @@ fn transform_export_named( fn transform_export_default_decl( default_decl: ExportDefaultDecl, + callee_allocator: &dyn RuntimeCalleeAllocator, unresolved_mark: Mark, options: &TransformModuleDeclsOptions, ) -> ExportModuleItem { @@ -466,6 +645,7 @@ fn transform_export_default_decl( class_decl.ident, exported_ident, class_decl.class, + callee_allocator, unresolved_mark, options.is_target_legacy, ); @@ -480,6 +660,7 @@ fn transform_export_default_decl( fn_decl.ident, exported_ident, fn_decl.function, + callee_allocator, unresolved_mark, options.is_target_legacy, ); @@ -488,11 +669,14 @@ fn transform_export_default_decl( } } +// export default 'foo'; +// export default foo; fn transform_export_default_expr( export_expr: ExportDefaultExpr, unresolved_mark: Mark, ) -> Vec { let mut items = vec![]; + let exports_assign_left = create_exports_assign_left( Ident::new( FARM_MODULE_SYSTEM_DEFAULT.into(), @@ -501,6 +685,7 @@ fn transform_export_default_expr( ), unresolved_mark, ); + items.push(create_exports_assign_stmt( exports_assign_left, *export_expr.expr, @@ -508,13 +693,18 @@ fn transform_export_default_expr( items } -fn transform_export_all(export_all: ExportAll, unresolved_mark: Mark) -> Vec { +fn transform_export_all( + export_all: ExportAll, + callee_allocator: &dyn RuntimeCalleeAllocator, + unresolved_mark: Mark, +) -> Vec { let mut items = vec![]; let (require_item, val_name_ident) = create_require_stmt(*export_all.src, unresolved_mark); items.push(require_item); // module._e(exports, val_name_ident) - let callee = create_module_helper_callee("_e", unresolved_mark); + let callee = Callee::Expr(callee_allocator.export_star_callee()); + let call_expr = Expr::Call(CallExpr { span: DUMMY_SP, callee, @@ -644,6 +834,7 @@ fn create_export_fn_decl_stmts( fn_ident: Option, exports_ident: Ident, function: Box, + callee_allocator: &dyn RuntimeCalleeAllocator, unresolved_mark: Mark, is_target_legacy: bool, ) -> ExportModuleItem { @@ -673,6 +864,7 @@ fn create_export_fn_decl_stmts( let call_expr = create_define_export_property_ident_call_expr( Some(exports_ident.to_id()), ident.to_id(), + callee_allocator, unresolved_mark, is_target_legacy, ); @@ -694,6 +886,7 @@ fn create_export_class_decl_stmts( class_ident: Option, exports_ident: Ident, class: Box, + callee_allocator: &dyn RuntimeCalleeAllocator, unresolved_mark: Mark, is_target_legacy: bool, ) -> ExportModuleItem { @@ -720,6 +913,7 @@ fn create_export_class_decl_stmts( let call_expr = create_define_export_property_ident_call_expr( Some(exports_ident.to_id()), ident.to_id(), + callee_allocator, unresolved_mark, is_target_legacy, ); @@ -737,21 +931,20 @@ fn create_export_class_decl_stmts( export } -fn create_module_helper_callee(helper: &str, unresolved_mark: Mark) -> Callee { - let prop = IdentName::new(helper.into(), DUMMY_SP); - Callee::Expr(Box::new(Expr::Member(MemberExpr { - span: DUMMY_SP, - obj: Box::new(Expr::Ident(Ident::new( - FARM_MODULE_SYSTEM_MODULE.into(), - DUMMY_SP, - SyntaxContext::empty().apply_mark(unresolved_mark), - ))), - prop: MemberProp::Ident(prop), - }))) -} +// fn create_module_helper_callee(helper: &str, unresolved_mark: Mark) -> Callee { +// let prop = Ident::new(helper.into(), DUMMY_SP); +// Callee::Expr(Box::new(Expr::Member(MemberExpr { +// span: DUMMY_SP, +// obj: Box::new(Expr::Ident(Ident::new( +// FARM_MODULE_SYSTEM_MODULE.into(), +// DUMMY_SP.apply_mark(unresolved_mark), +// ))), +// prop: MemberProp::Ident(prop), +// }))) +// } fn create_module_helper_item( - helper: &str, + helper: Box, val_name_ident: Ident, src: Str, unresolved_mark: Mark, @@ -765,17 +958,12 @@ fn create_module_helper_item( Box::new(Expr::Call(create_module_helper_call_expr( helper, vec![prop], - unresolved_mark, ))), ) } -fn create_module_helper_call_expr( - helper: &str, - args: Vec, - unresolved_mark: Mark, -) -> CallExpr { - let callee = create_module_helper_callee(helper, unresolved_mark); +fn create_module_helper_call_expr(helper: Box, args: Vec) -> CallExpr { + let callee = Callee::Expr(helper); let call_expr = CallExpr { span: DUMMY_SP, callee, @@ -789,6 +977,7 @@ fn create_module_helper_call_expr( fn create_define_export_property_ident_call_expr( exported_ident: Option, local_ident: Id, + callee_allocator: &dyn RuntimeCalleeAllocator, unresolved_mark: Mark, is_target_legacy: bool, ) -> CallExpr { @@ -841,7 +1030,7 @@ fn create_define_export_property_ident_call_expr( }; // module.o(exports, ident, function(){return ident;}) create_module_helper_call_expr( - "o", + callee_allocator.define_property_callee(), vec![ ExprOrSpread { spread: None, @@ -860,7 +1049,6 @@ fn create_define_export_property_ident_call_expr( expr: Box::new(expr), }, ], - unresolved_mark, ) } @@ -934,11 +1122,11 @@ impl VisitMut for ImportBindingsHandler { mod tests { use std::sync::Arc; - use farmfe_core::{swc_common::Globals, swc_ecma_ast::EsVersion, swc_ecma_parser::Syntax}; - use farmfe_toolkit::{ + use crate::{ common::{create_swc_source_map, Source}, script::{codegen_module, parse_module, swc_try_with::try_with}, }; + use farmfe_core::{swc_common::Globals, swc_ecma_ast::EsVersion, swc_ecma_parser::Syntax}; use super::*; @@ -991,9 +1179,14 @@ export * from './e'; .ast; try_with(cm.clone(), &Globals::new(), || { + let callee_allocator = OriginalRuntimeCallee { + unresolved_mark: Mark::new(), + }; + transform_module_decls( &mut ast, Mark::new(), + &callee_allocator, TransformModuleDeclsOptions { is_target_legacy: true, }, @@ -1090,9 +1283,13 @@ export const f = 1, h = 2; .ast; try_with(cm.clone(), &Globals::new(), || { + let callee_allocator = OriginalRuntimeCallee { + unresolved_mark: Mark::new(), + }; transform_module_decls( &mut ast, Mark::new(), + &callee_allocator, TransformModuleDeclsOptions { is_target_legacy: false, }, diff --git a/cspell.json b/cspell.json index e4eefd39e..56ee9b0f1 100644 --- a/cspell.json +++ b/cspell.json @@ -112,6 +112,7 @@ "Glvyg", "gnueabihf", "guolao", + "Gurubase", "hashbrown", "hasher", "Hensel", @@ -130,6 +131,7 @@ "instanceof", "Instantiator", "JDEL", + "itertools", "jfif", "JIDA", "jquery", diff --git a/docs/docs/contribution.mdx b/docs/docs/contribution.mdx index 3e217e251..026d1d644 100644 --- a/docs/docs/contribution.mdx +++ b/docs/docs/contribution.mdx @@ -2,7 +2,7 @@ import { PackageManagerTabs } from '../src/theme/PackageManagerTabs'; # Contribution Guide -Thank you for your interest in contributing to Farm!. Before submitting your contribution, please make sure to take a moment and read through the following guidelines. +Thank you for your interest in contributing to Farm! Farm is currently actively developing version 2.0. We will be introducing numerous new features, expanding ecosystem compatibility, and implementing various optimizations and updates to address current issues. Before submitting your contribution, please make sure to take a moment and read through the following guidelines. ## Code of Conduct @@ -36,15 +36,32 @@ Please feel free to open an issue using the [feature request template](https://g ## Setup +### Branches + +- `main` -> Farm v1.x +- `v2-dev` -> Farm v2.0.0-nightly + +--- + - Fork and clone the repo. - Create a branch for your PR with `git checkout -b your-branch-name`. - To keep `main` branch pointing to remote repository and make pull requests from branches on your fork. To do this, run: + +- adds a new remote repository named "upstream" that points to the original repository ```bash git remote add upstream https://github.com/farm-fe/farm.git +``` + +- retrieves all the branches and their respective commits from the upstream repository that you just configured +```bash git fetch upstream +``` + +- sets up tracking between your local main branch and the main branch of the upstream repository +```bash git branch --set-upstream-to=upstream/main main ``` @@ -53,6 +70,8 @@ Please feel free to open an issue using the [feature request template](https://g ### Dependencies + + - Install Rust using [rustup](https://www.rust-lang.org/tools/install). - [Node.js](https://nodejs.org) **version 16+** @@ -65,7 +84,7 @@ Please feel free to open an issue using the [feature request template](https://g We recommend that you use vscode for development and recommend two necessary plugins that you need to install - `rust-analyzer` support rust language -- `biome` farm use biome to detect and format the code +- `biome` farm use biome as lint and format the code You can install them in the extension @@ -83,9 +102,9 @@ Farm development is very simple. You only need to execute `pnpm bootstrap` in th - use `pnpm bootstrap` to install dependencies and build core packages with series of initialization operations. -- Work with examples (open a new terminal): `cd examples/react && pnpm start`, report an issue if the example does not start normally. +- Work with examples (open a new terminal): `cd examples/refactor-react && pnpm start`, report an issue if the example does not start normally. -- If `examples/react` project runs successfully, the development environment has been configured successfully +- If `examples/refactor-react` project runs successfully, the development environment has been configured successfully - If you changed Rust code in `crates`, run `npm run build:rs` under `packages/core` again to get the latest binary. diff --git a/docs/docs/quick-start.mdx b/docs/docs/quick-start.mdx index 3150b6002..e19a16504 100644 --- a/docs/docs/quick-start.mdx +++ b/docs/docs/quick-start.mdx @@ -37,9 +37,10 @@ Farm needs **Node 16.18.0 and above**. :::warning If you are using the nightly version, you need to install all Farm dependencies as nightly versions. We have provided nightly versions for all core packages and plugins. e.g: - ::: + + :::note{title="Then follow the prompts!"} You can also directly specify the project name and the template you want to use via additional command line options: diff --git a/docs/i18n/zh/docusaurus-plugin-content-docs/current/contribution.md b/docs/i18n/zh/docusaurus-plugin-content-docs/current/contribution.mdx similarity index 86% rename from docs/i18n/zh/docusaurus-plugin-content-docs/current/contribution.md rename to docs/i18n/zh/docusaurus-plugin-content-docs/current/contribution.mdx index 5c26c2140..7bc5fffe3 100644 --- a/docs/i18n/zh/docusaurus-plugin-content-docs/current/contribution.md +++ b/docs/i18n/zh/docusaurus-plugin-content-docs/current/contribution.mdx @@ -8,7 +8,7 @@ ## 错误报告 -目前 Farm 正在快速开发和迭代中, 在开发和使用中可能会遇到一些问题, 如果您遇到了一些我们不可预料的问题, 请提交 issues 用来报告错误问题, 通过新建一个 [issues](https://github.com/farm-fe/farm/issues/new/choose) 来报告您所遇到的问题。 +目前 Farm 正在快速开发和迭代中, 正在积极开发 2.0 版本我们会增加许多新功能以及加大生态兼容性以及各种目前问题的优化与更新 在开发和使用中可能会遇到一些问题, 如果您遇到了一些我们不可预料的问题, 请提交 issues 用来报告错误问题, 通过新建一个 [issues](https://github.com/farm-fe/farm/issues/new/choose) 来报告您所遇到的问题。 ## 创建新特性 @@ -36,17 +36,28 @@ - 保证您的 `main` 分支指向远程仓库, 并从分支上发出拉取请求, 请确保您的分支是基于 `main` 分支的, 并且运行: + +- 添加了 Farm 的 upstream 远程仓库 ```bash git remote add upstream https://github.com/farm-fe/farm.git +``` + +- 从 upstream 远程仓库获取所有分支和它们的提交 +```bash git fetch upstream - git branch --set-upstream-to=upstream/main main ``` +- 建立了你本地 main 分支与 upstream 仓库 main 分支之间的跟踪关系 +```bash + git branch --set-upstream-to=upstream/main main +``` ## 设置您的本地开发环境 ### 依赖 + + - 安装 Rust 环境 [rustup](https://www.rust-lang.org/tools/install)。 - 确保您的 [Node.js](https://nodejs.org) 版本在 **16** 以上。 diff --git a/docs/sidebars.js b/docs/sidebars.js index 54fdb7f2d..e12657b6a 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -22,7 +22,16 @@ const sidebars = { type: "category", label: "Getting Started", collapsed: false, - items: ["why-farm", "quick-start", "using-plugins", 'contribution'], + items: [ + "why-farm", + "quick-start", + "using-plugins", + { + type: "doc", + id: "contribution", + className: "sidebar-contribution-item", + }, + ], }, { type: "category", @@ -77,7 +86,7 @@ const sidebars = { "advanced/tree-shake", "advanced/minification", "advanced/polyfill", - "advanced/persistent-cache" + "advanced/persistent-cache", ], }, { diff --git a/docs/src/css/custom.scss b/docs/src/css/custom.scss index 4f9175d1f..6fc97ad51 100644 --- a/docs/src/css/custom.scss +++ b/docs/src/css/custom.scss @@ -371,3 +371,21 @@ html[data-theme="dark"] { width: 100%; height: 100%; } + +.sidebar-contribution-item > .menu__link { + font-weight: bold; +} + +.sidebar-contribution-item > .menu__link::after { + content: "Welcome ✨"; + margin-left: 0.5rem; + display: inline-block; + padding: 2px 6px; + background-color: var(--admonition-tip-c-bg); + border: 1px solid var(--admonition-tip-border-color); + border-radius: 4px; + color: var(--ifm-menu-color-active); + font-size: 12px; + font-weight: normal; + vertical-align: middle; +} diff --git a/docs/src/pages/index.module.css b/docs/src/pages/index.module.css index f753d790d..b156c37cf 100644 --- a/docs/src/pages/index.module.css +++ b/docs/src/pages/index.module.css @@ -27,6 +27,7 @@ .buttons { display: flex; align-items: center; + gap: 20px; /* justify-content: center; */ } diff --git a/docs/src/pages/index.tsx b/docs/src/pages/index.tsx index 5b70df3bb..a71267662 100644 --- a/docs/src/pages/index.tsx +++ b/docs/src/pages/index.tsx @@ -80,7 +80,7 @@ function HomepageHeader() {
Why Farm?
+ +
+ Contribute +
+ - + ); } diff --git a/docs/src/theme/CodeBlock/index.module.css b/docs/src/theme/CodeBlock/index.module.css index 822d76281..bc3f27eb9 100644 --- a/docs/src/theme/CodeBlock/index.module.css +++ b/docs/src/theme/CodeBlock/index.module.css @@ -136,3 +136,14 @@ .copy-success { color: var(--ifm-color-success); } + +.hover-button { + position: relative; + button { + position: absolute; + margin: 16px; + right: 0; + } +} + + diff --git a/docs/src/theme/CodeBlock/index.tsx b/docs/src/theme/CodeBlock/index.tsx index 2dc4994cc..e9ca160c4 100644 --- a/docs/src/theme/CodeBlock/index.tsx +++ b/docs/src/theme/CodeBlock/index.tsx @@ -78,18 +78,30 @@ export default function CodeBlockWrapper(props: Props): JSX.Element { setTimeout(() => setCopied(false), 2000); }); }; + const hiddenCopy = language === 'bash' || language === 'shell'; return ( <>
-
- {/* {fileName &&
{fileName} -
} */} + {!hiddenCopy &&
{fileName && (
{getFileIcon(fileName)} {fileName}
)} + {/* */} +
} +
+
- {/* */} -
); diff --git a/examples/arco-pro/farm.config.ts b/examples/arco-pro/farm.config.ts index 253f462cb..73d55828b 100644 --- a/examples/arco-pro/farm.config.ts +++ b/examples/arco-pro/farm.config.ts @@ -11,7 +11,8 @@ export default defineConfig((env) => { }, sourcemap: false, presetEnv: false, - // persistentCache: false, + concatenateModules: true, + persistentCache: false, resolve: { symlinks: true, alias: { @@ -20,8 +21,8 @@ export default defineConfig((env) => { react: resolve(process.cwd(), './node_modules/react') } }, - minify: false, - mode: 'development', + // minify: false, + // mode: 'development', // persistentCache: false, output: { path: './build', diff --git a/examples/decorators/farm.config.ts b/examples/decorators/farm.config.ts index 1c73ce4ae..30ed38e94 100644 --- a/examples/decorators/farm.config.ts +++ b/examples/decorators/farm.config.ts @@ -13,6 +13,7 @@ export default defineConfig({ excludes: ['node_modules/'], } }, + mode: 'development', presetEnv: false, minify: false, persistentCache: false, @@ -20,9 +21,14 @@ export default defineConfig({ main: 'src/broken.ts', }, output: { - targetEnv: 'node', + targetEnv: 'library-node', entryFilename: '[entryName].mjs', filename: '[name].[hash].mjs', + format: 'esm' }, + treeShaking: false, + resolve: { + autoExternalFailedResolve: true, + } }, }); diff --git a/examples/decorators/package.json b/examples/decorators/package.json index 17d71c32f..71eefcf75 100644 --- a/examples/decorators/package.json +++ b/examples/decorators/package.json @@ -10,6 +10,7 @@ "build": "farm build && node test.mjs" }, "dependencies": { + "@swc/helpers": "^0.5.0", "core-js": "^3.33.3", "reflect-metadata": "^0.1.13" } diff --git a/examples/module-concatenation/app.tsx b/examples/module-concatenation/app.tsx new file mode 100644 index 000000000..1a1173c2e --- /dev/null +++ b/examples/module-concatenation/app.tsx @@ -0,0 +1,18 @@ +import React from './react'; +import util1 from './util1.cjs'; + +import commonInner from './common.mjs'; + +function common() { + return 'common-outer'; +} + +export function App() { + return ( +
+

{util1.util1() + util1.util2()}

+

{commonInner()}

+
+ ); +} + diff --git a/examples/module-concatenation/common.mjs b/examples/module-concatenation/common.mjs new file mode 100644 index 000000000..51e8ba889 --- /dev/null +++ b/examples/module-concatenation/common.mjs @@ -0,0 +1,11 @@ +export default function common() { + return 'common'; +} +common(); + +// -----> + +// function a() { +// return +// } +// a(); \ No newline at end of file diff --git a/examples/module-concatenation/expected-app1.tsx b/examples/module-concatenation/expected-app1.tsx new file mode 100644 index 000000000..09d297165 --- /dev/null +++ b/examples/module-concatenation/expected-app1.tsx @@ -0,0 +1,38 @@ +// ----> +function (module, exports, farmRequire, farmDynamicRequire) { + var react = _interop_default_(farmRequire('./react')); + var util1 = _interop_default_(farmRequire('./util1.cjs')); + + // ---- content of common.mjs ---- + function common1() { + return 'common'; + } + common1(); + var commonInner = common1; + // ---- end of common.mjs ---- + + function common() { + return 'common-outer'; + } + + module.o(exports, 'App', function App() { + return ( + react.createElement( + 'div', + null, + [ + react.createElement( + 'h1', + null, + util1.util1() + util1.util2() + ), + react.createElement( + 'h1', + null, + commonInner() + ) + ] + ) + ); + }) +} diff --git a/examples/module-concatenation/farm.config.ts b/examples/module-concatenation/farm.config.ts new file mode 100644 index 000000000..7f8cccc94 --- /dev/null +++ b/examples/module-concatenation/farm.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "@farmfe/core"; + +export default defineConfig({ + compilation: { + concatenateModules: true, + persistentCache: false, + treeShaking: false, + }, + server: { + writeToDisk: true, + } +}) \ No newline at end of file diff --git a/examples/module-concatenation/index.html b/examples/module-concatenation/index.html new file mode 100644 index 000000000..8de9b098b --- /dev/null +++ b/examples/module-concatenation/index.html @@ -0,0 +1,12 @@ + + + + + + Document + + + + + + \ No newline at end of file diff --git a/examples/module-concatenation/index.tsx b/examples/module-concatenation/index.tsx new file mode 100644 index 000000000..133e131f8 --- /dev/null +++ b/examples/module-concatenation/index.tsx @@ -0,0 +1,44 @@ +import React from './react'; +import ReactDom from './react-dom'; + +import { App } from './app'; + +ReactDom.render( + , + document.getElementById('root') +); + +// // ----> +// const react = _interop_default_(farmRequire('./react')); +// const util1 = _interop_default_(farmRequire('./util1.cjs')); + +// function common1() { +// return 'common'; +// } +// common1(); +// var commonInner = common1; + +// function common() { +// return 'common-outer'; +// } + +// function App() { +// return ( +// react.createElement( +// 'div', +// null, +// [ +// react.createElement( +// 'h1', +// null, +// util1.util1() + util1.util2() +// ), +// react.createElement( +// 'h1', +// null, +// commonInner() +// ) +// ] +// ) +// ); +// } \ No newline at end of file diff --git a/examples/module-concatenation/package.json b/examples/module-concatenation/package.json new file mode 100644 index 000000000..ce7e262e5 --- /dev/null +++ b/examples/module-concatenation/package.json @@ -0,0 +1,26 @@ +{ + "name": "@farmfe-examples/module-concatenation", + "version": "0.0.1", + "private": true, + "type": "module", + "dependencies": { + "core-js": "^3.30.1", + "react": "18", + "react-dom": "18" + }, + "devDependencies": { + "@farmfe/cli": "workspace:*", + "@farmfe/core": "workspace:*", + "@farmfe/plugin-react": "workspace:*", + "@types/react": "18", + "@types/react-dom": "18", + "react-refresh": "^0.14.0" + }, + "scripts": { + "start": "farm start", + "dev": "farm start", + "build": "farm build", + "preview": "farm preview", + "clean": "farm clean" + } +} diff --git a/examples/module-concatenation/react-dom.js b/examples/module-concatenation/react-dom.js new file mode 100644 index 000000000..6d9496c44 --- /dev/null +++ b/examples/module-concatenation/react-dom.js @@ -0,0 +1,3 @@ +exports.render = function(element, container) { + container.appendChild(element) +} \ No newline at end of file diff --git a/examples/module-concatenation/react.js b/examples/module-concatenation/react.js new file mode 100644 index 000000000..73fa860f9 --- /dev/null +++ b/examples/module-concatenation/react.js @@ -0,0 +1,5 @@ +module.exports = { + useState: function() { + return [] + } +} \ No newline at end of file diff --git a/examples/module-concatenation/util1.cjs b/examples/module-concatenation/util1.cjs new file mode 100644 index 000000000..f1338e74b --- /dev/null +++ b/examples/module-concatenation/util1.cjs @@ -0,0 +1,6 @@ +const { util2 } = require('./util2'); + +exports.util1 = () => { + console.log('util1'); +}; +exports.util2 = util2; \ No newline at end of file diff --git a/examples/module-concatenation/util2.cjs b/examples/module-concatenation/util2.cjs new file mode 100644 index 000000000..6105f4ae0 --- /dev/null +++ b/examples/module-concatenation/util2.cjs @@ -0,0 +1,3 @@ +exports.util2 = () => { + console.log('util2'); +}; \ No newline at end of file diff --git a/examples/refactor-react/farm.config.ts b/examples/refactor-react/farm.config.ts index 1a776f40d..328ef3350 100644 --- a/examples/refactor-react/farm.config.ts +++ b/examples/refactor-react/farm.config.ts @@ -1,43 +1,48 @@ -import { defineConfig } from "@farmfe/core"; +import { defineConfig, loadEnv } from "@farmfe/core"; import react from "@farmfe/plugin-react"; import path from "path"; +import { config } from "process"; console.log(__dirname); -export default defineConfig({ - plugins: [ - react(), - // myCustomPlugin(), - compilerPlugin(), - ], - compilation: { - input: { - index: path.resolve(__dirname, "index.html"), - base: path.resolve(__dirname, 'base.html'), - about: path.resolve(__dirname, 'about.html'), - }, - // persistentCache: false, - persistentCache: { - cacheDir: "node_modules/.adny", - }, - output: { - // publicPath: "/aaa/", +export default defineConfig((config) => { + console.log(config, "config"); + console.log(loadEnv("development", process.cwd()), "loadEnv"); + + return { + plugins: [ + react(), + // myCustomPlugin(), + compilerPlugin(), + ], + compilation: { + input: { + index: path.resolve(__dirname, "index.html"), + base: path.resolve(__dirname, 'base.html'), + about: path.resolve(__dirname, 'about.html'), + }, + // persistentCache: false, + persistentCache: { + cacheDir: "node_modules/.adny", + }, + output: { + // publicPath: "/aaa/", + }, + resolve: { + // alias: { + // "@": path.resolve("src"), + // }, + alias: [{ find: "@", replacement: path.resolve("src") }], + }, }, - resolve: { - // alias: { - // "@": path.resolve("src"), - // }, - alias: [{ find: "@", replacement: path.resolve("src") }], + server: { + port: 4855, + appType: "mpa", }, - }, - timeUnit: "s", - server: { - port: 8854, - // appType: "mpa", - }, - preview: { - port: 3691, + preview: { + port: 3691, + } } }); @@ -46,7 +51,7 @@ function myCustomPlugin() { name: "custom", updateModules: { executor(data: any) { - console.log(data, "更新的模块"); + console.log(data); }, }, }; diff --git a/examples/refactor-react/src/main.tsx b/examples/refactor-react/src/main.tsx index a1b77f3a4..3bdd797bb 100644 --- a/examples/refactor-react/src/main.tsx +++ b/examples/refactor-react/src/main.tsx @@ -8,7 +8,6 @@ import FarmLogo from "./assets/logo.png"; export function Main() { const [count, setCount] = useState(0); // console.log(a); - return ( <>
diff --git a/examples/script-entry/farm.config.ts b/examples/script-entry/farm.config.ts index 0b99ee831..41e82f7cc 100644 --- a/examples/script-entry/farm.config.ts +++ b/examples/script-entry/farm.config.ts @@ -6,6 +6,13 @@ import { builtinModules } from 'module'; */ export default defineConfig({ compilation: { + // multiple bundle recommend config + treeShaking: false, + partialBundling: { + targetConcurrentRequests: Number.MAX_SAFE_INTEGER, + targetMinSize: 1, + }, + input: { index: './index.ts' }, @@ -21,19 +28,8 @@ export default defineConfig({ ...builtinModules.map((m) => `^node:${m}$`), ...builtinModules.map((m) => `^${m}$`) ], - runtime: { - isolate: true - }, minify: false, mode: 'development', - partialBundling: { - enforceResources: [ - { - name: 'xxx', - test: ['.+'] - } - ] - }, persistentCache: false, lazyCompilation: false }, diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 0b2c936f1..1396c94c6 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -31,10 +31,6 @@ cli ) .option('--base ', '[string] public base path') .option('-d, --debug [feat]', `[string | boolean] show debug logs`) - .option( - '-t, --timeUnit ', - '[string] time unit for time log (default: ms) optionals: ms, s' - ) .option( '--clearScreen', '[boolean] allow/disable clear screen when logging (default: true)', @@ -82,7 +78,6 @@ cli clearScreen: options.clearScreen, configFile: options.config, mode: options.mode, - timeUnit: options.timeUnit, compilation: { lazyCompilation: options.lazy, output: { @@ -128,7 +123,6 @@ cli configFile: options.config, mode: options.mode, watch: options.watch, - timeUnit: options.timeUnit, compilation: { output: { path: options?.outDir, diff --git a/packages/cli/src/types.ts b/packages/cli/src/types.ts index 4a97ebde2..c005567c9 100644 --- a/packages/cli/src/types.ts +++ b/packages/cli/src/types.ts @@ -6,7 +6,6 @@ export interface GlobalCliOptions { m?: string; mode?: 'development' | 'production' | string; clearScreen?: boolean; - timeUnit?: 'ms' | 's'; } export interface CleanOptions { diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index e361e497d..3a39642a1 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -8,6 +8,14 @@ ## 2.0.0-nightly-20241029095811 +## 1.3.32 + +### Patch Changes + +- 3ae860bd: fix plugin circle call between Runtime & LazyCompilation, fix runtime & lazyCompilation conflict + +## 1.3.31 + ### Patch Changes - b3a7caf: fix css url resolving issue diff --git a/packages/core/scripts/build-cjs.mjs b/packages/core/scripts/build-cjs.mjs index 77ad4af23..17c704421 100644 --- a/packages/core/scripts/build-cjs.mjs +++ b/packages/core/scripts/build-cjs.mjs @@ -1,12 +1,11 @@ import path from 'path'; // import { copyFile, readdir } from 'fs/promises'; -// TODO build cjs -// import { build } from '../dist/index.js'; +import { build } from '../dist/index.js'; -// await build({ -// configPath: path.join(process.cwd(), 'farm.config.ts') -// }); +await build({ + configPath: path.join(process.cwd(), 'farm.config.ts') +}); // if (!process.env.FARM_PUBLISH) { // // copy artifacts diff --git a/packages/core/src/config/env.ts b/packages/core/src/config/env.ts index 5de34545b..2bd6c6d43 100644 --- a/packages/core/src/config/env.ts +++ b/packages/core/src/config/env.ts @@ -28,6 +28,7 @@ export function loadEnv( prefixes = arraify(prefixes); const env: Record = {}; const envFiles = getEnvFilesForMode(mode, envDir); + const parsed = Object.fromEntries( envFiles.flatMap((filePath) => { if (!tryStatSync(filePath)?.isFile()) return []; diff --git a/packages/core/src/config/index.ts b/packages/core/src/config/index.ts index ce1ae2850..23d5e1444 100644 --- a/packages/core/src/config/index.ts +++ b/packages/core/src/config/index.ts @@ -72,6 +72,7 @@ import type { export * from './types.js'; export * from './constants.js'; +export * from './env.js'; export function defineFarmConfig(config: UserConfig): UserConfig; export function defineFarmConfig( @@ -98,7 +99,7 @@ const COMMANDS = { * @param configPath */ export async function resolveConfig( - inlineOptions: FarmCliOptions & UserConfig, + inlineOptions: FarmCliOptions & UserConfig & any, command: 'start' | 'build' | 'watch' | 'preview', defaultMode: CompilationMode = 'development', defaultNodeEnv: CompilationMode = 'development', @@ -443,6 +444,17 @@ export async function normalizeUserCompilationConfig( resolvedCompilation.treeShaking ??= isProduction; } + if (resolvedCompilation.concatenateModules === undefined) { + resolvedCompilation.concatenateModules ??= isProduction; + } + + if (resolvedCompilation.concatenateModules && !isProduction) { + resolvedUserConfig.logger.warn( + 'concatenateModules option is not supported with development mode, concatenateModules will be disabled' + ); + resolvedCompilation.concatenateModules = false; + } + if (resolvedCompilation.script?.plugins?.length) { resolvedUserConfig.logger.info( `Swc plugins are configured, note that Farm uses ${colors.yellow( diff --git a/packages/core/src/config/mergeConfig.ts b/packages/core/src/config/mergeConfig.ts index cd6167bbd..82b1dbbd6 100644 --- a/packages/core/src/config/mergeConfig.ts +++ b/packages/core/src/config/mergeConfig.ts @@ -59,7 +59,6 @@ export function mergeFarmCliConfig( 'compilation', 'envDir', 'envPrefix', - 'timeUnit', 'watch', 'plugins', 'publicDir', @@ -146,11 +145,6 @@ export function mergeFarmCliConfig( compilation: { sourcemap: options.sourcemap } }); } - if (options.timeUnit) { - left = mergeConfig(left, { - timeUnit: options.timeUnit - }); - } return mergeConfig(left, target); } @@ -189,7 +183,6 @@ export function initialCliOptions(options: any): any { preview: options.preview, clearScreen: !!options.clearScreen, configFile: options.configFile, - timeUnit: options.timeUnit, ...(mode && { mode }) }; diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts index 9edb45d04..4acc3b81a 100644 --- a/packages/core/src/config/schema.ts +++ b/packages/core/src/config/schema.ts @@ -5,6 +5,7 @@ import { z } from 'zod'; import { fromZodError } from 'zod-validation-error'; import { Logger } from '../utils/logger.js'; + import type { UserConfig } from './types.js'; enum TargetEnv { @@ -66,6 +67,37 @@ const outputSchema = z .strict() .optional(); +const WatchOptionsSchema = z.object({ + persistent: z.boolean().optional(), + ignored: z + .union([ + z.string(), + z.array(z.string()), + z.instanceof(RegExp), + z.array(z.instanceof(RegExp)), + z.function(z.tuple([z.string()]), z.boolean()) + ]) + .optional(), + ignoreInitial: z.boolean().optional(), + followSymlinks: z.boolean().optional(), + cwd: z.string().optional(), + useFsEvents: z.boolean().optional(), + disableGlobbing: z.boolean().optional(), + usePolling: z.boolean().optional(), + interval: z.number().positive().int().optional(), + binaryInterval: z.number().positive().int().optional(), + alwaysStat: z.boolean().optional(), + depth: z.number().positive().int().optional(), + awaitWriteFinish: z + .object({ + stabilityThreshold: z.number().positive().int().optional(), + pollInterval: z.number().positive().int().optional() + }) + .optional(), + atomic: z.union([z.boolean(), z.number().positive().int()]).optional(), + ignorePermissionErrors: z.boolean().optional() +}); + const serverSchema = z .object({ headers: z.record(z.string()).optional(), @@ -81,26 +113,6 @@ const serverSchema = z https: z.custom(), cors: z.boolean().optional(), appType: z.enum(['spa', 'mpa', 'custom']).optional(), - // TODO Can watch be placed on the outermost layer? - watch: z - .union([ - z.boolean(), - z.object({ - // TODO watcher config schema - ignored: z.array(z.string()).optional(), - watchOptions: z - .object({ - awaitWriteFinish: z.number().positive().int().optional() - }) - .optional() - }) - ]) - .optional(), - // watch: z - // .object({ - // awaitWriteFinish: z.number().positive().int().optional(), - // }) - // .optional(), proxy: z .record( z @@ -408,27 +420,26 @@ const compilationConfigSchema = z .optional() ]), comments: z.union([z.boolean(), z.literal('license')]).optional(), - custom: z.record(z.string(), z.string()).optional() + custom: z.record(z.string(), z.string()).optional(), + concatenateModules: z.boolean().optional() }) .strict(); const FarmConfigSchema = z .object({ root: z.string().optional(), - clearScreen: z.boolean().optional(), + mode: z.string().optional(), configPath: z.string().optional(), + clearScreen: z.boolean().optional(), + customLogger: z.instanceof(Logger).optional(), envDir: z.string().optional(), - timeUnit: z.union([z.literal('ms'), z.literal('s')]).optional(), envPrefix: z.union([z.string(), z.array(z.string())]).optional(), publicDir: z.string().optional(), - plugins: z.array(z.any()).optional(), - vitePlugins: z.array(z.any()).optional(), + watch: z.union([z.boolean(), WatchOptionsSchema]).optional(), compilation: compilationConfigSchema.optional(), - mode: z.string().optional(), - watch: z.boolean().optional(), server: serverSchema.optional(), - preview: previewServerSchema.optional(), - customLogger: z.custom((val) => val instanceof Logger).optional() + plugins: z.array(z.any()).optional(), + vitePlugins: z.array(z.any()).optional() }) .strict(); diff --git a/packages/core/src/config/types.ts b/packages/core/src/config/types.ts index ad3c1c2ef..7ebc18f7e 100644 --- a/packages/core/src/config/types.ts +++ b/packages/core/src/config/types.ts @@ -151,10 +151,9 @@ export interface UserConfig { root?: string; clearScreen?: boolean; envDir?: string; - watch?: boolean; + watch?: boolean | WatchOptions; envPrefix?: string | string[]; publicDir?: string; - timeUnit?: 'ms' | 's'; /** js plugin(which is a javascript object) and rust plugin(which is string refer to a .farm file or a package) */ plugins?: (RustPlugin | JsPlugin | JsPlugin[] | undefined | null | false)[]; /** vite plugins */ @@ -171,7 +170,7 @@ export interface UserConfig { /** Config related to preview server */ preview?: UserPreviewServerConfig; /** Files under this dir will always be treated as static assets. serve it in dev, and copy it to output.path when build */ - logger?: Logger; + customLogger?: Logger; } interface ResolvedCss extends CssConfig { @@ -198,15 +197,14 @@ export interface ResolvedCompilation } export interface ResolvedUserConfig extends UserConfig { - // watch?: boolean; - // root?: string; + root?: string; + mode?: string; env?: Record; envDir?: string; envFiles?: string[]; envPrefix?: string | string[]; configFilePath?: string; envMode?: string; - timeUnit?: 'ms' | 's'; configFileDependencies?: string[]; compilation?: ResolvedCompilation; server?: NormalizedServerConfig; @@ -214,7 +212,8 @@ export interface ResolvedUserConfig extends UserConfig { rustPlugins?: [string, string][]; inlineConfig?: FarmCliOptions; logger?: Logger; - watch?: boolean; + customLogger?: Logger; + watch?: boolean | WatchOptions; } export interface GlobalCliOptions { @@ -250,11 +249,8 @@ export interface FarmCLIPreviewOptions { export interface FarmCliOptions extends FarmCLIBuildOptions, FarmCLIPreviewOptions { - logger?: Logger; config?: string; configFile?: string; - // todo: check to delete - configPath?: string; compilation?: Config['config']; mode?: string; root?: string; @@ -265,7 +261,6 @@ export interface FarmCliOptions export type DevServerMiddleware = (context: Server) => any | undefined; export interface Alias { - // TODO support RegExp find: string; replacement: string; } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index cfd744dac..532e58b21 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -37,7 +37,8 @@ export async function start( const server = new Server(inlineConfig); try { await server.createServer(); - server.listen(); + await server.listen(); + server.printUrls(); } catch (error) { server.logger.error('Failed to start the server', { exit: false, error }); } @@ -67,7 +68,7 @@ export async function build( 'production', 'production' ); - + const logger = resolvedUserConfig.logger; const { persistentCache, output } = resolvedUserConfig.compilation; try { @@ -95,12 +96,10 @@ export async function build( resolvedUserConfig.configFilePath, resolvedUserConfig.root ); - resolvedUserConfig.logger.info( - `Using config file at ${bold(green(shortFile))}` - ); - resolvedUserConfig.logger.info( + logger.info(`Using config file at ${bold(green(shortFile))}`); + logger.info( `Build completed in ${bold( - green(`${elapsedTime}ms`) + green(`${logger.formatExecutionTime(elapsedTime)}`) )} ${persistentCacheText} Resources emitted to ${bold( green(output.path) )}.` @@ -111,7 +110,7 @@ export async function build( handlerWatcher(resolvedUserConfig, compiler); } } catch (err) { - resolvedUserConfig.logger.error(`Failed to build: ${err}`, { exit: true }); + logger.error(`Failed to build: ${err}`, { exit: true }); } } diff --git a/packages/core/src/server/hmr-engine.ts b/packages/core/src/server/hmr-engine.ts index b2961b266..3845be01c 100644 --- a/packages/core/src/server/hmr-engine.ts +++ b/packages/core/src/server/hmr-engine.ts @@ -8,7 +8,7 @@ import type { Resource } from '@farmfe/runtime/src/resource-loader.js'; import { UserHmrConfig } from '../config/index.js'; import type { JsUpdateResult } from '../types/binding.js'; import { convertErrorMessage } from '../utils/error.js'; -import { bold, cyan, formatExecutionTime, green } from '../utils/index.js'; +import { bold, cyan, green } from '../utils/index.js'; import { WebSocketClient } from './ws.js'; export class HmrEngine { @@ -47,7 +47,7 @@ export class HmrEngine { if (queue.length === 0) { return; } - + const logger = this.app.logger; let updatedFilesStr = queue .map((item) => { if (isAbsolute(item)) { @@ -82,16 +82,8 @@ export class HmrEngine { const result = await this.app.compiler.update(queue); - this.app.logger.info( - `${bold(cyan(updatedFilesStr))} updated in ${bold( - green( - formatExecutionTime( - performance.now() - start, - this.app.resolvedUserConfig.timeUnit - ) - ) - )}`, - true + logger.info( + `${bold(cyan(updatedFilesStr))} updated in ${bold(green(logger.formatExecutionTime(performance.now() - start)))}` ); // clear update queue after update finished diff --git a/packages/core/src/server/index.ts b/packages/core/src/server/index.ts index 6929dadf4..fa1ff65a4 100644 --- a/packages/core/src/server/index.ts +++ b/packages/core/src/server/index.ts @@ -318,19 +318,23 @@ export class Server extends httpServer { const { port: prevPort, host: prevHost } = this.serverOptions; const prevUrls = this.resolvedUrls; - await this.restart(); - - const { port, host } = this.serverOptions; + const newServer = await this.restart(); + const { + serverOptions: { port, host }, + resolvedUrls + } = newServer; if ( port !== prevPort || host !== prevHost || - this.hasUrlsChanged(prevUrls, this.resolvedUrls) + this.hasUrlsChanged(prevUrls, resolvedUrls) ) { __FARM_GLOBAL__.__FARM_SHOW_DEV_SERVER_URL__ = true; } else { __FARM_GLOBAL__.__FARM_SHOW_DEV_SERVER_URL__ = false; } + + newServer.printUrls(); } /** @@ -364,7 +368,7 @@ export class Server extends httpServer { } await this.watcher.close(); await newServer.listen(); - this.logger.info(bold(green('Server restarted successfully ✨ ✨'))); + return newServer; } /** @@ -430,8 +434,6 @@ export class Server extends httpServer { if (open) { this.#openServerBrowser(); } - - __FARM_GLOBAL__.__FARM_SHOW_DEV_SERVER_URL__ && this.printUrls(); } catch (error) { this.resolvedUserConfig.logger.error( `start farm dev server error: ${error} \n ${error.stack}` @@ -696,6 +698,9 @@ export class Server extends httpServer { } printUrls() { + if (!__FARM_GLOBAL__.__FARM_SHOW_DEV_SERVER_URL__) { + return; + } if (this.resolvedUrls) { printServerUrls( this.resolvedUrls, diff --git a/packages/core/src/server/middlewares/lazyCompilation.ts b/packages/core/src/server/middlewares/lazyCompilation.ts index cebc26b4b..97ea96fbc 100644 --- a/packages/core/src/server/middlewares/lazyCompilation.ts +++ b/packages/core/src/server/middlewares/lazyCompilation.ts @@ -74,9 +74,8 @@ export function lazyCompilationMiddleware( cyan(pathsStr) )} in ${bold( green( - formatExecutionTime( - performance.now() - start, - resolvedUserConfig.timeUnit + resolvedUserConfig.logger.formatExecutionTime( + performance.now() - start ) ) )}.` diff --git a/packages/core/src/types/binding.ts b/packages/core/src/types/binding.ts index a88168e51..113d200a0 100644 --- a/packages/core/src/types/binding.ts +++ b/packages/core/src/types/binding.ts @@ -472,6 +472,7 @@ export interface Config { persistentCache?: boolean | PersistentCacheConfig; comments?: boolean | 'license'; custom?: Record; + concatenateModules?: boolean; }; jsPlugins?: JsPlugin[]; // [rustPluginFilePath, jsonStringifiedOptions] diff --git a/packages/core/src/utils/logger.ts b/packages/core/src/utils/logger.ts index e5d981795..fdb579fee 100644 --- a/packages/core/src/utils/logger.ts +++ b/packages/core/src/utils/logger.ts @@ -9,7 +9,7 @@ import { } from './color.js'; import { ResolvedServerUrls } from './http.js'; import { getShortName } from './path.js'; -import { clearScreen, formatExecutionTime, pad, version } from './share.js'; +import { clearScreen, pad, version } from './share.js'; type LogLevelNames = 'trace' | 'debug' | 'info' | 'warn' | 'error'; @@ -38,6 +38,7 @@ interface LoggerOptions { allowClearScreen?: boolean; brandColor?: ColorFunction; exit?: boolean; + timeUnit?: 's' | 'ms'; } const LOGGER_METHOD = { @@ -63,12 +64,14 @@ export class Logger implements ILogger { private clear: () => void = () => {}; private customLogger?: Logger; + private timeUnit: 's' | 'ms'; constructor( { prefix = 'Farm', allowClearScreen = true, customLogger, + timeUnit = 'ms', brandColor }: LoggerOptions = {}, private levelValues: Record = { @@ -91,6 +94,7 @@ export class Logger implements ILogger { }; this.prefix = prefix; this.customLogger = customLogger; + this.timeUnit = timeUnit; this.brandPrefix(); } @@ -100,6 +104,14 @@ export class Logger implements ILogger { this.prefix = color ? color(formattedPrefix) : formattedPrefix; } + formatExecutionTime(duration: number): string { + if (this.timeUnit === 's') { + return `${(duration / 1000).toFixed(3)}s`; + } else { + return `${Math.floor(duration)}ms`; + } + } + private logMessage( level: LogLevelNames, message: string | Error, @@ -116,11 +128,29 @@ export class Logger implements ILogger { ? LOGGER_METHOD[level as keyof typeof LOGGER_METHOD] : 'log'; if (this.levelValues[level] <= this.levelValues[level]) { - this.canClearScreen && clearScreen && this.clear(); + if (this.canClearScreen && clearScreen) { + this.clear(); + } const prefix = showBanner ? `${this.prefix} ` : ''; - const prefixColor = this.colorMap[level]; - const loggerMessage = color ? color(message as string) : message; - console[loggerMethod](prefixColor(prefix) + loggerMessage); + const prefixColored = this.colorMap[level](prefix); + let loggerMessage: string; + + if (typeof message === 'string') { + const timeRegex = new RegExp(`\\{time:(\\d+(\\.\\d+)?)\\}`, 'g'); + loggerMessage = message.replace(timeRegex, (_, durationStr) => { + const duration = parseFloat(durationStr); + + return this.formatExecutionTime(duration); + }); + } else { + loggerMessage = message.message; + } + + if (color && typeof message === 'string') { + loggerMessage = color(loggerMessage); + } + + console[loggerMethod](prefixColored + loggerMessage); } } @@ -255,7 +285,7 @@ export function bootstrap( `${colors.bold(colors.green(` ✓`))} ${colors.bold( 'Compile in' )} ${colors.bold( - colors.green(formatExecutionTime(times, config.timeUnit)) + colors.green(config.logger.formatExecutionTime(times)) )} ${persistentCacheFlag}`, '\n' ); diff --git a/packages/core/src/watcher/index.ts b/packages/core/src/watcher/index.ts index 3b034445b..ed29bfc1b 100644 --- a/packages/core/src/watcher/index.ts +++ b/packages/core/src/watcher/index.ts @@ -166,10 +166,9 @@ export default class Watcher { } resolveChokidarOptions() { - // TODO type error here - // @ts-ignore - const userWatchOptions = this.config.server.watch; - const { ignored: ignoredList, ...otherOptions } = userWatchOptions ?? {}; + const userWatchOptions = this.config.watch; + const { ignored: ignoredList, ...otherOptions } = + typeof userWatchOptions === 'object' ? userWatchOptions : {}; const cacheDir = ( this.config.compilation.persistentCache as PersistentCacheConfig ).cacheDir; @@ -242,6 +241,7 @@ export async function handlerWatcher( resolvedUserConfig: ResolvedUserConfig, compiler: Compiler ) { + const logger = resolvedUserConfig.logger; const watcher = new Watcher(resolvedUserConfig); await watcher.createWatcher(); watcher.watcher.on('change', async (file: string | string[] | any) => { @@ -285,9 +285,9 @@ export async function handlerWatcher( const start = performance.now(); const result = await compiler.update([file], true); const elapsedTime = Math.floor(performance.now() - start); - resolvedUserConfig.logger.info( + logger.info( `update completed in ${bold( - green(`${elapsedTime}ms`) + green(`${logger.formatExecutionTime(elapsedTime)}ms`) )} Resources emitted to ${bold( green(resolvedUserConfig.compilation.output.path) )}.` diff --git a/packages/core/tests/config/index.spec.ts b/packages/core/tests/config/index.spec.ts index cd92fbef9..ca29a97d1 100644 --- a/packages/core/tests/config/index.spec.ts +++ b/packages/core/tests/config/index.spec.ts @@ -48,11 +48,8 @@ describe('mergeFarmCliConfig', () => { describe('normalizeUserCompilationConfig', () => { test('with default', async () => { let config = await normalizeUserCompilationConfig( - {}, - {}, - new NoopLogger(), - 'development', - true + { logger: new NoopLogger() }, + 'development' ); expect(config.input).toEqual({}); @@ -60,31 +57,43 @@ describe('mergeFarmCliConfig', () => { test('normalizeUserCompilationConfig without default and userConfig.compilation.input', async () => { expect(async () => { - await normalizeUserCompilationConfig( - {}, - {}, - new NoopLogger(), - 'development', - false - ); + await normalizeUserCompilationConfig({}, 'development'); }).rejects.toThrowError(); let config = await normalizeUserCompilationConfig( - {}, { + logger: new NoopLogger(), compilation: { input: { index: 'index.ts' } } }, - new NoopLogger(), - 'development', - false + 'development' ); expect(config.input).toEqual({ index: 'index.ts' }); }); + + test('concatenateModule should conflict by mode', async () => { + let config = await normalizeUserCompilationConfig( + { + compilation: { concatenateModules: true } + }, + 'development' + ); + + expect(config.concatenateModules).toBeFalsy(); + + config = await normalizeUserCompilationConfig( + { + compilation: { concatenateModules: true } + }, + 'production' + ); + + expect(config.concatenateModules).toBeTruthy(); + }); }); }); diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json index d3ba2eab2..19af35376 100644 --- a/packages/core/tsconfig.json +++ b/packages/core/tsconfig.json @@ -1,4 +1,7 @@ { "extends": "../../tsconfig.base.json", - "exclude": ["node_modules"] + "exclude": ["node_modules"], + "compilerOptions": { + "outDir": "dist" + } } diff --git a/packages/runtime/src/module.ts b/packages/runtime/src/module.ts index 3192c822d..40a47da64 100644 --- a/packages/runtime/src/module.ts +++ b/packages/runtime/src/module.ts @@ -16,6 +16,9 @@ export class Module { } o(to: any, to_k: string, get: () => any) { + if (Object.prototype.hasOwnProperty.call(to, to_k)) { + return; + } Object.defineProperty(to, to_k, { enumerable: true, get diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 16258cc15..c119ee9ba 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -232,7 +232,7 @@ importers: version: 4.30.9(@floating-ui/utils@0.2.8) '@arcgis/map-components': specifier: ^4.30.7 - version: 4.30.7(@arcgis/core@4.30.9(@floating-ui/utils@0.2.8))(@esri/calcite-components@2.12.2(@floating-ui/utils@0.2.8)) + version: 4.30.7(@arcgis/core@4.30.9(@floating-ui/utils@0.2.8))(@esri/calcite-components@2.13.0(@floating-ui/utils@0.2.8)) core-js: specifier: ^3.34.0 version: 3.37.1 @@ -460,6 +460,9 @@ importers: examples/decorators: dependencies: + '@swc/helpers': + specifier: ^0.5.0 + version: 0.5.3 core-js: specifier: ^3.33.3 version: 3.33.3 @@ -772,6 +775,37 @@ importers: specifier: workspace:* version: link:../../packages/core + examples/module-concatenation: + dependencies: + core-js: + specifier: ^3.30.1 + version: 3.37.1 + react: + specifier: '18' + version: 18.2.0 + react-dom: + specifier: '18' + version: 18.2.0(react@18.2.0) + devDependencies: + '@farmfe/cli': + specifier: workspace:* + version: link:../../packages/cli + '@farmfe/core': + specifier: workspace:* + version: link:../../packages/core + '@farmfe/plugin-react': + specifier: workspace:* + version: link:../../rust-plugins/react + '@types/react': + specifier: '18' + version: 18.2.35 + '@types/react-dom': + specifier: '18' + version: 18.2.14 + react-refresh: + specifier: ^0.14.0 + version: 0.14.2 + examples/multi-page-app: dependencies: clsx: @@ -4669,7 +4703,7 @@ packages: '@css-render/vue3-ssr@0.15.14': resolution: {integrity: sha512-//8027GSbxE9n3QlD73xFY6z4ZbHbvrOVB7AO6hsmrEzGbg+h2A09HboUyDgu+xsmj7JnvJD39Irt+2D0+iV8g==} peerDependencies: - vue: 3.4.23 + vue: ^3.0.11 '@csstools/cascade-layer-name-parser@2.0.1': resolution: {integrity: sha512-G9ZYN5+yr/E6xYSiy1BwOEFP5p88ZtWo8sL4NztKBkRRAwRkzVGa70M+D+fYHugMID5jkLeNt5X9jYd5EaVuyg==} @@ -5710,11 +5744,11 @@ packages: '@esri/calcite-colors@6.1.0': resolution: {integrity: sha512-wHQYWFtDa6c328EraXEVZvgOiaQyYr0yuaaZ0G3cB4C3lSkWefW34L/e5TLAhtuG3zJ/wR6pl5X1YYNfBc0/4Q==} - '@esri/calcite-components@2.12.2': - resolution: {integrity: sha512-Fmm7WpG+B7il0mpf7grL0ZsFJ06y6g04fGgcnpjLCjhmqy+kKiv8NFeMX529kVr5uyb43dcVOcbd/bv5RniJxg==} + '@esri/calcite-components@2.13.0': + resolution: {integrity: sha512-szlPLr4RjxegU9Bvxwf4/U2ciI2zJdoDpW7/A7353nz5x+bJJa3GvwEYyuye533faC9p2KoGpEXcB/8susISIg==} - '@esri/calcite-ui-icons@3.31.0': - resolution: {integrity: sha512-Ca3xVXU0LoxljEebuM9r3ss4tyXBfHROcxlFmbNwa2kDTVNSjUKCBgthgXnMD7akgguwwcL7zGnAp645SkJpow==} + '@esri/calcite-ui-icons@3.32.0': + resolution: {integrity: sha512-2UEddEeSnpXVWp/uNrgym3mrb8lZ5+vXFbtmvXv5NiE32nQGw2MFZD52L5Z+FsxqHJ9vVrtl/X6pTIgkd0c8jA==} hasBin: true '@farmfe/utils@0.0.1': @@ -5729,8 +5763,8 @@ packages: '@floating-ui/dom@1.5.3': resolution: {integrity: sha512-ClAbQnEqJAKCJOEbbLo5IUlZHkNszqhuxS4fHAVxRPXPya6Ysf2G8KypnYcOTpx6I8xcgF9bbHb6g/2KpbV8qA==} - '@floating-ui/dom@1.6.10': - resolution: {integrity: sha512-fskgCFv8J8OamCmyun8MfjB1Olfn+uZKjOKZ0vhYF3gRmEUXcGOjxWL8bBr7i4kIuPZ2KD2S3EUIOxnjC8kl2A==} + '@floating-ui/dom@1.6.11': + resolution: {integrity: sha512-qkMCxSR24v2vGkhYDo/UzxfJN3D4syqSjyuTFz6C7XcpU1pASPRieNI0Kj5VP3/503mOfYiGY891ugBX1GlABQ==} '@floating-ui/react-dom@2.1.1': resolution: {integrity: sha512-4h84MJt3CHrtG18mGsXuLCHMrug49d7DFkU0RMIyshRveBeyV2hmV/pDaF2Uxtu8kgq5r46llp5E5FQiR0K2Yg==} @@ -8596,9 +8630,6 @@ packages: '@types/sockjs@0.3.36': resolution: {integrity: sha512-MK9V6NzAS1+Ud7JV9lJLFqW85VbC9dq3LmwZCuBe4wBDgKC0Kj/jd8Xl+nSviU+Qc3+m7umHHyHg//2KSa0a0Q==} - '@types/sortablejs@1.15.7': - resolution: {integrity: sha512-PvgWCx1Lbgm88FdQ6S7OGvLIjWS66mudKPlfdrWil0TjsO5zmoZmzoKiiwRShs1dwPgrlkr0N4ewuy0/+QUXYQ==} - '@types/sortablejs@1.15.8': resolution: {integrity: sha512-b79830lW+RZfwaztgs1aVPgbasJ8e7AXtZYHTELNXZPsERt4ymJdjV4OccDbHQAvHrCcFpbF78jkm0R6h/pZVg==} @@ -11391,8 +11422,8 @@ packages: dayjs@1.11.10: resolution: {integrity: sha512-vjAczensTgRcqDERK0SR2XMwsF/tSvnvlv6VcF2GIhg6Sx4yOIt/irsr1RDJsKiIyBzJDpCoXiWWq28MqH2cnQ==} - dayjs@1.11.12: - resolution: {integrity: sha512-Rt2g+nTbLlDWZTwwrIXjy9MeiZmSDI375FvZs72ngxx8PDC6YXOeR3q5LAuPzjZQxhiWdRKac7RKV+YyQYfYIg==} + dayjs@1.11.13: + resolution: {integrity: sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==} de-indent@1.0.2: resolution: {integrity: sha512-e/1zu3xH5MQryN2zdVaF0OrdNLUbvWxzMbi+iNA6Bky7l1RoP8a2fIbRocyHclXt/arDrrR6lL3TqFD9pMQTsg==} @@ -12503,8 +12534,8 @@ packages: resolution: {integrity: sha512-a8Ge6cdKh9za/GZR/qtigTAk7SrGore56EFcoMshClsh7FLk1zwszc/ltuMfKhx56qeuyL/jWQ4J4axou0iJ9w==} engines: {node: '>=10'} - focus-trap@7.5.4: - resolution: {integrity: sha512-N7kHdlgsO/v+iD/dMoJKtsSqs5Dz/dXZVebRgJw23LDk+jMi/974zyiOYDziY2JPp8xivq9BmUGwIJMiuSBi7w==} + focus-trap@7.6.0: + resolution: {integrity: sha512-1td0l3pMkWJLFipobUcGaf+5DTY4PLDDrcqoSaKP8ediO/CoWCCYk/fT/Y2A4e6TNB+Sh6clRJCjOPPnKoNHnQ==} follow-redirects@1.15.3: resolution: {integrity: sha512-1VzOtuEM8pC9SFU1E+8KfTjZyMztRsgEfwQl44z8A25uy13jSzTj6dyK2Df52iV0vgHCfBwLhDWevLn95w5v6Q==} @@ -18053,12 +18084,12 @@ packages: resolution: {integrity: sha512-0xtkGhWCC9MGt/EzgnvbbbKhqWjl1+/rncmhTh5qCpbYguXh6S/qwePfv/JQ8jePXXmqingylxoC49pCkSPIbA==} engines: {node: '>= 6.3.0'} - sortablejs@1.15.1: - resolution: {integrity: sha512-P5Cjvb0UG1ZVNiDPj/n4V+DinttXG6K8n7vM/HQf0C25K3YKQTQY6fsr/sEGsJGpQ9exmPxluHxKBc0mLKU1lQ==} - sortablejs@1.15.2: resolution: {integrity: sha512-FJF5jgdfvoKn1MAKSdGs33bIqLi3LmsgVTliuX6iITj834F+JRQZN90Z93yql8h0K2t0RwDPBmxwlbZfDcxNZA==} + sortablejs@1.15.3: + resolution: {integrity: sha512-zdK3/kwwAK1cJgy1rwl1YtNTbRmc8qW/+vgXf75A7NHag5of4pyI6uK86ktmQETyWRH7IGaE73uZOOBcGxgqZg==} + source-map-js@1.0.2: resolution: {integrity: sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==} engines: {node: '>=0.10.0'} @@ -18631,8 +18662,8 @@ packages: thunky@1.1.0: resolution: {integrity: sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==} - timezone-groups@0.9.1: - resolution: {integrity: sha512-1+GERLQpmebtCpkroy+AAfN/PZu8drrp4VAX/KSFBWvoaAT+5ANZIMTSn8CDW2uwfrpo1SaxIJ6MqdlACYbq/g==} + timezone-groups@0.10.2: + resolution: {integrity: sha512-01G9JdlIybA9Njp0wJcGenXKWAw+woWbv6W/oMexWyPs7Nr/S2p2n1NRrMHbHaFzdf+PNNStQp1WILdnAGjYXQ==} engines: {node: '>=18.12.0'} tiny-each-async@2.0.3: @@ -20627,7 +20658,7 @@ snapshots: dependencies: '@esri/arcgis-html-sanitizer': 4.0.3 '@esri/calcite-colors': 6.1.0 - '@esri/calcite-components': 2.12.2(@floating-ui/utils@0.2.8) + '@esri/calcite-components': 2.13.0(@floating-ui/utils@0.2.8) '@vaadin/grid': 24.3.22 '@zip.js/zip.js': 2.7.52 luxon: 3.4.4 @@ -20636,12 +20667,12 @@ snapshots: transitivePeerDependencies: - '@floating-ui/utils' - '@arcgis/map-components@4.30.7(@arcgis/core@4.30.9(@floating-ui/utils@0.2.8))(@esri/calcite-components@2.12.2(@floating-ui/utils@0.2.8))': + '@arcgis/map-components@4.30.7(@arcgis/core@4.30.9(@floating-ui/utils@0.2.8))(@esri/calcite-components@2.13.0(@floating-ui/utils@0.2.8))': dependencies: '@arcgis/components-controllers': 4.30.7(@arcgis/core@4.30.9(@floating-ui/utils@0.2.8)) '@arcgis/components-utils': 4.30.7 '@arcgis/core': 4.30.9(@floating-ui/utils@0.2.8) - '@esri/calcite-components': 2.12.2(@floating-ui/utils@0.2.8) + '@esri/calcite-components': 2.13.0(@floating-ui/utils@0.2.8) '@stencil/core': 4.17.1 transitivePeerDependencies: - '@arcgis/core-adapter' @@ -24572,26 +24603,26 @@ snapshots: '@esri/calcite-colors@6.1.0': {} - '@esri/calcite-components@2.12.2(@floating-ui/utils@0.2.8)': + '@esri/calcite-components@2.13.0(@floating-ui/utils@0.2.8)': dependencies: - '@esri/calcite-ui-icons': 3.31.0 - '@floating-ui/dom': 1.6.10 + '@esri/calcite-ui-icons': 3.32.0 + '@floating-ui/dom': 1.6.11 '@stencil/core': 4.20.0 '@types/color': 3.0.6 - '@types/sortablejs': 1.15.7 + '@types/sortablejs': 1.15.8 color: 4.2.3 composed-offset-position: 0.0.6(@floating-ui/utils@0.2.8) - dayjs: 1.11.12 - focus-trap: 7.5.4 + dayjs: 1.11.13 + focus-trap: 7.6.0 interactjs: 1.10.27 lodash-es: 4.17.21 - sortablejs: 1.15.1 - timezone-groups: 0.9.1 + sortablejs: 1.15.3 + timezone-groups: 0.10.2 type-fest: 4.18.2 transitivePeerDependencies: - '@floating-ui/utils' - '@esri/calcite-ui-icons@3.31.0': {} + '@esri/calcite-ui-icons@3.32.0': {} '@farmfe/utils@0.0.1': {} @@ -24608,14 +24639,14 @@ snapshots: '@floating-ui/core': 1.5.0 '@floating-ui/utils': 0.1.6 - '@floating-ui/dom@1.6.10': + '@floating-ui/dom@1.6.11': dependencies: '@floating-ui/core': 1.6.8 '@floating-ui/utils': 0.2.8 '@floating-ui/react-dom@2.1.1(react-dom@18.2.0(react@18.2.0))(react@18.2.0)': dependencies: - '@floating-ui/dom': 1.6.10 + '@floating-ui/dom': 1.6.11 react: 18.2.0 react-dom: 18.2.0(react@18.2.0) @@ -26191,7 +26222,7 @@ snapshots: '@opentiny/vue-guide@3.18.0': dependencies: - '@floating-ui/dom': 1.6.10 + '@floating-ui/dom': 1.6.11 '@opentiny/vue-common': 3.18.0 '@opentiny/vue-renderless': 3.18.4 '@opentiny/vue-theme': 3.18.2 @@ -29891,8 +29922,6 @@ snapshots: dependencies: '@types/node': 20.14.12 - '@types/sortablejs@1.15.7': {} - '@types/sortablejs@1.15.8': {} '@types/stack-utils@2.0.3': {} @@ -31362,7 +31391,7 @@ snapshots: '@babel/runtime': 7.25.0 '@types/js-cookie': 2.2.7 ahooks-v3-count: 1.0.0 - dayjs: 1.11.12 + dayjs: 1.11.13 intersection-observer: 0.12.2 js-cookie: 2.2.1 lodash: 4.17.21 @@ -33508,7 +33537,7 @@ snapshots: dayjs@1.11.10: {} - dayjs@1.11.12: {} + dayjs@1.11.13: {} de-indent@1.0.2: {} @@ -34912,7 +34941,7 @@ snapshots: dependencies: tslib: 2.6.3 - focus-trap@7.5.4: + focus-trap@7.6.0: dependencies: tabbable: 6.2.0 @@ -41537,7 +41566,7 @@ snapshots: shepherd.js@11.1.1: dependencies: - '@floating-ui/dom': 1.6.10 + '@floating-ui/dom': 1.6.11 deepmerge: 4.3.1 shiki-twoslash@3.1.2(typescript@5.5.4): @@ -41738,10 +41767,10 @@ snapshots: sort-css-media-queries@2.2.0: {} - sortablejs@1.15.1: {} - sortablejs@1.15.2: {} + sortablejs@1.15.3: {} + source-map-js@1.0.2: {} source-map-js@1.2.0: {} @@ -42468,7 +42497,7 @@ snapshots: thunky@1.1.0: {} - timezone-groups@0.9.1: {} + timezone-groups@0.10.2: {} tiny-each-async@2.0.3: optional: true diff --git a/rust-plugins/react/src/is_react_refresh_boundary.ts b/rust-plugins/react/src/is_react_refresh_boundary.ts index c9782114b..40703a9ed 100644 --- a/rust-plugins/react/src/is_react_refresh_boundary.ts +++ b/rust-plugins/react/src/is_react_refresh_boundary.ts @@ -3,8 +3,6 @@ import Refresh from 'react-refresh'; type ModExport = Record; -// from: https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/src/refreshUtils.js - // @ts-ignore export function validateRefreshBoundaryAndEnqueueUpdate(prevExports: ModExport, nextExports: ModExport) { const ignoredExports = [] diff --git a/rust-plugins/react/src/react_refresh.rs b/rust-plugins/react/src/react_refresh.rs index b96c5a408..a82f3d612 100644 --- a/rust-plugins/react/src/react_refresh.rs +++ b/rust-plugins/react/src/react_refresh.rs @@ -31,11 +31,46 @@ lazy_static! { ) }; } - +// polyfill like https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/src/refreshUtils.js +// +// +// +// ```js +// Object.defineProperty(exports, "Foo", { +// get() { +// return Foo +// } +// }); +// +// Object.defineProperty(exports, "Bar", { +// get() { +// return Bar +// } +// }); +// +// +// +// // moduleA +// const Foo = () => {} +// +// // ... +// ReactRefreshUtil.registerExportsForReactRefresh(module.exports, module.id); +// // Until here, `Bar` is still not initialized +// // ... +// +// // moduleB +// const Bar = () => {} +// ``` +// + +// When merging multiple modules, the exports will be promoted and contain side effects +// so the getter cannot be triggered immediately when `registerExportsForReactRefresh`. +// maybe there are other better ways. const POST_CODE: &str = r#" window.$RefreshReg$ = prevRefreshReg; window.$RefreshSig$ = prevRefreshSig; if (import.meta.hot) { + setTimeout(() => { ReactRefreshUtil.registerExportsForReactRefresh(module.exports, module.id); import.meta.hot.accept(nextExport => { @@ -47,6 +82,7 @@ if (import.meta.hot) { }); ReactRefreshUtil.enqueueUpdate(); + }) } "#; diff --git a/scripts/build.mjs b/scripts/build.mjs index 352a716c1..8e652bddc 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -32,13 +32,28 @@ export const EXAMPLES_DIR = resolve(CWD, "./examples"); export const excludedJsPlugin = ["dts"]; +const skipExamples = [ + // circle build when run `pnpm run build` + "electron", + // @swc/plugin-emotion version conflict + "emotion", + // solid js plugin alias compatible + "solid", + "solid-ssr", + // tree shake failed when farm build + "vanilla-extract", +]; + export const buildExamples = async () => { const examples = fs.readdirSync("./examples"); console.log("Building", examples.length, "examples..."); for (const example of examples) { const examplePath = join("./examples", example); - if (!existsSync(join(examplePath, "package.json"))) { + if ( + !existsSync(join(examplePath, "package.json")) || + skipExamples.includes(example) + ) { continue; } console.log("Building", examplePath);