@luz-ds/ai 0.1.0 → 0.2.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 (70) hide show
  1. package/README.md +8 -6
  2. package/dist/skills/luz/SKILL.md +14 -10
  3. package/dist/skills/luz/assets/examples/landing-service/app.js +51 -0
  4. package/dist/skills/luz/assets/examples/landing-service/index.html.tpl +83 -0
  5. package/dist/skills/luz/assets/facts.json +5 -5
  6. package/dist/skills/luz/assets/templates/app.html.tpl +31 -28
  7. package/dist/skills/luz/assets/templates/blog.html.tpl +19 -19
  8. package/dist/skills/luz/assets/templates/docs.html.tpl +18 -18
  9. package/dist/skills/luz/assets/templates/landing.html.tpl +19 -19
  10. package/dist/skills/luz/references/components/accordion.md +16 -0
  11. package/dist/skills/luz/references/components/alert.md +13 -0
  12. package/dist/skills/luz/references/components/app-bar.md +34 -0
  13. package/dist/skills/luz/references/components/badge.md +7 -0
  14. package/dist/skills/luz/references/components/bar-list.md +18 -0
  15. package/dist/skills/luz/references/components/breadcrumb.md +13 -0
  16. package/dist/skills/luz/references/components/button-link.md +7 -0
  17. package/dist/skills/luz/references/components/button.md +7 -0
  18. package/dist/skills/luz/references/components/card.md +10 -0
  19. package/dist/skills/luz/references/components/checkbox.md +10 -0
  20. package/dist/skills/luz/references/components/code-block.md +9 -0
  21. package/dist/skills/luz/references/components/copy.md +8 -0
  22. package/dist/skills/luz/references/components/dashboard.md +27 -0
  23. package/dist/skills/luz/references/components/date.md +11 -0
  24. package/dist/skills/luz/references/components/dropdown.md +17 -0
  25. package/dist/skills/luz/references/components/email.md +11 -0
  26. package/dist/skills/luz/references/components/faq.md +38 -0
  27. package/dist/skills/luz/references/components/fieldset.md +17 -0
  28. package/dist/skills/luz/references/components/figure.md +12 -0
  29. package/dist/skills/luz/references/components/hero.md +24 -0
  30. package/dist/skills/luz/references/components/meter.md +8 -0
  31. package/dist/skills/luz/references/components/modal.md +26 -0
  32. package/dist/skills/luz/references/components/navbar.md +23 -0
  33. package/dist/skills/luz/references/components/number.md +11 -0
  34. package/dist/skills/luz/references/components/objects-actions.md +20 -0
  35. package/dist/skills/luz/references/components/objects-grid.md +15 -0
  36. package/dist/skills/luz/references/components/objects-list.md +10 -0
  37. package/dist/skills/luz/references/components/objects-media.md +12 -0
  38. package/dist/skills/luz/references/components/objects-page.md +18 -0
  39. package/dist/skills/luz/references/components/objects-shell.md +15 -0
  40. package/dist/skills/luz/references/components/page-header.md +12 -0
  41. package/dist/skills/luz/references/components/pagination.md +15 -0
  42. package/dist/skills/luz/references/components/progress.md +8 -0
  43. package/dist/skills/luz/references/components/prose.md +19 -0
  44. package/dist/skills/luz/references/components/radio.md +13 -0
  45. package/dist/skills/luz/references/components/range.md +10 -0
  46. package/dist/skills/luz/references/components/section.md +26 -0
  47. package/dist/skills/luz/references/components/select.md +14 -0
  48. package/dist/skills/luz/references/components/sidebar.md +23 -0
  49. package/dist/skills/luz/references/components/site-footer.md +17 -0
  50. package/dist/skills/luz/references/components/site-header.md +26 -0
  51. package/dist/skills/luz/references/components/skip-link.md +11 -0
  52. package/dist/skills/luz/references/components/stat.md +17 -0
  53. package/dist/skills/luz/references/components/switch.md +11 -0
  54. package/dist/skills/luz/references/components/table-sort.md +23 -0
  55. package/dist/skills/luz/references/components/table.md +17 -0
  56. package/dist/skills/luz/references/components/tabs.md +12 -0
  57. package/dist/skills/luz/references/components/tag.md +7 -0
  58. package/dist/skills/luz/references/components/text.md +11 -0
  59. package/dist/skills/luz/references/components/textarea.md +11 -0
  60. package/dist/skills/luz/references/components/toast.md +15 -0
  61. package/dist/skills/luz/references/components/tool.md +38 -0
  62. package/dist/skills/luz/references/components.md +101 -0
  63. package/dist/skills/luz/references/design.md +204 -0
  64. package/dist/skills/luz/references/done.md +45 -0
  65. package/dist/skills/luz/references/kinds/app.md +8 -1
  66. package/dist/skills/luz/references/kinds/landing.md +2 -2
  67. package/dist/skills/luz/references/magic.md +84 -0
  68. package/dist/skills/luz/references/reviewers.md +12 -2
  69. package/dist/skills/luz/scripts/luz.mjs +275 -8
  70. package/package.json +1 -1
@@ -0,0 +1,84 @@
1
+ # Magic, step by step
2
+
3
+ `/luz magic <description>` builds a prototype from one description, with no question. The rules of the Magic section of SKILL.md hold at every step; this is the order to work in, and an example.
4
+
5
+ ## 1. Decide
6
+
7
+ Decide each answer from the description, and write it down:
8
+
9
+ - **The kind**, by what the visitor does on the page:
10
+
11
+ | The page | Kind |
12
+ | --- | --- |
13
+ | Presents a thing and leads to a step that happens later (buy, book, sign up) | landing |
14
+ | Presents one tool to visitors, who use it right there, with the text that explains it around it | landing, with an integrated service: the hero is the tool |
15
+ | Is the tool itself, used again and again: settings and a result, a dashboard, a back office | app |
16
+ | Is posts or articles | blog |
17
+ | Is the documentation of something | docs |
18
+
19
+ If none fits, take landing, the simplest, and say so in the report.
20
+ - **The stack**: plain HTML, unless the description names Astro.
21
+ - **The name**: the one it gives, or a short one that fits.
22
+ - **The language**: the one the description is written in; one only.
23
+ - **The look**: LUZ's default.
24
+ - **For an app**, what `references/kinds/app.md` would have asked: no navigation under four views; one view to start with; the data made in the browser, or sample data marked as sample; and the words of the empty, loading and error states.
25
+
26
+ ## 2. Write a short spec
27
+
28
+ Five lines, in the message of your decisions, before you write any file, and a sixth with the direction of `references/design.md` (composition, voice of the type, density). Say first which reading of the description you took when it could be read two ways. It is not a question: it makes you decide before you write.
29
+
30
+ 1. The main action, and the verb on its button.
31
+ 2. What the person gets from it, and where it shows.
32
+ 3. The views (one, for a prototype, unless the description needs more).
33
+ 4. The empty, loading and error states, in words.
34
+ 5. What is left out of this prototype.
35
+
36
+ ## 3. Keep it small
37
+
38
+ Build the least that shows the description: one view, one main action, the fields that change the result most, defaults that give a result at once. Add only after every point of `references/done.md` passes. A prototype has one script, `app.js`, and a second only past about 300 lines; never more than five files of JavaScript. Leave the rest for the list of what is left out.
39
+
40
+ ## 4. Write the page
41
+
42
+ Show the page full: an app or a tool gets a few rows of sample data, with a line on the page that says "Sample data" (in the page's language), so the person sees what it looks like in use; write its empty state too. No sample price, review, address or real name.
43
+
44
+ Work in small steps: one block of the page, `shot`, a line on what you see, fix it, then the next block. A landing with an integrated service starts from `assets/examples/landing-service/`: copy its two files over the starter page (`index.html.tpl` as `index.html`), then change every word. Run `magic` with the flags you decided. Then read `references/design.md`, take the recipe of the page, and fill the starter with the blocks of `references/components.md`: remove what the recipe does not use (a sidebar under four views, sample cards, an account menu with no accounts). For an app with a script, follow "JavaScript" in `references/kinds/app.md`.
45
+
46
+ ## 5. Check
47
+
48
+ Run the check after each step that writes HTML or CSS, and fix every finding (R6).
49
+
50
+ ## 6. Look
51
+
52
+ Run `shot --target <folder>`. Give it --target and nothing else: its pictures go to a new temporary folder. Open them if you can see images, and go through `references/done.md`: its criteria and its score. When `shot` says the first primary action is below the first screen at 1440 px, Layout is 0: move the result up (a shorter lead, the tool recipe, two fields a row). Fix every point at 0, then run the check and `shot` again.
53
+
54
+ ## 7. Review
55
+
56
+ If your assistant lists a helper called `luz-agent-ux` (the agent of luz-ai, which only reads), give it the page and the file list, and apply what it marks high priority, within R5 and R9. If it lists none, go through the design list of `references/reviewers.md` yourself. Then the other lists of `references/reviewers.md`.
57
+
58
+ ## 8. Report
59
+
60
+ What you decided, the spec, the files, what the check found, the score of `references/done.md`, what you left out, and what neither you nor the check could verify. It is a prototype: say what the person should do to make it theirs.
61
+
62
+ ## Example
63
+
64
+ The description: "a responsive web page to generate fake QA data by country and category, in batches, with export, for GitHub Pages".
65
+
66
+ The message of decisions:
67
+
68
+ > Kind: app, a tool of one view (settings and a result), so no sidebar. Stack: plain HTML. Name: Fake data. Language: English. Folder: ./fake-data. The check runs with npx, which downloads the checker once.
69
+ >
70
+ > 1. Main action: the data is made as the settings change, so there is no button; "Download CSV" is the primary action.
71
+ > 2. The person gets a table of rows, on the right on a wide screen and first on a phone.
72
+ > 3. One view.
73
+ > 4. Empty: "Choose at least one field." Error: "The batch is too large: 1,000 rows at most."
74
+ > 5. Left out: more than three countries, formats other than CSV and JSON, saving settings.
75
+
76
+ The files:
77
+
78
+ ```
79
+ fake-data/
80
+ index.html the tool recipe: settings (country, category, rows; more in a details) and the result table
81
+ app.js makes the rows from the settings, fills the table, copies and downloads
82
+ ```
83
+
84
+ The report gives the decisions, the files, "the check found nothing", what `shot` measured (no sideways scroll, the download button in the first screen at 1440 px), the score (for example 16 of 18: the phone at 1, three buttons in a row; type at 1, the lead is two lines too long), with the reason of each 1, what was left out, and that nobody tried it with a screen reader.
@@ -4,11 +4,21 @@ Go through each list on the page the check cannot see. If you have a helper for
4
4
 
5
5
  ## Structure and accessibility
6
6
 
7
- - Every page has `lang`, one `h1`, landmarks (`header`, `nav`, `main`, `footer`) and a skip link that reaches `main`.
7
+ - Every page has `lang`, one `h1`, landmarks (`header`, `main`, `footer`, and `nav` when there is navigation) and a skip link that reaches `main`.
8
8
  - Native elements do the job (`button`, `a`, `dialog`, `details`, `form`, `table`). ARIA only where no element does it.
9
9
  - Every image has `alt` text that says what it shows, or `alt=""` when it is decoration.
10
10
  - Every control has a visible label. The current page has `aria-current="page"` in the navigation.
11
- - The page works without JavaScript. A state class such as `is-active` is set by LUZ's scripts and never typed.
11
+ - The page works without JavaScript. A tool that cannot (it computes in the browser) keeps its heading, text and form readable without it, and says in a `<noscript>` what does not work and why. A state class such as `is-active` is set by LUZ's scripts and never typed.
12
+
13
+ ## Design
14
+
15
+ The points of `references/done.md`, with the page in front of you or its HTML:
16
+
17
+ - The result or the product is the first thing the eye finds, and the setup comes second.
18
+ - One primary action per view, named by its verb; the other actions are secondary, outline or ghost.
19
+ - Labels of one to three words; more than seven controls are grouped or folded; the defaults give a result.
20
+ - No sidebar under four destinations; no sideways scroll at 390 px; the result one tap away on a phone.
21
+ - Every action answers where the person acted; empty, loading and error states have words.
12
22
 
13
23
  ## Style
14
24
 
@@ -4,17 +4,22 @@
4
4
  *
5
5
  * It reads and reports; `init`, `site new` (and `magic`, the same), `agent add`, `skill add` and `remove` write or delete: only the files
6
6
  * they name, under the folder it is given, and never over one that exists unless --force says so (`magic` never takes it). It never asks a question, never reaches the
7
- * network and runs no program. It finds its own data from its own path, so it works from any folder.
7
+ * network and runs no program but one: `shot` starts the browser of the machine (Chrome, Chromium or Edge), headless, to take
8
+ * pictures of a page, and writes them only into a new folder of its own. It finds its own data from its own path, so it works from any folder.
8
9
  *
9
10
  * luz-ai doctor [--dir <folder>] [--json]
10
11
  * luz-ai lint [path...] [--target portable|claude] [--json]
11
12
  * luz-ai facts [--json]
12
13
  * luz-ai site new --name <name> --kind <kind> --stack <stack> --target <folder> [--lang <code>] [--dry-run] [--force] [--json]
14
+ * luz-ai shot --target <folder> [--page <file>] [--out <folder>] [--json]
13
15
  *
14
16
  * Exit codes: 0 nothing blocks, 1 a problem blocks, 2 the command was used wrongly.
15
17
  */
16
- import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
17
- import { basename, dirname, join, relative, resolve, sep } from "node:path";
18
+ import { spawn } from "node:child_process";
19
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
20
+ import { createServer } from "node:http";
21
+ import { homedir, tmpdir } from "node:os";
22
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
18
23
  import { fileURLToPath } from "node:url";
19
24
  import { parseArgs } from "node:util";
20
25
 
@@ -49,7 +54,7 @@ const BANNER = [
49
54
  /** The banner and a blank line, or nothing when stdout is not a terminal. */
50
55
  const banner = (tty) => (tty ? `${BANNER.join("\n")}\n\n` : "");
51
56
 
52
- const HELP = `luz-ai: starts a site with LUZ and lints the skills and subagents of a project. Only init, new, magic, add and remove write.
57
+ const HELP = `luz-ai: starts a site with LUZ and lints the skills and subagents of a project. Only init, new, magic, add and remove write; shot writes only its pictures, in a new folder.
53
58
 
54
59
  Usage:
55
60
  luz-ai <command> [options]
@@ -66,6 +71,7 @@ Commands:
66
71
  facts the versions, the kinds of site and the stacks of this release
67
72
  doctor the project, the assistants it has and whether their skills and agents pass lint
68
73
  lint the front matter and the body of skills (SKILL.md) and subagents (.md)
74
+ shot pictures and measures of a page at 390, 820 and 1440 px, with the browser of the machine (in a new folder)
69
75
 
70
76
  Options:
71
77
  --json one JSON object on stdout
@@ -190,6 +196,29 @@ Example:
190
196
  luz-ai remove luz-agent-optimiza --dry-run
191
197
  `;
192
198
 
199
+ const HELP_SHOT = `luz-ai shot: pictures of a page at three widths, and what can be measured on them, to look at before saying it is done.
200
+
201
+ Usage:
202
+ luz-ai shot --target <folder> [--page <file>] [--click <selector>] [--out <folder>] [--json]
203
+
204
+ --target the folder of the site
205
+ --page the page in it, index.html by default
206
+ --click a CSS selector: a second picture at each width after that element is clicked (a copy button, a tab)
207
+ --out a folder that does not exist yet, for the pictures; by default a new folder in the temporary folder of the machine
208
+
209
+ It starts the browser of the machine, headless: Chrome, Chromium or Edge, or the one LUZ_BROWSER names (a path to one of
210
+ them; any other program is refused). It runs no other program, changes nothing in the site and writes only the pictures,
211
+ into its own new folder. The page is served from the site's folder on 127.0.0.1, at a port the system picks, for the
212
+ browser alone and only while the pictures are taken, so its scripts run as on a real host. It takes the first screen at 390 x 844,
213
+ 820 x 1180 and 1440 x 900, and measures each: how far the page scrolls sideways, how many screens it is long, where the
214
+ first primary action is and whether it is in the first screen, how many primary actions there are and how many "…" are left.
215
+ The page loads LUZ from its CDN, as a visitor's browser would. With no browser it says so and exits 0: then read the HTML
216
+ against references/done.md.
217
+
218
+ Example:
219
+ luz-ai shot --target ./acme
220
+ `;
221
+
193
222
  const HELP_FACTS = `luz-ai facts: the versions of the LUZ packages, the kinds of site and the stacks of this release.
194
223
 
195
224
  Usage:
@@ -587,6 +616,18 @@ function runDoctor(dir) {
587
616
  if (differ.length) warnings.push(`${entry.name} is not the same in ${SKILL_PLACES[0]} and ${SKILL_PLACES[1]} (${differ.slice(0, 3).join(", ")}${differ.length > 3 ? ", …" : ""}): ${entry.name === SELF ? "run init --target claude,codex --force" : skillNames().includes(entry.name) ? `run add ${entry.name} --force` : "make the two copies the same"}`);
588
617
  }
589
618
  }
619
+ // The luz skill of the project against the one of this luz-ai: an old copy has no design guide and no shot, and says nothing
620
+ const own = resolve(HERE, "..");
621
+ const carried = (map) => new Map([...map].filter(([k]) => ["SKILL.md", "LICENSE", "agents", "assets", "references", "scripts"].includes(k.split(sep)[0]) && !k.split(sep).some((part) => part.startsWith("."))));
622
+ for (const place of SKILL_PLACES) {
623
+ const copy = join(dir, place, SELF);
624
+ if (!existsSync(copy) || isLink(copy) || realpathSync(copy) === realpathSync(own)) continue;
625
+ const mine = carried(tree(own));
626
+ const theirs = carried(tree(copy));
627
+ // A name of the project's copy is written only when it is plain (no hidden character, no line break)
628
+ const differ = [...new Set([...mine.keys(), ...theirs.keys()])].filter((k) => mine.get(k) !== theirs.get(k)).map((k) => k.split(sep).join("/")).filter((k) => /^[\w./-]{1,120}$/.test(k)).sort();
629
+ if (differ.length) warnings.push(`the luz skill in ${place} is not the one of luz-ai ${FACTS.versions.ai} (${differ.slice(0, 3).join(", ")}${differ.length > 3 ? `, and ${differ.length - 3} more` : ""}): tell the person, who updates it with npx @luz-ds/ai@latest init --target ${place.startsWith(".claude") ? "claude" : "codex"} --force`);
630
+ }
590
631
  const { checked, problems: found, warnings: soft } = runCheck([], dir);
591
632
  problems.push(...found);
592
633
  warnings.push(...soft);
@@ -595,6 +636,216 @@ function runDoctor(dir) {
595
636
 
596
637
  // ---- facts and site new ---------------------------------------------------------------------------------------
597
638
 
639
+ // The widths of references/done.md: a phone, a tablet, a laptop
640
+ const SHOT_SIZES = [[390, 844], [820, 1180], [1440, 900]];
641
+ const BROWSERS = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome", "microsoft-edge", "microsoft-edge-stable", "msedge"];
642
+ // The names a browser's program has: LUZ_BROWSER is taken only when it names one, so it never runs another program
643
+ const BROWSER_NAMES = new Set([...BROWSERS, "chrome-headless-shell", "google chrome", "microsoft edge"]);
644
+ const isBrowserName = (path) => BROWSER_NAMES.has(basename(path).toLowerCase().replace(/\.exe$/, ""));
645
+ const BROWSER_APPS = [
646
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
647
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
648
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
649
+ ...["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"].flatMap((v) => (process.env[v] ? [join(process.env[v], "Google/Chrome/Application/chrome.exe"), join(process.env[v], "Microsoft/Edge/Application/msedge.exe")] : [])),
650
+ ];
651
+
652
+ /** The browser to start: LUZ_BROWSER, else the first of the usual names on the PATH, else the usual places. Null when none. */
653
+ function findBrowser() {
654
+ const named = process.env.LUZ_BROWSER;
655
+ if (named) return isAbsolute(named) && existsSync(named) && isBrowserName(named) ? named : null;
656
+ const exts = process.platform === "win32" ? [".exe", ""] : [""];
657
+ // Not a folder of the project's packages (npx puts node_modules/.bin first) and not a relative one
658
+ for (const dir of (process.env.PATH ?? "").split(delimiter).filter((d) => d && isAbsolute(d) && !d.split(/[\\/]/).includes("node_modules"))) {
659
+ for (const name of BROWSERS) for (const ext of exts) if (existsSync(join(dir, name + ext))) return join(dir, name + ext);
660
+ }
661
+ return BROWSER_APPS.find((p) => existsSync(p)) ?? null;
662
+ }
663
+
664
+ /** The script the server adds to the page for a run of `shot`: it measures, or it clicks, then it writes into the DOM. */
665
+ function shotScript(mode, click) {
666
+ const measure = `const root = document.documentElement;
667
+ const primary = [...document.querySelectorAll(".luz-btn--primary, button:not([type]), button[type=submit]")].filter((e) => e.getClientRects().length);
668
+ const top = primary.length ? Math.round(primary[0].getBoundingClientRect().top + scrollY) : null;
669
+ const pre = document.createElement("pre");
670
+ pre.id = "luz-shot-m";
671
+ pre.textContent = JSON.stringify({ overflowX: Math.max(0, root.scrollWidth - innerWidth), screens: Math.round((root.scrollHeight / innerHeight) * 10) / 10,
672
+ primary: primary.length, primaryTop: top, primaryInFirstScreen: top !== null && top < innerHeight, placeholders: document.body.innerText.split("…").length - 1 });
673
+ document.body.append(pre);`;
674
+ // The selector is the person's flag, never the page's: it is written as JSON, with < escaped, so it cannot close the script
675
+ const clicker = `const target = document.querySelector(${JSON.stringify(click ?? "").replace(/</g, "\\x3c")});
676
+ if (target) target.click();`;
677
+ return `<script>addEventListener("load", () => setTimeout(() => {
678
+ ${mode === "click" ? clicker : measure}
679
+ }, 1500));</script>`;
680
+ }
681
+
682
+ // What the server of `shot` hands out: the files of the site, by their extension
683
+ const TYPES = { ".html": "text/html", ".htm": "text/html", ".css": "text/css", ".js": "text/javascript", ".mjs": "text/javascript", ".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".avif": "image/avif", ".ico": "image/x-icon", ".woff2": "font/woff2", ".woff": "font/woff", ".txt": "text/plain", ".csv": "text/csv", ".xml": "application/xml" };
684
+
685
+ /**
686
+ * A server of the site's folder on 127.0.0.1, at a port the system picks, for the browser of `shot` only: GET and HEAD, the
687
+ * files under the folder and nothing outside it (a link out is refused), so a module script loads as it does on a real host.
688
+ * The page gets the script of the run it is asked for (`?luz-shot=measure` or `click`); no other query changes anything.
689
+ * It answers only the Host it was given, and never a hidden file, a folder of packages or a type of file it does not know.
690
+ */
691
+ function serveSite(root, page, click) {
692
+ const base = realpathSync(root);
693
+ let host = "";
694
+ const server = createServer((req, res) => {
695
+ const deny = (code) => {
696
+ res.writeHead(code, { "content-type": "text/plain" });
697
+ res.end(String(code));
698
+ };
699
+ if (req.method !== "GET" && req.method !== "HEAD") return deny(405);
700
+ // Only the browser of shot, at the address it was given: no other name for this machine (a page rebinding a domain)
701
+ if (req.headers.host !== host) return deny(421);
702
+ let url;
703
+ try {
704
+ url = new URL(req.url ?? "/", "http://127.0.0.1");
705
+ } catch {
706
+ return deny(400);
707
+ }
708
+ let rel;
709
+ try {
710
+ rel = decodeURIComponent(url.pathname).replace(/^\/+/, "");
711
+ } catch {
712
+ return deny(400);
713
+ }
714
+ if (rel === "" || rel.endsWith("/")) rel += "index.html";
715
+ // No hidden file or folder (.env, .git) and no package of the project: a page's script could read them and send them away
716
+ const hidden = (path) => path.split(/[\\/]/).some((part) => part.startsWith(".") || part === "node_modules");
717
+ if (hidden(rel)) return deny(404);
718
+ const wanted = resolve(base, rel);
719
+ let real;
720
+ try {
721
+ real = realpathSync(wanted);
722
+ } catch {
723
+ return deny(404);
724
+ }
725
+ if (real !== base && !real.startsWith(base + sep)) return deny(403);
726
+ // The same on the real path: a link inside the site to a hidden folder is refused too
727
+ if (hidden(relative(base, real))) return deny(404);
728
+ if (!statSync(real).isFile()) return deny(404);
729
+ const ext = real.slice(real.lastIndexOf(".")).toLowerCase();
730
+ if (!Object.hasOwn(TYPES, ext)) return deny(404);
731
+ let body = readFileSync(real);
732
+ const mode = url.searchParams.get("luz-shot");
733
+ if (relative(base, real) === page && (mode === "measure" || mode === "click")) {
734
+ const html = body.toString("utf-8");
735
+ const script = shotScript(mode, click);
736
+ body = Buffer.from(/<\/body>/i.test(html) ? html.replace(/<\/body>/i, () => `${script}</body>`) : html + script);
737
+ }
738
+ res.writeHead(200, { "content-type": TYPES[ext], "cache-control": "no-store" });
739
+ res.end(req.method === "HEAD" ? undefined : body);
740
+ });
741
+ return new Promise((done, fail) => {
742
+ server.once("error", fail);
743
+ server.listen(0, "127.0.0.1", () => {
744
+ host = `127.0.0.1:${server.address().port}`;
745
+ done(server);
746
+ });
747
+ });
748
+ }
749
+
750
+ /** Runs the browser with no shell and no wait on the loop, so the server keeps answering it; a minute at most. */
751
+ function runBrowser(browser, args) {
752
+ return new Promise((done) => {
753
+ const child = spawn(browser, args, { shell: false, stdio: ["ignore", "pipe", "ignore"] });
754
+ let stdout = "";
755
+ child.stdout.on("data", (chunk) => {
756
+ if (stdout.length < 4_000_000) stdout += chunk;
757
+ });
758
+ const timer = setTimeout(() => child.kill("SIGKILL"), 60000);
759
+ child.on("error", (error) => {
760
+ clearTimeout(timer);
761
+ done({ status: null, stdout, error });
762
+ });
763
+ child.on("close", (status, signal) => {
764
+ clearTimeout(timer);
765
+ done({ status, signal, stdout });
766
+ });
767
+ });
768
+ }
769
+
770
+ /** What a page may write as its measures: numbers and true or false under the names `shot` measures, nothing else. */
771
+ const MEASURES = { overflowX: "number", screens: "number", primary: "number", primaryTop: "number", primaryInFirstScreen: "boolean", placeholders: "number" };
772
+ function cleanMeasures(raw) {
773
+ if (raw === null || typeof raw !== "object") return null;
774
+ const out = {};
775
+ for (const [key, type] of Object.entries(MEASURES)) {
776
+ const value = raw[key];
777
+ if (typeof value === type && (type !== "number" || Number.isFinite(value))) out[key] = value;
778
+ else if (key === "primaryTop" && value === null) out[key] = null;
779
+ else return null;
780
+ }
781
+ return out;
782
+ }
783
+
784
+ async function runShot(values) {
785
+ if (!values.target) return { error: "--target is missing: the folder of the site. Example: luz-ai shot --target ./acme" };
786
+ const site = resolve(values.target);
787
+ const page = (values.page ?? "index.html").split("\\").join("/");
788
+ if (/[\r\n]/.test(page) || HIDDEN.test(page) || isAbsolute(page) || page.split("/").includes("..")) return { error: "--page is a file inside --target, on one line, with no .." };
789
+ const click = values.click;
790
+ if (click !== undefined && (click.length === 0 || click.length > 200 || /[\r\n<]/.test(click) || HIDDEN.test(click))) return { error: "--click is one CSS selector on one line, of 200 characters at most, with no <" };
791
+ const file = join(site, page);
792
+ if (!existsSync(file) || !statSync(file).isFile()) return { error: `${file} was not found` };
793
+ const browser = findBrowser();
794
+ const report = { ok: false, browser, page: file, out: null, shots: [], next: [] };
795
+ if (!browser) {
796
+ report.next = [process.env.LUZ_BROWSER ? "LUZ_BROWSER does not name the program of Chrome, Chromium or Edge, so nothing was started. Read the HTML against references/done.md, say that nobody looked at the page rendered, and tell the person." : "No browser was found. Read the HTML against references/done.md and say that nobody looked at the page rendered; the person may set LUZ_BROWSER to the path of Chrome, Chromium or Edge."];
797
+ return { report };
798
+ }
799
+ if (values.out && existsSync(resolve(values.out))) return { error: `${resolve(values.out)} exists: shot writes only into a folder that does not exist yet` };
800
+ // A browser installed as a snap sees only the home folder, not the temporary folder of the machine
801
+ const out = values.out ? resolve(values.out) : mkdtempSync(join(/[\\/]snap[\\/]/.test(browser) ? homedir() : tmpdir(), "luz-shot-"));
802
+ if (values.out) mkdirSync(out);
803
+ report.out = out;
804
+ const server = await serveSite(site, relative(realpathSync(site), realpathSync(file)), click);
805
+ const origin = `http://127.0.0.1:${server.address().port}/`;
806
+ const at = (mode) => `${origin}${page.split("/").map(encodeURIComponent).join("/")}${mode ? `?luz-shot=${mode}` : ""}`;
807
+ const base = ["--headless", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check", "--mute-audio", "--disable-background-networking", "--disable-extensions", "--disable-sync", "--virtual-time-budget=10000", `--user-data-dir=${join(out, "profile")}`];
808
+ try {
809
+ for (const [width, height] of SHOT_SIZES) {
810
+ const size = `--window-size=${width},${height}`;
811
+ const picture = join(out, `${width}.png`);
812
+ const shotRun = await runBrowser(browser, [...base, size, `--screenshot=${picture}`, at(null)]);
813
+ const dump = await runBrowser(browser, [...base, size, "--dump-dom", at("measure")]);
814
+ let measures = null;
815
+ const json = /<pre id="luz-shot-m">([^<]*)<\/pre>/.exec(dump.stdout ?? "")?.[1];
816
+ try {
817
+ measures = json ? cleanMeasures(JSON.parse(json.replace(/&quot;/g, '"').replace(/&amp;/g, "&"))) : null;
818
+ } catch {
819
+ measures = null;
820
+ }
821
+ const shot = { width, height, file: existsSync(picture) ? picture : null, measures, error: shotRun.error ? String(shotRun.error.message) : existsSync(picture) ? null : `the browser wrote no picture (exit ${shotRun.status ?? shotRun.signal})` };
822
+ if (click !== undefined) {
823
+ const after = join(out, `${width}-after-click.png`);
824
+ await runBrowser(browser, [...base, size, `--screenshot=${after}`, at("click")]);
825
+ shot.afterClick = existsSync(after) ? after : null;
826
+ }
827
+ report.shots.push(shot);
828
+ }
829
+ } finally {
830
+ await new Promise((done) => server.close(() => done()));
831
+ }
832
+ report.ok = report.shots.some((s) => s.file);
833
+ report.next = report.ok
834
+ ? ["Open each picture now and say in one line what you see in it before you go on; then go through references/done.md with the pictures and the measures. If you cannot see images, say so in the report."]
835
+ : [`The browser wrote nothing in ${out} (a browser installed as a flatpak may not reach that folder). Read the HTML against references/done.md, say that nobody looked at the page rendered, and tell the person.`];
836
+ return { report };
837
+ }
838
+
839
+ function shotText(r) {
840
+ if (!r.browser) return `shot: no browser found\n ${r.next.join("\n ")}\n`;
841
+ const line = (s) => {
842
+ const m = s.measures;
843
+ const what = m && !m.error ? [`sideways ${m.overflowX} px`, `${m.screens} screens`, m.primaryTop === null ? "no primary action" : `first primary at ${m.primaryTop} px${m.primaryInFirstScreen ? " (first screen)" : " (below the first screen)"}`, `${m.primary} primary`, `${m.placeholders} … left`].join(", ") : "no measures";
844
+ return ` ${s.width} px: ${s.file ?? s.error}\n ${what}${s.afterClick ? `\n after the click: ${s.afterClick}` : ""}`;
845
+ };
846
+ return [`shot: ${r.shots.filter((s) => s.file).length} of ${r.shots.length} pictures of ${r.page}, with ${r.browser}`, ...r.shots.map(line), `next: ${r.next.join(" ")}`, ""].join("\n");
847
+ }
848
+
598
849
  function runFacts(json) {
599
850
  if (json) return `${JSON.stringify(FACTS, null, 2)}\n`;
600
851
  const lines = ["facts:", ...Object.entries(FACTS.versions).map(([pkg, v]) => ` @luz-ds/${pkg} ${v}`), ` kinds: ${FACTS.kinds.join(", ")}`, ` stacks: ${FACTS.stacks.map((s) => (s.page ? s.id : `${s.id} (by hand)`)).join(", ")}`];
@@ -1162,7 +1413,7 @@ export function main(argv, { tty = Boolean(process.stdout.isTTY) } = {}) {
1162
1413
  const [command, ...rest] = argv;
1163
1414
  if (command === "--help" || command === "-h") return show(banner(tty) + HELP);
1164
1415
  if (!command) return usage("a command is missing (init, new, magic, site new, agents, skills, list, add, remove, agent, skill, facts, doctor or lint)", true);
1165
- if (!["init", "site", "agent", "skill", "facts", "doctor", "lint", "list", "remove"].includes(command)) return usage(`"${command}" is not a command (init, new, magic, site new, agents, skills, list, add, remove, agent, skill, facts, doctor, lint)`, true);
1416
+ if (!["init", "site", "agent", "skill", "facts", "doctor", "lint", "list", "remove", "shot"].includes(command)) return usage(`"${command}" is not a command (init, new, magic, site new, agents, skills, list, add, remove, agent, skill, facts, doctor, lint, shot)`, true);
1166
1417
  let args;
1167
1418
  try {
1168
1419
  args = parseArgs({
@@ -1183,17 +1434,20 @@ export function main(argv, { tty = Boolean(process.stdout.isTTY) } = {}) {
1183
1434
  all: { type: "boolean" },
1184
1435
  for: { type: "string" },
1185
1436
  set: { type: "string", multiple: true },
1437
+ page: { type: "string" },
1438
+ click: { type: "string" },
1439
+ out: { type: "string" },
1186
1440
  },
1187
1441
  });
1188
1442
  } catch (error) {
1189
1443
  return usage(error.message);
1190
1444
  }
1191
1445
  const { values, positionals } = args;
1192
- for (const flag of ["dir", "target"]) {
1446
+ for (const flag of ["dir", "target", "out"]) {
1193
1447
  const v = values[flag];
1194
1448
  if (v !== undefined && (/[\r\n]/.test(v) || HIDDEN.test(v) || v.startsWith("-"))) return usage(`--${flag} is a path on one line, with no control or hidden character, and not starting with "-"`);
1195
1449
  }
1196
- if (values.help) return show({ init: HELP_INIT, site: HELP_SITE, agent: HELP_AGENT, skill: HELP_SKILL, facts: HELP_FACTS, doctor: HELP_DOCTOR, lint: HELP_LINT, list: HELP_LIST, remove: HELP_REMOVE }[command]);
1450
+ if (values.help) return show({ init: HELP_INIT, site: HELP_SITE, agent: HELP_AGENT, skill: HELP_SKILL, facts: HELP_FACTS, doctor: HELP_DOCTOR, lint: HELP_LINT, list: HELP_LIST, remove: HELP_REMOVE, shot: HELP_SHOT }[command]);
1197
1451
  if (values.all && command !== "init") return usage("--all is only for init");
1198
1452
  if (magic && !values.help) {
1199
1453
  if (values.force) return usage("magic never takes --force: it writes only into a folder that does not exist yet");
@@ -1256,6 +1510,14 @@ export function main(argv, { tty = Boolean(process.stdout.isTTY) } = {}) {
1256
1510
  return 0;
1257
1511
  }
1258
1512
  if (command === "facts") return show(runFacts(values.json));
1513
+ if (command === "shot") {
1514
+ if (positionals.length) return usage("shot takes no word: use --target <folder>");
1515
+ return runShot(values).then(({ error, report }) => {
1516
+ if (error) return usage(error);
1517
+ process.stdout.write(values.json ? `${JSON.stringify(report, null, 2)}\n` : shotText(report));
1518
+ return 0;
1519
+ });
1520
+ }
1259
1521
  if (command === "lint" && values.target && !["portable", "claude"].includes(values.target)) return usage(`--target is portable or claude, not "${values.target}"`);
1260
1522
  if (command === "doctor" && positionals.length) return usage("doctor takes no path: use --dir <folder>");
1261
1523
 
@@ -1281,4 +1543,9 @@ const started = (() => {
1281
1543
  return false;
1282
1544
  }
1283
1545
  })();
1284
- if (started) process.exitCode = main(process.argv.slice(2));
1546
+ if (started) {
1547
+ // `shot` answers later (its server waits on the browser): its exit code arrives as a promise
1548
+ const code = main(process.argv.slice(2));
1549
+ if (code instanceof Promise) code.then((c) => (process.exitCode = c));
1550
+ else process.exitCode = code;
1551
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luz-ds/ai",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "LUZ Design System — the luz skill for AI assistants (Claude Code, Codex, Gemini CLI, Cursor): it asks what you want to make, writes a starter page that @luz-ds/check reads without a finding, and adds the agents and skills of luz-ai",
5
5
  "license": "MIT",
6
6
  "type": "module",