@storyblok/api-client 0.2.4 → 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.
Files changed (61) hide show
  1. package/dist/client.cjs +176 -0
  2. package/dist/client.cjs.map +1 -0
  3. package/dist/client.d.cts +333 -0
  4. package/dist/client.d.mts +333 -0
  5. package/dist/client.mjs +175 -0
  6. package/dist/client.mjs.map +1 -0
  7. package/dist/error.cjs.map +1 -1
  8. package/dist/error.d.cts +13 -2
  9. package/dist/error.d.mts +13 -2
  10. package/dist/error.mjs.map +1 -1
  11. package/dist/generated/datasource_entries/types.gen.d.cts +1 -16
  12. package/dist/generated/datasource_entries/types.gen.d.mts +1 -16
  13. package/dist/generated/datasources/types.gen.d.cts +1 -28
  14. package/dist/generated/datasources/types.gen.d.mts +1 -28
  15. package/dist/generated/links/types.gen.d.cts +1 -18
  16. package/dist/generated/links/types.gen.d.mts +1 -18
  17. package/dist/generated/shared/client/index.d.mts +1 -1
  18. package/dist/generated/shared/client/types.gen.d.cts +39 -3
  19. package/dist/generated/shared/client/types.gen.d.mts +39 -3
  20. package/dist/generated/shared/core/serverSentEvents.gen.d.cts +4 -1
  21. package/dist/generated/shared/core/serverSentEvents.gen.d.mts +4 -1
  22. package/dist/generated/shared/core/types.gen.d.cts +14 -1
  23. package/dist/generated/shared/core/types.gen.d.mts +14 -1
  24. package/dist/generated/spaces/types.gen.d.cts +1 -9
  25. package/dist/generated/spaces/types.gen.d.mts +1 -9
  26. package/dist/generated/stories/index.d.mts +1 -1
  27. package/dist/generated/stories/types.gen.d.cts +72 -9
  28. package/dist/generated/stories/types.gen.d.mts +72 -9
  29. package/dist/generated/tags/types.gen.d.cts +1 -16
  30. package/dist/generated/tags/types.gen.d.mts +1 -16
  31. package/dist/index.cjs +2 -153
  32. package/dist/index.d.cts +4 -172
  33. package/dist/index.d.mts +4 -172
  34. package/dist/index.mjs +2 -150
  35. package/dist/resources/datasource-entries.cjs.map +1 -1
  36. package/dist/resources/datasource-entries.mjs.map +1 -1
  37. package/dist/resources/datasources.cjs.map +1 -1
  38. package/dist/resources/datasources.mjs.map +1 -1
  39. package/dist/resources/links.cjs.map +1 -1
  40. package/dist/resources/links.mjs.map +1 -1
  41. package/dist/resources/spaces.cjs.map +1 -1
  42. package/dist/resources/spaces.mjs.map +1 -1
  43. package/dist/resources/stories.cjs +6 -4
  44. package/dist/resources/stories.cjs.map +1 -1
  45. package/dist/resources/stories.d.cts +78 -3
  46. package/dist/resources/stories.d.mts +79 -3
  47. package/dist/resources/stories.mjs +6 -4
  48. package/dist/resources/stories.mjs.map +1 -1
  49. package/dist/resources/tags.cjs.map +1 -1
  50. package/dist/resources/tags.mjs.map +1 -1
  51. package/dist/utils/rate-limit.cjs +9 -5
  52. package/dist/utils/rate-limit.cjs.map +1 -1
  53. package/dist/utils/rate-limit.d.cts +4 -18
  54. package/dist/utils/rate-limit.d.mts +4 -18
  55. package/dist/utils/rate-limit.mjs +10 -4
  56. package/dist/utils/rate-limit.mjs.map +1 -1
  57. package/package.json +18 -8
  58. package/dist/index.cjs.map +0 -1
  59. package/dist/index.mjs.map +0 -1
  60. package/dist/types.d.cts +0 -37
  61. package/dist/types.d.mts +0 -37
@@ -0,0 +1,176 @@
1
+ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
2
+ const require_utils_gen = require('./generated/shared/client/utils.gen.cjs');
3
+ const require_client_gen = require('./generated/shared/client/client.gen.cjs');
4
+ require('./generated/shared/client/index.cjs');
5
+ const require_cache = require('./utils/cache.cjs');
6
+ const require_error = require('./error.cjs');
7
+ const require_rate_limit = require('./utils/rate-limit.cjs');
8
+ const require_request = require('./utils/request.cjs');
9
+ const require_cv = require('./utils/cv.cjs');
10
+ const require_stories = require('./resources/stories.cjs');
11
+ const require_links = require('./resources/links.cjs');
12
+ const require_tags = require('./resources/tags.cjs');
13
+ const require_datasources = require('./resources/datasources.cjs');
14
+ const require_datasource_entries = require('./resources/datasource-entries.cjs');
15
+ const require_spaces = require('./resources/spaces.cjs');
16
+ let _storyblok_region_helper = require("@storyblok/region-helper");
17
+
18
+ //#region src/client.ts
19
+ const createApiClientBase = (config) => {
20
+ const { accessToken, region = "eu", baseUrl, headers = {}, throwOnError = false, cache = {}, inlineRelations = false, retry, timeout = 3e4, rateLimit, fetch: customFetch } = config;
21
+ const retryOptions = {
22
+ limit: 3,
23
+ backoffLimit: 2e4,
24
+ jitter: true,
25
+ ...retry
26
+ };
27
+ const throttleManager = require_rate_limit.createThrottleManager(rateLimit ?? {});
28
+ const cacheProvider = cache.provider ?? require_cache.createMemoryCacheProvider();
29
+ const swrOptions = cache.onRevalidationError ? { onRevalidationError: cache.onRevalidationError } : void 0;
30
+ const strategy = cache.strategy ? typeof cache.strategy === "string" ? require_cache.createStrategy(cache.strategy, swrOptions) : cache.strategy : require_cache.createStrategy("cache-first");
31
+ const cacheTtlMs = cache.ttlMs ?? 6e4;
32
+ const cacheFlush = cache.flush ?? "auto";
33
+ let currentCv;
34
+ const client = require_client_gen.createClient(require_utils_gen.createConfig({
35
+ auth: accessToken,
36
+ baseUrl: baseUrl || (0, _storyblok_region_helper.getRegionBaseUrl)(region),
37
+ headers,
38
+ throwOnError,
39
+ kyOptions: {
40
+ throwHttpErrors: true,
41
+ timeout,
42
+ retry: retryOptions,
43
+ ...customFetch && { fetch: customFetch }
44
+ }
45
+ }));
46
+ client.interceptors.error.use((error, response) => new require_error.ClientError(response?.statusText || "API request failed", {
47
+ status: response?.status ?? 0,
48
+ statusText: response?.statusText ?? "",
49
+ data: error
50
+ }));
51
+ const security = [{
52
+ in: "query",
53
+ name: "token",
54
+ type: "apiKey"
55
+ }];
56
+ const updateCv = async (result) => {
57
+ const nextCv = require_cv.extractCv(result.data);
58
+ if (nextCv === void 0) return true;
59
+ if (currentCv !== void 0 && nextCv < currentCv) return false;
60
+ if (cacheFlush === "auto" && currentCv !== void 0 && currentCv !== nextCv) await cacheProvider.flush();
61
+ currentCv = nextCv;
62
+ return true;
63
+ };
64
+ const cacheSuccessResult = async (key, result) => {
65
+ const shouldCacheResult = await updateCv(result);
66
+ if (result.error === void 0 && shouldCacheResult) await cacheProvider.set(key, {
67
+ value: result,
68
+ ttlMs: cacheTtlMs
69
+ });
70
+ return result;
71
+ };
72
+ const requestNetwork = async (method, path, query, options) => {
73
+ return client.request({
74
+ ...options,
75
+ method,
76
+ query,
77
+ security,
78
+ url: path
79
+ });
80
+ };
81
+ /**
82
+ * Wraps a raw SDK call to cast the `error: unknown` type returned by
83
+ * generated code to `ClientError` — the error interceptor ensures the
84
+ * runtime value IS a ClientError.
85
+ */
86
+ const asApiResponse = (p) => p;
87
+ const requestWithCache = async (method, path, rawQuery, fetchFn, cacheOptions) => {
88
+ const query = currentCv !== void 0 ? require_cv.applyCvToQuery(rawQuery, currentCv) : rawQuery;
89
+ if (!require_request.shouldUseCache(method, path, rawQuery)) {
90
+ const networkResult = await fetchFn(query);
91
+ throttleManager.adaptToResponse(networkResult.response);
92
+ await updateCv(networkResult);
93
+ return networkResult;
94
+ }
95
+ const baseKey = require_request.createCacheKey(method, path, rawQuery);
96
+ const key = cacheOptions?.cacheKeyPrefix ? `${cacheOptions.cacheKeyPrefix}:${baseKey}` : baseKey;
97
+ const cachedResult = (await cacheProvider.get(key))?.value;
98
+ const loadNetwork = async () => {
99
+ const result = await fetchFn(query);
100
+ throttleManager.adaptToResponse(result.response);
101
+ return cacheSuccessResult(key, result);
102
+ };
103
+ return strategy({
104
+ key,
105
+ cachedResult,
106
+ loadNetwork
107
+ });
108
+ };
109
+ const request = async (method, path, options = {}) => {
110
+ const rawQuery = options.query || {};
111
+ return requestWithCache(method, path, rawQuery, (query) => {
112
+ return throttleManager.execute(path, rawQuery, () => requestNetwork(method, path, query, options));
113
+ });
114
+ };
115
+ const getRequest = (path, options = {}) => {
116
+ return request("GET", path, options);
117
+ };
118
+ const resourceDeps = {
119
+ client,
120
+ requestWithCache,
121
+ asApiResponse,
122
+ throttleManager
123
+ };
124
+ const stories = require_stories.createStoriesResource({
125
+ ...resourceDeps,
126
+ inlineRelations
127
+ });
128
+ /**
129
+ * Flush the in-memory cache and reset the tracked cv.
130
+ *
131
+ * Call this explicitly when `cache.flush` is set to `'manual'`, e.g. after
132
+ * receiving a Storyblok webhook event that signals content has changed.
133
+ */
134
+ const flushCache = async () => {
135
+ await cacheProvider.flush();
136
+ currentCv = void 0;
137
+ };
138
+ return {
139
+ datasourceEntries: require_datasource_entries.createDatasourceEntriesResource(resourceDeps),
140
+ datasources: require_datasources.createDatasourcesResource(resourceDeps),
141
+ flushCache,
142
+ get: getRequest,
143
+ interceptors: client.interceptors,
144
+ links: require_links.createLinksResource(resourceDeps),
145
+ spaces: require_spaces.createSpacesResource(resourceDeps),
146
+ stories,
147
+ tags: require_tags.createTagsResource(resourceDeps)
148
+ };
149
+ };
150
+ /**
151
+ * Creates a Storyblok Content Delivery API client.
152
+ *
153
+ * Use `.withTypes<YourTypes>()` on the returned client to enable discriminated
154
+ * union typing on `story.content` without including any schema values in your bundle.
155
+ *
156
+ * @example
157
+ * ```ts
158
+ * import type { pageBlock, heroBlock } from './blocks';
159
+ *
160
+ * const client = createApiClient({ accessToken: 'your-token' })
161
+ * .withTypes<StoryblokTypes>();
162
+ * ```
163
+ */
164
+ const createApiClient = (config) => {
165
+ const self = {
166
+ ...createApiClientBase(config),
167
+ withTypes() {
168
+ return self;
169
+ }
170
+ };
171
+ return self;
172
+ };
173
+
174
+ //#endregion
175
+ exports.createApiClient = createApiClient;
176
+ //# sourceMappingURL=client.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.cjs","names":["createThrottleManager","createMemoryCacheProvider","createStrategy","createClient","createConfig","ClientError","extractCv","applyCvToQuery","shouldUseCache","createCacheKey","createStoriesResource","createDatasourceEntriesResource","createDatasourcesResource","createLinksResource","createSpacesResource","createTagsResource"],"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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OAAO,MAAM,QAAQ;;CAGtC,MAAM,eAA2C;EAC/C;EACA;EACA;EACA;EACD;CAED,MAAM,UAAUC,sCAAgE;EAC9E,GAAG;EACH;EACD,CAAC;;;;;;;CAQF,MAAM,aAAa,YAA2B;AAC5C,QAAM,cAAc,OAAO;AAC3B,cAAY;;AAGd,QAAO;EACL,mBAAmBC,2DAAgC,aAAa;EAChE,aAAaC,8CAA0B,aAAa;EACpD;EACA,KAAK;EACL,cAAc,OAAO;EACrB,OAAOC,kCAAoB,aAAa;EACxC,QAAQC,oCAAqB,aAAa;EAC1C;EACA,MAAMC,gCAAmB,aAAa;EACvC;;;;;;;;;;;;;;;;AAiBH,MAAa,mBAIX,WAC+D;CAE/D,MAAM,OAAmE;EACvE,GAFW,oBAAoB,OAAO;EAGtC,YAAmH;AACjH,UAAO;;EAEV;AACD,QAAO"}
@@ -0,0 +1,333 @@
1
+ import { DatasourceEntryCapi, ListData } from "./generated/datasource_entries/types.gen.cjs";
2
+ import { DatasourceCapi, GetData, ListData as ListData$1 } from "./generated/datasources/types.gen.cjs";
3
+ import { Middleware } from "./generated/shared/client/utils.gen.cjs";
4
+ import { Client, RequestOptions, ResolvedRequestOptions } from "./generated/shared/client/types.gen.cjs";
5
+ import { LinkCapi, ListData as ListData$2 } from "./generated/links/types.gen.cjs";
6
+ import { SpaceCapi } from "./generated/spaces/types.gen.cjs";
7
+ import { StoryCapi } from "./generated/stories/types.gen.cjs";
8
+ import { ListData as ListData$3, TagCapi } from "./generated/tags/types.gen.cjs";
9
+ import { CacheProvider, CacheStrategy, CacheStrategyHandler } from "./utils/cache.cjs";
10
+ import { ClientError } from "./error.cjs";
11
+ import { RateLimitConfig, ThrottleManager } from "./utils/rate-limit.cjs";
12
+ import { StoryWithInlinedRelations, createStoriesResource } from "./resources/stories.cjs";
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.cts.map