@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.
- package/LICENSE +29 -0
- package/README.md +393 -2
- package/dist/chunk-67VKUBOP.js +40 -0
- package/dist/chunk-67VKUBOP.js.map +1 -0
- package/dist/chunk-7ZL7TFBK.js +28 -0
- package/dist/chunk-7ZL7TFBK.js.map +1 -0
- package/dist/chunk-DQXJDZWU.js +9 -0
- package/dist/chunk-DQXJDZWU.js.map +1 -0
- package/dist/chunk-USZSRPT5.js +119 -0
- package/dist/chunk-USZSRPT5.js.map +1 -0
- package/dist/chunk-VVRAYLFD.js +329 -0
- package/dist/chunk-VVRAYLFD.js.map +1 -0
- package/dist/client/index.d.ts +60 -0
- package/dist/client/index.js +59 -0
- package/dist/client/index.js.map +1 -0
- package/dist/clients-DLlMBN4c.d.ts +10 -0
- package/dist/config-BVCvQ8Wx.d.ts +66 -0
- package/dist/index.d.ts +354 -0
- package/dist/index.js +395 -0
- package/dist/index.js.map +1 -0
- package/dist/integration.d.ts +37 -0
- package/dist/integration.js +51 -0
- package/dist/integration.js.map +1 -0
- package/dist/lynkow-cache-B5WLYsmk.d.ts +154 -0
- package/dist/middleware/index.d.ts +187 -0
- package/dist/middleware/index.js +582 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/next-headers-3VG6LM4M.js +3 -0
- package/dist/next-headers-3VG6LM4M.js.map +1 -0
- package/dist/next-navigation-VNM5XXCX.js +7 -0
- package/dist/next-navigation-VNM5XXCX.js.map +1 -0
- package/dist/react/index.d.ts +134 -0
- package/dist/react/index.js +128 -0
- package/dist/react/index.js.map +1 -0
- package/dist/server/index.d.ts +493 -0
- package/dist/server/index.js +989 -0
- package/dist/server/index.js.map +1 -0
- package/dist/site-locales-tmcu43n2.d.ts +80 -0
- package/package.json +91 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../lynkow-next/src/server/buyer-forwarding.ts","../../../lynkow-next/src/server/buyer-session.ts","../../src/server/buyer.ts","../../../lynkow-next/src/server/same-origin.ts","../../src/server/request.ts","../../../lynkow-next/src/server/json-ld.tsx","../../../lynkow-next/src/server/metadata.ts","../../../lynkow-next/src/server/origin.ts","../../src/server/head.ts","../../src/server/create-server.ts","../../src/shims/next-cache.ts","../../../lynkow-next/src/server/signature.ts","../../../lynkow-next/src/server/revalidation.ts","../../src/server/revalidate.ts"],"names":["readBuyerTokens","createBuyerClient","setCartCookie","setCustomerCookie","clearBuyerCookies","signOut","resolveBuyerForwarding","assertSameOrigin","TAGS","text"],"mappings":";;;;;;;;AAwBA,IAAM,WAAA,GAAc,+BAAA;AAmCb,SAAS,uBAAuB,OAAA,EAAgD;AACrF,EAAA,IAAI;AACF,IAAA,MAAM,SAAA,GAAY,QAAQ,mBAAmB,CAAA;AAC7C,IAAA,IAAI,CAAC,SAAA,EAAW,OAAO,EAAC;AACxB,IAAA,MAAM,QAAA,GAAW,eAAA,CAAgB,OAAA,EAAS,OAAA,CAAQ,yBAAyB,CAAC,CAAA;AAC5E,IAAA,OAAO,QAAA,GAAW,EAAE,SAAA,EAAW,QAAA,KAAa,EAAC;AAAA,EAC/C,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF;AAMO,SAAS,YAAA,GAAwB;AACtC,EAAA,OAAO,OAAA,CAAQ,mBAAmB,CAAA,KAAM,MAAA;AAC1C;AAQA,eAAsB,wBAAA,GAAwE;AAC5F,EAAA,IAAI,QAAA;AACJ,EAAA,IAAI;AAGF,IAAA,MAAM,EAAE,OAAA,EAAQ,GAAI,MAAM,OAAO,6BAAc,CAAA;AAC/C,IAAA,QAAA,GAAW,MAAM,OAAA,EAAQ;AAAA,EAC3B,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,kBAAkB,KAAK,CAAA;AAC7B,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,MAAM,EAAE,SAAA,EAAW,QAAA,EAA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IAAA,OAAO,QAAA,CAAS,KAAK,EAAE,KAAA,EAAO,SAAS,KAAA,EAAO,WAAA,EAAa,MAAM,CAAA;AAAA,EACnE,CAAA;AACF;;;AC5ZO,SAAS,wBAAA,CAAyB;AAAA,EACvC,MAAA;AAAA,EACA,WAAA;AAAA,EACA,KAAA,GAAQ;AACV,CAAA,EAAwC;AACtC,EAAA,MAAM,OAAA,GAAU,wBAAwB,WAAA,GAAc,EAAE,QAAQ,WAAA,EAAY,GAAI,EAAE,MAAA,EAAQ,CAAA;AAC1F,EAAA,OAAO,eAAe,IAAA,CAAK,EAAE,OAAA,EAAQ,EAAG;AAGtC,IAAA,IAAI,OAAA,GAAU,KAAA;AACd,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,eAAA,CAAgB,KAAA,EAAO,YAAY;AAC9C,QAAA,MAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,OAAO,CAAA;AACtC,QAAA,OAAA,GAAU,IAAA;AACV,QAAA,OAAO,QAAA;AAAA,MACT,CAAC,CAAA;AAAA,IACH,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,CAAC,OAAA,EAAS;AACZ,QAAA,OAAA,CAAQ,KAAA,CAAM,4CAA4C,KAAK,CAAA;AAC/D,QAAA,OAAO,QAAA,CAAS,KAAK,EAAE,KAAA,EAAO,uBAAsB,EAAG,EAAE,MAAA,EAAQ,GAAA,EAAK,CAAA;AAAA,MACxE;AACA,MAAA,OAAA,CAAQ,KAAA,CAAM,+DAA+D,KAAK,CAAA;AAClF,MAAA,OAAO,QAAA,CAAS,KAAK,EAAE,KAAA,EAAO,yBAAwB,EAAG,EAAE,MAAA,EAAQ,GAAA,EAAK,CAAA;AAAA,IAC1E;AAAA,EACF,CAAA;AACF","file":"index.js","sourcesContent":["import { isIP } from 'node:net'\n\n/**\n * Buyer IP forwarding: the server key and the buyer's IP address a buyer\n * client sends so the Lynkow API counts each buyer, rather than your server,\n * against its rate limits.\n *\n * Both values are read on the server only, from the environment and the\n * incoming request headers, and never reach a client bundle: this module is\n * imported by `@lynkow/next/server` alone.\n */\n\n/**\n * What a buyer client forwards: both values, or neither. Spread it into the\n * options of `createBuyerClient`.\n */\nexport interface BuyerForwarding {\n /** The site's server key, from `LYNKOW_SERVER_KEY`. */\n serverKey?: string\n /** The buyer's IP address, read from the request headers. */\n clientIp?: string\n}\n\n/** A valid HTTP header name: `Headers.get` throws on anything else. */\nconst HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/\n\n/**\n * The server key and the buyer's IP address to forward for one request, or\n * an empty object when there is nothing to forward. Server only, never\n * throws.\n *\n * `createBuyerClient` already does this on its own, for every write and for\n * `orders.getGuest()`, once `LYNKOW_SERVER_KEY` is set. Call it only from\n * custom code that builds its own client with `createClient` from `lynkow`:\n * `createClient({ siteId, ...resolveBuyerForwarding(await headers()) })`.\n *\n * Two variables are read on each call:\n *\n * - `LYNKOW_SERVER_KEY`: the site's server key (`lkw_srv_...`). Unset or\n * empty, nothing is forwarded.\n * - `LYNKOW_CLIENT_IP_HEADER`, optional: the name of one request header your\n * CDN or host sets, and overwrites on every request, with the visitor's\n * address. When set, that header alone is read, and a value holding a\n * comma, or that is not an IP address, forwards nothing.\n *\n * Otherwise the address comes from `X-Forwarded-For`, read from the right:\n * the first public address, skipping the private and internal ones\n * (loopback, private networks, carrier-grade NAT, link-local, IPv6 unique\n * local) that hosts append for their own hops. A visitor cannot write the\n * entries your host's proxy appended. An entry that is not an IP address\n * stops the walk. Behind a CDN in front of your host, that first public\n * address is the CDN's: set `LYNKOW_CLIENT_IP_HEADER` to the header your CDN\n * writes with the visitor's address.\n *\n * @param headers - The incoming request headers, such as `await headers()`\n * from `next/headers` or the `headers` of a `Request`.\n * @returns `{ serverKey, clientIp }`, or `{}` when the key is unset or no\n * address qualifies.\n */\nexport function resolveBuyerForwarding(headers: Pick<Headers, 'get'>): BuyerForwarding {\n try {\n const serverKey = readEnv('LYNKOW_SERVER_KEY')\n if (!serverKey) return {}\n const clientIp = resolveClientIp(headers, readEnv('LYNKOW_CLIENT_IP_HEADER'))\n return clientIp ? { serverKey, clientIp } : {}\n } catch {\n return {}\n }\n}\n\n/**\n * Whether `LYNKOW_SERVER_KEY` is set, which turns on the automatic forwarding\n * of `createBuyerClient`.\n */\nexport function hasServerKey(): boolean {\n return readEnv('LYNKOW_SERVER_KEY') !== undefined\n}\n\n/**\n * The forwarding headers of the current request, read through `next/headers`,\n * or `undefined` when there is nothing to forward or no request to read from\n * (a build, a script). Never throws, except to let through the signals Next\n * raises from `headers()` to stop a static render.\n */\nexport async function requestForwardingHeaders(): Promise<Record<string, string> | undefined> {\n let incoming: Pick<Headers, 'get'>\n try {\n // Imported on use, so a module that imports `@lynkow/next/server` never\n // loads `next/headers` until a write needs the buyer's address.\n const { headers } = await import('next/headers')\n incoming = await headers()\n } catch (error) {\n await rethrowNextSignal(error)\n return undefined\n }\n const { serverKey, clientIp } = resolveBuyerForwarding(incoming)\n return serverKey && clientIp\n ? { 'X-Lynkow-Server-Key': serverKey, 'X-Lynkow-Client-Ip': clientIp }\n : undefined\n}\n\n/**\n * Rethrows the errors Next uses for control flow (a dynamic render, a\n * postponed one), which must not be swallowed, and nothing else.\n */\nasync function rethrowNextSignal(error: unknown): Promise<void> {\n let rethrow: ((error: unknown) => void) | undefined\n try {\n rethrow = (await import('next/navigation')).unstable_rethrow\n } catch {\n return\n }\n rethrow?.(error)\n}\n\nfunction readEnv(name: string): string | undefined {\n const value = typeof process === 'undefined' ? undefined : process.env[name]\n return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n\n/**\n * The buyer's IP address: the override header's value when one is named,\n * otherwise the first public `X-Forwarded-For` entry from the right.\n */\nfunction resolveClientIp(\n headers: Pick<Headers, 'get'>,\n overrideHeader: string | undefined\n): string | undefined {\n if (overrideHeader) return singleIp(headers, overrideHeader)\n\n const entries = headers.get('x-forwarded-for')?.split(',') ?? []\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i]?.trim()\n if (!entry) continue\n if (isIP(entry) === 0) return undefined\n if (!isPublicIp(entry)) continue\n return entry\n }\n return undefined\n}\n\n/** The one IP address a header holds, or `undefined` for anything else. */\nfunction singleIp(headers: Pick<Headers, 'get'>, name: string): string | undefined {\n if (!HEADER_NAME.test(name)) return undefined\n const value = headers.get(name)?.trim()\n return value && !value.includes(',') && isIP(value) !== 0 ? value : undefined\n}\n\n/** Whether `ip`, already a valid IPv4 or IPv6 address, is publicly routable. */\nfunction isPublicIp(ip: string): boolean {\n const v4 = ipv4Octets(ip)\n if (v4) return isPublicIpv4(v4)\n const groups = ipv6Groups(ip)\n if (!groups) return false\n if (groups.every((group) => group === 0)) return false // ::\n if (groups.slice(0, 7).every((group) => group === 0) && groups[7] === 1) return false // ::1\n const first = groups[0] ?? 0\n return (first & 0xfe00) !== 0xfc00 && (first & 0xffc0) !== 0xfe80 && (first & 0xff00) !== 0xff00\n}\n\nfunction isPublicIpv4([a, b]: number[]): boolean {\n return !(\n a === 0 ||\n a === 10 ||\n a === 127 ||\n (a === 100 && b !== undefined && b >= 64 && b <= 127) ||\n (a === 169 && b === 254) ||\n (a === 172 && b !== undefined && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) ||\n (a !== undefined && a >= 224)\n )\n}\n\n/**\n * The four octets of an IPv4 address, written as such or as an IPv4-mapped\n * IPv6 address (`::ffff:a.b.c.d`), or `null` for any other address.\n */\nfunction ipv4Octets(ip: string): number[] | null {\n if (isIP(ip) === 4) return ip.split('.').map(Number)\n const groups = ipv6Groups(ip)\n if (!groups || !groups.slice(0, 5).every((group) => group === 0) || groups[5] !== 0xffff) {\n return null\n }\n const high = groups[6] ?? 0\n const low = groups[7] ?? 0\n return [high >> 8, high & 0xff, low >> 8, low & 0xff]\n}\n\n/**\n * The eight 16-bit groups of an IPv6 address, or null when it is not one or\n * carries a zone.\n */\nfunction ipv6Groups(ip: string): number[] | null {\n if (ip.includes('%') || isIP(ip) !== 6) return null\n let address = ip.toLowerCase()\n const dotted = address.match(/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/)\n if (dotted) {\n const [a = 0, b = 0, c = 0, d = 0] = dotted.slice(1).map(Number)\n address = `${address.slice(0, dotted.index)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`\n }\n const [head, tail] = address.split('::')\n const left = head ? head.split(':') : []\n const right = tail ? tail.split(':') : []\n const missing = address.includes('::') ? 8 - left.length - right.length : 0\n return [...left, ...Array<string>(missing).fill('0'), ...right].map((group) => parseInt(group, 16))\n}\n","import { createClient, type Client } from 'lynkow'\nimport { uncached } from '../cache.js'\nimport { baseClientConfig } from '../clients.js'\nimport type { LynkowNextConfig } from '../config.js'\nimport { hasServerKey, requestForwardingHeaders } from './buyer-forwarding.js'\n\n/**\n * The buyer session on the server: a Lynkow client created for one request and\n * seeded from that request's cookies, and the helpers that write and clear\n * those cookies.\n *\n * The SDK keeps a buyer's state on the client instance: the guest cart token\n * and the signed-in customer's session token. The clients of `createClients`\n * serve every request the process handles, so buyer state on one of them would\n * hand one visitor's cart or session to the next. A buyer client belongs to one\n * request and is dropped with it, and nothing in this module is kept between\n * calls.\n */\n\n/** The names of the two buyer cookies. */\nexport const BUYER_COOKIE_NAMES = {\n /** The guest cart token. */\n cart: '__Host-lynkow-cart',\n /** The signed-in customer's session token. */\n customer: '__Host-lynkow-customer',\n} as const\n\nconst THIRTY_DAYS_S = 30 * 24 * 60 * 60\n\n/**\n * The longest life of the customer cookie, in seconds: the 30 days the Lynkow\n * API gives a customer session token. A cookie that outlived its token would\n * only keep sending a credential the API refuses.\n */\nconst CUSTOMER_MAX_AGE_S = THIRTY_DAYS_S\n\n/**\n * The longest life of the cart cookie, in seconds. The API issues guest cart\n * tokens with no expiry, so the cookie takes the customer session's 30 days\n * rather than living as long as the browser keeps it.\n */\nconst CART_MAX_AGE_S = THIRTY_DAYS_S\n\n/** The longest token value accepted, about what a browser stores in one cookie. */\nconst MAX_TOKEN_LENGTH = 4096\n\n/**\n * Visible ASCII except `,` and `;`. The value becomes a cookie and then a\n * request header (`X-Lynkow-Cart-Token`, `Authorization: Bearer`), so a space,\n * a line break or a separator would let one value smuggle in another.\n */\nconst TOKEN_VALUE = /^[\\x21-\\x2b\\x2d-\\x3a\\x3c-\\x7e]+$/\n\n/**\n * Reads a cookie by name. `await cookies()` from `next/headers` and the\n * `cookies` of a `NextRequest` are both readers.\n */\nexport interface BuyerCookieReader {\n get(name: string): { value: string } | undefined\n}\n\n/**\n * Writes a cookie. `await cookies()` from `next/headers`, in a Server Action or\n * a Route Handler, and the `cookies` of a `NextResponse` are both writers.\n */\nexport interface BuyerCookieWriter {\n set(name: string, value: string, options: BuyerCookieAttributes): unknown\n}\n\n/**\n * The attributes of every buyer cookie. The `__Host-` prefix makes the browser\n * refuse the cookie unless it is `Secure`, has `Path=/` and names no `Domain`,\n * so a subdomain can neither read nor plant it. `HttpOnly` keeps it out of\n * page scripts, and `SameSite=Lax` keeps it off cross-site subrequests and\n * form posts.\n */\nexport interface BuyerCookieAttributes {\n httpOnly: true\n secure: true\n sameSite: 'lax'\n path: '/'\n /** Seconds the browser keeps the cookie; `0` deletes it. */\n maxAge: number\n}\n\n/** The two buyer tokens a request carries, each `null` when absent or unusable. */\nexport interface BuyerTokens {\n cartToken: string | null\n customerToken: string | null\n}\n\n/** Options of {@link createBuyerClient}. */\nexport interface BuyerClientOptions {\n /**\n * The locale the client reads in, typically the route's. Omitted, the API\n * answers in the site's default locale.\n */\n locale?: string\n /**\n * The site's server key (`lkw_srv_...`), created on the Storefront settings\n * page. A secret API token also works. With `clientIp`, it makes the API\n * count this buyer, rather than your server, against its rate limits.\n * Leave both unset to let the client forward them on its own from\n * `LYNKOW_SERVER_KEY`. Setting either one turns that off for this client.\n */\n serverKey?: string\n /**\n * The buyer's IP address, read from a request header your host sets and\n * overwrites. Sent only together with `serverKey`.\n */\n clientIp?: string\n}\n\n/** Options of {@link setCartCookie} and {@link setCustomerCookie}. */\nexport interface BuyerCookieOptions {\n /**\n * When the token stops being valid, as a `Date` or epoch milliseconds. The\n * cookie then lives until that moment, never longer than its 30-day ceiling.\n * A moment already past deletes the cookie instead of writing the token.\n */\n expiresAt?: Date | number\n}\n\n/** Options of {@link signOut}. */\nexport interface SignOutOptions {\n /**\n * `true` also revokes, through the API, every session this customer has open\n * on any device. Omitted, signing out forgets the session on this site only\n * and makes no request to the API, so the token stays valid on the API until\n * it expires.\n */\n everywhere?: boolean\n}\n\n/**\n * Reads the buyer's cart token and customer token from a request or a cookie\n * store.\n *\n * A value that is empty, longer than 4096 characters, or holds anything but\n * visible ASCII without `,` and `;` is treated as absent: it is never thrown\n * on and never forwarded, since the token travels on as a request header. A\n * cookie sent twice keeps its last value, as Next's own cookie reader does.\n *\n * @param source - The incoming `Request` (a `NextRequest` is one), or a cookie\n * store such as `await cookies()` from `next/headers`.\n */\nexport function readBuyerTokens(source: Request | BuyerCookieReader): BuyerTokens {\n const read = isRequest(source)\n ? (name: string) => cookieFromHeader(source.headers.get('cookie'), name)\n : (name: string) => source.get(name)?.value\n\n return {\n cartToken: usableToken(read(BUYER_COOKIE_NAMES.cart)),\n customerToken: usableToken(read(BUYER_COOKIE_NAMES.customer)),\n }\n}\n\n/**\n * Creates the Lynkow client of ONE buyer request, seeded with the cart token\n * and the customer token read from the buyer cookies.\n *\n * Call it in a Server Component, a Server Action or a Route Handler, once per\n * request, and drop the client with the request. Never store it in a module\n * variable, a cache or a client shared between requests: the SDK keeps the\n * cart and the session on the instance, so a shared buyer client hands one\n * visitor's cart or session to the next. For the same reason, never use the\n * clients of `createClients` for `cart` or `customers` calls on the server.\n *\n * Every read of this client bypasses the Next cache (`cache: 'no-store'`, the\n * same option as `uncached()`), because a buyer's cart and account must never\n * be cached for another visitor. Do not pass `cached()` or a `cache` option to\n * its reads, do not call it inside a `'use cache'` function, and do not use it\n * on a route whose `fetchCache` is `'force-cache'` or `'only-cache'`, which\n * would override `no-store`. The SDK's own cache is off.\n *\n * Every call reaches the API from your server, so without forwarding the API\n * sees your server's address for every buyer, and the buyers of your store\n * share one rate limit on sign-in and other per-visitor limits. Set\n * `LYNKOW_SERVER_KEY` to the site's server key and the client forwards the\n * buyer's IP address with it on every write (POST, PATCH, PUT, DELETE) and\n * on the guest order read (`orders.getGuest()`), resolved from the request\n * headers as `resolveBuyerForwarding` describes. Other reads never touch the\n * request headers, so forwarding never makes a page dynamic. Passing\n * `serverKey` or `clientIp` yourself replaces this for the client.\n *\n * @param config - The configuration from `resolveConfig`.\n * @param source - The incoming `Request` (a `NextRequest` is one), or a cookie\n * store such as `await cookies()` from `next/headers`.\n * @param options - See {@link BuyerClientOptions}.\n *\n * @example\n * // src/app/cart/page.tsx\n * import { cookies } from 'next/headers'\n * import { createBuyerClient } from '@lynkow/next/server'\n *\n * export default async function CartPage() {\n * const buyer = createBuyerClient(config, await cookies())\n * const cart = await buyer.cart.retrieve()\n * // ...\n * }\n */\nexport function createBuyerClient(\n config: LynkowNextConfig,\n source: Request | BuyerCookieReader,\n options: BuyerClientOptions = {}\n): Client {\n const { cartToken, customerToken } = readBuyerTokens(source)\n const explicit = options.serverKey !== undefined || options.clientIp !== undefined\n const serverKey = options.serverKey?.trim()\n const clientIp = options.clientIp?.trim()\n\n const client = createClient({\n ...baseClientConfig(config, options.locale),\n ...(customerToken ? { customerToken } : {}),\n // The secret stays on this per-request client and never enters the\n // resolved config, which reaches client bundles. Both or neither: the\n // SDK sends the pair only when both are present.\n ...(serverKey && clientIp ? { serverKey, clientIp } : {}),\n // Resolved per write and only then, so a read never calls `headers()`.\n ...(!explicit && hasServerKey() ? { requestHeaders: forwardOnWrites } : {}),\n // A client-wide option, so it also covers the reads that take no request\n // options, such as `customers.me()`.\n fetchOptions: uncached().fetchOptions,\n })\n if (cartToken) client.cart.setCartToken(cartToken)\n\n return client\n}\n\nconst WRITE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/**\n * The reads the API rate-limits per buyer, which forward too. Each is scoped\n * to one buyer by a token or a cookie, so its page is dynamic already and\n * reading `headers()` there changes nothing. Keep in step with the GET routes\n * of `apps/api/start/routes.ts` that carry a per-client write bucket.\n */\nconst FORWARDED_READS = [\n // GET /storefront/:siteId/orders/guest, on the form-submission bucket.\n /\\/storefront\\/[^/]+\\/orders\\/guest$/,\n]\n\n/** The SDK header provider of automatic forwarding: writes, and the reads above. */\nfunction forwardOnWrites({\n method,\n url,\n}: {\n method: string\n url: string\n}): Promise<Record<string, string> | undefined> | undefined {\n return WRITE_METHODS.has(method) || (method === 'GET' && isForwardedRead(url))\n ? requestForwardingHeaders()\n : undefined\n}\n\nfunction isForwardedRead(url: string): boolean {\n let pathname: string\n try {\n pathname = new URL(url).pathname\n } catch {\n return false\n }\n return FORWARDED_READS.some((pattern) => pattern.test(pathname))\n}\n\n/**\n * Stores the guest cart token in the buyer's cart cookie, for 30 days at most.\n *\n * Call it from a Server Action or a Route Handler only: Next refuses to set a\n * cookie while a page renders. The `__Host-` cookie needs HTTPS, or a browser\n * that treats `localhost` as secure.\n *\n * @param store - `await cookies()` from `next/headers`, or the `cookies` of a `NextResponse`.\n * @param token - The token `cart.getCartToken()` returns once a guest cart exists.\n * @param options - See {@link BuyerCookieOptions}.\n * @throws {TypeError} When the token is empty, too long or not cookie-safe, or\n * `expiresAt` is not a valid date. Nothing is written then.\n */\nexport function setCartCookie(\n store: BuyerCookieWriter,\n token: string,\n options: BuyerCookieOptions = {}\n): void {\n writeToken(store, BUYER_COOKIE_NAMES.cart, token, CART_MAX_AGE_S, options.expiresAt)\n}\n\n/**\n * Stores the customer session token in the buyer's customer cookie, for 30\n * days at most, the lifetime of a session the Lynkow API issues.\n *\n * Call it with the token `customers.login()` has just returned, from a Server\n * Action or a Route Handler only: Next refuses to set a cookie while a page\n * renders. The token is a bearer credential: it goes into this `HttpOnly`\n * cookie and nowhere a page script can read it. The `__Host-` cookie needs\n * HTTPS, or a browser that treats `localhost` as secure.\n *\n * @param store - `await cookies()` from `next/headers`, or the `cookies` of a `NextResponse`.\n * @param token - The session token, opaque: it is stored as it is, never decoded.\n * @param options - See {@link BuyerCookieOptions}.\n * @throws {TypeError} When the token is empty, too long or not cookie-safe, or\n * `expiresAt` is not a valid date. Nothing is written then.\n *\n * @example\n * 'use server'\n * import { cookies } from 'next/headers'\n * import { createBuyerClient, setCustomerCookie } from '@lynkow/next/server'\n *\n * export async function login(email: string, password: string) {\n * const store = await cookies()\n * const { token } = await createBuyerClient(config, store).customers.login({ email, password })\n * setCustomerCookie(store, token)\n * }\n */\nexport function setCustomerCookie(\n store: BuyerCookieWriter,\n token: string,\n options: BuyerCookieOptions = {}\n): void {\n writeToken(store, BUYER_COOKIE_NAMES.customer, token, CUSTOMER_MAX_AGE_S, options.expiresAt)\n}\n\n/**\n * Deletes both buyer cookies: the cart and the customer session.\n *\n * Each is overwritten empty with `Max-Age=0` and the same `__Host-`\n * attributes it was set with. A store's own `delete` would not do: it writes\n * no `Secure`, and a browser ignores a `__Host-` cookie without `Secure`, so\n * the old cookie would silently survive.\n *\n * Call it from a Server Action or a Route Handler only.\n *\n * @param store - `await cookies()` from `next/headers`, or the `cookies` of a `NextResponse`.\n */\nexport function clearBuyerCookies(store: BuyerCookieWriter): void {\n store.set(BUYER_COOKIE_NAMES.cart, '', attributes(0))\n store.set(BUYER_COOKIE_NAMES.customer, '', attributes(0))\n}\n\n/**\n * Signs the buyer out: calls the SDK's `customers.logout()` on the request's\n * buyer client, then deletes both buyer cookies and forgets the cart on that\n * client.\n *\n * By default the logout forgets the session on this site and makes no\n * request to the API: the session token itself stays valid on the API until\n * it expires, so a copy taken earlier keeps working. With\n * `{ everywhere: true }` it sends `POST /customers/logout`, which revokes\n * every session this customer has open, the only revocation the API offers.\n * The cookies are deleted even when that call fails, and the failure is then\n * rethrown.\n *\n * Call it from a Server Action or a Route Handler only. In a Route Handler,\n * catch that failure and return a response: Next sends the cookies a handler\n * set only with the response it returns, so a handler that throws leaves both\n * cookies in the browser.\n *\n * @param client - The buyer client of this request, from {@link createBuyerClient}.\n * @param store - `await cookies()` from `next/headers`, or the `cookies` of a `NextResponse`.\n * @param options - See {@link SignOutOptions}.\n */\nexport async function signOut(\n client: Client,\n store: BuyerCookieWriter,\n options: SignOutOptions = {}\n): Promise<void> {\n try {\n await client.customers.logout(options)\n } finally {\n // The cookies first: they are what outlives this request.\n clearBuyerCookies(store)\n client.cart.setCartToken(null)\n }\n}\n\n/** Writes one token cookie, or deletes it when its expiry has already passed. */\nfunction writeToken(\n store: BuyerCookieWriter,\n name: string,\n token: string,\n ceiling: number,\n expiresAt: Date | number | undefined\n): void {\n if (!isTokenValue(token)) {\n // The value itself is a credential, so it never goes into the message.\n throw new TypeError(\n `${name} takes 1 to ${MAX_TOKEN_LENGTH} visible ASCII characters, without \",\" or \";\"`\n )\n }\n const maxAge = lifetime(ceiling, expiresAt)\n store.set(name, maxAge > 0 ? token : '', attributes(maxAge))\n}\n\n/** Whole seconds until `expiresAt`, at most `ceiling`, never below zero. */\nfunction lifetime(ceiling: number, expiresAt: Date | number | undefined): number {\n if (expiresAt === undefined) return ceiling\n const at = expiresAt instanceof Date ? expiresAt.getTime() : expiresAt\n if (typeof at !== 'number' || Number.isNaN(at)) {\n throw new TypeError('expiresAt is not a valid date')\n }\n return Math.min(ceiling, Math.max(0, Math.floor((at - Date.now()) / 1000)))\n}\n\n/** A fresh attribute object per cookie, so no store can alter another's. */\nfunction attributes(maxAge: number): BuyerCookieAttributes {\n return { httpOnly: true, secure: true, sameSite: 'lax', path: '/', maxAge }\n}\n\nfunction isTokenValue(value: unknown): value is string {\n return typeof value === 'string' && value.length <= MAX_TOKEN_LENGTH && TOKEN_VALUE.test(value)\n}\n\nfunction usableToken(value: unknown): string | null {\n return isTokenValue(value) ? value : null\n}\n\n/**\n * Whether the source is a request rather than a cookie store. Tested on the\n * shape rather than with `instanceof`, which fails across runtimes that each\n * have their own `Request`.\n */\nfunction isRequest(source: Request | BuyerCookieReader): source is Request {\n const headers = (source as { headers?: unknown }).headers\n return (\n typeof headers === 'object' &&\n headers !== null &&\n typeof (headers as { get?: unknown }).get === 'function'\n )\n}\n\n/**\n * The decoded value of a cookie in a `Cookie` header. A pair that does not\n * decode is skipped, and the last pair of a name wins, as in Next's reader.\n */\nfunction cookieFromHeader(header: string | null, name: string): string | undefined {\n if (!header) return undefined\n let value: string | undefined\n for (const pair of header.split(';')) {\n const at = pair.indexOf('=')\n if (at === -1 || pair.slice(0, at).trim() !== name) continue\n try {\n value = decodeURIComponent(pair.slice(at + 1).trim())\n } catch {\n // Not percent-decodable: ignored, like any other malformed pair.\n }\n }\n return value\n}\n","/**\n * The buyer session on an Astro server: a Lynkow client created for one\n * request and seeded from that request's cookies, and the helpers that write\n * and clear those cookies through `Astro.cookies` (or `context.cookies` in an\n * endpoint, a middleware or an action).\n *\n * The cookie rules, the token checks and the IP forwarding are the ones of\n * `@lynkow/next`, shared with it: both buyer cookies are `__Host-`, `Secure`,\n * `HttpOnly`, `SameSite=Lax`, and live 30 days at most.\n */\nimport type { AstroCookies } from 'astro'\nimport type { Client } from 'lynkow'\nimport type { LynkowNextConfig } from '../../../lynkow-next/src/config.js'\nimport {\n BUYER_COOKIE_NAMES,\n clearBuyerCookies as clearShared,\n createBuyerClient as createShared,\n readBuyerTokens as readShared,\n setCartCookie as setCartShared,\n setCustomerCookie as setCustomerShared,\n signOut as signOutShared,\n type BuyerClientOptions,\n type BuyerCookieOptions,\n type BuyerTokens,\n type SignOutOptions,\n} from '../../../lynkow-next/src/server/buyer-session.js'\n\nexport { BUYER_COOKIE_NAMES }\nexport type { BuyerClientOptions, BuyerCookieOptions, BuyerTokens, SignOutOptions }\n\n/**\n * Reads the buyer's cart token and customer token from `Astro.cookies` or the\n * incoming `Request`. A value that is empty, longer than 4096 characters, or\n * holds anything but visible ASCII without `,` and `;` is treated as absent.\n */\nexport function readBuyerTokens(source: AstroCookies | Request): BuyerTokens {\n return readShared(source)\n}\n\n/**\n * Creates the Lynkow client of ONE buyer request, seeded with the cart token\n * and the customer token read from the buyer cookies.\n *\n * Call it once per request, in a page, an endpoint or an action, and drop the\n * client with the request: the SDK keeps the cart and the session on the\n * instance, so a client shared between requests would hand one visitor's cart\n * or session to the next. Its reads are never cached.\n *\n * With `LYNKOW_SERVER_KEY` set to the site's server key, the client forwards\n * the buyer's IP address with it on every write and on the guest order read,\n * read from the current request, which the middleware of\n * `@lynkow/astro/middleware` (or `runWithRequest`) makes available. Passing\n * `serverKey` or `clientIp` yourself replaces this for the client.\n *\n * @example\n * ---\n * // src/pages/[locale]/cart.astro\n * import { createBuyerClient } from '@lynkow/astro/server'\n * const buyer = createBuyerClient(config, Astro.cookies, { locale })\n * const cart = await buyer.cart.retrieve()\n * ---\n */\nexport function createBuyerClient(\n config: LynkowNextConfig,\n source: AstroCookies | Request,\n options: BuyerClientOptions = {}\n): Client {\n return createShared(config, source, options)\n}\n\n/**\n * Stores the guest cart token in the buyer's cart cookie, for 30 days at most.\n * Call it from an endpoint, an action or a middleware, before the response\n * starts.\n *\n * @throws {TypeError} When the token is empty, too long or not cookie-safe, or\n * `expiresAt` is not a valid date. Nothing is written then.\n */\nexport function setCartCookie(\n cookies: AstroCookies,\n token: string,\n options: BuyerCookieOptions = {}\n): void {\n setCartShared(cookies, token, options)\n}\n\n/**\n * Stores the customer session token `customers.login()` returned in the\n * buyer's customer cookie, for 30 days at most. The token is a bearer\n * credential: it goes into this `HttpOnly` cookie and nowhere a page script\n * can read it.\n *\n * @throws {TypeError} When the token is empty, too long or not cookie-safe, or\n * `expiresAt` is not a valid date. Nothing is written then.\n */\nexport function setCustomerCookie(\n cookies: AstroCookies,\n token: string,\n options: BuyerCookieOptions = {}\n): void {\n setCustomerShared(cookies, token, options)\n}\n\n/**\n * Deletes both buyer cookies by overwriting them empty with `Max-Age=0` and\n * the same `__Host-` attributes they were set with.\n */\nexport function clearBuyerCookies(cookies: AstroCookies): void {\n clearShared(cookies)\n}\n\n/**\n * Signs the buyer out: `customers.logout()` on the request's buyer client,\n * then both buyer cookies deleted and the cart forgotten on that client. With\n * `{ everywhere: true }` it also revokes every session the customer has open,\n * through the API. The cookies are deleted even when that call fails, and the\n * failure is then rethrown.\n */\nexport async function signOut(\n client: Client,\n cookies: AstroCookies,\n options: SignOutOptions = {}\n): Promise<void> {\n await signOutShared(client, cookies, options)\n}\n","/**\n * Checks that a mutating request was sent by a page of this site.\n *\n * A browser sends `Origin` on a cross-origin request and on a POST, PUT, PATCH\n * or DELETE, so a mutating request whose `Origin` names another host, or names\n * none, did not come from a page of this site. Refusing it stops another site\n * from making a signed-in buyer's browser change their cart or account through\n * a Route Handler. Next runs a similar check on Server Actions by itself; a\n * Route Handler gets one only by calling this.\n *\n * Use it at the top of a mutating Route Handler (POST, PUT, PATCH, DELETE).\n * Not on a GET: a same-site GET often carries no `Origin`, and a GET must not\n * change anything anyway. A page served with `Referrer-Policy: no-referrer`\n * makes the browser send `Origin: null` even on its own POSTs, which this\n * check refuses.\n *\n * The request's host is the first value of `X-Forwarded-Host`, else `Host`,\n * else the host of the request URL, as in Next's own Server Action check.\n * Both sides are compared lowercased, port included.\n *\n * This only reads request headers. It is unrelated to `rewriteOrigin`, which\n * rewrites URLs inside a response body.\n *\n * @returns `null` when the request may proceed, otherwise a 403 response to\n * return as it is. Never throws on request input.\n *\n * @example\n * // src/app/api/cart/lines/route.ts\n * import { assertSameOrigin } from '@lynkow/next/server'\n *\n * export async function POST(request: Request) {\n * const refused = assertSameOrigin(request)\n * if (refused) return refused\n * // ...\n * }\n */\nexport function assertSameOrigin(request: Request): Response | null {\n const origin = originHost(request.headers.get('origin'))\n const host = requestHost(request)\n if (origin === null || host === null || origin !== host) {\n return Response.json({ error: 'Forbidden' }, { status: 403 })\n }\n return null\n}\n\n/**\n * The lowercased `host[:port]` of an `Origin` header, or null when it is\n * absent, empty, the opaque `null`, unparsable, or not http(s).\n */\nfunction originHost(value: string | null): string | null {\n const trimmed = value?.trim()\n if (!trimmed || trimmed === 'null') return null\n let url: URL\n try {\n url = new URL(trimmed)\n } catch {\n return null\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return null\n return url.host.toLowerCase() || null\n}\n\n/** The lowercased host the request was sent to, or null when none can be read. */\nfunction requestHost(request: Request): string | null {\n const forwarded = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim()\n const host = forwarded || request.headers.get('host')?.trim() || urlHost(request.url)\n return host ? host.toLowerCase() : null\n}\n\nfunction urlHost(url: string): string {\n try {\n return new URL(url).host\n } catch {\n return ''\n }\n}\n","import {\n resolveBuyerForwarding as resolveShared,\n type BuyerForwarding,\n} from '../../../lynkow-next/src/server/buyer-forwarding.js'\nimport { assertSameOrigin as assertShared } from '../../../lynkow-next/src/server/same-origin.js'\n\nexport type { BuyerForwarding }\n\n/**\n * The server key and the buyer's IP address to forward for one request, or\n * an empty object when there is nothing to forward. Server only, never throws.\n *\n * `createBuyerClient` already does this on its own once `LYNKOW_SERVER_KEY` is\n * set. Call it only from code that builds its own client with `createClient`\n * from `lynkow`: `createClient({ siteId, ...resolveBuyerForwarding(request.headers) })`.\n *\n * `LYNKOW_SERVER_KEY` is the site's server key (`lkw_srv_...`); unset, nothing\n * is forwarded. The address is the value of the one header\n * `LYNKOW_CLIENT_IP_HEADER` names, when set, else the first public\n * `X-Forwarded-For` entry from the right.\n *\n * @param headers - The incoming request headers, such as `Astro.request.headers`\n */\nexport function resolveBuyerForwarding(headers: Pick<Headers, 'get'>): BuyerForwarding {\n return resolveShared(headers)\n}\n\n/**\n * Checks that a mutating request was sent by a page of this site: its `Origin`\n * must name the request's host (`X-Forwarded-Host`, else `Host`, else the URL's\n * host), compared lowercased, port included. Astro checks the origin of form\n * submissions and actions on its own when `security.checkOrigin` is on; an\n * endpoint that changes a buyer's cart or account calls this at its top. Not on\n * a GET, which often carries no `Origin`.\n *\n * @returns `null` when the request may proceed, otherwise a 403 response to\n * return as it is. Never throws on request input.\n * @example\n * // src/pages/api/cart.ts\n * export const POST: APIRoute = async ({ request }) => {\n * const refused = assertSameOrigin(request)\n * if (refused) return refused\n * // ...\n * }\n */\nexport function assertSameOrigin(request: Request): Response | null {\n return assertShared(request)\n}\n","import type { BodyRewriter } from './origin.js'\n\n/** Props of the `JsonLdScript` component {@link createLynkowServer} returns. */\nexport interface JsonLdScriptProps {\n /** The schema.org nodes, such as a page's `structuredData.graph`. Nothing renders when empty. */\n nodes: object[] | null | undefined\n locale: string\n}\n\n/**\n * The payload of one `<script type=\"application/ld+json\">`: the nodes as a\n * single `@graph` under one `@context`, which is what lets nodes reference each\n * other by `@id`, with URLs on this site's public form: on this deployment's\n * origin, and without the default locale's prefix when it is served unprefixed.\n *\n * Every `<` is written `<`, which JSON reads back as the same character.\n * The HTML parser then never sees a tag inside the script: escaping only\n * `</script` would still let a `<!--` from CMS content change how the parser\n * reads the rest of the element.\n */\nexport function jsonLdPayload(\n nodes: object[],\n siteDomain: string | null | undefined,\n rewrite: BodyRewriter\n): string {\n const stripped = nodes.map((node) => {\n const copy = { ...(node as Record<string, unknown>) }\n delete copy['@context']\n return copy\n })\n const payload = JSON.stringify({ '@context': 'https://schema.org', '@graph': stripped })\n return rewrite(payload, siteDomain).replace(/</g, '\\\\u003c')\n}\n\nexport function createJsonLdScript(\n rewrite: BodyRewriter,\n getSiteDomain: (locale: string) => Promise<string | null | undefined>\n) {\n /**\n * A list of schema.org nodes as ONE `<script type=\"application/ld+json\">`.\n * An async server component: the site's domain is read to put the graph's\n * URLs on this site's public form, so they agree with the canonical tag.\n */\n return async function JsonLdScript({ nodes, locale }: JsonLdScriptProps) {\n if (!nodes || nodes.length === 0) return null\n const html = jsonLdPayload(nodes, await getSiteDomain(locale), rewrite)\n return <script type=\"application/ld+json\" dangerouslySetInnerHTML={{ __html: html }} />\n }\n}\n","import type { Metadata } from 'next'\nimport type {\n Content,\n Page,\n Product,\n ProductCategory,\n ProductCollection,\n ResolvedCategory,\n} from 'lynkow'\nimport type { LocalePaths } from '../locale-paths.js'\n\n/** The metadata builders {@link createLynkowServer} returns. */\nexport interface MetadataBuilders {\n /**\n * Next metadata from a Lynkow page's SEO block.\n *\n * The hreflang set is built from `page.alternates`, so a page translated into\n * two of five locales advertises two alternates rather than five dead ones,\n * plus `x-default`, the URL of the default locale's alternate (omitted when\n * the page has none). The fallbacks walk the same order the API does: an\n * explicit SEO field, then the Open Graph twin, then the page name.\n *\n * A page served in another locale than the one asked for (`isFallback`)\n * advertises no hreflang set, and its canonical URL is the default locale's\n * one: its SEO `canonicalUrl` when set, else the API's fallback canonical\n * (`page.canonicalUrl`, else `page.canonicalPath` made absolute), else the\n * default locale's alternate, else `fallbackPath` in the default locale.\n *\n * `og:locale` is the locale served, in the `ll_CC` form Open Graph uses\n * (`fr_FR`, `pt_BR`), and `og:locale:alternate` lists the other locales of\n * the hreflang set in the same form.\n *\n * An editor's `metaTitle` is the whole `<title>`, brand included, so it is\n * set `absolute` and a layout's `%s | <site name>` template is not appended\n * to it. Only the page name, the fallback, goes through the template.\n *\n * @param fallbackPath - The locale-agnostic path of the route, used for the\n * canonical URL when the page advertises no alternate for `locale`\n */\n pageMetadata(page: Page, locale: string, fallbackPath: string): Metadata\n\n /**\n * Metadata for a route the application owns rather than one Lynkow drives,\n * such as `/reviews`. Its hreflang set is every configured locale, the route\n * exists in each of them by construction, plus `x-default`, its URL in the\n * default locale. A single-language site gets no hreflang set.\n *\n * @param path - The locale-agnostic path, with a leading slash\n */\n routeMetadata(locale: string, path: string, title: string, description: string): Metadata\n\n /**\n * Next metadata from a blog article's SEO fields.\n *\n * The title is the article's `metaTitle`, set `absolute` like a page's, or\n * its title through the layout's template. The description is its\n * `metaDescription`, else its excerpt. The canonical URL is `canonicalUrl`\n * when set, else the site URL plus the article's path. Open Graph is of type\n * `article`, carries the article's own locale as `og:locale`, in `ll_CC`\n * form (the default locale when the article's is not configured), and falls\n * back to the featured image. `noIndex` and `noFollow` are applied\n * independently: an article can stay out of the index while its links are\n * still followed.\n *\n * On a multilingual site the hreflang set is built from `content.alternates`,\n * plus `x-default` when one of them is in the default locale, and\n * `og:locale:alternate` lists their locales. An article served in another\n * locale than the one asked for (`isFallback`) gets neither, and its\n * canonical URL is the default locale's one: `canonicalUrl` when set (the\n * merchant's, or the one the API fills on a fallback when the site has a\n * domain), else the default locale's alternate, else `canonicalPath` (the\n * path the API names canonical, sent when the site has no domain), else its\n * path, in the default locale.\n */\n articleMetadata(content: Content): Metadata\n\n /**\n * Next metadata for a blog category archive, from the category\n * `paths.resolve()` returns.\n *\n * The same rules as {@link MetadataBuilders.articleMetadata}. A category\n * carries no SEO fields, so the title is its name through the layout's\n * template, the description is its own, and the Open Graph image is its\n * image. Open Graph is of type `website`. The locale is the one the category\n * was served in, in `ll_CC` form (the default locale when the site does not\n * configure it), and its hreflang set comes from its `alternates`, which the\n * API sends only when the resolve carried a locale. A category served in\n * another locale than the one asked for (`isFallback`) gets no hreflang set.\n * Its canonical URL follows the same rule as\n * {@link MetadataBuilders.articleMetadata}.\n */\n categoryMetadata(category: ResolvedCategory): Metadata\n\n /**\n * Next metadata from a product's SEO fields.\n *\n * The same rules as {@link MetadataBuilders.articleMetadata}, with\n * `seoTitle` and `seoDescription` in place of the meta fields and the\n * product description as the fallback. The locale is the one the product was\n * served in, its `locale` (the default locale when it carries none or one the\n * site does not configure), and its hreflang set comes from its `alternates`.\n * On a fallback the canonical URL prefers `canonicalPath` to `path`. Open\n * Graph is of type `website`, and its image falls back to the first gallery\n * image and its alt text.\n */\n productMetadata(product: Product): Metadata\n\n /**\n * Next metadata from a product collection's SEO fields, on the rules of\n * {@link MetadataBuilders.productMetadata}. The image falls back to the\n * collection's own image and its alt text. A collection with no public path\n * and no `canonicalUrl` gets no canonical URL.\n */\n productCollectionMetadata(collection: ProductCollection): Metadata\n\n /**\n * Next metadata from a product category's SEO fields, on the rules of\n * {@link MetadataBuilders.productMetadata}, with the category name as the\n * fallback title. The image falls back to the category's own image and its\n * alt text. A category with no public path and no `canonicalUrl` gets no\n * canonical URL.\n */\n productCategoryMetadata(category: ProductCategory): Metadata\n}\n\n/**\n * The SEO fields an article, a product, a collection and a category share,\n * each already resolved to the record's own naming.\n */\ninterface RecordSeo {\n /** The editor's meta or SEO title: the whole `<title>` when set. */\n seoTitle: string | null\n /** The record's own title or name, which goes through the layout's template. */\n name: string\n /** The SEO description, else the record's excerpt or description. */\n description: string | null\n keywords: string | null\n canonicalUrl: string | null\n /** The path the API returned, or null when the record has no public URL. */\n path: string | null\n /**\n * The path the API names canonical, which a fallback's canonical URL prefers\n * to {@link RecordSeo.path}. Sent on a read that carried a locale.\n */\n canonicalPath?: string | null\n /** The record's translations, each with its locale and the path the API returned. */\n alternates?: readonly Alternate[] | null\n /** Whether the record was served in another locale than the one asked for. */\n isFallback?: boolean\n ogTitle: string | null\n ogDescription: string | null\n ogImage: string | null\n ogImageAlt: string | null\n /** The record's own image, used when no Open Graph image is set. */\n image: { url: string; alt: string | null } | null\n twitterCard: Product['twitterCard']\n noIndex: boolean\n noFollow: boolean\n}\n\n/** One translation of a record: its locale and the path the API returned for it. */\ninterface Alternate {\n locale: string\n path: string\n}\n\n/**\n * A locale in the `ll_CC` form of `og:locale`: `fr` is `fr_FR`, `pt-BR` is\n * `pt_BR`, `zh-Hant` is `zh_TW`. A tag with no region takes its most likely\n * one. A tag that does not parse, or resolves no region, is returned as given.\n */\nfunction ogLocale(tag: string): string {\n try {\n const parsed = new Intl.Locale(tag)\n const region = parsed.region ?? parsed.maximize().region\n return region ? `${parsed.language.toLowerCase()}_${region.toUpperCase()}` : tag\n } catch {\n return tag\n }\n}\n\n/**\n * The `og:locale:alternate` list: each locale of `locales` in `ll_CC` form,\n * once, without the served one, or undefined when none is left.\n */\nfunction ogAlternateLocales(served: string, locales: readonly string[]): string[] | undefined {\n const own = ogLocale(served)\n const list = [...new Set(locales.map(ogLocale))].filter((code) => code !== own)\n return list.length > 0 ? list : undefined\n}\n\n/**\n * A Twitter card as the editor set it, in the shape Next renders.\n *\n * Next requires an app descriptor on an `app` card and a player descriptor on a\n * `player` card, which no Lynkow record holds, and its renderer reads the app\n * ids without a guard: an `app` card with no descriptor fails the whole page\n * render. Empty descriptors keep the card and emit no app or player tag.\n */\nfunction twitterCard(card: NonNullable<Product['twitterCard']>) {\n switch (card) {\n case 'app':\n return { card, app: { id: {} } }\n case 'player':\n return { card, players: [] }\n default:\n return { card }\n }\n}\n\nexport function createMetadataBuilders(paths: LocalePaths): MetadataBuilders {\n /** A path the API returned, made public and absolute. */\n function apiUrl(path: string, locale: string): string {\n return paths.absoluteUrl(paths.fromApiPath(path, locale))\n }\n\n /** A route this application owns, which the CMS knows nothing about. */\n function routeUrl(locale: string, path: string): string {\n return paths.absoluteUrl(paths.localePath(locale, path))\n }\n\n /**\n * The absolute URL of each alternate in a configured locale, keyed by that\n * locale's configured spelling. An alternate in a locale the site does not\n * configure is left out: its URL would not be served.\n */\n function alternateUrls(alternates: readonly Alternate[] | null | undefined): Record<string, string> {\n const urls: Record<string, string> = {}\n for (const alternate of alternates ?? []) {\n const code = paths.toLocale(alternate.locale)\n if (code) urls[code] = apiUrl(alternate.path, code)\n }\n return urls\n }\n\n /**\n * The hreflang set of `urls`, plus `x-default` when one of them is in the\n * default locale, or undefined when `urls` is empty. `x-default` is never\n * pointed at a URL no alternate vouches for.\n */\n function hreflang(urls: Record<string, string>): Record<string, string> | undefined {\n if (Object.keys(urls).length === 0) return undefined\n const byDefault = urls[paths.defaultLocale]\n return byDefault ? { ...urls, 'x-default': byDefault } : urls\n }\n\n function pageMetadata(page: Page, locale: string, fallbackPath: string): Metadata {\n const seo = page.seo\n const title = seo?.metaTitle || page.name || undefined\n const description = seo?.metaDescription || undefined\n const fallback = page.isFallback === true\n const urls = alternateUrls(page.alternates)\n\n let canonical: string\n if (fallback) {\n // The merchant's canonical, else the API's fallback canonical (absolute\n // when the site has a domain, a path otherwise), else the default\n // locale's alternate, else the route in the default locale.\n canonical =\n seo?.canonicalUrl ||\n page.canonicalUrl ||\n (page.canonicalPath ? apiUrl(page.canonicalPath, paths.defaultLocale) : undefined) ||\n urls[paths.defaultLocale] ||\n routeUrl(paths.defaultLocale, fallbackPath)\n } else {\n const wanted = paths.toLocale(locale)\n const current = wanted\n ? page.alternates?.find((alt) => paths.toLocale(alt.locale) === wanted)\n : undefined\n canonical =\n seo?.canonicalUrl ||\n (current ? apiUrl(current.path, locale) : routeUrl(locale, fallbackPath))\n }\n\n // The locale actually served: on a fallback, the page's own, not the route's.\n const served = fallback && page.locale ? page.locale : locale\n\n return {\n title: seo?.metaTitle ? { absolute: seo.metaTitle } : title,\n description,\n keywords: seo?.keywords?.length ? seo.keywords : undefined,\n alternates: {\n canonical,\n languages: fallback ? undefined : hreflang(urls),\n },\n robots: seo?.noIndex ? { index: false, follow: false } : undefined,\n openGraph: {\n type: 'website',\n locale: ogLocale(served),\n alternateLocale: fallback ? undefined : ogAlternateLocales(served, Object.keys(urls)),\n url: seo?.ogUrl || canonical,\n siteName: seo?.ogSiteName || undefined,\n title: seo?.ogTitle || title,\n description: seo?.ogDescription || description,\n images: seo?.ogImage?.url\n ? [{ url: seo.ogImage.url, alt: seo.ogImage.alt || undefined }]\n : undefined,\n },\n twitter: {\n ...twitterCard(seo?.twitterCard || 'summary_large_image'),\n title: seo?.twitterTitle || seo?.ogTitle || title,\n description: seo?.twitterDescription || seo?.ogDescription || description,\n images: seo?.twitterImage?.url ? [seo.twitterImage.url] : undefined,\n },\n }\n }\n\n function routeMetadata(\n locale: string,\n path: string,\n title: string,\n description: string\n ): Metadata {\n const url = routeUrl(locale, path)\n const multilingual = paths.locales.length > 1\n const languages = multilingual\n ? {\n ...Object.fromEntries(paths.locales.map((code) => [code, routeUrl(code, path)])),\n 'x-default': routeUrl(paths.defaultLocale, path),\n }\n : undefined\n\n return {\n title,\n description,\n alternates: { canonical: url, languages },\n openGraph: {\n type: 'website',\n locale: ogLocale(locale),\n alternateLocale: multilingual ? ogAlternateLocales(locale, paths.locales) : undefined,\n url,\n title,\n description,\n },\n }\n }\n\n /**\n * Next metadata from one record's SEO fields, in `locale`, the locale the\n * record was served in, which is both the `og:locale` and the locale an\n * unprefixed API path is read in.\n */\n function recordMetadata(\n record: RecordSeo,\n locale: string,\n type: 'article' | 'website'\n ): Metadata {\n const title = record.seoTitle || record.name\n const description = record.description || undefined\n const fallback = record.isFallback === true\n // A single-language site advertises no hreflang set.\n const urls = paths.locales.length > 1 ? alternateUrls(record.alternates) : {}\n const languages = fallback ? undefined : hreflang(urls)\n\n let canonical: string | undefined\n if (fallback) {\n // The default locale's URL: the API's canonical, else the default\n // locale's translation, else the record's own path in the default locale.\n const path = record.canonicalPath || record.path\n canonical =\n record.canonicalUrl ||\n alternateUrls(record.alternates)[paths.defaultLocale] ||\n (path ? apiUrl(path, paths.defaultLocale) : undefined)\n } else {\n canonical = record.canonicalUrl || (record.path ? apiUrl(record.path, locale) : undefined)\n }\n const image = record.ogImage ? { url: record.ogImage, alt: record.ogImageAlt } : record.image\n\n return {\n title: record.seoTitle ? { absolute: record.seoTitle } : record.name,\n description,\n keywords: record.keywords || undefined,\n alternates:\n canonical || languages\n ? { ...(canonical ? { canonical } : {}), ...(languages ? { languages } : {}) }\n : undefined,\n // Independent, unlike a page's: a record can stay out of the index while\n // its links are still followed, or the reverse.\n robots:\n record.noIndex || record.noFollow\n ? { index: !record.noIndex, follow: !record.noFollow }\n : undefined,\n openGraph: {\n type,\n locale: ogLocale(locale),\n alternateLocale: languages ? ogAlternateLocales(locale, Object.keys(urls)) : undefined,\n url: canonical,\n title: record.ogTitle || title,\n description: record.ogDescription || description,\n images: image ? [{ url: image.url, alt: image.alt || undefined }] : undefined,\n },\n twitter: record.twitterCard ? twitterCard(record.twitterCard) : undefined,\n }\n }\n\n function articleMetadata(content: Content): Metadata {\n // A post is served in its own locale, the default one when the site does\n // not configure it.\n const locale = paths.toLocale(content.locale) ?? paths.defaultLocale\n return recordMetadata(\n {\n seoTitle: content.metaTitle,\n name: content.title,\n description: content.metaDescription || content.excerpt,\n keywords: content.keywords,\n canonicalUrl: content.canonicalUrl,\n path: content.path,\n canonicalPath: content.canonicalPath,\n alternates: content.alternates,\n isFallback: content.isFallback,\n ogTitle: content.ogTitle,\n ogDescription: content.ogDescription,\n ogImage: content.ogImage,\n ogImageAlt: null,\n image: content.featuredImage ? { url: content.featuredImage, alt: null } : null,\n twitterCard: content.twitterCard,\n noIndex: content.noIndex,\n noFollow: content.noFollow,\n },\n locale,\n 'article'\n )\n }\n\n function categoryMetadata(category: ResolvedCategory): Metadata {\n // A category archive is served in the category's own locale, the default\n // one when the site does not configure it.\n const locale = paths.toLocale(category.locale) ?? paths.defaultLocale\n return recordMetadata(\n {\n seoTitle: null,\n name: category.name,\n description: category.description,\n keywords: null,\n canonicalUrl: category.canonicalUrl ?? null,\n path: category.path,\n canonicalPath: category.canonicalPath,\n alternates: category.alternates,\n isFallback: category.isFallback,\n ogTitle: null,\n ogDescription: null,\n ogImage: null,\n ogImageAlt: null,\n image: category.image ? { url: category.image, alt: null } : null,\n twitterCard: null,\n noIndex: false,\n noFollow: false,\n },\n locale,\n 'website'\n )\n }\n\n /**\n * The SEO and locale fields the three commerce records share, under the same\n * names. Each record is translated, so its metadata is built in the locale\n * it was served in, from its own alternates.\n */\n function commerceSeo(\n record: Product | ProductCollection | ProductCategory\n ): Omit<RecordSeo, 'name' | 'description' | 'path' | 'image'> {\n return {\n seoTitle: record.seoTitle,\n keywords: record.keywords,\n canonicalUrl: record.canonicalUrl,\n canonicalPath: record.canonicalPath,\n alternates: record.alternates,\n isFallback: record.isFallback,\n ogTitle: record.ogTitle,\n ogDescription: record.ogDescription,\n ogImage: record.ogImage,\n ogImageAlt: record.ogImageAlt,\n twitterCard: record.twitterCard,\n noIndex: record.noIndex,\n noFollow: record.noFollow,\n }\n }\n\n /** The locale a commerce record was served in, the default one when it names none. */\n function servedLocale(record: Product | ProductCollection | ProductCategory): string {\n return paths.toLocale(record.locale) ?? paths.defaultLocale\n }\n\n function productMetadata(product: Product): Metadata {\n const first = product.gallery[0]\n return recordMetadata(\n {\n ...commerceSeo(product),\n name: product.title,\n description: product.seoDescription || product.description,\n path: product.path,\n image: first ? { url: first.url, alt: first.alt } : null,\n },\n servedLocale(product),\n 'website'\n )\n }\n\n function productCollectionMetadata(collection: ProductCollection): Metadata {\n return recordMetadata(\n {\n ...commerceSeo(collection),\n name: collection.title,\n description: collection.seoDescription || collection.description,\n path: collection.path,\n image: collection.image ? { url: collection.image, alt: collection.imageAlt } : null,\n },\n servedLocale(collection),\n 'website'\n )\n }\n\n function productCategoryMetadata(category: ProductCategory): Metadata {\n return recordMetadata(\n {\n ...commerceSeo(category),\n name: category.name,\n description: category.seoDescription || category.description,\n path: category.path,\n image: category.image ? { url: category.image, alt: category.imageAlt } : null,\n },\n servedLocale(category),\n 'website'\n )\n }\n\n return {\n pageMetadata,\n routeMetadata,\n articleMetadata,\n categoryMetadata,\n productMetadata,\n productCollectionMetadata,\n productCategoryMetadata,\n }\n}\n","import type { LocalePaths } from '../locale-paths.js'\n\n/**\n * Rewrite the site's own domain to the origin this deployment is served from.\n *\n * Lynkow generates `sitemap.xml`, `robots.txt`, `llms.txt` and the JSON-LD\n * graph with absolute URLs built from the site's configured domain, which is\n * correct in production and wrong everywhere else: on localhost, on a preview\n * deployment or on a staging host, a verbatim copy would point at another site.\n *\n * When the two match, the body passes through untouched.\n *\n * @param body - What the API returned\n * @param siteDomain - The site's configured domain, such as `www.example.com`\n * @param siteUrl - The origin this deployment is served from, as `resolveConfig` returns it\n */\nexport function rewriteOrigin(\n body: string,\n siteDomain: string | null | undefined,\n siteUrl: string\n): string {\n if (!siteDomain) return body\n\n const sources = [`https://${siteDomain}`, `http://${siteDomain}`]\n return sources.reduce(\n (acc, source) => (source === siteUrl ? acc : acc.split(source).join(siteUrl)),\n body\n )\n}\n\n/**\n * Every absolute URL on `siteUrl` whose first segment is the default locale,\n * mapped to its unprefixed public form, the one the site serves: the default\n * locale never carries a locale segment.\n *\n * A body written by an API that still prefixed the default locale, or cached\n * from one, would otherwise list `/en/about`, which the API answers with a\n * redirect to `/about`.\n *\n * Only an absolute URL on `siteUrl` is touched, never a bare path in prose.\n * The segment is matched as the API writes it, lowercased, and only when a\n * `/`, `?`, `#`, a quote, `<`, `>`, whitespace, `)`, `]`, a backslash (a JSON\n * escape, in a JSON-LD graph) or the end of the body follows it, so `/en`\n * never matches inside `/en-gb/` or `/entry`. The pattern\n * is a literal followed by one lookahead, so its cost stays linear in the body.\n */\nexport function unprefixDefaultLocale(body: string, siteUrl: string, defaultLocale: string): string {\n const pattern = new RegExp(\n `${escapeRegExp(siteUrl)}/${escapeRegExp(defaultLocale.toLowerCase())}(?=[/?#\"'<>\\\\s)\\\\]\\\\\\\\]|$)`,\n 'g'\n )\n // `/en/about` loses `/en`, `/en?x` and `/en` alone become `/?x` and `/`.\n return body.replace(pattern, (match: string, offset: number) =>\n body[offset + match.length] === '/' ? siteUrl : `${siteUrl}/`\n )\n}\n\n/** Puts the absolute URLs of a body the API generated on this site's public form. */\nexport type BodyRewriter = (body: string, siteDomain: string | null | undefined) => string\n\n/**\n * The one place a body the API generated gets its public URLs: the site domain\n * moved to `siteUrl` by {@link rewriteOrigin}, then the default locale\n * unprefixed by {@link unprefixDefaultLocale}, always.\n *\n * The default locale is read from `paths` on every call, so it follows the\n * site's language settings when `paths` reads a runtime source.\n *\n * @param siteUrl - The origin this deployment is served from, as `resolveConfig` returns it\n * @param paths - The locale helpers the default locale is read from\n */\nexport function createBodyRewriter(\n siteUrl: string,\n paths: Pick<LocalePaths, 'defaultLocale'>\n): BodyRewriter {\n return (body, siteDomain) =>\n unprefixDefaultLocale(rewriteOrigin(body, siteDomain, siteUrl), siteUrl, paths.defaultLocale)\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n","/**\n * The `<head>` data of a page, flat and typed, built from the metadata\n * builders `@lynkow/next` shares with this package. An Astro layout renders it\n * with plain tags; nothing here renders HTML.\n */\n\n/** One hreflang alternate. */\nexport interface HeadAlternate {\n /** A configured locale, or `x-default`. */\n hreflang: string\n href: string\n}\n\n/** One Open Graph image. */\nexport interface HeadImage {\n url: string\n alt?: string\n}\n\n/** The Open Graph `article:*` tags of a blog article. */\nexport interface HeadArticle {\n /** `article:published_time`, an ISO 8601 date. */\n publishedTime?: string\n /** `article:modified_time`, an ISO 8601 date. */\n modifiedTime?: string\n /** One `article:author` per name. */\n authors: string[]\n /** One `article:tag` per tag name. */\n tags: string[]\n}\n\n/** The Open Graph tags of a page. */\nexport interface HeadOpenGraph {\n type?: string\n /** `og:locale`, in the `ll_CC` form Open Graph uses (`fr_FR`). */\n locale?: string\n /** `og:locale:alternate`, in the same form. */\n alternateLocales: string[]\n url?: string\n siteName?: string\n title?: string\n description?: string\n images: HeadImage[]\n /** The `article:*` tags, set by `articleHead` only. */\n article?: HeadArticle\n}\n\n/**\n * The Twitter card tags of a page. What the card leaves unset is taken from\n * Open Graph, as Next does: title, description and images.\n */\nexport interface HeadTwitter {\n /** The card set by the editor, else `summary_large_image` with an image and `summary` without. */\n card: string\n title?: string\n description?: string\n images: HeadImage[]\n}\n\n/** Everything a page's `<head>` needs for its SEO. */\nexport interface HeadData {\n /** The `<title>` text, before any layout template. */\n title?: string\n /**\n * `true` when {@link HeadData.title} is the editor's whole title, brand\n * included: a layout must not append its `%s | Site` template to it.\n */\n titleAbsolute: boolean\n description?: string\n /** The `keywords` meta, comma-separated. */\n keywords?: string\n /** The canonical URL. */\n canonical?: string\n /** The hreflang set, empty when the page advertises none. */\n alternates: HeadAlternate[]\n /** The `robots` meta, such as `noindex, nofollow`, or undefined to leave it out. */\n robots?: string\n openGraph?: HeadOpenGraph\n twitter?: HeadTwitter\n}\n\n/**\n * The subset of Next's `Metadata` the shared builders produce. Spelled out\n * here so this package reads it without depending on `next`.\n */\nexport interface BuiltMetadata {\n title?: string | { absolute: string } | null\n description?: string | null\n keywords?: string | string[] | null\n alternates?: {\n canonical?: string | null\n languages?: Record<string, string> | null\n } | null\n robots?: { index?: boolean; follow?: boolean } | null\n openGraph?: {\n type?: string\n locale?: string\n alternateLocale?: string[] | null\n url?: string | null\n siteName?: string | null\n title?: string | null\n description?: string | null\n images?: { url: string; alt?: string | null }[] | null\n } | null\n twitter?: {\n card?: string\n title?: string | null\n description?: string | null\n images?: string[] | null\n } | null\n}\n\nfunction text(value: string | null | undefined): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\n/** Puts optional fields on `target` only when they hold a value. */\nfunction assign<T extends object>(target: T, fields: { [K in keyof T]?: T[K] | undefined }): T {\n for (const [key, value] of Object.entries(fields)) {\n if (value !== undefined) (target as Record<string, unknown>)[key] = value\n }\n return target\n}\n\n/** Converts what a shared metadata builder returned into {@link HeadData}. */\nexport function toHeadData(metadata: BuiltMetadata): HeadData {\n const title = metadata.title\n const absolute = typeof title === 'object' && title !== null\n const head: HeadData = assign<HeadData>(\n { titleAbsolute: absolute, alternates: [] },\n {\n title: absolute ? text(title.absolute) : text(title),\n description: text(metadata.description),\n // Joined as Next's renderer joins them, with a bare comma.\n keywords: Array.isArray(metadata.keywords) ? text(metadata.keywords.join(',')) : text(metadata.keywords),\n canonical: text(metadata.alternates?.canonical),\n }\n )\n\n for (const [hreflang, href] of Object.entries(metadata.alternates?.languages ?? {})) {\n head.alternates.push({ hreflang, href })\n }\n\n if (metadata.robots) {\n const { index = true, follow = true } = metadata.robots\n head.robots = `${index ? 'index' : 'noindex'}, ${follow ? 'follow' : 'nofollow'}`\n }\n\n const og = metadata.openGraph\n if (og) {\n head.openGraph = assign<HeadOpenGraph>(\n {\n alternateLocales: [...(og.alternateLocale ?? [])],\n images: (og.images ?? []).map((image) =>\n assign<HeadImage>({ url: image.url }, { alt: text(image.alt) })\n ),\n },\n {\n type: text(og.type),\n locale: text(og.locale),\n url: text(og.url),\n siteName: text(og.siteName),\n // Next fills an Open Graph title and description left unset from the page's own.\n title: text(og.title) ?? head.title,\n description: text(og.description) ?? head.description,\n }\n )\n }\n\n // Next's rules (`postProcessMetadata`): with Open Graph, a Twitter card is\n // always emitted, and each of its title, description and images left unset\n // is taken from Open Graph, then from the page. Its card, when none is set,\n // is `summary_large_image` with an image and `summary` without.\n const twitter = metadata.twitter\n const openGraph = head.openGraph\n if (twitter || openGraph) {\n const images: HeadImage[] = twitter?.images\n ? twitter.images.map((url) => ({ url }))\n : (openGraph?.images ?? []).map((image) => ({ ...image }))\n head.twitter = assign<HeadTwitter>(\n {\n card: twitter?.card || (images.length > 0 ? 'summary_large_image' : 'summary'),\n images,\n },\n {\n title: text(twitter?.title) ?? openGraph?.title ?? head.title,\n description: text(twitter?.description) ?? openGraph?.description ?? head.description,\n }\n )\n }\n\n return head\n}\n","import type { APIRoute } from 'astro'\nimport {\n isLynkowError,\n type BaseRequestOptions,\n type Client,\n type Content,\n type Page,\n type Product,\n type ProductCategory,\n type ProductCollection,\n type ResolvedCategory,\n} from 'lynkow'\nimport { REVALIDATE, TAGS } from '../cache/policy.js'\nimport type { LynkowNextConfig } from '../../../lynkow-next/src/config.js'\nimport { createLocalePaths } from '../../../lynkow-next/src/locale-paths.js'\nimport { jsonLdPayload } from '../../../lynkow-next/src/server/json-ld.js'\nimport { createMetadataBuilders } from '../../../lynkow-next/src/server/metadata.js'\nimport { createBodyRewriter } from '../../../lynkow-next/src/server/origin.js'\nimport type { SiteLocales } from '../../../lynkow-next/src/site-locales.js'\nimport { cached } from '../cache/hint.js'\nimport { toHeadData, type BuiltMetadata, type HeadArticle, type HeadData } from './head.js'\n\n/** `Content-Type` of an XML text route, such as `sitemap.xml`. */\nexport const XML = 'application/xml; charset=utf-8'\n/** `Content-Type` of a plain text route, such as `robots.txt` or `llms.txt`. */\nexport const TEXT = 'text/plain; charset=utf-8'\n\nconst TEXT_CACHE_CONTROL = `public, max-age=0, s-maxage=${REVALIDATE.seo}, stale-while-revalidate=86400`\n\n/**\n * Reads one text file from Lynkow for a route. `options` carries the cache\n * tags and duration; pass it to the SDK call. `locale` is the route's, which a\n * localized file such as `llms.txt` passes explicitly, since the SDK reads the\n * locale of that call from its options.\n */\nexport type TextReader = (client: Client, options: BaseRequestOptions, locale: string) => Promise<string>\n\n/** Options of {@link createLynkowServer}. */\nexport interface LynkowServerOptions {\n config: LynkowNextConfig\n /** The client of a locale, typically the function `createClients(config)` returns. */\n client: (locale: string) => Client\n /**\n * The site's configured domain, which Lynkow builds the absolute URLs of\n * its generated files from, or null when it has none. Read it from a cached\n * call, such as the site configuration the layout already fetches.\n */\n getSiteDomain: (locale: string) => Promise<string | null | undefined>\n /**\n * The runtime source of the site's languages, from `createSiteLocales`.\n * Without a static locale list, `textRoute` and `jsonLd` await it; the head\n * builders and `rewriteOrigin`, which are synchronous, read its current\n * value, so call them once it has loaded (after `await siteLocales.get()`).\n */\n siteLocales?: SiteLocales\n}\n\n/** The server helpers {@link createLynkowServer} returns. */\nexport interface LynkowServer {\n /**\n * An Astro endpoint serving a text file Lynkow generates, such as\n * `sitemap.xml`, `robots.txt` or `llms.txt`: the upstream read is cached\n * under `TAGS.seo` and its URLs are put on their public form through\n * {@link LynkowServer.rewriteOrigin}. Under a `[locale]` segment the route's\n * locale is used; anywhere else, or for a locale that is not configured, the\n * default one. A file the site does not produce (Lynkow answers NOT_FOUND)\n * answers 404; any other error throws.\n *\n * @example\n * // src/pages/sitemap.xml.ts\n * export const prerender = false\n * export const GET = server.textRoute((client, options) => client.seo.sitemap(options), XML)\n */\n textRoute(read: TextReader, contentType: string): APIRoute\n\n /**\n * The payload of one `<script type=\"application/ld+json\">` holding `nodes`\n * as a single `@graph`, with URLs on this site's public form and every `<`\n * escaped, or null when there are no nodes. Render it with `set:html`.\n */\n jsonLd(nodes: object[] | null | undefined, locale: string): Promise<string | null>\n\n /**\n * The head of a Lynkow page, from its SEO block: canonical URL, hreflang set\n * from the page's own alternates, Open Graph and Twitter tags. The rules are\n * those of `pageMetadata` in `@lynkow/next`.\n *\n * @param fallbackPath - The locale-agnostic path of the route, for the\n * canonical URL when the page advertises no alternate for `locale`\n */\n pageHead(page: Page, locale: string, fallbackPath: string): HeadData\n /**\n * The head of a route the site owns rather than one Lynkow drives, such as\n * `/reviews`: its hreflang set is every configured locale.\n *\n * @param path - The locale-agnostic path, with a leading slash\n */\n routeHead(locale: string, path: string, title: string, description: string): HeadData\n /** The head of a blog article, from its SEO fields. */\n articleHead(content: Content): HeadData\n /** The head of a blog category archive, from the category `paths.resolve()` returns. */\n categoryHead(category: ResolvedCategory): HeadData\n /** The head of a product, from its SEO fields. */\n productHead(product: Product): HeadData\n /** The head of a product collection, from its SEO fields. */\n productCollectionHead(collection: ProductCollection): HeadData\n /** The head of a product category, from its SEO fields. */\n productCategoryHead(category: ProductCategory): HeadData\n\n /**\n * Puts the absolute URLs of a body the API generated on this site's public\n * form: the site's domain moved to `siteUrl`, and the default locale's\n * prefix removed. Synchronous, so with a runtime source it needs the\n * source loaded first.\n */\n rewriteOrigin(body: string, siteDomain: string | null | undefined): string\n}\n\n/**\n * The server-side helpers of a Lynkow site on Astro, bound to one\n * configuration: text routes, JSON-LD, and the head data of a page, an\n * article, a category, a product, a product collection and a product category.\n *\n * @example\n * // src/lib/server.ts\n * import { createLynkowServer } from '@lynkow/astro/server'\n *\n * export const server = createLynkowServer({\n * config,\n * client: (locale) => lynkow(locale),\n * getSiteDomain: async (locale) => (await getSiteShell(locale)).domain,\n * siteLocales,\n * })\n */\nexport function createLynkowServer({\n config,\n client,\n getSiteDomain,\n siteLocales,\n}: LynkowServerOptions): LynkowServer {\n const paths = createLocalePaths(config, siteLocales)\n const rewrite = createBodyRewriter(config.siteUrl, paths)\n const builders = createMetadataBuilders(paths)\n // Read only when the paths read it: a static locale list wins over the source.\n const live = config.locales.length > 0 ? undefined : siteLocales\n\n const head = <A extends unknown[]>(build: (...args: A) => unknown) =>\n (...args: A): HeadData => toHeadData(build(...args) as BuiltMetadata)\n\n function textRoute(read: TextReader, contentType: string): APIRoute {\n /** The file, or null when Lynkow does not produce it. */\n async function readText(locale: string): Promise<string | null> {\n try {\n return await read(client(locale), cached([TAGS.seo], REVALIDATE.seo), locale)\n } catch (error) {\n if (isLynkowError(error) && error.code === 'NOT_FOUND') return null\n throw error\n }\n }\n\n return async function GET({ params }) {\n await live?.get()\n const locale = paths.toLocale(params['locale']) ?? paths.defaultLocale\n const [domain, body] = await Promise.all([getSiteDomain(locale), readText(locale)])\n if (body === null) {\n return new Response('Not found', {\n status: 404,\n headers: { 'content-type': TEXT, 'cache-control': TEXT_CACHE_CONTROL },\n })\n }\n return new Response(rewrite(body, domain), {\n headers: { 'content-type': contentType, 'cache-control': TEXT_CACHE_CONTROL },\n })\n }\n }\n\n async function jsonLd(nodes: object[] | null | undefined, locale: string): Promise<string | null> {\n if (!nodes || nodes.length === 0) return null\n await live?.get()\n return jsonLdPayload(nodes, await getSiteDomain(locale), rewrite)\n }\n\n const buildArticleHead = head(builders.articleMetadata)\n\n /** The article's head, with the Open Graph `article:*` tags Next's builder leaves out. */\n function articleHead(content: Content): HeadData {\n const data = buildArticleHead(content)\n const article: HeadArticle = {\n authors: content.author?.fullName ? [content.author.fullName] : [],\n tags: (content.tags ?? []).map((tag) => tag.name),\n }\n if (content.publishedAt) article.publishedTime = content.publishedAt\n if (content.updatedAt) article.modifiedTime = content.updatedAt\n if (data.openGraph) data.openGraph.article = article\n return data\n }\n\n return {\n textRoute,\n jsonLd,\n pageHead: head(builders.pageMetadata),\n routeHead: head(builders.routeMetadata),\n articleHead,\n categoryHead: head(builders.categoryMetadata),\n productHead: head(builders.productMetadata),\n productCollectionHead: head(builders.productCollectionMetadata),\n productCategoryHead: head(builders.productCategoryMetadata),\n rewriteOrigin: rewrite,\n }\n}\n","/**\n * Stands in for `next/cache` in the code this package shares with\n * `@lynkow/next`: the revalidation handler calls `revalidateTag()`, which\n * here evicts the tag from the Astro data cache.\n *\n * The cache evicted is the one {@link runInvalidation} names, the process-wide\n * `lynkowCache` outside it. An eviction may be asynchronous with a shared\n * store, so the evictions started inside {@link runInvalidation} are awaited\n * before it returns.\n *\n * Built into this package by an esbuild alias, never imported from `next`.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks'\nimport { lynkowCache, type LynkowCache } from '../cache/lynkow-cache.js'\n\ninterface Invalidation {\n readonly cache: LynkowCache\n readonly pending: Promise<void>[]\n}\n\nconst STORAGE = Symbol.for('@lynkow/astro/invalidation')\n\nconst storage = ((globalThis as Record<symbol, unknown>)[STORAGE] ??=\n new AsyncLocalStorage<Invalidation>()) as AsyncLocalStorage<Invalidation>\n\n/**\n * Runs `fn` with `cache` as the target of `revalidateTag()`, then waits for\n * every eviction it started. The second deletion an eviction leaves to the\n * background after a slow store write (see `LynkowCache.invalidateTags`) is\n * not awaited.\n *\n * @throws The first eviction's failure, once `fn` has returned.\n */\nexport async function runInvalidation<T>(cache: LynkowCache, fn: () => Promise<T>): Promise<T> {\n const invalidation: Invalidation = { cache, pending: [] }\n const result = await storage.run(invalidation, fn)\n await Promise.all(invalidation.pending)\n return result\n}\n\n/**\n * Evicts `tag` from the current data cache. The second argument, the\n * staleness Next allows a reader, is ignored: an eviction here never serves\n * the evicted entry again.\n */\nexport function revalidateTag(tag: string, _profile?: unknown): undefined {\n const invalidation = storage.getStore()\n const done = (invalidation?.cache ?? lynkowCache).invalidateTags([tag])\n if (invalidation) {\n // Handled now, so a failure before `runInvalidation` awaits it is not an\n // unhandled rejection; `Promise.all` still sees it.\n done.catch(() => {})\n invalidation.pending.push(done)\n } else {\n done.catch((error: unknown) => {\n console.error('[lynkow] a cache tag could not be evicted', error)\n })\n }\n return undefined\n}\n","import { createHmac, timingSafeEqual } from 'node:crypto'\n\nconst PREFIX = 'sha256='\nconst HEX_DIGEST = /^[0-9a-f]{64}$/i\n\n/**\n * Verify a Lynkow webhook: its HMAC first, then the freshness of the timestamp\n * that HMAC covers.\n *\n * The API builds `{ event, timestamp, data }` once per delivery attempt, signs\n * `JSON.stringify` of it with the webhook's secret, sends the digest as\n * `X-Webhook-Signature: sha256=<hex>`, and POSTs that exact same string as the\n * body (`webhook_service.ts`, `sendWebhook` and `generateSignature`). So the raw\n * request text is verifiable byte for byte, and the `timestamp` inside it is\n * authenticated.\n *\n * That is why the handler reads `await request.text()` and never `request.json()`:\n * parsing and re-serialising would reorder no keys today, but it is not a\n * property JSON guarantees, and a signature checked against a re-serialisation\n * is a signature that fails for reasons nobody can reproduce.\n *\n * Returns `true` only when every check passes, and `false` for anything else,\n * including an empty secret, a missing or malformed header, a body that is not\n * JSON, and a stale or future timestamp. It never throws on request input, so a\n * crafted header is a rejection rather than a 500. The result deliberately does\n * not say which check failed.\n *\n * It is safe to call on its own: it does not rely on the caller having checked\n * that a secret is configured.\n */\nexport function verifySignature(rawBody: string, header: string | null, secret: string): boolean {\n // An empty key still produces a valid HMAC, one anybody can compute. A\n // verifier that accepted it would authenticate every request.\n if (typeof secret !== 'string' || secret.length === 0) return false\n if (typeof rawBody !== 'string') return false\n if (!hasSignatureShape(header)) return false\n\n const received = header.slice(PREFIX.length)\n const expected = createHmac('sha256', secret).update(rawBody).digest()\n if (!timingSafeEqual(Buffer.from(received, 'hex'), expected)) return false\n\n // Only a body the signature vouches for is parsed.\n return isFresh(rawBody, Date.now())\n}\n\n/**\n * Whether a header has the shape of a Lynkow signature, `sha256=` and 64 hex\n * digits, which a handler can check before reading the body.\n *\n * The FORMAT is validated before anything is compared. A string length counts\n * UTF-16 code units and a UTF-8 buffer counts bytes, so comparing text lets 64\n * non-ASCII characters through a length check and into `timingSafeEqual`,\n * which throws on a byte-length mismatch. Decoding validated hex yields exactly\n * 32 bytes on both sides, so the comparison cannot throw. The shape of a\n * SHA-256 hex digest is public, so this test leaks nothing.\n */\nexport function hasSignatureShape(header: string | null | undefined): header is string {\n return (\n typeof header === 'string' &&\n header.startsWith(PREFIX) &&\n HEX_DIGEST.test(header.slice(PREFIX.length))\n )\n}\n\n/**\n * How far the signed timestamp may sit from this server's clock, in either\n * direction. Without it, one captured request replays forever, and replaying a\n * revalidation is a free cache eviction lever.\n *\n * The API stamps every delivery ATTEMPT afresh, retries included, so this window\n * does not have to absorb the retry schedule, only one attempt's delay plus\n * clock skew between the API and this site. That delay is not capped by the\n * API's 30-second abort: the stamp is taken BEFORE the destination's DNS lookup,\n * which has no timeout of its own, and the abort covers only the 30 seconds\n * after the address resolves. A lookup slow enough to push an attempt past the\n * window fails closed: this site answers 401. That 401 is not always retried.\n * The API retries an event only when EVERY webhook subscribed to it failed, so\n * a retry, with a fresh stamp, follows only when no other webhook on that event\n * accepted it. With several webhooks on one event, a stale 401 here while\n * another one answered 2xx loses this revalidation, and the page stays stale\n * until its `REVALIDATE` ceiling runs out.\n */\nconst FRESHNESS_WINDOW_MS = 5 * 60 * 1000\n\n/** Fail closed: a missing, non-string or unparseable timestamp is not fresh. */\nfunction isFresh(rawBody: string, now: number): boolean {\n let envelope: unknown\n try {\n envelope = JSON.parse(rawBody)\n } catch {\n return false\n }\n if (typeof envelope !== 'object' || envelope === null) return false\n\n const timestamp = (envelope as { timestamp?: unknown }).timestamp\n if (typeof timestamp !== 'string') return false\n\n const signedAt = Date.parse(timestamp)\n if (!Number.isFinite(signedAt)) return false\n\n return Math.abs(now - signedAt) <= FRESHNESS_WINDOW_MS\n}\n","import { revalidateTag } from 'next/cache'\nimport { TAGS } from '../cache.js'\nimport type { SiteLocales } from '../site-locales.js'\nimport { hasSignatureShape, verifySignature } from './signature.js'\n\n/**\n * The largest body the handler reads. A delivery carries a summary of one\n * resource (the API leaves article bodies out of it) and the API itself refuses\n * a JSON body over 1 MiB, so every real delivery fits with room to spare, while\n * an unauthenticated caller cannot make this route buffer more.\n */\nconst MAX_BODY_BYTES = 5 * 1024 * 1024\n\n/** The body as text, or null past {@link MAX_BODY_BYTES}, declared or streamed. */\nasync function readBody(request: Request): Promise<string | null> {\n if (Number(request.headers.get('content-length')) > MAX_BODY_BYTES) return null\n if (!request.body) return ''\n\n const reader = request.body.getReader()\n const decoder = new TextDecoder()\n let text = ''\n let size = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) return text + decoder.decode()\n size += value.byteLength\n if (size > MAX_BODY_BYTES) {\n await reader.cancel()\n return null\n }\n text += decoder.decode(value, { stream: true })\n }\n}\n\n/** The envelope the Lynkow API POSTs to a webhook. */\nexport interface WebhookEnvelope {\n event: string\n timestamp: string\n data: Record<string, unknown>\n}\n\n/**\n * Which cache tags one resource drops.\n *\n * Keyed on the RESOURCE half of the event name rather than on the full name,\n * because the read side does not distinguish them: a page that reads the\n * article list is equally stale after a `content.created` and after a\n * `content.archived`.\n *\n * Eviction is deliberately generous. A tag dropped for nothing costs one API\n * round trip on the next request; a tag NOT dropped serves stale content until\n * the `REVALIDATE` ceiling expires, which is up to an hour.\n *\n * `slug` is present on the `content.*`, `form.*`, `category.*`, `tag.*` and\n * `site_block.*` payloads, and absent on `media.*`, `seo.updated` and\n * `site.updated`, which ask for no slug-scoped tag. The `product.*`,\n * `product_category.*` and `product_collection.*` payloads carry `slug` and\n * `path` too, and ask for none either: a site reads those records under its own\n * tags, which this table cannot know. Those records are search records as well,\n * and the SEO settings hold the search switches, so these events and\n * `seo.updated` also drop `TAGS.search`. A `site_block.*` payload\n * carries `slug` and `locale`, never `path`: a page read by path is evicted by\n * the collective `TAGS.pages`, and `TAGS.page(slug)` exists for pages read by\n * slug. The global blocks (header, footer, branding) are read under\n * `TAGS.site`. Only `site_block.created` names the block's `type`, so a\n * `site_block.*` event drops `TAGS.site` unless its payload says the block is\n * a `page` block.\n *\n * `site.updated` also announces a save of the cookie consent settings, with\n * `fields: ['cookie_consent']` (and a `locale` for a copy saved in one\n * language). An event naming that field alone drops `TAGS.consent` alone, see\n * {@link onlyConsentChanged}; any other `site.updated` drops it with the site\n * tags.\n *\n * A `product_variant.*` or `product_option.*` payload names its parent by\n * `productId` and carries no `slug` or `path`. Editing a variant or an option\n * fires that event only, never `product.updated`, yet it changes what a product\n * read returns: the variants, their prices, and the offers of the product's\n * structured data. Both take the list of a product event.\n *\n * A `review.*` payload carries no `slug` and no `path`. A product's structured\n * data carries the rating of its approved linked reviews, so a review event\n * stales a product read as well as the review lists. This package defines no\n * product tag, so a review event drops `TAGS.reviews` and `TAGS.paths`, the one\n * tag of this table a product event already drops for what `paths.resolve`\n * answers on a product URL (on a keyed client, the record with its graph).\n * Neither the sitemap nor a search record carries the rating, so `TAGS.seo` and\n * `TAGS.search` stay. A site whose product page reads its record under its own\n * tag must add `TAGS.reviews` (or `TAGS.paths`) to that read, or a new rating\n * waits out the `REVALIDATE` ceiling. The two exceptions, a review created\n * unpublished and a review event whose payload says no product is or was\n * linked, are made in {@link tagsForEvent}.\n */\nfunction tagsForResource(\n resource: string,\n slug: string | null,\n data: Record<string, unknown>\n): string[] {\n switch (resource) {\n case 'content':\n return [\n TAGS.contents,\n TAGS.paths,\n TAGS.seo,\n TAGS.search,\n ...(slug ? [TAGS.content(slug)] : []),\n ]\n\n case 'category':\n // A category archive is resolved through the same `paths.resolve` call as\n // an article, under `TAGS.content(<last segment>)`, so a renamed category\n // has to drop that key too.\n return [\n TAGS.categories,\n TAGS.contents,\n TAGS.paths,\n TAGS.seo,\n TAGS.search,\n ...(slug ? [TAGS.content(slug)] : []),\n ]\n\n case 'tag':\n return [TAGS.tags, TAGS.contents, TAGS.search]\n\n case 'site_block':\n // `type` is compared with one literal and never becomes part of a tag.\n return [\n TAGS.pages,\n TAGS.paths,\n TAGS.seo,\n ...(data['type'] === 'page' ? [] : [TAGS.site]),\n ...(slug ? [TAGS.page(slug)] : []),\n ]\n\n case 'variable':\n // Variables are interpolated inside block data, so a change is visible on\n // any page, not on one identifiable page.\n return [TAGS.pages, TAGS.site]\n\n case 'form':\n return [TAGS.forms, ...(slug ? [TAGS.form(slug)] : [])]\n\n case 'review':\n // The review lists, and the product reads whose graph carries the rating.\n // Built from constants only: nothing the payload carries ever becomes a\n // tag.\n return [TAGS.reviews, TAGS.paths]\n\n case 'media':\n // `media.replaced` swaps the file behind a URL that is embedded in block\n // data and in article bodies, and neither payload says where.\n return [TAGS.pages, TAGS.contents, TAGS.search]\n\n case 'redirect':\n return [TAGS.paths]\n\n case 'sitemap_entry':\n case 'sitemap_rule':\n return [TAGS.seo]\n\n case 'seo':\n case 'product':\n case 'product_category':\n case 'product_collection':\n case 'product_variant':\n case 'product_option':\n // The SEO settings hold the blog and commerce URL prefixes, so one save can\n // move every article and every product, category and collection URL. Each\n // product, category and collection is a URL the sitemap lists and\n // `paths.resolve` answers, so a rename, a move, a status change or a delete\n // stales both. The payloads carry `slug` and `path` but ask for no\n // slug-scoped tag: a site reads those records under its own tags. They are\n // also Lynkow search records, and the SEO settings hold the search\n // switches, so a search result page stales too. A variant or an option\n // changes the product read that `paths.resolve` answers (its variants,\n // prices and offers), which is what `TAGS.paths` covers; it takes the\n // whole product list so that the product and its sub-records stay one\n // rule, at the cost of one round trip for each of the two other tags.\n return [TAGS.seo, TAGS.paths, TAGS.search]\n\n case 'site':\n return [TAGS.site, TAGS.seo, TAGS.consent]\n\n case 'search_profile':\n case 'search_config':\n return [TAGS.search]\n\n default:\n return []\n }\n}\n\n/**\n * Whether a `site.updated` payload names the cookie consent settings as the\n * only change: `fields` is a non-empty array whose every entry is\n * `cookie_consent`. A missing `fields`, an empty one, or one naming anything\n * else answers no, and the event takes the full list of the table.\n */\nfunction onlyConsentChanged(data: unknown): boolean {\n if (typeof data !== 'object' || data === null) return false\n const fields = (data as Record<string, unknown>)['fields']\n return (\n Array.isArray(fields) && fields.length > 0 && fields.every((field) => field === 'cookie_consent')\n )\n}\n\n/**\n * Whether a review event's payload says that no product is, and none was,\n * linked to the reviews it concerns.\n *\n * Only an exact shape answers yes: `productId: null` on `review.created` and\n * `review.deleted`, `productId: null` together with `previousProductId: null`\n * on `review.updated` (the link after and before the update), and\n * `productIds: []` on `review.bulk_updated` and `review.bulk_deleted`.\n * Anything else answers no and keeps the generous list: a product id, a\n * non-empty list, a value of another type, and a missing key, which is what an\n * API older than these fields sends. The values are only compared with `null`\n * or measured as an empty array; none of them is ever read further, turned\n * into a tag or passed to Next.\n */\nfunction linksNoProduct(event: string, data: unknown): boolean {\n if (typeof data !== 'object' || data === null) return false\n const payload = data as Record<string, unknown>\n\n switch (event) {\n case 'review.created':\n case 'review.deleted':\n return payload['productId'] === null\n\n case 'review.updated':\n return payload['productId'] === null && payload['previousProductId'] === null\n\n case 'review.bulk_updated':\n case 'review.bulk_deleted': {\n const productIds = payload['productIds']\n return Array.isArray(productIds) && productIds.length === 0\n }\n\n default:\n return false\n }\n}\n\n/** The suffix of a grouped delivery: `content.published.batch`. */\nconst BATCH_SUFFIX = '.batch'\n\n/**\n * The tags one delivered event invalidates, deduplicated.\n *\n * An unknown event returns an empty list rather than throwing. Lynkow adds\n * events without asking its consumers, and a site that fails on an event it has\n * never heard of turns a new CMS feature into an outage.\n */\nexport function tagsForEvent(envelope: WebhookEnvelope): string[] {\n const batched = envelope.event.endsWith(BATCH_SUFFIX)\n const event = batched ? envelope.event.slice(0, -BATCH_SUFFIX.length) : envelope.event\n\n // `form.submitted` fires on every visitor submission and changes nothing a\n // site reads: the form schema is untouched and submissions are never listed.\n // Left in the table it would evict the schema of every form on a spam wave.\n // A burst of them, grouped into one delivery, changes nothing either.\n if (event === 'form.submitted') return []\n\n if (batched) return tagsForBatch(event, asRecord(envelope.data))\n\n // `review.created` is the event an anonymous visitor submission fires. A\n // review created pending or rejected is public nowhere, so it changes no\n // product rating: it keeps the review tag and leaves the path table alone.\n // Otherwise every submission held for moderation would evict that table, the\n // lever the line above closes for forms. A submission the site approves on\n // arrival is public at once and takes the full list. Only `review.created`\n // qualifies: a `review.updated` to `pending` is an un-approval, which does\n // change the rating. The status is compared with two literals and never\n // becomes part of a tag; a missing status, or any other value, takes the\n // generous list of the table.\n if (envelope.event === 'review.created') {\n const status = envelope.data?.['status']\n if (status === 'pending' || status === 'rejected') return [TAGS.reviews]\n }\n\n // A review linked to no product, before or after the event, feeds no\n // product's rating, so the path table stays. That also bounds what an\n // anonymous submission the site approves on arrival can evict: the review\n // lists, unless it names a product. See `linksNoProduct` for the exact\n // payloads that qualify; every other one takes the generous list.\n if (linksNoProduct(envelope.event, envelope.data)) return [TAGS.reviews]\n\n // A cookie consent save changes the consent configuration and nothing else.\n if (envelope.event === 'site.updated' && onlyConsentChanged(envelope.data)) {\n return [TAGS.consent]\n }\n\n const data = asRecord(envelope.data)\n const slug = data['slug']\n\n return [\n ...new Set(tagsForResource(resourceOf(event), typeof slug === 'string' ? slug : null, data)),\n ]\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {}\n}\n\nfunction resourceOf(event: string): string {\n return event.split('.')[0] ?? ''\n}\n\n/**\n * The tags of a grouped delivery, sent in place of many events of one type\n * that arrived together. Its `data.items` lists `{ id, slug }` for each event,\n * so it drops the resource's tags plus each listed slug's tag. A truncated\n * list loses nothing: the resource's collective tags are always dropped, and\n * a slug read by its own tag waits out the `REVALIDATE` ceiling at worst.\n *\n * The event name, never `data.event`, picks the resource, and a slug becomes\n * a tag only through the same `TAGS` builders as a single event.\n */\nfunction tagsForBatch(event: string, data: Record<string, unknown>): string[] {\n const resource = resourceOf(event)\n const items = Array.isArray(data['items']) ? data['items'] : []\n\n // The `review.created` rule of `tagsForEvent`, over a whole burst: one held\n // for moderation keeps the review tag only, so a wave of anonymous\n // submissions cannot evict the path table. Only a complete list qualifies,\n // since a truncated one does not show every status.\n if (\n event === 'review.created' &&\n data['truncated'] === false &&\n items.length > 0 &&\n items.every((item) => {\n const status = asRecord(item)['status']\n return status === 'pending' || status === 'rejected'\n })\n ) {\n return [TAGS.reviews]\n }\n\n const tags = new Set(tagsForResource(resource, null, {}))\n for (const item of items) {\n const slug = asRecord(item)['slug']\n if (typeof slug !== 'string' || slug === '') continue\n for (const tag of tagsForResource(resource, slug, {})) tags.add(tag)\n }\n return [...tags]\n}\n\n/** Options of {@link createRevalidateHandler}. */\nexport interface RevalidateHandlerOptions {\n /**\n * The webhook's signing secret, read by the application from a server-only\n * environment variable. Absent or empty, the endpoint stays closed.\n */\n secret: string | undefined\n /**\n * The runtime source of the site's languages, from `createSiteLocales`, when\n * the site reads its locales at runtime. A `site.updated` event, which the\n * API fires when the site's language settings change, marks it stale, so the\n * next request reads the new languages. One naming only the cookie consent\n * settings leaves it alone.\n */\n siteLocales?: SiteLocales\n}\n\n/**\n * The `POST` handler of a revalidation webhook.\n *\n * Point a Lynkow webhook at the route that exports it and give it the secret\n * passed here. Every event the webhook subscribes to drops the cache tags that\n * event can invalidate, so an edit is live in seconds instead of waiting out\n * the `REVALIDATE` ceiling. The route must run on Node, since the signature\n * check needs `node:crypto`.\n *\n * Given the site's runtime language source, a `site.updated` event also marks\n * that source stale, so the next request reads the site's languages again,\n * unless the event names the cookie consent settings as its only change.\n * Pass the same instance the rest of the application reads: a second one would\n * be marked stale while the first keeps serving its value until its own TTL.\n *\n * @example\n * // src/app/api/revalidate/route.ts\n * import { createRevalidateHandler } from '@lynkow/next/server'\n *\n * export const runtime = 'nodejs'\n * export const POST = createRevalidateHandler({ secret: process.env.LYNKOW_WEBHOOK_SECRET })\n */\nexport function createRevalidateHandler({ secret, siteLocales }: RevalidateHandlerOptions) {\n return async function POST(request: Request): Promise<Response> {\n if (!secret) {\n // Fail closed. An unauthenticated revalidation endpoint is a free cache\n // eviction lever: anyone who finds the URL can force every page of the\n // site back to the origin on every request.\n return Response.json({ error: 'Revalidation webhook is not configured' }, { status: 503 })\n }\n\n // One answer for a missing or bad signature and for a stale or replayed body\n // alike: the caller learns that the request was refused, never which check\n // refused it. A header without the shape of a signature is refused before\n // the body is read at all.\n const signature = request.headers.get('x-webhook-signature')\n if (!hasSignatureShape(signature)) {\n return Response.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n // The signature covers the bytes, so read the bytes. See `verifySignature`.\n const rawBody = await readBody(request)\n if (rawBody === null) {\n return Response.json({ error: 'Body too large' }, { status: 413 })\n }\n\n if (!verifySignature(rawBody, signature, secret)) {\n return Response.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n // The verifier has already parsed this body to read its timestamp, so this\n // cannot fail today. It stays guarded anyway: an unhandled throw here would\n // be a 500, which is exactly the failure a crafted request must never reach.\n let envelope: WebhookEnvelope\n try {\n envelope = JSON.parse(rawBody) as WebhookEnvelope\n } catch {\n return Response.json({ error: 'Body is not JSON' }, { status: 400 })\n }\n\n if (typeof envelope?.event !== 'string') {\n return Response.json({ error: 'Body carries no event name' }, { status: 400 })\n }\n\n // The site's language settings may have changed: the next request reads\n // them again. A cookie consent save alone cannot change them. A grouped\n // delivery names no fields, so it always counts as a change. A failure\n // here must not keep the tags below from dropping, nor change the answer.\n const siteChanged =\n envelope.event === `site.updated${BATCH_SUFFIX}` ||\n (envelope.event === 'site.updated' && !onlyConsentChanged(envelope.data))\n if (siteChanged && siteLocales) {\n try {\n siteLocales.invalidate()\n } catch (error) {\n console.error('[lynkow] the site languages could not be marked stale', error)\n }\n }\n\n const tags = tagsForEvent(envelope)\n for (const tag of tags) {\n // Next 16 made the second argument mandatory: it is the staleness a reader\n // that already holds the entry is still allowed. `{ expire: 0 }` grants\n // none, which is the only setting that matches what this route means. A\n // named profile such as `'max'` would say the opposite, and `updateTag`,\n // which expires immediately by definition, throws outside a Server Action.\n revalidateTag(tag, { expire: 0 })\n }\n\n // 200 with an empty `revalidated` is the right answer for an event this site\n // does not read, not an error: the webhook is working, the event just has no\n // consequence here. A 4xx would fill the delivery log with failures and\n // teach whoever reads it to ignore the log.\n return Response.json({ event: envelope.event, revalidated: tags })\n }\n}\n","import type { APIRoute } from 'astro'\nimport { createRevalidateHandler } from '../../../lynkow-next/src/server/revalidation.js'\nimport type { SiteLocales } from '../../../lynkow-next/src/site-locales.js'\nimport { lynkowCache, type LynkowCache } from '../cache/lynkow-cache.js'\nimport { runInvalidation } from '../shims/next-cache.js'\n\n/** Options of {@link createRevalidateEndpoint}. */\nexport interface RevalidateEndpointOptions {\n /**\n * The webhook's signing secret, read from a server-only environment\n * variable such as `LYNKOW_WEBHOOK_SECRET`. Absent or empty, the endpoint\n * stays closed and answers 503.\n */\n secret: string | undefined\n /**\n * The runtime source of the site's languages, from `createSiteLocales`. A\n * `site.updated` event marks it stale, unless it names the cookie consent\n * settings as its only change. Pass the instance the rest of the site reads.\n */\n siteLocales?: SiteLocales\n /** The data cache to evict from. Defaults to `lynkowCache`, the one `createClients` uses by default. */\n cache?: LynkowCache\n}\n\n/**\n * The `POST` endpoint of a revalidation webhook, for `src/pages/api/revalidate.ts`.\n *\n * Point a Lynkow webhook at it and give it the same secret. Each signed event\n * evicts the cache tags it can invalidate, so an edit is live on the next\n * request instead of waiting out the `REVALIDATE` ceiling. It is the handler\n * of `@lynkow/next`, with the same checks: a missing secret answers 503, a\n * missing, malformed, wrong or stale signature 401, a body over 5 MiB 413, a\n * signed body that names no event 400, and an event the site does not read\n * 200 with nothing evicted. It answers 500 when the cache store fails to\n * evict, or the body cannot be read, so the delivery is retried.\n *\n * @example\n * // src/pages/api/revalidate.ts\n * import { createRevalidateEndpoint } from '@lynkow/astro/server'\n * import { siteLocales } from '@/lib/lynkow'\n *\n * export const prerender = false\n * export const POST = createRevalidateEndpoint({\n * secret: process.env.LYNKOW_WEBHOOK_SECRET,\n * siteLocales,\n * })\n */\nexport function createRevalidateEndpoint({\n secret,\n siteLocales,\n cache = lynkowCache,\n}: RevalidateEndpointOptions): APIRoute {\n const handler = createRevalidateHandler(siteLocales ? { secret, siteLocales } : { secret })\n return async function POST({ request }) {\n // Whether the handler itself returned: past that point, only an eviction\n // can have failed. Before it, the handler did (a body that could not be read).\n let handled = false\n try {\n return await runInvalidation(cache, async () => {\n const response = await handler(request)\n handled = true\n return response\n })\n } catch (error) {\n if (!handled) {\n console.error('[lynkow] the revalidation webhook failed', error)\n return Response.json({ error: 'Revalidation failed' }, { status: 500 })\n }\n console.error('[lynkow] the revalidation webhook could not evict the cache', error)\n return Response.json({ error: 'Cache eviction failed' }, { status: 500 })\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { SiteConfig, Market, Client } from 'lynkow';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The site's language detection settings, as its configuration returns them.
|
|
5
|
+
* Only `enabled` is set per site. The order (`['cookie', 'browser']`), the
|
|
6
|
+
* cookie name (`_lkw_lang`) and its lifetime (365 days) are fixed by Lynkow.
|
|
7
|
+
*/
|
|
8
|
+
type SiteLocalesDetection = SiteConfig['i18n']['detection'];
|
|
9
|
+
/** What the site's language settings said at one read. */
|
|
10
|
+
interface SiteLocalesSnapshot {
|
|
11
|
+
/** The locales the site serves, in the order the site lists them. */
|
|
12
|
+
readonly locales: readonly string[];
|
|
13
|
+
/** The site's default locale. */
|
|
14
|
+
readonly defaultLocale: string;
|
|
15
|
+
/**
|
|
16
|
+
* The writing direction of each locale, keyed by locale code. A locale the
|
|
17
|
+
* site does not give a direction is `'ltr'`.
|
|
18
|
+
*/
|
|
19
|
+
readonly directions: Readonly<Record<string, 'ltr' | 'rtl'>>;
|
|
20
|
+
/** The site's language detection settings. */
|
|
21
|
+
readonly detection: SiteLocalesDetection;
|
|
22
|
+
/**
|
|
23
|
+
* Always an empty list: language detection no longer reads markets.
|
|
24
|
+
*
|
|
25
|
+
* @deprecated Read the site's markets with `lynkow.markets.list()` when you
|
|
26
|
+
* need them. This field will be dropped in a future minor.
|
|
27
|
+
*/
|
|
28
|
+
readonly markets?: readonly Market[];
|
|
29
|
+
}
|
|
30
|
+
/** Options of {@link createSiteLocales}. */
|
|
31
|
+
interface SiteLocalesOptions {
|
|
32
|
+
/**
|
|
33
|
+
* Returns a Lynkow client, the default locale's when called with no
|
|
34
|
+
* argument: typically the function `createClients(config)` returns. The
|
|
35
|
+
* source calls it with no argument, and before its first load that function
|
|
36
|
+
* returns a client naming no locale when the configuration has neither a
|
|
37
|
+
* static list nor a default, so the API answers the site config read in the
|
|
38
|
+
* site's default locale.
|
|
39
|
+
*/
|
|
40
|
+
client: (locale?: string) => Client;
|
|
41
|
+
/**
|
|
42
|
+
* How long a read stays fresh, in milliseconds. Defaults to `60_000`. `0`
|
|
43
|
+
* reads the site on every call that is not already waiting for a read.
|
|
44
|
+
*/
|
|
45
|
+
ttlMs?: number;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The site's languages, read from Lynkow at runtime and kept in memory.
|
|
49
|
+
*
|
|
50
|
+
* One instance is shared by everything the process serves: concurrent callers
|
|
51
|
+
* share a single read, and a read stays fresh for `ttlMs`.
|
|
52
|
+
*/
|
|
53
|
+
interface SiteLocales {
|
|
54
|
+
/**
|
|
55
|
+
* The site's languages. Returns the kept value while it is fresh, and reads
|
|
56
|
+
* the site otherwise. When the read fails and a value was loaded before,
|
|
57
|
+
* that last good value is returned and the site is not read again before
|
|
58
|
+
* another `ttlMs` has passed.
|
|
59
|
+
*
|
|
60
|
+
* @throws The read's error, only when the read fails and nothing was ever
|
|
61
|
+
* loaded. The next call reads again.
|
|
62
|
+
*/
|
|
63
|
+
get(): Promise<SiteLocalesSnapshot>;
|
|
64
|
+
/**
|
|
65
|
+
* The last good value, synchronously. When it is no longer fresh, a read
|
|
66
|
+
* starts in the background and a later call sees its result; a failure of
|
|
67
|
+
* that read is swallowed and the last good value is kept.
|
|
68
|
+
*
|
|
69
|
+
* @throws {Error} When nothing was ever loaded: await {@link get} first.
|
|
70
|
+
*/
|
|
71
|
+
current(): SiteLocalesSnapshot;
|
|
72
|
+
/**
|
|
73
|
+
* Marks the kept value as stale, so the next {@link get} reads the site,
|
|
74
|
+
* for instance after the site's language settings changed. The last good
|
|
75
|
+
* value is kept as the fallback if that read fails.
|
|
76
|
+
*/
|
|
77
|
+
invalidate(): void;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export type { SiteLocalesOptions as S, SiteLocales as a, SiteLocalesDetection as b, SiteLocalesSnapshot as c };
|
package/package.json
CHANGED
|
@@ -1,6 +1,93 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lynkow/astro",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Astro adapter for Lynkow: configuration, locale routing, a tagged data cache, the revalidation webhook, the buyer session and page metadata, for a site built on the Lynkow SDK",
|
|
5
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
6
|
+
"author": "Lynkow",
|
|
7
|
+
"homepage": "https://docs.lynkow.com",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"sideEffects": false,
|
|
10
|
+
"publishConfig": {
|
|
11
|
+
"access": "public"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist",
|
|
15
|
+
"LICENSE",
|
|
16
|
+
"README.md"
|
|
17
|
+
],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"default": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./server": {
|
|
24
|
+
"types": "./dist/server/index.d.ts",
|
|
25
|
+
"default": "./dist/server/index.js"
|
|
26
|
+
},
|
|
27
|
+
"./integration": {
|
|
28
|
+
"types": "./dist/integration.d.ts",
|
|
29
|
+
"default": "./dist/integration.js"
|
|
30
|
+
},
|
|
31
|
+
"./middleware": {
|
|
32
|
+
"types": "./dist/middleware/index.d.ts",
|
|
33
|
+
"default": "./dist/middleware/index.js"
|
|
34
|
+
},
|
|
35
|
+
"./react": {
|
|
36
|
+
"types": "./dist/react/index.d.ts",
|
|
37
|
+
"default": "./dist/react/index.js"
|
|
38
|
+
},
|
|
39
|
+
"./client": {
|
|
40
|
+
"types": "./dist/client/index.d.ts",
|
|
41
|
+
"default": "./dist/client/index.js"
|
|
42
|
+
},
|
|
43
|
+
"./package.json": "./package.json"
|
|
44
|
+
},
|
|
45
|
+
"types": "./dist/index.d.ts",
|
|
46
|
+
"scripts": {
|
|
47
|
+
"build": "rm -rf dist && tsup",
|
|
48
|
+
"dev": "tsup --watch",
|
|
49
|
+
"typecheck": "tsc --noEmit",
|
|
50
|
+
"lint": "eslint .",
|
|
51
|
+
"test": "vitest",
|
|
52
|
+
"test:run": "vitest run",
|
|
53
|
+
"prepublishOnly": "npm run build"
|
|
54
|
+
},
|
|
55
|
+
"peerDependencies": {
|
|
56
|
+
"astro": "^7.0.0",
|
|
57
|
+
"lynkow": "~1.65.6",
|
|
58
|
+
"react": "^18.2.0 || ^19.0.0"
|
|
59
|
+
},
|
|
60
|
+
"peerDependenciesMeta": {
|
|
61
|
+
"react": {
|
|
62
|
+
"optional": true
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
"devDependencies": {
|
|
66
|
+
"@eslint/js": "^10.0.1",
|
|
67
|
+
"@testing-library/react": "^16.3.3",
|
|
68
|
+
"@types/node": "^20.10.0",
|
|
69
|
+
"@types/react": "^19.3.0",
|
|
70
|
+
"@types/react-dom": "^19.3.0",
|
|
71
|
+
"astro": "^7.4.13",
|
|
72
|
+
"eslint": "^10.11.0",
|
|
73
|
+
"globals": "^17.13.0",
|
|
74
|
+
"jsdom": "^27.4.0",
|
|
75
|
+
"lynkow": "~1.65.6",
|
|
76
|
+
"next": "^16.4.6",
|
|
77
|
+
"react": "^19.3.1",
|
|
78
|
+
"react-dom": "^19.3.1",
|
|
79
|
+
"tsup": "^9.0.0",
|
|
80
|
+
"typescript": "^5.3.3",
|
|
81
|
+
"typescript-eslint": "^8.72.1",
|
|
82
|
+
"vitest": "^4.0.17"
|
|
83
|
+
},
|
|
84
|
+
"engines": {
|
|
85
|
+
"node": ">=22.12.0"
|
|
86
|
+
},
|
|
87
|
+
"keywords": [
|
|
88
|
+
"lynkow",
|
|
89
|
+
"astro",
|
|
90
|
+
"headless",
|
|
91
|
+
"cms"
|
|
92
|
+
]
|
|
93
|
+
}
|