@astralkit/cli 4.7.2 → 4.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +18 -0
- package/bin/index.js +4 -2
- package/package.json +1 -1
- package/src/commands/add.js +217 -16
- package/src/commands/list.js +29 -3
- package/src/commands/search.js +2 -2
- package/src/lib/api.js +39 -2
- package/src/lib/validators.js +22 -0
- package/src/lib/website.js +147 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,26 @@ All notable changes to the `@astralkit/cli` package.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [4.8.0] (2026-12-01)
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- **A whole website in one install:** `astralkit add zest --website` installs every section of a website template as a component and writes the page that renders them in order. Plain `astralkit add zest` does the same when nothing else has that name. Before, a website was installed by naming each of its sections, and the page was left to write.
|
|
12
|
+
- **Next.js with the App Router:** each page is a route under the website's name (`app/zest/page.tsx`), so it can be opened at once. The navigation and the footer sit beside `<main>`, the sections inside it.
|
|
13
|
+
- **A template of several pages** (Luma, Openhouse) gets every page (`app/luma/about/page.tsx`), and the links between its pages (`about.html`, `index.html#care`) are pointed at those routes.
|
|
14
|
+
- **React:** one component per page, next to the sections. **HTML** (`-f html`): one `.html` file per page in a folder of their own, each a single document.
|
|
15
|
+
- Run it again and only what is missing is installed; a page that exists is kept (`--overwrite` replaces).
|
|
16
|
+
- A missing key or a plan without premium components is said once, with the command to run again, not once for every section. The same when the registry cannot be reached.
|
|
17
|
+
- `astralkit list --websites` lists the websites.
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
- In a website install the project's stylesheet, the icon package question and the summary of what changed are handled once for the whole website.
|
|
21
|
+
- A "too many requests" answer from the registry is waited out once (as long as it asks, at most 70 seconds) instead of failing the install.
|
|
22
|
+
|
|
23
|
+
## [4.7.3] (2026-12-01)
|
|
24
|
+
|
|
25
|
+
### Changed
|
|
26
|
+
- **`search` and `list` print one sentence per result.** Each result showed its whole description, a paragraph for most components, so fifty results ran to several screens. Now it is the first sentence, cut at 160 characters with an ellipsis when that sentence is longer. The full description is on the component's page at astralkit.com.
|
|
27
|
+
|
|
8
28
|
## [4.7.2] (2026-11-30)
|
|
9
29
|
|
|
10
30
|
### Fixed
|
package/README.md
CHANGED
|
@@ -89,8 +89,25 @@ astralkit add button-variants --framework react
|
|
|
89
89
|
| `--booster` | Install a booster |
|
|
90
90
|
| `--workflow` | Scaffold a workflow |
|
|
91
91
|
| `--overlay` | Merge workflow into current project |
|
|
92
|
+
| `--website` | Install a whole website template |
|
|
92
93
|
| `--dry-run` | Preview without writing files |
|
|
93
94
|
|
|
95
|
+
#### A whole website in one install
|
|
96
|
+
|
|
97
|
+
A website template (a landing page, or a site of several pages) installs as one unit: every section as a component, and the page files that put them in order.
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
astralkit add zest --website # 8 sections + app/zest/page.tsx
|
|
101
|
+
astralkit add luma --website # 19 sections + 12 pages under app/luma/
|
|
102
|
+
astralkit list --websites # every website
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
- **Next.js (App Router):** each page is a route under the website's name (`app/zest/page.tsx`). Links between the pages of a multi-page template are pointed at those routes.
|
|
106
|
+
- **React:** one component per page, next to the sections (`src/components/ui/zest-page.jsx`).
|
|
107
|
+
- **HTML** (`-f html`): one `.html` file per page, in a folder of their own.
|
|
108
|
+
|
|
109
|
+
Each section is still a component of its own (`astralkit add zest-hero`). Run the command again and it installs only what is missing; `--overwrite` replaces what is there. Websites are premium: Pro and Lifetime.
|
|
110
|
+
|
|
94
111
|
### `astralkit remove <name>`
|
|
95
112
|
|
|
96
113
|
Remove a previously installed component, booster, or workflow.
|
|
@@ -108,6 +125,7 @@ Browse available content.
|
|
|
108
125
|
astralkit list # components
|
|
109
126
|
astralkit list --boosters # boosters
|
|
110
127
|
astralkit list --workflows # workflows
|
|
128
|
+
astralkit list --websites # website templates
|
|
111
129
|
astralkit list --category forms
|
|
112
130
|
astralkit list --pro # pro-only items
|
|
113
131
|
```
|
package/bin/index.js
CHANGED
|
@@ -41,13 +41,14 @@ program
|
|
|
41
41
|
// ─── add ─────────────────────────────────────────────
|
|
42
42
|
program
|
|
43
43
|
.command('add <names...>')
|
|
44
|
-
.description('Add one or more components, boosters, or
|
|
44
|
+
.description('Add one or more components, boosters, workflows, or a whole website to your project')
|
|
45
45
|
.option('--api-key <key>', 'Your API key')
|
|
46
46
|
.option('-f, --framework <framework>', 'Framework version (html, react, nextjs)')
|
|
47
47
|
.option('--dir <directory>', 'Override output directory')
|
|
48
48
|
.option('--overwrite', 'Overwrite existing files', false)
|
|
49
49
|
.option('--booster', 'Install a booster (feature module)')
|
|
50
50
|
.option('--workflow', 'Scaffold a workflow (complete app template)')
|
|
51
|
+
.option('--website', 'Install a whole website template: every section, and the pages that order them')
|
|
51
52
|
.option('--overlay', 'Merge workflow into current project')
|
|
52
53
|
.option('--dry-run', 'Preview what will be installed without writing files', false)
|
|
53
54
|
.option('-y, --yes', 'Accept all prompts with their defaults (also implied when no TTY is attached — agent/CI shells)', false)
|
|
@@ -118,13 +119,14 @@ program
|
|
|
118
119
|
// ─── list ────────────────────────────────────────────
|
|
119
120
|
program
|
|
120
121
|
.command('list')
|
|
121
|
-
.description('List available components, boosters, or
|
|
122
|
+
.description('List available components, boosters, workflows, or websites')
|
|
122
123
|
.option('-c, --category <category>', 'Filter by category')
|
|
123
124
|
.option('--framework <framework>', 'Filter by framework')
|
|
124
125
|
.option('--pro', 'Show only pro items', false)
|
|
125
126
|
.option('--free', 'Show only free items', false)
|
|
126
127
|
.option('--boosters', 'List boosters')
|
|
127
128
|
.option('--workflows', 'List workflows')
|
|
129
|
+
.option('--websites', 'List website templates (each installs as one unit)')
|
|
128
130
|
.action(listCommand);
|
|
129
131
|
|
|
130
132
|
// ─── search ──────────────────────────────────────────
|
package/package.json
CHANGED
package/src/commands/add.js
CHANGED
|
@@ -2,7 +2,7 @@ import fs from 'fs';
|
|
|
2
2
|
import path from 'path';
|
|
3
3
|
import pc from 'picocolors';
|
|
4
4
|
import * as p from '@clack/prompts';
|
|
5
|
-
import { getComponent, getBooster, getWorkflow, listComponents, listBoosters, listWorkflows, LOCAL_REGISTRY_DIR } from '../lib/api.js';
|
|
5
|
+
import { getComponent, getBooster, getWorkflow, getWebsite, listComponents, listBoosters, listWorkflows, LOCAL_REGISTRY_DIR } from '../lib/api.js';
|
|
6
6
|
import {
|
|
7
7
|
detectFramework,
|
|
8
8
|
detectTypeScript,
|
|
@@ -16,6 +16,7 @@ import { saveApiKey, getApiKey, getAuth } from '../lib/auth.js';
|
|
|
16
16
|
import { applyMerges } from '../lib/merges.js';
|
|
17
17
|
import { ensureComponentStylesheets } from '../lib/stylesheets.js';
|
|
18
18
|
import { setAssumeYes, confirm as askConfirm, select as askSelect, text as askText } from '../lib/ask.js';
|
|
19
|
+
import { planPages, pageSource, pointLinksAtRoutes, composeHtml, relativeImport } from '../lib/website.js';
|
|
19
20
|
|
|
20
21
|
const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
|
|
21
22
|
|
|
@@ -25,6 +26,9 @@ class ExitSignal extends Error {
|
|
|
25
26
|
constructor(code) { super('exit'); this.code = code; }
|
|
26
27
|
}
|
|
27
28
|
let inBatch = false;
|
|
29
|
+
// Why the last install stopped (AUTH_REQUIRED, PRO_REQUIRED, ...): a website install reads it, so that a missing
|
|
30
|
+
// key is said once, not once for every section.
|
|
31
|
+
let lastFailure = null;
|
|
28
32
|
function exit(code) {
|
|
29
33
|
if (inBatch) throw new ExitSignal(code);
|
|
30
34
|
process.exit(code);
|
|
@@ -89,6 +93,7 @@ async function addOne(nameOrSlug, options) {
|
|
|
89
93
|
// If explicit type flag provided, skip smart detection
|
|
90
94
|
if (options.booster) return addBooster(nameOrSlug, options);
|
|
91
95
|
if (options.workflow) return addWorkflow(nameOrSlug, options);
|
|
96
|
+
if (options.website) return addWebsite(nameOrSlug, options);
|
|
92
97
|
|
|
93
98
|
// ─── Smart detection: search all registries for the slug ───
|
|
94
99
|
const ora = (await import('ora')).default;
|
|
@@ -117,6 +122,13 @@ async function addOne(nameOrSlug, options) {
|
|
|
117
122
|
spinner.stop();
|
|
118
123
|
|
|
119
124
|
if (matches.length === 0) {
|
|
125
|
+
// Not a component, a booster or a workflow: it may be a whole website template (zest, luma).
|
|
126
|
+
const site = await getWebsite(nameOrSlug).catch(() => null);
|
|
127
|
+
if (site) {
|
|
128
|
+
p.log.step(`Found ${pc.cyan(site.name)} as a ${pc.bold('website')}`);
|
|
129
|
+
return addWebsite(nameOrSlug, options, site);
|
|
130
|
+
}
|
|
131
|
+
|
|
120
132
|
// No exact match — try fuzzy suggestions
|
|
121
133
|
const allItems = [
|
|
122
134
|
...((components.status === 'fulfilled' ? (components.value?.components || components.value?.data || []) : []) || []).map(c => ({ ...c, type: 'component' })),
|
|
@@ -259,7 +271,9 @@ async function addComponent(componentSlug, options) {
|
|
|
259
271
|
const spinner = ora(`Fetching ${pc.cyan(componentSlug)} (${FRAMEWORK_LABELS[framework]})...`).start();
|
|
260
272
|
|
|
261
273
|
try {
|
|
262
|
-
const data = await getComponent(componentSlug, framework
|
|
274
|
+
const data = await getComponent(componentSlug, framework, {
|
|
275
|
+
onWait: (seconds) => { spinner.text = `The registry asks for a pause: waiting ${seconds} seconds, then fetching ${pc.cyan(componentSlug)}...`; },
|
|
276
|
+
});
|
|
263
277
|
|
|
264
278
|
if (!data.files?.length) {
|
|
265
279
|
spinner.fail(`No ${framework} code available for "${componentSlug}".`);
|
|
@@ -302,24 +316,19 @@ async function addComponent(componentSlug, options) {
|
|
|
302
316
|
|
|
303
317
|
spinner.succeed(`Added ${pc.cyan(data.name || componentSlug)} (${FRAMEWORK_LABELS[framework]})`);
|
|
304
318
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
const cssEntry = findCssEntryFile();
|
|
310
|
-
if (cssEntry) {
|
|
311
|
-
const missing = getMissingCssImports(cssEntry.path);
|
|
312
|
-
if (missing.length > 0) {
|
|
313
|
-
p.log.warn(`Missing CSS imports in ${cssEntry.relative}. Run ${pc.cyan('astralkit init')} to fix.`);
|
|
314
|
-
}
|
|
315
|
-
}
|
|
319
|
+
// (a website install says these once, at its end, not once for every section)
|
|
320
|
+
if (!options.collectInto) printSetupHints();
|
|
316
321
|
|
|
317
322
|
// Detect if component uses Phosphor Icons (CSS class-based icons)
|
|
318
323
|
const componentCode = data.files?.map(f => f.content).join('') || '';
|
|
319
324
|
|
|
320
325
|
// The stylesheets the component asks for (a template section's palette and typefaces, a date picker's dialog)
|
|
321
326
|
// go into the project's stylesheet. An HTML file loads its own from the CDN.
|
|
322
|
-
|
|
327
|
+
// (a website install does it once, for all its sections together)
|
|
328
|
+
if (framework !== 'html') {
|
|
329
|
+
if (options.collectInto) options.collectInto.code.push(...filesToWrite.map(f => f.content));
|
|
330
|
+
else await ensureComponentStylesheets(filesToWrite.map(f => f.content).join('\n'), installSummary);
|
|
331
|
+
}
|
|
323
332
|
let usesPhosphorCss = componentCode.includes('class="ph ') || componentCode.includes("class='ph ") || componentCode.includes('"ph ph-') || componentCode.includes("'ph ph-");
|
|
324
333
|
|
|
325
334
|
// Phosphor conflict guard: @phosphor-icons/web and @phosphor-icons/react
|
|
@@ -329,7 +338,11 @@ async function addComponent(componentSlug, options) {
|
|
|
329
338
|
// warn loudly and let the user opt out of auto-installing web.
|
|
330
339
|
if (usesPhosphorCss) {
|
|
331
340
|
const hostPkg = readHostPackageJson();
|
|
332
|
-
|
|
341
|
+
// (a website install asks once: every section after the first takes the same answer, without the warning)
|
|
342
|
+
const shared = options.collectInto;
|
|
343
|
+
if (shared && shared.phosphorWeb !== undefined) {
|
|
344
|
+
usesPhosphorCss = shared.phosphorWeb;
|
|
345
|
+
} else if (hostHasDep(hostPkg, '@phosphor-icons/react')) {
|
|
333
346
|
p.log.warn(`This component uses ${pc.cyan('@phosphor-icons/web')} (CSS class-based icons).`);
|
|
334
347
|
p.log.warn(`Your project already uses ${pc.cyan('@phosphor-icons/react')} (React components) — a ${pc.bold('separate package')} from the same vendor.`);
|
|
335
348
|
p.log.warn(`Installing both ships two icon systems side by side.`);
|
|
@@ -351,6 +364,7 @@ async function addComponent(componentSlug, options) {
|
|
|
351
364
|
reason: 'host project uses @phosphor-icons/react; user declined',
|
|
352
365
|
});
|
|
353
366
|
}
|
|
367
|
+
if (shared) shared.phosphorWeb = usesPhosphorCss;
|
|
354
368
|
}
|
|
355
369
|
}
|
|
356
370
|
|
|
@@ -513,7 +527,9 @@ async function addComponent(componentSlug, options) {
|
|
|
513
527
|
}
|
|
514
528
|
}
|
|
515
529
|
|
|
516
|
-
|
|
530
|
+
// a website install prints one summary for all its sections
|
|
531
|
+
if (options.collectInto) mergeSummary(options.collectInto, installSummary);
|
|
532
|
+
else printInstallSummary(installSummary);
|
|
517
533
|
return true;
|
|
518
534
|
|
|
519
535
|
} catch (err) {
|
|
@@ -522,6 +538,26 @@ async function addComponent(componentSlug, options) {
|
|
|
522
538
|
}
|
|
523
539
|
}
|
|
524
540
|
|
|
541
|
+
// What the project still needs before AstralKit components draw as designed.
|
|
542
|
+
function printSetupHints() {
|
|
543
|
+
if (!isAstralkitInstalled()) {
|
|
544
|
+
p.log.warn('Run ' + pc.cyan('astralkit init') + ' to set up design tokens.');
|
|
545
|
+
}
|
|
546
|
+
const cssEntry = findCssEntryFile();
|
|
547
|
+
if (cssEntry) {
|
|
548
|
+
const missing = getMissingCssImports(cssEntry.path);
|
|
549
|
+
if (missing.length > 0) {
|
|
550
|
+
p.log.warn(`Missing CSS imports in ${cssEntry.relative}. Run ${pc.cyan('astralkit init')} to fix.`);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function mergeSummary(into, from) {
|
|
556
|
+
for (const key of ['created', 'installed', 'alreadySatisfied']) for (const item of from[key]) if (!into[key].includes(item)) into[key].push(item);
|
|
557
|
+
for (const item of from.modified) if (!into.modified.some(have => have.path === item.path && have.note === item.note)) into.modified.push(item);
|
|
558
|
+
for (const item of from.skipped) if (!into.skipped.some(have => have.what === item.what)) into.skipped.push(item);
|
|
559
|
+
}
|
|
560
|
+
|
|
525
561
|
// End-of-install summary. Prints what the CLI did to the user's project so
|
|
526
562
|
// they never have to run `git diff` just to find out what was touched. Split
|
|
527
563
|
// into Created / Modified / Installed / Skipped so each category is scannable.
|
|
@@ -555,6 +591,170 @@ function printInstallSummary(s) {
|
|
|
555
591
|
}
|
|
556
592
|
}
|
|
557
593
|
|
|
594
|
+
// A whole website template as one install (2026-12-01): every section as a component, exactly as each installs
|
|
595
|
+
// alone, then one file per page that renders them in page order. `astralkit add zest --website`, or plain
|
|
596
|
+
// `astralkit add zest` when nothing else is called that.
|
|
597
|
+
async function addWebsite(name, options, known) {
|
|
598
|
+
if (!validateSlug(name, 'website name')) exit(1);
|
|
599
|
+
if (!fs.existsSync(path.join(process.cwd(), 'package.json'))) {
|
|
600
|
+
p.log.warn('No package.json found. Run this inside a project directory.');
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
const ora = (await import('ora')).default;
|
|
604
|
+
const framework = resolveFramework(options);
|
|
605
|
+
const ext = resolveExtension(framework);
|
|
606
|
+
const componentsDir = options.dir || 'src/components/ui';
|
|
607
|
+
if (!isSafeInstallDir(process.cwd(), componentsDir)) {
|
|
608
|
+
console.log(pc.red(`Refusing install: unsafe --dir value "${componentsDir}"`));
|
|
609
|
+
exit(1);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
let site = known;
|
|
613
|
+
if (!site) {
|
|
614
|
+
const spinner = ora(`Looking for the ${pc.cyan(name)} website...`).start();
|
|
615
|
+
try {
|
|
616
|
+
site = await getWebsite(name);
|
|
617
|
+
} catch (err) {
|
|
618
|
+
spinner.fail('Could not ask the registry.');
|
|
619
|
+
console.error(pc.red(err.message));
|
|
620
|
+
exit(1);
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
if (!site) {
|
|
624
|
+
spinner.fail(`There is no website called "${name}".`);
|
|
625
|
+
p.log.info('See every website: ' + pc.cyan('astralkit list --websites'));
|
|
626
|
+
exit(1);
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
spinner.stop();
|
|
630
|
+
}
|
|
631
|
+
// The registry's answer names files and folders: nothing in it may leave the project.
|
|
632
|
+
const safeName = (text) => typeof text === 'string' && /^[a-z0-9]+(-[a-z0-9]+)*$/.test(text);
|
|
633
|
+
const pages = (site.pages || []).filter(page => (page.route === '' || safeName(page.route)) && /^[a-z0-9-]+\.html$/.test(page.file || '') && Array.isArray(page.sections) && page.sections.every(safeName));
|
|
634
|
+
const sections = (site.sections || []).map(section => section.slug).filter(safeName);
|
|
635
|
+
if (!safeName(site.slug) || !sections.length || !pages.length) {
|
|
636
|
+
p.log.error(`The registry's answer for "${name}" cannot be installed.`);
|
|
637
|
+
exit(1);
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
site = { ...site, name: sanitizeForTerminal(site.name || site.slug), pages };
|
|
641
|
+
|
|
642
|
+
const command = `npx @astralkit/cli add ${site.slug} --website`;
|
|
643
|
+
const dir = path.resolve(process.cwd(), componentsDir);
|
|
644
|
+
const plan = planPages({ site, framework, cwd: process.cwd(), componentsDir, ext });
|
|
645
|
+
// a section's file once it is in the project (a React install may be .jsx in a TypeScript project)
|
|
646
|
+
const sectionFile = (slug) => (framework === 'html' ? [`${slug}.html`] : [`${slug}.tsx`, `${slug}.jsx`]).map(file => path.join(dir, file)).find(file => fs.existsSync(file)) || null;
|
|
647
|
+
const label = FRAMEWORK_LABELS[framework] || 'HTML';
|
|
648
|
+
const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
|
|
649
|
+
|
|
650
|
+
console.log();
|
|
651
|
+
p.log.step(`${pc.bold(site.name)}: ${count(sections.length, 'section')}, ${count(pages.length, 'page')} (${label})`);
|
|
652
|
+
|
|
653
|
+
if (options.dryRun) {
|
|
654
|
+
console.log(pc.bold('\nDry run, no files will be written:\n'));
|
|
655
|
+
for (const slug of sections) {
|
|
656
|
+
const have = sectionFile(slug);
|
|
657
|
+
const shown = `${componentsDir}/${slug}${framework === 'html' ? '.html' : framework === 'nextjs' ? '.tsx' : '.jsx'}`;
|
|
658
|
+
console.log(` ${have ? (options.overwrite ? pc.yellow('overwrite') : pc.gray('keep ')) : pc.green('+ create')} ${shown}`);
|
|
659
|
+
}
|
|
660
|
+
for (const { file } of plan.pages) {
|
|
661
|
+
const have = fs.existsSync(path.resolve(process.cwd(), file));
|
|
662
|
+
console.log(` ${have ? (options.overwrite ? pc.yellow('overwrite') : pc.gray('keep ')) : pc.green('+ create')} ${file}`);
|
|
663
|
+
}
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// 1. every section, as a component
|
|
668
|
+
const summary = { created: [], modified: [], installed: [], alreadySatisfied: [], skipped: [], code: [] };
|
|
669
|
+
const present = new Set();
|
|
670
|
+
const fresh = [];
|
|
671
|
+
const kept = [];
|
|
672
|
+
const failed = [];
|
|
673
|
+
let stopped = null;
|
|
674
|
+
const wasInBatch = inBatch;
|
|
675
|
+
inBatch = true;
|
|
676
|
+
try {
|
|
677
|
+
for (const slug of sections) {
|
|
678
|
+
if (!options.overwrite && sectionFile(slug)) { present.add(slug); kept.push(slug); continue; }
|
|
679
|
+
lastFailure = null;
|
|
680
|
+
let done = false;
|
|
681
|
+
try {
|
|
682
|
+
done = (await addComponent(slug, { ...options, collectInto: summary })) === true;
|
|
683
|
+
} catch (err) {
|
|
684
|
+
if (!(err instanceof ExitSignal)) throw err;
|
|
685
|
+
}
|
|
686
|
+
if (done) { present.add(slug); fresh.push(slug); continue; }
|
|
687
|
+
failed.push(slug);
|
|
688
|
+
// no key, a plan without premium components, or no way to the registry: every other section would say the same
|
|
689
|
+
if (['AUTH_REQUIRED', 'PRO_REQUIRED', 'TIMEOUT', 'NETWORK_ERROR'].includes(lastFailure)) { stopped = lastFailure; break; }
|
|
690
|
+
}
|
|
691
|
+
} finally {
|
|
692
|
+
inBatch = wasInBatch;
|
|
693
|
+
}
|
|
694
|
+
if (stopped) {
|
|
695
|
+
const offline = stopped === 'TIMEOUT' || stopped === 'NETWORK_ERROR';
|
|
696
|
+
console.log();
|
|
697
|
+
p.log.warn(offline ? `The registry could not be reached, so ${pc.bold(site.name)} was not finished.` : `${pc.bold(site.name)} is a premium website: its sections come with Pro and Lifetime.`);
|
|
698
|
+
console.log(pc.gray(` ${fresh.length ? `${count(fresh.length, 'section')} installed before it stopped (they are kept). ` : 'Nothing was installed. '}${offline ? 'Run the same command again in a moment:' : 'Sign in or upgrade, then run the same command again:'}`));
|
|
699
|
+
console.log(` ${pc.cyan(command)}`);
|
|
700
|
+
exit(1);
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// the stylesheets the sections ask for (the template's palette and typefaces), once
|
|
705
|
+
if (framework !== 'html' && summary.code.length) await ensureComponentStylesheets(summary.code.join('\n'), summary);
|
|
706
|
+
|
|
707
|
+
// 2. in an app with real routes, the links between the template's pages point at those routes
|
|
708
|
+
if (plan.kind === 'routes' && pages.length > 1) {
|
|
709
|
+
for (const slug of fresh) {
|
|
710
|
+
const file = sectionFile(slug);
|
|
711
|
+
if (!file) continue;
|
|
712
|
+
const pointed = pointLinksAtRoutes(fs.readFileSync(file, 'utf8'), site, plan.base);
|
|
713
|
+
if (!pointed.changed) continue;
|
|
714
|
+
fs.writeFileSync(file, pointed.code);
|
|
715
|
+
summary.modified.push({ path: path.relative(process.cwd(), file).replace(/\\/g, '/'), note: `${count(pointed.changed, 'link')} pointed at ${plan.base}` });
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// 3. the pages
|
|
720
|
+
const written = [];
|
|
721
|
+
for (const { page, file } of plan.pages) {
|
|
722
|
+
const own = page.sections.filter(slug => present.has(slug));
|
|
723
|
+
const target = path.resolve(process.cwd(), file);
|
|
724
|
+
if (!own.length) { summary.skipped.push({ what: file, reason: 'none of its sections were installed' }); continue; }
|
|
725
|
+
if (fs.existsSync(target) && !options.overwrite) { summary.skipped.push({ what: file, reason: 'already exists, use --overwrite to replace it' }); continue; }
|
|
726
|
+
const content = plan.kind === 'html'
|
|
727
|
+
? composeHtml({ site, page, documents: own.map(slug => fs.readFileSync(sectionFile(slug), 'utf8')) })
|
|
728
|
+
: pageSource({ site, page, sections: own, command, importFrom: (slug) => relativeImport(target, path.join(dir, slug)) });
|
|
729
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
730
|
+
fs.writeFileSync(target, content);
|
|
731
|
+
summary.created.push(file);
|
|
732
|
+
written.push({ page, file });
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// 4. what happened, once
|
|
736
|
+
console.log();
|
|
737
|
+
if (failed.length) p.log.warn(`${site.name}: ${count(present.size, 'section')} of ${sections.length} are in your project. Not installed: ${failed.join(', ')} (the reason for each is printed above)`);
|
|
738
|
+
else if (!fresh.length && !written.length) p.log.success(`${pc.bold(site.name)} is already in your project: nothing to add. Use ${pc.cyan('--overwrite')} to install it again.`);
|
|
739
|
+
else p.log.success(`${pc.bold(site.name)} is in your project: ${count(present.size, 'section')}${written.length ? `, ${count(written.length, 'page')}` : ''}`);
|
|
740
|
+
if (kept.length) console.log(pc.gray(` Already there, left as they are: ${kept.join(', ')}`));
|
|
741
|
+
if (framework !== 'html') printSetupHints();
|
|
742
|
+
printInstallSummary(summary);
|
|
743
|
+
|
|
744
|
+
const home = written.find(item => !item.page.route) || written[0];
|
|
745
|
+
if (home) {
|
|
746
|
+
console.log();
|
|
747
|
+
p.log.step(pc.bold('Next'));
|
|
748
|
+
if (plan.kind === 'routes') console.log(` Start your app and open ${pc.cyan(plan.base)}. To make it your home page, move ${pc.cyan(home.file)} to ${pc.cyan(home.file.replace(`/${site.slug}/page`, '/page'))}.`);
|
|
749
|
+
else if (plan.kind === 'html') console.log(` Open ${pc.cyan(home.file)} in a browser.`);
|
|
750
|
+
else console.log(` Render the page from ${pc.cyan(home.file)} where your app shows its home page.`);
|
|
751
|
+
if (pages.length > 1 && plan.kind === 'components') console.log(pc.gray(' Its pages link to each other by file name (about.html): point those links at your own routes.'));
|
|
752
|
+
console.log(pc.gray(` The business in it${site.sample_business ? ` (${sanitizeForTerminal(site.sample_business)})` : ''} is sample content: keep each section's layout, and change the name, the copy and the photos.`));
|
|
753
|
+
}
|
|
754
|
+
if (failed.length) { exit(1); return; }
|
|
755
|
+
return true;
|
|
756
|
+
}
|
|
757
|
+
|
|
558
758
|
async function addBooster(slug, options) {
|
|
559
759
|
if (!validateSlug(slug, 'booster name')) exit(1);
|
|
560
760
|
|
|
@@ -824,6 +1024,7 @@ async function addWorkflow(slug, options) {
|
|
|
824
1024
|
}
|
|
825
1025
|
|
|
826
1026
|
function handleAddError(err, slug, framework) {
|
|
1027
|
+
lastFailure = err.code || 'ERROR';
|
|
827
1028
|
if (err.code === 'AUTH_REQUIRED') {
|
|
828
1029
|
if (!getApiKey() && !getAuth().token) {
|
|
829
1030
|
// no key at all: say what the component is and the three ways to give one
|
package/src/commands/list.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import pc from 'picocolors';
|
|
2
2
|
import * as p from '@clack/prompts';
|
|
3
|
-
import { listComponents, listBoosters, listWorkflows } from '../lib/api.js';
|
|
4
|
-
import { sanitizeForTerminal } from '../lib/validators.js';
|
|
3
|
+
import { listComponents, listBoosters, listWorkflows, listWebsites } from '../lib/api.js';
|
|
4
|
+
import { sanitizeForTerminal, firstSentence } from '../lib/validators.js';
|
|
5
5
|
|
|
6
6
|
// Server-supplied string passthrough protection — strips ANSI/control sequences
|
|
7
7
|
// before printing. Prevents a malicious API from rewriting the terminal.
|
|
@@ -9,7 +9,33 @@ const s = (v) => sanitizeForTerminal(v || '');
|
|
|
9
9
|
|
|
10
10
|
const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React', html: 'HTML' };
|
|
11
11
|
|
|
12
|
+
/** The website templates: each is one install of all its sections and pages. */
|
|
13
|
+
async function listWebsitesCommand() {
|
|
14
|
+
const ora = (await import('ora')).default;
|
|
15
|
+
const spinner = ora('Fetching websites...').start();
|
|
16
|
+
try {
|
|
17
|
+
const res = await listWebsites();
|
|
18
|
+
const items = res?.websites || [];
|
|
19
|
+
spinner.stop();
|
|
20
|
+
if (!items.length) { p.log.info('No websites found.'); return; }
|
|
21
|
+
console.log();
|
|
22
|
+
console.log(pc.bold(` ${items.length} websites available\n`));
|
|
23
|
+
for (const item of items) {
|
|
24
|
+
const pages = item.pages > 1 ? `, ${item.pages} pages` : '';
|
|
25
|
+
console.log(` ${pc.cyan(s(item.slug))}${item.is_pro ? pc.magenta(' [PRO]') : pc.green(' [FREE]')}`);
|
|
26
|
+
console.log(pc.gray(` ${s(item.name)}. ${s(item.industry)}. ${item.sections} sections${pages}.`));
|
|
27
|
+
console.log();
|
|
28
|
+
}
|
|
29
|
+
console.log(pc.gray(' astralkit add <name> --website to install the whole website'));
|
|
30
|
+
} catch (err) {
|
|
31
|
+
spinner.fail('Failed to fetch websites.');
|
|
32
|
+
console.error(pc.red(err.message));
|
|
33
|
+
process.exit(1);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
12
37
|
export async function listCommand(options) {
|
|
38
|
+
if (options.websites) return listWebsitesCommand();
|
|
13
39
|
const ora = (await import('ora')).default;
|
|
14
40
|
const type = options.boosters ? 'boosters' : options.workflows ? 'workflows' : 'components';
|
|
15
41
|
const spinner = ora(`Fetching ${type}...`).start();
|
|
@@ -39,7 +65,7 @@ export async function listCommand(options) {
|
|
|
39
65
|
const proTag = item.is_pro ? pc.magenta(' [PRO]') : pc.green(' [FREE]');
|
|
40
66
|
const fw = item.frameworks?.map(f => FRAMEWORK_LABELS[f] || f).join(', ') || '';
|
|
41
67
|
console.log(` ${pc.cyan(s(item.slug || item.name))}${proTag}`);
|
|
42
|
-
if (item.description) console.log(pc.gray(` ${
|
|
68
|
+
if (item.description) console.log(pc.gray(` ${firstSentence(item.description)}`));
|
|
43
69
|
if (fw) console.log(pc.gray(` Frameworks: ${s(fw)}`));
|
|
44
70
|
console.log();
|
|
45
71
|
}
|
package/src/commands/search.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import pc from 'picocolors';
|
|
2
2
|
import * as p from '@clack/prompts';
|
|
3
3
|
import { listComponents, listBoosters, listWorkflows } from '../lib/api.js';
|
|
4
|
-
import { sanitizeForTerminal } from '../lib/validators.js';
|
|
4
|
+
import { sanitizeForTerminal, firstSentence } from '../lib/validators.js';
|
|
5
5
|
|
|
6
6
|
const s = (v) => sanitizeForTerminal(v || '');
|
|
7
7
|
|
|
@@ -58,7 +58,7 @@ export async function searchCommand(query, options) {
|
|
|
58
58
|
const proTag = item.is_pro ? pc.magenta(' [PRO]') : pc.green(' [FREE]');
|
|
59
59
|
const fw = item.frameworks?.map(f => FRAMEWORK_LABELS[f] || f).join(', ') || '';
|
|
60
60
|
console.log(` ${pc.cyan(s(item.slug || item.name))}${typeLabel}${proTag}`);
|
|
61
|
-
if (item.description) console.log(pc.gray(` ${
|
|
61
|
+
if (item.description) console.log(pc.gray(` ${firstSentence(item.description)}`));
|
|
62
62
|
if (fw) console.log(pc.gray(` Frameworks: ${s(fw)}`));
|
|
63
63
|
console.log();
|
|
64
64
|
}
|
package/src/lib/api.js
CHANGED
|
@@ -117,6 +117,10 @@ export async function apiRequest(urlPath, options = {}) {
|
|
|
117
117
|
const safeBody = (body || response.statusText || '').replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '').slice(0, 500);
|
|
118
118
|
const err = new Error(`API error ${response.status}: ${safeBody}`);
|
|
119
119
|
err.code = 'API_ERROR';
|
|
120
|
+
err.status = response.status;
|
|
121
|
+
// a 429 says how long to wait
|
|
122
|
+
const wait = Number(response.headers.get('retry-after'));
|
|
123
|
+
if (Number.isFinite(wait) && wait > 0) err.retryAfter = wait;
|
|
120
124
|
throw err;
|
|
121
125
|
}
|
|
122
126
|
|
|
@@ -139,8 +143,41 @@ export async function listComponents({ category, framework, pro, free, search }
|
|
|
139
143
|
return res.json();
|
|
140
144
|
}
|
|
141
145
|
|
|
142
|
-
|
|
143
|
-
|
|
146
|
+
/**
|
|
147
|
+
* A component's files. The registry allows a number of downloads a minute; a whole website is many sections, so a
|
|
148
|
+
* "too many requests" answer is waited out once (as long as the registry says, at most 70 seconds) instead of failing
|
|
149
|
+
* the install half way. `onWait(seconds)` lets the caller say so on screen.
|
|
150
|
+
*/
|
|
151
|
+
export async function getComponent(slug, framework = 'html', { onWait } = {}) {
|
|
152
|
+
const urlPath = `/api/cli/components/${encodeURIComponent(slug)}?framework=${encodeURIComponent(framework)}`;
|
|
153
|
+
try {
|
|
154
|
+
return await (await apiRequest(urlPath)).json();
|
|
155
|
+
} catch (err) {
|
|
156
|
+
if (err.status !== 429) throw err;
|
|
157
|
+
const seconds = Math.min(Math.max(Math.ceil(err.retryAfter || 60), 1), 70);
|
|
158
|
+
onWait?.(seconds);
|
|
159
|
+
await new Promise(done => setTimeout(done, seconds * 1000));
|
|
160
|
+
return (await apiRequest(urlPath)).json();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* A website template as one install: its pages and the sections of each, in page order. Null when there is no
|
|
166
|
+
* website by that name (or it is not published yet). No code is in the answer: each section is then asked for as
|
|
167
|
+
* a component.
|
|
168
|
+
*/
|
|
169
|
+
export async function getWebsite(name) {
|
|
170
|
+
try {
|
|
171
|
+
return await (await apiRequest(`/api/cli/websites/${encodeURIComponent(name)}`)).json();
|
|
172
|
+
} catch (err) {
|
|
173
|
+
if (err.status === 404 || err.status === 400) return null;
|
|
174
|
+
throw err;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** The website templates that can be installed as one unit. */
|
|
179
|
+
export async function listWebsites() {
|
|
180
|
+
const res = await apiRequest('/api/cli/websites');
|
|
144
181
|
return res.json();
|
|
145
182
|
}
|
|
146
183
|
|
package/src/lib/validators.js
CHANGED
|
@@ -58,6 +58,28 @@ export function sanitizeForTerminal(str) {
|
|
|
58
58
|
return str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
/**
|
|
62
|
+
* The first sentence of a description, for one-line listings (`search`, `list`). A registry description runs to a
|
|
63
|
+
* paragraph: printed whole, fifty results fill the terminal many times over.
|
|
64
|
+
* A sentence ends at . ! or ? followed by a space and a capital, a digit or an opening mark, so "audit.log(",
|
|
65
|
+
* "Next.js" and "e.g. this" do not end one. A first sentence longer than `max` is cut at a word, with an ellipsis.
|
|
66
|
+
*/
|
|
67
|
+
export function firstSentence(str, max = 160) {
|
|
68
|
+
const text = sanitizeForTerminal(str).replace(/\s+/g, ' ').trim();
|
|
69
|
+
if (!text) return '';
|
|
70
|
+
let sentence = text;
|
|
71
|
+
const end = /[.!?](?=\s+[A-Z0-9<`"'(\[])/g;
|
|
72
|
+
for (let hit = end.exec(text); hit; hit = end.exec(text)) {
|
|
73
|
+
const before = text.slice(0, hit.index);
|
|
74
|
+
if (/(?:\b(?:e\.g|i\.e|vs|etc|approx|incl)|\b[A-Z])$/.test(before)) continue; // an abbreviation or an initial
|
|
75
|
+
sentence = text.slice(0, hit.index + 1);
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
if (sentence.length <= max) return sentence;
|
|
79
|
+
const cut = sentence.slice(0, max);
|
|
80
|
+
return `${cut.slice(0, Math.max(cut.lastIndexOf(' '), max - 30)).replace(/[\s,;:(\p{Pd}]+$/u, '')}…`;
|
|
81
|
+
}
|
|
82
|
+
|
|
61
83
|
export function validateFramework(framework) {
|
|
62
84
|
if (!framework) return true;
|
|
63
85
|
if (VALID_FRAMEWORKS.includes(framework)) return true;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A website template as one install: the page files that put its sections in order.
|
|
3
|
+
*
|
|
4
|
+
* `astralkit add zest --website` installs every section of the template as a component (the same files, in the same
|
|
5
|
+
* folder, as installing each alone), then writes one file per page that renders them in page order:
|
|
6
|
+
*
|
|
7
|
+
* Next.js, App Router app/zest/page.tsx (and app/luma/about/page.tsx for a template of several pages)
|
|
8
|
+
* React, Pages Router src/components/ui/zest-page.jsx
|
|
9
|
+
* HTML src/components/ui/zest/index.html (and about.html beside it)
|
|
10
|
+
*
|
|
11
|
+
* Nothing here talks to the network or the terminal: it works out file names and file contents.
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'fs';
|
|
14
|
+
import path from 'path';
|
|
15
|
+
|
|
16
|
+
const posix = (file) => file.replace(/\\/g, '/');
|
|
17
|
+
|
|
18
|
+
/** zest-hero -> ZestHero. A name that would start with a digit gets a letter in front. */
|
|
19
|
+
export function componentName(slug) {
|
|
20
|
+
const name = String(slug).split(/[^a-zA-Z0-9]+/).filter(Boolean).map(part => part[0].toUpperCase() + part.slice(1)).join('');
|
|
21
|
+
return /^[A-Z]/.test(name) ? name : `Page${name}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The App Router folder of a Next.js project, if it has one. */
|
|
25
|
+
export function appDirOf(cwd) {
|
|
26
|
+
for (const candidate of ['src/app', 'app']) if (fs.existsSync(path.join(cwd, candidate))) return candidate;
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Where each page of the website goes. Returns { kind, pages: [{ page, file }], base }:
|
|
32
|
+
* kind 'routes' real routes (Next.js App Router); `base` is the address of the home page (/zest)
|
|
33
|
+
* kind 'components' one component per page, next to the sections
|
|
34
|
+
* kind 'html' one .html file per page, in a folder of their own
|
|
35
|
+
*/
|
|
36
|
+
export function planPages({ site, framework, cwd, componentsDir, ext }) {
|
|
37
|
+
if (framework === 'html') {
|
|
38
|
+
return { kind: 'html', base: null, pages: site.pages.map(page => ({ page, file: posix(path.join(componentsDir, site.slug, page.file)) })) };
|
|
39
|
+
}
|
|
40
|
+
const appDir = framework === 'nextjs' ? appDirOf(cwd) : null;
|
|
41
|
+
if (appDir) {
|
|
42
|
+
return {
|
|
43
|
+
kind: 'routes',
|
|
44
|
+
base: `/${site.slug}`,
|
|
45
|
+
pages: site.pages.map(page => ({ page, file: posix(path.join(appDir, site.slug, page.route, `page${ext}`)) })),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
kind: 'components',
|
|
50
|
+
base: null,
|
|
51
|
+
pages: site.pages.map(page => ({ page, file: posix(path.join(componentsDir, `${site.slug}${page.route ? `-${page.route}` : ''}-page${ext}`)) })),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* A page as a React component: the navigation and the footer are landmarks of their own, so they sit beside <main>,
|
|
57
|
+
* not in it. `sections` are the slugs that are really in the project; `importFrom(slug)` is the path to import one from.
|
|
58
|
+
*/
|
|
59
|
+
export function pageSource({ site, page, sections, importFrom, command }) {
|
|
60
|
+
const header = sections[0]?.endsWith('-navigation') ? sections[0] : null;
|
|
61
|
+
const footer = sections.length > 1 && sections[sections.length - 1].endsWith('-footer') ? sections[sections.length - 1] : null;
|
|
62
|
+
const body = sections.filter(slug => slug !== header && slug !== footer);
|
|
63
|
+
const tag = (slug) => `<${componentName(slug)} />`;
|
|
64
|
+
const title = page.route ? `${site.name}: ${page.name}` : site.name;
|
|
65
|
+
return [
|
|
66
|
+
'/**',
|
|
67
|
+
` * ${title}`,
|
|
68
|
+
` * The ${site.name} website template${page.route ? `, its "${page.name}" page` : ''}: its sections, in page order.`,
|
|
69
|
+
` * Written by: ${command}`,
|
|
70
|
+
' *',
|
|
71
|
+
' * Each section is a component of its own. The business in them is sample content: keep the layout,',
|
|
72
|
+
' * and change the name, the copy and the photos in the section files.',
|
|
73
|
+
' */',
|
|
74
|
+
...sections.map(slug => `import ${componentName(slug)} from '${importFrom(slug)}';`),
|
|
75
|
+
'',
|
|
76
|
+
`export default function ${componentName(`${site.slug}-${page.route || ''}-page`)}() {`,
|
|
77
|
+
' return (',
|
|
78
|
+
' <>',
|
|
79
|
+
...(header ? [` ${tag(header)}`] : []),
|
|
80
|
+
...(body.length ? [' <main>', ...body.map(slug => ` ${tag(slug)}`), ' </main>'] : []),
|
|
81
|
+
...(footer ? [` ${tag(footer)}`] : []),
|
|
82
|
+
' </>',
|
|
83
|
+
' );',
|
|
84
|
+
'}',
|
|
85
|
+
'',
|
|
86
|
+
].join('\n');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* A template of several pages links them by file name (href="about.html", href="index.html#care"), which is right
|
|
91
|
+
* for a folder of HTML files. In an app with real routes those links are pointed at the routes: /luma/about, /luma#care.
|
|
92
|
+
* Only links to the template's own pages are touched. Returns the new code and how many links changed.
|
|
93
|
+
*/
|
|
94
|
+
export function pointLinksAtRoutes(code, site, base) {
|
|
95
|
+
const routeOf = new Map(site.pages.map(page => [page.file, page.route ? `${base}/${page.route}` : base]));
|
|
96
|
+
let changed = 0;
|
|
97
|
+
const out = code.replace(/(href=)(["'])([\w-]+\.html)(#[^"']*)?\2/g, (whole, attr, quote, file, hash = '') => {
|
|
98
|
+
if (!routeOf.has(file)) return whole;
|
|
99
|
+
changed++;
|
|
100
|
+
return `${attr}${quote}${routeOf.get(file)}${hash}${quote}`;
|
|
101
|
+
});
|
|
102
|
+
return { code: out, changed };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* One HTML page out of the HTML files of its sections. Each section file is a whole document with the same kind of
|
|
107
|
+
* head (the AstralKit and Tailwind scripts, the template's palette and typefaces): the page takes every head line
|
|
108
|
+
* once, in the order first seen, and the bodies one after another.
|
|
109
|
+
*/
|
|
110
|
+
export function composeHtml({ site, page, documents }) {
|
|
111
|
+
const head = [];
|
|
112
|
+
const seen = new Set();
|
|
113
|
+
const bodies = [];
|
|
114
|
+
for (const html of documents) {
|
|
115
|
+
const headPart = /<head[^>]*>([\s\S]*?)<\/head>/i.exec(html)?.[1] || '';
|
|
116
|
+
for (const line of headPart.split('\n').map(text => text.trim()).filter(Boolean)) {
|
|
117
|
+
if (/^<title[\s>]/i.test(line) || seen.has(line)) continue;
|
|
118
|
+
seen.add(line);
|
|
119
|
+
head.push(line);
|
|
120
|
+
}
|
|
121
|
+
const bodyPart = /<body[^>]*>([\s\S]*)<\/body>/i.exec(html)?.[1];
|
|
122
|
+
if (bodyPart) bodies.push(bodyPart.trim());
|
|
123
|
+
}
|
|
124
|
+
const title = (page.route ? `${site.name}: ${page.name}` : site.name).replace(/&/g, '&').replace(/</g, '<');
|
|
125
|
+
const charset = head.findIndex(line => /<meta[^>]+charset/i.test(line));
|
|
126
|
+
const at = charset < 0 ? 0 : charset + 1;
|
|
127
|
+
head.splice(at, 0, `<title>${title}</title>`);
|
|
128
|
+
return [
|
|
129
|
+
`<!-- ${site.name}${page.route ? `: ${page.name}` : ''}. The ${site.name} website template from AstralKit: its sections, in page order. -->`,
|
|
130
|
+
'<!DOCTYPE html>',
|
|
131
|
+
'<html lang="en">',
|
|
132
|
+
'<head>',
|
|
133
|
+
...head.map(line => ` ${line}`),
|
|
134
|
+
'</head>',
|
|
135
|
+
'<body>',
|
|
136
|
+
bodies.join('\n'),
|
|
137
|
+
'</body>',
|
|
138
|
+
'</html>',
|
|
139
|
+
'',
|
|
140
|
+
].join('\n');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The import path of a file from another file's folder, without its extension ("../../components/ui/zest-hero"). */
|
|
144
|
+
export function relativeImport(fromFile, toFile) {
|
|
145
|
+
const to = posix(path.relative(path.dirname(fromFile), toFile)).replace(/\.(tsx|jsx|ts|js)$/, '');
|
|
146
|
+
return to.startsWith('.') ? to : `./${to}`;
|
|
147
|
+
}
|