@storystick/client 0.2.0-rc.1 → 0.2.0-rc.3

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/client API contract
2
2
 
3
- Install this candidate explicitly with `@storystick/client@0.2.0-rc.1` 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/client@0.2.0-rc.3` 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.1, cohort `sdk-0.2.0-rc.1`. ESM distribution; no CommonJS or universal Edge compatibility is promised.
5
+ Version 0.2.0-rc.3, cohort `sdk-0.2.0-rc.3`. 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
 
@@ -15,7 +15,7 @@ This package is a product integration facade. Reserved contracts are required be
15
15
  | `./adapter` | Reserved SDK contract |
16
16
  | `./seo` | Supported beta entry |
17
17
 
18
- 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.
18
+ 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.
19
19
 
20
20
  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.
21
21
 
package/README.md CHANGED
@@ -177,5 +177,14 @@ code does not inherit deployment or Studio concepts.
177
177
  ## Candidate distribution contract
178
178
 
179
179
  See [PUBLIC-API.md](./PUBLIC-API.md) for supported entries, reserved SDK contracts,
180
- the qualified runtime matrix and the candidate cohort. Upgrade Storystick
181
- packages together.
180
+ the qualified runtime matrix and the candidate cohort. Keep shared contracts
181
+ compatible. Use the [release guide](../../release/README.md) to select the
182
+ packages and consumers that need an update; an independent adapter fix does
183
+ not require republishing every package.
184
+
185
+ ## Hosted connection
186
+
187
+ Clients use the public production service by default. Framework adapters manage
188
+ service discovery; application content code needs no infrastructure URL or
189
+ platform environment selector. A key's live/test scope is independent of the
190
+ service destination.
package/dist/.source-hash CHANGED
@@ -1 +1 @@
1
- e9b1f5ad508349c6004d7e10c0272e3d09bbce936e2556b3c8e7d474d778c994
1
+ 8658badf612513cc5a25cae98ec06dd62445f9653b6cc2701472594e6b8b7328
@@ -1,94 +1,17 @@
1
- /**
2
- * Infrastructure URL resolution — ADR-131 C9.
3
- *
4
- * Centralizes derivation of the three Convex-flavoured URLs the customer-
5
- * bundled SDK packages need at runtime :
6
- *
7
- * - `endpoint` — gateway HTTP root, `.convex.site` form. Hosts the
8
- * custom HTTP routes (JWKS, Pattern-D queries).
9
- * - `convexUrl` — standard Convex RPC + WebSocket sync URL, `.convex.cloud`
10
- * form. Used by `ConvexReactClient` (WS) and the server-
11
- * side `ConvexHttpClient` (preview session lookup,
12
- * observation tap mutation).
13
- * - `jwksUrl` — `${endpoint}/api/jwks.json` by default.
14
- *
15
- * Cascade (per URL, independent) :
16
- *
17
- * 1. Explicit `options.*Url` — call-site override (props, env vars read
18
- * by the adapter and forwarded as options, factory args).
19
- * 2. Auto-derive from `resolveProject(projectId).endpoint`.
20
- * 3. Fail-loud — `resolveProject` throws a typed `StorystickError` if
21
- * the gateway returns 404/503/network error.
22
- *
23
- * The single `resolveProject` round-trip is shared across the three URLs ;
24
- * subsequent calls hit the per-process cache (server) or sessionStorage
25
- * cache (browser).
26
- *
27
- * **Env vars are NOT read here.** The bundler-replace behaviour of
28
- * `process.env.NEXT_PUBLIC_*` requires literal property access in the
29
- * adapter package (Next/React) so the static replacement at build time
30
- * resolves the value into the browser bundle. Adapters call this helper
31
- * after reading their respective env vars and forwarding them as options.
32
- *
33
- * Direction produit (owner 2026-05-26 PM) :
34
- *
35
- * > "Convex doit rester transparent au dev. Hors de question qu'une env
36
- * > var mentionnant convex.cloud / .site / etc apparaisse côté customer."
37
- *
38
- * The 5-var customer allowlist is `STORYSTICK_PROJECT_ID`, `STORYSTICK_API_KEY`,
39
- * `NEXT_PUBLIC_STORYSTICK_PROJECT_ID`, `NEXT_PUBLIC_STORYSTICK_PUBLISHABLE_KEY`,
40
- * `NEXT_PUBLIC_STORYSTICK_STUDIO_ORIGIN`. All Convex-flavoured URLs are
41
- * derived from `projectId` via this module.
42
- * Resource-storage bucket credentials belong exclusively to the server-side
43
- * storage resolver; they are never customer env vars or resolver options.
44
- */
1
+ /** Resolve hosted infrastructure from public discovery. Explicit URLs are for local/self-hosted use. */
2
+ import { type ServiceConnection } from '@storystick/types/public-endpoints';
45
3
  export interface ResolveInfraOptions {
46
- /** Explicit endpoint override (gateway HTTP root, `.convex.site`). */
4
+ service?: ServiceConnection;
47
5
  endpoint?: string;
48
- /** Explicit Convex RPC URL override (`.convex.cloud`). */
49
6
  convexUrl?: string;
50
- /** Explicit JWKS URL override. */
51
7
  jwksUrl?: string;
52
- /**
53
- * Optional gateway URL passed through to `resolveProject()` for self-host
54
- * overrides. Unused by default ; resolution falls back to
55
- * `DEFAULT_GATEWAY_URL` inside `resolve.ts`.
56
- */
57
8
  gatewayUrl?: string;
58
9
  }
59
10
  export interface ResolvedInfra {
60
- /** Gateway HTTP root (`.convex.site` form). HTTP custom routes + JWKS. */
61
11
  endpoint: string;
62
- /** Convex RPC / WS URL (`.convex.cloud` form). */
12
+ /** Internal adapter name; hosted connections use the public sync service. */
63
13
  convexUrl: string;
64
- /** JWKS endpoint (default `${endpoint}/api/jwks.json`). */
65
14
  jwksUrl: string;
66
15
  }
67
- /**
68
- * Synchronously derive `ResolvedInfra` when `endpoint` is already known
69
- * (explicit prop or env override). Used by adapters that need an
70
- * initial value during render — e.g. `<StorystickQueryProvider>`
71
- * synchronously seeds its `infra` state when all required values are
72
- * explicit, so generated clients can execute on the first render
73
- * inside an immediately-available `ConvexProvider` (codex R2 P2 fix).
74
- *
75
- * Returns `null` when `endpoint` is missing (gateway round-trip needed).
76
- */
77
16
  export declare function resolveInfraSync(options?: ResolveInfraOptions): ResolvedInfra | null;
78
- /**
79
- * Resolve the three infrastructure URLs for `projectId`.
80
- *
81
- * Idempotent + cache-aware — repeated calls with the same `projectId` reuse
82
- * the `resolveProject` cache (per-process Map server-side, sessionStorage
83
- * browser-side). Safe to call eagerly at module init.
84
- *
85
- * The `resolveProject` round-trip happens only when no explicit endpoint
86
- * override is supplied — `convexUrl` + `jwksUrl` are pure transforms on
87
- * `endpoint`. If `endpoint` is provided (prop or env escape hatch), the
88
- * helper completes without any network call ; gateway failures cannot
89
- * stall the boot path in that case.
90
- *
91
- * Throws (propagates) the `StorystickError` from `resolveProject` when the
92
- * gateway returns 404/503/network error AND no explicit `endpoint` is set.
93
- */
94
17
  export declare function resolveInfra(projectId: string, options?: ResolveInfraOptions): Promise<ResolvedInfra>;
@@ -1,130 +1,44 @@
1
- /**
2
- * Infrastructure URL resolution — ADR-131 C9.
3
- *
4
- * Centralizes derivation of the three Convex-flavoured URLs the customer-
5
- * bundled SDK packages need at runtime :
6
- *
7
- * - `endpoint` — gateway HTTP root, `.convex.site` form. Hosts the
8
- * custom HTTP routes (JWKS, Pattern-D queries).
9
- * - `convexUrl` — standard Convex RPC + WebSocket sync URL, `.convex.cloud`
10
- * form. Used by `ConvexReactClient` (WS) and the server-
11
- * side `ConvexHttpClient` (preview session lookup,
12
- * observation tap mutation).
13
- * - `jwksUrl` — `${endpoint}/api/jwks.json` by default.
14
- *
15
- * Cascade (per URL, independent) :
16
- *
17
- * 1. Explicit `options.*Url` — call-site override (props, env vars read
18
- * by the adapter and forwarded as options, factory args).
19
- * 2. Auto-derive from `resolveProject(projectId).endpoint`.
20
- * 3. Fail-loud — `resolveProject` throws a typed `StorystickError` if
21
- * the gateway returns 404/503/network error.
22
- *
23
- * The single `resolveProject` round-trip is shared across the three URLs ;
24
- * subsequent calls hit the per-process cache (server) or sessionStorage
25
- * cache (browser).
26
- *
27
- * **Env vars are NOT read here.** The bundler-replace behaviour of
28
- * `process.env.NEXT_PUBLIC_*` requires literal property access in the
29
- * adapter package (Next/React) so the static replacement at build time
30
- * resolves the value into the browser bundle. Adapters call this helper
31
- * after reading their respective env vars and forwarding them as options.
32
- *
33
- * Direction produit (owner 2026-05-26 PM) :
34
- *
35
- * > "Convex doit rester transparent au dev. Hors de question qu'une env
36
- * > var mentionnant convex.cloud / .site / etc apparaisse côté customer."
37
- *
38
- * The 5-var customer allowlist is `STORYSTICK_PROJECT_ID`, `STORYSTICK_API_KEY`,
39
- * `NEXT_PUBLIC_STORYSTICK_PROJECT_ID`, `NEXT_PUBLIC_STORYSTICK_PUBLISHABLE_KEY`,
40
- * `NEXT_PUBLIC_STORYSTICK_STUDIO_ORIGIN`. All Convex-flavoured URLs are
41
- * derived from `projectId` via this module.
42
- * Resource-storage bucket credentials belong exclusively to the server-side
43
- * storage resolver; they are never customer env vars or resolver options.
44
- */
1
+ /** Resolve hosted infrastructure from public discovery. Explicit URLs are for local/self-hosted use. */
2
+ import { DEFAULT_SERVICE_CONNECTION, parseServiceConnection, assertServiceOrigin } from '@storystick/types/public-endpoints';
45
3
  import { resolveProject } from './resolve.js';
46
- const JWKS_PATH = '/api/jwks.json';
47
- /**
48
- * Swap `.convex.site` → `.convex.cloud` on a Convex deployment URL. Returns
49
- * the input unchanged for non-Convex-Cloud deployments (self-host) — the
50
- * customer sets `convexUrl` explicitly in that case.
51
- *
52
- * **CSO trade-off (codex R2 P1, accepted per ADR-131 C9 brief direction
53
- * produit) :** the default `convexUrl` resolves to a raw `.convex.cloud`
54
- * deployment URL, bypassing the sub-gateway Worker (`services/sub-gateway/`).
55
- * Pre-C9, the default was `http://localhost:8787` (dev Worker URL) and
56
- * customers in prod were expected to set
57
- * `NEXT_PUBLIC_STORYSTICK_GATEWAY_SYNC_URL` explicitly — usually to the
58
- * Worker public URL (e.g. `https://gateway.storystick.app`). The Worker
59
- * is not deployed yet (5 Path B manual steps in
60
- * `services/sub-gateway/wrangler.toml`), so the spike-Vercel Fix 2 already
61
- * documents `.convex.cloud` direct as the only working posture today.
62
- *
63
- * Once the Worker is deployed, replace this default with the Worker
64
- * public URL constant ; the rest of the cascade is unchanged. The
65
- * explicit `options.convexUrl` override remains the escape hatch for
66
- * customers needing to bypass the constant (self-host, internal Vercel
67
- * deploys, etc.).
68
- *
69
- * See `storystick-hq/notes/adr-131-chantier/c9-hidden-vars-audit.md` §9
70
- * for the deferred-follow-up list.
71
- */
72
- function gatewayToConvex(endpoint) {
73
- if (endpoint.includes('.convex.site')) {
74
- return endpoint.replace('.convex.site', '.convex.cloud');
75
- }
76
- return endpoint;
77
- }
78
- function stripTrailingSlash(url) {
79
- return url.replace(/\/$/, '');
4
+ function syncForExplicitEndpoint(endpoint) {
5
+ if (endpoint === DEFAULT_SERVICE_CONNECTION.apiOrigin)
6
+ return DEFAULT_SERVICE_CONNECTION.syncOrigin;
7
+ // Only explicitly selected local/self-hosted deployments use this convention.
8
+ const url = new URL(endpoint);
9
+ if (url.hostname.endsWith('.convex.site'))
10
+ url.hostname = url.hostname.replace(/\.convex\.site$/, '.convex.cloud');
11
+ return url.toString().replace(/\/$/, '');
80
12
  }
81
- /**
82
- * Synchronously derive `ResolvedInfra` when `endpoint` is already known
83
- * (explicit prop or env override). Used by adapters that need an
84
- * initial value during render — e.g. `<StorystickQueryProvider>`
85
- * synchronously seeds its `infra` state when all required values are
86
- * explicit, so generated clients can execute on the first render
87
- * inside an immediately-available `ConvexProvider` (codex R2 P2 fix).
88
- *
89
- * Returns `null` when `endpoint` is missing (gateway round-trip needed).
90
- */
91
13
  export function resolveInfraSync(options = {}) {
14
+ if (options.service !== undefined) {
15
+ const service = parseServiceConnection(options.service);
16
+ assertServiceOrigin(options.endpoint, service.apiOrigin);
17
+ assertServiceOrigin(options.gatewayUrl, service.apiOrigin);
18
+ assertServiceOrigin(options.convexUrl, service.syncOrigin);
19
+ if (options.jwksUrl !== undefined && options.jwksUrl !== `${service.apiOrigin}/api/jwks.json`)
20
+ throw new TypeError('Service configuration conflicts with JWKS URL.');
21
+ return null; // Keep discovery validation, including before using cached results.
22
+ }
92
23
  if (options.endpoint === undefined)
93
24
  return null;
94
- const endpoint = stripTrailingSlash(options.endpoint);
95
- const convexUrl = stripTrailingSlash(options.convexUrl ?? gatewayToConvex(endpoint));
96
- const jwksUrl = options.jwksUrl !== undefined ? options.jwksUrl : `${endpoint}${JWKS_PATH}`;
97
- return { endpoint, convexUrl, jwksUrl };
25
+ const endpoint = options.endpoint.replace(/\/$/, '');
26
+ return {
27
+ endpoint,
28
+ convexUrl: (options.convexUrl ?? syncForExplicitEndpoint(endpoint)).replace(/\/$/, ''),
29
+ jwksUrl: options.jwksUrl ?? `${endpoint}/api/jwks.json`,
30
+ };
98
31
  }
99
- /**
100
- * Resolve the three infrastructure URLs for `projectId`.
101
- *
102
- * Idempotent + cache-aware — repeated calls with the same `projectId` reuse
103
- * the `resolveProject` cache (per-process Map server-side, sessionStorage
104
- * browser-side). Safe to call eagerly at module init.
105
- *
106
- * The `resolveProject` round-trip happens only when no explicit endpoint
107
- * override is supplied — `convexUrl` + `jwksUrl` are pure transforms on
108
- * `endpoint`. If `endpoint` is provided (prop or env escape hatch), the
109
- * helper completes without any network call ; gateway failures cannot
110
- * stall the boot path in that case.
111
- *
112
- * Throws (propagates) the `StorystickError` from `resolveProject` when the
113
- * gateway returns 404/503/network error AND no explicit `endpoint` is set.
114
- */
115
32
  export async function resolveInfra(projectId, options = {}) {
116
- // The gateway round-trip is needed only when we don't already know the
117
- // endpoint — convexUrl + jwksUrl are pure transforms on it. Explicit
118
- // endpoint prop alone is enough to skip the round-trip.
119
- let endpointSource = options.endpoint;
120
- if (endpointSource === undefined) {
121
- const config = await resolveProject(projectId, options.gatewayUrl);
122
- endpointSource = config.endpoint;
123
- }
124
- const endpoint = stripTrailingSlash(endpointSource);
125
- const convexUrl = stripTrailingSlash(options.convexUrl ?? gatewayToConvex(endpoint));
126
- const jwksUrl = options.jwksUrl !== undefined
127
- ? options.jwksUrl
128
- : `${endpoint}${JWKS_PATH}`;
129
- return { endpoint, convexUrl, jwksUrl };
33
+ const explicit = resolveInfraSync(options);
34
+ if (explicit)
35
+ return explicit;
36
+ const service = options.service === undefined ? undefined : parseServiceConnection(options.service);
37
+ const gateway = service?.apiOrigin ?? options.gatewayUrl ?? DEFAULT_SERVICE_CONNECTION.apiOrigin;
38
+ const config = await resolveProject(projectId, gateway, service);
39
+ return {
40
+ endpoint: config.endpoint.replace(/\/$/, ''),
41
+ convexUrl: (service?.syncOrigin ?? options.convexUrl ?? config.syncEndpoint ?? syncForExplicitEndpoint(config.endpoint)).replace(/\/$/, ''),
42
+ jwksUrl: options.jwksUrl ?? `${config.endpoint.replace(/\/$/, '')}/api/jwks.json`,
43
+ };
130
44
  }
@@ -1,7 +1,7 @@
1
1
  import { StorystickError } from './errors.js';
2
2
  import { getInternalClientRuntime } from './query-client.js';
3
3
  import { LOCALE_ROUTE_COLLISION } from '@storystick/types/errors/codes/locale-lifecycle';
4
- import { samePublicReadIdentity } from '@storystick/types/public-delivery';
4
+ import { hasUsablePreviewToken } from './preview-scope.js';
5
5
  import { attachPublicRouteIdentity } from './public-delivery.js';
6
6
  export async function publishedLocaleRoutes(client, storyTypes) {
7
7
  if (storyTypes.length === 0)
@@ -11,22 +11,20 @@ export async function publishedLocaleRoutes(client, storyTypes) {
11
11
  const seenCursors = new Set();
12
12
  let cursor = null;
13
13
  let identity;
14
- let witnessed;
14
+ const preview = hasUsablePreviewToken(runtime.requestContext);
15
15
  for (let page = 0; page < 10_000; page += 1) {
16
16
  const response = await runtime.transport.request({
17
17
  udfPath: 'queries:listPublishedLocaleRoutes',
18
- args: { storyTypes: [...storyTypes], cursor, numItems: 500 },
18
+ args: { storyTypes: [...storyTypes], ...(preview ? { cursor, numItems: 500 } : {}) },
19
19
  options: undefined,
20
20
  requestContext: runtime.requestContext,
21
21
  });
22
- if (witnessed !== undefined && (witnessed !== Boolean(response.publicReadIdentity) ||
23
- (identity && response.publicReadIdentity && !samePublicReadIdentity(identity, response.publicReadIdentity))))
24
- throw new StorystickError('The public route inventory changed during pagination.', {
25
- code: 'storystick/QUERY_GENERATION_CHANGED', category: 'system', retryable: true,
26
- });
27
- witnessed = Boolean(response.publicReadIdentity);
28
22
  identity = response.publicReadIdentity;
29
23
  const result = response.data;
24
+ if (!result || !Array.isArray(result.page) || (!preview && (!result.isDone || result.continueCursor !== '' || result.page.length > 10_000)))
25
+ throw new StorystickError('Public route inventory is not a complete bounded snapshot.', {
26
+ code: 'storystick/QUERY_PROTOCOL', category: 'system', retryable: false,
27
+ });
30
28
  routes.push(...result.page.map((route) => ({
31
29
  ...route,
32
30
  seo: route.seo ?? { indexable: true },
@@ -1,3 +1,4 @@
1
+ import { type ServiceConnection } from '@storystick/types/public-endpoints';
1
2
  import type { PreviewReadContext } from '@storystick/types/preview-query-targeting';
2
3
  import type { ClientAuth, DefaultRequestOptions, RequestContext, Transport, PublicTransport } from './types.js';
3
4
  import { type QueryExecutionHost, type QueryForSchema } from './query-builder.js';
@@ -7,6 +8,7 @@ export type ClientOptions<TSchema extends QuerySchemaDefinition> = ClientAuth &
7
8
  readonly schema: TSchema;
8
9
  readonly projectId: string;
9
10
  readonly endpoint?: string;
11
+ readonly service?: ServiceConnection;
10
12
  /** Explicit public Query V2 gateway; control and Preview keep endpoint. */
11
13
  readonly deliveryEndpoint?: string;
12
14
  /** Customer application build identity for generation-paired reads. */
@@ -1,4 +1,4 @@
1
- import { STORYSTICK_GATEWAY_ORIGIN } from '@storystick/types/public-endpoints';
1
+ import { DEFAULT_SERVICE_CONNECTION, parseServiceConnection, assertServiceOrigin } from '@storystick/types/public-endpoints';
2
2
  import { isExactPublicQueryResultV2 } from '@storystick/types/delivery-contract';
3
3
  import { attachPublicReadIdentity } from './public-delivery.js';
4
4
  import { createHttpTransportV2, assertResponseProject, assertProjectMatch, } from './transport.js';
@@ -55,7 +55,6 @@ export function bindClientSchemaToAuthority(authority, schema) {
55
55
  schemas.set(schema, bound);
56
56
  return bound;
57
57
  }
58
- const DEFAULT_GATEWAY_URL = STORYSTICK_GATEWAY_ORIGIN;
59
58
  export function createClient(options) {
60
59
  // An untyped caller cannot opt into internal Preview authority through this entry.
61
60
  return createInternalClient({ ...options, requestContext: undefined });
@@ -64,7 +63,7 @@ export function createInternalClient(options) {
64
63
  const normalized = normalizeClientOptions(options);
65
64
  const sourceTransport = normalized.transport ?? createHttpTransportV2({
66
65
  projectId: normalized.projectId,
67
- endpoint: normalized.endpoint ?? DEFAULT_GATEWAY_URL,
66
+ endpoint: normalized.endpoint ?? normalized.service?.apiOrigin ?? DEFAULT_SERVICE_CONNECTION.apiOrigin,
68
67
  deliveryEndpoint: normalized.deliveryEndpoint,
69
68
  apiKey: normalized.apiKey ?? normalized.publishableKey,
70
69
  applicationBuildId: normalized.applicationBuildId,
@@ -73,6 +72,14 @@ export function createInternalClient(options) {
73
72
  }
74
73
  function normalizeClientOptions(options) {
75
74
  validateSchema(options.schema);
75
+ if (options.service !== undefined) {
76
+ const service = parseServiceConnection(options.service);
77
+ assertServiceOrigin(options.endpoint, service.apiOrigin);
78
+ assertServiceOrigin(options.deliveryEndpoint, service.apiOrigin);
79
+ if (options.transport !== undefined)
80
+ throw new TypeError('A service-bound client cannot override its transport.');
81
+ options = { ...options, service };
82
+ }
76
83
  if (options.localeRouting?.publicOrigins) {
77
84
  for (const locale of options.localeRouting.locales) {
78
85
  if (locale.enabled && !options.localeRouting.publicOrigins[locale.code]) {
@@ -122,7 +129,7 @@ function createClientWithTransport(options, sourceTransport) {
122
129
  kind,
123
130
  cacheKey: createPreviewProvenanceReadCacheKey(kind, {
124
131
  projectId: options.projectId,
125
- endpoint: options.endpoint ?? DEFAULT_GATEWAY_URL,
132
+ endpoint: options.endpoint ?? options.service?.apiOrigin ?? DEFAULT_SERVICE_CONNECTION.apiOrigin,
126
133
  authority: previewReadCacheAuthority(options.requestContext),
127
134
  query: canonical,
128
135
  options: requestOptions,
@@ -42,11 +42,14 @@ export async function resolveStorystickPage(client, input) {
42
42
  }
43
43
  const canonical = normalizePathname(input.pathname);
44
44
  const runtime = getInternalClientRuntime(client);
45
+ const publicOrigins = input.publicOrigins ?? runtime.localeRouting?.publicOrigins;
45
46
  // Dispatch a single cross-storytype call via the configured client's
46
47
  // transport. We don't go through a generated story query because this helper
47
48
  // isn't bound to a single storytype — the backend resolves any URL-routable
48
49
  // type that matches the canonical pathname (ADR-094 §1.bis).
49
50
  const args = { pathname: canonical, ...(input.locale ? { locale: input.locale } : {}) };
51
+ if (input.dataQueries !== undefined && !hasUsablePreviewToken(runtime.requestContext))
52
+ args.data = input.dataQueries;
50
53
  if (input.storyTypes && input.storyTypes.length > 0) {
51
54
  args.storyTypes = [...input.storyTypes];
52
55
  }
@@ -55,7 +58,8 @@ export async function resolveStorystickPage(client, input) {
55
58
  cacheKey: createPreviewProvenanceReadCacheKey('resolved-route', {
56
59
  pathname: canonical,
57
60
  locale: input.locale,
58
- publicOrigins: runtime.localeRouting?.publicOrigins,
61
+ publicOrigins,
62
+ dataQueries: input.dataQueries,
59
63
  storyTypes: input.storyTypes ? [...input.storyTypes].sort() : undefined,
60
64
  }),
61
65
  executeRaw: async () => {
@@ -72,17 +76,21 @@ export async function resolveStorystickPage(client, input) {
72
76
  if ('notFound' in data) {
73
77
  return {
74
78
  type: 'notFound',
75
- ...(data.localeContext ? { localeContext: siteLocaleContext(data.localeContext, runtime.localeRouting?.publicOrigins) } : {}),
79
+ ...(data.localeContext ? { localeContext: siteLocaleContext(data.localeContext, publicOrigins) } : {}),
76
80
  };
77
81
  }
78
82
  if ('redirectTo' in data) {
79
83
  let redirectTo = data.redirectTo;
80
- if (runtime.localeRouting?.publicOrigins && redirectTo.startsWith('/') && !redirectTo.startsWith('//')) {
81
- const resolved = resolveLocalePathname(redirectTo, runtime.localeRouting);
84
+ if (publicOrigins && redirectTo.startsWith('/') && !redirectTo.startsWith('//')) {
85
+ const settings = data.localeSettings ?? runtime.localeRouting;
86
+ if (!settings)
87
+ throw new TypeError('Published redirect is missing its locale settings.');
88
+ const routing = { ...settings, publicOrigins };
89
+ const resolved = resolveLocalePathname(redirectTo, routing);
82
90
  if (!resolved.ok)
83
91
  throw new TypeError('Invalid published redirect locale.');
84
92
  const suffix = redirectTo.match(/[?#].*$/)?.[0] ?? '';
85
- redirectTo = publicHrefForLocale(resolved.pathname, resolved.locale, runtime.localeRouting) + suffix;
93
+ redirectTo = publicHrefForLocale(resolved.pathname, resolved.locale, routing) + suffix;
86
94
  }
87
95
  return {
88
96
  type: 'redirect',
@@ -101,10 +109,23 @@ export async function resolveStorystickPage(client, input) {
101
109
  ...previewAssetDependenciesFromValue(data.document),
102
110
  ]);
103
111
  }
104
- const localeContext = siteLocaleContext(data.localeContext, runtime.localeRouting?.publicOrigins);
112
+ const localeContext = siteLocaleContext(data.localeContext, publicOrigins);
105
113
  attachDocumentLocaleRouting(data.document, localeContext);
106
- if (!hasUsablePreviewToken(runtime.requestContext))
114
+ if (!hasUsablePreviewToken(runtime.requestContext)) {
107
115
  attachPublicRouteIdentity(data.document, response.publicReadIdentity);
116
+ if (input.dataQueries !== undefined) {
117
+ if (!data.data || Object.keys(data.data).length !== Object.keys(input.dataQueries).length ||
118
+ !Object.keys(input.dataQueries).every(key => Object.hasOwn(data.data, key) && Array.isArray(data.data[key])))
119
+ throw new TypeError('The public route is missing its composed page data.');
120
+ attachPublicRouteIdentity(data.data, response.publicReadIdentity);
121
+ for (const rows of Object.values(data.data)) {
122
+ attachDocumentLocaleRouting(rows, localeContext);
123
+ attachPublicRouteIdentity(rows, response.publicReadIdentity);
124
+ for (const row of rows)
125
+ attachPublicRouteIdentity(row, response.publicReadIdentity);
126
+ }
127
+ }
128
+ }
108
129
  return {
109
130
  type: 'document',
110
131
  document: data.document,
@@ -115,6 +136,7 @@ export async function resolveStorystickPage(client, input) {
115
136
  primaryLocale: data.primaryLocale,
116
137
  alternates: data.alternates,
117
138
  seo: data.seo ?? { indexable: true },
139
+ ...(data.data ? { data: data.data } : {}),
118
140
  };
119
141
  },
120
142
  });
package/dist/resolve.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type ServiceConnection } from '@storystick/types/public-endpoints';
1
2
  /**
2
3
  * Project shortId resolution
3
4
  *
@@ -24,6 +25,7 @@ export interface ProjectConfig {
24
25
  /** Storystick gateway endpoint.
25
26
  * Same URL for every project on this Storystick deployment. */
26
27
  readonly endpoint: string;
28
+ readonly syncEndpoint?: string;
27
29
  /** Public project identifier — the 8-char Crockford shortId that
28
30
  * appears in URLs, SDK env config, API key prefixes, logs. */
29
31
  readonly projectId: string;
@@ -40,4 +42,4 @@ export interface ProjectConfig {
40
42
  * const config = await resolveProject('a3k9m2x7')
41
43
  * // → { endpoint: 'https://...', projectId: 'a3k9m2x7', plan: 'free', ... }
42
44
  */
43
- export declare function resolveProject(projectId: string, gatewayUrl?: string): Promise<ProjectConfig>;
45
+ export declare function resolveProject(projectId: string, gatewayUrl?: string, selectedService?: ServiceConnection): Promise<ProjectConfig>;
package/dist/resolve.js CHANGED
@@ -1,9 +1,9 @@
1
- import { STORYSTICK_GATEWAY_ORIGIN } from '@storystick/types/public-endpoints';
1
+ import { STORYSTICK_GATEWAY_ORIGIN, DEFAULT_SERVICE_CONNECTION, parseServiceConnection, assertServiceOrigin } from '@storystick/types/public-endpoints';
2
2
  // ─────────────────────────────────────────────
3
3
  // Constants
4
4
  // ─────────────────────────────────────────────
5
5
  const DEFAULT_GATEWAY_URL = STORYSTICK_GATEWAY_ORIGIN;
6
- const PROJECT_CACHE_PREFIX = 'storystick:project:v1:';
6
+ const PROJECT_CACHE_PREFIX = 'storystick:project:v2:';
7
7
  const PROJECT_CACHE_TTL_MS = 5 * 60 * 1000;
8
8
  // Module-level cache for server-side (bounded and refreshed after five minutes)
9
9
  const PROJECT_CACHE_MAX_ENTRIES = 128;
@@ -21,8 +21,19 @@ const inFlight = new Map();
21
21
  * const config = await resolveProject('a3k9m2x7')
22
22
  * // → { endpoint: 'https://...', projectId: 'a3k9m2x7', plan: 'free', ... }
23
23
  */
24
- export async function resolveProject(projectId, gatewayUrl) {
25
- const gateway = gatewayUrl ?? DEFAULT_GATEWAY_URL;
24
+ export async function resolveProject(projectId, gatewayUrl, selectedService) {
25
+ const service = selectedService === undefined
26
+ ? (gatewayUrl === undefined || gatewayUrl === DEFAULT_GATEWAY_URL ? DEFAULT_SERVICE_CONNECTION : undefined)
27
+ : parseServiceConnection(selectedService);
28
+ if (service)
29
+ assertServiceOrigin(gatewayUrl, service.apiOrigin);
30
+ const gateway = gatewayUrl ?? service?.apiOrigin ?? DEFAULT_GATEWAY_URL;
31
+ const checked = (config) => {
32
+ if (service && (config.endpoint !== service.apiOrigin || config.syncEndpoint !== service.syncOrigin)) {
33
+ throw new Error('StorystickError: Project discovery returned an unexpected service origin.');
34
+ }
35
+ return config;
36
+ };
26
37
  // ADR-131 C9 codex R3 P2 fix : the cache key must include the gateway
27
38
  // URL so that a self-host customer passing a non-default `gatewayUrl`
28
39
  // does not get the default-gateway-resolved config back from the cache.
@@ -31,25 +42,25 @@ export async function resolveProject(projectId, gatewayUrl) {
31
42
  const cacheKey = `${projectId}::${gateway}`;
32
43
  const cached = getFromCache(cacheKey, projectId);
33
44
  if (cached)
34
- return cached;
45
+ return checked(cached);
35
46
  const pending = inFlight.get(cacheKey);
36
47
  if (pending)
37
- return pending;
38
- const request = fetchProject(projectId, gateway, cacheKey);
48
+ return checked(await pending);
49
+ const request = fetchProject(projectId, gateway, cacheKey, checked);
39
50
  // Bound bookkeeping even when a discovery endpoint is unavailable.
40
51
  if (inFlight.size < PROJECT_CACHE_MAX_ENTRIES)
41
52
  inFlight.set(cacheKey, request);
42
53
  try {
43
- return await request;
54
+ return checked(await request);
44
55
  }
45
56
  finally {
46
57
  if (inFlight.get(cacheKey) === request)
47
58
  inFlight.delete(cacheKey);
48
59
  }
49
60
  }
50
- async function fetchProject(projectId, gateway, cacheKey) {
61
+ async function fetchProject(projectId, gateway, cacheKey, checked) {
51
62
  const url = `${gateway}/api/projects/${encodeURIComponent(projectId)}/config`;
52
- const response = await fetch(url);
63
+ const response = await fetch(url, { redirect: 'error' });
53
64
  if (!response.ok) {
54
65
  if (response.status === 404) {
55
66
  const body = await response.json().catch(() => ({}));
@@ -64,15 +75,13 @@ async function fetchProject(projectId, gateway, cacheKey) {
64
75
  }
65
76
  throw new Error(`StorystickError: Failed to resolve project "${projectId}" (HTTP ${response.status})`);
66
77
  }
67
- // Gateway returns { endpoint, projectId: <convex _id>, name, shortId,
68
- // urlLabel, plan, features }. Post-Wave-2 the SDK treats the shortId
69
- // as the public projectId; the Convex `_id` stays hidden inside the
70
- // gateway (used only for JWT minting + internal FK integrity).
78
+ // The shortId is the public project identity; deployment IDs are not needed.
71
79
  const raw = await response.json();
72
80
  if (!isRecord(raw))
73
81
  throw new Error('StorystickError: Invalid project discovery response.');
74
82
  const config = {
75
83
  endpoint: raw.endpoint,
84
+ ...(typeof raw.syncEndpoint === 'string' ? { syncEndpoint: raw.syncEndpoint } : {}),
76
85
  projectId: raw.shortId,
77
86
  name: raw.name,
78
87
  plan: raw.plan,
@@ -81,6 +90,7 @@ async function fetchProject(projectId, gateway, cacheKey) {
81
90
  if (!isProjectConfig(config, projectId)) {
82
91
  throw new Error('StorystickError: Invalid project discovery response.');
83
92
  }
93
+ checked(config);
84
94
  Object.freeze(config.features);
85
95
  Object.freeze(config);
86
96
  // Store in cache (keyed by projectId + gateway URL — see cacheKey above)
package/dist/transport.js CHANGED
@@ -55,7 +55,8 @@ export function createHttpTransportV2(opts) {
55
55
  async function request(input) {
56
56
  assertProjectMatch(input.expectedProjectId ?? opts.projectId, opts.projectId);
57
57
  const { udfPath, args, options, requestContext, signal: signalArg } = input;
58
- const { method, path } = endpointForUdf(udfPath);
58
+ const { method: endpointMethod, path } = endpointForUdf(udfPath);
59
+ const method = udfPath === 'queries:getRouteByPathname' && args.data !== undefined ? 'POST' : endpointMethod;
59
60
  // Use the shared `hasUsablePreviewToken` predicate so the builder's
60
61
  // `assertPreviewIntent` guard and this preview-path switch agree on
61
62
  // what counts as "bound": a non-empty string. `previewToken: ''`
@@ -69,7 +70,7 @@ export function createHttpTransportV2(opts) {
69
70
  ? opts.deliveryEndpoint : endpoint;
70
71
  const url = buildUrl({ endpoint: readEndpoint, path, method, args, options, isPreview });
71
72
  const body = method === 'POST'
72
- ? buildPostBody(args, options, isPreview, udfPath !== 'queries:queryV2')
73
+ ? buildPostBody(args, options, isPreview, udfPath !== 'queries:queryV2' && udfPath !== 'queries:getRouteByPathname')
73
74
  : undefined;
74
75
  const signal = signalArg ?? options?.signal;
75
76
  const fetchInit = buildFetchInit({
@@ -140,7 +141,7 @@ export function createHttpTransportV2(opts) {
140
141
  }
141
142
  }
142
143
  let publicReadIdentity;
143
- if (!isPreview && ['queries:queryV2', 'queries:getRouteByPathname', 'queries:listPublishedLocaleRoutes'].includes(input.udfPath) && response.headers.has(PUBLIC_DELIVERY_IDENTITY_HEADER)) {
144
+ if (!isPreview && ['queries:queryV2', 'queries:getRouteByPathname', 'queries:listPublishedLocaleRoutes', 'locales:get'].includes(input.udfPath) && response.headers.has(PUBLIC_DELIVERY_IDENTITY_HEADER)) {
144
145
  let value = null;
145
146
  try {
146
147
  value = JSON.parse(response.headers.get(PUBLIC_DELIVERY_IDENTITY_HEADER));
@@ -211,7 +212,7 @@ async function fetchTransportResponse(fetchFn, url, init) {
211
212
  }
212
213
  }
213
214
  function queryResponseMetadata(udfPath, response) {
214
- if (udfPath !== 'queries:queryV2')
215
+ if (udfPath !== 'queries:queryV2' && udfPath !== 'queries:getRouteByPathname')
215
216
  return {};
216
217
  const queryHash = response.headers.get('X-Storystick-Query-Hash');
217
218
  const readScopeIdentity = response.headers.get('X-Storystick-Read-Scope-Identity');
package/dist/types.d.ts CHANGED
@@ -25,6 +25,7 @@ export type ResolvedRoute = {
25
25
  primaryLocale: string;
26
26
  alternates: Readonly<Record<string, string>>;
27
27
  seo: PublicationSeo;
28
+ data?: Record<string, QueryResult[]>;
28
29
  } | {
29
30
  type: 'redirect';
30
31
  redirectTo: string;
@@ -53,6 +54,8 @@ export interface QueryResult extends DeliveryDocumentV1 {
53
54
  resolved?: Record<string, QueryResult | QueryResult[] | null>;
54
55
  }
55
56
  export interface ResolveRouteInput {
57
+ publicOrigins?: import('./locale-routing.js').PublicLocaleOrigins;
58
+ dataQueries?: import('@storystick/types/delivery-contract').PublicRouteDataQueries;
56
59
  /** Explicit locale: pathname is canonical and unprefixed (domain deployments). */
57
60
  locale?: string;
58
61
  pathname: string | string[] | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storystick/client",
3
- "version": "0.2.0-rc.1",
3
+ "version": "0.2.0-rc.3",
4
4
  "license": "FSL-1.1-MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -43,8 +43,8 @@
43
43
  "tag": "beta"
44
44
  },
45
45
  "dependencies": {
46
- "@storystick/media": "0.2.0-rc.1",
47
- "@storystick/types": "0.1.0-rc.1"
46
+ "@storystick/media": "0.2.0-rc.3",
47
+ "@storystick/types": "0.1.0-rc.3"
48
48
  },
49
49
  "devDependencies": {
50
50
  "typescript": "^5.8.2",
@@ -52,7 +52,7 @@
52
52
  "@types/node": "^22.13.10"
53
53
  },
54
54
  "engines": {
55
- "node": ">=24.19.0 <25"
55
+ "node": "^22.13.0 || ^24.19.0"
56
56
  },
57
57
  "repository": {
58
58
  "type": "git",