@tomsher/cms-theme-kit 0.1.3 → 0.1.6
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 +34 -10
- package/dist/bin.js.map +1 -1
- package/dist/{chunk-ZUBE6H6H.js → chunk-OATE235V.js} +24 -11
- package/dist/chunk-OATE235V.js.map +1 -0
- package/dist/{chunk-C5SWGZ55.js → chunk-PEG6K5NX.js} +2 -2
- package/dist/{chunk-OJEPFH5L.js → chunk-UMGL5N53.js} +236 -310
- package/dist/chunk-UMGL5N53.js.map +1 -0
- package/dist/{chunk-QOSNX2RN.js → chunk-VDICVCKJ.js} +17 -17
- package/dist/chunk-VDICVCKJ.js.map +1 -0
- package/dist/{chunk-UOEFVNM4.js → chunk-VY553LTO.js} +171 -64
- package/dist/chunk-VY553LTO.js.map +1 -0
- package/dist/{data-source-XSFJYQNF.js → data-source-I5BXXWXI.js} +4 -4
- package/dist/{server-EN4JAEFG.js → server-PV5PFQ7A.js} +39 -12
- package/dist/server-PV5PFQ7A.js.map +1 -0
- package/dist/{static-server-7OTKQJZM.js → static-server-7NG4AY2E.js} +5 -5
- package/dist/static-server-7NG4AY2E.js.map +1 -0
- package/package.json +2 -3
- package/dist/chunk-OJEPFH5L.js.map +0 -1
- package/dist/chunk-QOSNX2RN.js.map +0 -1
- package/dist/chunk-UOEFVNM4.js.map +0 -1
- package/dist/chunk-ZUBE6H6H.js.map +0 -1
- package/dist/server-EN4JAEFG.js.map +0 -1
- package/dist/static-server-7OTKQJZM.js.map +0 -1
- /package/dist/{chunk-C5SWGZ55.js.map → chunk-PEG6K5NX.js.map} +0 -0
- /package/dist/{data-source-XSFJYQNF.js.map → data-source-I5BXXWXI.js.map} +0 -0
package/dist/bin.js
CHANGED
|
@@ -4,14 +4,14 @@ import {
|
|
|
4
4
|
isTextPath,
|
|
5
5
|
readLocalTheme,
|
|
6
6
|
toHashMap
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-PEG6K5NX.js";
|
|
8
8
|
import {
|
|
9
9
|
ApiError,
|
|
10
10
|
CliError,
|
|
11
11
|
diffHashes,
|
|
12
12
|
liquidThemeFolderNames,
|
|
13
13
|
staticThemeHomePath
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-VY553LTO.js";
|
|
15
15
|
|
|
16
16
|
// src/constants.ts
|
|
17
17
|
var cliName = "cms-theme-kit";
|
|
@@ -225,16 +225,32 @@ var CmsClient = class {
|
|
|
225
225
|
}
|
|
226
226
|
// Returns the raw JSON body; the payload sits in requestedData (see transform.interceptor.ts).
|
|
227
227
|
async previewData(themeId, request, countryCode) {
|
|
228
|
-
const headers = { "Content-Type": "application/json" };
|
|
229
|
-
if (countryCode) {
|
|
230
|
-
headers["x-country-code"] = countryCode;
|
|
231
|
-
}
|
|
232
228
|
return this.requestJson(this.themesUrl(themeId, "preview-data"), {
|
|
233
229
|
method: "POST",
|
|
234
|
-
headers,
|
|
230
|
+
headers: this.jsonHeaders(countryCode),
|
|
235
231
|
body: JSON.stringify(request)
|
|
236
232
|
});
|
|
237
233
|
}
|
|
234
|
+
// Resolves a storefront URL to the template that serves it; null when no page matches.
|
|
235
|
+
async resolveRoute(themeId, path, templatePaths, countryCode) {
|
|
236
|
+
try {
|
|
237
|
+
const body = await this.requestJson(this.themesUrl(themeId, "resolve-route"), {
|
|
238
|
+
method: "POST",
|
|
239
|
+
headers: this.jsonHeaders(countryCode),
|
|
240
|
+
body: JSON.stringify({ path, templatePaths })
|
|
241
|
+
});
|
|
242
|
+
return unwrapRequestedData(body).templatePath;
|
|
243
|
+
} catch (error) {
|
|
244
|
+
if (error instanceof ApiError && error.status === 404) {
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
throw error;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
async listRoutes(themeId, countryCode) {
|
|
251
|
+
const headers = countryCode ? { "x-country-code": countryCode } : void 0;
|
|
252
|
+
return unwrapRequestedData(await this.requestJson(this.themesUrl(themeId, "routes"), { headers }));
|
|
253
|
+
}
|
|
238
254
|
async validateFiles(themeId, files, removed) {
|
|
239
255
|
const body = await this.requestJson(this.themesUrl(themeId, "validate"), {
|
|
240
256
|
method: "POST",
|
|
@@ -280,6 +296,13 @@ var CmsClient = class {
|
|
|
280
296
|
form.append("file", new Blob([new Uint8Array(zip)], { type: "application/zip" }), "theme.zip");
|
|
281
297
|
return form;
|
|
282
298
|
}
|
|
299
|
+
jsonHeaders(countryCode) {
|
|
300
|
+
const headers = { "Content-Type": "application/json" };
|
|
301
|
+
if (countryCode) {
|
|
302
|
+
headers["x-country-code"] = countryCode;
|
|
303
|
+
}
|
|
304
|
+
return headers;
|
|
305
|
+
}
|
|
283
306
|
async requestJson(url, init = {}) {
|
|
284
307
|
const response = await this.send(url, init);
|
|
285
308
|
return await response.json();
|
|
@@ -889,7 +912,7 @@ var runDev = async (argv) => {
|
|
|
889
912
|
const metadata = await readThemeMetadata(dir);
|
|
890
913
|
const mode = await resolveDevMode(stringOption(values, "mode"), dir, metadata);
|
|
891
914
|
if (mode === "static") {
|
|
892
|
-
const { startStaticDevServer } = await import("./static-server-
|
|
915
|
+
const { startStaticDevServer } = await import("./static-server-7NG4AY2E.js");
|
|
893
916
|
const server2 = await startStaticDevServer({ themeDir: dir, port });
|
|
894
917
|
console.log(`Previewing static theme at ${server2.url}/`);
|
|
895
918
|
console.log(`Pages: ${server2.url}/__templates`);
|
|
@@ -897,8 +920,8 @@ var runDev = async (argv) => {
|
|
|
897
920
|
await serveUntilInterrupted(dir, server2);
|
|
898
921
|
return;
|
|
899
922
|
}
|
|
900
|
-
const { createFixturesDataSource, createLiveDataSource } = await import("./data-source-
|
|
901
|
-
const { startDevServer } = await import("./server-
|
|
923
|
+
const { createFixturesDataSource, createLiveDataSource } = await import("./data-source-I5BXXWXI.js");
|
|
924
|
+
const { startDevServer } = await import("./server-PV5PFQ7A.js");
|
|
902
925
|
const dataMode = stringOption(values, "data") ?? "live";
|
|
903
926
|
const templatePath = stringOption(values, "template") ?? defaultTemplate;
|
|
904
927
|
const countryCode = stringOption(values, "country");
|
|
@@ -921,6 +944,7 @@ var runDev = async (argv) => {
|
|
|
921
944
|
store: stringOption(values, "store"),
|
|
922
945
|
metadata
|
|
923
946
|
});
|
|
947
|
+
process.env.NEXT_PUBLIC_IMAGE_URL ??= connection.cmsUrl;
|
|
924
948
|
dataSource = createLiveDataSource({
|
|
925
949
|
client: new CmsClient(connection),
|
|
926
950
|
themeId: metadata.themeId,
|
package/dist/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/constants.ts","../src/lib/credentials.ts","../src/lib/connection.ts","../src/lib/args.ts","../src/lib/envelope.ts","../src/lib/auth.ts","../src/lib/prompt.ts","../src/commands/login.ts","../src/commands/pull.ts","../src/lib/cms-client.ts","../src/lib/pull.ts","../src/lib/zip.ts","../src/lib/metadata.ts","../src/commands/themes.ts","../src/commands/push.ts","../src/lib/push.ts","../src/commands/status.ts","../src/lib/status.ts","../src/commands/dev.ts","../src/lib/dev/watcher.ts","../src/commands/validate.ts","../src/cli.ts","../src/bin.ts"],"sourcesContent":["export const cliName = 'cms-theme-kit';\nexport const packageScope = '@tomsher';\nexport const packageName = `${packageScope}/${cliName}`;\nexport const metadataFolderName = '.cms-theme-kit';\nexport const metadataFileName = 'theme.json';\nexport const metadataSchemaVersion = 1;\nexport const credentialsDirSegments = ['.config', 'tomsher'] as const;\nexport const credentialsFileName = 'credentials.json';\nexport const credentialsDisplayPath = `~/${credentialsDirSegments.join('/')}/${credentialsFileName}`;\nexport const tokenEnvVar = 'CMS_THEME_KIT_TOKEN';\n","import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { credentialsDirSegments, credentialsFileName } from '../constants';\nimport { CliError } from './errors';\n\nexport interface StoredLogin {\n cmsUrl: string;\n store: string;\n token: string;\n email: string | null;\n}\n\nexport interface CredentialsFile {\n logins: StoredLogin[];\n}\n\nexport const credentialsFilePath = (): string => {\n return join(homedir(), ...credentialsDirSegments, credentialsFileName);\n};\n\nexport const readCredentials = async (filePath: string = credentialsFilePath()): Promise<CredentialsFile> => {\n let raw: string;\n\n try {\n raw = await readFile(filePath, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return { logins: [] };\n }\n\n throw error;\n }\n\n let parsed: Partial<CredentialsFile>;\n\n try {\n parsed = JSON.parse(raw) as Partial<CredentialsFile>;\n } catch {\n throw new CliError(`Credentials file is not valid JSON: ${filePath}`);\n }\n\n return { logins: Array.isArray(parsed.logins) ? parsed.logins : [] };\n};\n\nexport const findLogin = (credentials: CredentialsFile, cmsUrl: string, store: string): StoredLogin | undefined => {\n return credentials.logins.find((login) => login.cmsUrl === cmsUrl && login.store === store);\n};\n\n// Stores one token per cmsUrl+store pair. The file is kept at mode 0600 because it holds bearer tokens.\nexport const saveLogin = async (login: StoredLogin, filePath: string = credentialsFilePath()): Promise<void> => {\n const credentials = await readCredentials(filePath);\n const others = credentials.logins.filter((item) => item.cmsUrl !== login.cmsUrl || item.store !== login.store);\n const content = JSON.stringify({ logins: [...others, login] }, null, 4);\n\n await mkdir(dirname(filePath), { recursive: true, mode: 0o700 });\n await writeFile(filePath, `${content}\\n`, { mode: 0o600 });\n await chmod(filePath, 0o600);\n};\n","import { tokenEnvVar } from '../constants';\nimport { CliError } from './errors';\nimport { readCredentials, findLogin } from './credentials';\nimport type { ThemeMetadata } from './metadata';\n\nexport interface CmsConnection {\n cmsUrl: string;\n store: string;\n token: string;\n}\n\nexport interface ConnectionOptions {\n cmsUrl?: string;\n store?: string;\n metadata?: ThemeMetadata | null;\n}\n\nexport const normalizeCmsUrl = (value: string): string => {\n return value.trim().replace(/\\/+$/, '');\n};\n\n// Precedence: flags, then the theme's own metadata, then the only saved login. The token comes from the env override first.\nexport const resolveConnection = async (options: ConnectionOptions): Promise<CmsConnection> => {\n const credentials = await readCredentials();\n const onlyLogin = credentials.logins.length === 1 ? credentials.logins[0] : undefined;\n const cmsUrl = normalizeCmsUrl(options.cmsUrl ?? options.metadata?.cmsUrl ?? onlyLogin?.cmsUrl ?? '');\n const store = options.store ?? options.metadata?.store ?? onlyLogin?.store ?? '';\n\n if (!cmsUrl) {\n throw new CliError('Missing CMS URL. Pass --cms-url or run the login command first.');\n }\n\n if (!store) {\n throw new CliError('Missing store slug. Pass --store <slug>.');\n }\n\n const token = process.env[tokenEnvVar] || findLogin(credentials, cmsUrl, store)?.token;\n\n if (!token) {\n throw new CliError(`Not logged in to ${cmsUrl} (store \"${store}\"). Run: login ${cmsUrl} --store ${store}`);\n }\n\n return { cmsUrl, store, token };\n};\n","import { parseArgs, type ParseArgsOptionsConfig } from 'node:util';\nimport { CliError } from './errors';\n\nexport interface ParsedArgs {\n values: Record<string, string | boolean | undefined>;\n positionals: string[];\n}\n\n// Wraps node:util parseArgs so bad flags become CliError (exit 1) instead of a stack trace.\nexport const parseCommandArgs = (argv: string[], options: ParseArgsOptionsConfig): ParsedArgs => {\n try {\n const parsed = parseArgs({ args: argv, options, allowPositionals: true, strict: true });\n return {\n values: parsed.values as Record<string, string | boolean | undefined>,\n positionals: parsed.positionals,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(message);\n }\n};\n\nexport const stringOption = (values: ParsedArgs['values'], key: string): string | undefined => {\n const value = values[key];\n return typeof value === 'string' ? value : undefined;\n};\n\nexport const booleanOption = (values: ParsedArgs['values'], key: string): boolean => {\n return values[key] === true;\n};\n","import { CliError } from './errors';\n\n// Every CMS response is wrapped by the server's TransformInterceptor as { status, message, requestedData }.\nexport const unwrapRequestedData = <T>(body: unknown): T => {\n if (body && typeof body === 'object' && 'requestedData' in body) {\n return (body as { requestedData: T }).requestedData;\n }\n\n throw new CliError('Unexpected CMS response: missing requestedData.');\n};\n","import { ApiError, CliError } from './errors';\nimport { unwrapRequestedData } from './envelope';\nimport { normalizeCmsUrl } from './connection';\n\nexport interface LoginOptions {\n cmsUrl: string;\n store: string;\n email: string;\n password: string;\n fetchImpl?: typeof fetch;\n}\n\nexport interface LoginResult {\n token: string;\n email: string;\n}\n\n// Route: POST /admin/:store/auth/login (AdminAuthController mounted under the auth path).\nexport const loginToCms = async (options: LoginOptions): Promise<LoginResult> => {\n const fetchImpl = options.fetchImpl ?? fetch;\n const url = `${normalizeCmsUrl(options.cmsUrl)}/admin/${encodeURIComponent(options.store)}/auth/login`;\n const response = await fetchImpl(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify({ email: options.email, password: options.password }),\n });\n\n if (!response.ok) {\n throw await ApiError.fromResponse(response);\n }\n\n const session = unwrapRequestedData<{ token?: string; user?: { email?: string } }>(await response.json());\n const token = session.token;\n\n if (!token) {\n throw new CliError('Login response did not include a token.');\n }\n\n return { token, email: session.user?.email ?? options.email };\n};\n","import { createInterface } from 'node:readline';\nimport { Writable } from 'node:stream';\n\n// Asks one question on the terminal. When hidden is true, typed characters are not echoed.\nexport const askLine = async (question: string, hidden = false): Promise<string> => {\n const output = process.stdout;\n let muted = false;\n const filteredOutput = new Writable({\n write(chunk, encoding, callback) {\n if (!muted) {\n output.write(chunk, encoding);\n }\n\n callback();\n },\n });\n const readline = createInterface({ input: process.stdin, output: filteredOutput, terminal: true });\n\n // readline prints the question itself; printing it earlier would be erased when readline redraws the line.\n const answer = await new Promise<string>((resolve) => {\n readline.question(question, resolve);\n muted = hidden;\n });\n\n muted = false;\n output.write('\\n');\n readline.close();\n return answer.trim();\n};\n","import { cliName, credentialsDisplayPath } from '../constants';\nimport { normalizeCmsUrl } from '../lib/connection';\nimport { parseCommandArgs, stringOption } from '../lib/args';\nimport { loginToCms } from '../lib/auth';\nimport { CliError } from '../lib/errors';\nimport { saveLogin } from '../lib/credentials';\nimport { askLine } from '../lib/prompt';\n\nexport const loginHelp = `Usage: ${cliName} login <cms-url> --store <slug> [--email <email>] [--password <password>]\n\nSigns in to a CMS store and saves the token to ${credentialsDisplayPath} (mode 0600).\nMissing email or password are prompted for on the terminal; the password is not echoed.\nPassing --password on the command line can leave it in shell history.\n\nOptions:\n --store <slug> Store (tenant) slug to sign in to (required)\n --email <email> Admin account email\n --password <value> Admin account password\n -h, --help Show this help\n`;\n\nexport const runLogin = async (argv: string[]): Promise<void> => {\n const { values, positionals } = parseCommandArgs(argv, {\n store: { type: 'string' },\n email: { type: 'string' },\n password: { type: 'string' },\n });\n const cmsUrlArg = positionals[0];\n const store = stringOption(values, 'store');\n\n if (!cmsUrlArg) {\n throw new CliError('Missing <cms-url>. See: login --help');\n }\n\n if (!store) {\n throw new CliError('Missing --store <slug>. See: login --help');\n }\n\n const cmsUrl = normalizeCmsUrl(cmsUrlArg);\n const email = stringOption(values, 'email') ?? (await askLine('Email: '));\n const password = stringOption(values, 'password') ?? (await askLine('Password: ', true));\n\n if (!email || !password) {\n throw new CliError('Email and password are required.');\n }\n\n const result = await loginToCms({ cmsUrl, store, email, password });\n await saveLogin({ cmsUrl, store, token: result.token, email: result.email });\n\n console.log(`Logged in to ${cmsUrl} (store \"${store}\") as ${result.email}.`);\n};\n","import { resolve } from 'node:path';\nimport { cliName } from '../constants';\nimport { booleanOption, parseCommandArgs, stringOption } from '../lib/args';\nimport { CliError } from '../lib/errors';\nimport { resolveConnection } from '../lib/connection';\nimport { CmsClient } from '../lib/cms-client';\nimport { findTheme, isExportMode, pullTheme } from '../lib/pull';\nimport { readThemeMetadata, themeExportModes } from '../lib/metadata';\n\nexport const pullHelp = `Usage: ${cliName} pull [theme] [options]\n\nDownloads a theme from the CMS (export-zip) into a folder and records the base hashes\nthat later status and push commands compare against.\n\nArguments:\n theme Theme id or slug. Optional when the folder already has a theme linked.\n\nOptions:\n --mode <mode> ${themeExportModes.join(' | ')} (default: theme)\n --dir <folder> Target folder (default: ./<theme slug>, or the current folder when linked)\n --force Overwrite a non-empty target folder\n --cms-url <url> CMS base URL (default: from the linked theme or the only saved login)\n --store <slug> Store slug (default: from the linked theme or the only saved login)\n --published Not supported yet: the server exports only the draft\n -h, --help Show this help\n`;\n\nexport const runPull = async (argv: string[]): Promise<void> => {\n const { values, positionals } = parseCommandArgs(argv, {\n 'cms-url': { type: 'string' },\n store: { type: 'string' },\n mode: { type: 'string' },\n dir: { type: 'string' },\n force: { type: 'boolean' },\n published: { type: 'boolean' },\n });\n\n if (booleanOption(values, 'published')) {\n throw new CliError(\n '--published is not supported: the server only exports the draft theme (no published-version export).',\n );\n }\n\n const mode = stringOption(values, 'mode') ?? 'theme';\n\n if (!isExportMode(mode)) {\n throw new CliError(`Invalid --mode \"${mode}\". Use one of: ${themeExportModes.join(', ')}.`);\n }\n\n const reference = positionals[0];\n const dirOption = stringOption(values, 'dir');\n const existing = await readThemeMetadata(resolve(dirOption ?? '.'));\n const ref = reference ?? existing?.themeId;\n\n if (!ref) {\n throw new CliError('Pass a theme id or slug, or run pull inside a folder that already has a linked theme.');\n }\n\n const connection = await resolveConnection({\n cmsUrl: stringOption(values, 'cms-url'),\n store: stringOption(values, 'store'),\n metadata: existing,\n });\n const client = new CmsClient(connection);\n const theme = findTheme(await client.listThemes(), ref);\n const targetDir = dirOption ?? (reference ? theme.slug : '.');\n const result = await pullTheme({\n client,\n theme,\n mode,\n targetDir,\n force: booleanOption(values, 'force'),\n cmsUrl: connection.cmsUrl,\n store: connection.store,\n });\n\n console.log(`Pulled \"${theme.name}\" (${mode}) into ${result.dir}: ${result.fileCount} files.`);\n};\n","import type { DeclaredEntityQuery } from '@tomsher/cms-core/types';\nimport { ApiError } from './errors';\nimport { unwrapRequestedData } from './envelope';\nimport type { CmsConnection } from './connection';\n\nexport interface ThemePreviewRequest {\n entities: DeclaredEntityQuery[];\n contentCollections: string[];\n sources: string[];\n page?: {\n templatePath: string;\n category: 'collections' | 'details';\n };\n}\n\nexport interface RemoteTheme {\n id: string;\n name: string;\n slug: string;\n version: string | null;\n renderMode: string;\n}\n\nexport interface RemoteFile {\n filename: string;\n contentHash: string | null;\n}\n\nexport interface BatchFile {\n filename: string;\n content: string;\n expectedHash?: string;\n}\n\nexport interface ValidateFile {\n filename: string;\n content: string;\n}\n\nexport interface ThemeValidationIssue {\n code: string;\n message: string;\n filename?: string;\n path?: string;\n}\n\nexport interface ThemeValidationResult {\n valid: boolean;\n issues: ThemeValidationIssue[];\n}\n\nexport interface ZipThemeFields {\n name?: string;\n renderMode: string;\n}\n\n// Routes are the admin theme endpoints under /admin/:store/themes (themes.controller.ts).\nexport class CmsClient {\n private readonly connection: CmsConnection;\n private readonly fetchImpl: typeof fetch;\n\n constructor(connection: CmsConnection, fetchImpl: typeof fetch = fetch) {\n this.connection = connection;\n this.fetchImpl = fetchImpl;\n }\n\n async listThemes(): Promise<RemoteTheme[]> {\n return unwrapRequestedData<RemoteTheme[]>(await this.requestJson<unknown>(this.themesUrl()));\n }\n\n async listFiles(themeId: string): Promise<RemoteFile[]> {\n return unwrapRequestedData<RemoteFile[]>(await this.requestJson<unknown>(this.themesUrl(themeId, 'files')));\n }\n\n async exportZip(themeId: string, mode: string): Promise<Uint8Array> {\n const query = new URLSearchParams({ mode });\n const response = await this.send(`${this.themesUrl(themeId, 'export-zip')}?${query.toString()}`);\n return new Uint8Array(await response.arrayBuffer());\n }\n\n // Returns the raw JSON body; the payload sits in requestedData (see transform.interceptor.ts).\n async previewData(themeId: string, request: ThemePreviewRequest, countryCode?: string): Promise<unknown> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n\n if (countryCode) {\n headers['x-country-code'] = countryCode;\n }\n\n return this.requestJson<unknown>(this.themesUrl(themeId, 'preview-data'), {\n method: 'POST',\n headers,\n body: JSON.stringify(request),\n });\n }\n\n async validateFiles(themeId: string, files: ValidateFile[], removed: string[]): Promise<ThemeValidationResult> {\n const body = await this.requestJson<unknown>(this.themesUrl(themeId, 'validate'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ files, removed }),\n });\n return unwrapRequestedData<ThemeValidationResult>(body);\n }\n\n async saveFilesBatch(themeId: string, files: BatchFile[]): Promise<void> {\n await this.send(this.themesUrl(themeId, 'files', 'batch'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ files }),\n });\n }\n\n async uploadThemeZip(themeId: string, zip: Uint8Array, renderMode: string): Promise<void> {\n await this.send(this.themesUrl(themeId, 'upload-zip'), {\n method: 'POST',\n body: this.zipForm(zip, { renderMode }),\n });\n }\n\n async createThemeFromZip(fields: ZipThemeFields, zip: Uint8Array): Promise<RemoteTheme> {\n const body = await this.requestJson<unknown>(this.themesUrl('upload-zip'), {\n method: 'POST',\n body: this.zipForm(zip, fields),\n });\n return unwrapRequestedData<{ theme: RemoteTheme }>(body).theme;\n }\n\n private themesUrl(...segments: string[]): string {\n const base = `${this.connection.cmsUrl}/admin/${encodeURIComponent(this.connection.store)}/themes`;\n const path = segments.map((segment) => `/${encodeURIComponent(segment)}`).join('');\n return `${base}${path}`;\n }\n\n private zipForm(zip: Uint8Array, fields: ZipThemeFields): FormData {\n const form = new FormData();\n\n if (fields.name) {\n form.append('name', fields.name);\n }\n\n form.append('renderMode', fields.renderMode);\n form.append('importStructure', 'false');\n form.append('importEntries', 'false');\n form.append('importMedia', 'false');\n form.append('file', new Blob([new Uint8Array(zip)], { type: 'application/zip' }), 'theme.zip');\n return form;\n }\n\n private async requestJson<T>(url: string, init: RequestInit = {}): Promise<T> {\n const response = await this.send(url, init);\n return (await response.json()) as T;\n }\n\n private async send(url: string, init: RequestInit = {}): Promise<Response> {\n const headers = new Headers(init.headers);\n headers.set('Authorization', `Bearer ${this.connection.token}`);\n headers.set('Accept', 'application/json');\n\n const response = await this.fetchImpl(url, { ...init, headers });\n\n if (!response.ok) {\n throw await ApiError.fromResponse(response);\n }\n\n return response;\n }\n}\n","import { mkdir, readdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { metadataSchemaVersion } from '../constants';\nimport { CliError } from './errors';\nimport type { CmsClient, RemoteTheme } from './cms-client';\nimport { extractZip } from './zip';\nimport { readLocalTheme, toHashMap } from './theme-files';\nimport { themeExportModes, writeThemeMetadata, type ThemeExportMode, type ThemeMetadata } from './metadata';\n\nexport const isExportMode = (value: string): value is ThemeExportMode => {\n return (themeExportModes as readonly string[]).includes(value);\n};\n\nexport const findTheme = (themes: RemoteTheme[], reference: string): RemoteTheme => {\n const match = themes.find((theme) => theme.id === reference || theme.slug === reference);\n\n if (!match) {\n throw new CliError(`Theme \"${reference}\" was not found in this store.`);\n }\n\n return match;\n};\n\nexport const isNonEmptyDirectory = async (dir: string): Promise<boolean> => {\n try {\n const entries = await readdir(dir);\n return entries.length > 0;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return false;\n }\n\n throw error;\n }\n};\n\nexport interface PullOptions {\n client: CmsClient;\n theme: RemoteTheme;\n mode: ThemeExportMode;\n targetDir: string;\n force: boolean;\n cmsUrl: string;\n store: string;\n}\n\nexport const pullTheme = async (options: PullOptions): Promise<{ dir: string; fileCount: number }> => {\n const targetDir = resolve(options.targetDir);\n\n if (!options.force && (await isNonEmptyDirectory(targetDir))) {\n throw new CliError(`Refusing to overwrite non-empty folder ${targetDir}. Pass --force to overwrite.`);\n }\n\n const archive = await options.client.exportZip(options.theme.id, options.mode);\n\n await mkdir(targetDir, { recursive: true });\n await extractZip(archive, targetDir);\n\n const localFiles = await readLocalTheme(targetDir);\n const metadata: ThemeMetadata = {\n version: metadataSchemaVersion,\n cmsUrl: options.cmsUrl,\n store: options.store,\n themeId: options.theme.id,\n slug: options.theme.slug,\n renderMode: options.theme.renderMode,\n pulledVersion: options.theme.version,\n mode: options.mode,\n baseHashes: toHashMap(localFiles),\n };\n\n await writeThemeMetadata(targetDir, metadata);\n return { dir: targetDir, fileCount: localFiles.length };\n};\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, resolve, sep } from 'node:path';\nimport { unzipSync, zipSync } from 'fflate';\nimport { CliError } from './errors';\n\nexport interface ZipInput {\n path: string;\n bytes: Uint8Array;\n}\n\n// Maps an archive entry to a file path inside targetDir, or throws if it would escape it (zip-slip).\nexport const resolveArchivePath = (targetDir: string, entryName: string): string => {\n const normalized = entryName.replace(/\\\\/g, '/');\n\n if (isAbsolute(entryName) || normalized.startsWith('/') || /^[a-zA-Z]:/.test(normalized)) {\n throw new CliError(`Unsafe archive path: ${entryName}`);\n }\n\n if (normalized.split('/').some((segment) => segment === '..')) {\n throw new CliError(`Unsafe archive path: ${entryName}`);\n }\n\n const root = resolve(targetDir);\n const target = resolve(root, normalized);\n\n if (!target.startsWith(root + sep)) {\n throw new CliError(`Unsafe archive path: ${entryName}`);\n }\n\n return target;\n};\n\n// Validates every entry before writing anything, so a bad archive leaves the folder untouched.\nexport const extractZip = async (archive: Uint8Array, targetDir: string): Promise<string[]> => {\n const entries = unzipSync(archive);\n const plan = Object.entries(entries)\n .filter(([name]) => !name.endsWith('/'))\n .map(([name, bytes]) => ({ name, bytes, target: resolveArchivePath(targetDir, name) }));\n\n for (const item of plan) {\n await mkdir(dirname(item.target), { recursive: true });\n await writeFile(item.target, item.bytes);\n }\n\n return plan.map((item) => item.name);\n};\n\nexport const buildZip = (files: ZipInput[]): Uint8Array => {\n const input: Record<string, Uint8Array> = {};\n\n for (const file of files) {\n input[file.path] = file.bytes;\n }\n\n return zipSync(input, { level: 6 });\n};\n","import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { metadataFileName, metadataFolderName, metadataSchemaVersion } from '../constants';\nimport { CliError } from './errors';\n\nexport const themeExportModes = ['theme', 'theme-structure', 'theme-complete'] as const;\n\nexport type ThemeExportMode = (typeof themeExportModes)[number];\n\nexport interface ThemeMetadata {\n version: number;\n cmsUrl: string;\n store: string;\n themeId: string;\n slug: string;\n renderMode: string;\n pulledVersion: string | null;\n mode: ThemeExportMode;\n baseHashes: Record<string, string>;\n}\n\nconst metadataPath = (themeDir: string): string => {\n return join(themeDir, metadataFolderName, metadataFileName);\n};\n\nexport const readThemeMetadata = async (themeDir: string): Promise<ThemeMetadata | null> => {\n let raw: string;\n\n try {\n raw = await readFile(metadataPath(themeDir), 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n\n throw error;\n }\n\n try {\n return JSON.parse(raw) as ThemeMetadata;\n } catch {\n throw new CliError(`${metadataPath(themeDir)} is not valid JSON.`);\n }\n};\n\nexport const writeThemeMetadata = async (themeDir: string, metadata: ThemeMetadata): Promise<void> => {\n await mkdir(join(themeDir, metadataFolderName), { recursive: true });\n const content = JSON.stringify({ ...metadata, version: metadataSchemaVersion }, null, 4);\n await writeFile(metadataPath(themeDir), `${content}\\n`);\n};\n","import { cliName } from '../constants';\nimport { parseCommandArgs, stringOption } from '../lib/args';\nimport { CmsClient } from '../lib/cms-client';\nimport { resolveConnection } from '../lib/connection';\n\nexport const themesHelp = `Usage: ${cliName} themes [options]\n\nLists the themes of the store (id, slug, render mode, version).\n\nOptions:\n --cms-url <url> CMS base URL (default: the only saved login)\n --store <slug> Store slug (default: the only saved login)\n -h, --help Show this help\n`;\n\nexport const runThemes = async (argv: string[]): Promise<void> => {\n const { values } = parseCommandArgs(argv, {\n 'cms-url': { type: 'string' },\n store: { type: 'string' },\n });\n const connection = await resolveConnection({\n cmsUrl: stringOption(values, 'cms-url'),\n store: stringOption(values, 'store'),\n });\n const themes = await new CmsClient(connection).listThemes();\n\n if (themes.length === 0) {\n console.log('No themes in this store.');\n return;\n }\n\n for (const theme of themes) {\n console.log(`${theme.id} ${theme.slug} ${theme.renderMode} v${theme.version ?? '-'} ${theme.name}`);\n }\n};\n","import { resolve } from 'node:path';\nimport { cliName } from '../constants';\nimport { booleanOption, parseCommandArgs, stringOption } from '../lib/args';\nimport { resolveConnection } from '../lib/connection';\nimport { CliError } from '../lib/errors';\nimport { CmsClient } from '../lib/cms-client';\nimport { readThemeMetadata } from '../lib/metadata';\nimport { pushTheme, type PushSummary } from '../lib/push';\n\nexport const pushHelp = `Usage: ${cliName} push [options]\n\nSends locally changed theme files to the CMS as a draft. Never publishes.\nText changes go through files/batch (chunks of 200). Deletions, binary assets, or any\nremote change to a file you did not pull force a whole-theme zip upload instead.\n\nOptions:\n --dir <folder> Theme folder (default: current folder)\n --dry-run Show what would be sent, without sending it\n --force Overwrite files changed on the CMS since pull\n --create --name <name> Create a new theme from this folder instead of updating a linked one\n --render-mode <mode> liquid | static (used with --create; default: linked theme's mode, else liquid)\n --cms-url <url> CMS base URL (default: from the linked theme or the only saved login)\n --store <slug> Store slug (default: from the linked theme or the only saved login)\n -h, --help Show this help\n`;\n\nconst renderModes = ['liquid', 'static'];\n\nconst describeSummary = (summary: PushSummary): string => {\n const { added, modified, deleted } = summary.diff;\n const counts = `${added.length} added, ${modified.length} modified, ${deleted.length} deleted`;\n\n if (summary.method === 'none') {\n return 'No local changes to push.';\n }\n\n if (summary.dryRun) {\n return `Dry run: would push via ${summary.method} (${counts}). Nothing was sent.`;\n }\n\n if (summary.method === 'create') {\n return `Created theme ${summary.themeId}. It is a draft; nothing was published.`;\n }\n\n const target = `theme ${summary.themeId} via ${summary.method} (${counts})`;\n\n return `Pushed to ${target}. Saved as draft; the live theme was not changed.`;\n};\n\nexport const runPush = async (argv: string[]): Promise<void> => {\n const { values } = parseCommandArgs(argv, {\n dir: { type: 'string' },\n 'cms-url': { type: 'string' },\n store: { type: 'string' },\n force: { type: 'boolean' },\n 'dry-run': { type: 'boolean' },\n create: { type: 'boolean' },\n name: { type: 'string' },\n 'render-mode': { type: 'string' },\n });\n const dir = resolve(stringOption(values, 'dir') ?? '.');\n const metadata = await readThemeMetadata(dir);\n const renderMode = stringOption(values, 'render-mode') ?? metadata?.renderMode ?? 'liquid';\n\n if (!renderModes.includes(renderMode)) {\n throw new CliError(`Invalid --render-mode \"${renderMode}\". Use liquid or static.`);\n }\n\n const connection = await resolveConnection({\n cmsUrl: stringOption(values, 'cms-url'),\n store: stringOption(values, 'store'),\n metadata,\n });\n const summary = await pushTheme({\n dir,\n client: new CmsClient(connection),\n metadata,\n cmsUrl: connection.cmsUrl,\n store: connection.store,\n create: booleanOption(values, 'create'),\n name: stringOption(values, 'name'),\n renderMode,\n force: booleanOption(values, 'force'),\n dryRun: booleanOption(values, 'dry-run'),\n });\n\n console.log(describeSummary(summary));\n};\n","import { metadataSchemaVersion } from '../constants';\nimport { CliError } from './errors';\nimport type { CmsClient, BatchFile, RemoteFile } from './cms-client';\nimport { buildZip } from './zip';\nimport { diffHashes, type ThemeDiff } from './hash';\nimport { isPushablePath, isTextPath, readLocalTheme, toHashMap, type LocalFile } from './theme-files';\nimport { writeThemeMetadata, type ThemeMetadata } from './metadata';\n\n// Server limit for files in one files/batch request (BatchSaveThemeFilesDto).\nexport const maxBatchFiles = 200;\n\nexport interface Conflict {\n path: string;\n expected: string | null;\n remote: string | null;\n}\n\nexport interface PushOptions {\n dir: string;\n client: CmsClient;\n metadata: ThemeMetadata | null;\n cmsUrl: string;\n store: string;\n create: boolean;\n name?: string;\n renderMode: string;\n force: boolean;\n dryRun: boolean;\n}\n\nexport type PushMethod = 'none' | 'batch' | 'zip' | 'create';\n\nexport interface PushSummary {\n method: PushMethod;\n diff: ThemeDiff;\n themeId: string | null;\n dryRun: boolean;\n}\n\nexport const chunkArray = <T>(items: T[], size: number): T[][] => {\n const chunks: T[][] = [];\n\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n\n return chunks;\n};\n\n// A path is in conflict when the remote copy differs from what was pulled, or when a remote file\n// would be lost by a whole-theme zip upload (a file the local folder does not know about).\nexport const findConflicts = (\n base: Record<string, string>,\n local: Record<string, string>,\n remote: Record<string, string>,\n): Conflict[] => {\n const paths = new Set([...Object.keys(base), ...Object.keys(local), ...Object.keys(remote)]);\n const conflicts: Conflict[] = [];\n\n for (const path of [...paths].sort()) {\n const baseHash = base[path];\n const remoteHash = remote[path];\n\n if (baseHash !== undefined) {\n if (remoteHash !== baseHash) {\n conflicts.push({ path, expected: baseHash, remote: remoteHash ?? null });\n }\n\n continue;\n }\n\n if (remoteHash !== undefined && remoteHash !== local[path]) {\n conflicts.push({ path, expected: null, remote: remoteHash });\n }\n }\n\n return conflicts;\n};\n\nexport const toRemoteHashes = (files: RemoteFile[]): Record<string, string> => {\n const hashes: Record<string, string> = {};\n\n for (const file of files) {\n if (isPushablePath(file.filename)) {\n hashes[file.filename] = file.contentHash ?? '';\n }\n }\n\n return hashes;\n};\n\nconst formatConflicts = (conflicts: Conflict[]): string => {\n const lines = conflicts.map((conflict) => {\n return ` - ${conflict.path} (pulled ${conflict.expected ?? 'none'}, remote ${conflict.remote ?? 'missing'})`;\n });\n\n return [\n 'The theme changed on the CMS since you pulled it. Conflicting files:',\n ...lines,\n 'Run pull into a new folder to merge, or pass --force to overwrite.',\n ].join('\\n');\n};\n\nconst toBatchFile = (file: LocalFile, baseHashes: Record<string, string>, force: boolean): BatchFile => {\n const expectedHash = force ? undefined : baseHashes[file.path];\n\n return {\n filename: file.path,\n content: new TextDecoder().decode(file.bytes),\n expectedHash,\n };\n};\n\nexport const pushTheme = async (options: PushOptions): Promise<PushSummary> => {\n if (options.create && options.metadata) {\n throw new CliError(\n `This folder is already linked to theme ${options.metadata.themeId}. Remove .cms-theme-kit to create a new theme.`,\n );\n }\n\n const localFiles = await readLocalTheme(options.dir);\n\n if (localFiles.length === 0) {\n throw new CliError(`No theme files found in ${options.dir}.`);\n }\n\n const localHashes = toHashMap(localFiles);\n const baseHashes = options.metadata?.baseHashes ?? {};\n const diff = diffHashes(baseHashes, localHashes);\n\n if (options.create) {\n return createTheme(options, localFiles, localHashes, diff);\n }\n\n const metadata = options.metadata as ThemeMetadata;\n const changedCount = diff.added.length + diff.modified.length + diff.deleted.length;\n\n if (changedCount === 0) {\n return { method: 'none', diff, themeId: metadata.themeId, dryRun: options.dryRun };\n }\n\n const remoteFiles = await options.client.listFiles(metadata.themeId);\n const conflicts = findConflicts(baseHashes, localHashes, toRemoteHashes(remoteFiles));\n\n if (conflicts.length > 0 && !options.force) {\n throw new CliError(formatConflicts(conflicts));\n }\n\n // The batch endpoint is text-only and cannot delete, so anything else needs a whole-theme zip upload.\n const needsZip =\n diff.deleted.length > 0 || [...diff.added, ...diff.modified].some((path) => !isTextPath(path));\n const method: PushMethod = needsZip ? 'zip' : 'batch';\n\n if (options.dryRun) {\n return { method, diff, themeId: metadata.themeId, dryRun: true };\n }\n\n if (needsZip) {\n const zip = buildZip(localFiles);\n await options.client.uploadThemeZip(metadata.themeId, zip, metadata.renderMode);\n metadata.baseHashes = localHashes;\n await writeThemeMetadata(options.dir, metadata);\n return { method, diff, themeId: metadata.themeId, dryRun: false };\n }\n\n const changedPaths = new Set([...diff.added, ...diff.modified]);\n const changedFiles = localFiles.filter((file) => changedPaths.has(file.path));\n\n // Metadata is saved after every chunk so a failure mid-push leaves the base hashes accurate.\n for (const chunk of chunkArray(changedFiles, maxBatchFiles)) {\n const batch = chunk.map((file) => toBatchFile(file, baseHashes, options.force));\n await options.client.saveFilesBatch(metadata.themeId, batch);\n\n for (const file of chunk) {\n metadata.baseHashes[file.path] = file.hash;\n }\n\n await writeThemeMetadata(options.dir, metadata);\n }\n\n return { method, diff, themeId: metadata.themeId, dryRun: false };\n};\n\nconst createTheme = async (\n options: PushOptions,\n localFiles: LocalFile[],\n localHashes: Record<string, string>,\n diff: ThemeDiff,\n): Promise<PushSummary> => {\n if (!options.name) {\n throw new CliError('Creating a theme needs --name <name>.');\n }\n\n if (options.dryRun) {\n return { method: 'create', diff, themeId: null, dryRun: true };\n }\n\n const theme = await options.client.createThemeFromZip(\n { name: options.name, renderMode: options.renderMode },\n buildZip(localFiles),\n );\n const metadata: ThemeMetadata = {\n version: metadataSchemaVersion,\n cmsUrl: options.cmsUrl,\n store: options.store,\n themeId: theme.id,\n slug: theme.slug,\n renderMode: theme.renderMode,\n pulledVersion: theme.version,\n mode: 'theme',\n baseHashes: localHashes,\n };\n\n await writeThemeMetadata(options.dir, metadata);\n return { method: 'create', diff, themeId: theme.id, dryRun: false };\n};\n","import { resolve } from 'node:path';\nimport { cliName, metadataFileName, metadataFolderName } from '../constants';\nimport { booleanOption, parseCommandArgs, stringOption } from '../lib/args';\nimport { resolveConnection } from '../lib/connection';\nimport { CliError } from '../lib/errors';\nimport { CmsClient } from '../lib/cms-client';\nimport { diffHashes } from '../lib/hash';\nimport { readThemeMetadata } from '../lib/metadata';\nimport { remoteChangedPaths } from '../lib/status';\nimport { readLocalTheme, toHashMap } from '../lib/theme-files';\nimport { toRemoteHashes } from '../lib/push';\n\nexport const statusHelp = `Usage: ${cliName} status [options]\n\nCompares the local theme folder with the hashes recorded at pull time.\n\nOptions:\n --dir <folder> Theme folder (default: current folder)\n --remote Also fetch the CMS file list and show files changed on the CMS since pull\n --cms-url <url> CMS base URL (only used with --remote)\n --store <slug> Store slug (only used with --remote)\n -h, --help Show this help\n`;\n\nconst printSection = (title: string, paths: string[]): void => {\n console.log(`${title} (${paths.length}):`);\n\n for (const path of paths) {\n console.log(` ${path}`);\n }\n};\n\nexport const runStatus = async (argv: string[]): Promise<void> => {\n const { values } = parseCommandArgs(argv, {\n dir: { type: 'string' },\n remote: { type: 'boolean' },\n 'cms-url': { type: 'string' },\n store: { type: 'string' },\n });\n const dir = resolve(stringOption(values, 'dir') ?? '.');\n const metadata = await readThemeMetadata(dir);\n\n if (!metadata) {\n throw new CliError(`No ${metadataFolderName}/${metadataFileName} in ${dir}. Run pull first.`);\n }\n\n const localHashes = toHashMap(await readLocalTheme(dir));\n const diff = diffHashes(metadata.baseHashes, localHashes);\n\n console.log(`Theme \"${metadata.slug}\" (${metadata.themeId}) in ${dir}`);\n printSection('Added locally', diff.added);\n printSection('Modified locally', diff.modified);\n printSection('Deleted locally', diff.deleted);\n\n if (booleanOption(values, 'remote')) {\n const connection = await resolveConnection({\n cmsUrl: stringOption(values, 'cms-url'),\n store: stringOption(values, 'store'),\n metadata,\n });\n const client = new CmsClient(connection);\n const remoteHashes = toRemoteHashes(await client.listFiles(metadata.themeId));\n printSection('Changed on the CMS since pull', remoteChangedPaths(metadata.baseHashes, remoteHashes));\n }\n};\n","// Paths whose remote hash no longer matches the hash recorded at pull time, or that only exist remotely.\nexport const remoteChangedPaths = (base: Record<string, string>, remote: Record<string, string>): string[] => {\n const paths = new Set([...Object.keys(base), ...Object.keys(remote)]);\n const changed: string[] = [];\n\n for (const path of [...paths].sort()) {\n if (base[path] !== remote[path]) {\n changed.push(path);\n }\n }\n\n return changed;\n};\n","import { stat } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { liquidThemeFolderNames, staticThemeHomePath } from '@tomsher/cms-core/constants';\nimport { cliName, metadataFileName, metadataFolderName } from '../constants';\nimport { parseCommandArgs, stringOption } from '../lib/args';\nimport { resolveConnection } from '../lib/connection';\nimport { CliError } from '../lib/errors';\nimport { CmsClient } from '../lib/cms-client';\nimport type { DataSource } from '../lib/dev/data-source';\nimport type { DevServer } from '../lib/dev/server';\nimport { watchThemeDir } from '../lib/dev/watcher';\nimport { readThemeMetadata, type ThemeMetadata } from '../lib/metadata';\n\nexport const devHelp = `Usage: ${cliName} dev [options]\n\nServes the theme on localhost. Liquid themes are rendered with the same engine as the theme editor preview;\nstatic themes (static/index.html) are served as plain HTML pages.\nSaving a file in the theme folder reloads open pages. Stop with Ctrl-C.\n\nOptions:\n --dir <folder> Theme folder (default: current folder)\n --port <n> Port to listen on (default: 4400)\n --mode <mode> liquid | static (default: from the linked theme; without one, static when the\n folder has static/index.html and no templates/)\n --data <source> live | fixtures (default: live; liquid themes only)\n live: preview data from the CMS (needs a pulled theme and login)\n fixtures: fixtures/<template path with / replaced by -> JSON file\n --country <code> Country code sent with live data requests, e.g. AE\n --lang <code> Language used for locale overrides (default: en)\n --template <path> Template served at / (default: templates/index.json; liquid themes only)\n --cms-url <url> CMS base URL (live data only; default: from the linked theme or the only saved login)\n --store <slug> Store slug (live data only; default: from the linked theme or the only saved login)\n -h, --help Show this help\n`;\n\nconst defaultPort = 4400;\nconst defaultTemplate = 'templates/index.json';\nconst defaultLanguage = 'en';\nconst dataSourceNames = ['live', 'fixtures'];\nconst devModes = ['liquid', 'static'];\n\nconst parsePort = (value: string | undefined): number => {\n if (value === undefined) {\n return defaultPort;\n }\n\n const port = Number(value);\n\n if (!Number.isInteger(port) || port < 0 || port > 65535) {\n throw new CliError(`Invalid --port \"${value}\". Use a whole number from 0 to 65535.`);\n }\n\n return port;\n};\n\nconst pathExists = async (path: string): Promise<boolean> => {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n};\n\n// The linked theme's render mode wins. Without metadata, a folder with static/index.html and no templates/ is static.\nconst resolveDevMode = async (requested: string | undefined, themeDir: string, metadata: ThemeMetadata | null): Promise<string> => {\n if (requested !== undefined) {\n if (!devModes.includes(requested)) {\n throw new CliError(`Invalid --mode \"${requested}\". Use liquid or static.`);\n }\n\n return requested;\n }\n\n if (metadata) {\n return metadata.renderMode === 'static' ? 'static' : 'liquid';\n }\n\n const hasStaticHome = await pathExists(join(themeDir, staticThemeHomePath));\n const hasTemplates = await pathExists(join(themeDir, liquidThemeFolderNames.templates));\n\n return hasStaticHome && !hasTemplates ? 'static' : 'liquid';\n};\n\nconst waitForShutdown = (): Promise<void> => {\n return new Promise((resolveWait) => {\n process.once('SIGINT', resolveWait);\n process.once('SIGTERM', resolveWait);\n });\n};\n\nconst serveUntilInterrupted = async (themeDir: string, server: DevServer): Promise<void> => {\n const watcher = watchThemeDir(themeDir, () => {\n server.notifyChanged().catch((error: unknown) => {\n console.error(`error: could not reload theme: ${error instanceof Error ? error.message : String(error)}`);\n });\n });\n\n await waitForShutdown();\n watcher.close();\n await server.close();\n};\n\n// Loaded on demand: importing the liquid engine logs a LiquidJS warning, which other commands must not show.\nexport const runDev = async (argv: string[]): Promise<void> => {\n const { values } = parseCommandArgs(argv, {\n dir: { type: 'string' },\n port: { type: 'string' },\n mode: { type: 'string' },\n data: { type: 'string' },\n country: { type: 'string' },\n lang: { type: 'string' },\n template: { type: 'string' },\n 'cms-url': { type: 'string' },\n store: { type: 'string' },\n });\n const dir = resolve(stringOption(values, 'dir') ?? '.');\n const port = parsePort(stringOption(values, 'port'));\n const metadata = await readThemeMetadata(dir);\n const mode = await resolveDevMode(stringOption(values, 'mode'), dir, metadata);\n\n if (mode === 'static') {\n const { startStaticDevServer } = await import('../lib/dev/static-server');\n const server = await startStaticDevServer({ themeDir: dir, port });\n\n console.log(`Previewing static theme at ${server.url}/`);\n console.log(`Pages: ${server.url}/__templates`);\n console.log('Press Ctrl-C to stop.');\n\n await serveUntilInterrupted(dir, server);\n return;\n }\n\n const { createFixturesDataSource, createLiveDataSource } = await import('../lib/dev/data-source');\n const { startDevServer } = await import('../lib/dev/server');\n const dataMode = stringOption(values, 'data') ?? 'live';\n const templatePath = stringOption(values, 'template') ?? defaultTemplate;\n const countryCode = stringOption(values, 'country');\n const languageCode = stringOption(values, 'lang') ?? defaultLanguage;\n\n if (!dataSourceNames.includes(dataMode)) {\n throw new CliError(`Invalid --data \"${dataMode}\". Use live or fixtures.`);\n }\n\n if (!templatePath.startsWith('templates/') || !templatePath.endsWith('.json')) {\n throw new CliError(`Invalid --template \"${templatePath}\". Use a path like templates/index.json.`);\n }\n\n let dataSource: DataSource;\n\n if (dataMode === 'fixtures') {\n dataSource = createFixturesDataSource(dir);\n } else {\n if (!metadata) {\n throw new CliError(`No ${metadataFolderName}/${metadataFileName} in ${dir}. Run pull first, or use --data fixtures.`);\n }\n\n const connection = await resolveConnection({\n cmsUrl: stringOption(values, 'cms-url'),\n store: stringOption(values, 'store'),\n metadata,\n });\n dataSource = createLiveDataSource({\n client: new CmsClient(connection),\n themeId: metadata.themeId,\n countryCode,\n });\n }\n\n const server = await startDevServer({\n themeDir: dir,\n port,\n templatePath,\n languageCode,\n countryCode,\n dataSource,\n });\n\n console.log(`Previewing ${templatePath} at ${server.url}/ (data: ${dataMode}).`);\n console.log(`Templates: ${server.url}/__templates`);\n console.log('Press Ctrl-C to stop.');\n\n await serveUntilInterrupted(dir, server);\n};\n","import { watch } from 'node:fs';\nimport { metadataFolderName } from '../../constants';\n\nconst ignoredSegments = [metadataFolderName, 'node_modules', '.git'];\n\nexport const isIgnoredWatchPath = (relativePath: string): boolean => {\n return relativePath\n .split(/[\\\\/]/)\n .some((segment) => ignoredSegments.includes(segment));\n};\n\nexport interface ThemeWatcher {\n close: () => void;\n}\n\n// Coalesces bursts of file events (editor saves, multi-file writes) into one onChange call.\nexport const watchThemeDir = (themeDir: string, onChange: () => void, debounceMs = 100): ThemeWatcher => {\n let timer: NodeJS.Timeout | undefined;\n const watcher = watch(themeDir, { recursive: true }, (_eventType, filename) => {\n if (filename && isIgnoredWatchPath(String(filename))) {\n return;\n }\n\n clearTimeout(timer);\n timer = setTimeout(onChange, debounceMs);\n });\n\n return {\n close: () => {\n clearTimeout(timer);\n watcher.close();\n },\n };\n};\n","import { resolve } from 'node:path';\nimport { cliName, metadataFileName, metadataFolderName } from '../constants';\nimport { parseCommandArgs, stringOption } from '../lib/args';\nimport { CmsClient } from '../lib/cms-client';\nimport { resolveConnection } from '../lib/connection';\nimport { CliError } from '../lib/errors';\nimport { diffHashes } from '../lib/hash';\nimport { readThemeMetadata } from '../lib/metadata';\nimport { isTextPath, readLocalTheme, toHashMap } from '../lib/theme-files';\n\nexport const validateHelp = `Usage: ${cliName} validate [options]\n\nChecks the local theme with the same rules the CMS applies when publishing.\nOnly changed files are sent; nothing is saved on the CMS.\n\nOptions:\n --dir <folder> Theme folder (default: current folder)\n --cms-url <url> CMS base URL\n --store <slug> Store slug\n -h, --help Show this help\n`;\n\nexport const runValidate = async (argv: string[]): Promise<void> => {\n const { values } = parseCommandArgs(argv, {\n dir: { type: 'string' },\n 'cms-url': { type: 'string' },\n store: { type: 'string' },\n });\n const dir = resolve(stringOption(values, 'dir') ?? '.');\n const metadata = await readThemeMetadata(dir);\n\n if (!metadata) {\n throw new CliError(`No ${metadataFolderName}/${metadataFileName} in ${dir}. Run pull first.`);\n }\n\n const localFiles = await readLocalTheme(dir);\n const diff = diffHashes(metadata.baseHashes, toHashMap(localFiles));\n const changed = new Set([...diff.added, ...diff.modified]);\n const files = localFiles\n .filter((file) => changed.has(file.path) && isTextPath(file.path))\n .map((file) => ({ filename: file.path, content: Buffer.from(file.bytes).toString('utf8') }));\n\n const connection = await resolveConnection({\n cmsUrl: stringOption(values, 'cms-url'),\n store: stringOption(values, 'store'),\n metadata,\n });\n const result = await new CmsClient(connection).validateFiles(metadata.themeId, files, diff.deleted);\n\n if (result.valid) {\n console.log('Theme is valid.');\n return;\n }\n\n for (const issue of result.issues) {\n const location = [issue.filename, issue.path].filter(Boolean).join(' ');\n console.error(`${location ? `${location}: ` : ''}${issue.message}`);\n }\n\n throw new CliError(`${result.issues.length} validation issue(s).`);\n};\n","import { cliName } from './constants';\nimport { loginHelp, runLogin } from './commands/login';\nimport { pullHelp, runPull } from './commands/pull';\nimport { runThemes, themesHelp } from './commands/themes';\nimport { pushHelp, runPush } from './commands/push';\nimport { statusHelp, runStatus } from './commands/status';\nimport { devHelp, runDev } from './commands/dev';\nimport { runValidate, validateHelp } from './commands/validate';\nimport { CliError } from './lib/errors';\n\ninterface CommandEntry {\n summary: string;\n help: string;\n run: (argv: string[]) => Promise<void>;\n}\n\nconst commands: Record<string, CommandEntry> = {\n login: {\n summary: 'Sign in to a CMS store and save the token',\n help: loginHelp,\n run: runLogin,\n },\n themes: {\n summary: 'List the themes of the store',\n help: themesHelp,\n run: runThemes,\n },\n pull: {\n summary: 'Download a theme into a local folder',\n help: pullHelp,\n run: runPull,\n },\n status: {\n summary: 'Show local changes since the last pull',\n help: statusHelp,\n run: runStatus,\n },\n push: {\n summary: 'Send changed theme files back as a draft',\n help: pushHelp,\n run: runPush,\n },\n dev: {\n summary: 'Serve the theme locally with live reload',\n help: devHelp,\n run: runDev,\n },\n validate: {\n summary: 'Check the local theme with the CMS publish rules',\n help: validateHelp,\n run: runValidate,\n },\n};\n\nconst mainHelp = (): string => {\n const lines = Object.entries(commands).map(([name, entry]) => ` ${name.padEnd(10)}${entry.summary}`);\n\n return [\n `Usage: ${cliName} <command> [options]`,\n '',\n 'Commands:',\n ...lines,\n '',\n `Run \"${cliName} <command> --help\" for command options.`,\n 'Set CMS_THEME_KIT_TOKEN to use a token without a saved login.',\n '',\n ].join('\\n');\n};\n\nconst describeError = (error: unknown): string => {\n if (error instanceof CliError) {\n return error.message;\n }\n\n if (error instanceof Error) {\n const cause = error.cause instanceof Error ? `: ${error.cause.message}` : '';\n return `${error.message}${cause}`;\n }\n\n return String(error);\n};\n\n// Returns the process exit code instead of exiting, so the entry point stays a one-liner.\nexport const main = async (argv: string[]): Promise<number> => {\n const [name, ...rest] = argv;\n\n if (!name || name === '--help' || name === '-h' || name === 'help') {\n console.log(mainHelp());\n return 0;\n }\n\n if (!Object.hasOwn(commands, name)) {\n console.error(`error: unknown command \"${name}\"\\n`);\n console.error(mainHelp());\n return 1;\n }\n\n const command = commands[name];\n\n if (rest.includes('--help') || rest.includes('-h')) {\n console.log(command.help);\n return 0;\n }\n\n try {\n await command.run(rest);\n return 0;\n } catch (error) {\n console.error(`error: ${describeError(error)}`);\n return error instanceof CliError ? error.exitCode : 1;\n }\n};\n","import { main } from './cli';\n\nprocess.exitCode = await main(process.argv.slice(2));\n"],"mappings":";;;;;;;;;;;;;;;;AAAO,IAAM,UAAU;AAChB,IAAM,eAAe;AACrB,IAAM,cAAc,GAAG,YAAY,IAAI,OAAO;AAC9C,IAAM,qBAAqB;AAC3B,IAAM,mBAAmB;AACzB,IAAM,wBAAwB;AAC9B,IAAM,yBAAyB,CAAC,WAAW,SAAS;AACpD,IAAM,sBAAsB;AAC5B,IAAM,yBAAyB,KAAK,uBAAuB,KAAK,GAAG,CAAC,IAAI,mBAAmB;AAC3F,IAAM,cAAc;;;ACT3B,SAAS,OAAO,OAAO,UAAU,iBAAiB;AAClD,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAevB,IAAM,sBAAsB,MAAc;AAC7C,SAAO,KAAK,QAA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,KAAK;AAAA,EACnC;AAEA,SAAO,OAAO,KAAK;AACvB;AAGO,IAAM,OAAO,OAAO,SAAoC;AAC3D,QAAM,CAAC,MAAM,GAAG,IAAI,IAAI;AAExB,MAAI,CAAC,QAAQ,SAAS,YAAY,SAAS,QAAQ,SAAS,QAAQ;AAChE,YAAQ,IAAI,SAAS,CAAC;AACtB,WAAO;AAAA,EACX;AAEA,MAAI,CAAC,OAAO,OAAO,UAAU,IAAI,GAAG;AAChC,YAAQ,MAAM,2BAA2B,IAAI;AAAA,CAAK;AAClD,YAAQ,MAAM,SAAS,CAAC;AACxB,WAAO;AAAA,EACX;AAEA,QAAM,UAAU,SAAS,IAAI;AAE7B,MAAI,KAAK,SAAS,QAAQ,KAAK,KAAK,SAAS,IAAI,GAAG;AAChD,YAAQ,IAAI,QAAQ,IAAI;AACxB,WAAO;AAAA,EACX;AAEA,MAAI;AACA,UAAM,QAAQ,IAAI,IAAI;AACtB,WAAO;AAAA,EACX,SAAS,OAAO;AACZ,YAAQ,MAAM,UAAU,cAAc,KAAK,CAAC,EAAE;AAC9C,WAAO,iBAAiB,WAAW,MAAM,WAAW;AAAA,EACxD;AACJ;;;AC7GA,QAAQ,WAAW,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC;","names":["resolve","resolve","mkdir","resolve","mkdir","writeFile","dirname","mkdir","dirname","writeFile","mkdir","readFile","writeFile","join","join","readFile","mkdir","writeFile","resolve","mkdir","resolve","resolve","resolve","resolve","resolve","join","resolve","join","resolve","server","resolve","resolve"]}
|
|
1
|
+
{"version":3,"sources":["../src/constants.ts","../src/lib/credentials.ts","../src/lib/connection.ts","../src/lib/args.ts","../src/lib/envelope.ts","../src/lib/auth.ts","../src/lib/prompt.ts","../src/commands/login.ts","../src/commands/pull.ts","../src/lib/cms-client.ts","../src/lib/pull.ts","../src/lib/zip.ts","../src/lib/metadata.ts","../src/commands/themes.ts","../src/commands/push.ts","../src/lib/push.ts","../src/commands/status.ts","../src/lib/status.ts","../src/commands/dev.ts","../src/lib/dev/watcher.ts","../src/commands/validate.ts","../src/cli.ts","../src/bin.ts"],"sourcesContent":["export const cliName = 'cms-theme-kit';\nexport const packageScope = '@tomsher';\nexport const packageName = `${packageScope}/${cliName}`;\nexport const metadataFolderName = '.cms-theme-kit';\nexport const metadataFileName = 'theme.json';\nexport const metadataSchemaVersion = 1;\nexport const credentialsDirSegments = ['.config', 'tomsher'] as const;\nexport const credentialsFileName = 'credentials.json';\nexport const credentialsDisplayPath = `~/${credentialsDirSegments.join('/')}/${credentialsFileName}`;\nexport const tokenEnvVar = 'CMS_THEME_KIT_TOKEN';\n","import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { credentialsDirSegments, credentialsFileName } from '../constants';\nimport { CliError } from './errors';\n\nexport interface StoredLogin {\n cmsUrl: string;\n store: string;\n token: string;\n email: string | null;\n}\n\nexport interface CredentialsFile {\n logins: StoredLogin[];\n}\n\nexport const credentialsFilePath = (): string => {\n return join(homedir(), ...credentialsDirSegments, credentialsFileName);\n};\n\nexport const readCredentials = async (filePath: string = credentialsFilePath()): Promise<CredentialsFile> => {\n let raw: string;\n\n try {\n raw = await readFile(filePath, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return { logins: [] };\n }\n\n throw error;\n }\n\n let parsed: Partial<CredentialsFile>;\n\n try {\n parsed = JSON.parse(raw) as Partial<CredentialsFile>;\n } catch {\n throw new CliError(`Credentials file is not valid JSON: ${filePath}`);\n }\n\n return { logins: Array.isArray(parsed.logins) ? parsed.logins : [] };\n};\n\nexport const findLogin = (credentials: CredentialsFile, cmsUrl: string, store: string): StoredLogin | undefined => {\n return credentials.logins.find((login) => login.cmsUrl === cmsUrl && login.store === store);\n};\n\n// Stores one token per cmsUrl+store pair. The file is kept at mode 0600 because it holds bearer tokens.\nexport const saveLogin = async (login: StoredLogin, filePath: string = credentialsFilePath()): Promise<void> => {\n const credentials = await readCredentials(filePath);\n const others = credentials.logins.filter((item) => item.cmsUrl !== login.cmsUrl || item.store !== login.store);\n const content = JSON.stringify({ logins: [...others, login] }, null, 4);\n\n await mkdir(dirname(filePath), { recursive: true, mode: 0o700 });\n await writeFile(filePath, `${content}\\n`, { mode: 0o600 });\n await chmod(filePath, 0o600);\n};\n","import { tokenEnvVar } from '../constants';\nimport { CliError } from './errors';\nimport { readCredentials, findLogin } from './credentials';\nimport type { ThemeMetadata } from './metadata';\n\nexport interface CmsConnection {\n cmsUrl: string;\n store: string;\n token: string;\n}\n\nexport interface ConnectionOptions {\n cmsUrl?: string;\n store?: string;\n metadata?: ThemeMetadata | null;\n}\n\nexport const normalizeCmsUrl = (value: string): string => {\n return value.trim().replace(/\\/+$/, '');\n};\n\n// Precedence: flags, then the theme's own metadata, then the only saved login. The token comes from the env override first.\nexport const resolveConnection = async (options: ConnectionOptions): Promise<CmsConnection> => {\n const credentials = await readCredentials();\n const onlyLogin = credentials.logins.length === 1 ? credentials.logins[0] : undefined;\n const cmsUrl = normalizeCmsUrl(options.cmsUrl ?? options.metadata?.cmsUrl ?? onlyLogin?.cmsUrl ?? '');\n const store = options.store ?? options.metadata?.store ?? onlyLogin?.store ?? '';\n\n if (!cmsUrl) {\n throw new CliError('Missing CMS URL. Pass --cms-url or run the login command first.');\n }\n\n if (!store) {\n throw new CliError('Missing store slug. Pass --store <slug>.');\n }\n\n const token = process.env[tokenEnvVar] || findLogin(credentials, cmsUrl, store)?.token;\n\n if (!token) {\n throw new CliError(`Not logged in to ${cmsUrl} (store \"${store}\"). Run: login ${cmsUrl} --store ${store}`);\n }\n\n return { cmsUrl, store, token };\n};\n","import { parseArgs, type ParseArgsOptionsConfig } from 'node:util';\nimport { CliError } from './errors';\n\nexport interface ParsedArgs {\n values: Record<string, string | boolean | undefined>;\n positionals: string[];\n}\n\n// Wraps node:util parseArgs so bad flags become CliError (exit 1) instead of a stack trace.\nexport const parseCommandArgs = (argv: string[], options: ParseArgsOptionsConfig): ParsedArgs => {\n try {\n const parsed = parseArgs({ args: argv, options, allowPositionals: true, strict: true });\n return {\n values: parsed.values as Record<string, string | boolean | undefined>,\n positionals: parsed.positionals,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(message);\n }\n};\n\nexport const stringOption = (values: ParsedArgs['values'], key: string): string | undefined => {\n const value = values[key];\n return typeof value === 'string' ? value : undefined;\n};\n\nexport const booleanOption = (values: ParsedArgs['values'], key: string): boolean => {\n return values[key] === true;\n};\n","import { CliError } from './errors';\n\n// Every CMS response is wrapped by the server's TransformInterceptor as { status, message, requestedData }.\nexport const unwrapRequestedData = <T>(body: unknown): T => {\n if (body && typeof body === 'object' && 'requestedData' in body) {\n return (body as { requestedData: T }).requestedData;\n }\n\n throw new CliError('Unexpected CMS response: missing requestedData.');\n};\n","import { ApiError, CliError } from './errors';\nimport { unwrapRequestedData } from './envelope';\nimport { normalizeCmsUrl } from './connection';\n\nexport interface LoginOptions {\n cmsUrl: string;\n store: string;\n email: string;\n password: string;\n fetchImpl?: typeof fetch;\n}\n\nexport interface LoginResult {\n token: string;\n email: string;\n}\n\n// Route: POST /admin/:store/auth/login (AdminAuthController mounted under the auth path).\nexport const loginToCms = async (options: LoginOptions): Promise<LoginResult> => {\n const fetchImpl = options.fetchImpl ?? fetch;\n const url = `${normalizeCmsUrl(options.cmsUrl)}/admin/${encodeURIComponent(options.store)}/auth/login`;\n const response = await fetchImpl(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify({ email: options.email, password: options.password }),\n });\n\n if (!response.ok) {\n throw await ApiError.fromResponse(response);\n }\n\n const session = unwrapRequestedData<{ token?: string; user?: { email?: string } }>(await response.json());\n const token = session.token;\n\n if (!token) {\n throw new CliError('Login response did not include a token.');\n }\n\n return { token, email: session.user?.email ?? options.email };\n};\n","import { createInterface } from 'node:readline';\nimport { Writable } from 'node:stream';\n\n// Asks one question on the terminal. When hidden is true, typed characters are not echoed.\nexport const askLine = async (question: string, hidden = false): Promise<string> => {\n const output = process.stdout;\n let muted = false;\n const filteredOutput = new Writable({\n write(chunk, encoding, callback) {\n if (!muted) {\n output.write(chunk, encoding);\n }\n\n callback();\n },\n });\n const readline = createInterface({ input: process.stdin, output: filteredOutput, terminal: true });\n\n // readline prints the question itself; printing it earlier would be erased when readline redraws the line.\n const answer = await new Promise<string>((resolve) => {\n readline.question(question, resolve);\n muted = hidden;\n });\n\n muted = false;\n output.write('\\n');\n readline.close();\n return answer.trim();\n};\n","import { cliName, credentialsDisplayPath } from '../constants';\nimport { normalizeCmsUrl } from '../lib/connection';\nimport { parseCommandArgs, stringOption } from '../lib/args';\nimport { loginToCms } from '../lib/auth';\nimport { CliError } from '../lib/errors';\nimport { saveLogin } from '../lib/credentials';\nimport { askLine } from '../lib/prompt';\n\nexport const loginHelp = `Usage: ${cliName} login <cms-url> --store <slug> [--email <email>] [--password <password>]\n\nSigns in to a CMS store and saves the token to ${credentialsDisplayPath} (mode 0600).\nMissing email or password are prompted for on the terminal; the password is not echoed.\nPassing --password on the command line can leave it in shell history.\n\nOptions:\n --store <slug> Store (tenant) slug to sign in to (required)\n --email <email> Admin account email\n --password <value> Admin account password\n -h, --help Show this help\n`;\n\nexport const runLogin = async (argv: string[]): Promise<void> => {\n const { values, positionals } = parseCommandArgs(argv, {\n store: { type: 'string' },\n email: { type: 'string' },\n password: { type: 'string' },\n });\n const cmsUrlArg = positionals[0];\n const store = stringOption(values, 'store');\n\n if (!cmsUrlArg) {\n throw new CliError('Missing <cms-url>. See: login --help');\n }\n\n if (!store) {\n throw new CliError('Missing --store <slug>. See: login --help');\n }\n\n const cmsUrl = normalizeCmsUrl(cmsUrlArg);\n const email = stringOption(values, 'email') ?? (await askLine('Email: '));\n const password = stringOption(values, 'password') ?? (await askLine('Password: ', true));\n\n if (!email || !password) {\n throw new CliError('Email and password are required.');\n }\n\n const result = await loginToCms({ cmsUrl, store, email, password });\n await saveLogin({ cmsUrl, store, token: result.token, email: result.email });\n\n console.log(`Logged in to ${cmsUrl} (store \"${store}\") as ${result.email}.`);\n};\n","import { resolve } from 'node:path';\nimport { cliName } from '../constants';\nimport { booleanOption, parseCommandArgs, stringOption } from '../lib/args';\nimport { CliError } from '../lib/errors';\nimport { resolveConnection } from '../lib/connection';\nimport { CmsClient } from '../lib/cms-client';\nimport { findTheme, isExportMode, pullTheme } from '../lib/pull';\nimport { readThemeMetadata, themeExportModes } from '../lib/metadata';\n\nexport const pullHelp = `Usage: ${cliName} pull [theme] [options]\n\nDownloads a theme from the CMS (export-zip) into a folder and records the base hashes\nthat later status and push commands compare against.\n\nArguments:\n theme Theme id or slug. Optional when the folder already has a theme linked.\n\nOptions:\n --mode <mode> ${themeExportModes.join(' | ')} (default: theme)\n --dir <folder> Target folder (default: ./<theme slug>, or the current folder when linked)\n --force Overwrite a non-empty target folder\n --cms-url <url> CMS base URL (default: from the linked theme or the only saved login)\n --store <slug> Store slug (default: from the linked theme or the only saved login)\n --published Not supported yet: the server exports only the draft\n -h, --help Show this help\n`;\n\nexport const runPull = async (argv: string[]): Promise<void> => {\n const { values, positionals } = parseCommandArgs(argv, {\n 'cms-url': { type: 'string' },\n store: { type: 'string' },\n mode: { type: 'string' },\n dir: { type: 'string' },\n force: { type: 'boolean' },\n published: { type: 'boolean' },\n });\n\n if (booleanOption(values, 'published')) {\n throw new CliError(\n '--published is not supported: the server only exports the draft theme (no published-version export).',\n );\n }\n\n const mode = stringOption(values, 'mode') ?? 'theme';\n\n if (!isExportMode(mode)) {\n throw new CliError(`Invalid --mode \"${mode}\". Use one of: ${themeExportModes.join(', ')}.`);\n }\n\n const reference = positionals[0];\n const dirOption = stringOption(values, 'dir');\n const existing = await readThemeMetadata(resolve(dirOption ?? '.'));\n const ref = reference ?? existing?.themeId;\n\n if (!ref) {\n throw new CliError('Pass a theme id or slug, or run pull inside a folder that already has a linked theme.');\n }\n\n const connection = await resolveConnection({\n cmsUrl: stringOption(values, 'cms-url'),\n store: stringOption(values, 'store'),\n metadata: existing,\n });\n const client = new CmsClient(connection);\n const theme = findTheme(await client.listThemes(), ref);\n const targetDir = dirOption ?? (reference ? theme.slug : '.');\n const result = await pullTheme({\n client,\n theme,\n mode,\n targetDir,\n force: booleanOption(values, 'force'),\n cmsUrl: connection.cmsUrl,\n store: connection.store,\n });\n\n console.log(`Pulled \"${theme.name}\" (${mode}) into ${result.dir}: ${result.fileCount} files.`);\n};\n","import type { DeclaredEntityQuery } from '@tomsher/cms-core/types';\nimport { ApiError } from './errors';\nimport { unwrapRequestedData } from './envelope';\nimport type { CmsConnection } from './connection';\n\nexport interface ThemePreviewRequest {\n entities: DeclaredEntityQuery[];\n contentCollections: string[];\n sources: string[];\n linkSources: string[];\n templatePaths: string[];\n page?: {\n templatePath: string;\n category: 'collections' | 'details';\n path?: string;\n };\n}\n\nexport interface RemoteRoute {\n path: string;\n kind: string;\n}\n\nexport interface RemoteTheme {\n id: string;\n name: string;\n slug: string;\n version: string | null;\n renderMode: string;\n}\n\nexport interface RemoteFile {\n filename: string;\n contentHash: string | null;\n}\n\nexport interface BatchFile {\n filename: string;\n content: string;\n expectedHash?: string;\n}\n\nexport interface ValidateFile {\n filename: string;\n content: string;\n}\n\nexport interface ThemeValidationIssue {\n code: string;\n message: string;\n filename?: string;\n path?: string;\n}\n\nexport interface ThemeValidationResult {\n valid: boolean;\n issues: ThemeValidationIssue[];\n}\n\nexport interface ZipThemeFields {\n name?: string;\n renderMode: string;\n}\n\n// Routes are the admin theme endpoints under /admin/:store/themes (themes.controller.ts).\nexport class CmsClient {\n private readonly connection: CmsConnection;\n private readonly fetchImpl: typeof fetch;\n\n constructor(connection: CmsConnection, fetchImpl: typeof fetch = fetch) {\n this.connection = connection;\n this.fetchImpl = fetchImpl;\n }\n\n async listThemes(): Promise<RemoteTheme[]> {\n return unwrapRequestedData<RemoteTheme[]>(await this.requestJson<unknown>(this.themesUrl()));\n }\n\n async listFiles(themeId: string): Promise<RemoteFile[]> {\n return unwrapRequestedData<RemoteFile[]>(await this.requestJson<unknown>(this.themesUrl(themeId, 'files')));\n }\n\n async exportZip(themeId: string, mode: string): Promise<Uint8Array> {\n const query = new URLSearchParams({ mode });\n const response = await this.send(`${this.themesUrl(themeId, 'export-zip')}?${query.toString()}`);\n return new Uint8Array(await response.arrayBuffer());\n }\n\n // Returns the raw JSON body; the payload sits in requestedData (see transform.interceptor.ts).\n async previewData(themeId: string, request: ThemePreviewRequest, countryCode?: string): Promise<unknown> {\n return this.requestJson<unknown>(this.themesUrl(themeId, 'preview-data'), {\n method: 'POST',\n headers: this.jsonHeaders(countryCode),\n body: JSON.stringify(request),\n });\n }\n\n // Resolves a storefront URL to the template that serves it; null when no page matches.\n async resolveRoute(themeId: string, path: string, templatePaths: string[], countryCode?: string): Promise<string | null> {\n try {\n const body = await this.requestJson<unknown>(this.themesUrl(themeId, 'resolve-route'), {\n method: 'POST',\n headers: this.jsonHeaders(countryCode),\n body: JSON.stringify({ path, templatePaths }),\n });\n\n return unwrapRequestedData<{ templatePath: string }>(body).templatePath;\n } catch (error) {\n if (error instanceof ApiError && error.status === 404) {\n return null;\n }\n\n throw error;\n }\n }\n\n async listRoutes(themeId: string, countryCode?: string): Promise<RemoteRoute[]> {\n const headers = countryCode ? { 'x-country-code': countryCode } : undefined;\n\n return unwrapRequestedData<RemoteRoute[]>(await this.requestJson<unknown>(this.themesUrl(themeId, 'routes'), { headers }));\n }\n\n async validateFiles(themeId: string, files: ValidateFile[], removed: string[]): Promise<ThemeValidationResult> {\n const body = await this.requestJson<unknown>(this.themesUrl(themeId, 'validate'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ files, removed }),\n });\n return unwrapRequestedData<ThemeValidationResult>(body);\n }\n\n async saveFilesBatch(themeId: string, files: BatchFile[]): Promise<void> {\n await this.send(this.themesUrl(themeId, 'files', 'batch'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ files }),\n });\n }\n\n async uploadThemeZip(themeId: string, zip: Uint8Array, renderMode: string): Promise<void> {\n await this.send(this.themesUrl(themeId, 'upload-zip'), {\n method: 'POST',\n body: this.zipForm(zip, { renderMode }),\n });\n }\n\n async createThemeFromZip(fields: ZipThemeFields, zip: Uint8Array): Promise<RemoteTheme> {\n const body = await this.requestJson<unknown>(this.themesUrl('upload-zip'), {\n method: 'POST',\n body: this.zipForm(zip, fields),\n });\n return unwrapRequestedData<{ theme: RemoteTheme }>(body).theme;\n }\n\n private themesUrl(...segments: string[]): string {\n const base = `${this.connection.cmsUrl}/admin/${encodeURIComponent(this.connection.store)}/themes`;\n const path = segments.map((segment) => `/${encodeURIComponent(segment)}`).join('');\n return `${base}${path}`;\n }\n\n private zipForm(zip: Uint8Array, fields: ZipThemeFields): FormData {\n const form = new FormData();\n\n if (fields.name) {\n form.append('name', fields.name);\n }\n\n form.append('renderMode', fields.renderMode);\n form.append('importStructure', 'false');\n form.append('importEntries', 'false');\n form.append('importMedia', 'false');\n form.append('file', new Blob([new Uint8Array(zip)], { type: 'application/zip' }), 'theme.zip');\n return form;\n }\n\n private jsonHeaders(countryCode?: string): Record<string, string> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n\n if (countryCode) {\n headers['x-country-code'] = countryCode;\n }\n\n return headers;\n }\n\n private async requestJson<T>(url: string, init: RequestInit = {}): Promise<T> {\n const response = await this.send(url, init);\n return (await response.json()) as T;\n }\n\n private async send(url: string, init: RequestInit = {}): Promise<Response> {\n const headers = new Headers(init.headers);\n headers.set('Authorization', `Bearer ${this.connection.token}`);\n headers.set('Accept', 'application/json');\n\n const response = await this.fetchImpl(url, { ...init, headers });\n\n if (!response.ok) {\n throw await ApiError.fromResponse(response);\n }\n\n return response;\n }\n}\n","import { mkdir, readdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { metadataSchemaVersion } from '../constants';\nimport { CliError } from './errors';\nimport type { CmsClient, RemoteTheme } from './cms-client';\nimport { extractZip } from './zip';\nimport { readLocalTheme, toHashMap } from './theme-files';\nimport { themeExportModes, writeThemeMetadata, type ThemeExportMode, type ThemeMetadata } from './metadata';\n\nexport const isExportMode = (value: string): value is ThemeExportMode => {\n return (themeExportModes as readonly string[]).includes(value);\n};\n\nexport const findTheme = (themes: RemoteTheme[], reference: string): RemoteTheme => {\n const match = themes.find((theme) => theme.id === reference || theme.slug === reference);\n\n if (!match) {\n throw new CliError(`Theme \"${reference}\" was not found in this store.`);\n }\n\n return match;\n};\n\nexport const isNonEmptyDirectory = async (dir: string): Promise<boolean> => {\n try {\n const entries = await readdir(dir);\n return entries.length > 0;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return false;\n }\n\n throw error;\n }\n};\n\nexport interface PullOptions {\n client: CmsClient;\n theme: RemoteTheme;\n mode: ThemeExportMode;\n targetDir: string;\n force: boolean;\n cmsUrl: string;\n store: string;\n}\n\nexport const pullTheme = async (options: PullOptions): Promise<{ dir: string; fileCount: number }> => {\n const targetDir = resolve(options.targetDir);\n\n if (!options.force && (await isNonEmptyDirectory(targetDir))) {\n throw new CliError(`Refusing to overwrite non-empty folder ${targetDir}. Pass --force to overwrite.`);\n }\n\n const archive = await options.client.exportZip(options.theme.id, options.mode);\n\n await mkdir(targetDir, { recursive: true });\n await extractZip(archive, targetDir);\n\n const localFiles = await readLocalTheme(targetDir);\n const metadata: ThemeMetadata = {\n version: metadataSchemaVersion,\n cmsUrl: options.cmsUrl,\n store: options.store,\n themeId: options.theme.id,\n slug: options.theme.slug,\n renderMode: options.theme.renderMode,\n pulledVersion: options.theme.version,\n mode: options.mode,\n baseHashes: toHashMap(localFiles),\n };\n\n await writeThemeMetadata(targetDir, metadata);\n return { dir: targetDir, fileCount: localFiles.length };\n};\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, resolve, sep } from 'node:path';\nimport { unzipSync, zipSync } from 'fflate';\nimport { CliError } from './errors';\n\nexport interface ZipInput {\n path: string;\n bytes: Uint8Array;\n}\n\n// Maps an archive entry to a file path inside targetDir, or throws if it would escape it (zip-slip).\nexport const resolveArchivePath = (targetDir: string, entryName: string): string => {\n const normalized = entryName.replace(/\\\\/g, '/');\n\n if (isAbsolute(entryName) || normalized.startsWith('/') || /^[a-zA-Z]:/.test(normalized)) {\n throw new CliError(`Unsafe archive path: ${entryName}`);\n }\n\n if (normalized.split('/').some((segment) => segment === '..')) {\n throw new CliError(`Unsafe archive path: ${entryName}`);\n }\n\n const root = resolve(targetDir);\n const target = resolve(root, normalized);\n\n if (!target.startsWith(root + sep)) {\n throw new CliError(`Unsafe archive path: ${entryName}`);\n }\n\n return target;\n};\n\n// Validates every entry before writing anything, so a bad archive leaves the folder untouched.\nexport const extractZip = async (archive: Uint8Array, targetDir: string): Promise<string[]> => {\n const entries = unzipSync(archive);\n const plan = Object.entries(entries)\n .filter(([name]) => !name.endsWith('/'))\n .map(([name, bytes]) => ({ name, bytes, target: resolveArchivePath(targetDir, name) }));\n\n for (const item of plan) {\n await mkdir(dirname(item.target), { recursive: true });\n await writeFile(item.target, item.bytes);\n }\n\n return plan.map((item) => item.name);\n};\n\nexport const buildZip = (files: ZipInput[]): Uint8Array => {\n const input: Record<string, Uint8Array> = {};\n\n for (const file of files) {\n input[file.path] = file.bytes;\n }\n\n return zipSync(input, { level: 6 });\n};\n","import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { metadataFileName, metadataFolderName, metadataSchemaVersion } from '../constants';\nimport { CliError } from './errors';\n\nexport const themeExportModes = ['theme', 'theme-structure', 'theme-complete'] as const;\n\nexport type ThemeExportMode = (typeof themeExportModes)[number];\n\nexport interface ThemeMetadata {\n version: number;\n cmsUrl: string;\n store: string;\n themeId: string;\n slug: string;\n renderMode: string;\n pulledVersion: string | null;\n mode: ThemeExportMode;\n baseHashes: Record<string, string>;\n}\n\nconst metadataPath = (themeDir: string): string => {\n return join(themeDir, metadataFolderName, metadataFileName);\n};\n\nexport const readThemeMetadata = async (themeDir: string): Promise<ThemeMetadata | null> => {\n let raw: string;\n\n try {\n raw = await readFile(metadataPath(themeDir), 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n\n throw error;\n }\n\n try {\n return JSON.parse(raw) as ThemeMetadata;\n } catch {\n throw new CliError(`${metadataPath(themeDir)} is not valid JSON.`);\n }\n};\n\nexport const writeThemeMetadata = async (themeDir: string, metadata: ThemeMetadata): Promise<void> => {\n await mkdir(join(themeDir, metadataFolderName), { recursive: true });\n const content = JSON.stringify({ ...metadata, version: metadataSchemaVersion }, null, 4);\n await writeFile(metadataPath(themeDir), `${content}\\n`);\n};\n","import { cliName } from '../constants';\nimport { parseCommandArgs, stringOption } from '../lib/args';\nimport { CmsClient } from '../lib/cms-client';\nimport { resolveConnection } from '../lib/connection';\n\nexport const themesHelp = `Usage: ${cliName} themes [options]\n\nLists the themes of the store (id, slug, render mode, version).\n\nOptions:\n --cms-url <url> CMS base URL (default: the only saved login)\n --store <slug> Store slug (default: the only saved login)\n -h, --help Show this help\n`;\n\nexport const runThemes = async (argv: string[]): Promise<void> => {\n const { values } = parseCommandArgs(argv, {\n 'cms-url': { type: 'string' },\n store: { type: 'string' },\n });\n const connection = await resolveConnection({\n cmsUrl: stringOption(values, 'cms-url'),\n store: stringOption(values, 'store'),\n });\n const themes = await new CmsClient(connection).listThemes();\n\n if (themes.length === 0) {\n console.log('No themes in this store.');\n return;\n }\n\n for (const theme of themes) {\n console.log(`${theme.id} ${theme.slug} ${theme.renderMode} v${theme.version ?? '-'} ${theme.name}`);\n }\n};\n","import { resolve } from 'node:path';\nimport { cliName } from '../constants';\nimport { booleanOption, parseCommandArgs, stringOption } from '../lib/args';\nimport { resolveConnection } from '../lib/connection';\nimport { CliError } from '../lib/errors';\nimport { CmsClient } from '../lib/cms-client';\nimport { readThemeMetadata } from '../lib/metadata';\nimport { pushTheme, type PushSummary } from '../lib/push';\n\nexport const pushHelp = `Usage: ${cliName} push [options]\n\nSends locally changed theme files to the CMS as a draft. Never publishes.\nText changes go through files/batch (chunks of 200). Deletions, binary assets, or any\nremote change to a file you did not pull force a whole-theme zip upload instead.\n\nOptions:\n --dir <folder> Theme folder (default: current folder)\n --dry-run Show what would be sent, without sending it\n --force Overwrite files changed on the CMS since pull\n --create --name <name> Create a new theme from this folder instead of updating a linked one\n --render-mode <mode> liquid | static (used with --create; default: linked theme's mode, else liquid)\n --cms-url <url> CMS base URL (default: from the linked theme or the only saved login)\n --store <slug> Store slug (default: from the linked theme or the only saved login)\n -h, --help Show this help\n`;\n\nconst renderModes = ['liquid', 'static'];\n\nconst describeSummary = (summary: PushSummary): string => {\n const { added, modified, deleted } = summary.diff;\n const counts = `${added.length} added, ${modified.length} modified, ${deleted.length} deleted`;\n\n if (summary.method === 'none') {\n return 'No local changes to push.';\n }\n\n if (summary.dryRun) {\n return `Dry run: would push via ${summary.method} (${counts}). Nothing was sent.`;\n }\n\n if (summary.method === 'create') {\n return `Created theme ${summary.themeId}. It is a draft; nothing was published.`;\n }\n\n const target = `theme ${summary.themeId} via ${summary.method} (${counts})`;\n\n return `Pushed to ${target}. Saved as draft; the live theme was not changed.`;\n};\n\nexport const runPush = async (argv: string[]): Promise<void> => {\n const { values } = parseCommandArgs(argv, {\n dir: { type: 'string' },\n 'cms-url': { type: 'string' },\n store: { type: 'string' },\n force: { type: 'boolean' },\n 'dry-run': { type: 'boolean' },\n create: { type: 'boolean' },\n name: { type: 'string' },\n 'render-mode': { type: 'string' },\n });\n const dir = resolve(stringOption(values, 'dir') ?? '.');\n const metadata = await readThemeMetadata(dir);\n const renderMode = stringOption(values, 'render-mode') ?? metadata?.renderMode ?? 'liquid';\n\n if (!renderModes.includes(renderMode)) {\n throw new CliError(`Invalid --render-mode \"${renderMode}\". Use liquid or static.`);\n }\n\n const connection = await resolveConnection({\n cmsUrl: stringOption(values, 'cms-url'),\n store: stringOption(values, 'store'),\n metadata,\n });\n const summary = await pushTheme({\n dir,\n client: new CmsClient(connection),\n metadata,\n cmsUrl: connection.cmsUrl,\n store: connection.store,\n create: booleanOption(values, 'create'),\n name: stringOption(values, 'name'),\n renderMode,\n force: booleanOption(values, 'force'),\n dryRun: booleanOption(values, 'dry-run'),\n });\n\n console.log(describeSummary(summary));\n};\n","import { metadataSchemaVersion } from '../constants';\nimport { CliError } from './errors';\nimport type { CmsClient, BatchFile, RemoteFile } from './cms-client';\nimport { buildZip } from './zip';\nimport { diffHashes, type ThemeDiff } from './hash';\nimport { isPushablePath, isTextPath, readLocalTheme, toHashMap, type LocalFile } from './theme-files';\nimport { writeThemeMetadata, type ThemeMetadata } from './metadata';\n\n// Server limit for files in one files/batch request (BatchSaveThemeFilesDto).\nexport const maxBatchFiles = 200;\n\nexport interface Conflict {\n path: string;\n expected: string | null;\n remote: string | null;\n}\n\nexport interface PushOptions {\n dir: string;\n client: CmsClient;\n metadata: ThemeMetadata | null;\n cmsUrl: string;\n store: string;\n create: boolean;\n name?: string;\n renderMode: string;\n force: boolean;\n dryRun: boolean;\n}\n\nexport type PushMethod = 'none' | 'batch' | 'zip' | 'create';\n\nexport interface PushSummary {\n method: PushMethod;\n diff: ThemeDiff;\n themeId: string | null;\n dryRun: boolean;\n}\n\nexport const chunkArray = <T>(items: T[], size: number): T[][] => {\n const chunks: T[][] = [];\n\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n\n return chunks;\n};\n\n// A path is in conflict when the remote copy differs from what was pulled, or when a remote file\n// would be lost by a whole-theme zip upload (a file the local folder does not know about).\nexport const findConflicts = (\n base: Record<string, string>,\n local: Record<string, string>,\n remote: Record<string, string>,\n): Conflict[] => {\n const paths = new Set([...Object.keys(base), ...Object.keys(local), ...Object.keys(remote)]);\n const conflicts: Conflict[] = [];\n\n for (const path of [...paths].sort()) {\n const baseHash = base[path];\n const remoteHash = remote[path];\n\n if (baseHash !== undefined) {\n if (remoteHash !== baseHash) {\n conflicts.push({ path, expected: baseHash, remote: remoteHash ?? null });\n }\n\n continue;\n }\n\n if (remoteHash !== undefined && remoteHash !== local[path]) {\n conflicts.push({ path, expected: null, remote: remoteHash });\n }\n }\n\n return conflicts;\n};\n\nexport const toRemoteHashes = (files: RemoteFile[]): Record<string, string> => {\n const hashes: Record<string, string> = {};\n\n for (const file of files) {\n if (isPushablePath(file.filename)) {\n hashes[file.filename] = file.contentHash ?? '';\n }\n }\n\n return hashes;\n};\n\nconst formatConflicts = (conflicts: Conflict[]): string => {\n const lines = conflicts.map((conflict) => {\n return ` - ${conflict.path} (pulled ${conflict.expected ?? 'none'}, remote ${conflict.remote ?? 'missing'})`;\n });\n\n return [\n 'The theme changed on the CMS since you pulled it. Conflicting files:',\n ...lines,\n 'Run pull into a new folder to merge, or pass --force to overwrite.',\n ].join('\\n');\n};\n\nconst toBatchFile = (file: LocalFile, baseHashes: Record<string, string>, force: boolean): BatchFile => {\n const expectedHash = force ? undefined : baseHashes[file.path];\n\n return {\n filename: file.path,\n content: new TextDecoder().decode(file.bytes),\n expectedHash,\n };\n};\n\nexport const pushTheme = async (options: PushOptions): Promise<PushSummary> => {\n if (options.create && options.metadata) {\n throw new CliError(\n `This folder is already linked to theme ${options.metadata.themeId}. Remove .cms-theme-kit to create a new theme.`,\n );\n }\n\n const localFiles = await readLocalTheme(options.dir);\n\n if (localFiles.length === 0) {\n throw new CliError(`No theme files found in ${options.dir}.`);\n }\n\n const localHashes = toHashMap(localFiles);\n const baseHashes = options.metadata?.baseHashes ?? {};\n const diff = diffHashes(baseHashes, localHashes);\n\n if (options.create) {\n return createTheme(options, localFiles, localHashes, diff);\n }\n\n const metadata = options.metadata as ThemeMetadata;\n const changedCount = diff.added.length + diff.modified.length + diff.deleted.length;\n\n if (changedCount === 0) {\n return { method: 'none', diff, themeId: metadata.themeId, dryRun: options.dryRun };\n }\n\n const remoteFiles = await options.client.listFiles(metadata.themeId);\n const conflicts = findConflicts(baseHashes, localHashes, toRemoteHashes(remoteFiles));\n\n if (conflicts.length > 0 && !options.force) {\n throw new CliError(formatConflicts(conflicts));\n }\n\n // The batch endpoint is text-only and cannot delete, so anything else needs a whole-theme zip upload.\n const needsZip =\n diff.deleted.length > 0 || [...diff.added, ...diff.modified].some((path) => !isTextPath(path));\n const method: PushMethod = needsZip ? 'zip' : 'batch';\n\n if (options.dryRun) {\n return { method, diff, themeId: metadata.themeId, dryRun: true };\n }\n\n if (needsZip) {\n const zip = buildZip(localFiles);\n await options.client.uploadThemeZip(metadata.themeId, zip, metadata.renderMode);\n metadata.baseHashes = localHashes;\n await writeThemeMetadata(options.dir, metadata);\n return { method, diff, themeId: metadata.themeId, dryRun: false };\n }\n\n const changedPaths = new Set([...diff.added, ...diff.modified]);\n const changedFiles = localFiles.filter((file) => changedPaths.has(file.path));\n\n // Metadata is saved after every chunk so a failure mid-push leaves the base hashes accurate.\n for (const chunk of chunkArray(changedFiles, maxBatchFiles)) {\n const batch = chunk.map((file) => toBatchFile(file, baseHashes, options.force));\n await options.client.saveFilesBatch(metadata.themeId, batch);\n\n for (const file of chunk) {\n metadata.baseHashes[file.path] = file.hash;\n }\n\n await writeThemeMetadata(options.dir, metadata);\n }\n\n return { method, diff, themeId: metadata.themeId, dryRun: false };\n};\n\nconst createTheme = async (\n options: PushOptions,\n localFiles: LocalFile[],\n localHashes: Record<string, string>,\n diff: ThemeDiff,\n): Promise<PushSummary> => {\n if (!options.name) {\n throw new CliError('Creating a theme needs --name <name>.');\n }\n\n if (options.dryRun) {\n return { method: 'create', diff, themeId: null, dryRun: true };\n }\n\n const theme = await options.client.createThemeFromZip(\n { name: options.name, renderMode: options.renderMode },\n buildZip(localFiles),\n );\n const metadata: ThemeMetadata = {\n version: metadataSchemaVersion,\n cmsUrl: options.cmsUrl,\n store: options.store,\n themeId: theme.id,\n slug: theme.slug,\n renderMode: theme.renderMode,\n pulledVersion: theme.version,\n mode: 'theme',\n baseHashes: localHashes,\n };\n\n await writeThemeMetadata(options.dir, metadata);\n return { method: 'create', diff, themeId: theme.id, dryRun: false };\n};\n","import { resolve } from 'node:path';\nimport { cliName, metadataFileName, metadataFolderName } from '../constants';\nimport { booleanOption, parseCommandArgs, stringOption } from '../lib/args';\nimport { resolveConnection } from '../lib/connection';\nimport { CliError } from '../lib/errors';\nimport { CmsClient } from '../lib/cms-client';\nimport { diffHashes } from '../lib/hash';\nimport { readThemeMetadata } from '../lib/metadata';\nimport { remoteChangedPaths } from '../lib/status';\nimport { readLocalTheme, toHashMap } from '../lib/theme-files';\nimport { toRemoteHashes } from '../lib/push';\n\nexport const statusHelp = `Usage: ${cliName} status [options]\n\nCompares the local theme folder with the hashes recorded at pull time.\n\nOptions:\n --dir <folder> Theme folder (default: current folder)\n --remote Also fetch the CMS file list and show files changed on the CMS since pull\n --cms-url <url> CMS base URL (only used with --remote)\n --store <slug> Store slug (only used with --remote)\n -h, --help Show this help\n`;\n\nconst printSection = (title: string, paths: string[]): void => {\n console.log(`${title} (${paths.length}):`);\n\n for (const path of paths) {\n console.log(` ${path}`);\n }\n};\n\nexport const runStatus = async (argv: string[]): Promise<void> => {\n const { values } = parseCommandArgs(argv, {\n dir: { type: 'string' },\n remote: { type: 'boolean' },\n 'cms-url': { type: 'string' },\n store: { type: 'string' },\n });\n const dir = resolve(stringOption(values, 'dir') ?? '.');\n const metadata = await readThemeMetadata(dir);\n\n if (!metadata) {\n throw new CliError(`No ${metadataFolderName}/${metadataFileName} in ${dir}. Run pull first.`);\n }\n\n const localHashes = toHashMap(await readLocalTheme(dir));\n const diff = diffHashes(metadata.baseHashes, localHashes);\n\n console.log(`Theme \"${metadata.slug}\" (${metadata.themeId}) in ${dir}`);\n printSection('Added locally', diff.added);\n printSection('Modified locally', diff.modified);\n printSection('Deleted locally', diff.deleted);\n\n if (booleanOption(values, 'remote')) {\n const connection = await resolveConnection({\n cmsUrl: stringOption(values, 'cms-url'),\n store: stringOption(values, 'store'),\n metadata,\n });\n const client = new CmsClient(connection);\n const remoteHashes = toRemoteHashes(await client.listFiles(metadata.themeId));\n printSection('Changed on the CMS since pull', remoteChangedPaths(metadata.baseHashes, remoteHashes));\n }\n};\n","// Paths whose remote hash no longer matches the hash recorded at pull time, or that only exist remotely.\nexport const remoteChangedPaths = (base: Record<string, string>, remote: Record<string, string>): string[] => {\n const paths = new Set([...Object.keys(base), ...Object.keys(remote)]);\n const changed: string[] = [];\n\n for (const path of [...paths].sort()) {\n if (base[path] !== remote[path]) {\n changed.push(path);\n }\n }\n\n return changed;\n};\n","import { stat } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { liquidThemeFolderNames, staticThemeHomePath } from '@tomsher/cms-core/constants';\nimport { cliName, metadataFileName, metadataFolderName } from '../constants';\nimport { parseCommandArgs, stringOption } from '../lib/args';\nimport { resolveConnection } from '../lib/connection';\nimport { CliError } from '../lib/errors';\nimport { CmsClient } from '../lib/cms-client';\nimport type { DataSource } from '../lib/dev/data-source';\nimport type { DevServer } from '../lib/dev/server';\nimport { watchThemeDir } from '../lib/dev/watcher';\nimport { readThemeMetadata, type ThemeMetadata } from '../lib/metadata';\n\nexport const devHelp = `Usage: ${cliName} dev [options]\n\nServes the theme on localhost. Liquid themes are rendered with the same engine as the theme editor preview;\nstatic themes (static/index.html) are served as plain HTML pages.\nSaving a file in the theme folder reloads open pages. Stop with Ctrl-C.\n\nOptions:\n --dir <folder> Theme folder (default: current folder)\n --port <n> Port to listen on (default: 4400)\n --mode <mode> liquid | static (default: from the linked theme; without one, static when the\n folder has static/index.html and no templates/)\n --data <source> live | fixtures (default: live; liquid themes only)\n live: preview data from the CMS (needs a pulled theme and login)\n fixtures: fixtures/<template path with / replaced by -> JSON file\n --country <code> Country code sent with live data requests, e.g. AE\n --lang <code> Language used for locale overrides (default: en)\n --template <path> Template served at / (default: templates/index.json; liquid themes only)\n --cms-url <url> CMS base URL (live data only; default: from the linked theme or the only saved login)\n --store <slug> Store slug (live data only; default: from the linked theme or the only saved login)\n -h, --help Show this help\n`;\n\nconst defaultPort = 4400;\nconst defaultTemplate = 'templates/index.json';\nconst defaultLanguage = 'en';\nconst dataSourceNames = ['live', 'fixtures'];\nconst devModes = ['liquid', 'static'];\n\nconst parsePort = (value: string | undefined): number => {\n if (value === undefined) {\n return defaultPort;\n }\n\n const port = Number(value);\n\n if (!Number.isInteger(port) || port < 0 || port > 65535) {\n throw new CliError(`Invalid --port \"${value}\". Use a whole number from 0 to 65535.`);\n }\n\n return port;\n};\n\nconst pathExists = async (path: string): Promise<boolean> => {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n};\n\n// The linked theme's render mode wins. Without metadata, a folder with static/index.html and no templates/ is static.\nconst resolveDevMode = async (requested: string | undefined, themeDir: string, metadata: ThemeMetadata | null): Promise<string> => {\n if (requested !== undefined) {\n if (!devModes.includes(requested)) {\n throw new CliError(`Invalid --mode \"${requested}\". Use liquid or static.`);\n }\n\n return requested;\n }\n\n if (metadata) {\n return metadata.renderMode === 'static' ? 'static' : 'liquid';\n }\n\n const hasStaticHome = await pathExists(join(themeDir, staticThemeHomePath));\n const hasTemplates = await pathExists(join(themeDir, liquidThemeFolderNames.templates));\n\n return hasStaticHome && !hasTemplates ? 'static' : 'liquid';\n};\n\nconst waitForShutdown = (): Promise<void> => {\n return new Promise((resolveWait) => {\n process.once('SIGINT', resolveWait);\n process.once('SIGTERM', resolveWait);\n });\n};\n\nconst serveUntilInterrupted = async (themeDir: string, server: DevServer): Promise<void> => {\n const watcher = watchThemeDir(themeDir, () => {\n server.notifyChanged().catch((error: unknown) => {\n console.error(`error: could not reload theme: ${error instanceof Error ? error.message : String(error)}`);\n });\n });\n\n await waitForShutdown();\n watcher.close();\n await server.close();\n};\n\n// Loaded on demand: importing the liquid engine logs a LiquidJS warning, which other commands must not show.\nexport const runDev = async (argv: string[]): Promise<void> => {\n const { values } = parseCommandArgs(argv, {\n dir: { type: 'string' },\n port: { type: 'string' },\n mode: { type: 'string' },\n data: { type: 'string' },\n country: { type: 'string' },\n lang: { type: 'string' },\n template: { type: 'string' },\n 'cms-url': { type: 'string' },\n store: { type: 'string' },\n });\n const dir = resolve(stringOption(values, 'dir') ?? '.');\n const port = parsePort(stringOption(values, 'port'));\n const metadata = await readThemeMetadata(dir);\n const mode = await resolveDevMode(stringOption(values, 'mode'), dir, metadata);\n\n if (mode === 'static') {\n const { startStaticDevServer } = await import('../lib/dev/static-server');\n const server = await startStaticDevServer({ themeDir: dir, port });\n\n console.log(`Previewing static theme at ${server.url}/`);\n console.log(`Pages: ${server.url}/__templates`);\n console.log('Press Ctrl-C to stop.');\n\n await serveUntilInterrupted(dir, server);\n return;\n }\n\n const { createFixturesDataSource, createLiveDataSource } = await import('../lib/dev/data-source');\n const { startDevServer } = await import('../lib/dev/server');\n const dataMode = stringOption(values, 'data') ?? 'live';\n const templatePath = stringOption(values, 'template') ?? defaultTemplate;\n const countryCode = stringOption(values, 'country');\n const languageCode = stringOption(values, 'lang') ?? defaultLanguage;\n\n if (!dataSourceNames.includes(dataMode)) {\n throw new CliError(`Invalid --data \"${dataMode}\". Use live or fixtures.`);\n }\n\n if (!templatePath.startsWith('templates/') || !templatePath.endsWith('.json')) {\n throw new CliError(`Invalid --template \"${templatePath}\". Use a path like templates/index.json.`);\n }\n\n let dataSource: DataSource;\n\n if (dataMode === 'fixtures') {\n dataSource = createFixturesDataSource(dir);\n } else {\n if (!metadata) {\n throw new CliError(`No ${metadataFolderName}/${metadataFileName} in ${dir}. Run pull first, or use --data fixtures.`);\n }\n\n const connection = await resolveConnection({\n cmsUrl: stringOption(values, 'cms-url'),\n store: stringOption(values, 'store'),\n metadata,\n });\n process.env.NEXT_PUBLIC_IMAGE_URL ??= connection.cmsUrl;\n dataSource = createLiveDataSource({\n client: new CmsClient(connection),\n themeId: metadata.themeId,\n countryCode,\n });\n }\n\n const server = await startDevServer({\n themeDir: dir,\n port,\n templatePath,\n languageCode,\n countryCode,\n dataSource,\n });\n\n console.log(`Previewing ${templatePath} at ${server.url}/ (data: ${dataMode}).`);\n console.log(`Templates: ${server.url}/__templates`);\n console.log('Press Ctrl-C to stop.');\n\n await serveUntilInterrupted(dir, server);\n};\n","import { watch } from 'node:fs';\nimport { metadataFolderName } from '../../constants';\n\nconst ignoredSegments = [metadataFolderName, 'node_modules', '.git'];\n\nexport const isIgnoredWatchPath = (relativePath: string): boolean => {\n return relativePath\n .split(/[\\\\/]/)\n .some((segment) => ignoredSegments.includes(segment));\n};\n\nexport interface ThemeWatcher {\n close: () => void;\n}\n\n// Coalesces bursts of file events (editor saves, multi-file writes) into one onChange call.\nexport const watchThemeDir = (themeDir: string, onChange: () => void, debounceMs = 100): ThemeWatcher => {\n let timer: NodeJS.Timeout | undefined;\n const watcher = watch(themeDir, { recursive: true }, (_eventType, filename) => {\n if (filename && isIgnoredWatchPath(String(filename))) {\n return;\n }\n\n clearTimeout(timer);\n timer = setTimeout(onChange, debounceMs);\n });\n\n return {\n close: () => {\n clearTimeout(timer);\n watcher.close();\n },\n };\n};\n","import { resolve } from 'node:path';\nimport { cliName, metadataFileName, metadataFolderName } from '../constants';\nimport { parseCommandArgs, stringOption } from '../lib/args';\nimport { CmsClient } from '../lib/cms-client';\nimport { resolveConnection } from '../lib/connection';\nimport { CliError } from '../lib/errors';\nimport { diffHashes } from '../lib/hash';\nimport { readThemeMetadata } from '../lib/metadata';\nimport { isTextPath, readLocalTheme, toHashMap } from '../lib/theme-files';\n\nexport const validateHelp = `Usage: ${cliName} validate [options]\n\nChecks the local theme with the same rules the CMS applies when publishing.\nOnly changed files are sent; nothing is saved on the CMS.\n\nOptions:\n --dir <folder> Theme folder (default: current folder)\n --cms-url <url> CMS base URL\n --store <slug> Store slug\n -h, --help Show this help\n`;\n\nexport const runValidate = async (argv: string[]): Promise<void> => {\n const { values } = parseCommandArgs(argv, {\n dir: { type: 'string' },\n 'cms-url': { type: 'string' },\n store: { type: 'string' },\n });\n const dir = resolve(stringOption(values, 'dir') ?? '.');\n const metadata = await readThemeMetadata(dir);\n\n if (!metadata) {\n throw new CliError(`No ${metadataFolderName}/${metadataFileName} in ${dir}. Run pull first.`);\n }\n\n const localFiles = await readLocalTheme(dir);\n const diff = diffHashes(metadata.baseHashes, toHashMap(localFiles));\n const changed = new Set([...diff.added, ...diff.modified]);\n const files = localFiles\n .filter((file) => changed.has(file.path) && isTextPath(file.path))\n .map((file) => ({ filename: file.path, content: Buffer.from(file.bytes).toString('utf8') }));\n\n const connection = await resolveConnection({\n cmsUrl: stringOption(values, 'cms-url'),\n store: stringOption(values, 'store'),\n metadata,\n });\n const result = await new CmsClient(connection).validateFiles(metadata.themeId, files, diff.deleted);\n\n if (result.valid) {\n console.log('Theme is valid.');\n return;\n }\n\n for (const issue of result.issues) {\n const location = [issue.filename, issue.path].filter(Boolean).join(' ');\n console.error(`${location ? `${location}: ` : ''}${issue.message}`);\n }\n\n throw new CliError(`${result.issues.length} validation issue(s).`);\n};\n","import { cliName } from './constants';\nimport { loginHelp, runLogin } from './commands/login';\nimport { pullHelp, runPull } from './commands/pull';\nimport { runThemes, themesHelp } from './commands/themes';\nimport { pushHelp, runPush } from './commands/push';\nimport { statusHelp, runStatus } from './commands/status';\nimport { devHelp, runDev } from './commands/dev';\nimport { runValidate, validateHelp } from './commands/validate';\nimport { CliError } from './lib/errors';\n\ninterface CommandEntry {\n summary: string;\n help: string;\n run: (argv: string[]) => Promise<void>;\n}\n\nconst commands: Record<string, CommandEntry> = {\n login: {\n summary: 'Sign in to a CMS store and save the token',\n help: loginHelp,\n run: runLogin,\n },\n themes: {\n summary: 'List the themes of the store',\n help: themesHelp,\n run: runThemes,\n },\n pull: {\n summary: 'Download a theme into a local folder',\n help: pullHelp,\n run: runPull,\n },\n status: {\n summary: 'Show local changes since the last pull',\n help: statusHelp,\n run: runStatus,\n },\n push: {\n summary: 'Send changed theme files back as a draft',\n help: pushHelp,\n run: runPush,\n },\n dev: {\n summary: 'Serve the theme locally with live reload',\n help: devHelp,\n run: runDev,\n },\n validate: {\n summary: 'Check the local theme with the CMS publish rules',\n help: validateHelp,\n run: runValidate,\n },\n};\n\nconst mainHelp = (): string => {\n const lines = Object.entries(commands).map(([name, entry]) => ` ${name.padEnd(10)}${entry.summary}`);\n\n return [\n `Usage: ${cliName} <command> [options]`,\n '',\n 'Commands:',\n ...lines,\n '',\n `Run \"${cliName} <command> --help\" for command options.`,\n 'Set CMS_THEME_KIT_TOKEN to use a token without a saved login.',\n '',\n ].join('\\n');\n};\n\nconst describeError = (error: unknown): string => {\n if (error instanceof CliError) {\n return error.message;\n }\n\n if (error instanceof Error) {\n const cause = error.cause instanceof Error ? `: ${error.cause.message}` : '';\n return `${error.message}${cause}`;\n }\n\n return String(error);\n};\n\n// Returns the process exit code instead of exiting, so the entry point stays a one-liner.\nexport const main = async (argv: string[]): Promise<number> => {\n const [name, ...rest] = argv;\n\n if (!name || name === '--help' || name === '-h' || name === 'help') {\n console.log(mainHelp());\n return 0;\n }\n\n if (!Object.hasOwn(commands, name)) {\n console.error(`error: unknown command \"${name}\"\\n`);\n console.error(mainHelp());\n return 1;\n }\n\n const command = commands[name];\n\n if (rest.includes('--help') || rest.includes('-h')) {\n console.log(command.help);\n return 0;\n }\n\n try {\n await command.run(rest);\n return 0;\n } catch (error) {\n console.error(`error: ${describeError(error)}`);\n return error instanceof CliError ? error.exitCode : 1;\n }\n};\n","import { main } from './cli';\n\nprocess.exitCode = await main(process.argv.slice(2));\n"],"mappings":";;;;;;;;;;;;;;;;AAAO,IAAM,UAAU;AAChB,IAAM,eAAe;AACrB,IAAM,cAAc,GAAG,YAAY,IAAI,OAAO;AAC9C,IAAM,qBAAqB;AAC3B,IAAM,mBAAmB;AACzB,IAAM,wBAAwB;AAC9B,IAAM,yBAAyB,CAAC,WAAW,SAAS;AACpD,IAAM,sBAAsB;AAC5B,IAAM,yBAAyB,KAAK,uBAAuB,KAAK,GAAG,CAAC,IAAI,mBAAmB;AAC3F,IAAM,cAAc;;;ACT3B,SAAS,OAAO,OAAO,UAAU,iBAAiB;AAClD,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAevB,IAAM,sBAAsB,MAAc;AAC7C,SAAO,KA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IAAI,QAAQ,IAAI;AACxB,WAAO;AAAA,EACX;AAEA,MAAI;AACA,UAAM,QAAQ,IAAI,IAAI;AACtB,WAAO;AAAA,EACX,SAAS,OAAO;AACZ,YAAQ,MAAM,UAAU,cAAc,KAAK,CAAC,EAAE;AAC9C,WAAO,iBAAiB,WAAW,MAAM,WAAW;AAAA,EACxD;AACJ;;;AC7GA,QAAQ,WAAW,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC;","names":["resolve","resolve","mkdir","resolve","mkdir","writeFile","dirname","mkdir","dirname","writeFile","mkdir","readFile","writeFile","join","join","readFile","mkdir","writeFile","resolve","mkdir","resolve","resolve","resolve","resolve","resolve","join","resolve","join","resolve","server","resolve","resolve"]}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
|
+
collectThemeLinkTargetReferences,
|
|
3
4
|
getLiquidThemeCollectionHandles,
|
|
4
5
|
getLiquidThemeEntityQueries,
|
|
5
6
|
getLiquidThemeEntitySources,
|
|
6
7
|
getLiquidThemeReachableBuffers,
|
|
7
8
|
requiresCurrentEntry
|
|
8
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-UMGL5N53.js";
|
|
9
10
|
import {
|
|
10
11
|
CliError,
|
|
11
12
|
liquidThemeFolderNames,
|
|
@@ -13,13 +14,13 @@ import {
|
|
|
13
14
|
sha256Hex,
|
|
14
15
|
themeTemplateCategories,
|
|
15
16
|
themeTemplateCategoryKeys
|
|
16
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-VY553LTO.js";
|
|
17
18
|
|
|
18
19
|
// src/lib/dev/data-source.ts
|
|
19
20
|
import { readFile } from "fs/promises";
|
|
20
21
|
import { join } from "path";
|
|
21
22
|
|
|
22
|
-
// ../cms-
|
|
23
|
+
// ../cms-core/dist/utils/index.js
|
|
23
24
|
var getLiquidThemeTemplateCategory = (path) => {
|
|
24
25
|
if (path === liquidThemeTemplatePaths.index) return themeTemplateCategoryKeys.pages;
|
|
25
26
|
if (path === liquidThemeTemplatePaths.collection) return themeTemplateCategoryKeys.collections;
|
|
@@ -42,14 +43,23 @@ var isRecord = (value) => {
|
|
|
42
43
|
var emptyPreviewData = () => {
|
|
43
44
|
return { entities: {}, contentCollections: {} };
|
|
44
45
|
};
|
|
45
|
-
var
|
|
46
|
+
var hasLinkTargetReferences = (content) => {
|
|
47
|
+
try {
|
|
48
|
+
return collectThemeLinkTargetReferences(JSON.parse(content)).length > 0;
|
|
49
|
+
} catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
var buildPreviewRequest = (buffers, templatePath, path) => {
|
|
46
54
|
const reachable = getLiquidThemeReachableBuffers(buffers, templatePath);
|
|
47
55
|
const category = getLiquidThemeTemplateCategory(templatePath);
|
|
48
|
-
const page = category === themeTemplateCategoryKeys.collections || category === themeTemplateCategoryKeys.details ? { templatePath, category } : void 0;
|
|
56
|
+
const page = category === themeTemplateCategoryKeys.collections || category === themeTemplateCategoryKeys.details ? { templatePath, category, ...path ? { path } : {} } : void 0;
|
|
49
57
|
const entities = getLiquidThemeEntityQueries(reachable, templatePath).filter((query) => page || !requiresCurrentEntry(query));
|
|
50
58
|
const contentCollections = getLiquidThemeCollectionHandles(buffers, templatePath);
|
|
51
59
|
const sources = getLiquidThemeEntitySources(reachable, templatePath);
|
|
52
|
-
|
|
60
|
+
const templatePaths = Object.keys(buffers).filter((path2) => /^templates\/[^/]+\.json$/.test(path2));
|
|
61
|
+
const linkSources = Object.entries(buffers).filter(([path2, content]) => path2.endsWith(".json") && hasLinkTargetReferences(content)).map(([, content]) => content);
|
|
62
|
+
return { entities, contentCollections, sources, linkSources, templatePaths, page };
|
|
53
63
|
};
|
|
54
64
|
var normalizePreviewData = (raw) => {
|
|
55
65
|
const body = isRecord(raw) ? raw : {};
|
|
@@ -62,6 +72,7 @@ var normalizePreviewData = (raw) => {
|
|
|
62
72
|
return {
|
|
63
73
|
entities: isRecord(payload.entities) ? payload.entities : {},
|
|
64
74
|
contentCollections: isRecord(payload.contentCollections) ? payload.contentCollections : {},
|
|
75
|
+
linkTargets: isRecord(payload.linkTargets) ? payload.linkTargets : void 0,
|
|
65
76
|
page: isRecord(payload.page) ? payload.page : void 0,
|
|
66
77
|
collection: isRecord(payload.collection) ? payload.collection : void 0
|
|
67
78
|
};
|
|
@@ -88,17 +99,19 @@ var createFixturesDataSource = (themeDir) => {
|
|
|
88
99
|
};
|
|
89
100
|
};
|
|
90
101
|
var hasPreviewWork = (request) => {
|
|
91
|
-
return request.entities.length > 0 || request.contentCollections.length > 0 || Boolean(request.page);
|
|
102
|
+
return request.entities.length > 0 || request.contentCollections.length > 0 || request.linkSources.length > 0 || Boolean(request.page);
|
|
92
103
|
};
|
|
93
104
|
var cacheKeyOf = (request) => {
|
|
94
|
-
const keyInput = { entities: request.entities, contentCollections: request.contentCollections, page: request.page };
|
|
105
|
+
const keyInput = { entities: request.entities, contentCollections: request.contentCollections, linkSources: request.linkSources, templatePaths: request.templatePaths, page: request.page };
|
|
95
106
|
return sha256Hex(new TextEncoder().encode(JSON.stringify(keyInput)));
|
|
96
107
|
};
|
|
97
108
|
var createLiveDataSource = (options) => {
|
|
98
109
|
const cache = /* @__PURE__ */ new Map();
|
|
99
110
|
return {
|
|
100
|
-
|
|
101
|
-
|
|
111
|
+
resolveRoute: (path, templatePaths) => options.client.resolveRoute(options.themeId, path, templatePaths, options.countryCode),
|
|
112
|
+
listRoutes: () => options.client.listRoutes(options.themeId, options.countryCode),
|
|
113
|
+
load: async ({ buffers, templatePath, path }) => {
|
|
114
|
+
const request = buildPreviewRequest(buffers, templatePath, path);
|
|
102
115
|
if (!hasPreviewWork(request)) {
|
|
103
116
|
return emptyPreviewData();
|
|
104
117
|
}
|
|
@@ -125,4 +138,4 @@ export {
|
|
|
125
138
|
createFixturesDataSource,
|
|
126
139
|
createLiveDataSource
|
|
127
140
|
};
|
|
128
|
-
//# sourceMappingURL=chunk-
|
|
141
|
+
//# sourceMappingURL=chunk-OATE235V.js.map
|