Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): experimental render — tsconfig paths by TypeScript's rules; name a stripped rendered file (#8012)

Joey49e72367eb42
diff --git a/.changeset/cli-render-paths-stripped.md b/.changeset/cli-render-paths-stripped.md
new file mode 100644
index 0000000000..71f267a167
--- /dev/null
+++ b/.changeset/cli-render-paths-stripped.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[experimental] `astryx experimental render` matches `compilerOptions.paths` keys and targets by TypeScript's rules, from the project's own tsconfig.json or jsconfig.json (a config it `extends` is not read). Newly, a `*` may sit anywhere in a key or a target (`"theme-*-x"`, `"./icons/icon-*"`), and a key's targets are tried in order, so a module, stylesheet, image or JSON file under a later target is found; `--reverse` puts a file back under the target its sent path names (the one whose folders match the most of the path above the file, a target with text before its `*` included), else under the first target. Only bare specifiers are matched, an import whose targets do not exist resolves as a package, and a catch-all `"*"` key never turns a missing package into a path error. A module the page loads from outside its own files and outside `node_modules` (a sibling package's source, say) resolves a bare import through the same aliases first, as the page's own files and TypeScript do, so the page and that module load one copy of a package; an import no alias places resolves as a package, so an installed package that a prefix key also names (`"@scope/*"` and `@scope/realpkg`) still loads. `--reverse` of a rendered file that lost its embedded source on the way (and has no Astryx components to rebuild from) now fails with `ERR_RENDER_SOURCE_DAMAGED`, saying so, instead of `ERR_RENDER_NOT_ASTRYX`.
+
+@josephfarina
diff --git a/packages/cli/api/render/_adapter.mjs b/packages/cli/api/render/_adapter.mjs
index a2e75b28b7..398ebad0ad 100644
--- a/packages/cli/api/render/_adapter.mjs
+++ b/packages/cli/api/render/_adapter.mjs
@@ -548,6 +548,15 @@ export function reverseToFile({cwd, input, output, overwrite}) {
...(missing.length > 0 ? {missing} : {}),
};
}
+ // A file a render wrote, whose source block was taken out on the way
+ // (sanitizers and editors strip <script> elements), says so.
+ if (!isAstryxMarkup(html) && /<meta name="generator" content="Astryx[ "]/.test(html)) {
+ throw new AstryxError(
+ `${shown(cwd, input)} was rendered by Astryx, but its embedded source was removed (a sanitizer or an editor strips <script> blocks) and it has no Astryx components to rebuild from; nothing was written. Render the page again from its source and send the new file as is.`,
+ [],
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
+ );
+ }
if (!isAstryxMarkup(html)) {
throw new AstryxError(
`${shown(cwd, input)} is not an Astryx page: it has no embedded source and no Astryx components to rebuild from. To start an Astryx page like it, run astryx build "<what the page is>".`,
diff --git a/packages/cli/api/render/render.doc.mjs b/packages/cli/api/render/render.doc.mjs
index 84f4752b23..a872cf0e0f 100644
--- a/packages/cli/api/render/render.doc.mjs
+++ b/packages/cli/api/render/render.doc.mjs
@@ -99,9 +99,9 @@ export const doc = {
{code: 'ERR_RENDER_FAILED', when: 'the page throws while rendering for any other reason'},
{
code: 'ERR_RENDER_NOT_ASTRYX',
- when: 'reversing a file with no embedded source and no Astryx markup; the suggestion is `astryx build "<what the page is>"`',
+ when: 'reversing a file a render did not write, with no embedded source and no Astryx markup; the suggestion is `astryx build "<what the page is>"`',
},
- {code: 'ERR_RENDER_SOURCE_DAMAGED', when: 'reversing a file whose embedded source is damaged, lists a path twice, carries a module, stylesheet or JSON file the page does not reach through its imports, or an image, font or media file whose bytes are not one, or carries a file a render never embeds (a dotfile or dot-folder, `node_modules`, a package manifest, lockfile or tool configuration, or any kind but a page module, stylesheet, JSON or image)'},
+ {code: 'ERR_RENDER_SOURCE_DAMAGED', when: 'reversing a file a render wrote whose embedded source was removed (and that has no Astryx components to rebuild from), a file whose embedded source is damaged, lists a path twice, carries a module, stylesheet or JSON file the page does not reach through its imports, or an image, font or media file whose bytes are not one, or carries a file a render never embeds (a dotfile or dot-folder, `node_modules`, a package manifest, lockfile or tool configuration, or any kind but a page module, stylesheet, JSON or image)'},
{code: 'ERR_PATH_TRAVERSAL', when: 'a file would be written outside the current folder (symlinks followed), or through a symbolic link: `out`, or with `reverse` the page or an embedded file; or, with `reverse`, a file other than the page would go into a folder that already exists'},
],
examples: [
diff --git a/packages/cli/api/render/render.test.mjs b/packages/cli/api/render/render.test.mjs
index 3014f9d054..8e5b6a6102 100644
--- a/packages/cli/api/render/render.test.mjs
+++ b/packages/cli/api/render/render.test.mjs
@@ -704,6 +704,283 @@ describe('render(): every write stays inside the current folder', () => {
}
}, 90_000);
+ it('resolves tsconfig paths by TypeScript rules: exact keys, a star anywhere, targets in order', async () => {
+ put(
+ 'tsp/tsconfig.json',
+ JSON.stringify({
+ compilerOptions: {
+ baseUrl: '.',
+ paths: {
+ '@lib': ['./libsrc/index.ts'],
+ '@lib/*': ['./libsrc/*'],
+ '~*': ['./missing/*', './other/*'],
+ 'theme-*-x': ['./themes/*.ts'],
+ },
+ },
+ }),
+ );
+ put('tsp/package.json', '{"name":"tsp","private":true}');
+ put('tsp/libsrc/index.ts', "export const Lib = 'lib-index';\n");
+ put('tsp/libsrc/button.tsx', "export const Button = () => <b>lib-button</b>;\n");
+ put('tsp/other/util.ts', "export const util = 'second-target';\n");
+ put('tsp/themes/blue.ts', "export const theme = 'mid-star';\n");
+ put(
+ 'tsp/page.tsx',
+ [
+ "import {Lib} from '@lib';",
+ "import {Button} from '@lib/button';",
+ "import {util} from '~util';",
+ "import {theme} from 'theme-blue-x';",
+ 'export default function Page() { return <p>{Lib} {util} {theme} <Button /></p>; }',
+ '',
+ ].join('\n'),
+ );
+ await render('tsp/page.tsx', {cwd: dir});
+ const html = fs.readFileSync(path.join(dir, 'tsp/page.html'), 'utf8');
+ for (const text of ['lib-index', 'lib-button', 'second-target', 'mid-star']) expect(html).toContain(text);
+ }, 60_000);
+
+ it('loads a JSON file through any key shape, from the first target that has it, and gives it back', async () => {
+ put('jsonp/tsconfig.json', JSON.stringify({compilerOptions: {baseUrl: '.', paths: {'~*': ['./lib/data/*'], 'cfg-*': ['./lib/missing/*', './lib/more/*']}}}));
+ put('jsonp/package.json', '{"name":"jsonp","private":true}');
+ put('jsonp/lib/data/cfg.json', '{"label":"first-target-json"}\n');
+ put('jsonp/lib/more/extra.json', '{"label":"later-target-json"}\n');
+ put(
+ 'jsonp/page.tsx',
+ "import cfg from '~cfg.json';\nimport extra from 'cfg-extra.json';\nexport default function Page() { return <p>{cfg.label} {extra.label}</p>; }\n",
+ );
+ const r = /** @type {any} */ (await render('jsonp/page.tsx', {cwd: dir}));
+ expect(r.data.files).toEqual(expect.arrayContaining(['page.tsx', 'lib/data/cfg.json', 'lib/more/extra.json']));
+ const html = fs.readFileSync(path.join(dir, 'jsonp/page.html'), 'utf8');
+ expect(html).toContain('first-target-json');
+ expect(html).toContain('later-target-json');
+ // Back into a project with the same paths: each file goes where its alias points.
+ fs.mkdirSync(path.join(dir, 'jsonp-to'), {recursive: true});
+ put('jsonp-to/tsconfig.json', fs.readFileSync(path.join(dir, 'jsonp/tsconfig.json'), 'utf8'));
+ put('jsonp-to/package.json', '{"name":"jsonp-to","private":true}');
+ fs.copyFileSync(path.join(dir, 'jsonp/page.html'), path.join(dir, 'jsonp-to/page.html'));
+ const back = /** @type {any} */ (await render('page.html', {cwd: path.join(dir, 'jsonp-to'), reverse: true, out: 'lib/app/page.tsx'}));
+ // The file sent from the later target goes back under that target.
+ expect(back.data.files).toEqual(expect.arrayContaining(['lib/data/cfg.json', 'lib/more/extra.json']));
+ }, 60_000);
+
+ it.each([
+ ['folder names that end alike', ['./lib/app/*', './lib/webapp/*'], 'lib/webapp/Top.tsx', 'lib/webapp/Top.tsx'],
+ ['targets that share their last folder', ['./lib/ui/src/*', './lib/icons/src/*'], 'lib/icons/src/Top.tsx', 'lib/icons/src/Top.tsx'],
+ // Every embedded path is relative to the folder that holds them all, so
+ // a page inside the later target names no target folder: the first wins.
+ ['a page inside the later target', ['./lib/missing/*', './lib/src/*'], 'lib/src/Top.tsx', 'lib/missing/Top.tsx', 'lib/src/pages/page.tsx'],
+ ])('gives back an aliased module by whole folder names: %s', async (name, targets, sentFrom, comesBack, pageAt = 'page.tsx') => {
+ const base = `segments-${String(name).replace(/\W+/g, '-')}`;
+ const paths = {compilerOptions: {baseUrl: '.', paths: {'@/*': targets}}};
+ put(`${base}/tsconfig.json`, JSON.stringify(paths));
+ put(`${base}/package.json`, '{"name":"segments","private":true}');
+ put(`${base}/${sentFrom}`, "export const Top = () => <i>segment-top</i>;\n");
+ put(`${base}/${pageAt}`, "import {Top} from '@/Top';\nexport default function Page() { return <p><Top /></p>; }\n");
+ await render(`${base}/${pageAt}`, {cwd: dir});
+ const html = `${base}/${pageAt.replace(/\.tsx$/, '.html')}`;
+ fs.mkdirSync(path.join(dir, `${base}-to`), {recursive: true});
+ put(`${base}-to/tsconfig.json`, JSON.stringify(paths));
+ put(`${base}-to/package.json`, '{"name":"segments-to","private":true}');
+ fs.copyFileSync(path.join(dir, html), path.join(dir, `${base}-to/page.html`));
+ const back = /** @type {any} */ (await render('page.html', {cwd: path.join(dir, `${base}-to`), reverse: true, out: 'lib/zz/page.tsx'}));
+ expect(back.data.files).toContain(comesBack);
+ }, 60_000);
+
+ it('gives back a folder an exact key names under the target it was sent from', async () => {
+ const paths = {compilerOptions: {baseUrl: '.', paths: {'@cfg': ['./lib/a/settings', './lib/b/settings']}}};
+ put('exactdir/tsconfig.json', JSON.stringify(paths));
+ put('exactdir/package.json', '{"name":"exactdir","private":true}');
+ put('exactdir/lib/b/settings/index.ts', "export const setting = 'from-b';\n");
+ put('exactdir/page.tsx', "import {setting} from '@cfg';\nexport default function Page() { return <p>{setting}</p>; }\n");
+ await render('exactdir/page.tsx', {cwd: dir});
+ expect(fs.readFileSync(path.join(dir, 'exactdir/page.html'), 'utf8')).toContain('from-b');
+ fs.mkdirSync(path.join(dir, 'exactdir-to'), {recursive: true});
+ put('exactdir-to/tsconfig.json', JSON.stringify(paths));
+ put('exactdir-to/package.json', '{"name":"exactdir-to","private":true}');
+ fs.copyFileSync(path.join(dir, 'exactdir/page.html'), path.join(dir, 'exactdir-to/page.html'));
+ const back = /** @type {any} */ (await render('page.html', {cwd: path.join(dir, 'exactdir-to'), reverse: true, out: 'lib/zz/page.tsx'}));
+ expect(back.data.files).toContain('lib/b/settings/index.ts');
+ expect(back.data.files).not.toContain('lib/a/settings/index.ts');
+ }, 60_000);
+
+ it('resolves path aliases in modules outside the project folder, through every key and target', async () => {
+ put(
+ 'sib/app/tsconfig.json',
+ JSON.stringify({
+ compilerOptions: {
+ baseUrl: '.',
+ paths: {
+ '@scope/ui': ['../ui/src/index.tsx'],
+ '@scope/tokens': ['../tokens/src/index.ts'],
+ '@lib/*': ['../missing/*', '../lib/*'],
+ },
+ },
+ }),
+ );
+ put('sib/app/package.json', '{"name":"sib-app","private":true}');
+ put('sib/tokens/src/index.ts', "export const accent = 'token-accent';\n");
+ put('sib/lib/util.ts', "export const util = 'later-target-util';\n");
+ put(
+ 'sib/ui/src/index.tsx',
+ "import {accent} from '@scope/tokens';\nimport {util} from '@lib/util';\nexport const Badge = () => <b>{accent} {util}</b>;\n",
+ );
+ put('sib/app/page.tsx', "import {Badge} from '@scope/ui';\nexport default function Page() { return <p><Badge /></p>; }\n");
+ await render('sib/app/page.tsx', {cwd: dir});
+ const html = fs.readFileSync(path.join(dir, 'sib/app/page.html'), 'utf8');
+ expect(html).toContain('token-accent');
+ expect(html).toContain('later-target-util');
+ }, 60_000);
+
+ it('gives the page and a sibling package one copy of a package the aliases place, even when a built copy is linked', async () => {
+ const paths = {compilerOptions: {baseUrl: '.', paths: {'@scope/ui': ['../ui/src/index.tsx'], '@scope/tokens': ['../tokens/src/index.ts']}}};
+ put('mono/app/tsconfig.json', JSON.stringify(paths));
+ put('mono/app/package.json', '{"name":"mono-app","private":true}');
+ put('mono/tokens/package.json', '{"name":"@scope/tokens","main":"dist/index.js"}');
+ put('mono/tokens/src/index.ts', "import {createContext} from 'react';\nexport const Theme = createContext('default-theme');\n");
+ put('mono/tokens/dist/index.js', "const {createContext} = require('react');\nexports.Theme = createContext('built-copy');\n");
+ // The built package, linked into the sibling's node_modules as a workspace would.
+ fs.mkdirSync(path.join(dir, 'mono/ui/node_modules/@scope'), {recursive: true});
+ fs.symlinkSync(path.join(dir, 'mono/tokens'), path.join(dir, 'mono/ui/node_modules/@scope/tokens'), 'dir');
+ put('mono/ui/src/index.tsx', "import {useContext} from 'react';\nimport {Theme} from '@scope/tokens';\nexport const Badge = () => <b>{useContext(Theme)}</b>;\n");
+ put(
+ 'mono/app/page.tsx',
+ "import {Theme} from '@scope/tokens';\nimport {Badge} from '@scope/ui';\nexport default function Page() { return <Theme.Provider value=\"page-theme\"><Badge /></Theme.Provider>; }\n",
+ );
+ await render('mono/app/page.tsx', {cwd: dir});
+ const html = fs.readFileSync(path.join(dir, 'mono/app/page.html'), 'utf8');
+ expect(html).toContain('page-theme');
+ }, 60_000);
+
+ it('places an aliased subpath that a linked package does not export', async () => {
+ put('expo/app/tsconfig.json', JSON.stringify({compilerOptions: {baseUrl: '.', paths: {'@scope/ui': ['../ui/src/index.tsx'], '@scope/tokens/*': ['../tokens/src/*']}}}));
+ put('expo/app/package.json', '{"name":"expo-app","private":true}');
+ put('expo/tokens/package.json', '{"name":"@scope/tokens","exports":{".":"./dist/index.js"}}');
+ put('expo/tokens/dist/index.js', "exports.red = 'built-red';\n");
+ put('expo/tokens/src/colors.ts', "export const red = 'source-red';\n");
+ fs.mkdirSync(path.join(dir, 'expo/ui/node_modules/@scope'), {recursive: true});
+ fs.symlinkSync(path.join(dir, 'expo/tokens'), path.join(dir, 'expo/ui/node_modules/@scope/tokens'), 'dir');
+ put('expo/ui/src/index.tsx', "import {red} from '@scope/tokens/colors';\nexport const Swatch = () => <i>{red}</i>;\n");
+ put('expo/app/page.tsx', "import {Swatch} from '@scope/ui';\nexport default function Page() { return <p><Swatch /></p>; }\n");
+ await render('expo/app/page.tsx', {cwd: dir});
+ expect(fs.readFileSync(path.join(dir, 'expo/app/page.html'), 'utf8')).toContain('source-red');
+ }, 60_000);
+
+ it('compiles a sibling module with the TypeScript it can hold: type assertions and decorators', async () => {
+ put('tsx-sib/app/tsconfig.json', JSON.stringify({compilerOptions: {baseUrl: '.', experimentalDecorators: true, paths: {'@scope/store': ['../store/src/index.ts']}}}));
+ put('tsx-sib/app/package.json', '{"name":"tsx-sib-app","private":true}');
+ put(
+ 'tsx-sib/store/src/index.ts',
+ "const raw: unknown = 'asserted-label';\nexport const label = <string>raw;\nfunction tag(target: any) { target.tagged = 'decorated-store'; }\n@tag\nexport class Store { static tagged: string; }\n",
+ );
+ put('tsx-sib/store/src/other.ts', "const raw: unknown = 'relative-label';\nexport const other = <string>raw;\n");
+ put(
+ 'tsx-sib/app/page.tsx',
+ "import {label, Store} from '@scope/store';\nimport {other} from '../store/src/other';\nexport default function Page() { return <p>{label} {(Store as any).tagged} {other}</p>; }\n",
+ );
+ await render('tsx-sib/app/page.tsx', {cwd: dir});
+ const html = fs.readFileSync(path.join(dir, 'tsx-sib/app/page.html'), 'utf8');
+ expect(html).toContain('asserted-label');
+ expect(html).toContain('decorated-store');
+ expect(html).toContain('relative-label');
+ }, 60_000);
+
+ it('loads an installed package a prefix key names when the key places no file', async () => {
+ put('pkgpre/tsconfig.json', JSON.stringify({compilerOptions: {baseUrl: '.', paths: {'@scope/*': ['./src/*']}}}));
+ put('pkgpre/package.json', '{"name":"pkgpre","private":true}');
+ put('pkgpre/node_modules/@scope/realpkg/package.json', '{"name":"@scope/realpkg","main":"index.js"}');
+ put('pkgpre/node_modules/@scope/realpkg/index.js', "exports.real = 'installed-package';\n");
+ put('pkgpre/src/local.ts', "export {real} from '@scope/realpkg';\n");
+ put('pkgpre/page.tsx', "import {real} from '@scope/realpkg';\nimport {real as again} from './src/local';\nexport default function Page() { return <p>{real} {again}</p>; }\n");
+ await render('pkgpre/page.tsx', {cwd: dir});
+ expect(fs.readFileSync(path.join(dir, 'pkgpre/page.html'), 'utf8')).toContain('installed-package installed-package');
+ }, 60_000);
+
+ it('gives back a nested aliased module under the target it was sent from', async () => {
+ const paths = {compilerOptions: {baseUrl: '.', paths: {'@/*': ['./lib/missing/*', './lib/src/*']}}};
+ put('nested/tsconfig.json', JSON.stringify(paths));
+ put('nested/package.json', '{"name":"nested","private":true}');
+ put('nested/lib/src/c/Header.tsx', "export const Header = () => <b>nested-header</b>;\n");
+ put('nested/lib/src/Top.tsx', "export const Top = () => <i>top-level</i>;\n");
+ put('nested/page.tsx', "import {Header} from '@/c/Header';\nimport {Top} from '@/Top';\nexport default function Page() { return <p><Header /><Top /></p>; }\n");
+ await render('nested/page.tsx', {cwd: dir});
+ expect(fs.readFileSync(path.join(dir, 'nested/page.html'), 'utf8')).toContain('nested-header');
+ fs.mkdirSync(path.join(dir, 'nested-to'), {recursive: true});
+ put('nested-to/tsconfig.json', JSON.stringify(paths));
+ put('nested-to/package.json', '{"name":"nested-to","private":true}');
+ fs.copyFileSync(path.join(dir, 'nested/page.html'), path.join(dir, 'nested-to/page.html'));
+ const back = /** @type {any} */ (await render('page.html', {cwd: path.join(dir, 'nested-to'), reverse: true, out: 'lib/app/page.tsx'}));
+ expect(back.data.files).toEqual(expect.arrayContaining(['lib/src/c/Header.tsx', 'lib/src/Top.tsx']));
+ expect(back.data.files).not.toEqual(expect.arrayContaining(['lib/missing/c/Header.tsx']));
+ }, 60_000);
+
+ it('names a package a catch-all key cannot place as not installed, and renders a page whose package stylesheet is missing with a warning', async () => {
+ put('catchall2/tsconfig.json', JSON.stringify({compilerOptions: {baseUrl: '.', paths: {'*': ['./types/*']}}}));
+ put('catchall2/package.json', '{"name":"catchall2","private":true}');
+ put('catchall2/dep.tsx', "import x from 'not-a-real-package-xyz';\nexport default () => <p>{String(x)}</p>;\n");
+ expect(await codeOf(() => render('catchall2/dep.tsx', {cwd: dir}))).toBe('ERR_RENDER_MISSING_DEPENDENCY');
+ put('catchall2/sheet.tsx', "import 'not-a-real-package-xyz/style.css';\nexport default () => <p>styled</p>;\n");
+ const r = /** @type {any} */ (await render('catchall2/sheet.tsx', {cwd: dir}));
+ expect(r.data.warnings.map((/** @type {any} */ w) => w.code)).toContain('missing-asset');
+ }, 60_000);
+
+ it('leaves relative and package imports alone under a catch-all paths key', async () => {
+ put('catchall/tsconfig.json', JSON.stringify({compilerOptions: {baseUrl: '.', paths: {'*': ['./types/*']}}}));
+ put('catchall/package.json', '{"name":"catchall","private":true}');
+ // A decoy at baseUrl that `./Header` must not load.
+ put('catchall/Header.tsx', "export const Header = () => <b>decoy</b>;\n");
+ put('catchall/src/Header.tsx', "export const Header = () => <b>local-header</b>;\n");
+ put('catchall/src/styles.css', '.c { color: red; }\n');
+ put('catchall/src/logo.png', PNG);
+ put(
+ 'catchall/src/page.tsx',
+ [
+ "import './styles.css';",
+ "import '@astryxdesign/core/astryx.css';",
+ "import logo from './logo.png';",
+ "import {Header} from './Header';",
+ 'export default function Page() { return <p className="c"><img src={logo} alt="" /><Header /></p>; }',
+ '',
+ ].join('\n'),
+ );
+ const r = /** @type {any} */ (await render('catchall/src/page.tsx', {cwd: dir}));
+ const html = fs.readFileSync(path.join(dir, 'catchall/src/page.html'), 'utf8');
+ expect(html).toContain('local-header');
+ expect(html).not.toContain('decoy');
+ expect(html).toContain('color: red');
+ expect(html).toContain('data:image/png;base64,');
+ expect(r.data.stylesheets).toEqual(expect.arrayContaining(['@astryxdesign/core/astryx.css']));
+ }, 60_000);
+
+ it('gives back a file reached through a target with text before its star', async () => {
+ put('starseg/tsconfig.json', JSON.stringify({compilerOptions: {baseUrl: '.', paths: {'@icon/*': ['./icons/icon-*']}}}));
+ put('starseg/package.json', '{"name":"starseg","private":true}');
+ put('starseg/icons/icon-home.tsx', "export const Home = () => <i>home-icon</i>;\n");
+ put('starseg/page.tsx', "import {Home} from '@icon/home';\nexport default function Page() { return <p><Home /></p>; }\n");
+ await render('starseg/page.tsx', {cwd: dir});
+ fs.mkdirSync(path.join(dir, 'starseg-to'), {recursive: true});
+ put('starseg-to/tsconfig.json', JSON.stringify({compilerOptions: {baseUrl: '.', paths: {'@icon/*': ['./icons/icon-*']}}}));
+ put('starseg-to/package.json', '{"name":"starseg-to","private":true}');
+ fs.copyFileSync(path.join(dir, 'starseg/page.html'), path.join(dir, 'starseg-to/page.html'));
+ const cwd = path.join(dir, 'starseg-to');
+ const back = /** @type {any} */ (await render('page.html', {cwd, reverse: true, out: 'icons/app/page.tsx'}));
+ expect(back.data.files).toEqual(expect.arrayContaining(['icons/icon-home.tsx']));
+ }, 60_000);
+
+ it('refuses a rendered file whose source block was stripped, in its own words', async () => {
+ put('stripped-own.html', '<!doctype html><html><head><meta name="generator" content="Astryx 0.7.5"></head><body><p>Hello</p></body></html>');
+ /** @type {any} */
+ let error;
+ try {
+ await render('stripped-own.html', {cwd: dir, reverse: true});
+ } catch (e) {
+ error = e;
+ }
+ expect(error?.code).toBe('ERR_RENDER_SOURCE_DAMAGED');
+ expect(error.message).toContain('rendered by Astryx');
+ expect(error.message).not.toContain('not an Astryx page');
+ });
+
it('refuses a carried "image" whose bytes are not one', async () => {
const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
put('fake-img.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.tsx', [{path: 'page.tsx', bytes: Buffer.from('export default () => null;\n')}, {path: 'hook.png', bytes: Buffer.from('process.exit(1)\n')}])}</body>`);
diff --git a/packages/cli/assets/docs/tree/render-pages.doc.mjs b/packages/cli/assets/docs/tree/render-pages.doc.mjs
index 0f4a939556..c602e3859d 100644
--- a/packages/cli/assets/docs/tree/render-pages.doc.mjs
+++ b/packages/cli/assets/docs/tree/render-pages.doc.mjs
@@ -86,7 +86,7 @@ export const docs = {
},
{
type: 'prose',
- text: 'It writes the page, the modules, stylesheets and JSON files the page reaches through its own imports, and the images, fonts and media the render carried (however the page named them, as long as their bytes really are one): each goes where the page\'s relative imports find it from wherever you put the page, and a file the page imports through a path alias (`@/components/Header`) goes where your project\'s `tsconfig.json` or `jsconfig.json` alias points. Every file but the page goes inside the one new folder the restore creates (the topmost folder on the page\'s path that does not exist yet), never into a folder that already exists: a page that imports other files comes back into a new folder (`--out restored/app/page.tsx`), and a file it imports through a path alias comes back only when that alias points inside the new folder. Nor does it write a file that a test, story or benchmark runner would run by its default patterns (Jest, Vitest, Bun, AVA, Playwright, Storybook, Cypress and `node --test`: names such as `*.test.*`, `*.spec.*`, `*_test.*`, `*-test.*`, `*.bench.*`, `*.stories.*`, `*.cy.*`, and anything under `test/`, `tests/` or `__tests__/`), judged from the repository root (every folder above the file up to it), else the topmost folder with a package.json. Restored files are the sender\'s code: read them before you run or import them. Without `--out`, everything comes back into a new folder beside the HTML file, named after it (`page.html` comes back into `page-restored/`). A received file that carries anything else (a file the page never imports, a dotfile, `package.json`, a tool configuration, a path that leaves the folder) is refused with nothing written. An existing file is never replaced unless you pass `--overwrite`, and the refusal names every one; a generated, vendored or ignored file, and any path through a symbolic link, is not written even then. Add `--json` for the result as data: what was written, how big it is, and every warning.',
+ text: 'It writes the page, the modules, stylesheets and JSON files the page reaches through its own imports, and the images, fonts and media the render carried (however the page named them, as long as their bytes really are one): each goes where the page\'s relative imports find it from wherever you put the page, and a file the page imports through a path alias (`@/components/Header`) goes where your project\'s `tsconfig.json` or `jsconfig.json` alias points. Every file but the page goes inside the one new folder the restore creates (the topmost folder on the page\'s path that does not exist yet), never into a folder that already exists: a page that imports other files comes back into a new folder (`--out restored/app/page.tsx`), and a file it imports through a path alias comes back only when that alias points inside the new folder. Nor does it write a file that a test, story or benchmark runner would run by its default patterns (Jest, Vitest, Bun, AVA, Playwright, Storybook, Cypress and `node --test`: names such as `*.test.*`, `*.spec.*`, `*_test.*`, `*-test.*`, `*.bench.*`, `*.stories.*`, `*.cy.*`, and anything under `test/`, `tests/` or `__tests__/`), judged from the repository root (every folder above the file up to it), else the topmost folder with a package.json. Restored files are the sender\'s code: read them before you run or import them. Without `--out`, everything comes back into a new folder beside the HTML file, named after it (`page.html` comes back into `page-restored/`). A received file that carries anything else (a file the page never imports, a dotfile, `package.json`, a tool configuration, a path that leaves the folder) is refused with nothing written. A rendered file that lost its embedded source on the way (a sanitizer or an editor strips `<script>` blocks) and has no Astryx components to rebuild from is refused with `ERR_RENDER_SOURCE_DAMAGED`. An existing file is never replaced unless you pass `--overwrite`, and the refusal names every one; a generated, vendored or ignored file, and any path through a symbolic link, is not written even then. Add `--json` for the result as data: what was written, how big it is, and every warning.',
},
],
},
diff --git a/packages/cli/foundation/render/embedded-imports.mjs b/packages/cli/foundation/render/embedded-imports.mjs
index d93238133a..c572109cba 100644
--- a/packages/cli/foundation/render/embedded-imports.mjs
+++ b/packages/cli/foundation/render/embedded-imports.mjs
@@ -18,6 +18,7 @@ import * as path from 'node:path';
import {parse} from '@babel/parser';
import {PAGE_EXTENSIONS} from './embedded-files.mjs';
import postcss from 'postcss';
+import {matchPath, readPathsIn} from './ts-paths.mjs';
import {isAssetPath} from './assets.mjs';
/**
@@ -131,41 +132,17 @@ function scanModule(source, file) {
}
/**
- * Path aliases (`compilerOptions.paths`) of the project that holds `dir`, as
- * absolute prefixes: `"@/*": ["./src/*"]` becomes `["@/", "<root>/src/"]`.
+ * The path aliases (`compilerOptions.paths`) of the project that holds
+ * `dir`, by TypeScript's rules (see ts-paths.mjs).
* @param {string} dir
- * @returns {[string, string][]}
+ * @returns {import('./ts-paths.mjs').PathPattern[]}
*/
export function receivingAliases(dir) {
let d = dir;
while (!fs.existsSync(d) && path.dirname(d) !== d) d = path.dirname(d);
for (;;) {
- for (const name of ['tsconfig.json', 'jsconfig.json']) {
- const file = path.join(d, name);
- if (!fs.existsSync(file)) continue;
- try {
- const text = fs
- .readFileSync(file, 'utf8')
- .replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, str) => str ?? '')
- .replace(/,(\s*[}\]])/g, '$1');
- const options = JSON.parse(text)?.compilerOptions ?? {};
- const base = path.resolve(d, typeof options.baseUrl === 'string' ? options.baseUrl : '.');
- /** @type {[string, string][]} */
- const out = [];
- for (const [key, targets] of Object.entries(options.paths ?? {})) {
- const target = Array.isArray(targets) ? targets[0] : undefined;
- if (typeof target !== 'string') continue;
- if (key.endsWith('/*') && target.endsWith('/*')) {
- out.push([key.slice(0, -1), `${path.resolve(base, target.slice(0, -2))}${path.sep}`]);
- } else if (!key.includes('*') && !target.includes('*')) {
- out.push([key, path.resolve(base, target)]);
- }
- }
- return out;
- } catch {
- return [];
- }
- }
+ const found = readPathsIn(d);
+ if (found) return found;
if (fs.existsSync(path.join(d, 'package.json'))) return [];
const up = path.dirname(d);
if (up === d) return [];
@@ -185,8 +162,8 @@ export function receivingAliases(dir) {
* The embedded files the page reaches through its imports.
* @param {{path: string, base64: string}[]} files the embedded files, page
* first; every path appears once (callers refuse duplicates first)
- * @param {{aliases?: [string, string][]}} [options] the receiving project's
- * path aliases, absolute (see receivingAliases)
+ * @param {{aliases?: import('./ts-paths.mjs').PathPattern[]}} [options] the
+ * receiving project's path aliases (see receivingAliases)
* @returns {{reached: Map<string, Reach>, missing: string[]}} the reached
* tree paths, and the relative imports the file does not carry
*/
@@ -285,29 +262,61 @@ export function reachableFiles(files, {aliases = []} = {}) {
if (fresh) queue.push(target);
continue;
}
- for (const [key, aliasTarget] of aliases) {
- const named = key.endsWith('/') ? bare.startsWith(key) : bare === key;
- if (!named) continue;
- // A wildcard alias names a path under its target; an exact alias
- // (`"@theme": ["./src/theme.ts"]`) names its target file itself.
- const exactExt = key.endsWith('/') ? '' : path.extname(aliasTarget);
- const rest = key.endsWith('/')
- ? bare.slice(key.length)
- : path.basename(aliasTarget, exactExt);
- const hit = rest ? bySuffix(rest) : null;
- if (!hit) break;
- const target = hit.path;
- // The alias names the module without its extension or index file;
- // the file keeps both: `@/c/Header` -> `<alias target>/c/Header.tsx`.
- const abs = key.endsWith('/')
- ? aliasTarget + hit.tail
- : exactExt
- ? aliasTarget
- : aliasTarget + hit.tail.slice(rest.length);
- const {r, fresh} = reach(target);
- r.aliased.add(abs);
- if (fresh) queue.push(target);
- break;
+ const match = matchPath(aliases, bare);
+ if (match) {
+ // Each target in order: the file the alias names, matched in the
+ // tree by the path's tail, and placed where this project's target
+ // puts it (`@/c/Header` -> `<target>/c/Header.tsx`). The target whose
+ // folders match the most whole segments of the sent path above the
+ // file wins; with no match, the first target does.
+ /** @type {{abs: string, hit: {path: string, tail: string}, score: number}[]} */
+ const options = [];
+ for (const target of match.pattern.targets) {
+ const named = target.replace('*', match.capture);
+ const ext = path.extname(named);
+ const star = target.indexOf('*');
+ // The tail starts at the path segment that holds the `*`, so text
+ // before it (`icons/icon-*`) is part of the file name.
+ const cut = star === -1 ? -1 : target.lastIndexOf(path.sep, star) + 1;
+ const rest = (star === -1 ? path.basename(named, ext) : target.slice(cut).replace('*', match.capture))
+ .split(path.sep)
+ .join('/')
+ .replace(/^\/+/, '');
+ const hit = rest ? bySuffix(rest) : null;
+ if (!hit) continue;
+ // The file keeps its own extension or index: `<target>/c/Header` ->
+ // `<target>/c/Header.tsx`.
+ const abs =
+ star !== -1
+ ? target.slice(0, cut) + hit.tail
+ : ext
+ ? named
+ : named + hit.tail.slice(rest.length);
+ // The folders that hold the target's `*` (or, for a target with
+ // none, the target's own folders), against the folders of the sent
+ // path above the part the alias named, from the nearest up.
+ const targetFolders = (star === -1 ? path.dirname(named) : target.slice(0, cut)).split(path.sep).filter(Boolean);
+ const sentTail = hit.tail;
+ const sentFolders = hit.path.slice(0, hit.path.length - sentTail.length).split('/').filter(Boolean);
+ let score = 0;
+ while (
+ score < sentFolders.length &&
+ score < targetFolders.length &&
+ sentFolders[sentFolders.length - 1 - score] === targetFolders[targetFolders.length - 1 - score]
+ ) {
+ score += 1;
+ }
+ options.push({abs, hit, score});
+ }
+ const chosen = options.reduce(
+ (/** @type {(typeof options)[number] | undefined} */ best, o) => (!best || o.score > best.score ? o : best),
+ undefined,
+ );
+ if (chosen) {
+ const {r, fresh} = reach(chosen.hit.path);
+ r.aliased.add(chosen.abs);
+ if (fresh) queue.push(chosen.hit.path);
+ }
}
}
}
diff --git a/packages/cli/foundation/render/page-worker.mjs b/packages/cli/foundation/render/page-worker.mjs
index 6b177ea3e1..64be98c0b6 100644
--- a/packages/cli/foundation/render/page-worker.mjs
+++ b/packages/cli/foundation/render/page-worker.mjs
@@ -29,6 +29,7 @@ import {pathToFileURL} from 'node:url';
import {format} from 'node:util';
import {parentPort, workerData} from 'node:worker_threads';
import {transformSync} from '@babel/core';
+import {matchPath, readPathsIn, resolvePath} from './ts-paths.mjs';
import {createJiti} from 'jiti';
import {assetDataUri, isAssetPath} from './assets.mjs';
import {SINGLE_COPY, isServedPackage, packageOf} from './served-packages.mjs';
@@ -354,6 +355,39 @@ async function drawCharts(markup, Page) {
};
}
+/**
+ * Babel plugin: a bare import that a path alias places loads from that file,
+ * as in TypeScript, before any installed copy. An import the aliases do not
+ * place is left alone, so an installed package loads. It runs on the page's
+ * own files, before {@link pagePlugin}, and on every module the page loads
+ * from outside them and outside `node_modules` (a sibling package's source,
+ * say).
+ */
+function aliasPlugin() {
+ return () => {
+ /** @param {any} node a string literal to point at the file an alias places */
+ const point = node => {
+ if (node?.type !== 'StringLiteral') return;
+ const file = resolvePath(PATHS, node.value);
+ if (file) node.value = file;
+ };
+ return {
+ visitor: {
+ 'ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration'(/** @type {any} */ p) {
+ point(p.node.source);
+ },
+ CallExpression(/** @type {any} */ p) {
+ const callee = p.node.callee;
+ if (callee?.type === 'Import' || (callee?.type === 'Identifier' && callee.name === 'require')) point(p.node.arguments?.[0]);
+ },
+ ImportExpression(/** @type {any} */ p) {
+ point(p.node.source);
+ },
+ },
+ };
+ };
+}
+
/**
* Babel plugin: replace asset imports with data: URIs and stylesheet imports
* with nothing (their CSS is inlined into the page), and record static text
@@ -398,6 +432,23 @@ function pagePlugin(filename) {
p.remove();
return;
}
+ if (/\.css$/i.test(bare) && bare === raw && namesAlias(raw)) {
+ // An aliased stylesheet with no target falls back to a package, as in
+ // TypeScript; when there is none either, the alias is wrong.
+ let found = true;
+ try {
+ createRequire(filename).resolve(raw);
+ } catch {
+ found = false;
+ }
+ if (!found) {
+ const err = new Error(
+ `${path.basename(filename)} imports ${spec} through a path alias that does not lead to a file.`,
+ );
+ /** @type {any} */ (err).renderCode = 'ERR_FILE_NOT_FOUND';
+ throw err;
+ }
+ }
if (/\.css$/i.test(bare)) {
if (bare.startsWith('.') || path.isAbsolute(bare)) {
const file = path.resolve(dir, bare);
@@ -522,61 +573,34 @@ function pagePlugin(filename) {
}
/**
- * Path aliases from the project's tsconfig.json or jsconfig.json
- * (`compilerOptions.paths`), as jiti aliases: `"@/*": ["./src/*"]` becomes
- * `{"@/": "<root>/src/"}`.
- * @returns {Record<string, string>}
+ * The project's path aliases (`compilerOptions.paths` in tsconfig.json or
+ * jsconfig.json), matched by TypeScript's rules (see ts-paths.mjs).
*/
-function projectAliases() {
- /** @type {Record<string, string>} */
- const alias = {};
- for (const name of ['tsconfig.json', 'jsconfig.json']) {
- const file = path.join(root, name);
- if (!fs.existsSync(file)) continue;
- /** @type {any} */
- let config;
- try {
- // Allow the comments and trailing commas these files often carry.
- const text = fs
- .readFileSync(file, 'utf8')
- .replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, str) => str ?? '')
- .replace(/,(\s*[}\]])/g, '$1');
- config = JSON.parse(text);
- } catch {
- continue;
- }
- const options = config?.compilerOptions ?? {};
- const baseDir = path.resolve(root, typeof options.baseUrl === 'string' ? options.baseUrl : '.');
- for (const [key, targets] of Object.entries(options.paths ?? {})) {
- const target = Array.isArray(targets) ? targets[0] : undefined;
- if (typeof target !== 'string') continue;
- if (key.endsWith('/*') && target.endsWith('/*')) {
- alias[key.slice(0, -1)] = `${path.resolve(baseDir, target.slice(0, -2))}/`;
- } else if (!key.includes('*') && !target.includes('*')) {
- alias[key] = path.resolve(baseDir, target);
- }
- }
- break;
- }
- return alias;
-}
-
-const ALIASES = projectAliases();
+const PATHS = readPathsIn(root) ?? [];
/** @param {string} spec whether a specifier goes through a project alias */
-const isAliased = spec =>
- Object.keys(ALIASES).some(key => (key.endsWith('/') ? spec.startsWith(key) : spec === key));
-
-/** @param {string} spec a specifier through a project alias, as an absolute path */
-const resolveAlias = spec => {
- for (const [key, target] of Object.entries(ALIASES)) {
- if (key.endsWith('/') ? spec.startsWith(key) : spec === key) {
- return key.endsWith('/') ? target + spec.slice(key.length) : target;
- }
- }
- return spec;
+const isAliased = spec => resolvePath(PATHS, spec) !== null;
+
+/**
+ * Whether a specifier that resolves to no file was meant for an alias: it
+ * matches a key with a literal prefix. A catch-all key (`"*"`) matches every
+ * package name too, so an import it cannot place is a package that is not
+ * installed.
+ * @param {string} spec
+ */
+const namesAlias = spec => {
+ const match = matchPath(PATHS, spec);
+ return match !== null && match.pattern.prefix !== '';
};
+/**
+ * A specifier through a project alias, as the absolute path of the first
+ * target that exists; the specifier itself when none does, so it resolves as
+ * a package.
+ * @param {string} spec
+ */
+const resolveAlias = spec => resolvePath(PATHS, spec) ?? spec;
+
/** Packages the page took from the package set, by name: their folders. */
/** @type {Map<string, string>} */
const fromSet = new Map();
@@ -600,6 +624,7 @@ function packageDirOf(file, name) {
const moduleApi = /** @type {any} */ (Module);
+
/** A module at the served Core's folder: what resolves as the Core would. */
const servedParent = served ? new moduleApi(path.join(served.dir, 'package.json')) : null;
if (servedParent && served) {
@@ -675,7 +700,7 @@ const jiti = createJiti(entry, {
extensions: ['.js', '.mjs', '.cjs', '.jsx', '.ts', '.tsx', '.mts', '.cts', '.json'],
moduleCache: true,
interopDefault: true,
- alias: {...SINGLE_COPY_ALIASES, ...ALIASES},
+ alias: SINGLE_COPY_ALIASES,
jsx: {runtime: 'automatic'},
transform(opts) {
const filename = opts.filename ?? '';
@@ -695,6 +720,7 @@ const jiti = createJiti(entry, {
generatorOpts: {retainLines: true},
compact: false,
plugins: [
+ aliasPlugin(),
pagePlugin(filename),
...(source.includes('stylex')
? [
@@ -714,6 +740,31 @@ const jiti = createJiti(entry, {
const rules = /** @type {any} */ (result?.metadata)?.stylex;
if (Array.isArray(rules)) stylexRules.push(...rules);
source = result?.code ?? source;
+ } else if (
+ PATHS.length > 0 &&
+ filename &&
+ !filename.includes(NODE_MODULES) &&
+ /\.(tsx?|jsx?|mjs|cjs|mts|cts)$/.test(filename)
+ ) {
+ const ts = /\.(tsx?|mts|cts)$/.test(filename);
+ const result = transformSync(source, {
+ filename,
+ babelrc: false,
+ configFile: false,
+ sourceType: 'unambiguous',
+ // The options jiti compiles these files with: JSX only in .jsx and
+ // .tsx files (so `<string>value` stays a type assertion), and legacy
+ // decorators.
+ parserOpts: {
+ plugins: /** @type {import('@babel/core').ParserOptions['plugins']} */ (
+ ts ? [...(/\.[cm]?tsx$/.test(filename) ? ['jsx'] : []), 'typescript', 'decorators-legacy'] : ['jsx']
+ ),
+ },
+ generatorOpts: {retainLines: true},
+ compact: false,
+ plugins: [aliasPlugin()],
+ });
+ source = result?.code ?? source;
}
return {code: plain.transform({...opts, source, babel: {...opts.babel, compact: false}})};
},
@@ -743,7 +794,7 @@ function classify(e) {
const missing =
/Cannot find (?:module|package) ['"]([^'"]+)['"]/.exec(message) ??
/Failed to resolve import ['"]([^'"]+)['"]/.exec(message);
- if (missing && (isAliased(missing[1]) || /^[@~#]\/|^#/.test(missing[1]))) {
+ if (missing && (namesAlias(missing[1]) || /^[@~#]\/|^#/.test(missing[1]))) {
return fail(
'ERR_FILE_NOT_FOUND',
`The page imports ${missing[1]} through a path alias that does not lead to a file. Check \`compilerOptions.paths\` in the project's tsconfig.json, or import it by a relative path.`,
diff --git a/packages/cli/foundation/render/ts-paths.mjs b/packages/cli/foundation/render/ts-paths.mjs
new file mode 100644
index 0000000000..699e5c8839
--- /dev/null
+++ b/packages/cli/foundation/render/ts-paths.mjs
@@ -0,0 +1,138 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file A project's `compilerOptions.paths` (tsconfig.json or jsconfig.json),
+ * read and matched by TypeScript's rules, for `astryx experimental render`:
+ * an exact key matches only itself; a key may hold one `*` anywhere, and the
+ * longest matching prefix wins; a target may hold one `*`, which takes what
+ * the key's `*` matched; targets are tried in order, and when none exists the
+ * import resolves as a package. Only bare specifiers are matched. Targets
+ * resolve from `baseUrl` (default: the config's folder).
+ *
+ * @position foundation/render — used by page-worker.mjs and embedded-imports.mjs
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+/**
+ * @typedef {object} PathPattern
+ * @property {string} key - The key as written.
+ * @property {string} prefix - What comes before the key's `*` (all of it, for an exact key).
+ * @property {string} suffix - What comes after the key's `*`.
+ * @property {boolean} wildcard - Whether the key holds a `*`.
+ * @property {string[]} targets - Absolute target patterns, in order.
+ */
+
+/** Extensions an extensionless candidate may stand for, in resolution order. */
+const EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs', '.mts', '.cts', '.json'];
+
+/**
+ * The path patterns of the config in `dir` (tsconfig.json, else
+ * jsconfig.json), or none. Comments and trailing commas are allowed.
+ * @param {string} dir
+ * @returns {PathPattern[] | null} null when neither file is there
+ */
+export function readPathsIn(dir) {
+ for (const name of ['tsconfig.json', 'jsconfig.json']) {
+ const file = path.join(dir, name);
+ if (!fs.existsSync(file)) continue;
+ try {
+ const text = fs
+ .readFileSync(file, 'utf8')
+ .replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, str) => str ?? '')
+ .replace(/,(\s*[}\]])/g, '$1');
+ const options = JSON.parse(text)?.compilerOptions ?? {};
+ const base = path.resolve(dir, typeof options.baseUrl === 'string' ? options.baseUrl : '.');
+ /** @type {PathPattern[]} */
+ const out = [];
+ for (const [key, targets] of Object.entries(options.paths ?? {})) {
+ if (!Array.isArray(targets)) continue;
+ const star = key.indexOf('*');
+ if (star !== key.lastIndexOf('*')) continue;
+ out.push({
+ key,
+ prefix: star === -1 ? key : key.slice(0, star),
+ suffix: star === -1 ? '' : key.slice(star + 1),
+ wildcard: star !== -1,
+ targets: targets
+ .filter(t => typeof t === 'string' && t.indexOf('*') === t.lastIndexOf('*'))
+ .map(t => path.resolve(base, t)),
+ });
+ }
+ return out;
+ } catch {
+ return [];
+ }
+ }
+ return null;
+}
+
+/**
+ * The pattern a specifier matches by TypeScript's rules, and what its `*`
+ * matched: an exact key first, else the wildcard key with the longest prefix.
+ * @param {PathPattern[]} patterns
+ * @param {string} spec
+ * @returns {{pattern: PathPattern, capture: string} | null}
+ */
+export function matchPath(patterns, spec) {
+ // TypeScript applies `paths` only to bare specifiers.
+ if (/^\.{1,2}(\/|$)|^\//.test(spec)) return null;
+ const exact = patterns.find(p => !p.wildcard && p.key === spec);
+ if (exact) return {pattern: exact, capture: ''};
+ /** @type {{pattern: PathPattern, capture: string} | null} */
+ let best = null;
+ for (const p of patterns) {
+ if (!p.wildcard) continue;
+ if (spec.length < p.prefix.length + p.suffix.length) continue;
+ if (!spec.startsWith(p.prefix) || !spec.endsWith(p.suffix)) continue;
+ if (best && best.pattern.prefix.length >= p.prefix.length) continue;
+ best = {pattern: p, capture: spec.slice(p.prefix.length, spec.length - p.suffix.length)};
+ }
+ return best;
+}
+
+/**
+ * The absolute paths a match names, one per target, in order.
+ * @param {{pattern: PathPattern, capture: string}} match
+ * @returns {string[]}
+ */
+export const candidatesOf = match => match.pattern.targets.map(t => t.replace('*', match.capture));
+
+/**
+ * The file a candidate path stands for: itself, with an extension, or its
+ * folder's index; null when none exists.
+ * @param {string} candidate
+ * @returns {string | null}
+ */
+export function existingFile(candidate) {
+ const isFile = (/** @type {string} */ f) => {
+ try {
+ return fs.statSync(f).isFile();
+ } catch {
+ return false;
+ }
+ };
+ if (isFile(candidate)) return candidate;
+ for (const ext of EXTENSIONS) if (isFile(candidate + ext)) return candidate + ext;
+ for (const ext of EXTENSIONS) if (isFile(path.join(candidate, `index${ext}`))) return path.join(candidate, `index${ext}`);
+ return null;
+}
+
+/**
+ * Resolve a specifier through path patterns: the first target that names an
+ * existing file wins.
+ * @param {PathPattern[]} patterns
+ * @param {string} spec
+ * @returns {string | null} the file, or null when the specifier matches no
+ * pattern or no target exists
+ */
+export function resolvePath(patterns, spec) {
+ const match = matchPath(patterns, spec);
+ if (!match) return null;
+ for (const candidate of candidatesOf(match)) {
+ const file = existingFile(candidate);
+ if (file) return file;
+ }
+ return null;
+}
diff --git a/packages/cli/foundation/response/error-codes.doc.mjs b/packages/cli/foundation/response/error-codes.doc.mjs
index e0ff41521d..317a7112d6 100644
--- a/packages/cli/foundation/response/error-codes.doc.mjs
+++ b/packages/cli/foundation/response/error-codes.doc.mjs
@@ -338,13 +338,13 @@ export const doc = {
value: 'ERR_RENDER_NOT_ASTRYX',
stability: 'experimental',
description:
- '`render --reverse` was given a file with no embedded source and no Astryx markup. Nothing was written. Raised only by the experimental render command.',
+ '`render --reverse` was given a file that a render did not write, with no embedded source and no Astryx markup. Nothing was written. Raised only by the experimental render command.',
},
{
value: 'ERR_RENDER_SOURCE_DAMAGED',
stability: 'experimental',
description:
- '`render --reverse` refused the received file, and nothing was written: its embedded source is damaged (not valid, or a file does not match its checksum), lists a path twice, carries a module, stylesheet or JSON file the page does not reach through its own imports, or an image, font or media file whose bytes are not one, or carries a file a render never embeds: a dotfile or dot-folder, anything under node_modules, a package manifest, lockfile or tool configuration, a file a test, story or benchmark runner would run, or any kind but a page module, stylesheet, JSON file or image. Raised only by the experimental render command.',
+ '`render --reverse` refused the received file, and nothing was written: its embedded source was removed (a file a render wrote, with no Astryx components left to rebuild from) or is damaged (not valid, or a file does not match its checksum), lists a path twice, carries a module, stylesheet or JSON file the page does not reach through its own imports, or an image, font or media file whose bytes are not one, or carries a file a render never embeds: a dotfile or dot-folder, anything under node_modules, a package manifest, lockfile or tool configuration, a file a test, story or benchmark runner would run, or any kind but a page module, stylesheet, JSON file or image. Raised only by the experimental render command.',
},
],
};
diff --git a/packages/cli/foundation/response/error-codes.mjs b/packages/cli/foundation/response/error-codes.mjs
index abd6e833d9..684207cfd7 100644
--- a/packages/cli/foundation/response/error-codes.mjs
+++ b/packages/cli/foundation/response/error-codes.mjs
@@ -298,8 +298,9 @@ export const ERROR_CODES = Object.freeze({
*/
ERR_RENDER_FAILED: 'ERR_RENDER_FAILED',
/**
- * `render --reverse` was given an HTML file that holds no Astryx markup and
- * no embedded source, so there is nothing to rebuild. Nothing was written.
+ * `render --reverse` was given an HTML file that a render did not write and
+ * that holds no Astryx markup and no embedded source, so there is nothing
+ * to rebuild. Nothing was written.
*/
ERR_RENDER_NOT_ASTRYX: 'ERR_RENDER_NOT_ASTRYX',
/**