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
@@ -1,96 +1,95 @@
1
1
  /**
2
- * `create-ailk apply-design <name|path> [--target <site-dir>]` — make an
3
- * existing site wear a design, changing only how it LOOKS (#6819, spec
4
- * docs/specs/6819-apply-design-name-path-one-spec.md).
2
+ * `create-ailk apply-design <name|path> [--target <site-dir>] [--api-url
3
+ * <origin>] [--workspace <id>]` — make an existing site wear a design, by
4
+ * writing its hub design record (#6819, spec
5
+ * docs/specs/6819-apply-design-name-path-one-spec.md; record-only since
6
+ * #12477 D5, spec docs/specs/12477-retire-the-generated-look-files-spec.md).
5
7
  *
6
- * Composes four already-shipped units and edits none of them: #6813's
7
- * resolver and theme splicer, #6816's preset validator and applier, #6760's
8
- * design gate and #6813's manifest writer. Every refusal happens before the
9
- * first write (D3); every new text is planned in memory, then written in one
10
- * pass (D4). Routes, content fields, `brand:` and structured data never move —
11
- * except a placeholder home's `sections:`, which a design's home arc may
12
- * replace (#7743 D7).
8
+ * A site's look is its hub design record (#12470) and nothing else, so this
9
+ * command writes that record and no file: not the retired look files, not
10
+ * `design.yaml`, `DESIGN.md`, a page or the manifest — no copy in the
11
+ * repository can drift from the record.
12
+ *
13
+ * Every refusal happens before the record is written: the scaffolded repo
14
+ * (C1), the design resolved (C3) and its presets validated (C4), the licence
15
+ * gate (C5), then the credentials and, on a spoke, that they are the site's
16
+ * own (D5 step 1). A site whose look is still only in its files is refused
17
+ * before the write (step 3): #12476's import writes only where the hub holds
18
+ * no record, so a record written first would lose the site's own look.
19
+ *
20
+ * The credentials are the seed's (`seed-workspace.ts`): the origin from
21
+ * `--api-url`, else `AILK_API_URL`; the workspace from `--workspace`, else
22
+ * `AILK_WORKSPACE_ID`; the agent key from `AILK_AGENT_KEY` and nowhere else.
23
+ * The transport is `look-hub.ts`'s: bearer header only, no redirect, the key
24
+ * never printed.
13
25
  *
14
26
  * Reads no module URL of its own — every package directory it reads is passed in
15
27
  * — so Jest's CJS transform can import it, unlike `programmatic.ts`.
16
28
  */
17
- import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, } from "node:fs";
18
- import { dirname, join, relative, resolve, sep } from "node:path";
29
+ import { existsSync, statSync } from "node:fs";
30
+ import { join, resolve } from "node:path";
19
31
  import { parseArgs } from "node:util";
20
- import { planDesignMd } from "./apply-design-md.js";
21
- import { compileDesignFonts, compileDesignTheme } from "./design-compile.js";
22
- import { CONTACT_PAGE_PATH, DESIGN_SEED_PAGES, HOME_PAGE_PATH, designHomeSeeds, planDesignHome, shapeHomePath, shippedHomeSeeds, siteIdentityName, } from "./design-home.js";
23
- import { applyDesignPresets, readSectionLookCatalog, shippedPageTypes, validateDesignPresets, } from "./design-presets.js";
24
- import { resolveDesign, spliceThemeBlock } from "./design-scaffold.js";
25
- import { chromeKnobReaders, unreadChromeKnobs } from "./lib/chrome-readers.js";
32
+ import { readSectionLookCatalog, shippedPageTypes, validateDesignPresets, } from "./design-presets.js";
33
+ import { resolveDesign } from "./design-scaffold.js";
26
34
  import { readSiteKey } from "./lib/license-key-files.js";
27
35
  import { CONVERSION_HINT_URL, LicenseRequiredError, assertDesignAllowed, deriveLevel, } from "./lib/module-license-gate.js";
28
36
  import { LEVEL_LABEL } from "./lib/module-tier.js";
37
+ import { describeAnswer, designUrl, hubRequest, retiredLookSources, storedVersion, } from "./look-hub.js";
38
+ import { lookRecordFor } from "./look-record.js";
29
39
  import { ParseError } from "./parse-args.js";
30
- import { SITE_CHROME_PATH, renderSiteChrome, resolveSiteChrome, } from "./site-chrome.js";
31
- import { SITE_FONTS_PATH, renderSiteFonts } from "./site-fonts.js";
32
- import { SITE_ROSTER_PATH, planHomeRecord, planSiteManifestDesign, readSiteRoster, } from "./site-roster.js";
33
- /** #7781 — thrown before any write when the design sets a chrome knob that a reader file of the site does not read. */
34
- export class UnreadChromeError extends Error {
35
- unread;
36
- constructor(unread) {
37
- super(`design chrome would not render: the site's own copy of these files does not read the knob the design sets (update them from the current create-ailk overlay, or pass --allow-unread-chrome to apply anyway):\n${unread
38
- .map(({ knob, file }) => ` ${knob} — ${file}`)
39
- .join("\n")}`);
40
- this.unread = unread;
41
- this.name = "UnreadChromeError";
40
+ import { AGENT_KEY_ENV_VAR, WORKSPACE_ID_ENV_VAR } from "./seed-workspace.js";
41
+ import { readSiteRoster } from "./site-roster.js";
42
+ import { HUB_ORIGIN_ENV_VAR, TopologyError, normalizeHubUrl, readSiteTopology, spokeOriginMismatch, spokeWorkspaceMismatch, } from "./topology.js";
43
+ /** A refusal the CLI exits 2 on, thrown before the hub record is written. */
44
+ export class ApplyDesignRefusedError extends Error {
45
+ exitCode = 2;
46
+ constructor(message) {
47
+ super(`apply-design: ${message}`);
48
+ this.name = "ApplyDesignRefusedError";
42
49
  }
43
50
  }
44
- /** The site's locale layout — the one reader of the generated site-fonts.ts. */
45
- const SITE_LAYOUT_PATH = "apps/web/app/[locale]/layout.tsx";
46
51
  export const APPLY_DESIGN_HELP = `create-ailk apply-design — make an existing site wear a design.
47
52
 
48
53
  Usage:
49
- create-ailk apply-design <name> [--target <site-dir>]
50
- create-ailk apply-design <path> [--target <site-dir>]
54
+ AILK_AGENT_KEY=<key> create-ailk apply-design <name|path> [--target <site-dir>]
55
+ [--api-url <origin>] [--workspace <wksp_id>]
51
56
 
52
57
  Arguments:
53
- <name|path> A shipped design (standard, minimalism), or a
54
- directory holding a DESIGN.md. A relative path
58
+ <name|path> The name of a look this installer ships (create-ailk
59
+ --help lists them), or a
60
+ directory holding a design.yaml. A relative path
55
61
  resolves from the current directory.
56
62
 
57
63
  Options:
58
64
  --target <site-dir> An already-scaffolded repo (contains
59
65
  architecture.yaml). Defaults to the current dir.
60
- --allow-unread-chrome Apply the design even when a file of the site does
61
- not read a chrome setting the design sets (a site
62
- scaffolded before the setting existed). Without it
63
- that is refused; with it each such file is reported.
66
+ --api-url <origin> The site's API origin. Else AILK_API_URL. https:
67
+ only (http: on localhost or 127.0.0.1).
68
+ --workspace <wksp_id> The site's workspace. Else AILK_WORKSPACE_ID.
64
69
  --help, -h Print this message.
65
70
 
66
- Writes only the look: DESIGN.md (replaced whole by the design's, keeping the
67
- site's Source template and Version lines), the theme: block of
68
- content/_site.mdx, the generated apps/web/lib/site-chrome.ts, the generated
69
- apps/web/lib/site-fonts.ts, the look fields of sections the site's pages
70
- already place, and the design/layout/theme record in .ailk-site-manifest.json.
71
- Never adds, removes or renames a route or page, never touches a content field
72
- (except a placeholder home's sections, below) or the brand: block, and leaves
73
- every other page's structured data unchanged.
71
+ Writes the design to the site's hub design record — the one place a site's
72
+ look comes from — and changes no file. A library look is recorded by name and
73
+ version, keeping the starter's own layout settings as its changes; a design
74
+ given as a directory is recorded as a look of the workspace's own. The record's
75
+ header and footer styles and its brand override are kept as they are.
74
76
 
75
- A design may seed the placeholder home's sections — its home arc — while they
76
- are still a placeholder: the shape's own, or a design's arc of them. It never
77
- changes a home whose sections were edited; it reports it and leaves it. A
78
- seeded home takes the design's looks; look values on the sections it replaced
79
- are not kept. A design that ships no arc restores the shape's own sections on
80
- a home that still wears another design's untouched arc.
77
+ The agent key is read from AILK_AGENT_KEY only and needs the site-design
78
+ grant. On a spoke, the workspace and origin must be the ones its apps/web env
79
+ files name. A site whose look is still in its files (content/_site.mdx
80
+ theme:, apps/web/lib/site-chrome.ts, apps/web/lib/site-fonts.ts) is refused
81
+ until its look is imported into the hub.
81
82
 
82
83
  A design other than standard needs a Pro or Pro Plus key: the site's own
83
84
  ailk.key (put one there with create-ailk license set <key>), else
84
- AILK_LICENSE_KEY. A malformed package, a preset the validator refuses or a
85
- missing key is refused before any file is written.
86
-
87
- A preset sets the look fields it names and never unsets one: a field it does
88
- not name keeps whatever value the page has. Running it again changes nothing.
85
+ AILK_LICENSE_KEY. A malformed package, a preset the validator refuses, a
86
+ missing key or credential is refused before anything is written. Exit 2 on a
87
+ refusal of the site or its credentials, 1 on any other failure.
89
88
  `;
90
89
  /**
91
90
  * Parse the argv AFTER the `apply-design` word (D1). Strict `node:util`
92
91
  * parseArgs, like `parseSyncRoutesArgs`: exactly one positional, the design
93
- * reference, and an optional `--target`.
92
+ * reference, and the optional `--target`, `--api-url` and `--workspace`.
94
93
  */
95
94
  export function parseApplyDesignArgs(argv) {
96
95
  const parsed = parseArgs({
@@ -99,7 +98,8 @@ export function parseApplyDesignArgs(argv) {
99
98
  allowPositionals: true,
100
99
  options: {
101
100
  target: { type: "string" },
102
- "allow-unread-chrome": { type: "boolean", default: false },
101
+ "api-url": { type: "string" },
102
+ workspace: { type: "string" },
103
103
  help: { type: "boolean", default: false, short: "h" },
104
104
  },
105
105
  });
@@ -114,40 +114,28 @@ export function parseApplyDesignArgs(argv) {
114
114
  return {
115
115
  design,
116
116
  target: parsed.values.target,
117
- allowUnreadChrome: parsed.values["allow-unread-chrome"] === true,
117
+ apiUrl: parsed.values["api-url"],
118
+ workspaceId: parsed.values.workspace,
118
119
  help,
119
120
  };
120
121
  }
121
- /** `abs` relative to `root`, with `/` separators. */
122
- function siteRelative(root, abs) {
123
- return relative(root, abs).split(sep).join("/");
122
+ /** A value given, or `undefined` for an absent or empty one. */
123
+ function given(value) {
124
+ const trimmed = value?.trim();
125
+ return trimmed === undefined || trimmed === "" ? undefined : trimmed;
124
126
  }
125
- /** Every `.mdx` under `dir`, sorted by path (D4 step 3). */
126
- function listMdxFiles(dir) {
127
- if (!existsSync(dir))
128
- return [];
129
- const out = [];
130
- const stack = [dir];
131
- while (stack.length > 0) {
132
- const current = stack.pop();
133
- for (const entry of readdirSync(current, { withFileTypes: true })) {
134
- const abs = join(current, entry.name);
135
- if (entry.isDirectory())
136
- stack.push(abs);
137
- else if (entry.name.endsWith(".mdx"))
138
- out.push(abs);
139
- }
140
- }
141
- return out.sort();
127
+ function isPlainObject(value) {
128
+ return typeof value === "object" && value !== null && !Array.isArray(value);
142
129
  }
143
130
  /**
144
- * Apply a design to an existing site (D2–D7). Refuses before any write
145
- * (C1–C6); otherwise writes only the files whose text changes — page files,
146
- * `site-chrome.ts`, `site-fonts.ts`, `DESIGN.md`, `_site.mdx`, then the manifest last.
131
+ * Apply a design to an existing site (D5): refuse before the write (C1–C5,
132
+ * the credentials, a site still carrying its look files), then read and
133
+ * write the site's hub design record. Writes no file.
147
134
  */
148
135
  export async function applyDesign(opts) {
149
136
  const targetAbs = resolve(opts.targetDir);
150
137
  const env = opts.env ?? process.env;
138
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
151
139
  // C1 — a scaffolded repo (the `addModule` wording).
152
140
  if (!existsSync(targetAbs)) {
153
141
  throw new Error(`apply-design target does not exist: ${targetAbs}. Point apply-design at an already-scaffolded repo.`);
@@ -158,34 +146,20 @@ export async function applyDesign(opts) {
158
146
  if (!existsSync(join(targetAbs, "architecture.yaml"))) {
159
147
  throw new Error(`not a scaffolded repo: no architecture.yaml at ${targetAbs}. Run \`create-ailk <target-dir>\` to scaffold first.`);
160
148
  }
161
- // C2 — the site config the theme lives in.
162
- const siteMdxPath = join(targetAbs, "content", "_site.mdx");
163
- if (!existsSync(siteMdxPath)) {
164
- throw new Error(`no content/_site.mdx at ${targetAbs}: there is no theme to replace`);
165
- }
166
149
  // C3 — resolve (a malformed package throws DesignPackageError, naming the field).
167
150
  const resolved = resolveDesign(opts.design, {
168
151
  designsDir: opts.designsDir,
169
152
  cwd: opts.cwd ?? process.cwd(),
170
153
  });
171
154
  const { pkg } = resolved;
172
- const hasPresets = Object.keys(pkg.sections).length > 0;
173
155
  // C4 — the presets, validated exactly as scaffold() validates them.
174
- let lookCatalog;
175
- const catalog = () => (lookCatalog ??= readSectionLookCatalog(opts.catalogPath));
176
- if (hasPresets) {
156
+ if (Object.keys(pkg.sections).length > 0) {
177
157
  validateDesignPresets(pkg.sections, {
178
- catalog: catalog(),
158
+ catalog: readSectionLookCatalog(opts.catalogPath),
179
159
  pageTypes: shippedPageTypes(opts.siteTemplatesDir),
180
- file: join(resolved.dir, "DESIGN.md"),
160
+ file: join(resolved.dir, "design.yaml"),
181
161
  });
182
162
  }
183
- // #7743 D7 — the home seeds (the design's and every shipped design's), validated beside the presets.
184
- const designSeeds = designHomeSeeds(resolved, { designsDir: opts.designsDir, catalog });
185
- const shippedSeeds = shippedHomeSeeds({ designsDir: opts.designsDir, catalog });
186
- // #8661 D11 — and the contact seeds, the same way.
187
- const contactSeeds = designHomeSeeds(resolved, { designsDir: opts.designsDir, catalog, page: "contact" });
188
- const shippedContactSeeds = shippedHomeSeeds({ designsDir: opts.designsDir, catalog, page: "contact" });
189
163
  // C5 — the design gate, fed the site's own key (D6). A Free design reads no key.
190
164
  if (!resolved.free) {
191
165
  const key = readSiteKey(targetAbs, env);
@@ -203,240 +177,94 @@ export async function applyDesign(opts) {
203
177
  throw new LicenseRequiredError(`design "${resolved.display}" is a Pro feature — this site's licence level is ${LEVEL_LABEL[level]}; put a Pro or Pro Plus key in the site with create-ailk license set <key>, or set AILK_LICENSE_KEY → ${CONVERSION_HINT_URL}`);
204
178
  }
205
179
  }
206
- // #7781 — after the licence gate, before any plan: every chrome knob the design sets must be read by
207
- // the site's own copy of each overlay file that reads it. The reader map is derived from the overlay.
208
- const roster = readSiteRoster(targetAbs);
209
- const chrome = resolveSiteChrome(roster?.template.layout, pkg.layout);
210
- const templatesDir = opts.templatesDir ?? join(dirname(opts.siteTemplatesDir), "templates");
211
- const unreadChrome = unreadChromeKnobs(chrome, chromeKnobReaders(templatesDir), targetAbs);
212
- if (unreadChrome.length > 0 && opts.allowUnreadChrome !== true)
213
- throw new UnreadChromeError(unreadChrome);
214
- // C6 / D4 — plan every write in memory.
215
- const theme = compileDesignTheme(pkg);
216
- const siteMdxCurrent = readFileSync(siteMdxPath, "utf8");
217
- const siteMdxNext = spliceThemeBlock(siteMdxCurrent, theme, siteMdxPath);
218
- const chromePath = join(targetAbs, SITE_CHROME_PATH);
219
- const chromeCurrent = existsSync(chromePath) ? readFileSync(chromePath, "utf8") : undefined;
220
- const chromeNext = renderSiteChrome(chrome);
221
- // #7720 D4.2 — a face-less design never adds the file to a site that lacks it.
222
- const fonts = compileDesignFonts(pkg);
223
- const fontsPath = join(targetAbs, SITE_FONTS_PATH);
224
- const fontsCurrent = existsSync(fontsPath) ? readFileSync(fontsPath, "utf8") : undefined;
225
- const fontsNext = renderSiteFonts(fonts);
226
- const writeFonts = fontsNext !== fontsCurrent && (fontsCurrent !== undefined || fonts !== undefined);
227
- const fontFamilies = writeFonts && fonts !== undefined
228
- ? [...new Set([fonts.display?.family, fonts.body?.family])].filter((family) => family !== undefined)
229
- : undefined;
230
- const layoutPath = join(targetAbs, SITE_LAYOUT_PATH);
231
- const fontsUnwired = fontFamilies !== undefined &&
232
- !(existsSync(layoutPath) && readFileSync(layoutPath, "utf8").includes("lib/site-fonts"));
233
- const designMdPath = join(targetAbs, "DESIGN.md");
234
- const designMdCurrent = existsSync(designMdPath) ? readFileSync(designMdPath, "utf8") : undefined;
235
- const designMdNext = planDesignMd(resolved.dir, targetAbs);
236
- // #7743 D7 — the home is planned before the presets, so a seeded home is
237
- // written once, carrying both. The one `planDesignHome` call site here.
238
- // #8661 D11 — the contact page is planned right after it, its heading named
239
- // from the site's `siteIdentity.name`.
240
- const shape = roster?.template.shape;
241
- const siteName = siteIdentityName(siteMdxCurrent);
242
- const plans = [
243
- ["home", designSeeds, shippedSeeds],
244
- ["contact", contactSeeds, shippedContactSeeds],
245
- ].map(([page, pageSeeds, shippedPageSeeds]) => {
246
- const target = pageSeeds.find((seed) => seed.shape === shape);
247
- const path = join(targetAbs, ...DESIGN_SEED_PAGES[page].path.split("/"));
248
- const current = existsSync(path) ? readFileSync(path, "utf8") : undefined;
249
- const plan = planDesignHome({
250
- page,
251
- siteName,
252
- current,
253
- shape,
254
- target,
255
- shapeHome: shape === undefined || current === undefined
256
- ? ""
257
- : readFileSync(shapeHomePath(shape, { siteTemplatesDir: opts.siteTemplatesDir, templatesDir, page }), "utf8"),
258
- shippedSeeds: shippedPageSeeds,
259
- catalog: catalog(),
260
- });
261
- // The page this site would take: the shape's seed, or (with no shape to pick one) any seed at all.
262
- const offered = target !== undefined || (shape === undefined && pageSeeds.length > 0);
263
- const action = plan.outcome === "seeded" || plan.outcome === "restored" ? plan.outcome : undefined;
264
- return { path, plan, offered, action };
265
- });
266
- const [homeSeeding, contactSeeding] = plans;
267
- const homePlan = homeSeeding.plan;
268
- const homeArc = homeSeeding.offered;
269
- const homePath = homeSeeding.path;
270
- const homeAction = homeSeeding.action;
271
- const contactPlan = contactSeeding.plan;
272
- const contactPath = contactSeeding.path;
273
- const contactAction = contactSeeding.action;
274
- const pageWrites = [];
275
- if (roster !== undefined && (hasPresets || homeAction !== undefined || contactAction !== undefined)) {
276
- const pageTypes = new Set();
277
- for (const row of roster.rows) {
278
- const pageType = row.value["pageType"];
279
- if (typeof pageType === "string")
280
- pageTypes.add(pageType);
281
- }
282
- const contentDir = join(targetAbs, "content");
283
- // An authored home kept from a design's arc is reported as kept, so no preset dresses it either (D3, F4).
284
- const homeKept = homePlan.outcome === "authored" && homeArc;
285
- // #8661 D11 — likewise an authored contact page kept from the design's own.
286
- const contactKept = contactPlan.outcome === "authored" && contactSeeding.offered;
287
- const pages = listMdxFiles(contentDir)
288
- .filter((path) => path !== siteMdxPath && !(homeKept && path === homePath) && !(contactKept && path === contactPath))
289
- .map((path) => ({
290
- path,
291
- text: path === homePath && homePlan.text !== undefined
292
- ? homePlan.text
293
- : path === contactPath && contactPlan.text !== undefined
294
- ? contactPlan.text
295
- : readFileSync(path, "utf8"),
296
- }));
297
- const presetResult = hasPresets
298
- ? applyDesignPresets(pages, pkg.sections, { pageTypes })
299
- : { pages: [], applied: [] };
300
- for (const page of pages) {
301
- const preset = presetResult.pages.find((p) => p.path === page.path);
302
- const home = page.path === homePath ? homeAction : undefined;
303
- const contact = page.path === contactPath ? contactAction : undefined;
304
- if (preset === undefined && home === undefined && contact === undefined)
305
- continue;
306
- const fields = [
307
- ...new Set(presetResult.applied
308
- .filter((a) => a.path === page.path)
309
- .map((a) => `${a.sectionType}.${a.field}`)),
310
- ].sort();
311
- pageWrites.push({
312
- path: page.path,
313
- text: preset?.text ?? page.text,
314
- fields,
315
- ...(home !== undefined ? { home } : {}),
316
- ...(contact !== undefined ? { contact } : {}),
317
- });
318
- }
180
+ // D5 step 1 — the credentials, and on a spoke that they are its own, before any hub request.
181
+ const apiKey = given(env[AGENT_KEY_ENV_VAR]);
182
+ if (apiKey === undefined) {
183
+ throw new ApplyDesignRefusedError(`set ${AGENT_KEY_ENV_VAR} to an agent key with the site-design grant. It is read from the environment only — never a flag or a file. Nothing was written.`);
319
184
  }
320
- let manifest = "no-roster";
321
- let manifestNext;
322
- const rosterAbs = roster !== undefined ? join(targetAbs, roster.path) : undefined;
323
- if (roster !== undefined && rosterAbs !== undefined) {
324
- if (roster.path === SITE_ROSTER_PATH) {
325
- manifestNext = planSiteManifestDesign(readFileSync(rosterAbs, "utf8"), { design: resolved.recorded, layout: chrome, theme }, rosterAbs);
326
- // #7743 D6 — the `/` row records the home as written, in the same single write.
327
- // #8661 — and the `/contact` row the contact page.
328
- for (const page of ["home", "contact"]) {
329
- const written = pageWrites.find((write) => write[page] !== undefined);
330
- if (written === undefined)
331
- continue;
332
- manifestNext =
333
- planHomeRecord(manifestNext ?? readFileSync(rosterAbs, "utf8"), written.text, catalog(), page) ??
334
- manifestNext;
335
- }
336
- manifest = manifestNext === undefined ? "unchanged" : "recorded";
337
- }
338
- else {
339
- manifest = "legacy-roster";
340
- }
185
+ const workspaceId = given(opts.workspaceId) ?? given(env[WORKSPACE_ID_ENV_VAR]);
186
+ if (workspaceId === undefined) {
187
+ throw new ApplyDesignRefusedError(`no workspace id was given. Pass --workspace <wksp_id>, or set ${WORKSPACE_ID_ENV_VAR}. Nothing was written.`);
188
+ }
189
+ const rawOrigin = given(opts.apiUrl) ?? given(env[HUB_ORIGIN_ENV_VAR]);
190
+ if (rawOrigin === undefined) {
191
+ throw new ApplyDesignRefusedError(`no API origin was given. Pass --api-url <origin>, or set ${HUB_ORIGIN_ENV_VAR}. Nothing was written.`);
192
+ }
193
+ let origin;
194
+ try {
195
+ origin = normalizeHubUrl(rawOrigin);
196
+ }
197
+ catch (err) {
198
+ if (!(err instanceof TopologyError))
199
+ throw err;
200
+ throw new ApplyDesignRefusedError("the API origin must be an https: origin (http: only on a loopback host) with no path, query, fragment or credentials. Nothing was written.");
341
201
  }
342
- // Write — page files, site-chrome.ts, site-fonts.ts, DESIGN.md, _site.mdx, the manifest last (D4).
343
- const changes = [];
344
- for (const page of pageWrites) {
345
- writeFileSync(page.path, page.text);
346
- const path = siteRelative(targetAbs, page.path);
347
- changes.push(page.home !== undefined
348
- ? { path, kind: "home", action: page.home, fields: page.fields }
349
- : page.contact !== undefined
350
- ? { path, kind: "contact", action: page.contact, fields: page.fields }
351
- : { path, kind: "preset", fields: page.fields });
202
+ let topology;
203
+ try {
204
+ topology = readSiteTopology(targetAbs);
352
205
  }
353
- if (chromeNext !== chromeCurrent) {
354
- mkdirSync(dirname(chromePath), { recursive: true });
355
- writeFileSync(chromePath, chromeNext);
356
- changes.push({ path: SITE_CHROME_PATH, kind: "layout" });
206
+ catch (err) {
207
+ if (!(err instanceof TopologyError))
208
+ throw err;
209
+ throw new ApplyDesignRefusedError(`${err.message}. Nothing was written.`);
357
210
  }
358
- if (writeFonts) {
359
- mkdirSync(dirname(fontsPath), { recursive: true });
360
- writeFileSync(fontsPath, fontsNext);
361
- changes.push({ path: SITE_FONTS_PATH, kind: "fonts" });
211
+ if (topology === "spoke") {
212
+ const mismatch = spokeWorkspaceMismatch(targetAbs, workspaceId) ?? spokeOriginMismatch(targetAbs, origin);
213
+ if (mismatch !== undefined)
214
+ throw new ApplyDesignRefusedError(`${mismatch}. Nothing was written.`);
362
215
  }
363
- if (designMdNext !== designMdCurrent) {
364
- writeFileSync(designMdPath, designMdNext);
365
- changes.push({ path: "DESIGN.md", kind: "design" });
216
+ // Read before any request: a manifest the roster reader refuses stops the run here.
217
+ const templateLayout = readSiteRoster(targetAbs)?.template.layout;
218
+ // Step 2 — the record as it stands.
219
+ const url = designUrl(origin, workspaceId);
220
+ const read = await hubRequest(fetchImpl, url, apiKey);
221
+ const readVersion = storedVersion(read);
222
+ if (readVersion === undefined || !isPlainObject(read.data)) {
223
+ throw new Error(`apply-design: the hub's design read answered ${describeAnswer(read)}. Nothing was written.`);
366
224
  }
367
- if (siteMdxNext !== siteMdxCurrent) {
368
- writeFileSync(siteMdxPath, siteMdxNext);
369
- changes.push({ path: "content/_site.mdx", kind: "theme" });
225
+ // Step 3 — imported, or already on its record.
226
+ if (!isPlainObject(read.data["settings"]) && retiredLookSources(targetAbs).length > 0) {
227
+ throw new ApplyDesignRefusedError("this site's look is still in its files — import it first (#12476's runbook), then apply-design. Nothing was written.");
370
228
  }
371
- if (manifestNext !== undefined && rosterAbs !== undefined) {
372
- writeFileSync(rosterAbs, manifestNext);
373
- changes.push({ path: SITE_ROSTER_PATH, kind: "manifest" });
229
+ // Step 4 — the new look, keeping the record's own header and footer styles,
230
+ // brand override and creative-direction answers exactly as read: the hub
231
+ // refuses an agent's write that changes the brand, and any write that
232
+ // changes the answers.
233
+ const stored = isPlainObject(read.data["design"]) ? read.data["design"] : {};
234
+ const design = {
235
+ ...lookRecordFor({ resolved, templateLayout }),
236
+ ...(stored["chrome"] !== undefined && { chrome: stored["chrome"] }),
237
+ ...(stored["brand"] !== undefined && { brand: stored["brand"] }),
238
+ ...(stored["direction"] !== undefined && { direction: stored["direction"] }),
239
+ };
240
+ const written = await hubRequest(fetchImpl, url, apiKey, {
241
+ method: "PUT",
242
+ body: { version: readVersion, design },
243
+ });
244
+ const version = storedVersion(written);
245
+ if (typeof version !== "number") {
246
+ if (written.status === 409) {
247
+ throw new Error("apply-design: the record was saved meanwhile — run apply-design again.");
248
+ }
249
+ if (written.status === 403) {
250
+ throw new Error(`apply-design: the hub refused the write (${describeAnswer(written)}) — the agent key needs the site-design grant, and the look must be in the workspace's plan.`);
251
+ }
252
+ throw new Error(`apply-design: the hub's design write answered ${describeAnswer(written)}.`);
374
253
  }
375
254
  return {
376
255
  targetDir: targetAbs,
377
256
  design: resolved.recorded,
378
257
  display: resolved.display,
379
- changes,
380
- manifest,
381
- home: homePlan.outcome,
382
- ...(homeArc ? { homeArc: true } : {}),
383
- contact: contactPlan.outcome,
384
- ...(contactSeeding.offered ? { contactSeed: true } : {}),
385
- ...(roster !== undefined ? { rosterPath: roster.path } : {}),
386
- ...(fontFamilies !== undefined ? { fonts: fontFamilies } : {}),
387
- ...(fontsUnwired ? { fontsUnwired: true } : {}),
388
- ...(unreadChrome.length > 0 ? { unreadChrome } : {}),
258
+ record: { version, look: design.from?.look ?? null, workspaceId, origin },
389
259
  };
390
260
  }
391
- /** The changed-file report (D9). */
261
+ /** The report (D5 step 5): the record written, and where. No line names a file. */
392
262
  export function formatApplyDesignReport(result) {
393
- const lines = [];
394
- if (result.changes.length === 0) {
395
- lines.push(`[create-ailk] The site already wears design "${result.design}" — no file changed.`);
396
- }
397
- else {
398
- lines.push(`[create-ailk] Applied design "${result.design}" to ${result.targetDir}`);
399
- for (const change of result.changes) {
400
- const suffix = change.kind === "preset"
401
- ? ` (${change.fields.join(", ")})`
402
- : change.kind === "home" || change.kind === "contact"
403
- ? ` (${[change.action, change.fields.join(", ")].filter((part) => part !== "").join("; ")})`
404
- : "";
405
- lines.push(` ${change.kind.padEnd(8)} ${change.path}${suffix}`);
406
- }
407
- const n = result.changes.length;
408
- const homeWritten = result.changes.some((change) => change.kind === "home");
409
- const contactWritten = result.changes.some((change) => change.kind === "contact");
410
- const contactNote = "the contact page's sections and title were replaced.";
411
- lines.push(`${n} file${n === 1 ? "" : "s"} changed. ${homeWritten
412
- ? `Routes are unchanged; the home page's sections were replaced.${contactWritten ? ` And ${contactNote}` : ""}`
413
- : contactWritten
414
- ? `Routes are unchanged; ${contactNote}`
415
- : "Routes and structured data are unchanged."}`);
416
- }
417
- if (result.home === "authored" && result.homeArc === true) {
418
- lines.push(`home kept: ${HOME_PAGE_PATH} has authored sections — the ${result.design} home arc was not applied`);
419
- }
420
- else if (result.home === "no-shape" && result.homeArc === true) {
421
- lines.push("home not seeded: the site records no shape");
422
- }
423
- if (result.contact === "authored" && result.contactSeed === true) {
424
- lines.push(`contact kept: ${CONTACT_PAGE_PATH} has an authored title or sections — the ${result.design} contact page was not applied`);
425
- }
426
- if (result.fonts !== undefined) {
427
- lines.push(`fonts: ${result.fonts.join(", ")} load at next build through next/font/google — a family that is not a variable Google font fails there`);
428
- }
429
- if (result.fontsUnwired === true) {
430
- lines.push(`fonts not loaded: ${SITE_LAYOUT_PATH} predates lib/site-fonts — update the layout from the current create-ailk overlay`);
431
- }
432
- for (const { knob, file } of result.unreadChrome ?? []) {
433
- lines.push(`chrome not rendered: ${knob} — ${file} does not read it`);
434
- }
435
- if (result.manifest === "legacy-roster") {
436
- lines.push(`manifest not recorded: ${result.rosterPath} predates the design record`);
437
- }
438
- else if (result.manifest === "no-roster") {
439
- lines.push(`manifest not recorded: the site has no ${SITE_ROSTER_PATH}`);
440
- }
263
+ const { record } = result;
264
+ const lines = [
265
+ `[create-ailk] ${result.targetDir} now wears design "${result.design}" — hub design record version ${record.version} (workspace ${record.workspaceId} at ${record.origin}).`,
266
+ ];
267
+ if (record.look === null)
268
+ lines.push(`its own look (from ${result.display})`);
441
269
  return `${lines.join("\n")}\n`;
442
270
  }