shop-client 3.8.2
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/LICENSE +21 -0
- package/README.md +912 -0
- package/dist/checkout.d.mts +31 -0
- package/dist/checkout.d.ts +31 -0
- package/dist/checkout.js +115 -0
- package/dist/checkout.js.map +1 -0
- package/dist/checkout.mjs +7 -0
- package/dist/checkout.mjs.map +1 -0
- package/dist/chunk-2KBOKOAD.mjs +177 -0
- package/dist/chunk-2KBOKOAD.mjs.map +1 -0
- package/dist/chunk-BWKBRM2Z.mjs +136 -0
- package/dist/chunk-BWKBRM2Z.mjs.map +1 -0
- package/dist/chunk-O4BPIIQ6.mjs +503 -0
- package/dist/chunk-O4BPIIQ6.mjs.map +1 -0
- package/dist/chunk-QCTICSBE.mjs +398 -0
- package/dist/chunk-QCTICSBE.mjs.map +1 -0
- package/dist/chunk-QL5OUZGP.mjs +91 -0
- package/dist/chunk-QL5OUZGP.mjs.map +1 -0
- package/dist/chunk-WTK5HUFI.mjs +1287 -0
- package/dist/chunk-WTK5HUFI.mjs.map +1 -0
- package/dist/collections.d.mts +64 -0
- package/dist/collections.d.ts +64 -0
- package/dist/collections.js +540 -0
- package/dist/collections.js.map +1 -0
- package/dist/collections.mjs +9 -0
- package/dist/collections.mjs.map +1 -0
- package/dist/index.d.mts +233 -0
- package/dist/index.d.ts +233 -0
- package/dist/index.js +3241 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +702 -0
- package/dist/index.mjs.map +1 -0
- package/dist/products.d.mts +63 -0
- package/dist/products.d.ts +63 -0
- package/dist/products.js +1206 -0
- package/dist/products.js.map +1 -0
- package/dist/products.mjs +9 -0
- package/dist/products.mjs.map +1 -0
- package/dist/store-CJVUz2Yb.d.mts +608 -0
- package/dist/store-CJVUz2Yb.d.ts +608 -0
- package/dist/store.d.mts +1 -0
- package/dist/store.d.ts +1 -0
- package/dist/store.js +698 -0
- package/dist/store.js.map +1 -0
- package/dist/store.mjs +9 -0
- package/dist/store.mjs.map +1 -0
- package/dist/utils/rate-limit.d.mts +25 -0
- package/dist/utils/rate-limit.d.ts +25 -0
- package/dist/utils/rate-limit.js +203 -0
- package/dist/utils/rate-limit.js.map +1 -0
- package/dist/utils/rate-limit.mjs +11 -0
- package/dist/utils/rate-limit.mjs.map +1 -0
- package/package.json +116 -0
|
@@ -0,0 +1,1287 @@
|
|
|
1
|
+
import {
|
|
2
|
+
formatPrice
|
|
3
|
+
} from "./chunk-BWKBRM2Z.mjs";
|
|
4
|
+
import {
|
|
5
|
+
rateLimitedFetch
|
|
6
|
+
} from "./chunk-2KBOKOAD.mjs";
|
|
7
|
+
|
|
8
|
+
// src/products.ts
|
|
9
|
+
import { filter, isNonNullish } from "remeda";
|
|
10
|
+
|
|
11
|
+
// src/ai/enrich.ts
|
|
12
|
+
import TurndownService from "turndown";
|
|
13
|
+
import { gfm } from "turndown-plugin-gfm";
|
|
14
|
+
function ensureOpenRouter(apiKey) {
|
|
15
|
+
const key = apiKey || process.env.OPENROUTER_API_KEY;
|
|
16
|
+
if (!key) {
|
|
17
|
+
throw new Error(
|
|
18
|
+
"Missing OpenRouter API key. Set OPENROUTER_API_KEY or pass apiKey."
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
return key;
|
|
22
|
+
}
|
|
23
|
+
function normalizeDomainToBase(domain) {
|
|
24
|
+
if (domain.startsWith("http://") || domain.startsWith("https://")) {
|
|
25
|
+
try {
|
|
26
|
+
const u = new URL(domain);
|
|
27
|
+
return `${u.protocol}//${u.hostname}`;
|
|
28
|
+
} catch {
|
|
29
|
+
return domain;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return `https://${domain}`;
|
|
33
|
+
}
|
|
34
|
+
async function fetchAjaxProduct(domain, handle) {
|
|
35
|
+
const base = normalizeDomainToBase(domain);
|
|
36
|
+
const url = `${base}/products/${handle}.js`;
|
|
37
|
+
const res = await rateLimitedFetch(url);
|
|
38
|
+
if (!res.ok) throw new Error(`Failed to fetch AJAX product: ${url}`);
|
|
39
|
+
const data = await res.json();
|
|
40
|
+
return data;
|
|
41
|
+
}
|
|
42
|
+
async function fetchProductPage(domain, handle) {
|
|
43
|
+
const base = normalizeDomainToBase(domain);
|
|
44
|
+
const url = `${base}/products/${handle}`;
|
|
45
|
+
const res = await rateLimitedFetch(url);
|
|
46
|
+
if (!res.ok) throw new Error(`Failed to fetch product page: ${url}`);
|
|
47
|
+
return res.text();
|
|
48
|
+
}
|
|
49
|
+
function extractMainSection(html) {
|
|
50
|
+
const startMatch = html.match(
|
|
51
|
+
/<section[^>]*id="shopify-section-template--.*?__main"[^>]*>/
|
|
52
|
+
);
|
|
53
|
+
if (!startMatch) return null;
|
|
54
|
+
const startIndex = html.indexOf(startMatch[0]);
|
|
55
|
+
if (startIndex === -1) return null;
|
|
56
|
+
const endIndex = html.indexOf("</section>", startIndex);
|
|
57
|
+
if (endIndex === -1) return null;
|
|
58
|
+
return html.substring(startIndex, endIndex + "</section>".length);
|
|
59
|
+
}
|
|
60
|
+
function htmlToMarkdown(html, options) {
|
|
61
|
+
var _a;
|
|
62
|
+
if (!html) return "";
|
|
63
|
+
const td = new TurndownService({
|
|
64
|
+
headingStyle: "atx",
|
|
65
|
+
codeBlockStyle: "fenced",
|
|
66
|
+
bulletListMarker: "-",
|
|
67
|
+
emDelimiter: "*",
|
|
68
|
+
strongDelimiter: "**",
|
|
69
|
+
linkStyle: "inlined"
|
|
70
|
+
});
|
|
71
|
+
const useGfm = (_a = options == null ? void 0 : options.useGfm) != null ? _a : true;
|
|
72
|
+
if (useGfm) {
|
|
73
|
+
td.use(gfm);
|
|
74
|
+
}
|
|
75
|
+
["script", "style", "nav", "footer"].forEach((tag) => {
|
|
76
|
+
td.remove((node) => {
|
|
77
|
+
var _a2;
|
|
78
|
+
return ((_a2 = node.nodeName) == null ? void 0 : _a2.toLowerCase()) === tag;
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
const removeByClass = (className) => td.remove((node) => {
|
|
82
|
+
const cls = typeof node.getAttribute === "function" ? node.getAttribute("class") || "" : "";
|
|
83
|
+
return cls.split(/\s+/).includes(className);
|
|
84
|
+
});
|
|
85
|
+
[
|
|
86
|
+
"product-form",
|
|
87
|
+
"shopify-payment-button",
|
|
88
|
+
"shopify-payment-buttons",
|
|
89
|
+
"product__actions",
|
|
90
|
+
"product__media-wrapper",
|
|
91
|
+
"loox-rating",
|
|
92
|
+
"jdgm-widget",
|
|
93
|
+
"stamped-reviews"
|
|
94
|
+
].forEach(removeByClass);
|
|
95
|
+
["button", "input", "select", "label"].forEach((tag) => {
|
|
96
|
+
td.remove((node) => {
|
|
97
|
+
var _a2;
|
|
98
|
+
return ((_a2 = node.nodeName) == null ? void 0 : _a2.toLowerCase()) === tag;
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
["quantity-selector", "product-atc-wrapper"].forEach(removeByClass);
|
|
102
|
+
return td.turndown(html);
|
|
103
|
+
}
|
|
104
|
+
async function mergeWithLLM(bodyInput, pageInput, options) {
|
|
105
|
+
var _a, _b;
|
|
106
|
+
const inputType = (_a = options == null ? void 0 : options.inputType) != null ? _a : "markdown";
|
|
107
|
+
const bodyLabel = inputType === "html" ? "BODY HTML" : "BODY MARKDOWN";
|
|
108
|
+
const pageLabel = inputType === "html" ? "PAGE HTML" : "PAGE MARKDOWN";
|
|
109
|
+
const prompt = (options == null ? void 0 : options.outputFormat) === "json" ? `You are extracting structured buyer-useful information from Shopify product content.
|
|
110
|
+
|
|
111
|
+
Inputs:
|
|
112
|
+
1) ${bodyLabel}: ${inputType === "html" ? "Raw Shopify product body_html" : "Cleaned version of Shopify product body_html"}
|
|
113
|
+
2) ${pageLabel}: ${inputType === "html" ? "Raw product page HTML (main section)" : "Extracted product page HTML converted to markdown"}
|
|
114
|
+
|
|
115
|
+
Return ONLY valid JSON (no markdown, no code fences) with this shape:
|
|
116
|
+
{
|
|
117
|
+
"title": null | string,
|
|
118
|
+
"description": null | string,
|
|
119
|
+
"materials": string[] | [],
|
|
120
|
+
"care": string[] | [],
|
|
121
|
+
"fit": null | string,
|
|
122
|
+
"images": null | string[],
|
|
123
|
+
"returnPolicy": null | string
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
Rules:
|
|
127
|
+
- Do not invent facts; if a field is unavailable, use null or []
|
|
128
|
+
- Prefer concise, factual statements
|
|
129
|
+
- Do NOT include product gallery/hero images in "images"; include only documentation images like size charts or measurement guides. If none, set "images": null.
|
|
130
|
+
|
|
131
|
+
${bodyLabel}:
|
|
132
|
+
${bodyInput}
|
|
133
|
+
|
|
134
|
+
${pageLabel}:
|
|
135
|
+
${pageInput}
|
|
136
|
+
` : `
|
|
137
|
+
You are enriching a Shopify product for a modern shopping-discovery app.
|
|
138
|
+
|
|
139
|
+
Inputs:
|
|
140
|
+
1) ${bodyLabel}: ${inputType === "html" ? "Raw Shopify product body_html" : "Cleaned version of Shopify product body_html"}
|
|
141
|
+
2) ${pageLabel}: ${inputType === "html" ? "Raw product page HTML (main section)" : "Extracted product page HTML converted to markdown"}
|
|
142
|
+
|
|
143
|
+
Your tasks:
|
|
144
|
+
- Merge them into a single clean markdown document
|
|
145
|
+
- Remove duplicate content
|
|
146
|
+
- Remove product images
|
|
147
|
+
- Remove UI text, buttons, menus, review widgets, theme junk
|
|
148
|
+
- Remove product options
|
|
149
|
+
- Keep only available buyer-useful info: features, materials, care, fit, size chart, return policy, size chart, care instructions
|
|
150
|
+
- Include image of size-chart if present
|
|
151
|
+
- Don't include statements like information not available.
|
|
152
|
+
- Maintain structured headings (## Description, ## Materials, etc.)
|
|
153
|
+
- Output ONLY markdown (no commentary)
|
|
154
|
+
|
|
155
|
+
${bodyLabel}:
|
|
156
|
+
${bodyInput}
|
|
157
|
+
|
|
158
|
+
${pageLabel}:
|
|
159
|
+
${pageInput}
|
|
160
|
+
`;
|
|
161
|
+
const apiKey = ensureOpenRouter(options == null ? void 0 : options.apiKey);
|
|
162
|
+
const defaultModel = process.env.OPENROUTER_MODEL || "openai/gpt-4o-mini";
|
|
163
|
+
const model = (_b = options == null ? void 0 : options.model) != null ? _b : defaultModel;
|
|
164
|
+
const result = await callOpenRouter(model, prompt, apiKey);
|
|
165
|
+
if ((options == null ? void 0 : options.outputFormat) === "json") {
|
|
166
|
+
const cleaned = result.replace(/```json|```/g, "").trim();
|
|
167
|
+
const obj = safeParseJson(cleaned);
|
|
168
|
+
if (!obj.ok) {
|
|
169
|
+
throw new Error(`LLM returned invalid JSON: ${obj.error}`);
|
|
170
|
+
}
|
|
171
|
+
const schema = validateStructuredJson(obj.value);
|
|
172
|
+
if (!schema.ok) {
|
|
173
|
+
throw new Error(`LLM JSON schema invalid: ${schema.error}`);
|
|
174
|
+
}
|
|
175
|
+
const value = obj.value;
|
|
176
|
+
if (Array.isArray(value.images)) {
|
|
177
|
+
const filtered = value.images.filter((url) => {
|
|
178
|
+
if (typeof url !== "string") return false;
|
|
179
|
+
const u = url.toLowerCase();
|
|
180
|
+
const productPatterns = [
|
|
181
|
+
"cdn.shopify.com",
|
|
182
|
+
"/products/",
|
|
183
|
+
"%2Fproducts%2F",
|
|
184
|
+
"_large",
|
|
185
|
+
"_grande",
|
|
186
|
+
"_1024x1024",
|
|
187
|
+
"_2048x"
|
|
188
|
+
];
|
|
189
|
+
const looksLikeProductImage = productPatterns.some(
|
|
190
|
+
(p) => u.includes(p)
|
|
191
|
+
);
|
|
192
|
+
return !looksLikeProductImage;
|
|
193
|
+
});
|
|
194
|
+
value.images = filtered.length > 0 ? filtered : null;
|
|
195
|
+
}
|
|
196
|
+
return JSON.stringify(value);
|
|
197
|
+
}
|
|
198
|
+
return result;
|
|
199
|
+
}
|
|
200
|
+
function safeParseJson(input) {
|
|
201
|
+
try {
|
|
202
|
+
const v = JSON.parse(input);
|
|
203
|
+
return { ok: true, value: v };
|
|
204
|
+
} catch (err) {
|
|
205
|
+
return { ok: false, error: (err == null ? void 0 : err.message) || "Failed to parse JSON" };
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function validateStructuredJson(obj) {
|
|
209
|
+
if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
|
|
210
|
+
return { ok: false, error: "Top-level must be a JSON object" };
|
|
211
|
+
}
|
|
212
|
+
const o = obj;
|
|
213
|
+
if ("title" in o && !(o.title === null || typeof o.title === "string")) {
|
|
214
|
+
return { ok: false, error: "title must be null or string" };
|
|
215
|
+
}
|
|
216
|
+
if ("description" in o && !(o.description === null || typeof o.description === "string")) {
|
|
217
|
+
return { ok: false, error: "description must be null or string" };
|
|
218
|
+
}
|
|
219
|
+
if ("fit" in o && !(o.fit === null || typeof o.fit === "string")) {
|
|
220
|
+
return { ok: false, error: "fit must be null or string" };
|
|
221
|
+
}
|
|
222
|
+
if ("returnPolicy" in o && !(o.returnPolicy === null || typeof o.returnPolicy === "string")) {
|
|
223
|
+
return { ok: false, error: "returnPolicy must be null or string" };
|
|
224
|
+
}
|
|
225
|
+
const validateStringArray = (arr, field) => {
|
|
226
|
+
if (!Array.isArray(arr))
|
|
227
|
+
return { ok: false, error: `${field} must be an array` };
|
|
228
|
+
for (const item of arr) {
|
|
229
|
+
if (typeof item !== "string")
|
|
230
|
+
return { ok: false, error: `${field} items must be strings` };
|
|
231
|
+
}
|
|
232
|
+
return { ok: true };
|
|
233
|
+
};
|
|
234
|
+
if ("materials" in o) {
|
|
235
|
+
const res = validateStringArray(o.materials, "materials");
|
|
236
|
+
if (!res.ok) return res;
|
|
237
|
+
}
|
|
238
|
+
if ("care" in o) {
|
|
239
|
+
const res = validateStringArray(o.care, "care");
|
|
240
|
+
if (!res.ok) return res;
|
|
241
|
+
}
|
|
242
|
+
if ("images" in o) {
|
|
243
|
+
if (!(o.images === null || Array.isArray(o.images))) {
|
|
244
|
+
return { ok: false, error: "images must be null or an array" };
|
|
245
|
+
}
|
|
246
|
+
if (Array.isArray(o.images)) {
|
|
247
|
+
const res = validateStringArray(o.images, "images");
|
|
248
|
+
if (!res.ok) return res;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return { ok: true };
|
|
252
|
+
}
|
|
253
|
+
async function callOpenRouter(model, prompt, apiKey) {
|
|
254
|
+
var _a, _b, _c;
|
|
255
|
+
if (process.env.OPENROUTER_OFFLINE === "1") {
|
|
256
|
+
return mockOpenRouterResponse(prompt);
|
|
257
|
+
}
|
|
258
|
+
const headers = {
|
|
259
|
+
"Content-Type": "application/json",
|
|
260
|
+
Authorization: `Bearer ${apiKey}`
|
|
261
|
+
};
|
|
262
|
+
const referer = process.env.OPENROUTER_SITE_URL || process.env.SITE_URL;
|
|
263
|
+
const title = process.env.OPENROUTER_APP_TITLE || "Shop Search";
|
|
264
|
+
if (referer) headers["HTTP-Referer"] = referer;
|
|
265
|
+
if (title) headers["X-Title"] = title;
|
|
266
|
+
const buildPayload = (m) => ({
|
|
267
|
+
model: m,
|
|
268
|
+
messages: [{ role: "user", content: prompt }],
|
|
269
|
+
temperature: 0.2
|
|
270
|
+
});
|
|
271
|
+
const base = (process.env.OPENROUTER_BASE_URL || "https://openrouter.ai/api/v1").replace(/\/$/, "");
|
|
272
|
+
const endpoints = [`${base}/chat/completions`];
|
|
273
|
+
const fallbackEnv = (process.env.OPENROUTER_FALLBACK_MODELS || "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
274
|
+
const defaultModel = process.env.OPENROUTER_MODEL || "openai/gpt-4o-mini";
|
|
275
|
+
const modelsToTry = Array.from(
|
|
276
|
+
/* @__PURE__ */ new Set([model, ...fallbackEnv, defaultModel])
|
|
277
|
+
).filter(Boolean);
|
|
278
|
+
let lastErrorText = "";
|
|
279
|
+
for (const m of modelsToTry) {
|
|
280
|
+
for (const url of endpoints) {
|
|
281
|
+
try {
|
|
282
|
+
const controller = new AbortController();
|
|
283
|
+
const timeout = setTimeout(() => controller.abort(), 15e3);
|
|
284
|
+
const response = await rateLimitedFetch(url, {
|
|
285
|
+
method: "POST",
|
|
286
|
+
headers,
|
|
287
|
+
body: JSON.stringify(buildPayload(m)),
|
|
288
|
+
signal: controller.signal
|
|
289
|
+
});
|
|
290
|
+
clearTimeout(timeout);
|
|
291
|
+
if (!response.ok) {
|
|
292
|
+
const text = await response.text();
|
|
293
|
+
lastErrorText = text || `${url}: HTTP ${response.status}`;
|
|
294
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
const data = await response.json();
|
|
298
|
+
const content = (_c = (_b = (_a = data == null ? void 0 : data.choices) == null ? void 0 : _a[0]) == null ? void 0 : _b.message) == null ? void 0 : _c.content;
|
|
299
|
+
if (typeof content === "string") return content;
|
|
300
|
+
lastErrorText = JSON.stringify(data);
|
|
301
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
302
|
+
} catch (err) {
|
|
303
|
+
lastErrorText = `${url}: ${(err == null ? void 0 : err.message) || String(err)}`;
|
|
304
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
throw new Error(`OpenRouter request failed: ${lastErrorText}`);
|
|
309
|
+
}
|
|
310
|
+
function mockOpenRouterResponse(prompt) {
|
|
311
|
+
const p = prompt.toLowerCase();
|
|
312
|
+
if (p.includes("return only valid json") && p.includes('"audience":')) {
|
|
313
|
+
return JSON.stringify({
|
|
314
|
+
audience: "generic",
|
|
315
|
+
vertical: "clothing",
|
|
316
|
+
category: null,
|
|
317
|
+
subCategory: null
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
if (p.includes("return only valid json") && p.includes('"materials":')) {
|
|
321
|
+
return JSON.stringify({
|
|
322
|
+
title: null,
|
|
323
|
+
description: null,
|
|
324
|
+
materials: [],
|
|
325
|
+
care: [],
|
|
326
|
+
fit: null,
|
|
327
|
+
images: null,
|
|
328
|
+
returnPolicy: null
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
return [
|
|
332
|
+
"## Description",
|
|
333
|
+
"Offline merge of product body and page.",
|
|
334
|
+
"",
|
|
335
|
+
"## Materials",
|
|
336
|
+
"- Not available"
|
|
337
|
+
].join("\n");
|
|
338
|
+
}
|
|
339
|
+
async function enrichProduct(domain, handle, options) {
|
|
340
|
+
var _a;
|
|
341
|
+
const ajaxProduct = await fetchAjaxProduct(domain, handle);
|
|
342
|
+
const bodyHtml = ajaxProduct.description || "";
|
|
343
|
+
const pageHtml = await fetchProductPage(domain, handle);
|
|
344
|
+
const extractedHtml = extractMainSection(pageHtml);
|
|
345
|
+
const inputType = (_a = options == null ? void 0 : options.inputType) != null ? _a : "markdown";
|
|
346
|
+
const bodyInput = inputType === "html" ? bodyHtml : htmlToMarkdown(bodyHtml, { useGfm: options == null ? void 0 : options.useGfm });
|
|
347
|
+
const pageInput = inputType === "html" ? extractedHtml || pageHtml : htmlToMarkdown(extractedHtml, { useGfm: options == null ? void 0 : options.useGfm });
|
|
348
|
+
const mergedMarkdown = await mergeWithLLM(bodyInput, pageInput, {
|
|
349
|
+
apiKey: options == null ? void 0 : options.apiKey,
|
|
350
|
+
inputType,
|
|
351
|
+
model: options == null ? void 0 : options.model,
|
|
352
|
+
outputFormat: options == null ? void 0 : options.outputFormat
|
|
353
|
+
});
|
|
354
|
+
if ((options == null ? void 0 : options.outputFormat) === "json") {
|
|
355
|
+
try {
|
|
356
|
+
const obj = JSON.parse(mergedMarkdown);
|
|
357
|
+
if (obj && Array.isArray(obj.images)) {
|
|
358
|
+
const productImageCandidates = [];
|
|
359
|
+
if (ajaxProduct.featured_image) {
|
|
360
|
+
productImageCandidates.push(String(ajaxProduct.featured_image));
|
|
361
|
+
}
|
|
362
|
+
if (Array.isArray(ajaxProduct.images)) {
|
|
363
|
+
for (const img of ajaxProduct.images) {
|
|
364
|
+
if (typeof img === "string" && img.length > 0) {
|
|
365
|
+
productImageCandidates.push(img);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
if (Array.isArray(ajaxProduct.media)) {
|
|
370
|
+
for (const m of ajaxProduct.media) {
|
|
371
|
+
if (m == null ? void 0 : m.src) productImageCandidates.push(String(m.src));
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
if (Array.isArray(ajaxProduct.variants)) {
|
|
375
|
+
for (const v of ajaxProduct.variants) {
|
|
376
|
+
const fi = v == null ? void 0 : v.featured_image;
|
|
377
|
+
if (fi == null ? void 0 : fi.src) productImageCandidates.push(String(fi.src));
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
const productSet = new Set(
|
|
381
|
+
productImageCandidates.map((u) => String(u).toLowerCase())
|
|
382
|
+
);
|
|
383
|
+
const filtered = obj.images.filter((url) => {
|
|
384
|
+
if (typeof url !== "string") return false;
|
|
385
|
+
const u = url.toLowerCase();
|
|
386
|
+
if (productSet.has(u)) return false;
|
|
387
|
+
const productPatterns = [
|
|
388
|
+
"cdn.shopify.com",
|
|
389
|
+
"/products/",
|
|
390
|
+
"%2Fproducts%2F",
|
|
391
|
+
"_large",
|
|
392
|
+
"_grande",
|
|
393
|
+
"_1024x1024",
|
|
394
|
+
"_2048x"
|
|
395
|
+
];
|
|
396
|
+
const looksLikeProductImage = productPatterns.some(
|
|
397
|
+
(p) => u.includes(p)
|
|
398
|
+
);
|
|
399
|
+
return !looksLikeProductImage;
|
|
400
|
+
});
|
|
401
|
+
obj.images = filtered.length > 0 ? filtered : null;
|
|
402
|
+
const sanitized = JSON.stringify(obj);
|
|
403
|
+
return {
|
|
404
|
+
bodyHtml,
|
|
405
|
+
pageHtml,
|
|
406
|
+
extractedMainHtml: extractedHtml || "",
|
|
407
|
+
mergedMarkdown: sanitized
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
} catch {
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
return {
|
|
414
|
+
bodyHtml,
|
|
415
|
+
pageHtml,
|
|
416
|
+
extractedMainHtml: extractedHtml || "",
|
|
417
|
+
mergedMarkdown
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
async function classifyProduct(productContent, options) {
|
|
421
|
+
var _a;
|
|
422
|
+
const apiKey = ensureOpenRouter(options == null ? void 0 : options.apiKey);
|
|
423
|
+
const defaultModel = process.env.OPENROUTER_MODEL || "openai/gpt-4o-mini";
|
|
424
|
+
const model = (_a = options == null ? void 0 : options.model) != null ? _a : defaultModel;
|
|
425
|
+
const prompt = `Classify the following product using a three-tiered hierarchy:
|
|
426
|
+
|
|
427
|
+
Product Content:
|
|
428
|
+
${productContent}
|
|
429
|
+
|
|
430
|
+
Classification Rules:
|
|
431
|
+
1. First determine the vertical (main product category)
|
|
432
|
+
2. Then determine the category (specific type within that vertical)
|
|
433
|
+
3. Finally determine the subCategory (sub-type within that category)
|
|
434
|
+
|
|
435
|
+
Vertical must be one of: clothing, beauty, accessories, home-decor, food-and-beverages
|
|
436
|
+
Audience must be one of: adult_male, adult_female, kid_male, kid_female, generic
|
|
437
|
+
|
|
438
|
+
Hierarchy Examples:
|
|
439
|
+
- Clothing \u2192 tops \u2192 t-shirts
|
|
440
|
+
- Clothing \u2192 footwear \u2192 sneakers
|
|
441
|
+
- Beauty \u2192 skincare \u2192 moisturizers
|
|
442
|
+
- Accessories \u2192 bags \u2192 backpacks
|
|
443
|
+
- Home-decor \u2192 furniture \u2192 chairs
|
|
444
|
+
- Food-and-beverages \u2192 snacks \u2192 chips
|
|
445
|
+
|
|
446
|
+
IMPORTANT CONSTRAINTS:
|
|
447
|
+
- Category must be relevant to the chosen vertical
|
|
448
|
+
- subCategory must be relevant to both vertical and category
|
|
449
|
+
- subCategory must be a single word or hyphenated words (no spaces)
|
|
450
|
+
- subCategory should NOT be material (e.g., "cotton", "leather") or color (e.g., "red", "blue")
|
|
451
|
+
- Focus on product type/function, not attributes
|
|
452
|
+
|
|
453
|
+
If you're not confident about category or sub-category, you can leave them optional.
|
|
454
|
+
|
|
455
|
+
Return ONLY valid JSON (no markdown, no code fences) with keys:
|
|
456
|
+
{
|
|
457
|
+
"audience": "adult_male" | "adult_female" | "kid_male" | "kid_female" | "generic",
|
|
458
|
+
"vertical": "clothing" | "beauty" | "accessories" | "home-decor" | "food-and-beverages",
|
|
459
|
+
"category": null | string,
|
|
460
|
+
"subCategory": null | string
|
|
461
|
+
}`;
|
|
462
|
+
const raw = await callOpenRouter(model, prompt, apiKey);
|
|
463
|
+
const cleaned = raw.replace(/```json|```/g, "").trim();
|
|
464
|
+
const parsed = safeParseJson(cleaned);
|
|
465
|
+
if (!parsed.ok) {
|
|
466
|
+
throw new Error(`LLM returned invalid JSON: ${parsed.error}`);
|
|
467
|
+
}
|
|
468
|
+
const validated = validateClassification(parsed.value);
|
|
469
|
+
if (!validated.ok) {
|
|
470
|
+
throw new Error(`LLM JSON schema invalid: ${validated.error}`);
|
|
471
|
+
}
|
|
472
|
+
return validated.value;
|
|
473
|
+
}
|
|
474
|
+
function validateClassification(obj) {
|
|
475
|
+
var _a, _b;
|
|
476
|
+
if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
|
|
477
|
+
return { ok: false, error: "Top-level must be a JSON object" };
|
|
478
|
+
}
|
|
479
|
+
const o = obj;
|
|
480
|
+
const audienceValues = [
|
|
481
|
+
"adult_male",
|
|
482
|
+
"adult_female",
|
|
483
|
+
"kid_male",
|
|
484
|
+
"kid_female",
|
|
485
|
+
"generic"
|
|
486
|
+
];
|
|
487
|
+
if (typeof o.audience !== "string" || !audienceValues.includes(o.audience)) {
|
|
488
|
+
return {
|
|
489
|
+
ok: false,
|
|
490
|
+
error: "audience must be one of: adult_male, adult_female, kid_male, kid_female, generic"
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
const verticalValues = [
|
|
494
|
+
"clothing",
|
|
495
|
+
"beauty",
|
|
496
|
+
"accessories",
|
|
497
|
+
"home-decor",
|
|
498
|
+
"food-and-beverages"
|
|
499
|
+
];
|
|
500
|
+
if (typeof o.vertical !== "string" || !verticalValues.includes(o.vertical)) {
|
|
501
|
+
return {
|
|
502
|
+
ok: false,
|
|
503
|
+
error: "vertical must be one of: clothing, beauty, accessories, home-decor, food-and-beverages"
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
if ("category" in o && !(o.category === null || typeof o.category === "string")) {
|
|
507
|
+
return { ok: false, error: "category must be null or string" };
|
|
508
|
+
}
|
|
509
|
+
if ("subCategory" in o && !(o.subCategory === null || typeof o.subCategory === "string")) {
|
|
510
|
+
return { ok: false, error: "subCategory must be null or string" };
|
|
511
|
+
}
|
|
512
|
+
if (typeof o.subCategory === "string") {
|
|
513
|
+
const sc = o.subCategory.trim();
|
|
514
|
+
if (!/^[A-Za-z0-9-]+$/.test(sc)) {
|
|
515
|
+
return {
|
|
516
|
+
ok: false,
|
|
517
|
+
error: "subCategory must be single word or hyphenated, no spaces"
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
return {
|
|
522
|
+
ok: true,
|
|
523
|
+
value: {
|
|
524
|
+
audience: o.audience,
|
|
525
|
+
vertical: o.vertical,
|
|
526
|
+
category: typeof o.category === "string" ? o.category : (_a = o.category) != null ? _a : null,
|
|
527
|
+
subCategory: typeof o.subCategory === "string" ? o.subCategory : (_b = o.subCategory) != null ? _b : null
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
async function generateSEOContent(product, options) {
|
|
532
|
+
var _a;
|
|
533
|
+
const apiKey = ensureOpenRouter(options == null ? void 0 : options.apiKey);
|
|
534
|
+
const defaultModel = process.env.OPENROUTER_MODEL || "openai/gpt-4o-mini";
|
|
535
|
+
const model = (_a = options == null ? void 0 : options.model) != null ? _a : defaultModel;
|
|
536
|
+
if (process.env.OPENROUTER_OFFLINE === "1") {
|
|
537
|
+
const baseTags = Array.isArray(product.tags) ? product.tags.slice(0, 6) : [];
|
|
538
|
+
const titlePart = product.title.trim().slice(0, 50);
|
|
539
|
+
const vendorPart = (product.vendor || "").trim();
|
|
540
|
+
const pricePart = typeof product.price === "number" ? `$${product.price}` : "";
|
|
541
|
+
const metaTitle = vendorPart ? `${titlePart} | ${vendorPart}` : titlePart;
|
|
542
|
+
const metaDescription = `Discover ${product.title}. ${pricePart ? `Priced at ${pricePart}. ` : ""}Crafted to delight customers with quality and style.`.slice(
|
|
543
|
+
0,
|
|
544
|
+
160
|
|
545
|
+
);
|
|
546
|
+
const shortDescription = `${product.title} \u2014 ${vendorPart || "Premium"} quality, designed to impress.`;
|
|
547
|
+
const longDescription = product.description || `Introducing ${product.title}, combining performance and style for everyday use.`;
|
|
548
|
+
const marketingCopy = `Get ${product.title} today${pricePart ? ` for ${pricePart}` : ""}. Limited availability \u2014 don\u2019t miss out!`;
|
|
549
|
+
const res = {
|
|
550
|
+
metaTitle,
|
|
551
|
+
metaDescription,
|
|
552
|
+
shortDescription,
|
|
553
|
+
longDescription,
|
|
554
|
+
tags: baseTags.length ? baseTags : ["new", "featured", "popular"],
|
|
555
|
+
marketingCopy
|
|
556
|
+
};
|
|
557
|
+
const validated2 = validateSEOContent(res);
|
|
558
|
+
if (!validated2.ok)
|
|
559
|
+
throw new Error(`Offline SEO content invalid: ${validated2.error}`);
|
|
560
|
+
return validated2.value;
|
|
561
|
+
}
|
|
562
|
+
const prompt = `Generate SEO-optimized content for this product:
|
|
563
|
+
|
|
564
|
+
Title: ${product.title}
|
|
565
|
+
Description: ${product.description || "N/A"}
|
|
566
|
+
Vendor: ${product.vendor || "N/A"}
|
|
567
|
+
Price: ${typeof product.price === "number" ? `$${product.price}` : "N/A"}
|
|
568
|
+
Tags: ${Array.isArray(product.tags) && product.tags.length ? product.tags.join(", ") : "N/A"}
|
|
569
|
+
|
|
570
|
+
Create compelling, SEO-friendly content that will help this product rank well and convert customers.
|
|
571
|
+
|
|
572
|
+
Return ONLY valid JSON (no markdown, no code fences) with keys: {
|
|
573
|
+
"metaTitle": string,
|
|
574
|
+
"metaDescription": string,
|
|
575
|
+
"shortDescription": string,
|
|
576
|
+
"longDescription": string,
|
|
577
|
+
"tags": string[],
|
|
578
|
+
"marketingCopy": string
|
|
579
|
+
}`;
|
|
580
|
+
const raw = await callOpenRouter(model, prompt, apiKey);
|
|
581
|
+
const cleaned = raw.replace(/```json|```/g, "").trim();
|
|
582
|
+
const parsed = safeParseJson(cleaned);
|
|
583
|
+
if (!parsed.ok) {
|
|
584
|
+
throw new Error(`LLM returned invalid JSON: ${parsed.error}`);
|
|
585
|
+
}
|
|
586
|
+
const validated = validateSEOContent(parsed.value);
|
|
587
|
+
if (!validated.ok) {
|
|
588
|
+
throw new Error(`LLM JSON schema invalid: ${validated.error}`);
|
|
589
|
+
}
|
|
590
|
+
return validated.value;
|
|
591
|
+
}
|
|
592
|
+
function validateSEOContent(obj) {
|
|
593
|
+
if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
|
|
594
|
+
return { ok: false, error: "Top-level must be a JSON object" };
|
|
595
|
+
}
|
|
596
|
+
const o = obj;
|
|
597
|
+
const requiredStrings = [
|
|
598
|
+
"metaTitle",
|
|
599
|
+
"metaDescription",
|
|
600
|
+
"shortDescription",
|
|
601
|
+
"longDescription",
|
|
602
|
+
"marketingCopy"
|
|
603
|
+
];
|
|
604
|
+
for (const key of requiredStrings) {
|
|
605
|
+
if (typeof o[key] !== "string" || !o[key].trim()) {
|
|
606
|
+
return { ok: false, error: `${key} must be a non-empty string` };
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
if (!Array.isArray(o.tags)) {
|
|
610
|
+
return { ok: false, error: "tags must be an array" };
|
|
611
|
+
}
|
|
612
|
+
for (const t of o.tags) {
|
|
613
|
+
if (typeof t !== "string")
|
|
614
|
+
return { ok: false, error: "tags items must be strings" };
|
|
615
|
+
}
|
|
616
|
+
return {
|
|
617
|
+
ok: true,
|
|
618
|
+
value: {
|
|
619
|
+
metaTitle: String(o.metaTitle),
|
|
620
|
+
metaDescription: String(o.metaDescription),
|
|
621
|
+
shortDescription: String(o.shortDescription),
|
|
622
|
+
longDescription: String(o.longDescription),
|
|
623
|
+
tags: o.tags,
|
|
624
|
+
marketingCopy: String(o.marketingCopy)
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
async function determineStoreType(storeInfo, options) {
|
|
629
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
|
|
630
|
+
const apiKey = ensureOpenRouter(options == null ? void 0 : options.apiKey);
|
|
631
|
+
const defaultModel = process.env.OPENROUTER_MODEL || "openai/gpt-4o-mini";
|
|
632
|
+
const model = (_a = options == null ? void 0 : options.model) != null ? _a : defaultModel;
|
|
633
|
+
const productLines = Array.isArray(storeInfo.showcase.products) ? storeInfo.showcase.products.slice(0, 10).map((p) => {
|
|
634
|
+
if (typeof p === "string") return `- ${p}`;
|
|
635
|
+
const pt = typeof (p == null ? void 0 : p.productType) === "string" && p.productType.trim() ? p.productType : "N/A";
|
|
636
|
+
return `- ${String((p == null ? void 0 : p.title) || "N/A")}: ${pt}`;
|
|
637
|
+
}) : [];
|
|
638
|
+
const collectionLines = Array.isArray(storeInfo.showcase.collections) ? storeInfo.showcase.collections.slice(0, 5).map((c) => {
|
|
639
|
+
if (typeof c === "string") return `- ${c}`;
|
|
640
|
+
return `- ${String((c == null ? void 0 : c.title) || "N/A")}`;
|
|
641
|
+
}) : [];
|
|
642
|
+
const storeContent = `Store Title: ${storeInfo.title}
|
|
643
|
+
Store Description: ${(_b = storeInfo.description) != null ? _b : "N/A"}
|
|
644
|
+
|
|
645
|
+
Sample Products:
|
|
646
|
+
${productLines.join("\n") || "- N/A"}
|
|
647
|
+
|
|
648
|
+
Sample Collections:
|
|
649
|
+
${collectionLines.join("\n") || "- N/A"}`;
|
|
650
|
+
const textNormalized = `${storeInfo.title} ${(_c = storeInfo.description) != null ? _c : ""} ${productLines.join(" ")} ${collectionLines.join(" ")}`.toLowerCase();
|
|
651
|
+
if (process.env.OPENROUTER_OFFLINE === "1") {
|
|
652
|
+
const text = `${storeInfo.title} ${(_d = storeInfo.description) != null ? _d : ""} ${productLines.join(" ")} ${collectionLines.join(" ")}`.toLowerCase();
|
|
653
|
+
const verticalKeywords = {
|
|
654
|
+
clothing: /(dress|shirt|pant|jean|hoodie|tee|t[- ]?shirt|sneaker|apparel|clothing)/,
|
|
655
|
+
beauty: /(skincare|moisturizer|serum|beauty|cosmetic|makeup)/,
|
|
656
|
+
accessories: /(bag|belt|watch|wallet|accessor(y|ies)|sunglasses|jewell?ery)/,
|
|
657
|
+
"home-decor": /(sofa|chair|table|decor|home|candle|lamp|rug)/,
|
|
658
|
+
"food-and-beverages": /(snack|food|beverage|coffee|tea|chocolate|gourmet)/
|
|
659
|
+
};
|
|
660
|
+
const audienceKeywords = {
|
|
661
|
+
kid: /(\bkid\b|\bchild\b|\bchildren\b|\btoddler\b|\bboy\b|\bgirl\b)/,
|
|
662
|
+
kid_male: /\bboys\b|\bboy\b/,
|
|
663
|
+
kid_female: /\bgirls\b|\bgirl\b/,
|
|
664
|
+
adult_male: /\bmen\b|\bmale\b|\bman\b|\bmens\b/,
|
|
665
|
+
adult_female: /\bwomen\b|\bfemale\b|\bwoman\b|\bwomens\b/
|
|
666
|
+
};
|
|
667
|
+
const audiences = [];
|
|
668
|
+
if ((_e = audienceKeywords.kid) == null ? void 0 : _e.test(text)) {
|
|
669
|
+
if ((_f = audienceKeywords.kid_male) == null ? void 0 : _f.test(text)) audiences.push("kid_male");
|
|
670
|
+
if ((_g = audienceKeywords.kid_female) == null ? void 0 : _g.test(text)) audiences.push("kid_female");
|
|
671
|
+
if (!((_h = audienceKeywords.kid_male) == null ? void 0 : _h.test(text)) && !((_i = audienceKeywords.kid_female) == null ? void 0 : _i.test(text)))
|
|
672
|
+
audiences.push("generic");
|
|
673
|
+
} else {
|
|
674
|
+
if ((_j = audienceKeywords.adult_male) == null ? void 0 : _j.test(text)) audiences.push("adult_male");
|
|
675
|
+
if ((_k = audienceKeywords.adult_female) == null ? void 0 : _k.test(text))
|
|
676
|
+
audiences.push("adult_female");
|
|
677
|
+
if (audiences.length === 0) audiences.push("generic");
|
|
678
|
+
}
|
|
679
|
+
const verticals = Object.entries(verticalKeywords).filter(([, rx]) => rx.test(text)).map(([k]) => k);
|
|
680
|
+
if (verticals.length === 0) verticals.push("accessories");
|
|
681
|
+
const allTitles = productLines.join(" ").toLowerCase();
|
|
682
|
+
const categoryMap = {
|
|
683
|
+
shirts: /(shirt|t[- ]?shirt|tee)/,
|
|
684
|
+
pants: /(pant|trouser|chino)/,
|
|
685
|
+
shorts: /shorts?/,
|
|
686
|
+
jeans: /jeans?/,
|
|
687
|
+
dresses: /dress/,
|
|
688
|
+
skincare: /(serum|moisturizer|skincare|cream)/,
|
|
689
|
+
accessories: /(belt|watch|wallet|bag)/,
|
|
690
|
+
footwear: /(sneaker|shoe|boot)/,
|
|
691
|
+
decor: /(candle|lamp|rug|sofa|chair|table)/,
|
|
692
|
+
beverages: /(coffee|tea|chocolate)/
|
|
693
|
+
};
|
|
694
|
+
const categories = Object.entries(categoryMap).filter(([, rx]) => rx.test(allTitles)).map(([name]) => name);
|
|
695
|
+
const defaultCategories = categories.length ? categories : ["general"];
|
|
696
|
+
const breakdown = {};
|
|
697
|
+
for (const aud of audiences) {
|
|
698
|
+
breakdown[aud] = breakdown[aud] || {};
|
|
699
|
+
for (const v of verticals) {
|
|
700
|
+
breakdown[aud][v] = Array.from(new Set(defaultCategories));
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
return pruneBreakdownForSignals(breakdown, textNormalized);
|
|
704
|
+
}
|
|
705
|
+
const prompt = `Analyze this store and build a multi-audience breakdown of verticals and categories.
|
|
706
|
+
Store Information:
|
|
707
|
+
${storeContent}
|
|
708
|
+
|
|
709
|
+
Return ONLY valid JSON (no markdown, no code fences) using this shape:
|
|
710
|
+
{
|
|
711
|
+
"adult_male": { "clothing": ["shirts", "pants"], "accessories": ["belts"] },
|
|
712
|
+
"adult_female": { "beauty": ["skincare"], "clothing": ["dresses"] },
|
|
713
|
+
"generic": { "clothing": ["t-shirts"] }
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
Rules:
|
|
717
|
+
- Keys MUST be audience: "adult_male" | "adult_female" | "kid_male" | "kid_female" | "generic".
|
|
718
|
+
- Nested keys MUST be vertical: "clothing" | "beauty" | "accessories" | "home-decor" | "food-and-beverages".
|
|
719
|
+
- Values MUST be non-empty arrays of category strings.
|
|
720
|
+
`;
|
|
721
|
+
const raw = await callOpenRouter(model, prompt, apiKey);
|
|
722
|
+
const cleaned = raw.replace(/```json|```/g, "").trim();
|
|
723
|
+
const parsed = safeParseJson(cleaned);
|
|
724
|
+
if (!parsed.ok) {
|
|
725
|
+
throw new Error(`LLM returned invalid JSON: ${parsed.error}`);
|
|
726
|
+
}
|
|
727
|
+
const validated = validateStoreTypeBreakdown(parsed.value);
|
|
728
|
+
if (!validated.ok) {
|
|
729
|
+
throw new Error(`LLM JSON schema invalid: ${validated.error}`);
|
|
730
|
+
}
|
|
731
|
+
return pruneBreakdownForSignals(validated.value, textNormalized);
|
|
732
|
+
}
|
|
733
|
+
function validateStoreTypeBreakdown(obj) {
|
|
734
|
+
if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
|
|
735
|
+
return {
|
|
736
|
+
ok: false,
|
|
737
|
+
error: "Top-level must be an object keyed by audience"
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
const audienceKeys = [
|
|
741
|
+
"adult_male",
|
|
742
|
+
"adult_female",
|
|
743
|
+
"kid_male",
|
|
744
|
+
"kid_female",
|
|
745
|
+
"generic"
|
|
746
|
+
];
|
|
747
|
+
const verticalKeys = [
|
|
748
|
+
"clothing",
|
|
749
|
+
"beauty",
|
|
750
|
+
"accessories",
|
|
751
|
+
"home-decor",
|
|
752
|
+
"food-and-beverages"
|
|
753
|
+
];
|
|
754
|
+
const o = obj;
|
|
755
|
+
const out = {};
|
|
756
|
+
const keys = Object.keys(o);
|
|
757
|
+
if (keys.length === 0) {
|
|
758
|
+
return { ok: false, error: "At least one audience key is required" };
|
|
759
|
+
}
|
|
760
|
+
for (const aKey of keys) {
|
|
761
|
+
if (!audienceKeys.includes(aKey)) {
|
|
762
|
+
return { ok: false, error: `Invalid audience key: ${aKey}` };
|
|
763
|
+
}
|
|
764
|
+
const vObj = o[aKey];
|
|
765
|
+
if (!vObj || typeof vObj !== "object" || Array.isArray(vObj)) {
|
|
766
|
+
return {
|
|
767
|
+
ok: false,
|
|
768
|
+
error: `Audience ${aKey} must map to an object of verticals`
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
const vOut = {};
|
|
772
|
+
for (const vKey of Object.keys(vObj)) {
|
|
773
|
+
if (!verticalKeys.includes(vKey)) {
|
|
774
|
+
return {
|
|
775
|
+
ok: false,
|
|
776
|
+
error: `Invalid vertical key ${vKey} for audience ${aKey}`
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
const cats = vObj[vKey];
|
|
780
|
+
if (!Array.isArray(cats) || cats.length === 0 || !cats.every((c) => typeof c === "string" && c.trim())) {
|
|
781
|
+
return {
|
|
782
|
+
ok: false,
|
|
783
|
+
error: `Vertical ${vKey} for audience ${aKey} must be a non-empty array of strings`
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
vOut[vKey] = cats.map(
|
|
787
|
+
(c) => c.trim()
|
|
788
|
+
);
|
|
789
|
+
}
|
|
790
|
+
out[aKey] = vOut;
|
|
791
|
+
}
|
|
792
|
+
return { ok: true, value: out };
|
|
793
|
+
}
|
|
794
|
+
function pruneBreakdownForSignals(breakdown, text) {
|
|
795
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
796
|
+
const audienceKeywords = {
|
|
797
|
+
kid: /(\bkid\b|\bchild\b|\bchildren\b|\btoddler\b|\bboy\b|\bgirl\b)/,
|
|
798
|
+
kid_male: /\bboys\b|\bboy\b/,
|
|
799
|
+
kid_female: /\bgirls\b|\bgirl\b/,
|
|
800
|
+
adult_male: /\bmen\b|\bmale\b|\bman\b|\bmens\b/,
|
|
801
|
+
adult_female: /\bwomen\b|\bfemale\b|\bwoman\b|\bwomens\b/
|
|
802
|
+
};
|
|
803
|
+
const verticalKeywords = {
|
|
804
|
+
clothing: /(dress|shirt|pant|jean|hoodie|tee|t[- ]?shirt|sneaker|apparel|clothing)/,
|
|
805
|
+
beauty: /(skincare|moisturizer|serum|beauty|cosmetic|makeup)/,
|
|
806
|
+
accessories: /(bag|belt|watch|wallet|accessor(y|ies)|sunglasses|jewell?ery)/,
|
|
807
|
+
// Tighten home-decor detection to avoid matching generic "Home" nav labels
|
|
808
|
+
// and other unrelated uses. Require specific furniture/decor terms or phrases.
|
|
809
|
+
"home-decor": /(sofa|chair|table|candle|lamp|rug|furniture|home[- ]?decor|homeware|housewares|living\s?room|dining\s?table|bed(?:room)?|wall\s?(art|mirror|clock))/,
|
|
810
|
+
"food-and-beverages": /(snack|food|beverage|coffee|tea|chocolate|gourmet)/
|
|
811
|
+
};
|
|
812
|
+
const signaledAudiences = /* @__PURE__ */ new Set();
|
|
813
|
+
if ((_a = audienceKeywords.kid) == null ? void 0 : _a.test(text)) {
|
|
814
|
+
if ((_b = audienceKeywords.kid_male) == null ? void 0 : _b.test(text))
|
|
815
|
+
signaledAudiences.add("kid_male");
|
|
816
|
+
if ((_c = audienceKeywords.kid_female) == null ? void 0 : _c.test(text))
|
|
817
|
+
signaledAudiences.add("kid_female");
|
|
818
|
+
if (!((_d = audienceKeywords.kid_male) == null ? void 0 : _d.test(text)) && !((_e = audienceKeywords.kid_female) == null ? void 0 : _e.test(text)))
|
|
819
|
+
signaledAudiences.add("generic");
|
|
820
|
+
} else {
|
|
821
|
+
if ((_f = audienceKeywords.adult_male) == null ? void 0 : _f.test(text))
|
|
822
|
+
signaledAudiences.add("adult_male");
|
|
823
|
+
if ((_g = audienceKeywords.adult_female) == null ? void 0 : _g.test(text))
|
|
824
|
+
signaledAudiences.add("adult_female");
|
|
825
|
+
if (signaledAudiences.size === 0) signaledAudiences.add("generic");
|
|
826
|
+
}
|
|
827
|
+
const signaledVerticals = new Set(
|
|
828
|
+
Object.entries(verticalKeywords).filter(([, rx]) => rx.test(text)).map(([k]) => k) || []
|
|
829
|
+
);
|
|
830
|
+
if (signaledVerticals.size === 0) signaledVerticals.add("accessories");
|
|
831
|
+
const pruned = {};
|
|
832
|
+
for (const [audience, verticals] of Object.entries(breakdown)) {
|
|
833
|
+
const a = audience;
|
|
834
|
+
if (!signaledAudiences.has(a)) continue;
|
|
835
|
+
const vOut = {};
|
|
836
|
+
for (const [vertical, categories] of Object.entries(verticals || {})) {
|
|
837
|
+
const v = vertical;
|
|
838
|
+
if (!signaledVerticals.has(v)) continue;
|
|
839
|
+
vOut[v] = categories;
|
|
840
|
+
}
|
|
841
|
+
if (Object.keys(vOut).length > 0) {
|
|
842
|
+
pruned[a] = vOut;
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
if (Object.keys(pruned).length === 0) {
|
|
846
|
+
const vOut = {};
|
|
847
|
+
for (const v of Array.from(signaledVerticals)) {
|
|
848
|
+
vOut[v] = ["general"];
|
|
849
|
+
}
|
|
850
|
+
pruned.generic = vOut;
|
|
851
|
+
}
|
|
852
|
+
const adultHasData = pruned.adult_male && Object.keys(pruned.adult_male).length > 0 || pruned.adult_female && Object.keys(pruned.adult_female).length > 0;
|
|
853
|
+
if (adultHasData) {
|
|
854
|
+
delete pruned.generic;
|
|
855
|
+
}
|
|
856
|
+
return pruned;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// src/products.ts
|
|
860
|
+
function createProductOperations(baseUrl, storeDomain, fetchProducts, productsDto, productDto, getStoreInfo, findProduct) {
|
|
861
|
+
function applyCurrencyOverride(product, currency) {
|
|
862
|
+
var _a, _b, _c, _d, _e, _f;
|
|
863
|
+
const priceMin = (_b = (_a = product.priceMin) != null ? _a : product.price) != null ? _b : 0;
|
|
864
|
+
const priceMax = (_d = (_c = product.priceMax) != null ? _c : product.price) != null ? _d : 0;
|
|
865
|
+
const compareAtMin = (_f = (_e = product.compareAtPriceMin) != null ? _e : product.compareAtPrice) != null ? _f : 0;
|
|
866
|
+
return {
|
|
867
|
+
...product,
|
|
868
|
+
currency,
|
|
869
|
+
localizedPricing: {
|
|
870
|
+
currency,
|
|
871
|
+
priceFormatted: formatPrice(priceMin, currency),
|
|
872
|
+
priceMinFormatted: formatPrice(priceMin, currency),
|
|
873
|
+
priceMaxFormatted: formatPrice(priceMax, currency),
|
|
874
|
+
compareAtPriceFormatted: formatPrice(compareAtMin, currency)
|
|
875
|
+
}
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
function maybeOverrideProductsCurrency(products, currency) {
|
|
879
|
+
if (!products || !currency) return products;
|
|
880
|
+
return products.map((p) => applyCurrencyOverride(p, currency));
|
|
881
|
+
}
|
|
882
|
+
const operations = {
|
|
883
|
+
/**
|
|
884
|
+
* Fetches all products from the store across all pages.
|
|
885
|
+
*
|
|
886
|
+
* @returns {Promise<Product[] | null>} Array of all products or null if error occurs
|
|
887
|
+
*
|
|
888
|
+
* @throws {Error} When there's a network error or API failure
|
|
889
|
+
*
|
|
890
|
+
* @example
|
|
891
|
+
* ```typescript
|
|
892
|
+
* const shop = new ShopClient('https://exampleshop.com');
|
|
893
|
+
* const allProducts = await shop.products.all();
|
|
894
|
+
*
|
|
895
|
+
* console.log(`Found ${allProducts?.length} products`);
|
|
896
|
+
* allProducts?.forEach(product => {
|
|
897
|
+
* console.log(product.title, product.price);
|
|
898
|
+
* });
|
|
899
|
+
* ```
|
|
900
|
+
*/
|
|
901
|
+
all: async (options) => {
|
|
902
|
+
const limit = 250;
|
|
903
|
+
const allProducts = [];
|
|
904
|
+
async function fetchAll() {
|
|
905
|
+
let currentPage = 1;
|
|
906
|
+
while (true) {
|
|
907
|
+
const products = await fetchProducts(currentPage, limit);
|
|
908
|
+
if (!products || products.length === 0 || products.length < limit) {
|
|
909
|
+
if (products && products.length > 0) {
|
|
910
|
+
allProducts.push(...products);
|
|
911
|
+
}
|
|
912
|
+
break;
|
|
913
|
+
}
|
|
914
|
+
allProducts.push(...products);
|
|
915
|
+
currentPage++;
|
|
916
|
+
}
|
|
917
|
+
return allProducts;
|
|
918
|
+
}
|
|
919
|
+
try {
|
|
920
|
+
const products = await fetchAll();
|
|
921
|
+
return maybeOverrideProductsCurrency(products, options == null ? void 0 : options.currency);
|
|
922
|
+
} catch (error) {
|
|
923
|
+
console.error("Failed to fetch all products:", storeDomain, error);
|
|
924
|
+
throw error;
|
|
925
|
+
}
|
|
926
|
+
},
|
|
927
|
+
/**
|
|
928
|
+
* Fetches products with pagination support.
|
|
929
|
+
*
|
|
930
|
+
* @param options - Pagination options
|
|
931
|
+
* @param options.page - Page number (default: 1)
|
|
932
|
+
* @param options.limit - Number of products per page (default: 250, max: 250)
|
|
933
|
+
*
|
|
934
|
+
* @returns {Promise<Product[] | null>} Array of products for the specified page or null if error occurs
|
|
935
|
+
*
|
|
936
|
+
* @throws {Error} When there's a network error or API failure
|
|
937
|
+
*
|
|
938
|
+
* @example
|
|
939
|
+
* ```typescript
|
|
940
|
+
* const shop = new ShopClient('https://example.myshopify.com');
|
|
941
|
+
*
|
|
942
|
+
* // Get first page with default limit (250)
|
|
943
|
+
* const firstPage = await shop.products.paginated();
|
|
944
|
+
*
|
|
945
|
+
* // Get second page with custom limit
|
|
946
|
+
* const secondPage = await shop.products.paginated({ page: 2, limit: 50 });
|
|
947
|
+
* ```
|
|
948
|
+
*/
|
|
949
|
+
paginated: async (options) => {
|
|
950
|
+
var _a, _b;
|
|
951
|
+
const page = (_a = options == null ? void 0 : options.page) != null ? _a : 1;
|
|
952
|
+
const limit = Math.min((_b = options == null ? void 0 : options.limit) != null ? _b : 250, 250);
|
|
953
|
+
const url = `${baseUrl}products.json?limit=${limit}&page=${page}`;
|
|
954
|
+
try {
|
|
955
|
+
const response = await rateLimitedFetch(url);
|
|
956
|
+
if (!response.ok) {
|
|
957
|
+
console.error(
|
|
958
|
+
`HTTP error! status: ${response.status} for ${storeDomain} page ${page}`
|
|
959
|
+
);
|
|
960
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
961
|
+
}
|
|
962
|
+
const data = await response.json();
|
|
963
|
+
if (data.products.length === 0) {
|
|
964
|
+
return [];
|
|
965
|
+
}
|
|
966
|
+
const normalized = productsDto(data.products);
|
|
967
|
+
return maybeOverrideProductsCurrency(normalized, options == null ? void 0 : options.currency);
|
|
968
|
+
} catch (error) {
|
|
969
|
+
console.error(
|
|
970
|
+
`Error fetching products for ${storeDomain} page ${page} with limit ${limit}:`,
|
|
971
|
+
error
|
|
972
|
+
);
|
|
973
|
+
return null;
|
|
974
|
+
}
|
|
975
|
+
},
|
|
976
|
+
/**
|
|
977
|
+
* Finds a specific product by its handle.
|
|
978
|
+
*
|
|
979
|
+
* @param productHandle - The product handle (URL slug) to search for
|
|
980
|
+
*
|
|
981
|
+
* @returns {Promise<Product | null>} The product if found, null if not found
|
|
982
|
+
*
|
|
983
|
+
* @throws {Error} When the handle is invalid or there's a network error
|
|
984
|
+
*
|
|
985
|
+
* @example
|
|
986
|
+
* ```typescript
|
|
987
|
+
* const shop = new ShopClient('https://exampleshop.com');
|
|
988
|
+
*
|
|
989
|
+
* // Find product by handle
|
|
990
|
+
* const product = await shop.products.find('awesome-t-shirt');
|
|
991
|
+
*
|
|
992
|
+
* if (product) {
|
|
993
|
+
* console.log(product.title, product.price);
|
|
994
|
+
* console.log('Available variants:', product.variants.length);
|
|
995
|
+
* }
|
|
996
|
+
*
|
|
997
|
+
* // Handle with query string
|
|
998
|
+
* const productWithVariant = await shop.products.find('t-shirt?variant=123');
|
|
999
|
+
* ```
|
|
1000
|
+
*/
|
|
1001
|
+
find: async (productHandle, options) => {
|
|
1002
|
+
var _a, _b;
|
|
1003
|
+
if (!productHandle || typeof productHandle !== "string") {
|
|
1004
|
+
throw new Error("Product handle is required and must be a string");
|
|
1005
|
+
}
|
|
1006
|
+
try {
|
|
1007
|
+
let qs = null;
|
|
1008
|
+
if (productHandle.includes("?")) {
|
|
1009
|
+
const parts = productHandle.split("?");
|
|
1010
|
+
const handlePart = (_a = parts[0]) != null ? _a : productHandle;
|
|
1011
|
+
const qsPart = (_b = parts[1]) != null ? _b : null;
|
|
1012
|
+
productHandle = handlePart;
|
|
1013
|
+
qs = qsPart;
|
|
1014
|
+
}
|
|
1015
|
+
const sanitizedHandle = productHandle.trim().replace(/[^a-zA-Z0-9\-_]/g, "");
|
|
1016
|
+
if (!sanitizedHandle) {
|
|
1017
|
+
throw new Error("Invalid product handle format");
|
|
1018
|
+
}
|
|
1019
|
+
if (sanitizedHandle.length > 255) {
|
|
1020
|
+
throw new Error("Product handle is too long");
|
|
1021
|
+
}
|
|
1022
|
+
let finalHandle = sanitizedHandle;
|
|
1023
|
+
try {
|
|
1024
|
+
const htmlResp = await rateLimitedFetch(
|
|
1025
|
+
`${baseUrl}products/${encodeURIComponent(sanitizedHandle)}`
|
|
1026
|
+
);
|
|
1027
|
+
if (htmlResp.ok) {
|
|
1028
|
+
const finalUrl = htmlResp.url;
|
|
1029
|
+
if (finalUrl) {
|
|
1030
|
+
const pathname = new URL(finalUrl).pathname.replace(/\/$/, "");
|
|
1031
|
+
const parts = pathname.split("/").filter(Boolean);
|
|
1032
|
+
const idx = parts.indexOf("products");
|
|
1033
|
+
const maybeHandle = idx >= 0 ? parts[idx + 1] : void 0;
|
|
1034
|
+
if (typeof maybeHandle === "string" && maybeHandle.length) {
|
|
1035
|
+
finalHandle = maybeHandle;
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
} catch {
|
|
1040
|
+
}
|
|
1041
|
+
const url = `${baseUrl}products/${encodeURIComponent(finalHandle)}.js${qs ? `?${qs}` : ""}`;
|
|
1042
|
+
const response = await rateLimitedFetch(url);
|
|
1043
|
+
if (!response.ok) {
|
|
1044
|
+
if (response.status === 404) {
|
|
1045
|
+
return null;
|
|
1046
|
+
}
|
|
1047
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
1048
|
+
}
|
|
1049
|
+
const product = await response.json();
|
|
1050
|
+
const productData = productDto(product);
|
|
1051
|
+
return (options == null ? void 0 : options.currency) ? applyCurrencyOverride(productData, options.currency) : productData;
|
|
1052
|
+
} catch (error) {
|
|
1053
|
+
if (error instanceof Error) {
|
|
1054
|
+
console.error(
|
|
1055
|
+
`Error fetching product ${productHandle}:`,
|
|
1056
|
+
baseUrl,
|
|
1057
|
+
error.message
|
|
1058
|
+
);
|
|
1059
|
+
}
|
|
1060
|
+
throw error;
|
|
1061
|
+
}
|
|
1062
|
+
},
|
|
1063
|
+
/**
|
|
1064
|
+
* Enrich a product by generating merged markdown from body_html and product page.
|
|
1065
|
+
* Adds `enriched_content` to the returned product.
|
|
1066
|
+
*/
|
|
1067
|
+
enriched: async (productHandle, options) => {
|
|
1068
|
+
if (!productHandle || typeof productHandle !== "string") {
|
|
1069
|
+
throw new Error("Product handle is required and must be a string");
|
|
1070
|
+
}
|
|
1071
|
+
const apiKey = (options == null ? void 0 : options.apiKey) || process.env.OPENROUTER_API_KEY;
|
|
1072
|
+
if (!apiKey) {
|
|
1073
|
+
throw new Error(
|
|
1074
|
+
"Missing OpenRouter API key. Pass options.apiKey or set OPENROUTER_API_KEY."
|
|
1075
|
+
);
|
|
1076
|
+
}
|
|
1077
|
+
const baseProduct = await operations.find(productHandle);
|
|
1078
|
+
if (!baseProduct) {
|
|
1079
|
+
return null;
|
|
1080
|
+
}
|
|
1081
|
+
const handle = baseProduct.handle;
|
|
1082
|
+
const enriched = await enrichProduct(storeDomain, handle, {
|
|
1083
|
+
apiKey,
|
|
1084
|
+
useGfm: options == null ? void 0 : options.useGfm,
|
|
1085
|
+
inputType: options == null ? void 0 : options.inputType,
|
|
1086
|
+
model: options == null ? void 0 : options.model,
|
|
1087
|
+
outputFormat: options == null ? void 0 : options.outputFormat
|
|
1088
|
+
});
|
|
1089
|
+
return {
|
|
1090
|
+
...baseProduct,
|
|
1091
|
+
enriched_content: enriched.mergedMarkdown
|
|
1092
|
+
};
|
|
1093
|
+
},
|
|
1094
|
+
classify: async (productHandle, options) => {
|
|
1095
|
+
if (!productHandle || typeof productHandle !== "string") {
|
|
1096
|
+
throw new Error("Product handle is required and must be a string");
|
|
1097
|
+
}
|
|
1098
|
+
const apiKey = (options == null ? void 0 : options.apiKey) || process.env.OPENROUTER_API_KEY;
|
|
1099
|
+
if (!apiKey) {
|
|
1100
|
+
throw new Error(
|
|
1101
|
+
"Missing OpenRouter API key. Pass options.apiKey or set OPENROUTER_API_KEY."
|
|
1102
|
+
);
|
|
1103
|
+
}
|
|
1104
|
+
const enrichedProduct = await operations.enriched(productHandle, {
|
|
1105
|
+
apiKey,
|
|
1106
|
+
inputType: "html",
|
|
1107
|
+
model: options == null ? void 0 : options.model,
|
|
1108
|
+
outputFormat: "json"
|
|
1109
|
+
});
|
|
1110
|
+
if (!enrichedProduct || !enrichedProduct.enriched_content) return null;
|
|
1111
|
+
let productContent = enrichedProduct.enriched_content;
|
|
1112
|
+
try {
|
|
1113
|
+
const obj = JSON.parse(enrichedProduct.enriched_content);
|
|
1114
|
+
const lines = [];
|
|
1115
|
+
if (obj.title && typeof obj.title === "string")
|
|
1116
|
+
lines.push(`Title: ${obj.title}`);
|
|
1117
|
+
if (obj.description && typeof obj.description === "string")
|
|
1118
|
+
lines.push(`Description: ${obj.description}`);
|
|
1119
|
+
if (Array.isArray(obj.materials) && obj.materials.length)
|
|
1120
|
+
lines.push(`Materials: ${obj.materials.join(", ")}`);
|
|
1121
|
+
if (Array.isArray(obj.care) && obj.care.length)
|
|
1122
|
+
lines.push(`Care: ${obj.care.join(", ")}`);
|
|
1123
|
+
if (obj.fit && typeof obj.fit === "string")
|
|
1124
|
+
lines.push(`Fit: ${obj.fit}`);
|
|
1125
|
+
if (obj.returnPolicy && typeof obj.returnPolicy === "string")
|
|
1126
|
+
lines.push(`ReturnPolicy: ${obj.returnPolicy}`);
|
|
1127
|
+
productContent = lines.join("\n");
|
|
1128
|
+
} catch {
|
|
1129
|
+
}
|
|
1130
|
+
const classification = await classifyProduct(productContent, {
|
|
1131
|
+
apiKey,
|
|
1132
|
+
model: options == null ? void 0 : options.model
|
|
1133
|
+
});
|
|
1134
|
+
return classification;
|
|
1135
|
+
},
|
|
1136
|
+
generateSEOContent: async (productHandle, options) => {
|
|
1137
|
+
if (!productHandle || typeof productHandle !== "string") {
|
|
1138
|
+
throw new Error("Product handle is required and must be a string");
|
|
1139
|
+
}
|
|
1140
|
+
const apiKey = (options == null ? void 0 : options.apiKey) || process.env.OPENROUTER_API_KEY;
|
|
1141
|
+
if (!apiKey) {
|
|
1142
|
+
throw new Error(
|
|
1143
|
+
"Missing OpenRouter API key. Pass options.apiKey or set OPENROUTER_API_KEY."
|
|
1144
|
+
);
|
|
1145
|
+
}
|
|
1146
|
+
const baseProduct = await operations.find(productHandle);
|
|
1147
|
+
if (!baseProduct) return null;
|
|
1148
|
+
const payload = {
|
|
1149
|
+
title: baseProduct.title,
|
|
1150
|
+
description: baseProduct.bodyHtml || void 0,
|
|
1151
|
+
vendor: baseProduct.vendor,
|
|
1152
|
+
price: baseProduct.price,
|
|
1153
|
+
tags: baseProduct.tags
|
|
1154
|
+
};
|
|
1155
|
+
const seo = await generateSEOContent(payload, {
|
|
1156
|
+
apiKey,
|
|
1157
|
+
model: options == null ? void 0 : options.model
|
|
1158
|
+
});
|
|
1159
|
+
return seo;
|
|
1160
|
+
},
|
|
1161
|
+
/**
|
|
1162
|
+
* Fetches products that are showcased/featured on the store's homepage.
|
|
1163
|
+
*
|
|
1164
|
+
* @returns {Promise<Product[]>} Array of showcased products found on the homepage
|
|
1165
|
+
*
|
|
1166
|
+
* @throws {Error} When there's a network error or API failure
|
|
1167
|
+
*
|
|
1168
|
+
* @example
|
|
1169
|
+
* ```typescript
|
|
1170
|
+
* const shop = new ShopClient('https://exampleshop.com');
|
|
1171
|
+
* const showcasedProducts = await shop.products.showcased();
|
|
1172
|
+
*
|
|
1173
|
+
* console.log(`Found ${showcasedProducts.length} showcased products`);
|
|
1174
|
+
* showcasedProducts.forEach(product => {
|
|
1175
|
+
* console.log(`Featured: ${product.title} - ${product.price}`);
|
|
1176
|
+
* });
|
|
1177
|
+
* ```
|
|
1178
|
+
*/
|
|
1179
|
+
showcased: async () => {
|
|
1180
|
+
const storeInfo = await getStoreInfo();
|
|
1181
|
+
const products = await Promise.all(
|
|
1182
|
+
storeInfo.showcase.products.map(
|
|
1183
|
+
(productHandle) => findProduct(productHandle)
|
|
1184
|
+
)
|
|
1185
|
+
);
|
|
1186
|
+
return filter(products, isNonNullish);
|
|
1187
|
+
},
|
|
1188
|
+
/**
|
|
1189
|
+
* Creates a filter map of variant options and their distinct values from all products.
|
|
1190
|
+
*
|
|
1191
|
+
* @returns {Promise<Record<string, string[]> | null>} Map of option names to their distinct values or null if error occurs
|
|
1192
|
+
*
|
|
1193
|
+
* @throws {Error} When there's a network error or API failure
|
|
1194
|
+
*
|
|
1195
|
+
* @example
|
|
1196
|
+
* ```typescript
|
|
1197
|
+
* const shop = new ShopClient('https://exampleshop.com');
|
|
1198
|
+
* const filters = await shop.products.filter();
|
|
1199
|
+
*
|
|
1200
|
+
* console.log('Available filters:', filters);
|
|
1201
|
+
* // Output: { "Size": ["S", "M", "L", "XL"], "Color": ["Red", "Blue", "Green"] }
|
|
1202
|
+
*
|
|
1203
|
+
* // Use filters for UI components
|
|
1204
|
+
* Object.entries(filters || {}).forEach(([optionName, values]) => {
|
|
1205
|
+
* console.log(`${optionName}: ${values.join(', ')}`);
|
|
1206
|
+
* });
|
|
1207
|
+
* ```
|
|
1208
|
+
*/
|
|
1209
|
+
filter: async () => {
|
|
1210
|
+
try {
|
|
1211
|
+
const products = await operations.all();
|
|
1212
|
+
if (!products || products.length === 0) {
|
|
1213
|
+
return {};
|
|
1214
|
+
}
|
|
1215
|
+
const filterMap = {};
|
|
1216
|
+
products.forEach((product) => {
|
|
1217
|
+
if (product.variants && product.variants.length > 0) {
|
|
1218
|
+
if (product.options && product.options.length > 0) {
|
|
1219
|
+
product.options.forEach((option) => {
|
|
1220
|
+
const lowercaseOptionName = option.name.toLowerCase();
|
|
1221
|
+
if (!filterMap[lowercaseOptionName]) {
|
|
1222
|
+
filterMap[lowercaseOptionName] = /* @__PURE__ */ new Set();
|
|
1223
|
+
}
|
|
1224
|
+
option.values.forEach((value) => {
|
|
1225
|
+
const trimmed = value == null ? void 0 : value.trim();
|
|
1226
|
+
if (trimmed) {
|
|
1227
|
+
let set = filterMap[lowercaseOptionName];
|
|
1228
|
+
if (!set) {
|
|
1229
|
+
set = /* @__PURE__ */ new Set();
|
|
1230
|
+
filterMap[lowercaseOptionName] = set;
|
|
1231
|
+
}
|
|
1232
|
+
set.add(trimmed.toLowerCase());
|
|
1233
|
+
}
|
|
1234
|
+
});
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
product.variants.forEach((variant) => {
|
|
1238
|
+
var _a, _b, _c, _d, _e, _f;
|
|
1239
|
+
if (variant.option1) {
|
|
1240
|
+
const optionName = (((_b = (_a = product.options) == null ? void 0 : _a[0]) == null ? void 0 : _b.name) || "Option 1").toLowerCase();
|
|
1241
|
+
let set1 = filterMap[optionName];
|
|
1242
|
+
if (!set1) {
|
|
1243
|
+
set1 = /* @__PURE__ */ new Set();
|
|
1244
|
+
filterMap[optionName] = set1;
|
|
1245
|
+
}
|
|
1246
|
+
set1.add(variant.option1.trim().toLowerCase());
|
|
1247
|
+
}
|
|
1248
|
+
if (variant.option2) {
|
|
1249
|
+
const optionName = (((_d = (_c = product.options) == null ? void 0 : _c[1]) == null ? void 0 : _d.name) || "Option 2").toLowerCase();
|
|
1250
|
+
let set2 = filterMap[optionName];
|
|
1251
|
+
if (!set2) {
|
|
1252
|
+
set2 = /* @__PURE__ */ new Set();
|
|
1253
|
+
filterMap[optionName] = set2;
|
|
1254
|
+
}
|
|
1255
|
+
set2.add(variant.option2.trim().toLowerCase());
|
|
1256
|
+
}
|
|
1257
|
+
if (variant.option3) {
|
|
1258
|
+
const optionName = (((_f = (_e = product.options) == null ? void 0 : _e[2]) == null ? void 0 : _f.name) || "Option 3").toLowerCase();
|
|
1259
|
+
if (!filterMap[optionName]) {
|
|
1260
|
+
filterMap[optionName] = /* @__PURE__ */ new Set();
|
|
1261
|
+
}
|
|
1262
|
+
filterMap[optionName].add(variant.option3.trim().toLowerCase());
|
|
1263
|
+
}
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
});
|
|
1267
|
+
const result = {};
|
|
1268
|
+
Object.entries(filterMap).forEach(([optionName, valueSet]) => {
|
|
1269
|
+
result[optionName] = Array.from(valueSet).sort();
|
|
1270
|
+
});
|
|
1271
|
+
return result;
|
|
1272
|
+
} catch (error) {
|
|
1273
|
+
console.error("Failed to create product filters:", storeDomain, error);
|
|
1274
|
+
throw error;
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
};
|
|
1278
|
+
return operations;
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
export {
|
|
1282
|
+
classifyProduct,
|
|
1283
|
+
generateSEOContent,
|
|
1284
|
+
determineStoreType,
|
|
1285
|
+
createProductOperations
|
|
1286
|
+
};
|
|
1287
|
+
//# sourceMappingURL=chunk-WTK5HUFI.mjs.map
|