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

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 (282) hide show
  1. package/README.md +16 -1
  2. package/dist/astrale.js +51105 -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 +13 -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 +14 -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 +10 -0
  192. package/src/ui/.spec/laws.ts +36 -0
  193. package/src/ui/.spec/layout.ts +16 -0
  194. package/src/ui/__tests__/ui.test.ts +981 -0
  195. package/src/ui/index.ts +13 -0
  196. package/src/ui/lock.ts +87 -0
  197. package/src/ui/model.ts +83 -0
  198. package/src/ui/operations.ts +710 -0
  199. package/src/ui/project.ts +219 -0
  200. package/src/ui/release.ts +321 -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/main.js +30 -51
  274. package/.check-workspace.cjs +0 -40
  275. package/src/admin/binding.ts +0 -168
  276. package/src/commands/__tests__/instance-create-hosts.test.ts +0 -29
  277. package/studio/client/dist/assets/elk-api-lwhFo7vB.js +0 -1
  278. package/studio/client/dist/assets/index-B-c-smo9.js +0 -8
  279. package/studio/client/dist/assets/index-BckHuAWk.js +0 -81
  280. package/studio/client/dist/assets/index-C4aNQ6dz.css +0 -1
  281. package/studio/client/dist/assets/index-ChOr3yP0.css +0 -1
  282. package/studio/server/introspect/anatomy/views/legacy.ts +0 -232
@@ -0,0 +1,710 @@
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
+ UiError,
10
+ type UiLock,
11
+ type UiPreset,
12
+ type UiRegistryItem,
13
+ type UiRelease,
14
+ } from './model'
15
+ import {
16
+ assertSupportedUiProject,
17
+ discoverUiProject,
18
+ projectRelative,
19
+ type UiProject,
20
+ } from './project'
21
+ import {
22
+ readUiRegistryItem,
23
+ readUiReleaseSnapshot,
24
+ registryItemUrl,
25
+ resolveUiRelease,
26
+ } from './release'
27
+ import { defaultUiRunner, shadcnInvocation, type UiRunner } from './runner'
28
+
29
+ type Dependencies = { fetcher?: typeof fetch; runner?: UiRunner }
30
+
31
+ async function exists(target: string): Promise<boolean> {
32
+ return access(target).then(
33
+ () => true,
34
+ () => false,
35
+ )
36
+ }
37
+
38
+ async function readOptional(target: string): Promise<string | undefined> {
39
+ return readFile(target, 'utf8').catch(() => undefined)
40
+ }
41
+
42
+ function manifestDependencies(manifest: Record<string, unknown>): Record<string, string> {
43
+ return { ...(manifest.dependencies as Record<string, string> | undefined) }
44
+ }
45
+
46
+ function domainRegistryPackagePath(project: UiProject): string {
47
+ return path.join(project.root, 'components/package.json')
48
+ }
49
+
50
+ function pnpmWorkspacePath(project: UiProject): string {
51
+ return path.join(project.root, 'pnpm-workspace.yaml')
52
+ }
53
+
54
+ function domainRegistryPackageName(manifest: Record<string, unknown>): string {
55
+ const name = typeof manifest.name === 'string' ? manifest.name : 'astrale-domain'
56
+ return name + '-ui-registry'
57
+ }
58
+
59
+ function appendWorkspace(manifest: Record<string, unknown>, workspace: string): void {
60
+ const configured = manifest.workspaces
61
+ if (configured === undefined) {
62
+ manifest.workspaces = [workspace]
63
+ return
64
+ }
65
+ if (Array.isArray(configured) && configured.every((value) => typeof value === 'string')) {
66
+ if (!configured.includes(workspace)) manifest.workspaces = [...configured, workspace]
67
+ return
68
+ }
69
+ if (configured && typeof configured === 'object') {
70
+ const candidate = configured as { packages?: unknown }
71
+ if (
72
+ Array.isArray(candidate.packages) &&
73
+ candidate.packages.every((value) => typeof value === 'string')
74
+ ) {
75
+ if (!candidate.packages.includes(workspace)) {
76
+ manifest.workspaces = { ...candidate, packages: [...candidate.packages, workspace] }
77
+ }
78
+ return
79
+ }
80
+ }
81
+ throw new UiError('UI_PROJECT_UNSUPPORTED', 'package.json has an invalid workspaces field.')
82
+ }
83
+
84
+ async function appendPnpmWorkspace(project: UiProject, workspace: string): Promise<void> {
85
+ const target = pnpmWorkspacePath(project)
86
+ const source = await readOptional(target)
87
+ if (source === undefined) {
88
+ await writeFile(target, "packages:\n - '" + workspace + "'\n", 'utf8')
89
+ return
90
+ }
91
+ const document = parseDocument(source)
92
+ if (document.errors.length > 0) {
93
+ throw new UiError('UI_PROJECT_UNSUPPORTED', 'pnpm-workspace.yaml is not valid YAML.')
94
+ }
95
+ const packages = document.get('packages', true)
96
+ if (!isSeq(packages)) {
97
+ throw new UiError(
98
+ 'UI_PROJECT_UNSUPPORTED',
99
+ 'pnpm-workspace.yaml must declare a packages sequence.',
100
+ )
101
+ }
102
+ const values = packages.toJSON()
103
+ if (!Array.isArray(values) || !values.every((value) => typeof value === 'string')) {
104
+ throw new UiError(
105
+ 'UI_PROJECT_UNSUPPORTED',
106
+ 'pnpm-workspace.yaml must declare a packages sequence.',
107
+ )
108
+ }
109
+ if (!values.includes(workspace)) packages.add(workspace)
110
+ await writeFile(target, String(document), 'utf8')
111
+ }
112
+
113
+ async function hasDomainRegistryWorkspace(project: UiProject): Promise<boolean> {
114
+ if (!project.isAstraleDomain || !(await exists(domainRegistryPackagePath(project)))) return false
115
+ const registryManifest = JSON.parse(
116
+ await readFile(domainRegistryPackagePath(project), 'utf8'),
117
+ ) as Record<string, unknown>
118
+ if (
119
+ registryManifest.private !== true ||
120
+ typeof registryManifest.name !== 'string' ||
121
+ registryManifest.name === UI_PACKAGE ||
122
+ registryManifest.name === project.packageJson.name
123
+ ) {
124
+ return false
125
+ }
126
+ if (project.manager === 'pnpm') {
127
+ const source = await readOptional(pnpmWorkspacePath(project))
128
+ if (source === undefined) return false
129
+ const document = parseDocument(source)
130
+ if (document.errors.length > 0) return false
131
+ const packages = document.get('packages', true)
132
+ const values = isSeq(packages) ? packages.toJSON() : undefined
133
+ return Array.isArray(values) && values.includes('components')
134
+ }
135
+ const configured = project.packageJson.workspaces
136
+ const workspaces = Array.isArray(configured)
137
+ ? configured
138
+ : configured && typeof configured === 'object'
139
+ ? (configured as { packages?: unknown }).packages
140
+ : undefined
141
+ return Array.isArray(workspaces) && workspaces.includes('components')
142
+ }
143
+
144
+ async function writeDomainRegistryWorkspace(
145
+ project: UiProject,
146
+ manifest: Record<string, unknown>,
147
+ ): Promise<void> {
148
+ if (!project.isAstraleDomain) return
149
+ if (project.manager === 'pnpm') await appendPnpmWorkspace(project, 'components')
150
+ else appendWorkspace(manifest, 'components')
151
+ const target = domainRegistryPackagePath(project)
152
+ const existing = await readOptional(target)
153
+ const registryManifest = existing
154
+ ? (JSON.parse(existing) as Record<string, unknown>)
155
+ : { name: domainRegistryPackageName(manifest) }
156
+ if (registryManifest.private === false) {
157
+ throw new UiError(
158
+ 'UI_PROJECT_UNSUPPORTED',
159
+ 'The Astrale registry source workspace must remain private.',
160
+ )
161
+ }
162
+ if (
163
+ registryManifest.name === UI_PACKAGE ||
164
+ registryManifest.name === manifest.name ||
165
+ (registryManifest.name !== undefined && typeof registryManifest.name !== 'string')
166
+ ) {
167
+ throw new UiError(
168
+ 'UI_PROJECT_UNSUPPORTED',
169
+ 'The Astrale registry source workspace must have a distinct package name.',
170
+ )
171
+ }
172
+ await writeJson(target, {
173
+ ...registryManifest,
174
+ name: registryManifest.name ?? domainRegistryPackageName(manifest),
175
+ private: true,
176
+ type: registryManifest.type ?? 'module',
177
+ })
178
+ }
179
+
180
+ export type InitUiOptions = {
181
+ path?: string
182
+ preset?: UiPreset
183
+ version?: string
184
+ dryRun?: boolean
185
+ force?: boolean
186
+ install?: boolean
187
+ }
188
+
189
+ export async function initUi(
190
+ options: InitUiOptions,
191
+ dependencies: Dependencies = {},
192
+ ): Promise<Record<string, unknown>> {
193
+ const project = await discoverUiProject(options.path)
194
+ assertSupportedUiProject(project)
195
+ const preset = options.preset ?? 'astrale'
196
+ if (!UI_PRESETS.includes(preset)) {
197
+ throw new UiError('UI_PROJECT_UNSUPPORTED', 'Unknown UI preset: ' + preset)
198
+ }
199
+ if ((await exists(project.uiLockPath)) && !options.force) {
200
+ const lock = await readUiLock(project.uiLockPath)
201
+ const css = (await readOptional(project.cssPath)) ?? ''
202
+ const components = await readOptional(project.componentsPath)
203
+ .then((value) => (value ? (JSON.parse(value) as Record<string, unknown>) : undefined))
204
+ .catch(() => undefined)
205
+ const requestedVersion = options.version?.replace(/^v/u, '')
206
+ const desired =
207
+ (!requestedVersion || requestedVersion === lock.package.version) &&
208
+ (!options.preset || options.preset === lock.preset) &&
209
+ css.includes(UI_PACKAGE + '/theme.css') &&
210
+ css.includes(UI_PACKAGE + '/presets/' + lock.preset + '.css') &&
211
+ components?.style === 'base-nova' &&
212
+ (!project.isAstraleDomain || (await hasDomainRegistryWorkspace(project)))
213
+ if (!desired) {
214
+ throw new UiError(
215
+ 'UI_ITEM_CONFLICT',
216
+ 'Existing Astrale UI initialization differs from the requested state.',
217
+ 'Run astrale ui doctor, then repeat init with --force after reviewing the changes.',
218
+ )
219
+ }
220
+ return { status: 'unchanged', root: project.root, lock }
221
+ }
222
+ const release = await resolveUiRelease(options.version, dependencies.fetcher)
223
+ const cssRelative = projectRelative(project, project.cssPath)
224
+ const plan = {
225
+ status: options.dryRun ? 'planned' : 'initialized',
226
+ root: project.root,
227
+ package: UI_PACKAGE + '@' + release.version,
228
+ manager: project.manager,
229
+ preset,
230
+ files: [
231
+ 'package.json',
232
+ cssRelative,
233
+ 'components.json',
234
+ 'astrale-ui.lock.json',
235
+ ...(project.isAstraleDomain ? ['components/package.json'] : []),
236
+ ...(project.isAstraleDomain && project.manager === 'pnpm' ? ['pnpm-workspace.yaml'] : []),
237
+ ...(project.lockPath ? [projectRelative(project, project.lockPath)] : []),
238
+ ],
239
+ tooling: {
240
+ shadcn: release.compatibility.shadcn,
241
+ base: release.compatibility.base,
242
+ style: release.compatibility.style,
243
+ baseUi: release.compatibility.baseUi,
244
+ },
245
+ }
246
+ if (options.dryRun) return plan
247
+
248
+ if (project.isAstraleDomain) {
249
+ await assertSafePlannedTarget(project, 'components/package.json')
250
+ if (project.manager === 'pnpm') {
251
+ await assertSafePlannedTarget(project, 'pnpm-workspace.yaml')
252
+ }
253
+ }
254
+
255
+ const mutationPaths = [
256
+ project.packageJsonPath,
257
+ project.cssPath,
258
+ project.componentsPath,
259
+ project.uiLockPath,
260
+ ...(project.isAstraleDomain ? [domainRegistryPackagePath(project)] : []),
261
+ ...(project.isAstraleDomain && project.manager === 'pnpm' ? [pnpmWorkspacePath(project)] : []),
262
+ ...(project.lockPath ? [project.lockPath] : []),
263
+ ]
264
+ const snapshots = new Map<string, string | undefined>()
265
+ for (const target of mutationPaths) snapshots.set(target, await readOptional(target))
266
+
267
+ try {
268
+ const manifest = { ...project.packageJson }
269
+ manifest.dependencies = {
270
+ ...manifestDependencies(manifest),
271
+ [UI_PACKAGE]: release.version,
272
+ }
273
+ await writeDomainRegistryWorkspace(project, manifest)
274
+ await writeJson(project.packageJsonPath, manifest)
275
+
276
+ const currentCss = (await readOptional(project.cssPath)) ?? ''
277
+ const imports = [
278
+ "@import '" + UI_PACKAGE + "/theme.css';",
279
+ "@import '" + UI_PACKAGE + '/presets/' + preset + ".css';",
280
+ ]
281
+ const withoutAstrale = currentCss
282
+ .replace(
283
+ /^@import\s+['"]@astrale-os\/ui\/(?:theme\.css|presets\/[a-z-]+\.css)['"];?\s*$/gmu,
284
+ '',
285
+ )
286
+ .trimStart()
287
+ await mkdir(path.dirname(project.cssPath), { recursive: true })
288
+ await writeFile(project.cssPath, imports.join('\n') + '\n\n' + withoutAstrale, 'utf8')
289
+
290
+ const components = JSON.parse((await readOptional(project.componentsPath)) ?? '{}') as Record<
291
+ string,
292
+ unknown
293
+ >
294
+ await writeJson(project.componentsPath, {
295
+ $schema: 'https://ui.shadcn.com/schema.json',
296
+ ...components,
297
+ style: 'base-nova',
298
+ rsc: components.rsc ?? false,
299
+ tsx: components.tsx ?? true,
300
+ tailwind: {
301
+ config: '',
302
+ baseColor: 'neutral',
303
+ cssVariables: true,
304
+ prefix: '',
305
+ ...(components.tailwind as Record<string, unknown> | undefined),
306
+ css: cssRelative,
307
+ },
308
+ aliases: {
309
+ components: '@/components',
310
+ utils: '@/lib/utils',
311
+ ui: '@/components/ui',
312
+ lib: '@/lib',
313
+ hooks: '@/hooks',
314
+ ...(components.aliases as Record<string, unknown> | undefined),
315
+ },
316
+ })
317
+
318
+ if (options.install !== false) {
319
+ const result = await (dependencies.runner ?? defaultUiRunner)(
320
+ project.manager,
321
+ ['install'],
322
+ project.root,
323
+ )
324
+ if (result.code !== 0) {
325
+ throw new UiError(
326
+ 'UI_DEPENDENCY_INSTALL_FAILED',
327
+ project.manager + ' install failed.',
328
+ result.stderr.trim() || undefined,
329
+ )
330
+ }
331
+ }
332
+
333
+ const lock: UiLock = {
334
+ $schema:
335
+ 'https://raw.githubusercontent.com/astrale-os/ui/' +
336
+ release.ref +
337
+ '/schemas/ui-lock.schema.json',
338
+ version: 1,
339
+ package: { name: UI_PACKAGE, version: release.version },
340
+ registry: {
341
+ repository: 'astrale-os/ui',
342
+ ref: release.ref,
343
+ commit: release.commit,
344
+ },
345
+ tooling: {
346
+ shadcn: release.compatibility.shadcn,
347
+ base: 'base',
348
+ style: 'nova',
349
+ baseUi: release.compatibility.baseUi,
350
+ },
351
+ preset,
352
+ items: {},
353
+ }
354
+ await writeJson(project.uiLockPath, lock)
355
+ return { ...plan, lock }
356
+ } catch (error) {
357
+ for (const [target, value] of snapshots) {
358
+ if (value !== undefined) await writeFile(target, value, 'utf8')
359
+ else await rm(target, { force: true })
360
+ }
361
+ throw error
362
+ }
363
+ }
364
+
365
+ async function pinUiDependency(
366
+ project: UiProject,
367
+ version: string,
368
+ runner: UiRunner,
369
+ ): Promise<void> {
370
+ const manifest = JSON.parse(await readFile(project.packageJsonPath, 'utf8')) as Record<
371
+ string,
372
+ unknown
373
+ >
374
+ if (manifestDependencies(manifest)[UI_PACKAGE] === version) return
375
+ manifest.dependencies = { ...manifestDependencies(manifest), [UI_PACKAGE]: version }
376
+ await writeJson(project.packageJsonPath, manifest)
377
+ const result = await runner(project.manager, ['install'], project.root)
378
+ if (result.code !== 0) {
379
+ throw new UiError(
380
+ 'UI_DEPENDENCY_INSTALL_FAILED',
381
+ project.manager + ' install failed while restoring the locked UI release.',
382
+ result.stderr.trim() || undefined,
383
+ )
384
+ }
385
+ }
386
+
387
+ export async function listUi(
388
+ query: string | undefined,
389
+ options: { type?: string; limit?: number; version?: string },
390
+ dependencies: Dependencies = {},
391
+ ): Promise<UiRegistryItem[]> {
392
+ const release = await resolveUiRelease(options.version, dependencies.fetcher)
393
+ const needle = query?.trim().toLowerCase()
394
+ return release.registry.items
395
+ .filter((item) => {
396
+ if (options.type && !item.meta.canonicalAddress.startsWith(options.type + '/')) return false
397
+ if (!needle) return true
398
+ return [item.meta.canonicalAddress, item.name, item.title, item.description]
399
+ .filter(Boolean)
400
+ .some((value) => String(value).toLowerCase().includes(needle))
401
+ })
402
+ .slice(0, options.limit ?? 100)
403
+ }
404
+
405
+ export async function listLockedUi(
406
+ input: string | undefined,
407
+ dependencies: Dependencies = {},
408
+ ): Promise<UiRegistryItem[]> {
409
+ const project = await discoverUiProject(input)
410
+ const { release } = await lockedRelease(project, dependencies.fetcher)
411
+ return release.registry.items
412
+ }
413
+
414
+ async function lockedRelease(
415
+ project: UiProject,
416
+ fetcher?: typeof fetch,
417
+ ): Promise<{ lock: UiLock; release: UiRelease }> {
418
+ const lock = await readUiLock(project.uiLockPath)
419
+ const release = await readUiReleaseSnapshot(
420
+ {
421
+ version: lock.package.version,
422
+ ref: lock.registry.ref,
423
+ commit: lock.registry.commit,
424
+ },
425
+ fetcher,
426
+ )
427
+ return { lock, release }
428
+ }
429
+
430
+ export async function addUi(
431
+ addresses: string[],
432
+ options: { project?: string; dryRun?: boolean; overwrite?: boolean; yes?: boolean },
433
+ dependencies: Dependencies = {},
434
+ ): Promise<Record<string, unknown>> {
435
+ if (addresses.length === 0) {
436
+ throw new UiError('UI_ITEM_NOT_FOUND', 'No UI item was provided.')
437
+ }
438
+ const project = await discoverUiProject(options.project)
439
+ const { lock, release } = await lockedRelease(project, dependencies.fetcher)
440
+ const items = addresses.map((address) => findItem(release, address))
441
+ const itemDocuments = await Promise.all(
442
+ items.map((item) => readUiRegistryItem(release, item, dependencies.fetcher)),
443
+ )
444
+ if (options.overwrite && !options.yes) {
445
+ throw new UiError(
446
+ 'UI_LOCAL_CHANGES',
447
+ 'Replacing installed UI source requires explicit confirmation.',
448
+ 'Review the locally edited files, then repeat with both --overwrite and --yes.',
449
+ )
450
+ }
451
+ await rejectLocalChanges(project, lock, items, options.overwrite === true)
452
+ const targets = (
453
+ await Promise.all(
454
+ items.flatMap((item) =>
455
+ item.files
456
+ .filter((file) => file.target)
457
+ .map((file) => assertSafePlannedTarget(project, file.target!)),
458
+ ),
459
+ )
460
+ ).filter((target, index, all) => all.indexOf(target) === index)
461
+ const invocation = shadcnInvocation(project.manager, release.compatibility.shadcn, [
462
+ 'add',
463
+ ...items.map((item) => registryItemUrl(release, item.name)),
464
+ '--cwd',
465
+ project.root,
466
+ ...(options.dryRun ? ['--dry-run'] : []),
467
+ ...(options.overwrite ? ['--overwrite'] : []),
468
+ ...(options.yes ? ['--yes'] : []),
469
+ ])
470
+ const snapshots = new Map<string, string | undefined>()
471
+ if (!options.dryRun) {
472
+ for (const target of [project.packageJsonPath, project.lockPath!, ...targets]) {
473
+ snapshots.set(target, await readOptional(target))
474
+ }
475
+ }
476
+ let result: Awaited<ReturnType<UiRunner>>
477
+ try {
478
+ result = await (dependencies.runner ?? defaultUiRunner)(
479
+ invocation.file,
480
+ invocation.args,
481
+ project.root,
482
+ )
483
+ if (result.code !== 0) {
484
+ throw new UiError(
485
+ 'UI_TOOL_FAILED',
486
+ 'The pinned shadcn operation failed.',
487
+ result.stderr.trim(),
488
+ )
489
+ }
490
+ if (!options.dryRun) {
491
+ for (const target of targets) {
492
+ if (!(await exists(target))) {
493
+ throw new UiError('UI_TOOL_FAILED', 'The pinned shadcn operation omitted an item file.')
494
+ }
495
+ }
496
+ await pinUiDependency(project, lock.package.version, dependencies.runner ?? defaultUiRunner)
497
+ }
498
+ } catch (error) {
499
+ for (const [target, previous] of snapshots) {
500
+ if (previous === undefined) await rm(target, { force: true })
501
+ else await writeFile(target, previous, 'utf8')
502
+ }
503
+ throw error
504
+ }
505
+ if (options.dryRun) {
506
+ return {
507
+ status: 'planned',
508
+ items: items.map((item) => item.meta.canonicalAddress),
509
+ sources: itemDocuments.map((item) => ({
510
+ address: item.meta.canonicalAddress,
511
+ dependencies: item.dependencies ?? [],
512
+ files: item.files.map((file) => file.target).filter(Boolean),
513
+ })),
514
+ command: [invocation.file, ...invocation.args],
515
+ output: result.stdout,
516
+ }
517
+ }
518
+
519
+ try {
520
+ for (const [index, item] of items.entries()) {
521
+ const itemDocument = itemDocuments[index]!
522
+ const files: Record<string, string> = {}
523
+ for (const file of item.files) {
524
+ if (!file.target) continue
525
+ const target = await safeTarget(project, file.target)
526
+ files[projectRelative(project, target)] = digest(await readFile(target))
527
+ }
528
+ lock.items[item.meta.canonicalAddress] = {
529
+ address: item.meta.canonicalAddress,
530
+ sourceDigest: digest(JSON.stringify(itemDocument)),
531
+ files,
532
+ }
533
+ }
534
+ await writeJson(project.uiLockPath, lock)
535
+ } catch (error) {
536
+ for (const [target, previous] of snapshots) {
537
+ if (previous === undefined) await rm(target, { force: true })
538
+ else await writeFile(target, previous, 'utf8')
539
+ }
540
+ throw error
541
+ }
542
+ return {
543
+ status: 'installed',
544
+ items: items.map((item) => item.meta.canonicalAddress),
545
+ files: Object.fromEntries(
546
+ items.map((item) => [
547
+ item.meta.canonicalAddress,
548
+ lock.items[item.meta.canonicalAddress]?.files,
549
+ ]),
550
+ ),
551
+ }
552
+ }
553
+
554
+ export async function doctorUi(
555
+ input?: string,
556
+ ): Promise<{ healthy: boolean; checks: Array<{ check: string; ok: boolean; detail?: string }> }> {
557
+ const project = await discoverUiProject(input)
558
+ const checks: Array<{ check: string; ok: boolean; detail?: string }> = []
559
+ let lock: UiLock | undefined
560
+ try {
561
+ lock = parseUiLock(JSON.parse(await readFile(project.uiLockPath, 'utf8')))
562
+ checks.push({ check: 'lock', ok: true })
563
+ } catch (error) {
564
+ checks.push({
565
+ check: 'lock',
566
+ ok: false,
567
+ detail: error instanceof Error ? error.message : String(error),
568
+ })
569
+ }
570
+ const dependencies = manifestDependencies(project.packageJson)
571
+ checks.push({
572
+ check: 'package',
573
+ ok: typeof dependencies[UI_PACKAGE] === 'string',
574
+ detail: dependencies[UI_PACKAGE],
575
+ })
576
+ const css = (await readOptional(project.cssPath)) ?? ''
577
+ checks.push({ check: 'theme', ok: css.includes(UI_PACKAGE + '/theme.css') })
578
+ checks.push({
579
+ check: 'preset',
580
+ ok: UI_PRESETS.some((preset) => css.includes(UI_PACKAGE + '/presets/' + preset + '.css')),
581
+ })
582
+ checks.push({ check: 'components', ok: await exists(project.componentsPath) })
583
+ if (lock) {
584
+ for (const item of Object.values(lock.items)) {
585
+ for (const [file, expected] of Object.entries(item.files)) {
586
+ const actual = await readFile(path.join(project.root, file))
587
+ .then(digest)
588
+ .catch(() => '')
589
+ checks.push({ check: 'item:' + item.address + ':' + file, ok: actual === expected })
590
+ }
591
+ }
592
+ }
593
+ return { healthy: checks.every((check) => check.ok), checks }
594
+ }
595
+
596
+ export async function applyPreset(
597
+ preset: UiPreset,
598
+ options: { project?: string; dryRun?: boolean },
599
+ ): Promise<Record<string, unknown>> {
600
+ if (!UI_PRESETS.includes(preset)) {
601
+ throw new UiError('UI_ITEM_NOT_FOUND', 'Unknown preset: ' + preset)
602
+ }
603
+ const project = await discoverUiProject(options.project)
604
+ const lock = await readUiLock(project.uiLockPath)
605
+ const css = (await readOptional(project.cssPath)) ?? ''
606
+ const next = css.replace(
607
+ /@astrale-os\/ui\/presets\/[a-z-]+\.css/gu,
608
+ '@astrale-os/ui/presets/' + preset + '.css',
609
+ )
610
+ if (next === css && !css.includes('@astrale-os/ui/presets/')) {
611
+ throw new UiError('UI_CONFIG_MISSING', 'No Astrale preset import was found.')
612
+ }
613
+ if (!options.dryRun) {
614
+ await writeFile(project.cssPath, next, 'utf8')
615
+ lock.preset = preset
616
+ await writeJson(project.uiLockPath, lock)
617
+ }
618
+ return {
619
+ status: options.dryRun ? 'planned' : 'applied',
620
+ preset,
621
+ file: projectRelative(project, project.cssPath),
622
+ }
623
+ }
624
+
625
+ function findItem(release: UiRelease, address: string): UiRegistryItem {
626
+ const normalized = address.replace(/^@astrale\//u, '')
627
+ const exact = release.registry.items.find(
628
+ (item) => item.meta.canonicalAddress === normalized || item.name === normalized,
629
+ )
630
+ if (exact) return exact
631
+ const shorthand = release.registry.items.filter((item) =>
632
+ item.meta.canonicalAddress.endsWith('/' + normalized),
633
+ )
634
+ if (shorthand.length === 1) return shorthand[0]!
635
+ throw new UiError(
636
+ 'UI_ITEM_NOT_FOUND',
637
+ shorthand.length > 1
638
+ ? 'UI item "' + address + '" is ambiguous.'
639
+ : 'UI item "' + address + '" was not found.',
640
+ shorthand.length > 1
641
+ ? 'Use one of: ' + shorthand.map((item) => item.meta.canonicalAddress).join(', ')
642
+ : 'Run astrale ui list to discover canonical addresses.',
643
+ )
644
+ }
645
+
646
+ async function rejectLocalChanges(
647
+ project: UiProject,
648
+ lock: UiLock,
649
+ items: UiRegistryItem[],
650
+ overwrite: boolean,
651
+ ): Promise<void> {
652
+ if (overwrite) return
653
+ for (const item of items) {
654
+ const installed = lock.items[item.meta.canonicalAddress]
655
+ if (!installed) continue
656
+ for (const [file, expected] of Object.entries(installed.files)) {
657
+ const actual = await readFile(path.join(project.root, file))
658
+ .then(digest)
659
+ .catch(() => '')
660
+ if (actual !== expected) {
661
+ throw new UiError(
662
+ 'UI_LOCAL_CHANGES',
663
+ 'Installed UI file has local changes: ' + file,
664
+ 'Review the file, then repeat add with explicit --overwrite --yes.',
665
+ )
666
+ }
667
+ }
668
+ }
669
+ }
670
+
671
+ async function safeTarget(project: UiProject, relative: string): Promise<string> {
672
+ if (path.isAbsolute(relative) || relative.split(/[\\/]/u).includes('..')) {
673
+ throw new UiError('UI_LOCK_INVALID', 'Unsafe registry target: ' + relative)
674
+ }
675
+ const target = path.resolve(project.root, relative)
676
+ projectRelative(project, target)
677
+ const parent = await realpath(path.dirname(target))
678
+ const root = await realpath(project.root)
679
+ if (parent !== root && !parent.startsWith(root + path.sep)) {
680
+ throw new UiError('UI_LOCK_INVALID', 'Registry target escapes through a symlink: ' + relative)
681
+ }
682
+ if ((await exists(target)) && (await lstat(target)).isSymbolicLink()) {
683
+ throw new UiError('UI_LOCK_INVALID', 'Registry target is a symlink: ' + relative)
684
+ }
685
+ return target
686
+ }
687
+
688
+ async function assertSafePlannedTarget(project: UiProject, relative: string): Promise<string> {
689
+ if (path.isAbsolute(relative) || relative.split(/[\\/]/u).includes('..')) {
690
+ throw new UiError('UI_LOCK_INVALID', 'Unsafe registry target: ' + relative)
691
+ }
692
+ const target = path.resolve(project.root, relative)
693
+ projectRelative(project, target)
694
+ const root = await realpath(project.root)
695
+ const physicalTarget = path.resolve(root, path.relative(project.root, target))
696
+ let current = root
697
+ for (const segment of path.relative(root, physicalTarget).split(path.sep)) {
698
+ current = path.join(current, segment)
699
+ if (!(await exists(current))) break
700
+ if ((await lstat(current)).isSymbolicLink()) {
701
+ throw new UiError('UI_LOCK_INVALID', 'Registry target traverses a symlink: ' + relative)
702
+ }
703
+ }
704
+ return target
705
+ }
706
+
707
+ async function writeJson(target: string, value: unknown): Promise<void> {
708
+ await mkdir(path.dirname(target), { recursive: true })
709
+ await writeFile(target, JSON.stringify(value, null, 2) + '\n', 'utf8')
710
+ }