@astrale-os/cli 1.0.0-beta.2 → 1.0.0-beta.21

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 (283) hide show
  1. package/README.md +16 -1
  2. package/dist/astrale.js +51279 -58057
  3. package/dist/public/connect-core.js +2085 -30702
  4. package/dist/public/keys/index.js +884 -29476
  5. package/dist/public/paths/index.js +13101 -41452
  6. package/dist/types/admin/contract.d.ts +26 -0
  7. package/dist/types/admin/instance/client.d.ts +20 -0
  8. package/dist/types/admin/instance/index.d.ts +2 -0
  9. package/dist/types/admin/instance/model.d.ts +6 -10
  10. package/dist/types/connection/auth.d.ts +3 -0
  11. package/dist/types/connection/call.d.ts +3 -0
  12. package/dist/types/connection/command.d.ts +27 -0
  13. package/dist/types/connection/credential.d.ts +14 -0
  14. package/dist/types/connection/errors.d.ts +1 -0
  15. package/dist/types/connection/exchange.d.ts +9 -0
  16. package/dist/types/connection/failure/classify.d.ts +2 -0
  17. package/dist/types/connection/failure/index.d.ts +5 -0
  18. package/dist/types/connection/failure/model.d.ts +25 -0
  19. package/dist/types/connection/failure/render.d.ts +3 -0
  20. package/dist/types/connection/index.d.ts +8 -0
  21. package/dist/types/connection/reasons.d.ts +37 -0
  22. package/dist/types/connection/self.d.ts +37 -0
  23. package/dist/types/connection/session.d.ts +31 -0
  24. package/dist/types/connection/target.d.ts +38 -0
  25. package/dist/types/errors.d.ts +1 -1
  26. package/dist/types/lib/admin-instance.d.ts +17 -0
  27. package/dist/types/lib/admin-target.d.ts +11 -36
  28. package/dist/types/lib/config.d.ts +7 -59
  29. package/dist/types/lib/failure-debug.d.ts +1 -0
  30. package/dist/types/lib/idp.d.ts +25 -173
  31. package/dist/types/lib/instance-target.d.ts +1 -1
  32. package/dist/types/lib/instance.d.ts +30 -88
  33. package/dist/types/lib/log.d.ts +5 -3
  34. package/dist/types/lib/output.d.ts +1 -1
  35. package/dist/types/lib/proc.d.ts +43 -0
  36. package/dist/types/lib/self.d.ts +9 -0
  37. package/dist/types/lib/update.d.ts +109 -0
  38. package/dist/types/lib/validation.d.ts +4 -1
  39. package/package.json +15 -20
  40. package/src/__tests__/fixtures/publication.ts +20 -0
  41. package/src/admin/.spec/architecture.md +12 -5
  42. package/src/admin/__tests__/fixture.ts +25 -0
  43. package/src/admin/catalog/.spec/api.d.ts +1 -3
  44. package/src/admin/catalog/.spec/architecture.md +5 -4
  45. package/src/admin/catalog/__tests__/client.test.ts +143 -69
  46. package/src/admin/catalog/client.ts +40 -54
  47. package/src/admin/catalog/model.ts +3 -4
  48. package/src/admin/contract.ts +46 -0
  49. package/src/admin/graph/.spec/api.d.ts +4 -10
  50. package/src/admin/graph/nodes.ts +1 -1
  51. package/src/admin/instance/.spec/api.d.ts +5 -9
  52. package/src/admin/instance/.spec/architecture.md +7 -7
  53. package/src/admin/instance/__tests__/client.test.ts +157 -175
  54. package/src/admin/instance/client.ts +39 -128
  55. package/src/admin/instance/index.ts +1 -2
  56. package/src/admin/instance/model.ts +12 -18
  57. package/src/commands/__tests__/admin-instance.test.ts +11 -8
  58. package/src/commands/__tests__/call-describe.test.ts +46 -33
  59. package/src/commands/__tests__/call.test.ts +34 -0
  60. package/src/commands/__tests__/domain-install-operation.test.ts +7 -22
  61. package/src/commands/__tests__/domain-install-owned.test.ts +1 -1
  62. package/src/commands/__tests__/domain-list.test.ts +5 -25
  63. package/src/commands/__tests__/install-direct.test.ts +115 -8
  64. package/src/commands/__tests__/install-identity-override.test.ts +3 -14
  65. package/src/commands/__tests__/instance-list-rows.test.ts +1 -1
  66. package/src/commands/__tests__/instance-status.test.ts +139 -0
  67. package/src/commands/__tests__/introspect-parse.test.ts +80 -1
  68. package/src/commands/__tests__/logs.test.ts +250 -2
  69. package/src/commands/__tests__/read-commands.test.ts +62 -10
  70. package/src/commands/__tests__/token-ttl.test.ts +49 -4
  71. package/src/commands/__tests__/update.test.ts +25 -3
  72. package/src/commands/__tests__/view.test.ts +49 -0
  73. package/src/commands/call-describe.ts +60 -68
  74. package/src/commands/call.ts +71 -59
  75. package/src/commands/domain/install.ts +54 -35
  76. package/src/commands/domain/list.ts +1 -1
  77. package/src/commands/domain/publish.ts +14 -11
  78. package/src/commands/domain/uninstall.ts +2 -2
  79. package/src/commands/get.ts +14 -15
  80. package/src/commands/identity/__tests__/register.test.ts +3 -3
  81. package/src/commands/identity/register.ts +5 -4
  82. package/src/commands/instance/create.ts +8 -16
  83. package/src/commands/instance/delete.ts +12 -9
  84. package/src/commands/instance/list.ts +2 -2
  85. package/src/commands/instance/status.ts +66 -20
  86. package/src/commands/instance/use.ts +16 -12
  87. package/src/commands/introspect.ts +48 -35
  88. package/src/commands/logs.ts +123 -33
  89. package/src/commands/mutate.ts +6 -5
  90. package/src/commands/query.ts +35 -32
  91. package/src/commands/token.ts +42 -27
  92. package/src/commands/ui/__tests__/commands.test.ts +152 -0
  93. package/src/commands/ui/add.ts +51 -0
  94. package/src/commands/ui/doctor.ts +21 -0
  95. package/src/commands/ui/init.ts +38 -0
  96. package/src/commands/ui/list.ts +26 -0
  97. package/src/commands/ui/preset-apply.ts +19 -0
  98. package/src/commands/ui/preset-list.ts +12 -0
  99. package/src/commands/ui/shared.ts +25 -0
  100. package/src/commands/update.ts +31 -11
  101. package/src/commands/view.ts +82 -37
  102. package/src/connection/.spec/api.d.ts +7 -8
  103. package/src/connection/.spec/architecture.md +5 -4
  104. package/src/connection/.spec/flows/session.ts +2 -2
  105. package/src/connection/.spec/laws/connection.ts +6 -2
  106. package/src/connection/.spec/layout.ts +1 -0
  107. package/src/connection/__tests__/credential.test.ts +20 -1
  108. package/src/connection/__tests__/errors.test.ts +27 -20
  109. package/src/connection/__tests__/exchange.test.ts +30 -1
  110. package/src/connection/__tests__/failure-fixtures.ts +39 -0
  111. package/src/connection/__tests__/failure-safety.test.ts +75 -0
  112. package/src/connection/__tests__/self.test.ts +31 -11
  113. package/src/connection/__tests__/session.test.ts +3 -3
  114. package/src/connection/__tests__/target.test.ts +1 -0
  115. package/src/connection/auth.ts +13 -0
  116. package/src/connection/call.ts +1 -1
  117. package/src/connection/credential.ts +2 -2
  118. package/src/connection/errors.ts +1 -355
  119. package/src/connection/exchange.ts +47 -23
  120. package/src/connection/failure/classify.ts +110 -0
  121. package/src/connection/failure/index.ts +18 -0
  122. package/src/connection/failure/model.ts +28 -0
  123. package/src/connection/failure/render.ts +116 -0
  124. package/src/connection/reasons.ts +16 -0
  125. package/src/connection/self.ts +39 -21
  126. package/src/connection/session.ts +19 -8
  127. package/src/errors.ts +3 -2
  128. package/src/graph/.spec/api.d.ts +12 -5
  129. package/src/graph/.spec/layout.ts +9 -1
  130. package/src/graph/__tests__/mutation.test.ts +2 -2
  131. package/src/graph/__tests__/query.test.ts +25 -6
  132. package/src/graph/class.ts +30 -0
  133. package/src/graph/index.ts +1 -0
  134. package/src/graph/query.ts +21 -32
  135. package/src/identity/.spec/api.d.ts +2 -2
  136. package/src/identity/__tests__/registration.test.ts +1 -1
  137. package/src/identity/registration.ts +3 -3
  138. package/src/keys/__tests__/keys.test.ts +4 -0
  139. package/src/keys/credential.ts +1 -0
  140. package/src/lib/__tests__/admin-target.test.ts +12 -0
  141. package/src/lib/__tests__/binary.test.ts +16 -1
  142. package/src/lib/__tests__/command-dx.test.ts +1 -1
  143. package/src/lib/__tests__/domain-publication.test.ts +10 -16
  144. package/src/lib/__tests__/idp.test.ts +34 -4
  145. package/src/lib/__tests__/instance-candidates.test.ts +1 -3
  146. package/src/lib/__tests__/instance-target.test.ts +7 -39
  147. package/src/lib/__tests__/log-errors.test.ts +64 -0
  148. package/src/lib/__tests__/studio-server-deps.test.ts +1 -1
  149. package/src/lib/__tests__/update.test.ts +264 -11
  150. package/src/lib/__tests__/view-assets.test.ts +25 -0
  151. package/src/lib/__tests__/view-external-open-intent.test.ts +150 -0
  152. package/src/lib/__tests__/view-external-open-origins.test.ts +27 -0
  153. package/src/lib/__tests__/view-open-intent.test.ts +0 -2
  154. package/src/lib/__tests__/view-server.test.ts +26 -3
  155. package/src/lib/__tests__/view-session.test.ts +2 -1
  156. package/src/lib/admin-instance.ts +14 -8
  157. package/src/lib/admin-target.ts +21 -2
  158. package/src/lib/binary.ts +22 -5
  159. package/src/lib/command-dx.ts +9 -9
  160. package/src/lib/domain-publication.ts +9 -7
  161. package/src/lib/failure-debug.ts +26 -0
  162. package/src/lib/idp.ts +34 -3
  163. package/src/lib/instance-candidates.ts +2 -2
  164. package/src/lib/instance-target.ts +3 -14
  165. package/src/lib/instance.ts +16 -11
  166. package/src/lib/log.ts +16 -9
  167. package/src/lib/output.ts +1 -1
  168. package/src/lib/proc.ts +7 -2
  169. package/src/lib/provision-instance.ts +34 -57
  170. package/src/lib/update.ts +298 -45
  171. package/src/lib/validation.ts +2 -2
  172. package/src/lib/view/assets.ts +11 -2
  173. package/src/lib/view/external-open-intent.ts +41 -0
  174. package/src/lib/view/external-open-origins.ts +37 -0
  175. package/src/lib/view/host-capabilities.ts +17 -0
  176. package/src/lib/view/resolve.ts +1 -1
  177. package/src/lib/view/server.ts +18 -3
  178. package/src/lib/view/session.ts +2 -0
  179. package/src/program/.spec/api.d.ts +1 -0
  180. package/src/program/__tests__/program.test.ts +163 -6
  181. package/src/program/argv.ts +14 -0
  182. package/src/program/build.ts +26 -4
  183. package/src/program/command.ts +1 -0
  184. package/src/program/index.ts +1 -0
  185. package/src/program/registry.ts +2 -1
  186. package/src/setup/__tests__/instance-step.test.ts +27 -10
  187. package/src/setup/steps/instance.ts +22 -15
  188. package/src/telemetry/__tests__/recorder.test.ts +1 -0
  189. package/src/telemetry/recorder.ts +9 -1
  190. package/src/ui/.spec/api.d.ts +14 -0
  191. package/src/ui/.spec/architecture.md +12 -0
  192. package/src/ui/.spec/laws.ts +43 -0
  193. package/src/ui/.spec/layout.ts +16 -0
  194. package/src/ui/__tests__/ui.test.ts +1292 -0
  195. package/src/ui/index.ts +13 -0
  196. package/src/ui/lock.ts +89 -0
  197. package/src/ui/model.ts +83 -0
  198. package/src/ui/operations.ts +932 -0
  199. package/src/ui/project.ts +219 -0
  200. package/src/ui/release.ts +336 -0
  201. package/src/ui/runner.ts +18 -0
  202. package/studio/client/dist/assets/elk-api-DjmKsHXc.js +1 -0
  203. package/studio/client/dist/assets/index-7YHdeCxp.js +81 -0
  204. package/studio/client/dist/assets/index-C0FAnwNw.css +2 -0
  205. package/studio/client/dist/assets/rolldown-runtime-Dd_uD5pT.js +1 -0
  206. package/studio/client/dist/assets/schema-studio-BilUNb6Z.css +1 -0
  207. package/studio/client/dist/assets/schema-studio-CABpTfvH.js +8 -0
  208. package/studio/client/dist/index.html +3 -2
  209. package/studio/package.json +7 -13
  210. package/studio/server/agent/ask.test.ts +1 -1
  211. package/studio/server/agent/bridge/grant.test.ts +1 -1
  212. package/studio/server/agent/bridge/routes.test.ts +1 -1
  213. package/studio/server/agent/harness/claude/adapter.test.ts +15 -5
  214. package/studio/server/agent/harness/gateway/token.test.ts +1 -1
  215. package/studio/server/agent/harness/gateway/token.ts +3 -3
  216. package/studio/server/agent/prompts/anchors.test.ts +32 -36
  217. package/studio/server/agent/prompts/anchors.ts +20 -49
  218. package/studio/server/agent/prompts/system.test.ts +3 -2
  219. package/studio/server/agent/prompts/system.ts +3 -3
  220. package/studio/server/agent/routes.test.ts +1 -1
  221. package/studio/server/agent/run/coordinator.test.ts +1 -1
  222. package/studio/server/api/canvas.ts +0 -1
  223. package/studio/server/api-agent-loadout.test.ts +1 -1
  224. package/studio/server/api.test.ts +1 -1
  225. package/studio/server/cache.test.ts +23 -12
  226. package/studio/server/cache.ts +12 -15
  227. package/studio/server/domain.test.ts +50 -68
  228. package/studio/server/domain.ts +82 -63
  229. package/studio/server/handoff/copy.ts +1 -1
  230. package/studio/server/index.ts +1 -1
  231. package/studio/server/instances/probe.test.ts +1 -1
  232. package/studio/server/introspect/anatomy/views/routes.ts +46 -37
  233. package/studio/server/introspect/anatomy/views.ts +9 -14
  234. package/studio/server/introspect/anatomy-extras.test.ts +26 -42
  235. package/studio/server/introspect/anatomy.test.ts +22 -14
  236. package/studio/server/introspect/anatomy.ts +6 -9
  237. package/studio/server/introspect/bundle.ts +0 -3
  238. package/studio/server/introspect/canonical-schema.test.ts +94 -389
  239. package/studio/server/introspect/canonical-schema.ts +227 -457
  240. package/studio/server/introspect/core-extractor.ts +18 -127
  241. package/studio/server/introspect/core.ts +1 -2
  242. package/studio/server/introspect/diff.test.ts +11 -7
  243. package/studio/server/introspect/diff.ts +18 -55
  244. package/studio/server/introspect/extractor.ts +22 -117
  245. package/studio/server/introspect/overlay-tsmorph.test.ts +119 -240
  246. package/studio/server/introspect/overlay.test.ts +26 -54
  247. package/studio/server/introspect/overlay.ts +10 -37
  248. package/studio/server/introspect/revision.test.ts +1 -1
  249. package/studio/server/introspect/revision.ts +1 -1
  250. package/studio/server/introspect/runtime.test.ts +65 -183
  251. package/studio/server/introspect/runtime.ts +8 -25
  252. package/studio/server/introspect/schema-ir-json.test.ts +70 -0
  253. package/studio/server/introspect/schema-ir-json.ts +38 -68
  254. package/studio/server/introspect/schema-refs.test.ts +43 -88
  255. package/studio/server/introspect/schema-refs.ts +14 -49
  256. package/studio/server/introspect/source-overlay/handlers.ts +116 -636
  257. package/studio/server/introspect/source-overlay/kernel-calls.ts +0 -3
  258. package/studio/server/introspect/source-overlay/spans.ts +15 -45
  259. package/studio/server/state/baseline.test.ts +14 -9
  260. package/studio/server/state/baseline.ts +3 -5
  261. package/studio/server/state/visibility.ts +1 -5
  262. package/studio/server/views/model.ts +3 -3
  263. package/studio/server/views/target.test.ts +17 -74
  264. package/studio/server/views/target.ts +24 -50
  265. package/studio/server/watch.test.ts +11 -11
  266. package/studio/server/watch.ts +8 -4
  267. package/studio/server/workspace-watch.ts +2 -2
  268. package/studio/shared/contracts/schema.ts +38 -107
  269. package/studio/shared/contracts/surface.test.ts +13 -15
  270. package/studio/shared/contracts/workspace.ts +2 -11
  271. package/studio/shared/schema/identity.test.ts +20 -44
  272. package/studio/shared/schema/identity.ts +9 -23
  273. package/viewer/dist/index.html +21 -0
  274. package/viewer/dist/main.js +30 -51
  275. package/.check-workspace.cjs +0 -40
  276. package/src/admin/binding.ts +0 -168
  277. package/src/commands/__tests__/instance-create-hosts.test.ts +0 -29
  278. package/studio/client/dist/assets/elk-api-lwhFo7vB.js +0 -1
  279. package/studio/client/dist/assets/index-B-c-smo9.js +0 -8
  280. package/studio/client/dist/assets/index-BckHuAWk.js +0 -81
  281. package/studio/client/dist/assets/index-C4aNQ6dz.css +0 -1
  282. package/studio/client/dist/assets/index-ChOr3yP0.css +0 -1
  283. package/studio/server/introspect/anatomy/views/legacy.ts +0 -232
@@ -0,0 +1,932 @@
1
+ import { access, lstat, mkdir, readFile, realpath, rm, writeFile } from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import { isSeq, parseDocument } from 'yaml'
4
+
5
+ import { digest, parseUiLock, readUiLock } from './lock'
6
+ import {
7
+ UI_PACKAGE,
8
+ UI_PRESETS,
9
+ UI_LOCK_FILE,
10
+ UiError,
11
+ type UiLock,
12
+ type UiPreset,
13
+ type UiRegistryItem,
14
+ type UiRelease,
15
+ } from './model'
16
+ import {
17
+ assertSupportedUiProject,
18
+ discoverUiProject,
19
+ projectRelative,
20
+ type UiProject,
21
+ } from './project'
22
+ import {
23
+ readUiRegistryItem,
24
+ readUiReleaseSnapshot,
25
+ registryItemUrl,
26
+ resolveUiRelease,
27
+ } from './release'
28
+ import { defaultUiRunner, shadcnInvocation, type UiRunner } from './runner'
29
+
30
+ type Dependencies = { fetcher?: typeof fetch; runner?: UiRunner }
31
+
32
+ const LOCAL_THEME_MAX_BYTES = 131_072
33
+ const THEME_SLUG = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u
34
+ const REQUIRED_THEME_TOKENS = [
35
+ 'background',
36
+ 'foreground',
37
+ 'card',
38
+ 'card-foreground',
39
+ 'popover',
40
+ 'popover-foreground',
41
+ 'primary',
42
+ 'primary-foreground',
43
+ 'secondary',
44
+ 'secondary-foreground',
45
+ 'muted',
46
+ 'muted-foreground',
47
+ 'accent',
48
+ 'accent-foreground',
49
+ 'destructive',
50
+ 'destructive-foreground',
51
+ 'border',
52
+ 'input',
53
+ 'ring',
54
+ 'chart-1',
55
+ 'chart-2',
56
+ 'chart-3',
57
+ 'chart-4',
58
+ 'chart-5',
59
+ 'font-body',
60
+ 'font-heading',
61
+ 'radius',
62
+ 'radius-panel',
63
+ 'control-height',
64
+ 'control-height-sm',
65
+ 'control-height-lg',
66
+ 'shadow-control',
67
+ 'shadow-panel',
68
+ 'motion-fast',
69
+ 'motion-standard',
70
+ ] as const
71
+
72
+ async function exists(target: string): Promise<boolean> {
73
+ return access(target).then(
74
+ () => true,
75
+ () => false,
76
+ )
77
+ }
78
+
79
+ async function readOptional(target: string): Promise<string | undefined> {
80
+ return readFile(target, 'utf8').catch(() => undefined)
81
+ }
82
+
83
+ function isLocalThemeAddress(address: string): boolean {
84
+ return (address.startsWith('./') || address.startsWith('../')) && address.endsWith('.css')
85
+ }
86
+
87
+ function admitLocalThemeCss(source: string, slug: string): void {
88
+ if (new TextEncoder().encode(source).byteLength > LOCAL_THEME_MAX_BYTES) {
89
+ throw new UiError('UI_ITEM_CONFLICT', 'Local theme CSS exceeds 128 KiB.')
90
+ }
91
+ if (
92
+ !source.includes('Consumer-owned after installation.') ||
93
+ !source.includes("[data-ui-theme='" + slug + "']") ||
94
+ !source.includes("[data-ui-theme='" + slug + "'].dark") ||
95
+ /@import\b|url\s*\(/iu.test(source) ||
96
+ REQUIRED_THEME_TOKENS.some(
97
+ (token) => source.match(new RegExp(`--ui-${token}:`, 'gu'))?.length !== 2,
98
+ )
99
+ ) {
100
+ throw new UiError(
101
+ 'UI_ITEM_CONFLICT',
102
+ 'Local theme CSS is not an admitted Astrale playground export.',
103
+ 'Export the CSS from the Astrale UI playground, keep its filename aligned with the theme name, and try again.',
104
+ )
105
+ }
106
+ }
107
+
108
+ function themeImport(project: UiProject, target: string): string {
109
+ let relative = path.relative(path.dirname(project.cssPath), target).split(path.sep).join('/')
110
+ if (!relative.startsWith('.')) relative = './' + relative
111
+ return "@import '" + relative + "';"
112
+ }
113
+
114
+ function activateTheme(current: string, statement: string): string {
115
+ const lines = current
116
+ .split(/\r?\n/u)
117
+ .filter(
118
+ (line) =>
119
+ !/^@import\s+['"][^'"]*components\/astrale\/theme\/[a-z][a-z0-9-]*\.css['"];?\s*$/u.test(
120
+ line,
121
+ ),
122
+ )
123
+ const packageImport = lines.reduce(
124
+ (last, line, index) =>
125
+ /^@import\s+['"]@astrale-os\/ui\/(?:theme\.css|presets\/[a-z-]+\.css)['"];?\s*$/u.test(line)
126
+ ? index
127
+ : last,
128
+ -1,
129
+ )
130
+ lines.splice(packageImport + 1, 0, statement)
131
+ return lines
132
+ .join('\n')
133
+ .replace(/\n{3,}/gu, '\n\n')
134
+ .replace(/^\n/u, '')
135
+ }
136
+
137
+ function manifestDependencies(manifest: Record<string, unknown>): Record<string, string> {
138
+ return { ...(manifest.dependencies as Record<string, string> | undefined) }
139
+ }
140
+
141
+ function domainRegistryPackagePath(project: UiProject): string {
142
+ return path.join(project.root, 'components/package.json')
143
+ }
144
+
145
+ function pnpmWorkspacePath(project: UiProject): string {
146
+ return path.join(project.root, 'pnpm-workspace.yaml')
147
+ }
148
+
149
+ function domainRegistryPackageName(manifest: Record<string, unknown>): string {
150
+ const name = typeof manifest.name === 'string' ? manifest.name : 'astrale-domain'
151
+ return name + '-ui-registry'
152
+ }
153
+
154
+ function appendWorkspace(manifest: Record<string, unknown>, workspace: string): void {
155
+ const configured = manifest.workspaces
156
+ if (configured === undefined) {
157
+ manifest.workspaces = [workspace]
158
+ return
159
+ }
160
+ if (Array.isArray(configured) && configured.every((value) => typeof value === 'string')) {
161
+ if (!configured.includes(workspace)) manifest.workspaces = [...configured, workspace]
162
+ return
163
+ }
164
+ if (configured && typeof configured === 'object') {
165
+ const candidate = configured as { packages?: unknown }
166
+ if (
167
+ Array.isArray(candidate.packages) &&
168
+ candidate.packages.every((value) => typeof value === 'string')
169
+ ) {
170
+ if (!candidate.packages.includes(workspace)) {
171
+ manifest.workspaces = { ...candidate, packages: [...candidate.packages, workspace] }
172
+ }
173
+ return
174
+ }
175
+ }
176
+ throw new UiError('UI_PROJECT_UNSUPPORTED', 'package.json has an invalid workspaces field.')
177
+ }
178
+
179
+ async function appendPnpmWorkspace(project: UiProject, workspace: string): Promise<void> {
180
+ const target = pnpmWorkspacePath(project)
181
+ const source = await readOptional(target)
182
+ if (source === undefined) {
183
+ await writeFile(target, "packages:\n - '" + workspace + "'\n", 'utf8')
184
+ return
185
+ }
186
+ const document = parseDocument(source)
187
+ if (document.errors.length > 0) {
188
+ throw new UiError('UI_PROJECT_UNSUPPORTED', 'pnpm-workspace.yaml is not valid YAML.')
189
+ }
190
+ const packages = document.get('packages', true)
191
+ if (!isSeq(packages)) {
192
+ throw new UiError(
193
+ 'UI_PROJECT_UNSUPPORTED',
194
+ 'pnpm-workspace.yaml must declare a packages sequence.',
195
+ )
196
+ }
197
+ const values = packages.toJSON()
198
+ if (!Array.isArray(values) || !values.every((value) => typeof value === 'string')) {
199
+ throw new UiError(
200
+ 'UI_PROJECT_UNSUPPORTED',
201
+ 'pnpm-workspace.yaml must declare a packages sequence.',
202
+ )
203
+ }
204
+ if (!values.includes(workspace)) packages.add(workspace)
205
+ await writeFile(target, String(document), 'utf8')
206
+ }
207
+
208
+ async function hasDomainRegistryWorkspace(project: UiProject): Promise<boolean> {
209
+ if (!project.isAstraleDomain || !(await exists(domainRegistryPackagePath(project)))) return false
210
+ const registryManifest = JSON.parse(
211
+ await readFile(domainRegistryPackagePath(project), 'utf8'),
212
+ ) as Record<string, unknown>
213
+ if (
214
+ registryManifest.private !== true ||
215
+ typeof registryManifest.name !== 'string' ||
216
+ registryManifest.name === UI_PACKAGE ||
217
+ registryManifest.name === project.packageJson.name
218
+ ) {
219
+ return false
220
+ }
221
+ if (project.manager === 'pnpm') {
222
+ const source = await readOptional(pnpmWorkspacePath(project))
223
+ if (source === undefined) return false
224
+ const document = parseDocument(source)
225
+ if (document.errors.length > 0) return false
226
+ const packages = document.get('packages', true)
227
+ const values = isSeq(packages) ? packages.toJSON() : undefined
228
+ return Array.isArray(values) && values.includes('components')
229
+ }
230
+ const configured = project.packageJson.workspaces
231
+ const workspaces = Array.isArray(configured)
232
+ ? configured
233
+ : configured && typeof configured === 'object'
234
+ ? (configured as { packages?: unknown }).packages
235
+ : undefined
236
+ return Array.isArray(workspaces) && workspaces.includes('components')
237
+ }
238
+
239
+ async function writeDomainRegistryWorkspace(
240
+ project: UiProject,
241
+ manifest: Record<string, unknown>,
242
+ ): Promise<void> {
243
+ if (!project.isAstraleDomain) return
244
+ if (project.manager === 'pnpm') await appendPnpmWorkspace(project, 'components')
245
+ else appendWorkspace(manifest, 'components')
246
+ const target = domainRegistryPackagePath(project)
247
+ const existing = await readOptional(target)
248
+ const registryManifest = existing
249
+ ? (JSON.parse(existing) as Record<string, unknown>)
250
+ : { name: domainRegistryPackageName(manifest) }
251
+ if (registryManifest.private === false) {
252
+ throw new UiError(
253
+ 'UI_PROJECT_UNSUPPORTED',
254
+ 'The Astrale registry source workspace must remain private.',
255
+ )
256
+ }
257
+ if (
258
+ registryManifest.name === UI_PACKAGE ||
259
+ registryManifest.name === manifest.name ||
260
+ (registryManifest.name !== undefined && typeof registryManifest.name !== 'string')
261
+ ) {
262
+ throw new UiError(
263
+ 'UI_PROJECT_UNSUPPORTED',
264
+ 'The Astrale registry source workspace must have a distinct package name.',
265
+ )
266
+ }
267
+ await writeJson(target, {
268
+ ...registryManifest,
269
+ name: registryManifest.name ?? domainRegistryPackageName(manifest),
270
+ private: true,
271
+ type: registryManifest.type ?? 'module',
272
+ })
273
+ }
274
+
275
+ export type InitUiOptions = {
276
+ path?: string
277
+ preset?: UiPreset
278
+ version?: string
279
+ dryRun?: boolean
280
+ force?: boolean
281
+ install?: boolean
282
+ }
283
+
284
+ export async function initUi(
285
+ options: InitUiOptions,
286
+ dependencies: Dependencies = {},
287
+ ): Promise<Record<string, unknown>> {
288
+ const project = await discoverUiProject(options.path)
289
+ await assertSafePlannedTarget(project, UI_LOCK_FILE)
290
+ assertSupportedUiProject(project)
291
+ const preset = options.preset ?? 'astrale'
292
+ if (!UI_PRESETS.includes(preset)) {
293
+ throw new UiError('UI_PROJECT_UNSUPPORTED', 'Unknown UI preset: ' + preset)
294
+ }
295
+ if ((await exists(project.uiLockPath)) && !options.force) {
296
+ const lock = await readUiLock(project.uiLockPath)
297
+ const css = (await readOptional(project.cssPath)) ?? ''
298
+ const components = await readOptional(project.componentsPath)
299
+ .then((value) => (value ? (JSON.parse(value) as Record<string, unknown>) : undefined))
300
+ .catch(() => undefined)
301
+ const requestedVersion = options.version?.replace(/^v/u, '')
302
+ const desired =
303
+ (!requestedVersion || requestedVersion === lock.package.version) &&
304
+ (!options.preset || options.preset === lock.preset) &&
305
+ css.includes(UI_PACKAGE + '/theme.css') &&
306
+ css.includes(UI_PACKAGE + '/presets/' + lock.preset + '.css') &&
307
+ components?.style === 'base-nova' &&
308
+ (!project.isAstraleDomain || (await hasDomainRegistryWorkspace(project)))
309
+ if (!desired) {
310
+ throw new UiError(
311
+ 'UI_ITEM_CONFLICT',
312
+ 'Existing Astrale UI initialization differs from the requested state.',
313
+ 'Run astrale ui doctor, then repeat init with --force after reviewing the changes.',
314
+ )
315
+ }
316
+ return { status: 'unchanged', root: project.root, lock }
317
+ }
318
+ const release = await resolveUiRelease(options.version, dependencies.fetcher)
319
+ const cssRelative = projectRelative(project, project.cssPath)
320
+ const plan = {
321
+ status: options.dryRun ? 'planned' : 'initialized',
322
+ root: project.root,
323
+ package: UI_PACKAGE + '@' + release.version,
324
+ manager: project.manager,
325
+ preset,
326
+ files: [
327
+ 'package.json',
328
+ cssRelative,
329
+ 'components.json',
330
+ 'astrale-ui.lock.json',
331
+ ...(project.isAstraleDomain ? ['components/package.json'] : []),
332
+ ...(project.isAstraleDomain && project.manager === 'pnpm' ? ['pnpm-workspace.yaml'] : []),
333
+ ...(project.lockPath ? [projectRelative(project, project.lockPath)] : []),
334
+ ],
335
+ tooling: {
336
+ shadcn: release.compatibility.shadcn,
337
+ base: release.compatibility.base,
338
+ style: release.compatibility.style,
339
+ baseUi: release.compatibility.baseUi,
340
+ },
341
+ }
342
+ if (options.dryRun) return plan
343
+
344
+ if (project.isAstraleDomain) {
345
+ await assertSafePlannedTarget(project, 'components/package.json')
346
+ if (project.manager === 'pnpm') {
347
+ await assertSafePlannedTarget(project, 'pnpm-workspace.yaml')
348
+ }
349
+ }
350
+
351
+ const mutationPaths = [
352
+ project.packageJsonPath,
353
+ project.cssPath,
354
+ project.componentsPath,
355
+ project.uiLockPath,
356
+ ...(project.isAstraleDomain ? [domainRegistryPackagePath(project)] : []),
357
+ ...(project.isAstraleDomain && project.manager === 'pnpm' ? [pnpmWorkspacePath(project)] : []),
358
+ ...(project.lockPath ? [project.lockPath] : []),
359
+ ]
360
+ const snapshots = new Map<string, string | undefined>()
361
+ for (const target of mutationPaths) snapshots.set(target, await readOptional(target))
362
+
363
+ try {
364
+ const manifest = { ...project.packageJson }
365
+ manifest.dependencies = {
366
+ ...manifestDependencies(manifest),
367
+ [UI_PACKAGE]: release.version,
368
+ }
369
+ await writeDomainRegistryWorkspace(project, manifest)
370
+ await writeJson(project.packageJsonPath, manifest)
371
+
372
+ const currentCss = (await readOptional(project.cssPath)) ?? ''
373
+ const imports = [
374
+ "@import '" + UI_PACKAGE + "/theme.css';",
375
+ "@import '" + UI_PACKAGE + '/presets/' + preset + ".css';",
376
+ ]
377
+ const withoutAstrale = currentCss
378
+ .replace(
379
+ /^@import\s+['"]@astrale-os\/ui\/(?:theme\.css|presets\/[a-z-]+\.css)['"];?\s*$/gmu,
380
+ '',
381
+ )
382
+ .trimStart()
383
+ await mkdir(path.dirname(project.cssPath), { recursive: true })
384
+ await writeFile(project.cssPath, imports.join('\n') + '\n\n' + withoutAstrale, 'utf8')
385
+
386
+ const components = JSON.parse((await readOptional(project.componentsPath)) ?? '{}') as Record<
387
+ string,
388
+ unknown
389
+ >
390
+ await writeJson(project.componentsPath, {
391
+ $schema: 'https://ui.shadcn.com/schema.json',
392
+ ...components,
393
+ style: 'base-nova',
394
+ rsc: components.rsc ?? false,
395
+ tsx: components.tsx ?? true,
396
+ tailwind: {
397
+ config: '',
398
+ baseColor: 'neutral',
399
+ cssVariables: true,
400
+ prefix: '',
401
+ ...(components.tailwind as Record<string, unknown> | undefined),
402
+ css: cssRelative,
403
+ },
404
+ aliases: {
405
+ components: '@/components',
406
+ utils: '@/lib/utils',
407
+ ui: '@/components/ui',
408
+ lib: '@/lib',
409
+ hooks: '@/hooks',
410
+ ...(components.aliases as Record<string, unknown> | undefined),
411
+ },
412
+ })
413
+
414
+ if (options.install !== false) {
415
+ const result = await (dependencies.runner ?? defaultUiRunner)(
416
+ project.manager,
417
+ ['install'],
418
+ project.root,
419
+ )
420
+ if (result.code !== 0) {
421
+ throw new UiError(
422
+ 'UI_DEPENDENCY_INSTALL_FAILED',
423
+ project.manager + ' install failed.',
424
+ result.stderr.trim() || undefined,
425
+ )
426
+ }
427
+ }
428
+
429
+ const lock: UiLock = {
430
+ $schema:
431
+ 'https://raw.githubusercontent.com/astrale-os/ui/' +
432
+ release.ref +
433
+ '/schemas/ui-lock.schema.json',
434
+ version: 1,
435
+ package: { name: UI_PACKAGE, version: release.version },
436
+ registry: {
437
+ repository: 'astrale-os/ui',
438
+ ref: release.ref,
439
+ commit: release.commit,
440
+ },
441
+ tooling: {
442
+ shadcn: release.compatibility.shadcn,
443
+ base: 'base',
444
+ style: 'nova',
445
+ baseUi: release.compatibility.baseUi,
446
+ },
447
+ preset,
448
+ items: {},
449
+ }
450
+ await writeJson(project.uiLockPath, lock)
451
+ return { ...plan, lock }
452
+ } catch (error) {
453
+ for (const [target, value] of snapshots) {
454
+ if (value !== undefined) await writeFile(target, value, 'utf8')
455
+ else await rm(target, { force: true })
456
+ }
457
+ throw error
458
+ }
459
+ }
460
+
461
+ async function pinUiDependency(
462
+ project: UiProject,
463
+ version: string,
464
+ runner: UiRunner,
465
+ ): Promise<void> {
466
+ const manifest = JSON.parse(await readFile(project.packageJsonPath, 'utf8')) as Record<
467
+ string,
468
+ unknown
469
+ >
470
+ if (manifestDependencies(manifest)[UI_PACKAGE] === version) return
471
+ manifest.dependencies = { ...manifestDependencies(manifest), [UI_PACKAGE]: version }
472
+ await writeJson(project.packageJsonPath, manifest)
473
+ const result = await runner(project.manager, ['install'], project.root)
474
+ if (result.code !== 0) {
475
+ throw new UiError(
476
+ 'UI_DEPENDENCY_INSTALL_FAILED',
477
+ project.manager + ' install failed while restoring the locked UI release.',
478
+ result.stderr.trim() || undefined,
479
+ )
480
+ }
481
+ }
482
+
483
+ export async function listUi(
484
+ query: string | undefined,
485
+ options: { type?: string; limit?: number; version?: string },
486
+ dependencies: Dependencies = {},
487
+ ): Promise<UiRegistryItem[]> {
488
+ const release = await resolveUiRelease(options.version, dependencies.fetcher)
489
+ const needle = query?.trim().toLowerCase()
490
+ return release.registry.items
491
+ .filter((item) => {
492
+ if (options.type && !item.meta.canonicalAddress.startsWith(options.type + '/')) return false
493
+ if (!needle) return true
494
+ return [item.meta.canonicalAddress, item.name, item.title, item.description]
495
+ .filter(Boolean)
496
+ .some((value) => String(value).toLowerCase().includes(needle))
497
+ })
498
+ .slice(0, options.limit ?? 100)
499
+ }
500
+
501
+ export async function listLockedUi(
502
+ input: string | undefined,
503
+ dependencies: Dependencies = {},
504
+ ): Promise<UiRegistryItem[]> {
505
+ const project = await discoverUiProject(input)
506
+ const { release } = await lockedRelease(project, dependencies.fetcher)
507
+ return release.registry.items
508
+ }
509
+
510
+ async function lockedRelease(
511
+ project: UiProject,
512
+ fetcher?: typeof fetch,
513
+ ): Promise<{ lock: UiLock; release: UiRelease }> {
514
+ const lock = await readUiLock(project.uiLockPath)
515
+ const release = await readUiReleaseSnapshot(
516
+ {
517
+ version: lock.package.version,
518
+ ref: lock.registry.ref,
519
+ commit: lock.registry.commit,
520
+ },
521
+ fetcher,
522
+ )
523
+ return { lock, release }
524
+ }
525
+
526
+ async function addLocalTheme(
527
+ address: string,
528
+ project: UiProject,
529
+ options: { dryRun?: boolean; overwrite?: boolean },
530
+ ): Promise<Record<string, unknown>> {
531
+ const sourcePath = path.resolve(project.root, address)
532
+ const sourceInfo = await lstat(sourcePath).catch(() => undefined)
533
+ if (!sourceInfo?.isFile() || sourceInfo.isSymbolicLink()) {
534
+ throw new UiError('UI_ITEM_NOT_FOUND', 'Local theme is not a regular file: ' + address)
535
+ }
536
+ const slug = path.basename(sourcePath, '.css')
537
+ if (!THEME_SLUG.test(slug)) {
538
+ throw new UiError(
539
+ 'UI_ITEM_CONFLICT',
540
+ 'Local theme filename must be a kebab-case theme name.',
541
+ 'Rename it to a name such as observatory.css.',
542
+ )
543
+ }
544
+ const source = await readFile(sourcePath, 'utf8')
545
+ admitLocalThemeCss(source, slug)
546
+
547
+ const lock = await readUiLock(project.uiLockPath)
548
+ const canonicalAddress = 'theme/' + slug
549
+ const relativeTarget = 'components/astrale/theme/' + slug + '.css'
550
+ const target = await assertSafePlannedTarget(project, relativeTarget)
551
+ const existing = await readOptional(target)
552
+ const installed = lock.items[canonicalAddress]
553
+ if (existing !== undefined && !installed && !options.overwrite) {
554
+ throw new UiError(
555
+ 'UI_LOCAL_CHANGES',
556
+ 'Theme target already exists outside the Astrale UI lock: ' + relativeTarget,
557
+ 'Review the file, then repeat with explicit --overwrite --yes.',
558
+ )
559
+ }
560
+ if (installed && !options.overwrite) {
561
+ const expected = installed.files[relativeTarget]
562
+ if (!expected || digest(existing ?? '') !== expected) {
563
+ throw new UiError(
564
+ 'UI_LOCAL_CHANGES',
565
+ 'Installed UI file has local changes: ' + relativeTarget,
566
+ 'Review the file, then repeat add with explicit --overwrite --yes.',
567
+ )
568
+ }
569
+ }
570
+ const statement = themeImport(project, target)
571
+ const result = {
572
+ status: options.dryRun ? 'planned' : 'installed',
573
+ items: [canonicalAddress],
574
+ files: { [canonicalAddress]: { [relativeTarget]: digest(source) } },
575
+ activation: { file: projectRelative(project, project.cssPath), import: statement },
576
+ source: address,
577
+ }
578
+ if (options.dryRun) return result
579
+
580
+ const snapshots = new Map<string, string | undefined>()
581
+ for (const mutation of [target, project.cssPath, project.uiLockPath]) {
582
+ snapshots.set(mutation, await readOptional(mutation))
583
+ }
584
+ try {
585
+ await mkdir(path.dirname(target), { recursive: true })
586
+ await writeFile(target, source, 'utf8')
587
+ const css = (await readOptional(project.cssPath)) ?? ''
588
+ await writeFile(project.cssPath, activateTheme(css, statement), 'utf8')
589
+ lock.items[canonicalAddress] = {
590
+ address: canonicalAddress,
591
+ sourceDigest: digest(source),
592
+ files: { [relativeTarget]: digest(source) },
593
+ }
594
+ await writeJson(project.uiLockPath, lock)
595
+ return result
596
+ } catch (error) {
597
+ for (const [mutation, previous] of snapshots) {
598
+ if (previous === undefined) await rm(mutation, { force: true })
599
+ else await writeFile(mutation, previous, 'utf8')
600
+ }
601
+ throw error
602
+ }
603
+ }
604
+
605
+ export async function addUi(
606
+ addresses: string[],
607
+ options: { project?: string; dryRun?: boolean; overwrite?: boolean; yes?: boolean },
608
+ dependencies: Dependencies = {},
609
+ ): Promise<Record<string, unknown>> {
610
+ if (addresses.length === 0) {
611
+ throw new UiError('UI_ITEM_NOT_FOUND', 'No UI item was provided.')
612
+ }
613
+ const project = await discoverUiProject(options.project)
614
+ await assertSafePlannedTarget(project, UI_LOCK_FILE)
615
+ if (options.overwrite && !options.yes) {
616
+ throw new UiError(
617
+ 'UI_LOCAL_CHANGES',
618
+ 'Replacing installed UI source requires explicit confirmation.',
619
+ 'Review the locally edited files, then repeat with both --overwrite and --yes.',
620
+ )
621
+ }
622
+ const localThemes = addresses.filter(isLocalThemeAddress)
623
+ if (localThemes.length > 0) {
624
+ if (addresses.length !== 1) {
625
+ throw new UiError(
626
+ 'UI_ITEM_CONFLICT',
627
+ 'Install one local theme at a time and do not mix local files with registry addresses.',
628
+ )
629
+ }
630
+ return addLocalTheme(localThemes[0]!, project, options)
631
+ }
632
+ const { lock, release } = await lockedRelease(project, dependencies.fetcher)
633
+ const items = addresses.map((address) => findItem(release, address))
634
+ const themes = items.filter((item) => item.type === 'registry:theme')
635
+ if (themes.length > 1) {
636
+ throw new UiError('UI_ITEM_CONFLICT', 'Only one theme can be activated per add operation.')
637
+ }
638
+ const itemDocuments = await Promise.all(
639
+ items.map((item) => readUiRegistryItem(release, item, dependencies.fetcher)),
640
+ )
641
+ await rejectLocalChanges(project, lock, items, options.overwrite === true)
642
+ const targets = (
643
+ await Promise.all(
644
+ items.flatMap((item) =>
645
+ item.files
646
+ .filter((file) => file.target)
647
+ .map((file) => assertSafePlannedTarget(project, file.target!)),
648
+ ),
649
+ )
650
+ ).filter((target, index, all) => all.indexOf(target) === index)
651
+ const invocation = shadcnInvocation(project.manager, release.compatibility.shadcn, [
652
+ 'add',
653
+ ...items.map((item) => registryItemUrl(release, item.name)),
654
+ '--cwd',
655
+ project.root,
656
+ ...(options.dryRun ? ['--dry-run'] : []),
657
+ ...(options.overwrite ? ['--overwrite'] : []),
658
+ ...(options.yes ? ['--yes'] : []),
659
+ ])
660
+ const snapshots = new Map<string, string | undefined>()
661
+ if (!options.dryRun) {
662
+ for (const target of [
663
+ project.packageJsonPath,
664
+ project.lockPath!,
665
+ project.cssPath,
666
+ project.uiLockPath,
667
+ ...targets,
668
+ ]) {
669
+ snapshots.set(target, await readOptional(target))
670
+ }
671
+ }
672
+ let result: Awaited<ReturnType<UiRunner>>
673
+ try {
674
+ result = await (dependencies.runner ?? defaultUiRunner)(
675
+ invocation.file,
676
+ invocation.args,
677
+ project.root,
678
+ )
679
+ if (result.code !== 0) {
680
+ throw new UiError(
681
+ 'UI_TOOL_FAILED',
682
+ 'The pinned shadcn operation failed.',
683
+ result.stderr.trim(),
684
+ )
685
+ }
686
+ if (!options.dryRun) {
687
+ for (const target of targets) {
688
+ if (!(await exists(target))) {
689
+ throw new UiError('UI_TOOL_FAILED', 'The pinned shadcn operation omitted an item file.')
690
+ }
691
+ }
692
+ await pinUiDependency(project, lock.package.version, dependencies.runner ?? defaultUiRunner)
693
+ const theme = themes[0]
694
+ const themeTarget = theme?.files[0]?.target
695
+ if (themeTarget) {
696
+ const target = await safeTarget(project, themeTarget)
697
+ const css = (await readOptional(project.cssPath)) ?? ''
698
+ await writeFile(project.cssPath, activateTheme(css, themeImport(project, target)), 'utf8')
699
+ }
700
+ }
701
+ } catch (error) {
702
+ for (const [target, previous] of snapshots) {
703
+ if (previous === undefined) await rm(target, { force: true })
704
+ else await writeFile(target, previous, 'utf8')
705
+ }
706
+ throw error
707
+ }
708
+ if (options.dryRun) {
709
+ return {
710
+ status: 'planned',
711
+ items: items.map((item) => item.meta.canonicalAddress),
712
+ sources: itemDocuments.map((item) => ({
713
+ address: item.meta.canonicalAddress,
714
+ dependencies: item.dependencies ?? [],
715
+ files: item.files.map((file) => file.target).filter(Boolean),
716
+ })),
717
+ command: [invocation.file, ...invocation.args],
718
+ output: result.stdout,
719
+ activation: themes[0]
720
+ ? {
721
+ file: projectRelative(project, project.cssPath),
722
+ import: themeImport(
723
+ project,
724
+ targets.find((target) => target.endsWith('.css'))!,
725
+ ),
726
+ }
727
+ : undefined,
728
+ }
729
+ }
730
+
731
+ try {
732
+ for (const [index, item] of items.entries()) {
733
+ const itemDocument = itemDocuments[index]!
734
+ const files: Record<string, string> = {}
735
+ for (const file of item.files) {
736
+ if (!file.target) continue
737
+ const target = await safeTarget(project, file.target)
738
+ files[projectRelative(project, target)] = digest(await readFile(target))
739
+ }
740
+ lock.items[item.meta.canonicalAddress] = {
741
+ address: item.meta.canonicalAddress,
742
+ sourceDigest: digest(JSON.stringify(itemDocument)),
743
+ files,
744
+ }
745
+ }
746
+ await writeJson(project.uiLockPath, lock)
747
+ } catch (error) {
748
+ for (const [target, previous] of snapshots) {
749
+ if (previous === undefined) await rm(target, { force: true })
750
+ else await writeFile(target, previous, 'utf8')
751
+ }
752
+ throw error
753
+ }
754
+ return {
755
+ status: 'installed',
756
+ items: items.map((item) => item.meta.canonicalAddress),
757
+ files: Object.fromEntries(
758
+ items.map((item) => [
759
+ item.meta.canonicalAddress,
760
+ lock.items[item.meta.canonicalAddress]?.files,
761
+ ]),
762
+ ),
763
+ }
764
+ }
765
+
766
+ export async function doctorUi(
767
+ input?: string,
768
+ ): Promise<{ healthy: boolean; checks: Array<{ check: string; ok: boolean; detail?: string }> }> {
769
+ const project = await discoverUiProject(input)
770
+ const checks: Array<{ check: string; ok: boolean; detail?: string }> = []
771
+ let lock: UiLock | undefined
772
+ try {
773
+ lock = parseUiLock(JSON.parse(await readFile(project.uiLockPath, 'utf8')))
774
+ checks.push({ check: 'lock', ok: true })
775
+ } catch (error) {
776
+ checks.push({
777
+ check: 'lock',
778
+ ok: false,
779
+ detail: error instanceof Error ? error.message : String(error),
780
+ })
781
+ }
782
+ const dependencies = manifestDependencies(project.packageJson)
783
+ checks.push({
784
+ check: 'package',
785
+ ok: typeof dependencies[UI_PACKAGE] === 'string',
786
+ detail: dependencies[UI_PACKAGE],
787
+ })
788
+ const css = (await readOptional(project.cssPath)) ?? ''
789
+ checks.push({ check: 'theme', ok: css.includes(UI_PACKAGE + '/theme.css') })
790
+ checks.push({
791
+ check: 'preset',
792
+ ok: UI_PRESETS.some((preset) => css.includes(UI_PACKAGE + '/presets/' + preset + '.css')),
793
+ })
794
+ checks.push({ check: 'components', ok: await exists(project.componentsPath) })
795
+ if (lock) {
796
+ for (const item of Object.values(lock.items)) {
797
+ for (const [file, expected] of Object.entries(item.files)) {
798
+ const actual = await readFile(path.join(project.root, file))
799
+ .then(digest)
800
+ .catch(() => '')
801
+ checks.push({ check: 'item:' + item.address + ':' + file, ok: actual === expected })
802
+ }
803
+ }
804
+ const themeFiles = Object.values(lock.items)
805
+ .filter((item) => item.address.startsWith('theme/'))
806
+ .flatMap((item) => Object.keys(item.files).filter((file) => file.endsWith('.css')))
807
+ if (themeFiles.length > 0) {
808
+ const active = themeFiles.some((file) =>
809
+ css.includes(themeImport(project, path.join(project.root, file))),
810
+ )
811
+ checks.push({ check: 'theme-active', ok: active })
812
+ }
813
+ }
814
+ return { healthy: checks.every((check) => check.ok), checks }
815
+ }
816
+
817
+ export async function applyPreset(
818
+ preset: UiPreset,
819
+ options: { project?: string; dryRun?: boolean },
820
+ ): Promise<Record<string, unknown>> {
821
+ if (!UI_PRESETS.includes(preset)) {
822
+ throw new UiError('UI_ITEM_NOT_FOUND', 'Unknown preset: ' + preset)
823
+ }
824
+ const project = await discoverUiProject(options.project)
825
+ await assertSafePlannedTarget(project, UI_LOCK_FILE)
826
+ const lock = await readUiLock(project.uiLockPath)
827
+ const css = (await readOptional(project.cssPath)) ?? ''
828
+ const next = css.replace(
829
+ /@astrale-os\/ui\/presets\/[a-z-]+\.css/gu,
830
+ '@astrale-os/ui/presets/' + preset + '.css',
831
+ )
832
+ if (next === css && !css.includes('@astrale-os/ui/presets/')) {
833
+ throw new UiError('UI_CONFIG_MISSING', 'No Astrale preset import was found.')
834
+ }
835
+ if (!options.dryRun) {
836
+ await writeFile(project.cssPath, next, 'utf8')
837
+ lock.preset = preset
838
+ await writeJson(project.uiLockPath, lock)
839
+ }
840
+ return {
841
+ status: options.dryRun ? 'planned' : 'applied',
842
+ preset,
843
+ file: projectRelative(project, project.cssPath),
844
+ }
845
+ }
846
+
847
+ function findItem(release: UiRelease, address: string): UiRegistryItem {
848
+ const normalized = address.replace(/^@astrale\//u, '')
849
+ const exact = release.registry.items.find(
850
+ (item) => item.meta.canonicalAddress === normalized || item.name === normalized,
851
+ )
852
+ if (exact) return exact
853
+ const shorthand = release.registry.items.filter((item) =>
854
+ item.meta.canonicalAddress.endsWith('/' + normalized),
855
+ )
856
+ if (shorthand.length === 1) return shorthand[0]!
857
+ throw new UiError(
858
+ 'UI_ITEM_NOT_FOUND',
859
+ shorthand.length > 1
860
+ ? 'UI item "' + address + '" is ambiguous.'
861
+ : 'UI item "' + address + '" was not found.',
862
+ shorthand.length > 1
863
+ ? 'Use one of: ' + shorthand.map((item) => item.meta.canonicalAddress).join(', ')
864
+ : 'Run astrale ui list to discover canonical addresses.',
865
+ )
866
+ }
867
+
868
+ async function rejectLocalChanges(
869
+ project: UiProject,
870
+ lock: UiLock,
871
+ items: UiRegistryItem[],
872
+ overwrite: boolean,
873
+ ): Promise<void> {
874
+ if (overwrite) return
875
+ for (const item of items) {
876
+ const installed = lock.items[item.meta.canonicalAddress]
877
+ if (!installed) continue
878
+ for (const [file, expected] of Object.entries(installed.files)) {
879
+ const actual = await readFile(path.join(project.root, file))
880
+ .then(digest)
881
+ .catch(() => '')
882
+ if (actual !== expected) {
883
+ throw new UiError(
884
+ 'UI_LOCAL_CHANGES',
885
+ 'Installed UI file has local changes: ' + file,
886
+ 'Review the file, then repeat add with explicit --overwrite --yes.',
887
+ )
888
+ }
889
+ }
890
+ }
891
+ }
892
+
893
+ async function safeTarget(project: UiProject, relative: string): Promise<string> {
894
+ if (path.isAbsolute(relative) || relative.split(/[\\/]/u).includes('..')) {
895
+ throw new UiError('UI_LOCK_INVALID', 'Unsafe registry target: ' + relative)
896
+ }
897
+ const target = path.resolve(project.root, relative)
898
+ projectRelative(project, target)
899
+ const parent = await realpath(path.dirname(target))
900
+ const root = await realpath(project.root)
901
+ if (parent !== root && !parent.startsWith(root + path.sep)) {
902
+ throw new UiError('UI_LOCK_INVALID', 'Registry target escapes through a symlink: ' + relative)
903
+ }
904
+ if ((await exists(target)) && (await lstat(target)).isSymbolicLink()) {
905
+ throw new UiError('UI_LOCK_INVALID', 'Registry target is a symlink: ' + relative)
906
+ }
907
+ return target
908
+ }
909
+
910
+ async function assertSafePlannedTarget(project: UiProject, relative: string): Promise<string> {
911
+ if (path.isAbsolute(relative) || relative.split(/[\\/]/u).includes('..')) {
912
+ throw new UiError('UI_LOCK_INVALID', 'Unsafe registry target: ' + relative)
913
+ }
914
+ const target = path.resolve(project.root, relative)
915
+ projectRelative(project, target)
916
+ const root = await realpath(project.root)
917
+ const physicalTarget = path.resolve(root, path.relative(project.root, target))
918
+ let current = root
919
+ for (const segment of path.relative(root, physicalTarget).split(path.sep)) {
920
+ current = path.join(current, segment)
921
+ if (!(await exists(current))) break
922
+ if ((await lstat(current)).isSymbolicLink()) {
923
+ throw new UiError('UI_LOCK_INVALID', 'Registry target traverses a symlink: ' + relative)
924
+ }
925
+ }
926
+ return target
927
+ }
928
+
929
+ async function writeJson(target: string, value: unknown): Promise<void> {
930
+ await mkdir(path.dirname(target), { recursive: true })
931
+ await writeFile(target, JSON.stringify(value, null, 2) + '\n', 'utf8')
932
+ }