@storyblok/management-api-client 0.6.0 → 0.6.2
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/README.md +1 -3
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +3 -3
- package/dist/client.d.mts +3 -3
- package/dist/client.mjs.map +1 -1
- package/dist/utils/rate-limit.cjs +3 -7
- package/dist/utils/rate-limit.cjs.map +1 -1
- package/dist/utils/rate-limit.mjs +3 -6
- package/dist/utils/rate-limit.mjs.map +1 -1
- package/dist/utils/throttle.cjs +57 -0
- package/dist/utils/throttle.cjs.map +1 -0
- package/dist/utils/throttle.mjs +56 -0
- package/dist/utils/throttle.mjs.map +1 -0
- package/package.json +1 -2
package/README.md
CHANGED
|
@@ -38,9 +38,7 @@
|
|
|
38
38
|
|
|
39
39
|
## Documentation
|
|
40
40
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
Full package documentation is coming soon. For now, browse the [package source on GitHub](https://github.com/storyblok/monoblok/tree/alpha/packages/mapi-client) or see it used in the [Astro playground](https://github.com/storyblok/monoblok/tree/alpha/packages/schema/playground/astro).
|
|
41
|
+
For complete documentation, please visit the [package reference](https://www.storyblok.com/docs/libraries/js/management-api-client).
|
|
44
42
|
|
|
45
43
|
## Contributing
|
|
46
44
|
|
package/dist/client.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.cjs","names":["createThrottleManager","createClient","createConfig","ClientError","createAssetFoldersResource","createAssetsResource","createComponentFoldersResource","createDatasourceEntriesResource","createDatasourcesResource","createExperimentsResource","createInternalTagsResource","createPresetsResource","createSharedAssetFoldersResource","createSharedAssetsResource","createSharedInternalTagsResource","createSpacesResource","createUsersResource","createComponentsResource","createStoriesResource"],"sources":["../src/client.ts"],"sourcesContent":["import type { Client, ResolvedRequestOptions, RetryOptions } from './generated/mapi/client';\nimport type { Middleware } from './generated/mapi/client/utils.gen';\nimport { createClient, createConfig } from './generated/mapi/client';\nimport { getManagementBaseUrl } from '@storyblok/region-helper';\nimport type { Region } from '@storyblok/region-helper';\nimport type { Block } from './generated/types/block';\nimport { ClientError } from './error';\nimport type { RateLimitConfig } from './utils/rate-limit';\nimport { createThrottleManager } from './utils/rate-limit';\nimport { querySerializer } from './utils/query-serializer';\nimport { createAssetFoldersResource } from './resources/asset-folders';\nimport { createAssetsResource } from './resources/assets';\nimport { createComponentFoldersResource } from './resources/component-folders';\nimport { createComponentsResource } from './resources/components';\nimport { createDatasourceEntriesResource } from './resources/datasource-entries';\nimport { createDatasourcesResource } from './resources/datasources';\nimport { createExperimentsResource } from './resources/experiments';\nimport { createInternalTagsResource } from './resources/internal-tags';\nimport { createPresetsResource } from './resources/presets';\nimport { createSharedAssetFoldersResource } from './resources/shared-asset-folders';\nimport { createSharedAssetsResource } from './resources/shared-assets';\nimport { createSharedInternalTagsResource } from './resources/shared-internal-tags';\nimport { createSpacesResource } from './resources/spaces';\nimport { createStoriesResource } from './resources/stories';\nimport { createUsersResource } from './resources/users';\n\n// ---------------------------------------------------------------------------\n// Client types (co-located with runtime)\n// ---------------------------------------------------------------------------\n\nexport type ApiResponse<T, ThrowOnError extends boolean = false> =\n ThrowOnError extends true\n ? { data: T; error?: never; response: Response; request: Request }\n : | { data: T; error: undefined; response: Response; request: Request }\n | { data: undefined; error: ClientError; response: Response; request: Request };\n\nexport interface RequestConfigOverrides {\n throwOnError?: boolean;\n}\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(123, {\n * fetchOptions: {\n * cache: 'no-store',\n * next: { revalidate: 60 },\n * },\n * })\n * ```\n */\nexport type FetchOptions = Record<string, unknown>;\n\nexport interface HttpRequestOptions {\n query?: Record<string, unknown>;\n body?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n throwOnError?: RequestConfigOverrides['throwOnError'];\n fetchOptions?: FetchOptions;\n}\n\n/**\n * Dependencies injected into every resource factory.\n */\nexport interface MapiResourceDeps<DefaultThrowOnError extends boolean = false> {\n client: Client;\n spaceId?: number;\n wrapRequest: <TData, ThrowOnError extends boolean = DefaultThrowOnError>(fn: () => Promise<unknown>, throwOnError?: ThrowOnError) => Promise<ApiResponse<TData, ThrowOnError>>;\n}\n\ntype TokenConfig =\n | {\n /** Personal access token for authentication. */\n personalAccessToken: string;\n oauthToken?: never;\n }\n | {\n personalAccessToken?: never;\n /** OAuth bearer token for authentication. */\n oauthToken: string;\n }\n | {\n personalAccessToken?: undefined;\n oauthToken?: undefined;\n };\n\nexport type ManagementApiClientConfig<\n ThrowOnError extends boolean = false,\n> = TokenConfig & {\n /**\n * The Storyblok space ID. Used as the default for space-scoped endpoints.\n * You can also override it per request via `path.space_id`.\n */\n spaceId?: number;\n /**\n * Storyblok region. Determines the base URL.\n * @default 'eu'\n */\n region?: Region;\n /**\n * Override the base URL entirely (e.g. for testing).\n */\n baseUrl?: string;\n /**\n * Additional request headers.\n */\n headers?: Record<string, string>;\n /**\n * Throw on HTTP errors instead of returning them.\n * @default false\n */\n throwOnError?: ThrowOnError;\n /**\n * Retry configuration for failed requests.\n */\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 Management API rate limits.\n *\n * - `undefined` (default): single bucket at maxConcurrency: 6.\n * - `number`: fixed max concurrent requests per second.\n * - `{ maxConcurrency?: number; adaptToServerHeaders?: boolean }`: full config.\n * - `false`: disable rate limiting entirely.\n */\n rateLimit?: RateLimitConfig | number | false;\n};\n\n// ---------------------------------------------------------------------------\n// Client factory\n// ---------------------------------------------------------------------------\n\nfunction getAuthorizationHeader(config: ManagementApiClientConfig<boolean>): string | undefined {\n if (config.personalAccessToken) {\n return config.personalAccessToken;\n }\n if (config.oauthToken) {\n return config.oauthToken.startsWith('Bearer ')\n ? config.oauthToken\n : `Bearer ${config.oauthToken}`;\n }\n return undefined;\n}\n\nconst createManagementApiClientBase = <DefaultThrowOnError extends boolean = false>(\n config: ManagementApiClientConfig<DefaultThrowOnError>,\n): {\n deps: MapiResourceDeps<DefaultThrowOnError>;\n resources: Omit<ReturnType<typeof buildResources<DefaultThrowOnError>>, never>;\n} => {\n const {\n spaceId,\n region = 'eu',\n baseUrl,\n headers = {},\n throwOnError = false,\n retry = {\n limit: 12,\n backoffLimit: 20_000,\n methods: ['get', 'post', 'put', 'delete', 'patch', 'head', 'options', 'trace'],\n statusCodes: [429],\n },\n timeout = 30_000,\n rateLimit,\n } = config;\n\n const throttleManager = createThrottleManager(rateLimit ?? {});\n const authHeader = getAuthorizationHeader(config);\n\n const client: Client = createClient(\n createConfig({\n baseUrl: baseUrl || getManagementBaseUrl(region),\n headers: {\n ...(authHeader ? { Authorization: authHeader } : {}),\n ...headers,\n },\n // Default serializer throws on nested objects; MAPI needs `filter_query`\n // serialized as a nested hash (`filter_query[field][op]=value`).\n querySerializer,\n throwOnError,\n kyOptions: {\n throwHttpErrors: true,\n timeout,\n retry,\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 function wrapRequest<TData, CurrentThrowOnError extends boolean = DefaultThrowOnError>(\n fn: () => Promise<unknown>,\n _throwOnError?: CurrentThrowOnError,\n ): Promise<ApiResponse<TData, CurrentThrowOnError>> {\n return throttleManager.execute(\n () => fn() as Promise<ApiResponse<TData, CurrentThrowOnError>>,\n );\n }\n\n const deps: MapiResourceDeps<DefaultThrowOnError> = { client, spaceId, wrapRequest };\n return { deps, resources: buildResources(deps, client) };\n};\n\nfunction buildResources<DefaultThrowOnError extends boolean = false>(\n deps: MapiResourceDeps<DefaultThrowOnError>,\n client: Client,\n) {\n /**\n * Escape hatch: send a GET request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpGet = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.get({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a POST request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpPost = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.post({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a PUT request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpPut = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.put({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a PATCH request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpPatch = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.patch({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a DELETE request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpDelete = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.delete({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n return {\n assetFolders: createAssetFoldersResource(deps),\n assets: createAssetsResource(deps),\n componentFolders: createComponentFoldersResource(deps),\n datasourceEntries: createDatasourceEntriesResource(deps),\n datasources: createDatasourcesResource(deps),\n experiments: createExperimentsResource(deps),\n delete: httpDelete,\n get: httpGet,\n patch: httpPatch,\n interceptors: client.interceptors as Middleware<Request, Response, unknown, ResolvedRequestOptions>,\n internalTags: createInternalTagsResource(deps),\n post: httpPost,\n presets: createPresetsResource(deps),\n put: httpPut,\n sharedAssetFolders: createSharedAssetFoldersResource(deps),\n sharedAssets: createSharedAssetsResource(deps),\n sharedInternalTags: createSharedInternalTagsResource(deps),\n spaces: createSpacesResource(deps),\n users: createUsersResource<DefaultThrowOnError>({ client, wrapRequest: deps.wrapRequest }),\n };\n}\n\ntype StoryblokTypesConfig = { components: Block } | { blocks: Block };\n\ntype ResolveComponents<T extends StoryblokTypesConfig> =\n T extends { components: infer C extends Block } ? C\n : T extends { blocks: infer B extends Block } ? B\n : never;\n\n/** Extracts the `fieldType → value` plugin map from a Schema, defaulting to an empty map. */\ntype ResolveFieldPlugins<T> = T extends { fieldPlugins: infer P } ? P : Record<never, never>;\n\n/**\n * The return type of `createManagementApiClient`, parameterised by `TBlocks` so that\n * `.stories` methods can narrow story content types without touching the runtime object.\n * Component *definitions* (`.components`) are wire-shaped and not narrowed by `TBlocks`.\n */\nexport type ManagementApiClient<\n TBlocks extends Block = Block,\n TFieldPlugins = Record<never, never>,\n DefaultThrowOnError extends boolean = false,\n> = ReturnType<typeof buildResources<DefaultThrowOnError>> & {\n components: ReturnType<typeof createComponentsResource<DefaultThrowOnError>>;\n stories: ReturnType<typeof createStoriesResource<TBlocks, TFieldPlugins, DefaultThrowOnError>>;\n /**\n * Returns the same client instance cast to a version that narrows story content\n * to the provided component types. No runtime cost — 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 = createManagementApiClient({ personalAccessToken: '...' })\n * .withTypes<Schema>();\n * ```\n */\n withTypes: <T extends StoryblokTypesConfig>() => ManagementApiClient<ResolveComponents<T>, ResolveFieldPlugins<T>, DefaultThrowOnError>;\n};\n\nexport const createManagementApiClient = <\n DefaultThrowOnError extends boolean = false,\n>(\n config: ManagementApiClientConfig<DefaultThrowOnError>,\n): ManagementApiClient<Block, Record<never, never>, DefaultThrowOnError> => {\n const { deps, resources } = createManagementApiClientBase(config);\n const self: ManagementApiClient<Block, Record<never, never>, DefaultThrowOnError> = {\n ...resources,\n components: createComponentsResource<DefaultThrowOnError>(deps),\n stories: createStoriesResource<Block, Record<never, never>, DefaultThrowOnError>(deps),\n withTypes<T extends StoryblokTypesConfig>() {\n return self as unknown as ManagementApiClient<ResolveComponents<T>, ResolveFieldPlugins<T>, DefaultThrowOnError>;\n },\n };\n return self;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA+IA,SAAS,uBAAuB,QAAgE;AAC9F,KAAI,OAAO,oBACT,QAAO,OAAO;AAEhB,KAAI,OAAO,WACT,QAAO,OAAO,WAAW,WAAW,UAAU,GAC1C,OAAO,aACP,UAAU,OAAO;;AAKzB,MAAM,iCACJ,WAIG;CACH,MAAM,EACJ,SACA,SAAS,MACT,SACA,UAAU,EAAE,EACZ,eAAe,OACf,QAAQ;EACN,OAAO;EACP,cAAc;EACd,SAAS;GAAC;GAAO;GAAQ;GAAO;GAAU;GAAS;GAAQ;GAAW;GAAQ;EAC9E,aAAa,CAAC,IAAI;EACnB,EACD,UAAU,KACV,cACE;CAEJ,MAAM,kBAAkBA,yCAAsB,aAAa,EAAE,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,MAAM,OAA8E;EAClF,GAAG;EACH,YAAYC,4CAA8C,KAAK;EAC/D,SAASC,sCAAwE,KAAK;EACtF,YAA4C;AAC1C,UAAO;;EAEV;AACD,QAAO"}
|
|
1
|
+
{"version":3,"file":"client.cjs","names":["createThrottleManager","createClient","createConfig","ClientError","createAssetFoldersResource","createAssetsResource","createComponentFoldersResource","createDatasourceEntriesResource","createDatasourcesResource","createExperimentsResource","createInternalTagsResource","createPresetsResource","createSharedAssetFoldersResource","createSharedAssetsResource","createSharedInternalTagsResource","createSpacesResource","createUsersResource","createComponentsResource","createStoriesResource"],"sources":["../src/client.ts"],"sourcesContent":["import type { Client, ResolvedRequestOptions, RetryOptions } from './generated/mapi/client';\nimport type { Middleware } from './generated/mapi/client/utils.gen';\nimport { createClient, createConfig } from './generated/mapi/client';\nimport { getManagementBaseUrl } from '@storyblok/region-helper';\nimport type { Region } from '@storyblok/region-helper';\nimport type { Block } from './generated/types/block';\nimport { ClientError } from './error';\nimport type { RateLimitConfig } from './utils/rate-limit';\nimport { createThrottleManager } from './utils/rate-limit';\nimport { querySerializer } from './utils/query-serializer';\nimport { createAssetFoldersResource } from './resources/asset-folders';\nimport { createAssetsResource } from './resources/assets';\nimport { createComponentFoldersResource } from './resources/component-folders';\nimport { createComponentsResource } from './resources/components';\nimport { createDatasourceEntriesResource } from './resources/datasource-entries';\nimport { createDatasourcesResource } from './resources/datasources';\nimport { createExperimentsResource } from './resources/experiments';\nimport { createInternalTagsResource } from './resources/internal-tags';\nimport { createPresetsResource } from './resources/presets';\nimport { createSharedAssetFoldersResource } from './resources/shared-asset-folders';\nimport { createSharedAssetsResource } from './resources/shared-assets';\nimport { createSharedInternalTagsResource } from './resources/shared-internal-tags';\nimport { createSpacesResource } from './resources/spaces';\nimport { createStoriesResource } from './resources/stories';\nimport { createUsersResource } from './resources/users';\n\n// ---------------------------------------------------------------------------\n// Client types (co-located with runtime)\n// ---------------------------------------------------------------------------\n\nexport type ApiResponse<T, ThrowOnError extends boolean = false> =\n ThrowOnError extends true\n ? { data: T; error?: never; response: Response; request: Request }\n : | { data: T; error: undefined; response: Response; request: Request }\n | { data: undefined; error: ClientError; response: Response; request: Request };\n\nexport interface RequestConfigOverrides {\n throwOnError?: boolean;\n}\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(123, {\n * fetchOptions: {\n * cache: 'no-store',\n * next: { revalidate: 60 },\n * },\n * })\n * ```\n */\nexport type FetchOptions = Record<string, unknown>;\n\nexport interface HttpRequestOptions {\n query?: Record<string, unknown>;\n body?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n throwOnError?: RequestConfigOverrides['throwOnError'];\n fetchOptions?: FetchOptions;\n}\n\n/**\n * Dependencies injected into every resource factory.\n */\nexport interface MapiResourceDeps<DefaultThrowOnError extends boolean = false> {\n client: Client;\n spaceId?: number;\n wrapRequest: <TData, ThrowOnError extends boolean = DefaultThrowOnError>(fn: () => Promise<unknown>, throwOnError?: ThrowOnError) => Promise<ApiResponse<TData, ThrowOnError>>;\n}\n\ntype TokenConfig =\n | {\n /** Personal access token for authentication. */\n personalAccessToken: string;\n oauthToken?: never;\n }\n | {\n personalAccessToken?: never;\n /** OAuth bearer token for authentication. */\n oauthToken: string;\n }\n | {\n personalAccessToken?: undefined;\n oauthToken?: undefined;\n };\n\nexport type ManagementApiClientConfig<\n ThrowOnError extends boolean = false,\n> = TokenConfig & {\n /**\n * The Storyblok space ID. Used as the default for space-scoped endpoints.\n * You can also override it per request via `path.space_id`.\n */\n spaceId?: number;\n /**\n * Storyblok region. Determines the base URL.\n * @default 'eu'\n */\n region?: Region;\n /**\n * Override the base URL entirely (e.g. for testing).\n */\n baseUrl?: string;\n /**\n * Additional request headers.\n */\n headers?: Record<string, string>;\n /**\n * Throw on HTTP errors instead of returning them.\n * @default false\n */\n throwOnError?: ThrowOnError;\n /**\n * Retry configuration for failed requests.\n */\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 Management API rate limits.\n *\n * - `undefined` (default): single bucket at 6 requests per second.\n * - `number`: fixed requests per second.\n * - `{ requestsPerSecond?: number }`: full config.\n * - `false`: disable rate limiting entirely.\n */\n rateLimit?: RateLimitConfig | number | false;\n};\n\n// ---------------------------------------------------------------------------\n// Client factory\n// ---------------------------------------------------------------------------\n\nfunction getAuthorizationHeader(config: ManagementApiClientConfig<boolean>): string | undefined {\n if (config.personalAccessToken) {\n return config.personalAccessToken;\n }\n if (config.oauthToken) {\n return config.oauthToken.startsWith('Bearer ')\n ? config.oauthToken\n : `Bearer ${config.oauthToken}`;\n }\n return undefined;\n}\n\nconst createManagementApiClientBase = <DefaultThrowOnError extends boolean = false>(\n config: ManagementApiClientConfig<DefaultThrowOnError>,\n): {\n deps: MapiResourceDeps<DefaultThrowOnError>;\n resources: Omit<ReturnType<typeof buildResources<DefaultThrowOnError>>, never>;\n} => {\n const {\n spaceId,\n region = 'eu',\n baseUrl,\n headers = {},\n throwOnError = false,\n retry = {\n limit: 12,\n backoffLimit: 20_000,\n methods: ['get', 'post', 'put', 'delete', 'patch', 'head', 'options', 'trace'],\n statusCodes: [429],\n },\n timeout = 30_000,\n rateLimit,\n } = config;\n\n const throttleManager = createThrottleManager(rateLimit ?? {});\n const authHeader = getAuthorizationHeader(config);\n\n const client: Client = createClient(\n createConfig({\n baseUrl: baseUrl || getManagementBaseUrl(region),\n headers: {\n ...(authHeader ? { Authorization: authHeader } : {}),\n ...headers,\n },\n // Default serializer throws on nested objects; MAPI needs `filter_query`\n // serialized as a nested hash (`filter_query[field][op]=value`).\n querySerializer,\n throwOnError,\n kyOptions: {\n throwHttpErrors: true,\n timeout,\n retry,\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 function wrapRequest<TData, CurrentThrowOnError extends boolean = DefaultThrowOnError>(\n fn: () => Promise<unknown>,\n _throwOnError?: CurrentThrowOnError,\n ): Promise<ApiResponse<TData, CurrentThrowOnError>> {\n return throttleManager.execute(\n () => fn() as Promise<ApiResponse<TData, CurrentThrowOnError>>,\n );\n }\n\n const deps: MapiResourceDeps<DefaultThrowOnError> = { client, spaceId, wrapRequest };\n return { deps, resources: buildResources(deps, client) };\n};\n\nfunction buildResources<DefaultThrowOnError extends boolean = false>(\n deps: MapiResourceDeps<DefaultThrowOnError>,\n client: Client,\n) {\n /**\n * Escape hatch: send a GET request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpGet = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.get({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a POST request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpPost = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.post({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a PUT request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpPut = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.put({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a PATCH request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpPatch = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.patch({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a DELETE request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpDelete = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.delete({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n return {\n assetFolders: createAssetFoldersResource(deps),\n assets: createAssetsResource(deps),\n componentFolders: createComponentFoldersResource(deps),\n datasourceEntries: createDatasourceEntriesResource(deps),\n datasources: createDatasourcesResource(deps),\n experiments: createExperimentsResource(deps),\n delete: httpDelete,\n get: httpGet,\n patch: httpPatch,\n interceptors: client.interceptors as Middleware<Request, Response, unknown, ResolvedRequestOptions>,\n internalTags: createInternalTagsResource(deps),\n post: httpPost,\n presets: createPresetsResource(deps),\n put: httpPut,\n sharedAssetFolders: createSharedAssetFoldersResource(deps),\n sharedAssets: createSharedAssetsResource(deps),\n sharedInternalTags: createSharedInternalTagsResource(deps),\n spaces: createSpacesResource(deps),\n users: createUsersResource<DefaultThrowOnError>({ client, wrapRequest: deps.wrapRequest }),\n };\n}\n\ntype StoryblokTypesConfig = { components: Block } | { blocks: Block };\n\ntype ResolveComponents<T extends StoryblokTypesConfig> =\n T extends { components: infer C extends Block } ? C\n : T extends { blocks: infer B extends Block } ? B\n : never;\n\n/** Extracts the `fieldType → value` plugin map from a Schema, defaulting to an empty map. */\ntype ResolveFieldPlugins<T> = T extends { fieldPlugins: infer P } ? P : Record<never, never>;\n\n/**\n * The return type of `createManagementApiClient`, parameterised by `TBlocks` so that\n * `.stories` methods can narrow story content types without touching the runtime object.\n * Component *definitions* (`.components`) are wire-shaped and not narrowed by `TBlocks`.\n */\nexport type ManagementApiClient<\n TBlocks extends Block = Block,\n TFieldPlugins = Record<never, never>,\n DefaultThrowOnError extends boolean = false,\n> = ReturnType<typeof buildResources<DefaultThrowOnError>> & {\n components: ReturnType<typeof createComponentsResource<DefaultThrowOnError>>;\n stories: ReturnType<typeof createStoriesResource<TBlocks, TFieldPlugins, DefaultThrowOnError>>;\n /**\n * Returns the same client instance cast to a version that narrows story content\n * to the provided component types. No runtime cost — 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 = createManagementApiClient({ personalAccessToken: '...' })\n * .withTypes<Schema>();\n * ```\n */\n withTypes: <T extends StoryblokTypesConfig>() => ManagementApiClient<ResolveComponents<T>, ResolveFieldPlugins<T>, DefaultThrowOnError>;\n};\n\nexport const createManagementApiClient = <\n DefaultThrowOnError extends boolean = false,\n>(\n config: ManagementApiClientConfig<DefaultThrowOnError>,\n): ManagementApiClient<Block, Record<never, never>, DefaultThrowOnError> => {\n const { deps, resources } = createManagementApiClientBase(config);\n const self: ManagementApiClient<Block, Record<never, never>, DefaultThrowOnError> = {\n ...resources,\n components: createComponentsResource<DefaultThrowOnError>(deps),\n stories: createStoriesResource<Block, Record<never, never>, DefaultThrowOnError>(deps),\n withTypes<T extends StoryblokTypesConfig>() {\n return self as unknown as ManagementApiClient<ResolveComponents<T>, ResolveFieldPlugins<T>, DefaultThrowOnError>;\n },\n };\n return self;\n};\n"],"mapp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BC,2DAAgC,KAAK;EACxD,aAAaC,8CAA0B,KAAK;EAC5C,aAAaC,8CAA0B,KAAK;EAC5C,QAAQ;EACR,KAAK;EACL,OAAO;EACP,cAAc,OAAO;EACrB,cAAcC,iDAA2B,KAAK;EAC9C,MAAM;EACN,SAASC,sCAAsB,KAAK;EACpC,KAAK;EACL,oBAAoBC,8DAAiC,KAAK;EAC1D,cAAcC,iDAA2B,KAAK;EAC9C,oBAAoBC,8DAAiC,KAAK;EAC1D,QAAQC,oCAAqB,KAAK;EAClC,OAAOC,kCAAyC;GAAE;GAAQ,aAAa,KAAK;GAAa,CAAC;EAC3F;;AA2CH,MAAa,6BAGX,WAC0E;CAC1E,MAAM,EAAE,MAAM,cAAc,8BAA8B,OAAO;CACjE,MAAM,OAA8E;EAClF,GAAG;EACH,YAAYC,4CAA8C,KAAK;EAC/D,SAASC,sCAAwE,KAAK;EACtF,YAA4C;AAC1C,UAAO;;EAEV;AACD,QAAO"}
|
package/dist/client.d.cts
CHANGED
|
@@ -114,9 +114,9 @@ type ManagementApiClientConfig<ThrowOnError extends boolean = false> = TokenConf
|
|
|
114
114
|
/**
|
|
115
115
|
* Preventive rate limiting to avoid hitting the Storyblok Management API rate limits.
|
|
116
116
|
*
|
|
117
|
-
* - `undefined` (default): single bucket at
|
|
118
|
-
* - `number`: fixed
|
|
119
|
-
* - `{
|
|
117
|
+
* - `undefined` (default): single bucket at 6 requests per second.
|
|
118
|
+
* - `number`: fixed requests per second.
|
|
119
|
+
* - `{ requestsPerSecond?: number }`: full config.
|
|
120
120
|
* - `false`: disable rate limiting entirely.
|
|
121
121
|
*/
|
|
122
122
|
rateLimit?: RateLimitConfig | number | false;
|
package/dist/client.d.mts
CHANGED
|
@@ -114,9 +114,9 @@ type ManagementApiClientConfig<ThrowOnError extends boolean = false> = TokenConf
|
|
|
114
114
|
/**
|
|
115
115
|
* Preventive rate limiting to avoid hitting the Storyblok Management API rate limits.
|
|
116
116
|
*
|
|
117
|
-
* - `undefined` (default): single bucket at
|
|
118
|
-
* - `number`: fixed
|
|
119
|
-
* - `{
|
|
117
|
+
* - `undefined` (default): single bucket at 6 requests per second.
|
|
118
|
+
* - `number`: fixed requests per second.
|
|
119
|
+
* - `{ requestsPerSecond?: number }`: full config.
|
|
120
120
|
* - `false`: disable rate limiting entirely.
|
|
121
121
|
*/
|
|
122
122
|
rateLimit?: RateLimitConfig | number | false;
|
package/dist/client.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.mjs","names":[],"sources":["../src/client.ts"],"sourcesContent":["import type { Client, ResolvedRequestOptions, RetryOptions } from './generated/mapi/client';\nimport type { Middleware } from './generated/mapi/client/utils.gen';\nimport { createClient, createConfig } from './generated/mapi/client';\nimport { getManagementBaseUrl } from '@storyblok/region-helper';\nimport type { Region } from '@storyblok/region-helper';\nimport type { Block } from './generated/types/block';\nimport { ClientError } from './error';\nimport type { RateLimitConfig } from './utils/rate-limit';\nimport { createThrottleManager } from './utils/rate-limit';\nimport { querySerializer } from './utils/query-serializer';\nimport { createAssetFoldersResource } from './resources/asset-folders';\nimport { createAssetsResource } from './resources/assets';\nimport { createComponentFoldersResource } from './resources/component-folders';\nimport { createComponentsResource } from './resources/components';\nimport { createDatasourceEntriesResource } from './resources/datasource-entries';\nimport { createDatasourcesResource } from './resources/datasources';\nimport { createExperimentsResource } from './resources/experiments';\nimport { createInternalTagsResource } from './resources/internal-tags';\nimport { createPresetsResource } from './resources/presets';\nimport { createSharedAssetFoldersResource } from './resources/shared-asset-folders';\nimport { createSharedAssetsResource } from './resources/shared-assets';\nimport { createSharedInternalTagsResource } from './resources/shared-internal-tags';\nimport { createSpacesResource } from './resources/spaces';\nimport { createStoriesResource } from './resources/stories';\nimport { createUsersResource } from './resources/users';\n\n// ---------------------------------------------------------------------------\n// Client types (co-located with runtime)\n// ---------------------------------------------------------------------------\n\nexport type ApiResponse<T, ThrowOnError extends boolean = false> =\n ThrowOnError extends true\n ? { data: T; error?: never; response: Response; request: Request }\n : | { data: T; error: undefined; response: Response; request: Request }\n | { data: undefined; error: ClientError; response: Response; request: Request };\n\nexport interface RequestConfigOverrides {\n throwOnError?: boolean;\n}\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(123, {\n * fetchOptions: {\n * cache: 'no-store',\n * next: { revalidate: 60 },\n * },\n * })\n * ```\n */\nexport type FetchOptions = Record<string, unknown>;\n\nexport interface HttpRequestOptions {\n query?: Record<string, unknown>;\n body?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n throwOnError?: RequestConfigOverrides['throwOnError'];\n fetchOptions?: FetchOptions;\n}\n\n/**\n * Dependencies injected into every resource factory.\n */\nexport interface MapiResourceDeps<DefaultThrowOnError extends boolean = false> {\n client: Client;\n spaceId?: number;\n wrapRequest: <TData, ThrowOnError extends boolean = DefaultThrowOnError>(fn: () => Promise<unknown>, throwOnError?: ThrowOnError) => Promise<ApiResponse<TData, ThrowOnError>>;\n}\n\ntype TokenConfig =\n | {\n /** Personal access token for authentication. */\n personalAccessToken: string;\n oauthToken?: never;\n }\n | {\n personalAccessToken?: never;\n /** OAuth bearer token for authentication. */\n oauthToken: string;\n }\n | {\n personalAccessToken?: undefined;\n oauthToken?: undefined;\n };\n\nexport type ManagementApiClientConfig<\n ThrowOnError extends boolean = false,\n> = TokenConfig & {\n /**\n * The Storyblok space ID. Used as the default for space-scoped endpoints.\n * You can also override it per request via `path.space_id`.\n */\n spaceId?: number;\n /**\n * Storyblok region. Determines the base URL.\n * @default 'eu'\n */\n region?: Region;\n /**\n * Override the base URL entirely (e.g. for testing).\n */\n baseUrl?: string;\n /**\n * Additional request headers.\n */\n headers?: Record<string, string>;\n /**\n * Throw on HTTP errors instead of returning them.\n * @default false\n */\n throwOnError?: ThrowOnError;\n /**\n * Retry configuration for failed requests.\n */\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 Management API rate limits.\n *\n * - `undefined` (default): single bucket at maxConcurrency: 6.\n * - `number`: fixed max concurrent requests per second.\n * - `{ maxConcurrency?: number; adaptToServerHeaders?: boolean }`: full config.\n * - `false`: disable rate limiting entirely.\n */\n rateLimit?: RateLimitConfig | number | false;\n};\n\n// ---------------------------------------------------------------------------\n// Client factory\n// ---------------------------------------------------------------------------\n\nfunction getAuthorizationHeader(config: ManagementApiClientConfig<boolean>): string | undefined {\n if (config.personalAccessToken) {\n return config.personalAccessToken;\n }\n if (config.oauthToken) {\n return config.oauthToken.startsWith('Bearer ')\n ? config.oauthToken\n : `Bearer ${config.oauthToken}`;\n }\n return undefined;\n}\n\nconst createManagementApiClientBase = <DefaultThrowOnError extends boolean = false>(\n config: ManagementApiClientConfig<DefaultThrowOnError>,\n): {\n deps: MapiResourceDeps<DefaultThrowOnError>;\n resources: Omit<ReturnType<typeof buildResources<DefaultThrowOnError>>, never>;\n} => {\n const {\n spaceId,\n region = 'eu',\n baseUrl,\n headers = {},\n throwOnError = false,\n retry = {\n limit: 12,\n backoffLimit: 20_000,\n methods: ['get', 'post', 'put', 'delete', 'patch', 'head', 'options', 'trace'],\n statusCodes: [429],\n },\n timeout = 30_000,\n rateLimit,\n } = config;\n\n const throttleManager = createThrottleManager(rateLimit ?? {});\n const authHeader = getAuthorizationHeader(config);\n\n const client: Client = createClient(\n createConfig({\n baseUrl: baseUrl || getManagementBaseUrl(region),\n headers: {\n ...(authHeader ? { Authorization: authHeader } : {}),\n ...headers,\n },\n // Default serializer throws on nested objects; MAPI needs `filter_query`\n // serialized as a nested hash (`filter_query[field][op]=value`).\n querySerializer,\n throwOnError,\n kyOptions: {\n throwHttpErrors: true,\n timeout,\n retry,\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 function wrapRequest<TData, CurrentThrowOnError extends boolean = DefaultThrowOnError>(\n fn: () => Promise<unknown>,\n _throwOnError?: CurrentThrowOnError,\n ): Promise<ApiResponse<TData, CurrentThrowOnError>> {\n return throttleManager.execute(\n () => fn() as Promise<ApiResponse<TData, CurrentThrowOnError>>,\n );\n }\n\n const deps: MapiResourceDeps<DefaultThrowOnError> = { client, spaceId, wrapRequest };\n return { deps, resources: buildResources(deps, client) };\n};\n\nfunction buildResources<DefaultThrowOnError extends boolean = false>(\n deps: MapiResourceDeps<DefaultThrowOnError>,\n client: Client,\n) {\n /**\n * Escape hatch: send a GET request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpGet = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.get({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a POST request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpPost = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.post({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a PUT request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpPut = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.put({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a PATCH request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpPatch = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.patch({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a DELETE request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpDelete = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.delete({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n return {\n assetFolders: createAssetFoldersResource(deps),\n assets: createAssetsResource(deps),\n componentFolders: createComponentFoldersResource(deps),\n datasourceEntries: createDatasourceEntriesResource(deps),\n datasources: createDatasourcesResource(deps),\n experiments: createExperimentsResource(deps),\n delete: httpDelete,\n get: httpGet,\n patch: httpPatch,\n interceptors: client.interceptors as Middleware<Request, Response, unknown, ResolvedRequestOptions>,\n internalTags: createInternalTagsResource(deps),\n post: httpPost,\n presets: createPresetsResource(deps),\n put: httpPut,\n sharedAssetFolders: createSharedAssetFoldersResource(deps),\n sharedAssets: createSharedAssetsResource(deps),\n sharedInternalTags: createSharedInternalTagsResource(deps),\n spaces: createSpacesResource(deps),\n users: createUsersResource<DefaultThrowOnError>({ client, wrapRequest: deps.wrapRequest }),\n };\n}\n\ntype StoryblokTypesConfig = { components: Block } | { blocks: Block };\n\ntype ResolveComponents<T extends StoryblokTypesConfig> =\n T extends { components: infer C extends Block } ? C\n : T extends { blocks: infer B extends Block } ? B\n : never;\n\n/** Extracts the `fieldType → value` plugin map from a Schema, defaulting to an empty map. */\ntype ResolveFieldPlugins<T> = T extends { fieldPlugins: infer P } ? P : Record<never, never>;\n\n/**\n * The return type of `createManagementApiClient`, parameterised by `TBlocks` so that\n * `.stories` methods can narrow story content types without touching the runtime object.\n * Component *definitions* (`.components`) are wire-shaped and not narrowed by `TBlocks`.\n */\nexport type ManagementApiClient<\n TBlocks extends Block = Block,\n TFieldPlugins = Record<never, never>,\n DefaultThrowOnError extends boolean = false,\n> = ReturnType<typeof buildResources<DefaultThrowOnError>> & {\n components: ReturnType<typeof createComponentsResource<DefaultThrowOnError>>;\n stories: ReturnType<typeof createStoriesResource<TBlocks, TFieldPlugins, DefaultThrowOnError>>;\n /**\n * Returns the same client instance cast to a version that narrows story content\n * to the provided component types. No runtime cost — 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 = createManagementApiClient({ personalAccessToken: '...' })\n * .withTypes<Schema>();\n * ```\n */\n withTypes: <T extends StoryblokTypesConfig>() => ManagementApiClient<ResolveComponents<T>, ResolveFieldPlugins<T>, DefaultThrowOnError>;\n};\n\nexport const createManagementApiClient = <\n DefaultThrowOnError extends boolean = false,\n>(\n config: ManagementApiClientConfig<DefaultThrowOnError>,\n): ManagementApiClient<Block, Record<never, never>, DefaultThrowOnError> => {\n const { deps, resources } = createManagementApiClientBase(config);\n const self: ManagementApiClient<Block, Record<never, never>, DefaultThrowOnError> = {\n ...resources,\n components: createComponentsResource<DefaultThrowOnError>(deps),\n stories: createStoriesResource<Block, Record<never, never>, DefaultThrowOnError>(deps),\n withTypes<T extends StoryblokTypesConfig>() {\n return self as unknown as ManagementApiClient<ResolveComponents<T>, ResolveFieldPlugins<T>, DefaultThrowOnError>;\n },\n };\n return self;\n};\n"],"mappings":";;;;;;;;;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xD,aAAa,0BAA0B,KAAK;EAC5C,aAAa,0BAA0B,KAAK;EAC5C,QAAQ;EACR,KAAK;EACL,OAAO;EACP,cAAc,OAAO;EACrB,cAAc,2BAA2B,KAAK;EAC9C,MAAM;EACN,SAAS,sBAAsB,KAAK;EACpC,KAAK;EACL,oBAAoB,iCAAiC,KAAK;EAC1D,cAAc,2BAA2B,KAAK;EAC9C,oBAAoB,iCAAiC,KAAK;EAC1D,QAAQ,qBAAqB,KAAK;EAClC,OAAO,oBAAyC;GAAE;GAAQ,aAAa,KAAK;GAAa,CAAC;EAC3F;;AA2CH,MAAa,6BAGX,WAC0E;CAC1E,MAAM,EAAE,MAAM,cAAc,8BAA8B,OAAO;CACjE,MAAM,OAA8E;EAClF,GAAG;EACH,YAAY,yBAA8C,KAAK;EAC/D,SAAS,sBAAwE,KAAK;EACtF,YAA4C;AAC1C,UAAO;;EAEV;AACD,QAAO"}
|
|
1
|
+
{"version":3,"file":"client.mjs","names":[],"sources":["../src/client.ts"],"sourcesContent":["import type { Client, ResolvedRequestOptions, RetryOptions } from './generated/mapi/client';\nimport type { Middleware } from './generated/mapi/client/utils.gen';\nimport { createClient, createConfig } from './generated/mapi/client';\nimport { getManagementBaseUrl } from '@storyblok/region-helper';\nimport type { Region } from '@storyblok/region-helper';\nimport type { Block } from './generated/types/block';\nimport { ClientError } from './error';\nimport type { RateLimitConfig } from './utils/rate-limit';\nimport { createThrottleManager } from './utils/rate-limit';\nimport { querySerializer } from './utils/query-serializer';\nimport { createAssetFoldersResource } from './resources/asset-folders';\nimport { createAssetsResource } from './resources/assets';\nimport { createComponentFoldersResource } from './resources/component-folders';\nimport { createComponentsResource } from './resources/components';\nimport { createDatasourceEntriesResource } from './resources/datasource-entries';\nimport { createDatasourcesResource } from './resources/datasources';\nimport { createExperimentsResource } from './resources/experiments';\nimport { createInternalTagsResource } from './resources/internal-tags';\nimport { createPresetsResource } from './resources/presets';\nimport { createSharedAssetFoldersResource } from './resources/shared-asset-folders';\nimport { createSharedAssetsResource } from './resources/shared-assets';\nimport { createSharedInternalTagsResource } from './resources/shared-internal-tags';\nimport { createSpacesResource } from './resources/spaces';\nimport { createStoriesResource } from './resources/stories';\nimport { createUsersResource } from './resources/users';\n\n// ---------------------------------------------------------------------------\n// Client types (co-located with runtime)\n// ---------------------------------------------------------------------------\n\nexport type ApiResponse<T, ThrowOnError extends boolean = false> =\n ThrowOnError extends true\n ? { data: T; error?: never; response: Response; request: Request }\n : | { data: T; error: undefined; response: Response; request: Request }\n | { data: undefined; error: ClientError; response: Response; request: Request };\n\nexport interface RequestConfigOverrides {\n throwOnError?: boolean;\n}\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(123, {\n * fetchOptions: {\n * cache: 'no-store',\n * next: { revalidate: 60 },\n * },\n * })\n * ```\n */\nexport type FetchOptions = Record<string, unknown>;\n\nexport interface HttpRequestOptions {\n query?: Record<string, unknown>;\n body?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n throwOnError?: RequestConfigOverrides['throwOnError'];\n fetchOptions?: FetchOptions;\n}\n\n/**\n * Dependencies injected into every resource factory.\n */\nexport interface MapiResourceDeps<DefaultThrowOnError extends boolean = false> {\n client: Client;\n spaceId?: number;\n wrapRequest: <TData, ThrowOnError extends boolean = DefaultThrowOnError>(fn: () => Promise<unknown>, throwOnError?: ThrowOnError) => Promise<ApiResponse<TData, ThrowOnError>>;\n}\n\ntype TokenConfig =\n | {\n /** Personal access token for authentication. */\n personalAccessToken: string;\n oauthToken?: never;\n }\n | {\n personalAccessToken?: never;\n /** OAuth bearer token for authentication. */\n oauthToken: string;\n }\n | {\n personalAccessToken?: undefined;\n oauthToken?: undefined;\n };\n\nexport type ManagementApiClientConfig<\n ThrowOnError extends boolean = false,\n> = TokenConfig & {\n /**\n * The Storyblok space ID. Used as the default for space-scoped endpoints.\n * You can also override it per request via `path.space_id`.\n */\n spaceId?: number;\n /**\n * Storyblok region. Determines the base URL.\n * @default 'eu'\n */\n region?: Region;\n /**\n * Override the base URL entirely (e.g. for testing).\n */\n baseUrl?: string;\n /**\n * Additional request headers.\n */\n headers?: Record<string, string>;\n /**\n * Throw on HTTP errors instead of returning them.\n * @default false\n */\n throwOnError?: ThrowOnError;\n /**\n * Retry configuration for failed requests.\n */\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 Management API rate limits.\n *\n * - `undefined` (default): single bucket at 6 requests per second.\n * - `number`: fixed requests per second.\n * - `{ requestsPerSecond?: number }`: full config.\n * - `false`: disable rate limiting entirely.\n */\n rateLimit?: RateLimitConfig | number | false;\n};\n\n// ---------------------------------------------------------------------------\n// Client factory\n// ---------------------------------------------------------------------------\n\nfunction getAuthorizationHeader(config: ManagementApiClientConfig<boolean>): string | undefined {\n if (config.personalAccessToken) {\n return config.personalAccessToken;\n }\n if (config.oauthToken) {\n return config.oauthToken.startsWith('Bearer ')\n ? config.oauthToken\n : `Bearer ${config.oauthToken}`;\n }\n return undefined;\n}\n\nconst createManagementApiClientBase = <DefaultThrowOnError extends boolean = false>(\n config: ManagementApiClientConfig<DefaultThrowOnError>,\n): {\n deps: MapiResourceDeps<DefaultThrowOnError>;\n resources: Omit<ReturnType<typeof buildResources<DefaultThrowOnError>>, never>;\n} => {\n const {\n spaceId,\n region = 'eu',\n baseUrl,\n headers = {},\n throwOnError = false,\n retry = {\n limit: 12,\n backoffLimit: 20_000,\n methods: ['get', 'post', 'put', 'delete', 'patch', 'head', 'options', 'trace'],\n statusCodes: [429],\n },\n timeout = 30_000,\n rateLimit,\n } = config;\n\n const throttleManager = createThrottleManager(rateLimit ?? {});\n const authHeader = getAuthorizationHeader(config);\n\n const client: Client = createClient(\n createConfig({\n baseUrl: baseUrl || getManagementBaseUrl(region),\n headers: {\n ...(authHeader ? { Authorization: authHeader } : {}),\n ...headers,\n },\n // Default serializer throws on nested objects; MAPI needs `filter_query`\n // serialized as a nested hash (`filter_query[field][op]=value`).\n querySerializer,\n throwOnError,\n kyOptions: {\n throwHttpErrors: true,\n timeout,\n retry,\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 function wrapRequest<TData, CurrentThrowOnError extends boolean = DefaultThrowOnError>(\n fn: () => Promise<unknown>,\n _throwOnError?: CurrentThrowOnError,\n ): Promise<ApiResponse<TData, CurrentThrowOnError>> {\n return throttleManager.execute(\n () => fn() as Promise<ApiResponse<TData, CurrentThrowOnError>>,\n );\n }\n\n const deps: MapiResourceDeps<DefaultThrowOnError> = { client, spaceId, wrapRequest };\n return { deps, resources: buildResources(deps, client) };\n};\n\nfunction buildResources<DefaultThrowOnError extends boolean = false>(\n deps: MapiResourceDeps<DefaultThrowOnError>,\n client: Client,\n) {\n /**\n * Escape hatch: send a GET request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpGet = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.get({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a POST request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpPost = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.post({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a PUT request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpPut = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.put({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a PATCH request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpPatch = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.patch({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n /**\n * Escape hatch: send a DELETE request to any MAPI endpoint not yet wrapped\n * in a dedicated resource method.\n */\n const httpDelete = <TData = unknown>(\n path: string,\n options: HttpRequestOptions = {},\n ): Promise<ApiResponse<TData, DefaultThrowOnError>> => {\n const { fetchOptions, ...rest } = options;\n return deps.wrapRequest<TData>(() =>\n client.delete({ url: path, ...rest, ...(fetchOptions ? { kyOptions: { ...client.getConfig().kyOptions, ...fetchOptions } } : {}) }),\n );\n };\n\n return {\n assetFolders: createAssetFoldersResource(deps),\n assets: createAssetsResource(deps),\n componentFolders: createComponentFoldersResource(deps),\n datasourceEntries: createDatasourceEntriesResource(deps),\n datasources: createDatasourcesResource(deps),\n experiments: createExperimentsResource(deps),\n delete: httpDelete,\n get: httpGet,\n patch: httpPatch,\n interceptors: client.interceptors as Middleware<Request, Response, unknown, ResolvedRequestOptions>,\n internalTags: createInternalTagsResource(deps),\n post: httpPost,\n presets: createPresetsResource(deps),\n put: httpPut,\n sharedAssetFolders: createSharedAssetFoldersResource(deps),\n sharedAssets: createSharedAssetsResource(deps),\n sharedInternalTags: createSharedInternalTagsResource(deps),\n spaces: createSpacesResource(deps),\n users: createUsersResource<DefaultThrowOnError>({ client, wrapRequest: deps.wrapRequest }),\n };\n}\n\ntype StoryblokTypesConfig = { components: Block } | { blocks: Block };\n\ntype ResolveComponents<T extends StoryblokTypesConfig> =\n T extends { components: infer C extends Block } ? C\n : T extends { blocks: infer B extends Block } ? B\n : never;\n\n/** Extracts the `fieldType → value` plugin map from a Schema, defaulting to an empty map. */\ntype ResolveFieldPlugins<T> = T extends { fieldPlugins: infer P } ? P : Record<never, never>;\n\n/**\n * The return type of `createManagementApiClient`, parameterised by `TBlocks` so that\n * `.stories` methods can narrow story content types without touching the runtime object.\n * Component *definitions* (`.components`) are wire-shaped and not narrowed by `TBlocks`.\n */\nexport type ManagementApiClient<\n TBlocks extends Block = Block,\n TFieldPlugins = Record<never, never>,\n DefaultThrowOnError extends boolean = false,\n> = ReturnType<typeof buildResources<DefaultThrowOnError>> & {\n components: ReturnType<typeof createComponentsResource<DefaultThrowOnError>>;\n stories: ReturnType<typeof createStoriesResource<TBlocks, TFieldPlugins, DefaultThrowOnError>>;\n /**\n * Returns the same client instance cast to a version that narrows story content\n * to the provided component types. No runtime cost — 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 = createManagementApiClient({ personalAccessToken: '...' })\n * .withTypes<Schema>();\n * ```\n */\n withTypes: <T extends StoryblokTypesConfig>() => ManagementApiClient<ResolveComponents<T>, ResolveFieldPlugins<T>, DefaultThrowOnError>;\n};\n\nexport const createManagementApiClient = <\n DefaultThrowOnError extends boolean = false,\n>(\n config: ManagementApiClientConfig<DefaultThrowOnError>,\n): ManagementApiClient<Block, Record<never, never>, DefaultThrowOnError> => {\n const { deps, resources } = createManagementApiClientBase(config);\n const self: ManagementApiClient<Block, Record<never, never>, DefaultThrowOnError> = {\n ...resources,\n components: createComponentsResource<DefaultThrowOnError>(deps),\n stories: createStoriesResource<Block, Record<never, never>, DefaultThrowOnError>(deps),\n withTypes<T extends StoryblokTypesConfig>() {\n return self as unknown as ManagementApiClient<ResolveComponents<T>, ResolveFieldPlugins<T>, DefaultThrowOnError>;\n },\n };\n return self;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+IA,SAAS,uBAAuB,QAAgE;AAC9F,KAAI,OAAO,oBACT,QAAO,OAAO;AAEhB,KAAI,OAAO,WACT,QAAO,OAAO,WAAW,WAAW,UAAU,GAC1C,OAAO,aACP,UAAU,OAAO;;AAKzB,MAAM,iCACJ,WAIG;CACH,MAAM,EACJ,SACA,SAAS,MACT,SACA,UAAU,EAAE,EACZ,eAAe,OACf,QAAQ;EACN,OAAO;EACP,cAAc;EACd,SAAS;GAAC;GAAO;GAAQ;GAAO;GAAU;GAAS;GAAQ;GAAW;GAAQ;EAC9E,aAAa,CAAC,IAAI;EACnB,EACD,UAAU,KACV,cACE;CAEJ,MAAM,kBAAkB,sBAAsB,aAAa,EAAE,CAAC;CAC9D,MAAM,aAAa,uBAAuB,OAAO;CAEjD,MAAM,SAAiB,aACrB,aAAa;EACX,SAAS,WAAW,qBAAqB,OAAO;EAChD,SAAS;GACP,GAAI,aAAa,EAAE,eAAe,YAAY,GAAG,EAAE;GACnD,GAAG;GACJ;EAGD;EACA;EACA,WAAW;GACT,iBAAiB;GACjB;GACA;GACD;EACF,CAAC,CACH;AAED,QAAO,aAAa,MAAM,KACvB,OAAgB,aACf,IAAI,YAAY,UAAU,cAAc,sBAAsB;EAC5D,QAAQ,UAAU,UAAU;EAC5B,YAAY,UAAU,cAAc;EACpC,MAAM;EACP,CAAC,CACL;CAED,SAAS,YACP,IACA,eACkD;AAClD,SAAO,gBAAgB,cACf,IAAI,CACX;;CAGH,MAAM,OAA8C;EAAE;EAAQ;EAAS;EAAa;AACpF,QAAO;EAAE;EAAM,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AAG;GAAM,GAAI,eAAe,EAAE,WAAW;IAAE,GAAG,OAAO,WAAW,CAAC;IAAW,GAAG;IAAc,EAAE,GAAG,EAAE;GAAG,CAAC,CACpI;;AAGH,QAAO;EACL,cAAc,2BAA2B,KAAK;EAC9C,QAAQ,qBAAqB,KAAK;EAClC,kBAAkB,+BAA+B,KAAK;EACtD,mBAAmB,gCAAgC,KAAK;EACxD,aAAa,0BAA0B,KAAK;EAC5C,aAAa,0BAA0B,KAAK;EAC5C,QAAQ;EACR,KAAK;EACL,OAAO;EACP,cAAc,OAAO;EACrB,cAAc,2BAA2B,KAAK;EAC9C,MAAM;EACN,SAAS,sBAAsB,KAAK;EACpC,KAAK;EACL,oBAAoB,iCAAiC,KAAK;EAC1D,cAAc,2BAA2B,KAAK;EAC9C,oBAAoB,iCAAiC,KAAK;EAC1D,QAAQ,qBAAqB,KAAK;EAClC,OAAO,oBAAyC;GAAE;GAAQ,aAAa,KAAK;GAAa,CAAC;EAC3F;;AA2CH,MAAa,6BAGX,WAC0E;CAC1E,MAAM,EAAE,MAAM,cAAc,8BAA8B,OAAO;CACjE,MAAM,OAA8E;EAClF,GAAG;EACH,YAAY,yBAA8C,KAAK;EAC/D,SAAS,sBAAwE,KAAK;EACtF,YAA4C;AAC1C,UAAO;;EAEV;AACD,QAAO"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
const
|
|
2
|
-
let async_sema = require("async-sema");
|
|
1
|
+
const require_throttle = require('./throttle.cjs');
|
|
3
2
|
|
|
4
3
|
//#region src/utils/rate-limit.ts
|
|
5
4
|
const DEFAULT_REQUESTS_PER_SECOND = 6;
|
|
@@ -16,11 +15,8 @@ function createThrottleManager(config) {
|
|
|
16
15
|
if (config === false) return { execute: (fn) => fn() };
|
|
17
16
|
const { requestsPerSecond, maxConcurrency } = typeof config === "number" ? { requestsPerSecond: config } : config;
|
|
18
17
|
const rps = requestsPerSecond ?? maxConcurrency ?? DEFAULT_REQUESTS_PER_SECOND;
|
|
19
|
-
const
|
|
20
|
-
return { execute:
|
|
21
|
-
await rl();
|
|
22
|
-
return fn();
|
|
23
|
-
} };
|
|
18
|
+
const throttle = require_throttle.createThrottle(Math.min(rps, MAX_RATE_LIMIT));
|
|
19
|
+
return { execute: (fn) => throttle.execute(fn) };
|
|
24
20
|
}
|
|
25
21
|
|
|
26
22
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rate-limit.cjs","names":[],"sources":["../../src/utils/rate-limit.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"rate-limit.cjs","names":["createThrottle"],"sources":["../../src/utils/rate-limit.ts"],"sourcesContent":["import { createThrottle } from './throttle';\n\nconst DEFAULT_REQUESTS_PER_SECOND = 6;\nconst MAX_RATE_LIMIT = 1_000;\n\nexport interface RateLimitConfig {\n /**\n * Maximum number of MAPI requests to start per second.\n * Defaults to 6. Capped at 1000.\n */\n requestsPerSecond?: number;\n /**\n * @deprecated Use `requestsPerSecond` instead.\n * @todo(next-major): Remove this field.\n */\n maxConcurrency?: number;\n}\n\nexport interface ThrottleManager {\n execute: <T>(fn: () => Promise<T>) => Promise<T>;\n}\n\n/**\n * Creates a `ThrottleManager` from the user-supplied `rateLimit` config.\n *\n * - `false` -> no throttling (passthrough)\n * - `number` -> N requests per second\n * - `{ requestsPerSecond: n }` -> N requests per second\n * - `{}` / `undefined` (default) -> DEFAULT_REQUESTS_PER_SECOND per second\n */\nexport function createThrottleManager(config: RateLimitConfig | number | false): ThrottleManager {\n if (config === false) {\n return { execute: fn => fn() };\n }\n\n const resolvedConfig: RateLimitConfig = typeof config === 'number' ? { requestsPerSecond: config } : config;\n const { requestsPerSecond, maxConcurrency } = resolvedConfig;\n const rps = requestsPerSecond ?? maxConcurrency ?? DEFAULT_REQUESTS_PER_SECOND;\n const throttle = createThrottle(Math.min(rps, MAX_RATE_LIMIT));\n\n return {\n execute: fn => throttle.execute(fn),\n };\n}\n"],"mappings":";;;AAEA,MAAM,8BAA8B;AACpC,MAAM,iBAAiB;;;;;;;;;AA2BvB,SAAgB,sBAAsB,QAA2D;AAC/F,KAAI,WAAW,MACb,QAAO,EAAE,UAAS,OAAM,IAAI,EAAE;CAIhC,MAAM,EAAE,mBAAmB,mBADa,OAAO,WAAW,WAAW,EAAE,mBAAmB,QAAQ,GAAG;CAErG,MAAM,MAAM,qBAAqB,kBAAkB;CACnD,MAAM,WAAWA,gCAAe,KAAK,IAAI,KAAK,eAAe,CAAC;AAE9D,QAAO,EACL,UAAS,OAAM,SAAS,QAAQ,GAAG,EACpC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createThrottle } from "./throttle.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/utils/rate-limit.ts
|
|
4
4
|
const DEFAULT_REQUESTS_PER_SECOND = 6;
|
|
@@ -15,11 +15,8 @@ function createThrottleManager(config) {
|
|
|
15
15
|
if (config === false) return { execute: (fn) => fn() };
|
|
16
16
|
const { requestsPerSecond, maxConcurrency } = typeof config === "number" ? { requestsPerSecond: config } : config;
|
|
17
17
|
const rps = requestsPerSecond ?? maxConcurrency ?? DEFAULT_REQUESTS_PER_SECOND;
|
|
18
|
-
const
|
|
19
|
-
return { execute:
|
|
20
|
-
await rl();
|
|
21
|
-
return fn();
|
|
22
|
-
} };
|
|
18
|
+
const throttle = createThrottle(Math.min(rps, MAX_RATE_LIMIT));
|
|
19
|
+
return { execute: (fn) => throttle.execute(fn) };
|
|
23
20
|
}
|
|
24
21
|
|
|
25
22
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rate-limit.mjs","names":[],"sources":["../../src/utils/rate-limit.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"rate-limit.mjs","names":[],"sources":["../../src/utils/rate-limit.ts"],"sourcesContent":["import { createThrottle } from './throttle';\n\nconst DEFAULT_REQUESTS_PER_SECOND = 6;\nconst MAX_RATE_LIMIT = 1_000;\n\nexport interface RateLimitConfig {\n /**\n * Maximum number of MAPI requests to start per second.\n * Defaults to 6. Capped at 1000.\n */\n requestsPerSecond?: number;\n /**\n * @deprecated Use `requestsPerSecond` instead.\n * @todo(next-major): Remove this field.\n */\n maxConcurrency?: number;\n}\n\nexport interface ThrottleManager {\n execute: <T>(fn: () => Promise<T>) => Promise<T>;\n}\n\n/**\n * Creates a `ThrottleManager` from the user-supplied `rateLimit` config.\n *\n * - `false` -> no throttling (passthrough)\n * - `number` -> N requests per second\n * - `{ requestsPerSecond: n }` -> N requests per second\n * - `{}` / `undefined` (default) -> DEFAULT_REQUESTS_PER_SECOND per second\n */\nexport function createThrottleManager(config: RateLimitConfig | number | false): ThrottleManager {\n if (config === false) {\n return { execute: fn => fn() };\n }\n\n const resolvedConfig: RateLimitConfig = typeof config === 'number' ? { requestsPerSecond: config } : config;\n const { requestsPerSecond, maxConcurrency } = resolvedConfig;\n const rps = requestsPerSecond ?? maxConcurrency ?? DEFAULT_REQUESTS_PER_SECOND;\n const throttle = createThrottle(Math.min(rps, MAX_RATE_LIMIT));\n\n return {\n execute: fn => throttle.execute(fn),\n };\n}\n"],"mappings":";;;AAEA,MAAM,8BAA8B;AACpC,MAAM,iBAAiB;;;;;;;;;AA2BvB,SAAgB,sBAAsB,QAA2D;AAC/F,KAAI,WAAW,MACb,QAAO,EAAE,UAAS,OAAM,IAAI,EAAE;CAIhC,MAAM,EAAE,mBAAmB,mBADa,OAAO,WAAW,WAAW,EAAE,mBAAmB,QAAQ,GAAG;CAErG,MAAM,MAAM,qBAAqB,kBAAkB;CACnD,MAAM,WAAW,eAAe,KAAK,IAAI,KAAK,eAAe,CAAC;AAE9D,QAAO,EACL,UAAS,OAAM,SAAS,QAAQ,GAAG,EACpC"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/utils/throttle.ts
|
|
3
|
+
/**
|
|
4
|
+
* Creates a per-second rate limiter. At most `limit` calls may start within any
|
|
5
|
+
* rolling one-second window; once the window is full, further calls wait until
|
|
6
|
+
* the oldest call in it ages out. This matches how the Storyblok API enforces
|
|
7
|
+
* its limits: a fixed number of requests per one-second window, not a cap on
|
|
8
|
+
* the number of simultaneous requests.
|
|
9
|
+
*
|
|
10
|
+
* The limiter holds only a list of recent start timestamps, pruned against
|
|
11
|
+
* `Date.now()` on every attempt, and every wait resolves the promise the caller
|
|
12
|
+
* already awaits. It therefore keeps no counter that a scheduled callback must
|
|
13
|
+
* decrement, and schedules no timer that outlives the awaited call. That is a
|
|
14
|
+
* hard requirement on runtimes which suspend between requests and drop pending
|
|
15
|
+
* timers (for example Cloudflare Workers): a shared limiter that released its
|
|
16
|
+
* slots from a detached timer would leak its in-flight count across requests
|
|
17
|
+
* until it deadlocked.
|
|
18
|
+
*
|
|
19
|
+
* A non-positive or non-finite `limit` disables throttling and lets every call
|
|
20
|
+
* through.
|
|
21
|
+
*/
|
|
22
|
+
function createThrottle(initialLimit) {
|
|
23
|
+
const intervalMs = 1e3;
|
|
24
|
+
let limit = initialLimit;
|
|
25
|
+
const starts = [];
|
|
26
|
+
const acquire = () => {
|
|
27
|
+
if (!Number.isFinite(limit) || limit <= 0) return Promise.resolve();
|
|
28
|
+
return new Promise((resolve) => {
|
|
29
|
+
const attempt = () => {
|
|
30
|
+
if (!Number.isFinite(limit) || limit <= 0) {
|
|
31
|
+
resolve();
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
while (starts.length > 0 && starts[0] <= now - intervalMs) starts.shift();
|
|
36
|
+
if (starts.length < limit) {
|
|
37
|
+
starts.push(now);
|
|
38
|
+
resolve();
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const wait = starts[0] + intervalMs - now;
|
|
42
|
+
setTimeout(attempt, wait > 0 ? wait : 0);
|
|
43
|
+
};
|
|
44
|
+
attempt();
|
|
45
|
+
});
|
|
46
|
+
};
|
|
47
|
+
return {
|
|
48
|
+
execute: (fn) => acquire().then(fn),
|
|
49
|
+
setLimit: (n) => {
|
|
50
|
+
limit = n;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
//#endregion
|
|
56
|
+
exports.createThrottle = createThrottle;
|
|
57
|
+
//# sourceMappingURL=throttle.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"throttle.cjs","names":[],"sources":["../../src/utils/throttle.ts"],"sourcesContent":["// This file is duplicated verbatim in @storyblok/api-client and\n// @storyblok/management-api-client. The two copies must stay identical; apply\n// any change to both. It is intentionally not extracted into a shared package\n// so the two independently published clients keep no shared runtime dependency.\n\nexport interface Throttle {\n /** Runs `fn` once a per-second slot is available and returns its result. */\n execute: <T>(fn: () => Promise<T>) => Promise<T>;\n /** Adjusts the per-second limit applied to subsequent windows. */\n setLimit: (limit: number) => void;\n}\n\n/**\n * Creates a per-second rate limiter. At most `limit` calls may start within any\n * rolling one-second window; once the window is full, further calls wait until\n * the oldest call in it ages out. This matches how the Storyblok API enforces\n * its limits: a fixed number of requests per one-second window, not a cap on\n * the number of simultaneous requests.\n *\n * The limiter holds only a list of recent start timestamps, pruned against\n * `Date.now()` on every attempt, and every wait resolves the promise the caller\n * already awaits. It therefore keeps no counter that a scheduled callback must\n * decrement, and schedules no timer that outlives the awaited call. That is a\n * hard requirement on runtimes which suspend between requests and drop pending\n * timers (for example Cloudflare Workers): a shared limiter that released its\n * slots from a detached timer would leak its in-flight count across requests\n * until it deadlocked.\n *\n * A non-positive or non-finite `limit` disables throttling and lets every call\n * through.\n */\nexport function createThrottle(initialLimit: number): Throttle {\n const intervalMs = 1000;\n let limit = initialLimit;\n // Start timestamps of the calls currently inside the rolling window.\n const starts: number[] = [];\n\n const acquire = (): Promise<void> => {\n if (!Number.isFinite(limit) || limit <= 0) {\n return Promise.resolve();\n }\n\n return new Promise<void>((resolve) => {\n const attempt = () => {\n // The limit can drop to a non-positive or non-finite value (via\n // setLimit) while this call is waiting. Re-check the disabled guard so\n // parked callers resolve instead of rescheduling forever.\n if (!Number.isFinite(limit) || limit <= 0) {\n resolve();\n return;\n }\n\n const now = Date.now();\n while (starts.length > 0 && starts[0] <= now - intervalMs) {\n starts.shift();\n }\n\n if (starts.length < limit) {\n starts.push(now);\n resolve();\n return;\n }\n\n // Window is full: retry once the oldest call ages out. The timer only\n // resolves the promise the caller awaits, so it is never orphaned.\n const wait = starts[0] + intervalMs - now;\n setTimeout(attempt, wait > 0 ? wait : 0);\n };\n\n attempt();\n });\n };\n\n return {\n execute: <T>(fn: () => Promise<T>): Promise<T> => acquire().then(fn),\n setLimit: (n: number) => {\n limit = n;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,eAAe,cAAgC;CAC7D,MAAM,aAAa;CACnB,IAAI,QAAQ;CAEZ,MAAM,SAAmB,EAAE;CAE3B,MAAM,gBAA+B;AACnC,MAAI,CAAC,OAAO,SAAS,MAAM,IAAI,SAAS,EACtC,QAAO,QAAQ,SAAS;AAG1B,SAAO,IAAI,SAAe,YAAY;GACpC,MAAM,gBAAgB;AAIpB,QAAI,CAAC,OAAO,SAAS,MAAM,IAAI,SAAS,GAAG;AACzC,cAAS;AACT;;IAGF,MAAM,MAAM,KAAK,KAAK;AACtB,WAAO,OAAO,SAAS,KAAK,OAAO,MAAM,MAAM,WAC7C,QAAO,OAAO;AAGhB,QAAI,OAAO,SAAS,OAAO;AACzB,YAAO,KAAK,IAAI;AAChB,cAAS;AACT;;IAKF,MAAM,OAAO,OAAO,KAAK,aAAa;AACtC,eAAW,SAAS,OAAO,IAAI,OAAO,EAAE;;AAG1C,YAAS;IACT;;AAGJ,QAAO;EACL,UAAa,OAAqC,SAAS,CAAC,KAAK,GAAG;EACpE,WAAW,MAAc;AACvB,WAAQ;;EAEX"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
//#region src/utils/throttle.ts
|
|
2
|
+
/**
|
|
3
|
+
* Creates a per-second rate limiter. At most `limit` calls may start within any
|
|
4
|
+
* rolling one-second window; once the window is full, further calls wait until
|
|
5
|
+
* the oldest call in it ages out. This matches how the Storyblok API enforces
|
|
6
|
+
* its limits: a fixed number of requests per one-second window, not a cap on
|
|
7
|
+
* the number of simultaneous requests.
|
|
8
|
+
*
|
|
9
|
+
* The limiter holds only a list of recent start timestamps, pruned against
|
|
10
|
+
* `Date.now()` on every attempt, and every wait resolves the promise the caller
|
|
11
|
+
* already awaits. It therefore keeps no counter that a scheduled callback must
|
|
12
|
+
* decrement, and schedules no timer that outlives the awaited call. That is a
|
|
13
|
+
* hard requirement on runtimes which suspend between requests and drop pending
|
|
14
|
+
* timers (for example Cloudflare Workers): a shared limiter that released its
|
|
15
|
+
* slots from a detached timer would leak its in-flight count across requests
|
|
16
|
+
* until it deadlocked.
|
|
17
|
+
*
|
|
18
|
+
* A non-positive or non-finite `limit` disables throttling and lets every call
|
|
19
|
+
* through.
|
|
20
|
+
*/
|
|
21
|
+
function createThrottle(initialLimit) {
|
|
22
|
+
const intervalMs = 1e3;
|
|
23
|
+
let limit = initialLimit;
|
|
24
|
+
const starts = [];
|
|
25
|
+
const acquire = () => {
|
|
26
|
+
if (!Number.isFinite(limit) || limit <= 0) return Promise.resolve();
|
|
27
|
+
return new Promise((resolve) => {
|
|
28
|
+
const attempt = () => {
|
|
29
|
+
if (!Number.isFinite(limit) || limit <= 0) {
|
|
30
|
+
resolve();
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const now = Date.now();
|
|
34
|
+
while (starts.length > 0 && starts[0] <= now - intervalMs) starts.shift();
|
|
35
|
+
if (starts.length < limit) {
|
|
36
|
+
starts.push(now);
|
|
37
|
+
resolve();
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const wait = starts[0] + intervalMs - now;
|
|
41
|
+
setTimeout(attempt, wait > 0 ? wait : 0);
|
|
42
|
+
};
|
|
43
|
+
attempt();
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
execute: (fn) => acquire().then(fn),
|
|
48
|
+
setLimit: (n) => {
|
|
49
|
+
limit = n;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
//#endregion
|
|
55
|
+
export { createThrottle };
|
|
56
|
+
//# sourceMappingURL=throttle.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"throttle.mjs","names":[],"sources":["../../src/utils/throttle.ts"],"sourcesContent":["// This file is duplicated verbatim in @storyblok/api-client and\n// @storyblok/management-api-client. The two copies must stay identical; apply\n// any change to both. It is intentionally not extracted into a shared package\n// so the two independently published clients keep no shared runtime dependency.\n\nexport interface Throttle {\n /** Runs `fn` once a per-second slot is available and returns its result. */\n execute: <T>(fn: () => Promise<T>) => Promise<T>;\n /** Adjusts the per-second limit applied to subsequent windows. */\n setLimit: (limit: number) => void;\n}\n\n/**\n * Creates a per-second rate limiter. At most `limit` calls may start within any\n * rolling one-second window; once the window is full, further calls wait until\n * the oldest call in it ages out. This matches how the Storyblok API enforces\n * its limits: a fixed number of requests per one-second window, not a cap on\n * the number of simultaneous requests.\n *\n * The limiter holds only a list of recent start timestamps, pruned against\n * `Date.now()` on every attempt, and every wait resolves the promise the caller\n * already awaits. It therefore keeps no counter that a scheduled callback must\n * decrement, and schedules no timer that outlives the awaited call. That is a\n * hard requirement on runtimes which suspend between requests and drop pending\n * timers (for example Cloudflare Workers): a shared limiter that released its\n * slots from a detached timer would leak its in-flight count across requests\n * until it deadlocked.\n *\n * A non-positive or non-finite `limit` disables throttling and lets every call\n * through.\n */\nexport function createThrottle(initialLimit: number): Throttle {\n const intervalMs = 1000;\n let limit = initialLimit;\n // Start timestamps of the calls currently inside the rolling window.\n const starts: number[] = [];\n\n const acquire = (): Promise<void> => {\n if (!Number.isFinite(limit) || limit <= 0) {\n return Promise.resolve();\n }\n\n return new Promise<void>((resolve) => {\n const attempt = () => {\n // The limit can drop to a non-positive or non-finite value (via\n // setLimit) while this call is waiting. Re-check the disabled guard so\n // parked callers resolve instead of rescheduling forever.\n if (!Number.isFinite(limit) || limit <= 0) {\n resolve();\n return;\n }\n\n const now = Date.now();\n while (starts.length > 0 && starts[0] <= now - intervalMs) {\n starts.shift();\n }\n\n if (starts.length < limit) {\n starts.push(now);\n resolve();\n return;\n }\n\n // Window is full: retry once the oldest call ages out. The timer only\n // resolves the promise the caller awaits, so it is never orphaned.\n const wait = starts[0] + intervalMs - now;\n setTimeout(attempt, wait > 0 ? wait : 0);\n };\n\n attempt();\n });\n };\n\n return {\n execute: <T>(fn: () => Promise<T>): Promise<T> => acquire().then(fn),\n setLimit: (n: number) => {\n limit = n;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,eAAe,cAAgC;CAC7D,MAAM,aAAa;CACnB,IAAI,QAAQ;CAEZ,MAAM,SAAmB,EAAE;CAE3B,MAAM,gBAA+B;AACnC,MAAI,CAAC,OAAO,SAAS,MAAM,IAAI,SAAS,EACtC,QAAO,QAAQ,SAAS;AAG1B,SAAO,IAAI,SAAe,YAAY;GACpC,MAAM,gBAAgB;AAIpB,QAAI,CAAC,OAAO,SAAS,MAAM,IAAI,SAAS,GAAG;AACzC,cAAS;AACT;;IAGF,MAAM,MAAM,KAAK,KAAK;AACtB,WAAO,OAAO,SAAS,KAAK,OAAO,MAAM,MAAM,WAC7C,QAAO,OAAO;AAGhB,QAAI,OAAO,SAAS,OAAO;AACzB,YAAO,KAAK,IAAI;AAChB,cAAS;AACT;;IAKF,MAAM,OAAO,OAAO,KAAK,aAAa;AACtC,eAAW,SAAS,OAAO,IAAI,OAAO,EAAE;;AAG1C,YAAS;IACT;;AAGJ,QAAO;EACL,UAAa,OAAqC,SAAS,CAAC,KAAK,GAAG;EACpE,WAAW,MAAc;AACvB,WAAQ;;EAEX"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@storyblok/management-api-client",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.6.
|
|
4
|
+
"version": "0.6.2",
|
|
5
5
|
"private": false,
|
|
6
6
|
"description": "Storyblok Management API Client",
|
|
7
7
|
"author": "",
|
|
@@ -30,7 +30,6 @@
|
|
|
30
30
|
"access": "public"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"async-sema": "^3.1.1",
|
|
34
33
|
"ky": "^1.14.3",
|
|
35
34
|
"@storyblok/region-helper": "1.5.0"
|
|
36
35
|
},
|