@occluze/tether 0.3.6 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +12 -7
  2. package/dist/esm/astro.js +2 -0
  3. package/dist/esm/chunks/chunk-HHMOPDZG.js +1 -0
  4. package/dist/esm/chunks/chunk-HXKV6QGB.js +4 -0
  5. package/dist/esm/chunks/chunk-RBVRRQIU.js +1 -0
  6. package/dist/esm/chunks/chunk-RNZMTQTX.js +1 -0
  7. package/dist/esm/chunks/chunk-VC46IEJQ.js +1 -0
  8. package/dist/esm/chunks/diagnose-J667GHGS.js +1 -0
  9. package/dist/esm/chunks/markets-ui-EGWIEUOZ.js +1 -0
  10. package/dist/esm/index.js +1 -0
  11. package/dist/esm/server.js +1 -0
  12. package/dist/presets/barba.esm.js +4 -5
  13. package/dist/tether.diagnose.js +320 -0
  14. package/dist/tether.diagnose.min.js +1 -0
  15. package/dist/tether.esm.js +2 -2608
  16. package/dist/tether.js +637 -833
  17. package/dist/tether.markets.js +213 -0
  18. package/dist/tether.markets.min.js +1 -0
  19. package/dist/tether.min.js +3 -132
  20. package/dist/tether.min.js.map +4 -4
  21. package/package.json +52 -11
  22. package/src/astro.js +73 -0
  23. package/src/cart.js +79 -7
  24. package/src/client.js +25 -15
  25. package/src/config.js +4 -0
  26. package/src/diagnose.js +1 -1
  27. package/src/dom.js +32 -9
  28. package/src/fragments.js +12 -11
  29. package/src/index.js +80 -160
  30. package/src/initial.js +66 -0
  31. package/src/lazy-iife.js +43 -0
  32. package/src/lazy.js +9 -0
  33. package/src/loader.js +50 -7
  34. package/src/markets-ui.js +89 -0
  35. package/src/markets.js +1 -1
  36. package/src/mounting.js +129 -0
  37. package/src/parts/diagnose.js +3 -0
  38. package/src/parts/markets.js +3 -0
  39. package/src/product.js +86 -61
  40. package/src/server.js +179 -0
  41. package/src/status.js +2 -6
  42. package/types/astro.d.ts +15 -0
  43. package/types/barba.d.ts +16 -0
  44. package/types/index.d.ts +347 -0
  45. package/types/server.d.ts +94 -0
@@ -0,0 +1,320 @@
1
+ (() => {
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
7
+
8
+ // src/diagnose.js
9
+ var diagnose_exports = {};
10
+ __export(diagnose_exports, {
11
+ apiVersionStatus: () => apiVersionStatus,
12
+ checkMarkup: () => checkMarkup,
13
+ diagnose: () => diagnose
14
+ });
15
+
16
+ // tether-core:config.js
17
+ var m = window.Tether.__core["config.js"];
18
+ var { DEFAULTS, cfg, configure, isConfigured, log, reportError, warn } = m;
19
+
20
+ // tether-core:client.js
21
+ var m2 = window.Tether.__core["client.js"];
22
+ var { TetherError, endpoint, gql, request, unwrap, withContext } = m2;
23
+
24
+ // tether-core:dom.js
25
+ var m3 = window.Tether.__core["dom.js"];
26
+ var { attr, busy, cdnUrl, dataKey, emit, formatDate, formatMoney, get, has, hasTemplate, imageUrl, notifyLayoutChanged, parseJSONAttr, productUrl, qsa, readText, repeat, repeatKeyed, sameImage, scoped, sel, setImage, setSelected, setText, setTextTracked, show, toAttributes, watchImages } = m3;
27
+
28
+ // tether-core:loader.js
29
+ var m4 = window.Tether.__core["loader.js"];
30
+ var { clearProductCache, getProduct, getProducts, getRecommendations, hydrateProducts, normalizeProductKey, primeProduct, refreshProducts, takeStale } = m4;
31
+
32
+ // tether-core:selling-plans.js
33
+ var m5 = window.Tether.__core["selling-plans.js"];
34
+ var { GID, allPlans, allocationFor, findPlan, hasPlans, planAdjustment, planCheckoutCharge, planPrice, planSavings, plansForVariant, toGid } = m5;
35
+
36
+ // tether-core:status.js
37
+ var m6 = window.Tether.__core["status.js"];
38
+ var { STATUS_KEYS, boundary, isNotFound, ownedBy, resolveProductKey, setScopeStatus } = m6;
39
+
40
+ // src/api-version.js
41
+ var parse = (v) => {
42
+ const m7 = /^(\d{4})-(01|04|07|10)$/.exec(String(v || ""));
43
+ return m7 ? { y: +m7[1], m: +m7[2] } : null;
44
+ };
45
+ var fmt = (y, m7) => `${y}-${String(m7).padStart(2, "0")}`;
46
+ function nextApiVersion(v, steps = 1) {
47
+ const p = parse(v);
48
+ if (!p) throw new Error(`not a quarterly Shopify API version: ${v}`);
49
+ const q = p.y * 4 + (p.m - 1) / 3 + steps;
50
+ return fmt(Math.floor(q / 4), q % 4 * 3 + 1);
51
+ }
52
+ function apiVersionStatus(version, now = /* @__PURE__ */ new Date()) {
53
+ if (version === "unstable") return { version, ok: false, note: '"unstable" changes without notice: pin a dated version such as 2026-07' };
54
+ const p = parse(version);
55
+ if (!p) return { version, ok: false, note: "not a quarterly version (YYYY-01, -04, -07 or -10)" };
56
+ const released = new Date(Date.UTC(p.y, p.m - 1, 1));
57
+ const supportedUntil = new Date(Date.UTC(p.y + 1, p.m - 1, 1));
58
+ const monthsLeft = (supportedUntil - now) / (30.44 * 24 * 3600 * 1e3);
59
+ let note = `supported until about ${supportedUntil.toISOString().slice(0, 7)}`;
60
+ if (released > now) note = "not released yet (release candidate at best)";
61
+ else if (monthsLeft <= 0) note = "no longer supported: Shopify falls back to the oldest supported version. Upgrade (see README)";
62
+ else if (monthsLeft < 3) note = `${note}: plan the upgrade to ${nextApiVersion(version)} or later (see README)`;
63
+ return { version, ok: released <= now && monthsLeft > 0, monthsLeft: Math.round(monthsLeft), next: nextApiVersion(version), note };
64
+ }
65
+
66
+ // src/markets.js
67
+ var COUNTRY = /^[A-Z]{2}$/;
68
+ var REGIONAL_LANGUAGES = /* @__PURE__ */ new Set(["PT_BR", "PT_PT", "ZH_CN", "ZH_TW"]);
69
+ var storageKey = () => `${cfg.prefix}:market:${cfg.domain}`;
70
+ var defaultEnv = () => ({
71
+ document: typeof document !== "undefined" ? document : null,
72
+ location: typeof window !== "undefined" ? window.location : null,
73
+ storage: (() => {
74
+ try {
75
+ return window.localStorage;
76
+ } catch {
77
+ return null;
78
+ }
79
+ })(),
80
+ global: typeof window !== "undefined" ? window : {}
81
+ });
82
+ function toCountry(v) {
83
+ const c = String(v || "").trim().toUpperCase();
84
+ return COUNTRY.test(c) && c !== "XX" && c !== "T1" ? c : null;
85
+ }
86
+ function toLanguage(v) {
87
+ const raw = String(v || "").trim().replace("-", "_").toUpperCase();
88
+ if (!raw) return null;
89
+ if (REGIONAL_LANGUAGES.has(raw)) return raw;
90
+ const primary = raw.split("_")[0];
91
+ return /^[A-Z]{2,3}$/.test(primary) ? primary : null;
92
+ }
93
+ function readCookie(doc, name) {
94
+ if (!doc || !name) return null;
95
+ const hit = String(doc.cookie || "").split(";").map((c) => c.trim()).find((c) => c.startsWith(`${name}=`));
96
+ return hit ? decodeURIComponent(hit.slice(name.length + 1)) : null;
97
+ }
98
+ var lookup = (locales, key) => {
99
+ if (!locales || !key) return null;
100
+ const k = String(key).toLowerCase();
101
+ const found = Object.keys(locales).find((x) => x.toLowerCase() === k);
102
+ return found ? locales[found] : null;
103
+ };
104
+ var readers = {
105
+ saved(m7, env) {
106
+ if (m7.remember === false || !env.storage) return null;
107
+ try {
108
+ return JSON.parse(env.storage.getItem(storageKey()) || "null");
109
+ } catch {
110
+ return null;
111
+ }
112
+ },
113
+ server(m7, env) {
114
+ const meta = (name) => env.document?.querySelector?.(`meta[name="${name}"]`)?.getAttribute("content");
115
+ const country = env.global.TETHER_COUNTRY || meta("tether-country") || readCookie(env.document, m7.cookie || "tether_country");
116
+ const language = env.global.TETHER_LANGUAGE || meta("tether-language");
117
+ return { country, language };
118
+ },
119
+ webflow(m7, env) {
120
+ const segment = (env.location?.pathname || "/").split("/").filter(Boolean)[0];
121
+ const fromPath = lookup(m7.locales, segment);
122
+ if (fromPath) return fromPath;
123
+ const lang = env.document?.documentElement?.getAttribute("lang");
124
+ if (!lang) return null;
125
+ const mapped = lookup(m7.locales, lang) || lookup(m7.locales, lang.split("-")[0]);
126
+ if (mapped) return { locale: lang, ...mapped };
127
+ if (m7.locales && m7.strict) return null;
128
+ const region = lang.split("-")[1];
129
+ return { language: lang, country: region && region.length === 2 ? region : null, locale: lang };
130
+ }
131
+ };
132
+ function detectMarket(markets = cfg.markets, env = defaultEnv()) {
133
+ const m7 = markets || {};
134
+ if (m7.detect === false) return {};
135
+ const list = !m7.detect ? ["saved"] : m7.detect === true ? ["saved", "server", "webflow"] : [].concat(m7.detect);
136
+ markets = m7;
137
+ const out = { sources: {} };
138
+ list.forEach((name) => {
139
+ const r = readers[name]?.(markets, env);
140
+ if (!r) return;
141
+ const vals = { country: toCountry(r.country), language: toLanguage(r.language), locale: r.locale || null };
142
+ Object.entries(vals).forEach(([k, v]) => {
143
+ if (v && !out[k]) {
144
+ out[k] = v;
145
+ out.sources[k] = name;
146
+ }
147
+ });
148
+ });
149
+ return out;
150
+ }
151
+
152
+ // src/diagnose.js
153
+ var mask = (t) => t ? `${String(t).slice(0, 4)}\u2026${String(t).slice(-4)} (${String(t).length} chars)` : "(missing)";
154
+ function describe(el) {
155
+ const id = el.id ? `#${el.id}` : "";
156
+ const cls = el.className && typeof el.className === "string" ? `.${el.className.trim().split(/\s+/).slice(0, 2).join(".")}` : "";
157
+ return `<${el.tagName.toLowerCase()}${id}${cls}>`;
158
+ }
159
+ function checkMarkup(root = document) {
160
+ const problems = [];
161
+ const add = (level, message, el) => problems.push({ level, message, element: el ? describe(el) : void 0, el });
162
+ const inProduct = (el) => Boolean(el.closest(sel("product")));
163
+ const listSel = `${sel("collection")},${sel("products")},${sel("recommendations")}`;
164
+ qsa(root, sel("product")).forEach((el) => {
165
+ if (el.closest(listSel) && el.closest(sel("list"))) return;
166
+ const { key, fromUrl, raw } = resolveProductKey(el);
167
+ if (!raw) add("error", `${attr("product")} has no value. Bind it to the Shopify handle (CMS field), or use "url:handle".`, el);
168
+ else if (fromUrl && !key) add("warn", `${attr("product")}="${raw}" but this URL has no value for it (e.g. ?handle=my-product).`, el);
169
+ });
170
+ const productOnly = ["bind", "option-list", "option", "variant-select", "add-to-cart", "purchase", "plan-list", "plan", "qty", "line-attribute"];
171
+ productOnly.forEach((name) => {
172
+ qsa(root, sel(name)).forEach((el) => {
173
+ if (inProduct(el)) return;
174
+ if (name === "line-attribute" && el.closest(sel("group"))) return;
175
+ add("warn", `${attr(name)} outside any ${attr("product")}: it does nothing here.`, el);
176
+ });
177
+ });
178
+ qsa(root, sel("group-add")).forEach((el) => {
179
+ if (!el.closest(sel("group"))) add("warn", `${attr("group-add")} outside a ${attr("group")}.`, el);
180
+ });
181
+ [...qsa(root, sel("option-list")), ...qsa(root, sel("plan-list")), ...qsa(root, sel("cart-lines")), ...qsa(root, sel("list"))].forEach((el) => {
182
+ if (!el.firstElementChild && !hasTemplate(el)) {
183
+ add("warn", "Repeater without a template child: put one example element inside it.", el);
184
+ }
185
+ });
186
+ qsa(root, listSel).forEach((el) => {
187
+ if (!qsa(el, sel("list")).length) add("error", `List without a ${attr("list")} child: products have nowhere to render.`, el);
188
+ });
189
+ const known = /* @__PURE__ */ new Set([
190
+ "in-stock",
191
+ "out-of-stock",
192
+ "backorder",
193
+ "low-stock",
194
+ "on-sale",
195
+ "not-on-sale",
196
+ "has-variants",
197
+ "single-variant",
198
+ "subscription-available",
199
+ "subscription-unavailable",
200
+ "subscription-only",
201
+ "one-time-available",
202
+ "subscription-selected",
203
+ "one-time-selected",
204
+ "has-savings",
205
+ "loading",
206
+ "ready",
207
+ "error",
208
+ "not-found",
209
+ "cart-empty",
210
+ "cart-filled",
211
+ "cart-has-subscription",
212
+ "cart-no-subscription",
213
+ "cart-has-discount",
214
+ "cart-error",
215
+ "cart-warning",
216
+ "list-empty",
217
+ "list-filled"
218
+ ]);
219
+ qsa(root, sel("show")).forEach((el) => {
220
+ const k = get(el, "show");
221
+ if (!known.has(k)) add("warn", `Unknown ${attr("show")}="${k}".`, el);
222
+ });
223
+ qsa(root, sel("bind")).forEach((el) => {
224
+ const k = get(el, "bind") || "";
225
+ if (!k.startsWith("metafield:")) return;
226
+ const ref = k.slice(10);
227
+ const listed = (cfg.metafields || []).some((m7) => (typeof m7 === "string" ? m7 : `${m7.namespace}.${m7.key}`) === ref);
228
+ if (!listed) add("error", `${attr("bind")}="${k}" but "${ref}" is not in config.metafields, so it stays empty.`, el);
229
+ });
230
+ if (qsa(root, sel("cart-open")).length && !qsa(root, sel("cart-drawer")).length) {
231
+ add("warn", `${attr("cart-open")} exists but there is no ${attr("cart-drawer")} on this page.`);
232
+ }
233
+ if (qsa(root, sel("cart-drawer")).length > 1) add("warn", `More than one ${attr("cart-drawer")}.`);
234
+ qsa(root, `[${attr("state")}="error"]`).forEach((el) => {
235
+ if (el.matches(boundary())) add("error", `Scope failed to load (${get(el, "error") || "error"}).`, el);
236
+ });
237
+ return problems;
238
+ }
239
+ async function diagnose({ root = document, silent = false, version, now = /* @__PURE__ */ new Date() } = {}) {
240
+ const report = {
241
+ version,
242
+ config: {
243
+ domain: cfg.domain || "(missing)",
244
+ token: mask(cfg.token),
245
+ apiVersion: cfg.apiVersion,
246
+ endpoint: cfg.domain ? endpoint() : null,
247
+ country: cfg.country,
248
+ language: cfg.language,
249
+ locale: cfg.locale,
250
+ markets: cfg.markets || null,
251
+ prefix: cfg.prefix,
252
+ productPath: cfg.productPath,
253
+ metafields: cfg.metafields,
254
+ autoMount: cfg.autoMount,
255
+ observe: cfg.observe,
256
+ onError: typeof cfg.onError === "function"
257
+ },
258
+ apiVersion: apiVersionStatus(cfg.apiVersion, now),
259
+ market: cfg.markets?.detect ? detectMarket(cfg.markets) : null,
260
+ reachable: false,
261
+ shop: null,
262
+ latencyMs: null,
263
+ products: [],
264
+ sellingPlans: [],
265
+ problems: []
266
+ };
267
+ if (!isConfigured()) {
268
+ report.problems.push({ level: "error", message: "TETHER_CONFIG needs domain and token." });
269
+ } else {
270
+ const t0 = Date.now();
271
+ try {
272
+ const data = await gql("query TetherDiagnose { shop { name primaryDomain { url } paymentSettings { currencyCode } } }", {}, { context: false });
273
+ report.reachable = true;
274
+ report.shop = { name: data.shop?.name, url: data.shop?.primaryDomain?.url, currency: data.shop?.paymentSettings?.currencyCode };
275
+ } catch (err) {
276
+ const hint = err.status === 401 || err.status === 403 ? "Token rejected: use the public Storefront token from the Headless channel, not an Admin token." : err.status === 404 ? "Store or API version not found: check domain (x.myshopify.com) and apiVersion." : "";
277
+ report.problems.push({ level: "error", message: `Storefront API not reachable: ${err.message}${hint ? `. ${hint}` : ""}` });
278
+ }
279
+ report.latencyMs = Date.now() - t0;
280
+ if (report.reachable) {
281
+ const keys = [...new Set(qsa(root, sel("product")).map((el) => resolveProductKey(el).key).filter(Boolean))].slice(0, 20);
282
+ const results = await Promise.allSettled(keys.map((k) => getProduct(k)));
283
+ results.forEach((r, i) => {
284
+ if (r.status === "fulfilled") {
285
+ const p = r.value;
286
+ const plans = allPlans(p);
287
+ report.products.push({ key: keys[i], handle: p.handle, title: p.title, plans: plans.length, requiresSellingPlan: p.requiresSellingPlan });
288
+ plans.forEach((pl) => report.sellingPlans.push({ product: p.handle, group: pl.group?.name, plan: pl.name, id: pl.id }));
289
+ } else {
290
+ report.products.push({ key: keys[i], error: r.reason?.message });
291
+ report.problems.push({ level: "error", message: `Product "${keys[i]}": ${r.reason?.message}. Is it published to the Headless channel?` });
292
+ }
293
+ });
294
+ }
295
+ }
296
+ if (!report.apiVersion.ok || (report.apiVersion.monthsLeft ?? 99) < 3) {
297
+ report.problems.push({ level: report.apiVersion.ok ? "warn" : "error", message: `apiVersion ${cfg.apiVersion}: ${report.apiVersion.note}` });
298
+ }
299
+ if (typeof document !== "undefined") report.problems.push(...checkMarkup(root));
300
+ if (!silent) print(report);
301
+ return report;
302
+ }
303
+ function print(r) {
304
+ const c = console;
305
+ const errors = r.problems.filter((p) => p.level === "error").length;
306
+ c.group?.(`[${cfg.prefix}] diagnose: ${errors ? `${errors} error(s)` : "no errors"}, ${r.problems.length - errors} warning(s)`);
307
+ c.log("version", r.version, "| API", r.apiVersion.version, `(${r.apiVersion.note})`);
308
+ c.log("config", r.config);
309
+ if (r.market) c.log("market detected", r.market, "(in use:", r.config.country, r.config.language, ")");
310
+ c.log(r.reachable ? `Storefront API reachable: ${r.shop?.name} (${r.latencyMs} ms)` : "Storefront API NOT reachable");
311
+ if (r.products.length) (c.table || c.log)(r.products);
312
+ if (r.sellingPlans.length) (c.table || c.log)(r.sellingPlans);
313
+ else if (r.reachable) c.log("No selling plans on the products of this page.");
314
+ r.problems.forEach((p) => (p.level === "error" ? c.error : c.warn)(p.message, p.el || ""));
315
+ c.groupEnd?.();
316
+ }
317
+
318
+ // src/parts/diagnose.js
319
+ window.Tether.__parts.diagnose = diagnose_exports;
320
+ })();
@@ -0,0 +1 @@
1
+ (()=>{var V=Object.defineProperty;var D=(e,t)=>{for(var o in t)V(e,o,{get:t[o],enumerable:!0})};var k={};D(k,{apiVersionStatus:()=>$,checkMarkup:()=>L,diagnose:()=>X});var I=window.Tether.__core["config.js"],{DEFAULTS:te,cfg:l,configure:oe,isConfigured:E,log:ne,reportError:re,warn:ae}=I;var N=window.Tether.__core["client.js"],{TetherError:ie,endpoint:P,gql:w,request:le,unwrap:ce,withContext:ue}=N;var M=window.Tether.__core["dom.js"],{attr:f,busy:pe,cdnUrl:fe,dataKey:me,emit:ge,formatDate:he,formatMoney:ye,get:h,has:we,hasTemplate:T,imageUrl:be,notifyLayoutChanged:$e,parseJSONAttr:Se,productUrl:ke,qsa:u,readText:Ee,repeat:Pe,repeatKeyed:Te,sameImage:xe,scoped:Ce,sel:c,setImage:ve,setSelected:_e,setText:Ae,setTextTracked:Ue,show:Le,toAttributes:Ve,watchImages:De}=M;var q=window.Tether.__core["loader.js"],{clearProductCache:Ne,getProduct:x,getProducts:Me,getRecommendations:qe,hydrateProducts:Oe,normalizeProductKey:Re,primeProduct:je,refreshProducts:Ge,takeStale:ze}=q;var O=window.Tether.__core["selling-plans.js"],{GID:He,allPlans:C,allocationFor:Ke,findPlan:Ye,hasPlans:Fe,planAdjustment:Ze,planCheckoutCharge:Je,planPrice:We,planSavings:Xe,plansForVariant:Qe,toGid:et}=O;var R=window.Tether.__core["status.js"],{STATUS_KEYS:ot,boundary:v,isNotFound:nt,ownedBy:rt,resolveProductKey:b,setScopeStatus:at}=R;var A=e=>{let t=/^(\d{4})-(01|04|07|10)$/.exec(String(e||""));return t?{y:+t[1],m:+t[2]}:null},j=(e,t)=>`${e}-${String(t).padStart(2,"0")}`;function _(e,t=1){let o=A(e);if(!o)throw new Error(`not a quarterly Shopify API version: ${e}`);let s=o.y*4+(o.m-1)/3+t;return j(Math.floor(s/4),s%4*3+1)}function $(e,t=new Date){if(e==="unstable")return{version:e,ok:!1,note:'"unstable" changes without notice: pin a dated version such as 2026-07'};let o=A(e);if(!o)return{version:e,ok:!1,note:"not a quarterly version (YYYY-01, -04, -07 or -10)"};let s=new Date(Date.UTC(o.y,o.m-1,1)),n=new Date(Date.UTC(o.y+1,o.m-1,1)),d=(n-t)/(30.44*24*3600*1e3),a=`supported until about ${n.toISOString().slice(0,7)}`;return s>t?a="not released yet (release candidate at best)":d<=0?a="no longer supported: Shopify falls back to the oldest supported version. Upgrade (see README)":d<3&&(a=`${a}: plan the upgrade to ${_(e)} or later (see README)`),{version:e,ok:s<=t&&d>0,monthsLeft:Math.round(d),next:_(e),note:a}}var G=/^[A-Z]{2}$/,z=new Set(["PT_BR","PT_PT","ZH_CN","ZH_TW"]),B=()=>`${l.prefix}:market:${l.domain}`,H=()=>({document:typeof document<"u"?document:null,location:typeof window<"u"?window.location:null,storage:(()=>{try{return window.localStorage}catch{return null}})(),global:typeof window<"u"?window:{}});function K(e){let t=String(e||"").trim().toUpperCase();return G.test(t)&&t!=="XX"&&t!=="T1"?t:null}function Y(e){let t=String(e||"").trim().replace("-","_").toUpperCase();if(!t)return null;if(z.has(t))return t;let o=t.split("_")[0];return/^[A-Z]{2,3}$/.test(o)?o:null}function F(e,t){if(!e||!t)return null;let o=String(e.cookie||"").split(";").map(s=>s.trim()).find(s=>s.startsWith(`${t}=`));return o?decodeURIComponent(o.slice(t.length+1)):null}var S=(e,t)=>{if(!e||!t)return null;let o=String(t).toLowerCase(),s=Object.keys(e).find(n=>n.toLowerCase()===o);return s?e[s]:null},Z={saved(e,t){if(e.remember===!1||!t.storage)return null;try{return JSON.parse(t.storage.getItem(B())||"null")}catch{return null}},server(e,t){let o=d=>t.document?.querySelector?.(`meta[name="${d}"]`)?.getAttribute("content"),s=t.global.TETHER_COUNTRY||o("tether-country")||F(t.document,e.cookie||"tether_country"),n=t.global.TETHER_LANGUAGE||o("tether-language");return{country:s,language:n}},webflow(e,t){let o=(t.location?.pathname||"/").split("/").filter(Boolean)[0],s=S(e.locales,o);if(s)return s;let n=t.document?.documentElement?.getAttribute("lang");if(!n)return null;let d=S(e.locales,n)||S(e.locales,n.split("-")[0]);if(d)return{locale:n,...d};if(e.locales&&e.strict)return null;let a=n.split("-")[1];return{language:n,country:a&&a.length===2?a:null,locale:n}}};function U(e=l.markets,t=H()){let o=e||{};if(o.detect===!1)return{};let s=o.detect?o.detect===!0?["saved","server","webflow"]:[].concat(o.detect):["saved"];e=o;let n={sources:{}};return s.forEach(d=>{let a=Z[d]?.(e,t);if(!a)return;let r={country:K(a.country),language:Y(a.language),locale:a.locale||null};Object.entries(r).forEach(([i,p])=>{p&&!n[i]&&(n[i]=p,n.sources[i]=d)})}),n}var J=e=>e?`${String(e).slice(0,4)}\u2026${String(e).slice(-4)} (${String(e).length} chars)`:"(missing)";function W(e){let t=e.id?`#${e.id}`:"",o=e.className&&typeof e.className=="string"?`.${e.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";return`<${e.tagName.toLowerCase()}${t}${o}>`}function L(e=document){let t=[],o=(r,i,p)=>t.push({level:r,message:i,element:p?W(p):void 0,el:p}),s=r=>!!r.closest(c("product")),n=`${c("collection")},${c("products")},${c("recommendations")}`;u(e,c("product")).forEach(r=>{if(r.closest(n)&&r.closest(c("list")))return;let{key:i,fromUrl:p,raw:m}=b(r);m?p&&!i&&o("warn",`${f("product")}="${m}" but this URL has no value for it (e.g. ?handle=my-product).`,r):o("error",`${f("product")} has no value. Bind it to the Shopify handle (CMS field), or use "url:handle".`,r)}),["bind","option-list","option","variant-select","add-to-cart","purchase","plan-list","plan","qty","line-attribute"].forEach(r=>{u(e,c(r)).forEach(i=>{s(i)||r==="line-attribute"&&i.closest(c("group"))||o("warn",`${f(r)} outside any ${f("product")}: it does nothing here.`,i)})}),u(e,c("group-add")).forEach(r=>{r.closest(c("group"))||o("warn",`${f("group-add")} outside a ${f("group")}.`,r)}),[...u(e,c("option-list")),...u(e,c("plan-list")),...u(e,c("cart-lines")),...u(e,c("list"))].forEach(r=>{!r.firstElementChild&&!T(r)&&o("warn","Repeater without a template child: put one example element inside it.",r)}),u(e,n).forEach(r=>{u(r,c("list")).length||o("error",`List without a ${f("list")} child: products have nowhere to render.`,r)});let a=new Set(["in-stock","out-of-stock","backorder","low-stock","on-sale","not-on-sale","has-variants","single-variant","subscription-available","subscription-unavailable","subscription-only","one-time-available","subscription-selected","one-time-selected","has-savings","loading","ready","error","not-found","cart-empty","cart-filled","cart-has-subscription","cart-no-subscription","cart-has-discount","cart-error","cart-warning","list-empty","list-filled"]);return u(e,c("show")).forEach(r=>{let i=h(r,"show");a.has(i)||o("warn",`Unknown ${f("show")}="${i}".`,r)}),u(e,c("bind")).forEach(r=>{let i=h(r,"bind")||"";if(!i.startsWith("metafield:"))return;let p=i.slice(10);(l.metafields||[]).some(g=>(typeof g=="string"?g:`${g.namespace}.${g.key}`)===p)||o("error",`${f("bind")}="${i}" but "${p}" is not in config.metafields, so it stays empty.`,r)}),u(e,c("cart-open")).length&&!u(e,c("cart-drawer")).length&&o("warn",`${f("cart-open")} exists but there is no ${f("cart-drawer")} on this page.`),u(e,c("cart-drawer")).length>1&&o("warn",`More than one ${f("cart-drawer")}.`),u(e,`[${f("state")}="error"]`).forEach(r=>{r.matches(v())&&o("error",`Scope failed to load (${h(r,"error")||"error"}).`,r)}),t}async function X({root:e=document,silent:t=!1,version:o,now:s=new Date}={}){let n={version:o,config:{domain:l.domain||"(missing)",token:J(l.token),apiVersion:l.apiVersion,endpoint:l.domain?P():null,country:l.country,language:l.language,locale:l.locale,markets:l.markets||null,prefix:l.prefix,productPath:l.productPath,metafields:l.metafields,autoMount:l.autoMount,observe:l.observe,onError:typeof l.onError=="function"},apiVersion:$(l.apiVersion,s),market:l.markets?.detect?U(l.markets):null,reachable:!1,shop:null,latencyMs:null,products:[],sellingPlans:[],problems:[]};if(!E())n.problems.push({level:"error",message:"TETHER_CONFIG needs domain and token."});else{let d=Date.now();try{let a=await w("query TetherDiagnose { shop { name primaryDomain { url } paymentSettings { currencyCode } } }",{},{context:!1});n.reachable=!0,n.shop={name:a.shop?.name,url:a.shop?.primaryDomain?.url,currency:a.shop?.paymentSettings?.currencyCode}}catch(a){let r=a.status===401||a.status===403?"Token rejected: use the public Storefront token from the Headless channel, not an Admin token.":a.status===404?"Store or API version not found: check domain (x.myshopify.com) and apiVersion.":"";n.problems.push({level:"error",message:`Storefront API not reachable: ${a.message}${r?`. ${r}`:""}`})}if(n.latencyMs=Date.now()-d,n.reachable){let a=[...new Set(u(e,c("product")).map(i=>b(i).key).filter(Boolean))].slice(0,20);(await Promise.allSettled(a.map(i=>x(i)))).forEach((i,p)=>{if(i.status==="fulfilled"){let m=i.value,g=C(m);n.products.push({key:a[p],handle:m.handle,title:m.title,plans:g.length,requiresSellingPlan:m.requiresSellingPlan}),g.forEach(y=>n.sellingPlans.push({product:m.handle,group:y.group?.name,plan:y.name,id:y.id}))}else n.products.push({key:a[p],error:i.reason?.message}),n.problems.push({level:"error",message:`Product "${a[p]}": ${i.reason?.message}. Is it published to the Headless channel?`})})}}return(!n.apiVersion.ok||(n.apiVersion.monthsLeft??99)<3)&&n.problems.push({level:n.apiVersion.ok?"warn":"error",message:`apiVersion ${l.apiVersion}: ${n.apiVersion.note}`}),typeof document<"u"&&n.problems.push(...L(e)),t||Q(n),n}function Q(e){let t=console,o=e.problems.filter(s=>s.level==="error").length;t.group?.(`[${l.prefix}] diagnose: ${o?`${o} error(s)`:"no errors"}, ${e.problems.length-o} warning(s)`),t.log("version",e.version,"| API",e.apiVersion.version,`(${e.apiVersion.note})`),t.log("config",e.config),e.market&&t.log("market detected",e.market,"(in use:",e.config.country,e.config.language,")"),t.log(e.reachable?`Storefront API reachable: ${e.shop?.name} (${e.latencyMs} ms)`:"Storefront API NOT reachable"),e.products.length&&(t.table||t.log)(e.products),e.sellingPlans.length?(t.table||t.log)(e.sellingPlans):e.reachable&&t.log("No selling plans on the products of this page."),e.problems.forEach(s=>(s.level==="error"?t.error:t.warn)(s.message,s.el||"")),t.groupEnd?.()}window.Tether.__parts.diagnose=k;})();