@nullvoxpopuli/ember-vite 1.0.3 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,28 +8,29 @@ A speed-optimized default meta-config for ember projects.
8
8
  npm add @nullvoxpopuli/ember-vite
9
9
  ```
10
10
 
11
- Requires node 24+
11
+ Requires node 24+. These packages ship TypeScript source, so type-checking
12
+ needs TypeScript 6+ with `lib` covering `es2025` (for example `esnext`).
12
13
 
13
14
  ## Usage
14
15
 
15
- in your vite config
16
+ In your vite config:
16
17
 
17
18
  ```js
18
19
  import { defineConfig } from "vite";
19
20
  import { ember } from "@nullvoxpopuli/ember-vite";
20
21
 
21
22
  export default defineConfig({
22
- plugins: [
23
- ember(),
24
- ],
25
- }
23
+ plugins: [ember()],
24
+ });
26
25
  ```
27
26
 
28
- And remove any plugins from embroider or babel.
29
- Then delete from your package.json: `@rollup/plugin-babel`, `@embroider/core`, `@embroider/vite`.
27
+ Then:
28
+
29
+ 1. Remove any plugins from embroider or babel.
30
+ 2. Delete from your package.json: `@rollup/plugin-babel`, `@embroider/core`, `@embroider/vite`.
30
31
 
31
32
  > [!NOTE]
32
- > babel related deps are still needed for linting, so don't delete those
33
+ > Linting still needs the babel related deps, so keep those.
33
34
 
34
35
  ## Requirements
35
36
 
@@ -43,34 +44,18 @@ The `ember()` plugin takes the following options:
43
44
 
44
45
  ```ts
45
46
  ember({
46
- // optional production configs
47
47
  production: {
48
- // optional configuration of codeSplitting.groups
49
- // in the vite config.
50
- //
51
- // Docs here:
52
- // https://rolldown.rs/reference/OutputOptions.codeSplitting#groups
53
48
  codeSplittingGroups: [
54
- /* ... */
49
+ /* https://rolldown.rs/reference/OutputOptions.codeSplitting#groups */
55
50
  ],
56
51
  },
57
- // optional babel config
58
52
  babel: {
59
- // defaults to true.
60
- // when babel runs, do so in parallel across many cores.
61
53
  parallel: false,
62
- // optional way to configure when babel is activateed.
63
- // by default, all transforming is oxc, except when babel is needed
64
- // (for things not currently implemented in oxc)
65
54
  include: {
66
- // if a file imports from anything in this array, use babel instead of
67
- // oxc for that file.
68
- //
69
- // For example: ['ember-concurrency', 'ember-intl/format-message'],
70
- whenImporting: [
71
- /* ... */
72
- ],
55
+ whenImporting: ["ember-concurrency", "ember-intl/format-message"],
73
56
  },
74
57
  },
75
58
  });
76
59
  ```
60
+
61
+ Each option is documented on its type.
package/dist/index.js CHANGED
@@ -1,165 +1,75 @@
1
+ import { buildMacros } from "@embroider/macros/babel";
1
2
  import { ember as ember$1, extensions, resolver, templateTag } from "@embroider/vite";
2
3
  import { existsSync } from "node:fs";
3
4
  import { join, resolve } from "node:path";
4
- import { babel } from "@rollup/plugin-babel";
5
- import { parse } from "oxc-parser";
6
- import { transform } from "oxc-transform";
7
- import { walk } from "zimmerframe";
8
- //#region src/maybe-babel.ts
5
+ import { maybeBabel, maybeBabel as maybeBabel$1 } from "@nullvoxpopuli/ember-build-tooling-utils";
6
+ //#region src/test-html.ts
9
7
  /**
10
- * Reasons we have to have babel
11
- * - decorators
12
- * - ember-concurrency
13
- * - scoped-css
14
- * - template compilation optimization
8
+ * Everything a QUnit + testem run needs, with no project-specific references.
9
+ *
10
+ * - root-relative specifiers keep it independent of where the project keeps its files
11
+ * - the globs pick up tests/** as well as co-located `*-test` modules under src/**
15
12
  */
13
+ const DEFAULT_TEST_HTML = `<!doctype html>
14
+ <html>
15
+ <head>
16
+ <meta charset="utf-8" />
17
+ <title>Tests</title>
18
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
19
+ </head>
20
+ <body>
21
+ <div id="qunit"></div>
22
+ <div id="qunit-fixture">
23
+ <div id="ember-testing-container">
24
+ <div id="ember-testing"></div>
25
+ </div>
26
+ </div>
27
+
28
+ <script src="/testem.js" integrity="" data-embroider-ignore><\/script>
29
+ <script type="module">
30
+ import "ember-testing";
31
+ <\/script>
32
+
33
+ <script type="module">
34
+ import { start } from "/tests/test-helper";
35
+ import.meta.glob("/tests/**/*.{js,ts,gjs,gts}", { eager: true });
36
+ import.meta.glob("/src/**/*-test.{js,ts,gjs,gts}", { eager: true });
37
+ start();
38
+ <\/script>
39
+ </body>
40
+ </html>
41
+ `;
16
42
  /**
17
- * if a file imports any of these, it must be optimize
43
+ * Lets a project run its tests without maintaining a tests/index.html.
44
+ *
45
+ * Whenever that file is absent, this plugin answers for it:
46
+ * - `load` supplies the html to the build
47
+ * (so `tests/index.html` still lands in dist for testem)
48
+ * - the dev-server middleware serves it, through `transformIndexHtml`,
49
+ * so the html goes through the same pipeline as an on-disk file
50
+ *
51
+ * A tests/index.html on disk always wins.
52
+ * Every hook here defers to it.
18
53
  */
19
- const babelTemplateImports = /* @__PURE__ */ new Set([
20
- "@ember/template-compiler",
21
- "@ember/template-compilation",
22
- "ember-cli-htmlbars",
23
- "ember-cli-htmlbars-inline-precompile",
24
- "htmlbars-inline-precompile"
25
- ]);
26
- const babelMacroImports = /* @__PURE__ */ new Set([
27
- "@embroider/macros",
28
- "@glimmer/env",
29
- "@ember/application/deprecations",
30
- "@ember/debug"
31
- ]);
32
- const babelOtherImports = /* @__PURE__ */ new Set([
33
- "ember-concurrency",
34
- "ember-scoped-css",
35
- "ember-intl/helpers/format-message"
36
- ]);
37
- const babelRequiredImports = [
38
- ...babelTemplateImports,
39
- ...babelMacroImports,
40
- ...babelOtherImports
41
- ];
42
- const counts = {
43
- total: 0,
44
- babel: 0,
45
- why: {
46
- decorators: 0,
47
- formatMessage: 0,
48
- imports: {
49
- templates: 0,
50
- macros: 0,
51
- other: 0
52
- },
53
- initializeRuntimeMacrosConfig: 0
54
- }
55
- };
56
- function maybeBabel(options) {
57
- const { env, parallel, ...restOptions } = options;
58
- const original = (() => {
59
- const babelPath = resolve(join(process.cwd(), "./babel.config.js"));
60
- return babel({
61
- babelHelpers: "runtime",
62
- extensions,
63
- skipPreflightCheck: true,
64
- ...restOptions,
65
- configFile: babelPath,
66
- parallel: parallel ?? true
67
- });
68
- })();
69
- /**
70
- * In @rollup/plugin-babel v7+, the `transform` hook is the object form
71
- * `{ filter, handler }` rather than a plain function. Normalize to the
72
- * underlying handler so we can invoke it directly.
73
- */
74
- const originalTransform = typeof original.transform === "function" ? original.transform : original.transform?.handler;
75
- const babelMacros = new Set(babelRequiredImports);
76
- if (env.mode === "development") babelMacros.delete("@ember/debug");
77
- async function doTransform(code, id) {
78
- counts.total++;
79
- const ext = id.split(".").at(-1);
80
- const lang = ext === "gjs" ? "js" : ext === "gts" ? "ts" : ext;
81
- let needsBabel = false;
82
- walk((await parse(id, code, { lang })).program, {}, {
83
- Decorator(_node, { stop }) {
84
- needsBabel = true;
85
- counts.why.decorators++;
86
- stop();
87
- },
88
- MemberExpression(node, { stop }) {
89
- if (node.property?.name === "formatMessage" && node.object?.name === "intl") {
90
- needsBabel = true;
91
- counts.why.formatMessage++;
92
- stop();
93
- }
94
- },
95
- ImportDeclaration(node, { stop }) {
96
- const value = node.source.value;
97
- if (babelMacros.has(value)) {
98
- needsBabel = true;
99
- if (babelTemplateImports.has(value)) counts.why.imports.templates++;
100
- else if (babelMacroImports.has(value)) counts.why.imports.macros++;
101
- else counts.why.imports.other++;
102
- stop();
103
- }
104
- }
105
- });
106
- if (!needsBabel && code.includes("initializeRuntimeMacrosConfig")) {
107
- counts.why.initializeRuntimeMacrosConfig++;
108
- needsBabel = true;
109
- }
110
- if (needsBabel) {
111
- counts.babel++;
112
- return await originalTransform.call(this, code, id);
113
- }
114
- if (ext === "json") return;
115
- if (ext === "js" || ext === "gjs") return null;
116
- const result = await transform(id, code, {
117
- lang,
118
- typescript: {
119
- onlyRemoveTypeImports: true,
120
- /**
121
- * We should work towards disabling this.
122
- */
123
- allowNamespaces: true,
124
- removeClassFieldsWithoutInitializer: false,
125
- rewriteImportExtensions: false
126
- }
127
- });
128
- if (result.errors?.length) {
129
- console.error(`Errors during oxc-transform of ${id}:`);
130
- for (const err of result.errors) {
131
- if (err.labels) console.error(err.labels);
132
- console.error(err.codeframe || err.message);
133
- }
134
- throw result.errors;
135
- }
136
- return result;
137
- }
54
+ function testHtml() {
55
+ const htmlPath = join(process.cwd(), "tests", "index.html");
138
56
  return {
139
- enforce: "pre",
140
- buildEnd() {
141
- if (process.env.INSPECT) console.debug(`Babel usage: ${counts.babel} / ${counts.total}`, counts.why);
57
+ name: "ember:default-test-html",
58
+ resolveId(id) {
59
+ if (id === htmlPath && !existsSync(htmlPath)) return id;
142
60
  },
143
- ...original,
144
- name: "nullvoxpopuli:babel",
145
- transform: {
146
- filter: { id: {
147
- include: [
148
- /\.js/,
149
- /\.gjs/,
150
- /\.ts/,
151
- /\.gts/
152
- ],
153
- exclude: [/\.json/]
154
- } },
155
- handler(code, id) {
156
- try {
157
- return doTransform.call(this, code, id);
158
- } catch (e) {
159
- debugger;
160
- throw e;
161
- }
162
- }
61
+ load(id) {
62
+ if (id === htmlPath && !existsSync(htmlPath)) return DEFAULT_TEST_HTML;
63
+ },
64
+ configureServer(server) {
65
+ server.middlewares.use(async (req, res, next) => {
66
+ if (existsSync(htmlPath)) return next();
67
+ const url = (req.url ?? "").split("?")[0];
68
+ if (url !== "/tests" && url !== "/tests/" && url !== "/tests/index.html") return next();
69
+ const html = await server.transformIndexHtml("/tests/index.html", DEFAULT_TEST_HTML);
70
+ res.setHeader("Content-Type", "text/html");
71
+ res.end(html);
72
+ });
163
73
  }
164
74
  };
165
75
  }
@@ -170,8 +80,78 @@ const cwd = process.cwd();
170
80
  function absolutePath(relativePath) {
171
81
  return join(cwd, relativePath);
172
82
  }
83
+ /**
84
+ * Everything a project without its own babel config needs:
85
+ *
86
+ * - TypeScript stripping
87
+ * - template compilation, to the wire format
88
+ * (vite serves and bundles for the project's own ember-source,
89
+ * so the final compile happens here)
90
+ * - build macros, evaluated at build time
91
+ * - decorator-transforms, with its runtime left as a bare specifier
92
+ * so it resolves from the project
93
+ * (the project depends on `decorator-transforms`)
94
+ *
95
+ * The plugins are named, not imported.
96
+ * babel resolves them from the project, which carries them as its own dependencies.
97
+ */
98
+ function defaultBabelPlugins() {
99
+ const macros = buildMacros();
100
+ return [
101
+ ["@babel/plugin-transform-typescript", {
102
+ allExtensions: true,
103
+ onlyRemoveTypeImports: true,
104
+ allowDeclareFields: true
105
+ }],
106
+ ["babel-plugin-ember-template-compilation", { transforms: [...macros.templateMacros] }],
107
+ ["module:decorator-transforms", { runtime: { import: "decorator-transforms/runtime-esm" } }],
108
+ ...macros.babelMacros
109
+ ];
110
+ }
111
+ /**
112
+ * The project's babel config wins when it exists.
113
+ * `babel.configFile` selects which one (e.g. a test-only `config/test/babel.config.js`).
114
+ *
115
+ * Without one (libraries), `defaultBabelPlugins` covers TypeScript, templates, macros, and decorators,
116
+ * so no config file is required.
117
+ *
118
+ * Helpers are inlined in that case:
119
+ * projects without a babel config don't carry `@babel/runtime`.
120
+ */
121
+ function babelOptions(nvpConfig) {
122
+ const configFile = resolve(join(process.cwd(), nvpConfig.babel?.configFile ?? "./babel.config.js"));
123
+ if (existsSync(configFile)) return { configFile };
124
+ return {
125
+ configFile: false,
126
+ babelrc: false,
127
+ babelHelpers: "inline",
128
+ plugins: defaultBabelPlugins()
129
+ };
130
+ }
131
+ /**
132
+ * Additional opt-ins beyond maybeBabel's built-in list.
133
+ *
134
+ * These libraries ship code that still needs babel:
135
+ * - ember-concurrency's decorators
136
+ * - ember-scoped-css transforms
137
+ * - ember-intl's formatMessage macro
138
+ *
139
+ * The `initializeRuntimeMacrosConfig` runtime call must also be compiled away.
140
+ */
141
+ function babelFilter(nvpConfig) {
142
+ return { include: {
143
+ imports: [
144
+ "ember-concurrency",
145
+ "ember-scoped-css",
146
+ "ember-intl/helpers/format-message",
147
+ ...nvpConfig.babel?.include?.whenImporting ?? []
148
+ ],
149
+ code: [/\bintl\.formatMessage\b/, "initializeRuntimeMacrosConfig"]
150
+ } };
151
+ }
173
152
  function ember(nvpConfig = {}) {
174
- const babelConfigFile = resolve(join(process.cwd(), "./babel.config.js"));
153
+ const babel = babelOptions(nvpConfig);
154
+ const filter = babelFilter(nvpConfig);
175
155
  return [
176
156
  {
177
157
  name: "ember:nullvoxpopuli",
@@ -193,20 +173,21 @@ function ember(nvpConfig = {}) {
193
173
  viteConfig.optimizeDeps.rolldownOptions.plugins = [
194
174
  resolver({ rolldown: true }),
195
175
  templateTag(),
196
- maybeBabel({
197
- env,
176
+ maybeBabel$1({
177
+ ...babel,
198
178
  parallel: nvpConfig.babel?.parallel,
199
- configFile: babelConfigFile
179
+ filter
200
180
  })
201
181
  ];
202
182
  }
203
183
  },
204
184
  resolver({ rolldown: true }),
205
185
  templateTag(),
206
- maybeBabel({
207
- env: { mode: "development" },
186
+ testHtml(),
187
+ maybeBabel$1({
188
+ ...babel,
208
189
  parallel: nvpConfig.babel?.parallel,
209
- configFile: babelConfigFile
190
+ filter
210
191
  })
211
192
  ];
212
193
  }
@@ -219,14 +200,12 @@ function applyConfig(viteConfig, env, nvpConfig) {
219
200
  return prod(viteConfig, nvpConfig);
220
201
  }
221
202
  function dev(viteConfig, nvpConfig) {
222
- /**************************************
223
- *
203
+ /**
224
204
  * build config for tests
225
205
  *
226
- * NOTE: we can't minify because some tests
227
- * are checking x.constructor.name, which changes when minified
228
- *
229
- *************************************/
206
+ * NOTE: we can't minify.
207
+ * some tests check x.constructor.name, which changes when minified
208
+ */
230
209
  Object.assign(viteConfig.build, {
231
210
  sourcemap: true,
232
211
  cleanCssOptions: { sourceMap: true },
@@ -236,9 +215,10 @@ function dev(viteConfig, nvpConfig) {
236
215
  viteConfig.build.rolldownOptions ||= {};
237
216
  viteConfig.build.rolldownOptions.input ||= {};
238
217
  viteConfig.build.rolldownOptions.output ||= {};
239
- Object.assign(viteConfig.build.rolldownOptions.input, { main: absolutePath("./index.html") });
240
- if (existsSync("./tests.html")) Object.assign(viteConfig.build.rolldownOptions.input, { tests: absolutePath("./tests.html") });
218
+ if (existsSync("./index.html")) Object.assign(viteConfig.build.rolldownOptions.input, { main: absolutePath("./index.html") });
241
219
  if (existsSync("./tests/index.html")) Object.assign(viteConfig.build.rolldownOptions.input, { tests: absolutePath("./tests/index.html") });
220
+ else if (existsSync("./tests.html")) Object.assign(viteConfig.build.rolldownOptions.input, { tests: absolutePath("./tests.html") });
221
+ else if (existsSync("./tests")) Object.assign(viteConfig.build.rolldownOptions.input, { tests: absolutePath("./tests/index.html") });
242
222
  Object.assign(viteConfig.build.rolldownOptions.output, {
243
223
  cleanDir: true,
244
224
  strictExecutionOrder: true,
@@ -277,7 +257,7 @@ function prod(viteConfig, nvpConfig) {
277
257
  viteConfig.build.rolldownOptions.input ||= {};
278
258
  viteConfig.build.rolldownOptions.optimization ||= {};
279
259
  viteConfig.build.rolldownOptions.output ||= {};
280
- Object.assign(viteConfig.build.rolldownOptions.input, { main: absolutePath("./index.html") });
260
+ if (existsSync("./index.html")) Object.assign(viteConfig.build.rolldownOptions.input, { main: absolutePath("./index.html") });
281
261
  Object.assign(viteConfig.build.rolldownOptions.optimization, {
282
262
  inlineConst: {
283
263
  mode: "smart",
@@ -289,7 +269,8 @@ function prod(viteConfig, nvpConfig) {
289
269
  minify: true,
290
270
  cleanDir: true,
291
271
  /**
292
- * This is needed due to how we manage module state.
272
+ * Needed due to how we manage module state.
273
+ *
293
274
  * This can create waterfalls when too much top-level await is used.
294
275
  */
295
276
  strictExecutionOrder: true,
@@ -298,10 +279,10 @@ function prod(viteConfig, nvpConfig) {
298
279
  */
299
280
  codeSplitting: {
300
281
  /**
301
- * Kind of a shame this isn't automatic based on dynamic import usage
302
- * in vite8.
303
- * Kinda forces us to know every potential problem area of the app,
304
- * rather than rely on automatic optimizations based on import/module usage
282
+ * Kind of a shame this isn't automatic based on dynamic import usage in vite8.
283
+ *
284
+ * This forces us to know every potential problem area of the app,
285
+ * rather than rely on automatic optimizations based on import/module usage.
305
286
  */
306
287
  groups: [...nvpConfig?.production?.codeSplittingGroups ?? []] }
307
288
  });
package/index.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export { ember } from "./src/ember.ts";
2
- export { maybeBabel } from "./src/maybe-babel.ts";
2
+ export { maybeBabel } from "@nullvoxpopuli/ember-build-tooling-utils";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nullvoxpopuli/ember-vite",
3
- "version": "1.0.3",
3
+ "version": "1.1.1",
4
4
  "description": "Meta plugin for ember projects focusing on speed.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -19,18 +19,16 @@
19
19
  "dependencies": {
20
20
  "@babel/core": "^7.28.10",
21
21
  "@embroider/core": "^4.4.2",
22
+ "@embroider/macros": "^1.20.3",
22
23
  "@embroider/vite": "^1.5.0",
23
- "@rollup/plugin-babel": "^7.1.0",
24
- "oxc-parser": "^0.132.0",
25
- "oxc-transform": "^0.132.0",
26
- "zimmerframe": "^1.1.4"
24
+ "@nullvoxpopuli/ember-build-tooling-utils": "1.1.1"
27
25
  },
28
26
  "engines": {
29
27
  "node": ">= 24"
30
28
  },
31
29
  "devDependencies": {
32
30
  "rolldown": "^1.1.2",
33
- "typescript": "^5.9.3",
31
+ "typescript": "^6.0.3",
34
32
  "vite": "^8.0.14"
35
33
  },
36
34
  "scripts": {
package/src/ember.ts CHANGED
@@ -1,9 +1,12 @@
1
+ import { buildMacros } from "@embroider/macros/babel";
1
2
  import { ember as embroiderEmber, extensions, resolver, templateTag } from "@embroider/vite";
2
3
  import { existsSync } from "node:fs";
3
4
  import { join, resolve } from "node:path";
4
5
  import type { ConfigEnv, ResolvedConfig } from "vite";
5
6
 
6
- import { maybeBabel } from "./maybe-babel.ts";
7
+ import { maybeBabel } from "@nullvoxpopuli/ember-build-tooling-utils";
8
+
9
+ import { testHtml } from "./test-html.ts";
7
10
 
8
11
  const emberConfig = embroiderEmber()[3]!;
9
12
 
@@ -12,6 +15,99 @@ function absolutePath(relativePath: string) {
12
15
  return join(cwd, relativePath);
13
16
  }
14
17
 
18
+ /**
19
+ * Everything a project without its own babel config needs:
20
+ *
21
+ * - TypeScript stripping
22
+ * - template compilation, to the wire format
23
+ * (vite serves and bundles for the project's own ember-source,
24
+ * so the final compile happens here)
25
+ * - build macros, evaluated at build time
26
+ * - decorator-transforms, with its runtime left as a bare specifier
27
+ * so it resolves from the project
28
+ * (the project depends on `decorator-transforms`)
29
+ *
30
+ * The plugins are named, not imported.
31
+ * babel resolves them from the project, which carries them as its own dependencies.
32
+ */
33
+ function defaultBabelPlugins() {
34
+ const macros = buildMacros();
35
+
36
+ return [
37
+ [
38
+ "@babel/plugin-transform-typescript",
39
+ {
40
+ allExtensions: true,
41
+ onlyRemoveTypeImports: true,
42
+ allowDeclareFields: true,
43
+ },
44
+ ],
45
+ ["babel-plugin-ember-template-compilation", { transforms: [...macros.templateMacros] }],
46
+ ["module:decorator-transforms", { runtime: { import: "decorator-transforms/runtime-esm" } }],
47
+ ...macros.babelMacros,
48
+ ];
49
+ }
50
+
51
+ type BabelOptions =
52
+ | { configFile: string }
53
+ | {
54
+ configFile: false;
55
+ babelrc: false;
56
+ babelHelpers: "inline";
57
+ plugins: ReturnType<typeof defaultBabelPlugins>;
58
+ };
59
+
60
+ /**
61
+ * The project's babel config wins when it exists.
62
+ * `babel.configFile` selects which one (e.g. a test-only `config/test/babel.config.js`).
63
+ *
64
+ * Without one (libraries), `defaultBabelPlugins` covers TypeScript, templates, macros, and decorators,
65
+ * so no config file is required.
66
+ *
67
+ * Helpers are inlined in that case:
68
+ * projects without a babel config don't carry `@babel/runtime`.
69
+ */
70
+ function babelOptions(nvpConfig: Config): BabelOptions {
71
+ const configFile = resolve(
72
+ join(process.cwd(), nvpConfig.babel?.configFile ?? "./babel.config.js"),
73
+ );
74
+
75
+ if (existsSync(configFile)) {
76
+ return { configFile };
77
+ }
78
+
79
+ return {
80
+ configFile: false,
81
+ babelrc: false,
82
+ babelHelpers: "inline",
83
+ plugins: defaultBabelPlugins(),
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Additional opt-ins beyond maybeBabel's built-in list.
89
+ *
90
+ * These libraries ship code that still needs babel:
91
+ * - ember-concurrency's decorators
92
+ * - ember-scoped-css transforms
93
+ * - ember-intl's formatMessage macro
94
+ *
95
+ * The `initializeRuntimeMacrosConfig` runtime call must also be compiled away.
96
+ */
97
+ function babelFilter(nvpConfig: Config) {
98
+ return {
99
+ include: {
100
+ imports: [
101
+ "ember-concurrency",
102
+ "ember-scoped-css",
103
+ "ember-intl/helpers/format-message",
104
+ ...(nvpConfig.babel?.include?.whenImporting ?? []),
105
+ ],
106
+ code: [/\bintl\.formatMessage\b/, "initializeRuntimeMacrosConfig"] as (string | RegExp)[],
107
+ },
108
+ };
109
+ }
110
+
15
111
  interface Config {
16
112
  babel?: {
17
113
  /**
@@ -21,9 +117,20 @@ interface Config {
21
117
  parallel?: false;
22
118
 
23
119
  /**
24
- * optional way to configure when babel is activateed.
25
- * by default, all transforming is oxc, except when babel is needed
26
- * (for things not currently implemented in oxc)
120
+ * which babel config file to use for this build, relative to the
121
+ * project root. defaults to "./babel.config.js".
122
+ *
123
+ * useful when the root babel config belongs to another pipeline
124
+ * (e.g. a library's publish build) and the vite build needs its own,
125
+ * such as "./config/test/babel.config.js".
126
+ */
127
+ configFile?: string;
128
+
129
+ /**
130
+ * optional way to configure when babel is activated.
131
+ *
132
+ * by default, all transforming is oxc,
133
+ * except when babel is needed (for things not currently implemented in oxc)
27
134
  */
28
135
  include?: {
29
136
  /**
@@ -51,14 +158,16 @@ interface Config {
51
158
  }
52
159
 
53
160
  export function ember(nvpConfig: Config = {}) {
54
- const babelConfigFile = resolve(join(process.cwd(), "./babel.config.js"));
55
- const defaultEnv = { mode: process.env.NODE_ENV || "development" };
161
+ const babel = babelOptions(nvpConfig);
162
+ const filter = babelFilter(nvpConfig);
56
163
 
57
164
  /*
58
- * Plugins must be returned as top-level array entries — NOT pushed into
59
- * config.plugins inside a config() hook. Vite 8 extracts user plugins
60
- * *before* config hooks run, so anything added later is invisible to the
61
- * plugin container (resolveId, load, etc. hooks never fire).
165
+ * Plugins must be returned as top-level array entries,
166
+ * NOT pushed into config.plugins inside a config() hook.
167
+ *
168
+ * Vite 8 extracts user plugins *before* config hooks run,
169
+ * so anything added later is invisible to the plugin container
170
+ * (resolveId, load, etc. hooks never fire).
62
171
  */
63
172
  return [
64
173
  {
@@ -95,19 +204,23 @@ export function ember(nvpConfig: Config = {}) {
95
204
  resolver({ rolldown: true }),
96
205
  templateTag(),
97
206
 
98
- // Libraries will have precompileTemplate and macros, etc,
99
- // and we need to compile that away using this app's
100
- // template compiler
101
- maybeBabel({ env, parallel: nvpConfig.babel?.parallel, configFile: babelConfigFile }),
207
+ // Libraries ship precompileTemplate calls and macros.
208
+ // Both must compile away here, with this app's template compiler.
209
+ maybeBabel({
210
+ ...babel,
211
+ parallel: nvpConfig.babel?.parallel,
212
+ filter,
213
+ }),
102
214
  ];
103
215
  },
104
216
  },
105
217
  resolver({ rolldown: true }),
106
218
  templateTag(),
219
+ testHtml(),
107
220
  maybeBabel({
108
- env: defaultEnv,
221
+ ...babel,
109
222
  parallel: nvpConfig.babel?.parallel,
110
- configFile: babelConfigFile,
223
+ filter,
111
224
  }),
112
225
  ];
113
226
  }
@@ -127,14 +240,12 @@ function applyConfig(viteConfig: ResolvedConfig, env: ConfigEnv, nvpConfig: Conf
127
240
  }
128
241
 
129
242
  function dev(viteConfig: ResolvedConfig, nvpConfig: Config) {
130
- /**************************************
131
- *
243
+ /**
132
244
  * build config for tests
133
245
  *
134
- * NOTE: we can't minify because some tests
135
- * are checking x.constructor.name, which changes when minified
136
- *
137
- *************************************/
246
+ * NOTE: we can't minify.
247
+ * some tests check x.constructor.name, which changes when minified
248
+ */
138
249
  Object.assign(viteConfig.build, {
139
250
  sourcemap: true,
140
251
  cleanCssOptions: { sourceMap: true },
@@ -146,13 +257,10 @@ function dev(viteConfig: ResolvedConfig, nvpConfig: Config) {
146
257
  viteConfig.build.rolldownOptions.input ||= {};
147
258
  viteConfig.build.rolldownOptions.output ||= {};
148
259
 
149
- Object.assign(viteConfig.build.rolldownOptions.input, {
150
- main: absolutePath("./index.html"),
151
- });
152
-
153
- if (existsSync("./tests.html")) {
260
+ // libraries don't, by default, have a "demo app" entrypoint
261
+ if (existsSync("./index.html")) {
154
262
  Object.assign(viteConfig.build.rolldownOptions.input, {
155
- tests: absolutePath("./tests.html"),
263
+ main: absolutePath("./index.html"),
156
264
  });
157
265
  }
158
266
 
@@ -160,6 +268,16 @@ function dev(viteConfig: ResolvedConfig, nvpConfig: Config) {
160
268
  Object.assign(viteConfig.build.rolldownOptions.input, {
161
269
  tests: absolutePath("./tests/index.html"),
162
270
  });
271
+ } else if (existsSync("./tests.html")) {
272
+ Object.assign(viteConfig.build.rolldownOptions.input, {
273
+ tests: absolutePath("./tests.html"),
274
+ });
275
+ } else if (existsSync("./tests")) {
276
+ // no html of its own: the default-test-html plugin answers for
277
+ // tests/index.html
278
+ Object.assign(viteConfig.build.rolldownOptions.input, {
279
+ tests: absolutePath("./tests/index.html"),
280
+ });
163
281
  }
164
282
 
165
283
  Object.assign(viteConfig.build.rolldownOptions.output, {
@@ -203,9 +321,12 @@ function prod(viteConfig: ResolvedConfig, nvpConfig: Config) {
203
321
  viteConfig.build.rolldownOptions.optimization ||= {};
204
322
  viteConfig.build.rolldownOptions.output ||= {};
205
323
 
206
- Object.assign(viteConfig.build.rolldownOptions.input, {
207
- main: absolutePath("./index.html"),
208
- });
324
+ // libraries don't, by default, have a "demo app" entrypoint
325
+ if (existsSync("./index.html")) {
326
+ Object.assign(viteConfig.build.rolldownOptions.input, {
327
+ main: absolutePath("./index.html"),
328
+ });
329
+ }
209
330
 
210
331
  Object.assign(viteConfig.build.rolldownOptions.optimization, {
211
332
  inlineConst: {
@@ -219,7 +340,8 @@ function prod(viteConfig: ResolvedConfig, nvpConfig: Config) {
219
340
  minify: true,
220
341
  cleanDir: true,
221
342
  /**
222
- * This is needed due to how we manage module state.
343
+ * Needed due to how we manage module state.
344
+ *
223
345
  * This can create waterfalls when too much top-level await is used.
224
346
  */
225
347
  strictExecutionOrder: true,
@@ -228,10 +350,10 @@ function prod(viteConfig: ResolvedConfig, nvpConfig: Config) {
228
350
  */
229
351
  codeSplitting: {
230
352
  /**
231
- * Kind of a shame this isn't automatic based on dynamic import usage
232
- * in vite8.
233
- * Kinda forces us to know every potential problem area of the app,
234
- * rather than rely on automatic optimizations based on import/module usage
353
+ * Kind of a shame this isn't automatic based on dynamic import usage in vite8.
354
+ *
355
+ * This forces us to know every potential problem area of the app,
356
+ * rather than rely on automatic optimizations based on import/module usage.
235
357
  */
236
358
  groups: [...(nvpConfig?.production?.codeSplittingGroups ?? [])],
237
359
  },
@@ -0,0 +1,88 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import type { ViteDevServer } from "vite";
4
+
5
+ /**
6
+ * Everything a QUnit + testem run needs, with no project-specific references.
7
+ *
8
+ * - root-relative specifiers keep it independent of where the project keeps its files
9
+ * - the globs pick up tests/** as well as co-located `*-test` modules under src/**
10
+ */
11
+ const DEFAULT_TEST_HTML = `<!doctype html>
12
+ <html>
13
+ <head>
14
+ <meta charset="utf-8" />
15
+ <title>Tests</title>
16
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
17
+ </head>
18
+ <body>
19
+ <div id="qunit"></div>
20
+ <div id="qunit-fixture">
21
+ <div id="ember-testing-container">
22
+ <div id="ember-testing"></div>
23
+ </div>
24
+ </div>
25
+
26
+ <script src="/testem.js" integrity="" data-embroider-ignore></script>
27
+ <script type="module">
28
+ import "ember-testing";
29
+ </script>
30
+
31
+ <script type="module">
32
+ import { start } from "/tests/test-helper";
33
+ import.meta.glob("/tests/**/*.{js,ts,gjs,gts}", { eager: true });
34
+ import.meta.glob("/src/**/*-test.{js,ts,gjs,gts}", { eager: true });
35
+ start();
36
+ </script>
37
+ </body>
38
+ </html>
39
+ `;
40
+
41
+ /**
42
+ * Lets a project run its tests without maintaining a tests/index.html.
43
+ *
44
+ * Whenever that file is absent, this plugin answers for it:
45
+ * - `load` supplies the html to the build
46
+ * (so `tests/index.html` still lands in dist for testem)
47
+ * - the dev-server middleware serves it, through `transformIndexHtml`,
48
+ * so the html goes through the same pipeline as an on-disk file
49
+ *
50
+ * A tests/index.html on disk always wins.
51
+ * Every hook here defers to it.
52
+ */
53
+ export function testHtml() {
54
+ const htmlPath = join(process.cwd(), "tests", "index.html");
55
+
56
+ return {
57
+ name: "ember:default-test-html",
58
+
59
+ resolveId(id: string) {
60
+ if (id === htmlPath && !existsSync(htmlPath)) {
61
+ return id;
62
+ }
63
+ },
64
+
65
+ load(id: string) {
66
+ if (id === htmlPath && !existsSync(htmlPath)) {
67
+ return DEFAULT_TEST_HTML;
68
+ }
69
+ },
70
+
71
+ configureServer(server: ViteDevServer) {
72
+ server.middlewares.use(async (req, res, next) => {
73
+ if (existsSync(htmlPath)) return next();
74
+
75
+ const url = (req.url ?? "").split("?")[0];
76
+
77
+ if (url !== "/tests" && url !== "/tests/" && url !== "/tests/index.html") {
78
+ return next();
79
+ }
80
+
81
+ const html = await server.transformIndexHtml("/tests/index.html", DEFAULT_TEST_HTML);
82
+
83
+ res.setHeader("Content-Type", "text/html");
84
+ res.end(html);
85
+ });
86
+ },
87
+ };
88
+ }
@@ -1,219 +0,0 @@
1
- /**
2
- * Reasons we have to have babel
3
- * - decorators
4
- * - ember-concurrency
5
- * - scoped-css
6
- * - template compilation optimization
7
- */
8
- import { extensions } from "@embroider/vite";
9
- import { babel } from "@rollup/plugin-babel";
10
- import { join, resolve } from "node:path";
11
- import { parse as oxcParse } from "oxc-parser";
12
- import { transform } from "oxc-transform";
13
- import { walk } from "zimmerframe";
14
-
15
- /**
16
- * if a file imports any of these, it must be optimize
17
- */
18
- const babelTemplateImports = new Set([
19
- // Templates
20
- "@ember/template-compiler",
21
- "@ember/template-compilation",
22
- "ember-cli-htmlbars",
23
- "ember-cli-htmlbars-inline-precompile",
24
- "htmlbars-inline-precompile",
25
- ]);
26
-
27
- const babelMacroImports = new Set([
28
- // Macros
29
- "@embroider/macros",
30
- "@glimmer/env",
31
- "@ember/application/deprecations",
32
- // Macros only needed in prod
33
- "@ember/debug",
34
- ]); // Babel plugins required from libraries
35
- const babelOtherImports = new Set([
36
- "ember-concurrency",
37
- "ember-scoped-css",
38
- "ember-intl/helpers/format-message",
39
- ]);
40
-
41
- const babelRequiredImports = [...babelTemplateImports, ...babelMacroImports, ...babelOtherImports];
42
-
43
- const counts = {
44
- total: 0,
45
- babel: 0,
46
- why: {
47
- decorators: 0,
48
- formatMessage: 0,
49
- imports: {
50
- templates: 0,
51
- macros: 0,
52
- other: 0,
53
- },
54
- initializeRuntimeMacrosConfig: 0,
55
- },
56
- };
57
- export function maybeBabel(options: { parallel?: boolean; configFile: string; env: any }) {
58
- const { env, parallel, ...restOptions } = options;
59
- const original = (() => {
60
- const babelPath = resolve(join(process.cwd(), "./babel.config.js"));
61
-
62
- return babel({
63
- babelHelpers: "runtime",
64
- extensions,
65
- skipPreflightCheck: true,
66
- ...restOptions,
67
- configFile: babelPath,
68
- parallel: parallel ?? true,
69
- });
70
- })();
71
-
72
- /**
73
- * In @rollup/plugin-babel v7+, the `transform` hook is the object form
74
- * `{ filter, handler }` rather than a plain function. Normalize to the
75
- * underlying handler so we can invoke it directly.
76
- */
77
- const originalTransform = (
78
- typeof original.transform === "function" ? original.transform : original.transform?.handler
79
- )!;
80
-
81
- const babelMacros = new Set(babelRequiredImports);
82
- if (env.mode === "development") {
83
- babelMacros.delete("@ember/debug");
84
- }
85
-
86
- async function doTransform(this: any, code: string, id: string) {
87
- counts.total++;
88
-
89
- const ext = id.split(".").at(-1);
90
- const lang = (ext === "gjs" ? "js" : ext === "gts" ? "ts" : ext) as
91
- | "js"
92
- | "ts"
93
- | "jsx"
94
- | "tsx"
95
- | "dts"
96
- | undefined;
97
-
98
- let needsBabel = false;
99
-
100
- const estree = await oxcParse(id, code, { lang });
101
-
102
- walk(
103
- estree.program as any,
104
- /* state */ {},
105
- {
106
- Decorator(_node: any, { stop }: any) {
107
- needsBabel = true;
108
- counts.why.decorators++;
109
- stop();
110
- },
111
- MemberExpression(node: any, { stop }: any) {
112
- if (node.property?.name === "formatMessage" && node.object?.name === "intl") {
113
- needsBabel = true;
114
- counts.why.formatMessage++;
115
- stop();
116
- }
117
- },
118
- ImportDeclaration(node: any, { stop }: any) {
119
- const value = node.source.value;
120
- if (babelMacros.has(value)) {
121
- needsBabel = true;
122
-
123
- if (babelTemplateImports.has(value)) {
124
- counts.why.imports.templates++;
125
- } else if (babelMacroImports.has(value)) {
126
- counts.why.imports.macros++;
127
- } else {
128
- counts.why.imports.other++;
129
- }
130
-
131
- stop();
132
- }
133
- },
134
- },
135
- );
136
-
137
- if (!needsBabel && code.includes("initializeRuntimeMacrosConfig")) {
138
- counts.why.initializeRuntimeMacrosConfig++;
139
- needsBabel = true;
140
- }
141
-
142
- if (needsBabel) {
143
- counts.babel++;
144
-
145
- const result = await originalTransform.call(this, code, id);
146
-
147
- return result;
148
- }
149
-
150
- if (ext === "json") {
151
- return;
152
- }
153
-
154
- if (ext === "js" || ext === "gjs") {
155
- // We don't need to process JS
156
- return null;
157
- }
158
-
159
- const result = await transform(id, code, {
160
- lang,
161
- typescript: {
162
- onlyRemoveTypeImports: true,
163
- /**
164
- * We should work towards disabling this.
165
- */
166
- allowNamespaces: true,
167
- removeClassFieldsWithoutInitializer: false,
168
- rewriteImportExtensions: false,
169
- },
170
- });
171
-
172
- if (result.errors?.length) {
173
- console.error(`Errors during oxc-transform of ${id}:`);
174
- for (const err of result.errors) {
175
- if (err.labels) {
176
- console.error(err.labels);
177
- }
178
- console.error(err.codeframe || err.message);
179
- }
180
- throw result.errors;
181
- }
182
-
183
- return result;
184
- }
185
-
186
- return {
187
- enforce: "pre",
188
- buildEnd() {
189
- if (process.env.INSPECT) {
190
- console.debug(`Babel usage: ${counts.babel} / ${counts.total}`, counts.why);
191
- }
192
- },
193
- ...original,
194
- name: "nullvoxpopuli:babel",
195
- transform: {
196
- filter: {
197
- id: {
198
- include: [/\.js/, /\.gjs/, /\.ts/, /\.gts/],
199
- exclude: [/\.json/],
200
- },
201
- // Enabling this opts us out of template compilation
202
- // it's an AND instead of OR
203
- // code: {
204
- // include: [/initializeRuntimeMacrosConfig/, /precompileTemplate/],
205
- // },
206
- },
207
- handler(this: any, code: string, id: string) {
208
- try {
209
- return doTransform.call(this, code, id);
210
- } catch (e) {
211
- // Use VSCode JavaScript Debug Terminal
212
- // eslint-disable-next-line no-debugger
213
- debugger;
214
- throw e;
215
- }
216
- },
217
- },
218
- };
219
- }