sellwavy-cli 0.0.0-stage → 0.1.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,253 @@
1
+ /**
2
+ * A Sellwavy store's pages as sections, and as files. No Node or browser
3
+ * APIs in here: the CLI uses it, and so does the dashboard's code editor
4
+ * (imported as @cli/sections.mjs), so a section is named, laid out, checked
5
+ * and merged the same way wherever it is edited.
6
+ *
7
+ * A store built with Sellwavy AI is a list of sections, each a piece of HTML
8
+ * with Tailwind classes: { key, label, html, page }. "header" and "footer"
9
+ * are shared by every page (page "global"); the rest belong to one of the
10
+ * pages below. This mirrors src/lib/ai/site-code.ts on the server, which
11
+ * cleans every section again when it is saved.
12
+ */
13
+
14
+ export const PAGES = ['home', 'products', 'product', 'about', 'contact']
15
+
16
+ export const PAGE_NAMES = {
17
+ global: 'Header & footer',
18
+ home: 'Home page',
19
+ products: 'All products page',
20
+ product: 'Product page',
21
+ about: 'About page',
22
+ contact: 'Contact page',
23
+ }
24
+
25
+ export const GLOBAL_KEYS = ['header', 'footer']
26
+ export const MAX_SECTIONS = 60
27
+ export const MAX_HTML = 40_000
28
+
29
+ export function normalizeKey(key) {
30
+ return String(key ?? '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-').slice(0, 40)
31
+ }
32
+
33
+ export function pageOf(s) {
34
+ if (GLOBAL_KEYS.includes(s.key)) return 'global'
35
+ return PAGES.includes(s.page) ? s.page : 'home'
36
+ }
37
+
38
+ /** "faq-block" → "Faq block": a name for a section nobody named. */
39
+ export function labelFor(key) {
40
+ return key.replace(/-+/g, ' ').trim().replace(/^\w/, ch => ch.toUpperCase())
41
+ }
42
+
43
+ /** A section's id across the whole store: "home/hero", "global/header". */
44
+ export function sectionId(s) {
45
+ return `${pageOf(s)}/${s.key}`
46
+ }
47
+
48
+ /** Sections as the server stores them, tidied: page set, html trimmed. */
49
+ export function normalizeSections(input) {
50
+ if (!Array.isArray(input)) return []
51
+ return input
52
+ .filter(s => s && typeof s.key === 'string' && typeof s.html === 'string')
53
+ .map(s => ({ key: s.key, label: s.label || s.key, html: s.html.trim(), page: pageOf(s) }))
54
+ }
55
+
56
+ /** Header and footer first, then each page in order, each page's sections as they stand. */
57
+ export function orderSections(sections) {
58
+ const out = []
59
+ for (const key of GLOBAL_KEYS) out.push(...sections.filter(s => pageOf(s) === 'global' && s.key === key))
60
+ for (const page of PAGES) out.push(...sections.filter(s => pageOf(s) === page))
61
+ return out
62
+ }
63
+
64
+ /** Whether two lists of sections are the same pages. */
65
+ export function sameSite(a, b) {
66
+ const plain = list => JSON.stringify(orderSections(normalizeSections(list)).map(s => [pageOf(s), s.key, s.label, s.html]))
67
+ return plain(a) === plain(b)
68
+ }
69
+
70
+ /** What changed from `before` to `after`, by section. */
71
+ export function diffSections(before, after) {
72
+ const was = new Map(before.map(s => [sectionId(s), s]))
73
+ const now = new Map(after.map(s => [sectionId(s), s]))
74
+ const added = [...now.keys()].filter(k => !was.has(k))
75
+ const removed = [...was.keys()].filter(k => !now.has(k))
76
+ const changed = [...now.keys()].filter(k => was.has(k) && (was.get(k).html !== now.get(k).html || was.get(k).label !== now.get(k).label))
77
+ const order = list => orderSections(list).map(sectionId).join('|')
78
+ const reordered = !added.length && !removed.length && order(before) !== order(after)
79
+ return { added, removed, changed, reordered }
80
+ }
81
+
82
+ /**
83
+ * Three-way merge, section by section, of local changes and changes made on
84
+ * the store since the last pull (an owner editing in the visual editor while
85
+ * an agent works on files). A section changed on only one side takes that
86
+ * side. One changed differently on both is a conflict, named in `conflicts`:
87
+ * left out of the result, unless `prefer` says which side wins.
88
+ */
89
+ export function mergeSite(base, local, remote, { prefer } = {}) {
90
+ const B = new Map(base.map(s => [sectionId(s), s]))
91
+ const L = new Map(local.map(s => [sectionId(s), s]))
92
+ const R = new Map(remote.map(s => [sectionId(s), s]))
93
+ const same = (a, b) => (!a && !b) || (!!a && !!b && a.html === b.html && a.label === b.label)
94
+ const picked = new Map()
95
+ const conflicts = []
96
+ const fromRemote = []
97
+
98
+ for (const k of new Set([...B.keys(), ...L.keys(), ...R.keys()])) {
99
+ const b = B.get(k), l = L.get(k), r = R.get(k)
100
+ const localChanged = !same(l, b)
101
+ const remoteChanged = !same(r, b)
102
+ if (!localChanged) {
103
+ if (r) picked.set(k, r)
104
+ if (remoteChanged) fromRemote.push(k)
105
+ } else if (!remoteChanged || same(l, r)) {
106
+ if (l) picked.set(k, l)
107
+ } else {
108
+ conflicts.push(k)
109
+ const win = prefer === 'local' ? l : prefer === 'remote' ? r : null
110
+ if (win) picked.set(k, win)
111
+ }
112
+ }
113
+
114
+ // Order, page by page: if the local side reordered the page, its order
115
+ // wins; otherwise the store's. Sections only the other side has are slotted
116
+ // in after the section they followed there.
117
+ const result = []
118
+ for (const page of ['global', ...PAGES]) {
119
+ const ids = list => list.filter(s => pageOf(s) === page).map(sectionId)
120
+ const bo = ids(base), lo = ids(local), ro = ids(remote)
121
+ const shared = (a, b) => a.filter(x => b.includes(x)).join('|')
122
+ const localReordered = shared(lo, bo) !== shared(bo, lo)
123
+ const [primary, secondary] = localReordered ? [lo, ro] : [ro, lo]
124
+ const order = primary.slice()
125
+ secondary.forEach((x, i) => {
126
+ if (order.includes(x)) return
127
+ const prev = secondary.slice(0, i).reverse().find(p => order.includes(p))
128
+ order.splice(prev ? order.indexOf(prev) + 1 : 0, 0, x)
129
+ })
130
+ for (const x of order) if (picked.has(x)) result.push(picked.get(x))
131
+ }
132
+ return { sections: orderSections(result), conflicts, fromRemote }
133
+ }
134
+
135
+ // ── Checks ────────────────────────────────────────────────────────────────
136
+
137
+ /**
138
+ * Things the server's cleaner will remove or ignore, so whoever wrote the
139
+ * code (a person or an agent) hears about it before it silently vanishes.
140
+ */
141
+ export function lintSection(s) {
142
+ const problems = []
143
+ const html = s.html
144
+ const has = re => re.test(html)
145
+ if (has(/<script\b/i)) problems.push('<script> is removed: interactions only through the data-sw-* hooks and CSS')
146
+ if (has(/<style\b/i)) problems.push('<style> is removed: style with Tailwind classes (or style="")')
147
+ if (has(/<(form|input|textarea|select)\b/i)) problems.push('<form>, <input>, <textarea> and <select> are removed: there is nowhere to send them')
148
+ if (has(/<iframe\b/i)) problems.push('<iframe> is removed: upload the video and use <video src="...">')
149
+ if (has(/\son[a-z]+\s*=/i)) problems.push('inline event handlers (onclick=...) are removed')
150
+ if (has(/javascript:/i)) problems.push('javascript: links are removed')
151
+ if (has(/\bclass="[^"]*\bfont-(sans|serif|mono|\[)/)) problems.push('font-sans/serif/mono/[...] classes are dropped: the store’s fonts are set in the editor')
152
+ if (html.length > MAX_HTML) problems.push(`longer than ${MAX_HTML.toLocaleString()} characters: the end is cut off`)
153
+ const page = pageOf(s)
154
+ if (page === 'product' && /data-sw-gallery/.test(html) && !/<img\b[^>]*\{\{\s*image\.url\s*\}\}/.test(html)) {
155
+ problems.push('data-sw-gallery should hold ONE <img src="{{image.url}}">, repeated per photo')
156
+ }
157
+ return problems
158
+ }
159
+
160
+ /** Checks a whole store's sections: per-section problems plus whole-site ones. */
161
+ export function lintSite(sections) {
162
+ const out = []
163
+ for (const s of sections) {
164
+ for (const p of lintSection(s)) out.push({ section: sectionId(s), problem: p })
165
+ }
166
+ if (sections.length > MAX_SECTIONS) out.push({ section: '*', problem: `${sections.length} sections: only the first ${MAX_SECTIONS} are kept` })
167
+ const product = sections.filter(s => pageOf(s) === 'product')
168
+ if (product.length && !product.some(s => /data-sw-buy/.test(s.html))) {
169
+ out.push({ section: 'product', problem: 'no <div data-sw-buy></div>: shoppers would have no Add to cart on the product page' })
170
+ }
171
+ return out
172
+ }
173
+
174
+ // ── As files ──────────────────────────────────────────────────────────────
175
+ //
176
+ // header.html, footer.html shared by every page
177
+ // <page>/<NN>-<key>.html a page's sections, in order
178
+ //
179
+ // The first line of each file names the section for the editor:
180
+ // <!-- section: Hero -->
181
+
182
+ const LABEL_LINE = /^?\s*<!--\s*section:\s*([^\n]*?)\s*-->[ \t]*\r?\n?/
183
+
184
+ /** A section as the text of its file. */
185
+ export function fileContent(s) {
186
+ return `<!-- section: ${String(s.label).replace(/-->/g, '')} -->\n${s.html.trim()}\n`
187
+ }
188
+
189
+ /** A file's text back as a section's label and HTML. */
190
+ export function parseSectionFile(text, key) {
191
+ const m = text.match(LABEL_LINE)
192
+ const label = (m?.[1] || '').trim() || labelFor(key)
193
+ const html = (m ? text.slice(m[0].length) : text).trim()
194
+ return { label: label.slice(0, 40), html }
195
+ }
196
+
197
+ /** "03-faq.html" → "faq". Empty when the name has no key in it. */
198
+ export function keyFromFileName(name) {
199
+ return normalizeKey(String(name).replace(/\.html$/i, '').replace(/^\d+[-_.\s]*/, ''))
200
+ }
201
+
202
+ /** Where each section lives, as a path relative to the site folder. */
203
+ export function sectionFiles(sections) {
204
+ const out = []
205
+ const count = {}
206
+ for (const s of orderSections(sections)) {
207
+ const page = pageOf(s)
208
+ if (page === 'global') {
209
+ out.push({ rel: `${s.key}.html`, section: s, page })
210
+ } else {
211
+ count[page] = (count[page] ?? 0) + 1
212
+ out.push({ rel: `${page}/${String(count[page]).padStart(2, '0')}-${s.key}.html`, section: s, page })
213
+ }
214
+ }
215
+ return out
216
+ }
217
+
218
+ /**
219
+ * Sections from a set of files ({ path: text }), paths relative to the site
220
+ * folder ("home/01-hero.html"). The other half of sectionFiles, for a folder
221
+ * read from a .zip. Returns what it could not use as warnings.
222
+ */
223
+ export function sectionsFromFiles(files) {
224
+ const sections = []
225
+ const warnings = []
226
+ const paths = Object.keys(files).sort((a, b) => a.localeCompare(b, 'en', { numeric: true }))
227
+ const seen = new Set()
228
+ for (const rel of paths) {
229
+ if (!/\.html$/i.test(rel)) continue
230
+ const parts = rel.split('/').filter(Boolean)
231
+ let page, key
232
+ if (parts.length === 1) {
233
+ key = keyFromFileName(parts[0].replace(/^\d+[-_.\s]*/, ''))
234
+ if (!GLOBAL_KEYS.includes(key)) { warnings.push(`${rel}: only header.html and footer.html go at the top; page sections go in a page folder.`); continue }
235
+ page = 'global'
236
+ } else if (parts.length === 2 && PAGES.includes(parts[0])) {
237
+ page = parts[0]
238
+ key = keyFromFileName(parts[1])
239
+ if (!key) { warnings.push(`${rel}: name it like 03-faq.html.`); continue }
240
+ if (GLOBAL_KEYS.includes(key)) { warnings.push(`${rel}: the header and footer are shared; use ${key}.html at the top.`); continue }
241
+ } else {
242
+ warnings.push(`${rel}: not a Sellwavy page (pages are ${PAGES.join(', ')}).`)
243
+ continue
244
+ }
245
+ const id = `${page}/${key}`
246
+ if (seen.has(id)) { warnings.push(`${rel}: a second "${key}" on the ${page} page; left out.`); continue }
247
+ const { label, html } = parseSectionFile(files[rel], key)
248
+ if (!html) { warnings.push(`${rel}: empty; left out.`); continue }
249
+ seen.add(id)
250
+ sections.push({ key, label, html, page })
251
+ }
252
+ return { sections: orderSections(sections), warnings }
253
+ }
package/lib/site.mjs ADDED
@@ -0,0 +1,129 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { CliError } from './ui.mjs'
4
+ import {
5
+ GLOBAL_KEYS, PAGES, fileContent, keyFromFileName, normalizeKey, orderSections, pageOf, parseSectionFile, sectionFiles,
6
+ } from './sections.mjs'
7
+
8
+ /**
9
+ * The store's pages as files on disk, one HTML file per section, laid out
10
+ * as sections.mjs describes:
11
+ *
12
+ * site/header.html, site/footer.html shared by every page
13
+ * site/<page>/<NN>-<key>.html a page's sections, in order
14
+ */
15
+
16
+ export { sectionFiles }
17
+
18
+ /** Every .html file the CLI manages in a site folder. */
19
+ function managedFiles(dir) {
20
+ const found = []
21
+ if (!fs.existsSync(dir)) return found
22
+ for (const name of fs.readdirSync(dir)) {
23
+ const full = path.join(dir, name)
24
+ if (name.endsWith('.html') && fs.statSync(full).isFile()) found.push(name)
25
+ }
26
+ for (const page of PAGES) {
27
+ const pdir = path.join(dir, page)
28
+ if (!fs.existsSync(pdir)) continue
29
+ for (const name of fs.readdirSync(pdir)) {
30
+ if (name.endsWith('.html')) found.push(`${page}/${name}`)
31
+ }
32
+ }
33
+ return found
34
+ }
35
+
36
+ /**
37
+ * Reads a site folder back into sections. Problems a person or an agent can
38
+ * fix (a stray file, a duplicate key) come back as warnings or errors with
39
+ * the file named.
40
+ */
41
+ export function readSiteDir(dir) {
42
+ if (!fs.existsSync(dir)) throw new CliError(`No ${path.relative(process.cwd(), dir) || dir} folder. Run: sellwavy site pull`)
43
+ const warnings = []
44
+ const sections = []
45
+
46
+ for (const name of fs.readdirSync(dir)) {
47
+ const full = path.join(dir, name)
48
+ const stat = fs.statSync(full)
49
+ if (stat.isDirectory()) {
50
+ if (!PAGES.includes(name) && !name.startsWith('.')) {
51
+ warnings.push(`site/${name}/ is ignored: pages are ${PAGES.join(', ')}.`)
52
+ }
53
+ continue
54
+ }
55
+ if (!name.endsWith('.html')) continue
56
+ const key = normalizeKey(name.replace(/\.html$/, ''))
57
+ if (!GLOBAL_KEYS.includes(key)) {
58
+ warnings.push(`site/${name} is ignored: only header.html and footer.html go at the top; page sections go in a page folder (site/home/...).`)
59
+ continue
60
+ }
61
+ const { label, html } = parseSectionFile(fs.readFileSync(full, 'utf8'), key)
62
+ if (html) sections.push({ key, label, html, page: 'global' })
63
+ }
64
+
65
+ for (const page of PAGES) {
66
+ const pdir = path.join(dir, page)
67
+ if (!fs.existsSync(pdir)) continue
68
+ const names = fs.readdirSync(pdir).filter(n => n.endsWith('.html')).sort((a, b) => a.localeCompare(b, 'en', { numeric: true }))
69
+ const seen = new Map()
70
+ for (const name of names) {
71
+ const key = keyFromFileName(name)
72
+ if (!key) {
73
+ warnings.push(`site/${page}/${name} is ignored: name it like 03-faq.html.`)
74
+ continue
75
+ }
76
+ if (GLOBAL_KEYS.includes(key)) {
77
+ warnings.push(`site/${page}/${name} is ignored: the header and footer are shared, edit site/${key}.html.`)
78
+ continue
79
+ }
80
+ if (seen.has(key)) {
81
+ throw new CliError(`site/${page}/${name} and site/${page}/${seen.get(key)} are both "${key}". Keys must be unique on a page; rename one.`)
82
+ }
83
+ seen.set(key, name)
84
+ const { label, html } = parseSectionFile(fs.readFileSync(path.join(pdir, name), 'utf8'), key)
85
+ if (!html) {
86
+ warnings.push(`site/${page}/${name} is empty and is left out.`)
87
+ continue
88
+ }
89
+ sections.push({ key, label, html, page })
90
+ }
91
+ }
92
+
93
+ return { sections: orderSections(sections), warnings }
94
+ }
95
+
96
+ /**
97
+ * Writes sections out as files, so the folder mirrors them exactly: files
98
+ * for sections that no longer exist are removed. Returns the files written.
99
+ */
100
+ export function writeSiteDir(dir, sections) {
101
+ const files = sectionFiles(sections)
102
+ const keep = new Set(files.map(f => f.rel))
103
+ for (const rel of managedFiles(dir)) {
104
+ if (!keep.has(rel)) fs.rmSync(path.join(dir, rel))
105
+ }
106
+ const written = []
107
+ for (const f of files) {
108
+ const full = path.join(dir, f.rel)
109
+ fs.mkdirSync(path.dirname(full), { recursive: true })
110
+ const content = fileContent(f.section)
111
+ const before = fs.existsSync(full) ? fs.readFileSync(full, 'utf8') : null
112
+ if (before !== content) {
113
+ fs.writeFileSync(full, content)
114
+ written.push(f.rel)
115
+ }
116
+ }
117
+ // Page folders left empty are tidied away.
118
+ for (const page of PAGES) {
119
+ const pdir = path.join(dir, page)
120
+ if (fs.existsSync(pdir) && fs.readdirSync(pdir).length === 0) fs.rmdirSync(pdir)
121
+ }
122
+ return written
123
+ }
124
+
125
+ /** The file a section is kept in, for messages. */
126
+ export function fileOf(sections, id) {
127
+ const hit = sectionFiles(sections).find(f => `${pageOf(f.section)}/${f.section.key}` === id)
128
+ return hit ? `site/${hit.rel}` : id
129
+ }
package/lib/ui.mjs ADDED
@@ -0,0 +1,72 @@
1
+ import readline from 'node:readline'
2
+
3
+ /**
4
+ * Terminal output. Colour only on a real terminal and never with NO_COLOR,
5
+ * so piped output (an agent reading it, a log file) stays plain text.
6
+ */
7
+
8
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR
9
+ const paint = code => s => (useColor ? `\x1b[${code}m${s}\x1b[0m` : String(s))
10
+
11
+ export const c = {
12
+ bold: paint('1'),
13
+ dim: paint('2'),
14
+ red: paint('31'),
15
+ green: paint('32'),
16
+ yellow: paint('33'),
17
+ cyan: paint('36'),
18
+ violet: paint('35'),
19
+ }
20
+
21
+ export const log = (...a) => console.log(...a)
22
+ export const ok = msg => console.log(`${c.green('✓')} ${msg}`)
23
+ export const warn = msg => console.error(`${c.yellow('!')} ${msg}`)
24
+ export const info = msg => console.log(`${c.dim('›')} ${msg}`)
25
+
26
+ /** A failure the user can act on: printed plainly, exit code 1. */
27
+ export class CliError extends Error {}
28
+
29
+ export function fail(msg) {
30
+ throw new CliError(msg)
31
+ }
32
+
33
+ /** Prints JSON for agents and scripts (--json). */
34
+ export function json(value) {
35
+ console.log(JSON.stringify(value, null, 2))
36
+ }
37
+
38
+ /** A plain aligned table. `cols` is [header, row => value][]. */
39
+ export function table(rows, cols) {
40
+ if (rows.length === 0) return
41
+ const cells = rows.map(r => cols.map(([, get]) => String(get(r) ?? '')))
42
+ const widths = cols.map(([h], i) => Math.max(h.length, ...cells.map(row => row[i].length)))
43
+ const line = row => row.map((v, i) => (i === row.length - 1 ? v : v.padEnd(widths[i]))).join(' ')
44
+ console.log(c.dim(line(cols.map(([h]) => h))))
45
+ for (const row of cells) console.log(line(row))
46
+ }
47
+
48
+ /** Asks yes/no on a terminal. Off a terminal (an agent, a pipe) the answer is no. */
49
+ export async function confirm(question) {
50
+ if (!process.stdin.isTTY) return false
51
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
52
+ const answer = await new Promise(resolve => rl.question(`${question} ${c.dim('[y/N]')} `, resolve))
53
+ rl.close()
54
+ return /^y(es)?$/i.test(answer.trim())
55
+ }
56
+
57
+ /** Asks the user to pick one of `items` on a terminal; returns the item. */
58
+ export async function choose(question, items, label) {
59
+ if (!process.stdin.isTTY) return null
60
+ items.forEach((item, i) => console.log(` ${c.bold(String(i + 1).padStart(2))} ${label(item)}`))
61
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
62
+ const answer = await new Promise(resolve => rl.question(`${question} `, resolve))
63
+ rl.close()
64
+ const n = Number(answer.trim())
65
+ return Number.isInteger(n) && n >= 1 && n <= items.length ? items[n - 1] : null
66
+ }
67
+
68
+ /** "Rs 2,500.00" from cents, without knowing the currency's symbol. */
69
+ export function money(cents, currency = '') {
70
+ const v = (Number(cents) || 0) / 100
71
+ return `${currency ? `${currency} ` : ''}${v.toLocaleString('en-US', { minimumFractionDigits: v % 1 ? 2 : 0, maximumFractionDigits: 2 })}`
72
+ }
@@ -0,0 +1 @@
1
+ export const VERSION = '0.1.0'
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "sellwavy-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Sellwavy from the terminal: build and run your store yourself, or let Claude Code and other AI agents do it.",
5
+ "type": "module",
6
+ "bin": {
7
+ "sellwavy": "bin/sellwavy.mjs",
8
+ "sellwavy-cli": "bin/sellwavy.mjs"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "lib",
13
+ "README.md"
14
+ ],
15
+ "engines": {
16
+ "node": ">=18.17"
17
+ },
18
+ "keywords": [
19
+ "sellwavy",
20
+ "ecommerce",
21
+ "store",
22
+ "cli",
23
+ "mcp",
24
+ "ai-agents",
25
+ "claude-code"
26
+ ],
27
+ "homepage": "https://sellwavy.com"
28
+ }