@storystick/astro 0.0.0-stage → 0.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +112 -0
  2. package/PUBLIC-API.md +23 -0
  3. package/README.md +163 -2
  4. package/dist/.source-hash +1 -0
  5. package/dist/browser.d.ts +1 -0
  6. package/dist/browser.js +327 -0
  7. package/dist/components/File.astro +9 -0
  8. package/dist/components/Image.astro +18 -0
  9. package/dist/components/Link.astro +14 -0
  10. package/dist/components/PreviewHost.astro +12 -0
  11. package/dist/components/PublicDeliveryReceipt.astro +6 -0
  12. package/dist/components/PublicHost.astro +3 -0
  13. package/dist/components/RichText.astro +7 -0
  14. package/dist/components/RichTextInline.astro +6 -0
  15. package/dist/components/RichTextNode.astro +7 -0
  16. package/dist/components/Slice.astro +8 -0
  17. package/dist/components/SliceZone.astro +20 -0
  18. package/dist/components/Storystick.astro +6 -0
  19. package/dist/components/Text.astro +8 -0
  20. package/dist/components/Video.astro +13 -0
  21. package/dist/components/Zone.astro +11 -0
  22. package/dist/components/index.d.ts +12 -0
  23. package/dist/components/index.js +12 -0
  24. package/dist/control.d.ts +3 -0
  25. package/dist/control.js +132 -0
  26. package/dist/index.d.ts +14 -0
  27. package/dist/index.js +9 -0
  28. package/dist/integration.d.ts +10 -0
  29. package/dist/integration.js +59 -0
  30. package/dist/middleware.d.ts +1 -0
  31. package/dist/middleware.js +34 -0
  32. package/dist/navigation.d.ts +7 -0
  33. package/dist/navigation.js +34 -0
  34. package/dist/publication.d.ts +10 -0
  35. package/dist/publication.js +29 -0
  36. package/dist/readback.d.ts +14 -0
  37. package/dist/readback.js +18 -0
  38. package/dist/render-gate.d.ts +36 -0
  39. package/dist/render-gate.js +84 -0
  40. package/dist/rich-text.d.ts +35 -0
  41. package/dist/rich-text.js +127 -0
  42. package/dist/routes/control.d.ts +3 -0
  43. package/dist/routes/control.js +5 -0
  44. package/dist/routes/error.astro +8 -0
  45. package/dist/routes/readback.d.ts +3 -0
  46. package/dist/routes/readback.js +4 -0
  47. package/dist/server.d.ts +128 -0
  48. package/dist/server.js +305 -0
  49. package/dist/sitemap.d.ts +5 -0
  50. package/dist/sitemap.js +28 -0
  51. package/dist/slices.d.ts +28 -0
  52. package/dist/slices.js +34 -0
  53. package/dist/text.d.ts +10 -0
  54. package/dist/text.js +9 -0
  55. package/package.json +73 -3
package/LICENSE ADDED
@@ -0,0 +1,112 @@
1
+ # Functional Source License, Version 1.1, MIT Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-MIT
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 Tanguy Freycon
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the MIT license that is effective on the second anniversary of the date we make
91
+ the Software available. On or after that date, you may use the Software under
92
+ the MIT license, in which case the following will apply:
93
+
94
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
95
+ this software and associated documentation files (the "Software"), to deal in
96
+ the Software without restriction, including without limitation the rights to
97
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
98
+ of the Software, and to permit persons to whom the Software is furnished to do
99
+ so, subject to the following conditions:
100
+
101
+ The above copyright notice and this permission notice shall be included in all
102
+ copies or substantial portions of the Software.
103
+
104
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
105
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
106
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
107
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
108
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
109
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
110
+ SOFTWARE.
111
+
112
+ This Agreement shall be governed by the laws of France.
package/PUBLIC-API.md ADDED
@@ -0,0 +1,23 @@
1
+ # @storystick/astro API contract
2
+
3
+ Install this candidate explicitly with `@storystick/astro@0.2.0-rc.1` after registry bootstrap and publication. This repository alone does not make the candidate or beta channel available on npm.
4
+
5
+ Version 0.2.0-rc.1, cohort `sdk-0.2.0-rc.1`. ESM distribution; no CommonJS or universal Edge compatibility is promised.
6
+
7
+ This package is a product integration facade. Reserved contracts are required between SDK packages and must be upgraded with the same cohort. Their public export paths do not promise independent stability.
8
+
9
+ | Entry | Status |
10
+ | --- | --- |
11
+ | `.` | Supported beta entry |
12
+ | `./integration` | Supported beta entry |
13
+ | `./components` | Supported beta entry |
14
+ | `./browser` | Reserved SDK contract |
15
+ | `./internal/*` | Reserved SDK contract |
16
+ | `./components/*` | Supported beta entry |
17
+ | `./routes/*` | Reserved SDK contract |
18
+
19
+ The qualified toolchain is Node 24.19.0 and pnpm 9.15.9. Next uses App Router 15.5.28, Sharp 0.35.5 and React/React DOM 19.2.8; Astro uses 7.4.4 with the Node adapter 11.1.9. Browser delivery is verified by bundling; hosted Preview activation and cross-browser behavior require the staging manual check. Source/CLI are Node tools, server entries belong on the server, and browser entries must never receive a server API key.
20
+
21
+ Use a generated Query V2 definition. A missing document/singleton returns null, an empty collection returns an empty array, and fetch throws on blocked/degraded execution. Execute exposes the complete result envelope. RSC metadata must remain plain JSON data; request authority must not be stored in shared module state.
22
+
23
+ The repository is private. Public package availability does not make the monorepo public, and npm provenance from that repository is unavailable. Product and pilot support: [Storystick](https://storystick.app).
package/README.md CHANGED
@@ -1,3 +1,164 @@
1
- # Temporary Holding Version
1
+ # @storystick/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
+ Native Astro rendering with the shared Storystick query, media and Preview contracts. The initial candidate is exercised on Astro 7.4.4, Node 24.3 and `@astrojs/node` 11.1.9. The connected pilot uses the compiled package. Main, Published, release, variant, pathless documents, templates, independent reads, detached editing and React islands have been exercised with a real dedicated Studio project. The native starter is also qualified from installed tarballs outside the workspace. This does not qualify other deployment adapters or browsers; see the lifecycle limits below.
4
+
5
+ ## Configure once
6
+
7
+ Generate your content definition with the Storystick CLI, then export your site from a server module:
8
+
9
+ ```ts
10
+ // src/storystick.ts
11
+ import { getSecret } from 'astro:env/server';
12
+ import { createSite } from '@storystick/astro';
13
+ import * as definition from '../generated/storystick/query';
14
+
15
+ export const site = createSite({
16
+ definition,
17
+ projectId: getSecret('STORYSTICK_PROJECT_ID')!,
18
+ apiKey: () => getSecret('STORYSTICK_API_KEY')!,
19
+ publishableKey: () => getSecret('STORYSTICK_PUBLISHABLE_KEY')!,
20
+ applicationBuildId: getSecret('STORYSTICK_APP_BUILD_ID'),
21
+ siteUrl: 'https://example.com',
22
+ });
23
+ ```
24
+
25
+ The API key stays on the server. Preview requires the publishable key and the registered application build identity. Gateway infrastructure resolves from the project ID; `infrastructure` is an override for isolated development or self-hosting.
26
+
27
+ ```js
28
+ // astro.config.mjs
29
+ import { defineConfig } from 'astro/config';
30
+ import storystick from '@storystick/astro/integration';
31
+ export default defineConfig({
32
+ integrations: [storystick({ site: './src/storystick.ts' })],
33
+ });
34
+ ```
35
+
36
+ The public build can be static or SSR. Its Storystick mount emits no markup, CSS or JavaScript. For a separate Preview deployment, use `output: 'server'`, your SSR adapter, and `preview: { origin: 'https://preview.example.com' }` in the integration. The integration owns `/api/storystick/*`, `/storystick-preview-error`, the exact allowed origin and a composable middleware. Preview responses are private/no-store and noindex. A base path other than `/` is currently rejected explicitly.
37
+
38
+ ## Read and route
39
+
40
+ ```astro
41
+ ---
42
+ import { Text, SliceZone, Storystick } from '@storystick/astro/components';
43
+ import { site } from '../storystick';
44
+ import Hero from '../components/Hero.astro';
45
+ const route = await site.resolvePage(Astro);
46
+ if (route.type === 'redirect') return Astro.redirect(route.redirectTo, route.permanent ? 308 : 302);
47
+ if (route.type === 'notFound') Astro.response.status = 404;
48
+ ---
49
+ {route.type === 'document' ? <>
50
+ <Text as="h1" value={route.document.fields.title}/>
51
+ <SliceZone slices={route.document.fields.sections} components={{ hero: Hero }}/>
52
+ </> : <h1>Page not found</h1>}
53
+ <Storystick site={site}/>
54
+ ```
55
+
56
+ Resolve redirects and response statuses in the page frontmatter, before rendering child components: Astro cannot redirect after a child has started streaming. Use a native `src/pages/[...pathname].astro` catch-all for CMS routing. For static generation, export `getStaticPaths = () => site.params()`; Preview uses on-demand rendering. The route result discriminates documents by the generated story type. Redirects, publication inventory, canonical URLs and language alternates use the same logic as the Next adapter.
57
+
58
+ Independent layouts/components call `await site.client(Astro)`, then the generated Query V2 API. Pass the same Astro request context: admission and read context are shared within that request, never across visitors. Build-time `site.client()` has no Preview authority. `site.metadata(route)` returns canonical/language URLs and indexing posture; `site.sitemap()` returns published sitemap entries. `sitemapResponse(await site.sitemap())` returns XML for a native `sitemap.xml.ts` endpoint. Large sites use `site.sitemapIds()`, per-shard `site.sitemap({ id })` and `sitemapIndexResponse(urls)`; the application owns those endpoint paths. `publicOrigins` and `domainLocale` support language domains.
59
+
60
+ An explicit `_ss_draft` destination resolves a routable document without a pathname through `site.resolvePage(Astro)`. When its pathname is assigned, the resolver returns a canonical redirect. A native homepage uses `await site.resolvePreviewDraft(Astro)` and keeps its own content when the result is `null`. This also accepts a template prototype bound to the admitted view. The prototype must match that view’s route and target; ordinary customer navigation leaves it. As the pilot demonstrates, Storystick does not replace arbitrary customer content.
61
+
62
+ ## Native components
63
+
64
+ - `Text`: clean text and field provenance; `previewText(value)` returns `{ text, attributes }` for your own element.
65
+ - `Image`, `File`, `Video`: existing asset resolvers with native HTML, a named `fallback` slot and optional resolver `options`. Storystick owns image transforms; no second Astro image transform is applied.
66
+ - `Link`: the shared safe link resolver (`link`, `document` or `href`), native navigation and locale-aware document references carried by content values.
67
+ - `RichText`, `RichTextInline`: native HTML, block/mark/list/embed component overrides, safe links and field provenance. Unknown blocks preserve text and report a diagnostic.
68
+ - `SliceZone`: dispatches generated slices to native Astro components. The component receives `slice`, `siblings`, `bindings`, `zones` and `context`. Optional generated `contracts` validate variations and project the exact field surface. A `fallback` Astro component receives `failure`; otherwise unresolved slices fail visibly. Rich text embeds use the same contracts and fallback.
69
+ - `Slice`: an explicit visual root, e.g. `<Slice as="section" slice={slice} siblings={siblings}>`. `sliceAttributes()` is the wrapper-free alternative.
70
+ - `Zone`: renders a named `zones.name` descriptor as rich text or a nested slice zone.
71
+
72
+ Autonomous query values carry model bindings, zones, references and asset metadata. Raw values can supply an explicit `{ document, path }` source. A missing slice renderer or unresolved model fails visibly instead of silently dropping a section.
73
+
74
+ ## Preview lifecycle
75
+
76
+ Put one `Storystick` mount in the shared layout. Astro's native ClientRouter owns navigation and body replacement; the SDK host persists. Customer islands follow native Astro lifecycle rules. A response is acknowledged only after its receipt, destination and read context match the actual installed render. Invalid or stale HTTP responses preserve the last accepted page and offer recovery. The existing React authoring host is used for detached editing; customer markup can stay native Astro without a React integration.
77
+
78
+ Customer React islands can opt into `transition:persist` and the ordinary Astro React integration. The pilot verified `client:load`, `client:idle` and `client:visible`: persisted state survives refresh/navigation while new props arrive; ordinary islands remount; visible islands hydrate on visibility and retain field provenance. Menus, forms and media follow these native lifetimes, rather than an SDK promise to preserve arbitrary DOM state.
79
+
80
+ A complete transport failure is different from an invalid HTTP response: Astro 7.4.4 falls back to full browser navigation when its page fetch fails. In the offline pilot this lost local island state; restoring the network and reloading Studio recovered editing. Seamless offline navigation, long real BFCache suspension and browser-specific third-party cookie behavior remain outside the qualified matrix. The SDK does not replace Astro's loader to hide those limits.
81
+
82
+ The browser reads explicit Storystick markers only. `debug` on the mount enables identity/checkpoint traces on its own host; credentials are never recorded. Public and Preview must have distinct cache/origin policies. The qualified deployment target is Astro 7.4.4 with the official Node adapter 11.1.9 on Node 24.3. Other deployment adapters, base paths and server islands require their own qualification. Template rendering, image delivery, live edits, field selection and navigation back to a CMS document have been exercised in the connected pilot. The current native image component has responsive candidates and contextual alt; automatic LQIP loading effects are not part of its initial HTML-only contract.
83
+
84
+ ## Development
85
+
86
+ `pnpm --filter @storystick/astro build`, `pnpm --filter @storystick/astro test`, and `pnpm --filter @storystick/astro exec astro-check --tsconfig tsconfig.check.json` cover TypeScript, native components and low-level contracts. The public fixture builds with `pnpm --filter @storystick/astro exec astro build --root tests/fixtures/public`. Manual connected qualification uses `services/spikes/astro-preview-pilot`; no Preview browser E2E harness is introduced.
87
+
88
+ ## Deployment and publication
89
+
90
+ `site.locale(Astro)` uses the resolved route locale, or the configured/project
91
+ locale for an independent layout. `SliceComponentProps<GeneratedSliceData>` types
92
+ a native slice without requiring an index signature on generated data.
93
+
94
+ Node SSR builds expose read-only `/api/storystick/health` and
95
+ `/api/storystick/migration-readback` endpoints through the integration. Readback
96
+ requires `applicationBuildId` and `applicationBuildDigest`, the deployed
97
+ application's lowercase SHA-256. It reports the build-paired schema and generated
98
+ query fingerprint for the CLI's existing migration attestation flow. It does not
99
+ activate a migration. Static output has no such request endpoints. Public SSR
100
+ rejects private Preview actions.
101
+
102
+ Public SSR has no SDK page cache. A deployment that adds a CDN cache owns its
103
+ invalidation. Static publication requires a new build and atomic deployment of
104
+ the resulting route inventory and sitemap. A missed hosting job must remain
105
+ recoverable by replaying or manually triggering that build.
106
+
107
+ For a server endpoint accepting Storystick publication deliveries:
108
+
109
+ ```ts
110
+ import type { APIRoute } from 'astro';
111
+ import { getSecret } from 'astro:env/server';
112
+ import { createPublicationHandler } from '@storystick/astro';
113
+ import { enqueueBuild } from '../your-build-queue';
114
+ const handle = createPublicationHandler({
115
+ projectId: getSecret('STORYSTICK_PROJECT_ID')!,
116
+ secret: () => getSecret('STORYSTICK_WEBHOOK_SECRET'),
117
+ onPublish: async event => { await enqueueBuild(event.projectId); return 'accepted'; },
118
+ });
119
+ export const prerender = false;
120
+ export const POST: APIRoute = ({ request }) => handle(request);
121
+ ```
122
+
123
+ Mount this outside the integration's reserved `/api/storystick/*` paths, for
124
+ example `/api/publication`, and configure that URL in Studio. A static-only
125
+ hosting target needs a separate server receiver. The SDK verifies the signature,
126
+ bounds actual body bytes to 1 MiB and checks the project and batch. It acknowledges
127
+ the callback's explicit `accepted` (durably enqueued) or `completed` (invalidation
128
+ performed) result; callback failure returns 503. Neither result certifies rendered
129
+ pages. The dispatcher retains a separate rendered proof obligation for instrumented
130
+ sites and retries until it is satisfied. Callbacks must tolerate repeated deliveries. Coalesce
131
+ builds while work is pending; do not keep a permanent content-hash deduplication
132
+ set, since an identical payload can represent a later legitimate publication.
133
+
134
+ ## Hosting and browser policy
135
+
136
+ Keep API keys and webhook secrets server-side. Configure the exact Preview origin
137
+ and Studio's allowed origins; do not reuse public CDN caching rules for Preview.
138
+ Production Preview requires HTTPS. Admission cookies are scoped by the shared
139
+ project/origin contract and remain HTTP-only; detached windows obtain their own
140
+ admission through Studio. Browser restrictions on third-party iframe cookies still
141
+ apply. Use the same site domain where appropriate, or the detached top-level
142
+ Preview flow when the browser blocks the embedding arrangement.
143
+
144
+ A custom CSP must permit Studio as a frame ancestor, the SDK's scripts and
145
+ styles, the configured content/asset origins, and the Preview/authoring HTTP and
146
+ WebSocket endpoints. Keep those policies specific to the chosen deployment;
147
+ there is no blanket wildcard policy supplied by the SDK.
148
+
149
+ The starter is available as `minimal-astro`. Its pinned artifact and the full
150
+ package dependency closure are qualified outside the workspace by
151
+ `pnpm starter:qualify:astro`: generation, Astro types, Node SSR, static localized
152
+ HTML, sitemap and unauthenticated Preview rejection. No browser test harness is
153
+ required for this distribution check.
154
+
155
+ The `deliveryEndpoint`, `deploymentId` and `publicRendering` site options connect
156
+ public reads and explicit rendering proof. See the repository's
157
+ [publication contract](../../services/public-content-gateway/PUBLICATION.md) for
158
+ receipt components, route manifests, v2 callbacks and qualified hosting modes.
159
+
160
+ ## Candidate distribution contract
161
+
162
+ See [PUBLIC-API.md](./PUBLIC-API.md) for supported entries, reserved SDK contracts,
163
+ the qualified runtime matrix and the candidate cohort. Upgrade Storystick
164
+ packages together.
@@ -0,0 +1 @@
1
+ 5f6f45338c96bd1cce60a00414498f8a9c138c04f19a80cf4bcc6d988b517a46
@@ -0,0 +1 @@
1
+ export declare function boot(): Promise<void>;
@@ -0,0 +1,327 @@
1
+ import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { navigate } from 'astro:transitions/client';
3
+ import { useSyncExternalStore } from 'react';
4
+ import { createRoot } from 'react-dom/client';
5
+ import { createInternalClient } from '@storystick/client/internal';
6
+ import { previewRuntime } from '@storystick/preview/runtime/store';
7
+ import { bootIframeRuntime } from '@storystick/preview/runtime/boot';
8
+ import { createPreviewRequestId } from '@storystick/preview/runtime/request-id';
9
+ import { isPreviewBrowserContext } from '@storystick/preview/identity/browser-context';
10
+ import { getNavigateHandler, getReloadHandler, setNavigateHandler, setReloadHandler } from '@storystick/preview/nav-handler';
11
+ import { notifyRouterTransition } from '@storystick/preview/router-subscriber';
12
+ import { setStandaloneOverlaySuspended } from '@storystick/preview/runtime/standalone-overlays';
13
+ import { PreviewStandaloneControls } from '@storystick/react/internal/preview-host';
14
+ import { canRefreshPresentedPreviewContext, createPreviewRuntimeAdapterStore, PREVIEW_RUNTIME_SERVER_SNAPSHOT } from '@storystick/preview/framework/runtime-adapter-store';
15
+ import { createPreviewProjectionGenerationWatch } from '@storystick/preview/framework/projection-generation-watch';
16
+ import { createPreviewGenerationRefresh } from '@storystick/preview/framework/generation-refresh';
17
+ import { isPreviewProjectionGenerationSignal } from '@storystick/preview/framework/generation-signal';
18
+ import { commitPreviewRenderReceipt } from '@storystick/preview/framework/render-receipt';
19
+ import { emitRuntimeError, emitRuntimeRecovered } from '@storystick/preview/runtime/emit-runtime-error';
20
+ import { createAstroRenderGate, isAstroRenderReceipt, renderLocation } from './render-gate.js';
21
+ import { createAstroNavigation } from './navigation.js';
22
+ const trace = [];
23
+ const record = (event, detail = {}) => {
24
+ if (!document.querySelector('[data-storystick-astro-host][data-storystick-debug]'))
25
+ return;
26
+ trace.push({ event, at: performance.now(), ...detail });
27
+ if (trace.length > 300)
28
+ trace.shift();
29
+ document.querySelector('[data-storystick-astro-host]')?.setAttribute('data-storystick-trace', JSON.stringify(trace));
30
+ };
31
+ let booted = false;
32
+ let disposeBoot;
33
+ if (import.meta.hot)
34
+ import.meta.hot.dispose(() => disposeBoot?.());
35
+ export async function boot() {
36
+ if (booted)
37
+ return;
38
+ const readRender = (doc = document) => {
39
+ try {
40
+ return JSON.parse(doc.querySelector('[data-storystick-astro-render]')?.textContent ?? 'null');
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ };
46
+ const initial = readRender();
47
+ if (!initial || !isPreviewBrowserContext(initial.config.projectId))
48
+ return;
49
+ booted = true;
50
+ const config = initial.config;
51
+ const lifetime = new AbortController();
52
+ let disposed = false;
53
+ window.__STORYSTICK_CODE_VERSION__ = config.codeVersion;
54
+ let watchCount = 0;
55
+ let driver = null;
56
+ let stopWatch;
57
+ let currentWatchKey = '';
58
+ let currentClientKey = '';
59
+ let currentReceipt = null;
60
+ let clearReceipt;
61
+ let renderError = initial.error ? 'The preview could not render this page.' : null;
62
+ let recoverAdmission = initial.recovery === 'admission';
63
+ let initialRecoveryLaunched = false;
64
+ let retryUrl = location.href;
65
+ let latestDestination = location.href;
66
+ let reportedLocation = null;
67
+ const retries = new Set();
68
+ const commands = new WeakMap();
69
+ const adapter = createPreviewRuntimeAdapterStore(previewRuntime);
70
+ const host = document.querySelector('[data-storystick-astro-host]');
71
+ const root = createRoot(host);
72
+ function Controls() {
73
+ const state = useSyncExternalStore(adapter.subscribe, adapter.getSnapshot, () => PREVIEW_RUNTIME_SERVER_SNAPSHOT);
74
+ if (window.parent !== window)
75
+ return null;
76
+ return _jsxs(_Fragment, { children: [renderError && _jsxs("aside", { role: "alert", "data-storystick-astro-error": true, style: { position: 'fixed', bottom: 16, left: 16, zIndex: 2147483646, padding: 16, background: '#fff', color: '#172b2a', border: '1px solid #aaa', borderRadius: 12 }, children: [_jsxs("p", { children: [renderError, " The last successful page is retained when available."] }), _jsx("button", { type: "button", onClick: () => void transition(retryUrl), children: "Retry preview" })] }), state.state !== 'idle' && _jsx(PreviewStandaloneControls, { projectId: config.projectId, state: state, pathname: location.pathname })] });
77
+ }
78
+ root.render(_jsx(Controls, {}));
79
+ record('boot');
80
+ const aligned = (receipt) => {
81
+ const context = previewRuntime.getState().session?.readContext;
82
+ return isAstroRenderReceipt(receipt) && context && receipt.readContext.contextId === context.contextId && receipt.readContext.revision === context.revision;
83
+ };
84
+ function fail(message, destination = latestDestination) {
85
+ if (disposed)
86
+ return;
87
+ renderError = message;
88
+ retryUrl = destination;
89
+ driver?.observeTransition(false);
90
+ emitRuntimeError({ code: 'runtime.customer_render_failed', message, severity: 'error', retryable: true });
91
+ root.render(_jsx(Controls, {}));
92
+ }
93
+ function commit(receipt, info) {
94
+ currentReceipt = receipt;
95
+ latestDestination = location.href;
96
+ clearReceipt?.();
97
+ clearReceipt = commitPreviewRenderReceipt(receipt);
98
+ renderError = null;
99
+ retries.clear();
100
+ emitRuntimeRecovered('runtime.customer_render_failed');
101
+ window.dispatchEvent(new CustomEvent('storystick.preview.rendered-context', { detail: {
102
+ sessionId: previewRuntime.getState().sessionId, source: 'framework', readContext: receipt.readContext,
103
+ } }));
104
+ reportLocation(receipt, info);
105
+ setStandaloneOverlaySuspended(false);
106
+ if (isPreviewProjectionGenerationSignal(receipt.projectionCheckpoint))
107
+ driver?.observeRenderedCheckpoint(receipt.projectionCheckpoint);
108
+ driver?.observeTransition(false);
109
+ record('render-accepted', { renderId: receipt.renderId, revision: receipt.readContext.revision, pathname: location.pathname, sameHost: host === document.querySelector('[data-storystick-astro-host]') });
110
+ root.render(_jsx(Controls, {}));
111
+ }
112
+ function reportLocation(receipt, info) {
113
+ reportedLocation = location.href;
114
+ const params = new URLSearchParams(location.search);
115
+ for (const key of [...params.keys()])
116
+ if (key.startsWith('_ss_'))
117
+ params.delete(key);
118
+ const presentation = { readContext: receipt.readContext, renderId: receipt.renderId, pathname: location.pathname };
119
+ notifyRouterTransition({ pathname: location.pathname, browserPathname: location.pathname,
120
+ search: params.toString(), hash: location.hash,
121
+ commandId: info && typeof info === 'object' ? commands.get(info) : undefined, presentation });
122
+ }
123
+ const gate = createAstroRenderGate({
124
+ readReceipt: (doc = document) => {
125
+ const rendered = readRender(doc);
126
+ return rendered?.config.projectId === config.projectId ? rendered.receipt : null;
127
+ },
128
+ readContext: () => previewRuntime.getState().session?.readContext,
129
+ readUrl: () => location.href,
130
+ commit,
131
+ reject(reason, destination) {
132
+ record('swap-rejected', { reason, pathname: destination.pathname });
133
+ driver?.observeTransition(false);
134
+ const context = previewRuntime.getState().session?.readContext;
135
+ const key = `${context?.contextId}:${context?.revision}:${renderLocation(destination)}`;
136
+ if (reason === 'context' && context && !retries.has(key)) {
137
+ retries.add(key);
138
+ // The native router aborts its prior navigation. The microtask runs
139
+ // after the rejected swap and cannot acknowledge that retained body.
140
+ queueMicrotask(() => { if (!disposed)
141
+ void transition(destination.href); });
142
+ }
143
+ else
144
+ fail('The preview could not render the requested page.', destination.href);
145
+ },
146
+ });
147
+ async function transition(destination, history = 'replace', commandId) {
148
+ if (disposed)
149
+ return;
150
+ try {
151
+ const url = new URL(destination, location.href);
152
+ if (url.origin !== location.origin)
153
+ throw new Error('STORYSTICK_NAVIGATION_ORIGIN');
154
+ // Astro otherwise skips the fetch for a same-page destination with a hash.
155
+ url.searchParams.set('_ss_refresh', createPreviewRequestId());
156
+ const info = {};
157
+ commands.set(info, commandId);
158
+ record('navigation-requested', { pathname: url.pathname, commandId });
159
+ await navigate(url.pathname + url.search + url.hash, { history, info });
160
+ }
161
+ catch (error) {
162
+ record('navigation-error', { message: String(error) });
163
+ fail('The preview request failed.', destination);
164
+ }
165
+ }
166
+ const navigation = createAstroNavigation(transition);
167
+ document.addEventListener('astro:before-preparation', ((event) => {
168
+ if (!commands.has(event.info))
169
+ navigation.invalidate();
170
+ latestDestination = event.to.href;
171
+ gate.prepare(event.signal);
172
+ driver?.observeTransition(true);
173
+ setStandaloneOverlaySuspended(true);
174
+ record('before-preparation', { pathname: event.to.pathname });
175
+ }), { signal: lifetime.signal });
176
+ document.addEventListener('astro:before-swap', ((event) => gate.beforeSwap(event)), { signal: lifetime.signal });
177
+ document.addEventListener('astro:after-swap', () => gate.afterSwap(), { signal: lifetime.signal });
178
+ const reportSameDocumentLocation = () => {
179
+ navigation.invalidate();
180
+ // Native hash/history navigation may not perform an Astro swap. Reuse only
181
+ // the already installed receipt, never manufacture another server render.
182
+ if (!renderError && currentReceipt && aligned(currentReceipt) && location.href !== reportedLocation &&
183
+ renderLocation(currentReceipt.renderedUrl) === renderLocation(location.href)) {
184
+ latestDestination = location.href;
185
+ reportLocation(currentReceipt);
186
+ record('same-document-location', { hash: location.hash });
187
+ }
188
+ };
189
+ window.addEventListener('hashchange', reportSameDocumentLocation, { signal: lifetime.signal });
190
+ window.addEventListener('popstate', reportSameDocumentLocation, { signal: lifetime.signal });
191
+ const navigateHandler = navigation.navigate;
192
+ const reloadHandler = (mode, options) => { navigation.invalidate(); if (mode === 'hard')
193
+ location.reload();
194
+ else
195
+ void transition(renderError ? retryUrl : location.href, 'replace', options.commandId); };
196
+ setNavigateHandler(navigateHandler);
197
+ setReloadHandler(reloadHandler);
198
+ let runtimeHandle;
199
+ let lastState = '';
200
+ const update = () => {
201
+ const state = previewRuntime.getState();
202
+ const context = state.session?.readContext;
203
+ const stateKey = `${state.state}:${state.error?.code}:${context?.revision}`;
204
+ if (lastState !== stateKey) {
205
+ lastState = stateKey;
206
+ record('runtime-state', { state: state.state, errorCode: state.error?.code, revision: context?.revision });
207
+ }
208
+ if (disposed)
209
+ return;
210
+ if (state.state !== 'authenticated' || !state.previewToken || !context) {
211
+ stopWatch?.();
212
+ stopWatch = undefined;
213
+ driver?.dispose();
214
+ driver = null;
215
+ watchCount = 0;
216
+ currentWatchKey = '';
217
+ currentClientKey = '';
218
+ return;
219
+ }
220
+ const key = `${state.sessionId}:${context.contextId}:${context.revision}`;
221
+ const clientKey = `${key}:${state.previewToken}`;
222
+ if (currentClientKey !== clientKey) {
223
+ currentClientKey = clientKey;
224
+ previewRuntime.setHttpClient(createInternalClient({
225
+ schema: { contractVersion: 2, fingerprint: 'query-schema.v2.preview-control-only', stories: {} },
226
+ projectId: config.projectId, publishableKey: config.publishableKey, endpoint: config.endpoint,
227
+ requestContext: { previewToken: state.previewToken, previewReadContext: context,
228
+ previewSessionId: state.sessionId, previewQueryConsumer: 'client-cache', previewObservationId: state.sessionId,
229
+ variantId: state.variantId, releaseId: state.releaseId },
230
+ }));
231
+ }
232
+ if (currentWatchKey !== key) {
233
+ currentWatchKey = key;
234
+ stopWatch?.();
235
+ driver?.dispose();
236
+ watchCount = 0;
237
+ const watch = createPreviewProjectionGenerationWatch(state.client, state.sessionId);
238
+ const receipt = readRender()?.receipt;
239
+ driver = createPreviewGenerationRefresh({ delayMs: 50,
240
+ initialCheckpoint: aligned(receipt) && isPreviewProjectionGenerationSignal(receipt.projectionCheckpoint) ? receipt.projectionCheckpoint : null,
241
+ refresh: () => driver?.dispatch(() => {
242
+ if (canRefreshPresentedPreviewContext(adapter.getSnapshot(), window.parent !== window))
243
+ void transition(renderError ? retryUrl : latestDestination);
244
+ else
245
+ driver?.observeTransition(false);
246
+ }),
247
+ setTimer: (callback, ms) => window.setTimeout(callback, ms), clearTimer: window.clearTimeout,
248
+ });
249
+ if (watch) {
250
+ watchCount = 1;
251
+ record('watch-started', { count: watchCount, revision: context.revision });
252
+ stopWatch = watch.subscribe(value => {
253
+ if (isPreviewProjectionGenerationSignal(value)) {
254
+ record('projection', { generation: value.generation, status: value.status, projectedThroughSeq: value.projectedThroughSeq });
255
+ driver?.observe(value);
256
+ }
257
+ }, () => driver?.resynchronize());
258
+ }
259
+ gate.initial();
260
+ if (recoverAdmission) {
261
+ recoverAdmission = false;
262
+ initialRecoveryLaunched = true;
263
+ record('admission-recovery');
264
+ void transition(location.href);
265
+ }
266
+ }
267
+ };
268
+ const unsubscribe = previewRuntime.subscribe(update);
269
+ if (!window.__ssPreviewProvenanceRuntimeInstalled) {
270
+ const reporter = document.createElement('script');
271
+ reporter.src = '/api/storystick/provenance-runtime';
272
+ reporter.dataset.storystickPreviewProvenanceRuntime = '';
273
+ document.head.append(reporter);
274
+ }
275
+ disposeBoot = () => {
276
+ if (disposed)
277
+ return;
278
+ disposed = true;
279
+ lifetime.abort();
280
+ navigation.dispose();
281
+ gate.dispose();
282
+ unsubscribe();
283
+ stopWatch?.();
284
+ driver?.dispose();
285
+ runtimeHandle?.teardown();
286
+ clearReceipt?.();
287
+ if (getNavigateHandler() === navigateHandler)
288
+ setNavigateHandler(null);
289
+ if (getReloadHandler() === reloadHandler)
290
+ setReloadHandler(null);
291
+ root.unmount();
292
+ previewRuntime.dispose();
293
+ watchCount = 0;
294
+ booted = false;
295
+ record('disposed');
296
+ };
297
+ window.addEventListener('pagehide', event => {
298
+ if (event.persisted) {
299
+ stopWatch?.();
300
+ stopWatch = undefined;
301
+ driver?.dispose();
302
+ driver = null;
303
+ watchCount = 0;
304
+ currentWatchKey = '';
305
+ record('suspended');
306
+ }
307
+ else
308
+ disposeBoot?.();
309
+ }, { signal: lifetime.signal });
310
+ window.addEventListener('pageshow', event => {
311
+ if (event.persisted) {
312
+ update();
313
+ driver?.resynchronize();
314
+ record('resumed');
315
+ }
316
+ }, { signal: lifetime.signal });
317
+ const initialized = previewRuntime.init({ projectId: config.projectId, gatewaySyncUrl: config.gatewaySyncUrl, tokenRoute: '/api/storystick/preview/token' });
318
+ runtimeHandle = await bootIframeRuntime();
319
+ await initialized;
320
+ if (disposed) {
321
+ runtimeHandle?.teardown();
322
+ return;
323
+ }
324
+ update();
325
+ if (renderError && !initialRecoveryLaunched)
326
+ fail(renderError);
327
+ }
@@ -0,0 +1,9 @@
1
+ ---
2
+ import type { HTMLAttributes } from 'astro/types';
3
+ import { resolveFile, type StorystickFileField, type ResolveFileOptions } from '@storystick/media';
4
+ import { cleanPreviewAttributes } from '../text.js';
5
+ interface Props extends Omit<HTMLAttributes<'a'>, 'href' | 'download' | 'type'> { file: StorystickFileField | null | undefined; options?: ResolveFileOptions }
6
+ const { file, options, ...attributes } = Astro.props;
7
+ const resolved = resolveFile(file, options);
8
+ ---
9
+ {resolved.status === 'ok' ? <a {...cleanPreviewAttributes(attributes)} {...resolved.props}><slot>{resolved.filename}</slot></a> : <slot name="fallback" />}