@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
package/LICENSE
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
Lynkow SDK - Proprietary License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lynkow. All rights reserved.
|
|
4
|
+
|
|
5
|
+
This software and associated documentation files (the "Software") are the
|
|
6
|
+
proprietary property of Lynkow and are protected by copyright law.
|
|
7
|
+
|
|
8
|
+
PERMITTED USE:
|
|
9
|
+
- You may use this Software solely in connection with Lynkow services
|
|
10
|
+
- You may install and use the Software in your applications that integrate
|
|
11
|
+
with the Lynkow platform
|
|
12
|
+
|
|
13
|
+
RESTRICTIONS:
|
|
14
|
+
- You may NOT copy, modify, merge, publish, distribute, sublicense, or sell
|
|
15
|
+
copies of the Software
|
|
16
|
+
- You may NOT reverse engineer, decompile, or disassemble the Software
|
|
17
|
+
- You may NOT use the Software for any purpose other than integrating with
|
|
18
|
+
Lynkow services
|
|
19
|
+
- You may NOT remove or alter any proprietary notices or labels on the Software
|
|
20
|
+
|
|
21
|
+
NO WARRANTY:
|
|
22
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
23
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
24
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
|
25
|
+
LYNKOW BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
|
26
|
+
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
27
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
28
|
+
|
|
29
|
+
For licensing inquiries, contact: contact@lynkow.com
|
package/README.md
CHANGED
|
@@ -1,3 +1,394 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lynkow/astro
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Astro adapter for [Lynkow](https://lynkow.com). It holds the code every
|
|
4
|
+
Lynkow site on Astro needs and no site should have to maintain by hand, so a fix
|
|
5
|
+
reaches an existing site as a version bump.
|
|
6
|
+
|
|
7
|
+
It builds on the [`lynkow`](https://www.npmjs.com/package/lynkow) SDK, which
|
|
8
|
+
stays framework-agnostic, and shares its configuration, locale, metadata, buyer
|
|
9
|
+
session and webhook rules with `@lynkow/next`.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @lynkow/astro lynkow
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
It requires Astro 7 with on-demand rendering (`output: 'server'` and a server
|
|
16
|
+
adapter such as `@astrojs/node`), Node 22.12 or later, and `lynkow` 1.65 (any
|
|
17
|
+
1.65.x from 1.65.6). A minor release of `lynkow` is a breaking one, so each
|
|
18
|
+
minor of the SDK needs a release of this adapter.
|
|
19
|
+
|
|
20
|
+
| Entry | For |
|
|
21
|
+
|---|---|
|
|
22
|
+
| `@lynkow/astro` | Configuration, locale paths, the data cache and its clients, `trackEvent`, image URLs. Safe to import anywhere |
|
|
23
|
+
| `@lynkow/astro/server` | Endpoints, pages and actions: text routes, JSON-LD, head data, the revalidation webhook, the buyer session and the same-origin check |
|
|
24
|
+
| `@lynkow/astro/middleware` | `src/middleware.ts`: redirects, language detection, locale routing, the preview framing headers |
|
|
25
|
+
| `@lynkow/astro/react` | React islands: the visual editor's `Editable` markers and hooks, the analytics tracker |
|
|
26
|
+
| `@lynkow/astro/client` | A `<script>` of the base layout: starts the visual editor |
|
|
27
|
+
| `@lynkow/astro/integration` | `astro.config.mjs`: loads the server-only variables in `astro dev` |
|
|
28
|
+
|
|
29
|
+
## Configuration
|
|
30
|
+
|
|
31
|
+
The adapter reads no environment variable for its configuration. Your
|
|
32
|
+
application reads its own, with literal `import.meta.env.PUBLIC_*` accesses that
|
|
33
|
+
Vite can inline, and passes the values to `resolveConfig`, which validates them
|
|
34
|
+
and throws one error listing every problem:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
// src/lib/config.ts
|
|
38
|
+
import { resolveConfig } from '@lynkow/astro'
|
|
39
|
+
|
|
40
|
+
export const config = resolveConfig(
|
|
41
|
+
{
|
|
42
|
+
siteId: import.meta.env.PUBLIC_LYNKOW_SITE_ID,
|
|
43
|
+
siteUrl: import.meta.env.PUBLIC_SITE_URL,
|
|
44
|
+
locales: import.meta.env.PUBLIC_LOCALES,
|
|
45
|
+
defaultLocale: import.meta.env.PUBLIC_DEFAULT_LOCALE,
|
|
46
|
+
apiUrl: import.meta.env.PUBLIC_LYNKOW_API_URL,
|
|
47
|
+
publishableKey: import.meta.env.PUBLIC_LYNKOW_PUBLISHABLE_KEY,
|
|
48
|
+
},
|
|
49
|
+
{ siteId: 'PUBLIC_LYNKOW_SITE_ID', siteUrl: 'PUBLIC_SITE_URL' }
|
|
50
|
+
)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Everything in the result is public. A server secret never belongs in it.
|
|
54
|
+
|
|
55
|
+
Without `locales`, the site's languages are read at runtime from Lynkow, so a
|
|
56
|
+
language enabled in the admin reaches the site without a rebuild:
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
// src/lib/lynkow.ts
|
|
60
|
+
import { createClients, createLocalePaths, createSiteLocales } from '@lynkow/astro'
|
|
61
|
+
import { config } from './config'
|
|
62
|
+
|
|
63
|
+
export const siteLocales = createSiteLocales({ client: (locale) => lynkow(locale) })
|
|
64
|
+
export const lynkow = createClients(config, { siteLocales, enhancements: { activateScripts: false } })
|
|
65
|
+
export const paths = createLocalePaths(config, siteLocales)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Middleware
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
// src/middleware.ts
|
|
72
|
+
import { sequence } from 'astro:middleware'
|
|
73
|
+
import { createLynkowMiddleware } from '@lynkow/astro/middleware'
|
|
74
|
+
import { config } from './lib/config'
|
|
75
|
+
import { lynkow, siteLocales } from './lib/lynkow'
|
|
76
|
+
|
|
77
|
+
export const onRequest = sequence(
|
|
78
|
+
createLynkowMiddleware({
|
|
79
|
+
config,
|
|
80
|
+
// Pass the options on: the redirect lookup asks for a client that does not retry.
|
|
81
|
+
client: (locale, options) => lynkow(locale, options),
|
|
82
|
+
siteLocales,
|
|
83
|
+
})
|
|
84
|
+
)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
It runs the same routing as `@lynkow/next`'s proxy, on every page request:
|
|
88
|
+
|
|
89
|
+
- **Redirects** stored in Lynkow, first, on the path as the visitor typed it,
|
|
90
|
+
with the status the editor chose.
|
|
91
|
+
- **Language detection**, on a first visit to `/` only, when the site turned it
|
|
92
|
+
on: the language cookie wins, then the browser's language. Never for a robot
|
|
93
|
+
or a preview request.
|
|
94
|
+
- **Locale routing.** The default locale is served without a prefix: `/about`
|
|
95
|
+
renders `src/pages/[locale]/about.astro` with `locale` set to the default,
|
|
96
|
+
under the same URL, through Astro's `next(url)` rewrite. Every other locale
|
|
97
|
+
lives under its prefix (`/fr/about`). The payment return pages and the
|
|
98
|
+
account email pages are served in the language cookie's locale.
|
|
99
|
+
- **The language cookie** `_lkw_lang` (365 days, readable by scripts, strictly
|
|
100
|
+
necessary) goes through `Astro.cookies`.
|
|
101
|
+
- **Framing.** Lynkow's dashboard may frame a preview request (the
|
|
102
|
+
`lynkow-preview` query parameter): the page's `Content-Security-Policy` gets
|
|
103
|
+
`frame-ancestors 'self' <cmsOrigin>` and loses `X-Frame-Options`. Every other
|
|
104
|
+
page gets `frame-ancestors 'self'`, unless its own policy already names its
|
|
105
|
+
framers. The rule is merged into the page's policy, directive by directive.
|
|
106
|
+
- **The request store** that the buyer client reads, so buyer writes forward
|
|
107
|
+
the buyer's address.
|
|
108
|
+
|
|
109
|
+
It never routes Astro's own paths (`/_astro/`, `/_image`, `/_actions/`,
|
|
110
|
+
`/_server-islands/`), `/api/`, the error pages `/404` and `/500`, and any path
|
|
111
|
+
that looks like a file, except `.html`, `.htm`, `.php`, `.asp`, `.aspx` and
|
|
112
|
+
`.jsp`, which are routed so a redirect stored on an old URL answers. Those
|
|
113
|
+
paths, actions and endpoints included, still run inside the request store, so a
|
|
114
|
+
buyer write from an action or an `/api/` route forwards the buyer's address.
|
|
115
|
+
`skip: (url) => boolean` adds paths not to route; `isSkippedPath` is the default
|
|
116
|
+
test. A prerendered page is left alone entirely.
|
|
117
|
+
|
|
118
|
+
A request is routed once. `Astro.rewrite('/404')` or `Astro.rewrite('/en/x')`
|
|
119
|
+
from a page makes Astro run the middleware again on the same request, and that
|
|
120
|
+
second pass renders the page named as it is, with no lookup, no redirect and no
|
|
121
|
+
cookie: only the framing rule applies. `accountPagesPath` (default
|
|
122
|
+
`/account`) and `cmsOrigin` (default: the Lynkow dashboard) match the
|
|
123
|
+
`@lynkow/next` options of the same names.
|
|
124
|
+
|
|
125
|
+
`isBot`, `prefersMarkdown`, `acceptQuality` and `createRedirectMatcher` are
|
|
126
|
+
exported for a middleware of your own.
|
|
127
|
+
|
|
128
|
+
## Caching
|
|
129
|
+
|
|
130
|
+
Astro has no data cache of its own for `fetch`, so the adapter brings one. A read
|
|
131
|
+
of a client from `createClients` is cached when its options carry `cached()`:
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
import { cached, REVALIDATE, TAGS } from '@lynkow/astro'
|
|
135
|
+
|
|
136
|
+
// `TAGS` covers the content reads only. A commerce read takes a tag of your
|
|
137
|
+
// own, as the starter's `CATALOG_TAGS` does.
|
|
138
|
+
const PRODUCTS_TAG = 'lynkow:products'
|
|
139
|
+
|
|
140
|
+
const page = await lynkow(locale).pages.getBySlug('home', cached([TAGS.page('home')], REVALIDATE.page))
|
|
141
|
+
const { data } = await lynkow(locale).products.list(filters, { ...cached([PRODUCTS_TAG], 300), market })
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
- `revalidate` is the ceiling: an entry older than that many seconds starts a
|
|
145
|
+
background load of a fresh copy, and is served as stale to every read until
|
|
146
|
+
that copy lands (for up to a day, then the read waits for the fresh copy).
|
|
147
|
+
When that background load fails, the stale copy keeps being served and the key
|
|
148
|
+
is not retried for 30 seconds.
|
|
149
|
+
- The tags are the floor: the revalidation webhook evicts them, so an edit is
|
|
150
|
+
live on the next request.
|
|
151
|
+
- Concurrent reads of one key share one API call, and every reader gets its own
|
|
152
|
+
copy, so mutating a result never alters what the next request reads.
|
|
153
|
+
- A read with no `cached()`, or with `uncached()`, goes to the API every time.
|
|
154
|
+
|
|
155
|
+
The cache lives in the server process (`lynkowCache`, 1000 entries by default).
|
|
156
|
+
`createLynkowCache({ max, store, staleWhileRevalidate })` builds another; pass it
|
|
157
|
+
to `createClients` and to `createRevalidateEndpoint` alike. A `CacheStore`
|
|
158
|
+
(`get`, `set`, `deleteTags`, each possibly asynchronous) lets several instances
|
|
159
|
+
share one cache. An eviction then cancels the loads in flight in the instance
|
|
160
|
+
that received the webhook only: a load another instance started before the edit
|
|
161
|
+
can still store its pre-edit result, which stays until its `revalidate` elapses
|
|
162
|
+
and is then served as stale to every read until the fresh copy lands. An
|
|
163
|
+
eviction waits up to 5 seconds for a store write already under way. One that
|
|
164
|
+
lands later is deleted again once it settles, after the webhook has answered. On
|
|
165
|
+
a host that suspends work once the response is sent, that deletion may run late
|
|
166
|
+
or never, and the pre-edit entry then stays until its `revalidate` elapses.
|
|
167
|
+
|
|
168
|
+
These clients are shared by every request: never use them for a buyer's cart or
|
|
169
|
+
session. Use `createBuyerClient` below.
|
|
170
|
+
|
|
171
|
+
## Server
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
// src/lib/server.ts
|
|
175
|
+
import { createLynkowServer } from '@lynkow/astro/server'
|
|
176
|
+
|
|
177
|
+
export const server = createLynkowServer({
|
|
178
|
+
config,
|
|
179
|
+
client: (locale) => lynkow(locale),
|
|
180
|
+
getSiteDomain: async (locale) => (await getSiteShell(locale)).domain,
|
|
181
|
+
siteLocales,
|
|
182
|
+
})
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
**Text routes.** `server.textRoute(read, contentType)` returns an Astro endpoint
|
|
186
|
+
serving a file Lynkow generates, cached under `TAGS.seo`, with its URLs moved to
|
|
187
|
+
this site's origin and the default locale unprefixed. A file the site does not
|
|
188
|
+
produce answers 404.
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
// src/pages/sitemap.xml.ts
|
|
192
|
+
import { XML } from '@lynkow/astro/server'
|
|
193
|
+
import { server } from '@/lib/server'
|
|
194
|
+
|
|
195
|
+
export const prerender = false
|
|
196
|
+
export const GET = server.textRoute((client, options) => client.seo.sitemap(options), XML)
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
**Head data.** `pageHead(page, locale, fallbackPath)`, `routeHead(locale, path,
|
|
200
|
+
title, description)`, `articleHead`, `categoryHead`, `productHead`,
|
|
201
|
+
`productCollectionHead` and `productCategoryHead` return a flat `HeadData`:
|
|
202
|
+
`title` (with `titleAbsolute` when the editor's title already holds the brand),
|
|
203
|
+
`description`, `keywords`, `canonical`, `alternates` (the hreflang set, with
|
|
204
|
+
`x-default`), `robots`, `openGraph` and `twitter`. `articleHead` also fills
|
|
205
|
+
`openGraph.article` (`publishedTime`, `modifiedTime`, `authors`, `tags`), the
|
|
206
|
+
values of the `article:*` tags. A layout renders it with plain
|
|
207
|
+
tags. The builders run synchronously, so with runtime locales call them after
|
|
208
|
+
`await siteLocales.get()`.
|
|
209
|
+
|
|
210
|
+
**JSON-LD.** `await server.jsonLd(nodes, locale)` returns the payload of one
|
|
211
|
+
`<script type="application/ld+json">`, or null when there are no nodes. It is
|
|
212
|
+
already escaped: render it with `set:html`.
|
|
213
|
+
|
|
214
|
+
## Revalidation webhook
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
// src/pages/api/revalidate.ts
|
|
218
|
+
import { createRevalidateEndpoint } from '@lynkow/astro/server'
|
|
219
|
+
import { siteLocales } from '@/lib/lynkow'
|
|
220
|
+
|
|
221
|
+
export const prerender = false
|
|
222
|
+
export const POST = createRevalidateEndpoint({ secret: process.env.LYNKOW_WEBHOOK_SECRET, siteLocales })
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Point a Lynkow webhook at it with the same secret. Each signed event evicts the
|
|
226
|
+
cache tags it can invalidate. Without a secret the endpoint answers 503; a
|
|
227
|
+
missing or wrong signature 401; a body over 5 MiB 413.
|
|
228
|
+
|
|
229
|
+
## Buyer session
|
|
230
|
+
|
|
231
|
+
A buyer's cart and account are read through a client created for one request
|
|
232
|
+
and seeded from the buyer's cookies, never cached:
|
|
233
|
+
|
|
234
|
+
```astro
|
|
235
|
+
---
|
|
236
|
+
// src/pages/[locale]/cart.astro
|
|
237
|
+
import { createBuyerClient } from '@lynkow/astro/server'
|
|
238
|
+
const buyer = createBuyerClient(config, Astro.cookies, { locale })
|
|
239
|
+
const cart = await buyer.cart.retrieve()
|
|
240
|
+
---
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
`setCartCookie(cookies, token)` and `setCustomerCookie(cookies, token)` store
|
|
244
|
+
the tokens in `__Host-` cookies (`Secure`, `HttpOnly`, `SameSite=Lax`, 30 days at
|
|
245
|
+
most), from an endpoint or an action. `clearBuyerCookies` and `signOut` remove
|
|
246
|
+
them. `assertSameOrigin(request)` refuses a mutating request sent from another
|
|
247
|
+
site.
|
|
248
|
+
|
|
249
|
+
### Buyer IP forwarding
|
|
250
|
+
|
|
251
|
+
Every buyer call reaches the API from your server. Set `LYNKOW_SERVER_KEY` to the
|
|
252
|
+
site's server key and a buyer client forwards the buyer's IP address with it on
|
|
253
|
+
every write, so the API counts each buyer, rather than your server, against its
|
|
254
|
+
rate limits. The address is the first public `X-Forwarded-For` entry from the
|
|
255
|
+
right, or the one header `LYNKOW_CLIENT_IP_HEADER` names when your CDN writes the
|
|
256
|
+
visitor's address there.
|
|
257
|
+
|
|
258
|
+
The client reads the current request from a store the Lynkow middleware fills.
|
|
259
|
+
A site that does not use it wraps its own middleware's `next()` in
|
|
260
|
+
`runWithRequest`, with the client's address as Astro resolved it, read the way
|
|
261
|
+
the Lynkow middleware reads it (Astro throws when the adapter has none):
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
// src/middleware.ts
|
|
265
|
+
import { defineMiddleware } from 'astro:middleware'
|
|
266
|
+
import { runWithRequest } from '@lynkow/astro/server'
|
|
267
|
+
|
|
268
|
+
export const onRequest = defineMiddleware((context, next) => {
|
|
269
|
+
let address: string | undefined
|
|
270
|
+
try {
|
|
271
|
+
address = context.clientAddress || undefined
|
|
272
|
+
} catch {
|
|
273
|
+
address = undefined
|
|
274
|
+
}
|
|
275
|
+
return runWithRequest(context.request, () => next(), address)
|
|
276
|
+
})
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
Outside a request nothing is forwarded, the key included.
|
|
280
|
+
`resolveBuyerForwarding(headers)` returns the same `{ serverKey, clientIp }` for
|
|
281
|
+
code that builds its own client.
|
|
282
|
+
|
|
283
|
+
## Visual editor
|
|
284
|
+
|
|
285
|
+
Lynkow's dashboard edits a site's blocks in place. Mark each block and each
|
|
286
|
+
editable field, then start the editor from the base layout:
|
|
287
|
+
|
|
288
|
+
```astro
|
|
289
|
+
---
|
|
290
|
+
// src/components/Hero.astro
|
|
291
|
+
const { data } = Astro.props
|
|
292
|
+
---
|
|
293
|
+
<section data-lynkow-block="hero">
|
|
294
|
+
<h1 data-lynkow-field="title" data-lynkow-type="text" data-lynkow-label="Title">{data.title}</h1>
|
|
295
|
+
<div data-lynkow-field="body" data-lynkow-type="richtext" set:html={data.body} />
|
|
296
|
+
</section>
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
```astro
|
|
300
|
+
<!-- src/layouts/Base.astro -->
|
|
301
|
+
<script>
|
|
302
|
+
import { startVisualEditor } from '@lynkow/astro/client'
|
|
303
|
+
startVisualEditor()
|
|
304
|
+
</script>
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
Outside the dashboard's preview frame `startVisualEditor` does nothing. Inside
|
|
308
|
+
it, every change is written into the page as it is typed: a field's text, or
|
|
309
|
+
its HTML for a `richtext` field. Mark the element that holds the text and
|
|
310
|
+
nothing else, use flat field keys (a repeater row cannot be marked), and give
|
|
311
|
+
`startVisualEditor({ cmsOrigin })` the same origin as the middleware, or
|
|
312
|
+
neither. It returns the function that stops it; `visualEditorStore` is the
|
|
313
|
+
state it shares with the React hooks.
|
|
314
|
+
|
|
315
|
+
## React
|
|
316
|
+
|
|
317
|
+
In a React island, `Editable` and `EditableBlock` write the same markers, and
|
|
318
|
+
the hooks follow the editor:
|
|
319
|
+
|
|
320
|
+
```tsx
|
|
321
|
+
import { Editable, EditableBlock } from '@lynkow/astro/react'
|
|
322
|
+
|
|
323
|
+
export function Hero({ data }: { data: { title: string; body: string } }) {
|
|
324
|
+
return (
|
|
325
|
+
<EditableBlock slug="hero" as="section">
|
|
326
|
+
<Editable field="title" as="h1">{data.title}</Editable>
|
|
327
|
+
<Editable field="body" type="richtext" as="div" html={data.body} />
|
|
328
|
+
</EditableBlock>
|
|
329
|
+
)
|
|
330
|
+
}
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
`useLynkowField(block, field, value)`, `useBlockData(block, data)` and
|
|
334
|
+
`useIsPreviewMode()` read the store `startVisualEditor` fills rather than a
|
|
335
|
+
React context, so they need no provider and work in every island; a server
|
|
336
|
+
render returns the values passed in. A field whose block is marked in an
|
|
337
|
+
`.astro` component around the island names it: `<Editable block="hero"
|
|
338
|
+
field="title">`. A hydrated island (`client:load`, `client:visible`, ...)
|
|
339
|
+
re-renders on each change; the static HTML around it is patched in place, and
|
|
340
|
+
so is static HTML passed into it as children, which an island that remounts
|
|
341
|
+
those children resets to what it was when the island hydrated, until the next
|
|
342
|
+
change of that field.
|
|
343
|
+
|
|
344
|
+
`LynkowTracker` loads Lynkow's analytics tracker when the visitor's consent
|
|
345
|
+
allows it (`trackerAllowed(consent)` is the same rule), from a hydrated island:
|
|
346
|
+
|
|
347
|
+
```tsx
|
|
348
|
+
<LynkowTracker config={config} consent={{ mode: null, state: 'not-required' }} />
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
## Integration
|
|
352
|
+
|
|
353
|
+
```js
|
|
354
|
+
// astro.config.mjs
|
|
355
|
+
import { defineConfig } from 'astro/config'
|
|
356
|
+
import node from '@astrojs/node'
|
|
357
|
+
import lynkow from '@lynkow/astro/integration'
|
|
358
|
+
|
|
359
|
+
export default defineConfig({
|
|
360
|
+
output: 'server',
|
|
361
|
+
adapter: node({ mode: 'standalone' }),
|
|
362
|
+
integrations: [lynkow()],
|
|
363
|
+
})
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
`astro dev` loads `.env` files into `import.meta.env` only. In development the
|
|
367
|
+
integration copies `LYNKOW_SERVER_KEY`, `LYNKOW_CLIENT_IP_HEADER`,
|
|
368
|
+
`LYNKOW_COUNTRY_HEADERS` and `LYNKOW_WEBHOOK_SECRET` from the files of the mode
|
|
369
|
+
the server runs in (`astro dev --mode staging` reads `.env.staging`) into
|
|
370
|
+
`process.env`, where the server code reads them, and leaves a variable already
|
|
371
|
+
set in the shell alone. In production, start the server with them in its
|
|
372
|
+
environment, for instance `node --env-file-if-exists=.env.local ./dist/server/entry.mjs`.
|
|
373
|
+
|
|
374
|
+
## Images
|
|
375
|
+
|
|
376
|
+
```astro
|
|
377
|
+
---
|
|
378
|
+
import { imageSrcSet, imageUrl } from '@lynkow/astro'
|
|
379
|
+
---
|
|
380
|
+
<img src={imageUrl({ src, width: 1280 })} srcset={imageSrcSet(src, [640, 960, 1280])} sizes="100vw" alt="" />
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
Lynkow media is resized on the Lynkow CDN, never upscaled, in the best format
|
|
384
|
+
the browser accepts. A relative URL or a URL that is not Lynkow media comes back
|
|
385
|
+
unchanged, and its `srcset` is empty.
|
|
386
|
+
|
|
387
|
+
## Analytics
|
|
388
|
+
|
|
389
|
+
`trackEvent(type, data)` sends one custom event, of the SDK's closed `AnalyticsEventType`, through the Lynkow tracker already on the page,
|
|
390
|
+
and returns `false` when no tracker has loaded.
|
|
391
|
+
|
|
392
|
+
## License
|
|
393
|
+
|
|
394
|
+
See [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// src/visual-editor/store.ts
|
|
2
|
+
var INITIAL = Object.freeze({ isPreviewMode: false, blocksData: Object.freeze({}) });
|
|
3
|
+
function createStore() {
|
|
4
|
+
let snapshot = INITIAL;
|
|
5
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
6
|
+
function publish(next) {
|
|
7
|
+
snapshot = next;
|
|
8
|
+
for (const listener of [...listeners]) listener();
|
|
9
|
+
}
|
|
10
|
+
return {
|
|
11
|
+
getSnapshot: () => snapshot,
|
|
12
|
+
getServerSnapshot: () => INITIAL,
|
|
13
|
+
subscribe(listener) {
|
|
14
|
+
listeners.add(listener);
|
|
15
|
+
return () => {
|
|
16
|
+
listeners.delete(listener);
|
|
17
|
+
};
|
|
18
|
+
},
|
|
19
|
+
setPreviewMode(isPreviewMode) {
|
|
20
|
+
if (snapshot.isPreviewMode !== isPreviewMode) publish({ ...snapshot, isPreviewMode });
|
|
21
|
+
},
|
|
22
|
+
setBlockData(blockSlug, data) {
|
|
23
|
+
publish({ ...snapshot, blocksData: { ...snapshot.blocksData, [blockSlug]: data } });
|
|
24
|
+
},
|
|
25
|
+
reset() {
|
|
26
|
+
if (snapshot !== INITIAL) publish(INITIAL);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
var STORE = /* @__PURE__ */ Symbol.for("@lynkow/astro/visual-editor-store");
|
|
31
|
+
var writableVisualEditorStore = globalThis[STORE] ??= createStore();
|
|
32
|
+
var visualEditorStore = {
|
|
33
|
+
getSnapshot: () => writableVisualEditorStore.getSnapshot(),
|
|
34
|
+
getServerSnapshot: () => writableVisualEditorStore.getServerSnapshot(),
|
|
35
|
+
subscribe: (listener) => writableVisualEditorStore.subscribe(listener)
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export { visualEditorStore, writableVisualEditorStore };
|
|
39
|
+
//# sourceMappingURL=chunk-67VKUBOP.js.map
|
|
40
|
+
//# sourceMappingURL=chunk-67VKUBOP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/visual-editor/store.ts"],"names":[],"mappings":";AA+BA,IAAM,OAAA,GAAgC,MAAA,CAAO,MAAA,CAAO,EAAE,aAAA,EAAe,KAAA,EAAO,UAAA,EAAY,MAAA,CAAO,MAAA,CAAO,EAAE,CAAA,EAAG,CAAA;AAE3G,SAAS,WAAA,GAAyC;AAChD,EAAA,IAAI,QAAA,GAAW,OAAA;AACf,EAAA,MAAM,SAAA,uBAAgB,GAAA,EAAgB;AAEtC,EAAA,SAAS,QAAQ,IAAA,EAAkC;AACjD,IAAA,QAAA,GAAW,IAAA;AACX,IAAA,KAAA,MAAW,QAAA,IAAY,CAAC,GAAG,SAAS,GAAG,QAAA,EAAS;AAAA,EAClD;AAEA,EAAA,OAAO;AAAA,IACL,aAAa,MAAM,QAAA;AAAA,IACnB,mBAAmB,MAAM,OAAA;AAAA,IACzB,UAAU,QAAA,EAAU;AAClB,MAAA,SAAA,CAAU,IAAI,QAAQ,CAAA;AACtB,MAAA,OAAO,MAAM;AACX,QAAA,SAAA,CAAU,OAAO,QAAQ,CAAA;AAAA,MAC3B,CAAA;AAAA,IACF,CAAA;AAAA,IACA,eAAe,aAAA,EAAe;AAC5B,MAAA,IAAI,QAAA,CAAS,kBAAkB,aAAA,EAAe,OAAA,CAAQ,EAAE,GAAG,QAAA,EAAU,eAAe,CAAA;AAAA,IACtF,CAAA;AAAA,IACA,YAAA,CAAa,WAAW,IAAA,EAAM;AAC5B,MAAA,OAAA,CAAQ,EAAE,GAAG,QAAA,EAAU,UAAA,EAAY,EAAE,GAAG,QAAA,CAAS,UAAA,EAAY,CAAC,SAAS,GAAG,IAAA,IAAQ,CAAA;AAAA,IACpF,CAAA;AAAA,IACA,KAAA,GAAQ;AACN,MAAA,IAAI,QAAA,KAAa,OAAA,EAAS,OAAA,CAAQ,OAAO,CAAA;AAAA,IAC3C;AAAA,GACF;AACF;AAEA,IAAM,KAAA,mBAAQ,MAAA,CAAO,GAAA,CAAI,mCAAmC,CAAA;AAMrD,IAAM,yBAAA,GAA8B,UAAA,CAAuC,KAAK,CAAA,KACrF,WAAA;AAGK,IAAM,iBAAA,GAAuC;AAAA,EAClD,WAAA,EAAa,MAAM,yBAAA,CAA0B,WAAA,EAAY;AAAA,EACzD,iBAAA,EAAmB,MAAM,yBAAA,CAA0B,iBAAA,EAAkB;AAAA,EACrE,SAAA,EAAW,CAAC,QAAA,KAAa,yBAAA,CAA0B,UAAU,QAAQ;AACvE","file":"chunk-67VKUBOP.js","sourcesContent":["/**\n * The state of the visual editor on the page, shared by `startVisualEditor`,\n * which writes it, and the React hooks of `@lynkow/astro/react`, which read\n * it. A module store rather than a React context: an Astro page is many\n * islands, each its own React root, and a context reaches none of the others.\n */\n\n/** What the editor has told the page so far. */\nexport interface VisualEditorSnapshot {\n /** Whether the page runs inside the Lynkow dashboard's visual editor. */\n readonly isPreviewMode: boolean\n /** The data of every block the editor changed, by block slug. */\n readonly blocksData: Readonly<Record<string, Record<string, any>>>\n}\n\n/** The store, as `useSyncExternalStore` reads it. */\nexport interface VisualEditorStore {\n getSnapshot(): VisualEditorSnapshot\n /** The state a server render and a hydration start from: not in preview, no data. */\n getServerSnapshot(): VisualEditorSnapshot\n /** Calls `listener` after every change; returns the unsubscribe function. */\n subscribe(listener: () => void): () => void\n}\n\n/** The store with its writers, for `startVisualEditor` only. */\nexport interface WritableVisualEditorStore extends VisualEditorStore {\n setPreviewMode(isPreviewMode: boolean): void\n setBlockData(blockSlug: string, data: Record<string, any>): void\n reset(): void\n}\n\nconst INITIAL: VisualEditorSnapshot = Object.freeze({ isPreviewMode: false, blocksData: Object.freeze({}) })\n\nfunction createStore(): WritableVisualEditorStore {\n let snapshot = INITIAL\n const listeners = new Set<() => void>()\n\n function publish(next: VisualEditorSnapshot): void {\n snapshot = next\n for (const listener of [...listeners]) listener()\n }\n\n return {\n getSnapshot: () => snapshot,\n getServerSnapshot: () => INITIAL,\n subscribe(listener) {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n setPreviewMode(isPreviewMode) {\n if (snapshot.isPreviewMode !== isPreviewMode) publish({ ...snapshot, isPreviewMode })\n },\n setBlockData(blockSlug, data) {\n publish({ ...snapshot, blocksData: { ...snapshot.blocksData, [blockSlug]: data } })\n },\n reset() {\n if (snapshot !== INITIAL) publish(INITIAL)\n },\n }\n}\n\nconst STORE = Symbol.for('@lynkow/astro/visual-editor-store')\n\n/**\n * One store per page, kept on `globalThis`, so the `./client` and `./react`\n * entries share it even when a bundler gives each its own copy of this file.\n */\nexport const writableVisualEditorStore = ((globalThis as Record<symbol, unknown>)[STORE] ??=\n createStore()) as WritableVisualEditorStore\n\n/** The visual editor's state on this page, read only. */\nexport const visualEditorStore: VisualEditorStore = {\n getSnapshot: () => writableVisualEditorStore.getSnapshot(),\n getServerSnapshot: () => writableVisualEditorStore.getServerSnapshot(),\n subscribe: (listener) => writableVisualEditorStore.subscribe(listener),\n}\n"]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
|
|
3
|
+
// src/shims/next-headers.ts
|
|
4
|
+
var CLIENT_ADDRESS = /* @__PURE__ */ Symbol.for("astro.clientAddress");
|
|
5
|
+
var STORAGE = /* @__PURE__ */ Symbol.for("@lynkow/astro/request-store");
|
|
6
|
+
var storage = globalThis[STORAGE] ??= new AsyncLocalStorage();
|
|
7
|
+
function runWithRequest(request, fn, clientAddress) {
|
|
8
|
+
return storage.run({ request, clientAddress }, fn);
|
|
9
|
+
}
|
|
10
|
+
function currentRequest() {
|
|
11
|
+
return storage.getStore()?.request;
|
|
12
|
+
}
|
|
13
|
+
async function headers() {
|
|
14
|
+
const store = storage.getStore();
|
|
15
|
+
if (!store) throw new Error("headers() was called outside a request");
|
|
16
|
+
const { request } = store;
|
|
17
|
+
if (request.headers.has("x-forwarded-for")) return request.headers;
|
|
18
|
+
const recorded = Reflect.get(request, CLIENT_ADDRESS);
|
|
19
|
+
const address = store.clientAddress || (typeof recorded === "string" ? recorded : void 0);
|
|
20
|
+
if (!address) return request.headers;
|
|
21
|
+
const copy = new Headers(request.headers);
|
|
22
|
+
copy.set("x-forwarded-for", address);
|
|
23
|
+
return copy;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export { currentRequest, headers, runWithRequest };
|
|
27
|
+
//# sourceMappingURL=chunk-7ZL7TFBK.js.map
|
|
28
|
+
//# sourceMappingURL=chunk-7ZL7TFBK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/shims/next-headers.ts"],"names":[],"mappings":";;;AAkBA,IAAM,cAAA,mBAAiB,MAAA,CAAO,GAAA,CAAI,qBAAqB,CAAA;AAEvD,IAAM,OAAA,mBAAU,MAAA,CAAO,GAAA,CAAI,6BAA6B,CAAA;AAMxD,IAAM,OAAA,GAAY,UAAA,CAAuC,OAAO,CAAA,KAC9D,IAAI,iBAAA,EAAgC;AAwB/B,SAAS,cAAA,CAAkB,OAAA,EAAkB,EAAA,EAAa,aAAA,EAA2B;AAC1F,EAAA,OAAO,QAAQ,GAAA,CAAI,EAAE,OAAA,EAAS,aAAA,IAAiB,EAAE,CAAA;AACnD;AAGO,SAAS,cAAA,GAAsC;AACpD,EAAA,OAAO,OAAA,CAAQ,UAAS,EAAG,OAAA;AAC7B;AAWA,eAAsB,OAAA,GAA4B;AAChD,EAAA,MAAM,KAAA,GAAQ,QAAQ,QAAA,EAAS;AAC/B,EAAA,IAAI,CAAC,KAAA,EAAO,MAAM,IAAI,MAAM,wCAAwC,CAAA;AACpE,EAAA,MAAM,EAAE,SAAQ,GAAI,KAAA;AACpB,EAAA,IAAI,QAAQ,OAAA,CAAQ,GAAA,CAAI,iBAAiB,CAAA,SAAU,OAAA,CAAQ,OAAA;AAC3D,EAAA,MAAM,QAAA,GAAoB,OAAA,CAAQ,GAAA,CAAI,OAAA,EAAS,cAAc,CAAA;AAC7D,EAAA,MAAM,UAAU,KAAA,CAAM,aAAA,KAAkB,OAAO,QAAA,KAAa,WAAW,QAAA,GAAW,MAAA,CAAA;AAClF,EAAA,IAAI,CAAC,OAAA,EAAS,OAAO,OAAA,CAAQ,OAAA;AAC7B,EAAA,MAAM,IAAA,GAAO,IAAI,OAAA,CAAQ,OAAA,CAAQ,OAAO,CAAA;AACxC,EAAA,IAAA,CAAK,GAAA,CAAI,mBAAmB,OAAO,CAAA;AACnC,EAAA,OAAO,IAAA;AACT","file":"chunk-7ZL7TFBK.js","sourcesContent":["/**\n * Stands in for `next/headers` in the code this package shares with\n * `@lynkow/next`, which reads the incoming request through `headers()`. Here\n * the request comes from an `AsyncLocalStorage` the middleware fills, through\n * {@link runWithRequest}.\n *\n * Built into this package by an esbuild alias, never imported from `next`.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks'\n\n/** What the store holds for one request. */\nexport interface RequestStore {\n readonly request: Request\n /** The address of the client, as Astro resolved it (`context.clientAddress`). */\n readonly clientAddress?: string\n}\n\n/** Where Astro's Node request reader records the socket's remote address. */\nconst CLIENT_ADDRESS = Symbol.for('astro.clientAddress')\n\nconst STORAGE = Symbol.for('@lynkow/astro/request-store')\n\n/**\n * One storage per process, kept on `globalThis` so the middleware entry and\n * the server entry share it even when each carries its own copy of this file.\n */\nconst storage = ((globalThis as Record<symbol, unknown>)[STORAGE] ??=\n new AsyncLocalStorage<RequestStore>()) as AsyncLocalStorage<RequestStore>\n\n/**\n * Runs `fn` with `request` as the current request, which the buyer client\n * reads to forward the buyer's IP address on its writes. The middleware of\n * `@lynkow/astro/middleware` does it for every request; call it yourself only\n * from a middleware of your own that does not use that one.\n *\n * `clientAddress` is the client's address as Astro resolved it, used by\n * {@link headers} when the request carries no `X-Forwarded-For`. Without it,\n * the address Astro's Node server recorded on the request is used, if any.\n *\n * @example\n * // src/middleware.ts\n * export const onRequest = defineMiddleware((context, next) => {\n * let address: string | undefined\n * try {\n * address = context.clientAddress || undefined\n * } catch {\n * address = undefined // the adapter provides none\n * }\n * return runWithRequest(context.request, () => next(), address)\n * })\n */\nexport function runWithRequest<T>(request: Request, fn: () => T, clientAddress?: string): T {\n return storage.run({ request, clientAddress }, fn)\n}\n\n/** The request being served, or undefined outside one (a build, a script). */\nexport function currentRequest(): Request | undefined {\n return storage.getStore()?.request\n}\n\n/**\n * The headers of the request being served, as `next/headers` returns them.\n * Like Next's server, which fills a missing `X-Forwarded-For` from the\n * socket's remote address, a request without one reads it as the client's\n * address Astro resolved: a copy carries it, the request itself is untouched,\n * and an `X-Forwarded-For` the request carries is never replaced.\n *\n * @throws {Error} Outside a request, as Next's own does.\n */\nexport async function headers(): Promise<Headers> {\n const store = storage.getStore()\n if (!store) throw new Error('headers() was called outside a request')\n const { request } = store\n if (request.headers.has('x-forwarded-for')) return request.headers\n const recorded: unknown = Reflect.get(request, CLIENT_ADDRESS)\n const address = store.clientAddress || (typeof recorded === 'string' ? recorded : undefined)\n if (!address) return request.headers\n const copy = new Headers(request.headers)\n copy.set('x-forwarded-for', address)\n return copy\n}\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// ../lynkow-next/src/analytics/global.ts
|
|
2
|
+
function trackerGlobal() {
|
|
3
|
+
if (typeof window === "undefined") return void 0;
|
|
4
|
+
return window.LynkowAnalytics;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export { trackerGlobal };
|
|
8
|
+
//# sourceMappingURL=chunk-DQXJDZWU.js.map
|
|
9
|
+
//# sourceMappingURL=chunk-DQXJDZWU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../lynkow-next/src/analytics/global.ts"],"names":[],"mappings":";AAeO,SAAS,aAAA,GAA2C;AACzD,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,EAAa,OAAO,MAAA;AAC1C,EAAA,OAAQ,MAAA,CAA0D,eAAA;AACpE","file":"chunk-DQXJDZWU.js","sourcesContent":["/**\n * The part of the tracker's `window.LynkowAnalytics` global this package calls.\n *\n * The SDK declares that global on `Window`, but only for a file whose\n * compilation imports `lynkow` itself, and the client entry that ships\n * `LynkowTracker` imports `lynkow/visual-editor` alone. Every member is\n * optional and checked before a call: the global is whichever tracker the API\n * served, and one served before `setConsent` existed lacks it.\n */\nexport interface TrackerGlobal {\n track?: (event: Record<string, unknown>) => void\n setConsent?: (granted: boolean) => void\n}\n\n/** The running tracker's global: `undefined` on the server or before a tracker loaded. */\nexport function trackerGlobal(): TrackerGlobal | undefined {\n if (typeof window === 'undefined') return undefined\n return (window as unknown as { LynkowAnalytics?: TrackerGlobal }).LynkowAnalytics\n}\n"]}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// ../lynkow-next/src/locale-paths.ts
|
|
2
|
+
var ABSOLUTE_HREF = /^([a-z][a-z0-9+.-]*:|\/\/)/i;
|
|
3
|
+
function createLocalePaths(config, source) {
|
|
4
|
+
const { siteUrl } = config;
|
|
5
|
+
if (config.locales.length === 0 && !source) {
|
|
6
|
+
throw new Error(
|
|
7
|
+
"createLocalePaths has no locales: pass a static `locales` list to resolveConfig, or the runtime source from createSiteLocales"
|
|
8
|
+
);
|
|
9
|
+
}
|
|
10
|
+
const live = config.locales.length > 0 ? void 0 : source;
|
|
11
|
+
const site = new URL(siteUrl);
|
|
12
|
+
let keyed = null;
|
|
13
|
+
let byKey = /* @__PURE__ */ new Map();
|
|
14
|
+
function current() {
|
|
15
|
+
const { locales, defaultLocale } = live ? live.current() : config;
|
|
16
|
+
if (locales !== keyed) {
|
|
17
|
+
byKey = new Map(locales.map((locale) => [locale.toLowerCase(), locale]));
|
|
18
|
+
keyed = locales;
|
|
19
|
+
}
|
|
20
|
+
return { locales, defaultLocale, byKey };
|
|
21
|
+
}
|
|
22
|
+
function toLocale(value) {
|
|
23
|
+
return value ? current().byKey.get(value.toLowerCase()) ?? null : null;
|
|
24
|
+
}
|
|
25
|
+
function leadingLocale(pathname) {
|
|
26
|
+
const end = pathname.indexOf("/", 1);
|
|
27
|
+
const locale = toLocale(end === -1 ? pathname.slice(1) : pathname.slice(1, end));
|
|
28
|
+
if (!locale) return null;
|
|
29
|
+
return { locale, rest: end === -1 ? "/" : pathname.slice(end) };
|
|
30
|
+
}
|
|
31
|
+
function localeFromPath(pathname) {
|
|
32
|
+
return leadingLocale(pathname)?.locale ?? current().defaultLocale;
|
|
33
|
+
}
|
|
34
|
+
function localePath(locale, path = "/") {
|
|
35
|
+
const { locales, defaultLocale } = current();
|
|
36
|
+
const canonical = toLocale(locale);
|
|
37
|
+
if (!canonical) {
|
|
38
|
+
throw new RangeError(
|
|
39
|
+
`${JSON.stringify(locale)} is not one of the configured locales (${locales.join(", ")})`
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
const { pathname: raw, suffix } = splitSuffix(path.startsWith("/") ? path : `/${path}`);
|
|
43
|
+
const pathname = onSite(raw);
|
|
44
|
+
if (canonical === defaultLocale) {
|
|
45
|
+
const leading = leadingLocale(pathname);
|
|
46
|
+
if (!leading || leading.locale === defaultLocale) return pathname + suffix;
|
|
47
|
+
}
|
|
48
|
+
const segment = `/${canonical.toLowerCase()}`;
|
|
49
|
+
return (pathname === "/" ? segment : segment + pathname) + suffix;
|
|
50
|
+
}
|
|
51
|
+
function fromApiPath(path, locale) {
|
|
52
|
+
if (!path.startsWith("/")) return path;
|
|
53
|
+
const { pathname: raw, suffix } = splitSuffix(path);
|
|
54
|
+
const pathname = onSite(raw);
|
|
55
|
+
const leading = leadingLocale(pathname);
|
|
56
|
+
return leading ? localePath(leading.locale, leading.rest + suffix) : localePath(locale, pathname + suffix);
|
|
57
|
+
}
|
|
58
|
+
function localizeHref(href, locale) {
|
|
59
|
+
if (!href || ABSOLUTE_HREF.test(href) || !href.startsWith("/")) return href;
|
|
60
|
+
return fromApiPath(href, locale);
|
|
61
|
+
}
|
|
62
|
+
function hrefLocale(href) {
|
|
63
|
+
if (!ABSOLUTE_HREF.test(href) && !href.startsWith("/")) return null;
|
|
64
|
+
try {
|
|
65
|
+
const url = new URL(href, site);
|
|
66
|
+
return url.origin === site.origin ? localeFromPath(url.pathname) : null;
|
|
67
|
+
} catch {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function negotiateLocale(acceptLanguage) {
|
|
72
|
+
const { locales, defaultLocale, byKey: byKey2 } = current();
|
|
73
|
+
if (!acceptLanguage) return defaultLocale;
|
|
74
|
+
const ranked = acceptLanguage.split(",").map((part) => {
|
|
75
|
+
const [tag = "", ...params] = part.trim().split(";");
|
|
76
|
+
const q = params.find((param) => param.trim().startsWith("q="));
|
|
77
|
+
return { tag: tag.trim().toLowerCase(), q: q ? Number.parseFloat(q.split("=")[1] ?? "") : 1 };
|
|
78
|
+
}).filter((entry) => entry.tag.length > 0 && entry.q > 0).sort((a, b) => b.q - a.q);
|
|
79
|
+
for (const { tag } of ranked) {
|
|
80
|
+
const exact = byKey2.get(tag);
|
|
81
|
+
if (exact) return exact;
|
|
82
|
+
const base = tag.split("-")[0];
|
|
83
|
+
const partial = locales.find((code) => code.toLowerCase().split("-")[0] === base);
|
|
84
|
+
if (partial) return partial;
|
|
85
|
+
}
|
|
86
|
+
return defaultLocale;
|
|
87
|
+
}
|
|
88
|
+
function absoluteUrl(path) {
|
|
89
|
+
return `${siteUrl}${path.startsWith("/") ? path : `/${path}`}`;
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
get locales() {
|
|
93
|
+
return current().locales;
|
|
94
|
+
},
|
|
95
|
+
get defaultLocale() {
|
|
96
|
+
return current().defaultLocale;
|
|
97
|
+
},
|
|
98
|
+
toLocale,
|
|
99
|
+
isLocale: (value) => toLocale(value) !== null,
|
|
100
|
+
localeFromPath,
|
|
101
|
+
localePath,
|
|
102
|
+
fromApiPath,
|
|
103
|
+
localizeHref,
|
|
104
|
+
hrefLocale,
|
|
105
|
+
negotiateLocale,
|
|
106
|
+
absoluteUrl
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
function onSite(pathname) {
|
|
110
|
+
return pathname.replace(/[\t\n\r]/g, "").replace(/^[/\\]+/, "/");
|
|
111
|
+
}
|
|
112
|
+
function splitSuffix(path) {
|
|
113
|
+
const index = path.search(/[?#]/);
|
|
114
|
+
return index === -1 ? { pathname: path, suffix: "" } : { pathname: path.slice(0, index), suffix: path.slice(index) };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export { ABSOLUTE_HREF, createLocalePaths };
|
|
118
|
+
//# sourceMappingURL=chunk-USZSRPT5.js.map
|
|
119
|
+
//# sourceMappingURL=chunk-USZSRPT5.js.map
|