@tomsher/cms-theme-kit 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.
package/dist/bin.js ADDED
@@ -0,0 +1,1078 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ isPushablePath,
4
+ isTextPath,
5
+ readLocalTheme,
6
+ toHashMap
7
+ } from "./chunk-YAYCHT4W.js";
8
+ import {
9
+ ApiError,
10
+ CliError,
11
+ diffHashes,
12
+ liquidThemeFolderNames,
13
+ staticThemeHomePath
14
+ } from "./chunk-TN3DQWJE.js";
15
+
16
+ // src/constants.ts
17
+ var cliName = "cms-theme-kit";
18
+ var packageScope = "@tomsher";
19
+ var packageName = `${packageScope}/${cliName}`;
20
+ var metadataFolderName = ".cms-theme-kit";
21
+ var metadataFileName = "theme.json";
22
+ var metadataSchemaVersion = 1;
23
+ var credentialsDirSegments = [".config", "tomsher"];
24
+ var credentialsFileName = "credentials.json";
25
+ var credentialsDisplayPath = `~/${credentialsDirSegments.join("/")}/${credentialsFileName}`;
26
+ var tokenEnvVar = "CMS_THEME_KIT_TOKEN";
27
+
28
+ // src/lib/credentials.ts
29
+ import { chmod, mkdir, readFile, writeFile } from "fs/promises";
30
+ import { homedir } from "os";
31
+ import { dirname, join } from "path";
32
+ var credentialsFilePath = () => {
33
+ return join(homedir(), ...credentialsDirSegments, credentialsFileName);
34
+ };
35
+ var readCredentials = async (filePath = credentialsFilePath()) => {
36
+ let raw;
37
+ try {
38
+ raw = await readFile(filePath, "utf8");
39
+ } catch (error) {
40
+ if (error.code === "ENOENT") {
41
+ return { logins: [] };
42
+ }
43
+ throw error;
44
+ }
45
+ let parsed;
46
+ try {
47
+ parsed = JSON.parse(raw);
48
+ } catch {
49
+ throw new CliError(`Credentials file is not valid JSON: ${filePath}`);
50
+ }
51
+ return { logins: Array.isArray(parsed.logins) ? parsed.logins : [] };
52
+ };
53
+ var findLogin = (credentials, cmsUrl, store) => {
54
+ return credentials.logins.find((login) => login.cmsUrl === cmsUrl && login.store === store);
55
+ };
56
+ var saveLogin = async (login, filePath = credentialsFilePath()) => {
57
+ const credentials = await readCredentials(filePath);
58
+ const others = credentials.logins.filter((item) => item.cmsUrl !== login.cmsUrl || item.store !== login.store);
59
+ const content = JSON.stringify({ logins: [...others, login] }, null, 4);
60
+ await mkdir(dirname(filePath), { recursive: true, mode: 448 });
61
+ await writeFile(filePath, `${content}
62
+ `, { mode: 384 });
63
+ await chmod(filePath, 384);
64
+ };
65
+
66
+ // src/lib/connection.ts
67
+ var normalizeCmsUrl = (value) => {
68
+ return value.trim().replace(/\/+$/, "");
69
+ };
70
+ var resolveConnection = async (options) => {
71
+ const credentials = await readCredentials();
72
+ const onlyLogin = credentials.logins.length === 1 ? credentials.logins[0] : void 0;
73
+ const cmsUrl = normalizeCmsUrl(options.cmsUrl ?? options.metadata?.cmsUrl ?? onlyLogin?.cmsUrl ?? "");
74
+ const store = options.store ?? options.metadata?.store ?? onlyLogin?.store ?? "";
75
+ if (!cmsUrl) {
76
+ throw new CliError("Missing CMS URL. Pass --cms-url or run the login command first.");
77
+ }
78
+ if (!store) {
79
+ throw new CliError("Missing store slug. Pass --store <slug>.");
80
+ }
81
+ const token = process.env[tokenEnvVar] || findLogin(credentials, cmsUrl, store)?.token;
82
+ if (!token) {
83
+ throw new CliError(`Not logged in to ${cmsUrl} (store "${store}"). Run: login ${cmsUrl} --store ${store}`);
84
+ }
85
+ return { cmsUrl, store, token };
86
+ };
87
+
88
+ // src/lib/args.ts
89
+ import { parseArgs } from "util";
90
+ var parseCommandArgs = (argv, options) => {
91
+ try {
92
+ const parsed = parseArgs({ args: argv, options, allowPositionals: true, strict: true });
93
+ return {
94
+ values: parsed.values,
95
+ positionals: parsed.positionals
96
+ };
97
+ } catch (error) {
98
+ const message = error instanceof Error ? error.message : String(error);
99
+ throw new CliError(message);
100
+ }
101
+ };
102
+ var stringOption = (values, key) => {
103
+ const value = values[key];
104
+ return typeof value === "string" ? value : void 0;
105
+ };
106
+ var booleanOption = (values, key) => {
107
+ return values[key] === true;
108
+ };
109
+
110
+ // src/lib/envelope.ts
111
+ var unwrapRequestedData = (body) => {
112
+ if (body && typeof body === "object" && "requestedData" in body) {
113
+ return body.requestedData;
114
+ }
115
+ throw new CliError("Unexpected CMS response: missing requestedData.");
116
+ };
117
+
118
+ // src/lib/auth.ts
119
+ var loginToCms = async (options) => {
120
+ const fetchImpl = options.fetchImpl ?? fetch;
121
+ const url = `${normalizeCmsUrl(options.cmsUrl)}/admin/${encodeURIComponent(options.store)}/auth/login`;
122
+ const response = await fetchImpl(url, {
123
+ method: "POST",
124
+ headers: {
125
+ "Content-Type": "application/json",
126
+ Accept: "application/json"
127
+ },
128
+ body: JSON.stringify({ email: options.email, password: options.password })
129
+ });
130
+ if (!response.ok) {
131
+ throw await ApiError.fromResponse(response);
132
+ }
133
+ const session = unwrapRequestedData(await response.json());
134
+ const token = session.token;
135
+ if (!token) {
136
+ throw new CliError("Login response did not include a token.");
137
+ }
138
+ return { token, email: session.user?.email ?? options.email };
139
+ };
140
+
141
+ // src/lib/prompt.ts
142
+ import { createInterface } from "readline";
143
+ import { Writable } from "stream";
144
+ var askLine = async (question, hidden = false) => {
145
+ const output = process.stdout;
146
+ let muted = false;
147
+ const filteredOutput = new Writable({
148
+ write(chunk, encoding, callback) {
149
+ if (!muted) {
150
+ output.write(chunk, encoding);
151
+ }
152
+ callback();
153
+ }
154
+ });
155
+ const readline = createInterface({ input: process.stdin, output: filteredOutput, terminal: true });
156
+ const answer = await new Promise((resolve8) => {
157
+ readline.question(question, resolve8);
158
+ muted = hidden;
159
+ });
160
+ muted = false;
161
+ output.write("\n");
162
+ readline.close();
163
+ return answer.trim();
164
+ };
165
+
166
+ // src/commands/login.ts
167
+ var loginHelp = `Usage: ${cliName} login <cms-url> --store <slug> [--email <email>] [--password <password>]
168
+
169
+ Signs in to a CMS store and saves the token to ${credentialsDisplayPath} (mode 0600).
170
+ Missing email or password are prompted for on the terminal; the password is not echoed.
171
+ Passing --password on the command line can leave it in shell history.
172
+
173
+ Options:
174
+ --store <slug> Store (tenant) slug to sign in to (required)
175
+ --email <email> Admin account email
176
+ --password <value> Admin account password
177
+ -h, --help Show this help
178
+ `;
179
+ var runLogin = async (argv) => {
180
+ const { values, positionals } = parseCommandArgs(argv, {
181
+ store: { type: "string" },
182
+ email: { type: "string" },
183
+ password: { type: "string" }
184
+ });
185
+ const cmsUrlArg = positionals[0];
186
+ const store = stringOption(values, "store");
187
+ if (!cmsUrlArg) {
188
+ throw new CliError("Missing <cms-url>. See: login --help");
189
+ }
190
+ if (!store) {
191
+ throw new CliError("Missing --store <slug>. See: login --help");
192
+ }
193
+ const cmsUrl = normalizeCmsUrl(cmsUrlArg);
194
+ const email = stringOption(values, "email") ?? await askLine("Email: ");
195
+ const password = stringOption(values, "password") ?? await askLine("Password: ", true);
196
+ if (!email || !password) {
197
+ throw new CliError("Email and password are required.");
198
+ }
199
+ const result = await loginToCms({ cmsUrl, store, email, password });
200
+ await saveLogin({ cmsUrl, store, token: result.token, email: result.email });
201
+ console.log(`Logged in to ${cmsUrl} (store "${store}") as ${result.email}.`);
202
+ };
203
+
204
+ // src/commands/pull.ts
205
+ import { resolve as resolve3 } from "path";
206
+
207
+ // src/lib/cms-client.ts
208
+ var CmsClient = class {
209
+ connection;
210
+ fetchImpl;
211
+ constructor(connection, fetchImpl = fetch) {
212
+ this.connection = connection;
213
+ this.fetchImpl = fetchImpl;
214
+ }
215
+ async listThemes() {
216
+ return unwrapRequestedData(await this.requestJson(this.themesUrl()));
217
+ }
218
+ async listFiles(themeId) {
219
+ return unwrapRequestedData(await this.requestJson(this.themesUrl(themeId, "files")));
220
+ }
221
+ async exportZip(themeId, mode) {
222
+ const query = new URLSearchParams({ mode });
223
+ const response = await this.send(`${this.themesUrl(themeId, "export-zip")}?${query.toString()}`);
224
+ return new Uint8Array(await response.arrayBuffer());
225
+ }
226
+ // Returns the raw JSON body; the payload sits in requestedData (see transform.interceptor.ts).
227
+ async previewData(themeId, request, countryCode) {
228
+ const headers = { "Content-Type": "application/json" };
229
+ if (countryCode) {
230
+ headers["x-country-code"] = countryCode;
231
+ }
232
+ return this.requestJson(this.themesUrl(themeId, "preview-data"), {
233
+ method: "POST",
234
+ headers,
235
+ body: JSON.stringify(request)
236
+ });
237
+ }
238
+ async validateFiles(themeId, files, removed) {
239
+ const body = await this.requestJson(this.themesUrl(themeId, "validate"), {
240
+ method: "POST",
241
+ headers: { "Content-Type": "application/json" },
242
+ body: JSON.stringify({ files, removed })
243
+ });
244
+ return unwrapRequestedData(body);
245
+ }
246
+ async saveFilesBatch(themeId, files) {
247
+ await this.send(this.themesUrl(themeId, "files", "batch"), {
248
+ method: "POST",
249
+ headers: { "Content-Type": "application/json" },
250
+ body: JSON.stringify({ files })
251
+ });
252
+ }
253
+ async uploadThemeZip(themeId, zip, renderMode) {
254
+ await this.send(this.themesUrl(themeId, "upload-zip"), {
255
+ method: "POST",
256
+ body: this.zipForm(zip, { renderMode })
257
+ });
258
+ }
259
+ async createThemeFromZip(fields, zip) {
260
+ const body = await this.requestJson(this.themesUrl("upload-zip"), {
261
+ method: "POST",
262
+ body: this.zipForm(zip, fields)
263
+ });
264
+ return unwrapRequestedData(body).theme;
265
+ }
266
+ themesUrl(...segments) {
267
+ const base = `${this.connection.cmsUrl}/admin/${encodeURIComponent(this.connection.store)}/themes`;
268
+ const path = segments.map((segment) => `/${encodeURIComponent(segment)}`).join("");
269
+ return `${base}${path}`;
270
+ }
271
+ zipForm(zip, fields) {
272
+ const form = new FormData();
273
+ if (fields.name) {
274
+ form.append("name", fields.name);
275
+ }
276
+ form.append("renderMode", fields.renderMode);
277
+ form.append("importStructure", "false");
278
+ form.append("importEntries", "false");
279
+ form.append("importMedia", "false");
280
+ form.append("file", new Blob([new Uint8Array(zip)], { type: "application/zip" }), "theme.zip");
281
+ return form;
282
+ }
283
+ async requestJson(url, init = {}) {
284
+ const response = await this.send(url, init);
285
+ return await response.json();
286
+ }
287
+ async send(url, init = {}) {
288
+ const headers = new Headers(init.headers);
289
+ headers.set("Authorization", `Bearer ${this.connection.token}`);
290
+ headers.set("Accept", "application/json");
291
+ const response = await this.fetchImpl(url, { ...init, headers });
292
+ if (!response.ok) {
293
+ throw await ApiError.fromResponse(response);
294
+ }
295
+ return response;
296
+ }
297
+ };
298
+
299
+ // src/lib/pull.ts
300
+ import { mkdir as mkdir4, readdir } from "fs/promises";
301
+ import { resolve as resolve2 } from "path";
302
+
303
+ // src/lib/zip.ts
304
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
305
+ import { dirname as dirname2, isAbsolute, resolve, sep } from "path";
306
+ import { unzipSync, zipSync } from "fflate";
307
+ var resolveArchivePath = (targetDir, entryName) => {
308
+ const normalized = entryName.replace(/\\/g, "/");
309
+ if (isAbsolute(entryName) || normalized.startsWith("/") || /^[a-zA-Z]:/.test(normalized)) {
310
+ throw new CliError(`Unsafe archive path: ${entryName}`);
311
+ }
312
+ if (normalized.split("/").some((segment) => segment === "..")) {
313
+ throw new CliError(`Unsafe archive path: ${entryName}`);
314
+ }
315
+ const root = resolve(targetDir);
316
+ const target = resolve(root, normalized);
317
+ if (!target.startsWith(root + sep)) {
318
+ throw new CliError(`Unsafe archive path: ${entryName}`);
319
+ }
320
+ return target;
321
+ };
322
+ var extractZip = async (archive, targetDir) => {
323
+ const entries = unzipSync(archive);
324
+ const plan = Object.entries(entries).filter(([name]) => !name.endsWith("/")).map(([name, bytes]) => ({ name, bytes, target: resolveArchivePath(targetDir, name) }));
325
+ for (const item of plan) {
326
+ await mkdir2(dirname2(item.target), { recursive: true });
327
+ await writeFile2(item.target, item.bytes);
328
+ }
329
+ return plan.map((item) => item.name);
330
+ };
331
+ var buildZip = (files) => {
332
+ const input = {};
333
+ for (const file of files) {
334
+ input[file.path] = file.bytes;
335
+ }
336
+ return zipSync(input, { level: 6 });
337
+ };
338
+
339
+ // src/lib/metadata.ts
340
+ import { mkdir as mkdir3, readFile as readFile2, writeFile as writeFile3 } from "fs/promises";
341
+ import { join as join2 } from "path";
342
+ var themeExportModes = ["theme", "theme-structure", "theme-complete"];
343
+ var metadataPath = (themeDir) => {
344
+ return join2(themeDir, metadataFolderName, metadataFileName);
345
+ };
346
+ var readThemeMetadata = async (themeDir) => {
347
+ let raw;
348
+ try {
349
+ raw = await readFile2(metadataPath(themeDir), "utf8");
350
+ } catch (error) {
351
+ if (error.code === "ENOENT") {
352
+ return null;
353
+ }
354
+ throw error;
355
+ }
356
+ try {
357
+ return JSON.parse(raw);
358
+ } catch {
359
+ throw new CliError(`${metadataPath(themeDir)} is not valid JSON.`);
360
+ }
361
+ };
362
+ var writeThemeMetadata = async (themeDir, metadata) => {
363
+ await mkdir3(join2(themeDir, metadataFolderName), { recursive: true });
364
+ const content = JSON.stringify({ ...metadata, version: metadataSchemaVersion }, null, 4);
365
+ await writeFile3(metadataPath(themeDir), `${content}
366
+ `);
367
+ };
368
+
369
+ // src/lib/pull.ts
370
+ var isExportMode = (value) => {
371
+ return themeExportModes.includes(value);
372
+ };
373
+ var findTheme = (themes, reference) => {
374
+ const match = themes.find((theme) => theme.id === reference || theme.slug === reference);
375
+ if (!match) {
376
+ throw new CliError(`Theme "${reference}" was not found in this store.`);
377
+ }
378
+ return match;
379
+ };
380
+ var isNonEmptyDirectory = async (dir) => {
381
+ try {
382
+ const entries = await readdir(dir);
383
+ return entries.length > 0;
384
+ } catch (error) {
385
+ if (error.code === "ENOENT") {
386
+ return false;
387
+ }
388
+ throw error;
389
+ }
390
+ };
391
+ var pullTheme = async (options) => {
392
+ const targetDir = resolve2(options.targetDir);
393
+ if (!options.force && await isNonEmptyDirectory(targetDir)) {
394
+ throw new CliError(`Refusing to overwrite non-empty folder ${targetDir}. Pass --force to overwrite.`);
395
+ }
396
+ const archive = await options.client.exportZip(options.theme.id, options.mode);
397
+ await mkdir4(targetDir, { recursive: true });
398
+ await extractZip(archive, targetDir);
399
+ const localFiles = await readLocalTheme(targetDir);
400
+ const metadata = {
401
+ version: metadataSchemaVersion,
402
+ cmsUrl: options.cmsUrl,
403
+ store: options.store,
404
+ themeId: options.theme.id,
405
+ slug: options.theme.slug,
406
+ renderMode: options.theme.renderMode,
407
+ pulledVersion: options.theme.version,
408
+ mode: options.mode,
409
+ baseHashes: toHashMap(localFiles)
410
+ };
411
+ await writeThemeMetadata(targetDir, metadata);
412
+ return { dir: targetDir, fileCount: localFiles.length };
413
+ };
414
+
415
+ // src/commands/pull.ts
416
+ var pullHelp = `Usage: ${cliName} pull [theme] [options]
417
+
418
+ Downloads a theme from the CMS (export-zip) into a folder and records the base hashes
419
+ that later status and push commands compare against.
420
+
421
+ Arguments:
422
+ theme Theme id or slug. Optional when the folder already has a theme linked.
423
+
424
+ Options:
425
+ --mode <mode> ${themeExportModes.join(" | ")} (default: theme)
426
+ --dir <folder> Target folder (default: ./<theme slug>, or the current folder when linked)
427
+ --force Overwrite a non-empty target folder
428
+ --cms-url <url> CMS base URL (default: from the linked theme or the only saved login)
429
+ --store <slug> Store slug (default: from the linked theme or the only saved login)
430
+ --published Not supported yet: the server exports only the draft
431
+ -h, --help Show this help
432
+ `;
433
+ var runPull = async (argv) => {
434
+ const { values, positionals } = parseCommandArgs(argv, {
435
+ "cms-url": { type: "string" },
436
+ store: { type: "string" },
437
+ mode: { type: "string" },
438
+ dir: { type: "string" },
439
+ force: { type: "boolean" },
440
+ published: { type: "boolean" }
441
+ });
442
+ if (booleanOption(values, "published")) {
443
+ throw new CliError(
444
+ "--published is not supported: the server only exports the draft theme (no published-version export)."
445
+ );
446
+ }
447
+ const mode = stringOption(values, "mode") ?? "theme";
448
+ if (!isExportMode(mode)) {
449
+ throw new CliError(`Invalid --mode "${mode}". Use one of: ${themeExportModes.join(", ")}.`);
450
+ }
451
+ const reference = positionals[0];
452
+ const dirOption = stringOption(values, "dir");
453
+ const existing = await readThemeMetadata(resolve3(dirOption ?? "."));
454
+ const ref = reference ?? existing?.themeId;
455
+ if (!ref) {
456
+ throw new CliError("Pass a theme id or slug, or run pull inside a folder that already has a linked theme.");
457
+ }
458
+ const connection = await resolveConnection({
459
+ cmsUrl: stringOption(values, "cms-url"),
460
+ store: stringOption(values, "store"),
461
+ metadata: existing
462
+ });
463
+ const client = new CmsClient(connection);
464
+ const theme = findTheme(await client.listThemes(), ref);
465
+ const targetDir = dirOption ?? (reference ? theme.slug : ".");
466
+ const result = await pullTheme({
467
+ client,
468
+ theme,
469
+ mode,
470
+ targetDir,
471
+ force: booleanOption(values, "force"),
472
+ cmsUrl: connection.cmsUrl,
473
+ store: connection.store
474
+ });
475
+ console.log(`Pulled "${theme.name}" (${mode}) into ${result.dir}: ${result.fileCount} files.`);
476
+ };
477
+
478
+ // src/commands/themes.ts
479
+ var themesHelp = `Usage: ${cliName} themes [options]
480
+
481
+ Lists the themes of the store (id, slug, render mode, version).
482
+
483
+ Options:
484
+ --cms-url <url> CMS base URL (default: the only saved login)
485
+ --store <slug> Store slug (default: the only saved login)
486
+ -h, --help Show this help
487
+ `;
488
+ var runThemes = async (argv) => {
489
+ const { values } = parseCommandArgs(argv, {
490
+ "cms-url": { type: "string" },
491
+ store: { type: "string" }
492
+ });
493
+ const connection = await resolveConnection({
494
+ cmsUrl: stringOption(values, "cms-url"),
495
+ store: stringOption(values, "store")
496
+ });
497
+ const themes = await new CmsClient(connection).listThemes();
498
+ if (themes.length === 0) {
499
+ console.log("No themes in this store.");
500
+ return;
501
+ }
502
+ for (const theme of themes) {
503
+ console.log(`${theme.id} ${theme.slug} ${theme.renderMode} v${theme.version ?? "-"} ${theme.name}`);
504
+ }
505
+ };
506
+
507
+ // src/commands/push.ts
508
+ import { resolve as resolve4 } from "path";
509
+
510
+ // src/lib/push.ts
511
+ var maxBatchFiles = 200;
512
+ var chunkArray = (items, size) => {
513
+ const chunks = [];
514
+ for (let index = 0; index < items.length; index += size) {
515
+ chunks.push(items.slice(index, index + size));
516
+ }
517
+ return chunks;
518
+ };
519
+ var findConflicts = (base, local, remote) => {
520
+ const paths = /* @__PURE__ */ new Set([...Object.keys(base), ...Object.keys(local), ...Object.keys(remote)]);
521
+ const conflicts = [];
522
+ for (const path of [...paths].sort()) {
523
+ const baseHash = base[path];
524
+ const remoteHash = remote[path];
525
+ if (baseHash !== void 0) {
526
+ if (remoteHash !== baseHash) {
527
+ conflicts.push({ path, expected: baseHash, remote: remoteHash ?? null });
528
+ }
529
+ continue;
530
+ }
531
+ if (remoteHash !== void 0 && remoteHash !== local[path]) {
532
+ conflicts.push({ path, expected: null, remote: remoteHash });
533
+ }
534
+ }
535
+ return conflicts;
536
+ };
537
+ var toRemoteHashes = (files) => {
538
+ const hashes = {};
539
+ for (const file of files) {
540
+ if (isPushablePath(file.filename)) {
541
+ hashes[file.filename] = file.contentHash ?? "";
542
+ }
543
+ }
544
+ return hashes;
545
+ };
546
+ var formatConflicts = (conflicts) => {
547
+ const lines = conflicts.map((conflict) => {
548
+ return ` - ${conflict.path} (pulled ${conflict.expected ?? "none"}, remote ${conflict.remote ?? "missing"})`;
549
+ });
550
+ return [
551
+ "The theme changed on the CMS since you pulled it. Conflicting files:",
552
+ ...lines,
553
+ "Run pull into a new folder to merge, or pass --force to overwrite."
554
+ ].join("\n");
555
+ };
556
+ var toBatchFile = (file, baseHashes, force) => {
557
+ const expectedHash = force ? void 0 : baseHashes[file.path];
558
+ return {
559
+ filename: file.path,
560
+ content: new TextDecoder().decode(file.bytes),
561
+ expectedHash
562
+ };
563
+ };
564
+ var pushTheme = async (options) => {
565
+ if (options.create && options.metadata) {
566
+ throw new CliError(
567
+ `This folder is already linked to theme ${options.metadata.themeId}. Remove .cms-theme-kit to create a new theme.`
568
+ );
569
+ }
570
+ const localFiles = await readLocalTheme(options.dir);
571
+ if (localFiles.length === 0) {
572
+ throw new CliError(`No theme files found in ${options.dir}.`);
573
+ }
574
+ const localHashes = toHashMap(localFiles);
575
+ const baseHashes = options.metadata?.baseHashes ?? {};
576
+ const diff = diffHashes(baseHashes, localHashes);
577
+ if (options.create) {
578
+ return createTheme(options, localFiles, localHashes, diff);
579
+ }
580
+ const metadata = options.metadata;
581
+ const changedCount = diff.added.length + diff.modified.length + diff.deleted.length;
582
+ if (changedCount === 0) {
583
+ return { method: "none", diff, themeId: metadata.themeId, dryRun: options.dryRun };
584
+ }
585
+ const remoteFiles = await options.client.listFiles(metadata.themeId);
586
+ const conflicts = findConflicts(baseHashes, localHashes, toRemoteHashes(remoteFiles));
587
+ if (conflicts.length > 0 && !options.force) {
588
+ throw new CliError(formatConflicts(conflicts));
589
+ }
590
+ const needsZip = diff.deleted.length > 0 || [...diff.added, ...diff.modified].some((path) => !isTextPath(path));
591
+ const method = needsZip ? "zip" : "batch";
592
+ if (options.dryRun) {
593
+ return { method, diff, themeId: metadata.themeId, dryRun: true };
594
+ }
595
+ if (needsZip) {
596
+ const zip = buildZip(localFiles);
597
+ await options.client.uploadThemeZip(metadata.themeId, zip, metadata.renderMode);
598
+ metadata.baseHashes = localHashes;
599
+ await writeThemeMetadata(options.dir, metadata);
600
+ return { method, diff, themeId: metadata.themeId, dryRun: false };
601
+ }
602
+ const changedPaths = /* @__PURE__ */ new Set([...diff.added, ...diff.modified]);
603
+ const changedFiles = localFiles.filter((file) => changedPaths.has(file.path));
604
+ for (const chunk of chunkArray(changedFiles, maxBatchFiles)) {
605
+ const batch = chunk.map((file) => toBatchFile(file, baseHashes, options.force));
606
+ await options.client.saveFilesBatch(metadata.themeId, batch);
607
+ for (const file of chunk) {
608
+ metadata.baseHashes[file.path] = file.hash;
609
+ }
610
+ await writeThemeMetadata(options.dir, metadata);
611
+ }
612
+ return { method, diff, themeId: metadata.themeId, dryRun: false };
613
+ };
614
+ var createTheme = async (options, localFiles, localHashes, diff) => {
615
+ if (!options.name) {
616
+ throw new CliError("Creating a theme needs --name <name>.");
617
+ }
618
+ if (options.dryRun) {
619
+ return { method: "create", diff, themeId: null, dryRun: true };
620
+ }
621
+ const theme = await options.client.createThemeFromZip(
622
+ { name: options.name, renderMode: options.renderMode },
623
+ buildZip(localFiles)
624
+ );
625
+ const metadata = {
626
+ version: metadataSchemaVersion,
627
+ cmsUrl: options.cmsUrl,
628
+ store: options.store,
629
+ themeId: theme.id,
630
+ slug: theme.slug,
631
+ renderMode: theme.renderMode,
632
+ pulledVersion: theme.version,
633
+ mode: "theme",
634
+ baseHashes: localHashes
635
+ };
636
+ await writeThemeMetadata(options.dir, metadata);
637
+ return { method: "create", diff, themeId: theme.id, dryRun: false };
638
+ };
639
+
640
+ // src/commands/push.ts
641
+ var pushHelp = `Usage: ${cliName} push [options]
642
+
643
+ Sends locally changed theme files to the CMS as a draft. Never publishes.
644
+ Text changes go through files/batch (chunks of 200). Deletions, binary assets, or any
645
+ remote change to a file you did not pull force a whole-theme zip upload instead.
646
+
647
+ Options:
648
+ --dir <folder> Theme folder (default: current folder)
649
+ --dry-run Show what would be sent, without sending it
650
+ --force Overwrite files changed on the CMS since pull
651
+ --create --name <name> Create a new theme from this folder instead of updating a linked one
652
+ --render-mode <mode> liquid | static (used with --create; default: linked theme's mode, else liquid)
653
+ --cms-url <url> CMS base URL (default: from the linked theme or the only saved login)
654
+ --store <slug> Store slug (default: from the linked theme or the only saved login)
655
+ -h, --help Show this help
656
+ `;
657
+ var renderModes = ["liquid", "static"];
658
+ var describeSummary = (summary) => {
659
+ const { added, modified, deleted } = summary.diff;
660
+ const counts = `${added.length} added, ${modified.length} modified, ${deleted.length} deleted`;
661
+ if (summary.method === "none") {
662
+ return "No local changes to push.";
663
+ }
664
+ if (summary.dryRun) {
665
+ return `Dry run: would push via ${summary.method} (${counts}). Nothing was sent.`;
666
+ }
667
+ if (summary.method === "create") {
668
+ return `Created theme ${summary.themeId}. It is a draft; nothing was published.`;
669
+ }
670
+ const target = `theme ${summary.themeId} via ${summary.method} (${counts})`;
671
+ return `Pushed to ${target}. Saved as draft; the live theme was not changed.`;
672
+ };
673
+ var runPush = async (argv) => {
674
+ const { values } = parseCommandArgs(argv, {
675
+ dir: { type: "string" },
676
+ "cms-url": { type: "string" },
677
+ store: { type: "string" },
678
+ force: { type: "boolean" },
679
+ "dry-run": { type: "boolean" },
680
+ create: { type: "boolean" },
681
+ name: { type: "string" },
682
+ "render-mode": { type: "string" }
683
+ });
684
+ const dir = resolve4(stringOption(values, "dir") ?? ".");
685
+ const metadata = await readThemeMetadata(dir);
686
+ const renderMode = stringOption(values, "render-mode") ?? metadata?.renderMode ?? "liquid";
687
+ if (!renderModes.includes(renderMode)) {
688
+ throw new CliError(`Invalid --render-mode "${renderMode}". Use liquid or static.`);
689
+ }
690
+ const connection = await resolveConnection({
691
+ cmsUrl: stringOption(values, "cms-url"),
692
+ store: stringOption(values, "store"),
693
+ metadata
694
+ });
695
+ const summary = await pushTheme({
696
+ dir,
697
+ client: new CmsClient(connection),
698
+ metadata,
699
+ cmsUrl: connection.cmsUrl,
700
+ store: connection.store,
701
+ create: booleanOption(values, "create"),
702
+ name: stringOption(values, "name"),
703
+ renderMode,
704
+ force: booleanOption(values, "force"),
705
+ dryRun: booleanOption(values, "dry-run")
706
+ });
707
+ console.log(describeSummary(summary));
708
+ };
709
+
710
+ // src/commands/status.ts
711
+ import { resolve as resolve5 } from "path";
712
+
713
+ // src/lib/status.ts
714
+ var remoteChangedPaths = (base, remote) => {
715
+ const paths = /* @__PURE__ */ new Set([...Object.keys(base), ...Object.keys(remote)]);
716
+ const changed = [];
717
+ for (const path of [...paths].sort()) {
718
+ if (base[path] !== remote[path]) {
719
+ changed.push(path);
720
+ }
721
+ }
722
+ return changed;
723
+ };
724
+
725
+ // src/commands/status.ts
726
+ var statusHelp = `Usage: ${cliName} status [options]
727
+
728
+ Compares the local theme folder with the hashes recorded at pull time.
729
+
730
+ Options:
731
+ --dir <folder> Theme folder (default: current folder)
732
+ --remote Also fetch the CMS file list and show files changed on the CMS since pull
733
+ --cms-url <url> CMS base URL (only used with --remote)
734
+ --store <slug> Store slug (only used with --remote)
735
+ -h, --help Show this help
736
+ `;
737
+ var printSection = (title, paths) => {
738
+ console.log(`${title} (${paths.length}):`);
739
+ for (const path of paths) {
740
+ console.log(` ${path}`);
741
+ }
742
+ };
743
+ var runStatus = async (argv) => {
744
+ const { values } = parseCommandArgs(argv, {
745
+ dir: { type: "string" },
746
+ remote: { type: "boolean" },
747
+ "cms-url": { type: "string" },
748
+ store: { type: "string" }
749
+ });
750
+ const dir = resolve5(stringOption(values, "dir") ?? ".");
751
+ const metadata = await readThemeMetadata(dir);
752
+ if (!metadata) {
753
+ throw new CliError(`No ${metadataFolderName}/${metadataFileName} in ${dir}. Run pull first.`);
754
+ }
755
+ const localHashes = toHashMap(await readLocalTheme(dir));
756
+ const diff = diffHashes(metadata.baseHashes, localHashes);
757
+ console.log(`Theme "${metadata.slug}" (${metadata.themeId}) in ${dir}`);
758
+ printSection("Added locally", diff.added);
759
+ printSection("Modified locally", diff.modified);
760
+ printSection("Deleted locally", diff.deleted);
761
+ if (booleanOption(values, "remote")) {
762
+ const connection = await resolveConnection({
763
+ cmsUrl: stringOption(values, "cms-url"),
764
+ store: stringOption(values, "store"),
765
+ metadata
766
+ });
767
+ const client = new CmsClient(connection);
768
+ const remoteHashes = toRemoteHashes(await client.listFiles(metadata.themeId));
769
+ printSection("Changed on the CMS since pull", remoteChangedPaths(metadata.baseHashes, remoteHashes));
770
+ }
771
+ };
772
+
773
+ // src/commands/dev.ts
774
+ import { stat } from "fs/promises";
775
+ import { join as join3, resolve as resolve6 } from "path";
776
+
777
+ // src/lib/dev/watcher.ts
778
+ import { watch } from "fs";
779
+ var ignoredSegments = [metadataFolderName, "node_modules", ".git"];
780
+ var isIgnoredWatchPath = (relativePath) => {
781
+ return relativePath.split(/[\\/]/).some((segment) => ignoredSegments.includes(segment));
782
+ };
783
+ var watchThemeDir = (themeDir, onChange, debounceMs = 100) => {
784
+ let timer;
785
+ const watcher = watch(themeDir, { recursive: true }, (_eventType, filename) => {
786
+ if (filename && isIgnoredWatchPath(String(filename))) {
787
+ return;
788
+ }
789
+ clearTimeout(timer);
790
+ timer = setTimeout(onChange, debounceMs);
791
+ });
792
+ return {
793
+ close: () => {
794
+ clearTimeout(timer);
795
+ watcher.close();
796
+ }
797
+ };
798
+ };
799
+
800
+ // src/commands/dev.ts
801
+ var devHelp = `Usage: ${cliName} dev [options]
802
+
803
+ Serves the theme on localhost. Liquid themes are rendered with the same engine as the theme editor preview;
804
+ static themes (static/index.html) are served as plain HTML pages.
805
+ Saving a file in the theme folder reloads open pages. Stop with Ctrl-C.
806
+
807
+ Options:
808
+ --dir <folder> Theme folder (default: current folder)
809
+ --port <n> Port to listen on (default: 4400)
810
+ --mode <mode> liquid | static (default: from the linked theme; without one, static when the
811
+ folder has static/index.html and no templates/)
812
+ --data <source> live | fixtures (default: live; liquid themes only)
813
+ live: preview data from the CMS (needs a pulled theme and login)
814
+ fixtures: fixtures/<template path with / replaced by -> JSON file
815
+ --country <code> Country code sent with live data requests, e.g. AE
816
+ --lang <code> Language used for locale overrides (default: en)
817
+ --template <path> Template served at / (default: templates/index.json; liquid themes only)
818
+ --cms-url <url> CMS base URL (live data only; default: from the linked theme or the only saved login)
819
+ --store <slug> Store slug (live data only; default: from the linked theme or the only saved login)
820
+ -h, --help Show this help
821
+ `;
822
+ var defaultPort = 4400;
823
+ var defaultTemplate = "templates/index.json";
824
+ var defaultLanguage = "en";
825
+ var dataSourceNames = ["live", "fixtures"];
826
+ var devModes = ["liquid", "static"];
827
+ var parsePort = (value) => {
828
+ if (value === void 0) {
829
+ return defaultPort;
830
+ }
831
+ const port = Number(value);
832
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
833
+ throw new CliError(`Invalid --port "${value}". Use a whole number from 0 to 65535.`);
834
+ }
835
+ return port;
836
+ };
837
+ var pathExists = async (path) => {
838
+ try {
839
+ await stat(path);
840
+ return true;
841
+ } catch {
842
+ return false;
843
+ }
844
+ };
845
+ var resolveDevMode = async (requested, themeDir, metadata) => {
846
+ if (requested !== void 0) {
847
+ if (!devModes.includes(requested)) {
848
+ throw new CliError(`Invalid --mode "${requested}". Use liquid or static.`);
849
+ }
850
+ return requested;
851
+ }
852
+ if (metadata) {
853
+ return metadata.renderMode === "static" ? "static" : "liquid";
854
+ }
855
+ const hasStaticHome = await pathExists(join3(themeDir, staticThemeHomePath));
856
+ const hasTemplates = await pathExists(join3(themeDir, liquidThemeFolderNames.templates));
857
+ return hasStaticHome && !hasTemplates ? "static" : "liquid";
858
+ };
859
+ var waitForShutdown = () => {
860
+ return new Promise((resolveWait) => {
861
+ process.once("SIGINT", resolveWait);
862
+ process.once("SIGTERM", resolveWait);
863
+ });
864
+ };
865
+ var serveUntilInterrupted = async (themeDir, server) => {
866
+ const watcher = watchThemeDir(themeDir, () => {
867
+ server.notifyChanged().catch((error) => {
868
+ console.error(`error: could not reload theme: ${error instanceof Error ? error.message : String(error)}`);
869
+ });
870
+ });
871
+ await waitForShutdown();
872
+ watcher.close();
873
+ await server.close();
874
+ };
875
+ var runDev = async (argv) => {
876
+ const { values } = parseCommandArgs(argv, {
877
+ dir: { type: "string" },
878
+ port: { type: "string" },
879
+ mode: { type: "string" },
880
+ data: { type: "string" },
881
+ country: { type: "string" },
882
+ lang: { type: "string" },
883
+ template: { type: "string" },
884
+ "cms-url": { type: "string" },
885
+ store: { type: "string" }
886
+ });
887
+ const dir = resolve6(stringOption(values, "dir") ?? ".");
888
+ const port = parsePort(stringOption(values, "port"));
889
+ const metadata = await readThemeMetadata(dir);
890
+ const mode = await resolveDevMode(stringOption(values, "mode"), dir, metadata);
891
+ if (mode === "static") {
892
+ const { startStaticDevServer } = await import("./static-server-WWP7CW4C.js");
893
+ const server2 = await startStaticDevServer({ themeDir: dir, port });
894
+ console.log(`Previewing static theme at ${server2.url}/`);
895
+ console.log(`Pages: ${server2.url}/__templates`);
896
+ console.log("Press Ctrl-C to stop.");
897
+ await serveUntilInterrupted(dir, server2);
898
+ return;
899
+ }
900
+ const { createFixturesDataSource, createLiveDataSource } = await import("./data-source-63RC4O5W.js");
901
+ const { startDevServer } = await import("./server-GITJIQTE.js");
902
+ const dataMode = stringOption(values, "data") ?? "live";
903
+ const templatePath = stringOption(values, "template") ?? defaultTemplate;
904
+ const countryCode = stringOption(values, "country");
905
+ const languageCode = stringOption(values, "lang") ?? defaultLanguage;
906
+ if (!dataSourceNames.includes(dataMode)) {
907
+ throw new CliError(`Invalid --data "${dataMode}". Use live or fixtures.`);
908
+ }
909
+ if (!templatePath.startsWith("templates/") || !templatePath.endsWith(".json")) {
910
+ throw new CliError(`Invalid --template "${templatePath}". Use a path like templates/index.json.`);
911
+ }
912
+ let dataSource;
913
+ if (dataMode === "fixtures") {
914
+ dataSource = createFixturesDataSource(dir);
915
+ } else {
916
+ if (!metadata) {
917
+ throw new CliError(`No ${metadataFolderName}/${metadataFileName} in ${dir}. Run pull first, or use --data fixtures.`);
918
+ }
919
+ const connection = await resolveConnection({
920
+ cmsUrl: stringOption(values, "cms-url"),
921
+ store: stringOption(values, "store"),
922
+ metadata
923
+ });
924
+ dataSource = createLiveDataSource({
925
+ client: new CmsClient(connection),
926
+ themeId: metadata.themeId,
927
+ countryCode
928
+ });
929
+ }
930
+ const server = await startDevServer({
931
+ themeDir: dir,
932
+ port,
933
+ templatePath,
934
+ languageCode,
935
+ countryCode,
936
+ dataSource
937
+ });
938
+ console.log(`Previewing ${templatePath} at ${server.url}/ (data: ${dataMode}).`);
939
+ console.log(`Templates: ${server.url}/__templates`);
940
+ console.log("Press Ctrl-C to stop.");
941
+ await serveUntilInterrupted(dir, server);
942
+ };
943
+
944
+ // src/commands/validate.ts
945
+ import { resolve as resolve7 } from "path";
946
+ var validateHelp = `Usage: ${cliName} validate [options]
947
+
948
+ Checks the local theme with the same rules the CMS applies when publishing.
949
+ Only changed files are sent; nothing is saved on the CMS.
950
+
951
+ Options:
952
+ --dir <folder> Theme folder (default: current folder)
953
+ --cms-url <url> CMS base URL
954
+ --store <slug> Store slug
955
+ -h, --help Show this help
956
+ `;
957
+ var runValidate = async (argv) => {
958
+ const { values } = parseCommandArgs(argv, {
959
+ dir: { type: "string" },
960
+ "cms-url": { type: "string" },
961
+ store: { type: "string" }
962
+ });
963
+ const dir = resolve7(stringOption(values, "dir") ?? ".");
964
+ const metadata = await readThemeMetadata(dir);
965
+ if (!metadata) {
966
+ throw new CliError(`No ${metadataFolderName}/${metadataFileName} in ${dir}. Run pull first.`);
967
+ }
968
+ const localFiles = await readLocalTheme(dir);
969
+ const diff = diffHashes(metadata.baseHashes, toHashMap(localFiles));
970
+ const changed = /* @__PURE__ */ new Set([...diff.added, ...diff.modified]);
971
+ const files = localFiles.filter((file) => changed.has(file.path) && isTextPath(file.path)).map((file) => ({ filename: file.path, content: Buffer.from(file.bytes).toString("utf8") }));
972
+ const connection = await resolveConnection({
973
+ cmsUrl: stringOption(values, "cms-url"),
974
+ store: stringOption(values, "store"),
975
+ metadata
976
+ });
977
+ const result = await new CmsClient(connection).validateFiles(metadata.themeId, files, diff.deleted);
978
+ if (result.valid) {
979
+ console.log("Theme is valid.");
980
+ return;
981
+ }
982
+ for (const issue of result.issues) {
983
+ const location = [issue.filename, issue.path].filter(Boolean).join(" ");
984
+ console.error(`${location ? `${location}: ` : ""}${issue.message}`);
985
+ }
986
+ throw new CliError(`${result.issues.length} validation issue(s).`);
987
+ };
988
+
989
+ // src/cli.ts
990
+ var commands = {
991
+ login: {
992
+ summary: "Sign in to a CMS store and save the token",
993
+ help: loginHelp,
994
+ run: runLogin
995
+ },
996
+ themes: {
997
+ summary: "List the themes of the store",
998
+ help: themesHelp,
999
+ run: runThemes
1000
+ },
1001
+ pull: {
1002
+ summary: "Download a theme into a local folder",
1003
+ help: pullHelp,
1004
+ run: runPull
1005
+ },
1006
+ status: {
1007
+ summary: "Show local changes since the last pull",
1008
+ help: statusHelp,
1009
+ run: runStatus
1010
+ },
1011
+ push: {
1012
+ summary: "Send changed theme files back as a draft",
1013
+ help: pushHelp,
1014
+ run: runPush
1015
+ },
1016
+ dev: {
1017
+ summary: "Serve the theme locally with live reload",
1018
+ help: devHelp,
1019
+ run: runDev
1020
+ },
1021
+ validate: {
1022
+ summary: "Check the local theme with the CMS publish rules",
1023
+ help: validateHelp,
1024
+ run: runValidate
1025
+ }
1026
+ };
1027
+ var mainHelp = () => {
1028
+ const lines = Object.entries(commands).map(([name, entry]) => ` ${name.padEnd(10)}${entry.summary}`);
1029
+ return [
1030
+ `Usage: ${cliName} <command> [options]`,
1031
+ "",
1032
+ "Commands:",
1033
+ ...lines,
1034
+ "",
1035
+ `Run "${cliName} <command> --help" for command options.`,
1036
+ "Set CMS_THEME_KIT_TOKEN to use a token without a saved login.",
1037
+ ""
1038
+ ].join("\n");
1039
+ };
1040
+ var describeError = (error) => {
1041
+ if (error instanceof CliError) {
1042
+ return error.message;
1043
+ }
1044
+ if (error instanceof Error) {
1045
+ const cause = error.cause instanceof Error ? `: ${error.cause.message}` : "";
1046
+ return `${error.message}${cause}`;
1047
+ }
1048
+ return String(error);
1049
+ };
1050
+ var main = async (argv) => {
1051
+ const [name, ...rest] = argv;
1052
+ if (!name || name === "--help" || name === "-h" || name === "help") {
1053
+ console.log(mainHelp());
1054
+ return 0;
1055
+ }
1056
+ if (!Object.hasOwn(commands, name)) {
1057
+ console.error(`error: unknown command "${name}"
1058
+ `);
1059
+ console.error(mainHelp());
1060
+ return 1;
1061
+ }
1062
+ const command = commands[name];
1063
+ if (rest.includes("--help") || rest.includes("-h")) {
1064
+ console.log(command.help);
1065
+ return 0;
1066
+ }
1067
+ try {
1068
+ await command.run(rest);
1069
+ return 0;
1070
+ } catch (error) {
1071
+ console.error(`error: ${describeError(error)}`);
1072
+ return error instanceof CliError ? error.exitCode : 1;
1073
+ }
1074
+ };
1075
+
1076
+ // src/bin.ts
1077
+ process.exitCode = await main(process.argv.slice(2));
1078
+ //# sourceMappingURL=bin.js.map