astralis-cli 0.6.0 → 0.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.
@@ -15,26 +15,31 @@ function exportTarget(pkg, subpath) {
15
15
  * own astralis-ui when it has one new enough, so the generated file matches
16
16
  * the version it will be loaded next to; otherwise the copy bundled with the
17
17
  * CLI. `source` is "project" or "bundled"; `outdated` names a project copy
18
- * that was passed over.
18
+ * that was passed over, and `broken` says why one couldn't be loaded.
19
19
  */
20
20
  export async function loadThemeLibrary(cwd) {
21
21
  let outdated = null;
22
+ let broken = null;
22
23
  const pkgPath = findInstalledLibrary(cwd);
23
24
  if (pkgPath) {
24
- const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
25
- const root = dirname(pkgPath);
26
- const [serializeFile, contrastFile, stylesFile] = THEME_EXPORTS.map((subpath) => exportTarget(pkg, subpath));
27
- if (serializeFile && contrastFile && stylesFile) {
28
- const [serialize, contrast] = await Promise.all(
29
- [serializeFile, contrastFile].map((file) => import(pathToFileURL(join(root, file)).href)),
30
- );
31
- return { serialize, contrast, stylesPath: join(root, stylesFile), version: pkg.version, source: "project" };
25
+ try {
26
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
27
+ const root = dirname(pkgPath);
28
+ const [serializeFile, contrastFile, stylesFile] = THEME_EXPORTS.map((subpath) => exportTarget(pkg, subpath));
29
+ if (serializeFile && contrastFile && stylesFile) {
30
+ const [serialize, contrast] = await Promise.all(
31
+ [serializeFile, contrastFile].map((file) => import(pathToFileURL(join(root, file)).href)),
32
+ );
33
+ return { serialize, contrast, stylesPath: join(root, stylesFile), version: pkg.version, source: "project" };
34
+ }
35
+ outdated = pkg.version;
36
+ } catch (error) {
37
+ broken = error.message;
32
38
  }
33
- outdated = pkg.version;
34
39
  }
35
40
 
36
41
  const [serialize, contrast] = await Promise.all([import("astralis-ui/serialize"), import("astralis-ui/contrast")]);
37
42
  const stylesPath = fileURLToPath(import.meta.resolve("astralis-ui/styles.css"));
38
43
  const version = JSON.parse(readFileSync(join(dirname(stylesPath), "..", "package.json"), "utf8")).version;
39
- return { serialize, contrast, stylesPath, version, source: "bundled", outdated };
44
+ return { serialize, contrast, stylesPath, version, source: "bundled", outdated, broken };
40
45
  }
@@ -0,0 +1,130 @@
1
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { bold, cyan, dim, warn } from "./ui.mjs";
4
+
5
+ /**
6
+ * The one fallback every command uses when it can't find, read, edit or write
7
+ * a file: say what was not done and why, the steps that finish it, how to
8
+ * check, and the docs section that explains it all. test/fallbacks.test.mjs
9
+ * holds every link here to a heading that exists.
10
+ */
11
+
12
+ const SITE = "https://astralis-ui.com/docs";
13
+ export const DOCS = {
14
+ byHand: `${SITE}/installation#by-hand`,
15
+ next: `${SITE}/installation#nextjs-app-router`,
16
+ nextPages: `${SITE}/installation#nextjs-pages-router`,
17
+ vite: `${SITE}/installation#vite--spa`,
18
+ theme: `${SITE}/cli#adding-the-theme-by-hand`,
19
+ devtools: `${SITE}/devtools#by-hand`,
20
+ ci: `${SITE}/validate-in-ci#set-up-ci-by-hand`,
21
+ create: `${SITE}/cli#creating-a-project-by-hand`,
22
+ };
23
+
24
+ /**
25
+ * What one part of a command still needs done by hand. `failed` marks a part
26
+ * the command tried and could not do, which makes the exit code 1; a shape it
27
+ * won't edit leaves it 0. `retry` is the command to run once the cause is fixed.
28
+ */
29
+ export function createGuide({ title, docs, check, retry }) {
30
+ return {
31
+ title,
32
+ docs,
33
+ check,
34
+ retry,
35
+ reasons: [],
36
+ steps: [],
37
+ failed: false,
38
+ /** Record one thing that was not done, as the reader should see it. */
39
+ because(reason, { failed = false } = {}) {
40
+ this.reasons.push(reason);
41
+ this.failed ||= failed;
42
+ return this;
43
+ },
44
+ /** One numbered step: what to do, and the exact code or command. */
45
+ step(text, code) {
46
+ this.steps.push({ text, code });
47
+ return this;
48
+ },
49
+ get needed() {
50
+ return this.reasons.length > 0;
51
+ },
52
+ };
53
+ }
54
+
55
+ const indent = (text, by) =>
56
+ text
57
+ .split("\n")
58
+ .map((line) => (line ? by + line : line))
59
+ .join("\n");
60
+
61
+ /** A guide as the text every command prints, without the leading marker. */
62
+ export function formatGuide(guide) {
63
+ const lines = [`${guide.title}:`, ...guide.reasons.map((reason) => ` - ${reason}`)];
64
+ lines.push("", ` ${bold("Manual setup:")}`);
65
+ guide.steps.forEach(({ text, code }, i) => {
66
+ lines.push(` ${i + 1}. ${text}`);
67
+ if (code) lines.push(cyan(indent(code.trimEnd(), " ")));
68
+ });
69
+ lines.push("");
70
+ if (guide.check) lines.push(` ${bold("Check it worked:")} ${guide.check}`);
71
+ if (guide.retry) lines.push(` ${dim("Or fix the cause and run it again:")} ${cyan(guide.retry)}`);
72
+ lines.push(` ${bold("Full guide:")} ${cyan(guide.docs)}`);
73
+ return lines.join("\n");
74
+ }
75
+
76
+ /** Print a guide if it has anything to say, and set the exit code it asks for. */
77
+ export function printGuide(guide) {
78
+ if (!guide?.needed) return;
79
+ console.log();
80
+ warn(formatGuide(guide));
81
+ if (guide.failed) process.exitCode = 1;
82
+ }
83
+
84
+ const PLAIN = {
85
+ EACCES: "it is read-only, or you don't have permission",
86
+ EPERM: "it is read-only, or you don't have permission",
87
+ EROFS: "the disk is read-only",
88
+ EISDIR: "it is a folder, not a file",
89
+ ENOENT: "it doesn't exist",
90
+ ENOTDIR: "part of its path is a file, not a folder",
91
+ EEXIST: "a file is in the way of its folder",
92
+ EBUSY: "another program has it open",
93
+ ENOSPC: "the disk is full",
94
+ };
95
+
96
+ /** Why a file operation failed, in plain words with the system's code. */
97
+ function fileProblem(error) {
98
+ return PLAIN[error?.code] ? `${PLAIN[error.code]} (${error.code})` : (error?.message ?? String(error));
99
+ }
100
+
101
+ /** { text } or { problem }; never throws. */
102
+ export function tryRead(path) {
103
+ try {
104
+ return { text: readFileSync(path, "utf8") };
105
+ } catch (error) {
106
+ return { problem: fileProblem(error) };
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Write a file, making its folder. Null on success, else why not; never
112
+ * throws. A dry run writes nothing but still reports a file it couldn't replace.
113
+ */
114
+ export function tryWrite(path, text, { dryRun = false } = {}) {
115
+ try {
116
+ if (dryRun) {
117
+ if (existsSync(path)) accessSync(path, constants.W_OK);
118
+ return null;
119
+ }
120
+ mkdirSync(dirname(path), { recursive: true });
121
+ writeFileSync(path, text);
122
+ return null;
123
+ } catch (error) {
124
+ return fileProblem(error);
125
+ }
126
+ }
127
+
128
+ /** Why a spawned command failed. */
129
+ export const commandProblem = (result) =>
130
+ result.error?.code === "ENOENT" ? "the program was not found" : (result.error?.message ?? `it exited with code ${result.status}`);
@@ -1,8 +1,8 @@
1
1
  /* ==========================================================================
2
2
  Issue snapshots (format astralis-snapshot/1): the unit of evidence in the
3
- feedback loop. Built by the DevTools from a rendered page and by
4
- `astralis report` from source files, and checked here before anything is
5
- sent. github.mjs turns one into a GitHub issue.
3
+ feedback loop. Built by the DevTools from a rendered page, and checked here
4
+ before anything is sent. github.mjs turns one into a GitHub issue. CLI
5
+ versions before 0.8.0 also built them from source files (source "cli").
6
6
 
7
7
  Pure JavaScript with no Node built-ins, so the same code runs in the
8
8
  browser overlay, the dev-server bridge, the CLI and the platform.
@@ -1,4 +1,4 @@
1
- import { join, dirname } from "node:path";
1
+ import { join, dirname, extname } from "node:path";
2
2
 
3
3
  /**
4
4
  * The welcome screen `astralis create` leaves behind.
@@ -29,6 +29,7 @@ import { join, dirname } from "node:path";
29
29
  */
30
30
  export const STARTER_IMPORTS = [
31
31
  "Badge",
32
+ "Box",
32
33
  "Button",
33
34
  "Card",
34
35
  "CardBody",
@@ -47,39 +48,72 @@ function starterSource() {
47
48
  } from "astralis-ui";
48
49
 
49
50
  /**
50
- * Astralis is wired up — this screen is rendering through the provider, the
51
- * precompiled stylesheet and the token scales.
52
- *
53
- * It is an ordinary file in your project. Edit it, or delete it and start over.
54
- */
55
- /**
56
- * The Astralis mark — four blocks, the last still being placed. Painted with
57
- * the brand token rather than fixed hex, so it re-colours with the theme.
51
+ * The Astralis mark: four blocks, the last still being placed. Painted with
52
+ * the brand token, so it re-colours with your theme, and the last block
53
+ * settles into place on hover.
58
54
  */
59
- function AstralisMark() {
55
+ function AstralisLogo() {
60
56
  return (
61
- <svg viewBox="0 0 32 32" width="28" height="28" aria-hidden="true" style={{ overflow: "visible" }}>
62
- <g fill="var(--astralis-color-brand-500)">
63
- <rect x="3" y="17" width="12" height="12" rx="3" />
64
- <rect x="17" y="17" width="12" height="12" rx="3" />
65
- <rect x="3" y="3" width="12" height="12" rx="3" />
66
- <rect x="19" y="1" width="12" height="12" rx="3" opacity="0.6" transform="rotate(14 25 7)" />
67
- </g>
68
- </svg>
57
+ <Flex className="starter-logo" alignItems="center" gap="2" color="base">
58
+ <style>{\`
59
+ .starter-block {
60
+ transform-box: fill-box;
61
+ transform-origin: center;
62
+ rotate: 14deg;
63
+ opacity: 0.6;
64
+ transition: rotate 300ms ease-out, translate 300ms ease-out, opacity 300ms ease-out;
65
+ }
66
+ .starter-logo:hover .starter-block { rotate: 0deg; translate: -2px 2px; opacity: 1; }
67
+ @media (prefers-reduced-motion: reduce) { .starter-block { transition: none; } }
68
+ \`}</style>
69
+ <svg viewBox="0 0 32 32" width="24" height="24" aria-hidden="true" style={{ overflow: "visible" }}>
70
+ <g fill="var(--astralis-color-brand-500)">
71
+ <rect x="3" y="17" width="12" height="12" rx="3" />
72
+ <rect x="17" y="17" width="12" height="12" rx="3" />
73
+ <rect x="3" y="3" width="12" height="12" rx="3" />
74
+ <rect className="starter-block" x="19" y="1" width="12" height="12" rx="3" />
75
+ </g>
76
+ </svg>
77
+ {/* 15px and 10px sit between the type scale's steps. */}
78
+ <Text as="span" fontFamily="heading" weight="semibold" letterSpacing="tight" lineHeight="normal" style={{ fontSize: "15px" }}>
79
+ Astralis
80
+ <Box
81
+ as="span"
82
+ ml="1.5"
83
+ px="1.5"
84
+ py="0.5"
85
+ rounded="md"
86
+ border="normal"
87
+ borderColor="base"
88
+ bg="subtle"
89
+ color="muted"
90
+ style={{
91
+ verticalAlign: "middle",
92
+ fontSize: "10px",
93
+ fontWeight: 500,
94
+ textTransform: "uppercase",
95
+ letterSpacing: "0.1em",
96
+ }}
97
+ >
98
+ UI
99
+ </Box>
100
+ </Text>
101
+ </Flex>
69
102
  );
70
103
  }
71
104
 
105
+ /**
106
+ * Astralis is wired up: this screen renders through the provider, the
107
+ * precompiled stylesheet and the token scales.
108
+ *
109
+ * It is an ordinary file in your project. Edit it, or delete it and start over.
110
+ */
72
111
  export default function Welcome() {
73
112
  return (
74
113
  <Container maxW="4xl" px={{ base: "6", lg: "8" }} py={{ base: "16", lg: "24" }}>
75
114
  <Stack gap="10" alignItems="stretch">
76
115
  <Flex justifyContent="between" alignItems="center" gap="4">
77
- <Flex alignItems="center" gap="3">
78
- <AstralisMark />
79
- <Badge variant="subtle" colorScheme="brand" size="xs">
80
- Astralis UI
81
- </Badge>
82
- </Flex>
116
+ <AstralisLogo />
83
117
  <ThemeToggle variant="text" colorScheme="gray" size="sm" aria-label="Toggle theme" />
84
118
  </Flex>
85
119
 
@@ -88,9 +122,8 @@ export default function Welcome() {
88
122
  You&apos;re set up.
89
123
  </Heading>
90
124
  <Text size="lg" color="muted" lineHeight="relaxed">
91
- Everything here is themed through one accent channel. Change{" "}
92
- <Code>colorScheme</Code> on any component and the rest follows — no
93
- rebuild, no Tailwind config in your project.
125
+ Welcome to Astralis. Your project is ready: edit this page to start building, add
126
+ ready-made blocks from the CLI, or browse the docs to see every component.
94
127
  </Text>
95
128
  </Stack>
96
129
 
@@ -128,7 +161,7 @@ export default function Welcome() {
128
161
  Try it
129
162
  </Heading>
130
163
  <Text color="muted" lineHeight="relaxed">
131
- Drop in a prebuilt section with <Code>astralis add hero-01</Code>,
164
+ Drop in a prebuilt section with <Code>npx astralis-cli add hero-01</Code>,
132
165
  or import anything from <Code>astralis-ui</Code> and compose your
133
166
  own.
134
167
  </Text>
@@ -162,11 +195,11 @@ export default function Welcome() {
162
195
  *
163
196
  * Next renders `page.tsx` beside the root layout; Vite renders `App.tsx`
164
197
  * beside `main.tsx`. The extension follows the entry, so a JavaScript project
165
- * gets .jsx (the source carries no type annotations either way).
198
+ * gets .jsx or .js (the source carries no type annotations either way).
166
199
  */
167
200
  export function starterTarget(framework, entryPath) {
168
201
  const dir = dirname(entryPath);
169
- const ext = entryPath.endsWith("x") ? (entryPath.endsWith(".tsx") ? "tsx" : "jsx") : "tsx";
202
+ const ext = extname(entryPath).slice(1);
170
203
  return join(dir, framework === "next" ? `page.${ext}` : `App.${ext}`);
171
204
  }
172
205
 
@@ -23,6 +23,10 @@
23
23
  "inherit" would copy the nearest w above, not the parent's width
24
24
  - a style prop the component does not take, which reaches the HTML as a
25
25
  stray attribute and changes nothing (unknown-style-prop)
26
+ - hover/focusVisible/active on a component that takes (unknown-state-prop)
27
+ no state props: only the box and text groups resolve them
28
+ - a prop the component's type does not take at all, when the spec lists
29
+ the type's whole prop set (ownProps) (unknown-prop)
26
30
  - a component left empty that its type requires children for (missing-children):
27
31
  tsc catches it too, but agents and copied snippets produce code no one type-checks
28
32
 
@@ -61,6 +65,12 @@ const DOCTRINE_PAINT_PROPS = new Set([
61
65
  so they are never reported as stray. */
62
66
  const HTML_ATTRIBUTE_NAMES = new Set(["width", "height", "size", "color", "wrap", "align", "border"]);
63
67
 
68
+ /* The recipe props a paint-prop hint may point to, when the component has them. */
69
+ const LOOK_PROPS = ["variant", "size", "colorScheme"];
70
+
71
+ /* Props React itself takes on every component, whatever its type declares. */
72
+ const REACT_PROPS = new Set(["key", "ref", "children"]);
73
+
64
74
  /* Packages whose components are icons, for the icon-only Button rule. */
65
75
  const ICON_PACKAGES = /^(lucide-react|react-icons(\/.*)?|@heroicons\/react(\/.*)?|@radix-ui\/react-icons|@tabler\/icons-react|@phosphor-icons\/react)$/;
66
76
 
@@ -98,6 +108,9 @@ export function prepareSpec(spec) {
98
108
  // them and older code must keep validating.
99
109
  bpKeys: new Set(["base", ...Object.keys(spec.breakpoints), ...Object.keys(spec.containerBreakpoints ?? {})]),
100
110
  stateProps: new Set(Object.keys(spec.states)),
111
+ // React's DOM and SVG attributes any component's type inherits (spec builds
112
+ // that list each component's ownProps). Null when the spec cannot say.
113
+ domAttributeSet: spec.domAttributes ? new Set(spec.domAttributes) : null,
101
114
  // Every exported value and type (spec 3+). Null for older specs.
102
115
  exportSet: spec.exports ? new Set(spec.exports) : null,
103
116
  };
@@ -418,7 +431,33 @@ function checkOwnValue(ctx, name, comp, prop, attr) {
418
431
  }
419
432
  }
420
433
 
421
- function checkComponentProp(ctx, identity, comp, allowed, attr, prop) {
434
+ /** The hint for a paint prop on a component that owns its look: its own
435
+ * variant/size/colorScheme, or for a part, the ones on the compound it belongs to. */
436
+ function lookHint(ctx, name, comp, prop) {
437
+ const lookOf = (entry) => LOOK_PROPS.filter((p) => entry?.props?.[p]);
438
+ const or = (list) => (list.length > 1 ? `${list.slice(0, -1).join(", ")} or ${list.at(-1)}` : list[0]);
439
+ if (comp.partOf) {
440
+ const owner = comp.partOf;
441
+ const vocab = lookOf(ctx.spec.components[owner]);
442
+ return `${name} is part of ${owner} and has no look of its own: ` +
443
+ (vocab.length ? `set ${or(vocab)} on the ${owner}, or ` : "") + `put ${prop} on a Box inside it`;
444
+ }
445
+ const vocab = lookOf(comp);
446
+ return vocab.length
447
+ ? `${name} owns how it looks; reach for ${or(vocab)}`
448
+ : `${name} owns how it looks; put ${prop} on a Box around it`;
449
+ }
450
+
451
+ /** Whether the component's type takes `prop` at all. Null when the spec cannot
452
+ * say: it lists ownProps only for types it read whole (not polymorphic ones). */
453
+ function takesProp(ctx, comp, allowed, prop) {
454
+ if (!comp.ownProps || (comp.domProps && !ctx.domAttributeSet)) return null;
455
+ if (allowed[prop] || comp.ownProps.includes(prop) || REACT_PROPS.has(prop) || /^data-/.test(prop)) return true;
456
+ if (comp.props?.[prop] || comp.scalarProps?.[prop] || comp.overrides?.includes(prop)) return true;
457
+ return Boolean(comp.domProps && (/^on[A-Z]/.test(prop) || ctx.domAttributeSet.has(prop)));
458
+ }
459
+
460
+ function checkComponentProp(ctx, identity, comp, allowed, attr, prop, open) {
422
461
  const name = identity.specName;
423
462
  if (comp.exclude?.includes(prop)) {
424
463
  const short = allowed[prop]?.short;
@@ -439,6 +478,14 @@ function checkComponentProp(ctx, identity, comp, allowed, attr, prop) {
439
478
  // Link only those they take as base props. Elsewhere no claim.
440
479
  if (comp.groups.includes("box")) checkStateValue(ctx, name, prop, attr.value);
441
480
  else if (comp.groups.includes("text")) checkStateValue(ctx, name, prop, attr.value, allowed);
481
+ // Only box- and text-group components resolve state props. Decided only
482
+ // when the spec read the type (ownStyleProps), and never against a state
483
+ // name the component declares itself.
484
+ else if (comp.ownStyleProps && !comp.props?.[prop] && !comp.scalarProps?.[prop] && !comp.ownProps?.includes(prop)) {
485
+ ctx.error("unknown-state-prop", attr,
486
+ `${name} does not take ${prop}: state props work on Box, the layout primitives, Text, Heading and Link, ` +
487
+ `so here it changes nothing (put ${prop} on a Box around ${name})`);
488
+ }
442
489
  return;
443
490
  }
444
491
  if (!overridden && allowed[prop]) {
@@ -463,10 +510,22 @@ function checkComponentProp(ctx, identity, comp, allowed, attr, prop) {
463
510
  ctx.error("unknown-style-prop", attr,
464
511
  `${name} does not take ${prop}: it reaches the HTML as a stray attribute and changes nothing` +
465
512
  (recipe
466
- ? ` (${name} owns how it looks; reach for variant, size or colorScheme)`
513
+ ? ` (${lookHint(ctx, name, comp, prop)})`
467
514
  : ` (${name} takes ${comp.groups.length ? `${comp.groups.join(", ")} props` : "no style props"}; put ${prop} on a Box around it)`));
515
+ return;
468
516
  }
469
- // Anything else: DOM prop or open-typed, no claim.
517
+ // Style-prop names are the rule above's; `as` or a spread may hand the
518
+ // element another component's props, so neither is judged.
519
+ if (open || ctx.stylePropNames.has(prop) || takesProp(ctx, comp, allowed, prop) !== false) return;
520
+ const candidates = [...comp.ownProps, ...Object.keys(allowed)].filter((p) => !/^(aria|data)-|^on[A-Z]/.test(p) || /^on[A-Z]/.test(prop));
521
+ // A near spelling, else the one prop that ends or starts with it (fit, objectFit).
522
+ const lower = prop.toLowerCase();
523
+ const affixed = candidates.filter((p) => lower.length >= 3 && (p.toLowerCase().endsWith(lower) || p.toLowerCase().startsWith(lower)));
524
+ const near = (affixed.length === 1 ? affixed[0] : null) ?? suggest(prop, candidates);
525
+ ctx.error("unknown-prop", attr,
526
+ `${name} has no ${prop} prop: ` +
527
+ (comp.domProps ? "it reaches the HTML as a stray attribute and changes nothing" : "it changes nothing") +
528
+ (near ? ` (did you mean "${near}"?)` : ""));
470
529
  }
471
530
 
472
531
  /* ---- one element: identity, then every attribute ----------------------------- */
@@ -524,6 +583,7 @@ function analyzeOpening(ctx, node) {
524
583
  if (comp) for (const g of comp.groups) Object.assign(allowed, ctx.spec.propGroups[g]);
525
584
 
526
585
  let hasSpread = false;
586
+ const open = node.attributes.some((a) => a.type === "JSXSpreadAttribute") || Boolean(findAttribute(node, "as"));
527
587
  let hasAlt = false;
528
588
  let hasAriaCover = false; // aria-label / aria-labelledby / aria-hidden
529
589
 
@@ -541,7 +601,7 @@ function analyzeOpening(ctx, node) {
541
601
  } else if (prop === "role") checkRole(ctx, attr);
542
602
  else if (prop === "tabIndex") checkTabIndex(ctx, attr);
543
603
  else if (prop === "alt") hasAlt = true;
544
- else if (comp) checkComponentProp(ctx, identity, comp, allowed, attr, prop);
604
+ else if (comp) checkComponentProp(ctx, identity, comp, allowed, attr, prop, open);
545
605
  }
546
606
 
547
607
  if (identity.specName === "Flex") {
@@ -0,0 +1,145 @@
1
+ import { existsSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { posix } from "./ui.mjs";
4
+ import { tryRead } from "./manual.mjs";
5
+
6
+ /** The lines that wire Astralis into an app, shared by init's edits and the steps it prints instead. */
7
+
8
+ export const PROVIDER_IMPORT = 'import { AstralisProvider } from "astralis-ui";';
9
+ export const STYLES_IMPORT = 'import "astralis-ui/styles.css";';
10
+ export const PROVIDER_OPEN = '<AstralisProvider defaultTheme="system">';
11
+ export const PROVIDER_CLOSE = "</AstralisProvider>";
12
+
13
+ // Applies `.astralis-dark` before first paint so a stored/system dark
14
+ // preference never flashes light (same script the Astralis docs site uses).
15
+ export const THEME_INIT_CONST =
16
+ 'const astralisThemeInit = `(function(){try{var t=localStorage.getItem("astralis-ui-theme");var d=t==="dark"||((!t||t==="system")&&window.matchMedia("(prefers-color-scheme: dark)").matches);if(d)document.documentElement.classList.add("astralis-dark");}catch(e){}})();`;';
17
+ export const THEME_INIT_ELEMENT = "<script dangerouslySetInnerHTML={{ __html: astralisThemeInit }} />";
18
+
19
+ /** The edits each kind of entry file needs, in order. */
20
+ export const WIRING = {
21
+ next: ["imports", "provider", "themeScript", "html"],
22
+ nextPages: ["imports", "provider"],
23
+ vite: ["imports", "provider"],
24
+ };
25
+
26
+ const RENDERED = { next: "{children}", nextPages: "<Component {...pageProps} />", vite: "<App />" };
27
+
28
+ /** The manual step for one of those edits, as guide.step()'s arguments. */
29
+ export function wiringStep(id, file, kind) {
30
+ const rendered = RENDERED[kind];
31
+ const steps = {
32
+ imports: [`Open ${file} and add these after its other imports:`, `${PROVIDER_IMPORT}\n${STYLES_IMPORT}`],
33
+ provider: [
34
+ `In ${file}, put the provider around what it renders (usually ${rendered}):`,
35
+ `${PROVIDER_OPEN}\n ${rendered}\n${PROVIDER_CLOSE}`,
36
+ ],
37
+ themeScript: [
38
+ `In ${file}, stop dark mode flashing light. This goes after the imports:`,
39
+ THEME_INIT_CONST,
40
+ ],
41
+ html: [`In ${file} (or the file that holds your <html>), let that script change <html> before React starts:`, '<html lang="en" suppressHydrationWarning>'],
42
+ };
43
+ return id === "themeScript"
44
+ ? [steps.themeScript, [`In ${file} (or the file that holds your <body>), run it as the first thing inside <body>:`, THEME_INIT_ELEMENT]]
45
+ : [steps[id]];
46
+ }
47
+
48
+ /** The whole of a new entry file, for a project that has none. */
49
+ export function newEntrySource(kind, file) {
50
+ const typed = /\.tsx$/.test(file);
51
+ if (kind === "vite") {
52
+ return `import { createRoot } from "react-dom/client";
53
+ ${PROVIDER_IMPORT}
54
+ ${STYLES_IMPORT}
55
+ import App from "./App";
56
+
57
+ createRoot(document.getElementById("root")${typed ? "!" : ""}).render(
58
+ ${PROVIDER_OPEN}
59
+ <App />
60
+ ${PROVIDER_CLOSE},
61
+ );`;
62
+ }
63
+ if (kind === "nextPages") {
64
+ return `${typed ? 'import type { AppProps } from "next/app";\n' : ""}${PROVIDER_IMPORT}
65
+ ${STYLES_IMPORT}
66
+
67
+ export default function App({ Component, pageProps }${typed ? ": AppProps" : ""}) {
68
+ return (
69
+ ${PROVIDER_OPEN}
70
+ <Component {...pageProps} />
71
+ ${PROVIDER_CLOSE}
72
+ );
73
+ }`;
74
+ }
75
+ return `${PROVIDER_IMPORT}
76
+ ${STYLES_IMPORT}
77
+
78
+ ${THEME_INIT_CONST}
79
+
80
+ export default function RootLayout({ children }${typed ? ": { children: React.ReactNode }" : ""}) {
81
+ return (
82
+ <html lang="en" suppressHydrationWarning>
83
+ <body>
84
+ ${THEME_INIT_ELEMENT}
85
+ ${PROVIDER_OPEN}{children}${PROVIDER_CLOSE}
86
+ </body>
87
+ </html>
88
+ );
89
+ }`;
90
+ }
91
+
92
+ const firstExisting = (cwd, candidates) => candidates.find((path) => existsSync(join(cwd, path))) ?? null;
93
+
94
+ /** A root layout one folder down, as route groups and [locale] routing have it: app/(site)/layout.tsx. */
95
+ function nestedLayout(cwd, appDir) {
96
+ try {
97
+ for (const entry of readdirSync(join(cwd, appDir), { withFileTypes: true })) {
98
+ if (!entry.isDirectory() || !/^[([]/.test(entry.name)) continue;
99
+ const layout = readdirSync(join(cwd, appDir, entry.name)).find((name) => /^layout\.(tsx|jsx|js)$/.test(name));
100
+ if (layout) return `${appDir}/${entry.name}/${layout}`;
101
+ }
102
+ } catch {
103
+ // An unreadable app folder only costs the hint.
104
+ }
105
+ return null;
106
+ }
107
+
108
+ /** The module script index.html loads: Vite's own definition of the entry. */
109
+ function viteEntryFromHtml(cwd) {
110
+ const html = tryRead(join(cwd, "index.html")).text ?? "";
111
+ for (const [tag] of html.matchAll(/<script\b[^>]*>/g)) {
112
+ const src = /\bsrc=["']\/?([^"':]+)["']/.exec(tag)?.[1];
113
+ if (src && /\btype=["']module["']/.test(tag)) return posix(src);
114
+ }
115
+ return null;
116
+ }
117
+
118
+ /**
119
+ * Where the wiring most likely goes when findEntryFile() found nothing:
120
+ * { file, exists, kind, appDir }. `kind` picks the steps' code and docs link;
121
+ * `appDir` is where a Next.js route handler belongs.
122
+ */
123
+ export function likelyEntry(cwd, framework) {
124
+ const found = (file, rest) => ({ file, exists: existsSync(join(cwd, file)), ...rest });
125
+ if (framework === "vite") {
126
+ const file = viteEntryFromHtml(cwd) ?? firstExisting(cwd, ["src/index.tsx", "src/index.jsx"]) ?? "src/main.tsx";
127
+ return found(file, { kind: "vite", appDir: null });
128
+ }
129
+ const appDir = firstExisting(cwd, ["app", "src/app"]);
130
+ if (appDir) return found(nestedLayout(cwd, appDir) ?? `${appDir}/layout.tsx`, { kind: "next", appDir });
131
+ const pages = firstExisting(cwd, ["pages", "src/pages"]);
132
+ if (pages) {
133
+ const file = firstExisting(cwd, ["tsx", "jsx", "js"].map((ext) => `${pages}/_app.${ext}`)) ?? `${pages}/_app.tsx`;
134
+ return found(file, { kind: "nextPages", appDir: pages === "pages" ? "app" : "src/app" });
135
+ }
136
+ const guess = existsSync(join(cwd, "src")) ? "src/app" : "app";
137
+ return found(`${guess}/layout.tsx`, { kind: "next", appDir: guess });
138
+ }
139
+
140
+ /** Add the steps that wire `ids` into an entry: edits to a file that exists, or the whole of one that doesn't. */
141
+ export function addWiringSteps(guide, { file, exists = true, kind }, ids = WIRING[kind]) {
142
+ if (!exists) return guide.step(`Create ${file} (or use the file your app starts from) with:`, newEntrySource(kind, file));
143
+ for (const id of ids) for (const step of wiringStep(id, file, kind)) guide.step(...step);
144
+ return guide;
145
+ }