@nullvoxpopuli/ember-vite 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -52,10 +52,13 @@ ember({
52
52
  babel: {
53
53
  parallel: false,
54
54
  include: {
55
- whenImporting: ["ember-concurrency", "ember-intl/format-message"],
55
+ whenImporting: ["my-babel-only-library"],
56
+ whenMatching: [/\bmyMacro\(/],
56
57
  },
57
58
  },
58
59
  });
59
60
  ```
60
61
 
61
62
  Each option is documented on its type.
63
+
64
+ If the project depends on `ember-concurrency`, `ember-intl`, `ember-scoped-css` or `unplugin-icons`, babel compiles their modules with no option.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { buildMacros } from "@embroider/macros/babel";
2
2
  import { ember as ember$1, extensions, resolver, templateTag } from "@embroider/vite";
3
- import { existsSync } from "node:fs";
3
+ import { existsSync, readFileSync } from "node:fs";
4
4
  import { join, resolve } from "node:path";
5
5
  import { maybeBabel, maybeBabel as maybeBabel$1 } from "@nullvoxpopuli/ember-build-tooling-utils";
6
6
  //#region src/test-html.ts
@@ -158,24 +158,55 @@ function babelOptions(nvpConfig) {
158
158
  };
159
159
  }
160
160
  /**
161
- * Additional opt-ins beyond maybeBabel's built-in list.
161
+ * Libraries that ship code that still needs babel.
162
+ * Each one adds to the filter only when the project depends on it,
163
+ * so other projects do not pay for the check.
162
164
  *
163
- * These libraries ship code that still needs babel:
164
165
  * - ember-concurrency's decorators
165
- * - ember-scoped-css transforms
166
166
  * - ember-intl's formatMessage macro
167
- *
168
- * The `initializeRuntimeMacrosConfig` runtime call must also be compiled away.
167
+ * - ember-scoped-css transforms
168
+ * - unplugin-icons, whose icon modules compile with `template()`.
169
+ * Their ids have no file extension, so only the id matches them.
170
+ */
171
+ const LIBRARY_FILTERS = {
172
+ "ember-concurrency": { imports: ["ember-concurrency"] },
173
+ "ember-intl": {
174
+ imports: ["ember-intl/helpers/format-message"],
175
+ code: [/\bintl\.formatMessage\b/]
176
+ },
177
+ "ember-scoped-css": { imports: ["ember-scoped-css"] },
178
+ "unplugin-icons": { ids: [/^~icons\//] }
179
+ };
180
+ function projectDependencies() {
181
+ const manifestPath = join(process.cwd(), "package.json");
182
+ if (!existsSync(manifestPath)) return /* @__PURE__ */ new Set();
183
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
184
+ return new Set(Object.keys({
185
+ ...manifest.dependencies,
186
+ ...manifest.devDependencies
187
+ }));
188
+ }
189
+ /**
190
+ * Additional opt-ins beyond maybeBabel's built-in list.
191
+ * The `initializeRuntimeMacrosConfig` runtime call must compile away in every project.
169
192
  */
170
193
  function babelFilter(nvpConfig) {
194
+ const imports = [];
195
+ const code = ["initializeRuntimeMacrosConfig"];
196
+ const ids = [];
197
+ const dependencies = projectDependencies();
198
+ for (const [name, filter] of Object.entries(LIBRARY_FILTERS)) {
199
+ if (!dependencies.has(name)) continue;
200
+ for (const specifier of filter.imports ?? []) imports.push(specifier);
201
+ for (const pattern of filter.code ?? []) code.push(pattern);
202
+ for (const pattern of filter.ids ?? []) ids.push(pattern);
203
+ }
204
+ for (const specifier of nvpConfig.babel?.include?.whenImporting ?? []) imports.push(specifier);
205
+ for (const pattern of nvpConfig.babel?.include?.whenMatching ?? []) code.push(pattern);
171
206
  return { include: {
172
- imports: [
173
- "ember-concurrency",
174
- "ember-scoped-css",
175
- "ember-intl/helpers/format-message",
176
- ...nvpConfig.babel?.include?.whenImporting ?? []
177
- ],
178
- code: [/\bintl\.formatMessage\b/, "initializeRuntimeMacrosConfig"]
207
+ imports,
208
+ code,
209
+ ids
179
210
  } };
180
211
  }
181
212
  function ember(nvpConfig = {}) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nullvoxpopuli/ember-vite",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
4
4
  "description": "Meta plugin for ember projects focusing on speed.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -21,13 +21,14 @@
21
21
  "@embroider/core": "^4.6.9",
22
22
  "@embroider/macros": "^1.21.3",
23
23
  "@embroider/vite": "^1.7.15",
24
- "@nullvoxpopuli/ember-build-tooling-utils": "1.2.0"
24
+ "@nullvoxpopuli/ember-build-tooling-utils": "1.3.0"
25
25
  },
26
26
  "engines": {
27
27
  "node": ">= 24"
28
28
  },
29
29
  "devDependencies": {
30
30
  "@babel/plugin-transform-typescript": "^7.28.10 || ^8.0.0",
31
+ "@rolldown/pluginutils": "^1.0.1",
31
32
  "babel-plugin-ember-template-compilation": "^4.0.1",
32
33
  "decorator-transforms": "^2.4.0",
33
34
  "rolldown": "^1.1.2",
package/src/ember.test.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import { extensions } from "@embroider/vite";
2
+ import { interpreter, type TopLevelFilterExpression } from "@rolldown/pluginutils";
3
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
2
5
  import { fileURLToPath } from "node:url";
3
6
  import type { ConfigEnv, ConfigPluginContext, Plugin } from "vite";
4
7
  import { afterEach, describe, expect, it } from "vitest";
@@ -108,20 +111,50 @@ async function compile(mode: string) {
108
111
  return result.code as string;
109
112
  }
110
113
 
111
- describe("default babel plugins", () => {
112
- let restoreCwd: (() => void) | undefined;
114
+ let restoreCwd: (() => void) | undefined;
113
115
 
114
- afterEach(() => {
115
- restoreCwd?.();
116
- restoreCwd = undefined;
117
- });
116
+ afterEach(() => {
117
+ restoreCwd?.();
118
+ restoreCwd = undefined;
119
+ });
118
120
 
119
- function inPackageRoot() {
120
- const previous = process.cwd();
121
- process.chdir(PACKAGE_ROOT);
122
- restoreCwd = () => process.chdir(previous);
123
- }
121
+ function inDirectory(directory: string) {
122
+ const previous = process.cwd();
123
+ process.chdir(directory);
124
+ restoreCwd = () => process.chdir(previous);
125
+ }
126
+
127
+ function inPackageRoot() {
128
+ inDirectory(PACKAGE_ROOT);
129
+ }
130
+
131
+ /**
132
+ * A project that depends on the libraries that need babel.
133
+ * It is inside this package, so babel resolves its plugins from here.
134
+ */
135
+ function inProjectWithLibraries() {
136
+ const cache = join(PACKAGE_ROOT, "node_modules/.cache");
137
+ mkdirSync(cache, { recursive: true });
138
+
139
+ const directory = mkdtempSync(join(cache, "project-"));
140
+ const devDependencies = {
141
+ "ember-concurrency": "*",
142
+ "ember-intl": "*",
143
+ "ember-scoped-css": "*",
144
+ "unplugin-icons": "*",
145
+ };
146
+
147
+ writeFileSync(join(directory, "package.json"), JSON.stringify({ devDependencies }));
148
+ inDirectory(directory);
149
+
150
+ const restore = restoreCwd!;
151
+ restoreCwd = () => {
152
+ restore();
153
+ rmSync(directory, { recursive: true, force: true });
154
+ };
155
+ }
124
156
 
157
+ describe("default babel plugins", () => {
125
158
  /**
126
159
  * vite sets NODE_ENV from the mode only after the config hooks run.
127
160
  * Under vitest, NODE_ENV is "test".
@@ -143,3 +176,142 @@ describe("default babel plugins", () => {
143
176
  expect(code).toContain("other build");
144
177
  });
145
178
  });
179
+
180
+ /**
181
+ * The module that unplugin-icons gives for an icon, with `compiler: "ember"`.
182
+ */
183
+ const ICON = [
184
+ `import { template } from "@ember/template-compiler";`,
185
+ `export default template("<svg ...attributes><path d='M20 6L9 17l-5-5'/></svg>");`,
186
+ ].join("\n");
187
+
188
+ describe("babel.include", () => {
189
+ function usesBabel(
190
+ options: Parameters<typeof ember>[0],
191
+ source: string,
192
+ moduleId = "/app/services/a.ts",
193
+ ) {
194
+ const plugins = ember(options) as Plugin[];
195
+ const babel = plugins.find((plugin) => plugin.name === "nullvoxpopuli:babel");
196
+ // @ts-expect-error maybeBabel sets the filter on the transform hook
197
+ const filter = babel.transform.filter as TopLevelFilterExpression[];
198
+
199
+ return interpreter(filter, source, moduleId);
200
+ }
201
+
202
+ const source = `owner.register(Key, Impl);`;
203
+
204
+ it("leaves files without a babel-only pattern to oxc", () => {
205
+ expect(usesBabel({}, source)).toBe(false);
206
+ });
207
+
208
+ it("sends files that contain a whenMatching string to babel", () => {
209
+ expect(usesBabel({ babel: { include: { whenMatching: [".register("] } } }, source)).toBe(true);
210
+ });
211
+
212
+ it("sends files that match a whenMatching regular expression to babel", () => {
213
+ expect(usesBabel({ babel: { include: { whenMatching: [/\.register\(/] } } }, source)).toBe(
214
+ true,
215
+ );
216
+ });
217
+
218
+ it("sends files that import a whenImporting module to babel", () => {
219
+ expect(
220
+ usesBabel(
221
+ { babel: { include: { whenImporting: ["my-lib"] } } },
222
+ `import { a } from "my-lib";`,
223
+ ),
224
+ ).toBe(true);
225
+ });
226
+ });
227
+
228
+ describe("libraries that need babel", () => {
229
+ function babelPerModule() {
230
+ const plugins = ember() as Plugin[];
231
+ const babel = plugins.find((plugin) => plugin.name === "nullvoxpopuli:babel");
232
+ // @ts-expect-error maybeBabel sets the filter on the transform hook
233
+ const filter = babel.transform.filter as TopLevelFilterExpression[];
234
+
235
+ return {
236
+ "ember-concurrency": interpreter(
237
+ filter,
238
+ `import { task } from "ember-concurrency";`,
239
+ "/app/components/a.js",
240
+ ),
241
+ "ember-intl import": interpreter(
242
+ filter,
243
+ `import formatMessage from "ember-intl/helpers/format-message";`,
244
+ "/app/components/a.js",
245
+ ),
246
+ "ember-intl formatMessage": interpreter(
247
+ filter,
248
+ `export const title = this.intl.formatMessage("Hello");`,
249
+ "/app/components/a.js",
250
+ ),
251
+ "ember-scoped-css": interpreter(
252
+ filter,
253
+ `import { scopedClass } from "ember-scoped-css";`,
254
+ "/app/components/a.js",
255
+ ),
256
+ "unplugin-icons": interpreter(filter, ICON, "~icons/lucide/check"),
257
+ };
258
+ }
259
+
260
+ it("leaves their modules to oxc when the project does not depend on them", () => {
261
+ inPackageRoot();
262
+
263
+ expect(babelPerModule()).toMatchInlineSnapshot(`
264
+ {
265
+ "ember-concurrency": false,
266
+ "ember-intl formatMessage": false,
267
+ "ember-intl import": false,
268
+ "ember-scoped-css": false,
269
+ "unplugin-icons": false,
270
+ }
271
+ `);
272
+ });
273
+
274
+ it("sends their modules to babel when the project depends on them", () => {
275
+ inProjectWithLibraries();
276
+
277
+ expect(babelPerModule()).toMatchInlineSnapshot(`
278
+ {
279
+ "ember-concurrency": true,
280
+ "ember-intl formatMessage": true,
281
+ "ember-intl import": true,
282
+ "ember-scoped-css": true,
283
+ "unplugin-icons": true,
284
+ }
285
+ `);
286
+ });
287
+
288
+ it("compiles the template of an icon module, which has no extension", async () => {
289
+ inProjectWithLibraries();
290
+
291
+ const plugins = ember() as Plugin[];
292
+ const config: any = {};
293
+
294
+ // @ts-expect-error the first entry is the config plugin
295
+ await plugins[0].config.call(ROLLDOWN, config, { command: "build", mode: "production" });
296
+
297
+ const babel = plugins.find((plugin) => plugin.name === "nullvoxpopuli:babel");
298
+ // @ts-expect-error the babel plugin has an object transform hook
299
+ const result = await babel.transform.handler.call(CONTEXT, ICON, "~icons/lucide/check");
300
+
301
+ expect(result.code).toMatchInlineSnapshot(`
302
+ "import { setComponentTemplate } from "@ember/component";
303
+ import { createTemplateFactory } from "@ember/template-factory";
304
+ import templateOnly from "@ember/component/template-only";
305
+ export default setComponentTemplate(createTemplateFactory(
306
+ /*
307
+ <svg ...attributes><path d='M20 6L9 17l-5-5'/></svg>
308
+ */
309
+ {
310
+ "id": null,
311
+ "block": "[[[11,\\"svg\\"],[17,1],[12],[10,\\"path\\"],[14,\\"d\\",\\"M20 6L9 17l-5-5\\"],[12],[13],[13]],[\\"&attrs\\"],[]]",
312
+ "moduleName": "(unknown template module)",
313
+ "isStrictMode": true
314
+ }), templateOnly());"
315
+ `);
316
+ });
317
+ });
package/src/ember.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { buildMacros } from "@embroider/macros/babel";
2
2
  import { ember as embroiderEmber, extensions, resolver, templateTag } from "@embroider/vite";
3
- import { existsSync } from "node:fs";
3
+ import { existsSync, readFileSync } from "node:fs";
4
4
  import { join, resolve } from "node:path";
5
5
  import type { ConfigEnv, ConfigPluginContext, ResolvedConfig, UserConfig } from "vite";
6
6
 
@@ -130,27 +130,66 @@ function babelOptions(nvpConfig: Config): BabelOptions {
130
130
  }
131
131
 
132
132
  /**
133
- * Additional opt-ins beyond maybeBabel's built-in list.
133
+ * Libraries that ship code that still needs babel.
134
+ * Each one adds to the filter only when the project depends on it,
135
+ * so other projects do not pay for the check.
134
136
  *
135
- * These libraries ship code that still needs babel:
136
137
  * - ember-concurrency's decorators
137
- * - ember-scoped-css transforms
138
138
  * - ember-intl's formatMessage macro
139
- *
140
- * The `initializeRuntimeMacrosConfig` runtime call must also be compiled away.
139
+ * - ember-scoped-css transforms
140
+ * - unplugin-icons, whose icon modules compile with `template()`.
141
+ * Their ids have no file extension, so only the id matches them.
142
+ */
143
+ const LIBRARY_FILTERS: Record<
144
+ string,
145
+ { imports?: string[]; code?: (string | RegExp)[]; ids?: RegExp[] }
146
+ > = {
147
+ "ember-concurrency": { imports: ["ember-concurrency"] },
148
+ "ember-intl": {
149
+ imports: ["ember-intl/helpers/format-message"],
150
+ code: [/\bintl\.formatMessage\b/],
151
+ },
152
+ "ember-scoped-css": { imports: ["ember-scoped-css"] },
153
+ "unplugin-icons": { ids: [/^~icons\//] },
154
+ };
155
+
156
+ function projectDependencies(): Set<string> {
157
+ const manifestPath = join(process.cwd(), "package.json");
158
+
159
+ if (!existsSync(manifestPath)) return new Set();
160
+
161
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
162
+
163
+ return new Set(Object.keys({ ...manifest.dependencies, ...manifest.devDependencies }));
164
+ }
165
+
166
+ /**
167
+ * Additional opt-ins beyond maybeBabel's built-in list.
168
+ * The `initializeRuntimeMacrosConfig` runtime call must compile away in every project.
141
169
  */
142
170
  function babelFilter(nvpConfig: Config) {
143
- return {
144
- include: {
145
- imports: [
146
- "ember-concurrency",
147
- "ember-scoped-css",
148
- "ember-intl/helpers/format-message",
149
- ...(nvpConfig.babel?.include?.whenImporting ?? []),
150
- ],
151
- code: [/\bintl\.formatMessage\b/, "initializeRuntimeMacrosConfig"] as (string | RegExp)[],
152
- },
153
- };
171
+ const imports: string[] = [];
172
+ const code: (string | RegExp)[] = ["initializeRuntimeMacrosConfig"];
173
+ const ids: RegExp[] = [];
174
+ const dependencies = projectDependencies();
175
+
176
+ for (const [name, filter] of Object.entries(LIBRARY_FILTERS)) {
177
+ if (!dependencies.has(name)) continue;
178
+
179
+ for (const specifier of filter.imports ?? []) imports.push(specifier);
180
+ for (const pattern of filter.code ?? []) code.push(pattern);
181
+ for (const pattern of filter.ids ?? []) ids.push(pattern);
182
+ }
183
+
184
+ for (const specifier of nvpConfig.babel?.include?.whenImporting ?? []) {
185
+ imports.push(specifier);
186
+ }
187
+
188
+ for (const pattern of nvpConfig.babel?.include?.whenMatching ?? []) {
189
+ code.push(pattern);
190
+ }
191
+
192
+ return { include: { imports, code, ids } };
154
193
  }
155
194
 
156
195
  interface Config {
@@ -182,9 +221,21 @@ interface Config {
182
221
  * if a file imports from anything in this array, use babel instead of
183
222
  * oxc for that file.
184
223
  *
185
- * For example: ['ember-concurrency'],
224
+ * For example: ['my-babel-only-library'],
186
225
  */
187
226
  whenImporting?: (string | "ember-concurrency" | "ember-scoped-css")[];
227
+
228
+ /**
229
+ * if a file's source contains any of these strings,
230
+ * or matches any of these regular expressions,
231
+ * use babel instead of oxc for that file.
232
+ *
233
+ * Use this for babel plugins that look for a code pattern rather than
234
+ * an import.
235
+ *
236
+ * For example: [/\.register\(/],
237
+ */
238
+ whenMatching?: (string | RegExp)[];
188
239
  };
189
240
  };
190
241
  /**