@lynkow/astro 0.0.0-stage → 0.1.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 (39) hide show
  1. package/LICENSE +29 -0
  2. package/README.md +390 -2
  3. package/dist/chunk-67VKUBOP.js +40 -0
  4. package/dist/chunk-67VKUBOP.js.map +1 -0
  5. package/dist/chunk-7ZL7TFBK.js +28 -0
  6. package/dist/chunk-7ZL7TFBK.js.map +1 -0
  7. package/dist/chunk-DQXJDZWU.js +9 -0
  8. package/dist/chunk-DQXJDZWU.js.map +1 -0
  9. package/dist/chunk-OGQ25G7G.js +329 -0
  10. package/dist/chunk-OGQ25G7G.js.map +1 -0
  11. package/dist/chunk-USZSRPT5.js +119 -0
  12. package/dist/chunk-USZSRPT5.js.map +1 -0
  13. package/dist/client/index.d.ts +60 -0
  14. package/dist/client/index.js +59 -0
  15. package/dist/client/index.js.map +1 -0
  16. package/dist/clients-DLlMBN4c.d.ts +10 -0
  17. package/dist/config-BVCvQ8Wx.d.ts +66 -0
  18. package/dist/index.d.ts +353 -0
  19. package/dist/index.js +395 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/integration.d.ts +37 -0
  22. package/dist/integration.js +51 -0
  23. package/dist/integration.js.map +1 -0
  24. package/dist/lynkow-cache-BKZFJRTI.d.ts +150 -0
  25. package/dist/middleware/index.d.ts +187 -0
  26. package/dist/middleware/index.js +582 -0
  27. package/dist/middleware/index.js.map +1 -0
  28. package/dist/next-headers-3VG6LM4M.js +3 -0
  29. package/dist/next-headers-3VG6LM4M.js.map +1 -0
  30. package/dist/next-navigation-VNM5XXCX.js +7 -0
  31. package/dist/next-navigation-VNM5XXCX.js.map +1 -0
  32. package/dist/react/index.d.ts +134 -0
  33. package/dist/react/index.js +128 -0
  34. package/dist/react/index.js.map +1 -0
  35. package/dist/server/index.d.ts +493 -0
  36. package/dist/server/index.js +989 -0
  37. package/dist/server/index.js.map +1 -0
  38. package/dist/site-locales-tmcu43n2.d.ts +80 -0
  39. package/package.json +91 -4
package/dist/index.js ADDED
@@ -0,0 +1,395 @@
1
+ import { createClients, lynkowCache, takeHint } from './chunk-OGQ25G7G.js';
2
+ export { REVALIDATE, TAGS2 as TAGS, cached, createLynkowCache, createMemoryStore, lynkowCache, uncached2 as uncached } from './chunk-OGQ25G7G.js';
3
+ export { ABSOLUTE_HREF, createLocalePaths } from './chunk-USZSRPT5.js';
4
+ import { trackerGlobal } from './chunk-DQXJDZWU.js';
5
+ import { MediaHelperService } from 'lynkow';
6
+
7
+ // ../lynkow-next/src/config.ts
8
+ var DEFAULT_API_URL = "https://api.lynkow.com";
9
+ var HOST = /^(?:[a-z0-9_-]+(?:\.[a-z0-9_-]+)*\.?|\[[0-9a-f:.]+\])$/i;
10
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
11
+ var LOCALE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;
12
+ function resolveConfig(input, labels = {}) {
13
+ const problems = [];
14
+ const name = (field) => `\`${labels[field] ?? field}\``;
15
+ const siteId = input.siteId?.trim() ?? "";
16
+ if (!siteId) problems.push(`${name("siteId")} is required`);
17
+ else if (!UUID.test(siteId)) problems.push(`${name("siteId")} is not a site UUID: ${quote(siteId)}`);
18
+ const rawSiteUrl = input.siteUrl?.trim() ?? "";
19
+ if (!rawSiteUrl) problems.push(`${name("siteUrl")} is required`);
20
+ const siteUrl = rawSiteUrl ? parseOrigin(name("siteUrl"), rawSiteUrl, problems) : void 0;
21
+ const rawApiUrl = input.apiUrl?.trim() ?? "";
22
+ const apiUrl = rawApiUrl ? parseOrigin(name("apiUrl"), rawApiUrl, problems) : DEFAULT_API_URL;
23
+ const locales = parseLocales(name("locales"), input.locales, problems);
24
+ const defaultLocale = parseDefaultLocale(name("defaultLocale"), input.defaultLocale, locales, problems);
25
+ const publishableKey = input.publishableKey?.trim() || void 0;
26
+ if (publishableKey && !publishableKey.startsWith("lkw_pk_")) {
27
+ problems.push(
28
+ `${name("publishableKey")} is not a publishable key (lkw_pk_...). This configuration reaches the browser, so it must never hold a secret API key`
29
+ );
30
+ }
31
+ if (problems.length > 0 || !siteUrl || !apiUrl) {
32
+ throw new TypeError(`Invalid Lynkow configuration:
33
+ - ${problems.join("\n - ")}`);
34
+ }
35
+ return Object.freeze({
36
+ siteId: siteId.toLowerCase(),
37
+ siteUrl,
38
+ apiUrl,
39
+ publishableKey,
40
+ locales: Object.freeze([...locales]),
41
+ defaultLocale
42
+ });
43
+ }
44
+ function parseOrigin(field, raw, problems) {
45
+ if (hasUnsafeCharacter(raw)) {
46
+ problems.push(`${field} contains whitespace or a control character`);
47
+ return void 0;
48
+ }
49
+ let url;
50
+ try {
51
+ url = new URL(raw);
52
+ } catch {
53
+ problems.push(`${field} is not an absolute URL${echoUrl(raw)}`);
54
+ return void 0;
55
+ }
56
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
57
+ problems.push(`${field} must use http or https${echoUrl(raw)}`);
58
+ } else if (url.username || url.password) {
59
+ problems.push(`${field} must not carry credentials`);
60
+ } else if (!HOST.test(url.hostname)) {
61
+ problems.push(`${field} has a host with characters no domain carries${echoUrl(raw)}`);
62
+ } else if (!/^\/+$/.test(url.pathname) || url.search || url.hash) {
63
+ problems.push(`${field} must be an origin, with no path, query or fragment${echoUrl(raw)}`);
64
+ } else {
65
+ return url.origin;
66
+ }
67
+ return void 0;
68
+ }
69
+ function parseLocales(field, input, problems) {
70
+ const list = typeof input === "string" ? input.split(",") : [...input ?? []];
71
+ const locales = list.map((locale) => String(locale).trim()).filter(Boolean);
72
+ const seen = /* @__PURE__ */ new Set();
73
+ for (const locale of locales) {
74
+ if (!LOCALE.test(locale)) problems.push(invalidLocale(field, locale));
75
+ const key = locale.toLowerCase();
76
+ if (seen.has(key)) problems.push(`${field} lists ${quote(locale)} twice`);
77
+ seen.add(key);
78
+ }
79
+ return locales;
80
+ }
81
+ function parseDefaultLocale(field, input, locales, problems) {
82
+ const wanted = input?.trim() ?? "";
83
+ if (locales.length === 0) {
84
+ if (wanted && !LOCALE.test(wanted)) {
85
+ problems.push(invalidLocale(field, wanted));
86
+ return "";
87
+ }
88
+ return wanted;
89
+ }
90
+ if (!wanted) return locales[0] ?? "";
91
+ const found = locales.find((locale) => locale.toLowerCase() === wanted.toLowerCase());
92
+ if (!found) {
93
+ problems.push(`${field} is ${quote(wanted)}, which is not one of the locales (${locales.join(", ")})`);
94
+ return "";
95
+ }
96
+ return found;
97
+ }
98
+ function invalidLocale(field, locale) {
99
+ return `${field} has an invalid locale ${quote(locale)}, expected a code such as "en" or "pt-BR"`;
100
+ }
101
+ function hasUnsafeCharacter(value) {
102
+ if (/\s/.test(value)) return true;
103
+ for (let index = 0; index < value.length; index++) {
104
+ const code = value.charCodeAt(index);
105
+ if (code < 32 || code === 127) return true;
106
+ }
107
+ return false;
108
+ }
109
+ function echoUrl(raw) {
110
+ return raw.includes("@") ? "" : `: ${quote(raw)}`;
111
+ }
112
+ function quote(value) {
113
+ return JSON.stringify(value.length > 120 ? `${value.slice(0, 120)}...` : value);
114
+ }
115
+
116
+ // ../lynkow-next/src/site-locales.ts
117
+ function createSiteLocales({ client, ttlMs = 6e4 }) {
118
+ if (typeof ttlMs !== "number" || !Number.isFinite(ttlMs) || ttlMs < 0) {
119
+ throw new RangeError(`ttlMs must be a finite number of at least 0, got ${String(ttlMs)}`);
120
+ }
121
+ let snapshot = null;
122
+ let checkedAt = null;
123
+ let generation = 0;
124
+ let inFlight = null;
125
+ function isFresh() {
126
+ return checkedAt !== null && Date.now() - checkedAt < ttlMs;
127
+ }
128
+ function refresh() {
129
+ if (inFlight) return inFlight;
130
+ const started = generation;
131
+ const attempt = Promise.resolve().then(() => client().site.getConfig()).then(toSnapshot).then(
132
+ (next) => {
133
+ if (inFlight === attempt) inFlight = null;
134
+ if (started === generation) {
135
+ snapshot = next;
136
+ checkedAt = Date.now();
137
+ } else if (snapshot === null) {
138
+ snapshot = next;
139
+ }
140
+ return next;
141
+ },
142
+ (error) => {
143
+ if (inFlight === attempt) inFlight = null;
144
+ if (snapshot === null) throw error;
145
+ if (started === generation) checkedAt = Date.now();
146
+ return snapshot;
147
+ }
148
+ );
149
+ inFlight = attempt;
150
+ return attempt;
151
+ }
152
+ return {
153
+ get() {
154
+ if (snapshot && isFresh()) return Promise.resolve(snapshot);
155
+ return refresh();
156
+ },
157
+ current() {
158
+ if (!snapshot) {
159
+ throw new Error(
160
+ "The site locales have not been loaded yet: await siteLocales.get() before reading them synchronously"
161
+ );
162
+ }
163
+ if (!isFresh()) refresh().catch(() => {
164
+ });
165
+ return snapshot;
166
+ },
167
+ invalidate() {
168
+ generation += 1;
169
+ checkedAt = null;
170
+ inFlight = null;
171
+ }
172
+ };
173
+ }
174
+ var NO_MARKETS = Object.freeze([]);
175
+ function toSnapshot(config) {
176
+ const { enabledLocales, defaultLocale, i18n } = config;
177
+ if (!Array.isArray(enabledLocales) || enabledLocales.length === 0 || typeof defaultLocale !== "string" || defaultLocale.length === 0) {
178
+ throw new Error("The site configuration carries no usable locale list or default locale");
179
+ }
180
+ const locales = Object.freeze([...enabledLocales]);
181
+ const directions = {};
182
+ for (const info of i18n.locales) directions[info.code] = info.direction ?? "ltr";
183
+ for (const locale of locales) directions[locale] ??= "ltr";
184
+ return Object.freeze({
185
+ locales,
186
+ defaultLocale,
187
+ directions: Object.freeze(directions),
188
+ detection: i18n.detection,
189
+ markets: NO_MARKETS
190
+ });
191
+ }
192
+
193
+ // src/config.ts
194
+ function resolveConfig2(input, labels = {}) {
195
+ return resolveConfig(input, labels);
196
+ }
197
+ function createSiteLocales2(options) {
198
+ return createSiteLocales(options);
199
+ }
200
+
201
+ // src/clients.ts
202
+ function createClients2(config, { cache = lynkowCache, ...options } = {}) {
203
+ const clients = createClients(config, options);
204
+ const site = `${config.siteId}|${config.apiUrl}|${fnv1a(config.publishableKey ?? "")}`;
205
+ const wrapped = /* @__PURE__ */ new WeakMap();
206
+ return function lynkow(locale, clientOptions) {
207
+ const client = clients(locale, clientOptions);
208
+ const asked = (locale ?? "").toLowerCase();
209
+ let byAsked = wrapped.get(client);
210
+ if (!byAsked) wrapped.set(client, byAsked = /* @__PURE__ */ new Map());
211
+ let proxy = byAsked.get(asked);
212
+ if (!proxy) {
213
+ proxy = cachingClient(client, () => `${site}|${asked}|${client.locale}`, cache);
214
+ byAsked.set(asked, proxy);
215
+ }
216
+ return proxy;
217
+ };
218
+ }
219
+ function fnv1a(text) {
220
+ let hash = 2166136261;
221
+ for (let i = 0; i < text.length; i++) {
222
+ hash ^= text.charCodeAt(i);
223
+ hash = Math.imul(hash, 16777619);
224
+ }
225
+ return (hash >>> 0).toString(16).padStart(8, "0");
226
+ }
227
+ function isAccessor(object, property) {
228
+ for (let current = object; current; current = Object.getPrototypeOf(current)) {
229
+ const descriptor = Object.getOwnPropertyDescriptor(current, property);
230
+ if (descriptor) return descriptor.get !== void 0;
231
+ }
232
+ return false;
233
+ }
234
+ function isService(value) {
235
+ if (Array.isArray(value)) return false;
236
+ for (let proto = Object.getPrototypeOf(value); proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
237
+ for (const name of Object.getOwnPropertyNames(proto)) {
238
+ const descriptor = Object.getOwnPropertyDescriptor(proto, name);
239
+ if (name !== "constructor" && typeof descriptor?.value === "function") return true;
240
+ }
241
+ }
242
+ return false;
243
+ }
244
+ function cachingClient(client, prefix, cache) {
245
+ const services = /* @__PURE__ */ new WeakMap();
246
+ return new Proxy(client, {
247
+ get(target, property) {
248
+ const value = Reflect.get(target, property, target);
249
+ if (typeof value === "function") return value.bind(target);
250
+ if (typeof value !== "object" || value === null || typeof property !== "string") return value;
251
+ let byName = services.get(value);
252
+ let service = byName?.get(property);
253
+ if (service) return service;
254
+ if (isAccessor(target, property) || !isService(value)) return value;
255
+ if (!byName) services.set(value, byName = /* @__PURE__ */ new Map());
256
+ service = cachingService(value, () => `${prefix()}|${property}`, cache);
257
+ byName.set(property, service);
258
+ return service;
259
+ }
260
+ });
261
+ }
262
+ function cachingService(service, prefix, cache) {
263
+ const methods = /* @__PURE__ */ new Map();
264
+ return new Proxy(service, {
265
+ get(target, property) {
266
+ const value = Reflect.get(target, property, target);
267
+ if (typeof value !== "function" || typeof property !== "string") return value;
268
+ let method = methods.get(property);
269
+ if (!method) {
270
+ const fn = value;
271
+ method = function(...args) {
272
+ const { policy, args: stripped } = takeHint(args);
273
+ if (!policy) return fn.apply(target, stripped);
274
+ const argsKey = stableKey(stripped);
275
+ if (argsKey === null) return fn.apply(target, stripped);
276
+ return cache.read(`${prefix()}.${property}|${argsKey}`, policy, async () => fn.apply(target, stripped));
277
+ };
278
+ methods.set(property, method);
279
+ }
280
+ return method;
281
+ }
282
+ });
283
+ }
284
+ var UNKEYABLE = /* @__PURE__ */ Symbol("unkeyable");
285
+ var UNDEFINED_ITEM = "\0undefined";
286
+ function stableKey(value) {
287
+ try {
288
+ return JSON.stringify(normalize(value)) ?? null;
289
+ } catch (error) {
290
+ if (error === UNKEYABLE) return null;
291
+ throw error;
292
+ }
293
+ }
294
+ function normalize(value) {
295
+ switch (typeof value) {
296
+ case "string":
297
+ case "boolean":
298
+ return value;
299
+ case "number":
300
+ if (!Number.isFinite(value)) throw UNKEYABLE;
301
+ return value;
302
+ case "undefined":
303
+ return void 0;
304
+ case "object":
305
+ break;
306
+ default:
307
+ throw UNKEYABLE;
308
+ }
309
+ if (value === null) return null;
310
+ if (Array.isArray(value)) return value.map((item) => item === void 0 ? UNDEFINED_ITEM : normalize(item));
311
+ if (typeof Headers !== "undefined" && value instanceof Headers) return headerList(value);
312
+ if (value instanceof Date) {
313
+ if (Number.isNaN(value.getTime())) throw UNKEYABLE;
314
+ return { $date: value.toISOString() };
315
+ }
316
+ const proto = Object.getPrototypeOf(value);
317
+ if (proto !== Object.prototype && proto !== null) throw UNKEYABLE;
318
+ const record = value;
319
+ const out = {};
320
+ for (const key of Object.keys(record).sort()) {
321
+ const item = record[key];
322
+ if (key === "fetchOptions" && typeof item === "object" && item !== null) {
323
+ out[key] = fetchOptionsKey(item);
324
+ continue;
325
+ }
326
+ const normalized = normalize(item);
327
+ if (normalized !== void 0) out[key] = normalized;
328
+ }
329
+ return out;
330
+ }
331
+ function fetchOptionsKey(fetchOptions) {
332
+ if (fetchOptions.headers === void 0) return {};
333
+ let headers;
334
+ try {
335
+ headers = new Headers(fetchOptions.headers);
336
+ } catch {
337
+ throw UNKEYABLE;
338
+ }
339
+ return { headers: headerList(headers) };
340
+ }
341
+ function headerList(headers) {
342
+ const list = [];
343
+ headers.forEach((value, name) => list.push([name, value]));
344
+ return list.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
345
+ }
346
+
347
+ // ../lynkow-next/src/analytics/events.ts
348
+ function trackEvent(type, data) {
349
+ const global = trackerGlobal();
350
+ if (typeof global?.track !== "function") return false;
351
+ global.track({
352
+ page_path: window.location.pathname,
353
+ page_url: window.location.href,
354
+ page_title: document.title,
355
+ // A page field in `data` wins; `event_type` never does, as in the SDK's
356
+ // `trackEvent`, so a stray key cannot contradict `type`.
357
+ ...data,
358
+ event_type: type
359
+ });
360
+ return true;
361
+ }
362
+ var media = new MediaHelperService();
363
+ function lynkowImageLoader({ src, width, quality }) {
364
+ if (!/^https?:\/\//i.test(src)) return src;
365
+ return media.transform(src, {
366
+ w: width,
367
+ // `scale-down` never upscales, so a small original stays small rather than
368
+ // being blown up to the layout's widest candidate.
369
+ fit: "scale-down",
370
+ // The CDN negotiates the format from `Accept`, so a modern browser gets
371
+ // WebP or AVIF without the application knowing which.
372
+ format: "auto",
373
+ quality: quality ?? 80
374
+ }) || src;
375
+ }
376
+
377
+ // src/image.ts
378
+ function imageUrl({ src, width, quality }) {
379
+ return lynkowImageLoader(quality === void 0 ? { src, width } : { src, width, quality });
380
+ }
381
+ function imageSrcSet(src, widths, quality) {
382
+ for (const width of widths) {
383
+ if (!Number.isInteger(width) || width < 1) {
384
+ throw new RangeError(`imageSrcSet() takes positive integer widths, got ${String(width)}`);
385
+ }
386
+ }
387
+ const sorted = [...new Set(widths)].sort((a, b) => a - b);
388
+ const first = sorted[0];
389
+ if (first === void 0 || imageUrl({ src, width: first, quality }) === src) return "";
390
+ return sorted.map((width) => `${imageUrl({ src, width, quality })} ${width}w`).join(", ");
391
+ }
392
+
393
+ export { createClients2 as createClients, createSiteLocales2 as createSiteLocales, imageSrcSet, imageUrl, resolveConfig2 as resolveConfig, trackEvent };
394
+ //# sourceMappingURL=index.js.map
395
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../lynkow-next/src/config.ts","../../lynkow-next/src/site-locales.ts","../src/config.ts","../src/clients.ts","../../lynkow-next/src/analytics/events.ts","../../lynkow-next/src/image-loader.ts","../src/image.ts"],"names":["resolveConfig","createSiteLocales","createClients"],"mappings":";;;;;;;AAyEA,IAAM,eAAA,GAAkB,wBAAA;AAOxB,IAAM,IAAA,GAAO,yDAAA;AAEb,IAAM,IAAA,GAAO,iEAAA;AAQb,IAAM,MAAA,GAAS,oCAAA;AAqBR,SAAS,aAAA,CACd,KAAA,EACA,MAAA,GAAiC,EAAC,EAChB;AAClB,EAAA,MAAM,WAAqB,EAAC;AAC5B,EAAA,MAAM,OAAO,CAAC,KAAA,KAAuC,KAAK,MAAA,CAAO,KAAK,KAAK,KAAK,CAAA,EAAA,CAAA;AAEhF,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,MAAA,EAAQ,IAAA,EAAK,IAAK,EAAA;AACvC,EAAA,IAAI,CAAC,QAAQ,QAAA,CAAS,IAAA,CAAK,GAAG,IAAA,CAAK,QAAQ,CAAC,CAAA,YAAA,CAAc,CAAA;AAAA,OAAA,IACjD,CAAC,IAAA,CAAK,IAAA,CAAK,MAAM,GAAG,QAAA,CAAS,IAAA,CAAK,CAAA,EAAG,IAAA,CAAK,QAAQ,CAAC,CAAA,qBAAA,EAAwB,KAAA,CAAM,MAAM,CAAC,CAAA,CAAE,CAAA;AAEnG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AA,CAAW,CAAA,iDAAA,EAAoD,MAAA,CAAO,KAAK,CAAC,CAAA,CAAE,CAAA;AAAA,IAC1F;AAAA,EACF;AACA,EAAA,MAAM,MAAA,GAAS,CAAC,GAAG,IAAI,GAAA,CAAI,MAAM,CAAC,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,IAAI,CAAC,CAAA;AACxD,EAAA,MAAM,KAAA,GAAQ,OAAO,CAAC,CAAA;AACtB,EAAA,IAAI,KAAA,KAAU,MAAA,IAAa,QAAA,CAAS,EAAE,GAAA,EAAK,KAAA,EAAO,KAAA,EAAO,OAAA,EAAS,CAAA,KAAM,GAAA,EAAK,OAAO,EAAA;AACpF,EAAA,OAAO,OAAO,GAAA,CAAI,CAAC,KAAA,KAAU,CAAA,EAAG,SAAS,EAAE,GAAA,EAAK,KAAA,EAAO,OAAA,EAAS,CAAC,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA,CAAG,CAAA,CAAE,KAAK,IAAI,CAAA;AAC1F","file":"index.js","sourcesContent":["/**\n * The configuration a Lynkow site hands this adapter, and the one function\n * that validates it.\n *\n * Nothing in this package reads `process.env`. Next inlines `NEXT_PUBLIC_*`\n * variables at build time by textual substitution, so only a literal\n * `process.env.NEXT_PUBLIC_X` written in the application's own source reaches\n * the browser bundle, and a library cannot spell out names an application\n * chose. The application reads its environment and passes the values here.\n *\n * Everything in the resolved configuration is public, because it reaches\n * client bundles. A server secret, such as the webhook signing secret, never\n * belongs in it.\n */\n\n/** What an application passes to {@link resolveConfig}, typically straight from its environment. */\nexport interface LynkowNextConfigInput {\n /** The site's UUID, shown in the Lynkow admin and returned by the MCP `list_sites` tool. */\n siteId: string | undefined\n /** The public origin of the site, such as `https://www.example.com`. No path, query or fragment. */\n siteUrl: string | undefined\n /**\n * A static override of the locales the site serves, as an array or a\n * comma-separated list, in the order they should be advertised. Leave it out,\n * or empty, to read the site's enabled locales at runtime from the source\n * created by `createSiteLocales`. When given, it wins over that source.\n */\n locales?: string | readonly string[] | undefined\n /**\n * A static override of the default locale. With `locales`, it must be one of\n * them and defaults to the first. Without them, it is kept as given, and when\n * it is left out too the runtime source supplies the site's default locale.\n */\n defaultLocale?: string | undefined\n /** The Lynkow API origin. Defaults to `https://api.lynkow.com`. */\n apiUrl?: string | undefined\n /** The site's publishable key (`lkw_pk_...`), which storefront reads need. */\n publishableKey?: string | undefined\n}\n\n/** A validated configuration, frozen. Every field is safe to ship to the browser. */\nexport interface LynkowNextConfig {\n readonly siteId: string\n /** The site's origin, with no trailing slash, so `${siteUrl}${path}` is always well formed. */\n readonly siteUrl: string\n /** The API origin, with no trailing slash. */\n readonly apiUrl: string\n readonly publishableKey: string | undefined\n /**\n * The static locale list, in its configured case, or empty when none was\n * given: the runtime source then supplies the live list. URLs carry locales\n * lowercased.\n */\n readonly locales: readonly string[]\n /**\n * The static default locale, in its configured case: one of `locales` when a\n * list was given. Empty when neither was given, the runtime source then\n * supplying the live one.\n */\n readonly defaultLocale: string\n}\n\n/**\n * Names to use for each field in error messages, such as the environment\n * variable the application reads it from.\n */\nexport type LynkowNextConfigLabels = Partial<Record<keyof LynkowNextConfigInput, string>>\n\n/**\n * The SDK's own default API origin, which it does not export. Repeated here\n * because the analytics tracker is a plain script tag rather than an SDK call,\n * and needs a real URL.\n */\nconst DEFAULT_API_URL = 'https://api.lynkow.com'\n\n/**\n * A DNS name or an IP literal. The URL standard lets a host carry `\"`, `'`, `&`\n * or a backtick, and the origin is pasted as text into JSON-LD, XML sitemaps and\n * HTML attributes, so only what a real host is made of passes.\n */\nconst HOST = /^(?:[a-z0-9_-]+(?:\\.[a-z0-9_-]+)*\\.?|\\[[0-9a-f:.]+\\])$/i\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n/**\n * A language subtag, then optional region or variant subtags: `en`, `fr`,\n * `pt-BR`. Strict on purpose: a locale becomes a path segment, and a value\n * such as `//evil.example` or `en/../fr` would turn a localized link into one\n * that leaves the site or lands on another locale.\n */\nconst LOCALE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/\n\n/**\n * Validates a configuration and fills in its defaults.\n *\n * It throws from a call the application made, never while this module is\n * imported, so a site owner gets an error they can read rather than a stack\n * trace out of a dependency's import graph.\n *\n * @param input - The values, typically read from the application's environment\n * @param labels - Optional names for the fields in error messages, such as\n * `{ siteId: 'NEXT_PUBLIC_LYNKOW_SITE_ID' }`\n * @throws {TypeError} Listing every problem found, one per line\n *\n * @example\n * export const config = resolveConfig({\n * siteId: process.env.NEXT_PUBLIC_LYNKOW_SITE_ID,\n * siteUrl: process.env.NEXT_PUBLIC_SITE_URL,\n * locales: process.env.NEXT_PUBLIC_LOCALES,\n * })\n */\nexport function resolveConfig(\n input: LynkowNextConfigInput,\n labels: LynkowNextConfigLabels = {}\n): LynkowNextConfig {\n const problems: string[] = []\n const name = (field: keyof LynkowNextConfigInput) => `\\`${labels[field] ?? field}\\``\n\n const siteId = input.siteId?.trim() ?? ''\n if (!siteId) problems.push(`${name('siteId')} is required`)\n else if (!UUID.test(siteId)) problems.push(`${name('siteId')} is not a site UUID: ${quote(siteId)}`)\n\n const rawSiteUrl = input.siteUrl?.trim() ?? ''\n if (!rawSiteUrl) problems.push(`${name('siteUrl')} is required`)\n const siteUrl = rawSiteUrl ? parseOrigin(name('siteUrl'), rawSiteUrl, problems) : undefined\n\n const rawApiUrl = input.apiUrl?.trim() ?? ''\n const apiUrl = rawApiUrl ? parseOrigin(name('apiUrl'), rawApiUrl, problems) : DEFAULT_API_URL\n\n const locales = parseLocales(name('locales'), input.locales, problems)\n\n const defaultLocale = parseDefaultLocale(name('defaultLocale'), input.defaultLocale, locales, problems)\n\n // An allowlist, not a denylist of `lkw_sk_`: legacy secret tokens are bare\n // hex and still authenticate, and every publishable key is `lkw_pk_`.\n const publishableKey = input.publishableKey?.trim() || undefined\n if (publishableKey && !publishableKey.startsWith('lkw_pk_')) {\n problems.push(\n `${name('publishableKey')} is not a publishable key (lkw_pk_...). This configuration reaches the browser, so it must never hold a secret API key`\n )\n }\n\n if (problems.length > 0 || !siteUrl || !apiUrl) {\n throw new TypeError(`Invalid Lynkow configuration:\\n - ${problems.join('\\n - ')}`)\n }\n\n return Object.freeze({\n siteId: siteId.toLowerCase(),\n siteUrl,\n apiUrl,\n publishableKey,\n locales: Object.freeze([...locales]),\n defaultLocale,\n })\n}\n\n/**\n * Parses an http(s) origin. Whitespace and control characters are refused\n * before the URL parser sees the value, because it silently strips tabs and\n * newlines, and a newline in a site URL written into robots.txt is a line of\n * its own.\n */\nfunction parseOrigin(field: string, raw: string, problems: string[]): string | undefined {\n if (hasUnsafeCharacter(raw)) {\n problems.push(`${field} contains whitespace or a control character`)\n return undefined\n }\n let url: URL\n try {\n url = new URL(raw)\n } catch {\n problems.push(`${field} is not an absolute URL${echoUrl(raw)}`)\n return undefined\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n problems.push(`${field} must use http or https${echoUrl(raw)}`)\n } else if (url.username || url.password) {\n problems.push(`${field} must not carry credentials`)\n } else if (!HOST.test(url.hostname)) {\n problems.push(`${field} has a host with characters no domain carries${echoUrl(raw)}`)\n } else if (!/^\\/+$/.test(url.pathname) || url.search || url.hash) {\n problems.push(`${field} must be an origin, with no path, query or fragment${echoUrl(raw)}`)\n } else {\n return url.origin\n }\n return undefined\n}\n\nfunction parseLocales(\n field: string,\n input: string | readonly string[] | undefined,\n problems: string[]\n): string[] {\n const list = typeof input === 'string' ? input.split(',') : [...(input ?? [])]\n const locales = list.map((locale) => String(locale).trim()).filter(Boolean)\n const seen = new Set<string>()\n for (const locale of locales) {\n if (!LOCALE.test(locale)) problems.push(invalidLocale(field, locale))\n const key = locale.toLowerCase()\n if (seen.has(key)) problems.push(`${field} lists ${quote(locale)} twice`)\n seen.add(key)\n }\n return locales\n}\n\n/**\n * The static default locale. With a static list it is one of them, the first\n * when none is given. Without one, a given value is checked like a list entry\n * and kept, and an absent one is empty: the runtime source supplies it.\n */\nfunction parseDefaultLocale(\n field: string,\n input: string | undefined,\n locales: readonly string[],\n problems: string[]\n): string {\n const wanted = input?.trim() ?? ''\n if (locales.length === 0) {\n if (wanted && !LOCALE.test(wanted)) {\n problems.push(invalidLocale(field, wanted))\n return ''\n }\n return wanted\n }\n if (!wanted) return locales[0] ?? ''\n const found = locales.find((locale) => locale.toLowerCase() === wanted.toLowerCase())\n if (!found) {\n problems.push(`${field} is ${quote(wanted)}, which is not one of the locales (${locales.join(', ')})`)\n return ''\n }\n return found\n}\n\nfunction invalidLocale(field: string, locale: string): string {\n return `${field} has an invalid locale ${quote(locale)}, expected a code such as \"en\" or \"pt-BR\"`\n}\n\nfunction hasUnsafeCharacter(value: string): boolean {\n if (/\\s/.test(value)) return true\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code < 0x20 || code === 0x7f) return true\n }\n return false\n}\n\n/**\n * A URL value appended to an error message, or nothing when it holds an `@`:\n * a value the parser refused can still carry credentials it never extracted.\n */\nfunction echoUrl(raw: string): string {\n return raw.includes('@') ? '' : `: ${quote(raw)}`\n}\n\n/** A value quoted for an error message, cut short so a pasted blob stays readable. */\nfunction quote(value: string): string {\n return JSON.stringify(value.length > 120 ? `${value.slice(0, 120)}...` : value)\n}\n","import type { Client, Market, SiteConfig } from 'lynkow'\n\n/**\n * The site's language detection settings, as its configuration returns them.\n * Only `enabled` is set per site. The order (`['cookie', 'browser']`), the\n * cookie name (`_lkw_lang`) and its lifetime (365 days) are fixed by Lynkow.\n */\nexport type SiteLocalesDetection = SiteConfig['i18n']['detection']\n\n/** What the site's language settings said at one read. */\nexport interface SiteLocalesSnapshot {\n /** The locales the site serves, in the order the site lists them. */\n readonly locales: readonly string[]\n /** The site's default locale. */\n readonly defaultLocale: string\n /**\n * The writing direction of each locale, keyed by locale code. A locale the\n * site does not give a direction is `'ltr'`.\n */\n readonly directions: Readonly<Record<string, 'ltr' | 'rtl'>>\n /** The site's language detection settings. */\n readonly detection: SiteLocalesDetection\n /**\n * Always an empty list: language detection no longer reads markets.\n *\n * @deprecated Read the site's markets with `lynkow.markets.list()` when you\n * need them. This field will be dropped in a future minor.\n */\n readonly markets?: readonly Market[]\n}\n\n/** Options of {@link createSiteLocales}. */\nexport interface SiteLocalesOptions {\n /**\n * Returns a Lynkow client, the default locale's when called with no\n * argument: typically the function `createClients(config)` returns. The\n * source calls it with no argument, and before its first load that function\n * returns a client naming no locale when the configuration has neither a\n * static list nor a default, so the API answers the site config read in the\n * site's default locale.\n */\n client: (locale?: string) => Client\n /**\n * How long a read stays fresh, in milliseconds. Defaults to `60_000`. `0`\n * reads the site on every call that is not already waiting for a read.\n */\n ttlMs?: number\n}\n\n/**\n * The site's languages, read from Lynkow at runtime and kept in memory.\n *\n * One instance is shared by everything the process serves: concurrent callers\n * share a single read, and a read stays fresh for `ttlMs`.\n */\nexport interface SiteLocales {\n /**\n * The site's languages. Returns the kept value while it is fresh, and reads\n * the site otherwise. When the read fails and a value was loaded before,\n * that last good value is returned and the site is not read again before\n * another `ttlMs` has passed.\n *\n * @throws The read's error, only when the read fails and nothing was ever\n * loaded. The next call reads again.\n */\n get(): Promise<SiteLocalesSnapshot>\n\n /**\n * The last good value, synchronously. When it is no longer fresh, a read\n * starts in the background and a later call sees its result; a failure of\n * that read is swallowed and the last good value is kept.\n *\n * @throws {Error} When nothing was ever loaded: await {@link get} first.\n */\n current(): SiteLocalesSnapshot\n\n /**\n * Marks the kept value as stale, so the next {@link get} reads the site,\n * for instance after the site's language settings changed. The last good\n * value is kept as the fallback if that read fails.\n */\n invalidate(): void\n}\n\n/**\n * A runtime source of the site's languages: the locales it serves, its default\n * locale, each locale's writing direction and its detection settings, read\n * from the site's configuration instead of being frozen at build time.\n *\n * Pass it to `createLocalePaths` so the locale helpers follow the site. A\n * static locale list in the configuration still wins over it.\n *\n * @throws {RangeError} When `ttlMs` is not a finite number of at least 0.\n *\n * @example\n * ```ts\n * import { createClients, createLocalePaths, createSiteLocales } from '@lynkow/next'\n *\n * // Declared before the clients it reads the site through, and passed to\n * // them: without a static locale list, `createClients(config)` alone throws.\n * // The arrow reads `lynkow` only when the source is asked, so the two are\n * // wired without a cycle.\n * export const siteLocales = createSiteLocales({\n * client: (locale) => lynkow(locale),\n * ttlMs: 60_000,\n * })\n * export const lynkow = createClients(config, { siteLocales })\n * export const paths = createLocalePaths(config, siteLocales)\n * ```\n */\nexport function createSiteLocales({ client, ttlMs = 60_000 }: SiteLocalesOptions): SiteLocales {\n if (typeof ttlMs !== 'number' || !Number.isFinite(ttlMs) || ttlMs < 0) {\n throw new RangeError(`ttlMs must be a finite number of at least 0, got ${String(ttlMs)}`)\n }\n\n let snapshot: SiteLocalesSnapshot | null = null\n /** When the kept value was last confirmed, or null when it must be read again. */\n let checkedAt: number | null = null\n /** Bumped by `invalidate()`, so a read started before it cannot count as fresh. */\n let generation = 0\n let inFlight: Promise<SiteLocalesSnapshot> | null = null\n\n function isFresh(): boolean {\n return checkedAt !== null && Date.now() - checkedAt < ttlMs\n }\n\n function refresh(): Promise<SiteLocalesSnapshot> {\n if (inFlight) return inFlight\n\n const started = generation\n // Started from a resolved promise, so a client that throws synchronously\n // rejects this read instead of escaping it, and the handlers below always\n // run after `inFlight` is assigned.\n const attempt: Promise<SiteLocalesSnapshot> = Promise.resolve()\n .then(() => client().site.getConfig())\n .then(toSnapshot)\n .then(\n (next) => {\n if (inFlight === attempt) inFlight = null\n // A read started before invalidate() never counts as fresh, and only\n // fills the fallback when nothing was loaded at all.\n if (started === generation) {\n snapshot = next\n checkedAt = Date.now()\n } else if (snapshot === null) {\n snapshot = next\n }\n return next\n },\n (error: unknown) => {\n if (inFlight === attempt) inFlight = null\n if (snapshot === null) throw error\n // Serve the last good value, and wait another ttlMs before asking a\n // failing API again.\n if (started === generation) checkedAt = Date.now()\n return snapshot\n }\n )\n inFlight = attempt\n return attempt\n }\n\n return {\n get() {\n if (snapshot && isFresh()) return Promise.resolve(snapshot)\n return refresh()\n },\n\n current() {\n if (!snapshot) {\n throw new Error(\n 'The site locales have not been loaded yet: await siteLocales.get() before reading them synchronously'\n )\n }\n if (!isFresh()) refresh().catch(() => {})\n return snapshot\n },\n\n invalidate() {\n generation += 1\n checkedAt = null\n inFlight = null\n },\n }\n}\n\n/** The deprecated `markets` field: always empty. */\nconst NO_MARKETS: readonly Market[] = Object.freeze([])\n\n/** The part of a site configuration the source keeps, checked for shape. */\nfunction toSnapshot(config: SiteConfig): SiteLocalesSnapshot {\n const { enabledLocales, defaultLocale, i18n } = config\n if (\n !Array.isArray(enabledLocales) ||\n enabledLocales.length === 0 ||\n typeof defaultLocale !== 'string' ||\n defaultLocale.length === 0\n ) {\n throw new Error('The site configuration carries no usable locale list or default locale')\n }\n\n const locales: readonly string[] = Object.freeze([...enabledLocales])\n const directions: Record<string, 'ltr' | 'rtl'> = {}\n for (const info of i18n.locales) directions[info.code] = info.direction ?? 'ltr'\n for (const locale of locales) directions[locale] ??= 'ltr'\n\n return Object.freeze({\n locales,\n defaultLocale,\n directions: Object.freeze(directions),\n detection: i18n.detection,\n markets: NO_MARKETS,\n })\n}\n","import {\n resolveConfig as resolveShared,\n type LynkowNextConfig,\n type LynkowNextConfigInput,\n type LynkowNextConfigLabels,\n} from '../../lynkow-next/src/config.js'\nimport {\n createSiteLocales as createSharedSiteLocales,\n type SiteLocales,\n type SiteLocalesOptions,\n} from '../../lynkow-next/src/site-locales.js'\n\n/**\n * Validates a configuration and fills in its defaults: `siteId` (a UUID) and\n * `siteUrl` (an origin) are required, `apiUrl` defaults to the Lynkow API, and\n * `locales` with `defaultLocale` are an optional static override of the site's\n * languages, which are otherwise read at runtime through `createSiteLocales`.\n *\n * The adapter reads no environment variable: the application reads its own,\n * with literal `import.meta.env.PUBLIC_*` accesses Vite can inline, and passes\n * the values here. Everything in the result is public, since it reaches the\n * browser. A server secret never belongs in it.\n *\n * @param input - The values, typically read from the application's environment\n * @param labels - Optional names for the fields in error messages, such as\n * `{ siteId: 'PUBLIC_LYNKOW_SITE_ID' }`\n * @throws {TypeError} Listing every problem found, one per line\n * @example\n * export const config = resolveConfig(\n * {\n * siteId: import.meta.env.PUBLIC_LYNKOW_SITE_ID,\n * siteUrl: import.meta.env.PUBLIC_SITE_URL,\n * locales: import.meta.env.PUBLIC_LOCALES,\n * },\n * { siteId: 'PUBLIC_LYNKOW_SITE_ID', siteUrl: 'PUBLIC_SITE_URL', locales: 'PUBLIC_LOCALES' }\n * )\n */\nexport function resolveConfig(\n input: LynkowNextConfigInput,\n labels: LynkowNextConfigLabels = {}\n): LynkowNextConfig {\n return resolveShared(input, labels)\n}\n\n/**\n * A runtime source of the site's languages: the locales it serves, its default\n * locale, each locale's writing direction and its detection settings, read from\n * the site's configuration and kept for `ttlMs` (a minute by default), so a\n * language enabled in the admin reaches the site without a rebuild.\n *\n * Declare it before the clients it reads the site through, and pass it to\n * them; the arrow reads `lynkow` only when the source is first asked, so the\n * two are wired without a cycle.\n *\n * @throws {RangeError} When `ttlMs` is not a finite number of at least 0.\n * @example\n * export const siteLocales = createSiteLocales({ client: (locale) => lynkow(locale) })\n * export const lynkow = createClients(config, { siteLocales })\n */\nexport function createSiteLocales(options: SiteLocalesOptions): SiteLocales {\n return createSharedSiteLocales(options)\n}\n","import type { Client, ClientConfig } from 'lynkow'\nimport { createClients as createSharedClients, type ClientOptions } from '../../lynkow-next/src/clients.js'\nimport type { LynkowNextConfig } from '../../lynkow-next/src/config.js'\nimport type { SiteLocales } from '../../lynkow-next/src/site-locales.js'\nimport { takeHint } from './cache/hint.js'\nimport { lynkowCache, type LynkowCache } from './cache/lynkow-cache.js'\n\nexport type { ClientOptions }\n\n/**\n * Options of {@link createClients}, applied to every client it creates.\n *\n * Declared here in full rather than extending the shared options type, so the\n * published declarations name no type that only a hashed chunk exports.\n */\nexport interface CreateClientsOptions {\n /**\n * The SDK's browser content enhancements, passed as they are to\n * `createClient({ enhancements })`. Set `{ activateScripts: false }` when the\n * page renders CMS HTML on the server: the browser has already run that\n * HTML's inline scripts on page load. Only a client created in the browser\n * uses it.\n */\n enhancements?: ClientConfig['enhancements']\n /**\n * The site's languages read at runtime, from `createSiteLocales`. When the\n * configuration has no static locale list, a locale is checked against the\n * languages this source last loaded, and a call with no locale gets the\n * site's default. Ignored when the configuration has a static list.\n */\n siteLocales?: SiteLocales\n /** The data cache the reads carrying `cached()` go through. Defaults to `lynkowCache`. */\n cache?: LynkowCache\n}\n\n/** Returns the Lynkow client of a locale, the default one when none is given. */\nexport type LynkowClients = (locale?: string, options?: ClientOptions) => Client\n\n/**\n * One Lynkow client per locale, reused across requests, whose reads go through\n * the Astro data cache when they carry `cached()` options.\n *\n * A read passed `cached(tags, revalidate)`, alone or spread into its own\n * options, is served from the cache: keyed on the client's locale, the\n * service and method, and the read's arguments (request headers included),\n * evicted by its tags, fresh for `revalidate` seconds. The hint is removed\n * before the SDK sees the options. A read without it, or with `uncached()`,\n * goes to the API every time. A fresh cache hit never calls the SDK method,\n * so a side effect of the method is skipped too: `site.getConfig` served from\n * the cache does not refresh the client's `availableLocales`. A stale hit\n * calls it in the background, so its side effect lands after that read has\n * returned.\n *\n * The SDK's own cache stays off, and every other rule of these clients is the\n * one `@lynkow/next` applies: FOR READS THAT ARE THE SAME FOR EVERY VISITOR.\n * The clients are shared by every request the process serves, so a buyer's\n * cart or session never goes through them: use `createBuyerClient` from\n * `@lynkow/astro/server`, whose reads are never cached. A locale outside the\n * site's languages throws a `RangeError`; await the site's languages before a\n * locale taken from a URL reaches this function.\n *\n * ```ts\n * const siteLocales = createSiteLocales({ client: (locale) => lynkow(locale) })\n * export const lynkow = createClients(config, { siteLocales })\n * ```\n *\n * @throws {RangeError} From the returned function, when a locale is given that\n * is not a well-formed language tag, or names none of the site's languages\n * once they are known.\n */\nexport function createClients(\n config: LynkowNextConfig,\n { cache = lynkowCache, ...options }: CreateClientsOptions = {}\n): LynkowClients {\n const clients = createSharedClients(config, options)\n // Every key starts with the site this factory reads, so two sites, or one\n // site behind two API origins or publishable keys, never share an entry of\n // a cache they share.\n const site = `${config.siteId}|${config.apiUrl}|${fnv1a(config.publishableKey ?? '')}`\n // Keyed on the client object, so each SDK client gets one wrapper per\n // asked locale spelling, and both die with the client.\n const wrapped = new WeakMap<Client, Map<string, Client>>()\n\n return function lynkow(locale?: string, clientOptions?: ClientOptions) {\n const client = clients(locale, clientOptions)\n // The asked locale is part of the key: a call with none is answered in\n // the site's default, which the client's own locale may not name yet.\n const asked = (locale ?? '').toLowerCase()\n let byAsked = wrapped.get(client)\n if (!byAsked) wrapped.set(client, (byAsked = new Map()))\n let proxy = byAsked.get(asked)\n if (!proxy) {\n proxy = cachingClient(client, () => `${site}|${asked}|${client.locale}`, cache)\n byAsked.set(asked, proxy)\n }\n return proxy\n }\n}\n\n/** A short, stable digest of a string, so a key names a publishable key without holding it. */\nfunction fnv1a(text: string): string {\n let hash = 0x811c9dc5\n for (let i = 0; i < text.length; i++) {\n hash ^= text.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193)\n }\n return (hash >>> 0).toString(16).padStart(8, '0')\n}\n\n/** Whether `object` defines `property` with a getter, on itself or its prototype chain. */\nfunction isAccessor(object: object, property: PropertyKey): boolean {\n for (let current: object | null = object; current; current = Object.getPrototypeOf(current)) {\n const descriptor = Object.getOwnPropertyDescriptor(current, property)\n if (descriptor) return descriptor.get !== undefined\n }\n return false\n}\n\n/**\n * Whether `value` is an SDK service: an instance of a class with methods.\n * Plain data (the frozen `config`, arrays) is not, and is passed through.\n */\nfunction isService(value: object): boolean {\n if (Array.isArray(value)) return false\n for (\n let proto: object | null = Object.getPrototypeOf(value);\n proto && proto !== Object.prototype;\n proto = Object.getPrototypeOf(proto)\n ) {\n for (const name of Object.getOwnPropertyNames(proto)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, name)\n if (name !== 'constructor' && typeof descriptor?.value === 'function') return true\n }\n }\n return false\n}\n\n/**\n * A client whose service reads honour the cache hint. A cache hit returns the\n * stored result without calling the SDK method, so any side effect of that\n * method is skipped too: `site.getConfig` refreshes the client's\n * `availableLocales` only when it actually reaches the API.\n */\nfunction cachingClient(client: Client, prefix: () => string, cache: LynkowCache): Client {\n // Per service object and per name it is read under (`blocks` and its alias\n // `globals` are one object), created once.\n const services = new WeakMap<object, Map<string, object>>()\n return new Proxy(client, {\n get(target, property) {\n const value: unknown = Reflect.get(target, property, target)\n if (typeof value === 'function') return value.bind(target)\n if (typeof value !== 'object' || value === null || typeof property !== 'string') return value\n // A pair already wrapped passed the checks below: look it up first.\n let byName = services.get(value)\n let service = byName?.get(property)\n if (service) return service\n // A getter is re-read on every access (`availableLocales`, `locale`).\n if (isAccessor(target, property) || !isService(value)) return value\n if (!byName) services.set(value, (byName = new Map()))\n service = cachingService(value, () => `${prefix()}|${property}`, cache)\n byName.set(property, service)\n return service\n },\n })\n}\n\nfunction cachingService(service: object, prefix: () => string, cache: LynkowCache): object {\n const methods = new Map<PropertyKey, unknown>()\n return new Proxy(service, {\n get(target, property) {\n const value: unknown = Reflect.get(target, property, target)\n if (typeof value !== 'function' || typeof property !== 'string') return value\n let method = methods.get(property)\n if (!method) {\n const fn = value as (...args: unknown[]) => unknown\n method = function (...args: unknown[]) {\n const { policy, args: stripped } = takeHint(args)\n if (!policy) return fn.apply(target, stripped)\n const argsKey = stableKey(stripped)\n // Arguments with no faithful text form are never cached: two of\n // them could otherwise share an entry.\n if (argsKey === null) return fn.apply(target, stripped)\n return cache.read(`${prefix()}.${property}|${argsKey}`, policy, async () => fn.apply(target, stripped))\n }\n methods.set(property, method)\n }\n return method\n },\n })\n}\n\n/** Thrown inside {@link normalize} on a value with no faithful text form. */\nconst UNKEYABLE = Symbol('unkeyable')\n\n/** How an `undefined` array item is written, distinct from `null`. */\nconst UNDEFINED_ITEM = '\\u0000undefined'\n\n/**\n * A deterministic text form of a read's arguments, or null when one of them\n * has none. Object keys are sorted and `undefined` properties left out; of\n * `fetchOptions` only the headers count, the one part of it that changes the\n * answer. Only strings, finite numbers, booleans, null, arrays, plain objects,\n * `Date` and `Headers` have a text form: anything else (a `Map`, a class\n * instance, a function, a bigint, `NaN`) makes the key null.\n */\nexport function stableKey(value: unknown): string | null {\n try {\n return JSON.stringify(normalize(value)) ?? null\n } catch (error) {\n if (error === UNKEYABLE) return null\n throw error\n }\n}\n\nfunction normalize(value: unknown): unknown {\n switch (typeof value) {\n case 'string':\n case 'boolean':\n return value\n case 'number':\n if (!Number.isFinite(value)) throw UNKEYABLE\n return value\n case 'undefined':\n return undefined\n case 'object':\n break\n default:\n throw UNKEYABLE\n }\n if (value === null) return null\n if (Array.isArray(value)) return value.map((item) => (item === undefined ? UNDEFINED_ITEM : normalize(item)))\n if (typeof Headers !== 'undefined' && value instanceof Headers) return headerList(value)\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) throw UNKEYABLE\n return { $date: value.toISOString() }\n }\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) throw UNKEYABLE\n\n const record = value as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(record).sort()) {\n const item = record[key]\n if (key === 'fetchOptions' && typeof item === 'object' && item !== null) {\n out[key] = fetchOptionsKey(item as RequestInit)\n continue\n }\n const normalized = normalize(item)\n if (normalized !== undefined) out[key] = normalized\n }\n return out\n}\n\n/** The headers of `fetchOptions`, the only part of it that changes the answer. */\nfunction fetchOptionsKey(fetchOptions: RequestInit): unknown {\n if (fetchOptions.headers === undefined) return {}\n let headers: Headers\n try {\n headers = new Headers(fetchOptions.headers)\n } catch {\n throw UNKEYABLE\n }\n return { headers: headerList(headers) }\n}\n\nfunction headerList(headers: Headers): [string, string][] {\n const list: [string, string][] = []\n headers.forEach((value, name) => list.push([name, value]))\n return list.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n}\n","import type { AnalyticsEventType } from 'lynkow'\nimport { trackerGlobal } from './global.js'\n\nexport type { AnalyticsEventType }\n\n/**\n * Sends one custom event through the tracker already on the page.\n *\n * `type` is a CLOSED enum of mechanical interactions, the SDK's\n * `AnalyticsEventType`: there is no free-form event name. A value outside it is\n * a compile error rather than a silently dropped row, since the collector\n * answers `204` to a payload it rejects.\n *\n * Returns `false` when no tracker has loaded, which is never an error: on an\n * `opt-in` site none loads before the visitor accepts analytics. `true` means\n * the event was handed to the tracker, which adds the session id, the visitor\n * id and the timestamp, and drops the event itself when the visitor refused on\n * an `opt-in` or `opt-out` site.\n *\n * The tracker already records pageviews, scroll, clicks, form events and Core\n * Web Vitals. Reach for this only for an interaction that escapes it, such as a\n * form submitted through `fetch` without a real `submit` event.\n */\nexport function trackEvent(type: AnalyticsEventType, data?: Record<string, unknown>): boolean {\n const global = trackerGlobal()\n if (typeof global?.track !== 'function') return false\n\n global.track({\n page_path: window.location.pathname,\n page_url: window.location.href,\n page_title: document.title,\n // A page field in `data` wins; `event_type` never does, as in the SDK's\n // `trackEvent`, so a stray key cannot contradict `type`.\n ...data,\n event_type: type,\n })\n return true\n}\n","import { MediaHelperService } from 'lynkow'\n\n/** Stateless and pure: it only rewrites a URL, so one instance serves every call. */\nconst media = new MediaHelperService()\n\n/** What `next/image` passes to a custom loader. */\nexport interface ImageLoaderParams {\n src: string\n width: number\n quality?: number\n}\n\n/**\n * A `next/image` loader that resizes Lynkow media on the Lynkow CDN.\n *\n * Next's own optimizer downloads the original, resizes it on the app server\n * and caches the result on that server's disk. Lynkow already resizes at the\n * CDN edge, close to the visitor and cached there, so with this loader the app\n * server never touches an image. Everything else about `next/image` stays:\n * lazy loading, `priority`, reserved space, and the srcset Next builds by\n * calling the loader once per candidate width.\n *\n * A relative URL, a file in `/public`, comes back unchanged: Lynkow media is\n * always absolute, and the SDK recognises it by the text of the URL alone, so\n * a local `/sites/logo.png` would otherwise be sent to a resizing endpoint this\n * server does not have. For the same reason an absolute URL on any host that\n * contains `/sites/` or `/avatars/`, even in its query string, is rewritten\n * into a resizing URL on its own host. Any other absolute URL comes back\n * unchanged.\n *\n * Next wants a FILE for a custom loader, so re-export it from one:\n *\n * @example\n * // src/image-loader.ts\n * export { default } from '@lynkow/next/image-loader'\n *\n * // next.config.ts\n * images: { loader: 'custom', loaderFile: './src/image-loader.ts' }\n */\nexport default function lynkowImageLoader({ src, width, quality }: ImageLoaderParams): string {\n if (!/^https?:\\/\\//i.test(src)) return src\n return (\n media.transform(src, {\n w: width,\n // `scale-down` never upscales, so a small original stays small rather than\n // being blown up to the layout's widest candidate.\n fit: 'scale-down',\n // The CDN negotiates the format from `Accept`, so a modern browser gets\n // WebP or AVIF without the application knowing which.\n format: 'auto',\n quality: quality ?? 80,\n }) || src\n )\n}\n\nexport { lynkowImageLoader }\n","import { lynkowImageLoader } from '../../lynkow-next/src/image-loader.js'\n\n/** What {@link imageUrl} takes. */\nexport interface ImageUrlParams {\n src: string\n /** The width to resize to, in pixels. */\n width: number\n /** The encoding quality, 1 to 100. Defaults to 80. */\n quality?: number\n}\n\n/**\n * The URL of a Lynkow image resized on the Lynkow CDN to `width`, never\n * upscaled, in the best format the browser accepts. A relative URL (a file in\n * `public/`) or a URL that is not Lynkow media comes back unchanged.\n */\nexport function imageUrl({ src, width, quality }: ImageUrlParams): string {\n return lynkowImageLoader(quality === undefined ? { src, width } : { src, width, quality })\n}\n\n/**\n * A `srcset` for `src`, one resized candidate per width, ascending, for an\n * `<img srcset sizes>` that lets the browser pick. Empty when `src` is not\n * Lynkow media, since every candidate would then be the same file.\n *\n * @throws {RangeError} When a width is not a positive integer.\n *\n * @example\n * <img src={imageUrl({ src, width: 1280 })} srcset={imageSrcSet(src, [640, 960, 1280])} sizes=\"100vw\" alt=\"\" />\n */\nexport function imageSrcSet(src: string, widths: readonly number[], quality?: number): string {\n for (const width of widths) {\n if (!Number.isInteger(width) || width < 1) {\n throw new RangeError(`imageSrcSet() takes positive integer widths, got ${String(width)}`)\n }\n }\n const sorted = [...new Set(widths)].sort((a, b) => a - b)\n const first = sorted[0]\n if (first === undefined || imageUrl({ src, width: first, quality }) === src) return ''\n return sorted.map((width) => `${imageUrl({ src, width, quality })} ${width}w`).join(', ')\n}\n"]}
@@ -0,0 +1,37 @@
1
+ import { AstroIntegration } from 'astro';
2
+
3
+ /**
4
+ * The server-only variables this package reads from `process.env` at runtime.
5
+ * `astro dev` loads `.env` files into `import.meta.env` only, so without the
6
+ * integration they would be missing in development.
7
+ */
8
+ declare const SERVER_ENV: readonly ["LYNKOW_SERVER_KEY", "LYNKOW_CLIENT_IP_HEADER", "LYNKOW_COUNTRY_HEADERS", "LYNKOW_WEBHOOK_SECRET"];
9
+ /**
10
+ * Copies {@link SERVER_ENV} from `env` into `target`, skipping a name the
11
+ * target already holds: a variable set in the shell wins over a `.env` file,
12
+ * as it does in production.
13
+ *
14
+ * @returns The names copied.
15
+ */
16
+ declare function copyServerEnv(env: Record<string, string | undefined>, target?: Record<string, string | undefined>): string[];
17
+ /**
18
+ * The Lynkow integration for `astro.config.mjs`.
19
+ *
20
+ * In `astro dev`, it copies the server-only Lynkow variables
21
+ * (`LYNKOW_SERVER_KEY`, `LYNKOW_CLIENT_IP_HEADER`, `LYNKOW_COUNTRY_HEADERS`,
22
+ * `LYNKOW_WEBHOOK_SECRET`) from the project's `.env` files into `process.env`,
23
+ * where the buyer client and the revalidation endpoint read them, exactly as
24
+ * a production server started with `node --env-file` has them. The files are
25
+ * those of the mode the server runs in (`astro dev --mode staging` reads
26
+ * `.env.staging`), from Vite's `envDir`. A variable already set in the shell
27
+ * is left as it is. Outside `astro dev` it does nothing.
28
+ *
29
+ * @example
30
+ * // astro.config.mjs
31
+ * import lynkow from '@lynkow/astro/integration'
32
+ *
33
+ * export default defineConfig({ integrations: [lynkow()] })
34
+ */
35
+ declare function lynkow(): AstroIntegration;
36
+
37
+ export { SERVER_ENV, copyServerEnv, lynkow as default };
@@ -0,0 +1,51 @@
1
+ import { createRequire } from 'node:module';
2
+ import { pathToFileURL } from 'node:url';
3
+
4
+ // src/integration.ts
5
+ var SERVER_ENV = [
6
+ "LYNKOW_SERVER_KEY",
7
+ "LYNKOW_CLIENT_IP_HEADER",
8
+ "LYNKOW_COUNTRY_HEADERS",
9
+ "LYNKOW_WEBHOOK_SECRET"
10
+ ];
11
+ function copyServerEnv(env, target = process.env) {
12
+ const copied = [];
13
+ for (const name of SERVER_ENV) {
14
+ const value = env[name];
15
+ if (value === void 0 || value === "" || target[name] !== void 0) continue;
16
+ target[name] = value;
17
+ copied.push(name);
18
+ }
19
+ return copied;
20
+ }
21
+ async function importVite() {
22
+ try {
23
+ const astro = createRequire(import.meta.url).resolve("astro/package.json");
24
+ const vite = createRequire(astro).resolve("vite");
25
+ return await import(pathToFileURL(vite).href);
26
+ } catch {
27
+ return import('vite');
28
+ }
29
+ }
30
+ function lynkow() {
31
+ return {
32
+ name: "@lynkow/astro",
33
+ hooks: {
34
+ "astro:config:setup": ({ command, updateConfig }) => {
35
+ if (command !== "dev") return;
36
+ const serverEnv = {
37
+ name: "@lynkow/astro:server-env",
38
+ async configResolved({ mode, envDir }) {
39
+ const vite = await importVite();
40
+ copyServerEnv(vite.loadEnv(mode, envDir, ""));
41
+ }
42
+ };
43
+ updateConfig({ vite: { plugins: [serverEnv] } });
44
+ }
45
+ }
46
+ };
47
+ }
48
+
49
+ export { SERVER_ENV, copyServerEnv, lynkow as default };
50
+ //# sourceMappingURL=integration.js.map
51
+ //# sourceMappingURL=integration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/integration.ts"],"names":[],"mappings":";;;;AAUO,IAAM,UAAA,GAAa;AAAA,EACxB,mBAAA;AAAA,EACA,yBAAA;AAAA,EACA,wBAAA;AAAA,EACA;AACF;AASO,SAAS,aAAA,CACd,GAAA,EACA,MAAA,GAA6C,OAAA,CAAQ,GAAA,EAC3C;AACV,EAAA,MAAM,SAAmB,EAAC;AAC1B,EAAA,KAAA,MAAW,QAAQ,UAAA,EAAY;AAC7B,IAAA,MAAM,KAAA,GAAQ,IAAI,IAAI,CAAA;AACtB,IAAA,IAAI,UAAU,MAAA,IAAa,KAAA,KAAU,MAAM,MAAA,CAAO,IAAI,MAAM,MAAA,EAAW;AACvE,IAAA,MAAA,CAAO,IAAI,CAAA,GAAI,KAAA;AACf,IAAA,MAAA,CAAO,KAAK,IAAI,CAAA;AAAA,EAClB;AACA,EAAA,OAAO,MAAA;AACT;AAQA,eAAe,UAAA,GAAmD;AAChE,EAAA,IAAI;AACF,IAAA,MAAM,QAAQ,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA,CAAE,QAAQ,oBAAoB,CAAA;AACzE,IAAA,MAAM,IAAA,GAAO,aAAA,CAAc,KAAK,CAAA,CAAE,QAAQ,MAAM,CAAA;AAChD,IAAA,OAAQ,MAAM,OAAO,aAAA,CAAc,IAAI,CAAA,CAAE,IAAA,CAAA;AAAA,EAC3C,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,OAAO,MAAM,CAAA;AAAA,EACtB;AACF;AAoBe,SAAR,MAAA,GAA4C;AACjD,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,eAAA;AAAA,IACN,KAAA,EAAO;AAAA,MACL,oBAAA,EAAsB,CAAC,EAAE,OAAA,EAAS,cAAa,KAAM;AACnD,QAAA,IAAI,YAAY,KAAA,EAAO;AAIvB,QAAA,MAAM,SAAA,GAAoB;AAAA,UACxB,IAAA,EAAM,0BAAA;AAAA,UACN,MAAM,cAAA,CAAe,EAAE,IAAA,EAAM,QAAO,EAAG;AAGrC,YAAA,MAAM,IAAA,GAAO,MAAM,UAAA,EAAW;AAC9B,YAAA,aAAA,CAAc,IAAA,CAAK,OAAA,CAAQ,IAAA,EAAM,MAAA,EAAQ,EAAE,CAAC,CAAA;AAAA,UAC9C;AAAA,SACF;AACA,QAAA,YAAA,CAAa,EAAE,MAAM,EAAE,OAAA,EAAS,CAAC,SAAS,CAAA,IAAK,CAAA;AAAA,MACjD;AAAA;AACF,GACF;AACF","file":"integration.js","sourcesContent":["import { createRequire } from 'node:module'\nimport { pathToFileURL } from 'node:url'\nimport type { AstroIntegration } from 'astro'\nimport type { loadEnv, Plugin } from 'vite'\n\n/**\n * The server-only variables this package reads from `process.env` at runtime.\n * `astro dev` loads `.env` files into `import.meta.env` only, so without the\n * integration they would be missing in development.\n */\nexport const SERVER_ENV = [\n 'LYNKOW_SERVER_KEY',\n 'LYNKOW_CLIENT_IP_HEADER',\n 'LYNKOW_COUNTRY_HEADERS',\n 'LYNKOW_WEBHOOK_SECRET',\n] as const\n\n/**\n * Copies {@link SERVER_ENV} from `env` into `target`, skipping a name the\n * target already holds: a variable set in the shell wins over a `.env` file,\n * as it does in production.\n *\n * @returns The names copied.\n */\nexport function copyServerEnv(\n env: Record<string, string | undefined>,\n target: Record<string, string | undefined> = process.env\n): string[] {\n const copied: string[] = []\n for (const name of SERVER_ENV) {\n const value = env[name]\n if (value === undefined || value === '' || target[name] !== undefined) continue\n target[name] = value\n copied.push(name)\n }\n return copied\n}\n\n/**\n * Vite as Astro loads it. Vite is a dependency of Astro, not of this package,\n * so it is resolved from Astro's own location: a strict `node_modules` layout\n * or Yarn Plug'n'Play does not let this package import it by name. The bare\n * import remains the fallback for a layout where that resolution fails.\n */\nasync function importVite(): Promise<{ loadEnv: typeof loadEnv }> {\n try {\n const astro = createRequire(import.meta.url).resolve('astro/package.json')\n const vite = createRequire(astro).resolve('vite')\n return (await import(pathToFileURL(vite).href)) as { loadEnv: typeof loadEnv }\n } catch {\n return import('vite')\n }\n}\n\n/**\n * The Lynkow integration for `astro.config.mjs`.\n *\n * In `astro dev`, it copies the server-only Lynkow variables\n * (`LYNKOW_SERVER_KEY`, `LYNKOW_CLIENT_IP_HEADER`, `LYNKOW_COUNTRY_HEADERS`,\n * `LYNKOW_WEBHOOK_SECRET`) from the project's `.env` files into `process.env`,\n * where the buyer client and the revalidation endpoint read them, exactly as\n * a production server started with `node --env-file` has them. The files are\n * those of the mode the server runs in (`astro dev --mode staging` reads\n * `.env.staging`), from Vite's `envDir`. A variable already set in the shell\n * is left as it is. Outside `astro dev` it does nothing.\n *\n * @example\n * // astro.config.mjs\n * import lynkow from '@lynkow/astro/integration'\n *\n * export default defineConfig({ integrations: [lynkow()] })\n */\nexport default function lynkow(): AstroIntegration {\n return {\n name: '@lynkow/astro',\n hooks: {\n 'astro:config:setup': ({ command, updateConfig }) => {\n if (command !== 'dev') return\n // The mode reaches Vite's resolved config, not this hook. Vite resolves\n // its config before it loads any module of the site, so the variables\n // are in place before the first read.\n const serverEnv: Plugin = {\n name: '@lynkow/astro:server-env',\n async configResolved({ mode, envDir }) {\n // Vite's loader reads the `.env` files in the order and with the\n // precedence `import.meta.env` uses.\n const vite = await importVite()\n copyServerEnv(vite.loadEnv(mode, envDir, ''))\n },\n }\n updateConfig({ vite: { plugins: [serverEnv] } })\n },\n },\n }\n}\n"]}