@lynkow/astro 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +29 -0
  2. package/README.md +393 -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-USZSRPT5.js +119 -0
  10. package/dist/chunk-USZSRPT5.js.map +1 -0
  11. package/dist/chunk-VVRAYLFD.js +329 -0
  12. package/dist/chunk-VVRAYLFD.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 +354 -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-B5WLYsmk.d.ts +154 -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-t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AAA,CAAK,MAAA,CAAO,MAAM,CAAA;AAChC,EAAA,OAAO,UAAU,EAAA,GACb,EAAE,UAAU,IAAA,EAAM,MAAA,EAAQ,IAAG,GAC7B,EAAE,UAAU,IAAA,CAAK,KAAA,CAAM,GAAG,KAAK,CAAA,EAAG,QAAQ,IAAA,CAAK,KAAA,CAAM,KAAK,CAAA,EAAE;AAClE","file":"chunk-USZSRPT5.js","sourcesContent":["import type { LynkowNextConfig } from './config.js'\nimport type { SiteLocales } from './site-locales.js'\n\n/** An href that names its own scheme (`https:`, `mailto:`), or a protocol-relative one. */\nexport const ABSOLUTE_HREF = /^([a-z][a-z0-9+.-]*:|\\/\\/)/i\n\n/**\n * The one place a public path gets its locale, bound to a configuration.\n *\n * Every localized path of a site goes through {@link LocalePaths.localePath}\n * or {@link LocalePaths.fromApiPath}. That is what keeps every localized path\n * consistent with the locale rule: a path built by hand as `/${locale}/...`\n * puts a segment in front of a default-locale path that is served without\n * one.\n *\n * The locales and the default locale are read at each use: from the static\n * list of the configuration when it has one, otherwise from the runtime\n * source given to {@link createLocalePaths}, so the helpers follow the site's\n * language settings as they change.\n */\nexport interface LocalePaths {\n /**\n * The configured locales: the configuration's static list when it has one,\n * otherwise the runtime source's current list.\n */\n readonly locales: readonly string[]\n /**\n * The default locale: the configuration's when it has a static list,\n * otherwise the runtime source's current one.\n */\n readonly defaultLocale: string\n\n /** The configured spelling of a locale, matched case-insensitively, or null. */\n toLocale(value: string | null | undefined): string | null\n\n /** Whether a value names a configured locale, in any case. */\n isLocale(value: string | null | undefined): value is string\n\n /**\n * The locale a path belongs to. A path whose first segment names a locale\n * belongs to it. Any other path belongs to the default locale, which is\n * served unprefixed. That includes paths that are not pages at all, such as\n * `/_next/...`, so a caller that routes requests filters those first.\n */\n localeFromPath(pathname: string): string | null\n\n /**\n * The public path of `path` in `locale`: `/fr/blog`, or `/blog` for the\n * default locale, which is never prefixed. The locale segment is written\n * lowercased, as the API writes it. A query or fragment is kept. A leading\n * run of slashes or backslashes collapses to one, so `//evil.example` stays a\n * path once a default locale is stripped. Dot segments are left as written:\n * `/.//evil.example` resolves to `//evil.example` in `new URL()`, so a caller\n * that resolves the result checks the resolved path, as the proxy does.\n *\n * A default-locale path whose first segment names another configured locale\n * keeps its locale segment: `/en/fr/x` rather than `/fr/x`, which would be\n * read as a French page. A first segment that names no configured locale\n * does not trigger it, so `/de/x` stays as it is on a site without `de`.\n *\n * @throws {RangeError} When `locale` is not a configured locale.\n */\n localePath(locale: string, path?: string): string\n\n /**\n * The public path of a path the API returned.\n *\n * The API serves the site's default locale unprefixed and prefixes a path\n * in any other locale with that locale (`/fr/blog/article`), which is kept.\n * A path with no locale segment, a default-locale path or any path on a\n * single-locale site, belongs to `locale`, so pass the locale of the row the\n * path came from. A path that still carries the default locale's own prefix\n * (`/en/blog/post`, a stored or older form) is mapped to its unprefixed URL\n * (`/blog/post`). Anything that is not a root-relative path is returned\n * unchanged.\n *\n * The API never returns a protocol-relative URL, so a leading run of slashes\n * or backslashes collapses to one before the locale is read: on a\n * single-locale site, a blog prefix of `/evil.example` makes an article path\n * `//evil.example/post`, which stays `/evil.example/post` on this site.\n */\n fromApiPath(path: string, locale: string): string\n\n /**\n * An href from CMS content, made to lead to `locale`.\n *\n * Navigation blocks store locale-agnostic hrefs (`/blog`, `/contact`), which\n * is right for an editor, so the locale is added at render: without it every\n * internal link goes through a redirect. An href that already names a locale\n * keeps it, normalized like {@link fromApiPath}. Absolute URLs, `mailto:` and\n * `tel:` links, anchors, query-only and relative hrefs are left untouched.\n */\n localizeHref(href: string, locale: string): string\n\n /**\n * The locale a link leads to on this site, or null when it leads elsewhere:\n * another origin, a `mailto:`, an anchor, a relative path. An absolute URL\n * on the site's own origin counts as this site, which catches an editor's\n * pasted `https://<site>/fr/...`.\n */\n hrefLocale(href: string): string | null\n\n /**\n * The best match between an `Accept-Language` header and the configured\n * locales, falling back to the default locale rather than to a 404. A\n * language the header marks `q=0` is one the browser refuses, so it is\n * never the match.\n */\n negotiateLocale(acceptLanguage: string | null | undefined): string\n\n /** `path` on the site's origin. */\n absoluteUrl(path: string): string\n}\n\n/**\n * Binds the locale path helpers to a configuration from {@link resolveConfig}.\n *\n * `source` supplies the locales and the default locale at runtime, through\n * {@link SiteLocales.current}, which must have been loaded once with\n * {@link SiteLocales.get}. A configuration with a non-empty static locale list\n * wins: its list and default locale are used and the source is never read.\n * The default locale is always served unprefixed.\n *\n * @throws {Error} When the configuration has no static locale list and no\n * source is given, since nothing would supply the locales.\n */\nexport function createLocalePaths(config: LynkowNextConfig, source?: SiteLocales): LocalePaths {\n const { siteUrl } = config\n if (config.locales.length === 0 && !source) {\n throw new Error(\n 'createLocalePaths has no locales: pass a static `locales` list to resolveConfig, or the runtime source from createSiteLocales'\n )\n }\n const live = config.locales.length > 0 ? undefined : source\n const site = new URL(siteUrl)\n\n // Rebuilt only when the list itself changes, not on every read.\n let keyed: readonly string[] | null = null\n let byKey: ReadonlyMap<string, string> = new Map()\n\n /** The locales and default locale in force now, with the case-insensitive index. */\n function current(): {\n locales: readonly string[]\n defaultLocale: string\n byKey: ReadonlyMap<string, string>\n } {\n const { locales, defaultLocale } = live ? live.current() : config\n if (locales !== keyed) {\n byKey = new Map(locales.map((locale) => [locale.toLowerCase(), locale]))\n keyed = locales\n }\n return { locales, defaultLocale, byKey }\n }\n\n function toLocale(value: string | null | undefined): string | null {\n return value ? (current().byKey.get(value.toLowerCase()) ?? null) : null\n }\n\n /** The locale named by the first segment of a pathname, and what follows it. */\n function leadingLocale(pathname: string): { locale: string; rest: string } | null {\n const end = pathname.indexOf('/', 1)\n const locale = toLocale(end === -1 ? pathname.slice(1) : pathname.slice(1, end))\n if (!locale) return null\n return { locale, rest: end === -1 ? '/' : pathname.slice(end) }\n }\n\n function localeFromPath(pathname: string): string | null {\n return leadingLocale(pathname)?.locale ?? current().defaultLocale\n }\n\n function localePath(locale: string, path = '/'): string {\n const { locales, defaultLocale } = current()\n const canonical = toLocale(locale)\n if (!canonical) {\n throw new RangeError(\n `${JSON.stringify(locale)} is not one of the configured locales (${locales.join(', ')})`\n )\n }\n const { pathname: raw, suffix } = splitSuffix(path.startsWith('/') ? path : `/${path}`)\n const pathname = onSite(raw)\n if (canonical === defaultLocale) {\n // Stripping the segment would turn `/en/fr/x` into `/fr/x`, a French\n // page, so a path that starts with another locale keeps it.\n const leading = leadingLocale(pathname)\n if (!leading || leading.locale === defaultLocale) return pathname + suffix\n }\n const segment = `/${canonical.toLowerCase()}`\n return (pathname === '/' ? segment : segment + pathname) + suffix\n }\n\n function fromApiPath(path: string, locale: string): string {\n if (!path.startsWith('/')) return path\n const { pathname: raw, suffix } = splitSuffix(path)\n const pathname = onSite(raw)\n const leading = leadingLocale(pathname)\n return leading\n ? localePath(leading.locale, leading.rest + suffix)\n : localePath(locale, pathname + suffix)\n }\n\n function localizeHref(href: string, locale: string): string {\n if (!href || ABSOLUTE_HREF.test(href) || !href.startsWith('/')) return href\n return fromApiPath(href, locale)\n }\n\n function hrefLocale(href: string): string | null {\n if (!ABSOLUTE_HREF.test(href) && !href.startsWith('/')) return null\n try {\n const url = new URL(href, site)\n return url.origin === site.origin ? localeFromPath(url.pathname) : null\n } catch {\n return null\n }\n }\n\n function negotiateLocale(acceptLanguage: string | null | undefined): string {\n const { locales, defaultLocale, byKey } = current()\n if (!acceptLanguage) return defaultLocale\n\n const ranked = acceptLanguage\n .split(',')\n .map((part) => {\n const [tag = '', ...params] = part.trim().split(';')\n const q = params.find((param) => param.trim().startsWith('q='))\n return { tag: tag.trim().toLowerCase(), q: q ? Number.parseFloat(q.split('=')[1] ?? '') : 1 }\n })\n // `q=0` means \"not acceptable\", so it never matches. A q that is not a\n // number is dropped too: `NaN > 0` is false.\n .filter((entry) => entry.tag.length > 0 && entry.q > 0)\n .sort((a, b) => b.q - a.q)\n\n for (const { tag } of ranked) {\n const exact = byKey.get(tag)\n if (exact) return exact\n\n const base = tag.split('-')[0]\n const partial = locales.find((code) => code.toLowerCase().split('-')[0] === base)\n if (partial) return partial\n }\n\n return defaultLocale\n }\n\n function absoluteUrl(path: string): string {\n return `${siteUrl}${path.startsWith('/') ? path : `/${path}`}`\n }\n\n return {\n get locales() {\n return current().locales\n },\n get defaultLocale() {\n return current().defaultLocale\n },\n toLocale,\n isLocale: (value): value is string => toLocale(value) !== null,\n localeFromPath,\n localePath,\n fromApiPath,\n localizeHref,\n hrefLocale,\n negotiateLocale,\n absoluteUrl,\n }\n}\n\n/**\n * A root-relative pathname that a browser cannot read as another host. The URL\n * parser drops tabs and newlines anywhere and reads a backslash as a slash, so\n * `/\\t/evil.example` and `/\\evil.example` are both `//evil.example` to it.\n */\nfunction onSite(pathname: string): string {\n return pathname.replace(/[\\t\\n\\r]/g, '').replace(/^[/\\\\]+/, '/')\n}\n\n/** A path split before its query string or fragment. */\nfunction splitSuffix(path: string): { pathname: string; suffix: string } {\n const index = path.search(/[?#]/)\n return index === -1\n ? { pathname: path, suffix: '' }\n : { pathname: path.slice(0, index), suffix: path.slice(index) }\n}\n"]}
@@ -0,0 +1,329 @@
1
+ import { createLocalePaths } from './chunk-USZSRPT5.js';
2
+ import { createClient } from 'lynkow';
3
+
4
+ // ../lynkow-next/src/cache.ts
5
+ var REVALIDATE = {
6
+ /** Site config and global blocks: header, footer, branding. */
7
+ site: 3600,
8
+ /** Structural pages driven by site blocks. */
9
+ page: 300,
10
+ /** Blog articles, categories, tags. */
11
+ blog: 300,
12
+ /** Approved reviews. */
13
+ reviews: 900,
14
+ /** Form schemas. */
15
+ forms: 3600,
16
+ /** The cookie consent banner configuration. */
17
+ consent: 3600,
18
+ /** sitemap.xml, robots.txt, llms.txt. */
19
+ seo: 3600,
20
+ /** The path table used for static generation and redirect matching. */
21
+ paths: 600,
22
+ /**
23
+ * One search result page.
24
+ *
25
+ * Short on purpose. Next keys its fetch cache on the full URL, so every
26
+ * distinct query is its own entry and a long ceiling would pin a large,
27
+ * unbounded set of them. The tag is what actually keeps results honest: a
28
+ * publish evicts every cached query at once.
29
+ */
30
+ search: 60
31
+ };
32
+ var TAGS = {
33
+ site: "lynkow:site",
34
+ pages: "lynkow:pages",
35
+ page: (slug) => `lynkow:page:${slug}`,
36
+ contents: "lynkow:contents",
37
+ content: (slug) => `lynkow:content:${slug}`,
38
+ categories: "lynkow:categories",
39
+ tags: "lynkow:tags",
40
+ reviews: "lynkow:reviews",
41
+ forms: "lynkow:forms",
42
+ form: (slug) => `lynkow:form:${slug}`,
43
+ consent: "lynkow:consent",
44
+ seo: "lynkow:seo",
45
+ paths: "lynkow:paths",
46
+ search: "lynkow:search"
47
+ };
48
+ function uncached() {
49
+ return { fetchOptions: { cache: "no-store" } };
50
+ }
51
+
52
+ // src/cache/policy.ts
53
+ var REVALIDATE2 = REVALIDATE;
54
+ var TAGS2 = TAGS;
55
+
56
+ // src/cache/hint.ts
57
+ var CACHE_HINT = /* @__PURE__ */ Symbol.for("@lynkow/astro/cache-hint");
58
+ function cached(tags, revalidate) {
59
+ if (!Array.isArray(tags) || tags.some((tag) => typeof tag !== "string" || tag === "")) {
60
+ throw new TypeError("cached() takes an array of non-empty tag strings");
61
+ }
62
+ if (typeof revalidate !== "number" || !Number.isFinite(revalidate) || revalidate < 0) {
63
+ throw new RangeError(`cached() takes a number of seconds of at least 0, got ${String(revalidate)}`);
64
+ }
65
+ const options = { [CACHE_HINT]: { tags: [...tags], revalidate } };
66
+ return options;
67
+ }
68
+ function uncached2() {
69
+ const options = { [CACHE_HINT]: null };
70
+ return options;
71
+ }
72
+ function isPlainObject(value) {
73
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
74
+ const proto = Object.getPrototypeOf(value);
75
+ return proto === Object.prototype || proto === null;
76
+ }
77
+ function takeHint(args) {
78
+ let policy;
79
+ const stripped = args.map((arg) => {
80
+ if (!isPlainObject(arg) || !Object.prototype.hasOwnProperty.call(arg, CACHE_HINT)) return arg;
81
+ const { [CACHE_HINT]: hint, ...rest } = arg;
82
+ policy = hint ?? null;
83
+ return rest;
84
+ });
85
+ return { policy, args: stripped };
86
+ }
87
+
88
+ // src/cache/store.ts
89
+ var DEFAULT_MAX_ENTRIES = 1e3;
90
+ function createMemoryStore({ max = DEFAULT_MAX_ENTRIES } = {}) {
91
+ if (!Number.isInteger(max) || max < 1) {
92
+ throw new RangeError(`max must be a positive integer, got ${String(max)}`);
93
+ }
94
+ const entries = /* @__PURE__ */ new Map();
95
+ const byTag = /* @__PURE__ */ new Map();
96
+ function unindex(key, entry) {
97
+ for (const tag of entry.tags) {
98
+ const keys = byTag.get(tag);
99
+ if (!keys) continue;
100
+ keys.delete(key);
101
+ if (keys.size === 0) byTag.delete(tag);
102
+ }
103
+ }
104
+ function remove(key) {
105
+ const entry = entries.get(key);
106
+ if (!entry) return;
107
+ entries.delete(key);
108
+ unindex(key, entry);
109
+ }
110
+ return {
111
+ get(key) {
112
+ const entry = entries.get(key);
113
+ if (!entry) return void 0;
114
+ entries.delete(key);
115
+ entries.set(key, entry);
116
+ return entry;
117
+ },
118
+ set(key, entry) {
119
+ remove(key);
120
+ entries.set(key, entry);
121
+ for (const tag of entry.tags) {
122
+ let keys = byTag.get(tag);
123
+ if (!keys) byTag.set(tag, keys = /* @__PURE__ */ new Set());
124
+ keys.add(key);
125
+ }
126
+ while (entries.size > max) {
127
+ const oldest = entries.keys().next();
128
+ if (oldest.done) break;
129
+ remove(oldest.value);
130
+ }
131
+ },
132
+ deleteTags(tags) {
133
+ for (const tag of tags) {
134
+ const keys = byTag.get(tag);
135
+ if (!keys) continue;
136
+ for (const key of [...keys]) remove(key);
137
+ }
138
+ }
139
+ };
140
+ }
141
+
142
+ // src/cache/lynkow-cache.ts
143
+ var DEFAULT_STALE_WHILE_REVALIDATE = 86400;
144
+ var REFRESH_RETRY_BACKOFF_MS = 3e4;
145
+ var STORE_WRITE_WAIT_MS = 5e3;
146
+ function hand(loaded) {
147
+ return loaded.detached ? structuredClone(loaded.value) : loaded.value;
148
+ }
149
+ async function settlesWithin(promise, ms) {
150
+ let timer;
151
+ const elapsed = new Promise((resolve) => {
152
+ timer = setTimeout(resolve, ms, false);
153
+ });
154
+ try {
155
+ return await Promise.race([promise.then(() => true), elapsed]);
156
+ } finally {
157
+ clearTimeout(timer);
158
+ }
159
+ }
160
+ function createLynkowCache({
161
+ max,
162
+ store,
163
+ staleWhileRevalidate = DEFAULT_STALE_WHILE_REVALIDATE
164
+ } = {}) {
165
+ if (!Number.isFinite(staleWhileRevalidate) || staleWhileRevalidate < 0) {
166
+ throw new RangeError(
167
+ `staleWhileRevalidate must be a number of seconds of at least 0, got ${String(staleWhileRevalidate)}`
168
+ );
169
+ }
170
+ const entries = store ?? createMemoryStore(max === void 0 ? {} : { max });
171
+ const flights = /* @__PURE__ */ new Map();
172
+ const retryAt = /* @__PURE__ */ new Map();
173
+ function fly(key, policy, load) {
174
+ const running = flights.get(key);
175
+ if (running) return running;
176
+ const tags = [...policy.tags];
177
+ async function run() {
178
+ await void 0;
179
+ try {
180
+ const value = await load();
181
+ retryAt.delete(key);
182
+ let detached;
183
+ try {
184
+ detached = structuredClone(value);
185
+ } catch {
186
+ return { value, detached: false };
187
+ }
188
+ if (!flight.cancelled) {
189
+ try {
190
+ flight.storing = Promise.resolve(
191
+ entries.set(key, {
192
+ value: detached,
193
+ tags,
194
+ storedAt: Date.now(),
195
+ revalidate: policy.revalidate
196
+ })
197
+ );
198
+ await flight.storing;
199
+ } catch (error) {
200
+ console.error("[lynkow] a cache entry could not be stored", error);
201
+ }
202
+ }
203
+ return { value: detached, detached: true };
204
+ } finally {
205
+ if (flights.get(key) === flight) flights.delete(key);
206
+ }
207
+ }
208
+ const flight = { tags, cancelled: false, done: run() };
209
+ flights.set(key, flight);
210
+ return flight;
211
+ }
212
+ function backOff(key) {
213
+ const now = Date.now();
214
+ for (const [held, until] of retryAt) if (until <= now) retryAt.delete(held);
215
+ retryAt.set(key, now + REFRESH_RETRY_BACKOFF_MS);
216
+ }
217
+ async function read(key, policy, load) {
218
+ if (!(policy.revalidate > 0)) return load();
219
+ let entry;
220
+ try {
221
+ entry = await entries.get(key);
222
+ } catch (error) {
223
+ console.error("[lynkow] the cache store could not be read, loading instead", error);
224
+ }
225
+ if (entry) {
226
+ const age = Date.now() - entry.storedAt;
227
+ const fresh = entry.revalidate * 1e3;
228
+ if (age < fresh) return hand({ value: entry.value, detached: true });
229
+ if (age < fresh + staleWhileRevalidate * 1e3) {
230
+ if (Date.now() >= (retryAt.get(key) ?? 0) && !flights.has(key)) {
231
+ fly(key, policy, load).done.catch((error) => {
232
+ backOff(key);
233
+ console.error("[lynkow] a background refresh failed, the stale entry is kept", error);
234
+ });
235
+ }
236
+ return hand({ value: entry.value, detached: true });
237
+ }
238
+ }
239
+ return hand(await fly(key, policy, load).done);
240
+ }
241
+ async function invalidateTags(tags) {
242
+ const dropped = new Set(tags);
243
+ const writes = [];
244
+ for (const [key, flight] of flights) {
245
+ if (flight.tags.some((tag) => dropped.has(tag))) {
246
+ flight.cancelled = true;
247
+ if (flight.storing) writes.push(flight.storing);
248
+ flights.delete(key);
249
+ }
250
+ }
251
+ const evicted = [...dropped];
252
+ if (writes.length > 0) {
253
+ const pending = new Set(writes);
254
+ const settled = Promise.allSettled(writes.map((write) => write.finally(() => pending.delete(write))));
255
+ if (!await settlesWithin(settled, STORE_WRITE_WAIT_MS)) {
256
+ const evictLate = () => entries.deleteTags(evicted);
257
+ for (const write of pending) {
258
+ void write.then(evictLate, evictLate).catch((error) => {
259
+ console.error("[lynkow] a cache tag could not be evicted after a late store write", error);
260
+ });
261
+ }
262
+ }
263
+ }
264
+ await entries.deleteTags(evicted);
265
+ }
266
+ return { read, invalidateTags };
267
+ }
268
+ var DEFAULT_CACHE = /* @__PURE__ */ Symbol.for("@lynkow/astro/default-cache");
269
+ var lynkowCache = globalThis[DEFAULT_CACHE] ??= createLynkowCache();
270
+ var LOCALE_TAG = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/i;
271
+ function baseClientConfig(config, locale) {
272
+ return {
273
+ siteId: config.siteId,
274
+ baseUrl: config.apiUrl,
275
+ ...config.publishableKey ? { publishableKey: config.publishableKey } : {},
276
+ ...locale ? { locale } : {},
277
+ cache: false
278
+ };
279
+ }
280
+ function createClients(config, { enhancements, siteLocales } = {}) {
281
+ const paths = createLocalePaths(config, siteLocales);
282
+ const live = config.locales.length > 0 ? void 0 : siteLocales;
283
+ const clients = /* @__PURE__ */ new Map();
284
+ function loaded() {
285
+ if (!live) return true;
286
+ try {
287
+ live.current();
288
+ return true;
289
+ } catch {
290
+ return false;
291
+ }
292
+ }
293
+ function clientFor(locale, retry) {
294
+ const key = `${locale ?? ""}${retry ? "" : ":no-retry"}`;
295
+ const existing = clients.get(key);
296
+ if (existing) return existing;
297
+ const client = createClient({
298
+ ...baseClientConfig(config, locale),
299
+ ...enhancements ? { enhancements } : {},
300
+ retry
301
+ });
302
+ clients.set(key, client);
303
+ return client;
304
+ }
305
+ return function lynkow(locale, { retry = true } = {}) {
306
+ const known = loaded();
307
+ const wanted = locale ?? (known && live ? paths.defaultLocale : config.defaultLocale);
308
+ if (locale === void 0 && !known && !wanted) return clientFor(void 0, retry);
309
+ const canonical = known ? paths.toLocale(wanted) : LOCALE_TAG.test(wanted) ? normalizeTag(wanted) : null;
310
+ if (!canonical) {
311
+ throw new RangeError(
312
+ known ? `${JSON.stringify(wanted)} is not one of the site's locales (${paths.locales.join(", ")})` : `${JSON.stringify(wanted)} is not a well-formed locale, expected a code such as "en" or "pt-BR"`
313
+ );
314
+ }
315
+ return clientFor(canonical, retry);
316
+ };
317
+ }
318
+ function normalizeTag(tag) {
319
+ return tag.split("-").map((subtag, index) => {
320
+ if (index === 0) return subtag.toLowerCase();
321
+ if (subtag.length === 2) return subtag.toUpperCase();
322
+ if (subtag.length === 4) return subtag.charAt(0).toUpperCase() + subtag.slice(1).toLowerCase();
323
+ return subtag.toLowerCase();
324
+ }).join("-");
325
+ }
326
+
327
+ export { REVALIDATE2 as REVALIDATE, TAGS, TAGS2, baseClientConfig, cached, createClients, createLynkowCache, createMemoryStore, lynkowCache, takeHint, uncached, uncached2 };
328
+ //# sourceMappingURL=chunk-VVRAYLFD.js.map
329
+ //# sourceMappingURL=chunk-VVRAYLFD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../lynkow-next/src/cache.ts","../src/cache/policy.ts","../src/cache/hint.ts","../src/cache/store.ts","../src/cache/lynkow-cache.ts","../../lynkow-next/src/clients.ts"],"names":["REVALIDATE","TAGS","uncached"],"mappings":";;;;AA4BO,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,IAAA,EAAM,IAAA;AAAA;AAAA,EAEN,IAAA,EAAM,GAAA;AAAA;AAAA,EAEN,IAAA,EAAM,GAAA;AAAA;AAAA,EAEN,OAAA,EAAS,GAAA;AAAA;AAAA,EAET,KAAA,EAAO,IAAA;AAAA;AAAA,EAEP,OAAA,EAAS,IAAA;AAAA;AAAA,EAET,GAAA,EAAK,IAAA;AAAA;AAAA,EAEL,KAAA,EAAO,GAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASP,MAAA,EAAQ;AACV,CAAA;AAEO,IAAM,IAAA,GAAO;AAAA,EAClB,IAAA,EAAM,aAAA;AAAA,EACN,KAAA,EAAO,cAAA;AAAA,EACP,IAAA,EAAM,CAAC,IAAA,KAAiB,CAAA,YAAA,EAAe,IAAI,CAAA,CAAA;AAAA,EAC3C,QAAA,EAAU,iBAAA;AAAA,EACV,OAAA,EAAS,CAAC,IAAA,KAAiB,CAAA,eAAA,EAAkB,IAAI,CAAA,CAAA;AAAA,EACjD,UAAA,EAAY,mBAAA;AAAA,EACZ,IAAA,EAAM,aAAA;AAAA,EACN,OAAA,EAAS,gBAAA;AAAA,EACT,KAAA,EAAO,cAAA;AAAA,EACP,IAAA,EAAM,CAAC,IAAA,KAAiB,CAAA,YAAA,EAAe,IAAI,CAAA,CAAA;AAAA,EAC3C,OAAA,EAAS,gBAAA;AAAA,EACT,GAAA,EAAK,YAAA;AAAA,EACL,KAAA,EAAO,cAAA;AAA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,CAAO,MAAA,KAAW,CAAA,EAAG,OAAO,OAAO,MAAA,CAAO,CAAC,CAAA,CAAE,WAAA,EAAY,GAAI,MAAA,CAAO,KAAA,CAAM,CAAC,EAAE,WAAA,EAAY;AAC7F,IAAA,OAAO,OAAO,WAAA,EAAY;AAAA,EAC5B,CAAC,CAAA,CACA,IAAA,CAAK,GAAG,CAAA;AACb","file":"chunk-VVRAYLFD.js","sourcesContent":["/**\n * The caching strategy of a Lynkow site on Next, in one file.\n *\n * Next 15 changed `fetch()` to be uncached by default, so nothing here is\n * inherited: a read that does not pass one of these option bags hits the Lynkow\n * API on every single request. Every data read in this app therefore goes\n * through `cached()`. The durations are defaults tuned for a content site; a\n * site that wants others passes its own number to `cached()`.\n *\n * Two mechanisms, deliberately combined:\n *\n * - `revalidate` is the ceiling. Even with no webhook wired, content is never\n * more than this many seconds stale.\n * - `tags` are the floor. The revalidation webhook calls `revalidateTag()` so\n * an edit in the admin appears in seconds rather than minutes.\n *\n * A tag is only useful if the webhook actually sends the matching event, so the\n * names here and the ones the revalidation handler maps MUST stay in step.\n */\nimport type { BaseRequestOptions } from 'lynkow'\n\n/**\n * `RequestInit` as Next extends it. Spelled out here because this entry\n * imports nothing from `next`, whose global types carry that extension.\n */\ntype NextRequestInit = RequestInit & { next?: { tags?: string[]; revalidate?: number | false } }\n\n/** Seconds. Tuned for a content site: rarely-changing structure lives longer. */\nexport const REVALIDATE = {\n /** Site config and global blocks: header, footer, branding. */\n site: 3600,\n /** Structural pages driven by site blocks. */\n page: 300,\n /** Blog articles, categories, tags. */\n blog: 300,\n /** Approved reviews. */\n reviews: 900,\n /** Form schemas. */\n forms: 3600,\n /** The cookie consent banner configuration. */\n consent: 3600,\n /** sitemap.xml, robots.txt, llms.txt. */\n seo: 3600,\n /** The path table used for static generation and redirect matching. */\n paths: 600,\n /**\n * One search result page.\n *\n * Short on purpose. Next keys its fetch cache on the full URL, so every\n * distinct query is its own entry and a long ceiling would pin a large,\n * unbounded set of them. The tag is what actually keeps results honest: a\n * publish evicts every cached query at once.\n */\n search: 60,\n} as const\n\nexport const TAGS = {\n site: 'lynkow:site',\n pages: 'lynkow:pages',\n page: (slug: string) => `lynkow:page:${slug}`,\n contents: 'lynkow:contents',\n content: (slug: string) => `lynkow:content:${slug}`,\n categories: 'lynkow:categories',\n tags: 'lynkow:tags',\n reviews: 'lynkow:reviews',\n forms: 'lynkow:forms',\n form: (slug: string) => `lynkow:form:${slug}`,\n consent: 'lynkow:consent',\n seo: 'lynkow:seo',\n paths: 'lynkow:paths',\n search: 'lynkow:search',\n} as const\n\n/**\n * Build the per-request options that put one Lynkow read into the Next cache.\n *\n * @example\n * const page = await lynkow(locale).pages.getBySlug('home', cached([TAGS.page('home')], REVALIDATE.page))\n */\nexport function cached(tags: string[], revalidate: number): BaseRequestOptions {\n const fetchOptions: NextRequestInit = { next: { tags, revalidate } }\n return { fetchOptions }\n}\n\n/**\n * For a read that must never be served from cache: a preview render, or a\n * form schema fetched at submit time.\n */\nexport function uncached(): BaseRequestOptions {\n return { fetchOptions: { cache: 'no-store' } }\n}\n","import { REVALIDATE as SHARED_REVALIDATE, TAGS as SHARED_TAGS } from '../../../lynkow-next/src/cache.js'\n\n/**\n * The default freshness ceilings of each kind of read, in seconds, for\n * `cached(tags, revalidate)`: the same values `@lynkow/next` uses. A site that\n * wants others passes its own number.\n */\nexport const REVALIDATE: typeof SHARED_REVALIDATE = SHARED_REVALIDATE\n\n/**\n * The cache tags the revalidation endpoint evicts for each webhook event. A\n * read tagged with one of them is evicted when that content changes, so the\n * names here and those the endpoint maps always stay in step.\n */\nexport const TAGS: typeof SHARED_TAGS = SHARED_TAGS\n","import type { BaseRequestOptions } from 'lynkow'\n\n/**\n * The key a read's options carry its cache policy under. A registered symbol,\n * so a second copy of this module, bundled into another entry, reads the same\n * key. It is a symbol so it never reaches a query string or a request body:\n * the client wrapper strips it before the SDK sees the options.\n */\nexport const CACHE_HINT: unique symbol = Symbol.for('@lynkow/astro/cache-hint')\n\n/** How long one read stays cached, and the tags that evict it. */\nexport interface CachePolicy {\n /** The tags a webhook event evicts this read by, such as `TAGS.page('home')`. */\n readonly tags: readonly string[]\n /** Seconds the result stays fresh. `0` never caches it. */\n readonly revalidate: number\n}\n\n/** Request options carrying a cache policy, or the explicit absence of one. */\ntype HintedOptions = BaseRequestOptions & { [CACHE_HINT]: CachePolicy | null }\n\n/**\n * The per-read options that put one Lynkow read into the Astro data cache.\n * Pass them to a read of a client from `createClients`, alone or spread into\n * the read's own options.\n *\n * @param tags - The tags a webhook event evicts this read by\n * @param revalidate - Seconds the result stays fresh; `0` never caches it\n * @throws {TypeError} When a tag is not a non-empty string.\n * @throws {RangeError} When `revalidate` is not a finite number of at least 0.\n *\n * @example\n * const page = await lynkow(locale).pages.getBySlug('home', cached([TAGS.page('home')], REVALIDATE.page))\n * // A commerce read takes a tag of your own: `TAGS` covers the content reads.\n * const { data } = await lynkow(locale).products.list(filters, { ...cached(['lynkow:products'], 300), market })\n */\nexport function cached(tags: readonly string[], revalidate: number): BaseRequestOptions {\n if (!Array.isArray(tags) || tags.some((tag) => typeof tag !== 'string' || tag === '')) {\n throw new TypeError('cached() takes an array of non-empty tag strings')\n }\n if (typeof revalidate !== 'number' || !Number.isFinite(revalidate) || revalidate < 0) {\n throw new RangeError(`cached() takes a number of seconds of at least 0, got ${String(revalidate)}`)\n }\n const options: HintedOptions = { [CACHE_HINT]: { tags: [...tags], revalidate } }\n return options\n}\n\n/**\n * For a read that must never be served from the cache: a preview render, or a\n * form schema read at submit time. A read with no `cached()` options is not\n * cached either; this one says so explicitly.\n */\nexport function uncached(): BaseRequestOptions {\n const options: HintedOptions = { [CACHE_HINT]: null }\n return options\n}\n\nfunction isPlainObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * The cache policy the arguments of one read carry, and the arguments with\n * the hint removed, ready for the SDK. `policy` is `null` for `uncached()`\n * and `undefined` when no argument carries a hint. When several arguments\n * carry one, the last wins.\n */\nexport function takeHint(args: readonly unknown[]): {\n policy: CachePolicy | null | undefined\n args: unknown[]\n} {\n let policy: CachePolicy | null | undefined\n const stripped = args.map((arg) => {\n if (!isPlainObject(arg) || !Object.prototype.hasOwnProperty.call(arg, CACHE_HINT)) return arg\n const { [CACHE_HINT]: hint, ...rest } = arg\n policy = (hint as CachePolicy | null) ?? null\n return rest\n })\n return { policy, args: stripped }\n}\n","/**\n * Where the data cache keeps its entries.\n *\n * The default store lives in the process's memory, which is right for one\n * Node server. A site running several instances behind a load balancer can\n * hand {@link createLynkowCache} a store shared between them; every method\n * may then answer asynchronously.\n */\n\n/** One cached read. */\nexport interface CacheEntry {\n /** The read's result, already detached from what any caller holds. */\n readonly value: unknown\n /** The tags a webhook event evicts this entry by. */\n readonly tags: readonly string[]\n /** When the result was loaded, in epoch milliseconds. */\n readonly storedAt: number\n /** Seconds the entry stays fresh. */\n readonly revalidate: number\n}\n\n/**\n * The storage behind {@link createLynkowCache}.\n *\n * Shared between instances, it has one limit: an eviction cancels the loads\n * in flight in the instance that receives the webhook only. A load another\n * instance started before the edit can still write its pre-edit result to the\n * shared store after the eviction, where it stays until its `revalidate`\n * elapses or the next eviction of one of its tags. Past its `revalidate`, it is\n * served as stale to every read until the fresh copy lands, within the\n * `staleWhileRevalidate` window. Keep `revalidate` short on reads where that\n * window matters.\n */\nexport interface CacheStore {\n /** The entry under `key`, or undefined. A store may evict on its own terms. */\n get(key: string): CacheEntry | undefined | Promise<CacheEntry | undefined>\n /** Stores `entry` under `key`, replacing any entry already there. */\n set(key: string, entry: CacheEntry): void | Promise<void>\n /** Deletes every entry carrying at least one of `tags`. */\n deleteTags(tags: readonly string[]): void | Promise<void>\n}\n\n/** Options of {@link createMemoryStore}. */\nexport interface MemoryStoreOptions {\n /** The most entries kept; the least recently used one goes first. Defaults to 1000. */\n max?: number\n}\n\nexport const DEFAULT_MAX_ENTRIES = 1000\n\n/**\n * An in-process store: a least-recently-used map, bounded by entry count,\n * with an index from each tag to the keys that carry it so an eviction by tag\n * never scans the whole map.\n *\n * @throws {RangeError} When `max` is not a positive integer.\n */\nexport function createMemoryStore({ max = DEFAULT_MAX_ENTRIES }: MemoryStoreOptions = {}): CacheStore {\n if (!Number.isInteger(max) || max < 1) {\n throw new RangeError(`max must be a positive integer, got ${String(max)}`)\n }\n // A Map iterates in insertion order, so re-inserting on use keeps the least\n // recently used entry first.\n const entries = new Map<string, CacheEntry>()\n const byTag = new Map<string, Set<string>>()\n\n function unindex(key: string, entry: CacheEntry): void {\n for (const tag of entry.tags) {\n const keys = byTag.get(tag)\n if (!keys) continue\n keys.delete(key)\n if (keys.size === 0) byTag.delete(tag)\n }\n }\n\n function remove(key: string): void {\n const entry = entries.get(key)\n if (!entry) return\n entries.delete(key)\n unindex(key, entry)\n }\n\n return {\n get(key) {\n const entry = entries.get(key)\n if (!entry) return undefined\n entries.delete(key)\n entries.set(key, entry)\n return entry\n },\n set(key, entry) {\n remove(key)\n entries.set(key, entry)\n for (const tag of entry.tags) {\n let keys = byTag.get(tag)\n if (!keys) byTag.set(tag, (keys = new Set()))\n keys.add(key)\n }\n while (entries.size > max) {\n const oldest = entries.keys().next()\n if (oldest.done) break\n remove(oldest.value)\n }\n },\n deleteTags(tags) {\n for (const tag of tags) {\n const keys = byTag.get(tag)\n if (!keys) continue\n for (const key of [...keys]) remove(key)\n }\n },\n }\n}\n","import type { CachePolicy } from './hint.js'\nimport { createMemoryStore, type CacheStore } from './store.js'\n\n/**\n * Seconds a stale entry may still be served while a fresh copy loads in the\n * background, by default. Past that, the read waits for the fresh copy.\n */\nexport const DEFAULT_STALE_WHILE_REVALIDATE = 86_400\n\n/**\n * Milliseconds a key waits after a failed background refresh before another\n * one may start. The stale entry is served meanwhile, so an API outage costs\n * one upstream call per key per backoff rather than one per request.\n */\nexport const REFRESH_RETRY_BACKOFF_MS = 30_000\n\n/**\n * Milliseconds an eviction waits for the store writes already under way for\n * its tags before deleting, so a store that hangs never holds the webhook. A\n * write still under way after that is deleted again once it settles, after the\n * webhook has answered. A host that suspends work once the response is sent may\n * run that deletion late or never, and the entry then stays until its\n * `revalidate` elapses.\n */\nexport const STORE_WRITE_WAIT_MS = 5_000\n\n/** Options of {@link createLynkowCache}. */\nexport interface LynkowCacheOptions {\n /**\n * The most entries the default in-memory store keeps. Ignored when `store`\n * is given. Defaults to 1000.\n */\n max?: number\n /** Where entries live. Defaults to an in-process LRU store. */\n store?: CacheStore\n /**\n * Seconds past its `revalidate` an entry may still be served while a fresh\n * copy loads in the background. Defaults to one day. `0` makes every read\n * of an expired entry wait for the fresh copy.\n */\n staleWhileRevalidate?: number\n}\n\n/** A tagged data cache for Lynkow reads. */\nexport interface LynkowCache {\n /**\n * The result of `load`, cached under `key` with `policy`.\n *\n * A fresh entry is returned without calling `load`. An expired one is\n * returned too while it is within the stale window. `load` then runs once in\n * the background to replace it, unless a load of that key is already under\n * way or a background refresh of it failed less than 30 seconds ago. Every\n * read until the fresh copy lands gets the stale entry. A missing entry, or\n * one past that window, waits for `load`. Concurrent reads of one key share\n * a single `load`. A failed `load` is never cached and rejects every read\n * waiting on it; a failed background refresh keeps the stale entry.\n *\n * Every caller gets its own copy (`structuredClone`), so mutating a result\n * never alters what the next request reads. A result that cannot be cloned\n * is returned as it is and not cached.\n */\n read<T>(key: string, policy: CachePolicy, load: () => Promise<T>): Promise<T>\n /**\n * Evicts every entry carrying one of `tags`, with no staleness allowed: the\n * next read of those keys waits for a fresh copy. A load already in flight\n * for one of them still answers the reads waiting on it, but its result is\n * not stored, and a write of it already under way is awaited, then deleted.\n * That wait lasts 5 seconds at most: a write still under way then is deleted\n * again once it settles, in the background after this promise resolves, and\n * until that second deletion a read can get its pre-edit entry. On a host that\n * suspends work once the response is sent, that deletion may run late or\n * never: the entry then stays until its `revalidate` elapses. Only the\n * loads of this cache are covered: with a store shared between instances, a\n * load another instance started before the eviction can still store its\n * result after it (see {@link CacheStore}).\n */\n invalidateTags(tags: readonly string[]): Promise<void>\n}\n\n/** One load in flight, shared by every read of its key. */\ninterface Flight {\n readonly tags: readonly string[]\n /** Set when one of the tags was invalidated while the load ran. */\n cancelled: boolean\n /** The write of the loaded entry to the store, once started. */\n storing?: Promise<void>\n readonly done: Promise<Loaded>\n}\n\n/** A loaded result, and whether it is a detached copy every reader may clone. */\ninterface Loaded {\n value: unknown\n detached: boolean\n}\n\nfunction hand<T>(loaded: Loaded): T {\n return (loaded.detached ? structuredClone(loaded.value) : loaded.value) as T\n}\n\n/** Whether `promise` settles within `ms`. The timer is always cleared. */\nasync function settlesWithin(promise: Promise<unknown>, ms: number): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const elapsed = new Promise<false>((resolve) => {\n timer = setTimeout(resolve, ms, false)\n })\n try {\n return await Promise.race([promise.then(() => true), elapsed])\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * Creates a tagged data cache: tags for eviction by the revalidation webhook,\n * `revalidate` as the freshness ceiling, stale-while-revalidate, one load per\n * key at a time, and a detached copy for every reader.\n *\n * @throws {RangeError} When `max` is not a positive integer, or\n * `staleWhileRevalidate` is not a finite number of at least 0.\n */\nexport function createLynkowCache({\n max,\n store,\n staleWhileRevalidate = DEFAULT_STALE_WHILE_REVALIDATE,\n}: LynkowCacheOptions = {}): LynkowCache {\n if (!Number.isFinite(staleWhileRevalidate) || staleWhileRevalidate < 0) {\n throw new RangeError(\n `staleWhileRevalidate must be a number of seconds of at least 0, got ${String(staleWhileRevalidate)}`\n )\n }\n const entries = store ?? createMemoryStore(max === undefined ? {} : { max })\n const flights = new Map<string, Flight>()\n /** Keys whose last background refresh failed, with when the next may start. */\n const retryAt = new Map<string, number>()\n\n /** Starts the load of `key`, or joins the one already running. */\n function fly(key: string, policy: CachePolicy, load: () => Promise<unknown>): Flight {\n const running = flights.get(key)\n if (running) return running\n\n const tags = [...policy.tags]\n\n async function run(): Promise<Loaded> {\n // Yield first: `flight` is assigned, and registered, before `load` can settle or throw.\n await undefined\n try {\n const value = await load()\n retryAt.delete(key)\n let detached: unknown\n try {\n detached = structuredClone(value)\n } catch {\n // Not cloneable, so not shareable between requests: not cached.\n return { value, detached: false }\n }\n if (!flight.cancelled) {\n try {\n // Kept on the flight so an eviction arriving mid-write waits for it.\n flight.storing = Promise.resolve(\n entries.set(key, {\n value: detached,\n tags,\n storedAt: Date.now(),\n revalidate: policy.revalidate,\n })\n )\n await flight.storing\n } catch (error) {\n console.error('[lynkow] a cache entry could not be stored', error)\n }\n }\n return { value: detached, detached: true }\n } finally {\n if (flights.get(key) === flight) flights.delete(key)\n }\n }\n\n const flight: Flight = { tags, cancelled: false, done: run() }\n flights.set(key, flight)\n return flight\n }\n\n /** Holds off the next background refresh of `key`, dropping elapsed holds. */\n function backOff(key: string): void {\n const now = Date.now()\n for (const [held, until] of retryAt) if (until <= now) retryAt.delete(held)\n retryAt.set(key, now + REFRESH_RETRY_BACKOFF_MS)\n }\n\n async function read<T>(key: string, policy: CachePolicy, load: () => Promise<T>): Promise<T> {\n if (!(policy.revalidate > 0)) return load()\n\n let entry\n try {\n entry = await entries.get(key)\n } catch (error) {\n console.error('[lynkow] the cache store could not be read, loading instead', error)\n }\n if (entry) {\n const age = Date.now() - entry.storedAt\n const fresh = entry.revalidate * 1000\n if (age < fresh) return hand<T>({ value: entry.value, detached: true })\n if (age < fresh + staleWhileRevalidate * 1000) {\n // Only the read that starts the refresh handles its failure, so one\n // failure is logged and backed off once, however many reads see it.\n if (Date.now() >= (retryAt.get(key) ?? 0) && !flights.has(key)) {\n fly(key, policy, load).done.catch((error: unknown) => {\n backOff(key)\n console.error('[lynkow] a background refresh failed, the stale entry is kept', error)\n })\n }\n return hand<T>({ value: entry.value, detached: true })\n }\n }\n return hand<T>(await fly(key, policy, load).done)\n }\n\n async function invalidateTags(tags: readonly string[]): Promise<void> {\n const dropped = new Set(tags)\n const writes: Promise<void>[] = []\n for (const [key, flight] of flights) {\n if (flight.tags.some((tag) => dropped.has(tag))) {\n flight.cancelled = true\n if (flight.storing) writes.push(flight.storing)\n flights.delete(key)\n }\n }\n const evicted = [...dropped]\n if (writes.length > 0) {\n // A write already under way lands first, so the deletion below removes it.\n const pending = new Set(writes)\n const settled = Promise.allSettled(writes.map((write) => write.finally(() => pending.delete(write))))\n if (!(await settlesWithin(settled, STORE_WRITE_WAIT_MS))) {\n // Not waited for any longer: each write still under way is deleted\n // again once it lands, whatever the others do. That second deletion\n // may also drop an entry stored after the eviction, which costs one\n // more load, never a stale read.\n const evictLate = () => entries.deleteTags(evicted)\n for (const write of pending) {\n void write.then(evictLate, evictLate).catch((error: unknown) => {\n console.error('[lynkow] a cache tag could not be evicted after a late store write', error)\n })\n }\n }\n }\n await entries.deleteTags(evicted)\n }\n\n return { read, invalidateTags }\n}\n\nconst DEFAULT_CACHE = Symbol.for('@lynkow/astro/default-cache')\n\n/**\n * The process-wide cache `createClients` and `createRevalidateEndpoint` use\n * when given none. Kept on `globalThis`, so two copies of this package loaded\n * side by side still share one cache, and an eviction always reaches it.\n */\nexport const lynkowCache: LynkowCache = ((globalThis as Record<symbol, unknown>)[DEFAULT_CACHE] ??=\n createLynkowCache()) as LynkowCache\n","import { createClient, type Client, type ClientConfig } from 'lynkow'\nimport type { LynkowNextConfig } from './config.js'\nimport { createLocalePaths } from './locale-paths.js'\nimport type { SiteLocales } from './site-locales.js'\n\n/**\n * A language subtag, then optional script, region or variant subtags: `en`,\n * `fr`, `pt-BR`. The same shape `resolveConfig` accepts for a configured\n * locale, strict for the same reason: a locale becomes a path segment.\n */\nconst LOCALE_TAG = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/i\n\n/** Options of the client {@link LynkowClients} returns. */\nexport interface ClientOptions {\n /**\n * `false` returns a client that sends each read once instead of retrying a\n * 429 or a 503. Defaults to `true`.\n */\n retry?: boolean\n}\n\n/** Options of {@link createClients}, applied to every client it creates. */\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 * site renders CMS HTML on the server, as a Next.js page usually does: the\n * browser has already run that HTML's inline scripts on page load, and the\n * SDK would run them a second time. Only a client created in the browser\n * uses it. Omitted, the SDK's default applies, which activates them.\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}\n\n/**\n * The `createClient` options every client of this package shares: the site,\n * the API origin, the publishable key and the locale when they are set, and\n * the SDK cache off. Each factory spreads it and adds its own fields.\n *\n * @internal Not re-exported from the package entries.\n */\nexport function baseClientConfig(config: LynkowNextConfig, locale?: string): ClientConfig {\n return {\n siteId: config.siteId,\n baseUrl: config.apiUrl,\n ...(config.publishableKey ? { publishableKey: config.publishableKey } : {}),\n ...(locale ? { locale } : {}),\n cache: false,\n }\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.\n *\n * The SDK's own cache stays OFF. On the server it is a process-global\n * unbounded `Map`, which would duplicate and outlive Next's data cache without\n * any of its invalidation. Caching is Next's job, expressed per read with\n * `cached()`.\n *\n * `{ retry: false }` gives a second client for the locale, because the SDK's\n * retry is a client setting rather than a per-read one. Only a read that\n * already knows what to do when it fails should ask for it.\n *\n * FOR READS THAT ARE THE SAME FOR EVERY VISITOR. The clients are shared by\n * every request the process serves, and the SDK keeps a buyer's state on the\n * client instance: the guest cart token and the signed-in customer session.\n * Calling `cart` or `customers` on one of these from server code would hand\n * one visitor's cart or session to the next. Buyer flows run in the browser,\n * or on a client created for that one request.\n *\n * A locale outside the site's languages throws a `RangeError` instead of\n * creating a client. The clients live as long as the process, so a locale\n * taken from a URL and passed through unchecked would grow that set without\n * bound. The languages are the configuration's static list when it has one,\n * otherwise those `options.siteLocales` last loaded. The locale is matched\n * case-insensitively and the client gets the site's spelling.\n *\n * Before `options.siteLocales` has loaded anything, there is no list to check\n * against, so any well-formed language tag is accepted and its client is\n * created, the tag written `pt-BR` whatever its case. Until that first load\n * the set of clients is bounded only by well-formedness, which is why the\n * source should be awaited before a locale from a URL reaches this function,\n * as the proxy does. A call with no locale gets the configuration's default\n * locale when it has a static list, otherwise the site's default once loaded,\n * and the configuration's default before then. With neither a static list nor\n * a configured default, a call with no locale before the first load gets a\n * client that names no locale, so the API answers in the site's default: that\n * is the client the runtime source reads the site's languages through, the\n * one read that cannot know them yet.\n *\n * The source reads the site through a client, and this function checks\n * locales through the source. The two are wired without a cycle by a closure\n * that reads the clients only when it is called:\n *\n * ```ts\n * const siteLocales = createSiteLocales({ client: (locale) => lynkow(locale) })\n * export const lynkow = createClients(config, { siteLocales })\n * ```\n *\n * `options` applies to every client; see {@link CreateClientsOptions}.\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 { enhancements, siteLocales }: CreateClientsOptions = {}\n): LynkowClients {\n const paths = createLocalePaths(config, siteLocales)\n const live = config.locales.length > 0 ? undefined : siteLocales\n const clients = new Map<string, Client>()\n\n /** Whether the site's languages are known: a static list, or a source that loaded once. */\n function loaded(): boolean {\n if (!live) return true\n try {\n live.current()\n return true\n } catch {\n return false\n }\n }\n\n /** The client of `locale`, created once per key; no locale lets the API pick the site's default. */\n function clientFor(locale: string | undefined, retry: boolean): Client {\n const key = `${locale ?? ''}${retry ? '' : ':no-retry'}`\n const existing = clients.get(key)\n if (existing) return existing\n\n const client = createClient({\n ...baseClientConfig(config, locale),\n ...(enhancements ? { enhancements } : {}),\n retry,\n })\n clients.set(key, client)\n return client\n }\n\n return function lynkow(locale?: string, { retry = true } = {}) {\n const known = loaded()\n const wanted = locale ?? (known && live ? paths.defaultLocale : config.defaultLocale)\n // No locale asked for, and none known yet: the bootstrap read of the\n // runtime source, which the API answers in the site's default locale.\n if (locale === undefined && !known && !wanted) return clientFor(undefined, retry)\n const canonical = known ? paths.toLocale(wanted) : LOCALE_TAG.test(wanted) ? normalizeTag(wanted) : null\n if (!canonical) {\n throw new RangeError(\n known\n ? `${JSON.stringify(wanted)} is not one of the site's locales (${paths.locales.join(', ')})`\n : `${JSON.stringify(wanted)} is not a well-formed locale, expected a code such as \"en\" or \"pt-BR\"`\n )\n }\n\n return clientFor(canonical, retry)\n }\n}\n\n/**\n * A well-formed tag written the way the API writes locales: the language in\n * lowercase, a four-letter script in title case and a two-letter region in\n * uppercase (`pt-BR`, `zh-Hant`), so two spellings of one locale share a\n * client.\n */\nfunction normalizeTag(tag: string): string {\n return tag\n .split('-')\n .map((subtag, index) => {\n if (index === 0) return subtag.toLowerCase()\n if (subtag.length === 2) return subtag.toUpperCase()\n if (subtag.length === 4) return subtag.charAt(0).toUpperCase() + subtag.slice(1).toLowerCase()\n return subtag.toLowerCase()\n })\n .join('-')\n}\n"]}
@@ -0,0 +1,60 @@
1
+ export { DEFAULT_CMS_ORIGIN, PREVIEW_PARAM } from 'lynkow/visual-editor';
2
+
3
+ /** Options of {@link startVisualEditor}. */
4
+ interface StartVisualEditorOptions {
5
+ /**
6
+ * Origin of the Lynkow dashboard that frames the site. Omit it to use the
7
+ * Lynkow dashboard; give the middleware the same value, or neither one. An
8
+ * empty value is refused by the SDK, which then does not start.
9
+ */
10
+ cmsOrigin?: string;
11
+ }
12
+ /**
13
+ * Starts the Lynkow visual editor on this page, once, and returns the function
14
+ * that stops it. Call it from a `<script>` of the base layout:
15
+ *
16
+ * ```astro
17
+ * <script>
18
+ * import { startVisualEditor } from '@lynkow/astro/client'
19
+ * startVisualEditor()
20
+ * </script>
21
+ * ```
22
+ *
23
+ * Outside the Lynkow dashboard's preview frame it does nothing. Inside it, the
24
+ * SDK's editor scans the page for the `data-lynkow-block` and
25
+ * `data-lynkow-field` markers, and every change an editor makes is written
26
+ * into the static HTML in place (see {@link patchField}) and published to the
27
+ * store the React hooks of `@lynkow/astro/react` read, so a hydrated island
28
+ * renders it too.
29
+ *
30
+ * A second call while it runs starts nothing and returns the same stop
31
+ * function. On the server it does nothing.
32
+ */
33
+ declare function startVisualEditor(options?: StartVisualEditorOptions): () => void;
34
+
35
+ /**
36
+ * The state of the visual editor on the page, shared by `startVisualEditor`,
37
+ * which writes it, and the React hooks of `@lynkow/astro/react`, which read
38
+ * it. A module store rather than a React context: an Astro page is many
39
+ * islands, each its own React root, and a context reaches none of the others.
40
+ */
41
+ /** What the editor has told the page so far. */
42
+ interface VisualEditorSnapshot {
43
+ /** Whether the page runs inside the Lynkow dashboard's visual editor. */
44
+ readonly isPreviewMode: boolean;
45
+ /** The data of every block the editor changed, by block slug. */
46
+ readonly blocksData: Readonly<Record<string, Record<string, any>>>;
47
+ }
48
+ /** The store, as `useSyncExternalStore` reads it. */
49
+ interface VisualEditorStore {
50
+ getSnapshot(): VisualEditorSnapshot;
51
+ /** The state a server render and a hydration start from: not in preview, no data. */
52
+ getServerSnapshot(): VisualEditorSnapshot;
53
+ /** Calls `listener` after every change; returns the unsubscribe function. */
54
+ subscribe(listener: () => void): () => void;
55
+ }
56
+ /** The visual editor's state on this page, read only. */
57
+ declare const visualEditorStore: VisualEditorStore;
58
+
59
+ export { startVisualEditor, visualEditorStore };
60
+ export type { StartVisualEditorOptions, VisualEditorSnapshot, VisualEditorStore };
@@ -0,0 +1,59 @@
1
+ import { writableVisualEditorStore } from '../chunk-67VKUBOP.js';
2
+ export { visualEditorStore } from '../chunk-67VKUBOP.js';
3
+ import { initVisualEditor } from 'lynkow/visual-editor';
4
+ export { DEFAULT_CMS_ORIGIN, PREVIEW_PARAM } from 'lynkow/visual-editor';
5
+
6
+ var RUNNING = /* @__PURE__ */ Symbol.for("@lynkow/astro/visual-editor-running");
7
+ function patchField(root, blockSlug, fieldKey, data) {
8
+ if (!Object.prototype.hasOwnProperty.call(data, fieldKey)) return 0;
9
+ const raw = data[fieldKey];
10
+ if (raw !== null && typeof raw !== "string" && typeof raw !== "number") return 0;
11
+ const value = raw === null ? "" : String(raw);
12
+ let written = 0;
13
+ for (const block of root.querySelectorAll("[data-lynkow-block]")) {
14
+ if (block.getAttribute("data-lynkow-block") !== blockSlug) continue;
15
+ for (const field of block.querySelectorAll("[data-lynkow-field]")) {
16
+ if (field.getAttribute("data-lynkow-field") !== fieldKey) continue;
17
+ if (field.closest("[data-lynkow-block]") !== block) continue;
18
+ if (field.closest("astro-slot, astro-island")?.localName === "astro-island") continue;
19
+ if (field.getAttribute("data-lynkow-type") === "richtext") {
20
+ if (field.innerHTML !== value) field.innerHTML = value;
21
+ } else if (field.textContent !== value) {
22
+ field.textContent = value;
23
+ }
24
+ written++;
25
+ }
26
+ }
27
+ return written;
28
+ }
29
+ function startVisualEditor(options = {}) {
30
+ if (typeof window === "undefined" || typeof document === "undefined") return () => {
31
+ };
32
+ const global = globalThis;
33
+ const running = global[RUNNING];
34
+ if (running) return running;
35
+ const instance = initVisualEditor("cmsOrigin" in options ? { cmsOrigin: options.cmsOrigin } : {});
36
+ const store = writableVisualEditorStore;
37
+ let unsubscribe = () => {
38
+ };
39
+ if (instance.isPreviewMode()) {
40
+ store.setPreviewMode(true);
41
+ unsubscribe = instance.onDataChange((blockSlug, fieldKey, _fieldPath, _value, allData) => {
42
+ patchField(document, blockSlug, fieldKey, allData);
43
+ store.setBlockData(blockSlug, allData);
44
+ });
45
+ }
46
+ const stop = () => {
47
+ if (global[RUNNING] !== stop) return;
48
+ global[RUNNING] = void 0;
49
+ unsubscribe();
50
+ instance.destroy();
51
+ store.reset();
52
+ };
53
+ global[RUNNING] = stop;
54
+ return stop;
55
+ }
56
+
57
+ export { startVisualEditor };
58
+ //# sourceMappingURL=index.js.map
59
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/client/visual-editor.ts"],"names":[],"mappings":";;;;;AAaA,IAAM,OAAA,mBAAU,MAA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AACT","file":"index.js","sourcesContent":["import { initVisualEditor } from 'lynkow/visual-editor'\nimport { writableVisualEditorStore } from '../visual-editor/store.js'\n\n/** Options of {@link startVisualEditor}. */\nexport interface StartVisualEditorOptions {\n /**\n * Origin of the Lynkow dashboard that frames the site. Omit it to use the\n * Lynkow dashboard; give the middleware the same value, or neither one. An\n * empty value is refused by the SDK, which then does not start.\n */\n cmsOrigin?: string\n}\n\nconst RUNNING = Symbol.for('@lynkow/astro/visual-editor-running')\n\ntype Global = Record<symbol, (() => void) | undefined>\n\n/**\n * Writes the value the editor sent for `fieldKey` into every element marked\n * with that field inside a block marked `blockSlug`, and returns how many it\n * wrote.\n *\n * - A `richtext` field (`data-lynkow-type=\"richtext\"`) gets the value as HTML,\n * any other its text, as the React `Editable` renders them.\n * - Only a flat key holding a string or a number is written (`null` empties\n * the element). A repeater row has no element to write to.\n * - A field inside a nested block belongs to that block, and a field an\n * `astro-island` renders is left to the island, which renders the same value\n * from the store when it is hydrated. Static content passed into the island\n * (inside its `astro-slot`) is never re-rendered by it, so it is written.\n * An island that remounts that content puts back the HTML Astro captured\n * when it hydrated, so the value written is lost until the field changes\n * again.\n * - An element already holding the value is not touched, so the caret of an\n * editor typing in it stays where it is.\n */\nexport function patchField(\n root: ParentNode,\n blockSlug: string,\n fieldKey: string,\n data: Record<string, unknown>\n): number {\n if (!Object.prototype.hasOwnProperty.call(data, fieldKey)) return 0\n const raw = data[fieldKey]\n if (raw !== null && typeof raw !== 'string' && typeof raw !== 'number') return 0\n const value = raw === null ? '' : String(raw)\n\n let written = 0\n for (const block of root.querySelectorAll('[data-lynkow-block]')) {\n if (block.getAttribute('data-lynkow-block') !== blockSlug) continue\n for (const field of block.querySelectorAll('[data-lynkow-field]')) {\n if (field.getAttribute('data-lynkow-field') !== fieldKey) continue\n if (field.closest('[data-lynkow-block]') !== block) continue\n // The nearest island boundary decides: an island renders its own subtree,\n // not the static HTML of its slot.\n if (field.closest('astro-slot, astro-island')?.localName === 'astro-island') continue\n // Same trust boundary as the React `Editable`: the SDK accepts these\n // messages from the dashboard's origin only.\n if (field.getAttribute('data-lynkow-type') === 'richtext') {\n if (field.innerHTML !== value) field.innerHTML = value\n } else if (field.textContent !== value) {\n field.textContent = value\n }\n written++\n }\n }\n return written\n}\n\n/**\n * Starts the Lynkow visual editor on this page, once, and returns the function\n * that stops it. Call it from a `<script>` of the base layout:\n *\n * ```astro\n * <script>\n * import { startVisualEditor } from '@lynkow/astro/client'\n * startVisualEditor()\n * </script>\n * ```\n *\n * Outside the Lynkow dashboard's preview frame it does nothing. Inside it, the\n * SDK's editor scans the page for the `data-lynkow-block` and\n * `data-lynkow-field` markers, and every change an editor makes is written\n * into the static HTML in place (see {@link patchField}) and published to the\n * store the React hooks of `@lynkow/astro/react` read, so a hydrated island\n * renders it too.\n *\n * A second call while it runs starts nothing and returns the same stop\n * function. On the server it does nothing.\n */\nexport function startVisualEditor(options: StartVisualEditorOptions = {}): () => void {\n if (typeof window === 'undefined' || typeof document === 'undefined') return () => {}\n const global = globalThis as unknown as Global\n const running = global[RUNNING]\n if (running) return running\n\n // Passed as given: the SDK tells an absent origin, which takes the default,\n // from an empty one, which it refuses.\n const instance = initVisualEditor('cmsOrigin' in options ? { cmsOrigin: options.cmsOrigin } : {})\n const store = writableVisualEditorStore\n let unsubscribe = () => {}\n\n if (instance.isPreviewMode()) {\n store.setPreviewMode(true)\n unsubscribe = instance.onDataChange((blockSlug, fieldKey, _fieldPath, _value, allData) => {\n patchField(document, blockSlug, fieldKey, allData)\n store.setBlockData(blockSlug, allData)\n })\n }\n\n const stop = () => {\n if (global[RUNNING] !== stop) return\n global[RUNNING] = undefined\n unsubscribe()\n instance.destroy()\n store.reset()\n }\n global[RUNNING] = stop\n return stop\n}\n"]}
@@ -0,0 +1,10 @@
1
+ /** Options of the client {@link LynkowClients} returns. */
2
+ interface ClientOptions {
3
+ /**
4
+ * `false` returns a client that sends each read once instead of retrying a
5
+ * 429 or a 503. Defaults to `true`.
6
+ */
7
+ retry?: boolean;
8
+ }
9
+
10
+ export type { ClientOptions as C };