slicejs-cli 4.4.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/client.js +192 -82
  2. package/commands/Print.js +158 -164
  3. package/commands/build/build.js +27 -1
  4. package/commands/buildProduction/buildProduction.js +42 -71
  5. package/commands/bundle/bundle.js +65 -60
  6. package/commands/docs/agents.js +260 -0
  7. package/commands/docs/events.js +365 -0
  8. package/commands/docs/index.js +123 -0
  9. package/commands/doctor/doctor.js +99 -12
  10. package/commands/export/checkExport.js +163 -0
  11. package/commands/export/clientRedirects.js +72 -0
  12. package/commands/export/copyDist.js +180 -0
  13. package/commands/export/export.js +236 -0
  14. package/commands/export/files.js +33 -0
  15. package/commands/export/hosts/cloudflare.js +48 -0
  16. package/commands/export/hosts/github.js +31 -0
  17. package/commands/export/hosts/index.js +69 -0
  18. package/commands/export/hosts/netlify.js +42 -0
  19. package/commands/export/hosts/nginx.js +73 -0
  20. package/commands/export/hosts/none.js +23 -0
  21. package/commands/export/hosts/s3.js +24 -0
  22. package/commands/export/hosts/shared.js +62 -0
  23. package/commands/export/hosts/vercel.js +69 -0
  24. package/commands/export/outDir.js +91 -0
  25. package/commands/export/prerender.js +121 -0
  26. package/commands/getComponent/getComponent.js +44 -40
  27. package/commands/init/init.js +32 -22
  28. package/commands/lint/lint.js +2 -2
  29. package/commands/lint/types.js +1 -1
  30. package/commands/listComponents/listComponents.js +205 -172
  31. package/commands/seo/check.js +7 -4
  32. package/commands/seo/images.js +77 -22
  33. package/commands/seo/sitemap.js +6 -3
  34. package/commands/seo/support.js +62 -0
  35. package/commands/setup/lint.js +1 -1
  36. package/commands/skill/skill.js +2 -2
  37. package/commands/startServer/startServer.js +60 -21
  38. package/commands/startServer/watchServer.js +3 -3
  39. package/commands/translator/check.js +32 -0
  40. package/commands/translator/init.js +125 -0
  41. package/commands/translator/scan.js +444 -0
  42. package/commands/typecheck/typecheck.js +2 -2
  43. package/commands/types/types.js +22 -3
  44. package/commands/utils/VersionChecker.js +14 -14
  45. package/commands/utils/bundling/BundleGenerator.js +45 -27
  46. package/commands/utils/bundling/DependencyAnalyzer.js +1007 -976
  47. package/commands/utils/componentCatalog.js +120 -0
  48. package/commands/utils/publicEnv.js +74 -0
  49. package/commands/utils/sliceConfigSchema.js +34 -0
  50. package/commands/utils/updateManager.js +12 -12
  51. package/package.json +22 -23
@@ -0,0 +1,123 @@
1
+ import fs from 'fs-extra';
2
+ import os from 'os';
3
+ import path from 'path';
4
+
5
+ import Print from '../Print.js';
6
+ import { generateTypesFile, runGenerateTypes } from '../types/types.js';
7
+ import { scanComponentCatalog, loadProjectConfig } from '../utils/componentCatalog.js';
8
+ import { checkAgents, generateAgents } from './agents.js';
9
+ import { checkEventDocs, generateEventDocs } from './events.js';
10
+
11
+ const TARGETS = new Set(['all', 'agents', 'types', 'events']);
12
+
13
+ function normalizeTarget(target) {
14
+ const value = String(target || 'all').toLowerCase();
15
+ if (!TARGETS.has(value)) {
16
+ throw new Error(`Unknown docs target "${target}". Use all, agents, types, or events.`);
17
+ }
18
+ return value;
19
+ }
20
+
21
+ async function loadCatalog(projectRoot) {
22
+ const config = await loadProjectConfig(projectRoot);
23
+ return scanComponentCatalog({ projectRoot, config });
24
+ }
25
+
26
+ // Automatic generation (dev/component commands) must not take over a project
27
+ // that keeps a hand-written AGENTS.md and has not opted into the scaffold.
28
+ export async function hasDocumentationScaffold(projectRoot) {
29
+ const rootAgents = path.join(projectRoot, 'AGENTS.md');
30
+ if (await fs.pathExists(rootAgents)) {
31
+ const content = await fs.readFile(rootAgents, 'utf8');
32
+ if (content.includes('<!-- slice:generated:categories:start -->')) return true;
33
+ }
34
+ return fs.pathExists(path.join(projectRoot, 'docs', 'events', 'index.md'));
35
+ }
36
+
37
+ export async function generateDocs({ projectRoot, target = 'all', outputPath }) {
38
+ const only = normalizeTarget(target);
39
+ const catalog = await loadCatalog(projectRoot);
40
+ const written = [];
41
+
42
+ if (only === 'all' || only === 'agents') {
43
+ const result = await generateAgents({ projectRoot, catalog });
44
+ written.push(...result.files);
45
+ }
46
+
47
+ if (only === 'all' || only === 'types') {
48
+ const resolvedOutput = outputPath
49
+ ? (path.isAbsolute(outputPath) ? outputPath : path.join(projectRoot, outputPath))
50
+ : path.join(projectRoot, 'src', 'slice-build.generated.d.ts');
51
+ await runGenerateTypes({ projectRoot, outputPath: resolvedOutput });
52
+ written.push(resolvedOutput);
53
+ }
54
+
55
+ if (only === 'all' || only === 'events') {
56
+ const result = await generateEventDocs({ projectRoot });
57
+ written.push(...result.files);
58
+ }
59
+
60
+ Print.success(`Documentation generated (${only}).`);
61
+ for (const file of [...new Set(written)].sort()) {
62
+ Print.info(path.relative(projectRoot, file).replace(/\\/g, '/'));
63
+ }
64
+ return { written };
65
+ }
66
+
67
+ async function checkTypes({ projectRoot }) {
68
+ const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'slice-docs-check-'));
69
+ const issues = [];
70
+ try {
71
+ const outputPath = path.join(tempRoot, 'slice-build.generated.d.ts');
72
+ const result = await generateTypesFile({ projectRoot, outputPath });
73
+ const pairs = [
74
+ [outputPath, path.join(projectRoot, 'src', 'slice-build.generated.d.ts')],
75
+ [path.join(tempRoot, 'slice-runtime.generated.d.ts'), path.join(projectRoot, 'src', 'slice-runtime.generated.d.ts')],
76
+ [result.manifestPath, path.join(projectRoot, 'src', 'slice-events.generated.js')],
77
+ ];
78
+ for (const [expectedPath, actualPath] of pairs) {
79
+ if (!(await fs.pathExists(actualPath))) {
80
+ issues.push(`missing ${path.relative(projectRoot, actualPath).replace(/\\/g, '/')}`);
81
+ continue;
82
+ }
83
+ const expected = await fs.readFile(expectedPath, 'utf8');
84
+ const actual = await fs.readFile(actualPath, 'utf8');
85
+ if (expected !== actual) {
86
+ issues.push(`outdated ${path.relative(projectRoot, actualPath).replace(/\\/g, '/')}`);
87
+ }
88
+ }
89
+ } finally {
90
+ await fs.remove(tempRoot);
91
+ }
92
+ return issues;
93
+ }
94
+
95
+ export async function checkDocs({ projectRoot, target = 'all' }) {
96
+ const only = normalizeTarget(target);
97
+ const catalog = await loadCatalog(projectRoot);
98
+ const issues = [];
99
+
100
+ if (only === 'all' || only === 'agents') {
101
+ const result = await checkAgents({ projectRoot, catalog });
102
+ issues.push(...result.issues);
103
+ }
104
+
105
+ if (only === 'all' || only === 'types') {
106
+ issues.push(...await checkTypes({ projectRoot }));
107
+ }
108
+
109
+ if (only === 'all' || only === 'events') {
110
+ const result = await checkEventDocs({ projectRoot });
111
+ issues.push(...result.issues);
112
+ }
113
+
114
+ if (issues.length) {
115
+ Print.warning(`Documentation drift detected (${only}).`);
116
+ for (const issue of issues) Print.info(issue);
117
+ Print.info('Run "slice docs generate" to update the generated files.');
118
+ return { ok: false, issues };
119
+ }
120
+
121
+ Print.success(`Documentation is current (${only}).`);
122
+ return { ok: true, issues: [] };
123
+ }
@@ -14,8 +14,60 @@ import { rangeMismatch } from '../utils/semver.js';
14
14
  import { parse as parseModule } from '@babel/parser';
15
15
  import traverse from '@babel/traverse';
16
16
  import ExternalModuleBundler from '../utils/bundling/ExternalModuleBundler.js';
17
- import { loadFrameworkSeo, loadManifest } from '../seo/support.js';
17
+ import { loadFrameworkSeo, loadManifest, loadSeoTranslator } from '../seo/support.js';
18
18
  import { loadRoutes } from '../seo/check.js';
19
+ import { checkProject as checkTranslatorProject } from '../translator/scan.js';
20
+ import { scanComponentCatalog } from '../utils/componentCatalog.js';
21
+ import { checkAgents } from '../docs/agents.js';
22
+ import { checkEventDocs } from '../docs/events.js';
23
+
24
+ /**
25
+ * Translator: is it configured, and does every key on the page exist in every locale?
26
+ * Same scan as `slice translator check`, so the row and the command cannot disagree.
27
+ */
28
+ async function checkTranslatorConfiguration() {
29
+ const projectRoot = getProjectRoot(import.meta.url);
30
+
31
+ let result;
32
+ try {
33
+ result = await checkTranslatorProject(projectRoot);
34
+ } catch (error) {
35
+ return {
36
+ message: `Translator check could not run: ${error.message}`,
37
+ suggestion: 'Update slicejs-web-framework (the template rules live in Translator/dom.js)'
38
+ };
39
+ }
40
+
41
+ if (!result.config?.enabled) {
42
+ return {
43
+ warn: true,
44
+ message: 'Not configured: data-t and slice.t() fall back to the key',
45
+ suggestion: 'Run `slice translator init`'
46
+ };
47
+ }
48
+
49
+ if (result.errors.length) {
50
+ return {
51
+ message: `${result.errors.length} problem(s): ${result.errors[0]}`,
52
+ suggestion: result.errors.length > 1 ? `${result.errors[1]} (run \`slice translator check\`)` : 'Run `slice translator check`'
53
+ };
54
+ }
55
+
56
+ if (result.warnings.length) {
57
+ return {
58
+ warn: true,
59
+ message: `${result.entries.length} key(s) x ${result.locales.length} locale(s)${contentSuffix(result)}, ${result.warnings.length} warning(s): ${result.warnings[0]}`,
60
+ suggestion: 'Run `slice translator check` for the full list'
61
+ };
62
+ }
63
+
64
+ return { pass: true, message: `${result.entries.length} key(s) across ${result.locales.length} locale(s)${contentSuffix(result)}` };
65
+ }
66
+
67
+ /** `, 2 content document(s)` when the app has content documents. */
68
+ function contentSuffix(result) {
69
+ return result.contentCount ? `, ${result.contentCount} content document(s)` : '';
70
+ }
19
71
 
20
72
  /**
21
73
  * SEO: is it configured, and is it safe to deploy?
@@ -58,9 +110,11 @@ async function checkSeoConfiguration() {
58
110
  }
59
111
 
60
112
  const routes = await loadRoutes(projectRoot).catch(() => []);
113
+ const translator = await loadSeoTranslator(projectRoot, framework);
61
114
  const { errors, warnings } = framework.validateSeoManifest(manifest, {
62
115
  routes,
63
- publicDir: path.join(projectRoot, 'src', 'public')
116
+ publicDir: path.join(projectRoot, 'src', 'public'),
117
+ translator
64
118
  });
65
119
 
66
120
  // The sitemap is a committed artifact, so a stale one is a deploy problem.
@@ -69,7 +123,7 @@ async function checkSeoConfiguration() {
69
123
  const origin = framework.normalizeOrigin(manifest.origin);
70
124
  if (!fs.existsSync(sitemapFile)) {
71
125
  warnings.push('sitemap.xml is missing: run `slice seo sitemap`');
72
- } else if (origin && fs.readFileSync(sitemapFile, 'utf8') !== framework.buildSitemap({ manifest, origin })) {
126
+ } else if (origin && fs.readFileSync(sitemapFile, 'utf8') !== framework.buildSitemap({ manifest, origin, translator })) {
73
127
  warnings.push('sitemap.xml is out of date: run `slice seo sitemap`');
74
128
  }
75
129
  }
@@ -566,6 +620,36 @@ async function checkExternalDependencies() {
566
620
  }
567
621
  }
568
622
 
623
+ /**
624
+ * Documentation: AGENTS guides, component inventories and the generated event catalog.
625
+ * Read-only; `slice docs generate` is the fix.
626
+ */
627
+ async function checkDocumentation() {
628
+ const projectRoot = getProjectRoot(import.meta.url);
629
+ const configPath = getConfigPath(import.meta.url);
630
+ if (!fs.existsSync(configPath)) {
631
+ return { warn: true, message: 'No sliceConfig.json', suggestion: 'Run `slice init`' };
632
+ }
633
+
634
+ try {
635
+ const config = await fs.readJson(configPath);
636
+ const catalog = await scanComponentCatalog({ projectRoot, config });
637
+ const agents = await checkAgents({ projectRoot, catalog });
638
+ const events = await checkEventDocs({ projectRoot });
639
+ const issues = [...agents.issues, ...events.issues];
640
+ if (issues.length === 0) {
641
+ return { pass: true, message: 'AGENTS guides, inventories and event docs are current' };
642
+ }
643
+ return {
644
+ warn: true,
645
+ message: `${issues.length} documentation item(s): ${issues[0]}`,
646
+ suggestion: 'Run `slice docs generate`'
647
+ };
648
+ } catch (error) {
649
+ return { warn: true, message: `Could not check documentation: ${error.message}`, suggestion: 'Run `slice docs generate`' };
650
+ }
651
+ }
652
+
569
653
  /**
570
654
  * Main diagnostic command
571
655
  */
@@ -574,6 +658,7 @@ export {
574
658
  checkDirectoryStructure,
575
659
  checkConfig,
576
660
  checkSeoConfiguration,
661
+ checkTranslatorConfiguration,
577
662
  checkPort,
578
663
  checkDependencies,
579
664
  checkComponents,
@@ -583,7 +668,7 @@ export {
583
668
 
584
669
  export default async function runDiagnostics() {
585
670
  Print.newLine();
586
- Print.title('🔍 Running Slice.js Diagnostics...');
671
+ Print.title('Slice.js diagnostics');
587
672
  Print.newLine();
588
673
 
589
674
  const checks = [
@@ -591,10 +676,12 @@ export default async function runDiagnostics() {
591
676
  { name: 'Project Structure', fn: checkDirectoryStructure },
592
677
  { name: 'Configuration', fn: checkConfig },
593
678
  { name: 'SEO', fn: checkSeoConfiguration },
679
+ { name: 'Translator', fn: checkTranslatorConfiguration },
594
680
  { name: 'Port Availability', fn: checkPort },
595
681
  { name: 'Package Manager', fn: checkPackageManagerSetup },
596
682
  { name: 'Dependencies', fn: checkDependencies },
597
683
  { name: 'Components & Routes', fn: checkComponents },
684
+ { name: 'Documentation', fn: checkDocumentation },
598
685
  { name: 'Server entry', fn: checkServerEntry },
599
686
  { name: 'External Dependencies', fn: checkExternalDependencies }
600
687
  ];
@@ -620,11 +707,11 @@ export default async function runDiagnostics() {
620
707
  results.forEach(result => {
621
708
  let status;
622
709
  if (result.pass) {
623
- status = chalk.green('✅ PASS');
710
+ status = chalk.green('PASS');
624
711
  } else if (result.warn) {
625
- status = chalk.yellow('⚠️ WARN');
712
+ status = chalk.yellow('WARN');
626
713
  } else {
627
- status = chalk.red('❌ FAIL');
714
+ status = chalk.red('FAIL');
628
715
  }
629
716
 
630
717
  const details = result.suggestion
@@ -654,13 +741,13 @@ export default async function runDiagnostics() {
654
741
  }
655
742
 
656
743
  if (issues === 0 && warnings === 0) {
657
- Print.success('All checks passed! 🎉');
744
+ Print.success('All checks passed');
658
745
  Print.info('Your Slice.js project is correctly configured');
659
746
  } else {
660
- console.log(chalk.bold('📊 Summary:'));
661
- console.log(chalk.green(` ✅ Passed: ${passed}`));
662
- if (warnings > 0) console.log(chalk.yellow(` ⚠️ Warnings: ${warnings}`));
663
- if (issues > 0) console.log(chalk.red(` ❌ Issues: ${issues}`));
747
+ console.log(chalk.bold('Summary'));
748
+ console.log(chalk.green(` Passed: ${passed}`));
749
+ if (warnings > 0) console.log(chalk.yellow(` Warnings: ${warnings}`));
750
+ if (issues > 0) console.log(chalk.red(` Failures: ${issues}`));
664
751
 
665
752
  Print.newLine();
666
753
 
@@ -0,0 +1,163 @@
1
+ // commands/export/checkExport.js
2
+ import fs from 'fs-extra';
3
+ import path from 'path';
4
+ import { listFiles, pagePathForUrl } from './files.js';
5
+ import { PARAM_ROUTE } from './prerender.js';
6
+
7
+ function routeCandidatesForCheck(pathname, translator) {
8
+ if (!translator?.enabled) return [pathname];
9
+ const locales = Array.isArray(translator.locales) && translator.locales.length
10
+ ? translator.locales
11
+ : [translator.defaultLocale || 'en'];
12
+ const prefix = translator.localePrefix;
13
+ if (prefix !== 'always' && prefix !== 'except-default') return [pathname];
14
+
15
+ return locales.map((locale) => {
16
+ if (prefix === 'except-default' && locale === (translator.defaultLocale || locales[0])) {
17
+ return pathname;
18
+ }
19
+ const tail = pathname === '/' ? '' : pathname;
20
+ return `/${locale}${tail}`;
21
+ });
22
+ }
23
+
24
+ async function readJsonIfExists(file) {
25
+ if (!await fs.pathExists(file)) return null;
26
+ try {
27
+ return JSON.parse(await fs.readFile(file, 'utf8'));
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * `--check` validates what the exporter promises: the runtime files exist, no
35
+ * source/secret artifacts slipped in, host rules are coherent, and every
36
+ * literal route has a prerendered page unless the export declares an SPA
37
+ * fallback. It cannot validate dynamic `${param}` routes: list concrete values
38
+ * in `seo.json -> routes[pattern].sitemap.paths` if you need pages for them.
39
+ */
40
+ export async function checkExport(outDir, { keepComponents = false, preset, explicitHost = null } = {}) {
41
+ const issues = [];
42
+ const warnings = [];
43
+
44
+ if (!await fs.pathExists(outDir)) {
45
+ return { issues: [`Export directory not found: ${outDir}`], warnings };
46
+ }
47
+
48
+ const required = [
49
+ 'index.html',
50
+ 'routes.js',
51
+ 'sliceConfig.json',
52
+ 'slice-env.json',
53
+ 'slice-env.generated.js',
54
+ 'bundles/bundle.config.json',
55
+ 'Slice/Slice.js'
56
+ ];
57
+
58
+ for (const file of required) {
59
+ if (!await fs.pathExists(path.join(outDir, file))) {
60
+ issues.push(`Missing ${file}`);
61
+ }
62
+ }
63
+
64
+ const has404 = await fs.pathExists(path.join(outDir, '404.html'));
65
+ const autoSpa = preset?.spaMode === 'omit-404' && !has404;
66
+ if (!has404 && !autoSpa) {
67
+ issues.push('Missing 404.html');
68
+ } else if (autoSpa) {
69
+ warnings.push('No 404.html: Cloudflare Pages will serve index.html for unknown routes (SPA).');
70
+ }
71
+
72
+ if (!keepComponents && await fs.pathExists(path.join(outDir, 'Components'))) {
73
+ issues.push('Components/ is present; component source is fetchable. Remove it or pass --keep-components.');
74
+ }
75
+ if (await fs.pathExists(path.join(outDir, 'public'))) {
76
+ issues.push('public/ was not flattened; /Themes, /images and other public assets will 404.');
77
+ }
78
+
79
+ const config = await readJsonIfExists(path.join(outDir, 'sliceConfig.json'));
80
+ const translator = config?.translator;
81
+ if (translator?.enabled) {
82
+ const value = typeof translator.path === 'string' && translator.path.trim()
83
+ ? translator.path
84
+ : '/locales';
85
+ const folder = value.replace(/^\/+|\/+$/g, '');
86
+ if (folder && !folder.includes('..') && !await fs.pathExists(path.join(outDir, folder))) {
87
+ issues.push(`Missing translator folder ${folder}/`);
88
+ }
89
+ }
90
+
91
+ const suspectDirs = new Set(['utils', 'src', 'api', 'node_modules', '.git']);
92
+ const suspectFiles = new Set([
93
+ 'appconfig.js',
94
+ 'slice-build.generated.d.ts',
95
+ 'slice-runtime.generated.d.ts'
96
+ ]);
97
+ for (const entry of await fs.readdir(outDir, { withFileTypes: true })) {
98
+ if (entry.isDirectory() && suspectDirs.has(entry.name.toLowerCase())) {
99
+ issues.push(`Source/build directory in export: ${entry.name}/`);
100
+ }
101
+ if (entry.isFile() && suspectFiles.has(entry.name.toLowerCase())) {
102
+ issues.push(`Source/build file in export: ${entry.name}`);
103
+ }
104
+ }
105
+
106
+ const files = await listFiles(outDir);
107
+ for (const file of files) {
108
+ const relative = file.path;
109
+ if (/\.map(?:\.(?:br|gz))?$/i.test(relative)) issues.push(`Source map in export: ${relative}`);
110
+ if (/\.d\.ts$/i.test(relative)) issues.push(`Type declaration in export: ${relative}`);
111
+ if (/(?:^|\/)\.env(?:\.[^/]+)?$/i.test(relative)) issues.push(`Env file in export: ${relative}`);
112
+ if (/(?:^|\/)(?:package(?:-lock)?\.json|pnpm-lock\.yaml|yarn\.lock|npm-shrinkwrap\.json)$/i.test(relative)) {
113
+ issues.push(`Package manifest in export: ${relative}`);
114
+ }
115
+ if (/(?:^|\/)(?:node_modules|\.git)(?:\/|$)/.test(relative)) {
116
+ issues.push(`Dependency or VCS folder in export: ${relative}`);
117
+ }
118
+ if (relative.endsWith('.js')) {
119
+ const content = await fs.readFile(path.join(outDir, relative), 'utf8');
120
+ if (/sourceMappingURL\s*=/.test(content)) {
121
+ issues.push(`sourceMappingURL reference in export: ${relative}`);
122
+ }
123
+ if (/fetch\s*\(\s*["'`]\/api\//.test(content)) {
124
+ warnings.push(`Bundle ${relative} calls /api/*; a static host cannot serve Express routes. Use slice start or a separate API origin.`);
125
+ }
126
+ }
127
+ }
128
+
129
+ if (preset) {
130
+ const hostCheck = await preset.check({ outDir, explicitHost });
131
+ issues.push(...hostCheck.issues);
132
+ warnings.push(...hostCheck.warnings);
133
+ }
134
+
135
+ const routesFile = path.join(outDir, 'routes.js');
136
+ if (await fs.pathExists(routesFile)) {
137
+ const source = await fs.readFile(routesFile, 'utf8');
138
+ const literalPaths = [...source.matchAll(/path\s*:\s*["'`]([^"'`]+)["'`]/g)]
139
+ .map((match) => match[1])
140
+ .filter((pathname) => pathname.startsWith('/') && !PARAM_ROUTE.test(pathname) && !pathname.includes('*'));
141
+
142
+ if (literalPaths.length === 0) {
143
+ warnings.push('Could not find literal routes in routes.js; route coverage was not checked.');
144
+ } else if (!preset || !await preset.spaFallback({ outDir })) {
145
+ for (const pathname of literalPaths) {
146
+ const candidates = routeCandidatesForCheck(pathname, config?.translator);
147
+ const present = [];
148
+ for (const candidate of candidates) {
149
+ if (await fs.pathExists(path.join(outDir, pagePathForUrl(candidate)))) present.push(candidate);
150
+ }
151
+ if (present.length === 0) {
152
+ issues.push(
153
+ `Route ${pathname} has no prerendered page and the export has no SPA fallback. Add sitemap.paths, prerender it, or pass --spa.`
154
+ );
155
+ } else if (present.length < candidates.length) {
156
+ warnings.push(`Route ${pathname} is missing ${candidates.length - present.length} localized page(s).`);
157
+ }
158
+ }
159
+ }
160
+ }
161
+
162
+ return { issues, warnings };
163
+ }
@@ -0,0 +1,72 @@
1
+ // commands/export/clientRedirects.js
2
+ //
3
+ // Hosts without server redirect rules (GitHub Pages, S3, `--host none`) get
4
+ // portable HTML redirect pages. The same module writes the client-side 404
5
+ // fallback used by `--spa` on those hosts.
6
+ import fs from 'fs-extra';
7
+ import path from 'path';
8
+ import { pagePathForUrl } from './files.js';
9
+ import { CLIENT_SPA_MARKER } from './hosts/shared.js';
10
+
11
+ function escapeHtml(value) {
12
+ return String(value)
13
+ .replace(/&/g, '&amp;')
14
+ .replace(/</g, '&lt;')
15
+ .replace(/>/g, '&gt;')
16
+ .replace(/"/g, '&quot;');
17
+ }
18
+
19
+ function clientRedirectHtml(to, origin) {
20
+ const absolute = /^https?:\/\//i.test(to) ? to : `${origin}${to}`;
21
+ return `<!doctype html>
22
+ <html>
23
+ <head>
24
+ <meta charset="utf-8">
25
+ <title>Redirecting…</title>
26
+ <link rel="canonical" href="${escapeHtml(absolute)}">
27
+ <meta name="robots" content="noindex">
28
+ <meta http-equiv="refresh" content="0; url=${escapeHtml(to)}">
29
+ </head>
30
+ <body>
31
+ <p>Redirecting to <a href="${escapeHtml(to)}">${escapeHtml(to)}</a>…</p>
32
+ </body>
33
+ </html>
34
+ `;
35
+ }
36
+
37
+ export async function writeClientRedirects(outDir, redirects, origin, { allowRoot = false } = {}) {
38
+ let written = 0;
39
+ const skipped = [];
40
+ for (const { from, to } of redirects) {
41
+ const file = path.join(outDir, pagePathForUrl(from));
42
+ if (await fs.pathExists(file)) {
43
+ if (!(allowRoot && from === '/')) {
44
+ // A canonical page already owns this path; do not replace it with a redirect.
45
+ skipped.push(from);
46
+ continue;
47
+ }
48
+ }
49
+ await fs.ensureDir(path.dirname(file));
50
+ await fs.writeFile(file, clientRedirectHtml(to, origin), 'utf8');
51
+ written += 1;
52
+ }
53
+ return { written, skipped };
54
+ }
55
+
56
+ /**
57
+ * GitHub/S3/none cannot return 200 for unknown routes. Writing the app shell as
58
+ * 404.html lets the client router render the route; the host keeps the 404
59
+ * status. The marker lets `--check` recognize this shape.
60
+ */
61
+ export async function writeClientSpa404(outDir) {
62
+ const shell = path.join(outDir, 'App', 'index.html');
63
+ const fallback = await fs.pathExists(shell)
64
+ ? shell
65
+ : path.join(outDir, 'index.html');
66
+ const html = await fs.readFile(fallback, 'utf8');
67
+ await fs.writeFile(
68
+ path.join(outDir, '404.html'),
69
+ `${html}\n${CLIENT_SPA_MARKER}\n`,
70
+ 'utf8'
71
+ );
72
+ }