@tomsher/cms-theme-kit 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -889,7 +889,7 @@ var runDev = async (argv) => {
889
889
  const metadata = await readThemeMetadata(dir);
890
890
  const mode = await resolveDevMode(stringOption(values, "mode"), dir, metadata);
891
891
  if (mode === "static") {
892
- const { startStaticDevServer } = await import("./static-server-BTUWXORJ.js");
892
+ const { startStaticDevServer } = await import("./static-server-WWP7CW4C.js");
893
893
  const server2 = await startStaticDevServer({ themeDir: dir, port });
894
894
  console.log(`Previewing static theme at ${server2.url}/`);
895
895
  console.log(`Pages: ${server2.url}/__templates`);
@@ -897,8 +897,8 @@ var runDev = async (argv) => {
897
897
  await serveUntilInterrupted(dir, server2);
898
898
  return;
899
899
  }
900
- const { createFixturesDataSource, createLiveDataSource } = await import("./data-source-CKDBOWKF.js");
901
- const { startDevServer } = await import("./server-SWGQTMET.js");
900
+ const { createFixturesDataSource, createLiveDataSource } = await import("./data-source-63RC4O5W.js");
901
+ const { startDevServer } = await import("./server-GITJIQTE.js");
902
902
  const dataMode = stringOption(values, "data") ?? "live";
903
903
  const templatePath = stringOption(values, "template") ?? defaultTemplate;
904
904
  const countryCode = stringOption(values, "country");
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ getLiquidThemeCollectionHandles,
4
+ getLiquidThemeEntityQueries,
5
+ getLiquidThemeEntitySources,
6
+ getLiquidThemeReachableBuffers,
7
+ requiresCurrentEntry
8
+ } from "./chunk-WSX3MAFK.js";
9
+ import {
10
+ CliError,
11
+ liquidThemeFolderNames,
12
+ liquidThemeTemplatePaths,
13
+ sha256Hex,
14
+ themeTemplateCategories,
15
+ themeTemplateCategoryKeys
16
+ } from "./chunk-TN3DQWJE.js";
17
+
18
+ // src/lib/dev/data-source.ts
19
+ import { readFile } from "fs/promises";
20
+ import { join } from "path";
21
+
22
+ // ../cms-theme-engines/dist/utils/index.js
23
+ var getLiquidThemeTemplateCategory = (path) => {
24
+ if (path === liquidThemeTemplatePaths.index) return themeTemplateCategoryKeys.pages;
25
+ if (path === liquidThemeTemplatePaths.collection) return themeTemplateCategoryKeys.collections;
26
+ if (path === liquidThemeTemplatePaths.entityDetails) return themeTemplateCategoryKeys.details;
27
+ if (path === liquidThemeTemplatePaths.notFound) return themeTemplateCategoryKeys.system;
28
+ for (const category of Object.keys(themeTemplateCategories)) {
29
+ const prefix = themeTemplateCategories[category].prefix;
30
+ if (!prefix) continue;
31
+ const categoryPrefix = `${liquidThemeFolderNames.templates}/${prefix}`;
32
+ const name = path.startsWith(categoryPrefix) ? path.slice(categoryPrefix.length) : "";
33
+ if (/^[a-z0-9][a-z0-9_-]*\.json$/.test(name)) return category;
34
+ }
35
+ return null;
36
+ };
37
+
38
+ // src/lib/dev/data-source.ts
39
+ var isRecord = (value) => {
40
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
41
+ };
42
+ var emptyPreviewData = () => {
43
+ return { entities: {}, contentCollections: {} };
44
+ };
45
+ var buildPreviewRequest = (buffers, templatePath) => {
46
+ const reachable = getLiquidThemeReachableBuffers(buffers, templatePath);
47
+ const category = getLiquidThemeTemplateCategory(templatePath);
48
+ const page = category === themeTemplateCategoryKeys.collections || category === themeTemplateCategoryKeys.details ? { templatePath, category } : void 0;
49
+ const entities = getLiquidThemeEntityQueries(reachable, templatePath).filter((query) => page || !requiresCurrentEntry(query));
50
+ const contentCollections = getLiquidThemeCollectionHandles(buffers, templatePath);
51
+ const sources = getLiquidThemeEntitySources(reachable, templatePath);
52
+ return { entities, contentCollections, sources, page };
53
+ };
54
+ var normalizePreviewData = (raw) => {
55
+ const body = isRecord(raw) ? raw : {};
56
+ let payload = body;
57
+ if (isRecord(body.requestedData)) {
58
+ payload = body.requestedData;
59
+ } else if (isRecord(body.data)) {
60
+ payload = body.data;
61
+ }
62
+ return {
63
+ entities: isRecord(payload.entities) ? payload.entities : {},
64
+ contentCollections: isRecord(payload.contentCollections) ? payload.contentCollections : {},
65
+ page: isRecord(payload.page) ? payload.page : void 0,
66
+ collection: isRecord(payload.collection) ? payload.collection : void 0
67
+ };
68
+ };
69
+ var createFixturesDataSource = (themeDir) => {
70
+ return {
71
+ load: async ({ templatePath }) => {
72
+ const fixturePath = join(themeDir, "fixtures", templatePath.replace(/\//g, "-"));
73
+ let raw;
74
+ try {
75
+ raw = await readFile(fixturePath, "utf8");
76
+ } catch (error) {
77
+ if (error.code === "ENOENT") {
78
+ return emptyPreviewData();
79
+ }
80
+ throw error;
81
+ }
82
+ try {
83
+ return normalizePreviewData(JSON.parse(raw));
84
+ } catch {
85
+ throw new CliError(`${fixturePath} is not valid JSON.`);
86
+ }
87
+ }
88
+ };
89
+ };
90
+ var hasPreviewWork = (request) => {
91
+ return request.entities.length > 0 || request.contentCollections.length > 0 || Boolean(request.page);
92
+ };
93
+ var cacheKeyOf = (request) => {
94
+ const keyInput = { entities: request.entities, contentCollections: request.contentCollections, page: request.page };
95
+ return sha256Hex(new TextEncoder().encode(JSON.stringify(keyInput)));
96
+ };
97
+ var createLiveDataSource = (options) => {
98
+ const cache = /* @__PURE__ */ new Map();
99
+ return {
100
+ load: async ({ buffers, templatePath }) => {
101
+ const request = buildPreviewRequest(buffers, templatePath);
102
+ if (!hasPreviewWork(request)) {
103
+ return emptyPreviewData();
104
+ }
105
+ const key = cacheKeyOf(request);
106
+ const cached = cache.get(key);
107
+ if (cached) {
108
+ return cached;
109
+ }
110
+ const pending = options.client.previewData(options.themeId, request, options.countryCode).then(normalizePreviewData);
111
+ cache.set(key, pending);
112
+ pending.catch(() => {
113
+ if (cache.get(key) === pending) {
114
+ cache.delete(key);
115
+ }
116
+ });
117
+ return pending;
118
+ }
119
+ };
120
+ };
121
+
122
+ export {
123
+ buildPreviewRequest,
124
+ normalizePreviewData,
125
+ createFixturesDataSource,
126
+ createLiveDataSource
127
+ };
128
+ //# sourceMappingURL=chunk-EUR46QER.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/dev/data-source.ts","../../cms-theme-engines/src/utils/analysis/liquid-theme-template.utils.ts","../../cms-theme-engines/src/utils/static-editor/static-html-editor.utils.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { getLiquidThemeCollectionHandles, getLiquidThemeEntityQueries, getLiquidThemeEntitySources, getLiquidThemeReachableBuffers, getLiquidThemeTemplateCategory, requiresCurrentEntry } from '@tomsher/cms-theme-engines/utils';\nimport { themeTemplateCategoryKeys } from '@tomsher/cms-core/constants';\nimport type { CmsClient, ThemePreviewRequest } from '../cms-client';\nimport { CliError } from '../errors';\nimport { sha256Hex } from '../hash';\n\nexport interface PreviewData {\n entities: Record<string, Record<string, unknown>>;\n contentCollections: Record<string, unknown>;\n page?: Record<string, unknown>;\n collection?: Record<string, unknown>;\n}\n\nexport interface DataSourceInput {\n templatePath: string;\n buffers: Record<string, string>;\n}\n\nexport interface DataSource {\n load: (input: DataSourceInput) => Promise<PreviewData>;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n};\n\nconst emptyPreviewData = (): PreviewData => {\n return { entities: {}, contentCollections: {} };\n};\n\n// Mirrors useThemeVisualBuilderEntities in the admin editor.\nexport const buildPreviewRequest = (buffers: Record<string, string>, templatePath: string): ThemePreviewRequest => {\n const reachable = getLiquidThemeReachableBuffers(buffers, templatePath);\n const category = getLiquidThemeTemplateCategory(templatePath);\n const page = category === themeTemplateCategoryKeys.collections || category === themeTemplateCategoryKeys.details ? { templatePath, category } : undefined;\n const entities = getLiquidThemeEntityQueries(reachable, templatePath).filter((query) => page || !requiresCurrentEntry(query));\n const contentCollections = getLiquidThemeCollectionHandles(buffers, templatePath);\n const sources = getLiquidThemeEntitySources(reachable, templatePath);\n\n return { entities, contentCollections, sources, page };\n};\n\n// The response is either the envelope { requestedData } or a bare payload; the editor reads requestedData.\nexport const normalizePreviewData = (raw: unknown): PreviewData => {\n const body = isRecord(raw) ? raw : {};\n let payload: Record<string, unknown> = body;\n\n if (isRecord(body.requestedData)) {\n payload = body.requestedData;\n } else if (isRecord(body.data)) {\n payload = body.data;\n }\n\n return {\n entities: isRecord(payload.entities) ? (payload.entities as PreviewData['entities']) : {},\n contentCollections: isRecord(payload.contentCollections) ? payload.contentCollections : {},\n page: isRecord(payload.page) ? payload.page : undefined,\n collection: isRecord(payload.collection) ? payload.collection : undefined,\n };\n};\n\nexport const createFixturesDataSource = (themeDir: string): DataSource => {\n return {\n load: async ({ templatePath }) => {\n const fixturePath = join(themeDir, 'fixtures', templatePath.replace(/\\//g, '-'));\n let raw: string;\n\n try {\n raw = await readFile(fixturePath, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return emptyPreviewData();\n }\n\n throw error;\n }\n\n try {\n return normalizePreviewData(JSON.parse(raw));\n } catch {\n throw new CliError(`${fixturePath} is not valid JSON.`);\n }\n },\n };\n};\n\nexport interface LiveDataSourceOptions {\n client: CmsClient;\n themeId: string;\n countryCode?: string;\n}\n\nconst hasPreviewWork = (request: ThemePreviewRequest): boolean => {\n return request.entities.length > 0 || request.contentCollections.length > 0 || Boolean(request.page);\n};\n\n// The key covers the query inputs only, so markup and CSS edits that keep the same queries reuse the cached data.\nconst cacheKeyOf = (request: ThemePreviewRequest): string => {\n const keyInput = { entities: request.entities, contentCollections: request.contentCollections, page: request.page };\n return sha256Hex(new TextEncoder().encode(JSON.stringify(keyInput)));\n};\n\n// Cached until the process restarts; a restart is also the only time theme metadata is read again.\nexport const createLiveDataSource = (options: LiveDataSourceOptions): DataSource => {\n const cache = new Map<string, Promise<PreviewData>>();\n\n return {\n load: async ({ buffers, templatePath }) => {\n const request = buildPreviewRequest(buffers, templatePath);\n\n if (!hasPreviewWork(request)) {\n return emptyPreviewData();\n }\n\n const key = cacheKeyOf(request);\n const cached = cache.get(key);\n\n if (cached) {\n return cached;\n }\n\n const pending = options.client\n .previewData(options.themeId, request, options.countryCode)\n .then(normalizePreviewData);\n\n cache.set(key, pending);\n pending.catch(() => {\n if (cache.get(key) === pending) {\n cache.delete(key);\n }\n });\n\n return pending;\n },\n };\n};\n","import { themeTemplateCategories, themeTemplateCategoryKeys, type ThemeTemplateCategory } from '@tomsher/cms-core/constants';\nimport { liquidThemeFolderNames, liquidThemeTemplatePaths } from '@tomsher/cms-core/constants';\n\nexport const getLiquidThemeTemplateCategory = (path: string): ThemeTemplateCategory | 'system' | null => {\n if (path === liquidThemeTemplatePaths.index) return themeTemplateCategoryKeys.pages;\n if (path === liquidThemeTemplatePaths.collection) return themeTemplateCategoryKeys.collections;\n if (path === liquidThemeTemplatePaths.entityDetails) return themeTemplateCategoryKeys.details;\n if (path === liquidThemeTemplatePaths.notFound) return themeTemplateCategoryKeys.system;\n\n for (const category of Object.keys(themeTemplateCategories) as (keyof typeof themeTemplateCategories)[]) {\n const prefix = themeTemplateCategories[category].prefix;\n if (!prefix) continue;\n const categoryPrefix = `${liquidThemeFolderNames.templates}/${prefix}`;\n const name = path.startsWith(categoryPrefix) ? path.slice(categoryPrefix.length) : '';\n if (/^[a-z0-9][a-z0-9_-]*\\.json$/.test(name)) return category;\n }\n return null;\n};\n\nexport const getLiquidThemeTemplateTitle = (path: string, category?: ThemeTemplateCategory): string => {\n if (path === liquidThemeTemplatePaths.index) return 'Home page';\n if (path === liquidThemeTemplatePaths.collection) return 'Collection';\n if (path === liquidThemeTemplatePaths.entityDetails) return 'Entity details';\n\n const templateCategory = category || getLiquidThemeTemplateCategory(path);\n const prefix = templateCategory && templateCategory !== themeTemplateCategoryKeys.system ? themeTemplateCategories[templateCategory].prefix : null;\n const templateName = path.replace(`${liquidThemeFolderNames.templates}/`, '').replace(/\\.json$/, '').replace(prefix || '', '');\n return templateName.replace(/[-_]/g, ' ').replace(/\\b\\w/g, (letter) => letter.toUpperCase());\n};\n\nexport const createLiquidThemeTemplatePath = (category: ThemeTemplateCategory, name: string): string =>\n `${liquidThemeFolderNames.templates}/${themeTemplateCategories[category].prefix}${name}.json`;\n","import { staticThemeFolderNames, staticThemeHtmlExtensionPattern } from '@tomsher/cms-core/constants';\n\nexport const getStaticHtmlPaths = (files: Array<{ path: string }>): string[] =>\n files\n .map((file) => file.path)\n .filter((path) => path.startsWith(`${staticThemeFolderNames.root}/`) && staticThemeHtmlExtensionPattern.test(path))\n .sort();\n\nexport const getStaticHtmlPageOptions = (paths: string[]) => paths.map((path) => ({ value: path, label: path }));\n\nexport const getStaticHtmlPageContent = (\n selectedPath: string,\n fileBuffers: Record<string, string | undefined>,\n files: Array<{ path: string; content?: string | null }>,\n): string => selectedPath ? fileBuffers[selectedPath] ?? files.find((file) => file.path === selectedPath)?.content ?? '' : '';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,YAAY;;;ACEd,IAAM,iCAAiC,CAAC,SAA0D;AACrG,MAAI,SAAS,yBAAyB,MAAO,QAAO,0BAA0B;AAC9E,MAAI,SAAS,yBAAyB,WAAY,QAAO,0BAA0B;AACnF,MAAI,SAAS,yBAAyB,cAAe,QAAO,0BAA0B;AACtF,MAAI,SAAS,yBAAyB,SAAU,QAAO,0BAA0B;AAEjF,aAAW,YAAY,OAAO,KAAK,uBAAuB,GAA+C;AACrG,UAAM,SAAS,wBAAwB,QAAQ,EAAE;AACjD,QAAI,CAAC,OAAQ;AACb,UAAM,iBAAiB,GAAG,uBAAuB,SAAS,IAAI,MAAM;AACpE,UAAM,OAAO,KAAK,WAAW,cAAc,IAAI,KAAK,MAAM,eAAe,MAAM,IAAI;AACnF,QAAI,8BAA8B,KAAK,IAAI,EAAG,QAAO;EACzD;AACA,SAAO;AACX;;;ADOA,IAAM,WAAW,CAAC,UAAqD;AACnE,SAAO,QAAQ,KAAK,KAAK,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC9E;AAEA,IAAM,mBAAmB,MAAmB;AACxC,SAAO,EA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
1
1
  #!/usr/bin/env node
2
2
  import {
3
- getThemeEntityQueryKey,
4
- getThemeLinkTargetReferenceKey,
5
- hasTranslatableFields,
6
- localizeStorefrontRoutes,
7
- localizeStorefrontUrl,
8
- setTranslatableArrayFieldPathValue
9
- } from "./chunk-6NVYKM2E.js";
10
- import {
11
- CliError,
12
3
  __commonJS,
13
4
  __toESM,
5
+ customFieldTypeConstants,
14
6
  entityKinds,
15
7
  liquidThemeConfigFilePaths,
16
8
  liquidThemeFolderNames,
17
9
  liquidThemeTemplatePaths,
18
10
  queryKeys,
19
- sha256Hex,
20
11
  themeAssetUrlPatterns,
21
12
  themeCustomizerLocaleNamespace,
22
13
  themeCustomizerLocalizedSettingTypes,
23
14
  themeFileExtensions,
24
- themeTemplateCategories,
25
- themeTemplateCategoryKeys
15
+ themeLinkTargetKinds
26
16
  } from "./chunk-TN3DQWJE.js";
27
17
 
28
18
  // ../node_modules/lodash/isArray.js
@@ -881,11 +871,7 @@ var require_get = __commonJS({
881
871
  }
882
872
  });
883
873
 
884
- // src/lib/dev/data-source.ts
885
- import { readFile } from "fs/promises";
886
- import { join } from "path";
887
-
888
- // ../liquid-engine/dist/chunk-C52D7ZTE.js
874
+ // ../cms-theme-engines/dist/chunk-C52D7ZTE.js
889
875
  var liquidAssetUrlPatterns = {
890
876
  themeAssetPrefix: /^assets\//i
891
877
  };
@@ -978,8 +964,209 @@ var customCssKey = "customCss";
978
964
  var themeEntityBindingSource = "entity";
979
965
  var themeEntityQueryTag = "entityQuery";
980
966
 
981
- // ../liquid-engine/dist/chunk-LKQOV7DG.js
967
+ // ../cms-theme-engines/dist/chunk-LKQOV7DG.js
982
968
  import sanitizeHtml from "sanitize-html";
969
+
970
+ // ../cms-core/dist/utils/index.js
971
+ var setTranslatableArrayFieldPathValue = (target, schemaFields, fieldPath, value, isTranslatable) => {
972
+ const path = fieldPath.split(".");
973
+ const rootField = schemaFields.find((field) => field.type === customFieldTypeConstants.array && String(field.id ?? field.key ?? field.name) === path[0]);
974
+ if (!rootField || path.length < 3 || path.length % 2 !== 1) return false;
975
+ let targetValue = target[rootField.id ?? rootField.key ?? rootField.name ?? ""];
976
+ let nestedFields = rootField.settings?.fields || rootField.fields || [];
977
+ for (let index = 1; index < path.length; index += 2) {
978
+ const arrayIndex = Number(path[index]);
979
+ const fieldId = path[index + 1];
980
+ const nestedField = nestedFields.find((field) => String(field.name ?? field.key ?? field.id) === fieldId);
981
+ if (!Number.isInteger(arrayIndex) || !nestedField || !Array.isArray(targetValue) || !targetValue[arrayIndex]) return false;
982
+ if (index === path.length - 2) {
983
+ if (!isTranslatable(nestedField)) return false;
984
+ targetValue[arrayIndex][fieldId] = value;
985
+ return true;
986
+ }
987
+ if (nestedField.type !== customFieldTypeConstants.array) return false;
988
+ targetValue = targetValue[arrayIndex][fieldId];
989
+ nestedFields = nestedField.settings?.fields || nestedField.fields || [];
990
+ }
991
+ return false;
992
+ };
993
+ var hasTranslatableFields = (schemaFields, componentsMap = {}, isFieldTranslatable = (field) => Boolean(field.settings?.isTranslatable)) => {
994
+ if (!Array.isArray(schemaFields)) return false;
995
+ return schemaFields.some((f) => {
996
+ if (isFieldTranslatable(f)) return true;
997
+ const nestedFields = f.settings?.fields || f.fields;
998
+ if (Array.isArray(nestedFields)) {
999
+ return hasTranslatableFields(nestedFields, componentsMap, isFieldTranslatable);
1000
+ }
1001
+ if (f.type === customFieldTypeConstants.component) {
1002
+ const nestedCompId = f.settings?.componentId || f.validations?.componentId;
1003
+ const nestedComp = componentsMap[nestedCompId];
1004
+ if (nestedComp?.schema) {
1005
+ return hasTranslatableFields(nestedComp.schema, componentsMap, isFieldTranslatable);
1006
+ }
1007
+ }
1008
+ return false;
1009
+ });
1010
+ };
1011
+ var buildStorefrontLocalePrefix = ({ countryCode, languageCode, includeCountry, includeLanguage }) => [
1012
+ ...includeCountry && countryCode ? [countryCode.toLowerCase()] : [],
1013
+ ...includeLanguage && languageCode ? [languageCode.toLowerCase()] : []
1014
+ ];
1015
+ var findStorefrontLanguage = (languages, languageCode) => {
1016
+ if (!languageCode) return void 0;
1017
+ const normalizedCode = languageCode.toLowerCase();
1018
+ return languages.find((language) => language.languageCode.toLowerCase() === normalizedCode);
1019
+ };
1020
+ var getStorefrontLocalePrefix = (localization) => {
1021
+ if (!localization) return [];
1022
+ return buildStorefrontLocalePrefix({
1023
+ countryCode: localization.country?.countryCode,
1024
+ languageCode: localization.language?.languageCode,
1025
+ includeCountry: localization.availableCountries.length > 1,
1026
+ includeLanguage: localization.availableLanguages.length > 1
1027
+ });
1028
+ };
1029
+ var localizeStorefrontUrl = (url, localization) => {
1030
+ const value = String(url || "/");
1031
+ if (/^(?:[a-z]+:)?\/\//i.test(value) || value.startsWith("mailto:") || value.startsWith("tel:") || value.startsWith("#") || value.startsWith("?")) return value;
1032
+ const prefix = getStorefrontLocalePrefix(localization);
1033
+ if (!prefix.length) return value;
1034
+ const match = value.match(/^([^?#]*)([?#].*)?$/);
1035
+ const path = match?.[1] || "/";
1036
+ const suffix = match?.[2] || "";
1037
+ const segments = path.split("/").filter(Boolean);
1038
+ const alreadyLocalized = prefix.every((segment, index) => segments[index]?.toLowerCase() === segment);
1039
+ if (alreadyLocalized) return value;
1040
+ const targetCountry = localization?.availableCountries.find((country) => country.countryCode.toLowerCase() === segments[0]?.toLowerCase());
1041
+ if (targetCountry) {
1042
+ const targetLanguages = targetCountry.languages || [];
1043
+ if (targetLanguages.length <= 1 || findStorefrontLanguage(targetLanguages, segments[1])) return value;
1044
+ } else if (localization?.availableCountries.length === 1 && findStorefrontLanguage(localization.availableLanguages, segments[0])) {
1045
+ return value;
1046
+ }
1047
+ return `/${[...prefix, ...segments].join("/")}${suffix}` || "/";
1048
+ };
1049
+ var localizeStorefrontRoutes = (routes, localization) => Object.fromEntries(Object.entries(routes).map(([key, value]) => [key, typeof value === "string" ? localizeStorefrontUrl(value, localization) : value]));
1050
+ var getThemeEntityQueryKey = (query) => `${query.type}:${query.handle}:${query.as || ""}`;
1051
+ var hasNonEmptyString = (value) => typeof value === "string" && value.trim().length > 0;
1052
+ var isSafeExternalThemeUrl = (value) => {
1053
+ if (typeof value !== "string") return false;
1054
+ try {
1055
+ const url = new URL(value);
1056
+ return url.protocol === "https:" && Boolean(url.hostname) && !url.username && !url.password;
1057
+ } catch {
1058
+ return false;
1059
+ }
1060
+ };
1061
+ var isThemeLinkTargetReference = (value) => {
1062
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1063
+ const reference = value;
1064
+ if (reference.kind === themeLinkTargetKinds.external) return isSafeExternalThemeUrl(reference.url);
1065
+ if (!hasNonEmptyString(reference.provider)) return false;
1066
+ if (!hasNonEmptyString(reference.entityId)) return false;
1067
+ if (reference.kind === themeLinkTargetKinds.single || reference.kind === themeLinkTargetKinds.listing) return true;
1068
+ return reference.kind === themeLinkTargetKinds.entry && hasNonEmptyString(reference.entryId);
1069
+ };
1070
+ var normalizeThemeLinkTargetReference = (value) => {
1071
+ if (!isThemeLinkTargetReference(value)) return null;
1072
+ if (value.kind === themeLinkTargetKinds.external) {
1073
+ return {
1074
+ kind: value.kind,
1075
+ url: value.url.trim()
1076
+ };
1077
+ }
1078
+ if (value.kind === themeLinkTargetKinds.entry) {
1079
+ return {
1080
+ kind: value.kind,
1081
+ provider: value.provider.trim(),
1082
+ entityId: value.entityId.trim(),
1083
+ entryId: value.entryId.trim()
1084
+ };
1085
+ }
1086
+ return {
1087
+ kind: value.kind,
1088
+ provider: value.provider.trim(),
1089
+ entityId: value.entityId.trim()
1090
+ };
1091
+ };
1092
+ var getThemeLinkTargetReferenceKey = (value) => {
1093
+ const reference = normalizeThemeLinkTargetReference(value);
1094
+ return reference ? JSON.stringify(reference) : null;
1095
+ };
1096
+ var safeDecodeAssetPath = (path) => {
1097
+ try {
1098
+ return decodeURIComponent(path);
1099
+ } catch {
1100
+ return path;
1101
+ }
1102
+ };
1103
+ var findThemeAssetUrl = (assetUrls, assetPath) => {
1104
+ const candidates = [.../* @__PURE__ */ new Set([assetPath, safeDecodeAssetPath(assetPath)])];
1105
+ for (const candidate of candidates) {
1106
+ if (assetUrls[candidate]) return assetUrls[candidate];
1107
+ }
1108
+ return void 0;
1109
+ };
1110
+ var findThemeAssetUrlBySuffix = (assetUrls, assetPath) => {
1111
+ const candidates = [.../* @__PURE__ */ new Set([assetPath, safeDecodeAssetPath(assetPath)])].map((candidate) => candidate.toLowerCase());
1112
+ return Object.entries(assetUrls).find(([path]) => {
1113
+ const lowerPath = path.toLowerCase();
1114
+ return candidates.some((candidate) => lowerPath.endsWith(`/${candidate}`));
1115
+ })?.[1];
1116
+ };
1117
+ var rewriteThemeCssAssetUrls = (content, assetUrls) => content.replace(/url\(\s*(['"]?)(?!data:|https?:|blob:|\/)([^'"\)]+)\1\s*\)/gi, (match, quote, assetPath) => {
1118
+ const normalizedPath = assetPath.trim().replace(/^\.\//, "");
1119
+ const assetUrl = findThemeAssetUrl(assetUrls, normalizedPath) || findThemeAssetUrlBySuffix(assetUrls, normalizedPath);
1120
+ return assetUrl ? `url(${quote}${assetUrl}${quote})` : match;
1121
+ });
1122
+ var rewriteThemeHtmlAssetUrls = (content, assetUrls) => content.replace(/\b(src|href|poster)=(['"])(\.\/)?assets\/([^'"]+)\2/gi, (match, attribute, quote, _relativePrefix, assetPath) => {
1123
+ const normalizedPath = assetPath.split(/[?#]/, 1)[0];
1124
+ const assetUrl = findThemeAssetUrl(assetUrls, normalizedPath);
1125
+ return assetUrl ? `${attribute}=${quote}${assetUrl}${assetPath.slice(normalizedPath.length)}${quote}` : match;
1126
+ });
1127
+ var isThemeMarkupFile = (filename) => filename.startsWith(`${liquidThemeFolderNames.layout}/`) || filename.startsWith(`${liquidThemeFolderNames.sections}/`) || filename.startsWith(`${liquidThemeFolderNames.snippets}/`);
1128
+ var rewriteLiquidThemeAssetBuffers = (buffers, assetUrls) => {
1129
+ const rewrittenBuffers = { ...buffers };
1130
+ for (const [filename, content] of Object.entries(buffers)) {
1131
+ if (!content) continue;
1132
+ if (filename.endsWith(".css")) rewrittenBuffers[filename] = rewriteThemeCssAssetUrls(content, assetUrls);
1133
+ if (isThemeMarkupFile(filename)) rewrittenBuffers[filename] = rewriteThemeHtmlAssetUrls(content, assetUrls);
1134
+ }
1135
+ return rewrittenBuffers;
1136
+ };
1137
+ var unsafeAssetPathCharacterPattern = /%(?![0-9a-f]{2})|[^a-z0-9._~:/@!$*+,;=%-]/giu;
1138
+ var encodeAssetPathCharacters = (path) => path.replace(unsafeAssetPathCharacterPattern, (character) => encodeURIComponent(character));
1139
+ var encodeThemeAssetUrl = (url) => {
1140
+ if (/^(?:data|blob):/i.test(url)) return url;
1141
+ const suffixStart = url.search(/[?#]/);
1142
+ if (suffixStart === -1) return encodeAssetPathCharacters(url);
1143
+ return `${encodeAssetPathCharacters(url.slice(0, suffixStart))}${url.slice(suffixStart).replace(/ /g, "%20")}`;
1144
+ };
1145
+ var getThemeAssetUrls = (files, rootDirectory, resolveMediaUrl) => Object.fromEntries(files.flatMap((file) => {
1146
+ const filename = file.path || file.filename;
1147
+ if (!filename || !file.fileUrl || !filename.startsWith(`${rootDirectory}/`)) return [];
1148
+ const paths = [filename, filename.slice(rootDirectory.length + 1)];
1149
+ const url = encodeThemeAssetUrl(resolveMediaUrl(file.fileUrl));
1150
+ return paths.map((path) => [path, url]);
1151
+ }));
1152
+ var decodeHtmlAttribute = (value) => value.replace(/&quot;/g, '"').replace(/&#0*39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
1153
+ var extractThemeStylesheets = (html) => {
1154
+ const stylesheets = /* @__PURE__ */ new Set();
1155
+ const content = html.replace(/<link\b[^>]*\brel=(['"])stylesheet\1[^>]*>/gi, (link) => {
1156
+ const href = link.match(/\bhref=(['"])(.*?)\1/i)?.[2];
1157
+ if (href) stylesheets.add(decodeHtmlAttribute(href));
1158
+ return "";
1159
+ });
1160
+ return { html: content, stylesheets: [...stylesheets] };
1161
+ };
1162
+ var renderThemeHtmlWithStylesheets = ({ html, stylesheets }) => {
1163
+ if (!stylesheets.length) return html;
1164
+ const links = stylesheets.map((href) => `<link rel="stylesheet" href="${href.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}">`).join("");
1165
+ return /<head\b[^>]*>/i.test(html) ? html.replace(/<head\b[^>]*>/i, (head) => `${head}${links}`) : `${links}${html}`;
1166
+ };
1167
+ var ensureThemeStylesheetsBeforeContent = (html) => renderThemeHtmlWithStylesheets(extractThemeStylesheets(html));
1168
+
1169
+ // ../cms-theme-engines/dist/chunk-LKQOV7DG.js
983
1170
  var import_get = __toESM(require_get(), 1);
984
1171
  var import_get2 = __toESM(require_get(), 1);
985
1172
  var formatImageUrl = (url) => {
@@ -1597,106 +1784,6 @@ var applyThemeCustomizerLocaleOverrides = (fileBuffers, languageCode, defaultLan
1597
1784
  return result;
1598
1785
  };
1599
1786
 
1600
- // ../liquid-engine/dist/utils/index.js
1601
- var getLiquidThemeTemplateCategory = (path) => {
1602
- if (path === liquidThemeTemplatePaths.index) return themeTemplateCategoryKeys.pages;
1603
- if (path === liquidThemeTemplatePaths.collection) return themeTemplateCategoryKeys.collections;
1604
- if (path === liquidThemeTemplatePaths.entityDetails) return themeTemplateCategoryKeys.details;
1605
- if (path === liquidThemeTemplatePaths.notFound) return themeTemplateCategoryKeys.system;
1606
- for (const category of Object.keys(themeTemplateCategories)) {
1607
- const prefix = themeTemplateCategories[category].prefix;
1608
- if (!prefix) continue;
1609
- const categoryPrefix = `${liquidThemeFolderNames.templates}/${prefix}`;
1610
- const name = path.startsWith(categoryPrefix) ? path.slice(categoryPrefix.length) : "";
1611
- if (/^[a-z0-9][a-z0-9_-]*\.json$/.test(name)) return category;
1612
- }
1613
- return null;
1614
- };
1615
-
1616
- // src/lib/dev/data-source.ts
1617
- var isRecord = (value) => {
1618
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1619
- };
1620
- var emptyPreviewData = () => {
1621
- return { entities: {}, contentCollections: {} };
1622
- };
1623
- var buildPreviewRequest = (buffers, templatePath) => {
1624
- const reachable = getLiquidThemeReachableBuffers(buffers, templatePath);
1625
- const category = getLiquidThemeTemplateCategory(templatePath);
1626
- const page = category === themeTemplateCategoryKeys.collections || category === themeTemplateCategoryKeys.details ? { templatePath, category } : void 0;
1627
- const entities = getLiquidThemeEntityQueries(reachable, templatePath).filter((query) => page || !requiresCurrentEntry(query));
1628
- const contentCollections = getLiquidThemeCollectionHandles(buffers, templatePath);
1629
- const sources = getLiquidThemeEntitySources(reachable, templatePath);
1630
- return { entities, contentCollections, sources, page };
1631
- };
1632
- var normalizePreviewData = (raw) => {
1633
- const body = isRecord(raw) ? raw : {};
1634
- let payload = body;
1635
- if (isRecord(body.requestedData)) {
1636
- payload = body.requestedData;
1637
- } else if (isRecord(body.data)) {
1638
- payload = body.data;
1639
- }
1640
- return {
1641
- entities: isRecord(payload.entities) ? payload.entities : {},
1642
- contentCollections: isRecord(payload.contentCollections) ? payload.contentCollections : {},
1643
- page: isRecord(payload.page) ? payload.page : void 0,
1644
- collection: isRecord(payload.collection) ? payload.collection : void 0
1645
- };
1646
- };
1647
- var createFixturesDataSource = (themeDir) => {
1648
- return {
1649
- load: async ({ templatePath }) => {
1650
- const fixturePath = join(themeDir, "fixtures", templatePath.replace(/\//g, "-"));
1651
- let raw;
1652
- try {
1653
- raw = await readFile(fixturePath, "utf8");
1654
- } catch (error) {
1655
- if (error.code === "ENOENT") {
1656
- return emptyPreviewData();
1657
- }
1658
- throw error;
1659
- }
1660
- try {
1661
- return normalizePreviewData(JSON.parse(raw));
1662
- } catch {
1663
- throw new CliError(`${fixturePath} is not valid JSON.`);
1664
- }
1665
- }
1666
- };
1667
- };
1668
- var hasPreviewWork = (request) => {
1669
- return request.entities.length > 0 || request.contentCollections.length > 0 || Boolean(request.page);
1670
- };
1671
- var cacheKeyOf = (request) => {
1672
- const keyInput = { entities: request.entities, contentCollections: request.contentCollections, page: request.page };
1673
- return sha256Hex(new TextEncoder().encode(JSON.stringify(keyInput)));
1674
- };
1675
- var createLiveDataSource = (options) => {
1676
- const cache = /* @__PURE__ */ new Map();
1677
- return {
1678
- load: async ({ buffers, templatePath }) => {
1679
- const request = buildPreviewRequest(buffers, templatePath);
1680
- if (!hasPreviewWork(request)) {
1681
- return emptyPreviewData();
1682
- }
1683
- const key = cacheKeyOf(request);
1684
- const cached = cache.get(key);
1685
- if (cached) {
1686
- return cached;
1687
- }
1688
- const pending = options.client.previewData(options.themeId, request, options.countryCode).then(normalizePreviewData);
1689
- cache.set(key, pending);
1690
- pending.catch(() => {
1691
- if (cache.get(key) === pending) {
1692
- cache.delete(key);
1693
- }
1694
- });
1695
- return pending;
1696
- }
1697
- };
1698
- };
1699
-
1700
1787
  export {
1701
1788
  maxRenderMs,
1702
1789
  maxOutputBytes,
@@ -1710,6 +1797,11 @@ export {
1710
1797
  defaultLayout,
1711
1798
  isSafePartialName,
1712
1799
  customCssKey,
1800
+ localizeStorefrontUrl,
1801
+ rewriteLiquidThemeAssetBuffers,
1802
+ getThemeAssetUrls,
1803
+ extractThemeStylesheets,
1804
+ ensureThemeStylesheetsBeforeContent,
1713
1805
  require_get,
1714
1806
  resolveThemeMediaUrl,
1715
1807
  normalizeLiquidAssetValue,
@@ -1740,10 +1832,11 @@ export {
1740
1832
  buildBlockList,
1741
1833
  buildCustomCssBlock,
1742
1834
  templateErrorHtml,
1743
- applyThemeCustomizerLocaleOverrides,
1744
- buildPreviewRequest,
1745
- normalizePreviewData,
1746
- createFixturesDataSource,
1747
- createLiveDataSource
1835
+ getLiquidThemeEntitySources,
1836
+ getLiquidThemeReachableBuffers,
1837
+ requiresCurrentEntry,
1838
+ getLiquidThemeEntityQueries,
1839
+ getLiquidThemeCollectionHandles,
1840
+ applyThemeCustomizerLocaleOverrides
1748
1841
  };
1749
- //# sourceMappingURL=chunk-ND62XRUU.js.map
1842
+ //# sourceMappingURL=chunk-WSX3MAFK.js.map