@storystick/client 0.0.0-stage → 0.2.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +112 -0
- package/PUBLIC-API.md +22 -0
- package/README.md +180 -2
- package/dist/.source-hash +1 -0
- package/dist/_fetchers.d.ts +51 -0
- package/dist/_fetchers.js +144 -0
- package/dist/_stateMachine.d.ts +102 -0
- package/dist/_stateMachine.js +168 -0
- package/dist/_wireAuth.d.ts +48 -0
- package/dist/_wireAuth.js +52 -0
- package/dist/adapter.d.ts +14 -0
- package/dist/adapter.js +10 -0
- package/dist/content-values.d.ts +11 -0
- package/dist/content-values.js +401 -0
- package/dist/errors.d.ts +65 -0
- package/dist/errors.js +45 -0
- package/dist/hydrate-slice.d.ts +2 -0
- package/dist/hydrate-slice.js +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +9 -0
- package/dist/infra-resolver.d.ts +94 -0
- package/dist/infra-resolver.js +130 -0
- package/dist/internal.d.ts +33 -0
- package/dist/internal.js +20 -0
- package/dist/locale-routing.d.ts +5 -0
- package/dist/locale-routing.js +33 -0
- package/dist/normalize-pathname.d.ts +79 -0
- package/dist/normalize-pathname.js +103 -0
- package/dist/preview-frame-dependencies.d.ts +39 -0
- package/dist/preview-frame-dependencies.js +84 -0
- package/dist/preview-query-receipt.d.ts +3 -0
- package/dist/preview-query-receipt.js +16 -0
- package/dist/preview-read-lifecycle.d.ts +10 -0
- package/dist/preview-read-lifecycle.js +40 -0
- package/dist/preview-read-observation.d.ts +18 -0
- package/dist/preview-read-observation.js +81 -0
- package/dist/preview-scope.d.ts +3 -0
- package/dist/preview-scope.js +22 -0
- package/dist/preview-target.d.ts +73 -0
- package/dist/preview-target.js +86 -0
- package/dist/project-locales.d.ts +4 -0
- package/dist/project-locales.js +12 -0
- package/dist/public-delivery.d.ts +36 -0
- package/dist/public-delivery.js +55 -0
- package/dist/published-routes.d.ts +3 -0
- package/dist/published-routes.js +100 -0
- package/dist/query-builder.d.ts +225 -0
- package/dist/query-builder.js +294 -0
- package/dist/query-client.d.ts +54 -0
- package/dist/query-client.js +306 -0
- package/dist/query-compiler.d.ts +5 -0
- package/dist/query-compiler.js +12 -0
- package/dist/query-schema.d.ts +32 -0
- package/dist/query-schema.js +1 -0
- package/dist/redirect-search.d.ts +4 -0
- package/dist/redirect-search.js +14 -0
- package/dist/reference-resolver.d.ts +37 -0
- package/dist/reference-resolver.js +126 -0
- package/dist/resolve-route.d.ts +27 -0
- package/dist/resolve-route.js +145 -0
- package/dist/resolve.d.ts +43 -0
- package/dist/resolve.js +160 -0
- package/dist/schemas.d.ts +71 -0
- package/dist/schemas.js +75 -0
- package/dist/seo.d.ts +52 -0
- package/dist/seo.js +93 -0
- package/dist/signed-webhook.d.ts +13 -0
- package/dist/signed-webhook.js +54 -0
- package/dist/transport.d.ts +29 -0
- package/dist/transport.js +584 -0
- package/dist/typed-route.d.ts +22 -0
- package/dist/typed-route.js +1 -0
- package/dist/types.d.ts +147 -0
- package/dist/types.js +1 -0
- package/package.json +70 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# Functional Source License, Version 1.1, MIT Future License
|
|
2
|
+
|
|
3
|
+
## Abbreviation
|
|
4
|
+
|
|
5
|
+
FSL-1.1-MIT
|
|
6
|
+
|
|
7
|
+
## Notice
|
|
8
|
+
|
|
9
|
+
Copyright 2026 Tanguy Freycon
|
|
10
|
+
|
|
11
|
+
## Terms and Conditions
|
|
12
|
+
|
|
13
|
+
### Licensor ("We")
|
|
14
|
+
|
|
15
|
+
The party offering the Software under these Terms and Conditions.
|
|
16
|
+
|
|
17
|
+
### The Software
|
|
18
|
+
|
|
19
|
+
The "Software" is each version of the software that we make available under
|
|
20
|
+
these Terms and Conditions, as indicated by our inclusion of these Terms and
|
|
21
|
+
Conditions with the Software.
|
|
22
|
+
|
|
23
|
+
### License Grant
|
|
24
|
+
|
|
25
|
+
Subject to your compliance with this License Grant and the Patents,
|
|
26
|
+
Redistribution and Trademark clauses below, we hereby grant you the right to
|
|
27
|
+
use, copy, modify, create derivative works, publicly perform, publicly display
|
|
28
|
+
and redistribute the Software for any Permitted Purpose identified below.
|
|
29
|
+
|
|
30
|
+
### Permitted Purpose
|
|
31
|
+
|
|
32
|
+
A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
|
|
33
|
+
means making the Software available to others in a commercial product or
|
|
34
|
+
service that:
|
|
35
|
+
|
|
36
|
+
1. substitutes for the Software;
|
|
37
|
+
|
|
38
|
+
2. substitutes for any other product or service we offer using the Software
|
|
39
|
+
that exists as of the date we make the Software available; or
|
|
40
|
+
|
|
41
|
+
3. offers the same or substantially similar functionality as the Software.
|
|
42
|
+
|
|
43
|
+
Permitted Purposes specifically include using the Software:
|
|
44
|
+
|
|
45
|
+
1. for your internal use and access;
|
|
46
|
+
|
|
47
|
+
2. for non-commercial education;
|
|
48
|
+
|
|
49
|
+
3. for non-commercial research; and
|
|
50
|
+
|
|
51
|
+
4. in connection with professional services that you provide to a licensee
|
|
52
|
+
using the Software in accordance with these Terms and Conditions.
|
|
53
|
+
|
|
54
|
+
### Patents
|
|
55
|
+
|
|
56
|
+
To the extent your use for a Permitted Purpose would necessarily infringe our
|
|
57
|
+
patents, the license grant above includes a license under our patents. If you
|
|
58
|
+
make a claim against any party that the Software infringes or contributes to
|
|
59
|
+
the infringement of any patent, then your patent license to the Software ends
|
|
60
|
+
immediately.
|
|
61
|
+
|
|
62
|
+
### Redistribution
|
|
63
|
+
|
|
64
|
+
The Terms and Conditions apply to all copies, modifications and derivatives of
|
|
65
|
+
the Software.
|
|
66
|
+
|
|
67
|
+
If you redistribute any copies, modifications or derivatives of the Software,
|
|
68
|
+
you must include a copy of or a link to these Terms and Conditions and not
|
|
69
|
+
remove any copyright notices provided in or with the Software.
|
|
70
|
+
|
|
71
|
+
### Disclaimer
|
|
72
|
+
|
|
73
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
|
|
74
|
+
IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
|
|
75
|
+
PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
|
|
76
|
+
|
|
77
|
+
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
|
|
78
|
+
SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
|
|
79
|
+
EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
|
|
80
|
+
|
|
81
|
+
### Trademarks
|
|
82
|
+
|
|
83
|
+
Except for displaying the License Details and identifying us as the origin of
|
|
84
|
+
the Software, you have no right under these Terms and Conditions to use our
|
|
85
|
+
trademarks, trade names, service marks or product names.
|
|
86
|
+
|
|
87
|
+
## Grant of Future License
|
|
88
|
+
|
|
89
|
+
We hereby irrevocably grant you an additional license to use the Software under
|
|
90
|
+
the MIT license that is effective on the second anniversary of the date we make
|
|
91
|
+
the Software available. On or after that date, you may use the Software under
|
|
92
|
+
the MIT license, in which case the following will apply:
|
|
93
|
+
|
|
94
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
95
|
+
this software and associated documentation files (the "Software"), to deal in
|
|
96
|
+
the Software without restriction, including without limitation the rights to
|
|
97
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
|
98
|
+
of the Software, and to permit persons to whom the Software is furnished to do
|
|
99
|
+
so, subject to the following conditions:
|
|
100
|
+
|
|
101
|
+
The above copyright notice and this permission notice shall be included in all
|
|
102
|
+
copies or substantial portions of the Software.
|
|
103
|
+
|
|
104
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
105
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
106
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
107
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
108
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
109
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
110
|
+
SOFTWARE.
|
|
111
|
+
|
|
112
|
+
This Agreement shall be governed by the laws of France.
|
package/PUBLIC-API.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# @storystick/client API contract
|
|
2
|
+
|
|
3
|
+
Install this candidate explicitly with `@storystick/client@0.2.0-rc.0` after registry bootstrap and publication. This repository alone does not make the candidate or beta channel available on npm.
|
|
4
|
+
|
|
5
|
+
Version 0.2.0-rc.0, cohort `sdk-0.2.0-rc.0`. ESM distribution; no CommonJS or universal Edge compatibility is promised.
|
|
6
|
+
|
|
7
|
+
This package is a product integration facade. Reserved contracts are required between SDK packages and must be upgraded with the same cohort. Their public export paths do not promise independent stability.
|
|
8
|
+
|
|
9
|
+
| Entry | Status |
|
|
10
|
+
| --- | --- |
|
|
11
|
+
| `.` | Supported beta entry |
|
|
12
|
+
| `./internal` | Reserved SDK contract |
|
|
13
|
+
| `./normalize-pathname` | Supported beta entry |
|
|
14
|
+
| `./locale-routing` | Supported beta entry |
|
|
15
|
+
| `./adapter` | Reserved SDK contract |
|
|
16
|
+
| `./seo` | Supported beta entry |
|
|
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.
|
|
19
|
+
|
|
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
|
+
|
|
22
|
+
The repository is private. Public package availability does not make the monorepo public, and npm provenance from that repository is unavailable. Product and pilot support: [Storystick](https://storystick.app).
|
package/README.md
CHANGED
|
@@ -1,3 +1,181 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @storystick/client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The generated, typed Query V2 client and universal Content Plane transport.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pnpm add @storystick/client@beta
|
|
7
|
+
pnpm add -D @storystick/cli@beta
|
|
8
|
+
pnpm storystick generate
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { createClient } from '@storystick/client'
|
|
13
|
+
import { querySchema } from '@/generated/storystick/query'
|
|
14
|
+
|
|
15
|
+
const client = createClient({
|
|
16
|
+
schema: querySchema,
|
|
17
|
+
projectId: process.env.STORYSTICK_PROJECT_ID!,
|
|
18
|
+
apiKey: process.env.STORYSTICK_API_KEY!,
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
const posts = await client.query('blogPost')
|
|
22
|
+
.select({ title: true, slug: true })
|
|
23
|
+
.page({ first: 20 })
|
|
24
|
+
.fetch()
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`.fetch()` returns exact data and throws `QueryExecutionError` for degraded or
|
|
28
|
+
blocked results. Missing addressed documents return `null`; empty collection
|
|
29
|
+
pages return `[]`. Use `.execute()` when you need the full envelope, pagination
|
|
30
|
+
cursor or diagnostics, and inspect `exactness` before using its data.
|
|
31
|
+
|
|
32
|
+
## Publication languages in collections
|
|
33
|
+
|
|
34
|
+
In public queries, `.locale('fr')` includes only documents with an active French
|
|
35
|
+
publication. To allow another published language for this collection, opt in:
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
const result = await client.query('blogPost')
|
|
39
|
+
.select({ title: true })
|
|
40
|
+
.locale('fr')
|
|
41
|
+
.publicationFallback('configured')
|
|
42
|
+
.page({ first: 20 })
|
|
43
|
+
.execute()
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The server chooses one publication per document: French first, then the project's
|
|
47
|
+
configured fallback languages. It applies content filters and sorting to that
|
|
48
|
+
chosen publication before counting and paginating. It never substitutes a draft.
|
|
49
|
+
`result.pageInfo.totalCount` gives the exact matching count before pagination
|
|
50
|
+
when available; blocked results omit it. `result.meta.locale.requested` keeps the
|
|
51
|
+
requested language and each document's `_locale.code` identifies its actual
|
|
52
|
+
publication language.
|
|
53
|
+
|
|
54
|
+
Omitting `.publicationFallback(...)` or passing `'none'` keeps the default local
|
|
55
|
+
selection. This choice is separate from field inheritance inside a publication.
|
|
56
|
+
It applies only to public collections; addressed reads and authorized Preview
|
|
57
|
+
continue to use their existing read scopes. Preview does not use publication
|
|
58
|
+
fallback to fill gaps in the working content.
|
|
59
|
+
|
|
60
|
+
Publication changes or a different collection policy invalidate an existing
|
|
61
|
+
cursor. Restart from the first page after `QUERY_CURSOR_INVALID`; do not merge
|
|
62
|
+
pages from different publication states. This option does not create translated
|
|
63
|
+
routes or change link resolution.
|
|
64
|
+
|
|
65
|
+
Update the backend and SDK together: the closed Query V2 response now includes
|
|
66
|
+
`totalCount` on computed collection pages, which older SDK validators reject.
|
|
67
|
+
|
|
68
|
+
The client is framework-neutral and can run in Node, browser loaders or other
|
|
69
|
+
server frameworks. Use a server API key only on the server; use a publishable
|
|
70
|
+
key for public browser reads. Preview request authority is supplied by the
|
|
71
|
+
framework's authorized request adapter, not by a document or URL parameter.
|
|
72
|
+
|
|
73
|
+
The generated story definition is carried all the way to the result. A
|
|
74
|
+
`selectAll()` document has the exact generated document fields; a narrowed
|
|
75
|
+
`select(...)` result exposes only the selected fields, with the same optionality
|
|
76
|
+
as the Story contract. No result cast is required.
|
|
77
|
+
|
|
78
|
+
Reference values remain document IDs in ordinary fields. Resolve them against
|
|
79
|
+
the delivery sidecar when a renderer needs a target address:
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { resolveReference, resolveReferences } from '@storystick/client'
|
|
83
|
+
|
|
84
|
+
const author = resolveReference(querySchema, 'author', post.fields.author, {
|
|
85
|
+
source: post,
|
|
86
|
+
path: 'author',
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
if (author.status === 'ok') {
|
|
90
|
+
console.log(author.document.resolvedPathname)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const related = resolveReferences(
|
|
94
|
+
querySchema,
|
|
95
|
+
'blogPost',
|
|
96
|
+
post.fields.relatedPosts,
|
|
97
|
+
{ source: post, path: 'relatedPosts' },
|
|
98
|
+
)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Both helpers return one discriminated outcome per input (`ok`, `empty`,
|
|
102
|
+
`missing`, `archived`, `unpublished`, `no-sidecar`, `wrong-type`, or
|
|
103
|
+
`ambiguous`, plus `pinnedSnapshotMissing` and `pinnedSnapshotMismatch`). Array
|
|
104
|
+
resolution preserves order. The generated schema fixes the target document
|
|
105
|
+
type, so an `ok` result is typed without an application-owned lookup table.
|
|
106
|
+
|
|
107
|
+
`PathnameValue` describes the structured editorial pathname field. Use the
|
|
108
|
+
separate `resolvedPathname` delivery-envelope string for routing. `safeHref()`
|
|
109
|
+
is the fail-closed URL boundary for app-owned anchors; it accepts relative URLs
|
|
110
|
+
and `http`, `https`, `mailto`, and `tel`, and rejects unsafe protocols.
|
|
111
|
+
|
|
112
|
+
`storystick generate` writes `generated/storystick/query.ts` (alongside the
|
|
113
|
+
other generated Storystick files). The `@/generated/storystick/query` import
|
|
114
|
+
above assumes the standard `@/*` project alias; use the equivalent relative
|
|
115
|
+
path if your project does not define it.
|
|
116
|
+
|
|
117
|
+
The generated schema controls story names, selections, filters, sorting and
|
|
118
|
+
addressing at compile time and is validated again at runtime.
|
|
119
|
+
|
|
120
|
+
Reusable selections are ordinary generated TypeScript values. They preserve
|
|
121
|
+
their exact result type without introducing another query language:
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
import { defineSelection } from '@/generated/storystick/query'
|
|
125
|
+
|
|
126
|
+
export const postCard = defineSelection('blogPost', {
|
|
127
|
+
title: true,
|
|
128
|
+
slug: true,
|
|
129
|
+
coverImage: true,
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
const posts = await client.query('blogPost').select(postCard).fetch()
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
The generated query definition is self-contained and has no runtime import from
|
|
136
|
+
this package. Framework adapters can therefore own compatible client versions
|
|
137
|
+
without making their internal package graph part of application setup.
|
|
138
|
+
|
|
139
|
+
Licensed under [FSL-1.1-MIT](./LICENSE).
|
|
140
|
+
|
|
141
|
+
`resolveReference` resolves address/identity metadata from a sidecar. It does not
|
|
142
|
+
promise the target's fields. Use `query(...).select({ relation: { resolve: ... } })`
|
|
143
|
+
or an explicit target query to read typed content.
|
|
144
|
+
|
|
145
|
+
The HTTP transport reserves status 200 for exact results. Non-exact Query V2
|
|
146
|
+
results use 503 when retryable or 422 otherwise, with `private, no-store`, so
|
|
147
|
+
native fetch caches do not retain them. `.execute()` still returns their full
|
|
148
|
+
envelope; `.fetch()` throws `QueryExecutionError`. Preview always bypasses the
|
|
149
|
+
persistent fetch cache. A subsequent read can recover without clearing caches.
|
|
150
|
+
|
|
151
|
+
## Read representation
|
|
152
|
+
|
|
153
|
+
Query V2 keeps the same selection syntax. Selecting a composition also loads its
|
|
154
|
+
bounded rendering dependencies (bindings, model fields and mapped zones).
|
|
155
|
+
Unselected host fields stay absent from `fields`; they are carried in the
|
|
156
|
+
internal versioned render plan. Scalar-only reads do not expand compositions.
|
|
157
|
+
|
|
158
|
+
SDK content objects carry JSON-safe `__ssContent` metadata, so they can be moved,
|
|
159
|
+
filtered or sent to a client component without passing their owning document as
|
|
160
|
+
technical context. Richtext reads return a ProseMirror `doc` object. Authored
|
|
161
|
+
storage remains serialized; do not write SDK rendering metadata into content.
|
|
162
|
+
|
|
163
|
+
An incompatible backend without the render plan fails with
|
|
164
|
+
`storystick/CONTENT_PROTOCOL`. Upgrade backend and SDK together and let the
|
|
165
|
+
Content Plane reconcile its projection; do not republish user documents to
|
|
166
|
+
repair an old projection. This pre-launch contract has no legacy fallback.
|
|
167
|
+
|
|
168
|
+
## Adapter boundaries
|
|
169
|
+
|
|
170
|
+
Application code uses the root content API above. Framework infrastructure such
|
|
171
|
+
as HTTP transport construction, project discovery and route resolution lives at
|
|
172
|
+
`@storystick/client/adapter`. Studio-only target resolution remains on the
|
|
173
|
+
existing internal entry. Those boundaries are for Storystick adapters and
|
|
174
|
+
tooling. They are intentionally absent from the root API so ordinary content
|
|
175
|
+
code does not inherit deployment or Studio concepts.
|
|
176
|
+
|
|
177
|
+
## Candidate distribution contract
|
|
178
|
+
|
|
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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
e9b1f5ad508349c6004d7e10c0272e3d09bbce936e2556b3c8e7d474d778c994
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Token fetchers — two origins, one result shape (ADR-045 §4, §11.1).
|
|
3
|
+
*
|
|
4
|
+
* - `apiKeyFetcher({ gatewayUrl, apiKey })` — explicit machine delegation.
|
|
5
|
+
* Calls `POST /api/tokens/issue` with Bearer <apiKey>. Used by mutation/import
|
|
6
|
+
* consumers. Ordinary HTTP reads authenticate directly in `transport.ts`.
|
|
7
|
+
*
|
|
8
|
+
* - `userSessionFetcher({ gatewayUrl, getSessionToken, projectId })` —
|
|
9
|
+
* Studio flow. Calls `POST /api/tokens/issue-for-user` with the caller's
|
|
10
|
+
* Convex Auth session token + the target projectId in the body.
|
|
11
|
+
*
|
|
12
|
+
* Both produce `{ token, expiresAt }` consumed by the state machine.
|
|
13
|
+
* Both attach the §11.5 CSRF headers (`X-Storystick-Client`, credentialed
|
|
14
|
+
* CORS) so they succeed against the gateway's three-layer defense.
|
|
15
|
+
*
|
|
16
|
+
* Errors: if the gateway replies non-2xx, we throw an `SdkError`-shaped
|
|
17
|
+
* `Error` with `.code` set to the gateway's ConvexError code. The state
|
|
18
|
+
* machine inspects `.code` to decide DEAD vs refreshable (see §13.3).
|
|
19
|
+
*/
|
|
20
|
+
import type { TokenFetcher } from './_stateMachine.js';
|
|
21
|
+
export interface ApiKeyFetcherOptions {
|
|
22
|
+
/** Central gateway URL, e.g. `https://<name>.convex.site`. */
|
|
23
|
+
gatewayUrl: string;
|
|
24
|
+
/** The caller's long-lived API key (`ss_sk_live_*` or `ss_pk_live_*`). */
|
|
25
|
+
apiKey: string;
|
|
26
|
+
/** Client tag for the CSRF stack. Default: `"sdk"`. */
|
|
27
|
+
client?: 'sdk' | 'hub' | 'studio' | 'ops';
|
|
28
|
+
/** Exact customer application build to pair with a schema generation. */
|
|
29
|
+
applicationBuildId?: string;
|
|
30
|
+
/**
|
|
31
|
+
* Optional override of `globalThis.fetch`, including for isolated tests.
|
|
32
|
+
*/
|
|
33
|
+
fetchImpl?: typeof fetch;
|
|
34
|
+
}
|
|
35
|
+
export declare function apiKeyFetcher({ gatewayUrl, apiKey, client, applicationBuildId, fetchImpl, }: ApiKeyFetcherOptions): TokenFetcher;
|
|
36
|
+
export interface UserSessionFetcherOptions {
|
|
37
|
+
/** Central gateway URL, e.g. `https://<name>.convex.site`. */
|
|
38
|
+
gatewayUrl: string;
|
|
39
|
+
/**
|
|
40
|
+
* Returns the caller's current Convex Auth session token. Called on
|
|
41
|
+
* every fetch (cheap — usually a ref-read). Return `null` when the user
|
|
42
|
+
* is not signed in; the fetcher will throw `UNAUTHENTICATED`, which the
|
|
43
|
+
* state machine will surface.
|
|
44
|
+
*/
|
|
45
|
+
getSessionToken: () => string | null;
|
|
46
|
+
/** The project the caller is asking a scope for. */
|
|
47
|
+
projectId: string;
|
|
48
|
+
/** Client tag for the CSRF stack. Default: `"studio"`. */
|
|
49
|
+
client?: 'studio' | 'hub' | 'ops';
|
|
50
|
+
}
|
|
51
|
+
export declare function userSessionFetcher({ gatewayUrl, getSessionToken, projectId, client, }: UserSessionFetcherOptions): TokenFetcher;
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Token fetchers — two origins, one result shape (ADR-045 §4, §11.1).
|
|
3
|
+
*
|
|
4
|
+
* - `apiKeyFetcher({ gatewayUrl, apiKey })` — explicit machine delegation.
|
|
5
|
+
* Calls `POST /api/tokens/issue` with Bearer <apiKey>. Used by mutation/import
|
|
6
|
+
* consumers. Ordinary HTTP reads authenticate directly in `transport.ts`.
|
|
7
|
+
*
|
|
8
|
+
* - `userSessionFetcher({ gatewayUrl, getSessionToken, projectId })` —
|
|
9
|
+
* Studio flow. Calls `POST /api/tokens/issue-for-user` with the caller's
|
|
10
|
+
* Convex Auth session token + the target projectId in the body.
|
|
11
|
+
*
|
|
12
|
+
* Both produce `{ token, expiresAt }` consumed by the state machine.
|
|
13
|
+
* Both attach the §11.5 CSRF headers (`X-Storystick-Client`, credentialed
|
|
14
|
+
* CORS) so they succeed against the gateway's three-layer defense.
|
|
15
|
+
*
|
|
16
|
+
* Errors: if the gateway replies non-2xx, we throw an `SdkError`-shaped
|
|
17
|
+
* `Error` with `.code` set to the gateway's ConvexError code. The state
|
|
18
|
+
* machine inspects `.code` to decide DEAD vs refreshable (see §13.3).
|
|
19
|
+
*/
|
|
20
|
+
import { contentShapeCapabilityHeaders, } from '@storystick/types';
|
|
21
|
+
function makeSdkError(code, message, opts = {}) {
|
|
22
|
+
const refLine = opts.ref
|
|
23
|
+
? `\n\nReference ID: ${opts.ref}\nShare this with support when reporting this issue.`
|
|
24
|
+
: '';
|
|
25
|
+
const err = new Error(`${message}${refLine}`);
|
|
26
|
+
err.code = code;
|
|
27
|
+
if (opts.ref !== undefined)
|
|
28
|
+
err.ref = opts.ref;
|
|
29
|
+
if (opts.payload !== undefined)
|
|
30
|
+
err.payload = opts.payload;
|
|
31
|
+
if (opts.category !== undefined)
|
|
32
|
+
err.category = opts.category;
|
|
33
|
+
if (opts.recoverable !== undefined)
|
|
34
|
+
err.recoverable = opts.recoverable;
|
|
35
|
+
if (opts.retryable !== undefined)
|
|
36
|
+
err.retryable = opts.retryable;
|
|
37
|
+
return err;
|
|
38
|
+
}
|
|
39
|
+
async function readTokenResponse(response) {
|
|
40
|
+
if (!response.ok) {
|
|
41
|
+
const body = (await response
|
|
42
|
+
.json()
|
|
43
|
+
.catch(() => ({})));
|
|
44
|
+
const wrapped = body.error;
|
|
45
|
+
const code = wrapped?.code ?? body.code ?? `HTTP_${response.status}`;
|
|
46
|
+
const message = wrapped?.message ??
|
|
47
|
+
body.message ??
|
|
48
|
+
`Gateway returned HTTP ${response.status} without a body.`;
|
|
49
|
+
throw makeSdkError(code, message, {
|
|
50
|
+
ref: wrapped?.ref,
|
|
51
|
+
payload: wrapped?.payload,
|
|
52
|
+
category: wrapped?.category,
|
|
53
|
+
recoverable: wrapped?.recoverable,
|
|
54
|
+
retryable: wrapped?.retryable,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
const body = (await response.json());
|
|
58
|
+
if (!body.token || typeof body.token !== 'string') {
|
|
59
|
+
throw makeSdkError('storystick/INVALID_GATEWAY_RESPONSE', 'Gateway returned 200 without a `token` field.', { category: 'system', recoverable: false, retryable: false });
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
token: body.token,
|
|
63
|
+
expiresAt: Date.now() + body.expiresIn * 1000,
|
|
64
|
+
...(typeof body.contentShapeCapability === 'string' &&
|
|
65
|
+
body.contentShapeCapability.length > 0
|
|
66
|
+
? { contentShapeCapability: body.contentShapeCapability }
|
|
67
|
+
: {}),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
export function apiKeyFetcher({ gatewayUrl, apiKey, client = 'sdk', applicationBuildId, fetchImpl, }) {
|
|
71
|
+
const fetchFn = fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
72
|
+
let retainedContentShapeCapability;
|
|
73
|
+
let initialMint;
|
|
74
|
+
const surface = 'api';
|
|
75
|
+
return async () => {
|
|
76
|
+
if (!retainedContentShapeCapability && initialMint)
|
|
77
|
+
return initialMint;
|
|
78
|
+
const mint = (async () => {
|
|
79
|
+
const response = await fetchFn(`${gatewayUrl}/api/tokens/issue`, {
|
|
80
|
+
method: 'POST',
|
|
81
|
+
headers: {
|
|
82
|
+
Authorization: `Bearer ${apiKey}`,
|
|
83
|
+
'Content-Type': 'application/json',
|
|
84
|
+
'X-Storystick-Client': client,
|
|
85
|
+
...contentShapeCapabilityHeaders(surface, retainedContentShapeCapability, applicationBuildId),
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
const result = await readTokenResponse(response);
|
|
89
|
+
retainedContentShapeCapability ??= result.contentShapeCapability;
|
|
90
|
+
return result;
|
|
91
|
+
})();
|
|
92
|
+
if (!retainedContentShapeCapability)
|
|
93
|
+
initialMint = mint;
|
|
94
|
+
try {
|
|
95
|
+
return await mint;
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
if (initialMint === mint)
|
|
99
|
+
initialMint = undefined;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
export function userSessionFetcher({ gatewayUrl, getSessionToken, projectId, client = 'studio', }) {
|
|
104
|
+
let retainedContentShapeCapability;
|
|
105
|
+
let initialMint;
|
|
106
|
+
const surface = client === 'studio' ? 'studio' : 'api';
|
|
107
|
+
return async () => {
|
|
108
|
+
if (!retainedContentShapeCapability && initialMint)
|
|
109
|
+
return initialMint;
|
|
110
|
+
const session = getSessionToken();
|
|
111
|
+
if (!session) {
|
|
112
|
+
throw makeSdkError('storystick/UNAUTHENTICATED', 'Not signed in.', {
|
|
113
|
+
category: 'auth',
|
|
114
|
+
recoverable: true,
|
|
115
|
+
retryable: false,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
const mint = (async () => {
|
|
119
|
+
const response = await fetch(`${gatewayUrl}/api/tokens/issue-for-user`, {
|
|
120
|
+
method: 'POST',
|
|
121
|
+
credentials: 'include',
|
|
122
|
+
headers: {
|
|
123
|
+
Authorization: `Bearer ${session}`,
|
|
124
|
+
'Content-Type': 'application/json',
|
|
125
|
+
'X-Storystick-Client': client,
|
|
126
|
+
...contentShapeCapabilityHeaders(surface, retainedContentShapeCapability),
|
|
127
|
+
},
|
|
128
|
+
body: JSON.stringify({ projectId }),
|
|
129
|
+
});
|
|
130
|
+
const result = await readTokenResponse(response);
|
|
131
|
+
retainedContentShapeCapability ??= result.contentShapeCapability;
|
|
132
|
+
return result;
|
|
133
|
+
})();
|
|
134
|
+
if (!retainedContentShapeCapability)
|
|
135
|
+
initialMint = mint;
|
|
136
|
+
try {
|
|
137
|
+
return await mint;
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
if (initialMint === mint)
|
|
141
|
+
initialMint = undefined;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Storystick SDK token state machine (ADR-045 §13).
|
|
3
|
+
*
|
|
4
|
+
* Pure state, zero Convex dep. Given a pluggable `fetcher` that returns
|
|
5
|
+
* `{ token, expiresAt }` from any issuance endpoint, the machine:
|
|
6
|
+
*
|
|
7
|
+
* 1. **Opportunistic JIT refresh** (§13.1) — on every `ensureToken()` call,
|
|
8
|
+
* if the cached token has ≤ `margin` seconds left, refresh BEFORE returning.
|
|
9
|
+
* Jitter on the margin per instance so a fleet cold-start doesn't thunder
|
|
10
|
+
* the gateway all at once.
|
|
11
|
+
* 2. **Single-flight coalescing** (§13.2) — N concurrent calls during a
|
|
12
|
+
* refresh share the same `pendingRefresh` promise, one HTTP call out.
|
|
13
|
+
* 3. **DEAD state** (§13.3) — hard-auth errors (INVALID_API_KEY, revoked,
|
|
14
|
+
* expired, not-a-member) lock the machine; all subsequent calls throw
|
|
15
|
+
* immediately. Exit only via explicit `reset()`.
|
|
16
|
+
* 4. **Reactive 401 backstop** — exposed as `forceRefresh()` for the wire
|
|
17
|
+
* layer to call when a Convex query returns 401 in-flight.
|
|
18
|
+
*
|
|
19
|
+
* Not included here on purpose: the transient-error backoff (§13.7) lives
|
|
20
|
+
* in the wire layer (Convex client's built-in retry), not in this file.
|
|
21
|
+
*/
|
|
22
|
+
export interface TokenFetchResult {
|
|
23
|
+
/** The compact JWT. */
|
|
24
|
+
token: string;
|
|
25
|
+
/** Absolute unix-ms at which the token expires. Used to compute margin. */
|
|
26
|
+
expiresAt: number;
|
|
27
|
+
/** Opaque first-epoch capability retained by the fetcher across refreshes. */
|
|
28
|
+
contentShapeCapability?: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* A token fetcher — the only thing the state machine needs from the
|
|
32
|
+
* outside. Keeps the state machine reusable across API-key and
|
|
33
|
+
* user-session origins.
|
|
34
|
+
*/
|
|
35
|
+
export type TokenFetcher = () => Promise<TokenFetchResult>;
|
|
36
|
+
/**
|
|
37
|
+
* Boundary error codes the state machine knows about. Post ADR-079 batch 5
|
|
38
|
+
* the codes are namespaced (`storystick/<NAME>`) ; the legacy-bare aliases
|
|
39
|
+
* are tolerated for the gateway-rollout window (matches `_fetchers.ts`'s
|
|
40
|
+
* dual-shape acceptance).
|
|
41
|
+
*/
|
|
42
|
+
export type StateMachineErrorCode = 'storystick/TOKEN_EXPIRED' | 'storystick/INVALID_TOKEN' | 'storystick/UNAUTHENTICATED' | 'storystick/VERIFY_UNAVAILABLE' | 'storystick/RATE_LIMITED' | 'storystick/INVALID_API_KEY' | 'storystick/API_KEY_REVOKED' | 'storystick/API_KEY_EXPIRED' | 'storystick/NOT_A_MEMBER' | 'storystick/ACCESS_DENIED' | 'storystick/CSRF_ORIGIN_REJECTED' | 'storystick/CSRF_CLIENT_HEADER_MISSING';
|
|
43
|
+
/**
|
|
44
|
+
* SDK-side error class. Post ADR-079 batch 5 enriched with canonical
|
|
45
|
+
* envelope metadata (`category`, `recoverable`, `retryable`, `payload`) when
|
|
46
|
+
* the gateway response carried them — see `_fetchers.ts`. The state
|
|
47
|
+
* machine's `isHardAuthError` / `isRefreshableError` prefer these
|
|
48
|
+
* canonical fields over the hardcoded code list (Tension #5 lock B).
|
|
49
|
+
*/
|
|
50
|
+
export interface SdkError extends Error {
|
|
51
|
+
code?: StateMachineErrorCode | string;
|
|
52
|
+
/**
|
|
53
|
+
* Gateway-issued ref ID (SPEC-1 Item #6 — ops-error-reporting). Populated
|
|
54
|
+
* when the gateway responded with a `{ error: { ref } }` body. Present
|
|
55
|
+
* on every non-2xx response from up-to-date deployments; absent for
|
|
56
|
+
* local validation errors that never hit the gateway.
|
|
57
|
+
*/
|
|
58
|
+
ref?: string;
|
|
59
|
+
/** Canonical category from the gateway envelope (post ADR-079 batch 4). */
|
|
60
|
+
category?: 'validation' | 'conflict' | 'auth' | 'system' | 'cancel';
|
|
61
|
+
/** True if the user can fix the cause and retry. */
|
|
62
|
+
recoverable?: boolean;
|
|
63
|
+
/** True if the SDK / CLI can auto-retry without user input. */
|
|
64
|
+
retryable?: boolean;
|
|
65
|
+
/** Per-code structured payload from the gateway envelope. */
|
|
66
|
+
payload?: unknown;
|
|
67
|
+
}
|
|
68
|
+
export interface TokenStateMachine {
|
|
69
|
+
/** Get a valid token, refreshing opportunistically if near expiry. */
|
|
70
|
+
ensureToken(): Promise<string>;
|
|
71
|
+
/** Bypass cache and force a refresh (reactive 401 backstop). */
|
|
72
|
+
forceRefresh(): Promise<string>;
|
|
73
|
+
/** Clear DEAD state. The next `ensureToken()` will attempt to refresh. */
|
|
74
|
+
reset(): void;
|
|
75
|
+
/** True if the last hard-auth error has locked the machine. */
|
|
76
|
+
isDead(): boolean;
|
|
77
|
+
}
|
|
78
|
+
export interface CreateStateMachineOptions {
|
|
79
|
+
fetcher: TokenFetcher;
|
|
80
|
+
/** Override the jitter base for tests. Default: 60s ± 10s. */
|
|
81
|
+
marginSecondsOverride?: number;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Construct a fresh state machine. Per-instance state (cache, pendingRefresh,
|
|
85
|
+
* DEAD flag, margin) is captured in the closure returned here — one instance
|
|
86
|
+
* per Convex client. Module-level sharing between clients is intentionally
|
|
87
|
+
* NOT supported: different clients have different issuance endpoints,
|
|
88
|
+
* different keys, different tenant scopes.
|
|
89
|
+
*/
|
|
90
|
+
export declare function createTokenStateMachine({ fetcher, marginSecondsOverride, }: CreateStateMachineOptions): TokenStateMachine;
|
|
91
|
+
/**
|
|
92
|
+
* Refreshable error : the SDK should attempt a token refresh + retry.
|
|
93
|
+
* Canonical signal : `category: 'auth' && retryable: true` (e.g. TOKEN_EXPIRED,
|
|
94
|
+
* INVALID_TOKEN, UNAUTHENTICATED have `retryable: true` in the catalogue).
|
|
95
|
+
*/
|
|
96
|
+
export declare function isRefreshableError(err: unknown): boolean;
|
|
97
|
+
/**
|
|
98
|
+
* Hard auth error : the SDK should NOT retry, mark itself DEAD, surface to
|
|
99
|
+
* user. Canonical signal : `category: 'auth' && recoverable: false` (e.g.
|
|
100
|
+
* INVALID_API_KEY, ACCESS_DENIED).
|
|
101
|
+
*/
|
|
102
|
+
export declare function isHardAuthError(err: unknown): boolean;
|