@storystick/next 0.2.0-rc.2 → 0.2.0-rc.4

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.2` 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.4` 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.2, cohort `sdk-0.2.0-rc.2`. ESM distribution; no CommonJS or universal Edge compatibility is promised.
5
+ Version 0.2.0-rc.4, cohort `sdk-0.2.0-rc.4`. 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
 
@@ -24,7 +24,7 @@ This package is a product integration facade. Reserved contracts are required be
24
24
  | `./testing` | Reserved SDK contract |
25
25
  | `./server` | Supported beta entry |
26
26
 
27
- 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.
27
+ Supported consumer Node versions: `^22.13.0 || ^24.19.0`. The release build toolchain remains 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.
28
28
 
29
29
  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.
30
30
 
package/README.md CHANGED
@@ -1,6 +1,21 @@
1
1
  # @storystick/next
2
2
 
3
- Minimal content reads and Preview for the Next.js 15 App Router, with React 19.
3
+ Minimal content reads and Preview for the Next.js 15 and 16 App Router, with React 19.
4
+
5
+ The supported framework ranges are `^15.5.28 || ^16.2.9`. Release preparation
6
+ qualifies both pinned minimum versions with the same SDK archives. The cache
7
+ webhook uses immediate tag expiration on both versions; Next 16's
8
+ stale-while-revalidate `max` profile is not substituted for that contract.
9
+
10
+ To repeat the standalone consumer recipe on Next 16:
11
+
12
+ ```sh
13
+ node scripts/starter-qualification.mjs --release-dir /path/to/candidate --next-version 16.2.9
14
+ ```
15
+
16
+ For SDK unit tests against an independently installed framework, set
17
+ `STORYSTICK_NEXT_TEST_ROOT` to that installation's `node_modules/next` directory.
18
+ This affects the test resolver only, never the package runtime.
4
19
 
5
20
  ```bash
6
21
  pnpm add @storystick/next@beta
@@ -519,5 +534,69 @@ must fail the next build. See the [Next 15 cache behavior](https://nextjs.org/do
519
534
  ## Candidate distribution contract
520
535
 
521
536
  See [PUBLIC-API.md](./PUBLIC-API.md) for supported entries, reserved SDK contracts,
522
- the qualified runtime matrix and the candidate cohort. Upgrade Storystick
523
- packages together.
537
+ the qualified runtime matrix and the candidate cohort. Keep shared contracts
538
+ compatible. Use the [release guide](../../release/README.md) to select the
539
+ packages and consumers that need an update; an independent adapter fix does
540
+ not require republishing every package.
541
+
542
+ ## Hosted connection
543
+
544
+ Run `storystick connect` from the website repository. The adapter uses the four
545
+ project connection variables written by the CLI and discovers the public
546
+ Storystick services. No infrastructure URL or platform environment selector is
547
+ required. Restart/rebuild Next after changing the connection: public variables
548
+ are embedded at build time.
549
+
550
+ Mount `<Storystick />` from a Server Component so server configuration reaches
551
+ the browser through the adapter. Explicit transport props remain available for
552
+ deliberate local/self-hosted integrations; conflicting service configuration
553
+ fails instead of silently selecting another destination.
554
+
555
+ ## Reactive rendering with a server seed
556
+
557
+ For content that must update locally while it is being edited, use the same
558
+ Query V2 definition in a client component. Server-only components continue to
559
+ update after the confirmed projection and Next refresh.
560
+
561
+ ```tsx
562
+ // Server Component
563
+ import { preloadQuery } from '@storystick/next/server'
564
+ const client = await site.client({ locale: 'en' })
565
+ const initialData = await preloadQuery(client.query('page').selectAll().by({ id }).locale('en'))
566
+ return <PageBody id={id} initialData={initialData} connection={site.browserOptions()} />
567
+ ```
568
+
569
+ ```tsx
570
+ 'use client'
571
+ import { createClient } from '@storystick/next'
572
+ import { useQuery } from '@storystick/next/query'
573
+ import { useMemo } from 'react'
574
+ import { querySchema } from '@/generated/storystick/query'
575
+
576
+ // Add props types from QuerySnapshot and your generated query definition.
577
+ function PageBody({ id, initialData, connection }) {
578
+ const connectionKey = JSON.stringify(connection)
579
+ const client = useMemo(() => createClient({
580
+ ...JSON.parse(connectionKey), schema: querySchema,
581
+ }), [connectionKey])
582
+ const result = useQuery(client.query('page').selectAll().by({ id }).locale('en'), { initialData })
583
+ if (result.status === 'error') throw result.error
584
+ if (!result.data) return null
585
+ return <PageContent page={result.data} />
586
+ }
587
+ ```
588
+
589
+ `browserOptions()` carries the selected public service and publishable key, never
590
+ a server API key or a session token. `preloadQuery` returns plain JSON with query,
591
+ project, schema, service and Preview context identities. It does not serialize a
592
+ query receipt as browser authority. The first mounted query obtains its own read
593
+ and receipt; a private seed never starts a public read while Preview authenticates.
594
+ Use stable components and keys so content changes do not reset local UI state.
595
+
596
+ The local editing projection remains an internal, bilateral qualification gate
597
+ (`STORYSTICK_PREVIEW_LIVE_QUERY_OVERLAY` on the Next server and the corresponding
598
+ Studio build gate). Installing this API alone does not activate it. It projects
599
+ bounded fields of already-authorized query results; filtered/sorted results,
600
+ new memberships and server-only components retain the confirmed refresh path.
601
+ A locally rendered edit is not a persistence acknowledgement. Navigation, save
602
+ errors and published delivery retain their existing authority checks.
package/dist/.source-hash CHANGED
@@ -1 +1 @@
1
- 211b14d8b654f14d3ad98557128d012e87d75573ab07151adeabe8bda3d331d1
1
+ 4ced3e6c171faffecd7beaf6850c7f41529aa6f6b00fdf8a1b0173c85b109792
@@ -4,9 +4,9 @@ export * from './rendering.js';
4
4
  import { renderStorystick } from './storystick.js';
5
5
  import { readPreviewServerRenderReceipt } from './server-runtime.js';
6
6
  export async function Storystick(props = {}) {
7
- const { projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion } = props;
7
+ const { projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion, service } = props;
8
8
  return renderStorystick({
9
- projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion,
9
+ projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion, service,
10
10
  previewServerRenderReceipt: await readPreviewServerRenderReceipt(projectId),
11
11
  });
12
12
  }
@@ -1,13 +1,3 @@
1
- /**
2
- * Internal helpers shared by the Preview activation and token routes.
3
- *
4
- * Server-only. Not re-exported from `@storystick/next/preview`.
5
- *
6
- * ADR-131 C9 — endpoint resolution flows through `resolveInfra()` which
7
- * shares its `resolveProject` cache with `server.ts` (same per-process
8
- * Map in `@storystick/client/resolve.ts`). The `STORYSTICK_ENDPOINT` env
9
- * escape hatch is preserved as an undocumented self-host override.
10
- */
11
1
  import type { NextRequest } from 'next/server';
12
2
  export type PreviewTransport = {
13
3
  endpoint: string;
@@ -56,6 +46,6 @@ export declare function _resetPreviewTransport(): void;
56
46
  /**
57
47
  * Allow tests to inject a transport without going through env vars or
58
48
  * `resolveProject`. The override is consumed by `getPreviewTransport`
59
- * on next call. Returns a dispose function that restores prior state.
49
+ * until `_resetPreviewTransport` clears it.
60
50
  */
61
51
  export declare function _setPreviewTransport(t: PreviewTransport | null): void;
@@ -1,3 +1,4 @@
1
+ import { serverInfraOptions } from '../service-config.js';
1
2
  /**
2
3
  * Internal helpers shared by the Preview activation and token routes.
3
4
  *
@@ -11,13 +12,15 @@
11
12
  import { resolveInfra } from '@storystick/client/adapter';
12
13
  import { previewControlClient } from '@storystick/preview/server/control-client';
13
14
  let _previewTransport = null;
15
+ let _previewTransportIdentity;
16
+ let _previewTransportOverride = null;
14
17
  export async function createPreviewControlClient(token) {
15
18
  const transport = await getPreviewTransport();
16
19
  return previewControlClient(transport.endpoint, token);
17
20
  }
18
21
  export async function getPreviewTransport() {
19
- if (_previewTransport)
20
- return _previewTransport;
22
+ if (_previewTransportOverride)
23
+ return _previewTransportOverride;
21
24
  const apiKey = process.env.STORYSTICK_API_KEY;
22
25
  if (!apiKey) {
23
26
  throw new Error('StorystickError: No STORYSTICK_API_KEY found.\n' +
@@ -32,10 +35,12 @@ export async function getPreviewTransport() {
32
35
  ' STORYSTICK_PROJECT_ID=a3k9m2x7\n' +
33
36
  ' STORYSTICK_API_KEY=ss_sk_live_...\n');
34
37
  }
35
- const directEndpoint = process.env.STORYSTICK_ENDPOINT;
36
- const infra = await resolveInfra(projectId, {
37
- endpoint: directEndpoint || undefined,
38
- });
38
+ const options = serverInfraOptions();
39
+ const identity = JSON.stringify([projectId, apiKey, options]);
40
+ if (_previewTransport && _previewTransportIdentity === identity)
41
+ return _previewTransport;
42
+ const infra = await resolveInfra(projectId, options);
43
+ _previewTransportIdentity = identity;
39
44
  _previewTransport = {
40
45
  endpoint: infra.endpoint,
41
46
  projectId,
@@ -86,12 +91,14 @@ export function resolvePreviewRequestOrigin(request) {
86
91
  /** Reset the transport singleton (testing only). */
87
92
  export function _resetPreviewTransport() {
88
93
  _previewTransport = null;
94
+ _previewTransportIdentity = undefined;
95
+ _previewTransportOverride = null;
89
96
  }
90
97
  /**
91
98
  * Allow tests to inject a transport without going through env vars or
92
99
  * `resolveProject`. The override is consumed by `getPreviewTransport`
93
- * on next call. Returns a dispose function that restores prior state.
100
+ * until `_resetPreviewTransport` clears it.
94
101
  */
95
102
  export function _setPreviewTransport(t) {
96
- _previewTransport = t;
103
+ _previewTransportOverride = t;
97
104
  }
@@ -7,6 +7,7 @@ import { createPreviewControlClient, getPreviewTransport, resolvePreviewRequestO
7
7
  import { resolvePreviewGrantAccess } from '@storystick/preview/server/extract-token';
8
8
  import { prunePreviewAdmissionCookies } from '@storystick/preview/server/route-session-cookie';
9
9
  import { previewControlErrorResponse, previewErrorResponse } from './route-errors.js';
10
+ import { serverInfraOptions } from '../service-config.js';
10
11
  export function createStorystickPreviewTokenHandler(options = {}) {
11
12
  return async function POST(request) {
12
13
  const sessionId = request.nextUrl.searchParams.get(PREVIEW_SESSION_QUERY_PARAM);
@@ -32,7 +33,8 @@ export function createStorystickPreviewTokenHandler(options = {}) {
32
33
  await client.context({ sessionId });
33
34
  const remainingMs = Math.max(0, fields.tokenExpiresAt - now);
34
35
  const response = NextResponse.json({ token: fields.token, expiresAt: fields.tokenExpiresAt,
35
- refreshAfter: now + Math.max(1000, Math.floor(remainingMs * 0.8)), sessionId, projectId: fields.projectId }, { headers: { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' } });
36
+ refreshAfter: now + Math.max(1000, Math.floor(remainingMs * 0.8)), sessionId, projectId: fields.projectId }, { headers: { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',
37
+ 'X-Storystick-Service': JSON.stringify(serverInfraOptions().service ?? null) } });
36
38
  // Safe even if this response arrives after a newer activation: all deletions
37
39
  // have lower sequence AND were observed in this particular request.
38
40
  prunePreviewAdmissionCookies({ response, reader, scope, requestUrl: requestOrigin + request.nextUrl.pathname,
@@ -0,0 +1,5 @@
1
+ import { type ServiceConnection } from '@storystick/types/public-endpoints';
2
+ /** Reuse existing identity carriers; the token route still authorizes every hint. */
3
+ export declare function recoverySessionId(projectId: string): string | null;
4
+ /** Error boundaries have no RSC props. Recover only from the site's authenticated route. */
5
+ export declare function recoverPreviewService(tokenRoute: string, projectId: string, sessionId: string | null, signal: AbortSignal): Promise<ServiceConnection | undefined>;
@@ -0,0 +1,32 @@
1
+ import { parseServiceConnection } from '@storystick/types/public-endpoints';
2
+ import { readPreviewSessionIdFromSearch, readStored } from '@storystick/preview/identity';
3
+ import { readStandalonePreviewSessionId } from '@storystick/preview/identity/browser-context';
4
+ /** Reuse existing identity carriers; the token route still authorizes every hint. */
5
+ export function recoverySessionId(projectId) {
6
+ if (new URLSearchParams(window.location.search).has('_ss_session'))
7
+ return readPreviewSessionIdFromSearch(window.location.search);
8
+ if (window.parent === window)
9
+ return readStandalonePreviewSessionId(projectId);
10
+ const stored = readStored();
11
+ return stored?.projectId === projectId && stored.expiresAt > Date.now() ? stored.sessionId : null;
12
+ }
13
+ /** Error boundaries have no RSC props. Recover only from the site's authenticated route. */
14
+ export async function recoverPreviewService(tokenRoute, projectId, sessionId, signal) {
15
+ if (!sessionId)
16
+ throw new Error('Preview session is required to recover the service.');
17
+ const url = new URL(tokenRoute, window.location.origin);
18
+ if (url.origin !== window.location.origin)
19
+ throw new Error('Preview service recovery must remain same-origin.');
20
+ url.searchParams.set('_ss_session', sessionId);
21
+ const response = await fetch(url.href, { method: 'POST', credentials: 'same-origin', redirect: 'error', cache: 'no-store', signal });
22
+ if (!response.ok)
23
+ throw new Error('Preview service recovery was refused.');
24
+ const body = await response.json();
25
+ if (body?.projectId !== projectId || body?.sessionId !== sessionId)
26
+ throw new Error('Preview service recovery identity mismatch.');
27
+ const raw = response.headers.get('X-Storystick-Service');
28
+ // Missing is not production: the route must understand this SDK contract.
29
+ if (raw === null)
30
+ throw new Error('Preview service configuration is missing.');
31
+ return raw === 'null' ? undefined : parseServiceConnection(raw);
32
+ }
@@ -31,3 +31,5 @@ export { Storystick } from './storystick.js';
31
31
  export { StorystickErrorRecovery } from './storystick-error-recovery.js';
32
32
  export type { StorystickProps } from './storystick.js';
33
33
  export { STORYSTICK_PREVIEW_ROBOTS } from './preview-metadata.js';
34
+ export { preloadQuery } from '@storystick/client';
35
+ export type { QuerySnapshot } from '@storystick/client';
package/dist/rendering.js CHANGED
@@ -40,3 +40,4 @@ export { STORYSTICK_PREVIEW_ROBOTS } from './preview-metadata.js';
40
40
  // import { useStorystickPreviewNavigation } from '@storystick/next/preview-nav'
41
41
  //
42
42
  // See `README.md` "Preview navigation" section for usage.
43
+ export { preloadQuery } from '@storystick/client';
@@ -5,7 +5,7 @@ export interface StorystickRevalidateHandlerOptions {
5
5
  projectId?: string | (() => string | undefined);
6
6
  signatureHeader?: string;
7
7
  }
8
- /** Next 15 revalidateTag expires the project's Data Cache synchronously. This
8
+ /** Expire the project's Data Cache on both Next 15 and Next 16. This
9
9
  * acknowledges the effect only; the publisher separately verifies rendered HTML. */
10
10
  export declare function createStorystickRevalidateHandler(options?: StorystickRevalidateHandlerOptions): (request: Request) => Promise<Response>;
11
11
  export declare const POST: (request: Request) => Promise<Response>;
@@ -3,7 +3,9 @@ import { storystickCacheTag } from './cache-tags.js';
3
3
  import { readSignedWebhook, signWebhookBody } from '@storystick/client/adapter';
4
4
  import { isPublicationEvent } from '@storystick/types/publication';
5
5
  import { revalidateTag } from 'next/cache';
6
- /** Next 15 revalidateTag expires the project's Data Cache synchronously. This
6
+ // Next 15 ignores the extra profile; Next 16 uses it for explicit immediate expiry.
7
+ const expireTag = revalidateTag;
8
+ /** Expire the project's Data Cache on both Next 15 and Next 16. This
7
9
  * acknowledges the effect only; the publisher separately verifies rendered HTML. */
8
10
  export function createStorystickRevalidateHandler(options = {}) {
9
11
  return async (request) => {
@@ -21,7 +23,7 @@ export function createStorystickRevalidateHandler(options = {}) {
21
23
  if (!isPublicationEvent(event) || event.projectId !== projectId)
22
24
  return json({ error: 'publication_invalid' }, 400);
23
25
  try {
24
- revalidateTag(storystickCacheTag(`storystick:project:${projectId}`));
26
+ expireTag(storystickCacheTag(`storystick:project:${projectId}`), { expire: 0 });
25
27
  }
26
28
  catch {
27
29
  return json({ error: 'publication_effect_failed' }, 503);
@@ -180,6 +180,23 @@ export declare function createSite<const TSchema extends QuerySchemaDefinition,
180
180
  client: (input?: {
181
181
  locale?: string;
182
182
  }) => Promise<Client<TSchema>>;
183
+ /** Public browser configuration from the same server-selected service.
184
+ * Request credentials and private operator configuration never cross RSC. */
185
+ browserOptions(): {
186
+ deliveryEndpoint?: string | undefined;
187
+ service: import("@storystick/types/public-endpoints").ServiceConnection;
188
+ projectId: string;
189
+ publishableKey: string;
190
+ } | {
191
+ deliveryEndpoint?: string | undefined;
192
+ endpoint: string;
193
+ projectId: string;
194
+ publishableKey: string;
195
+ } | {
196
+ deliveryEndpoint?: string | undefined;
197
+ projectId: string;
198
+ publishableKey: string;
199
+ };
183
200
  renderReceipt(input: {
184
201
  pathname: string;
185
202
  results: readonly object[];
@@ -1,3 +1,4 @@
1
+ import { serverInfraOptions } from './service-config.js';
1
2
  import { routeDataMatches } from '@storystick/types/public-delivery';
2
3
  import { PUBLIC_RENDER_CHALLENGE_HEADER, isPublicRenderChallenge } from '@storystick/types/public-delivery';
3
4
  import { fetchProjectLocaleSettings } from '@storystick/client/adapter';
@@ -181,20 +182,10 @@ function readProjectId() {
181
182
  ' STORYSTICK_PROJECT_ID=a3k9m2x7\n' +
182
183
  ' STORYSTICK_API_KEY=ss_sk_live_...\n');
183
184
  }
184
- /**
185
- * Resolve the gateway endpoint + Convex RPC URL for `projectId`. ADR-131
186
- * C9 — delegates to `resolveInfra` which auto-derives the `.convex.site` /
187
- * `.convex.cloud` pair from one gateway round-trip. Per-URL env escape
188
- * hatches (`STORYSTICK_ENDPOINT`, `STORYSTICK_CONVEX_URL`) are honoured
189
- * (undocumented in customer `.env.example`) for self-host overrides.
190
- */
185
+ /** Hosted routing follows the connection's environment. Legacy URL overrides
186
+ * are only read when no hosted environment was selected. */
191
187
  async function resolveServerInfra(projectId) {
192
- const directEndpoint = process.env.STORYSTICK_ENDPOINT;
193
- const directConvex = process.env.STORYSTICK_CONVEX_URL;
194
- return resolveInfra(projectId, {
195
- endpoint: directEndpoint && directEndpoint.length > 0 ? directEndpoint : undefined,
196
- convexUrl: directConvex && directConvex.length > 0 ? directConvex : undefined,
197
- });
188
+ return resolveInfra(projectId, serverInfraOptions());
198
189
  }
199
190
  /**
200
191
  * Build a Storystick client bound to the current Next.js request.
@@ -399,6 +390,7 @@ async function createNextServerClient(input) {
399
390
  projectId: input.projectId,
400
391
  apiKey: input.apiKey,
401
392
  endpoint: input.endpoint,
393
+ deliveryEndpoint: process.env.STORYSTICK_DELIVERY_ENDPOINT,
402
394
  defaults: input.locale ? { locale: input.locale } : undefined,
403
395
  requestContext,
404
396
  transport: withNextQueryOptions(input.projectId, localeGuardTransport(previewRuntimeForSchema(input.querySchema) ? undefined : input.locale, createPreviewReadIdentityTransport(createNextHttpTransport({
@@ -1503,6 +1495,19 @@ export function createSite(options) {
1503
1495
  };
1504
1496
  return Object.freeze({
1505
1497
  client,
1498
+ /** Public browser configuration from the same server-selected service.
1499
+ * Request credentials and private operator configuration never cross RSC. */
1500
+ browserOptions() {
1501
+ const { service, endpoint } = serverInfraOptions();
1502
+ const publishableKey = readRequiredEnv('NEXT_PUBLIC_STORYSTICK_PUBLISHABLE_KEY', 'Run storystick connect from the website repository.');
1503
+ return {
1504
+ projectId: readProjectId(),
1505
+ publishableKey,
1506
+ ...(service ? { service } : endpoint ? { endpoint } : {}),
1507
+ ...(!service && process.env.STORYSTICK_DELIVERY_ENDPOINT
1508
+ ? { deliveryEndpoint: process.env.STORYSTICK_DELIVERY_ENDPOINT } : {}),
1509
+ };
1510
+ },
1506
1511
  async renderReceipt(input) {
1507
1512
  if ((await draftMode()).isEnabled)
1508
1513
  return null;
package/dist/server.d.ts CHANGED
@@ -6,3 +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';
10
+ export type { QuerySnapshot } from '@storystick/client';
package/dist/server.js CHANGED
@@ -4,3 +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';
@@ -0,0 +1,6 @@
1
+ /** Server-side only input. Never read a second browser environment selector. */
2
+ export declare function serverInfraOptions(): {
3
+ service: import("@storystick/types/public-endpoints").ServiceConnection | undefined;
4
+ endpoint: string | undefined;
5
+ convexUrl: string | undefined;
6
+ };
@@ -0,0 +1,14 @@
1
+ import { assertServiceOrigin, serviceConnectionFromEnv } from '@storystick/types/public-endpoints';
2
+ /** Server-side only input. Never read a second browser environment selector. */
3
+ export function serverInfraOptions() {
4
+ const service = serviceConnectionFromEnv(process.env);
5
+ const endpoint = process.env.STORYSTICK_ENDPOINT || undefined;
6
+ const convexUrl = process.env.STORYSTICK_CONVEX_URL || undefined;
7
+ if (service) {
8
+ assertServiceOrigin(process.env.STORYSTICK_ENDPOINT, service.apiOrigin);
9
+ assertServiceOrigin(process.env.STORYSTICK_GATEWAY_URL, service.apiOrigin);
10
+ assertServiceOrigin(process.env.STORYSTICK_CONVEX_URL, service.syncOrigin);
11
+ assertServiceOrigin(process.env.STORYSTICK_DELIVERY_ENDPOINT, service.apiOrigin);
12
+ }
13
+ return { service, endpoint, convexUrl };
14
+ }
@@ -1,4 +1,7 @@
1
+ import type { ServiceConnection } from '@storystick/types/public-endpoints';
1
2
  export interface StorystickClientProps {
3
+ /** Complete alternate service, resolved by the server adapter. */
4
+ service?: ServiceConnection;
2
5
  /** Defaults to `process.env.NEXT_PUBLIC_STORYSTICK_PROJECT_ID`. */
3
6
  projectId?: string;
4
7
  /** Deploy/build signature exposed to the Preview iframe runtime. */
@@ -14,6 +17,8 @@ export interface StorystickClientProps {
14
17
  }
15
18
  /** @internal Props resolved by the server wrapper before the iframe runtime loads. */
16
19
  export interface StorystickPreviewRuntimeProps extends StorystickClientProps {
20
+ /** @internal Recover server selection when an error boundary replaces the RSC mount. */
21
+ readonly recoverServiceFromServer?: boolean;
17
22
  readonly previewServerRenderReceipt?: import('@storystick/preview/framework/render-receipt').PreviewFrameworkRenderReceipt | null;
18
23
  /** @internal Client error-boundary reset; never passed across an RSC boundary. */
19
24
  readonly resetRenderError?: () => void;
@@ -7,5 +7,5 @@ import { Storystick } from './storystick-component.js';
7
7
  * A normal public visit does not load the Preview runtime.
8
8
  */
9
9
  export function StorystickErrorRecovery({ error, reset, ...props }) {
10
- return _jsx(Storystick, { ...props, resetRenderError: reset, renderErrorDigest: error.digest });
10
+ return _jsx(Storystick, { ...props, recoverServiceFromServer: true, resetRenderError: reset, renderErrorDigest: error.digest });
11
11
  }
@@ -1,5 +1,7 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { parseServiceConnection } from '@storystick/types/public-endpoints';
4
+ import { recoverPreviewService, recoverySessionId } from './preview-service.js';
3
5
  import { PREVIEW_COPY } from '@storystick/preview/framework/preview-copy';
4
6
  import { hasExplicitPreviewBrowserContext } from '@storystick/preview/framework/browser-context';
5
7
  import { readStandalonePreviewSessionId, readStandaloneStudioUrl } from '@storystick/preview/identity/browser-context';
@@ -44,27 +46,15 @@ function readProjectId(propId) {
44
46
  process.env.STORYSTICK_PROJECT_ID ??
45
47
  null);
46
48
  }
47
- /**
48
- * Build the `resolveInfra()` options from props + (undocumented) env-var
49
- * escape hatches. The two `NEXT_PUBLIC_STORYSTICK_*` env reads are kept
50
- * as escape hatches for self-host customers and Storystick-internal
51
- * Vercel preview deploys ; they are intentionally absent from the
52
- * customer-facing `.env.example` per the C9 direction produit
53
- * ("Convex doit rester transparent au dev").
54
- */
49
+ /** Read public env variables literally so Next can replace them at build time.
50
+ * An active service rejects conflicting legacy URLs. Explicit props remain
51
+ * available for local/self-hosted adapters. */
55
52
  function buildInfraOptions(props) {
56
- const endpoint = props.endpoint ??
57
- process.env.NEXT_PUBLIC_STORYSTICK_GATEWAY_URL ??
58
- undefined;
59
- const convexUrl = props.gatewaySyncUrl ??
60
- process.env.NEXT_PUBLIC_STORYSTICK_GATEWAY_SYNC_URL ??
61
- undefined;
62
- const opts = {};
63
- if (endpoint)
64
- opts.endpoint = endpoint;
65
- if (convexUrl)
66
- opts.convexUrl = convexUrl;
67
- return opts;
53
+ return {
54
+ service: props.service === undefined ? undefined : parseServiceConnection(props.service),
55
+ endpoint: props.endpoint ?? process.env.NEXT_PUBLIC_STORYSTICK_GATEWAY_URL ?? undefined,
56
+ convexUrl: props.gatewaySyncUrl ?? process.env.NEXT_PUBLIC_STORYSTICK_GATEWAY_SYNC_URL ?? undefined,
57
+ };
68
58
  }
69
59
  function readPublishableKey(propKey) {
70
60
  if (propKey)
@@ -252,9 +242,9 @@ export function StorystickPreviewRuntime(props = {}) {
252
242
  const cv = readCodeVersion(props.codeVersion);
253
243
  window.__STORYSTICK_CODE_VERSION__ = cv;
254
244
  }
255
- const opts = buildInfraOptions(props);
256
245
  const tokenRoute = storystickRouteForBasePath(basePath, STORYSTICK_PREVIEW_TOKEN_ROUTE_PATH);
257
246
  let cancelled = false;
247
+ const recovery = new AbortController();
258
248
  const deadline = setTimeout(() => {
259
249
  if (!cancelled)
260
250
  setBootstrapSlow(true);
@@ -263,11 +253,19 @@ export function StorystickPreviewRuntime(props = {}) {
263
253
  setBootstrapSlow(false);
264
254
  void (async () => {
265
255
  try {
256
+ const opts = buildInfraOptions(props);
266
257
  const viewReady = ensureStandalonePreviewView(projectId);
258
+ if (props.recoverServiceFromServer) {
259
+ await viewReady;
260
+ const selected = await recoverPreviewService(tokenRoute, projectId, recoverySessionId(projectId), recovery.signal);
261
+ if (opts.service !== undefined && JSON.stringify(opts.service) !== JSON.stringify(selected))
262
+ throw new Error('Conflicting recovered Preview service.');
263
+ opts.service = selected;
264
+ }
267
265
  // Keep explicit sync configuration fast; discovery and recovery are independent.
268
266
  const discovered = resolveInfra(projectId, opts);
269
267
  const boot = viewReady.then(async () => {
270
- if (opts.convexUrl !== undefined && !cancelled)
268
+ if (opts.service === undefined && opts.convexUrl !== undefined && !cancelled)
271
269
  void previewRuntime.init({ projectId, gatewaySyncUrl: opts.convexUrl, tokenRoute });
272
270
  });
273
271
  const [resolved] = await Promise.all([discovered, boot]);
@@ -275,7 +273,7 @@ export function StorystickPreviewRuntime(props = {}) {
275
273
  if (cancelled)
276
274
  return;
277
275
  setInfra(resolved);
278
- if (opts.convexUrl === undefined)
276
+ if (opts.service !== undefined || opts.convexUrl === undefined)
279
277
  await previewRuntime.init({ projectId, gatewaySyncUrl: resolved.convexUrl, tokenRoute });
280
278
  }
281
279
  catch (err) {
@@ -290,6 +288,7 @@ export function StorystickPreviewRuntime(props = {}) {
290
288
  })();
291
289
  return () => {
292
290
  cancelled = true;
291
+ recovery.abort();
293
292
  clearTimeout(deadline);
294
293
  // Strict cleanup is intentionally NOT called here — the
295
294
  // singleton's lifecycle survives unmount/remount cycles
@@ -301,6 +300,10 @@ export function StorystickPreviewRuntime(props = {}) {
301
300
  basePath,
302
301
  props.projectId,
303
302
  props.gatewaySyncUrl,
303
+ props.recoverServiceFromServer,
304
+ props.service?.apiOrigin,
305
+ props.service?.syncOrigin,
306
+ props.service?.studioOrigin,
304
307
  props.endpoint,
305
308
  props.codeVersion,
306
309
  bootstrapAttempt,
@@ -1,4 +1,6 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { serverInfraOptions } from './service-config.js';
3
+ import { assertServiceOrigin, parseServiceConnection } from '@storystick/types/public-endpoints';
2
4
  import { Storystick as StorystickClient, } from './storystick-component.js';
3
5
  import { resolveStorystickServerCodeVersion } from './code-version.js';
4
6
  /**
@@ -8,8 +10,8 @@ import { resolveStorystickServerCodeVersion } from './code-version.js';
8
10
  * `codeVersion` prop.
9
11
  */
10
12
  export function Storystick(props = {}) {
11
- const { projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion } = props;
12
- return renderStorystick({ projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion });
13
+ const { projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion, service } = props;
14
+ return renderStorystick({ projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion, service });
13
15
  }
14
16
  /** @internal Runtime assembly and targeted tests; not exported by the SDK root. */
15
17
  export function renderStorystick(props = {}) {
@@ -17,7 +19,15 @@ export function renderStorystick(props = {}) {
17
19
  const includePreviewProvenanceRuntime = previewProvenanceRuntime ?? true;
18
20
  const includePreviewLiveQueryOverlay = previewLiveQueryOverlay ??
19
21
  process.env.STORYSTICK_PREVIEW_LIVE_QUERY_OVERLAY === '1';
20
- return (_jsx(StorystickClient, { ...clientProps, codeVersion: resolveStorystickServerCodeVersion({
22
+ const configured = serverInfraOptions();
23
+ const selected = clientProps.service === undefined ? configured.service : parseServiceConnection(clientProps.service);
24
+ if (configured.service && selected && JSON.stringify(configured.service) !== JSON.stringify(selected))
25
+ throw new TypeError('Conflicting server and component services.');
26
+ if (selected) {
27
+ assertServiceOrigin(clientProps.endpoint, selected.apiOrigin);
28
+ assertServiceOrigin(clientProps.gatewaySyncUrl, selected.syncOrigin);
29
+ }
30
+ return (_jsx(StorystickClient, { ...clientProps, service: selected, codeVersion: resolveStorystickServerCodeVersion({
21
31
  codeVersion: clientProps.codeVersion,
22
32
  }), previewProvenanceRuntimeEnabled: includePreviewProvenanceRuntime, previewProvenanceRuntimeSrc: previewProvenanceRuntimeSrc, previewLiveQueryOverlayEnabled: includePreviewLiveQueryOverlay }));
23
33
  }
package/dist/testing.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { serverInfraOptions } from './service-config.js';
1
2
  import 'server-only';
2
3
  import { createInternalClient } from '@storystick/client/internal';
3
4
  import { resolveInfra } from '@storystick/client/adapter';
@@ -11,12 +12,7 @@ const CONTROL_QUERY_SCHEMA = {
11
12
  export async function _buildBuildTimeClient() {
12
13
  const projectId = requiredEnv('STORYSTICK_PROJECT_ID');
13
14
  const apiKey = requiredEnv('STORYSTICK_API_KEY');
14
- const endpoint = process.env.STORYSTICK_ENDPOINT;
15
- const convexUrl = process.env.STORYSTICK_CONVEX_URL;
16
- const infra = await resolveInfra(projectId, {
17
- ...(endpoint ? { endpoint } : {}),
18
- ...(convexUrl ? { convexUrl } : {}),
19
- });
15
+ const infra = await resolveInfra(projectId, serverInfraOptions());
20
16
  return createInternalClient({
21
17
  schema: CONTROL_QUERY_SCHEMA,
22
18
  projectId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storystick/next",
3
- "version": "0.2.0-rc.2",
3
+ "version": "0.2.0-rc.4",
4
4
  "license": "FSL-1.1-MIT",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -82,17 +82,17 @@
82
82
  "tag": "beta"
83
83
  },
84
84
  "peerDependencies": {
85
- "next": "^15.5.28",
85
+ "next": "^15.5.28 || ^16.2.9",
86
86
  "react": "^19.2.8",
87
87
  "react-dom": "^19.2.8"
88
88
  },
89
89
  "dependencies": {
90
90
  "server-only": "^0.0.1",
91
- "@storystick/preview": "0.2.0-rc.2",
92
- "@storystick/types": "0.1.0-rc.2",
93
- "@storystick/client": "0.2.0-rc.2",
94
- "@storystick/media": "0.2.0-rc.2",
95
- "@storystick/react": "0.2.0-rc.2"
91
+ "@storystick/client": "0.2.0-rc.4",
92
+ "@storystick/react": "0.2.0-rc.4",
93
+ "@storystick/types": "0.1.0-rc.3",
94
+ "@storystick/media": "0.2.0-rc.3",
95
+ "@storystick/preview": "0.2.0-rc.4"
96
96
  },
97
97
  "devDependencies": {
98
98
  "@testing-library/react": "^16.3.2",
@@ -109,7 +109,7 @@
109
109
  "sharp": "0.35.5"
110
110
  },
111
111
  "engines": {
112
- "node": ">=24.19.0 <25"
112
+ "node": "^22.13.0 || ^24.19.0"
113
113
  },
114
114
  "repository": {
115
115
  "type": "git",
@@ -120,6 +120,9 @@
120
120
  "bugs": {
121
121
  "url": "https://storystick.app"
122
122
  },
123
+ "storystick": {
124
+ "serviceConfigVersion": 1
125
+ },
123
126
  "scripts": {
124
127
  "build": "node ../../scripts/package-dist.mjs clean && tsc && node ../../scripts/package-dist.mjs seal",
125
128
  "test": "vitest run",