create-ailk 0.46.6 → 0.48.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 (144) hide show
  1. package/README.md +180 -43
  2. package/component-catalog.json +223 -285
  3. package/component-catalog.md +1 -1
  4. package/dist/apply-design.d.ts +26 -68
  5. package/dist/apply-design.js +150 -322
  6. package/dist/cli.js +152 -17
  7. package/dist/compare-chrome.d.ts +108 -0
  8. package/dist/compare-chrome.js +481 -0
  9. package/dist/compare-look.d.ts +94 -0
  10. package/dist/compare-look.js +378 -0
  11. package/dist/copy.js +1 -1
  12. package/dist/design-compile.d.ts +17 -21
  13. package/dist/design-compile.js +32 -56
  14. package/dist/design-files.d.ts +93 -0
  15. package/dist/design-files.js +312 -0
  16. package/dist/design-home.d.ts +4 -2
  17. package/dist/design-home.js +88 -6
  18. package/dist/design-names.d.ts +13 -0
  19. package/dist/design-names.js +76 -0
  20. package/dist/design-package.d.ts +46 -56
  21. package/dist/design-package.js +285 -288
  22. package/dist/design-presets.d.ts +41 -0
  23. package/dist/design-presets.js +83 -4
  24. package/dist/design-scaffold.d.ts +12 -2
  25. package/dist/design-scaffold.js +72 -34
  26. package/dist/generated/design-settings.d.ts +56 -0
  27. package/dist/generated/design-settings.js +237 -0
  28. package/dist/index.d.ts +1 -1
  29. package/dist/index.js +2 -2
  30. package/dist/inventory.d.ts +3 -2
  31. package/dist/inventory.js +10 -4
  32. package/dist/lib/design-checks.d.ts +46 -0
  33. package/dist/lib/design-checks.js +79 -1
  34. package/dist/lib/env-catalog.js +5 -1
  35. package/dist/lib/module-license-gate.d.ts +1 -1
  36. package/dist/lib/module-license-gate.js +1 -1
  37. package/dist/lib/render-verdict.d.ts +13 -1
  38. package/dist/lib/render-verdict.js +41 -1
  39. package/dist/look-hub.d.ts +44 -0
  40. package/dist/look-hub.js +130 -0
  41. package/dist/look-record.d.ts +35 -0
  42. package/dist/look-record.js +85 -0
  43. package/dist/look-samples.d.ts +66 -0
  44. package/dist/look-samples.js +456 -0
  45. package/dist/look-settings.d.ts +53 -0
  46. package/dist/look-settings.js +363 -0
  47. package/dist/module-architecture.js +12 -0
  48. package/dist/parse-args.d.ts +10 -6
  49. package/dist/parse-args.js +26 -13
  50. package/dist/programmatic.d.ts +1 -19
  51. package/dist/programmatic.js +65 -103
  52. package/dist/retired-design-bodies.d.ts +29 -0
  53. package/dist/retired-design-bodies.js +51 -0
  54. package/dist/seed-flows.d.ts +1 -1
  55. package/dist/seed-flows.js +12 -14
  56. package/dist/seed-workspace.d.ts +4 -1
  57. package/dist/seed-workspace.js +139 -17
  58. package/dist/site-chrome.d.ts +41 -41
  59. package/dist/site-chrome.js +50 -70
  60. package/dist/site-fonts.d.ts +10 -14
  61. package/dist/site-fonts.js +5 -1
  62. package/dist/starter-grid.d.ts +2 -2
  63. package/dist/strip-look-copies.d.ts +67 -0
  64. package/dist/strip-look-copies.js +591 -0
  65. package/dist/template-manifest.d.ts +6 -14
  66. package/dist/template-manifest.js +0 -9
  67. package/dist/template-record.d.ts +3 -1
  68. package/dist/template-record.js +3 -1
  69. package/dist/topology.d.ts +15 -0
  70. package/dist/topology.js +60 -0
  71. package/dist/update.d.ts +57 -1
  72. package/dist/update.js +742 -13
  73. package/package.json +3 -4
  74. package/site-templates/aliases/hub.TEMPLATE-MANIFEST.json +2 -31
  75. package/site-templates/designs/minimalism/DESIGN.md +163 -297
  76. package/site-templates/designs/minimalism/LOOK.md +42 -0
  77. package/site-templates/designs/minimalism/design.yaml +167 -0
  78. package/site-templates/designs/standard/DESIGN.md +145 -149
  79. package/site-templates/designs/standard/LOOK.md +42 -0
  80. package/site-templates/designs/standard/design.yaml +72 -0
  81. package/site-templates/marketing-site/TEMPLATE-MANIFEST.json +2 -31
  82. package/site-templates/marketing-site/TEMPLATE-MANIFEST.md +1 -25
  83. package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.json +2 -31
  84. package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.md +1 -25
  85. package/site-templates/shapes/local-business-service/TEMPLATE-MANIFEST.json +2 -31
  86. package/site-templates/shapes/local-business-service/TEMPLATE-MANIFEST.md +1 -25
  87. package/site-templates/shapes/organization-service/TEMPLATE-MANIFEST.json +2 -31
  88. package/site-templates/shapes/organization-service/TEMPLATE-MANIFEST.md +1 -25
  89. package/site-templates/shapes/person-service/TEMPLATE-MANIFEST.json +2 -31
  90. package/site-templates/shapes/person-service/TEMPLATE-MANIFEST.md +1 -25
  91. package/site-templates/shapes/person-service/content/_site.mdx +0 -26
  92. package/templates/.claude/rules/extending.md +3 -2
  93. package/templates/.env.example +11 -4
  94. package/templates/CLAUDE.md +1 -1
  95. package/templates/DESIGN.md +145 -149
  96. package/templates/README.md +15 -16
  97. package/templates/apps/api/.env.example +29 -4
  98. package/templates/apps/api/CLAUDE.md +7 -4
  99. package/templates/apps/api/src/__tests__/vercel-handler.test.ts +176 -2
  100. package/templates/apps/api/src/lib/__mocks__/prisma.ts +30 -4
  101. package/templates/apps/api/src/vercel-handler.ts +32 -2
  102. package/templates/apps/mcp/.env.example +8 -0
  103. package/templates/apps/mcp/CLAUDE.md +5 -3
  104. package/templates/apps/web/.env.example +10 -3
  105. package/templates/apps/web/CLAUDE.md +31 -4
  106. package/templates/apps/web/app/[locale]/layout.tsx +141 -77
  107. package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +13 -3
  108. package/templates/apps/web/app/not-found.tsx +11 -11
  109. package/templates/apps/web/auth.ts +48 -35
  110. package/templates/apps/web/jest.config.cjs +5 -0
  111. package/templates/apps/web/lib/__tests__/hub-site-config.test.ts +542 -10
  112. package/templates/apps/web/lib/__tests__/library-fonts.test.ts +35 -0
  113. package/templates/apps/web/lib/__tests__/page-chrome-navigation.test.ts +233 -0
  114. package/templates/apps/web/lib/__tests__/page-chrome.test.ts +123 -26
  115. package/templates/apps/web/lib/__tests__/section-look.test.ts +150 -0
  116. package/templates/apps/web/lib/__tests__/site-identity-feature-list.test.ts +19 -1
  117. package/templates/apps/web/lib/__tests__/site-navigation.test.ts +288 -0
  118. package/templates/apps/web/lib/__tests__/site-theme.test.ts +81 -289
  119. package/templates/apps/web/lib/deck-page.ts +3 -10
  120. package/templates/apps/web/lib/deploy-fonts.ts +12 -0
  121. package/templates/apps/web/lib/hub-site-config.ts +237 -29
  122. package/templates/apps/web/lib/library-fonts.ts +41 -0
  123. package/templates/apps/web/lib/mcp-oauth.ts +11 -4
  124. package/templates/apps/web/lib/page-chrome.ts +105 -20
  125. package/templates/apps/web/lib/section-look.ts +28 -0
  126. package/templates/apps/web/lib/site-design.ts +205 -0
  127. package/templates/apps/web/lib/site-navigation.ts +208 -0
  128. package/templates/apps/web/lib/site-theme-head.ts +98 -13
  129. package/templates/apps/web/lib/site-theme.ts +40 -62
  130. package/templates/apps/web/messages/en.json +0 -6
  131. package/templates/apps/web/next.config.mjs +213 -11
  132. package/templates/apps/web/package.json +2 -0
  133. package/templates/apps/web/site-pages.config.tsx +4 -2
  134. package/templates/content/_site.mdx +0 -26
  135. package/templates/design.yaml +75 -0
  136. package/templates/project.yaml +14 -0
  137. package/versions.json +52 -51
  138. package/site-templates/marketing-site/DESIGN.md +0 -259
  139. package/site-templates/marketing-site-free/DESIGN.md +0 -259
  140. package/site-templates/saas-product/DESIGN.md +0 -259
  141. package/templates/apps/web/lib/__tests__/deck-page.test.ts +0 -288
  142. package/templates/apps/web/lib/__tests__/site-theme-head.test.ts +0 -70
  143. package/templates/apps/web/lib/site-chrome.ts +0 -46
  144. package/templates/apps/web/lib/site-fonts.ts +0 -15
@@ -0,0 +1,456 @@
1
+ /**
2
+ * A look's sample images (#12472, spec
3
+ * docs/specs/12472-each-look-in-the-library-spec.md D2, D3): a look whose
4
+ * directory has `samples/` carries one picture per kind of image slot its
5
+ * sample pages draw, described by `samples/samples.json`. A scaffold wearing
6
+ * that look copies them to `apps/web/public/look/<look>/` and puts them in the
7
+ * empty image slots of its seeded pages.
8
+ *
9
+ * A path design is third-party input (§ 9): its folder name, manifest, files
10
+ * and LOOK.md reach file paths and page text, so `readLookSamples` checks every
11
+ * one of them, and reads every sample's bytes, before the scaffold writes
12
+ * anything; `fillLookSamples` plans every page edit and checks its destination
13
+ * before its first write, and writes the bytes `readLookSamples` checked.
14
+ *
15
+ * Whether a look "has samples" is one rule everywhere (Clarifications): an
16
+ * entry named `samples` in its directory, of any type — found with `lstat`,
17
+ * never a followed link — so a symlink or a file named `samples` is refused
18
+ * rather than read as "no samples".
19
+ */
20
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, writeFileSync, } from "node:fs";
21
+ import { dirname, join, resolve, sep } from "node:path";
22
+ import { DesignFilesError, LOOK_FILE, MAX_DESIGN_FILE_BYTES, STARTED_FROM_MAX, STARTED_FROM_PATTERN, acceptedStartedFrom, } from "./design-files.js";
23
+ import { listMdxFiles, locatePageSections, parseFlowMapping, parseFlowSequence, scalarText, skipSpace, } from "./design-presets.js";
24
+ /** The folder a look's samples live in, and their manifest inside it. */
25
+ export const SAMPLES_DIR = "samples";
26
+ export const SAMPLES_MANIFEST = "samples.json";
27
+ /** The site folder a look's samples are copied to: `<site>/apps/web/public/look/<look>/`, served at `/look/<look>/`. */
28
+ const PUBLIC_LOOK_DIR = ["apps", "web", "public", "look"];
29
+ /** D2 — the bounds a sample is held to, because samples ship in the public create-ailk tarball. */
30
+ const SAMPLE_MAX_BYTES = 300_000;
31
+ const LOOK_SAMPLES_MAX_BYTES = 2_000_000;
32
+ const LOOK_SAMPLES_MAX = 32;
33
+ const SAMPLE_SIDE_MAX = 4096;
34
+ const SAMPLE_ALT_MAX = 200;
35
+ const SAMPLE_ALT_PREFIX = "Sample picture: ";
36
+ /** The four members a fill writes (SEC-12472-7), and nothing else. */
37
+ export const SAMPLE_FILL_MEMBERS = ["src", "alt", "width", "height"];
38
+ /** D3 — an image object is a look's sample fill when its `src` is under `/look/` and its `alt` starts `Sample picture: `. */
39
+ export function isSampleFill(src, alt) {
40
+ return src.startsWith("/look/") && alt.startsWith(SAMPLE_ALT_PREFIX);
41
+ }
42
+ /** D2 — a manifest key: `<section type>:<slot path>`, with no `/`, `\`, leading separator or `__proto__` step (SEC-12472-1). */
43
+ const SAMPLE_KEY_PATTERN = /^[a-z][A-Za-z0-9-]*:[A-Za-z][A-Za-z0-9]*(\[\])?(\.[A-Za-z][A-Za-z0-9]*(\[\])?)*$/;
44
+ const FORBIDDEN_STEPS = new Set(["__proto__", "constructor", "prototype"]);
45
+ const STYLE_KEY_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
46
+ const SAMPLE_REVIEWS = new Set(["pending", "approved"]);
47
+ const SAMPLE_MADE_WITH = "creative-production";
48
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
49
+ const JPEG_SIGNATURE = Buffer.from([0xff, 0xd8, 0xff]);
50
+ /** Thrown by `readLookSamples` and `fillLookSamples` before any write, naming the file, field or sample at fault. */
51
+ export class LookSamplesError extends Error {
52
+ subject;
53
+ reason;
54
+ constructor(subject, reason) {
55
+ super(`${subject}: ${reason}`);
56
+ this.subject = subject;
57
+ this.reason = reason;
58
+ this.name = "LookSamplesError";
59
+ }
60
+ }
61
+ /** D2 — a key's file stem: lower case, `[]` removed, every `:` or `.` a `-` (`hero:darkImage` → `hero-darkimage`). */
62
+ export function sampleStem(key) {
63
+ return key.toLowerCase().replace(/\[\]/g, "").replace(/[:.]/g, "-");
64
+ }
65
+ /** D2 — a sample's key in a hub: `look/<look>/<stem>`, the address a LOOK.md's `asset:` tokens name. */
66
+ export function sampleAssetKey(look, key) {
67
+ return `look/${look}/${sampleStem(key)}`;
68
+ }
69
+ /** The Clarifications' rule: the design's directory has an entry named `samples`, of any type, a dangling symlink included. */
70
+ export function hasSamplesEntry(designDir) {
71
+ try {
72
+ lstatSync(join(designDir, SAMPLES_DIR));
73
+ return true;
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ }
79
+ /** A PNG's or JPEG's pixel size, read from its header; undefined when the header does not say. */
80
+ function imageHeaderSize(bytes) {
81
+ if (bytes.subarray(0, 8).equals(PNG_SIGNATURE)) {
82
+ if (bytes.length < 24 || bytes.toString("latin1", 12, 16) !== "IHDR")
83
+ return undefined;
84
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
85
+ }
86
+ if (!bytes.subarray(0, 3).equals(JPEG_SIGNATURE))
87
+ return undefined;
88
+ // Walk the segments to the first start-of-frame (SOF0–SOF15 but DHT, JPG and DAC).
89
+ let i = 2;
90
+ while (i + 3 < bytes.length) {
91
+ if (bytes[i] !== 0xff)
92
+ return undefined;
93
+ const marker = bytes[i + 1];
94
+ if (marker === 0xff) {
95
+ i++;
96
+ continue;
97
+ }
98
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) {
99
+ i += 2;
100
+ continue;
101
+ }
102
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
103
+ if (i + 9 > bytes.length)
104
+ return undefined;
105
+ return { width: bytes.readUInt16BE(i + 7), height: bytes.readUInt16BE(i + 5) };
106
+ }
107
+ i += 2 + bytes.readUInt16BE(i + 2);
108
+ }
109
+ return undefined;
110
+ }
111
+ const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
112
+ const isSide = (value) => typeof value === "number" && Number.isInteger(value) && value > 0 && value <= SAMPLE_SIDE_MAX;
113
+ /** Every step of a key: the section type, then each path step without its `[]`. */
114
+ const keySteps = (key) => key.replace(":", ".").split(".").map((step) => step.replace(/\[\]$/, ""));
115
+ /** `lstat` without following, or undefined when absent. */
116
+ const lstatOrUndefined = (path) => lstatSync(path, { throwIfNoEntry: false });
117
+ /** Read a regular file from the design (never through a link), at most `max` bytes, sized from the opened file (SEC-12472-2). */
118
+ function readRegularFile(path, subject, max) {
119
+ const stat = lstatOrUndefined(path);
120
+ if (stat === undefined)
121
+ throw new LookSamplesError(subject, "absent");
122
+ if (!stat.isFile())
123
+ throw new LookSamplesError(subject, "not a regular file — a look's samples are read only from regular files in its own samples/ folder");
124
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
125
+ try {
126
+ const opened = fstatSync(fd);
127
+ if (!opened.isFile())
128
+ throw new LookSamplesError(subject, "not a regular file");
129
+ if (opened.size > max)
130
+ throw new LookSamplesError(subject, `larger than ${max} bytes`);
131
+ const bytes = Buffer.alloc(opened.size);
132
+ let read = 0;
133
+ while (read < bytes.length) {
134
+ const n = readSync(fd, bytes, read, bytes.length - read, read);
135
+ if (n === 0)
136
+ break;
137
+ read += n;
138
+ }
139
+ return bytes.subarray(0, read);
140
+ }
141
+ finally {
142
+ closeSync(fd);
143
+ }
144
+ }
145
+ /**
146
+ * D3 — a design's samples, checked for form, or undefined when its directory
147
+ * has no `samples` entry. The look's name is its LOOK.md's `started_from`, as
148
+ * `acceptedStartedFrom` accepts it (`designsDir` admits a byte-identical copy
149
+ * of a shipped look under another folder name; without it, only the folder's
150
+ * own name). Every sample's bytes are read and checked here; a sample's
151
+ * `style` naming a LOOK.md style is the root test's to check (D7).
152
+ *
153
+ * @throws LookSamplesError naming the file, field or sample, before anything is written.
154
+ */
155
+ export function readLookSamples(designDir, opts = {}) {
156
+ if (!hasSamplesEntry(designDir))
157
+ return undefined;
158
+ const lookPath = join(designDir, LOOK_FILE);
159
+ const lookStat = lstatOrUndefined(lookPath);
160
+ if (lookStat === undefined) {
161
+ throw new LookSamplesError(LOOK_FILE, "absent — a look with samples/ needs a LOOK.md: its samples are made under its styles, and the look's name is read from it");
162
+ }
163
+ if (!lookStat.isFile() || lookStat.size > MAX_DESIGN_FILE_BYTES) {
164
+ throw new LookSamplesError(LOOK_FILE, `not a regular file of at most ${MAX_DESIGN_FILE_BYTES} bytes`);
165
+ }
166
+ let look;
167
+ try {
168
+ look = acceptedStartedFrom(readFileSync(lookPath, "utf8"), designDir, opts.designsDir ?? "");
169
+ }
170
+ catch (err) {
171
+ if (err instanceof DesignFilesError)
172
+ throw new LookSamplesError(`${LOOK_FILE} started_from`, err.reason);
173
+ throw err;
174
+ }
175
+ const samplesDir = join(designDir, SAMPLES_DIR);
176
+ const dirStat = lstatSync(samplesDir);
177
+ if (!dirStat.isDirectory()) {
178
+ throw new LookSamplesError(SAMPLES_DIR, "not a directory — a look's samples/ is a real folder, never a symlink or a file");
179
+ }
180
+ const realSamples = realpathSync(samplesDir);
181
+ const manifestSubject = `${SAMPLES_DIR}/${SAMPLES_MANIFEST}`;
182
+ let manifest;
183
+ try {
184
+ manifest = JSON.parse(readRegularFile(join(samplesDir, SAMPLES_MANIFEST), manifestSubject, MAX_DESIGN_FILE_BYTES).toString("utf8"));
185
+ }
186
+ catch (err) {
187
+ if (err instanceof LookSamplesError)
188
+ throw err;
189
+ throw new LookSamplesError(manifestSubject, "not valid JSON");
190
+ }
191
+ if (!isPlainObject(manifest) || !isPlainObject(manifest["samples"])) {
192
+ throw new LookSamplesError(manifestSubject, "must be an object with `look` and a `samples` object");
193
+ }
194
+ if (manifest["look"] !== look) {
195
+ throw new LookSamplesError(`${manifestSubject} look`, `must be ${JSON.stringify(look)}, the look's name, not ${JSON.stringify(manifest["look"])}`);
196
+ }
197
+ const entries = Object.entries(manifest["samples"]);
198
+ if (entries.length < 1 || entries.length > LOOK_SAMPLES_MAX) {
199
+ throw new LookSamplesError(`${manifestSubject} samples`, `a look carries at least 1 and at most ${LOOK_SAMPLES_MAX} samples, not ${entries.length}`);
200
+ }
201
+ const samples = [];
202
+ const stems = new Set();
203
+ let total = 0;
204
+ for (const [key, entry] of entries) {
205
+ const at = (field) => `${manifestSubject} samples[${JSON.stringify(key)}]${field === "" ? "" : `.${field}`}`;
206
+ if (!SAMPLE_KEY_PATTERN.test(key) || keySteps(key).some((step) => FORBIDDEN_STEPS.has(step))) {
207
+ throw new LookSamplesError(at(""), "not a slot key: `<section type>:<slot path>`, letters and digits, no `/`, `\\` or `__proto__` step");
208
+ }
209
+ if (!isPlainObject(entry))
210
+ throw new LookSamplesError(at(""), "must be an object");
211
+ const stem = sampleStem(key);
212
+ if (stems.has(stem))
213
+ throw new LookSamplesError(at(""), `shares its file stem ${stem} with another sample`);
214
+ stems.add(stem);
215
+ const { file, alt, width, height, style, made_with: madeWith, review } = entry;
216
+ if (file !== `${stem}.jpg` && file !== `${stem}.png`) {
217
+ throw new LookSamplesError(at("file"), `must be ${stem}.jpg or ${stem}.png, the key's stem`);
218
+ }
219
+ if (typeof alt !== "string" ||
220
+ !alt.startsWith(SAMPLE_ALT_PREFIX) ||
221
+ alt.length > SAMPLE_ALT_MAX ||
222
+ alt.trim() === SAMPLE_ALT_PREFIX.trim() ||
223
+ // One line with no control character (SEC-12472-4).
224
+ // eslint-disable-next-line no-control-regex -- the control characters are what the check refuses.
225
+ /[\u0000-\u001f\u007f]/.test(alt)) {
226
+ throw new LookSamplesError(at("alt"), `one line of at most ${SAMPLE_ALT_MAX} characters with no control character, starting "${SAMPLE_ALT_PREFIX}" and saying what the picture shows`);
227
+ }
228
+ if (!isSide(width))
229
+ throw new LookSamplesError(at("width"), `a positive integer of at most ${SAMPLE_SIDE_MAX}`);
230
+ if (!isSide(height))
231
+ throw new LookSamplesError(at("height"), `a positive integer of at most ${SAMPLE_SIDE_MAX}`);
232
+ if (typeof style !== "string" || !STYLE_KEY_PATTERN.test(style)) {
233
+ throw new LookSamplesError(at("style"), "a style key of the look's LOOK.md");
234
+ }
235
+ if (madeWith !== SAMPLE_MADE_WITH)
236
+ throw new LookSamplesError(at("made_with"), `must be ${SAMPLE_MADE_WITH}`);
237
+ if (typeof review !== "string" || !SAMPLE_REVIEWS.has(review)) {
238
+ throw new LookSamplesError(at("review"), "must be pending or approved");
239
+ }
240
+ // The file: a regular file inside the real samples/ folder (SEC-12472-1, SEC-12472-2).
241
+ const subject = `${SAMPLES_DIR}/${file}`;
242
+ const source = join(samplesDir, file);
243
+ const stat = lstatOrUndefined(source);
244
+ if (stat === undefined)
245
+ throw new LookSamplesError(subject, "absent — the manifest names a file samples/ does not hold");
246
+ if (!stat.isFile())
247
+ throw new LookSamplesError(subject, "not a regular file — a sample is never a symlink");
248
+ if (dirname(realpathSync(source)) !== realSamples) {
249
+ throw new LookSamplesError(subject, "outside the look's samples/ folder");
250
+ }
251
+ const bytes = readRegularFile(source, subject, SAMPLE_MAX_BYTES);
252
+ total += bytes.length;
253
+ if (total > LOOK_SAMPLES_MAX_BYTES) {
254
+ throw new LookSamplesError(SAMPLES_DIR, `the look's samples total more than ${LOOK_SAMPLES_MAX_BYTES} bytes`);
255
+ }
256
+ const signature = file.endsWith(".png") ? PNG_SIGNATURE : JPEG_SIGNATURE;
257
+ if (!bytes.subarray(0, signature.length).equals(signature)) {
258
+ throw new LookSamplesError(subject, `does not start with the ${file.endsWith(".png") ? "PNG" : "JPEG"} signature its extension names`);
259
+ }
260
+ const size = imageHeaderSize(bytes);
261
+ if (size === undefined || size.width !== width || size.height !== height) {
262
+ throw new LookSamplesError(subject, `its header says ${size === undefined ? "no size" : `${size.width}×${size.height}`}, not the manifest's ${width}×${height}`);
263
+ }
264
+ samples.push({ key, file, alt, width, height, style, review, bytes });
265
+ }
266
+ // Nothing in samples/ the manifest does not name: an unlisted file would ship past every check above.
267
+ const named = new Set([SAMPLES_MANIFEST, ...samples.map((sample) => sample.file)]);
268
+ for (const name of readdirSync(samplesDir)) {
269
+ if (!named.has(name)) {
270
+ throw new LookSamplesError(`${SAMPLES_DIR}/${JSON.stringify(name)}`, "not named by the manifest — samples/ holds samples.json and the samples it names, nothing else");
271
+ }
272
+ }
273
+ return { look, samples };
274
+ }
275
+ /** The edit that adds `entries` to the mapping, before its first entry as `setSectionLookField` does, or into an empty `{ }`. */
276
+ function insertEntries(text, mapping, entries) {
277
+ const joined = entries.join(", ");
278
+ if (mapping.entries.length === 0) {
279
+ return { start: mapping.open, end: mapping.close + 1, text: `{ ${joined} }` };
280
+ }
281
+ const keyStart = skipSpace(text, mapping.open + 1, mapping.close);
282
+ const between = text.slice(mapping.open + 1, keyStart);
283
+ const nl = between.lastIndexOf("\n");
284
+ const separator = nl < 0 ? " " : between.slice(nl);
285
+ return { start: keyStart, end: keyStart, text: `${joined},${separator}` };
286
+ }
287
+ /** The four members a fill writes, each name and value through `JSON.stringify` (SEC-12472-4). */
288
+ function imageMembers(look, sample) {
289
+ const values = { src: `/look/${look}/${sample.file}`, alt: sample.alt, width: sample.width, height: sample.height };
290
+ return SAMPLE_FILL_MEMBERS.map((name) => [name, JSON.stringify(values[name])]);
291
+ }
292
+ const isNullScalar = (raw) => ["null", "~", ""].includes(raw.trim());
293
+ /**
294
+ * The edits that fill one image object in `mapping` at `field`: an absent (or
295
+ * null) object is created; an object with no non-empty `src` and no
296
+ * `"type": "video"` gains the four members; one with a source is left.
297
+ */
298
+ function fillAt(text, mapping, field, members, end) {
299
+ const entry = mapping.entries.find((e) => e.key === field);
300
+ const object = `{ ${members.map(([name, value]) => `${JSON.stringify(name)}: ${value}`).join(", ")} }`;
301
+ if (entry === undefined)
302
+ return [insertEntries(text, mapping, [`${JSON.stringify(field)}: ${object}`])];
303
+ const raw = text.slice(entry.valueStart, entry.valueEnd);
304
+ if (isNullScalar(raw))
305
+ return [{ start: entry.valueStart, end: entry.valueEnd, text: object }];
306
+ const image = parseFlowMapping(text, entry.valueStart, end);
307
+ return image === undefined ? [] : fillObject(text, image, members);
308
+ }
309
+ /** The edits that give an existing image object the four members, unless it has a source or is a video. */
310
+ function fillObject(text, image, members) {
311
+ // A member's text value: "" when absent or null.
312
+ const valueOf = (name) => {
313
+ const e = image.entries.find((x) => x.key === name);
314
+ const raw = e === undefined ? "" : text.slice(e.valueStart, e.valueEnd);
315
+ return isNullScalar(raw) ? "" : (scalarText(raw) ?? raw).trim();
316
+ };
317
+ if (valueOf("src") !== "" || valueOf("type") === "video")
318
+ return [];
319
+ const edits = [];
320
+ const absent = [];
321
+ for (const [name, value] of members) {
322
+ const e = image.entries.find((x) => x.key === name);
323
+ if (e !== undefined)
324
+ edits.push({ start: e.valueStart, end: e.valueEnd, text: value });
325
+ else
326
+ absent.push(`${JSON.stringify(name)}: ${value}`);
327
+ }
328
+ if (absent.length > 0)
329
+ edits.push(insertEntries(text, image, absent));
330
+ return edits;
331
+ }
332
+ /** A slot path's steps: `features[].image` → `[{ name: "features", each: true }, { name: "image", each: false }]`. */
333
+ const pathSteps = (path) => path.split(".").map((step) => ({ name: step.replace(/\[\]$/, ""), each: step.endsWith("[]") }));
334
+ /**
335
+ * D3 step 2 — the edits that fill every place `steps` reaches from `mapping`:
336
+ * an object step descends, an array step fans out over the items that exist
337
+ * (none is added), and only the last step's object is created.
338
+ */
339
+ function fillPath(text, mapping, steps, members, end) {
340
+ const [step, ...rest] = steps;
341
+ if (step === undefined)
342
+ return [];
343
+ if (rest.length === 0 && !step.each)
344
+ return fillAt(text, mapping, step.name, members, end);
345
+ const entry = mapping.entries.find((e) => e.key === step.name);
346
+ if (entry === undefined)
347
+ return [];
348
+ const objects = [];
349
+ if (step.each) {
350
+ const list = parseFlowSequence(text, entry.valueStart, end);
351
+ for (const item of list?.items ?? []) {
352
+ const object = parseFlowMapping(text, item.start, end);
353
+ if (object !== undefined)
354
+ objects.push(object);
355
+ }
356
+ }
357
+ else {
358
+ const object = parseFlowMapping(text, entry.valueStart, end);
359
+ if (object !== undefined)
360
+ objects.push(object);
361
+ }
362
+ return objects.flatMap((object) => rest.length === 0 ? fillObject(text, object, members) : fillPath(text, object, rest, members, end));
363
+ }
364
+ /**
365
+ * One page's text with every sample filled, or undefined when nothing changed.
366
+ * A page the preset locator cannot read is left whole, even part-filled: the
367
+ * design leg's box check names any slot it leaves.
368
+ */
369
+ export function fillPageText(text, file, look, samples) {
370
+ let out = text;
371
+ // One sample at a time, re-located after each: one sample's places are distinct
372
+ // objects, so its edits never overlap; two samples' could (two inserts into one `{}`).
373
+ for (const sample of samples) {
374
+ let located;
375
+ try {
376
+ located = locatePageSections(out, file);
377
+ }
378
+ catch {
379
+ return undefined;
380
+ }
381
+ if (located === undefined)
382
+ return undefined;
383
+ const colon = sample.key.indexOf(":");
384
+ const edits = [];
385
+ for (const section of located) {
386
+ // Block-form sections are not filled (no seeded page carries one); the leg's check names a box left.
387
+ if (section.form !== "flow" || section.type !== sample.key.slice(0, colon))
388
+ continue;
389
+ const data = parseFlowMapping(out, section.dataOpen, section.end);
390
+ if (data === undefined)
391
+ continue;
392
+ edits.push(...fillPath(out, data, pathSteps(sample.key.slice(colon + 1)), imageMembers(look, sample), section.end));
393
+ }
394
+ // Applied from the end, so each edit's offsets still hold in the text they were read from.
395
+ edits.sort((a, b) => b.start - a.start || b.end - a.end);
396
+ for (const edit of edits)
397
+ out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
398
+ }
399
+ return out === text ? undefined : out;
400
+ }
401
+ /**
402
+ * D3 steps 1–3 — copy a look's checked samples into the site and fill the
403
+ * empty image slots of its seeded pages under `content/`. Every page edit is
404
+ * planned and the destination checked before the first write: the scaffold
405
+ * refuses, writing nothing, when `apps/web/public/look` (or a folder on the
406
+ * way to it) is a symlink, or `public/look` already exists (SEC-12472-5).
407
+ * Nothing under `public/` is removed; each sample is created with `wx`.
408
+ *
409
+ * @returns the site-relative paths written.
410
+ * @throws LookSamplesError before any write.
411
+ */
412
+ export function fillLookSamples(siteDir, look, samples) {
413
+ if (!STARTED_FROM_PATTERN.test(look) || look.length > STARTED_FROM_MAX) {
414
+ throw new LookSamplesError("look", `not a look name: ${JSON.stringify(look)}`);
415
+ }
416
+ // Check: the destination, every folder on the way to it.
417
+ const site = resolve(siteDir);
418
+ const publicDir = join(site, ...PUBLIC_LOOK_DIR.slice(0, -1));
419
+ for (let n = 1; n <= PUBLIC_LOOK_DIR.length; n++) {
420
+ const path = join(site, ...PUBLIC_LOOK_DIR.slice(0, n));
421
+ const stat = lstatOrUndefined(path);
422
+ if (stat?.isSymbolicLink())
423
+ throw new LookSamplesError(PUBLIC_LOOK_DIR.slice(0, n).join("/"), "a symlink — create-ailk never writes through one");
424
+ if (stat !== undefined && n === PUBLIC_LOOK_DIR.length) {
425
+ throw new LookSamplesError(PUBLIC_LOOK_DIR.join("/"), "already exists — a look's samples are copied only into a new folder");
426
+ }
427
+ if (stat !== undefined && !stat.isDirectory())
428
+ throw new LookSamplesError(PUBLIC_LOOK_DIR.slice(0, n).join("/"), "not a directory");
429
+ }
430
+ const destDir = join(publicDir, "look", look);
431
+ for (const sample of samples) {
432
+ if (dirname(join(destDir, sample.file)) !== destDir) {
433
+ throw new LookSamplesError(`${SAMPLES_DIR}/${sample.file}`, "would be written outside the look's public folder");
434
+ }
435
+ }
436
+ // Plan: every page's filled text.
437
+ const pages = listMdxFiles(join(site, "content"))
438
+ // A page that is a symlink is never written through (SEC-12472-5's rule for every write here).
439
+ .filter((path) => lstatSync(path).isFile())
440
+ .map((path) => ({ path, text: fillPageText(readFileSync(path, "utf8"), path, look, samples) }))
441
+ .filter((page) => page.text !== undefined);
442
+ // Effect: the folders, the checked bytes, then the pages.
443
+ mkdirSync(publicDir, { recursive: true });
444
+ mkdirSync(join(publicDir, "look"));
445
+ mkdirSync(destDir);
446
+ const written = [];
447
+ for (const sample of samples) {
448
+ writeFileSync(join(destDir, sample.file), sample.bytes, { flag: "wx" });
449
+ written.push([...PUBLIC_LOOK_DIR, look, sample.file].join("/"));
450
+ }
451
+ for (const page of pages) {
452
+ writeFileSync(page.path, page.text);
453
+ written.push(page.path.slice(site.length + 1).split(sep).join("/"));
454
+ }
455
+ return written;
456
+ }
@@ -0,0 +1,53 @@
1
+ import { type DesignPackage } from "./design-package.js";
2
+ import { type TemplateLayout } from "./site-chrome.js";
3
+ import { type SiteRoster } from "./site-roster.js";
4
+ /** A site file larger than this is refused (D2). */
5
+ export declare const LOOK_SITE_FILE_MAX_BYTES = 1048576;
6
+ /** The hand-off file's `kind` and `format` (D2). */
7
+ export declare const LOOK_SETTINGS_KIND = "ailk-look-settings";
8
+ export declare const LOOK_SETTINGS_FORMAT = 1;
9
+ /**
10
+ * D2's printing rule: every character outside `[A-Za-z0-9._:/@ -]` becomes
11
+ * `\xNN`, one escape per UTF-8 byte, and the result is cut to 120 characters,
12
+ * so no site or hub value can carry a terminal escape or a forged line.
13
+ */
14
+ export declare function printable(value: string): string;
15
+ /** The canonical JSON of a value (D2): every object's keys sorted, no whitespace. */
16
+ export declare function canonicalJson(value: unknown): string;
17
+ /** The settings digest (D2): the SHA-256 of the settings' canonical JSON, UTF-8. */
18
+ export declare function settingsDigest(settings: unknown): string;
19
+ export interface LookSettingsOptions {
20
+ /** The site checkout. */
21
+ dir: string;
22
+ /** The hand-off file: must not exist, and must sit outside the checkout. */
23
+ out: string;
24
+ /** A result line (stdout). */
25
+ onLine?: (line: string) => void;
26
+ /** A refusal or failure line (stderr). */
27
+ onError?: (line: string) => void;
28
+ /**
29
+ * The layout the roster's template declares, as `apply-design` reads it
30
+ * (`roster.template.layout`, the default). No registered template declares
31
+ * one today, so a suite passes its own to exercise a template override.
32
+ */
33
+ templateLayoutOf?: (roster: SiteRoster) => TemplateLayout | undefined;
34
+ }
35
+ /** The file `--out` holds (D2). */
36
+ export interface LookSettingsFile {
37
+ kind: typeof LOOK_SETTINGS_KIND;
38
+ format: typeof LOOK_SETTINGS_FORMAT;
39
+ files: Record<string, string>;
40
+ settingsSha256: string;
41
+ settings: DesignPackage;
42
+ }
43
+ /** Reads, checks and hands over (D2); answers the exit code. */
44
+ export declare function lookSettings(o: LookSettingsOptions): {
45
+ exitCode: number;
46
+ };
47
+ export interface LookSettingsArgs {
48
+ target: string | undefined;
49
+ out: string | undefined;
50
+ help: boolean;
51
+ }
52
+ export declare const LOOK_SETTINGS_HELP = "create-ailk look-settings \u2014 the design settings a site's hub design record will hold.\n\nUsage:\n create-ailk look-settings [<dir>] --out <file>\n\nArguments:\n <dir> The site checkout. Defaults to the current dir.\n\nOptions:\n --out <file> Where the settings are handed over: a new file outside the checkout.\n -h, --help Show this help.\n\nReads design.yaml, the site roster, content/_site.mdx, apps/web/lib/site-chrome.ts and\napps/web/lib/site-fonts.ts as text, and hands the settings over only when they compile\nto the three generated look files byte for byte. Runs no site code and needs no credential.\nThe runbook is docs/internal/runbooks/site-design-import.md.\nExit 0 handed over, 1 a failure, 2 a bad flag or --out, 3 a generated file that differs.\n";
53
+ export declare function parseLookSettingsArgs(argv: string[]): LookSettingsArgs;