@nullvoxpopuli/ember-rolldown 2.6.0 → 2.7.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/dist/app-reexports.d.ts +75 -0
- package/dist/app-reexports.d.ts.map +1 -0
- package/dist/app-reexports.js +2 -0
- package/dist/app-reexports.js.map +1 -0
- package/dist/index.d.ts +91 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -0
- package/dist/plugin-like-CBvGkzCB.d.ts +27 -0
- package/dist/plugin-like-CBvGkzCB.d.ts.map +1 -0
- package/index.ts +2 -3
- package/package.json +12 -5
- package/src/app-reexports.ts +2 -2
- package/src/plugin-like.ts +23 -0
- package/src/published-types.test.ts +102 -0
- package/src/transform.test.ts +50 -2
- package/src/transform.ts +8 -1
- package/tsdown.config.ts +11 -0
- package/rolldown.config.js +0 -23
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { t as RolldownPluginLike } from "./plugin-like-CBvGkzCB.js";
|
|
2
|
+
//#region src/app-reexports.d.ts
|
|
3
|
+
interface AppReexportsOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Globs, matched against each built filename (relative to the output
|
|
6
|
+
* directory), selecting which modules get an app re-export.
|
|
7
|
+
*
|
|
8
|
+
* Defaults to `["services/*"]` -- top-level services only. Under strict
|
|
9
|
+
* mode, components and helpers are imported, but services are still
|
|
10
|
+
* injected by name, so they are the one thing an app must always be able
|
|
11
|
+
* to resolve.
|
|
12
|
+
*
|
|
13
|
+
* `.d.ts` files never match.
|
|
14
|
+
*/
|
|
15
|
+
include?: string[];
|
|
16
|
+
/**
|
|
17
|
+
* Globs removing files that `include` matched.
|
|
18
|
+
*/
|
|
19
|
+
exclude?: string[];
|
|
20
|
+
/**
|
|
21
|
+
* Rename a re-export: receives the built filename, returns the filename the
|
|
22
|
+
* app sees. Defaults to the built filename unchanged.
|
|
23
|
+
*/
|
|
24
|
+
mapFilename?: (filename: string) => string;
|
|
25
|
+
/**
|
|
26
|
+
* Which bindings a file's re-export module forwards: an array of names
|
|
27
|
+
* (default `["default"]`), or a raw export clause string such as `"*"`.
|
|
28
|
+
*/
|
|
29
|
+
exports?: (filename: string) => string[] | string | undefined;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Merges built modules into the consuming app's namespace, so classic
|
|
33
|
+
* resolution (`{{a-component}}`, service/helper lookup by name) finds them --
|
|
34
|
+
* the same job as `@embroider/addon-dev`'s `appReexports` rollup plugin.
|
|
35
|
+
*
|
|
36
|
+
* For every built file matching `include` (minus `exclude` and `.d.ts`), it
|
|
37
|
+
* writes a tiny module under `<outDir>/_app_/` re-exporting from the
|
|
38
|
+
* library's own name, and records the full set in `package.json` under
|
|
39
|
+
* `ember-addon.app-js`.
|
|
40
|
+
*
|
|
41
|
+
* Unlike the embroider plugin, nothing is written unless its content actually
|
|
42
|
+
* differs from what is on disk: the `_app_/` modules are compared
|
|
43
|
+
* byte-for-byte, and `package.json` is only rewritten when the `app-js` map
|
|
44
|
+
* itself changed (so an equivalent map in different formatting is left
|
|
45
|
+
* alone). This keeps rebuilds from re-triggering file watchers.
|
|
46
|
+
*
|
|
47
|
+
* This is a separate import, because most libraries don't need it:
|
|
48
|
+
*
|
|
49
|
+
* ```js
|
|
50
|
+
* import { defineConfig } from "tsdown";
|
|
51
|
+
* import { ember } from "@nullvoxpopuli/ember-rolldown";
|
|
52
|
+
* import { appReexports } from "@nullvoxpopuli/ember-rolldown/app-reexports";
|
|
53
|
+
*
|
|
54
|
+
* export default defineConfig({
|
|
55
|
+
* entry: ["./src/index.ts", "./src/services/session.ts"],
|
|
56
|
+
* plugins: [ember(), appReexports()],
|
|
57
|
+
* });
|
|
58
|
+
* ```
|
|
59
|
+
*
|
|
60
|
+
* With no arguments, top-level services (`services/*`) are re-exported. A
|
|
61
|
+
* string or array of strings is the include glob(s), optionally followed by
|
|
62
|
+
* the remaining options; an object gives full control:
|
|
63
|
+
*
|
|
64
|
+
* ```js
|
|
65
|
+
* appReexports(); // services/*
|
|
66
|
+
* appReexports("components/**"); // one include glob
|
|
67
|
+
* appReexports(["services/*", "helpers/*"]);
|
|
68
|
+
* appReexports("components/**", { exclude: ["components/-private/**"] });
|
|
69
|
+
* appReexports({ include: ["services/*", "helpers/*"], exclude: [...] });
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
declare function appReexports(includeOrOptions?: string | string[] | AppReexportsOptions, options?: Omit<AppReexportsOptions, "include">): RolldownPluginLike;
|
|
73
|
+
//#endregion
|
|
74
|
+
export { AppReexportsOptions, appReexports };
|
|
75
|
+
//# sourceMappingURL=app-reexports.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app-reexports.d.ts","names":[],"sources":["../src/app-reexports.ts"],"mappings":";;UAKiB;;;;;;;;;;;;EAYf;;;;EAKA;;;;;EAMA,eAAe;;;;;EAMf,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA4CG,aACd,uCAAsC,qBACtC,UAAS,KAAK,kCACb"}
|
package/dist/app-reexports.js
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app-reexports.js","names":[],"sources":["../src/app-reexports.ts"],"sourcesContent":["import { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, extname, join, matchesGlob, relative, resolve, sep } from \"node:path\";\n\nimport type { RolldownPluginLike } from \"./plugin-like.ts\";\n\nexport interface AppReexportsOptions {\n /**\n * Globs, matched against each built filename (relative to the output\n * directory), selecting which modules get an app re-export.\n *\n * Defaults to `[\"services/*\"]` -- top-level services only. Under strict\n * mode, components and helpers are imported, but services are still\n * injected by name, so they are the one thing an app must always be able\n * to resolve.\n *\n * `.d.ts` files never match.\n */\n include?: string[];\n\n /**\n * Globs removing files that `include` matched.\n */\n exclude?: string[];\n\n /**\n * Rename a re-export: receives the built filename, returns the filename the\n * app sees. Defaults to the built filename unchanged.\n */\n mapFilename?: (filename: string) => string;\n\n /**\n * Which bindings a file's re-export module forwards: an array of names\n * (default `[\"default\"]`), or a raw export clause string such as `\"*\"`.\n */\n exports?: (filename: string) => string[] | string | undefined;\n}\n\n/**\n * Merges built modules into the consuming app's namespace, so classic\n * resolution (`{{a-component}}`, service/helper lookup by name) finds them --\n * the same job as `@embroider/addon-dev`'s `appReexports` rollup plugin.\n *\n * For every built file matching `include` (minus `exclude` and `.d.ts`), it\n * writes a tiny module under `<outDir>/_app_/` re-exporting from the\n * library's own name, and records the full set in `package.json` under\n * `ember-addon.app-js`.\n *\n * Unlike the embroider plugin, nothing is written unless its content actually\n * differs from what is on disk: the `_app_/` modules are compared\n * byte-for-byte, and `package.json` is only rewritten when the `app-js` map\n * itself changed (so an equivalent map in different formatting is left\n * alone). This keeps rebuilds from re-triggering file watchers.\n *\n * This is a separate import, because most libraries don't need it:\n *\n * ```js\n * import { defineConfig } from \"tsdown\";\n * import { ember } from \"@nullvoxpopuli/ember-rolldown\";\n * import { appReexports } from \"@nullvoxpopuli/ember-rolldown/app-reexports\";\n *\n * export default defineConfig({\n * entry: [\"./src/index.ts\", \"./src/services/session.ts\"],\n * plugins: [ember(), appReexports()],\n * });\n * ```\n *\n * With no arguments, top-level services (`services/*`) are re-exported. A\n * string or array of strings is the include glob(s), optionally followed by\n * the remaining options; an object gives full control:\n *\n * ```js\n * appReexports(); // services/*\n * appReexports(\"components/**\"); // one include glob\n * appReexports([\"services/*\", \"helpers/*\"]);\n * appReexports(\"components/**\", { exclude: [\"components/-private/**\"] });\n * appReexports({ include: [\"services/*\", \"helpers/*\"], exclude: [...] });\n * ```\n */\nexport function appReexports(\n includeOrOptions: string | string[] | AppReexportsOptions = {},\n options: Omit<AppReexportsOptions, \"include\"> = {},\n): RolldownPluginLike {\n const resolved =\n typeof includeOrOptions === \"string\"\n ? { ...options, include: [includeOrOptions] }\n : Array.isArray(includeOrOptions)\n ? { ...options, include: includeOrOptions }\n : includeOrOptions;\n const include = resolved.include ?? [\"services/*\"];\n\n return {\n name: \"ember:app-reexports\",\n\n writeBundle(outputOptions, bundle) {\n const manifest = readJsonSync(\"package.json\");\n const outDir = outputOptions.dir ?? dirname(outputOptions.file ?? \"dist\");\n const appJs: Record<string, string> = {};\n\n // Sorted so the app-js map (and therefore package.json) is stable\n // across builds regardless of chunk emission order.\n for (const builtFilename of Object.keys(bundle).sort()) {\n if (!isIncluded(builtFilename, include, resolved.exclude)) continue;\n\n const appFilename = resolved.mapFilename?.(builtFilename) ?? builtFilename;\n const names = resolved.exports?.(builtFilename) || [\"default\"];\n const clause = typeof names === \"string\" ? names : `{ ${names.join(\", \")} }`;\n const withoutExtension = builtFilename.slice(0, -extname(builtFilename).length);\n const reexportPath = join(outDir, \"_app_\", appFilename);\n\n appJs[`./${appFilename}`] = `./${toPosix(relative(process.cwd(), resolve(reexportPath)))}`;\n\n writeFileIfChanged(\n reexportPath,\n `export ${clause} from \"${manifest.name}/${withoutExtension}\";\\n`,\n );\n }\n\n const existing = manifest[\"ember-addon\"]?.[\"app-js\"] ?? {};\n\n if (!sameStringRecord(existing, appJs)) {\n manifest[\"ember-addon\"] = { ...manifest[\"ember-addon\"], \"app-js\": appJs };\n writeFileSync(\"package.json\", JSON.stringify(manifest, null, 2) + \"\\n\");\n }\n },\n };\n}\n\nfunction readJsonSync(path: string) {\n return JSON.parse(readFileSync(path, { encoding: \"utf8\" }));\n}\n\nfunction isIncluded(filename: string, include: string[], exclude?: string[]): boolean {\n if (matchesGlob(filename, \"**/*.d.ts\")) return false;\n if (!include.some((glob) => matchesGlob(filename, glob))) return false;\n if (exclude?.some((glob) => matchesGlob(filename, glob))) return false;\n\n return true;\n}\n\nfunction writeFileIfChanged(path: string, content: string) {\n let existing: string | undefined;\n\n try {\n existing = readFileSync(path, { encoding: \"utf8\" });\n } catch {\n // Doesn't exist yet (or isn't readable) -- write it.\n }\n\n if (existing === content) return;\n\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, content);\n}\n\nfunction sameStringRecord(a: Record<string, string>, b: Record<string, string>): boolean {\n const aKeys = Object.keys(a);\n\n return aKeys.length === Object.keys(b).length && aKeys.every((key) => a[key] === b[key]);\n}\n\nfunction toPosix(path: string): string {\n return path.split(sep).join(\"/\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA,SAAgB,aACd,mBAA4D,CAAC,GAC7D,UAAgD,CAAC,GAC7B;CACpB,MAAM,WACJ,OAAO,qBAAqB,WACxB;EAAE,GAAG;EAAS,SAAS,CAAC,gBAAgB;CAAE,IAC1C,MAAM,QAAQ,gBAAgB,IAC5B;EAAE,GAAG;EAAS,SAAS;CAAiB,IACxC;CACR,MAAM,UAAU,SAAS,WAAW,CAAC,YAAY;CAEjD,OAAO;EACL,MAAM;EAEN,YAAY,eAAe,QAAQ;GACjC,MAAM,WAAW,aAAa,cAAc;GAC5C,MAAM,SAAS,cAAc,OAAO,QAAQ,cAAc,QAAQ,MAAM;GACxE,MAAM,QAAgC,CAAC;GAIvC,KAAK,MAAM,iBAAiB,OAAO,KAAK,MAAM,CAAC,CAAC,KAAK,GAAG;IACtD,IAAI,CAAC,WAAW,eAAe,SAAS,SAAS,OAAO,GAAG;IAE3D,MAAM,cAAc,SAAS,cAAc,aAAa,KAAK;IAC7D,MAAM,QAAQ,SAAS,UAAU,aAAa,KAAK,CAAC,SAAS;IAC7D,MAAM,SAAS,OAAO,UAAU,WAAW,QAAQ,KAAK,MAAM,KAAK,IAAI,EAAE;IACzE,MAAM,mBAAmB,cAAc,MAAM,GAAG,CAAC,QAAQ,aAAa,CAAC,CAAC,MAAM;IAC9E,MAAM,eAAe,KAAK,QAAQ,SAAS,WAAW;IAEtD,MAAM,KAAK,iBAAiB,KAAK,QAAQ,SAAS,QAAQ,IAAI,GAAG,QAAQ,YAAY,CAAC,CAAC;IAEvF,mBACE,cACA,UAAU,OAAO,SAAS,SAAS,KAAK,GAAG,iBAAiB,KAC9D;GACF;GAIA,IAAI,CAAC,iBAFY,SAAS,cAAc,GAAG,aAAa,CAAC,GAEzB,KAAK,GAAG;IACtC,SAAS,iBAAiB;KAAE,GAAG,SAAS;KAAgB,UAAU;IAAM;IACxE,cAAc,gBAAgB,KAAK,UAAU,UAAU,MAAM,CAAC,IAAI,IAAI;GACxE;EACF;CACF;AACF;AAEA,SAAS,aAAa,MAAc;CAClC,OAAO,KAAK,MAAM,aAAa,MAAM,EAAE,UAAU,OAAO,CAAC,CAAC;AAC5D;AAEA,SAAS,WAAW,UAAkB,SAAmB,SAA6B;CACpF,IAAI,YAAY,UAAU,WAAW,GAAG,OAAO;CAC/C,IAAI,CAAC,QAAQ,MAAM,SAAS,YAAY,UAAU,IAAI,CAAC,GAAG,OAAO;CACjE,IAAI,SAAS,MAAM,SAAS,YAAY,UAAU,IAAI,CAAC,GAAG,OAAO;CAEjE,OAAO;AACT;AAEA,SAAS,mBAAmB,MAAc,SAAiB;CACzD,IAAI;CAEJ,IAAI;EACF,WAAW,aAAa,MAAM,EAAE,UAAU,OAAO,CAAC;CACpD,QAAQ,CAER;CAEA,IAAI,aAAa,SAAS;CAE1B,UAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC5C,cAAc,MAAM,OAAO;AAC7B;AAEA,SAAS,iBAAiB,GAA2B,GAAoC;CACvF,MAAM,QAAQ,OAAO,KAAK,CAAC;CAE3B,OAAO,MAAM,WAAW,OAAO,KAAK,CAAC,CAAC,CAAC,UAAU,MAAM,OAAO,QAAQ,EAAE,SAAS,EAAE,IAAI;AACzF;AAEA,SAAS,QAAQ,MAAsB;CACrC,OAAO,KAAK,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;AACjC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { t as RolldownPluginLike } from "./plugin-like-CBvGkzCB.js";
|
|
2
|
+
import { Transform } from "babel-plugin-ember-template-compilation";
|
|
3
|
+
import { PluginItem } from "@babel/core";
|
|
4
|
+
//#region src/babel.d.ts
|
|
5
|
+
interface BabelOptions {
|
|
6
|
+
babelHelpers?: "bundled" | "runtime" | "inline" | "external";
|
|
7
|
+
/**
|
|
8
|
+
* The babel config file to use.
|
|
9
|
+
*
|
|
10
|
+
* - `undefined`: auto-detect. A `babel.publish.config.*` (in the package root
|
|
11
|
+
* or `config/`) wins, because this is a publish build; otherwise babel's own
|
|
12
|
+
* config resolution applies (see `detectConfigFile`).
|
|
13
|
+
* - a string: use that config file.
|
|
14
|
+
* - `false`: ignore config files entirely.
|
|
15
|
+
*
|
|
16
|
+
* Without a config file, templates, decorators, and TypeScript are still
|
|
17
|
+
* handled (see `defaultPlugins`).
|
|
18
|
+
*/
|
|
19
|
+
configFile?: string | false;
|
|
20
|
+
/**
|
|
21
|
+
* Extra babel plugins to run, appended after the config's plugins.
|
|
22
|
+
*/
|
|
23
|
+
plugins?: PluginItem[];
|
|
24
|
+
/**
|
|
25
|
+
* Template AST transforms (e.g. ember-scoped-css's `scopedCSS.template()`)
|
|
26
|
+
* passed to the default `babel-plugin-ember-template-compilation` entry.
|
|
27
|
+
*
|
|
28
|
+
* Only valid without a babel config file: with your own config, you list
|
|
29
|
+
* `babel-plugin-ember-template-compilation` yourself, so its `transforms`
|
|
30
|
+
* belong there.
|
|
31
|
+
*/
|
|
32
|
+
templateTransforms?: Transform[];
|
|
33
|
+
/**
|
|
34
|
+
* Opt additional files into babel (see maybeBabel's `filter`). Use this to
|
|
35
|
+
* cover addons that ship code needing babel (e.g. `ember-concurrency`).
|
|
36
|
+
*/
|
|
37
|
+
filter?: {
|
|
38
|
+
include: {
|
|
39
|
+
imports: string[];
|
|
40
|
+
code: (string | RegExp)[];
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
//#endregion
|
|
45
|
+
//#region index.d.ts
|
|
46
|
+
interface Config {
|
|
47
|
+
/**
|
|
48
|
+
* Options for the babel step; see `BabelOptions`.
|
|
49
|
+
*/
|
|
50
|
+
babel?: BabelOptions;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* A batteries-included plugin for building Ember v2 libraries (addons) with
|
|
54
|
+
* rolldown (or tsdown, which is built on rolldown).
|
|
55
|
+
*
|
|
56
|
+
* It bundles everything needed to compile `.gts`/`.gjs` and template-tag
|
|
57
|
+
* (`<template>`) source into publishable output:
|
|
58
|
+
*
|
|
59
|
+
* - `emberConfig()` — applies sensible tsdown defaults for a library build
|
|
60
|
+
* (sourcemaps, `clean`, `dts`, `.js`/`.d.ts` extensions, quiet logging);
|
|
61
|
+
* anything you set explicitly still wins.
|
|
62
|
+
* - `emberIsolatedDeclarations()` — errors when a tsconfig.json is present
|
|
63
|
+
* without `isolatedDeclarations: true` (required: it is the only
|
|
64
|
+
* declaration pipeline that can see compiled template-tag modules).
|
|
65
|
+
* - `emberExternals()` — keeps your dependencies, peerDependencies, and the
|
|
66
|
+
* ember virtual packages external, so consuming apps resolve them.
|
|
67
|
+
* - `emberTransform()` — preprocesses `<template>` via content-tag and maps
|
|
68
|
+
* `.gts`/`.gjs` to `.ts`/`.js` so rolldown can understand them.
|
|
69
|
+
* - `emberBabel()` — runs babel (template compilation, decorators, type
|
|
70
|
+
* stripping) with `babelHelpers: "bundled"`, but only on the files that
|
|
71
|
+
* actually need it (via `maybeBabel`); everything else stays on the fast
|
|
72
|
+
* native transform. The library's own `babel.config.js` is used when it
|
|
73
|
+
* exists; no config file is required.
|
|
74
|
+
*
|
|
75
|
+
* Usage in `tsdown.config.js` (import `defineConfig` from `tsdown` — or from
|
|
76
|
+
* `rolldown` for a `rolldown.config.js` — so it carries the correct types):
|
|
77
|
+
*
|
|
78
|
+
* ```js
|
|
79
|
+
* import { defineConfig } from "tsdown";
|
|
80
|
+
* import { ember } from "@nullvoxpopuli/ember-rolldown";
|
|
81
|
+
*
|
|
82
|
+
* export default defineConfig({
|
|
83
|
+
* entry: ["./src/index.ts"],
|
|
84
|
+
* plugins: [ember()],
|
|
85
|
+
* });
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
88
|
+
declare function ember(config?: Config): RolldownPluginLike[];
|
|
89
|
+
//#endregion
|
|
90
|
+
export { ember };
|
|
91
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/babel.ts","../index.ts"],"mappings":";;;;UAWiB;EACf;;;;;;;;;;;;;EAaA;;;;EAIA,UAAU;;;;;;;;;EASV,qBAAqB;;;;;EAKrB;IACE;MACE;MACA,gBAAgB;;;;;;UCvCZ;;;;EAIR,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAuCM,MAAM,SAAQ,SAAc"}
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
1
2
|
import { maybeBabel } from "@nullvoxpopuli/ember-build-tooling-utils";
|
|
2
3
|
import transformTypeScript from "@babel/plugin-transform-typescript";
|
|
3
4
|
import templateCompilation from "babel-plugin-ember-template-compilation";
|
|
@@ -5,7 +6,6 @@ import decoratorTransforms from "decorator-transforms";
|
|
|
5
6
|
import { loadPartialConfigSync } from "@babel/core";
|
|
6
7
|
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
7
8
|
import path, { dirname, resolve } from "node:path";
|
|
8
|
-
import { createRequire } from "node:module";
|
|
9
9
|
import pkg from "@embroider/core";
|
|
10
10
|
import { Preprocessor } from "content-tag";
|
|
11
11
|
import { readFile, readdir, writeFile } from "node:fs/promises";
|
|
@@ -396,7 +396,7 @@ function emberTransform() {
|
|
|
396
396
|
meta: { fileName }
|
|
397
397
|
};
|
|
398
398
|
}
|
|
399
|
-
const fileName = path.join(path.dirname(importer), id);
|
|
399
|
+
const fileName = path.isAbsolute(id) ? id : path.join(path.dirname(importer), id);
|
|
400
400
|
if (id.endsWith(".gts")) return {
|
|
401
401
|
id: fileName.replace(/\.gts$/, ".ts"),
|
|
402
402
|
meta: { fileName }
|
|
@@ -516,3 +516,5 @@ function ember(config = {}) {
|
|
|
516
516
|
}
|
|
517
517
|
//#endregion
|
|
518
518
|
export { ember };
|
|
519
|
+
|
|
520
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/babel.ts","../src/config.ts","../src/externals.ts","../src/isolated-declarations.ts","../src/transform.ts","../index.ts"],"sourcesContent":["import { maybeBabel } from \"@nullvoxpopuli/ember-build-tooling-utils\";\nimport transformTypeScript from \"@babel/plugin-transform-typescript\";\nimport templateCompilation from \"babel-plugin-ember-template-compilation\";\nimport decoratorTransforms from \"decorator-transforms\";\nimport { loadPartialConfigSync } from \"@babel/core\";\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { PluginItem } from \"@babel/core\";\nimport type { Transform } from \"babel-plugin-ember-template-compilation\";\nimport type { Plugin } from \"rolldown\";\n\nexport interface BabelOptions {\n babelHelpers?: \"bundled\" | \"runtime\" | \"inline\" | \"external\";\n /**\n * The babel config file to use.\n *\n * - `undefined`: auto-detect. A `babel.publish.config.*` (in the package root\n * or `config/`) wins, because this is a publish build; otherwise babel's own\n * config resolution applies (see `detectConfigFile`).\n * - a string: use that config file.\n * - `false`: ignore config files entirely.\n *\n * Without a config file, templates, decorators, and TypeScript are still\n * handled (see `defaultPlugins`).\n */\n configFile?: string | false;\n /**\n * Extra babel plugins to run, appended after the config's plugins.\n */\n plugins?: PluginItem[];\n /**\n * Template AST transforms (e.g. ember-scoped-css's `scopedCSS.template()`)\n * passed to the default `babel-plugin-ember-template-compilation` entry.\n *\n * Only valid without a babel config file: with your own config, you list\n * `babel-plugin-ember-template-compilation` yourself, so its `transforms`\n * belong there.\n */\n templateTransforms?: Transform[];\n /**\n * Opt additional files into babel (see maybeBabel's `filter`). Use this to\n * cover addons that ship code needing babel (e.g. `ember-concurrency`).\n */\n filter?: {\n include: {\n imports: string[];\n code: (string | RegExp)[];\n };\n };\n}\n\n/** Tried in order, so an ESM config wins over a JSON one of the same name. */\nconst PUBLISH_CONFIG_EXTENSIONS = [\"mjs\", \"cjs\", \"js\", \"mts\", \"cts\", \"ts\", \"json\"];\n\n/**\n * Tried in order: next to package.json first, then `config/` for libraries that\n * keep their build configuration out of the package root.\n */\nconst PUBLISH_CONFIG_DIRECTORIES = [\".\", \"config\"];\n\n/**\n * A `babel.publish.config.*` (in the package root or `config/`), if there is\n * one.\n *\n * A library's plain `babel.config.*` is its *development* config: it typically\n * compiles `@embroider/macros` away, targets the wire format, and wires up\n * whatever the in-package demo app or test suite needs. None of that belongs in\n * a published artifact -- macros must stay for the consuming app to evaluate,\n * and the wire format is private between one template compiler and one glimmer\n * runtime. Babel's own resolution can't tell the two apart (it finds whatever\n * `babel.config.*` exists), so a publish build has to prefer the config named\n * for publishing.\n */\nfunction detectPublishConfigFile(): string | undefined {\n for (const directory of PUBLISH_CONFIG_DIRECTORIES) {\n for (const extension of PUBLISH_CONFIG_EXTENSIONS) {\n const candidate = resolve(directory, `babel.publish.config.${extension}`);\n\n if (existsSync(candidate)) return candidate;\n }\n }\n\n return undefined;\n}\n\n/**\n * The config this publish build should use: a `babel.publish.config.*` when the\n * library has one, else the project's root babel config resolved the way babel\n * itself does (`babel.config.{js,cjs,mjs,cts,json}`, honoring `rootMode`\n * semantics) -- which for a library whose only config *is* its publish config\n * is the same file either way.\n *\n * The sync API evaluates the config file; on node 24+ that works for native\n * ESM configs too (require(esm)).\n */\nfunction detectConfigFile(): string | undefined {\n const publishConfig = detectPublishConfigFile();\n\n if (publishConfig) return publishConfig;\n\n const partial = loadPartialConfigSync({ cwd: process.cwd() });\n\n return partial?.config ?? undefined;\n}\n\n/**\n * Everything a library without its own babel config needs:\n *\n * - TypeScript stripping\n * - template compilation to `precompileTemplate` (`targetFormat: \"hbs\"`).\n * Published libraries must NOT ship wire format: the wire format is\n * private between the template compiler and the glimmer runtime of the\n * same version, so baking it in ties the published artifact to the\n * consuming app's exact ember-source. The consuming app performs final\n * compilation.\n * - decorator-transforms, with its runtime left as a bare specifier so the\n * consuming app resolves it (the library keeps `decorator-transforms` as\n * a real dependency).\n */\nfunction defaultPlugins(templateTransforms?: Transform[]): PluginItem[] {\n return [\n [\n transformTypeScript,\n {\n allExtensions: true,\n onlyRemoveTypeImports: true,\n allowDeclareFields: true,\n },\n ],\n [templateCompilation, { targetFormat: \"hbs\", transforms: templateTransforms ?? [] }],\n [\n decoratorTransforms,\n {\n // Emit `import ... from \"decorator-transforms/runtime-esm\"` as a bare\n // specifier so it stays external and the consuming app resolves it.\n runtime: { import: \"decorator-transforms/runtime-esm\" },\n },\n ],\n ];\n}\n\n/**\n * We still need babel (not just oxc/rolldown's native transforms) for two\n * reasons:\n *\n * - template compilation: `babel-plugin-ember-template-compilation` turns the\n * content-tag output into `precompileTemplate` calls; oxc has no equivalent.\n * - decorators: Ember uses the legacy/stage-1 decorator signature together\n * with `decorator-transforms`, which rewrites decorated class fields\n * (`@tracked x`) into getter/setters backed by a runtime. oxc's native\n * \"legacy decorators\" emit tsc-style `__decorate` output, which does not\n * match those semantics.\n *\n * But we don't want to send *every* file through babel and give back the speed\n * rolldown/oxc buys us -- so we run babel via `maybeBabel`, which filters down\n * to only the files that actually need it (template-tag, decorators, template\n * imports). Everything else stays on the native transform.\n *\n * The library's own babel config is used when it exists -- its\n * `babel.publish.config.*` (root or `config/`) in preference to its\n * `babel.config.*`, since this is a publish build. Without one, `defaultPlugins` covers templates, decorators,\n * and TypeScript, so no config file is required.\n *\n * Libraries default to `babelHelpers: \"bundled\"` so the emitted output is\n * self-contained.\n */\nexport function emberBabel(options: BabelOptions = {}): Plugin {\n const configFile = options.configFile === undefined ? detectConfigFile() : options.configFile;\n\n const shared = {\n babelHelpers: options.babelHelpers ?? \"bundled\",\n filter: options.filter,\n };\n\n if (configFile) {\n if (options.templateTransforms?.length) {\n throw new Error(\n `\\`babel.templateTransforms\\` cannot be combined with a babel config file (found ${configFile}). ` +\n `Your config lists babel-plugin-ember-template-compilation itself, so pass the transforms ` +\n `to its \\`transforms\\` option there instead.`,\n );\n }\n\n return maybeBabel({\n ...shared,\n configFile,\n plugins: options.plugins ?? [],\n }) as unknown as Plugin;\n }\n\n return maybeBabel({\n ...shared,\n // No config file (or the caller opted out): don't let babel go looking\n // for one -- we provide the whole plugin list inline.\n configFile: false,\n babelrc: false,\n plugins: defaultPlugins(options.templateTransforms).concat(options.plugins ?? []),\n }) as unknown as Plugin;\n}\n","import type { TsdownPlugin, UserConfig } from \"tsdown\";\n\n/**\n * Sensible defaults for an Ember v2 library, applied through plugin hooks so\n * they travel with `ember()` — you get them whether you use this package's\n * `defineConfig`, tsdown's, or a plain `tsdown.config.js` / `rolldown.config.js`.\n *\n * Every value is applied with `??=`, so anything you set explicitly wins.\n *\n * Under tsdown, the full set applies via the `tsdownConfig` hook (analogous to\n * Vite's `config` hook):\n *\n * - `sourcemap` — emit sourcemaps alongside the output.\n * - `clean` — wipe `dist/` between builds.\n * - `dts` — emit `.d.ts` declarations (via isolated declarations).\n * - `outExtensions` — `.js`/`.d.ts` rather than tsdown's default `.mjs`/`.d.mts`,\n * since exports maps conventionally point at `.js`/`.d.ts`.\n * - `report` — off; the size report is noise for a library build.\n * - `deps.neverBundle` — leave node builtins and the ember virtual packages to\n * the consuming app (`emberExternals()` handles the rest).\n *\n * A plain rolldown build has no notion of `clean`/`dts`/`outExtensions`/`report`\n * (those are tsdown-level concepts), so only the options with rolldown\n * equivalents are applied there, via rolldown's own `outputOptions` hook:\n *\n * - `output.sourcemap` — on (output option).\n *\n * Externals are handled by `emberExternals()` (a `resolveId` hook) in both cases.\n */\nexport function emberConfig(): TsdownPlugin {\n return {\n name: \"ember:config\",\n\n tsdownConfig(config: UserConfig) {\n config.sourcemap ??= true;\n config.clean ??= true;\n config.dts ??= { sourcemap: true };\n config.outExtensions ??= () => ({ js: \".js\", dts: \".d.ts\" });\n config.report ??= false;\n\n config.deps ??= {};\n config.deps.neverBundle ??= [\"node:*\", \"@ember/*\", \"@glimmer/*\"];\n },\n\n outputOptions(options) {\n options.sourcemap ??= true;\n return options;\n },\n };\n}\n","import { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\n\nimport type { Plugin } from \"rolldown\";\n\n// @embroider/core is cjs, so we default-import and destructure.\nimport pkg from \"@embroider/core\";\nconst { emberVirtualPackages, emberVirtualPeerDeps, packageName, templateCompilationModules } = pkg;\n\nconst compilationModules = new Set(templateCompilationModules.map((m) => m.module));\n\n/**\n * @param {string} path\n */\nfunction readJsonSync(path: string) {\n return JSON.parse(readFileSync(path, { encoding: \"utf8\" }));\n}\n\n/**\n * Everything the library declares as a `dependency` or `peerDependency` is\n * resolvable by the consuming app, so we never bundle it.\n */\nfunction resolvableDependencies(): Set<string> {\n const deps = new Set<string>();\n const manifest = readJsonSync(\"package.json\");\n\n for (const name of Object.keys(manifest.dependencies ?? {})) {\n deps.add(name);\n }\n for (const name of Object.keys(manifest.peerDependencies ?? {})) {\n deps.add(name);\n }\n\n return deps;\n}\n\n/**\n * The module names ember-source provides by renaming them into itself — the\n * keys of its `ember-addon.renamed-modules`, normalized from file paths to\n * import specifiers (`@glimmer/runtime/index.js` → `@glimmer/runtime`).\n *\n * This is the authoritative list of ember's provided modules, including\n * private API that @embroider/core's emberVirtualPackages doesn't cover\n * (e.g. `@glimmer/runtime`). It deliberately does NOT include real packages\n * like `@glimmer/component`, which a library may want bundled.\n *\n * Resolved from the library's own dependency graph; empty when ember-source\n * isn't resolvable there.\n */\nfunction emberSourceRenamedModules(): Set<string> {\n const provided = new Set<string>();\n\n try {\n const require = createRequire(path.resolve(\"package.json\"));\n const manifest = require(\"ember-source/package.json\") as {\n \"ember-addon\"?: { \"renamed-modules\"?: Record<string, string> };\n };\n\n for (const key of Object.keys(manifest[\"ember-addon\"]?.[\"renamed-modules\"] ?? {})) {\n provided.add(key.replace(/\\.js$/, \"\").replace(/\\/index$/, \"\"));\n }\n } catch {\n // The library doesn't have ember-source in its graph; nothing to provide.\n }\n\n return provided;\n}\n\n/**\n * Keeps the library's declared dependencies and the ember virtual packages\n * (things like `@ember/component`, `@glimmer/tracking`, the template compiler,\n * …) external, so the app that consumes the library resolves them instead of\n * the library bundling copies of them.\n */\nexport function emberExternals(): Plugin {\n let deps: Set<string>;\n let renamedModules: Set<string>;\n\n return {\n name: \"ember:externals\",\n\n buildStart() {\n this.addWatchFile(\"package.json\");\n deps = resolvableDependencies();\n renamedModules = emberSourceRenamedModules();\n },\n\n resolveId: {\n order: \"pre\",\n handler(source) {\n // Anything with a protocol (`node:`, virtual modules, …) is not ours\n // to externalize.\n if (source.includes(\":\")) {\n return null;\n }\n\n const pkgName = packageName(source);\n\n if (!pkgName) {\n // No package name means a relative import, which we don't deal with.\n return null;\n }\n\n if (\n deps.has(pkgName) ||\n emberVirtualPeerDeps.has(pkgName) ||\n emberVirtualPackages.has(pkgName) ||\n compilationModules.has(pkgName)\n ) {\n // `false` tells rolldown to treat the id as external.\n return false;\n }\n\n // Modules ember-source provides by renaming them into itself\n // (`ember-addon.renamed-modules`) — private API like\n // `@glimmer/runtime` that only exists inside the app's ember-source.\n // Matched on the full specifier: the renamed modules are module\n // paths, not packages.\n if (renamedModules.has(source)) {\n return false;\n }\n\n return undefined;\n },\n },\n };\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\n\nimport type { Plugin } from \"rolldown\";\nimport type { UserConfig } from \"tsdown\";\n\n/**\n * Resolve the tsconfig the build will actually use, mirroring tsdown's own\n * `tsconfig` option (`string | boolean`):\n *\n * - `undefined` / `true`: `tsconfig.json` in the cwd.\n * - a path to a file: that file.\n * - a path to a directory: `tsconfig.json` inside it.\n * - `false`: no tsconfig at all.\n *\n * Under plain rolldown there is no such option, so the cwd's `tsconfig.json`\n * is all there is.\n */\nfunction resolveTsconfigPath(option: string | boolean | undefined): string | undefined {\n if (option === false) return undefined;\n\n if (typeof option === \"string\") {\n const asPath = resolve(option);\n\n if (existsSync(asPath) && statSync(asPath).isDirectory()) {\n return resolve(asPath, \"tsconfig.json\");\n }\n\n return asPath;\n }\n\n return resolve(\"tsconfig.json\");\n}\n\n/**\n * Errors the build when the tsconfig it builds with does not set\n * `isolatedDeclarations: true`.\n *\n * This is required: declarations for `.gts`/`.gjs` (template tag) modules can\n * only be emitted by the isolated-declarations pipeline, which reads compiled\n * modules from the bundler's module graph. The `tsc`-based pipeline reads\n * source files from disk, where the compiled modules don't exist, and fails\n * with \"Source file not found\".\n *\n * Failing fast here -- rather than only when declaration emit happens to run\n * -- keeps the project honest: editors and `tsc`/`ember-tsc` then check the\n * same rules the build enforces (exported values need explicit type\n * annotations, e.g. `export const X: TOC<Sig> = <template>...`).\n *\n * The tsconfig checked is the one tsdown's `tsconfig` option points at, not\n * necessarily `tsconfig.json`. A library whose package also holds dev-only code\n * (a demo app, in-package tests) can therefore keep a permissive\n * `tsconfig.json` covering everything for editors and `tsc --noEmit`, and point\n * the build at a `tsconfig.publish.json` that covers only the publishable\n * sources -- isolated declarations then constrain exactly the code that gets\n * declarations emitted for it, and nothing else.\n *\n * Projects with no tsconfig (JavaScript libraries) or without the `typescript`\n * package have no declarations to emit, so there is nothing to check.\n * `tsconfig: false` is different: it is an explicit opt-out, and combined with\n * declaration emit it produces a confusing \"Source file not found\" from the\n * tsc-based pipeline, so it errors here instead.\n */\nexport function emberIsolatedDeclarations(): Plugin {\n let tsconfigOption: string | boolean | undefined;\n let emitsDeclarations = true;\n\n return {\n name: \"ember:isolated-declarations\",\n\n // Not called under plain rolldown, which leaves `tsconfigOption` undefined\n // -- i.e. the cwd's tsconfig.json, the only thing it could mean there.\n tsdownConfig(config: UserConfig) {\n tsconfigOption = config.tsconfig;\n // `emberConfig()` turns dts on unless the library turned it off, so an\n // explicit `false` is the only \"no declarations\" signal. Hook order\n // between plugins isn't guaranteed, so don't rely on it having run.\n emitsDeclarations = config.dts !== false;\n },\n\n async buildStart() {\n if (tsconfigOption === false) {\n if (!emitsDeclarations) return;\n\n // Without a tsconfig there is no `isolatedDeclarations`, so tsdown\n // falls back to the tsc-based declaration pipeline -- which reads\n // source files from disk and dies with \"Source file not found\" on\n // every `.gts`/`.gjs`, since those only exist compiled in the module\n // graph. Say so here instead of leaving that to be decoded.\n this.error(\n `\\`tsconfig: false\\` cannot be combined with declaration emit.\\n\\n` +\n `Declarations are emitted by the isolated-declarations pipeline, which needs a ` +\n `tsconfig setting \"compilerOptions.isolatedDeclarations\": true -- it is the only ` +\n `pipeline that can see compiled .gts/.gjs modules.\\n\\n` +\n `Either point tsdown's \\`tsconfig\\` option at such a config, or set \\`dts: false\\` ` +\n `if this library ships no types.`,\n );\n }\n\n const tsconfigPath = resolveTsconfigPath(tsconfigOption);\n\n if (!tsconfigPath || !existsSync(tsconfigPath)) return;\n\n let ts: typeof import(\"typescript\");\n\n try {\n ts = (await import(\"typescript\")).default;\n } catch {\n return;\n }\n\n const { config, error } = ts.readConfigFile(tsconfigPath, ts.sys.readFile);\n\n if (error) {\n // Unreadable/unparsable tsconfig: tsc itself will report this with a\n // better message than we can.\n return;\n }\n\n // Resolves `extends` chains, so the flag may come from a base config.\n const parsed = ts.parseJsonConfigFileContent(config, ts.sys, dirname(tsconfigPath));\n\n if (parsed.options.isolatedDeclarations !== true) {\n this.error(\n `${tsconfigPath} must set \"compilerOptions.isolatedDeclarations\": true.\\n\\n` +\n `Declarations for .gts/.gjs (template tag) modules can only be emitted by the ` +\n `isolated-declarations pipeline, which reads compiled modules from the bundler's ` +\n `module graph -- the tsc-based pipeline reads from disk and cannot see them.\\n\\n` +\n `Isolated declarations require exported values to have explicit type annotations, ` +\n `e.g. \\`export const X: TOC<Sig> = <template>...\\`.\\n\\n` +\n `If this tsconfig also covers dev-only code (a demo app, in-package tests) that ` +\n `should not be constrained this way, point tsdown's \\`tsconfig\\` option at a ` +\n `publish-only tsconfig that sets the flag and covers just the published sources.`,\n );\n }\n },\n };\n}\n","import { Preprocessor } from \"content-tag\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { readFile, writeFile, readdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { Plugin } from \"rolldown\";\n\nconst processor = new Preprocessor();\n\n/**\n * `.d.ts` files emitted for `.gts` source reference the original `.gts`\n * specifiers. Consumers can't resolve those, so we rewrite them back to\n * extension-less specifiers.\n */\nfunction fixDeclarationImports(content: string): string {\n return content\n .replace(/from\\s+'([^']+)\\.gts'/g, \"from '$1'\")\n .replace(/from\\s+\"([^\"]+)\\.gts\"/g, 'from \"$1\"')\n .replace(/import\\(\"([^\"]+)\\.gts\"\\)/g, 'import(\"$1\")')\n .replace(/import\\('([^']+)\\.gts'\\)/g, \"import('$1')\");\n}\n\nasync function fixDtsExtensionsInDir(dir: string): Promise<void> {\n const entries = await readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n await fixDtsExtensionsInDir(fullPath);\n } else if (entry.name.endsWith(\".d.ts\")) {\n const content = await readFile(fullPath, { encoding: \"utf8\" });\n const fixed = fixDeclarationImports(content);\n\n if (fixed !== content) {\n await writeFile(fullPath, fixed);\n }\n }\n }\n}\n\n/**\n * A sourcemap mapping every generated line to the same line of the input.\n *\n * `AAAA` is the [0, 0, 0, 0] VLQ segment (first line maps to source 0, line 0,\n * column 0); `AACA` is [0, 0, +1, 0] (each following line advances the source\n * line by one). Exact at line granularity, which is all the specifier rewrite\n * can disturb.\n */\nfunction lineIdentityMap(id: string, source: string) {\n return {\n version: 3,\n sources: [id],\n sourcesContent: [source],\n names: [],\n mappings: source\n .split(\"\\n\")\n .map((_, line) => (line === 0 ? \"AAAA\" : \"AACA\"))\n .join(\";\"),\n };\n}\n\n/**\n * Maps `.gts` -> `.ts` and `.gjs` -> `.js` (so rolldown can identify them as\n * ts/js) and preprocesses `<template>` via content-tag.\n */\nexport function emberTransform(): Plugin {\n return {\n name: \"ember:transform\",\n\n resolveId: {\n order: \"pre\",\n handler(id, importer) {\n // Entries have no importer: their ids come straight from the build\n // config (tsdown expands entry globs to on-disk paths). Resolve a\n // `.gts`/`.gjs` entry to the same virtual `.ts`/`.js` id an imported\n // module gets, so the load hook compiles it via content-tag instead\n // of the raw `<template>` source hitting the parser. Entries may be\n // any extension — the emitted `.js`/`.d.ts` paths mirror the entry\n // paths either way (that's how tsdown's dts support works).\n if (!importer) {\n if (!id.endsWith(\".gts\") && !id.endsWith(\".gjs\")) return null;\n if (!existsSync(id)) return null;\n\n // rolldown's default resolver realpaths entry ids (e.g. macOS\n // /var -> /private/var). Match it, or this same file imported from\n // another entry resolves to a second module id and gets duplicated\n // into both chunks.\n const fileName = realpathSync(path.resolve(id));\n\n return {\n id: fileName.replace(/\\.gts$/, \".ts\").replace(/\\.gjs$/, \".js\"),\n meta: { fileName },\n };\n }\n\n // An absolute specifier already names the file, so it needs no\n // importer-relative resolution — and joining it onto the importer's\n // directory would corrupt it. That is not hypothetical: a plugin's\n // virtual module (id prefixed with `\\0`) can generate imports of\n // on-disk files by absolute path, and `path.dirname(\"\\0./registry\")`\n // is `\"\\0.\"`, so joining yields `\"\\0./Users/.../thing.gts\"` — a path\n // no `existsSync`/`readFile` can accept (it has a null byte in it).\n const fileName = path.isAbsolute(id) ? id : path.join(path.dirname(importer), id);\n\n if (id.endsWith(\".gts\")) {\n return {\n id: fileName.replace(/\\.gts$/, \".ts\"),\n meta: { fileName },\n };\n }\n\n if (id.endsWith(\".gjs\")) {\n return {\n id: fileName.replace(/\\.gjs$/, \".js\"),\n meta: { fileName },\n };\n }\n\n // A `.ts`/`.js` specifier whose only backing file is a `.gts`/`.gjs`\n // resolves to the virtual module. This must also serve `.d.ts`\n // importers: rolldown-plugin-dts resolves a declaration module's\n // imports through the plugin pipeline (`this.resolve`), and — when the\n // resolution is a source file — loads it (registering its declaration)\n // before mapping the import to the declaration id. Virtual modules\n // exist nowhere else, so if we don't answer here the import either\n // fails to resolve (no file on disk) or, worse, resolves to a\n // declaration id that was never registered.\n if (id.endsWith(\".ts\")) {\n const gtsFileName = fileName.replace(/\\.ts$/, \".gts\");\n if (existsSync(gtsFileName) && !existsSync(fileName)) {\n return { id: fileName, meta: { fileName: gtsFileName } };\n }\n }\n\n if (id.endsWith(\".js\")) {\n const gjsFileName = fileName.replace(/\\.js$/, \".gjs\");\n if (existsSync(gjsFileName) && !existsSync(fileName)) {\n return { id: fileName, meta: { fileName: gjsFileName } };\n }\n }\n\n return null;\n },\n },\n\n load: {\n order: \"pre\",\n filter: {\n id: /\\.(ts|js)$/,\n },\n async handler(id) {\n const meta = this.getModuleInfo(id)?.meta ?? {};\n let fileName = meta?.fileName;\n\n // A virtual id can be loaded without having passed through our\n // resolveId (rolldown-plugin-dts calls `this.load({ id })` with just\n // the id), so no meta is attached: recover the backing file from disk.\n if (!fileName && !existsSync(id)) {\n if (id.endsWith(\".ts\") && existsSync(id.replace(/\\.ts$/, \".gts\"))) {\n fileName = id.replace(/\\.ts$/, \".gts\");\n } else if (id.endsWith(\".js\") && existsSync(id.replace(/\\.js$/, \".gjs\"))) {\n fileName = id.replace(/\\.js$/, \".gjs\");\n }\n }\n\n if (fileName) {\n this.addWatchFile(fileName);\n const source = await readFile(fileName, { encoding: \"utf8\" });\n\n if (source.includes(\"<template>\")) {\n const { code, map } = processor.process(source, {\n filename: fileName,\n });\n return { code, map };\n }\n\n return source;\n }\n\n return null;\n },\n },\n\n transform: {\n order: \"pre\",\n filter: {\n code: /\\.gts/,\n id: /\\.(js|ts)$/,\n },\n handler(input, id) {\n // Rewrite `.gts` specifiers to `.ts` — the (virtual) source id — in\n // runtime modules AND declaration modules alike. Declaration modules\n // must NOT be rewritten to `.d.ts`: rolldown-plugin-dts's resolver\n // treats a source-file resolution as \"load it (registering its\n // declaration), then map to the declaration id\", while a `.d.ts` id is\n // returned as-is — unloadable when the module isn't registered yet\n // (e.g. the `.gts` is only ever type-imported).\n const output = input.replace(\n /(['\"`])((?:\\.\\.?\\/|\\/|@|[A-Za-z0-9_\\-])[^'\"]*?\\.gts)\\1/g,\n (_m, q, p) => `${q}${p.replace(/\\.gts$/, \".ts\")}${q}`,\n );\n\n if (output === input) {\n return null;\n }\n\n // The rewrite only shortens import specifiers in place, so a\n // line-identity map is accurate to the line (and to the column for\n // everything before the first rewritten specifier on a line).\n return { code: output, map: lineIdentityMap(id, input) };\n },\n },\n\n writeBundle: {\n async handler(options) {\n const outDir = (options as { dir?: string }).dir;\n if (outDir) {\n await fixDtsExtensionsInDir(path.resolve(outDir));\n }\n },\n },\n };\n}\n","import { emberBabel, type BabelOptions } from \"./src/babel.ts\";\nimport { emberConfig } from \"./src/config.ts\";\nimport { emberExternals } from \"./src/externals.ts\";\nimport { emberIsolatedDeclarations } from \"./src/isolated-declarations.ts\";\nimport { emberTransform } from \"./src/transform.ts\";\nimport type { RolldownPluginLike } from \"./src/plugin-like.ts\";\n\ninterface Config {\n /**\n * Options for the babel step; see `BabelOptions`.\n */\n babel?: BabelOptions;\n}\n\n/**\n * A batteries-included plugin for building Ember v2 libraries (addons) with\n * rolldown (or tsdown, which is built on rolldown).\n *\n * It bundles everything needed to compile `.gts`/`.gjs` and template-tag\n * (`<template>`) source into publishable output:\n *\n * - `emberConfig()` — applies sensible tsdown defaults for a library build\n * (sourcemaps, `clean`, `dts`, `.js`/`.d.ts` extensions, quiet logging);\n * anything you set explicitly still wins.\n * - `emberIsolatedDeclarations()` — errors when a tsconfig.json is present\n * without `isolatedDeclarations: true` (required: it is the only\n * declaration pipeline that can see compiled template-tag modules).\n * - `emberExternals()` — keeps your dependencies, peerDependencies, and the\n * ember virtual packages external, so consuming apps resolve them.\n * - `emberTransform()` — preprocesses `<template>` via content-tag and maps\n * `.gts`/`.gjs` to `.ts`/`.js` so rolldown can understand them.\n * - `emberBabel()` — runs babel (template compilation, decorators, type\n * stripping) with `babelHelpers: \"bundled\"`, but only on the files that\n * actually need it (via `maybeBabel`); everything else stays on the fast\n * native transform. The library's own `babel.config.js` is used when it\n * exists; no config file is required.\n *\n * Usage in `tsdown.config.js` (import `defineConfig` from `tsdown` — or from\n * `rolldown` for a `rolldown.config.js` — so it carries the correct types):\n *\n * ```js\n * import { defineConfig } from \"tsdown\";\n * import { ember } from \"@nullvoxpopuli/ember-rolldown\";\n *\n * export default defineConfig({\n * entry: [\"./src/index.ts\"],\n * plugins: [ember()],\n * });\n * ```\n */\nexport function ember(config: Config = {}): RolldownPluginLike[] {\n return [\n emberConfig(),\n emberIsolatedDeclarations(),\n emberExternals(),\n emberTransform(),\n emberBabel(config.babel),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;AAoDA,MAAM,4BAA4B;CAAC;CAAO;CAAO;CAAM;CAAO;CAAO;CAAM;AAAM;;;;;AAMjF,MAAM,6BAA6B,CAAC,KAAK,QAAQ;;;;;;;;;;;;;;AAejD,SAAS,0BAA8C;CACrD,KAAK,MAAM,aAAa,4BACtB,KAAK,MAAM,aAAa,2BAA2B;EACjD,MAAM,YAAY,QAAQ,WAAW,wBAAwB,WAAW;EAExE,IAAI,WAAW,SAAS,GAAG,OAAO;CACpC;AAIJ;;;;;;;;;;;AAYA,SAAS,mBAAuC;CAC9C,MAAM,gBAAgB,wBAAwB;CAE9C,IAAI,eAAe,OAAO;CAI1B,OAFgB,sBAAsB,EAAE,KAAK,QAAQ,IAAI,EAAE,CAE9C,CAAC,EAAE,UAAU,KAAA;AAC5B;;;;;;;;;;;;;;;AAgBA,SAAS,eAAe,oBAAgD;CACtE,OAAO;EACL,CACE,qBACA;GACE,eAAe;GACf,uBAAuB;GACvB,oBAAoB;EACtB,CACF;EACA,CAAC,qBAAqB;GAAE,cAAc;GAAO,YAAY,sBAAsB,CAAC;EAAE,CAAC;EACnF,CACE,qBACA,EAGE,SAAS,EAAE,QAAQ,mCAAmC,EACxD,CACF;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,WAAW,UAAwB,CAAC,GAAW;CAC7D,MAAM,aAAa,QAAQ,eAAe,KAAA,IAAY,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GACzD;EACF;EAEA,aAAa,EACX,MAAM,QAAQ,SAAS;GACrB,MAAM,SAAU,QAA6B;GAC7C,IAAI,QACF,MAAM,sBAAsB,KAAK,QAAQ,MAAM,CAAC;EAEpD,EACF;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC5KA,SAAgB,MAAM,SAAiB,CAAC,GAAyB;CAC/D,OAAO;EACL,YAAY;EACZ,0BAA0B;EAC1B,eAAe;EACf,eAAe;EACf,WAAW,OAAO,KAAK;CACzB;AACF"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
//#region src/plugin-like.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* What this package hands back: an object that rolldown and tsdown accept in
|
|
4
|
+
* `plugins`.
|
|
5
|
+
*
|
|
6
|
+
* Structurally this *is* rolldown's `Plugin` -- `name` is its only required
|
|
7
|
+
* member, every hook is optional -- so the two are assignable in both
|
|
8
|
+
* directions: a consumer who imports rolldown's own type can still write
|
|
9
|
+
* `const plugins: Plugin[] = ember()`, and tsdown's `plugins` option lists
|
|
10
|
+
* `{ name: string }` among the shapes it takes.
|
|
11
|
+
*
|
|
12
|
+
* Declaring it here rather than re-exporting rolldown's type is what keeps
|
|
13
|
+
* `rolldown` out of the published declarations. Otherwise it has to become a
|
|
14
|
+
* runtime `dependency` purely so consumers can resolve a type: leave it a
|
|
15
|
+
* devDependency and the declaration bundler inlines a ~200kB private copy of
|
|
16
|
+
* rolldown's types instead, nominally distinct from the consumer's own.
|
|
17
|
+
*
|
|
18
|
+
* The precise hook signatures still apply inside this package -- each plugin
|
|
19
|
+
* function is typed with rolldown's real `Plugin` (a devDependency), and this
|
|
20
|
+
* type only widens what crosses the package boundary.
|
|
21
|
+
*/
|
|
22
|
+
interface RolldownPluginLike {
|
|
23
|
+
name: string;
|
|
24
|
+
}
|
|
25
|
+
//#endregion
|
|
26
|
+
export { RolldownPluginLike as t };
|
|
27
|
+
//# sourceMappingURL=plugin-like-CBvGkzCB.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin-like-CBvGkzCB.d.ts","names":[],"sources":["../src/plugin-like.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;UAoBiB;EACf"}
|
package/index.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import type { Plugin } from "rolldown";
|
|
2
|
-
|
|
3
1
|
import { emberBabel, type BabelOptions } from "./src/babel.ts";
|
|
4
2
|
import { emberConfig } from "./src/config.ts";
|
|
5
3
|
import { emberExternals } from "./src/externals.ts";
|
|
6
4
|
import { emberIsolatedDeclarations } from "./src/isolated-declarations.ts";
|
|
7
5
|
import { emberTransform } from "./src/transform.ts";
|
|
6
|
+
import type { RolldownPluginLike } from "./src/plugin-like.ts";
|
|
8
7
|
|
|
9
8
|
interface Config {
|
|
10
9
|
/**
|
|
@@ -49,7 +48,7 @@ interface Config {
|
|
|
49
48
|
* });
|
|
50
49
|
* ```
|
|
51
50
|
*/
|
|
52
|
-
export function ember(config: Config = {}):
|
|
51
|
+
export function ember(config: Config = {}): RolldownPluginLike[] {
|
|
53
52
|
return [
|
|
54
53
|
emberConfig(),
|
|
55
54
|
emberIsolatedDeclarations(),
|
package/package.json
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nullvoxpopuli/ember-rolldown",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.7.0",
|
|
4
4
|
"description": "Meta plugin for building ember v2 libraries/addons with rolldown & tsdown.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"exports": {
|
|
8
|
-
".":
|
|
9
|
-
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"default": "./dist/index.js"
|
|
11
|
+
},
|
|
12
|
+
"./app-reexports": {
|
|
13
|
+
"types": "./dist/app-reexports.d.ts",
|
|
14
|
+
"default": "./dist/app-reexports.js"
|
|
15
|
+
}
|
|
10
16
|
},
|
|
11
17
|
"keywords": [
|
|
12
18
|
"rolldown",
|
|
@@ -54,6 +60,7 @@
|
|
|
54
60
|
"typescript": "^6.0.3"
|
|
55
61
|
},
|
|
56
62
|
"scripts": {
|
|
57
|
-
"build": "
|
|
58
|
-
}
|
|
63
|
+
"build": "tsdown"
|
|
64
|
+
},
|
|
65
|
+
"types": "dist/index.d.ts"
|
|
59
66
|
}
|
package/src/app-reexports.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { dirname, extname, join, matchesGlob, relative, resolve, sep } from "node:path";
|
|
3
3
|
|
|
4
|
-
import type {
|
|
4
|
+
import type { RolldownPluginLike } from "./plugin-like.ts";
|
|
5
5
|
|
|
6
6
|
export interface AppReexportsOptions {
|
|
7
7
|
/**
|
|
@@ -79,7 +79,7 @@ export interface AppReexportsOptions {
|
|
|
79
79
|
export function appReexports(
|
|
80
80
|
includeOrOptions: string | string[] | AppReexportsOptions = {},
|
|
81
81
|
options: Omit<AppReexportsOptions, "include"> = {},
|
|
82
|
-
):
|
|
82
|
+
): RolldownPluginLike {
|
|
83
83
|
const resolved =
|
|
84
84
|
typeof includeOrOptions === "string"
|
|
85
85
|
? { ...options, include: [includeOrOptions] }
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What this package hands back: an object that rolldown and tsdown accept in
|
|
3
|
+
* `plugins`.
|
|
4
|
+
*
|
|
5
|
+
* Structurally this *is* rolldown's `Plugin` -- `name` is its only required
|
|
6
|
+
* member, every hook is optional -- so the two are assignable in both
|
|
7
|
+
* directions: a consumer who imports rolldown's own type can still write
|
|
8
|
+
* `const plugins: Plugin[] = ember()`, and tsdown's `plugins` option lists
|
|
9
|
+
* `{ name: string }` among the shapes it takes.
|
|
10
|
+
*
|
|
11
|
+
* Declaring it here rather than re-exporting rolldown's type is what keeps
|
|
12
|
+
* `rolldown` out of the published declarations. Otherwise it has to become a
|
|
13
|
+
* runtime `dependency` purely so consumers can resolve a type: leave it a
|
|
14
|
+
* devDependency and the declaration bundler inlines a ~200kB private copy of
|
|
15
|
+
* rolldown's types instead, nominally distinct from the consumer's own.
|
|
16
|
+
*
|
|
17
|
+
* The precise hook signatures still apply inside this package -- each plugin
|
|
18
|
+
* function is typed with rolldown's real `Plugin` (a devDependency), and this
|
|
19
|
+
* type only widens what crosses the package boundary.
|
|
20
|
+
*/
|
|
21
|
+
export interface RolldownPluginLike {
|
|
22
|
+
name: string;
|
|
23
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { execa } from "execa";
|
|
2
|
+
import { readdir, readFile, rm, stat } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { beforeAll, describe, expect, it } from "vitest";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* This package's own published shape: consumers write their build config in
|
|
9
|
+
* TypeScript, so `import { ember } from "@nullvoxpopuli/ember-rolldown"` has to
|
|
10
|
+
* carry types. Without them it is an implicit `any` (TS7016), and a config file
|
|
11
|
+
* silently stops being type-checked.
|
|
12
|
+
*/
|
|
13
|
+
const packageDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
14
|
+
|
|
15
|
+
interface Manifest {
|
|
16
|
+
dependencies: Record<string, string>;
|
|
17
|
+
peerDependencies: Record<string, string>;
|
|
18
|
+
publishConfig: { exports: Record<string, Record<string, string>> };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function readManifest(): Promise<Manifest> {
|
|
22
|
+
return JSON.parse(await readFile(path.join(packageDir, "package.json"), "utf8")) as Manifest;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function exists(relative: string) {
|
|
26
|
+
return Boolean(await stat(path.join(packageDir, relative)).catch(() => null));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function declarations() {
|
|
30
|
+
const files = (await readdir(path.join(packageDir, "dist"))).filter((file) =>
|
|
31
|
+
file.endsWith(".d.ts"),
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
return Object.fromEntries(
|
|
35
|
+
await Promise.all(
|
|
36
|
+
files.map(
|
|
37
|
+
async (file) =>
|
|
38
|
+
[file, await readFile(path.join(packageDir, "dist", file), "utf8")] as const,
|
|
39
|
+
),
|
|
40
|
+
),
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
describe("published types", () => {
|
|
45
|
+
beforeAll(async () => {
|
|
46
|
+
// `clean` is on, but don't let these assertions depend on that: stale
|
|
47
|
+
// artifacts from an earlier build satisfy every one of them on their own
|
|
48
|
+
await rm(path.join(packageDir, "dist"), { recursive: true, force: true });
|
|
49
|
+
await execa("pnpm", ["build"], { cwd: packageDir });
|
|
50
|
+
}, 120_000);
|
|
51
|
+
|
|
52
|
+
it("every publishConfig export declares types, and they exist", async () => {
|
|
53
|
+
const manifest = await readManifest();
|
|
54
|
+
const entries = Object.entries(manifest.publishConfig.exports);
|
|
55
|
+
|
|
56
|
+
expect(entries.length).toBeGreaterThan(0);
|
|
57
|
+
|
|
58
|
+
for (const [subpath, conditions] of entries) {
|
|
59
|
+
expect(conditions, `${subpath} declares types`).toHaveProperty("types");
|
|
60
|
+
expect(await exists(conditions["types"]!), `${subpath} -> ${conditions["types"]}`).toBe(true);
|
|
61
|
+
expect(await exists(conditions["default"]!), `${subpath} -> ${conditions["default"]}`).toBe(
|
|
62
|
+
true,
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* A declaration may only reach for packages a consumer is guaranteed to have.
|
|
69
|
+
* Reference a devDependency and there are two ways to lose, both quiet:
|
|
70
|
+
* the specifier survives and consumers can't resolve it (`skipLibCheck` hides
|
|
71
|
+
* that, degrading the type to an error type), or the declaration bundler
|
|
72
|
+
* inlines the whole type surface — a ~200kB copy of rolldown's types, in the
|
|
73
|
+
* case that prompted this test, nominally distinct from the consumer's own.
|
|
74
|
+
*
|
|
75
|
+
* `ember()` returns plugins, so `RolldownPluginLike` exists to keep rolldown
|
|
76
|
+
* on the devDependency side of that line.
|
|
77
|
+
*/
|
|
78
|
+
it("declarations only reference packages consumers have", async () => {
|
|
79
|
+
const manifest = await readManifest();
|
|
80
|
+
const available = new Set([
|
|
81
|
+
...Object.keys(manifest.dependencies),
|
|
82
|
+
...Object.keys(manifest.peerDependencies),
|
|
83
|
+
]);
|
|
84
|
+
|
|
85
|
+
for (const [file, contents] of Object.entries(await declarations())) {
|
|
86
|
+
const specifiers = [...contents.matchAll(/^import .* from "([^"]+)";$/gm)]
|
|
87
|
+
.map(([, specifier]) => specifier!)
|
|
88
|
+
.filter((specifier) => !specifier.startsWith("."));
|
|
89
|
+
|
|
90
|
+
for (const specifier of specifiers) {
|
|
91
|
+
const owner = specifier.startsWith("@")
|
|
92
|
+
? specifier.split("/").slice(0, 2).join("/")
|
|
93
|
+
: specifier.split("/")[0]!;
|
|
94
|
+
|
|
95
|
+
expect(available, `${file} imports ${specifier}`).toContain(owner);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// an inlined copy of a bundler's types, rather than an import of them
|
|
99
|
+
expect(contents, `${file} inlines rolldown's types`).not.toMatch(/interface PluginContext/);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
});
|
package/src/transform.test.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
|
|
|
2
2
|
import { tmpdir } from "node:os";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { rolldown } from "rolldown";
|
|
5
|
+
import type { Plugin } from "rolldown";
|
|
5
6
|
import { describe, expect, it } from "vitest";
|
|
6
7
|
|
|
7
8
|
import { emberTransform } from "./transform.ts";
|
|
@@ -15,7 +16,10 @@ import { emberTransform } from "./transform.ts";
|
|
|
15
16
|
*/
|
|
16
17
|
async function bundle(
|
|
17
18
|
files: Record<string, string>,
|
|
18
|
-
{
|
|
19
|
+
{
|
|
20
|
+
input = ["index.ts"],
|
|
21
|
+
plugins = () => [],
|
|
22
|
+
}: { input?: string[]; plugins?: (dir: string) => Plugin[] } = {},
|
|
19
23
|
): Promise<string> {
|
|
20
24
|
const dir = await mkdtemp(path.join(tmpdir(), "ember-rolldown-build-"));
|
|
21
25
|
|
|
@@ -29,7 +33,7 @@ async function bundle(
|
|
|
29
33
|
|
|
30
34
|
const build = await rolldown({
|
|
31
35
|
input: input.map((relative) => path.join(dir, relative)),
|
|
32
|
-
plugins: [emberTransform()],
|
|
36
|
+
plugins: [emberTransform(), ...plugins(dir)],
|
|
33
37
|
external: (id) => !isLocal(id),
|
|
34
38
|
onwarn() {},
|
|
35
39
|
});
|
|
@@ -174,6 +178,50 @@ describe("emberTransform (full plugin via rolldown)", () => {
|
|
|
174
178
|
`);
|
|
175
179
|
});
|
|
176
180
|
|
|
181
|
+
it("resolves an absolute .gts specifier imported from a plugin's virtual module", async () => {
|
|
182
|
+
/**
|
|
183
|
+
* The shape a code-generating plugin emits: a virtual module (id prefixed
|
|
184
|
+
* with `\0`, so it exists nowhere on disk) whose generated source imports
|
|
185
|
+
* real files by absolute path, because it has no directory to be relative
|
|
186
|
+
* to. `path.dirname` of such an id is `"\0."`, so the specifier must not be
|
|
187
|
+
* resolved against the importer's directory.
|
|
188
|
+
*/
|
|
189
|
+
const registry = (dir: string): Plugin[] => {
|
|
190
|
+
const source = "./registry?virtual=views";
|
|
191
|
+
const virtualId = `\0${source}`;
|
|
192
|
+
|
|
193
|
+
return [
|
|
194
|
+
{
|
|
195
|
+
name: "test:virtual-registry",
|
|
196
|
+
resolveId(id) {
|
|
197
|
+
return id === source ? virtualId : null;
|
|
198
|
+
},
|
|
199
|
+
load(id) {
|
|
200
|
+
if (id !== virtualId) return null;
|
|
201
|
+
|
|
202
|
+
return [
|
|
203
|
+
`import example from '${path.join(dir, "components/view/example.gts")}';`,
|
|
204
|
+
`export const views = { example };`,
|
|
205
|
+
].join("\n");
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
];
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
const code = await bundle(
|
|
212
|
+
{
|
|
213
|
+
"index.ts": `export { views } from './registry?virtual=views';`,
|
|
214
|
+
"components/view/example.gts": `<template>example</template>`,
|
|
215
|
+
},
|
|
216
|
+
{ plugins: registry },
|
|
217
|
+
);
|
|
218
|
+
|
|
219
|
+
// The absolutely-specified .gts got compiled and bundled in.
|
|
220
|
+
expect(code).not.toContain("<template>");
|
|
221
|
+
expect(code).toContain("template(");
|
|
222
|
+
expect(code).toContain("example");
|
|
223
|
+
});
|
|
224
|
+
|
|
177
225
|
it("compiles a .gts module used directly as an entry (no importer)", async () => {
|
|
178
226
|
const code = await bundle(
|
|
179
227
|
{
|
package/src/transform.ts
CHANGED
|
@@ -93,7 +93,14 @@ export function emberTransform(): Plugin {
|
|
|
93
93
|
};
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
-
|
|
96
|
+
// An absolute specifier already names the file, so it needs no
|
|
97
|
+
// importer-relative resolution — and joining it onto the importer's
|
|
98
|
+
// directory would corrupt it. That is not hypothetical: a plugin's
|
|
99
|
+
// virtual module (id prefixed with `\0`) can generate imports of
|
|
100
|
+
// on-disk files by absolute path, and `path.dirname("\0./registry")`
|
|
101
|
+
// is `"\0."`, so joining yields `"\0./Users/.../thing.gts"` — a path
|
|
102
|
+
// no `existsSync`/`readFile` can accept (it has a null byte in it).
|
|
103
|
+
const fileName = path.isAbsolute(id) ? id : path.join(path.dirname(importer), id);
|
|
97
104
|
|
|
98
105
|
if (id.endsWith(".gts")) {
|
|
99
106
|
return {
|
package/tsdown.config.ts
ADDED
package/rolldown.config.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { defineConfig } from "rolldown";
|
|
2
|
-
|
|
3
|
-
import manifest from "./package.json" with { type: "json" };
|
|
4
|
-
|
|
5
|
-
const deps = [
|
|
6
|
-
...Object.keys(manifest.dependencies || {}),
|
|
7
|
-
...Object.keys(manifest.peerDependencies || {}),
|
|
8
|
-
];
|
|
9
|
-
|
|
10
|
-
export default defineConfig({
|
|
11
|
-
input: {
|
|
12
|
-
index: "index.ts",
|
|
13
|
-
"app-reexports": "src/app-reexports.ts",
|
|
14
|
-
},
|
|
15
|
-
output: {
|
|
16
|
-
format: "esm",
|
|
17
|
-
dir: "dist",
|
|
18
|
-
},
|
|
19
|
-
external(id) {
|
|
20
|
-
if (id.startsWith("node:")) return true;
|
|
21
|
-
if (deps.some((dep) => id.startsWith(dep))) return true;
|
|
22
|
-
},
|
|
23
|
-
});
|