sellwavy-cli 0.0.0-stage → 0.1.1

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,716 @@
1
+ import crypto from 'node:crypto'
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { spawn } from 'node:child_process'
6
+ import { ApiError, createApi } from './api.mjs'
7
+ import { c, choose, confirm, fail, info, json, log, money, ok, table, warn } from './ui.mjs'
8
+ import {
9
+ configPath, readConfig, readState, resolveHost, writeConfig, writeProject, writeState,
10
+ } from './config.mjs'
11
+ import {
12
+ PAGES, PAGE_NAMES, diffSections, findProduct, getSite, lintSite, mergeSite, pageOf, productBody,
13
+ sameSite, saveSite, uploadMedia, resolveStore,
14
+ } from './core.mjs'
15
+ import { fileOf, readSiteDir, writeSiteDir } from './site.mjs'
16
+ import { CLAUDE_MD, agentsGuide } from './guide.mjs'
17
+ import { runMcp } from './mcp.mjs'
18
+
19
+ const STATE = 'site-state.json'
20
+
21
+ function openBrowser(url) {
22
+ const [cmd, args] =
23
+ process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
24
+ : process.platform === 'darwin' ? ['open', [url]]
25
+ : ['xdg-open', [url]]
26
+ try {
27
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true })
28
+ child.on('error', () => {})
29
+ child.unref()
30
+ } catch {
31
+ // No browser here (SSH, a container): the link is printed anyway.
32
+ }
33
+ }
34
+
35
+ const sleep = ms => new Promise(r => setTimeout(r, ms))
36
+
37
+ // ── Account ───────────────────────────────────────────────────────────────
38
+
39
+ export async function login(ctx) {
40
+ const host = resolveHost(ctx.flags)
41
+ if (ctx.flags.token) {
42
+ const token = String(ctx.flags.token).trim()
43
+ const me = await createApi({ host, token }).get('/api/cli/me')
44
+ writeConfig({ ...readConfig(), host, token, email: me.email })
45
+ ok(`Signed in to ${host} as ${c.bold(me.email)}`)
46
+ return
47
+ }
48
+ if (process.env.SELLWAVY_TOKEN) warn('SELLWAVY_TOKEN is set, so it will be used instead of this login until you unset it.')
49
+
50
+ // A login started with --no-wait and not finished yet carries on with the
51
+ // same key (and so the same code), so "approve, then run login again" works.
52
+ const config = readConfig()
53
+ const pending = config.pending?.host === host && typeof config.pending?.key === 'string' && Date.now() - (config.pending.at ?? 0) < PENDING_MS
54
+ ? config.pending
55
+ : null
56
+
57
+ // The key is made here and only its hash goes through the browser, so the
58
+ // key itself never leaves this computer.
59
+ const key = pending?.key ?? 'sw_' + crypto.randomBytes(32).toString('base64url')
60
+ const hash = crypto.createHash('sha256').update(key).digest('hex')
61
+ const code = `${hash.slice(0, 4)}-${hash.slice(4, 8)}`.toUpperCase()
62
+ const device = String(ctx.flags.name || pending?.device || `CLI on ${os.hostname()}`).slice(0, 60)
63
+ const url = `${host}/account/cli/authorize?code=${hash}&name=${encodeURIComponent(device)}`
64
+ const api = createApi({ host, token: key })
65
+
66
+ const signedIn = me => {
67
+ const next = { ...readConfig(), host, token: key, email: me.email }
68
+ delete next.pending
69
+ writeConfig(next)
70
+ ok(`Signed in as ${c.bold(me.email)}. ${me.stores.length} store${me.stores.length === 1 ? '' : 's'}.`)
71
+ log(`\nNext: ${c.bold('sellwavy init')} in a folder to link a store and pull its pages.`)
72
+ }
73
+ const check = async () => {
74
+ try {
75
+ return await api.get('/api/cli/me')
76
+ } catch (err) {
77
+ if (!(err instanceof ApiError) || (err.status !== 401 && err.status !== 0)) throw err
78
+ return null
79
+ }
80
+ }
81
+
82
+ // Finishing a --no-wait login that was approved meanwhile.
83
+ if (pending && !ctx.flags['no-wait']) {
84
+ const me = await check()
85
+ if (me) return signedIn(me)
86
+ }
87
+
88
+ if (!pending || ctx.flags['no-wait']) {
89
+ log(`\nTo connect this computer to Sellwavy, approve it in your browser.`)
90
+ }
91
+ log(`Type this code on the page: ${c.bold(code)}`)
92
+ log(`\n ${c.cyan(url)}\n`)
93
+ if (!pending && !ctx.flags['no-browser']) openBrowser(url)
94
+
95
+ // --no-wait: print the code and return, for an AI agent that can only read
96
+ // a command's output once it has ended. "sellwavy login" finishes it.
97
+ if (ctx.flags['no-wait']) {
98
+ writeConfig({ ...readConfig(), pending: { host, key, device, at: pending?.at ?? Date.now() } })
99
+ log('When it is approved, run: sellwavy login')
100
+ return
101
+ }
102
+
103
+ info('Waiting for approval… (Ctrl+C to cancel)')
104
+ const deadline = Date.now() + 10 * 60_000
105
+ let me = null
106
+ let offline = 0
107
+ while (!me && Date.now() < deadline) {
108
+ await sleep(2000)
109
+ try {
110
+ me = await api.get('/api/cli/me')
111
+ } catch (err) {
112
+ if (!(err instanceof ApiError)) throw err
113
+ if (err.status === 0 && ++offline > 5) throw err
114
+ }
115
+ }
116
+ if (!me) {
117
+ // Kept, so running login again shows this same code rather than a new one.
118
+ writeConfig({ ...readConfig(), pending: { host, key, device, at: pending?.at ?? Date.now() } })
119
+ fail('Timed out waiting for approval. Approve it with the code above, then run sellwavy login again.')
120
+ }
121
+ signedIn(me)
122
+ }
123
+
124
+ /** How long a login started and not finished keeps its code: a day. */
125
+ const PENDING_MS = 24 * 60 * 60_000
126
+
127
+ export async function logout(ctx) {
128
+ const config = readConfig()
129
+ if (!config.token) return info('Not signed in.')
130
+ try {
131
+ await createApi({ host: resolveHost(ctx.flags), token: config.token }).del('/api/cli/me')
132
+ } catch {
133
+ // Already revoked or offline: forgetting it here is what matters.
134
+ }
135
+ delete config.token
136
+ delete config.email
137
+ writeConfig(config)
138
+ ok('Signed out. The key is revoked.')
139
+ }
140
+
141
+ export async function whoami(ctx) {
142
+ const me = await ctx.api().get('/api/cli/me')
143
+ if (ctx.flags.json) return json({ email: me.email, host: ctx.host, stores: me.stores })
144
+ log(`${c.bold(me.email)} on ${ctx.host}`)
145
+ log(c.dim(`Key from ${process.env.SELLWAVY_TOKEN ? 'SELLWAVY_TOKEN' : configPath()}`))
146
+ }
147
+
148
+ export async function stores(ctx) {
149
+ const me = await ctx.api().get('/api/cli/me')
150
+ if (ctx.flags.json) return json(me.stores)
151
+ if (!me.stores.length) return info('No stores yet.')
152
+ const linked = ctx.project?.storeId
153
+ table(me.stores, [
154
+ ['', s => (s.id === linked ? c.green('●') : ' ')],
155
+ ['NAME', s => s.name],
156
+ ['SUBDOMAIN', s => s.subdomain],
157
+ ['AI PAGES', s => (s.aiDesign ? 'on' : 'off')],
158
+ ['URL', s => s.url],
159
+ ])
160
+ }
161
+
162
+ export async function link(ctx) {
163
+ const api = ctx.api()
164
+ const me = await api.get('/api/cli/me')
165
+ let store = null
166
+ if (ctx.args[0]) {
167
+ store = (await resolveStore(api, { wanted: ctx.args[0] })).store
168
+ } else if (me.stores.length === 1) {
169
+ store = me.stores[0]
170
+ } else if (me.stores.length > 1) {
171
+ store = await choose('Which store should this folder work on?', me.stores, s => `${s.name} ${c.dim(s.url)}`)
172
+ if (!store) fail(`Pick one: sellwavy link <${me.stores.map(s => s.subdomain).join('|')}>`)
173
+ } else {
174
+ fail('You have no stores yet. Create one on Sellwavy first.')
175
+ }
176
+ const root = ctx.project?.root ?? process.cwd()
177
+ writeProject(root, { storeId: store.id, subdomain: store.subdomain, name: store.name })
178
+ ctx.project = { root, storeId: store.id, subdomain: store.subdomain, name: store.name }
179
+ ok(`Linked ${c.bold(path.basename(root) || root)} to ${c.bold(store.name)} (${store.url})`)
180
+ return store
181
+ }
182
+
183
+ export async function open(ctx) {
184
+ const { store } = await ctx.store()
185
+ const what = ctx.args[0] || 'store'
186
+ const url = { store: store.url, editor: store.editorUrl, admin: store.adminUrl }[what]
187
+ if (!url) fail('Open what? sellwavy open [store|editor|admin]')
188
+ log(url)
189
+ openBrowser(url)
190
+ }
191
+
192
+ // ── Pages ─────────────────────────────────────────────────────────────────
193
+
194
+ function siteDir(ctx) {
195
+ const root = ctx.project?.root ?? process.cwd()
196
+ return { root, dir: path.resolve(root, ctx.flags.dir || 'site') }
197
+ }
198
+
199
+ function baseFor(root, storeId) {
200
+ const state = readState(root, STATE)
201
+ return state?.storeId === storeId && Array.isArray(state.base) ? state.base : null
202
+ }
203
+
204
+ function pageCounts(sections) {
205
+ return ['global', ...PAGES]
206
+ .map(p => [p, sections.filter(s => pageOf(s) === p).length])
207
+ .filter(([, n]) => n)
208
+ .map(([p, n]) => `${p === 'global' ? 'header/footer' : p} ${n}`)
209
+ .join(', ')
210
+ }
211
+
212
+ function printDiff(d, sections, label) {
213
+ const lines = [
214
+ ...d.added.map(id => ` ${c.green('+')} ${fileOf(sections, id)}`),
215
+ ...d.changed.map(id => ` ${c.yellow('~')} ${fileOf(sections, id)}`),
216
+ ...d.removed.map(id => ` ${c.red('-')} ${id}`),
217
+ ]
218
+ if (d.reordered) lines.push(` ${c.yellow('~')} section order`)
219
+ if (lines.length) {
220
+ log(label)
221
+ lines.forEach(l => log(l))
222
+ }
223
+ return lines.length
224
+ }
225
+
226
+ export function writeGuide(root, store, { force = false } = {}) {
227
+ const agents = path.join(root, 'AGENTS.md')
228
+ const claude = path.join(root, 'CLAUDE.md')
229
+ const written = []
230
+ if (force || !fs.existsSync(agents)) {
231
+ fs.writeFileSync(agents, agentsGuide({ storeName: store.name, storeUrl: store.url, editorUrl: store.editorUrl }))
232
+ written.push('AGENTS.md')
233
+ }
234
+ if (!fs.existsSync(claude)) {
235
+ fs.writeFileSync(claude, CLAUDE_MD)
236
+ written.push('CLAUDE.md')
237
+ } else if (!fs.readFileSync(claude, 'utf8').includes('@AGENTS.md')) {
238
+ warn('CLAUDE.md exists and does not mention AGENTS.md: add the line "@AGENTS.md" so Claude Code reads the Sellwavy guide.')
239
+ }
240
+ return written
241
+ }
242
+
243
+ export async function sitePull(ctx) {
244
+ const api = ctx.api()
245
+ const { store } = await ctx.store()
246
+ const { root, dir } = siteDir(ctx)
247
+ const remote = await getSite(api, store.id)
248
+ const base = baseFor(root, store.id)
249
+
250
+ // The folder mirrors the store, except for local work not pushed yet,
251
+ // which is never thrown away without --force.
252
+ let result = remote.sections
253
+ if (fs.existsSync(dir) && !ctx.flags.force) {
254
+ const { sections: local } = readSiteDir(dir)
255
+ const unpushed = local.length > 0 && !sameSite(local, base ?? remote.sections)
256
+ if (unpushed && base) {
257
+ const merged = mergeSite(base, local, remote.sections)
258
+ if (merged.conflicts.length) {
259
+ fail(
260
+ `These sections changed both here and on the store:\n${merged.conflicts.map(id => ` ${fileOf(local, id)}`).join('\n')}\n` +
261
+ 'Copy your version somewhere, then "sellwavy site pull --force" to take the store’s, or "sellwavy site push --force" to keep yours.',
262
+ )
263
+ }
264
+ result = merged.sections
265
+ } else if (unpushed) {
266
+ // Files this folder never pulled: someone's own project, or the wrong
267
+ // folder. Nothing is rewritten or renamed under them.
268
+ fail(`${path.relative(process.cwd(), dir) || dir}/ already has files that did not come from this store. Use an empty folder, or move them away first.`)
269
+ }
270
+ }
271
+ const d = diffSections(remote.sections, result)
272
+ const keptLocal = d.added.length + d.changed.length + d.removed.length
273
+
274
+ const written = writeSiteDir(dir, result)
275
+ writeState(root, STATE, { storeId: store.id, base: remote.sections, at: new Date().toISOString() })
276
+ const guide = ctx.flags['no-guide'] ? [] : writeGuide(root, store)
277
+
278
+ if (ctx.flags.json) return json({ store: store.subdomain, dir, files: written, sections: result.length, aiDesignOn: remote.aiDesign })
279
+ const rel = path.relative(process.cwd(), dir) || '.'
280
+ if (!remote.sections.length) {
281
+ ok(`${store.name} has no AI-built pages yet. ${rel}/ is ready for them.`)
282
+ log(`Write sections in ${rel}/ (see AGENTS.md) and run ${c.bold('sellwavy site push')}, or start with ${c.bold('sellwavy ai "Build my store"')}.`)
283
+ warn('The store shows its standard design until then: the first push (or sellwavy ai) replaces it with these pages on the live store.')
284
+ } else {
285
+ ok(`Pulled ${remote.sections.length} sections into ${rel}/ (${pageCounts(remote.sections)}). ${written.length} file${written.length === 1 ? '' : 's'} updated.`)
286
+ if (keptLocal) info(`Your ${keptLocal} unpushed change${keptLocal === 1 ? ' is' : 's are'} kept on top.`)
287
+ if (!remote.aiDesign) warn('This store’s AI-built pages are switched off, so they are not live. "sellwavy site push" switches them on.')
288
+ }
289
+ if (guide.length) info(`Wrote ${guide.join(' and ')} for AI agents.`)
290
+ }
291
+
292
+ /** Pushes the site folder. Returns true when something was saved. */
293
+ export async function sitePush(ctx, { quiet = false } = {}) {
294
+ const api = ctx.api()
295
+ const { store } = await ctx.store()
296
+ const { root, dir } = siteDir(ctx)
297
+ const { sections: local, warnings } = readSiteDir(dir)
298
+ warnings.forEach(w => warn(w))
299
+ if (!local.length) fail(`Nothing to push: ${path.relative(process.cwd(), dir) || dir}/ has no sections.`)
300
+
301
+ const remote = await getSite(api, store.id)
302
+ const base = baseFor(root, store.id)
303
+ let next = local
304
+ let fromStore = []
305
+ if (!ctx.flags.force) {
306
+ if (base) {
307
+ const merged = mergeSite(base, local, remote.sections)
308
+ if (merged.conflicts.length) {
309
+ fail(
310
+ `These sections were changed on the store (in the visual editor?) since your last pull, and here too:\n` +
311
+ `${merged.conflicts.map(id => ` ${fileOf(local, id)}`).join('\n')}\n` +
312
+ 'Run "sellwavy site status" to see them. Keep yours with "sellwavy site push --force", or take the store’s with "sellwavy site pull --force".',
313
+ )
314
+ }
315
+ next = merged.sections
316
+ fromStore = merged.fromRemote
317
+ } else if (remote.sections.length && !sameSite(local, remote.sections)) {
318
+ fail('This store already has pages you have not pulled. Run "sellwavy site pull" first, or "sellwavy site push --force" to replace them.')
319
+ }
320
+ }
321
+
322
+ const activate = !ctx.flags['keep-off']
323
+ const nothing = sameSite(next, remote.sections) && (remote.aiDesign || !activate)
324
+ const problems = lintSite(next)
325
+ for (const p of problems) warn(`${p.section === '*' || PAGES.includes(p.section) ? p.section : fileOf(next, p.section)}: ${p.problem}`)
326
+
327
+ if (nothing) {
328
+ if (!quiet) info('Nothing to push: the store already matches.')
329
+ writeState(root, STATE, { storeId: store.id, base: remote.sections, at: new Date().toISOString() })
330
+ return false
331
+ }
332
+
333
+ const d = diffSections(remote.sections, next)
334
+ // The store showing its standard design: this push swaps it for the pages
335
+ // here, on every page they cover. Said every time, not only when nothing
336
+ // else changes, as it is the biggest change a push can make.
337
+ const switchesOn = activate && !remote.aiDesign
338
+ if (ctx.flags['dry-run']) {
339
+ if (ctx.flags.json) return json({ ...d, switchesOn, warnings: problems })
340
+ printDiff(d, next, 'Would change:')
341
+ if (switchesOn) {
342
+ warn('This push also switches the store to these pages: they replace its current design on the live store. Add --keep-off to save them without showing them.')
343
+ }
344
+ return false
345
+ }
346
+
347
+ const saved = await saveSite(api, store.id, next, { activate })
348
+ const rewritten = writeSiteDir(dir, saved.sections)
349
+ writeState(root, STATE, { storeId: store.id, base: saved.sections, at: new Date().toISOString() })
350
+
351
+ // The server cleans every section; whatever it changed is now in the files.
352
+ const cleaned = diffSections(next, saved.sections)
353
+ if (ctx.flags.json) return json({ ...d, cleaned: cleaned.changed, url: store.url, editor: store.editorUrl })
354
+ printDiff(d, saved.sections, quiet ? `${new Date().toLocaleTimeString()} pushed:` : 'Pushed:')
355
+ if (fromStore.length) info(`Kept ${fromStore.length} change${fromStore.length === 1 ? '' : 's'} made on the store since your pull; ${rewritten.length} file${rewritten.length === 1 ? '' : 's'} updated.`)
356
+ if (cleaned.changed.length) warn(`Sellwavy cleaned ${cleaned.changed.map(id => fileOf(saved.sections, id)).join(', ')}: the file now holds what was kept.`)
357
+ if (switchesOn) info('The store now shows these pages in place of its standard design.')
358
+ if (!quiet) {
359
+ ok(`Live at ${c.cyan(store.url)}`)
360
+ log(c.dim(`Edit text, photos and videos in the visual editor: ${store.editorUrl}`))
361
+ }
362
+ return true
363
+ }
364
+
365
+ export async function siteStatus(ctx) {
366
+ const api = ctx.api()
367
+ const { store } = await ctx.store()
368
+ const { root, dir } = siteDir(ctx)
369
+ const base = baseFor(root, store.id)
370
+ const remote = await getSite(api, store.id)
371
+ const local = fs.existsSync(dir) ? readSiteDir(dir).sections : []
372
+ if (!base) {
373
+ if (ctx.flags.json) return json({ pulled: false })
374
+ return info('Not pulled yet. Run: sellwavy site pull')
375
+ }
376
+ const mine = diffSections(base, local)
377
+ const theirs = diffSections(base, remote.sections)
378
+ if (ctx.flags.json) return json({ local: mine, store: theirs, aiDesignOn: remote.aiDesign })
379
+ const a = printDiff(mine, local, 'Changed here, not pushed:')
380
+ const b = printDiff(theirs, remote.sections, 'Changed on the store since your pull:')
381
+ if (!a && !b) ok('Up to date with the store.')
382
+ if (!remote.aiDesign) warn('The AI-built pages are switched off on the store. "sellwavy site push" switches them on.')
383
+ }
384
+
385
+ export async function siteWatch(ctx) {
386
+ const { dir } = siteDir(ctx)
387
+ if (!fs.existsSync(dir)) fail('Nothing to watch yet. Run: sellwavy site pull')
388
+ const { store } = await ctx.store()
389
+ log(`Watching ${path.relative(process.cwd(), dir) || dir}/. Every save goes live on ${c.cyan(store.url)}. Ctrl+C to stop.`)
390
+ let timer = null
391
+ let running = false
392
+ let again = false
393
+ const run = async () => {
394
+ if (running) { again = true; return }
395
+ running = true
396
+ try {
397
+ await sitePush(ctx, { quiet: true })
398
+ } catch (err) {
399
+ warn(err.message)
400
+ } finally {
401
+ running = false
402
+ if (again) { again = false; run() }
403
+ }
404
+ }
405
+ const onChange = (_event, name) => {
406
+ if (name && !String(name).endsWith('.html')) return
407
+ clearTimeout(timer)
408
+ timer = setTimeout(run, 400)
409
+ }
410
+ try {
411
+ fs.watch(dir, { recursive: true }, onChange)
412
+ } catch {
413
+ // Older Node on Linux cannot watch recursively: watch each folder.
414
+ for (const d of [dir, ...PAGES.map(p => path.join(dir, p))]) {
415
+ if (fs.existsSync(d)) fs.watch(d, onChange)
416
+ }
417
+ }
418
+ await new Promise(() => {})
419
+ }
420
+
421
+ export async function init(ctx) {
422
+ // init sets up the folder it is run in. A linked folder further up (an
423
+ // earlier init) is left alone rather than relinked and pulled into.
424
+ if (ctx.project && ctx.project.root !== process.cwd()) ctx.project = null
425
+ if (!ctx.project?.storeId || ctx.args[0]) await link(ctx)
426
+ await sitePull(ctx)
427
+ log(`\nReady. Open this folder in Claude Code, Cursor or Codex and ask for changes, or connect the agent directly:`)
428
+ log(` ${c.bold('claude mcp add sellwavy -- npx -y sellwavy-cli mcp')}`)
429
+ }
430
+
431
+ export async function agents(ctx) {
432
+ const { store } = await ctx.store()
433
+ const root = ctx.project?.root ?? process.cwd()
434
+ const written = writeGuide(root, store, { force: !!ctx.flags.force })
435
+ if (written.length) ok(`Wrote ${written.join(' and ')}.`)
436
+ else info('AGENTS.md is already there. Use --force to rewrite it.')
437
+ }
438
+
439
+ // ── Sellwavy AI ───────────────────────────────────────────────────────────
440
+
441
+ export async function ai(ctx) {
442
+ const prompt = ctx.args.join(' ').trim()
443
+ if (prompt.length < 2) fail('Say what to change: sellwavy ai "make the hero darker" [--page home]')
444
+ const page = ctx.flags.page || 'home'
445
+ if (!PAGES.includes(page)) fail(`--page is one of: ${PAGES.join(', ')}`)
446
+ const api = ctx.api()
447
+ const { store } = await ctx.store()
448
+ const { sections } = await getSite(api, store.id)
449
+ info(`Sellwavy AI is working on the ${PAGE_NAMES[page].toLowerCase()}. This can take a minute or two…`)
450
+ const res = await api.post(`/api/stores/${store.id}/ai/site`, { prompt, page, sections })
451
+ if (ctx.flags.json && ctx.flags['dry-run']) return json(res)
452
+ log(`\n${res.summary}`)
453
+ for (const ch of res.changes ?? []) log(` ${c.dim('•')} ${ch}`)
454
+ if (ctx.flags['dry-run']) return info('Dry run: nothing saved.')
455
+ await saveSite(api, store.id, res.sections)
456
+ ok(`Saved. Live at ${c.cyan(store.url)}`)
457
+ if (res.products?.length) {
458
+ log(`\nThe AI suggested ${res.products.length} product${res.products.length === 1 ? '' : 's'} (not added):`)
459
+ for (const p of res.products) log(` ${p.title} ${c.dim(`${p.price}`)}`)
460
+ log(c.dim('Add them with: sellwavy products create --title "..." --price ...'))
461
+ }
462
+ if (ctx.project) log(c.dim('Run "sellwavy site pull" to bring the change into your files.'))
463
+ }
464
+
465
+ // ── Products ──────────────────────────────────────────────────────────────
466
+
467
+ function productFlags(flags) {
468
+ const out = {}
469
+ for (const k of ['title', 'description', 'price', 'inventory', 'stock', 'category', 'sku', 'status', 'tags', 'seo-title', 'seo-description']) {
470
+ if (flags[k] !== undefined) out[k.replace(/-(\w)/g, (_m, ch) => ch.toUpperCase())] = Array.isArray(flags[k]) ? flags[k].at(-1) : flags[k]
471
+ }
472
+ if (flags.image !== undefined) out.images = [].concat(flags.image)
473
+ return out
474
+ }
475
+
476
+ export async function productsList(ctx) {
477
+ const { store } = await ctx.store()
478
+ const list = await ctx.api().get(`/api/stores/${store.id}/products`)
479
+ if (ctx.flags.json) return json(list)
480
+ if (!list.length) return info('No products yet. Add one: sellwavy products create --title "..." --price 25')
481
+ table(list, [
482
+ ['ID', p => p.id],
483
+ ['TITLE', p => (p.title.length > 40 ? p.title.slice(0, 39) + '…' : p.title)],
484
+ ['PRICE', p => money(p.price, store.currency)],
485
+ ['STOCK', p => p.inventory],
486
+ ['STATUS', p => p.status],
487
+ ])
488
+ }
489
+
490
+ export async function productsGet(ctx) {
491
+ if (!ctx.args[0]) fail('Which product? sellwavy products get <id|slug>')
492
+ const { store } = await ctx.store()
493
+ const api = ctx.api()
494
+ const p = await findProduct(api, store.id, ctx.args[0])
495
+ json((await api.get(`/api/stores/${store.id}/products/${p.id}`)).product)
496
+ }
497
+
498
+ export async function productsCreate(ctx) {
499
+ const { store } = await ctx.store()
500
+ const api = ctx.api()
501
+ const body = await productBody(api, store.id, productFlags(ctx.flags))
502
+ const product = await api.post(`/api/stores/${store.id}/products`, body)
503
+ if (ctx.flags.json) return json(product)
504
+ ok(`Added ${c.bold(product.title)} (${product.id}) at ${money(product.price, store.currency)}`)
505
+ }
506
+
507
+ export async function productsUpdate(ctx) {
508
+ if (!ctx.args[0]) fail('Which product? sellwavy products update <id|slug> --price 30')
509
+ const { store } = await ctx.store()
510
+ const api = ctx.api()
511
+ const p = await findProduct(api, store.id, ctx.args[0])
512
+ const body = await productBody(api, store.id, productFlags(ctx.flags), { partial: true })
513
+ if (!Object.keys(body).length) fail('Nothing to change. Give --title, --price, --inventory, --status, --image, ...')
514
+ const res = await api.patch(`/api/stores/${store.id}/products/${p.id}`, body)
515
+ if (ctx.flags.json) return json(res.product)
516
+ ok(`Updated ${c.bold(res.product.title)}`)
517
+ }
518
+
519
+ export async function productsDelete(ctx) {
520
+ if (!ctx.args[0]) fail('Which product? sellwavy products delete <id|slug> --yes')
521
+ const { store } = await ctx.store()
522
+ const api = ctx.api()
523
+ const p = await findProduct(api, store.id, ctx.args[0])
524
+ if (!ctx.flags.yes && !(await confirm(`Delete "${p.title}" for good?`))) fail('Not deleted. Add --yes to confirm.')
525
+ await api.del(`/api/stores/${store.id}/products/${p.id}`)
526
+ ok(`Deleted ${p.title}`)
527
+ }
528
+
529
+ /** A small CSV reader: quoted fields, commas and newlines inside quotes. */
530
+ function parseCsv(text) {
531
+ const rows = []
532
+ let row = [], field = '', quoted = false
533
+ for (let i = 0; i < text.length; i++) {
534
+ const ch = text[i]
535
+ if (quoted) {
536
+ if (ch === '"' && text[i + 1] === '"') { field += '"'; i++ }
537
+ else if (ch === '"') quoted = false
538
+ else field += ch
539
+ } else if (ch === '"') quoted = true
540
+ else if (ch === ',') { row.push(field); field = '' }
541
+ else if (ch === '\n' || ch === '\r') {
542
+ if (ch === '\r' && text[i + 1] === '\n') i++
543
+ row.push(field); rows.push(row); row = []; field = ''
544
+ } else field += ch
545
+ }
546
+ if (field || row.length) { row.push(field); rows.push(row) }
547
+ const [head = [], ...body] = rows.filter(r => r.some(v => v.trim()))
548
+ const keys = head.map(h => h.trim().toLowerCase())
549
+ return body.map(r => Object.fromEntries(keys.map((k, i) => [k, r[i]?.trim() ?? ''])))
550
+ }
551
+
552
+ export async function productsImport(ctx) {
553
+ const file = ctx.args[0]
554
+ if (!file || !fs.existsSync(file)) fail('Give a .json or .csv file: sellwavy products import products.json')
555
+ const text = fs.readFileSync(file, 'utf8')
556
+ let items
557
+ if (file.toLowerCase().endsWith('.csv')) {
558
+ items = parseCsv(text).map(r => ({ ...r, images: (r.images || r.image || '').split(/[|\s]+/).filter(Boolean) }))
559
+ } else {
560
+ try { items = JSON.parse(text) } catch { fail(`${file} is not valid JSON.`) }
561
+ }
562
+ if (!Array.isArray(items) || !items.length) fail('The file should hold a list of products.')
563
+ const { store } = await ctx.store()
564
+ const api = ctx.api()
565
+ let added = 0
566
+ const failed = []
567
+ for (const [i, item] of items.entries()) {
568
+ try {
569
+ const body = await productBody(api, store.id, item)
570
+ const p = await api.post(`/api/stores/${store.id}/products`, body)
571
+ added++
572
+ if (!ctx.flags.json) ok(`${p.title}`)
573
+ } catch (err) {
574
+ failed.push({ row: i + 1, title: item?.title, error: err.message })
575
+ if (!ctx.flags.json) warn(`Row ${i + 1}${item?.title ? ` (${item.title})` : ''}: ${err.message}`)
576
+ }
577
+ }
578
+ if (ctx.flags.json) return json({ added, failed })
579
+ log(`${added} added${failed.length ? `, ${failed.length} failed` : ''}.`)
580
+ }
581
+
582
+ // ── Orders ────────────────────────────────────────────────────────────────
583
+
584
+ export async function ordersList(ctx) {
585
+ const { store } = await ctx.store()
586
+ let list = await ctx.api().get(`/api/stores/${store.id}/orders`)
587
+ if (ctx.flags.status) list = list.filter(o => o.status === String(ctx.flags.status).toUpperCase())
588
+ if (ctx.flags.json) return json(list)
589
+ if (!list.length) return info('No orders.')
590
+ table(list, [
591
+ ['ID', o => o.id],
592
+ ['DATE', o => new Date(o.createdAt).toLocaleDateString()],
593
+ ['CUSTOMER', o => o.customerName || o.customerEmail || ''],
594
+ ['ITEMS', o => o.itemCount],
595
+ ['TOTAL', o => money(o.total, store.currency)],
596
+ ['STATUS', o => o.status],
597
+ ])
598
+ }
599
+
600
+ export async function ordersGet(ctx) {
601
+ if (!ctx.args[0]) fail('Which order? sellwavy orders get <id>')
602
+ const { store } = await ctx.store()
603
+ const o = await ctx.api().get(`/api/stores/${store.id}/orders/${encodeURIComponent(ctx.args[0])}`)
604
+ if (ctx.flags.json) return json(o)
605
+ const cur = o.currency || store.currency
606
+ log(`${c.bold(`Order ${o.id}`)} ${o.status}${o.shippedAt ? ', shipped' : ''} ${new Date(o.createdAt).toLocaleString()}`)
607
+ log(`${o.customerName ?? ''} ${c.dim(o.customerEmail ?? '')} ${c.dim(o.customerPhone ?? '')}`)
608
+ const address = [o.customerAddress, o.customerCity, o.customerCountry].filter(Boolean).join(', ')
609
+ if (address) log(address)
610
+ for (const i of o.items) log(` ${i.quantity} × ${i.title}${i.variant ? ` (${i.variant})` : ''} ${money(i.price * i.quantity, cur)}`)
611
+ if (o.discountAmount) log(` Discount${o.discountCode ? ` ${o.discountCode}` : ''} -${money(o.discountAmount, cur)}`)
612
+ if (o.shippingAmount) log(` Shipping ${money(o.shippingAmount, cur)}`)
613
+ log(` ${c.bold('Total')} ${money(o.total, cur)} ${c.dim(o.paymentMethod ?? '')}`)
614
+ if (o.trackingInfo) log(`Tracking: ${o.trackingInfo}`)
615
+ if (o.notes) log(`Notes: ${o.notes}`)
616
+ }
617
+
618
+ export async function ordersShip(ctx) {
619
+ if (!ctx.args[0]) fail('Which order? sellwavy orders ship <id> [--tracking "DHL 123"]')
620
+ const { store } = await ctx.store()
621
+ const res = await ctx.api().post(`/api/stores/${store.id}/orders/${encodeURIComponent(ctx.args[0])}/ship`, { trackingInfo: ctx.flags.tracking ?? '' })
622
+ if (ctx.flags.json) return json(res)
623
+ ok('Marked shipped. The customer has been emailed.')
624
+ }
625
+
626
+ export async function ordersMarkPaid(ctx) {
627
+ if (!ctx.args[0]) fail('Which order? sellwavy orders mark-paid <id>')
628
+ const { store } = await ctx.store()
629
+ const res = await ctx.api().post(`/api/stores/${store.id}/orders/${encodeURIComponent(ctx.args[0])}/mark-paid`, {})
630
+ if (ctx.flags.json) return json(res)
631
+ ok('Marked paid.')
632
+ }
633
+
634
+ // ── Media ─────────────────────────────────────────────────────────────────
635
+
636
+ export async function mediaList(ctx) {
637
+ const { store } = await ctx.store()
638
+ const list = await ctx.api().get(`/api/stores/${store.id}/media`)
639
+ if (ctx.flags.json) return json(list)
640
+ if (!list.length) return info('The media library is empty.')
641
+ table(list, [['TYPE', m => m.type], ['NAME', m => m.filename], ['URL', m => m.url]])
642
+ }
643
+
644
+ export async function mediaUpload(ctx) {
645
+ if (!ctx.args.length) fail('What to upload? sellwavy media upload hero.mp4 photo.jpg')
646
+ const { store } = await ctx.store()
647
+ const api = ctx.api()
648
+ const results = []
649
+ for (const source of ctx.args) {
650
+ const m = await uploadMedia(api, store.id, source)
651
+ results.push({ source, url: m.url, type: m.type, id: m.id })
652
+ if (!ctx.flags.json) ok(`${path.basename(source)} ${c.dim('→')} ${m.url}`)
653
+ }
654
+ if (ctx.flags.json) json(results)
655
+ }
656
+
657
+ // ── Theme ─────────────────────────────────────────────────────────────────
658
+
659
+ const THEME_SUMMARY = ['primaryColor', 'accentColor', 'backgroundColor', 'textColor', 'footerColor', 'font', 'headingFont', 'logoUrl', 'faviconUrl', 'darkMode', 'aiHome']
660
+
661
+ export async function themeGet(ctx) {
662
+ const { store } = await ctx.store()
663
+ const t = (await ctx.api().get(`/api/stores/${store.id}/theme`)) ?? {}
664
+ delete t.aiSections
665
+ if (ctx.flags.json || ctx.flags.all) return json(t)
666
+ table(THEME_SUMMARY.filter(k => k in t), [['SETTING', k => k], ['VALUE', k => String(t[k] ?? '')]])
667
+ log(c.dim('\nEvery setting: sellwavy theme get --all. Change: sellwavy theme set primaryColor=#111111'))
668
+ }
669
+
670
+ function parseValue(v) {
671
+ if (v === 'true') return true
672
+ if (v === 'false') return false
673
+ if (/^-?\d+$/.test(v)) return Number(v)
674
+ if (/^[[{]/.test(v)) {
675
+ try { return JSON.parse(v) } catch { return v }
676
+ }
677
+ return v
678
+ }
679
+
680
+ export async function themeSet(ctx) {
681
+ const pairs = ctx.args.map(a => a.match(/^([A-Za-z][\w]*)=(.*)$/s))
682
+ if (!pairs.length || pairs.some(p => !p)) fail('Use key=value: sellwavy theme set primaryColor=#111111 font=sans')
683
+ const body = Object.fromEntries(pairs.map(([, k, v]) => [k, parseValue(v)]))
684
+ if ('aiSections' in body) fail('Pages are changed with "sellwavy site push", not theme set.')
685
+ const { store } = await ctx.store()
686
+ const t = await ctx.api().post(`/api/stores/${store.id}/theme`, body)
687
+ if (ctx.flags.json) return json(Object.fromEntries(Object.keys(body).map(k => [k, t?.[k]])))
688
+ for (const k of Object.keys(body)) ok(`${k} = ${JSON.stringify(t?.[k])}`)
689
+ }
690
+
691
+ // ── Anything else ─────────────────────────────────────────────────────────
692
+
693
+ export async function apiCall(ctx) {
694
+ const methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']
695
+ let [first, second] = ctx.args
696
+ let method = ctx.flags.method ? String(ctx.flags.method).toUpperCase() : null
697
+ if (first && methods.includes(first.toUpperCase())) { method = first.toUpperCase(); first = second }
698
+ if (!first) fail('sellwavy api [METHOD] <path> [-d \'{"json":true}\' | -d @file.json]')
699
+ let body
700
+ if (ctx.flags.data !== undefined) {
701
+ const raw = String(ctx.flags.data)
702
+ const text = raw.startsWith('@') ? fs.readFileSync(raw.slice(1), 'utf8') : raw
703
+ try { body = JSON.parse(text) } catch { fail('--data must be JSON.') }
704
+ }
705
+ method ||= body !== undefined ? 'POST' : 'GET'
706
+ let full = first
707
+ if (!first.startsWith('/api/')) {
708
+ const { store } = await ctx.store()
709
+ full = `/api/stores/${store.id}${first.startsWith('/') ? first : `/${first}`}`
710
+ }
711
+ json(await ctx.api().request(method, full, method === 'GET' || method === 'DELETE' ? undefined : (body ?? {})))
712
+ }
713
+
714
+ export async function mcp(ctx) {
715
+ await runMcp({ api: ctx.api(), defaultStore: ctx.flags.store, project: ctx.project })
716
+ }