@storystick/next 0.2.0-rc.6 → 0.2.0-rc.8

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/PUBLIC-API.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @storystick/next API contract
2
2
 
3
- Install this candidate explicitly with `@storystick/next@0.2.0-rc.4` after registry bootstrap and publication. This repository alone does not make the candidate or beta channel available on npm.
3
+ Install this candidate explicitly with `@storystick/next@0.2.0-rc.8` after registry bootstrap and publication. This repository alone does not make the candidate or beta channel available on npm.
4
4
 
5
- Version 0.2.0-rc.4, cohort `sdk-0.2.0-rc.4`. ESM distribution; no CommonJS or universal Edge compatibility is promised.
5
+ Version 0.2.0-rc.8, cohort `sdk-0.2.0-rc.8`. ESM distribution; no CommonJS or universal Edge compatibility is promised.
6
6
 
7
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
8
 
package/README.md CHANGED
@@ -593,6 +593,18 @@ query receipt as browser authority. The first mounted query obtains its own read
593
593
  and receipt; a private seed never starts a public read while Preview authenticates.
594
594
  Use stable components and keys so content changes do not reset local UI state.
595
595
 
596
+ For a site-bound Preview query, the Next server seed also carries the public
597
+ render rules for editable fields. Subsequent authenticated browser reads use
598
+ those same rules with their own receipts and watermarks, so Click to Edit stays
599
+ attached after hydration and refetch. These rules do not authorize a read and
600
+ are not included in public or Published seeds. Keep the entire seed intact.
601
+
602
+ When that reactive query replaces the page returned by `site.resolvePage`, pass
603
+ `{ primaryPage: { documentId: route.document.documentId, locale: route.localeContext.locale, publicPathname: route.publicPathname } }`
604
+ as the second argument to `preloadQuery`. The query must return that single
605
+ document. This preserves the resolved page and language through browser reads;
606
+ it does not replace the Preview session or its read receipts.
607
+
596
608
  The local editing projection remains an internal, bilateral qualification gate
597
609
  (`STORYSTICK_PREVIEW_LIVE_QUERY_OVERLAY` on the Next server and the corresponding
598
610
  Studio build gate). Installing this API alone does not activate it. It projects
package/dist/.source-hash CHANGED
@@ -1 +1 @@
1
- 4ced3e6c171faffecd7beaf6850c7f41529aa6f6b00fdf8a1b0173c85b109792
1
+ d0d57b2b4d96f064f45f2f3ac5636a3cc81e60e88e61b0c5241dd97eb90215e3
@@ -1,3 +1,4 @@
1
1
  export * from './rendering.js';
2
+ export { preloadQuery } from './preload-query.js';
2
3
  import type { StorystickProps } from './storystick.js';
3
4
  export declare function Storystick(props?: StorystickProps): Promise<import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>>>;
@@ -1,6 +1,7 @@
1
1
  // Server-only assembly of the existing mount. Client imports keep the same
2
2
  // entry and never pull next/headers or credentials into their bundle.
3
3
  export * from './rendering.js';
4
+ export { preloadQuery } from './preload-query.js';
4
5
  import { renderStorystick } from './storystick.js';
5
6
  import { readPreviewServerRenderReceipt } from './server-runtime.js';
6
7
  export async function Storystick(props = {}) {
@@ -0,0 +1,18 @@
1
+ import 'server-only';
2
+ import type { QueryExecuteOptions, QuerySnapshot } from '@storystick/client';
3
+ import type { QueryPageInfo, QueryResult } from '@storystick/types/query-contract';
4
+ import type { PreviewQueryRenderDefinition } from '@storystick/preview/query-render';
5
+ import { type PreviewPrimaryPage } from '@storystick/preview/provenance';
6
+ export interface PreloadQueryOptions extends QueryExecuteOptions {
7
+ /** The page resolved by the server when this query supplies its reactive rendering. */
8
+ readonly primaryPage?: PreviewPrimaryPage;
9
+ }
10
+ /** The server's semantic render rules also apply to subsequent browser reads. */
11
+ export declare function preloadQuery<TData, TPageInfo extends QueryPageInfo | null>(query: {
12
+ compile(): {
13
+ readonly canonical: string;
14
+ };
15
+ execute(options?: QueryExecuteOptions): Promise<QueryResult<TData, TPageInfo>>;
16
+ }, options?: PreloadQueryOptions): Promise<QuerySnapshot<TData, TPageInfo> & {
17
+ readonly previewRender?: PreviewQueryRenderDefinition;
18
+ }>;
@@ -0,0 +1,33 @@
1
+ import 'server-only';
2
+ import { preloadQuery as preloadClientQuery } from '@storystick/client';
3
+ import { getExecutableQueryDescriptor, getInternalClientRuntime } from '@storystick/client/internal';
4
+ import { previewRuntimeForSchema } from '@storystick/preview/server/provenance-runtime';
5
+ import { selectPreviewPrimaryPage } from '@storystick/preview/provenance';
6
+ /** The server's semantic render rules also apply to subsequent browser reads. */
7
+ export async function preloadQuery(query, options) {
8
+ const { primaryPage, ...executeOptions } = options ?? {};
9
+ if (primaryPage && !selectPreviewPrimaryPage([primaryPage], primaryPage.publicPathname)) {
10
+ throw new TypeError('Invalid Preview primary page.');
11
+ }
12
+ const snapshot = await preloadClientQuery(query, executeOptions);
13
+ const document = snapshot.result.data;
14
+ if (primaryPage && document !== null && (Array.isArray(document) || document.documentId !== primaryPage.documentId)) {
15
+ throw new TypeError('The Preview primary page must match the preloaded document.');
16
+ }
17
+ const client = getExecutableQueryDescriptor(query).host.client;
18
+ const runtime = client && previewRuntimeForSchema(client.schema);
19
+ if (!snapshot.preview || !runtime?.config.isEnabled() ||
20
+ (client && getInternalClientRuntime(client).requestContext?.previewReadContext?.perspective.kind === 'published'))
21
+ return snapshot;
22
+ const previewRender = {
23
+ version: 1,
24
+ codeVersion: runtime.config.resolveCodeVersion(),
25
+ manifest: await runtime.config.resolveSemanticManifest(),
26
+ ...(primaryPage && document ? { primaryPage: {
27
+ documentId: primaryPage.documentId,
28
+ locale: primaryPage.locale,
29
+ publicPathname: primaryPage.publicPathname,
30
+ } } : {}),
31
+ };
32
+ return { ...snapshot, previewRender };
33
+ }
@@ -0,0 +1,12 @@
1
+ import type { Client } from '@storystick/client';
2
+ import type { PreviewReadContext } from '@storystick/types/preview-query-targeting';
3
+ interface ClientOwner {
4
+ readonly client: Client;
5
+ readonly sessionId: string | null;
6
+ readonly previewToken: string | null;
7
+ readonly readContext: PreviewReadContext | null;
8
+ }
9
+ /** A layout and its error fallback may coexist. Restore only a surviving
10
+ * client for the current authority; never overwrite another runtime owner. */
11
+ export declare function attachPreviewHttpClient(owner: ClientOwner): () => void;
12
+ export {};
@@ -0,0 +1,26 @@
1
+ import { previewRuntime } from '@storystick/preview/runtime/store';
2
+ const owners = new Set();
3
+ function ownsCurrentAuthority(owner) {
4
+ const current = previewRuntime.getState();
5
+ const context = current.session?.readContext;
6
+ return current.state !== 'idle' &&
7
+ current.sessionId === owner.sessionId &&
8
+ current.previewToken === owner.previewToken &&
9
+ context?.contextId === owner.readContext?.contextId &&
10
+ context?.revision === owner.readContext?.revision;
11
+ }
12
+ /** A layout and its error fallback may coexist. Restore only a surviving
13
+ * client for the current authority; never overwrite another runtime owner. */
14
+ export function attachPreviewHttpClient(owner) {
15
+ if (!ownsCurrentAuthority(owner))
16
+ return () => { };
17
+ owners.add(owner);
18
+ previewRuntime.setHttpClient(owner.client);
19
+ return () => {
20
+ owners.delete(owner);
21
+ if (previewRuntime.getState().httpClient !== owner.client)
22
+ return;
23
+ const surviving = [...owners].reverse().find(ownsCurrentAuthority);
24
+ previewRuntime.setHttpClient(surviving?.client ?? null);
25
+ };
26
+ }
@@ -109,7 +109,7 @@ const useIsoLayoutEffect = typeof window === 'undefined' ? useEffect : useLayout
109
109
  import { setNavigateHandler, getNavigateHandler, setReloadHandler, getReloadHandler, } from '@storystick/preview/nav-handler';
110
110
  import { notifyRouterTransition } from '@storystick/preview/router-subscriber';
111
111
  import { isPreviewModeLatched, readPreviewSessionIdForNavigation, readPreviewVariantIdForNavigation, readPreviewReleaseIdForNavigation, setLatchedPreviewScope, } from './preview-mode-latch.js';
112
- import { beginPreviewNavigation, cancelPreviewRefreshCoordination, observePreviewNavigationCommit, } from './preview-refresh-coordinator.js';
112
+ import { beginPreviewNavigation, capturePreviewNavigationSettlement, cancelPreviewRefreshCoordination, observePreviewNavigationCommit, } from './preview-refresh-coordinator.js';
113
113
  import { PREVIEW_SESSION_QUERY_PARAM, writePreviewScopeToSearchParams, } from '@storystick/preview/identity';
114
114
  // A nested error fallback may coexist with the layout adapter. When it leaves,
115
115
  // return control to the latest still-mounted adapter, never to a stale closure.
@@ -238,6 +238,13 @@ function preservePreviewSession(pathname, explicitScope) {
238
238
  */
239
239
  export function useStorystickPreviewNavigation(appRouter, options) {
240
240
  const [refreshPending, startRefresh] = useTransition();
241
+ const [navigationSettlement, setNavigationSettlement] = useState(null);
242
+ useEffect(() => {
243
+ if (refreshPending || navigationSettlement === null || typeof window === 'undefined')
244
+ return;
245
+ setNavigationSettlement(null);
246
+ navigationSettlement.settle(`${stripBasePath(options?.basePath ?? '', window.location.pathname)}${window.location.search}${window.location.hash}`);
247
+ }, [navigationSettlement, refreshPending, options?.basePath]);
241
248
  const [refreshCommand, setRefreshCommand] = useState(null);
242
249
  const navigationRevisionRef = useRef(0);
243
250
  useEffect(() => {
@@ -393,25 +400,29 @@ export function useStorystickPreviewNavigation(appRouter, options) {
393
400
  });
394
401
  if (shouldReplace || (navigateOptions?.refresh === true && typeof router.refresh !== 'function')) {
395
402
  recordPreviewPerfMetric(window, { name: 'next.navigate.replace' });
396
- // Pages Router has no refresh(). A private query revision forces its
397
- // data navigation even for the exact same URL and fragment (which
398
- // Next otherwise treats as a hash-only transition without new data).
403
+ const settle = capturePreviewNavigationSettlement();
404
+ let href = destination;
405
+ // Pages Router needs a data navigation even for the same URL.
399
406
  if (navigateOptions?.refresh === true && typeof router.refresh !== 'function' && router === pagesRouter) {
400
407
  const refreshed = new URL(destination, 'https://preview.invalid');
401
408
  refreshed.searchParams.set('_ss_refresh', navigateOptions.commandId ?? createPreviewRequestId());
402
- startRefresh(() => {
403
- resetPreviewRenderFailure();
404
- router[navigateOptions?.history === 'push' ? 'push' : 'replace'](`${refreshed.pathname}${refreshed.search}${refreshed.hash}`);
405
- });
409
+ href = `${refreshed.pathname}${refreshed.search}${refreshed.hash}`;
406
410
  }
407
- else
408
- startRefresh(() => {
409
- resetPreviewRenderFailure();
410
- if (navigateOptions?.history === 'push')
411
- router.push(destination);
412
- else
413
- router.replace(destination);
414
- });
411
+ startRefresh(() => {
412
+ resetPreviewRenderFailure();
413
+ if (router !== pagesRouter)
414
+ setNavigationSettlement({ settle });
415
+ const result = navigateOptions?.history === 'push' ? router.push(href) : router.replace(href);
416
+ if (router === pagesRouter) {
417
+ // Pages Router supplies an operation-owned promise; route events
418
+ // alone cannot correlate a redirected destination with this request.
419
+ void Promise.resolve(result).then(committed => {
420
+ if (committed !== true)
421
+ return;
422
+ settle(`${stripBasePath(options?.basePath ?? '', window.location.pathname)}${window.location.search}${window.location.hash}`);
423
+ }, () => { });
424
+ }
425
+ });
415
426
  }
416
427
  };
417
428
  setNavigateHandler(ourHandler);
@@ -0,0 +1,5 @@
1
+ export declare function PreviewProvenanceRuntimeLoader({ enabled, source, sessionId }: {
2
+ readonly enabled: boolean;
3
+ readonly source: string;
4
+ readonly sessionId: string | null;
5
+ }): null;
@@ -0,0 +1,86 @@
1
+ "use client";
2
+ import { useEffect } from "react";
3
+ import { previewRuntime } from "@storystick/preview/runtime/store";
4
+ import { emitRuntimeError, emitRuntimeRecovered } from "@storystick/preview/runtime/emit-runtime-error";
5
+ const FAILURE_CODE = "runtime.provenance_unavailable";
6
+ const SCRIPT_SELECTOR = "script[data-storystick-preview-provenance-runtime]";
7
+ function requestRuntime(source, sessionId) {
8
+ const realm = window;
9
+ const isCurrentSession = () => previewRuntime.getState().sessionId === sessionId;
10
+ const reportFailure = () => {
11
+ if (!isCurrentSession())
12
+ return;
13
+ emitRuntimeError({
14
+ code: FAILURE_CODE,
15
+ message: "Preview editing controls could not load. Reload this preview to try again.",
16
+ severity: "warning",
17
+ retryable: !realm.__ssPreviewProvenanceRuntimeInstalled,
18
+ persistence: "until-recovered",
19
+ });
20
+ };
21
+ if (realm.__ssPreviewProvenanceRuntimeReady) {
22
+ if (isCurrentSession())
23
+ emitRuntimeRecovered(FAILURE_CODE);
24
+ return;
25
+ }
26
+ // The entry guard prevents duplicate listeners even after partial execution.
27
+ // Only the completion marker proves that the reporter installed successfully.
28
+ if (realm.__ssPreviewProvenanceRuntimeInstalled) {
29
+ reportFailure();
30
+ return;
31
+ }
32
+ const url = new URL(source, window.location.href);
33
+ url.searchParams.set("_ss_session", sessionId);
34
+ if (Array.from(document.querySelectorAll(SCRIPT_SELECTOR))
35
+ .some(script => script.src === url.href))
36
+ return;
37
+ const append = (retry) => {
38
+ const script = document.createElement("script");
39
+ script.src = url.href;
40
+ script.async = true;
41
+ script.dataset.storystickPreviewProvenanceRuntime = sessionId;
42
+ let settled = false;
43
+ script.onload = () => {
44
+ if (settled)
45
+ return;
46
+ settled = true;
47
+ script.onload = script.onerror = null;
48
+ if (realm.__ssPreviewProvenanceRuntimeReady) {
49
+ if (isCurrentSession())
50
+ emitRuntimeRecovered(FAILURE_CODE);
51
+ }
52
+ else {
53
+ // A successful download can still fail during execution. Retain the
54
+ // node: rerunning a partially installed observer is not a safe retry.
55
+ reportFailure();
56
+ }
57
+ };
58
+ script.onerror = () => {
59
+ if (settled)
60
+ return;
61
+ settled = true;
62
+ script.onload = script.onerror = null;
63
+ script.remove();
64
+ if (!isCurrentSession() || realm.__ssPreviewProvenanceRuntimeReady)
65
+ return;
66
+ // Resource errors do not execute the script. One fresh request is safe;
67
+ // a later remount can retry again because the failed node was removed.
68
+ if (retry && !realm.__ssPreviewProvenanceRuntimeInstalled)
69
+ append(false);
70
+ else
71
+ reportFailure();
72
+ };
73
+ document.head.appendChild(script);
74
+ };
75
+ append(true);
76
+ }
77
+ export function PreviewProvenanceRuntimeLoader({ enabled, source, sessionId }) {
78
+ useEffect(() => {
79
+ if (!enabled || !sessionId || typeof document === "undefined")
80
+ return;
81
+ requestRuntime(source, sessionId);
82
+ // Reporter lifetime is the document's lifetime. Preserve healthy requests
83
+ // across concurrent adapters, StrictMode and HMR; it has no uninstall API.
84
+ }, [enabled, sessionId, source]);
85
+ return null;
86
+ }
@@ -17,6 +17,10 @@ export declare function beginPreviewNavigation(input: {
17
17
  }): boolean;
18
18
  /** Called by the framework location adapter after a destination commit. */
19
19
  export declare function observePreviewNavigationCommit(committedLocation: string): boolean;
20
+ /** Capture the owner before starting its framework transition. Settlement
21
+ * releases refresh coordination after a redirect; it does not attest that
22
+ * the requested URL rendered. A stale transition cannot release its successor. */
23
+ export declare function capturePreviewNavigationSettlement(): (location: string) => boolean;
20
24
  /**
21
25
  * Run an exact content refresh now, or fold it into the navigation refresh
22
26
  * that will run immediately after the destination commits.
@@ -21,6 +21,7 @@ export function beginPreviewNavigation(input) {
21
21
  }
22
22
  const pending = {
23
23
  destination: input.destination,
24
+ currentLocation: input.currentLocation,
24
25
  refresh: input.refresh ?? null,
25
26
  runRefresh: input.runRefresh,
26
27
  timer: setTimeout(() => {
@@ -41,6 +42,19 @@ export function observePreviewNavigationCommit(committedLocation) {
41
42
  settlePendingNavigation();
42
43
  return true;
43
44
  }
45
+ /** Capture the owner before starting its framework transition. Settlement
46
+ * releases refresh coordination after a redirect; it does not attest that
47
+ * the requested URL rendered. A stale transition cannot release its successor. */
48
+ export function capturePreviewNavigationSettlement() {
49
+ const pending = pendingNavigation;
50
+ return (location) => {
51
+ if (pending === null || pendingNavigation !== pending ||
52
+ sameBrowserLocation(pending.currentLocation, location))
53
+ return false;
54
+ settlePendingNavigation();
55
+ return true;
56
+ };
57
+ }
44
58
  /**
45
59
  * Run an exact content refresh now, or fold it into the navigation refresh
46
60
  * that will run immediately after the destination commits.
package/dist/server.d.ts CHANGED
@@ -6,5 +6,5 @@ export { stripPreviewProvenance } from './clean.js';
6
6
  export { STORYSTICK_PREVIEW_ROBOTS } from './preview-metadata.js';
7
7
  export { createSite, createServerClient, resolvePage, buildStorystickSitemap, buildStorystickSitemapShards, STORYSTICK_SITEMAP_MAX_URLS, storystickAlternates, } from './server-runtime.js';
8
8
  export type { SiteDefinition, CreateSiteOptions, StorystickSitemapBuildOptions, ResolvePageDataCondition, ResolvePageDataDeclaration, ResolvePageDataDeclarations, ResolvedPageData, ResolvePageRouteInput, ResolvePageInput, ResolvedRouteForSchema, ResolvedRouteWithPageData, TypedResolvePageInput, ResolvedDocumentRoute, StorystickAlternatesOptions, StorystickPublishedLocaleRoute, StorystickSitemapOptions, } from './server-runtime.js';
9
- export { preloadQuery } from '@storystick/client';
9
+ export { preloadQuery } from './preload-query.js';
10
10
  export type { QuerySnapshot } from '@storystick/client';
package/dist/server.js CHANGED
@@ -4,4 +4,4 @@ export { StorystickError } from '@storystick/client';
4
4
  export { stripPreviewProvenance } from './clean.js';
5
5
  export { STORYSTICK_PREVIEW_ROBOTS } from './preview-metadata.js';
6
6
  export { createSite, createServerClient, resolvePage, buildStorystickSitemap, buildStorystickSitemapShards, STORYSTICK_SITEMAP_MAX_URLS, storystickAlternates, } from './server-runtime.js';
7
- export { preloadQuery } from '@storystick/client';
7
+ export { preloadQuery } from './preload-query.js';
@@ -20,6 +20,8 @@ import { observeSuspiciousPreviewCodewords } from "@storystick/preview/dev/suspi
20
20
  import { recordPreviewPerfMetric, } from "@storystick/preview/runtime/perf-metrics";
21
21
  import { createPreviewGenerationRefresh } from "@storystick/preview/framework/generation-refresh";
22
22
  import { beginPreviewNavigation, cancelPreviewRefreshCoordination, requestPreviewContentRefresh } from "./preview-refresh-coordinator.js";
23
+ import { PreviewProvenanceRuntimeLoader } from "./preview-provenance-runtime-loader.js";
24
+ import { attachPreviewHttpClient } from "./preview-http-client.js";
23
25
  import { stripBasePath, useStorystickPreviewNavigation } from "./preview-nav.js";
24
26
  import { useStorystickPreviewLocation } from "./preview-nav-location.js";
25
27
  import { resolveStorystickBrowserCodeVersion } from "./code-version.js";
@@ -61,29 +63,6 @@ function readPublishableKey(propKey) {
61
63
  return propKey;
62
64
  return process.env.NEXT_PUBLIC_STORYSTICK_PUBLISHABLE_KEY ?? null;
63
65
  }
64
- function previewRuntimeScriptSource(source, sessionId) {
65
- const url = new URL(source, window.location.href);
66
- url.searchParams.set("_ss_session", sessionId);
67
- return url.href;
68
- }
69
- function PreviewProvenanceRuntimeLoader({ enabled, source, sessionId, }) {
70
- useEffect(() => {
71
- if (!enabled || !sessionId || typeof document === "undefined")
72
- return;
73
- const alreadyRequested = Array.from(document.querySelectorAll("script[data-storystick-preview-provenance-runtime]")).some((script) => script.dataset.storystickPreviewProvenanceRuntime === sessionId);
74
- if (alreadyRequested)
75
- return;
76
- const script = document.createElement("script");
77
- script.src = previewRuntimeScriptSource(source, sessionId);
78
- script.async = true;
79
- script.dataset.storystickPreviewProvenanceRuntime = sessionId;
80
- document.head.appendChild(script);
81
- // The loaded reporter installs a page-global observer and has no uninstall
82
- // contract. Keep the matching script node as the idempotency marker across
83
- // StrictMode and HMR remounts instead of cancelling an in-flight download.
84
- }, [enabled, sessionId, source]);
85
- return null;
86
- }
87
66
  /**
88
67
  * ADR-131 §D7.1a — the iframe runtime reads `__STORYSTICK_CODE_VERSION__`
89
68
  * from `window` (see `snapshot-reporter.ts::readCodeVersionFromWindow`).
@@ -123,6 +102,7 @@ export function StorystickPreviewRuntime(props = {}) {
123
102
  const router = useRouter();
124
103
  const [refreshPending, startRefresh] = useTransition();
125
104
  const generationRefresh = useRef(null);
105
+ const installedCheckpointRenderId = useRef(null);
126
106
  const serverRenderReceipt = useRef(props.previewServerRenderReceipt);
127
107
  serverRenderReceipt.current = props.previewServerRenderReceipt;
128
108
  const basePath = props.basePath ?? "";
@@ -355,14 +335,8 @@ export function StorystickPreviewRuntime(props = {}) {
355
335
  stop();
356
336
  };
357
337
  }, [state.state]);
358
- // ADR-131 Amendment 002 §5.2 + Codex R1 fix — publish the iframe-side
359
- // HTTP client to previewRuntime.httpClient so schema-store (and
360
- // future tier-2/3 helpers) can fetch the gateway. This complements
361
- // the StorystickQueryProvider wiring : it covers the V5.2 95% path
362
- // where the customer mounts `<Storystick />` standalone WITHOUT
363
- // StorystickQueryProvider (e.g. examples/oignon-fugace). When both
364
- // are mounted, setHttpClient calls converge ; last-write wins,
365
- // both produce equivalent clients.
338
+ // Schema reads share the active adapter's HTTP client. An error fallback
339
+ // may temporarily own it while the layout remains mounted.
366
340
  const httpClient = useMemo(() => {
367
341
  if (state.state === "idle")
368
342
  return null;
@@ -408,13 +382,15 @@ export function StorystickPreviewRuntime(props = {}) {
408
382
  props.previewLiveQueryOverlayEnabled,
409
383
  ]);
410
384
  useEffect(() => {
411
- if (state.state === "idle")
385
+ if (state.state === "idle" || httpClient === null)
412
386
  return;
413
- previewRuntime.setHttpClient(httpClient);
414
- return () => {
415
- previewRuntime.setHttpClient(null);
416
- };
417
- }, [state.state, httpClient]);
387
+ return attachPreviewHttpClient({
388
+ client: httpClient,
389
+ sessionId: state.sessionId,
390
+ previewToken: state.previewToken,
391
+ readContext: state.readContext,
392
+ });
393
+ }, [state.state, httpClient, state.sessionId, state.previewToken, state.readContext]);
418
394
  // Standalone views refresh when their own perspective changes. Embedded views
419
395
  // receive Studio's correlated navigation command; refreshing here as well
420
396
  // would also replace a presentation that Studio is still retaining.
@@ -520,8 +496,8 @@ export function StorystickPreviewRuntime(props = {}) {
520
496
  if (watch === null)
521
497
  return;
522
498
  let active = true;
523
- // Seed this context's watcher once. Later layout receipts must not reset
524
- // its requested generation and repeatedly retry an active error boundary.
499
+ // Seed this context's watcher once. Healthy installed receipts below can
500
+ // cover later checkpoints without restarting the watcher.
525
501
  const receipt = serverRenderReceipt.current;
526
502
  const driver = createPreviewGenerationRefresh({
527
503
  delayMs: REFRESH_DEBOUNCE_MS,
@@ -553,6 +529,22 @@ export function StorystickPreviewRuntime(props = {}) {
553
529
  generationRefresh.current = null;
554
530
  };
555
531
  }, [router, startRefresh, state.client, state.sessionId, state.readContext?.contextId, state.readContext?.revision, state.renderedReadContext?.contextId, state.renderedReadContext?.revision, props.previewProvenanceRuntimeEnabled]);
532
+ useEffect(() => {
533
+ const receipt = props.previewServerRenderReceipt;
534
+ // A layout receipt alone cannot attest a page replaced by an error
535
+ // boundary, or one whose refresh transition has not settled yet.
536
+ if (refreshPending || props.resetRenderError || hasPreviewRenderFailure() ||
537
+ state.state !== 'authenticated' || !receipt ||
538
+ receipt.readContext.contextId !== state.readContext?.contextId ||
539
+ receipt.readContext.revision !== state.readContext?.revision)
540
+ return;
541
+ const driver = generationRefresh.current;
542
+ if (!driver || installedCheckpointRenderId.current === receipt.renderId)
543
+ return;
544
+ installedCheckpointRenderId.current = receipt.renderId;
545
+ driver.observeRenderedCheckpoint(receipt.projectionCheckpoint);
546
+ }, [props.previewServerRenderReceipt, props.resetRenderError, refreshPending,
547
+ state.state, state.client, state.sessionId, state.readContext?.contextId, state.readContext?.revision]);
556
548
  useEffect(() => {
557
549
  generationRefresh.current?.observeTransition(refreshPending);
558
550
  }, [refreshPending, state.client, state.sessionId, state.readContext?.contextId, state.readContext?.revision]);
@@ -27,7 +27,7 @@ export function renderStorystick(props = {}) {
27
27
  assertServiceOrigin(clientProps.endpoint, selected.apiOrigin);
28
28
  assertServiceOrigin(clientProps.gatewaySyncUrl, selected.syncOrigin);
29
29
  }
30
- return (_jsx(StorystickClient, { ...clientProps, service: selected, codeVersion: resolveStorystickServerCodeVersion({
30
+ return (_jsx(StorystickClient, { ...clientProps, service: selected, endpoint: clientProps.endpoint ?? configured.endpoint, gatewaySyncUrl: clientProps.gatewaySyncUrl ?? configured.convexUrl, codeVersion: resolveStorystickServerCodeVersion({
31
31
  codeVersion: clientProps.codeVersion,
32
32
  }), previewProvenanceRuntimeEnabled: includePreviewProvenanceRuntime, previewProvenanceRuntimeSrc: previewProvenanceRuntimeSrc, previewLiveQueryOverlayEnabled: includePreviewLiveQueryOverlay }));
33
33
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storystick/next",
3
- "version": "0.2.0-rc.6",
3
+ "version": "0.2.0-rc.8",
4
4
  "license": "FSL-1.1-MIT",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -88,11 +88,11 @@
88
88
  },
89
89
  "dependencies": {
90
90
  "server-only": "^0.0.1",
91
- "@storystick/client": "0.2.0-rc.4",
92
- "@storystick/media": "0.2.0-rc.3",
93
- "@storystick/react": "0.2.0-rc.6",
94
- "@storystick/preview": "0.2.0-rc.4",
95
- "@storystick/types": "0.1.0-rc.3"
91
+ "@storystick/client": "0.2.0-rc.6",
92
+ "@storystick/preview": "0.2.0-rc.6",
93
+ "@storystick/media": "0.2.0-rc.5",
94
+ "@storystick/react": "0.2.0-rc.8",
95
+ "@storystick/types": "0.1.0-rc.5"
96
96
  },
97
97
  "devDependencies": {
98
98
  "@testing-library/react": "^16.3.2",