@storyblok/api-client 0.2.3 → 1.0.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.cjs +176 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +333 -0
- package/dist/client.d.mts +333 -0
- package/dist/client.mjs +175 -0
- package/dist/client.mjs.map +1 -0
- package/dist/error.cjs.map +1 -1
- package/dist/error.d.cts +13 -2
- package/dist/error.d.mts +13 -2
- package/dist/error.mjs.map +1 -1
- package/dist/generated/datasource_entries/types.gen.d.cts +1 -16
- package/dist/generated/datasource_entries/types.gen.d.mts +1 -16
- package/dist/generated/datasources/types.gen.d.cts +1 -28
- package/dist/generated/datasources/types.gen.d.mts +1 -28
- package/dist/generated/links/types.gen.d.cts +1 -18
- package/dist/generated/links/types.gen.d.mts +1 -18
- package/dist/generated/shared/client/index.d.mts +1 -1
- package/dist/generated/shared/client/types.gen.d.cts +39 -3
- package/dist/generated/shared/client/types.gen.d.mts +39 -3
- package/dist/generated/shared/core/serverSentEvents.gen.d.cts +4 -1
- package/dist/generated/shared/core/serverSentEvents.gen.d.mts +4 -1
- package/dist/generated/shared/core/types.gen.d.cts +14 -1
- package/dist/generated/shared/core/types.gen.d.mts +14 -1
- package/dist/generated/spaces/types.gen.d.cts +1 -9
- package/dist/generated/spaces/types.gen.d.mts +1 -9
- package/dist/generated/stories/index.d.mts +1 -1
- package/dist/generated/stories/types.gen.d.cts +72 -9
- package/dist/generated/stories/types.gen.d.mts +72 -9
- package/dist/generated/tags/types.gen.d.cts +1 -16
- package/dist/generated/tags/types.gen.d.mts +1 -16
- package/dist/index.cjs +2 -153
- package/dist/index.d.cts +4 -172
- package/dist/index.d.mts +4 -172
- package/dist/index.mjs +2 -150
- package/dist/resources/datasource-entries.cjs.map +1 -1
- package/dist/resources/datasource-entries.mjs.map +1 -1
- package/dist/resources/datasources.cjs.map +1 -1
- package/dist/resources/datasources.mjs.map +1 -1
- package/dist/resources/links.cjs.map +1 -1
- package/dist/resources/links.mjs.map +1 -1
- package/dist/resources/spaces.cjs.map +1 -1
- package/dist/resources/spaces.mjs.map +1 -1
- package/dist/resources/stories.cjs +6 -4
- package/dist/resources/stories.cjs.map +1 -1
- package/dist/resources/stories.d.cts +78 -3
- package/dist/resources/stories.d.mts +79 -3
- package/dist/resources/stories.mjs +6 -4
- package/dist/resources/stories.mjs.map +1 -1
- package/dist/resources/tags.cjs.map +1 -1
- package/dist/resources/tags.mjs.map +1 -1
- package/dist/utils/inline-relations.cjs +13 -1
- package/dist/utils/inline-relations.cjs.map +1 -1
- package/dist/utils/inline-relations.mjs +13 -1
- package/dist/utils/inline-relations.mjs.map +1 -1
- package/dist/utils/rate-limit.cjs +9 -5
- package/dist/utils/rate-limit.cjs.map +1 -1
- package/dist/utils/rate-limit.d.cts +4 -18
- package/dist/utils/rate-limit.d.mts +4 -18
- package/dist/utils/rate-limit.mjs +10 -4
- package/dist/utils/rate-limit.mjs.map +1 -1
- package/package.json +18 -8
- package/dist/index.cjs.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/types.d.cts +0 -37
- package/dist/types.d.mts +0 -37
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { DatasourceEntryCapi, ListData } from "./generated/datasource_entries/types.gen.mjs";
|
|
2
|
+
import { DatasourceCapi, GetData, ListData as ListData$1 } from "./generated/datasources/types.gen.mjs";
|
|
3
|
+
import { Middleware } from "./generated/shared/client/utils.gen.mjs";
|
|
4
|
+
import { Client, RequestOptions, ResolvedRequestOptions } from "./generated/shared/client/types.gen.mjs";
|
|
5
|
+
import { LinkCapi, ListData as ListData$2 } from "./generated/links/types.gen.mjs";
|
|
6
|
+
import { SpaceCapi } from "./generated/spaces/types.gen.mjs";
|
|
7
|
+
import { StoryCapi } from "./generated/stories/types.gen.mjs";
|
|
8
|
+
import { ListData as ListData$3, TagCapi } from "./generated/tags/types.gen.mjs";
|
|
9
|
+
import { CacheProvider, CacheStrategy, CacheStrategyHandler } from "./utils/cache.mjs";
|
|
10
|
+
import { ClientError } from "./error.mjs";
|
|
11
|
+
import { RateLimitConfig, ThrottleManager } from "./utils/rate-limit.mjs";
|
|
12
|
+
import { StoryWithInlinedRelations, createStoriesResource } from "./resources/stories.mjs";
|
|
13
|
+
import { RetryOptions } from "ky";
|
|
14
|
+
import { Region } from "@storyblok/region-helper";
|
|
15
|
+
import { Block } from "@storyblok/schema";
|
|
16
|
+
|
|
17
|
+
//#region src/client.d.ts
|
|
18
|
+
type ApiResponse<Data = unknown, ThrowOnError extends boolean = false> = ThrowOnError extends true ? {
|
|
19
|
+
data: Data;
|
|
20
|
+
error?: never;
|
|
21
|
+
response: Response;
|
|
22
|
+
request: Request;
|
|
23
|
+
} : {
|
|
24
|
+
data?: Data;
|
|
25
|
+
error?: ClientError;
|
|
26
|
+
response: Response;
|
|
27
|
+
request: Request;
|
|
28
|
+
};
|
|
29
|
+
type HttpRequestOptions = Omit<RequestOptions, 'method' | 'security' | 'url'>;
|
|
30
|
+
type HttpRequestMethod = <TData = unknown>(path: string, options?: HttpRequestOptions) => Promise<ApiResponse<TData>>;
|
|
31
|
+
/**
|
|
32
|
+
* Arbitrary options forwarded to the underlying `fetch()` call.
|
|
33
|
+
*
|
|
34
|
+
* Standard `RequestInit` properties (`cache`, `credentials`, `mode`, …) and
|
|
35
|
+
* non-standard, vendor-specific properties (Next.js `next`, Cloudflare `cf`, …)
|
|
36
|
+
* are both supported.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* client.stories.get('home', {
|
|
41
|
+
* fetchOptions: {
|
|
42
|
+
* cache: 'no-store',
|
|
43
|
+
* next: { revalidate: 60, tags: ['home'] },
|
|
44
|
+
* },
|
|
45
|
+
* })
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
type FetchOptions = Record<string, unknown>;
|
|
49
|
+
interface RequestWithCacheOptions {
|
|
50
|
+
/** Prefix added to the cache key to namespace entries (e.g. `'inline'`). */
|
|
51
|
+
cacheKeyPrefix?: string;
|
|
52
|
+
}
|
|
53
|
+
interface ResourceDeps<DefaultThrowOnError extends boolean = false> {
|
|
54
|
+
client: Client;
|
|
55
|
+
requestWithCache: <TData, ThrowOnError extends boolean = DefaultThrowOnError>(method: 'GET', path: string, rawQuery: Record<string, unknown>, fetchFn: (query: Record<string, unknown>) => Promise<ApiResponse<TData, ThrowOnError>>, options?: RequestWithCacheOptions) => Promise<ApiResponse<TData, ThrowOnError>>;
|
|
56
|
+
asApiResponse: <TData, ThrowOnError extends boolean = DefaultThrowOnError>(p: Promise<unknown>) => Promise<ApiResponse<TData, ThrowOnError>>;
|
|
57
|
+
throttleManager: ThrottleManager;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Cache configuration.
|
|
61
|
+
*
|
|
62
|
+
* **Note:** Requests with `version: 'draft'` always bypass the cache regardless
|
|
63
|
+
* of the configured strategy. Only published content is cached.
|
|
64
|
+
*/
|
|
65
|
+
interface CacheConfig {
|
|
66
|
+
/** Custom cache provider. Defaults to an in-memory LRU cache (1 000 entries). */
|
|
67
|
+
provider?: CacheProvider;
|
|
68
|
+
/** Cache strategy for published requests. @default 'cache-first' */
|
|
69
|
+
strategy?: CacheStrategy | CacheStrategyHandler;
|
|
70
|
+
/** Time-to-live in milliseconds for cached entries. @default 60_000 */
|
|
71
|
+
ttlMs?: number;
|
|
72
|
+
/**
|
|
73
|
+
* Controls when the cache is flushed on cv change.
|
|
74
|
+
*
|
|
75
|
+
* - `'auto'` (default): automatically flush the cache whenever the API returns a new cv value.
|
|
76
|
+
* - `'manual'`: never auto-flush; call `client.flushCache()` explicitly (e.g. on webhook trigger).
|
|
77
|
+
*/
|
|
78
|
+
flush?: 'auto' | 'manual';
|
|
79
|
+
/**
|
|
80
|
+
* Called when SWR background revalidation fails.
|
|
81
|
+
* Only relevant when `strategy` is `'swr'`.
|
|
82
|
+
* @default console.warn
|
|
83
|
+
*/
|
|
84
|
+
onRevalidationError?: (error: unknown) => void;
|
|
85
|
+
}
|
|
86
|
+
interface ContentApiClientConfig<ThrowOnError extends boolean = false, InlineRelations extends boolean = false> {
|
|
87
|
+
accessToken: string;
|
|
88
|
+
region?: Region;
|
|
89
|
+
baseUrl?: string;
|
|
90
|
+
headers?: Record<string, string>;
|
|
91
|
+
throwOnError?: ThrowOnError;
|
|
92
|
+
cache?: CacheConfig;
|
|
93
|
+
inlineRelations?: InlineRelations;
|
|
94
|
+
retry?: RetryOptions;
|
|
95
|
+
/**
|
|
96
|
+
* Request timeout in milliseconds.
|
|
97
|
+
* @default 30_000
|
|
98
|
+
*/
|
|
99
|
+
timeout?: number;
|
|
100
|
+
/**
|
|
101
|
+
* Preventive rate limiting to avoid hitting the Storyblok CDN rate limits.
|
|
102
|
+
*
|
|
103
|
+
* - `undefined` (default): auto-detect tier from path + `per_page` query param.
|
|
104
|
+
* - `number`: fixed max concurrent requests per second (single queue).
|
|
105
|
+
* - `{ maxConcurrency?: number; adaptToServerHeaders?: boolean }`: full config.
|
|
106
|
+
* - `false`: disable rate limiting entirely.
|
|
107
|
+
*/
|
|
108
|
+
rateLimit?: RateLimitConfig | number | false;
|
|
109
|
+
/**
|
|
110
|
+
* Custom `fetch` function to use for all requests.
|
|
111
|
+
* Must be fully compatible with the Fetch API standard.
|
|
112
|
+
*
|
|
113
|
+
* Use cases:
|
|
114
|
+
* - SSR framework fetch wrappers (e.g., Next.js `fetch` with caching)
|
|
115
|
+
* - Custom instrumentation or logging around requests
|
|
116
|
+
*
|
|
117
|
+
* @default globalThis.fetch
|
|
118
|
+
*/
|
|
119
|
+
fetch?: typeof globalThis.fetch;
|
|
120
|
+
}
|
|
121
|
+
type StoryblokTypesConfig = {
|
|
122
|
+
components: Block;
|
|
123
|
+
} | {
|
|
124
|
+
blocks: Block;
|
|
125
|
+
};
|
|
126
|
+
type ResolveComponents<T extends StoryblokTypesConfig> = T extends {
|
|
127
|
+
components: infer C extends Block;
|
|
128
|
+
} ? C : T extends {
|
|
129
|
+
blocks: infer B extends Block;
|
|
130
|
+
} ? B : never;
|
|
131
|
+
/**
|
|
132
|
+
* The return type of `createApiClient`, parameterised by `TComponents` and `InlineRelations`
|
|
133
|
+
* so that `.withTypes<T>()` can change the story response types without touching the
|
|
134
|
+
* runtime object.
|
|
135
|
+
*/
|
|
136
|
+
type ContentApiClient<TComponents extends Block = Block, InlineRelations extends boolean = false, ThrowOnError extends boolean = false> = Omit<ReturnType<typeof createApiClientBase>, 'stories' | 'withTypes'> & {
|
|
137
|
+
stories: ReturnType<typeof createStoriesResource<TComponents, InlineRelations, ThrowOnError>>;
|
|
138
|
+
/**
|
|
139
|
+
* Returns the same client instance cast to a version that narrows story content
|
|
140
|
+
* to the provided component types. No runtime cost — the type parameter is erased.
|
|
141
|
+
*
|
|
142
|
+
* Accepts either `{ components: ... }` or `{ blocks: ... }` — the latter matches the
|
|
143
|
+
* `Schema` type produced by `@storyblok/schema`'s `InferSchema`.
|
|
144
|
+
*
|
|
145
|
+
* @example
|
|
146
|
+
* ```ts
|
|
147
|
+
* import type { Schema } from './schema';
|
|
148
|
+
*
|
|
149
|
+
* const client = createApiClient({ accessToken: 'your-token' })
|
|
150
|
+
* .withTypes<Schema>();
|
|
151
|
+
* // story.content is now typed as a discriminated union
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
withTypes: <T extends StoryblokTypesConfig>() => ContentApiClient<ResolveComponents<T>, InlineRelations, ThrowOnError>;
|
|
155
|
+
};
|
|
156
|
+
declare const createApiClientBase: <ThrowOnError extends boolean = false, InlineRelations extends boolean = false>(config: ContentApiClientConfig<ThrowOnError, InlineRelations>) => {
|
|
157
|
+
datasourceEntries: {
|
|
158
|
+
list: <ThrowOnError_1 extends boolean = ThrowOnError>(options?: {
|
|
159
|
+
query?: ListData["query"];
|
|
160
|
+
signal?: AbortSignal;
|
|
161
|
+
throwOnError?: ThrowOnError_1 | undefined;
|
|
162
|
+
fetchOptions?: FetchOptions;
|
|
163
|
+
}) => Promise<ApiResponse<{
|
|
164
|
+
datasource_entries: Array<DatasourceEntryCapi>;
|
|
165
|
+
cv?: number | null;
|
|
166
|
+
}, ThrowOnError_1>>;
|
|
167
|
+
};
|
|
168
|
+
datasources: {
|
|
169
|
+
get: <ThrowOnError_1 extends boolean = ThrowOnError>(id: GetData["path"]["id"], options?: {
|
|
170
|
+
query?: GetData["query"];
|
|
171
|
+
signal?: AbortSignal;
|
|
172
|
+
throwOnError?: ThrowOnError_1 | undefined;
|
|
173
|
+
fetchOptions?: FetchOptions;
|
|
174
|
+
}) => Promise<ApiResponse<{
|
|
175
|
+
datasource: DatasourceCapi;
|
|
176
|
+
cv?: number;
|
|
177
|
+
}, ThrowOnError_1>>;
|
|
178
|
+
list: <ThrowOnError_1 extends boolean = ThrowOnError>(options?: {
|
|
179
|
+
query?: ListData$1["query"];
|
|
180
|
+
signal?: AbortSignal;
|
|
181
|
+
throwOnError?: ThrowOnError_1 | undefined;
|
|
182
|
+
fetchOptions?: FetchOptions;
|
|
183
|
+
}) => Promise<ApiResponse<{
|
|
184
|
+
datasources: Array<DatasourceCapi>;
|
|
185
|
+
cv?: number;
|
|
186
|
+
}, ThrowOnError_1>>;
|
|
187
|
+
};
|
|
188
|
+
flushCache: () => Promise<void>;
|
|
189
|
+
get: (path: string, options?: HttpRequestOptions) => Promise<{
|
|
190
|
+
data?: unknown;
|
|
191
|
+
error?: ClientError;
|
|
192
|
+
response: Response;
|
|
193
|
+
request: Request;
|
|
194
|
+
}>;
|
|
195
|
+
interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions<"fields", boolean, string>>;
|
|
196
|
+
links: {
|
|
197
|
+
list: <ThrowOnError_1 extends boolean = ThrowOnError>(options?: {
|
|
198
|
+
query?: ListData$2["query"];
|
|
199
|
+
signal?: AbortSignal;
|
|
200
|
+
throwOnError?: ThrowOnError_1 | undefined;
|
|
201
|
+
fetchOptions?: FetchOptions;
|
|
202
|
+
}) => Promise<ApiResponse<{
|
|
203
|
+
links: {
|
|
204
|
+
[key: string]: LinkCapi;
|
|
205
|
+
};
|
|
206
|
+
cv?: number;
|
|
207
|
+
}, ThrowOnError_1>>;
|
|
208
|
+
};
|
|
209
|
+
spaces: {
|
|
210
|
+
get: <ThrowOnError_1 extends boolean = ThrowOnError>(options?: {
|
|
211
|
+
signal?: AbortSignal;
|
|
212
|
+
throwOnError?: ThrowOnError_1 | undefined;
|
|
213
|
+
fetchOptions?: FetchOptions;
|
|
214
|
+
}) => Promise<ApiResponse<{
|
|
215
|
+
space: SpaceCapi;
|
|
216
|
+
}, ThrowOnError_1>>;
|
|
217
|
+
};
|
|
218
|
+
stories: {
|
|
219
|
+
get: <ThrowOnError_1 extends boolean = ThrowOnError, const ResolveRelationsStr extends string | undefined = undefined>(identifier: string | number, options?: {
|
|
220
|
+
query?: (Omit<{
|
|
221
|
+
find_by?: "uuid";
|
|
222
|
+
version?: "published" | "draft";
|
|
223
|
+
cv?: number;
|
|
224
|
+
from_release?: string;
|
|
225
|
+
resolve_links?: "story" | "url" | "link";
|
|
226
|
+
resolve_links_level?: 1 | 2;
|
|
227
|
+
resolve_relations?: string;
|
|
228
|
+
resolve_level?: 2;
|
|
229
|
+
resolve_assets?: 0 | 1;
|
|
230
|
+
fallback_lang?: string;
|
|
231
|
+
language?: string;
|
|
232
|
+
}, "resolve_relations"> & {
|
|
233
|
+
resolve_relations?: ResolveRelationsStr | undefined;
|
|
234
|
+
}) | undefined;
|
|
235
|
+
signal?: AbortSignal;
|
|
236
|
+
throwOnError?: ThrowOnError_1 | undefined;
|
|
237
|
+
fetchOptions?: FetchOptions;
|
|
238
|
+
}) => Promise<ApiResponse<Omit<{
|
|
239
|
+
story: StoryCapi;
|
|
240
|
+
cv?: number;
|
|
241
|
+
rels?: Array<StoryCapi>;
|
|
242
|
+
links?: Array<{
|
|
243
|
+
[key: string]: unknown;
|
|
244
|
+
}>;
|
|
245
|
+
rel_uuids?: Array<string>;
|
|
246
|
+
link_uuids?: Array<string>;
|
|
247
|
+
}, "story"> & {
|
|
248
|
+
story: InlineRelations extends true ? StoryWithInlinedRelations : StoryCapi;
|
|
249
|
+
}, ThrowOnError_1>>;
|
|
250
|
+
list: <ThrowOnError_1 extends boolean = ThrowOnError, const ResolveRelationsStr_1 extends string | undefined = undefined>(options?: {
|
|
251
|
+
query?: (Omit<{
|
|
252
|
+
version?: "published" | "draft";
|
|
253
|
+
cv?: number;
|
|
254
|
+
starts_with?: string;
|
|
255
|
+
from_release?: string;
|
|
256
|
+
search_term?: string;
|
|
257
|
+
per_page?: number;
|
|
258
|
+
page?: number;
|
|
259
|
+
resolve_links?: "story" | "url" | "link";
|
|
260
|
+
resolve_links_level?: 1 | 2;
|
|
261
|
+
resolve_relations?: string;
|
|
262
|
+
resolve_level?: 2;
|
|
263
|
+
resolve_assets?: 0 | 1;
|
|
264
|
+
fallback_lang?: string;
|
|
265
|
+
language?: string;
|
|
266
|
+
content_type?: string;
|
|
267
|
+
by_slugs?: string;
|
|
268
|
+
excluding_slugs?: string;
|
|
269
|
+
by_uuids?: string;
|
|
270
|
+
by_uuids_ordered?: string;
|
|
271
|
+
excluding_ids?: string;
|
|
272
|
+
with_tag?: string;
|
|
273
|
+
sort_by?: string;
|
|
274
|
+
in_workflow_stages?: string;
|
|
275
|
+
filter_query?: string;
|
|
276
|
+
level?: number;
|
|
277
|
+
is_startpage?: 0 | 1;
|
|
278
|
+
first_published_at_gt?: string;
|
|
279
|
+
first_published_at_lt?: string;
|
|
280
|
+
published_at_gt?: string;
|
|
281
|
+
published_at_lt?: string;
|
|
282
|
+
updated_at_gt?: string;
|
|
283
|
+
updated_at_lt?: string;
|
|
284
|
+
excluding_fields?: string;
|
|
285
|
+
}, "resolve_relations"> & {
|
|
286
|
+
resolve_relations?: ResolveRelationsStr_1 | undefined;
|
|
287
|
+
}) | undefined;
|
|
288
|
+
signal?: AbortSignal;
|
|
289
|
+
throwOnError?: ThrowOnError_1 | undefined;
|
|
290
|
+
fetchOptions?: FetchOptions;
|
|
291
|
+
}) => Promise<ApiResponse<Omit<{
|
|
292
|
+
stories: Array<StoryCapi>;
|
|
293
|
+
cv?: number;
|
|
294
|
+
rels?: Array<StoryCapi>;
|
|
295
|
+
links?: Array<{
|
|
296
|
+
[key: string]: unknown;
|
|
297
|
+
}>;
|
|
298
|
+
rel_uuids?: Array<string>;
|
|
299
|
+
link_uuids?: Array<string>;
|
|
300
|
+
}, "stories"> & {
|
|
301
|
+
stories: (InlineRelations extends true ? StoryWithInlinedRelations : StoryCapi)[];
|
|
302
|
+
}, ThrowOnError_1>>;
|
|
303
|
+
};
|
|
304
|
+
tags: {
|
|
305
|
+
list: <ThrowOnError_1 extends boolean = ThrowOnError>(options?: {
|
|
306
|
+
query?: ListData$3["query"];
|
|
307
|
+
signal?: AbortSignal;
|
|
308
|
+
throwOnError?: ThrowOnError_1 | undefined;
|
|
309
|
+
fetchOptions?: FetchOptions;
|
|
310
|
+
}) => Promise<ApiResponse<{
|
|
311
|
+
tags: Array<TagCapi>;
|
|
312
|
+
cv?: number;
|
|
313
|
+
}, ThrowOnError_1>>;
|
|
314
|
+
};
|
|
315
|
+
};
|
|
316
|
+
/**
|
|
317
|
+
* Creates a Storyblok Content Delivery API client.
|
|
318
|
+
*
|
|
319
|
+
* Use `.withTypes<YourTypes>()` on the returned client to enable discriminated
|
|
320
|
+
* union typing on `story.content` without including any schema values in your bundle.
|
|
321
|
+
*
|
|
322
|
+
* @example
|
|
323
|
+
* ```ts
|
|
324
|
+
* import type { pageBlock, heroBlock } from './blocks';
|
|
325
|
+
*
|
|
326
|
+
* const client = createApiClient({ accessToken: 'your-token' })
|
|
327
|
+
* .withTypes<StoryblokTypes>();
|
|
328
|
+
* ```
|
|
329
|
+
*/
|
|
330
|
+
declare const createApiClient: <ThrowOnError extends boolean = false, InlineRelations extends boolean = false>(config: ContentApiClientConfig<ThrowOnError, InlineRelations>) => ContentApiClient<Block, InlineRelations, ThrowOnError>;
|
|
331
|
+
//#endregion
|
|
332
|
+
export { ApiResponse, CacheConfig, ContentApiClient, ContentApiClientConfig, FetchOptions, HttpRequestMethod, HttpRequestOptions, RequestWithCacheOptions, ResourceDeps, createApiClient };
|
|
333
|
+
//# sourceMappingURL=client.d.mts.map
|
package/dist/client.mjs
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { createConfig } from "./generated/shared/client/utils.gen.mjs";
|
|
2
|
+
import { createClient } from "./generated/shared/client/client.gen.mjs";
|
|
3
|
+
import "./generated/shared/client/index.mjs";
|
|
4
|
+
import { createMemoryCacheProvider, createStrategy } from "./utils/cache.mjs";
|
|
5
|
+
import { ClientError } from "./error.mjs";
|
|
6
|
+
import { createThrottleManager } from "./utils/rate-limit.mjs";
|
|
7
|
+
import { createCacheKey, shouldUseCache } from "./utils/request.mjs";
|
|
8
|
+
import { applyCvToQuery, extractCv } from "./utils/cv.mjs";
|
|
9
|
+
import { createStoriesResource } from "./resources/stories.mjs";
|
|
10
|
+
import { createLinksResource } from "./resources/links.mjs";
|
|
11
|
+
import { createTagsResource } from "./resources/tags.mjs";
|
|
12
|
+
import { createDatasourcesResource } from "./resources/datasources.mjs";
|
|
13
|
+
import { createDatasourceEntriesResource } from "./resources/datasource-entries.mjs";
|
|
14
|
+
import { createSpacesResource } from "./resources/spaces.mjs";
|
|
15
|
+
import { getRegionBaseUrl } from "@storyblok/region-helper";
|
|
16
|
+
|
|
17
|
+
//#region src/client.ts
|
|
18
|
+
const createApiClientBase = (config) => {
|
|
19
|
+
const { accessToken, region = "eu", baseUrl, headers = {}, throwOnError = false, cache = {}, inlineRelations = false, retry, timeout = 3e4, rateLimit, fetch: customFetch } = config;
|
|
20
|
+
const retryOptions = {
|
|
21
|
+
limit: 3,
|
|
22
|
+
backoffLimit: 2e4,
|
|
23
|
+
jitter: true,
|
|
24
|
+
...retry
|
|
25
|
+
};
|
|
26
|
+
const throttleManager = createThrottleManager(rateLimit ?? {});
|
|
27
|
+
const cacheProvider = cache.provider ?? createMemoryCacheProvider();
|
|
28
|
+
const swrOptions = cache.onRevalidationError ? { onRevalidationError: cache.onRevalidationError } : void 0;
|
|
29
|
+
const strategy = cache.strategy ? typeof cache.strategy === "string" ? createStrategy(cache.strategy, swrOptions) : cache.strategy : createStrategy("cache-first");
|
|
30
|
+
const cacheTtlMs = cache.ttlMs ?? 6e4;
|
|
31
|
+
const cacheFlush = cache.flush ?? "auto";
|
|
32
|
+
let currentCv;
|
|
33
|
+
const client = createClient(createConfig({
|
|
34
|
+
auth: accessToken,
|
|
35
|
+
baseUrl: baseUrl || getRegionBaseUrl(region),
|
|
36
|
+
headers,
|
|
37
|
+
throwOnError,
|
|
38
|
+
kyOptions: {
|
|
39
|
+
throwHttpErrors: true,
|
|
40
|
+
timeout,
|
|
41
|
+
retry: retryOptions,
|
|
42
|
+
...customFetch && { fetch: customFetch }
|
|
43
|
+
}
|
|
44
|
+
}));
|
|
45
|
+
client.interceptors.error.use((error, response) => new ClientError(response?.statusText || "API request failed", {
|
|
46
|
+
status: response?.status ?? 0,
|
|
47
|
+
statusText: response?.statusText ?? "",
|
|
48
|
+
data: error
|
|
49
|
+
}));
|
|
50
|
+
const security = [{
|
|
51
|
+
in: "query",
|
|
52
|
+
name: "token",
|
|
53
|
+
type: "apiKey"
|
|
54
|
+
}];
|
|
55
|
+
const updateCv = async (result) => {
|
|
56
|
+
const nextCv = extractCv(result.data);
|
|
57
|
+
if (nextCv === void 0) return true;
|
|
58
|
+
if (currentCv !== void 0 && nextCv < currentCv) return false;
|
|
59
|
+
if (cacheFlush === "auto" && currentCv !== void 0 && currentCv !== nextCv) await cacheProvider.flush();
|
|
60
|
+
currentCv = nextCv;
|
|
61
|
+
return true;
|
|
62
|
+
};
|
|
63
|
+
const cacheSuccessResult = async (key, result) => {
|
|
64
|
+
const shouldCacheResult = await updateCv(result);
|
|
65
|
+
if (result.error === void 0 && shouldCacheResult) await cacheProvider.set(key, {
|
|
66
|
+
value: result,
|
|
67
|
+
ttlMs: cacheTtlMs
|
|
68
|
+
});
|
|
69
|
+
return result;
|
|
70
|
+
};
|
|
71
|
+
const requestNetwork = async (method, path, query, options) => {
|
|
72
|
+
return client.request({
|
|
73
|
+
...options,
|
|
74
|
+
method,
|
|
75
|
+
query,
|
|
76
|
+
security,
|
|
77
|
+
url: path
|
|
78
|
+
});
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* Wraps a raw SDK call to cast the `error: unknown` type returned by
|
|
82
|
+
* generated code to `ClientError` — the error interceptor ensures the
|
|
83
|
+
* runtime value IS a ClientError.
|
|
84
|
+
*/
|
|
85
|
+
const asApiResponse = (p) => p;
|
|
86
|
+
const requestWithCache = async (method, path, rawQuery, fetchFn, cacheOptions) => {
|
|
87
|
+
const query = currentCv !== void 0 ? applyCvToQuery(rawQuery, currentCv) : rawQuery;
|
|
88
|
+
if (!shouldUseCache(method, path, rawQuery)) {
|
|
89
|
+
const networkResult = await fetchFn(query);
|
|
90
|
+
throttleManager.adaptToResponse(networkResult.response);
|
|
91
|
+
await updateCv(networkResult);
|
|
92
|
+
return networkResult;
|
|
93
|
+
}
|
|
94
|
+
const baseKey = createCacheKey(method, path, rawQuery);
|
|
95
|
+
const key = cacheOptions?.cacheKeyPrefix ? `${cacheOptions.cacheKeyPrefix}:${baseKey}` : baseKey;
|
|
96
|
+
const cachedResult = (await cacheProvider.get(key))?.value;
|
|
97
|
+
const loadNetwork = async () => {
|
|
98
|
+
const result = await fetchFn(query);
|
|
99
|
+
throttleManager.adaptToResponse(result.response);
|
|
100
|
+
return cacheSuccessResult(key, result);
|
|
101
|
+
};
|
|
102
|
+
return strategy({
|
|
103
|
+
key,
|
|
104
|
+
cachedResult,
|
|
105
|
+
loadNetwork
|
|
106
|
+
});
|
|
107
|
+
};
|
|
108
|
+
const request = async (method, path, options = {}) => {
|
|
109
|
+
const rawQuery = options.query || {};
|
|
110
|
+
return requestWithCache(method, path, rawQuery, (query) => {
|
|
111
|
+
return throttleManager.execute(path, rawQuery, () => requestNetwork(method, path, query, options));
|
|
112
|
+
});
|
|
113
|
+
};
|
|
114
|
+
const getRequest = (path, options = {}) => {
|
|
115
|
+
return request("GET", path, options);
|
|
116
|
+
};
|
|
117
|
+
const resourceDeps = {
|
|
118
|
+
client,
|
|
119
|
+
requestWithCache,
|
|
120
|
+
asApiResponse,
|
|
121
|
+
throttleManager
|
|
122
|
+
};
|
|
123
|
+
const stories = createStoriesResource({
|
|
124
|
+
...resourceDeps,
|
|
125
|
+
inlineRelations
|
|
126
|
+
});
|
|
127
|
+
/**
|
|
128
|
+
* Flush the in-memory cache and reset the tracked cv.
|
|
129
|
+
*
|
|
130
|
+
* Call this explicitly when `cache.flush` is set to `'manual'`, e.g. after
|
|
131
|
+
* receiving a Storyblok webhook event that signals content has changed.
|
|
132
|
+
*/
|
|
133
|
+
const flushCache = async () => {
|
|
134
|
+
await cacheProvider.flush();
|
|
135
|
+
currentCv = void 0;
|
|
136
|
+
};
|
|
137
|
+
return {
|
|
138
|
+
datasourceEntries: createDatasourceEntriesResource(resourceDeps),
|
|
139
|
+
datasources: createDatasourcesResource(resourceDeps),
|
|
140
|
+
flushCache,
|
|
141
|
+
get: getRequest,
|
|
142
|
+
interceptors: client.interceptors,
|
|
143
|
+
links: createLinksResource(resourceDeps),
|
|
144
|
+
spaces: createSpacesResource(resourceDeps),
|
|
145
|
+
stories,
|
|
146
|
+
tags: createTagsResource(resourceDeps)
|
|
147
|
+
};
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* Creates a Storyblok Content Delivery API client.
|
|
151
|
+
*
|
|
152
|
+
* Use `.withTypes<YourTypes>()` on the returned client to enable discriminated
|
|
153
|
+
* union typing on `story.content` without including any schema values in your bundle.
|
|
154
|
+
*
|
|
155
|
+
* @example
|
|
156
|
+
* ```ts
|
|
157
|
+
* import type { pageBlock, heroBlock } from './blocks';
|
|
158
|
+
*
|
|
159
|
+
* const client = createApiClient({ accessToken: 'your-token' })
|
|
160
|
+
* .withTypes<StoryblokTypes>();
|
|
161
|
+
* ```
|
|
162
|
+
*/
|
|
163
|
+
const createApiClient = (config) => {
|
|
164
|
+
const self = {
|
|
165
|
+
...createApiClientBase(config),
|
|
166
|
+
withTypes() {
|
|
167
|
+
return self;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
return self;
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
//#endregion
|
|
174
|
+
export { createApiClient };
|
|
175
|
+
//# sourceMappingURL=client.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.mjs","names":[],"sources":["../src/client.ts"],"sourcesContent":["import { createClient, createConfig } from './generated/shared/client';\nimport type { CacheProvider, CacheStrategy, CacheStrategyHandler } from './utils/cache';\nimport { createMemoryCacheProvider, createStrategy } from './utils/cache';\nimport { ClientError } from './error';\nimport type { RateLimitConfig, ThrottleManager } from './utils/rate-limit';\nimport { createThrottleManager } from './utils/rate-limit';\nimport { applyCvToQuery, extractCv } from './utils/cv';\nimport { createCacheKey, shouldUseCache } from './utils/request';\nimport { getRegionBaseUrl, type Region } from '@storyblok/region-helper';\nimport type { Block as Component } from '@storyblok/schema';\nimport type { RetryOptions } from 'ky';\nimport type { Client, RequestOptions } from './generated/shared/client';\nimport { createStoriesResource } from './resources/stories';\nimport { createLinksResource } from './resources/links';\nimport { createTagsResource } from './resources/tags';\nimport { createDatasourcesResource } from './resources/datasources';\nimport { createDatasourceEntriesResource } from './resources/datasource-entries';\nimport { createSpacesResource } from './resources/spaces';\n\n// ---------------------------------------------------------------------------\n// Client types (co-located with runtime)\n// ---------------------------------------------------------------------------\n\nexport type ApiResponse<Data = unknown, ThrowOnError extends boolean = false> =\n ThrowOnError extends true\n ? { data: Data; error?: never; response: Response; request: Request }\n : { data?: Data; error?: ClientError; response: Response; request: Request };\n\nexport type HttpRequestOptions = Omit<\n RequestOptions,\n 'method' | 'security' | 'url'\n>;\n\nexport type HttpRequestMethod = <TData = unknown>(\n path: string,\n options?: HttpRequestOptions,\n) => Promise<ApiResponse<TData>>;\n\n/**\n * Arbitrary options forwarded to the underlying `fetch()` call.\n *\n * Standard `RequestInit` properties (`cache`, `credentials`, `mode`, …) and\n * non-standard, vendor-specific properties (Next.js `next`, Cloudflare `cf`, …)\n * are both supported.\n *\n * @example\n * ```ts\n * client.stories.get('home', {\n * fetchOptions: {\n * cache: 'no-store',\n * next: { revalidate: 60, tags: ['home'] },\n * },\n * })\n * ```\n */\nexport type FetchOptions = Record<string, unknown>;\n\nexport interface RequestWithCacheOptions {\n /** Prefix added to the cache key to namespace entries (e.g. `'inline'`). */\n cacheKeyPrefix?: string;\n}\n\nexport interface ResourceDeps<DefaultThrowOnError extends boolean = false> {\n client: Client;\n requestWithCache: <TData, ThrowOnError extends boolean = DefaultThrowOnError>(\n method: 'GET',\n path: string,\n rawQuery: Record<string, unknown>,\n fetchFn: (query: Record<string, unknown>) => Promise<ApiResponse<TData, ThrowOnError>>,\n options?: RequestWithCacheOptions,\n ) => Promise<ApiResponse<TData, ThrowOnError>>;\n asApiResponse: <TData, ThrowOnError extends boolean = DefaultThrowOnError>(p: Promise<unknown>) => Promise<ApiResponse<TData, ThrowOnError>>;\n throttleManager: ThrottleManager;\n}\n\n// ---------------------------------------------------------------------------\n// Config types\n// ---------------------------------------------------------------------------\n\n/**\n * Cache configuration.\n *\n * **Note:** Requests with `version: 'draft'` always bypass the cache regardless\n * of the configured strategy. Only published content is cached.\n */\nexport interface CacheConfig {\n /** Custom cache provider. Defaults to an in-memory LRU cache (1 000 entries). */\n provider?: CacheProvider;\n /** Cache strategy for published requests. @default 'cache-first' */\n strategy?: CacheStrategy | CacheStrategyHandler;\n /** Time-to-live in milliseconds for cached entries. @default 60_000 */\n ttlMs?: number;\n /**\n * Controls when the cache is flushed on cv change.\n *\n * - `'auto'` (default): automatically flush the cache whenever the API returns a new cv value.\n * - `'manual'`: never auto-flush; call `client.flushCache()` explicitly (e.g. on webhook trigger).\n */\n flush?: 'auto' | 'manual';\n /**\n * Called when SWR background revalidation fails.\n * Only relevant when `strategy` is `'swr'`.\n * @default console.warn\n */\n onRevalidationError?: (error: unknown) => void;\n}\n\nexport interface ContentApiClientConfig<\n ThrowOnError extends boolean = false,\n InlineRelations extends boolean = false,\n> {\n accessToken: string;\n region?: Region;\n baseUrl?: string;\n headers?: Record<string, string>;\n throwOnError?: ThrowOnError;\n cache?: CacheConfig;\n inlineRelations?: InlineRelations;\n retry?: RetryOptions;\n /**\n * Request timeout in milliseconds.\n * @default 30_000\n */\n timeout?: number;\n /**\n * Preventive rate limiting to avoid hitting the Storyblok CDN rate limits.\n *\n * - `undefined` (default): auto-detect tier from path + `per_page` query param.\n * - `number`: fixed max concurrent requests per second (single queue).\n * - `{ maxConcurrency?: number; adaptToServerHeaders?: boolean }`: full config.\n * - `false`: disable rate limiting entirely.\n */\n rateLimit?: RateLimitConfig | number | false;\n /**\n * Custom `fetch` function to use for all requests.\n * Must be fully compatible with the Fetch API standard.\n *\n * Use cases:\n * - SSR framework fetch wrappers (e.g., Next.js `fetch` with caching)\n * - Custom instrumentation or logging around requests\n *\n * @default globalThis.fetch\n */\n fetch?: typeof globalThis.fetch;\n}\n\ntype StoryblokTypesConfig = { components: Component } | { blocks: Component };\n\ntype ResolveComponents<T extends StoryblokTypesConfig> =\n T extends { components: infer C extends Component } ? C\n : T extends { blocks: infer B extends Component } ? B\n : never;\n\n/**\n * The return type of `createApiClient`, parameterised by `TComponents` and `InlineRelations`\n * so that `.withTypes<T>()` can change the story response types without touching the\n * runtime object.\n */\nexport type ContentApiClient<\n TComponents extends Component = Component,\n InlineRelations extends boolean = false,\n ThrowOnError extends boolean = false,\n> = Omit<ReturnType<typeof createApiClientBase>, 'stories' | 'withTypes'> & {\n stories: ReturnType<typeof createStoriesResource<TComponents, InlineRelations, ThrowOnError>>;\n /**\n * Returns the same client instance cast to a version that narrows story content\n * to the provided component types. No runtime cost — the type parameter is erased.\n *\n * Accepts either `{ components: ... }` or `{ blocks: ... }` — the latter matches the\n * `Schema` type produced by `@storyblok/schema`'s `InferSchema`.\n *\n * @example\n * ```ts\n * import type { Schema } from './schema';\n *\n * const client = createApiClient({ accessToken: 'your-token' })\n * .withTypes<Schema>();\n * // story.content is now typed as a discriminated union\n * ```\n */\n withTypes: <T extends StoryblokTypesConfig>() => ContentApiClient<ResolveComponents<T>, InlineRelations, ThrowOnError>;\n};\n\n// ---------------------------------------------------------------------------\n// Client factory\n// ---------------------------------------------------------------------------\n\nexport const createApiClientBase = <\n ThrowOnError extends boolean = false,\n InlineRelations extends boolean = false,\n>(\n config: ContentApiClientConfig<ThrowOnError, InlineRelations>,\n) => {\n const {\n accessToken,\n region = 'eu',\n baseUrl,\n headers = {},\n throwOnError = false,\n cache = {},\n inlineRelations = false,\n retry,\n timeout = 30_000,\n rateLimit,\n fetch: customFetch,\n } = config;\n const retryOptions: RetryOptions = { limit: 3, backoffLimit: 20_000, jitter: true, ...retry };\n // `rateLimit` defaults to `{}` (auto-detect mode) when not supplied.\n const throttleManager = createThrottleManager(rateLimit ?? {});\n const cacheProvider = cache.provider ?? createMemoryCacheProvider();\n const swrOptions = cache.onRevalidationError ? { onRevalidationError: cache.onRevalidationError } : undefined;\n const strategy = cache.strategy\n ? typeof cache.strategy === 'string'\n ? createStrategy(cache.strategy, swrOptions)\n : cache.strategy\n : createStrategy('cache-first');\n const cacheTtlMs = cache.ttlMs ?? 60_000;\n const cacheFlush = cache.flush ?? 'auto';\n let currentCv: number | undefined;\n\n const client: Client = createClient(\n createConfig({\n auth: accessToken,\n baseUrl: baseUrl || getRegionBaseUrl(region),\n headers,\n throwOnError,\n kyOptions: {\n // Enable `throwHttpErrors` to make retry work, even if `throwOnError`\n // is `false`. The client's error handling will still work because it\n // catches `HTTPError`.\n throwHttpErrors: true,\n timeout,\n retry: retryOptions,\n ...(customFetch && { fetch: customFetch }),\n },\n }),\n );\n\n client.interceptors.error.use(\n (error: unknown, response: Response) =>\n new ClientError(response?.statusText || 'API request failed', {\n status: response?.status ?? 0,\n statusText: response?.statusText ?? '',\n data: error,\n }),\n );\n\n const security = [\n {\n in: 'query' as const,\n name: 'token',\n type: 'apiKey' as const,\n },\n ];\n\n const updateCv = async (result: ApiResponse): Promise<boolean> => {\n const nextCv = extractCv(result.data);\n if (nextCv === undefined) {\n return true;\n }\n\n // Guard against cv regression: SWR background revalidation may carry a\n // stale cv from a prior request; never move cv backward.\n if (currentCv !== undefined && nextCv < currentCv) {\n return false;\n }\n\n if (cacheFlush === 'auto' && currentCv !== undefined && currentCv !== nextCv) {\n await cacheProvider.flush();\n }\n\n currentCv = nextCv;\n return true;\n };\n\n const cacheSuccessResult = async <TResponse extends ApiResponse>(key: string, result: TResponse) => {\n const shouldCacheResult = await updateCv(result);\n if (result.error === undefined && shouldCacheResult) {\n await cacheProvider.set(key, {\n value: result,\n ttlMs: cacheTtlMs,\n });\n }\n return result;\n };\n\n const requestNetwork = async (\n method: 'GET',\n path: string,\n query: Record<string, unknown>,\n options: HttpRequestOptions,\n ): Promise<ApiResponse> => {\n return client.request<unknown, ClientError, boolean>({\n ...options,\n method,\n query,\n security,\n url: path,\n });\n };\n\n /**\n * Wraps a raw SDK call to cast the `error: unknown` type returned by\n * generated code to `ClientError` — the error interceptor ensures the\n * runtime value IS a ClientError.\n */\n const asApiResponse = <TData, ThrowOnError extends boolean = false>(\n p: Promise<unknown>,\n ): Promise<ApiResponse<TData, ThrowOnError>> => p as unknown as Promise<ApiResponse<TData, ThrowOnError>>;\n\n const requestWithCache = async <TData = unknown, ThrowOnError extends boolean = false>(\n method: 'GET',\n path: string,\n rawQuery: Record<string, unknown>,\n fetchFn: (query: Record<string, unknown>) => Promise<ApiResponse<TData, ThrowOnError>>,\n cacheOptions?: RequestWithCacheOptions,\n ): Promise<ApiResponse<TData, ThrowOnError>> => {\n const query = currentCv !== undefined ? applyCvToQuery(rawQuery, currentCv) : rawQuery;\n const cacheEnabled = shouldUseCache(method, path, rawQuery);\n\n if (!cacheEnabled) {\n const networkResult = await fetchFn(query);\n throttleManager.adaptToResponse(networkResult.response);\n await updateCv(networkResult);\n return networkResult;\n }\n\n const baseKey = createCacheKey(method, path, rawQuery);\n const key = cacheOptions?.cacheKeyPrefix ? `${cacheOptions.cacheKeyPrefix}:${baseKey}` : baseKey;\n const cachedEntry = await cacheProvider.get<ApiResponse<TData, ThrowOnError>>(key);\n const cachedResult = cachedEntry?.value;\n\n const loadNetwork = async () => {\n const result = await fetchFn(query);\n throttleManager.adaptToResponse(result.response);\n return cacheSuccessResult(key, result);\n };\n\n return strategy({\n key,\n cachedResult,\n loadNetwork,\n });\n };\n\n const request = async (\n method: 'GET',\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse> => {\n const rawQuery = options.query || {};\n\n return requestWithCache(method, path, rawQuery, (query) => {\n return throttleManager.execute(path, rawQuery, () => requestNetwork(method, path, query, options));\n });\n };\n\n const getRequest = (\n path: string,\n options: HttpRequestOptions = {},\n ) => {\n return request('GET', path, options);\n };\n\n const resourceDeps: ResourceDeps<ThrowOnError> = {\n client,\n requestWithCache,\n asApiResponse,\n throttleManager,\n };\n\n const stories = createStoriesResource<Component, InlineRelations, ThrowOnError>({\n ...resourceDeps,\n inlineRelations,\n });\n\n /**\n * Flush the in-memory cache and reset the tracked cv.\n *\n * Call this explicitly when `cache.flush` is set to `'manual'`, e.g. after\n * receiving a Storyblok webhook event that signals content has changed.\n */\n const flushCache = async (): Promise<void> => {\n await cacheProvider.flush();\n currentCv = undefined;\n };\n\n return {\n datasourceEntries: createDatasourceEntriesResource(resourceDeps),\n datasources: createDatasourcesResource(resourceDeps),\n flushCache,\n get: getRequest,\n interceptors: client.interceptors,\n links: createLinksResource(resourceDeps),\n spaces: createSpacesResource(resourceDeps),\n stories,\n tags: createTagsResource(resourceDeps),\n };\n};\n\n/**\n * Creates a Storyblok Content Delivery API client.\n *\n * Use `.withTypes<YourTypes>()` on the returned client to enable discriminated\n * union typing on `story.content` without including any schema values in your bundle.\n *\n * @example\n * ```ts\n * import type { pageBlock, heroBlock } from './blocks';\n *\n * const client = createApiClient({ accessToken: 'your-token' })\n * .withTypes<StoryblokTypes>();\n * ```\n */\nexport const createApiClient = <\n ThrowOnError extends boolean = false,\n InlineRelations extends boolean = false,\n>(\n config: ContentApiClientConfig<ThrowOnError, InlineRelations>,\n): ContentApiClient<Component, InlineRelations, ThrowOnError> => {\n const base = createApiClientBase(config);\n const self: ContentApiClient<Component, InlineRelations, ThrowOnError> = {\n ...base,\n withTypes<T extends StoryblokTypesConfig>(): ContentApiClient<ResolveComponents<T>, InlineRelations, ThrowOnError> {\n return self as unknown as ContentApiClient<ResolveComponents<T>, InlineRelations, ThrowOnError>;\n },\n };\n return self;\n};\n"],"mappings":"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"}
|
package/dist/error.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.cjs","names":[],"sources":["../src/error.ts"],"sourcesContent":["/**\n * Structured HTTP error thrown by the Content API client when `throwOnError: true`.\n */\nexport class ClientError extends Error {\n readonly response: { status: number; statusText: string; data:
|
|
1
|
+
{"version":3,"file":"error.cjs","names":[],"sources":["../src/error.ts"],"sourcesContent":["/**\n * Common shape of error bodies returned by the Storyblok Content Delivery API.\n *\n * Most error responses include an `error` or `message` field with a\n * human-readable description.\n */\nexport interface ApiErrorBody {\n error?: string;\n message?: string;\n [key: string]: unknown;\n}\n\n/**\n * Structured HTTP error thrown by the Content API client when `throwOnError: true`.\n */\nexport class ClientError extends Error {\n readonly response: { status: number; statusText: string; data: ApiErrorBody | undefined };\n\n constructor(\n message: string,\n options: { status: number; statusText: string; data: unknown },\n ) {\n super(message);\n this.name = 'ClientError';\n this.response = {\n status: options.status,\n statusText: options.statusText,\n data: options.data as ApiErrorBody | undefined,\n };\n }\n}\n"],"mappings":";;;;;AAeA,IAAa,cAAb,cAAiC,MAAM;CACrC,AAAS;CAET,YACE,SACA,SACA;AACA,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,WAAW;GACd,QAAQ,QAAQ;GAChB,YAAY,QAAQ;GACpB,MAAM,QAAQ;GACf"}
|
package/dist/error.d.cts
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
1
1
|
//#region src/error.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Common shape of error bodies returned by the Storyblok Content Delivery API.
|
|
4
|
+
*
|
|
5
|
+
* Most error responses include an `error` or `message` field with a
|
|
6
|
+
* human-readable description.
|
|
7
|
+
*/
|
|
8
|
+
interface ApiErrorBody {
|
|
9
|
+
error?: string;
|
|
10
|
+
message?: string;
|
|
11
|
+
[key: string]: unknown;
|
|
12
|
+
}
|
|
2
13
|
/**
|
|
3
14
|
* Structured HTTP error thrown by the Content API client when `throwOnError: true`.
|
|
4
15
|
*/
|
|
@@ -6,7 +17,7 @@ declare class ClientError extends Error {
|
|
|
6
17
|
readonly response: {
|
|
7
18
|
status: number;
|
|
8
19
|
statusText: string;
|
|
9
|
-
data:
|
|
20
|
+
data: ApiErrorBody | undefined;
|
|
10
21
|
};
|
|
11
22
|
constructor(message: string, options: {
|
|
12
23
|
status: number;
|
|
@@ -15,5 +26,5 @@ declare class ClientError extends Error {
|
|
|
15
26
|
});
|
|
16
27
|
}
|
|
17
28
|
//#endregion
|
|
18
|
-
export { ClientError };
|
|
29
|
+
export { ApiErrorBody, ClientError };
|
|
19
30
|
//# sourceMappingURL=error.d.cts.map
|
package/dist/error.d.mts
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
1
1
|
//#region src/error.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Common shape of error bodies returned by the Storyblok Content Delivery API.
|
|
4
|
+
*
|
|
5
|
+
* Most error responses include an `error` or `message` field with a
|
|
6
|
+
* human-readable description.
|
|
7
|
+
*/
|
|
8
|
+
interface ApiErrorBody {
|
|
9
|
+
error?: string;
|
|
10
|
+
message?: string;
|
|
11
|
+
[key: string]: unknown;
|
|
12
|
+
}
|
|
2
13
|
/**
|
|
3
14
|
* Structured HTTP error thrown by the Content API client when `throwOnError: true`.
|
|
4
15
|
*/
|
|
@@ -6,7 +17,7 @@ declare class ClientError extends Error {
|
|
|
6
17
|
readonly response: {
|
|
7
18
|
status: number;
|
|
8
19
|
statusText: string;
|
|
9
|
-
data:
|
|
20
|
+
data: ApiErrorBody | undefined;
|
|
10
21
|
};
|
|
11
22
|
constructor(message: string, options: {
|
|
12
23
|
status: number;
|
|
@@ -15,5 +26,5 @@ declare class ClientError extends Error {
|
|
|
15
26
|
});
|
|
16
27
|
}
|
|
17
28
|
//#endregion
|
|
18
|
-
export { ClientError };
|
|
29
|
+
export { ApiErrorBody, ClientError };
|
|
19
30
|
//# sourceMappingURL=error.d.mts.map
|
package/dist/error.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.mjs","names":[],"sources":["../src/error.ts"],"sourcesContent":["/**\n * Structured HTTP error thrown by the Content API client when `throwOnError: true`.\n */\nexport class ClientError extends Error {\n readonly response: { status: number; statusText: string; data:
|
|
1
|
+
{"version":3,"file":"error.mjs","names":[],"sources":["../src/error.ts"],"sourcesContent":["/**\n * Common shape of error bodies returned by the Storyblok Content Delivery API.\n *\n * Most error responses include an `error` or `message` field with a\n * human-readable description.\n */\nexport interface ApiErrorBody {\n error?: string;\n message?: string;\n [key: string]: unknown;\n}\n\n/**\n * Structured HTTP error thrown by the Content API client when `throwOnError: true`.\n */\nexport class ClientError extends Error {\n readonly response: { status: number; statusText: string; data: ApiErrorBody | undefined };\n\n constructor(\n message: string,\n options: { status: number; statusText: string; data: unknown },\n ) {\n super(message);\n this.name = 'ClientError';\n this.response = {\n status: options.status,\n statusText: options.statusText,\n data: options.data as ApiErrorBody | undefined,\n };\n }\n}\n"],"mappings":";;;;AAeA,IAAa,cAAb,cAAiC,MAAM;CACrC,AAAS;CAET,YACE,SACA,SACA;AACA,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,WAAW;GACd,QAAQ,QAAQ;GAChB,YAAY,QAAQ;GACpB,MAAM,QAAQ;GACf"}
|
|
@@ -47,21 +47,6 @@ type ListData = {
|
|
|
47
47
|
};
|
|
48
48
|
url: '/v2/cdn/datasource_entries';
|
|
49
49
|
};
|
|
50
|
-
type ListResponses = {
|
|
51
|
-
/**
|
|
52
|
-
* Array of datasource entries
|
|
53
|
-
*/
|
|
54
|
-
200: {
|
|
55
|
-
/**
|
|
56
|
-
* Array of datasource entry objects
|
|
57
|
-
*/
|
|
58
|
-
datasource_entries: Array<DatasourceEntryCapi>;
|
|
59
|
-
/**
|
|
60
|
-
* Cache version Unix timestamp
|
|
61
|
-
*/
|
|
62
|
-
cv?: number | null;
|
|
63
|
-
};
|
|
64
|
-
};
|
|
65
50
|
//#endregion
|
|
66
|
-
export { DatasourceEntryCapi, ListData
|
|
51
|
+
export { DatasourceEntryCapi, ListData };
|
|
67
52
|
//# sourceMappingURL=types.gen.d.cts.map
|
|
@@ -47,21 +47,6 @@ type ListData = {
|
|
|
47
47
|
};
|
|
48
48
|
url: '/v2/cdn/datasource_entries';
|
|
49
49
|
};
|
|
50
|
-
type ListResponses = {
|
|
51
|
-
/**
|
|
52
|
-
* Array of datasource entries
|
|
53
|
-
*/
|
|
54
|
-
200: {
|
|
55
|
-
/**
|
|
56
|
-
* Array of datasource entry objects
|
|
57
|
-
*/
|
|
58
|
-
datasource_entries: Array<DatasourceEntryCapi>;
|
|
59
|
-
/**
|
|
60
|
-
* Cache version Unix timestamp
|
|
61
|
-
*/
|
|
62
|
-
cv?: number | null;
|
|
63
|
-
};
|
|
64
|
-
};
|
|
65
50
|
//#endregion
|
|
66
|
-
export { DatasourceEntryCapi, ListData
|
|
51
|
+
export { DatasourceEntryCapi, ListData };
|
|
67
52
|
//# sourceMappingURL=types.gen.d.mts.map
|