@reqvire-org/ads 0.3.44 → 0.3.45

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 (175) hide show
  1. package/README.md +27 -9
  2. package/dist/assets.mjs +4 -4
  3. package/dist/brand-assets.mjs +41 -7
  4. package/dist/cli.mjs +21 -9
  5. package/dist/config.mjs +19 -10
  6. package/dist/create.mjs +48 -0
  7. package/dist/image-size.mjs +28 -0
  8. package/dist/index.mjs +1 -0
  9. package/dist/init.mjs +4 -5
  10. package/dist/mcp/preview-widget.bundle.js +1 -1
  11. package/dist/mcp/project-widget.bundle.js +1 -1
  12. package/dist/mcp/server.mjs +3 -4
  13. package/dist/mcp/skills.mjs +1 -1
  14. package/dist/preview-resources.mjs +1 -1
  15. package/dist/scenario-groups.mjs +2 -2
  16. package/dist/scenario-registry.mjs +3 -3
  17. package/dist/scenarios-compiler.mjs +1 -1
  18. package/dist/scenarios.mjs +6 -11
  19. package/dist/showcase/client.bundle.js +22 -22
  20. package/dist/showcase/draft-navigation.js +1 -1
  21. package/dist/showcase/index.html +1 -0
  22. package/dist/skills/ads-break-ui/SKILL.md +1 -1
  23. package/dist/skills/ads-designer/README.md +2 -2
  24. package/dist/skills/ads-designer/SKILL.md +37 -56
  25. package/dist/skills/ads-designer/references/branding.md +24 -9
  26. package/dist/skills/ads-designer/references/cli.md +5 -4
  27. package/dist/skills/ads-import/SKILL.md +1 -1
  28. package/dist/skills/ads-import/references/branding.md +4 -3
  29. package/dist/skills/ads-import/references/cli.md +5 -4
  30. package/dist/skills/ads-motion/SKILL.md +1 -1
  31. package/dist/skills/ads-port/SKILL.md +1 -1
  32. package/dist/skills/ads-port/references/cli.md +5 -4
  33. package/dist/{bootstrap-ds → starters/react}/README.md +13 -19
  34. package/dist/{skills/ads-designer/assets/bootstrap-ds → starters/react}/design-system/assets/brand/README.md +1 -1
  35. package/dist/starters/react/design-system/brand/Icons/AppIcon/AppIcon.ads.fixture.ts +7 -0
  36. package/dist/{bootstrap-ds/design-system/tokens/Brand.ads.scenario.tsx → starters/react/design-system/brand/Icons/AppIcon/AppIcon.ads.scenario.tsx} +2 -2
  37. package/dist/starters/react/design-system/brand/Identity/Logo/Logo.ads.fixture.ts +7 -0
  38. package/dist/{skills/ads-designer/assets/bootstrap-ds/design-system/tokens/Brand.ads.scenario.tsx → starters/react/design-system/brand/Identity/Logo/Logo.ads.scenario.tsx} +2 -2
  39. package/dist/{skills/ads-designer/assets/bootstrap-ds → starters/react}/tsconfig.build.json +2 -1
  40. package/dist/task-cache.mjs +1 -1
  41. package/dist/token-fixtures.mjs +1 -1
  42. package/dist/units.mjs +6 -6
  43. package/dist/validation.mjs +1 -1
  44. package/docs/ADS.md +4 -4
  45. package/docs/ARCHITECTURE.md +1 -1
  46. package/docs/CHANGELOG.md +36 -12
  47. package/docs/GUIDE.md +25 -22
  48. package/package.json +3 -5
  49. package/dist/bootstrap-ds/design-system/assets/brand/README.md +0 -36
  50. package/dist/bootstrap-ds/design-system/tokens/Brand.ads.fixture.ts +0 -12
  51. package/dist/bootstrap-ds/tsconfig.build.json +0 -19
  52. package/dist/skills/ads-designer/assets/bootstrap-ds/ADS.md +0 -258
  53. package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +0 -122
  54. package/dist/skills/ads-designer/assets/bootstrap-ds/biome.css.json +0 -21
  55. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/assets/brand/app-icon.svg +0 -4
  56. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/assets/brand/logo.dark.svg +0 -6
  57. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/assets/brand/logo.svg +0 -6
  58. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/assets/fonts/.gitkeep +0 -0
  59. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Actions/Button/Button.ads.fixture.ts +0 -1
  60. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Actions/Button/Button.ads.scenario.tsx +0 -13
  61. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Actions/Button/Button.tsx +0 -49
  62. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Actions/Button/README.md +0 -12
  63. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Content/Logo/Logo.ads.fixture.ts +0 -1
  64. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Content/Logo/Logo.ads.scenario.tsx +0 -12
  65. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Content/Logo/Logo.tsx +0 -41
  66. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Content/Logo/README.md +0 -10
  67. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Forms/TextField/README.md +0 -14
  68. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Forms/TextField/TextField.ads.fixture.ts +0 -6
  69. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Forms/TextField/TextField.ads.scenario.tsx +0 -13
  70. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/components/Forms/TextField/TextField.tsx +0 -57
  71. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/composition/Search/SearchPage/README.md +0 -4
  72. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/composition/Search/SearchPage/SearchPage.ads.fixture.ts +0 -7
  73. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/composition/Search/SearchPage/SearchPage.ads.scenario.tsx +0 -16
  74. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/controllers/.gitkeep +0 -0
  75. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/index.ts +0 -8
  76. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/patterns/Search/SearchBar/README.md +0 -12
  77. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/patterns/Search/SearchBar/SearchBar.ads.fixture.ts +0 -1
  78. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/patterns/Search/SearchBar/SearchBar.ads.scenario.tsx +0 -11
  79. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/patterns/Search/SearchBar/SearchBar.tsx +0 -41
  80. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/brand-preview/BrandPreview.tsx +0 -115
  81. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/demo-frame/DemoFrame.tsx +0 -29
  82. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/index.ts +0 -4
  83. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/screen-frame/ScreenFrame.tsx +0 -34
  84. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/review/token-preview/TokenPreview.tsx +0 -119
  85. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/showcase/mcp/index.html +0 -1
  86. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/showcase/mcp/main.tsx +0 -8
  87. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/styles.css +0 -5
  88. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/Brand.ads.fixture.ts +0 -12
  89. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/Color.ads.fixture.ts +0 -18
  90. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/Color.ads.scenario.tsx +0 -4
  91. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/SpaceTypeMotion.ads.fixture.ts +0 -36
  92. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/SpaceTypeMotion.ads.scenario.tsx +0 -4
  93. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/base.css +0 -30
  94. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/colors.css +0 -29
  95. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/elevation.css +0 -15
  96. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/spacing.css +0 -15
  97. package/dist/skills/ads-designer/assets/bootstrap-ds/design-system/tokens/typography.css +0 -13
  98. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +0 -20
  99. package/dist/skills/ads-designer/assets/bootstrap-ds/gitignore.template +0 -8
  100. package/dist/skills/ads-designer/assets/bootstrap-ds/package-lock.json +0 -4660
  101. package/dist/skills/ads-designer/assets/bootstrap-ds/package.json +0 -42
  102. package/dist/skills/ads-designer/assets/bootstrap-ds/scripts/build-mcp-previews.mjs +0 -3
  103. package/dist/skills/ads-designer/assets/bootstrap-ds/src/vite-env.d.ts +0 -7
  104. package/dist/skills/ads-designer/assets/bootstrap-ds/tsconfig.json +0 -35
  105. package/dist/skills/ads-designer/assets/bootstrap-ds/vite.config.ts +0 -23
  106. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/design-system/review/demo-frame/DemoFrame.tsx +0 -29
  107. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/design-system/review/screen-frame/ScreenFrame.tsx +0 -34
  108. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/design-system/review/token-preview/TokenPreview.tsx +0 -119
  109. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/design-system/showcase/mcp/main.tsx +0 -6
  110. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/ds.config.json +0 -20
  111. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/package.json +0 -38
  112. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/src/vite-env.d.ts +0 -7
  113. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/tsconfig.json +0 -36
  114. package/dist/skills/ads-designer/assets/bootstrap-ds-preact/vite.config.ts +0 -23
  115. /package/dist/{bootstrap-ds-preact → starters/preact}/design-system/review/demo-frame/DemoFrame.tsx +0 -0
  116. /package/dist/{bootstrap-ds-preact → starters/preact}/design-system/review/screen-frame/ScreenFrame.tsx +0 -0
  117. /package/dist/{bootstrap-ds-preact → starters/preact}/design-system/review/token-preview/TokenPreview.tsx +0 -0
  118. /package/dist/{bootstrap-ds-preact → starters/preact}/design-system/showcase/mcp/main.tsx +0 -0
  119. /package/dist/{bootstrap-ds-preact → starters/preact}/ds.config.json +0 -0
  120. /package/dist/{bootstrap-ds-preact → starters/preact}/package.json +0 -0
  121. /package/dist/{bootstrap-ds-preact → starters/preact}/src/vite-env.d.ts +0 -0
  122. /package/dist/{bootstrap-ds-preact → starters/preact}/tsconfig.json +0 -0
  123. /package/dist/{bootstrap-ds-preact → starters/preact}/vite.config.ts +0 -0
  124. /package/dist/{bootstrap-ds → starters/react}/ADS.md +0 -0
  125. /package/dist/{bootstrap-ds → starters/react}/biome.css.json +0 -0
  126. /package/dist/{bootstrap-ds → starters/react}/design-system/assets/brand/app-icon.svg +0 -0
  127. /package/dist/{bootstrap-ds → starters/react}/design-system/assets/brand/logo.dark.svg +0 -0
  128. /package/dist/{bootstrap-ds → starters/react}/design-system/assets/brand/logo.svg +0 -0
  129. /package/dist/{bootstrap-ds → starters/react}/design-system/assets/fonts/.gitkeep +0 -0
  130. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Actions/Button/Button.ads.fixture.ts +0 -0
  131. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Actions/Button/Button.ads.scenario.tsx +0 -0
  132. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Actions/Button/Button.tsx +0 -0
  133. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Actions/Button/README.md +0 -0
  134. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Content/Logo/Logo.ads.fixture.ts +0 -0
  135. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Content/Logo/Logo.ads.scenario.tsx +0 -0
  136. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Content/Logo/Logo.tsx +0 -0
  137. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Content/Logo/README.md +0 -0
  138. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Forms/TextField/README.md +0 -0
  139. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Forms/TextField/TextField.ads.fixture.ts +0 -0
  140. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Forms/TextField/TextField.ads.scenario.tsx +0 -0
  141. /package/dist/{bootstrap-ds → starters/react}/design-system/components/Forms/TextField/TextField.tsx +0 -0
  142. /package/dist/{bootstrap-ds → starters/react}/design-system/composition/Search/SearchPage/README.md +0 -0
  143. /package/dist/{bootstrap-ds → starters/react}/design-system/composition/Search/SearchPage/SearchPage.ads.fixture.ts +0 -0
  144. /package/dist/{bootstrap-ds → starters/react}/design-system/composition/Search/SearchPage/SearchPage.ads.scenario.tsx +0 -0
  145. /package/dist/{bootstrap-ds → starters/react}/design-system/controllers/.gitkeep +0 -0
  146. /package/dist/{bootstrap-ds → starters/react}/design-system/index.ts +0 -0
  147. /package/dist/{bootstrap-ds → starters/react}/design-system/patterns/Search/SearchBar/README.md +0 -0
  148. /package/dist/{bootstrap-ds → starters/react}/design-system/patterns/Search/SearchBar/SearchBar.ads.fixture.ts +0 -0
  149. /package/dist/{bootstrap-ds → starters/react}/design-system/patterns/Search/SearchBar/SearchBar.ads.scenario.tsx +0 -0
  150. /package/dist/{bootstrap-ds → starters/react}/design-system/patterns/Search/SearchBar/SearchBar.tsx +0 -0
  151. /package/dist/{bootstrap-ds → starters/react}/design-system/review/brand-preview/BrandPreview.tsx +0 -0
  152. /package/dist/{bootstrap-ds → starters/react}/design-system/review/demo-frame/DemoFrame.tsx +0 -0
  153. /package/dist/{bootstrap-ds → starters/react}/design-system/review/index.ts +0 -0
  154. /package/dist/{bootstrap-ds → starters/react}/design-system/review/screen-frame/ScreenFrame.tsx +0 -0
  155. /package/dist/{bootstrap-ds → starters/react}/design-system/review/token-preview/TokenPreview.tsx +0 -0
  156. /package/dist/{bootstrap-ds → starters/react}/design-system/showcase/mcp/index.html +0 -0
  157. /package/dist/{bootstrap-ds → starters/react}/design-system/showcase/mcp/main.tsx +0 -0
  158. /package/dist/{bootstrap-ds → starters/react}/design-system/styles.css +0 -0
  159. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/Color.ads.fixture.ts +0 -0
  160. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/Color.ads.scenario.tsx +0 -0
  161. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/SpaceTypeMotion.ads.fixture.ts +0 -0
  162. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/SpaceTypeMotion.ads.scenario.tsx +0 -0
  163. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/base.css +0 -0
  164. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/colors.css +0 -0
  165. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/elevation.css +0 -0
  166. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/spacing.css +0 -0
  167. /package/dist/{bootstrap-ds → starters/react}/design-system/tokens/typography.css +0 -0
  168. /package/dist/{bootstrap-ds → starters/react}/ds.config.json +0 -0
  169. /package/dist/{bootstrap-ds → starters/react}/gitignore.template +0 -0
  170. /package/dist/{bootstrap-ds → starters/react}/package-lock.json +0 -0
  171. /package/dist/{bootstrap-ds → starters/react}/package.json +0 -0
  172. /package/dist/{bootstrap-ds → starters/react}/scripts/build-mcp-previews.mjs +0 -0
  173. /package/dist/{bootstrap-ds → starters/react}/src/vite-env.d.ts +0 -0
  174. /package/dist/{bootstrap-ds → starters/react}/tsconfig.json +0 -0
  175. /package/dist/{bootstrap-ds → starters/react}/vite.config.ts +0 -0
package/README.md CHANGED
@@ -64,7 +64,24 @@ and composition previews can use dependency drafts through normal `@ds` imports;
64
64
  accepting a dependency automatically switches dependent drafts to accepted source.
65
65
  Drafts survive restart and Git clone, but cannot enter production imports.
66
66
 
67
- ## Set up your project
67
+ ## Create a new design system
68
+
69
+ `create` copies the starter shipped in this ADS version into a new folder and sets
70
+ it up, so the project always matches the tool that checks it:
71
+
72
+ ```sh
73
+ npx @reqvire-org/ads create my-design-system --framework react # or preact
74
+ cd my-design-system
75
+ npm install
76
+ npm run build
77
+ npm run dev:showcase
78
+ ```
79
+
80
+ With Bun: `bunx @reqvire-org/ads create my-design-system --framework preact
81
+ --package-manager bun`, then `bun install` and `bun --bun run build`. `--name` sets
82
+ the package name (default: the folder name).
83
+
84
+ ## Set up an existing project
68
85
 
69
86
  Run **inside your project**, where `package.json` lives. Install Bun 1.4.1+ for
70
87
  ADS tooling and previews. Your application can continue using Node/npm or Bun.
@@ -76,8 +93,7 @@ npm run build
76
93
  ```
77
94
 
78
95
  Use `--framework preact` for native Preact. Init saves the choice in
79
- `ds.config.json`; later runs can use plain `ads init`. A copied starter that
80
- already declares its framework can also omit the flag.
96
+ `ds.config.json`; later runs can use plain `ads init`.
81
97
 
82
98
  For a Bun project, Node is unnecessary:
83
99
 
@@ -233,7 +249,7 @@ happens automatically; no separate project showcase rebuild is needed.
233
249
 
234
250
  For an existing app, `init` adds the showcase launch script; it does not install
235
251
  a preview compiler. Integrate the [starter compiler and mount adapter](docs/GUIDE.md#showcase)
236
- with your build. The copied starter already includes that setup.
252
+ with your build. Projects from `ads create` already include that setup.
237
253
 
238
254
  There are no required showcase page files. Add a colocated scenario and fixture
239
255
  for tokens and each public UI owner; larger entries live under `composition/`.
@@ -340,11 +356,13 @@ The [dummy project](tests/fixtures/guard-project/README.md) tests the generic gu
340
356
 
341
357
  There are two different starting points in this checkout:
342
358
 
343
- - [bootstrap-ds/](bootstrap-ds/README.md) is the React application starter, and
344
- [bootstrap-ds-preact/](bootstrap-ds-preact/) the files that make it Preact:
345
- token defaults in two groups, build setup, one example component in each of two groups,
346
- a pattern and a composition, development-only review renderers, and a project preview compiler adapter. It is bundled with `ads-designer` so an agent can copy it when starting
347
- from zero. `ads init` uses its empty foundation files when a project has no ADS.
359
+ - [starters/react/](starters/react/README.md) is the React application starter, and
360
+ [starters/preact/](starters/preact/) the files that replace it for Preact:
361
+ token defaults in two groups, a brand preview with placeholder artwork, build
362
+ setup, example components, a pattern and a composition, development-only review
363
+ renderers, and a project preview compiler adapter. They ship in the npm package;
364
+ `ads create` copies them into a new project, and `ads init` uses their foundation
365
+ files when a project has no ADS.
348
366
  - [design-system/](design-system/README.md) is this repository's working example,
349
367
  with real components, patterns, and scenarios inspected through the built-in showcase. It demonstrates the architecture
350
368
  and helps us develop the tooling. Its UI source is excluded from the npm package
package/dist/assets.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import path from "node:path";
4
- import { isInside } from "./config.mjs";
4
+ import { brandFormats, isInside } from "./config.mjs";
5
5
  import { brandFiles, brandSourceDiagnostic, staleBrandOutputs } from "./brand-assets.mjs";
6
6
 
7
7
  function assetFiles(directory, prefix = "") {
@@ -41,7 +41,7 @@ function inspectBrand({ root, dsRoot, config }) {
41
41
  const relative = file => path.relative(root, file).replaceAll("\\", "/") || ".";
42
42
  for (const { file, message } of staleBrandOutputs({ root, dsRoot, config })) diagnostics.push({ rule: "brand-output-stale", file, line: 1, column: 1, message });
43
43
  const brand = path.join(dsRoot, "assets/brand");
44
- const artwork = assetFiles(brand).filter(file => file.toLowerCase().endsWith(".svg"));
44
+ const artwork = assetFiles(brand).filter(file => brandFormats.includes(path.extname(file).toLowerCase()));
45
45
  if (!artwork.length) return diagnostics;
46
46
  const warn = (rule, file, message) => diagnostics.push({ rule, severity: "warning", file: relative(file), line: 1, column: 1, guidanceUri: "ads://guides/branding", message });
47
47
  const readmeFile = path.join(brand, "README.md");
@@ -51,12 +51,12 @@ function inspectBrand({ root, dsRoot, config }) {
51
51
  const generated = [...config.assets.generatedPaths.map(entry => path.resolve(root, entry)), path.join(root, ".ds")];
52
52
  const sources = sourceTexts([dsRoot, path.join(root, config.sourceDir ?? "src")], [path.join(dsRoot, "assets"), ...generated]);
53
53
  const configured = new Set([config.assets.iconSource, ...config.assets.targets.map(target => target.from)].filter(Boolean).map(file => path.join(dsRoot, file)));
54
- const previews = path.join(dsRoot, config.tokenDir);
54
+ const previews = path.join(dsRoot, "brand");
55
55
  for (const name of artwork) {
56
56
  const file = path.join(brand, name), base = path.basename(name);
57
57
  if (readme !== null && !readme.includes(base)) warn("brand-readme", file, `Describe ${base} in assets/brand/README.md: its use, suitable backgrounds, credits and license.`);
58
58
  const referencing = sources.filter(source => source.text.includes(base));
59
- if (!referencing.some(source => isInside(previews, source.file) && previewFile.test(source.file))) warn("brand-preview", file, `Show ${base} in a token-folder brand scenario, so it can be reviewed with the foundation.`);
59
+ if (!referencing.some(source => isInside(previews, source.file) && previewFile.test(source.file))) warn("brand-preview", file, `Show ${base} in a brand/ scenario, so it can be reviewed in the showcase's Brand section.`);
60
60
  if (!configured.has(file) && !referencing.some(source => !previewFile.test(source.file))) warn("brand-unused", file, `${base} is not used by any component, assets.iconSource or assets.targets. Use it or remove it.`);
61
61
  }
62
62
  return diagnostics;
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { isInside, loadConfig } from "./config.mjs";
5
+ import { imageSize } from "./image-size.mjs";
5
6
 
6
7
  export const brandFiles = ["favicon.svg", "favicon.ico", "apple-touch-icon.png", "icon-192.png", "icon-512.png"];
7
8
 
@@ -14,8 +15,15 @@ export function brandSourceDiagnostic({ root, dsRoot, config }) {
14
15
  if (!stat || stat.isSymbolicLink() || (current === file ? !stat.isFile() : !stat.isDirectory())) valid = false;
15
16
  if (current === root) break;
16
17
  }
18
+ const relative = path.relative(root, file).replaceAll("\\", "/");
19
+ if (valid && !file.toLowerCase().endsWith(".svg")) {
20
+ // A finished image is a master only when it is square and big enough for the largest icon.
21
+ const size = imageSize(readFileSync(file));
22
+ if (size && size.width === size.height && size.width >= 512) return null;
23
+ return { rule: "asset-source", file: relative, line: 1, column: 1, message: `assets.iconSource ${size ? `is ${size.width}×${size.height}; it` : "is not a readable PNG, JPEG or WebP; it"} must be a square image of at least 512×512, or an SVG.` };
24
+ }
17
25
  if (valid && /<svg\b[\s\S]*<\/svg\s*>|<svg\b[^>]*\/>/i.test(readFileSync(file, "utf8"))) return null;
18
- return { rule: "asset-source", file: path.relative(root, file).replaceAll("\\", "/"), line: 1, column: 1, message: "assets.iconSource must be an existing SVG master inside assets/brand/, without symlinked paths." };
26
+ return { rule: "asset-source", file: relative, line: 1, column: 1, message: "assets.iconSource must be an existing SVG master inside assets/brand/, without symlinked paths." };
19
27
  }
20
28
 
21
29
  function assertOutput(root, file, { directory = false } = {}) {
@@ -78,12 +86,29 @@ function icns(entries) {
78
86
  return Buffer.concat([header, ...chunks]);
79
87
  }
80
88
 
89
+ const sized = target => ["size", "width", "height", "sizes", "background"].some(key => key in target);
90
+ /** A copy of the supplied file: the same format, no sizes. */
91
+ export const copiesTarget = target => !sized(target) && path.extname(target.to).toLowerCase() === path.extname(target.from).toLowerCase();
92
+
93
+ /** Why a raster master cannot make this target: ADS never enlarges a finished image. */
94
+ export function targetUpscale(source, target) {
95
+ if (copiesTarget(target) || target.from.toLowerCase().endsWith(".svg")) return null;
96
+ const size = imageSize(source);
97
+ if (!size) return `${target.from} is not a readable PNG, JPEG or WebP.`;
98
+ const sizes = target.sizes ?? [];
99
+ const width = target.width ?? target.size ?? Math.max(...sizes), height = target.height ?? target.size ?? Math.max(...sizes);
100
+ return Math.min(width / size.width, height / size.height) > 1 ? `${target.to} would enlarge ${target.from} (${size.width}×${size.height}) to ${width}×${height}. Supply a larger image or an SVG master.` : null;
101
+ }
102
+
81
103
  async function renderTarget(sharp, source, target) {
82
104
  const format = path.extname(target.to).toLowerCase();
83
- if (format === ".svg") return source;
105
+ if (copiesTarget(target)) return source;
106
+ const upscale = targetUpscale(source, target);
107
+ if (upscale) throw new Error(upscale);
108
+ const vector = target.from.toLowerCase().endsWith(".svg");
84
109
  const background = target.background;
85
110
  const png = async (width, height) => {
86
- let image = sharp(source, { density: Math.max(72, Math.ceil(Math.max(width, height) * 1.5)) })
111
+ let image = sharp(source, vector ? { density: Math.max(72, Math.ceil(Math.max(width, height) * 1.5)) } : {})
87
112
  .resize(width, height, { fit: "contain", background: { r: 0, g: 0, b: 0, alpha: 0 } });
88
113
  if (background) image = image.flatten({ background });
89
114
  return image.png().toBuffer();
@@ -129,6 +154,9 @@ export function staleBrandOutputs(options) {
129
154
  const file = path.join(root, target.to);
130
155
  const entry = recorded[target.to];
131
156
  let reason = null;
157
+ if (!existsSync(path.join(dsRoot, target.from))) { stale.push({ file: target.to, message: `${target.to} names a missing master ${target.from}.` }); continue; }
158
+ const upscale = targetUpscale(readFileSync(path.join(dsRoot, target.from)), target);
159
+ if (upscale) { stale.push({ file: target.to, message: upscale }); continue; }
132
160
  if (!existsSync(file)) reason = "is missing";
133
161
  else if (!entry || entry.fingerprint !== fingerprint(dsRoot, target)) reason = `no longer matches ${target.from} or its settings`;
134
162
  else if (entry.sha256 !== sha256(readFileSync(file))) reason = "was changed by hand";
@@ -152,6 +180,7 @@ async function generateCommitted(options) {
152
180
  let sharp;
153
181
  for (const target of config.assets.targets) {
154
182
  const file = path.join(root, target.to);
183
+ if (!existsSync(path.join(dsRoot, target.from))) throw new Error(`${target.to} names a missing master ${target.from}.`);
155
184
  const print = fingerprint(dsRoot, target);
156
185
  const entry = recorded[target.to];
157
186
  if (entry?.fingerprint === print && existsSync(file) && entry.sha256 === sha256(readFileSync(file))) { next[target.to] = entry; continue; }
@@ -196,10 +225,12 @@ export async function generateBrandAssets(directory = process.cwd()) {
196
225
  // before writing, so invalid SVG cannot replace the last successful outputs.
197
226
  const { default: sharp } = await import("sharp");
198
227
  const source = readFileSync(path.join(dsRoot, config.assets.iconSource));
199
- const outputs = new Map([["favicon.svg", source]]);
228
+ const vector = config.assets.iconSource.toLowerCase().endsWith(".svg");
229
+ // Only an SVG master is also the SVG favicon; a finished image makes the rest.
230
+ const outputs = new Map(vector ? [["favicon.svg", source]] : []);
200
231
  const sizes = [16, 32, 48, 180, 192, 512];
201
232
  const rendered = new Map();
202
- for (const size of sizes) rendered.set(size, await sharp(source, { density: 512 }).resize(size, size, { fit: "contain", background: { r: 0, g: 0, b: 0, alpha: 0 } }).png().toBuffer());
233
+ for (const size of sizes) rendered.set(size, await sharp(source, vector ? { density: 512 } : {}).resize(size, size, { fit: "contain", background: { r: 0, g: 0, b: 0, alpha: 0 } }).png().toBuffer());
203
234
  outputs.set("favicon.ico", ico([16, 32, 48].map((size) => ({ size, buffer: rendered.get(size) }))));
204
235
  outputs.set("apple-touch-icon.png", rendered.get(180));
205
236
  outputs.set("icon-192.png", rendered.get(192));
@@ -209,7 +240,10 @@ export async function generateBrandAssets(directory = process.cwd()) {
209
240
  try {
210
241
  for (const [name, buffer] of outputs) writeFileSync(path.join(staging, name), buffer);
211
242
  mkdirSync(output, { recursive: true });
212
- for (const name of brandFiles) renameSync(path.join(staging, name), path.join(output, name));
243
+ for (const name of brandFiles) {
244
+ if (outputs.has(name)) renameSync(path.join(staging, name), path.join(output, name));
245
+ else rmSync(path.join(output, name), { force: true });
246
+ }
213
247
  } finally { rmSync(staging, { recursive: true, force: true }); }
214
- return { directory: output, files: brandFiles.map((name) => path.join(output, name)), committed, skipped: false };
248
+ return { directory: output, files: [...outputs.keys()].map((name) => path.join(output, name)), committed, skipped: false };
215
249
  }
package/dist/cli.mjs CHANGED
@@ -8,9 +8,11 @@ import { assertBunRuntime } from "./runtime-requirements.mjs";
8
8
  const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
9
9
  const help = `ADS ${pkg.version} — tooling for a project's local design system
10
10
 
11
- Usage: ads init [options] Run inside your project
11
+ Usage: ads create <directory> --framework react|preact New design-system project
12
+ ads init [options] Run inside your project
12
13
  ads <command> [directory] [--json]
13
14
 
15
+ create <directory> Create a project from this version's starter, then init it
14
16
  init Set up ADS in the current project (requires package.json)
15
17
  check [directory] Check tokens, ownership, imports, and showcase coverage
16
18
  compile [directory] Build ADS previews with Bun (--watch for incremental previews)
@@ -26,9 +28,10 @@ Usage: ads init [options] Run inside your project
26
28
 
27
29
  --help Show this help
28
30
  --version Show the tool version
29
- --framework name Init only: react or preact (required until saved in config)
30
- --tool-package spec Init only: tool version or local tarball for devDependency
31
- --package-manager pm Init only: npm or bun (auto-detected from the project)
31
+ --framework name Create/init: react or preact (required until saved in config)
32
+ --name name Create only: package name (default: the folder name)
33
+ --tool-package spec Create/init: tool version or local tarball for devDependency
34
+ --package-manager pm Create/init: npm or bun (create default npm; init detects it)
32
35
  --port number MCP/showcase only: loopback website port (default: automatic)
33
36
  --no-showcase MCP only: disable the local website
34
37
  --mutations MCP only: enable guarded ADS source editing
@@ -49,6 +52,7 @@ async function main(args) {
49
52
  let toolPackage;
50
53
  let packageManager;
51
54
  let framework;
55
+ let name;
52
56
  let port;
53
57
  let unit;
54
58
  const selectedChecks = [];
@@ -82,6 +86,9 @@ async function main(args) {
82
86
  } else if (argument === "--package-manager") {
83
87
  if (packageManager !== undefined || !args[index + 1] || args[index + 1].startsWith("-")) throw new Error("Specify one package manager after --package-manager: npm or bun.");
84
88
  packageManager = args[++index];
89
+ } else if (argument === "--name") {
90
+ if (name !== undefined || !args[index + 1] || args[index + 1].startsWith("-")) throw new Error("Specify one package name after --name.");
91
+ name = args[++index];
85
92
  } else if (argument === "--framework") {
86
93
  if (framework !== undefined || !args[index + 1] || args[index + 1].startsWith("-")) throw new Error("Specify one framework after --framework: react or preact.");
87
94
  framework = args[++index];
@@ -90,7 +97,7 @@ async function main(args) {
90
97
  }
91
98
  if (positional.length > 2) throw new Error("Extra argument. Run ads --help.");
92
99
  const [command, directory] = positional;
93
- if(command!=="init"){
100
+ if(command!=="init"&&command!=="create"){
94
101
  const exitCode=await enterMemoryBudget(loadConfig(path.resolve(directory??process.cwd())).config,args);
95
102
  if(exitCode!==null){process.exitCode=exitCode;return;}
96
103
  }
@@ -103,9 +110,12 @@ async function main(args) {
103
110
  if ((port !== undefined || !showcase) && !["mcp", "showcase"].includes(command)) throw new Error("Website options are supported only by mcp/showcase.");
104
111
  if (!showcase && command !== "mcp") throw new Error("--no-showcase is supported only by mcp.");
105
112
  if (mutations && command !== "mcp") throw new Error("--mutations is supported only by mcp.");
106
- if (toolPackage !== undefined && command !== "init") throw new Error("--tool-package is supported only by init.");
107
- if (packageManager !== undefined && command !== "init") throw new Error("--package-manager is supported only by init.");
108
- if (framework !== undefined && command !== "init") throw new Error("--framework is supported only by init.");
113
+ const setup = command === "init" || command === "create";
114
+ if (toolPackage !== undefined && !setup) throw new Error("--tool-package is supported only by create and init.");
115
+ if (packageManager !== undefined && !setup) throw new Error("--package-manager is supported only by create and init.");
116
+ if (framework !== undefined && !setup) throw new Error("--framework is supported only by create and init.");
117
+ if (name !== undefined && command !== "create") throw new Error("--name is supported only by create.");
118
+ if (command === "create" && !directory) throw new Error("Name the new project's folder: ads create <directory> --framework react|preact.");
109
119
  if (command === "init" && directory) throw new Error("Run ads init inside the project, without a directory argument.");
110
120
  if ((unit || selectedChecks.length) && command !== "verify") throw new Error("--unit and --check are supported only by verify.");
111
121
  const target = path.resolve(directory ?? process.cwd());
@@ -116,7 +126,8 @@ async function main(args) {
116
126
  return;
117
127
  }
118
128
  let result;
119
- if (command === "init") result = initProject(target, { toolPackage, packageManager, framework });
129
+ if (command === "create") { const { createProject } = await import("./create.mjs"); result = createProject(target, { framework, packageManager, name, toolPackage }); }
130
+ else if (command === "init") result = initProject(target, { toolPackage, packageManager, framework });
120
131
  else if (command === "check") {const {checkCandidate}=await import("./validation-checks.mjs");result=await checkCandidate(target,undefined,target,{fresh});}
121
132
  else if (command === "validate") {
122
133
  const {createValidationController}=await import("./validation.mjs");
@@ -132,6 +143,7 @@ async function main(args) {
132
143
  else if (command === "lint-config") result = generateLintConfig(target);
133
144
  else throw new Error(`Unknown command: ${command}. Run ads --help.`);
134
145
  if (json) console.log(JSON.stringify(result, null, 2));
146
+ else if (command === "create") console.log(`Created ${result.name} in ${target}\nFramework: ${result.framework}\nNext: cd ${((folder) => /[\s'"$`\\]/.test(folder) ? JSON.stringify(folder) : folder)(path.relative(process.cwd(), target) || ".")} && ${result.packageManager} install && ${result.packageManager} run build && ${result.packageManager} run dev:showcase`);
135
147
  else if (command === "init") console.log(`Initialized ${target}\nFramework: ${result.framework}\nAdded ${result.toolDependency.name} (${result.toolDependency.spec}) as a development dependency.\nRun ${result.packageManager} install and ${result.packageManager} run build; the build runs ADS checks and generates configured brand assets automatically.`);
136
148
  else if (command === "assets") console.log(result.skipped ? "No assets.iconSource configured; brand generation skipped." : `Generated ${result.files.length} brand assets in ${result.directory}.`);
137
149
  else if (command === "lint-config") console.log(`Generated ${result.file}\nUse this optional configuration only in the project linter you choose to run.`);
package/dist/config.mjs CHANGED
@@ -34,33 +34,42 @@ export function isInside(parent, file) {
34
34
  }
35
35
 
36
36
  const iconSizes = [16, 32, 64, 128, 256, 512, 1024];
37
- /** Committed brand outputs: each renders one SVG master in assets/brand/ to a project path. */
37
+ /** Brand artwork formats: SVG masters, finished images, and finished icon files. */
38
+ export const brandFormats = [".svg", ".png", ".jpg", ".jpeg", ".webp", ".ico", ".icns"];
39
+ /** Formats a target can render from; finished .ico/.icns files are only copied. */
40
+ export const renderableFormats = [".svg", ".png", ".jpg", ".jpeg", ".webp"];
41
+ const sizeKeys = ["size", "width", "height", "sizes", "background"];
42
+ /** Committed brand outputs: each copies or renders one master in assets/brand/ to a project path. */
38
43
  function validateBrandTargets(targets, { root, dsRoot }) {
39
44
  if (!Array.isArray(targets)) throw new Error("assets.targets must be an array.");
40
45
  const outputs = new Set();
41
46
  for (const [index, target] of targets.entries()) {
42
47
  const field = `assets.targets[${index}]`;
43
48
  if (!target || typeof target !== "object" || Array.isArray(target)) throw new Error(`${field} must be an object.`);
44
- const unknown = Object.keys(target).filter(key => !["from", "to", "size", "width", "height", "sizes", "background"].includes(key));
49
+ const unknown = Object.keys(target).filter(key => !["from", "to", ...sizeKeys].includes(key));
45
50
  if (unknown.length) throw new Error(`${field} has unknown keys: ${unknown.join(", ")}.`);
46
51
  const source = projectPath(dsRoot, target.from, `${field}.from`);
47
- if (!isInside(path.join(dsRoot, "assets/brand"), source) || path.extname(source).toLowerCase() !== ".svg") throw new Error(`${field}.from must name an SVG inside the ADS's assets/brand/ folder.`);
52
+ const sourceFormat = path.extname(source).toLowerCase();
53
+ if (!isInside(path.join(dsRoot, "assets/brand"), source) || !brandFormats.includes(sourceFormat)) throw new Error(`${field}.from must name brand artwork inside the ADS's assets/brand/ folder (${brandFormats.join(", ")}).`);
48
54
  const output = projectPath(root, target.to, `${field}.to`);
49
55
  if (isInside(path.join(dsRoot, "assets"), output) || isInside(path.join(root, ".ds"), output)) throw new Error(`${field}.to must be outside the ADS assets/ folder and .ds/.`);
50
56
  if (outputs.has(output)) throw new Error(`${field}.to repeats an earlier target's output.`);
51
57
  outputs.add(output);
52
58
  const format = path.extname(output).toLowerCase();
59
+ const sized = sizeKeys.some(key => key in target);
60
+ // The same format without sizes is a copy of the supplied file.
61
+ if (!sized && format === sourceFormat) continue;
62
+ if (format === ".svg") throw new Error(`${field} copies an SVG master to .svg; it takes no sizes.`);
63
+ if (!renderableFormats.includes(sourceFormat)) throw new Error(`${field} copies the finished ${sourceFormat} file; give it the same extension and no sizes.`);
53
64
  const pixels = value => Number.isInteger(value) && value >= 1 && value <= 4096;
54
- if (target.background !== undefined && (format === ".svg" || typeof target.background !== "string" || !/^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(target.background))) throw new Error(`${field}.background must be a #RGB, #RRGGBB or #RRGGBBAA colour on a PNG, ICO or ICNS target.`);
55
- if (format === ".svg") {
56
- if (["size", "width", "height", "sizes"].some(key => key in target)) throw new Error(`${field} copies its SVG; it takes no sizes.`);
57
- } else if (format === ".png") {
65
+ if (target.background !== undefined && (typeof target.background !== "string" || !/^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(target.background))) throw new Error(`${field}.background must be a #RGB, #RRGGBB or #RRGGBBAA colour on a PNG, ICO or ICNS target.`);
66
+ if (format === ".png") {
58
67
  const square = target.size !== undefined, rectangle = target.width !== undefined || target.height !== undefined;
59
68
  if (square === rectangle || target.sizes !== undefined || (square ? !pixels(target.size) : !pixels(target.width) || !pixels(target.height))) throw new Error(`${field} renders a PNG at one size (1–4096) or one width and height.`);
60
69
  } else if (format === ".ico" || format === ".icns") {
61
70
  const allowed = format === ".ico" ? [16, 24, 32, 48, 64, 128, 256] : iconSizes;
62
71
  if (["size", "width", "height"].some(key => key in target) || !Array.isArray(target.sizes) || !target.sizes.length || new Set(target.sizes).size !== target.sizes.length || target.sizes.some(size => !allowed.includes(size))) throw new Error(`${field}.sizes must list distinct ${format.slice(1).toUpperCase()} sizes from ${allowed.join(", ")}.`);
63
- } else throw new Error(`${field}.to must end in .svg, .png, .ico or .icns.`);
72
+ } else throw new Error(`${field}.to must end in .svg, .png, .ico or .icns, or keep the supplied file's extension.`);
64
73
  }
65
74
  }
66
75
  /** A glyph set: SVGs in one assets/ folder become one generated TypeScript map. */
@@ -166,7 +175,7 @@ export function loadConfig(directory = process.cwd()) {
166
175
  }
167
176
  if (config.assets.iconSource !== null) {
168
177
  const source = projectPath(dsRoot, config.assets.iconSource, "assets.iconSource");
169
- if (!isInside(path.join(dsRoot, "assets/brand"), source) || path.extname(source).toLowerCase() !== ".svg") throw new Error("assets.iconSource must name an SVG inside the ADS's assets/brand/ folder.");
178
+ if (!isInside(path.join(dsRoot, "assets/brand"), source) || !renderableFormats.includes(path.extname(source).toLowerCase())) throw new Error("assets.iconSource must name an SVG, or a square PNG, JPEG or WebP of at least 512 px, inside the ADS's assets/brand/ folder.");
170
179
  }
171
180
  validateBrandTargets(config.assets.targets, { root, dsRoot });
172
181
  validateGlyphs(config.assets.glyphs, { dsRoot });
@@ -268,7 +277,7 @@ export function isDevelopmentFile(file, { dsRoot }) {
268
277
  if (!isInside(dsRoot, file)) return isTestFile(file) || adsFileRole(file) !== null;
269
278
  const relative = path.relative(dsRoot, file).replaceAll("\\", "/");
270
279
  return adsFileRole(file) !== null || isTestFile(file) || isScenarioFile(file) || isFixtureFile(file) || isBehaviorFile(file)
271
- || /^(?:showcase|composition|review)\//.test(relative)
280
+ || /^(?:showcase|composition|review|brand)\//.test(relative)
272
281
  || /(?:^|\/)(?:scenario|fixtures)(?:\/|$)/.test(relative)
273
282
  || /\.scenario(?:-adapter)?\.[cm]?[jt]sx?$/.test(relative);
274
283
  }
@@ -0,0 +1,48 @@
1
+ import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { supportedFrameworks } from "./config.mjs";
5
+ import { initProject } from "./init.mjs";
6
+
7
+ // The starters ship in this package: the React starter, and per framework the files that
8
+ // replace it. A created project therefore always matches the tool that checks it.
9
+ const starters = fileURLToPath(new URL("./starters/", import.meta.url));
10
+
11
+ /** An npm package name from a folder name. */
12
+ function packageName(value) {
13
+ const name = value.toLowerCase().replace(/[^a-z0-9._~-]+/g, "-").replace(/^[._-]+|[-.]+$/g, "");
14
+ return name || "design-system";
15
+ }
16
+
17
+ /** Creates a new design-system project in `directory` from this version's starter, then
18
+ * initializes ADS in it. The directory must be missing or empty. */
19
+ export function createProject(directory, { framework, packageManager = "npm", name, toolPackage } = {}) {
20
+ if (!supportedFrameworks.includes(framework)) throw new Error("Specify --framework react or --framework preact.");
21
+ if (!["npm", "bun"].includes(packageManager)) throw new Error("packageManager must be npm or bun.");
22
+ if (name !== undefined && (typeof name !== "string" || !name.trim())) throw new Error("Specify a package name after --name.");
23
+ const root = path.resolve(directory);
24
+ const stat = lstatSync(root, { throwIfNoEntry: false });
25
+ if (stat && (!stat.isDirectory() || stat.isSymbolicLink())) throw new Error(`${root} exists and is not a folder.`);
26
+ if (stat && readdirSync(root).length) throw new Error(`${root} is not empty. Create a project in a new or empty folder; run ads init inside an existing app.`);
27
+ mkdirSync(root, { recursive: true });
28
+ try {
29
+ cpSync(path.join(starters, "react"), root, { recursive: true });
30
+ // npm drops .gitignore files from packages, so the starter carries a template.
31
+ if (existsSync(path.join(root, "gitignore.template"))) renameSync(path.join(root, "gitignore.template"), path.join(root, ".gitignore"));
32
+ if (framework !== "react") cpSync(path.join(starters, framework), root, { recursive: true });
33
+ const packageFile = path.join(root, "package.json");
34
+ const pkg = JSON.parse(readFileSync(packageFile, "utf8"));
35
+ pkg.name = name?.trim() ?? packageName(path.basename(root));
36
+ // The starter's lockfile is React's npm lock; other frameworks and Bun create their own.
37
+ if (framework !== "react" || packageManager === "bun") rmSync(path.join(root, "package-lock.json"), { force: true });
38
+ if (packageManager === "bun") for (const [script, command] of Object.entries(pkg.scripts ?? {})) pkg.scripts[script] = command.replaceAll("npm run ", "bun run ");
39
+ writeFileSync(packageFile, `${JSON.stringify(pkg, null, 2)}\n`);
40
+ const initialized = initProject(root, { framework, packageManager, toolPackage });
41
+ return { ...initialized, created: true, name: pkg.name };
42
+ } catch (error) {
43
+ // A failed creation leaves the folder as it was found.
44
+ if (!stat) rmSync(root, { recursive: true, force: true });
45
+ else for (const entry of readdirSync(root)) rmSync(path.join(root, entry), { recursive: true, force: true });
46
+ throw error;
47
+ }
48
+ }
@@ -0,0 +1,28 @@
1
+ /** Pixel size of a PNG, JPEG or WebP from its header, without decoding; null for other data. */
2
+ export function imageSize(bytes) {
3
+ if (bytes.length >= 24 && bytes.readUInt32BE(0) === 0x89504e47 && bytes.toString("ascii", 12, 16) === "IHDR") {
4
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
5
+ }
6
+ if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {
7
+ // Walk the JPEG segments to the first start-of-frame marker.
8
+ for (let offset = 2; offset + 9 < bytes.length;) {
9
+ if (bytes[offset] !== 0xff) return null;
10
+ const marker = bytes[offset + 1];
11
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
12
+ return { width: bytes.readUInt16BE(offset + 7), height: bytes.readUInt16BE(offset + 5) };
13
+ }
14
+ offset += 2 + bytes.readUInt16BE(offset + 2);
15
+ }
16
+ return null;
17
+ }
18
+ if (bytes.length >= 30 && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP") {
19
+ const chunk = bytes.toString("ascii", 12, 16);
20
+ if (chunk === "VP8 ") return { width: bytes.readUInt16LE(26) & 0x3fff, height: bytes.readUInt16LE(28) & 0x3fff };
21
+ if (chunk === "VP8L") {
22
+ const bits = bytes.readUInt32LE(21);
23
+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
24
+ }
25
+ if (chunk === "VP8X") return { width: 1 + bytes.readUIntLE(24, 3), height: 1 + bytes.readUIntLE(27, 3) };
26
+ }
27
+ return null;
28
+ }
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  export { initProject } from "./init.mjs";
2
+ export { createProject } from "./create.mjs";
2
3
  export { checkProject } from "./check.mjs";
3
4
  export { inspectTokens, tokenContract } from "./tokens.mjs";
4
5
  export { inspectTokenOrigins } from "./token-origins.mjs";
package/dist/init.mjs CHANGED
@@ -7,10 +7,10 @@ import { foundationFiles } from "./token-policy.mjs";
7
7
  import { assertFrameworkCompiler } from "./ui-framework.mjs";
8
8
 
9
9
  const tool = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
10
- const starter = fileURLToPath(new URL("./bootstrap-ds/", import.meta.url));
10
+ const starter = fileURLToPath(new URL("./starters/react/", import.meta.url));
11
11
  /** A framework's starter file: Preact's overlay replaces the React starter's where they differ. */
12
12
  const starterFile = (framework, relative) => {
13
- const overlay = fileURLToPath(new URL(`./bootstrap-ds-${framework}/${relative}`, import.meta.url));
13
+ const overlay = fileURLToPath(new URL(`./starters/${framework}/${relative}`, import.meta.url));
14
14
  return framework !== "react" && existsSync(overlay) ? overlay : path.join(starter, relative);
15
15
  };
16
16
 
@@ -156,9 +156,8 @@ export function initProject(directory = process.cwd(), { toolPackage, packageMan
156
156
  return file;
157
157
  });
158
158
  if (!existingTokens.length) {
159
- // The starter's token groups, each a scenario with its fixture. Its Brand preview needs
160
- // the starter's artwork and review renderer, which an existing app brings itself.
161
- for (const name of readdirSync(path.join(starter, "design-system/tokens")).filter(name => /\.ads\.(?:scenario\.tsx|fixture\.ts)$/.test(name) && !name.startsWith("Brand.")).sort()) {
159
+ // The starter's token groups, each a scenario with its fixture.
160
+ for (const name of readdirSync(path.join(starter, "design-system/tokens")).filter(name => /\.ads\.(?:scenario\.tsx|fixture\.ts)$/.test(name)).sort()) {
162
161
  const content = readFileSync(path.join(starter, "design-system/tokens", name), "utf8").replaceAll('"@ds/review"', JSON.stringify(`${config.publicAlias}/review`)).replaceAll('"@ds"', JSON.stringify(config.publicAlias));
163
162
  addMissing(path.join(tokenRoot, name), content);
164
163
  }
@@ -105,7 +105,7 @@ Boolean requesting whether a visible border and background is provided by the ho
105
105
  - "app": Tool callable by the app from this server only`),csp:Oc().optional(),permissions:Oc().optional()}),Rz=l({mimeTypes:h(s()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),xz=l({method:u("ui/download-file"),params:l({contents:h(v([Zt,Dt])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),Pz=l({method:u("ui/message"),params:l({role:u("user").describe('Message role, currently only "user" is supported.'),content:h(Ce).describe("Message content blocks (text, image, etc.).")})}),Tz=l({method:u("ui/notifications/sandbox-resource-ready"),params:l({html:s().describe("HTML content to load into the inner iframe."),sandbox:s().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:rl.optional().describe("CSP configuration from resource metadata."),permissions:nl.optional().describe("Sandbox permissions from resource metadata.")})}),__=l({method:u("ui/notifications/tool-result"),params:at.describe("Standard MCP tool execution result.")}),zm=l({toolInfo:l({id:Re.optional().describe("JSON-RPC id of the tools/call request."),tool:it.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:t_.optional().describe("Current color theme preference."),styles:d_.optional().describe("Style configuration for theming the app."),displayMode:Ks.optional().describe("How the UI is currently displayed."),availableDisplayModes:h(Ks).optional().describe("Display modes the host supports."),containerDimensions:v([l({height:_().describe("Fixed container height in pixels.")}),l({maxHeight:v([_(),Ic()]).optional().describe("Maximum container height in pixels.")})]).and(v([l({width:_().describe("Fixed container width in pixels.")}),l({maxWidth:v([_(),Ic()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
106
106
  container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:s().optional().describe("User's language and region preference in BCP 47 format."),timeZone:s().optional().describe("User's timezone in IANA format."),userAgent:s().optional().describe("Host application identifier."),platform:v([u("web"),u("desktop"),u("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:l({touch:z().optional().describe("Whether the device supports touch input."),hover:z().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:l({top:_().describe("Top safe area inset in pixels."),right:_().describe("Right safe area inset in pixels."),bottom:_().describe("Bottom safe area inset in pixels."),left:_().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),y_=l({method:u("ui/notifications/host-context-changed"),params:zm.describe("Partial context update containing only changed fields.")}),Ez=l({method:u("ui/update-model-context"),params:l({content:h(Ce).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:b(s(),P().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),kz=l({method:u("ui/initialize"),params:l({appInfo:ke.describe("App identification (name and version)."),appCapabilities:f_.describe("Features and capabilities this app provides."),protocolVersion:s().describe("Protocol version this app supports.")})}),b_=l({protocolVersion:s().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:ke.describe("Host application identification and version."),hostCapabilities:m_.describe("Features and capabilities provided by the host."),hostContext:zm.describe("Rich context about the host environment.")}).passthrough(),v_={target:"draft-2020-12"};async function Sm(e,t){let o=e["~standard"];if(o.jsonSchema)return o.jsonSchema[t](v_);throw Error(`Schema (vendor: ${o.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function _m(e,t,o=""){let r=await e["~standard"].validate(t);if(r.issues){let n=r.issues.map((i)=>{let a=i.path?.map((c)=>typeof c==="object"?c.key:c).join(".");return a?`${a}: ${i.message}`:i.message}).join("; ");throw Error(o+n)}return r.value}function z_(e,t){let o={...e,...t};if(t.experimental!==void 0)o.experimental={...e.experimental,...t.experimental};if(t.tools!==void 0)o.tools={...e.tools,...t.tools};return o}class va extends ol{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new ym;_methods=new bm;setRequestHandler=(...e)=>{let[t,...o]=fm("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...o)};setNotificationHandler=(...e)=>{let[t,...o]=fm("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...o)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:a_,toolinputpartial:c_,toolresult:__,toolcancelled:l_,hostcontextchanged:y_};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(e){if(!va.ONE_SHOT_EVENTS.has(e)||this._everHadListener.has(e))return;if(this._everHadListener.add(e),!this._initializedSent)return;let t=`[ext-apps] "${String(e)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(t);console.warn(t)}setEventHandler(e,t){if(t)this._assertHandlerTiming(e);this._ensureEventSlot(e),this._events.setHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>{let r=o;if(e==="hostcontextchanged")this._hostContext={...this._hostContext,...r};this._events.dispatch(e,r)}),this._registeredEvents.add(e)}getEventHandler(e){return this._events.getHandler(e)}warnIfRequestHandlerReplaced(e,t,o){if(t&&o)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t={},o={autoResize:!0}){super(o);if(this._appInfo=e,this._appCapabilities=t,this.options=o,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!o.allowUnsafeEval)le({jitless:!0});this.replaceRequestHandler("ping",(r)=>(console.log("Received ping:",r.params),{})),this.setEventHandler("hostcontextchanged",void 0)}buildContext(e){return e}registerAppCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=z_(this._appCapabilities,e)}registerTool(e,t,o){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,n=()=>{if(r._initializedSent&&r._appCapabilities.tools?.listChanged)r.sendToolListChanged()},i=t.inputSchema!==void 0,a={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,n()},disable(){this.enabled=!1,n()},update(c){Object.assign(this,c),n()},remove(){if(r._registeredTools[e]!==a)return;delete r._registeredTools[e],n()},handler:async(c,d)=>{if(!a.enabled)throw Error(`Tool ${e} is disabled`);let p;if(i){let m=a.inputSchema,f=m?await _m(m,c??{},`Invalid input for tool ${e}: `):c??{};p=await o(f,d)}else p=await o(d);if(a.outputSchema&&!p.isError)p.structuredContent=await _m(a.outputSchema,p.structuredContent,`Invalid output for tool ${e}: `);return p}};if(this._registeredTools[e]=a,!this._appCapabilities.tools&&!this.transport)this.registerAppCapabilities({tools:{listChanged:!0}});return this.ensureToolHandlersInitialized(),n(),a}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){if(this._toolHandlersInitialized)return;this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let o=this._registeredTools[e.name];if(!o)throw Error(`Tool ${e.name} not found`);return o.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([o,r])=>r.enabled).map(async([o,r])=>{let n={name:o,title:r.title,description:r.description,inputSchema:r.inputSchema?await Sm(r.inputSchema,"input"):{type:"object",properties:{}}};if(r.outputSchema)n.outputSchema=await Sm(r.outputSchema,"output");if(r.annotations)n.annotations=r.annotations;if(r._meta)n._meta=r._meta;return n}))})}async sendToolListChanged(e={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(e){this.setEventHandler("toolinput",e)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(e){this.setEventHandler("toolinputpartial",e)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(e){this.setEventHandler("toolresult",e)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(e){this.setEventHandler("toolcancelled",e)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(e){this.setEventHandler("hostcontextchanged",e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,e),this._onteardown=e,this.replaceRequestHandler("ui/resource-teardown",{params:p_.shape.params,result:h_},(t,o)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(t,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",(t,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,o)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler("tools/list",(t,o)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(t.params,o)})}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;default:return}}assertNotificationCapability(e){}async callServerTool(e,t){if(this._assertInitialized("callServerTool"),typeof e==="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:e},{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:e},t)}async listServerResources(e,t){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:e},t)}async createSamplingMessage(e,t){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:e},t)}sendMessage(e,t){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:e},i_,t)}sendLog(e){return this.notification({method:"notifications/message",params:e})}updateModelContext(e,t){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:e},st,t)}openLink(e,t){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:e},n_,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:e},s_,t)}requestTeardown(e={}){return this.notification({method:"ui/notifications/request-teardown",params:e})}requestDisplayMode(e,t){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:e},g_,t)}sendSizeChanged(e){return this.notification({method:"ui/notifications/size-changed",params:e})}setupSizeChangedNotifications(){let e=!1,t=0,o=0,r=()=>{if(e)return;e=!0,requestAnimationFrame(()=>{e=!1;let i=document.documentElement,a=i.style.height;i.style.height="max-content";let c=Math.ceil(i.getBoundingClientRect().height);i.style.height=a;let d=Math.ceil(window.innerWidth);if(d!==t||c!==o)t=d,o=c,this.sendSizeChanged({width:d,height:c})})};r();let n=new ResizeObserver(r);return n.observe(document.documentElement),n.observe(document.body),()=>n.disconnect()}async connect(e=new vm(window.parent,window.parent),t){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect(e);let o=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:XS}},b_,t);if(o===void 0)throw Error(`Server sent invalid initialize result: ${o}`);if(this._hostCapabilities=o.hostCapabilities,this._hostInfo=o.hostInfo,this._hostContext=o.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize)this.setupSizeChangedNotifications()}catch(o){throw this.close(),o}}}function wm(e,t){let o=[],r=new Set;function n(i){if(r.has(i))return;r.add(i);let a=e.get(i);if(!a)throw Error(`Missing preview dependency metadata: ${i}`);for(let c of[...a.imports,...a.styles,...a.references])n(c);o.push(i)}return n(t),o}function Rm(e,t){if(!e||e.revision===t.revision)return[];let o=(r,n)=>{let i=new Map(Object.entries(r.assets));return JSON.stringify(wm(i,n.module).map((a)=>[a,i.get(a)]))};return t.scenarios.filter((r)=>{let n=e.scenarios.find((i)=>i.id===r.id);return!n||o(e,n)!==o(t,r)}).map((r)=>r.id)}class sl{constructor(e){this.read=e,this.records=new Map,this.bytes=new Map,this.urls=new Map,this.styles=new Map,this.styleReady=new Map,this.revisions=new Set,this.loadedModules=new Set,this.importing=Promise.resolve(),this.generation=0,this.prefetchGeneration=0,this.closed=!1,globalThis.__dsPreviewImport=(t)=>this.importModule(t)}register(e){if(e.schemaVersion!==1||!Array.isArray(e.scenarios)||!e.assets||typeof e.revision!=="string")throw Error("Unsupported preview manifest. Rebuild previews with the installed ADS version.");for(let[t,o]of Object.entries(e.assets)){if(!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(t)||!/^sha256:[a-f0-9]{64}$/.test(o.digest)||!["imports","dynamicImports","styles","references"].every((r)=>Array.isArray(o[r])&&o[r].every((n)=>Object.hasOwn(e.assets,n))))throw Error("Invalid preview dependency graph.");if(this.records.has(t)&&this.records.get(t).digest!==o.digest)throw Object.assign(Error("An immutable preview resource changed its content. Rebuild previews with the current ADS version."),{code:"ADS_RESOURCE_IDENTITY",category:"build",resourceUri:t})}for(let[t,o]of Object.entries(e.assets))this.records.set(t,o)}async resource(e){if(!this.bytes.has(e)){let t=(async()=>{let o=this.records.get(e);if(!o)throw Error(`Unknown preview dependency: ${e}`);let r;try{r=await this.read(e)}catch(d){throw Object.assign(Error(`Preview resource read failed for ${e}: ${d.message}`,{cause:d}),{code:"ADS_RESOURCE_READ",category:"transport",resourceUri:e})}if(this.closed)throw Error("The preview App was closed.");let n=r.contents.find((d)=>d.uri===e);if(!n)throw Object.assign(Error(`Missing preview dependency: ${e}`),{code:"ADS_RESOURCE_CONTENT",category:"build",resourceUri:e});let i=typeof n.text==="string"?new TextEncoder().encode(n.text):Uint8Array.from(atob(n.blob),(d)=>d.charCodeAt(0)),a=await crypto.subtle.digest("SHA-256",i),c="sha256:"+[...new Uint8Array(a)].map((d)=>d.toString(16).padStart(2,"0")).join("");if(i.length!==o.size||c!==o.digest)throw Object.assign(Error("Preview resource integrity check failed. Rebuild and reopen the preview."),{code:"ADS_RESOURCE_INTEGRITY",category:"build",resourceUri:e});return i})();this.bytes.set(e,t),t.catch(()=>this.bytes.delete(e))}return this.bytes.get(e)}closure(e){return wm(this.records,e)}async prefetch(e,t){if(this.closed)return;this.register(e);let o=++this.prefetchGeneration,r=new Set,n=[],i=0;for(let p of t){let m=e.scenarios.find((S)=>S.id===p);if(!m)continue;let f=this.closure(m.module).filter((S)=>!this.bytes.has(S)&&!r.has(S)),y=f.reduce((S,w)=>S+this.records.get(w).size,0);if(i+y>16777216||r.size+f.length>256)continue;i+=y,n.push(p);for(let S of f)r.add(S)}let a=[...r],c=0,d=async()=>{while(!this.closed&&o===this.prefetchGeneration&&c<a.length)await this.resource(a[c++])};return await Promise.all(Array.from({length:Math.min(3,a.length)},d)),{scenarios:n,resources:a.length}}async materialize(e){let t=this.closure(e);await Promise.all(t.map((r)=>this.resource(r)));let o={};for(let r of t){if(this.closed)throw Error("The preview App was closed.");if(this.urls.has(r))continue;let n=this.records.get(r),i=await this.resource(r);if(n.kind==="module"||n.mimeType==="text/css"||n.mimeType==="text/javascript"){let c=new TextDecoder().decode(i);for(let d of n.references){let p=this.urls.get(d);if(!p)throw Error("Unsupported cyclic asset reference.");c=c.replaceAll(d,p)}i=c}let a=URL.createObjectURL(new Blob([i],{type:n.mimeType}));if(this.urls.set(r,a),n.kind==="module")o[r]=a}if(Object.keys(o).length){let r=document.createElement("script");r.type="importmap",r.textContent=JSON.stringify({imports:o}),document.head.append(r)}return t}async importModule(e){let t=this.importing.then(()=>this.materialize(e));this.importing=t.catch(()=>{});let o=await t;await this.attachStyles(o);try{let r=await import(e);return this.loadedModules.add(e),r}catch(r){throw Error(`Preview module import failed for ${e}: ${r.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`,{cause:r})}}async attachStyles(e){for(let t of e){if(this.records.get(t).mimeType!=="text/css")continue;if(this.styles.has(t)){await this.styleReady.get(t);continue}let r=document.createElement("link");r.rel="stylesheet",r.href=this.urls.get(t),this.styles.set(t,r);let n=new Promise((i,a)=>{r.onload=i,r.onerror=()=>a(Error("The host CSP blocked a preview stylesheet."))});this.styleReady.set(t,n),document.head.append(r);try{await n}catch(i){throw r.remove(),this.styles.delete(t),this.styleReady.delete(t),i}}}async refreshStyles(e,t){let o=[e],r=new Set,n=new Set;for(let i=0;i<o.length;i++){let a=o[i];if(r.has(a))continue;r.add(a);for(let c of await this.materialize(a)){n.add(c);for(let d of this.records.get(c).dynamicImports)if(this.loadedModules.has(d))o.push(d)}}if(await this.attachStyles([...n]),t!==this.generation||this.closed)return!1;for(let[i,a]of this.styles)if(!n.has(i))a.remove(),this.styles.delete(i),this.styleReady.delete(i);for(let i of n)if(this.styles.has(i))document.head.append(this.styles.get(i));return!0}async mount(e,t,o){let r=++this.generation;this.register(e);let n=e.scenarios.find((d)=>d.id===t);if(!n)throw Error("The selected scenario is no longer registered.");let i=JSON.stringify(this.closure(n.module).map((d)=>[d,this.records.get(d)]));if(this.mounted?.id===t&&this.mounted.container===o&&this.mounted.signature===i)return this.refreshStyles(n.module,r);if(this.revisions.add(n.module),this.revisions.size>20)throw Object.assign(Error("Reopen the preview to release modules retained across 20 build revisions."),{code:"ADS_PREVIEW_REOPEN"});let a=await this.importModule(n.module);if(r!==this.generation)return!1;let c=this.unmount;if(this.unmount=void 0,this.mounted=void 0,await c?.(),r!==this.generation||this.closed)return!1;if(o.replaceChildren(),!await this.refreshStyles(n.module,r))return!1;if(typeof a.mount!=="function")throw Error("The compiled scenario has no mount adapter.");if(this.unmount=a.mount(o),typeof this.unmount!=="function")throw Error("The scenario mount adapter must return an unmount callback.");return this.mounted={id:t,container:o,signature:i},!0}async dispose(){if(this.closed)return;this.closed=!0,++this.generation,++this.prefetchGeneration,await this.unmount?.(),this.mounted=void 0;for(let e of this.styles.values())e.remove();for(let e of this.urls.values())URL.revokeObjectURL(e);this.styles.clear(),this.styleReady.clear(),this.urls.clear(),this.bytes.clear(),this.records.clear(),this.revisions.clear(),this.loadedModules.clear(),delete globalThis.__dsPreviewImport}}function xm(e){return Array.isArray(e)&&e.length>0&&e.every((t)=>t&&typeof t==="object"&&typeof t.token==="string"&&/^--[\w-]+$/.test(t.token)&&typeof t.property==="string"&&/^-?[a-z][a-z0-9-]*$/.test(t.property)&&typeof t.probe==="string"&&t.probe.trim().length>0)&&new Set(e.map((t)=>`${t.token}:${t.property}`)).size===e.length}function Pm(e,t){let o=t.getComputedStyle(e),r=e.getBoundingClientRect();if(o.display==="none"||o.visibility!=="visible"||!e.getClientRects().length||!(r.width||r.height))return!1;for(let n=e;n;n=n.parentElement)if(Number(t.getComputedStyle(n).opacity)===0)return!1;return!0}function Tm(e,t){if(!xm(t))return{ok:!1,diagnostics:["Token preview needs explicit { token, property, probe } samples from the project fixture. Rebuild with the current compiler."]};let o=e.ownerDocument,{defaultView:r,documentElement:n}=o,i=[],a=[],c=[...e.querySelectorAll("[data-ads-token], [data-ads-property]")],d=new Set(t.map((p)=>`${p.token}:${p.property}`));for(let p of c)if(!d.has(`${p.dataset.adsToken}:${p.dataset.adsProperty}`))i.push(`Undeclared rendered token sample ${p.dataset.adsToken}:${p.dataset.adsProperty}.`);for(let p of t){if(!r.CSS.supports(p.property,p.probe)){i.push(`${p.token}: the fixture probe is invalid for ${p.property}.`);continue}let m=r.getComputedStyle(n).getPropertyValue(p.token).trim();if(!m||!r.CSS.supports(p.property,m)){i.push(`${p.token}: its current value is invalid for the fixture's ${p.property} binding.`);continue}let f=c.filter((S)=>S.dataset.adsToken===p.token&&S.dataset.adsProperty===p.property);if(!f.length){i.push(`${p.token} needs a rendered ${p.property} sample, not only a name/value label.`);continue}let y=!1;for(let S of f){let w=[];for(let C=S.parentElement;C&&C!==e;C=C.parentElement)if(C.tagName==="DETAILS"&&!C.open)C.open=!0,w.push(C);let x=n.getAttribute("style"),R=S.getAttribute("style");try{if(!/^(?:-[a-z]+-)?transition(?:-|$)/.test(p.property))S.style.setProperty("transition","none","important");let C=r.getComputedStyle(S).getPropertyValue(p.property),N=Pm(S,r);n.style.setProperty(p.token,p.probe,"important");let O=r.getComputedStyle(S).getPropertyValue(p.property);y=Boolean(O&&O!==C&&(N||Pm(S,r)))}finally{if(x===null)n.removeAttribute("style");else n.setAttribute("style",x);if(R===null)S.removeAttribute("style");else S.setAttribute("style",R);for(let C of w)C.open=!1}if(y)break}if(y)a.push(p);else i.push(`${p.token} has no visible ${p.property} sample that responds to its value. Hardcoded copies do not satisfy coverage.`)}return{ok:!i.length,verified:a,diagnostics:i}}function Em({container:e=document.getElementById("root"),bindings:t=[],auditResources:o=!1}={}){let r=[],n=[],i=[];if(!e||!Array.isArray(t)||t.length>100)return{ok:!1,diagnostics:["Invalid bounded paint-audit descriptor."],verified:n};let a=e.ownerDocument,c=a.defaultView,d=["color","fill","stroke","stop-color","background-color","border-top-color","border-right-color","border-bottom-color","border-left-color"];function p(f,y,S,w=new Set){if(f=f.trim(),["none","currentColor"].includes(f))return!0;let x=/^var\(\s*(--[\w-]+)\s*\)$/.exec(f);if(x){let N=x[1];if(!S.tokens.includes(N)||w.has(N))return!1;let O=c.getComputedStyle(y).getPropertyValue(N).trim();return!!O&&c.CSS.supports("color",O)}let R=/^light-dark\(\s*(var\(\s*--[\w-]+\s*\)|currentColor)\s*,\s*(var\(\s*--[\w-]+\s*\)|currentColor)\s*\)$/.exec(f);if(R)return c.CSS.supports("color",f)&&p(R[1],y,S,w)&&p(R[2],y,S,w);let C=/^url\(\s*(["']?)#([^\s"'()#\\\p{Cc}]+)\1\s*\)$/u.exec(f);if(C&&c.CSS.supports("fill",f)){let N=[...a.querySelectorAll("[id]")].filter((O)=>O.id===C[2]);return N.length===1&&["linearGradient","radialGradient","pattern"].includes(N[0].localName)&&y.contains(N[0])}return!1}for(let f of t){if(!f||typeof f.scope!=="string"||!Array.isArray(f.tokens)||typeof f.prefix!=="string"||typeof f.suffix!=="string"){r.push("Invalid paint binding metadata; rebuild previews.");continue}let y;try{y=[...e.querySelectorAll(f.scope)]}catch{r.push(`${f.owner}: invalid binding scope.`);continue}if(y.length>20)i.push(`${f.owner}: only the first 20 instances were audited; use a focused scenario for complete evidence.`);for(let S of y.slice(0,20)){let w=[S,...S.querySelectorAll("*")];if(w.length>1000){i.push(`${f.owner}: instance exceeds 1000 elements; paint effects are not established.`);continue}let x=[...S.style].filter((R)=>R.startsWith(f.prefix)&&R.endsWith(f.suffix));if(x.length>100)i.push(`${f.owner}: only the first 100 binding keys were audited.`);for(let R of x.slice(0,100)){let C=S.style.getPropertyValue(R).trim(),N=R.slice(f.prefix.length,f.suffix?-f.suffix.length:void 0);if(!/^[A-Za-z0-9_-]+$/.test(N)||!p(C,S,f)){r.push(`${f.owner}: invalid or inaccessible paint ${R}: ${C}. Use an accessible token, instance-local SVG paint server, none or currentColor.`);continue}let O=S.getAttribute("style"),q=w.map((L)=>L.getAttribute("style"));try{for(let V of w)V.style.setProperty("transition","none","important");let L=w.map((V)=>d.map((ae)=>c.getComputedStyle(V).getPropertyValue(ae)));S.style.setProperty(R,"rgb(17, 103, 211)","important");let j=w.some((V,ae)=>d.some((Y,ge)=>c.getComputedStyle(V).getPropertyValue(Y)!==L[ae][ge]));if(!j)S.style.setProperty(R,"rgb(211, 67, 23)","important"),j=w.some((V,ae)=>d.some((Y,ge)=>c.getComputedStyle(V).getPropertyValue(Y)!==L[ae][ge]));if(!j)i.push(`${f.owner}: ${R} has no observed paint effect in its current instance. A written variable alone is not rendering evidence; check the relevant selected/visible consumer.`);else n.push({owner:f.owner,binding:f.name,variable:R})}finally{if(w.forEach((L,j)=>{if(q[j]===null)L.removeAttribute("style");else L.setAttribute("style",q[j])}),O===null)S.removeAttribute("style");else S.setAttribute("style",O)}}for(let R of w)for(let C of["fill","stroke","stop-color"]){let N=R.getAttribute(C);if(!N)continue;let O=/^var\(\s*(--[\w-]+)\s*\)$/.exec(N);if(O&&O[1].startsWith(f.prefix)&&O[1].endsWith(f.suffix)&&!x.includes(O[1]))r.push(`${f.owner}: ${O[1]} is consumed without a value in this instance.`);if(N.startsWith("url(")&&!p(N,S,f))r.push(`${f.owner}: missing, duplicated or out-of-instance local paint resource ${N}.`)}}}let m=o?[...e.querySelectorAll("[fill], [stroke], [style]")]:[];if(m.length>1000)i.push("Only the first 1000 potential SVG paint consumers were audited.");for(let f of m.slice(0,1000))for(let y of["fill","stroke"]){let S=f.getAttribute(y)??f.style.getPropertyValue(y);if(!S?.startsWith("url("))continue;let w=/^url\(\s*(["']?)#([^\s"'()#\\\p{Cc}]+)\1\s*\)$/u.exec(S)?.[2],x=w?[...a.querySelectorAll("[id]")].filter((C)=>C.id===w):[],R=f.ownerSVGElement??(f.localName==="svg"?f:null);if(x.length!==1||!R?.contains(x[0])||!["linearGradient","radialGradient","pattern"].includes(x[0]?.localName))r.push(`Invalid, missing, duplicated or nonlocal SVG paint resource ${S}. Keep IDs isolated per rendered instance.`)}return{ok:!r.length,complete:!i.length,verified:n,diagnostics:r.slice(0,40),limits:i.slice(0,20),scope:"observed App instances and current input; repeat after updates"}}var ye=new va({name:"ADS resource preview",version:"1.0.0"},{},{autoResize:!0}),Bt=document.getElementById("root"),il=document.getElementById("ads-preview-status"),ll,pl=async(e)=>{if(!ye.getHostCapabilities()?.serverResources)throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");try{return await ye.readServerResource({uri:ll?ll+encodeURIComponent(e):e},{timeout:15000})}catch(t){if(t.code===-32601||t.message==="Method not found")throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");throw t}},ei=new sl(pl),He,$m,Gt,ul,hl,al=!1,lt=0,Ys={},_e="",Qs=!1,cl,km,Cm=new Set;function Im(e){if(ye.getHostVersion()?.name!=="ADS showcase")return;let t=km;if(km=e,!t)return;let o=Rm(t,e).filter((r)=>r!==He&&Cm.has(r));if(!o.length)return;ei.prefetch(e,o).then((r)=>ut("prefetched",{revision:e.revision,...r})).catch((r)=>console.warn("ADS preview prefetch",r.message))}function Oe(e,t=!1){il.textContent=e,il.hidden=!e||ye.getHostVersion()?.name==="ADS showcase",il.setAttribute("role",t?"alert":"status")}async function ut(e,t={}){try{if(ye.getHostCapabilities()?.logging)await ye.sendLog({level:e==="error"?"error":"info",logger:"ads-preview",data:{state:e,id:He,...t}})}catch{}}function Om(e){if(Ys={...Ys,...e,styles:{...Ys.styles,...e.styles}},["light","dark"].includes(Ys.theme))document.documentElement.dataset.theme=Ys.theme}async function dl(e="ads://preview/manifest"){let t;try{t=await pl(e)}catch(o){throw Object.assign(Error(o.message,{cause:o}),{code:"ADS_MANIFEST_READ",category:"transport"})}return JSON.parse(t.contents.find((o)=>typeof o.text==="string").text)}async function Xs(e,t,o=!1,r="",n=!1){let i=o||n;if(!r&&e===He&&t&&t===Gt&&i===Qs){Oe(_e||(i?"Checking changes…":""),Boolean(_e)),await ut(_e?"error":i?"checking":"ready",_e?{message:_e}:{revision:Gt});return}let a=++lt;++ei.generation,He=e,Cm.add(e),document.documentElement.dataset.adsScenario=e,document.documentElement.dataset.adsPreviewState="loading";for(let c of["adsPreviewErrorCategory","adsPreviewErrorCode","adsPreviewResourceUri"])delete document.documentElement.dataset[c];_e="",Oe(""),await ut(r?"reverting":"loading");try{let c=await dl(o?"ads://preview/live":"ads://preview/manifest");if(t&&c.revision!==t){if(a===lt)Oe("Updating preview…"),await ut("loading",{code:"ADS_PREVIEW_CHANGED"});return}if(a!==lt)return;if(!await ei.mount(c,e,Bt)||a!==lt)return;if(Gt=c.revision,ul=c.session,Qs=i,await new Promise((m)=>requestAnimationFrame(()=>requestAnimationFrame(m))),await document.fonts.ready,a!==lt)return;let p=c.scenarios.find((m)=>m.id===e);if(Bt.dataset.adsPaintBindings=JSON.stringify(p?.paintBindings??[]),Bt.dataset.adsPaintAudit=String(Boolean(p?.paintAudit)),Bt.dataset.adsPaintAuditComplete="not-requested",p?.paintBindings?.length||p?.paintAudit){let m=Em({container:Bt,bindings:p.paintBindings??[],auditResources:Boolean(p.paintAudit)});if(!m.ok)throw Object.assign(Error(`Paint binding verification failed:
107
107
  ${m.diagnostics.join(`
108
- `)}`),{code:"ADS_PAINT_BINDING",category:"assertion"});if(Bt.dataset.adsPaintAuditComplete=String(m.complete),!m.complete)await ut("audit-limited",{limits:m.limits})}if(p?.kind==="tokens"&&!p.brand){let m=Tm(Bt,p.samples);if(!m.ok)throw _e=`Token preview verification failed:
108
+ `)}`),{code:"ADS_PAINT_BINDING",category:"assertion"});if(Bt.dataset.adsPaintAuditComplete=String(m.complete),!m.complete)await ut("audit-limited",{limits:m.limits})}if(p?.kind==="tokens"){let m=Tm(Bt,p.samples);if(!m.ok)throw _e=`Token preview verification failed:
109
109
  ${m.diagnostics.slice(0,20).join(`
110
110
  `)}`,Object.assign(Error(_e),{code:"ADS_TOKEN_SAMPLE",category:"assertion"})}if(a===lt){if(document.documentElement.dataset.adsPreviewRevision=Gt,document.documentElement.dataset.adsPreviewState=r?"error":i?"checking":"ready",Oe(r||(i?"Checking changes…":""),Boolean(r)),await ut(r?"error":i?"checking":"ready",{revision:Gt,selectionRevision:$m,...r?{message:r}:{}}),!i&&!r)Im(c)}}catch(c){if(a===lt){if(document.documentElement.dataset.adsPreviewState="error",document.documentElement.dataset.adsPreviewErrorCategory=c.category??"runner",document.documentElement.dataset.adsPreviewErrorCode=c.code??"ADS_PREVIEW_STARTUP",c.resourceUri)document.documentElement.dataset.adsPreviewResourceUri=c.resourceUri;Oe(c.message,!0),await ut("error",{message:c.message,...c.code?{code:c.code}:{},...c.category?{category:c.category}:{},...c.resourceUri?{resourceUri:c.resourceUri}:{}})}}}async function w_(){if(!He||al||document.visibilityState==="hidden")return;al=!0;try{let e=JSON.parse((await pl("ads://project/build")).contents.find((o)=>typeof o.text==="string").text);cl=void 0;let t=e.previews.find((o)=>o.id===He);if(t?.live&&!t.current)if(t.live.revision!==Gt||e.session!==ul||!Qs)await Xs(He,t.live.revision,!0);else Oe(_e||"Checking changes…",Boolean(_e));else if(!t||!t.current){let o=t?.diagnostics?.[0]?.message;if(o&&Qs){let r=await dl();await Xs(He,r.revision,!1,`Build failed. Showing the previous preview.
111
111
  ${o}`)}Oe(o?`Build failed. Showing the previous preview.