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