Files
pest/tests/Unit/Plugins/Tia/ViteDepsHelper.php
T
Ben Dailey 8c87eefebf fix(tia): load rolldown from vite/rolldown under Vite+ (#2061)
* fix(tia): load rolldown from vite/rolldown under Vite+

* refactor(tia): call loadRolldown() with its default root

---------

Co-authored-by: Ben Dailey <ben@dev-deb12>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-22 22:09:09 +05:30

839 lines
32 KiB
PHP

<?php
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
function tiaViteHelperPath(): string
{
return dirname(__DIR__, 4).'/bin/pest-tia-vite-deps.mjs';
}
function tiaJson(mixed $value): string
{
return json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
}
function tiaStripFixtures(): array
{
return [
'plain-object' => ['{"a":1,"b":2}', ['a' => 1, 'b' => 2]],
'plain-array' => ['[1,2,3]', [1, 2, 3]],
'nested' => ['{"a":{"b":[1,2]}}', ['a' => ['b' => [1, 2]]]],
'empty-object' => ['{}', []],
'empty-array' => ['[]', []],
'line-comment-own-line' => ["{\n// comment\n\"a\":1\n}", ['a' => 1]],
'line-comment-trailing' => ["{\"a\":1 // trailing\n}", ['a' => 1]],
'leading-line-comments' => ["// a\n// b\n{\"a\":1}", ['a' => 1]],
'line-comment-eof-no-newline' => ['{"a":1}// end', ['a' => 1]],
'block-comment-leading' => ['{/* c */"a":1}', ['a' => 1]],
'block-comment-inline' => ['{"a":1,/* c */"b":2}', ['a' => 1, 'b' => 2]],
'block-comment-multiline' => ["{\n/* line1\nline2 */\n\"a\":1\n}", ['a' => 1]],
'block-comment-eof' => ['{"a":1}/* end */', ['a' => 1]],
'jsdoc-style-block' => ["{\n/**\n * doc\n */\n\"a\":1\n}", ['a' => 1]],
'block-contains-double-slash' => ['{/* // inside */"a":1}', ['a' => 1]],
'line-then-block' => ["{// l\n/* b */\"a\":1}", ['a' => 1]],
'comment-with-quotes' => ['{/* "b":2 */"a":1}', ['a' => 1]],
'comment-with-braces-commas' => ['{"a":1 /* },{ */,"b":2}', ['a' => 1, 'b' => 2]],
'trailing-comma-object' => ['{"a":1,}', ['a' => 1]],
'trailing-comma-array' => ['[1,2,]', [1, 2]],
'trailing-comma-nested' => ['{"a":[1,2,],"b":{"c":3,},}', ['a' => [1, 2], 'b' => ['c' => 3]]],
'trailing-comma-newline' => ["{\n\"a\":1,\n}", ['a' => 1]],
'trailing-comma-then-block' => ['{"a":1, /* x */ }', ['a' => 1]],
'trailing-comma-then-line' => ["{\"a\":1, // x\n}", ['a' => 1]],
'crlf-line-comment' => ["{\r\n\"a\":1 // c\r\n}", ['a' => 1]],
'tabs-whitespace' => ["{\n\t\"a\":\t1\n}", ['a' => 1]],
'url-in-string' => [tiaJson(['u' => 'https://example.com//x']), ['u' => 'https://example.com//x']],
'glob-in-string' => [tiaJson(['g' => 'resources/js/**/*.ts']), ['g' => 'resources/js/**/*.ts']],
'path-alias-in-string' => [tiaJson(['p' => '@/*']), ['p' => '@/*']],
'block-open-in-string' => [tiaJson(['s' => 'a/*b']), ['s' => 'a/*b']],
'block-close-in-string' => [tiaJson(['s' => 'b*/c']), ['s' => 'b*/c']],
'block-both-in-string' => [tiaJson(['s' => 'x/*y*/z']), ['s' => 'x/*y*/z']],
'star-in-string' => [tiaJson(['s' => '5 * 3']), ['s' => '5 * 3']],
'single-slashes-in-string' => [tiaJson(['s' => 'a/b/c']), ['s' => 'a/b/c']],
'escaped-quote-in-string' => [tiaJson(['s' => 'a"b']), ['s' => 'a"b']],
'escaped-backslash-in-string' => [tiaJson(['s' => 'a\\']), ['s' => 'a\\']],
'backslash-then-slash' => [tiaJson(['s' => 'a\\/b']), ['s' => 'a\\/b']],
'newline-escape-in-string' => [tiaJson(['s' => "a\nb"]), ['s' => "a\nb"]],
'unicode-in-string' => [tiaJson(['s' => 'café ☕']), ['s' => 'café ☕']],
'block-secret' => ['{"a":1/*SECRET*/}', ['a' => 1]],
];
}
function tiaStripResults(): array
{
static $cache = null;
if ($cache !== null) {
return $cache;
}
$payload = [];
foreach (tiaStripFixtures() as $name => [$raw]) {
$payload[] = ['name' => $name, 'raw' => $raw];
}
$inputFile = tempnam(sys_get_temp_dir(), 'tia-strip-');
file_put_contents($inputFile, json_encode($payload));
$helper = str_replace('\\', '/', tiaViteHelperPath());
$input = str_replace('\\', '/', $inputFile);
$script = <<<JS
import { stripJsonComments } from '{$helper}'
import { readFileSync } from 'node:fs'
const cases = JSON.parse(readFileSync('{$input}', 'utf8'))
const out = {}
for (const c of cases) {
const stripped = stripJsonComments(c.raw)
const entry = { stripped }
try { entry.parsed = JSON.parse(stripped); entry.ok = true }
catch (e) { entry.ok = false; entry.error = String(e && e.message ? e.message : e) }
out[c.name] = entry
}
process.stdout.write(JSON.stringify(out))
JS;
$process = new Process(['node', '--input-type=module', '-e', $script]);
$process->mustRun();
@unlink($inputFile);
return $cache = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
}
function tiaAliasFixtures(): array
{
$config = fn (array $compilerOptions): array => ['tsconfig.json' => tiaJson(['compilerOptions' => $compilerOptions])];
return [
'basic' => [
$config(['baseUrl' => '.', 'paths' => ['@/*' => ['./resources/js/*']]]),
['@' => 'resources/js'],
],
'multiple-aliases' => [
$config(['baseUrl' => '.', 'paths' => ['@/*' => ['./resources/js/*'], '~/*' => ['./src/*']]]),
['@' => 'resources/js', '~' => 'src'],
],
'default-baseUrl' => [
$config(['paths' => ['@/*' => ['./resources/js/*']]]),
['@' => 'resources/js'],
],
'baseUrl-subdir' => [
$config(['baseUrl' => 'src', 'paths' => ['@/*' => ['lib/*']]]),
['@' => 'src/lib'],
],
'jsconfig-fallback' => [
['jsconfig.json' => tiaJson(['compilerOptions' => ['baseUrl' => '.', 'paths' => ['@/*' => ['./resources/js/*']]]])],
['@' => 'resources/js'],
],
'first-target-wins' => [
$config(['baseUrl' => '.', 'paths' => ['@/*' => ['./a/*', './b/*']]]),
['@' => 'a'],
],
'multiple-keys-mixed' => [
$config(['baseUrl' => '.', 'paths' => [
'@/*' => ['./resources/js/*'],
'bad' => ['./x/*'],
'~/*' => ['./nope'],
]]),
['@' => 'resources/js'],
],
'no-paths' => [
$config(['baseUrl' => '.']),
[],
],
'no-compiler-options' => [
['tsconfig.json' => '{}'],
[],
],
'key-without-glob' => [
$config(['baseUrl' => '.', 'paths' => ['@' => ['./resources/js/*']]]),
[],
],
'target-without-glob' => [
$config(['baseUrl' => '.', 'paths' => ['@/*' => ['./resources/js']]]),
[],
],
'target-not-array' => [
$config(['baseUrl' => '.', 'paths' => ['@/*' => './resources/js/*']]),
[],
],
'target-empty-array' => [
$config(['baseUrl' => '.', 'paths' => ['@/*' => []]]),
[],
],
'commented-tsconfig' => [
['tsconfig.json' => <<<'JSON'
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more. */
"target": "ESNext", // language target
"baseUrl": ".",
"paths": {
"@/*": ["./resources/js/*"],
},
},
}
JSON],
['@' => 'resources/js'],
],
'trailing-comma-paths' => [
['tsconfig.json' => '{"compilerOptions":{"baseUrl":".","paths":{"@/*":["./resources/js/*",],},},}'],
['@' => 'resources/js'],
],
'malformed-json' => [
['tsconfig.json' => '{ this is not json'],
[],
],
'missing-config' => [
[],
[],
],
'tsconfig-precedence' => [
[
'tsconfig.json' => tiaJson(['compilerOptions' => ['baseUrl' => '.', 'paths' => ['@/*' => ['./a/*']]]]),
'jsconfig.json' => tiaJson(['compilerOptions' => ['baseUrl' => '.', 'paths' => ['@/*' => ['./b/*']]]]),
],
['@' => 'a'],
],
];
}
function tiaAliasResults(): array
{
static $cache = null;
if ($cache !== null) {
return $cache;
}
$roots = [];
$written = [];
$payload = [];
foreach (tiaAliasFixtures() as $name => [$files]) {
$root = sys_get_temp_dir().'/pest-tia-'.bin2hex(random_bytes(6));
mkdir($root, 0755, true);
foreach ($files as $fname => $content) {
file_put_contents($root.'/'.$fname, $content);
$written[] = $root.'/'.$fname;
}
$root = str_replace('\\', '/', $root);
$roots[$name] = $root;
$payload[] = ['name' => $name, 'root' => $root];
}
$inputFile = tempnam(sys_get_temp_dir(), 'tia-alias-');
file_put_contents($inputFile, json_encode($payload));
$helper = str_replace('\\', '/', tiaViteHelperPath());
$input = str_replace('\\', '/', $inputFile);
$script = <<<JS
import { loadAliasFromTsconfig } from '{$helper}'
import { readFileSync } from 'node:fs'
const cases = JSON.parse(readFileSync('{$input}', 'utf8'))
const out = {}
for (const c of cases) out[c.name] = await loadAliasFromTsconfig(c.root)
process.stdout.write(JSON.stringify(out))
JS;
$process = new Process(['node', '--input-type=module', '-e', $script]);
$process->mustRun();
$aliases = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
@unlink($inputFile);
foreach ($written as $f) {
@unlink($f);
}
foreach ($roots as $r) {
@rmdir($r);
}
return $cache = ['roots' => $roots, 'aliases' => $aliases];
}
function tiaViteAliasFixtures(): array
{
return [
'root-slash-literal' => [
['vite.config.js' => "export default { resolve: { alias: { '@': '/resources/js' } } }"],
['@' => 'resources/js'],
],
'path-resolve' => [
['vite.config.ts' => "export default { resolve: { alias: { '@': path.resolve(__dirname, 'resources/js') } } }"],
['@' => 'resources/js'],
],
'file-url' => [
['vite.config.mjs' => "export default { resolve: { alias: { '@': fileURLToPath(new URL('./resources/js', import.meta.url)) } } }"],
['@' => 'resources/js'],
],
'tilde-alias' => [
['vite.config.js' => "export default { resolve: { alias: { '~': path.resolve(__dirname, 'resources') } } }"],
['~' => 'resources'],
],
'multiple-aliases' => [
['vite.config.js' => "export default { resolve: { alias: { '@': '/resources/js', '@css': '/resources/css' } } }"],
['@' => 'resources/js', '@css' => 'resources/css'],
],
'laravel-plugin-default' => [
[
'vite.config.js' => "import laravel from 'laravel-vite-plugin'\nexport default { plugins: [laravel({ input: ['resources/js/app.ts'] })] }",
'package.json' => tiaJson(['devDependencies' => ['laravel-vite-plugin' => '^1.0']]),
],
['@' => 'resources/js'],
],
'no-alias-no-plugin' => [
[
'vite.config.js' => 'export default { plugins: [] }',
'package.json' => tiaJson(['devDependencies' => ['vue' => '^3.0']]),
],
[],
],
'no-config' => [
[],
[],
],
];
}
function tiaViteAliasResults(): array
{
static $cache = null;
if ($cache !== null) {
return $cache;
}
$roots = [];
$written = [];
$payload = [];
foreach (tiaViteAliasFixtures() as $name => [$files]) {
$root = sys_get_temp_dir().'/pest-tia-vite-'.bin2hex(random_bytes(6));
mkdir($root, 0755, true);
foreach ($files as $fname => $content) {
file_put_contents($root.'/'.$fname, $content);
$written[] = $root.'/'.$fname;
}
$root = str_replace('\\', '/', $root);
$roots[$name] = $root;
$payload[] = ['name' => $name, 'root' => $root];
}
$inputFile = tempnam(sys_get_temp_dir(), 'tia-vite-alias-');
file_put_contents($inputFile, json_encode($payload));
$helper = str_replace('\\', '/', tiaViteHelperPath());
$input = str_replace('\\', '/', $inputFile);
$script = <<<JS
import { loadAliasFromViteConfig } from '{$helper}'
import { readFileSync } from 'node:fs'
const cases = JSON.parse(readFileSync('{$input}', 'utf8'))
const out = {}
for (const c of cases) out[c.name] = await loadAliasFromViteConfig(c.root)
process.stdout.write(JSON.stringify(out))
JS;
$process = new Process(['node', '--input-type=module', '-e', $script]);
$process->mustRun();
$aliases = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
@unlink($inputFile);
foreach ($written as $f) {
@unlink($f);
}
foreach ($roots as $r) {
@rmdir($r);
}
return $cache = ['roots' => $roots, 'aliases' => $aliases];
}
function tiaViteCasingFixtures(): array
{
return [
'exact' => ['resources/js/pages', true],
'wrong leaf' => ['resources/js/Pages', false],
'wrong parent' => ['Resources/js/pages', false],
'absent' => ['assets/js/pages', false],
];
}
function tiaViteCasingResults(): array
{
static $cache = null;
if ($cache !== null) {
return $cache;
}
$root = sys_get_temp_dir().'/pest-tia-vite-casing-'.bin2hex(random_bytes(6));
mkdir($root.'/resources/js/pages', 0755, true);
file_put_contents($root.'/resources/js/pages/Dashboard.vue', "<template>ok</template>\n");
$helper = str_replace('\\', '/', tiaViteHelperPath());
$normalized = str_replace('\\', '/', $root);
$payload = [];
foreach (tiaViteCasingFixtures() as $name => [$candidate]) {
$payload[] = ['name' => $name, 'candidate' => $candidate];
}
$inputFile = tempnam(sys_get_temp_dir(), 'tia-vite-casing-');
file_put_contents($inputFile, json_encode($payload));
$input = str_replace('\\', '/', $inputFile);
$script = <<<JS
import { matchesDiskCasing } from '{$helper}'
import { readFileSync } from 'node:fs'
const cases = JSON.parse(readFileSync('{$input}', 'utf8'))
const out = {}
for (const c of cases) out[c.name] = await matchesDiskCasing('{$normalized}', c.candidate)
process.stdout.write(JSON.stringify(out))
JS;
$process = new Process(['node', '--input-type=module', '-e', $script]);
$process->mustRun();
$results = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
@unlink($inputFile);
@unlink($root.'/resources/js/pages/Dashboard.vue');
@rmdir($root.'/resources/js/pages');
@rmdir($root.'/resources/js');
@rmdir($root.'/resources');
@rmdir($root);
return $cache = $results;
}
function tiaSfcFixtures(): array
{
return [
'script-setup' => [
"<script setup>\nimport A from '@/A.vue'\n</script>\n<template><A /></template>",
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
],
'plain-script-with-default' => [
"<script>\nimport A from '@/A.vue'\nexport default { components: { A } }\n</script>",
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
],
'typescript-lang' => [
"<script setup lang=\"ts\">\nimport type { Foo } from '@/types'\nimport B from '@/B.vue'\n</script>",
['imports' => ['@/types', '@/B.vue'], 'moduleType' => 'ts'],
],
'lang-tsx' => [
"<script setup lang=\"tsx\">\nimport C from '@/C.vue'\n</script>",
['imports' => ['@/C.vue'], 'moduleType' => 'ts'],
],
'lang-unquoted' => [
"<script setup lang=ts>\nimport D from '@/D.vue'\n</script>",
['imports' => ['@/D.vue'], 'moduleType' => 'ts'],
],
'both-script-blocks' => [
"<script>\nimport A from '@/A.vue'\nexport default {}\n</script>\n<script setup>\nimport B from '@/B.vue'\n</script>",
['imports' => ['@/A.vue', '@/B.vue'], 'moduleType' => 'js'],
],
'template-only' => [
'<template><div>hello</div></template>',
['imports' => [], 'moduleType' => 'js'],
],
'style-block-ignored' => [
"<script setup>\nimport A from '@/A.vue'\n</script>\n<style scoped>\n.a { color: red }\n</style>",
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
],
'dynamic-import' => [
"<script setup>\nconst C = () => import('@/Lazy.vue')\n</script>",
['imports' => ['@/Lazy.vue'], 'moduleType' => 'js'],
],
'svelte-component' => [
"<script>\nimport A from './A.svelte'\n</script>\n<h1>hi</h1>",
['imports' => ['./A.svelte'], 'moduleType' => 'js'],
],
'no-script-at-all' => [
'<div>plain markup</div>',
['imports' => [], 'moduleType' => 'js'],
],
'default-export-in-line-comment' => [
"<script setup>\n// export default is generated by Vue\nimport A from '@/A.vue'\n</script>",
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
],
'default-export-in-block-comment' => [
"<script setup>\n/* export default {} */\nimport A from '@/A.vue'\n</script>",
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
],
'default-export-in-string' => [
"<script setup>\nimport A from '@/A.vue'\nconst hint = 'export default'\n</script>",
['imports' => ['@/A.vue'], 'moduleType' => 'js'],
],
'generic-attribute' => [
"<script setup lang=\"ts\" generic=\"T extends Record<string, unknown>\">\nimport E from '@/E.vue'\n</script>",
['imports' => ['@/E.vue'], 'moduleType' => 'ts'],
],
'generic-attribute-single-quoted' => [
"<script setup lang='ts' generic='T extends Array<string>'>\nimport F from '@/F.vue'\n</script>",
['imports' => ['@/F.vue'], 'moduleType' => 'ts'],
],
'generic-attribute-before-lang' => [
"<script setup generic=\"K extends string, V extends Map<K, number>\" lang=\"ts\">\nimport G from '@/G.vue'\n</script>",
['imports' => ['@/G.vue'], 'moduleType' => 'ts'],
],
];
}
function tiaSfcResults(): array
{
static $cache = null;
if ($cache !== null) {
return $cache;
}
$payload = [];
foreach (tiaSfcFixtures() as $name => [$raw]) {
$payload[] = ['name' => $name, 'raw' => $raw];
}
$inputFile = tempnam(sys_get_temp_dir(), 'tia-sfc-');
file_put_contents($inputFile, json_encode($payload));
$helper = str_replace('\\', '/', tiaViteHelperPath());
$input = str_replace('\\', '/', $inputFile);
$script = <<<JS
import { extractSfcScript } from '{$helper}'
import { readFileSync } from 'node:fs'
const cases = JSON.parse(readFileSync('{$input}', 'utf8'))
const out = {}
for (const c of cases) {
const r = extractSfcScript(c.raw)
const imports = [...r.code.matchAll(/(?:from|import)\s*\(?\s*['"]([^'"]+)['"]/g)].map((m) => m[1])
out[c.name] = { code: r.code, moduleType: r.moduleType, imports }
}
process.stdout.write(JSON.stringify(out))
JS;
$process = new Process(['node', '--input-type=module', '-e', $script]);
$process->mustRun();
@unlink($inputFile);
return $cache = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
}
function tiaRolldownPackageDir(): ?string
{
$locate = fn (array $command, ?string $cwd = null): ?string => ($process = new Process($command, $cwd))->run() === 0
? (trim($process->getOutput()) ?: null)
: null;
$paths = [dirname(__DIR__, 4)];
if (($global = $locate(['npm', 'root', '-g'])) !== null) {
$paths[] = $global;
}
$manifest = $locate(['node', '-p', "require.resolve('rolldown/package.json', { paths: process.argv.slice(1) })", ...$paths]);
return $manifest === null ? null : dirname($manifest);
}
function tiaBuildOptionResults(): array
{
static $cache = null;
if ($cache !== null) {
return $cache;
}
$helper = str_replace('\\', '/', tiaViteHelperPath());
$script = <<<JS
import { stubAsset, TRANSFORM_OPTIONS } from '{$helper}'
const stubs = {}
for (const id of ['/app/resources/css/app.css', '/app/logo.svg', '/app/Page.vue', '/app/util.ts']) {
stubs[id] = stubAsset(id)
}
process.stdout.write(JSON.stringify({ stubs, transform: TRANSFORM_OPTIONS }))
JS;
$process = new Process(['node', '--input-type=module', '-e', $script]);
$process->mustRun();
return $cache = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
}
function tiaLoadRolldownResults(): array
{
static $cache = null;
if ($cache !== null) {
return $cache;
}
$vitePlus = sys_get_temp_dir().'/pest-tia-vite-plus-'.bin2hex(random_bytes(6));
$missing = sys_get_temp_dir().'/pest-tia-no-rolldown-'.bin2hex(random_bytes(6));
mkdir($vitePlus.'/node_modules/vite', 0755, true);
mkdir($missing, 0755, true);
file_put_contents($vitePlus.'/package.json', '{}');
file_put_contents($vitePlus.'/node_modules/vite/package.json', tiaJson([
'name' => 'vite',
'type' => 'module',
'exports' => ['./package.json' => './package.json', './rolldown' => './rolldown.mjs'],
]));
file_put_contents($vitePlus.'/node_modules/vite/rolldown.mjs', "export const rolldown = 'vite-plus-stub'\n");
file_put_contents($missing.'/package.json', '{}');
$helper = str_replace('\\', '/', tiaViteHelperPath());
$roots = tiaJson(['vite-plus' => str_replace('\\', '/', $vitePlus), 'missing' => str_replace('\\', '/', $missing)]);
$script = <<<JS
import { loadRolldown } from '{$helper}'
const out = {}
for (const [name, root] of Object.entries({$roots})) {
const loaded = await loadRolldown(root)
out[name] = loaded === null ? null : { rolldown: loaded.rolldown }
}
process.stdout.write(JSON.stringify(out))
JS;
$process = new Process(['node', '--input-type=module', '-e', $script]);
$process->run();
foreach (['node_modules/vite/rolldown.mjs', 'node_modules/vite/package.json', 'package.json'] as $file) {
@unlink($vitePlus.'/'.$file);
}
foreach (['node_modules/vite', 'node_modules', ''] as $dir) {
@rmdir($vitePlus.'/'.$dir);
}
@unlink($missing.'/package.json');
@rmdir($missing);
if (! $process->isSuccessful()) {
throw new ProcessFailedException($process);
}
return $cache = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
}
beforeEach(function (): void {
if ((new ExecutableFinder)->find('node') === null) {
$this->markTestSkipped('node is not available.');
}
});
it('strips JSONC down to something JSON.parse accepts', function (string $name): void {
$result = tiaStripResults()[$name];
[, $expected] = tiaStripFixtures()[$name];
expect($result['ok'])->toBeTrue(
"[{$name}] did not parse after stripping: ".($result['error'] ?? 'unknown').PHP_EOL.
'stripped: '.$result['stripped'],
)
->and($result['parsed'])->toEqual($expected);
})->with(array_keys(tiaStripFixtures()));
it('never touches comment-looking sequences inside string values', function (): void {
expect(tiaStripResults()['url-in-string']['stripped'])->toContain('https://example.com//x')
->and(tiaStripResults()['glob-in-string']['stripped'])->toContain('resources/js/**/*.ts')
->and(tiaStripResults()['block-both-in-string']['stripped'])->toContain('x/*y*/z');
});
it('removes the comment body entirely', function (): void {
expect(tiaStripResults()['block-secret']['stripped'])->not->toContain('SECRET');
});
it('builds the expected alias map from a tsconfig', function (string $name): void {
$results = tiaAliasResults();
[, $expectedRelative] = tiaAliasFixtures()[$name];
$root = $results['roots'][$name];
$expected = [];
foreach ($expectedRelative as $key => $relative) {
$expected[$key] = $root.'/'.$relative;
}
expect($results['aliases'][$name])->toEqual($expected);
})->with(array_keys(tiaAliasFixtures()));
it('builds the expected alias map from a vite config', function (string $name): void {
$results = tiaViteAliasResults();
[, $expectedRelative] = tiaViteAliasFixtures()[$name];
$root = $results['roots'][$name];
$expected = [];
foreach ($expectedRelative as $key => $relative) {
$expected[$key] = $root.'/'.$relative;
}
expect($results['aliases'][$name])->toEqual($expected);
})->with(array_keys(tiaViteAliasFixtures()));
it('accepts a page directory candidate only when it matches the casing on disk', function (string $name): void {
[, $expected] = tiaViteCasingFixtures()[$name];
expect(tiaViteCasingResults()[$name])->toBe($expected);
})->with(array_keys(tiaViteCasingFixtures()));
it('keeps every import a single file component declares', function (string $name): void {
[, $expected] = tiaSfcFixtures()[$name];
expect(tiaSfcResults()[$name]['imports'])->toEqual($expected['imports']);
})->with(array_keys(tiaSfcFixtures()));
it('reports the script block language so the parser matches it', function (string $name): void {
[, $expected] = tiaSfcFixtures()[$name];
expect(tiaSfcResults()[$name]['moduleType'])->toBe($expected['moduleType']);
})->with(array_keys(tiaSfcFixtures()));
it('always leaves a default export for importers to resolve against', function (string $name): void {
expect(tiaSfcResults()[$name]['code'])->toMatch('/export\s+default\b/');
})->with(array_keys(tiaSfcFixtures()));
it('ends the opening script tag after a quoted attribute that holds a closing angle bracket', function (string $name): void {
expect(tiaSfcResults()[$name]['code'])->toStartWith("\nimport ");
})->with(['generic-attribute', 'generic-attribute-single-quoted', 'generic-attribute-before-lang']);
it('does not add a second default export when the block already has one', function (): void {
preg_match_all('/export\s+default\b/', tiaSfcResults()['plain-script-with-default']['code'], $matches);
expect($matches[0])->toHaveCount(1);
});
it('drops template and style markup that the parser would reject', function (): void {
expect(tiaSfcResults()['style-block-ignored']['code'])->not->toContain('<style')
->and(tiaSfcResults()['style-block-ignored']['code'])->not->toContain('color: red')
->and(tiaSfcResults()['script-setup']['code'])->not->toContain('<template');
});
it('stubs assets as JS modules so rolldown does not reject them as CSS', function (string $id): void {
expect(tiaBuildOptionResults()['stubs'][$id])->toBe([
'code' => 'export default null',
'moduleType' => 'js',
'moduleSideEffects' => false,
]);
})->with(['/app/resources/css/app.css', '/app/logo.svg']);
it('leaves source modules for the other loaders', function (string $id): void {
expect(tiaBuildOptionResults()['stubs'][$id])->toBeNull();
})->with(['/app/Page.vue', '/app/util.ts']);
it('keeps value imports that only a template uses through the TypeScript transform', function (): void {
expect(tiaBuildOptionResults()['transform']['typescript']['onlyRemoveTypeImports'])->toBeTrue();
});
it('ignores a default export that only appears in a comment or string', function (string $name): void {
preg_match_all('/export\s+default\b/', tiaSfcResults()[$name]['code'], $matches);
expect(tiaSfcResults()[$name]['code'])->toEndWith("\nexport default {}\n")
->and($matches[0])->toHaveCount(2);
})->with(['default-export-in-line-comment', 'default-export-in-block-comment', 'default-export-in-string']);
it('loads the rolldown that Vite+ exposes as vite/rolldown', function (): void {
expect(tiaLoadRolldownResults()['vite-plus'])->toBe(['rolldown' => 'vite-plus-stub']);
});
it('finds no rolldown when neither rolldown nor vite/rolldown resolves', function (): void {
expect(tiaLoadRolldownResults()['missing'])->toBeNull();
});
it('bundles a script setup component that mentions export default in a comment', function (): void {
$rolldown = tiaRolldownPackageDir();
if ($rolldown === null) {
$this->markTestSkipped('rolldown is not resolvable.');
}
$root = sys_get_temp_dir().'/pest-tia-rolldown-'.bin2hex(random_bytes(6));
mkdir($root.'/resources/js/pages', 0755, true);
mkdir($root.'/resources/js/components', 0755, true);
mkdir($root.'/node_modules', 0755, true);
$root = realpath($root);
symlink($rolldown, $root.'/node_modules/rolldown');
file_put_contents($root.'/package.json', '{}');
file_put_contents($root.'/resources/js/pages/Dashboard.vue', <<<'VUE'
<script setup>
import Widget from '../components/Widget.vue'
</script>
<template><Widget /></template>
VUE);
file_put_contents($root.'/resources/js/components/Widget.vue', <<<'VUE'
<script setup>
// export default is generated by Vue
import { format } from './format.js'
</script>
<template>{{ format(1) }}</template>
VUE);
file_put_contents($root.'/resources/js/components/format.js', "export const format = (v) => String(v)\n");
$process = new Process(['node', tiaViteHelperPath(), $root]);
$process->run();
unlink($root.'/node_modules/rolldown');
foreach (['resources/js/pages/Dashboard.vue', 'resources/js/components/Widget.vue', 'resources/js/components/format.js', 'package.json'] as $file) {
@unlink($root.'/'.$file);
}
foreach (['node_modules', 'resources/js/pages', 'resources/js/components', 'resources/js', 'resources', ''] as $dir) {
@rmdir($root.'/'.$dir);
}
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
->and(json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR))->toMatchArray([
'resources/js/components/Widget.vue' => ['Dashboard'],
'resources/js/components/format.js' => ['Dashboard'],
]);
});
it('bundles a generic component whose script tag holds a closing angle bracket', function (): void {
$rolldown = tiaRolldownPackageDir();
if ($rolldown === null) {
$this->markTestSkipped('rolldown is not resolvable.');
}
$root = sys_get_temp_dir().'/pest-tia-rolldown-generic-'.bin2hex(random_bytes(6));
mkdir($root.'/resources/js/pages', 0755, true);
mkdir($root.'/resources/js/components', 0755, true);
mkdir($root.'/node_modules', 0755, true);
$root = realpath($root);
symlink($rolldown, $root.'/node_modules/rolldown');
file_put_contents($root.'/package.json', '{}');
file_put_contents($root.'/resources/js/pages/Items.vue', <<<'VUE'
<script setup lang="ts">
import SortableList from '../components/SortableList.vue'
</script>
<template><SortableList :items="[]" /></template>
VUE);
file_put_contents($root.'/resources/js/components/SortableList.vue', <<<'VUE'
<script setup lang="ts" generic="T extends Record<string, unknown>">
import { label } from './label.ts'
defineProps<{ items: T[] }>()
</script>
<template><li v-for="item in items">{{ label(item) }}</li></template>
VUE);
file_put_contents($root.'/resources/js/components/label.ts', "export const label = (v: unknown): string => String(v)\n");
$process = new Process(['node', tiaViteHelperPath(), $root]);
$process->run();
unlink($root.'/node_modules/rolldown');
foreach (['resources/js/pages/Items.vue', 'resources/js/components/SortableList.vue', 'resources/js/components/label.ts', 'package.json'] as $file) {
@unlink($root.'/'.$file);
}
foreach (['node_modules', 'resources/js/pages', 'resources/js/components', 'resources/js', 'resources', ''] as $dir) {
@rmdir($root.'/'.$dir);
}
expect($process->getExitCode())->toBe(0, $process->getErrorOutput())
->and(json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR))->toMatchArray([
'resources/js/components/SortableList.vue' => ['Items'],
'resources/js/components/label.ts' => ['Items'],
]);
});