@lynkow/astro 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +29 -0
  2. package/README.md +390 -2
  3. package/dist/chunk-67VKUBOP.js +40 -0
  4. package/dist/chunk-67VKUBOP.js.map +1 -0
  5. package/dist/chunk-7ZL7TFBK.js +28 -0
  6. package/dist/chunk-7ZL7TFBK.js.map +1 -0
  7. package/dist/chunk-DQXJDZWU.js +9 -0
  8. package/dist/chunk-DQXJDZWU.js.map +1 -0
  9. package/dist/chunk-OGQ25G7G.js +329 -0
  10. package/dist/chunk-OGQ25G7G.js.map +1 -0
  11. package/dist/chunk-USZSRPT5.js +119 -0
  12. package/dist/chunk-USZSRPT5.js.map +1 -0
  13. package/dist/client/index.d.ts +60 -0
  14. package/dist/client/index.js +59 -0
  15. package/dist/client/index.js.map +1 -0
  16. package/dist/clients-DLlMBN4c.d.ts +10 -0
  17. package/dist/config-BVCvQ8Wx.d.ts +66 -0
  18. package/dist/index.d.ts +353 -0
  19. package/dist/index.js +395 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/integration.d.ts +37 -0
  22. package/dist/integration.js +51 -0
  23. package/dist/integration.js.map +1 -0
  24. package/dist/lynkow-cache-BKZFJRTI.d.ts +150 -0
  25. package/dist/middleware/index.d.ts +187 -0
  26. package/dist/middleware/index.js +582 -0
  27. package/dist/middleware/index.js.map +1 -0
  28. package/dist/next-headers-3VG6LM4M.js +3 -0
  29. package/dist/next-headers-3VG6LM4M.js.map +1 -0
  30. package/dist/next-navigation-VNM5XXCX.js +7 -0
  31. package/dist/next-navigation-VNM5XXCX.js.map +1 -0
  32. package/dist/react/index.d.ts +134 -0
  33. package/dist/react/index.js +128 -0
  34. package/dist/react/index.js.map +1 -0
  35. package/dist/server/index.d.ts +493 -0
  36. package/dist/server/index.js +989 -0
  37. package/dist/server/index.js.map +1 -0
  38. package/dist/site-locales-tmcu43n2.d.ts +80 -0
  39. package/package.json +91 -4
package/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,391 @@
1
- # Temporary Holding Version
1
+ # @lynkow/astro
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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 is served
145
+ once more while a fresh copy loads in the background (for up to a day, then the
146
+ read waits for the fresh copy). When that background load fails, the stale copy
147
+ keeps being served and the key is not retried for 30 seconds.
148
+ - The tags are the floor: the revalidation webhook evicts them, so an edit is
149
+ live on the next request.
150
+ - Concurrent reads of one key share one API call, and every reader gets its own
151
+ copy, so mutating a result never alters what the next request reads.
152
+ - A read with no `cached()`, or with `uncached()`, goes to the API every time.
153
+
154
+ The cache lives in the server process (`lynkowCache`, 1000 entries by default).
155
+ `createLynkowCache({ max, store, staleWhileRevalidate })` builds another; pass it
156
+ to `createClients` and to `createRevalidateEndpoint` alike. A `CacheStore`
157
+ (`get`, `set`, `deleteTags`, each possibly asynchronous) lets several instances
158
+ share one cache. An eviction then cancels the loads in flight in the instance
159
+ that received the webhook only: a load another instance started before the edit
160
+ can still store its pre-edit result, which stays until its `revalidate` elapses
161
+ and is then served once more as stale while the fresh copy loads. An eviction
162
+ waits up to 5 seconds for a store write already under way, and deletes one that
163
+ lands later again once it settles.
164
+
165
+ These clients are shared by every request: never use them for a buyer's cart or
166
+ session. Use `createBuyerClient` below.
167
+
168
+ ## Server
169
+
170
+ ```ts
171
+ // src/lib/server.ts
172
+ import { createLynkowServer } from '@lynkow/astro/server'
173
+
174
+ export const server = createLynkowServer({
175
+ config,
176
+ client: (locale) => lynkow(locale),
177
+ getSiteDomain: async (locale) => (await getSiteShell(locale)).domain,
178
+ siteLocales,
179
+ })
180
+ ```
181
+
182
+ **Text routes.** `server.textRoute(read, contentType)` returns an Astro endpoint
183
+ serving a file Lynkow generates, cached under `TAGS.seo`, with its URLs moved to
184
+ this site's origin and the default locale unprefixed. A file the site does not
185
+ produce answers 404.
186
+
187
+ ```ts
188
+ // src/pages/sitemap.xml.ts
189
+ import { XML } from '@lynkow/astro/server'
190
+ import { server } from '@/lib/server'
191
+
192
+ export const prerender = false
193
+ export const GET = server.textRoute((client, options) => client.seo.sitemap(options), XML)
194
+ ```
195
+
196
+ **Head data.** `pageHead(page, locale, fallbackPath)`, `routeHead(locale, path,
197
+ title, description)`, `articleHead`, `categoryHead`, `productHead`,
198
+ `productCollectionHead` and `productCategoryHead` return a flat `HeadData`:
199
+ `title` (with `titleAbsolute` when the editor's title already holds the brand),
200
+ `description`, `keywords`, `canonical`, `alternates` (the hreflang set, with
201
+ `x-default`), `robots`, `openGraph` and `twitter`. `articleHead` also fills
202
+ `openGraph.article` (`publishedTime`, `modifiedTime`, `authors`, `tags`), the
203
+ values of the `article:*` tags. A layout renders it with plain
204
+ tags. The builders run synchronously, so with runtime locales call them after
205
+ `await siteLocales.get()`.
206
+
207
+ **JSON-LD.** `await server.jsonLd(nodes, locale)` returns the payload of one
208
+ `<script type="application/ld+json">`, or null when there are no nodes. It is
209
+ already escaped: render it with `set:html`.
210
+
211
+ ## Revalidation webhook
212
+
213
+ ```ts
214
+ // src/pages/api/revalidate.ts
215
+ import { createRevalidateEndpoint } from '@lynkow/astro/server'
216
+ import { siteLocales } from '@/lib/lynkow'
217
+
218
+ export const prerender = false
219
+ export const POST = createRevalidateEndpoint({ secret: process.env.LYNKOW_WEBHOOK_SECRET, siteLocales })
220
+ ```
221
+
222
+ Point a Lynkow webhook at it with the same secret. Each signed event evicts the
223
+ cache tags it can invalidate. Without a secret the endpoint answers 503; a
224
+ missing or wrong signature 401; a body over 5 MiB 413.
225
+
226
+ ## Buyer session
227
+
228
+ A buyer's cart and account are read through a client created for one request
229
+ and seeded from the buyer's cookies, never cached:
230
+
231
+ ```astro
232
+ ---
233
+ // src/pages/[locale]/cart.astro
234
+ import { createBuyerClient } from '@lynkow/astro/server'
235
+ const buyer = createBuyerClient(config, Astro.cookies, { locale })
236
+ const cart = await buyer.cart.retrieve()
237
+ ---
238
+ ```
239
+
240
+ `setCartCookie(cookies, token)` and `setCustomerCookie(cookies, token)` store
241
+ the tokens in `__Host-` cookies (`Secure`, `HttpOnly`, `SameSite=Lax`, 30 days at
242
+ most), from an endpoint or an action. `clearBuyerCookies` and `signOut` remove
243
+ them. `assertSameOrigin(request)` refuses a mutating request sent from another
244
+ site.
245
+
246
+ ### Buyer IP forwarding
247
+
248
+ Every buyer call reaches the API from your server. Set `LYNKOW_SERVER_KEY` to the
249
+ site's server key and a buyer client forwards the buyer's IP address with it on
250
+ every write, so the API counts each buyer, rather than your server, against its
251
+ rate limits. The address is the first public `X-Forwarded-For` entry from the
252
+ right, or the one header `LYNKOW_CLIENT_IP_HEADER` names when your CDN writes the
253
+ visitor's address there.
254
+
255
+ The client reads the current request from a store the Lynkow middleware fills.
256
+ A site that does not use it wraps its own middleware's `next()` in
257
+ `runWithRequest`, with the client's address as Astro resolved it, read the way
258
+ the Lynkow middleware reads it (Astro throws when the adapter has none):
259
+
260
+ ```ts
261
+ // src/middleware.ts
262
+ import { defineMiddleware } from 'astro:middleware'
263
+ import { runWithRequest } from '@lynkow/astro/server'
264
+
265
+ export const onRequest = defineMiddleware((context, next) => {
266
+ let address: string | undefined
267
+ try {
268
+ address = context.clientAddress || undefined
269
+ } catch {
270
+ address = undefined
271
+ }
272
+ return runWithRequest(context.request, () => next(), address)
273
+ })
274
+ ```
275
+
276
+ Outside a request nothing is forwarded, the key included.
277
+ `resolveBuyerForwarding(headers)` returns the same `{ serverKey, clientIp }` for
278
+ code that builds its own client.
279
+
280
+ ## Visual editor
281
+
282
+ Lynkow's dashboard edits a site's blocks in place. Mark each block and each
283
+ editable field, then start the editor from the base layout:
284
+
285
+ ```astro
286
+ ---
287
+ // src/components/Hero.astro
288
+ const { data } = Astro.props
289
+ ---
290
+ <section data-lynkow-block="hero">
291
+ <h1 data-lynkow-field="title" data-lynkow-type="text" data-lynkow-label="Title">{data.title}</h1>
292
+ <div data-lynkow-field="body" data-lynkow-type="richtext" set:html={data.body} />
293
+ </section>
294
+ ```
295
+
296
+ ```astro
297
+ <!-- src/layouts/Base.astro -->
298
+ <script>
299
+ import { startVisualEditor } from '@lynkow/astro/client'
300
+ startVisualEditor()
301
+ </script>
302
+ ```
303
+
304
+ Outside the dashboard's preview frame `startVisualEditor` does nothing. Inside
305
+ it, every change is written into the page as it is typed: a field's text, or
306
+ its HTML for a `richtext` field. Mark the element that holds the text and
307
+ nothing else, use flat field keys (a repeater row cannot be marked), and give
308
+ `startVisualEditor({ cmsOrigin })` the same origin as the middleware, or
309
+ neither. It returns the function that stops it; `visualEditorStore` is the
310
+ state it shares with the React hooks.
311
+
312
+ ## React
313
+
314
+ In a React island, `Editable` and `EditableBlock` write the same markers, and
315
+ the hooks follow the editor:
316
+
317
+ ```tsx
318
+ import { Editable, EditableBlock } from '@lynkow/astro/react'
319
+
320
+ export function Hero({ data }: { data: { title: string; body: string } }) {
321
+ return (
322
+ <EditableBlock slug="hero" as="section">
323
+ <Editable field="title" as="h1">{data.title}</Editable>
324
+ <Editable field="body" type="richtext" as="div" html={data.body} />
325
+ </EditableBlock>
326
+ )
327
+ }
328
+ ```
329
+
330
+ `useLynkowField(block, field, value)`, `useBlockData(block, data)` and
331
+ `useIsPreviewMode()` read the store `startVisualEditor` fills rather than a
332
+ React context, so they need no provider and work in every island; a server
333
+ render returns the values passed in. A field whose block is marked in an
334
+ `.astro` component around the island names it: `<Editable block="hero"
335
+ field="title">`. A hydrated island (`client:load`, `client:visible`, ...)
336
+ re-renders on each change; the static HTML around it is patched in place, and
337
+ so is static HTML passed into it as children, which an island that remounts
338
+ those children resets to what it was when the island hydrated, until the next
339
+ change of that field.
340
+
341
+ `LynkowTracker` loads Lynkow's analytics tracker when the visitor's consent
342
+ allows it (`trackerAllowed(consent)` is the same rule), from a hydrated island:
343
+
344
+ ```tsx
345
+ <LynkowTracker config={config} consent={{ mode: null, state: 'not-required' }} />
346
+ ```
347
+
348
+ ## Integration
349
+
350
+ ```js
351
+ // astro.config.mjs
352
+ import { defineConfig } from 'astro/config'
353
+ import node from '@astrojs/node'
354
+ import lynkow from '@lynkow/astro/integration'
355
+
356
+ export default defineConfig({
357
+ output: 'server',
358
+ adapter: node({ mode: 'standalone' }),
359
+ integrations: [lynkow()],
360
+ })
361
+ ```
362
+
363
+ `astro dev` loads `.env` files into `import.meta.env` only. In development the
364
+ integration copies `LYNKOW_SERVER_KEY`, `LYNKOW_CLIENT_IP_HEADER`,
365
+ `LYNKOW_COUNTRY_HEADERS` and `LYNKOW_WEBHOOK_SECRET` from the files of the mode
366
+ the server runs in (`astro dev --mode staging` reads `.env.staging`) into
367
+ `process.env`, where the server code reads them, and leaves a variable already
368
+ set in the shell alone. In production, start the server with them in its
369
+ environment, for instance `node --env-file-if-exists=.env.local ./dist/server/entry.mjs`.
370
+
371
+ ## Images
372
+
373
+ ```astro
374
+ ---
375
+ import { imageSrcSet, imageUrl } from '@lynkow/astro'
376
+ ---
377
+ <img src={imageUrl({ src, width: 1280 })} srcset={imageSrcSet(src, [640, 960, 1280])} sizes="100vw" alt="" />
378
+ ```
379
+
380
+ Lynkow media is resized on the Lynkow CDN, never upscaled, in the best format
381
+ the browser accepts. A relative URL or a URL that is not Lynkow media comes back
382
+ unchanged, and its `srcset` is empty.
383
+
384
+ ## Analytics
385
+
386
+ `trackEvent(type, data)` sends one custom event, of the SDK's closed `AnalyticsEventType`, through the Lynkow tracker already on the page,
387
+ and returns `false` when no tracker has loaded.
388
+
389
+ ## License
390
+
391
+ 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"]}