@atom63/cli 0.0.0-stage → 0.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,342 @@
1
+ /**
2
+ * Templates in the agent index: `template`, `copy` and `build`. Pure over the
3
+ * index except `copy`, which writes the template's files into a directory.
4
+ */
5
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
6
+ import path from 'node:path'
7
+
8
+ import { AtomError, closest, groundFor, queryTerms, score, search } from './core.mjs'
9
+ import { rules } from './rules.mjs'
10
+
11
+ export const templateKinds = ['page', 'block']
12
+
13
+ function findTemplate(index, id) {
14
+ const found = index.templates.find(template => template.id === id)
15
+ if (!found) {
16
+ throw new AtomError(
17
+ 'template.not_found',
18
+ `No template "${id}".`,
19
+ closest(
20
+ id,
21
+ index.templates.map(template => template.id)
22
+ )
23
+ )
24
+ }
25
+ return found
26
+ }
27
+
28
+ const summaryOf = template => ({
29
+ id: template.id,
30
+ kind: template.kind,
31
+ title: template.title,
32
+ description: template.description,
33
+ category: template.category,
34
+ readiness: template.readiness,
35
+ })
36
+
37
+ /** Score a template against a query; `search` scores the `template` kind the same way. */
38
+ function templateScore(query, terms, template) {
39
+ return score(query, terms, {
40
+ names: [template.id, template.title],
41
+ keywords: [...template.tags, template.category, ...template.componentsUsed],
42
+ prose: template.description,
43
+ })
44
+ }
45
+
46
+ /** With no id, every template (pages first); with one, its source and what it uses. */
47
+ export function template(index, id, { kind } = {}) {
48
+ if (kind && !templateKinds.includes(kind)) {
49
+ throw new AtomError('usage.invalid_flag', `--kind must be one of: ${templateKinds.join(', ')}`)
50
+ }
51
+ if (!id) {
52
+ const templates = index.templates.filter(entry => !kind || entry.kind === kind)
53
+ return { type: 'template.list', data: { templates: templates.map(summaryOf) } }
54
+ }
55
+ const found = findTemplate(index, id)
56
+ const entries = withBlocks(index, found)
57
+ return {
58
+ type: 'template.detail',
59
+ data: {
60
+ ...summaryOf(found),
61
+ tags: found.tags,
62
+ componentsUsed: found.componentsUsed,
63
+ blocksUsed: found.blocksUsed,
64
+ files: found.files,
65
+ // Templates ship in no package, so the detail carries every file a paste needs.
66
+ blockFiles: entries.slice(1).flatMap(entry => entry.files),
67
+ packages: [...new Set(entries.flatMap(entry => entry.packages))].sort(),
68
+ registry: `npx shadcn@latest add https://system.atom63.io/r/${found.id}.json`,
69
+ next: `atom63 copy ${found.id} <dir>`,
70
+ },
71
+ }
72
+ }
73
+
74
+ /** The template and every block it uses, transitively, each once. */
75
+ function withBlocks(index, root) {
76
+ const seen = new Map()
77
+ const visit = entry => {
78
+ if (seen.has(entry.id)) return
79
+ seen.set(entry.id, entry)
80
+ for (const blockId of entry.blocksUsed) visit(findTemplate(index, blockId))
81
+ }
82
+ visit(root)
83
+ return [...seen.values()]
84
+ }
85
+
86
+ /**
87
+ * Write a template and the blocks it uses into `dir`, keeping the
88
+ * `pages/<id>/` and `blocks/<id>/` layout so their relative imports still
89
+ * resolve. Existing files are left alone unless `force` is set.
90
+ */
91
+ export function copy(index, id, dir, { force = false, cwd = process.cwd() } = {}) {
92
+ const root = findTemplate(index, id)
93
+ const target = path.resolve(cwd, dir)
94
+ const written = []
95
+ const skipped = []
96
+ for (const entry of withBlocks(index, root)) {
97
+ for (const file of entry.files) {
98
+ const destination = path.join(target, file.path)
99
+ const relative = path.relative(cwd, destination)
100
+ if (existsSync(destination) && !force) {
101
+ skipped.push(relative)
102
+ continue
103
+ }
104
+ mkdirSync(path.dirname(destination), { recursive: true })
105
+ writeFileSync(destination, file.source)
106
+ written.push(relative)
107
+ }
108
+ }
109
+ const packages = [...new Set(withBlocks(index, root).flatMap(entry => entry.packages))].sort()
110
+ const main = root.files.find(file => file.path.endsWith(`/${root.id}.tsx`))
111
+ return {
112
+ type: 'template.copied',
113
+ data: {
114
+ id: root.id,
115
+ directory: path.relative(cwd, target) || '.',
116
+ written,
117
+ skipped,
118
+ packages,
119
+ next: [
120
+ `Install what the files import: ${packages.join(', ')}.`,
121
+ `Import it from ./${path.relative(cwd, path.join(target, main.path)).replace(/\.tsx$/, '')}, then replace the sample data and copy with your product's.`,
122
+ ...(skipped.length > 0
123
+ ? ['Some files already existed and were left alone; pass --force to overwrite them.']
124
+ : []),
125
+ ],
126
+ },
127
+ }
128
+ }
129
+
130
+ /* The frame and foundation every page starts from. */
131
+ const foundation = [
132
+ { name: 'Atom63Theme', from: '@atom63/ui-react', use: 'The theme boundary at the app root.' },
133
+ {
134
+ name: 'Page',
135
+ from: '@atom63/ui-react/layout',
136
+ use: 'The main landmark, when no app shell owns it.',
137
+ },
138
+ { name: 'Container', from: '@atom63/ui-react/layout', use: 'The content width and inset.' },
139
+ { name: 'Section', from: '@atom63/ui-react/layout', use: 'Rhythm between page regions.' },
140
+ {
141
+ name: 'SectionHeader',
142
+ from: '@atom63/ui-react/layout',
143
+ use: 'Headings with their descriptions.',
144
+ },
145
+ ]
146
+
147
+ const playbook = [
148
+ 'Search for the closest page: `atom63 build <idea>` or `atom63 template --kind page`.',
149
+ 'Copy it into your project with `atom63 copy <template> <dir>` and read what it uses.',
150
+ 'Adapt it with components from the kit: `atom63 component <slug>` for each one you add.',
151
+ 'Keep every color, space and radius on tokens, and follow `atom63 rules`.',
152
+ 'Check the result at a phone and a desktop width, in light and dark mode.',
153
+ ]
154
+
155
+ /* Words that mark an idea as a phone screen built for the web. */
156
+ const phoneWords = new Set(['android', 'iphone', 'mobile', 'phone', 'smartphone'])
157
+
158
+ /** Whether an idea is a phone screen: a phone word or a phone width (320–439 px), not SwiftUI. */
159
+ export function isPhoneIdea(idea) {
160
+ const terms = queryTerms(idea).map(({ term }) => term)
161
+ if (terms.includes('swiftui')) return false
162
+ return terms.some(term => phoneWords.has(term)) || /\b(3[2-9]\d|4[0-3]\d) ?px\b/i.test(idea)
163
+ }
164
+
165
+ /* What a phone idea is told to build on: the app-view template's phone layout. */
166
+ const phoneScreen = {
167
+ template: 'app-view',
168
+ use: 'Use AppView layout="phone" for the screen: edge to edge with no card or inset, safe-area aware, the top bar optional, and the tab bar docked at the bottom. It sets phone-sized type and controls inside it (data-a63-form-factor="phone": body 17px, subhead 15px, footnote 13px, 44px controls), so keep rows and labels on the defaults or the text roles (text-body, text-subhead, text-footnote) instead of shrinking them with text-sm or text-xs. Only the main region scrolls, so its last row stays visible above the tab bar. On a screen with no tab bar (a chat, a detail or a checkout step), leave tabBar out and dock the composer or action bar as bottomBar. The default layout ("window") is a padded desktop window with a rounded main card; do not use it on a phone.',
169
+ files:
170
+ 'AppView ships in no package: it is the app-view page template. Paste pages/app-view/app-view.tsx and blocks/tab-bar/tab-bar.tsx, which `atom63 template app-view` prints in full (or run `atom63 copy app-view src`). Its AppViewPhonePage is the phone sample to start from.',
171
+ imports: [
172
+ "import { House, Search } from 'lucide-react'",
173
+ "import { AppView } from './pages/app-view/app-view'",
174
+ "import { TabBar } from './blocks/tab-bar/tab-bar'",
175
+ ],
176
+ snippet: [
177
+ '<AppView',
178
+ ' layout="phone"',
179
+ ' tabBar={',
180
+ ' <TabBar',
181
+ ' items={[',
182
+ " { current: true, href: '#home', icon: <House aria-hidden />, label: 'Home' },",
183
+ " { href: '#search', icon: <Search aria-hidden />, label: 'Search' },",
184
+ ' ]}',
185
+ ' />',
186
+ ' }',
187
+ '>',
188
+ ' {/* No topBar: the first block pads itself for the status bar. */}',
189
+ ' <div className="flex flex-col gap-4 pt-[env(safe-area-inset-top)]">…</div>',
190
+ '</AppView>',
191
+ ].join('\n'),
192
+ next: 'atom63 template app-view',
193
+ }
194
+
195
+ /* Words that mark an idea as showing a money amount as its hero number. */
196
+ const amountWords = new Set([
197
+ 'amount',
198
+ 'balance',
199
+ 'bank',
200
+ 'banking',
201
+ 'checkout',
202
+ 'fintech',
203
+ 'money',
204
+ 'payment',
205
+ 'price',
206
+ 'pricing',
207
+ 'total',
208
+ 'wallet',
209
+ ])
210
+
211
+ /** Whether an idea shows a money amount: a balance, a price, a total or an amount to send. */
212
+ export function isAmountIdea(idea) {
213
+ return queryTerms(idea).some(({ term, weight }) => weight === 1 && amountWords.has(term))
214
+ }
215
+
216
+ /* How an amount idea is told to draw its hero number. */
217
+ const displayAmount = {
218
+ component: 'amount',
219
+ use: 'Draw the hero number (a balance, a price, the amount to send) with Amount: the display text role (size="md", 40px; size="lg" for display-large, 56px), the cents at half size and raised, tabular figures, formatted for the locale and read as one label. Where the reference keeps the smaller cents on the baseline (a Revolut-style balance), pass fraction="baseline" (iOS: fraction: .baseline). Keep amounts in list rows at body size with tabular-nums. Without the component, put the whole amount in one text-display tabular-nums span and wrap the fraction in amount-fraction (amount-fraction-baseline for cents on the baseline). iOS: AtomAmountText.',
220
+ imports: ["import { Amount } from '@atom63/ui-react'"],
221
+ snippet: [
222
+ '<p className="text-footnote text-muted-foreground">Main account</p>',
223
+ '<Amount currency="USD" size="lg" strong value={13250.75} />',
224
+ '',
225
+ '{/* The same without the component: */}',
226
+ '<span className="text-display tabular-nums">',
227
+ ' $13,250<span className="amount-fraction">.75</span>',
228
+ '</span>',
229
+ ].join('\n'),
230
+ next: 'atom63 component amount',
231
+ }
232
+
233
+ /* Words that mark an idea as a dense product screen: rows of data to scan and act on. */
234
+ const denseWords = new Set([
235
+ 'admin',
236
+ 'backlog',
237
+ 'crm',
238
+ 'dashboard',
239
+ 'dashboards',
240
+ 'datagrid',
241
+ 'email',
242
+ 'files',
243
+ 'inbox',
244
+ 'inboxes',
245
+ 'issue',
246
+ 'issues',
247
+ 'mail',
248
+ 'spreadsheet',
249
+ 'table',
250
+ 'tables',
251
+ 'ticket',
252
+ 'tickets',
253
+ 'tracker',
254
+ 'triage',
255
+ ])
256
+
257
+ /** Whether an idea is a dense desktop product screen: a table, an inbox, an issue tracker, an admin dashboard or a file list. */
258
+ export function isDenseIdea(idea) {
259
+ if (isPhoneIdea(idea)) return false
260
+ const terms = queryTerms(idea).filter(({ weight }) => weight === 1)
261
+ return (
262
+ terms.some(({ term }) => denseWords.has(term)) ||
263
+ /\bfile (list|browser|manager|explorer)s?\b/i.test(idea)
264
+ )
265
+ }
266
+
267
+ /* How a dense product screen is told to use compact density. */
268
+ const compactDensity = {
269
+ use: 'A dense product screen (a table, an inbox, an issue tracker, an admin dashboard, a file list) uses compact density: wrap the screen, or the dense region of it, in <UIProvider density="compact">. Compact sets the space unit to 3.5px instead of 4px, so the space steps, gaps, paddings and control heights all scale once by 0.875 (32px controls become 28px, a 16px gap 14px); text keeps its size. For the whole app, set data-a63-density="compact" on <html> instead.',
270
+ imports: ["import { UIProvider } from '@atom63/ui-react'"],
271
+ snippet: [
272
+ '<UIProvider density="compact">',
273
+ ' {/* the table, inbox or list */}',
274
+ '</UIProvider>',
275
+ '',
276
+ '// The whole app:',
277
+ "document.documentElement.dataset.a63Density = 'compact'",
278
+ ].join('\n'),
279
+ next: 'atom63 docs foundation-personalization',
280
+ }
281
+
282
+ /**
283
+ * A composition kit for an idea: the closest pages and blocks, the components
284
+ * the idea names, the always-on foundation and the rules. With no idea, the
285
+ * playbook for building with the kit.
286
+ */
287
+ export function build(index, idea) {
288
+ if (!idea?.trim()) {
289
+ return { type: 'build.playbook', data: { steps: playbook, foundation } }
290
+ }
291
+ const terms = queryTerms(idea)
292
+ const ranked = index.templates
293
+ .map(entry => ({ entry, value: templateScore(idea, terms, entry) }))
294
+ // A name, tag or component match (8 or more); a word in the description alone is noise.
295
+ .filter(({ value }) => value >= 8)
296
+ .sort((left, right) => right.value - left.value || left.entry.id.localeCompare(right.entry.id))
297
+ const pick = (kind, limit) =>
298
+ ranked
299
+ .filter(({ entry }) => entry.kind === kind)
300
+ .slice(0, limit)
301
+ .map(({ entry }) => ({ ...summaryOf(entry), next: `atom63 copy ${entry.id} <dir>` }))
302
+ const phone = isPhoneIdea(idea)
303
+ // A phone idea always gets the app-view page and the tab-bar block first.
304
+ const lead = (kind, limit, id) =>
305
+ [
306
+ { ...summaryOf(findTemplate(index, id)), next: `atom63 copy ${id} <dir>` },
307
+ ...pick(kind, limit).filter(entry => entry.id !== id),
308
+ ].slice(0, limit)
309
+ const pages = phone ? lead('page', 3, 'app-view') : pick('page', 3)
310
+ const blocks = phone ? lead('block', 5, 'tab-bar') : pick('block', 5)
311
+ // What the closest templates are built from comes first, then what the idea names.
312
+ const bySlug = new Map(index.components.map(entry => [entry.slug, entry]))
313
+ const used = [pages[0], ...blocks]
314
+ .filter(Boolean)
315
+ .flatMap(entry => findTemplate(index, entry.id).componentsUsed)
316
+ .filter(slug => bySlug.has(slug))
317
+ const found = search(index, idea, { kind: 'component', limit: 6 }).data.results
318
+ const named = found.map(result => result.id)
319
+ // A topic note ("track list" → Table variant="plain") replaces the summary.
320
+ const summaries = new Map(found.map(result => [result.id, result.summary]))
321
+ const components = [...new Set([...used, ...named])].slice(0, 8).map(slug => ({
322
+ slug,
323
+ summary: summaries.get(slug) ?? bySlug.get(slug).summary,
324
+ next: `atom63 component ${slug}`,
325
+ }))
326
+ const ground = groundFor(idea)
327
+ return {
328
+ type: 'build.kit',
329
+ data: {
330
+ idea,
331
+ ...(phone ? { phone: phoneScreen } : {}),
332
+ ...(isAmountIdea(idea) ? { amount: displayAmount } : {}),
333
+ ...(isDenseIdea(idea) ? { density: compactDensity } : {}),
334
+ pages,
335
+ blocks,
336
+ components,
337
+ ...(ground ? { ground } : {}),
338
+ foundation,
339
+ rules: rules.map(rule => rule.rule),
340
+ },
341
+ }
342
+ }