@intlayer/api 9.2.0 → 9.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/fetcher.cjs +29 -2
- package/dist/cjs/fetcher.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/dictionary.cjs +16 -0
- package/dist/cjs/getIntlayerAPI/dictionary.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -0
- package/dist/esm/fetcher.mjs +29 -3
- package/dist/esm/fetcher.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/dictionary.mjs +16 -0
- package/dist/esm/getIntlayerAPI/dictionary.mjs.map +1 -1
- package/dist/esm/index.mjs +2 -2
- package/dist/types/fetcher.d.ts +21 -1
- package/dist/types/fetcher.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/dictionary.d.ts +2 -0
- package/dist/types/getIntlayerAPI/dictionary.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/intlayer-editor/server/dist/controllers/configuration.controller.d.ts +1 -1
- package/dist/types/intlayer-editor/server/dist/controllers/dictionary.controller.d.ts +1 -1
- package/package.json +4 -4
package/dist/cjs/fetcher.cjs
CHANGED
|
@@ -2,6 +2,28 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
2
2
|
|
|
3
3
|
//#region src/fetcher.ts
|
|
4
4
|
/**
|
|
5
|
+
* Error thrown when the backend answers with a non-ok response.
|
|
6
|
+
*
|
|
7
|
+
* Carries the HTTP status and the backend error code alongside the message, so
|
|
8
|
+
* callers can tell a transient failure (5xx, network) from a deterministic one
|
|
9
|
+
* (4xx) instead of blindly retrying.
|
|
10
|
+
*/
|
|
11
|
+
var FetcherError = class extends Error {
|
|
12
|
+
/** HTTP status code of the response. */
|
|
13
|
+
status;
|
|
14
|
+
/** Error code returned by the backend, when available (ex: `DICTIONARY_NOT_FOUND`). */
|
|
15
|
+
code;
|
|
16
|
+
/** Raw error payload returned by the backend. */
|
|
17
|
+
data;
|
|
18
|
+
constructor(message, details) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = "FetcherError";
|
|
21
|
+
this.status = details.status;
|
|
22
|
+
this.code = details.code;
|
|
23
|
+
this.data = details.data;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
5
27
|
* Default options for the fetcher function.
|
|
6
28
|
* Sets the default method to 'GET', the 'Content-Type' header to 'application/json',
|
|
7
29
|
* and includes credentials in the request.
|
|
@@ -112,13 +134,18 @@ const fetcher = async (url, ...options) => {
|
|
|
112
134
|
const urlResult = `${url}${paramsString}`;
|
|
113
135
|
const response = await fetch(urlResult, formattedOptions);
|
|
114
136
|
if (!response.ok) {
|
|
115
|
-
const result = await response.json();
|
|
116
|
-
throw new
|
|
137
|
+
const result = await response.json().catch(() => void 0);
|
|
138
|
+
throw new FetcherError(JSON.stringify(result?.error) ?? "An error occurred", {
|
|
139
|
+
status: response.status,
|
|
140
|
+
code: result?.error?.code,
|
|
141
|
+
data: result?.error
|
|
142
|
+
});
|
|
117
143
|
}
|
|
118
144
|
return await response.json();
|
|
119
145
|
};
|
|
120
146
|
|
|
121
147
|
//#endregion
|
|
148
|
+
exports.FetcherError = FetcherError;
|
|
122
149
|
exports.fetcher = fetcher;
|
|
123
150
|
exports.fetcherOptions = fetcherOptions;
|
|
124
151
|
//# sourceMappingURL=fetcher.cjs.map
|
package/dist/cjs/fetcher.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetcher.cjs","names":[],"sources":["../../src/fetcher.ts"],"sourcesContent":["/**\n * Type definition for options used in the fetcher function.\n * Extends the standard RequestInit interface (excluding 'body'),\n * and adds 'body' and 'params' properties for convenience.\n */\nexport type FetcherOptions = Omit<RequestInit, 'body'> & {\n /**\n * Body of the request. Should be a key-value pair object.\n */\n body?: Record<string, unknown>;\n /**\n * Query parameters to be appended to the URL.\n */\n params?:\n | Record<string, string | string[] | undefined>\n | string[]\n | URLSearchParams;\n};\n\n/**\n * Default options for the fetcher function.\n * Sets the default method to 'GET', the 'Content-Type' header to 'application/json',\n * and includes credentials in the request.\n */\nexport const fetcherOptions: FetcherOptions = {\n method: 'GET', // Default HTTP method\n headers: {\n 'Content-Type': 'application/json', // Default content type\n },\n credentials: 'include',\n};\n\n/**\n * Utility function to remove properties with undefined values from an object.\n * This helps prevent sending undefined values in the request options.\n *\n * @param obj - The object to clean.\n * @returns The cleaned object without undefined values.\n */\nconst removeUndefined = (obj: object) => {\n Object.keys(obj).forEach((key) => {\n if (obj[key as keyof typeof obj] === undefined) {\n delete obj[key as keyof typeof obj];\n }\n });\n return obj;\n};\n\n/**\n * Deeply merges an array of objects into a single object.\n * Later objects in the array overwrite properties of earlier ones.\n *\n * @template T - The type of objects being merged.\n * @param objects - An array of objects to merge.\n * @returns The merged object.\n */\nconst deepMerge = <T extends object>(objects: (T | undefined)[]): T =>\n objects.reduce((acc, obj) => {\n const acc1: T = (acc ?? {}) as T;\n const obj1: T = removeUndefined(obj ?? {}) as T;\n\n if (typeof acc1 === 'object' && typeof obj1 === 'object') {\n // Merge the two objects\n return { ...acc1, ...obj1 };\n }\n\n // If one of them is not an object, return the defined one\n return obj1 ?? acc1;\n }, {} as T)!;\n\n/**\n * Fetcher function to make HTTP requests.\n * It merges default options with user-provided options,\n * handles query parameters and request body,\n * and returns the parsed JSON response.\n *\n * @template T - The expected type of the response data.\n * @param url - The endpoint URL.\n * @param options - Additional options to customize the request.\n * @returns A promise that resolves with the response data of type T.\n *\n * @example\n * ```typescript\n * // Making a GET request with query parameters\n * const data = await fetcher<MyResponseType>('https://api.example.com/data', {\n * params: { search: 'query' },\n * });\n *\n * // Making a POST request with a JSON body\n * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {\n * method: 'POST',\n * body: { key: 'value' },\n * });\n *\n * // Merge body, headers, and params\n * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {\n * method: 'POST',\n * body: { key: 'value' },\n * headers: { 'Content-Type': 'application/json' },\n * params: { search: 'query' },\n * },\n * {\n * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n * params: { page: 1 },\n * });\n * ```\n *\n * Result:\n * ```typescript\n * {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n * params: { page: 1, search: 'query' },\n * body: { key: 'value' },\n * }\n * ```\n */\nexport const fetcher = async <T>(\n url: string,\n ...options: FetcherOptions[]\n): Promise<T> => {\n const { signal } = new AbortController();\n\n // Initialize query parameters string and request body string\n let paramsString = '';\n let bodyString: string | undefined;\n\n // Extract other options excluding 'body', 'params', and 'headers'\n const otherOptions = options.map(\n ({ body, params, headers, ...otherOptions }) => otherOptions\n );\n\n // Merge default options with user-provided options\n const mergedOptions = deepMerge([fetcherOptions, ...otherOptions]);\n\n // Merge default headers with user-provided headers\n const mergedHeaders = deepMerge([\n fetcherOptions.headers,\n ...options.map((option) => option.headers),\n ]);\n\n // Merge query parameters\n const params = deepMerge(options.map((option) => option.params));\n\n const method = mergedOptions.method;\n\n // If the request method is not 'GET' or 'HEAD', prepare the request body\n if (method !== 'GET' && method !== 'HEAD') {\n // Merge all 'body' options\n const body = deepMerge(options.map((option) => option.body));\n if (\n mergedHeaders?.['Content-Type' as keyof HeadersInit] ===\n 'application/x-www-form-urlencoded'\n ) {\n // If the content type is 'application/x-www-form-urlencoded', encode the body accordingly\n bodyString = new URLSearchParams(\n body as Record<string, string>\n ).toString();\n } else {\n // Otherwise, stringify the body as JSON\n bodyString = JSON.stringify(body);\n }\n }\n\n // If there are query parameters, append them to the URL\n if (Object.entries(params).length > 0) {\n paramsString = `?${new URLSearchParams(\n params as Record<string, string>\n ).toString()}`;\n }\n\n // Prepare the final request options\n const formattedOptions: RequestInit = {\n ...mergedOptions,\n headers: mergedHeaders,\n body: bodyString,\n signal,\n };\n\n // Construct the full URL with query parameters\n const urlResult = `${url}${paramsString}`;\n\n // Make the HTTP request using fetch\n const response = await fetch(urlResult, formattedOptions);\n\n if (!response.ok) {\n const result = await response.json();\n\n // You can customize the error message or include more details\n throw new
|
|
1
|
+
{"version":3,"file":"fetcher.cjs","names":[],"sources":["../../src/fetcher.ts"],"sourcesContent":["/**\n * Error thrown when the backend answers with a non-ok response.\n *\n * Carries the HTTP status and the backend error code alongside the message, so\n * callers can tell a transient failure (5xx, network) from a deterministic one\n * (4xx) instead of blindly retrying.\n */\nexport class FetcherError extends Error {\n /** HTTP status code of the response. */\n public readonly status: number;\n /** Error code returned by the backend, when available (ex: `DICTIONARY_NOT_FOUND`). */\n public readonly code?: string;\n /** Raw error payload returned by the backend. */\n public readonly data?: unknown;\n\n constructor(\n message: string,\n details: { status: number; code?: string; data?: unknown }\n ) {\n super(message);\n\n this.name = 'FetcherError';\n this.status = details.status;\n this.code = details.code;\n this.data = details.data;\n }\n}\n\n/**\n * Type definition for options used in the fetcher function.\n * Extends the standard RequestInit interface (excluding 'body'),\n * and adds 'body' and 'params' properties for convenience.\n */\nexport type FetcherOptions = Omit<RequestInit, 'body'> & {\n /**\n * Body of the request. Should be a key-value pair object.\n */\n body?: Record<string, unknown>;\n /**\n * Query parameters to be appended to the URL.\n */\n params?:\n | Record<string, string | string[] | undefined>\n | string[]\n | URLSearchParams;\n};\n\n/**\n * Default options for the fetcher function.\n * Sets the default method to 'GET', the 'Content-Type' header to 'application/json',\n * and includes credentials in the request.\n */\nexport const fetcherOptions: FetcherOptions = {\n method: 'GET', // Default HTTP method\n headers: {\n 'Content-Type': 'application/json', // Default content type\n },\n credentials: 'include',\n};\n\n/**\n * Utility function to remove properties with undefined values from an object.\n * This helps prevent sending undefined values in the request options.\n *\n * @param obj - The object to clean.\n * @returns The cleaned object without undefined values.\n */\nconst removeUndefined = (obj: object) => {\n Object.keys(obj).forEach((key) => {\n if (obj[key as keyof typeof obj] === undefined) {\n delete obj[key as keyof typeof obj];\n }\n });\n return obj;\n};\n\n/**\n * Deeply merges an array of objects into a single object.\n * Later objects in the array overwrite properties of earlier ones.\n *\n * @template T - The type of objects being merged.\n * @param objects - An array of objects to merge.\n * @returns The merged object.\n */\nconst deepMerge = <T extends object>(objects: (T | undefined)[]): T =>\n objects.reduce((acc, obj) => {\n const acc1: T = (acc ?? {}) as T;\n const obj1: T = removeUndefined(obj ?? {}) as T;\n\n if (typeof acc1 === 'object' && typeof obj1 === 'object') {\n // Merge the two objects\n return { ...acc1, ...obj1 };\n }\n\n // If one of them is not an object, return the defined one\n return obj1 ?? acc1;\n }, {} as T)!;\n\n/**\n * Fetcher function to make HTTP requests.\n * It merges default options with user-provided options,\n * handles query parameters and request body,\n * and returns the parsed JSON response.\n *\n * @template T - The expected type of the response data.\n * @param url - The endpoint URL.\n * @param options - Additional options to customize the request.\n * @returns A promise that resolves with the response data of type T.\n *\n * @example\n * ```typescript\n * // Making a GET request with query parameters\n * const data = await fetcher<MyResponseType>('https://api.example.com/data', {\n * params: { search: 'query' },\n * });\n *\n * // Making a POST request with a JSON body\n * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {\n * method: 'POST',\n * body: { key: 'value' },\n * });\n *\n * // Merge body, headers, and params\n * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {\n * method: 'POST',\n * body: { key: 'value' },\n * headers: { 'Content-Type': 'application/json' },\n * params: { search: 'query' },\n * },\n * {\n * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n * params: { page: 1 },\n * });\n * ```\n *\n * Result:\n * ```typescript\n * {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n * params: { page: 1, search: 'query' },\n * body: { key: 'value' },\n * }\n * ```\n */\nexport const fetcher = async <T>(\n url: string,\n ...options: FetcherOptions[]\n): Promise<T> => {\n const { signal } = new AbortController();\n\n // Initialize query parameters string and request body string\n let paramsString = '';\n let bodyString: string | undefined;\n\n // Extract other options excluding 'body', 'params', and 'headers'\n const otherOptions = options.map(\n ({ body, params, headers, ...otherOptions }) => otherOptions\n );\n\n // Merge default options with user-provided options\n const mergedOptions = deepMerge([fetcherOptions, ...otherOptions]);\n\n // Merge default headers with user-provided headers\n const mergedHeaders = deepMerge([\n fetcherOptions.headers,\n ...options.map((option) => option.headers),\n ]);\n\n // Merge query parameters\n const params = deepMerge(options.map((option) => option.params));\n\n const method = mergedOptions.method;\n\n // If the request method is not 'GET' or 'HEAD', prepare the request body\n if (method !== 'GET' && method !== 'HEAD') {\n // Merge all 'body' options\n const body = deepMerge(options.map((option) => option.body));\n if (\n mergedHeaders?.['Content-Type' as keyof HeadersInit] ===\n 'application/x-www-form-urlencoded'\n ) {\n // If the content type is 'application/x-www-form-urlencoded', encode the body accordingly\n bodyString = new URLSearchParams(\n body as Record<string, string>\n ).toString();\n } else {\n // Otherwise, stringify the body as JSON\n bodyString = JSON.stringify(body);\n }\n }\n\n // If there are query parameters, append them to the URL\n if (Object.entries(params).length > 0) {\n paramsString = `?${new URLSearchParams(\n params as Record<string, string>\n ).toString()}`;\n }\n\n // Prepare the final request options\n const formattedOptions: RequestInit = {\n ...mergedOptions,\n headers: mergedHeaders,\n body: bodyString,\n signal,\n };\n\n // Construct the full URL with query parameters\n const urlResult = `${url}${paramsString}`;\n\n // Make the HTTP request using fetch\n const response = await fetch(urlResult, formattedOptions);\n\n if (!response.ok) {\n const result = await response.json().catch(() => undefined);\n\n // You can customize the error message or include more details\n throw new FetcherError(\n JSON.stringify(result?.error) ?? 'An error occurred',\n {\n status: response.status,\n code: result?.error?.code,\n data: result?.error,\n }\n );\n }\n return await response.json();\n};\n"],"mappings":";;;;;;;;;;AAOA,IAAa,eAAb,cAAkC,MAAM;;CAEtC,AAAgB;;CAEhB,AAAgB;;CAEhB,AAAgB;CAEhB,YACE,SACA,SACA;EACA,MAAM,OAAO;EAEb,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,OAAO,QAAQ;EACpB,KAAK,OAAO,QAAQ;CACtB;AACF;;;;;;AA0BA,MAAa,iBAAiC;CAC5C,QAAQ;CACR,SAAS,EACP,gBAAgB,mBAClB;CACA,aAAa;AACf;;;;;;;;AASA,MAAM,mBAAmB,QAAgB;CACvC,OAAO,KAAK,GAAG,CAAC,CAAC,SAAS,QAAQ;EAChC,IAAI,IAAI,SAA6B,QACnC,OAAO,IAAI;CAEf,CAAC;CACD,OAAO;AACT;;;;;;;;;AAUA,MAAM,aAA+B,YACnC,QAAQ,QAAQ,KAAK,QAAQ;CAC3B,MAAM,OAAW,OAAO,CAAC;CACzB,MAAM,OAAU,gBAAgB,OAAO,CAAC,CAAC;CAEzC,IAAI,OAAO,SAAS,YAAY,OAAO,SAAS,UAE9C,OAAO;EAAE,GAAG;EAAM,GAAG;CAAK;CAI5B,OAAO,QAAQ;AACjB,GAAG,CAAC,CAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDZ,MAAa,UAAU,OACrB,KACA,GAAG,YACY;CACf,MAAM,EAAE,WAAW,IAAI,gBAAgB;CAGvC,IAAI,eAAe;CACnB,IAAI;CAGJ,MAAM,eAAe,QAAQ,KAC1B,EAAE,MAAM,QAAQ,SAAS,GAAG,mBAAmB,YAClD;CAGA,MAAM,gBAAgB,UAAU,CAAC,gBAAgB,GAAG,YAAY,CAAC;CAGjE,MAAM,gBAAgB,UAAU,CAC9B,eAAe,SACf,GAAG,QAAQ,KAAK,WAAW,OAAO,OAAO,CAC3C,CAAC;CAGD,MAAM,SAAS,UAAU,QAAQ,KAAK,WAAW,OAAO,MAAM,CAAC;CAE/D,MAAM,SAAS,cAAc;CAG7B,IAAI,WAAW,SAAS,WAAW,QAAQ;EAEzC,MAAM,OAAO,UAAU,QAAQ,KAAK,WAAW,OAAO,IAAI,CAAC;EAC3D,IACE,gBAAgB,oBAChB,qCAGA,aAAa,IAAI,gBACf,IACF,CAAC,CAAC,SAAS;OAGX,aAAa,KAAK,UAAU,IAAI;CAEpC;CAGA,IAAI,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,GAClC,eAAe,IAAI,IAAI,gBACrB,MACF,CAAC,CAAC,SAAS;CAIb,MAAM,mBAAgC;EACpC,GAAG;EACH,SAAS;EACT,MAAM;EACN;CACF;CAGA,MAAM,YAAY,GAAG,MAAM;CAG3B,MAAM,WAAW,MAAM,MAAM,WAAW,gBAAgB;CAExD,IAAI,CAAC,SAAS,IAAI;EAChB,MAAM,SAAS,MAAM,SAAS,KAAK,CAAC,CAAC,YAAY,MAAS;EAG1D,MAAM,IAAI,aACR,KAAK,UAAU,QAAQ,KAAK,KAAK,qBACjC;GACE,QAAQ,SAAS;GACjB,MAAM,QAAQ,OAAO;GACrB,MAAM,QAAQ;EAChB,CACF;CACF;CACA,OAAO,MAAM,SAAS,KAAK;AAC7B"}
|
|
@@ -29,6 +29,21 @@ const getDictionaryAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
29
29
|
*/
|
|
30
30
|
const getDictionary = async (dictionaryKey, version, otherOptions = {}) => await require_fetcher.fetcher(`${PROJECT_API_ROUTE}/${dictionaryKey}`, authAPIOptions, otherOptions, { params: version ? { version: version.toString() } : void 0 });
|
|
31
31
|
/**
|
|
32
|
+
* Retrieves several dictionaries at once from their keys, in a single
|
|
33
|
+
* request. Keys matching no dictionary are absent from the result, so the
|
|
34
|
+
* caller should reconcile the response against the requested keys.
|
|
35
|
+
*
|
|
36
|
+
* @param dictionaryKeys - Dictionary keys to retrieve.
|
|
37
|
+
* @param version - Dictionary version of content.
|
|
38
|
+
*/
|
|
39
|
+
const getDictionariesByKeys = async (dictionaryKeys, version, otherOptions = {}) => await require_fetcher.fetcher(`${PROJECT_API_ROUTE}/by-keys`, authAPIOptions, otherOptions, {
|
|
40
|
+
cache: "no-store",
|
|
41
|
+
params: {
|
|
42
|
+
keys: dictionaryKeys.join(","),
|
|
43
|
+
version: version?.toString()
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
/**
|
|
32
47
|
* Adds a new dictionary to the database.
|
|
33
48
|
* @param dictionary - Dictionary data.
|
|
34
49
|
*/
|
|
@@ -58,6 +73,7 @@ const getDictionaryAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
58
73
|
getDictionariesKeys,
|
|
59
74
|
getDictionariesUpdateTimestamp,
|
|
60
75
|
getDictionary,
|
|
76
|
+
getDictionariesByKeys,
|
|
61
77
|
pushDictionaries,
|
|
62
78
|
addDictionary,
|
|
63
79
|
updateDictionary,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dictionary.cjs","names":["editor","fetcher","createEndpoint"],"sources":["../../../src/getIntlayerAPI/dictionary.ts"],"sourcesContent":["import type {\n AddDictionaryBody,\n AddDictionaryResult,\n DeleteDictionaryParam,\n DeleteDictionaryResult,\n GetDictionariesKeysResult,\n GetDictionariesParams,\n GetDictionariesResult,\n GetDictionariesUpdateTimestampResult,\n GetDictionaryParams,\n GetDictionaryQuery,\n GetDictionaryResult,\n PushDictionariesBody,\n PushDictionariesResult,\n UpdateDictionaryBody,\n UpdateDictionaryResult,\n} from '@intlayer/backend';\nimport { editor } from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { createEndpoint } from '../cms/createIntlayerCMS';\nimport { type FetcherOptions, fetcher } from '../fetcher';\n\nexport const getDictionaryAPI = (\n authAPIOptions: FetcherOptions = {},\n intlayerConfig?: IntlayerConfig\n) => {\n const backendURL = intlayerConfig?.editor?.backendURL ?? editor.backendURL;\n\n const PROJECT_API_ROUTE = `${backendURL}/api/dictionary`;\n\n /**\n * Retrieves a list of dictionaries based on filters and pagination.\n * @param filters - Filters and pagination options.\n */\n const getDictionaries = async (\n filters?: GetDictionariesParams,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionariesResult>(\n PROJECT_API_ROUTE,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n // @ts-ignore Number of parameter will be stringified by the fetcher\n params: filters,\n }\n );\n\n /**\n * Retrieves a list of dictionary keys related to the project.\n */\n const getDictionariesKeys = async (otherOptions: FetcherOptions = {}) =>\n await fetcher<GetDictionariesKeysResult>(\n `${PROJECT_API_ROUTE}/keys`,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n }\n );\n\n /**\n * Retrieves a list of dictionary keys related to the project.\n */\n const getDictionariesUpdateTimestamp = async (\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionariesUpdateTimestampResult>(\n `${PROJECT_API_ROUTE}/update`,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n }\n );\n\n /**\n * Retrieves a dictionary by its key and version.\n * @param dictionaryKey - Dictionary key.\n * @param version - Dictionary version of content.\n */\n const getDictionary = async (\n dictionaryKey: GetDictionaryParams['dictionaryKey'],\n version?: GetDictionaryQuery['version'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionaryResult>(\n `${PROJECT_API_ROUTE}/${dictionaryKey}`,\n authAPIOptions,\n otherOptions,\n {\n params: version ? { version: version.toString() } : undefined,\n }\n );\n\n /**\n * Adds a new dictionary to the database.\n * @param dictionary - Dictionary data.\n */\n const addDictionary = async (\n body: AddDictionaryBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AddDictionaryResult>(\n `${PROJECT_API_ROUTE}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'POST',\n body,\n }\n );\n\n const pushDictionaries = async (\n dictionaries: PushDictionariesBody['dictionaries'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<PushDictionariesResult>(\n `${PROJECT_API_ROUTE}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'PATCH',\n body: { dictionaries },\n }\n );\n\n /**\n * Updates an existing dictionary in the database.\n * @param dictionary - Updated dictionary data.\n */\n const updateDictionary = async (\n dictionary: UpdateDictionaryBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<UpdateDictionaryResult>(\n `${PROJECT_API_ROUTE}/${dictionary.id}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'PUT',\n body: dictionary,\n }\n );\n\n /**\n * Deletes a dictionary from the database by its ID.\n * @param id - Dictionary ID.\n */\n const deleteDictionary = async (\n id: DeleteDictionaryParam['dictionaryId'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<DeleteDictionaryResult>(\n `${PROJECT_API_ROUTE}/${id}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'DELETE',\n }\n );\n\n return {\n getDictionaries,\n getDictionariesKeys,\n getDictionariesUpdateTimestamp,\n getDictionary,\n pushDictionaries,\n addDictionary,\n updateDictionary,\n deleteDictionary,\n };\n};\n\n/**\n * Authenticated `dictionary` endpoint bound to an Intlayer CMS authenticator.\n *\n * Pass an authenticator created with `createIntlayerCMS`, or omit it to use\n * the build-time configuration (`@intlayer/config/built`).\n */\nexport const dictionaryEndpoint = createEndpoint(getDictionaryAPI);\n"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"dictionary.cjs","names":["editor","fetcher","createEndpoint"],"sources":["../../../src/getIntlayerAPI/dictionary.ts"],"sourcesContent":["import type {\n AddDictionaryBody,\n AddDictionaryResult,\n DeleteDictionaryParam,\n DeleteDictionaryResult,\n GetDictionariesByKeysResult,\n GetDictionariesKeysResult,\n GetDictionariesParams,\n GetDictionariesResult,\n GetDictionariesUpdateTimestampResult,\n GetDictionaryParams,\n GetDictionaryQuery,\n GetDictionaryResult,\n PushDictionariesBody,\n PushDictionariesResult,\n UpdateDictionaryBody,\n UpdateDictionaryResult,\n} from '@intlayer/backend';\nimport { editor } from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { createEndpoint } from '../cms/createIntlayerCMS';\nimport { type FetcherOptions, fetcher } from '../fetcher';\n\nexport const getDictionaryAPI = (\n authAPIOptions: FetcherOptions = {},\n intlayerConfig?: IntlayerConfig\n) => {\n const backendURL = intlayerConfig?.editor?.backendURL ?? editor.backendURL;\n\n const PROJECT_API_ROUTE = `${backendURL}/api/dictionary`;\n\n /**\n * Retrieves a list of dictionaries based on filters and pagination.\n * @param filters - Filters and pagination options.\n */\n const getDictionaries = async (\n filters?: GetDictionariesParams,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionariesResult>(\n PROJECT_API_ROUTE,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n // @ts-ignore Number of parameter will be stringified by the fetcher\n params: filters,\n }\n );\n\n /**\n * Retrieves a list of dictionary keys related to the project.\n */\n const getDictionariesKeys = async (otherOptions: FetcherOptions = {}) =>\n await fetcher<GetDictionariesKeysResult>(\n `${PROJECT_API_ROUTE}/keys`,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n }\n );\n\n /**\n * Retrieves a list of dictionary keys related to the project.\n */\n const getDictionariesUpdateTimestamp = async (\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionariesUpdateTimestampResult>(\n `${PROJECT_API_ROUTE}/update`,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n }\n );\n\n /**\n * Retrieves a dictionary by its key and version.\n * @param dictionaryKey - Dictionary key.\n * @param version - Dictionary version of content.\n */\n const getDictionary = async (\n dictionaryKey: GetDictionaryParams['dictionaryKey'],\n version?: GetDictionaryQuery['version'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionaryResult>(\n `${PROJECT_API_ROUTE}/${dictionaryKey}`,\n authAPIOptions,\n otherOptions,\n {\n params: version ? { version: version.toString() } : undefined,\n }\n );\n\n /**\n * Retrieves several dictionaries at once from their keys, in a single\n * request. Keys matching no dictionary are absent from the result, so the\n * caller should reconcile the response against the requested keys.\n *\n * @param dictionaryKeys - Dictionary keys to retrieve.\n * @param version - Dictionary version of content.\n */\n const getDictionariesByKeys = async (\n dictionaryKeys: string[],\n version?: GetDictionaryQuery['version'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionariesByKeysResult>(\n `${PROJECT_API_ROUTE}/by-keys`,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n params: {\n keys: dictionaryKeys.join(','),\n version: version?.toString(),\n },\n }\n );\n\n /**\n * Adds a new dictionary to the database.\n * @param dictionary - Dictionary data.\n */\n const addDictionary = async (\n body: AddDictionaryBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AddDictionaryResult>(\n `${PROJECT_API_ROUTE}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'POST',\n body,\n }\n );\n\n const pushDictionaries = async (\n dictionaries: PushDictionariesBody['dictionaries'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<PushDictionariesResult>(\n `${PROJECT_API_ROUTE}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'PATCH',\n body: { dictionaries },\n }\n );\n\n /**\n * Updates an existing dictionary in the database.\n * @param dictionary - Updated dictionary data.\n */\n const updateDictionary = async (\n dictionary: UpdateDictionaryBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<UpdateDictionaryResult>(\n `${PROJECT_API_ROUTE}/${dictionary.id}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'PUT',\n body: dictionary,\n }\n );\n\n /**\n * Deletes a dictionary from the database by its ID.\n * @param id - Dictionary ID.\n */\n const deleteDictionary = async (\n id: DeleteDictionaryParam['dictionaryId'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<DeleteDictionaryResult>(\n `${PROJECT_API_ROUTE}/${id}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'DELETE',\n }\n );\n\n return {\n getDictionaries,\n getDictionariesKeys,\n getDictionariesUpdateTimestamp,\n getDictionary,\n getDictionariesByKeys,\n pushDictionaries,\n addDictionary,\n updateDictionary,\n deleteDictionary,\n };\n};\n\n/**\n * Authenticated `dictionary` endpoint bound to an Intlayer CMS authenticator.\n *\n * Pass an authenticator created with `createIntlayerCMS`, or omit it to use\n * the build-time configuration (`@intlayer/config/built`).\n */\nexport const dictionaryEndpoint = createEndpoint(getDictionaryAPI);\n"],"mappings":";;;;;;AAuBA,MAAa,oBACX,iBAAiC,CAAC,GAClC,mBACG;CAGH,MAAM,oBAAoB,GAFP,gBAAgB,QAAQ,cAAcA,8BAAO,WAExB;;;;;CAMxC,MAAM,kBAAkB,OACtB,SACA,eAA+B,CAAC,MAEhC,MAAMC,wBACJ,mBACA,gBACA,cACA;EACE,OAAO;EAEP,QAAQ;CACV,CACF;;;;CAKF,MAAM,sBAAsB,OAAO,eAA+B,CAAC,MACjE,MAAMA,wBACJ,GAAG,kBAAkB,QACrB,gBACA,cACA,EACE,OAAO,WACT,CACF;;;;CAKF,MAAM,iCAAiC,OACrC,eAA+B,CAAC,MAEhC,MAAMA,wBACJ,GAAG,kBAAkB,UACrB,gBACA,cACA,EACE,OAAO,WACT,CACF;;;;;;CAOF,MAAM,gBAAgB,OACpB,eACA,SACA,eAA+B,CAAC,MAEhC,MAAMA,wBACJ,GAAG,kBAAkB,GAAG,iBACxB,gBACA,cACA,EACE,QAAQ,UAAU,EAAE,SAAS,QAAQ,SAAS,EAAE,IAAI,OACtD,CACF;;;;;;;;;CAUF,MAAM,wBAAwB,OAC5B,gBACA,SACA,eAA+B,CAAC,MAEhC,MAAMA,wBACJ,GAAG,kBAAkB,WACrB,gBACA,cACA;EACE,OAAO;EACP,QAAQ;GACN,MAAM,eAAe,KAAK,GAAG;GAC7B,SAAS,SAAS,SAAS;EAC7B;CACF,CACF;;;;;CAMF,MAAM,gBAAgB,OACpB,MACA,eAA+B,CAAC,MAEhC,MAAMA,wBACJ,GAAG,qBACH,gBACA,cACA;EACE,QAAQ;EACR;CACF,CACF;CAEF,MAAM,mBAAmB,OACvB,cACA,eAA+B,CAAC,MAEhC,MAAMA,wBACJ,GAAG,qBACH,gBACA,cACA;EACE,QAAQ;EACR,MAAM,EAAE,aAAa;CACvB,CACF;;;;;CAMF,MAAM,mBAAmB,OACvB,YACA,eAA+B,CAAC,MAEhC,MAAMA,wBACJ,GAAG,kBAAkB,GAAG,WAAW,MACnC,gBACA,cACA;EACE,QAAQ;EACR,MAAM;CACR,CACF;;;;;CAMF,MAAM,mBAAmB,OACvB,IACA,eAA+B,CAAC,MAEhC,MAAMA,wBACJ,GAAG,kBAAkB,GAAG,MACxB,gBACA,cACA,EACE,QAAQ,SACV,CACF;CAEF,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;;;;;;;AAQA,MAAa,qBAAqBC,6CAAe,gBAAgB"}
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -29,6 +29,7 @@ const require_distantDictionary_fetchDistantDictionaries = require('./distantDic
|
|
|
29
29
|
const require_distantDictionary_fetchDistantDictionary = require('./distantDictionary/fetchDistantDictionary.cjs');
|
|
30
30
|
const require_getIntlayerAPI_index = require('./getIntlayerAPI/index.cjs');
|
|
31
31
|
|
|
32
|
+
exports.FetcherError = require_fetcher.FetcherError;
|
|
32
33
|
exports.aiEndpoint = require_getIntlayerAPI_ai.aiEndpoint;
|
|
33
34
|
exports.analyticsEndpoint = require_getIntlayerAPI_analytics.analyticsEndpoint;
|
|
34
35
|
exports.assetEndpoint = require_getIntlayerAPI_asset.assetEndpoint;
|
package/dist/esm/fetcher.mjs
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
//#region src/fetcher.ts
|
|
2
2
|
/**
|
|
3
|
+
* Error thrown when the backend answers with a non-ok response.
|
|
4
|
+
*
|
|
5
|
+
* Carries the HTTP status and the backend error code alongside the message, so
|
|
6
|
+
* callers can tell a transient failure (5xx, network) from a deterministic one
|
|
7
|
+
* (4xx) instead of blindly retrying.
|
|
8
|
+
*/
|
|
9
|
+
var FetcherError = class extends Error {
|
|
10
|
+
/** HTTP status code of the response. */
|
|
11
|
+
status;
|
|
12
|
+
/** Error code returned by the backend, when available (ex: `DICTIONARY_NOT_FOUND`). */
|
|
13
|
+
code;
|
|
14
|
+
/** Raw error payload returned by the backend. */
|
|
15
|
+
data;
|
|
16
|
+
constructor(message, details) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = "FetcherError";
|
|
19
|
+
this.status = details.status;
|
|
20
|
+
this.code = details.code;
|
|
21
|
+
this.data = details.data;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
3
25
|
* Default options for the fetcher function.
|
|
4
26
|
* Sets the default method to 'GET', the 'Content-Type' header to 'application/json',
|
|
5
27
|
* and includes credentials in the request.
|
|
@@ -110,12 +132,16 @@ const fetcher = async (url, ...options) => {
|
|
|
110
132
|
const urlResult = `${url}${paramsString}`;
|
|
111
133
|
const response = await fetch(urlResult, formattedOptions);
|
|
112
134
|
if (!response.ok) {
|
|
113
|
-
const result = await response.json();
|
|
114
|
-
throw new
|
|
135
|
+
const result = await response.json().catch(() => void 0);
|
|
136
|
+
throw new FetcherError(JSON.stringify(result?.error) ?? "An error occurred", {
|
|
137
|
+
status: response.status,
|
|
138
|
+
code: result?.error?.code,
|
|
139
|
+
data: result?.error
|
|
140
|
+
});
|
|
115
141
|
}
|
|
116
142
|
return await response.json();
|
|
117
143
|
};
|
|
118
144
|
|
|
119
145
|
//#endregion
|
|
120
|
-
export { fetcher, fetcherOptions };
|
|
146
|
+
export { FetcherError, fetcher, fetcherOptions };
|
|
121
147
|
//# sourceMappingURL=fetcher.mjs.map
|
package/dist/esm/fetcher.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetcher.mjs","names":[],"sources":["../../src/fetcher.ts"],"sourcesContent":["/**\n * Type definition for options used in the fetcher function.\n * Extends the standard RequestInit interface (excluding 'body'),\n * and adds 'body' and 'params' properties for convenience.\n */\nexport type FetcherOptions = Omit<RequestInit, 'body'> & {\n /**\n * Body of the request. Should be a key-value pair object.\n */\n body?: Record<string, unknown>;\n /**\n * Query parameters to be appended to the URL.\n */\n params?:\n | Record<string, string | string[] | undefined>\n | string[]\n | URLSearchParams;\n};\n\n/**\n * Default options for the fetcher function.\n * Sets the default method to 'GET', the 'Content-Type' header to 'application/json',\n * and includes credentials in the request.\n */\nexport const fetcherOptions: FetcherOptions = {\n method: 'GET', // Default HTTP method\n headers: {\n 'Content-Type': 'application/json', // Default content type\n },\n credentials: 'include',\n};\n\n/**\n * Utility function to remove properties with undefined values from an object.\n * This helps prevent sending undefined values in the request options.\n *\n * @param obj - The object to clean.\n * @returns The cleaned object without undefined values.\n */\nconst removeUndefined = (obj: object) => {\n Object.keys(obj).forEach((key) => {\n if (obj[key as keyof typeof obj] === undefined) {\n delete obj[key as keyof typeof obj];\n }\n });\n return obj;\n};\n\n/**\n * Deeply merges an array of objects into a single object.\n * Later objects in the array overwrite properties of earlier ones.\n *\n * @template T - The type of objects being merged.\n * @param objects - An array of objects to merge.\n * @returns The merged object.\n */\nconst deepMerge = <T extends object>(objects: (T | undefined)[]): T =>\n objects.reduce((acc, obj) => {\n const acc1: T = (acc ?? {}) as T;\n const obj1: T = removeUndefined(obj ?? {}) as T;\n\n if (typeof acc1 === 'object' && typeof obj1 === 'object') {\n // Merge the two objects\n return { ...acc1, ...obj1 };\n }\n\n // If one of them is not an object, return the defined one\n return obj1 ?? acc1;\n }, {} as T)!;\n\n/**\n * Fetcher function to make HTTP requests.\n * It merges default options with user-provided options,\n * handles query parameters and request body,\n * and returns the parsed JSON response.\n *\n * @template T - The expected type of the response data.\n * @param url - The endpoint URL.\n * @param options - Additional options to customize the request.\n * @returns A promise that resolves with the response data of type T.\n *\n * @example\n * ```typescript\n * // Making a GET request with query parameters\n * const data = await fetcher<MyResponseType>('https://api.example.com/data', {\n * params: { search: 'query' },\n * });\n *\n * // Making a POST request with a JSON body\n * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {\n * method: 'POST',\n * body: { key: 'value' },\n * });\n *\n * // Merge body, headers, and params\n * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {\n * method: 'POST',\n * body: { key: 'value' },\n * headers: { 'Content-Type': 'application/json' },\n * params: { search: 'query' },\n * },\n * {\n * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n * params: { page: 1 },\n * });\n * ```\n *\n * Result:\n * ```typescript\n * {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n * params: { page: 1, search: 'query' },\n * body: { key: 'value' },\n * }\n * ```\n */\nexport const fetcher = async <T>(\n url: string,\n ...options: FetcherOptions[]\n): Promise<T> => {\n const { signal } = new AbortController();\n\n // Initialize query parameters string and request body string\n let paramsString = '';\n let bodyString: string | undefined;\n\n // Extract other options excluding 'body', 'params', and 'headers'\n const otherOptions = options.map(\n ({ body, params, headers, ...otherOptions }) => otherOptions\n );\n\n // Merge default options with user-provided options\n const mergedOptions = deepMerge([fetcherOptions, ...otherOptions]);\n\n // Merge default headers with user-provided headers\n const mergedHeaders = deepMerge([\n fetcherOptions.headers,\n ...options.map((option) => option.headers),\n ]);\n\n // Merge query parameters\n const params = deepMerge(options.map((option) => option.params));\n\n const method = mergedOptions.method;\n\n // If the request method is not 'GET' or 'HEAD', prepare the request body\n if (method !== 'GET' && method !== 'HEAD') {\n // Merge all 'body' options\n const body = deepMerge(options.map((option) => option.body));\n if (\n mergedHeaders?.['Content-Type' as keyof HeadersInit] ===\n 'application/x-www-form-urlencoded'\n ) {\n // If the content type is 'application/x-www-form-urlencoded', encode the body accordingly\n bodyString = new URLSearchParams(\n body as Record<string, string>\n ).toString();\n } else {\n // Otherwise, stringify the body as JSON\n bodyString = JSON.stringify(body);\n }\n }\n\n // If there are query parameters, append them to the URL\n if (Object.entries(params).length > 0) {\n paramsString = `?${new URLSearchParams(\n params as Record<string, string>\n ).toString()}`;\n }\n\n // Prepare the final request options\n const formattedOptions: RequestInit = {\n ...mergedOptions,\n headers: mergedHeaders,\n body: bodyString,\n signal,\n };\n\n // Construct the full URL with query parameters\n const urlResult = `${url}${paramsString}`;\n\n // Make the HTTP request using fetch\n const response = await fetch(urlResult, formattedOptions);\n\n if (!response.ok) {\n const result = await response.json();\n\n // You can customize the error message or include more details\n throw new
|
|
1
|
+
{"version":3,"file":"fetcher.mjs","names":[],"sources":["../../src/fetcher.ts"],"sourcesContent":["/**\n * Error thrown when the backend answers with a non-ok response.\n *\n * Carries the HTTP status and the backend error code alongside the message, so\n * callers can tell a transient failure (5xx, network) from a deterministic one\n * (4xx) instead of blindly retrying.\n */\nexport class FetcherError extends Error {\n /** HTTP status code of the response. */\n public readonly status: number;\n /** Error code returned by the backend, when available (ex: `DICTIONARY_NOT_FOUND`). */\n public readonly code?: string;\n /** Raw error payload returned by the backend. */\n public readonly data?: unknown;\n\n constructor(\n message: string,\n details: { status: number; code?: string; data?: unknown }\n ) {\n super(message);\n\n this.name = 'FetcherError';\n this.status = details.status;\n this.code = details.code;\n this.data = details.data;\n }\n}\n\n/**\n * Type definition for options used in the fetcher function.\n * Extends the standard RequestInit interface (excluding 'body'),\n * and adds 'body' and 'params' properties for convenience.\n */\nexport type FetcherOptions = Omit<RequestInit, 'body'> & {\n /**\n * Body of the request. Should be a key-value pair object.\n */\n body?: Record<string, unknown>;\n /**\n * Query parameters to be appended to the URL.\n */\n params?:\n | Record<string, string | string[] | undefined>\n | string[]\n | URLSearchParams;\n};\n\n/**\n * Default options for the fetcher function.\n * Sets the default method to 'GET', the 'Content-Type' header to 'application/json',\n * and includes credentials in the request.\n */\nexport const fetcherOptions: FetcherOptions = {\n method: 'GET', // Default HTTP method\n headers: {\n 'Content-Type': 'application/json', // Default content type\n },\n credentials: 'include',\n};\n\n/**\n * Utility function to remove properties with undefined values from an object.\n * This helps prevent sending undefined values in the request options.\n *\n * @param obj - The object to clean.\n * @returns The cleaned object without undefined values.\n */\nconst removeUndefined = (obj: object) => {\n Object.keys(obj).forEach((key) => {\n if (obj[key as keyof typeof obj] === undefined) {\n delete obj[key as keyof typeof obj];\n }\n });\n return obj;\n};\n\n/**\n * Deeply merges an array of objects into a single object.\n * Later objects in the array overwrite properties of earlier ones.\n *\n * @template T - The type of objects being merged.\n * @param objects - An array of objects to merge.\n * @returns The merged object.\n */\nconst deepMerge = <T extends object>(objects: (T | undefined)[]): T =>\n objects.reduce((acc, obj) => {\n const acc1: T = (acc ?? {}) as T;\n const obj1: T = removeUndefined(obj ?? {}) as T;\n\n if (typeof acc1 === 'object' && typeof obj1 === 'object') {\n // Merge the two objects\n return { ...acc1, ...obj1 };\n }\n\n // If one of them is not an object, return the defined one\n return obj1 ?? acc1;\n }, {} as T)!;\n\n/**\n * Fetcher function to make HTTP requests.\n * It merges default options with user-provided options,\n * handles query parameters and request body,\n * and returns the parsed JSON response.\n *\n * @template T - The expected type of the response data.\n * @param url - The endpoint URL.\n * @param options - Additional options to customize the request.\n * @returns A promise that resolves with the response data of type T.\n *\n * @example\n * ```typescript\n * // Making a GET request with query parameters\n * const data = await fetcher<MyResponseType>('https://api.example.com/data', {\n * params: { search: 'query' },\n * });\n *\n * // Making a POST request with a JSON body\n * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {\n * method: 'POST',\n * body: { key: 'value' },\n * });\n *\n * // Merge body, headers, and params\n * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {\n * method: 'POST',\n * body: { key: 'value' },\n * headers: { 'Content-Type': 'application/json' },\n * params: { search: 'query' },\n * },\n * {\n * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n * params: { page: 1 },\n * });\n * ```\n *\n * Result:\n * ```typescript\n * {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n * params: { page: 1, search: 'query' },\n * body: { key: 'value' },\n * }\n * ```\n */\nexport const fetcher = async <T>(\n url: string,\n ...options: FetcherOptions[]\n): Promise<T> => {\n const { signal } = new AbortController();\n\n // Initialize query parameters string and request body string\n let paramsString = '';\n let bodyString: string | undefined;\n\n // Extract other options excluding 'body', 'params', and 'headers'\n const otherOptions = options.map(\n ({ body, params, headers, ...otherOptions }) => otherOptions\n );\n\n // Merge default options with user-provided options\n const mergedOptions = deepMerge([fetcherOptions, ...otherOptions]);\n\n // Merge default headers with user-provided headers\n const mergedHeaders = deepMerge([\n fetcherOptions.headers,\n ...options.map((option) => option.headers),\n ]);\n\n // Merge query parameters\n const params = deepMerge(options.map((option) => option.params));\n\n const method = mergedOptions.method;\n\n // If the request method is not 'GET' or 'HEAD', prepare the request body\n if (method !== 'GET' && method !== 'HEAD') {\n // Merge all 'body' options\n const body = deepMerge(options.map((option) => option.body));\n if (\n mergedHeaders?.['Content-Type' as keyof HeadersInit] ===\n 'application/x-www-form-urlencoded'\n ) {\n // If the content type is 'application/x-www-form-urlencoded', encode the body accordingly\n bodyString = new URLSearchParams(\n body as Record<string, string>\n ).toString();\n } else {\n // Otherwise, stringify the body as JSON\n bodyString = JSON.stringify(body);\n }\n }\n\n // If there are query parameters, append them to the URL\n if (Object.entries(params).length > 0) {\n paramsString = `?${new URLSearchParams(\n params as Record<string, string>\n ).toString()}`;\n }\n\n // Prepare the final request options\n const formattedOptions: RequestInit = {\n ...mergedOptions,\n headers: mergedHeaders,\n body: bodyString,\n signal,\n };\n\n // Construct the full URL with query parameters\n const urlResult = `${url}${paramsString}`;\n\n // Make the HTTP request using fetch\n const response = await fetch(urlResult, formattedOptions);\n\n if (!response.ok) {\n const result = await response.json().catch(() => undefined);\n\n // You can customize the error message or include more details\n throw new FetcherError(\n JSON.stringify(result?.error) ?? 'An error occurred',\n {\n status: response.status,\n code: result?.error?.code,\n data: result?.error,\n }\n );\n }\n return await response.json();\n};\n"],"mappings":";;;;;;;;AAOA,IAAa,eAAb,cAAkC,MAAM;;CAEtC,AAAgB;;CAEhB,AAAgB;;CAEhB,AAAgB;CAEhB,YACE,SACA,SACA;EACA,MAAM,OAAO;EAEb,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,OAAO,QAAQ;EACpB,KAAK,OAAO,QAAQ;CACtB;AACF;;;;;;AA0BA,MAAa,iBAAiC;CAC5C,QAAQ;CACR,SAAS,EACP,gBAAgB,mBAClB;CACA,aAAa;AACf;;;;;;;;AASA,MAAM,mBAAmB,QAAgB;CACvC,OAAO,KAAK,GAAG,CAAC,CAAC,SAAS,QAAQ;EAChC,IAAI,IAAI,SAA6B,QACnC,OAAO,IAAI;CAEf,CAAC;CACD,OAAO;AACT;;;;;;;;;AAUA,MAAM,aAA+B,YACnC,QAAQ,QAAQ,KAAK,QAAQ;CAC3B,MAAM,OAAW,OAAO,CAAC;CACzB,MAAM,OAAU,gBAAgB,OAAO,CAAC,CAAC;CAEzC,IAAI,OAAO,SAAS,YAAY,OAAO,SAAS,UAE9C,OAAO;EAAE,GAAG;EAAM,GAAG;CAAK;CAI5B,OAAO,QAAQ;AACjB,GAAG,CAAC,CAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDZ,MAAa,UAAU,OACrB,KACA,GAAG,YACY;CACf,MAAM,EAAE,WAAW,IAAI,gBAAgB;CAGvC,IAAI,eAAe;CACnB,IAAI;CAGJ,MAAM,eAAe,QAAQ,KAC1B,EAAE,MAAM,QAAQ,SAAS,GAAG,mBAAmB,YAClD;CAGA,MAAM,gBAAgB,UAAU,CAAC,gBAAgB,GAAG,YAAY,CAAC;CAGjE,MAAM,gBAAgB,UAAU,CAC9B,eAAe,SACf,GAAG,QAAQ,KAAK,WAAW,OAAO,OAAO,CAC3C,CAAC;CAGD,MAAM,SAAS,UAAU,QAAQ,KAAK,WAAW,OAAO,MAAM,CAAC;CAE/D,MAAM,SAAS,cAAc;CAG7B,IAAI,WAAW,SAAS,WAAW,QAAQ;EAEzC,MAAM,OAAO,UAAU,QAAQ,KAAK,WAAW,OAAO,IAAI,CAAC;EAC3D,IACE,gBAAgB,oBAChB,qCAGA,aAAa,IAAI,gBACf,IACF,CAAC,CAAC,SAAS;OAGX,aAAa,KAAK,UAAU,IAAI;CAEpC;CAGA,IAAI,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,GAClC,eAAe,IAAI,IAAI,gBACrB,MACF,CAAC,CAAC,SAAS;CAIb,MAAM,mBAAgC;EACpC,GAAG;EACH,SAAS;EACT,MAAM;EACN;CACF;CAGA,MAAM,YAAY,GAAG,MAAM;CAG3B,MAAM,WAAW,MAAM,MAAM,WAAW,gBAAgB;CAExD,IAAI,CAAC,SAAS,IAAI;EAChB,MAAM,SAAS,MAAM,SAAS,KAAK,CAAC,CAAC,YAAY,MAAS;EAG1D,MAAM,IAAI,aACR,KAAK,UAAU,QAAQ,KAAK,KAAK,qBACjC;GACE,QAAQ,SAAS;GACjB,MAAM,QAAQ,OAAO;GACrB,MAAM,QAAQ;EAChB,CACF;CACF;CACA,OAAO,MAAM,SAAS,KAAK;AAC7B"}
|
|
@@ -28,6 +28,21 @@ const getDictionaryAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
28
28
|
*/
|
|
29
29
|
const getDictionary = async (dictionaryKey, version, otherOptions = {}) => await fetcher(`${PROJECT_API_ROUTE}/${dictionaryKey}`, authAPIOptions, otherOptions, { params: version ? { version: version.toString() } : void 0 });
|
|
30
30
|
/**
|
|
31
|
+
* Retrieves several dictionaries at once from their keys, in a single
|
|
32
|
+
* request. Keys matching no dictionary are absent from the result, so the
|
|
33
|
+
* caller should reconcile the response against the requested keys.
|
|
34
|
+
*
|
|
35
|
+
* @param dictionaryKeys - Dictionary keys to retrieve.
|
|
36
|
+
* @param version - Dictionary version of content.
|
|
37
|
+
*/
|
|
38
|
+
const getDictionariesByKeys = async (dictionaryKeys, version, otherOptions = {}) => await fetcher(`${PROJECT_API_ROUTE}/by-keys`, authAPIOptions, otherOptions, {
|
|
39
|
+
cache: "no-store",
|
|
40
|
+
params: {
|
|
41
|
+
keys: dictionaryKeys.join(","),
|
|
42
|
+
version: version?.toString()
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
/**
|
|
31
46
|
* Adds a new dictionary to the database.
|
|
32
47
|
* @param dictionary - Dictionary data.
|
|
33
48
|
*/
|
|
@@ -57,6 +72,7 @@ const getDictionaryAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
57
72
|
getDictionariesKeys,
|
|
58
73
|
getDictionariesUpdateTimestamp,
|
|
59
74
|
getDictionary,
|
|
75
|
+
getDictionariesByKeys,
|
|
60
76
|
pushDictionaries,
|
|
61
77
|
addDictionary,
|
|
62
78
|
updateDictionary,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dictionary.mjs","names":[],"sources":["../../../src/getIntlayerAPI/dictionary.ts"],"sourcesContent":["import type {\n AddDictionaryBody,\n AddDictionaryResult,\n DeleteDictionaryParam,\n DeleteDictionaryResult,\n GetDictionariesKeysResult,\n GetDictionariesParams,\n GetDictionariesResult,\n GetDictionariesUpdateTimestampResult,\n GetDictionaryParams,\n GetDictionaryQuery,\n GetDictionaryResult,\n PushDictionariesBody,\n PushDictionariesResult,\n UpdateDictionaryBody,\n UpdateDictionaryResult,\n} from '@intlayer/backend';\nimport { editor } from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { createEndpoint } from '../cms/createIntlayerCMS';\nimport { type FetcherOptions, fetcher } from '../fetcher';\n\nexport const getDictionaryAPI = (\n authAPIOptions: FetcherOptions = {},\n intlayerConfig?: IntlayerConfig\n) => {\n const backendURL = intlayerConfig?.editor?.backendURL ?? editor.backendURL;\n\n const PROJECT_API_ROUTE = `${backendURL}/api/dictionary`;\n\n /**\n * Retrieves a list of dictionaries based on filters and pagination.\n * @param filters - Filters and pagination options.\n */\n const getDictionaries = async (\n filters?: GetDictionariesParams,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionariesResult>(\n PROJECT_API_ROUTE,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n // @ts-ignore Number of parameter will be stringified by the fetcher\n params: filters,\n }\n );\n\n /**\n * Retrieves a list of dictionary keys related to the project.\n */\n const getDictionariesKeys = async (otherOptions: FetcherOptions = {}) =>\n await fetcher<GetDictionariesKeysResult>(\n `${PROJECT_API_ROUTE}/keys`,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n }\n );\n\n /**\n * Retrieves a list of dictionary keys related to the project.\n */\n const getDictionariesUpdateTimestamp = async (\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionariesUpdateTimestampResult>(\n `${PROJECT_API_ROUTE}/update`,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n }\n );\n\n /**\n * Retrieves a dictionary by its key and version.\n * @param dictionaryKey - Dictionary key.\n * @param version - Dictionary version of content.\n */\n const getDictionary = async (\n dictionaryKey: GetDictionaryParams['dictionaryKey'],\n version?: GetDictionaryQuery['version'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionaryResult>(\n `${PROJECT_API_ROUTE}/${dictionaryKey}`,\n authAPIOptions,\n otherOptions,\n {\n params: version ? { version: version.toString() } : undefined,\n }\n );\n\n /**\n * Adds a new dictionary to the database.\n * @param dictionary - Dictionary data.\n */\n const addDictionary = async (\n body: AddDictionaryBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AddDictionaryResult>(\n `${PROJECT_API_ROUTE}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'POST',\n body,\n }\n );\n\n const pushDictionaries = async (\n dictionaries: PushDictionariesBody['dictionaries'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<PushDictionariesResult>(\n `${PROJECT_API_ROUTE}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'PATCH',\n body: { dictionaries },\n }\n );\n\n /**\n * Updates an existing dictionary in the database.\n * @param dictionary - Updated dictionary data.\n */\n const updateDictionary = async (\n dictionary: UpdateDictionaryBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<UpdateDictionaryResult>(\n `${PROJECT_API_ROUTE}/${dictionary.id}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'PUT',\n body: dictionary,\n }\n );\n\n /**\n * Deletes a dictionary from the database by its ID.\n * @param id - Dictionary ID.\n */\n const deleteDictionary = async (\n id: DeleteDictionaryParam['dictionaryId'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<DeleteDictionaryResult>(\n `${PROJECT_API_ROUTE}/${id}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'DELETE',\n }\n );\n\n return {\n getDictionaries,\n getDictionariesKeys,\n getDictionariesUpdateTimestamp,\n getDictionary,\n pushDictionaries,\n addDictionary,\n updateDictionary,\n deleteDictionary,\n };\n};\n\n/**\n * Authenticated `dictionary` endpoint bound to an Intlayer CMS authenticator.\n *\n * Pass an authenticator created with `createIntlayerCMS`, or omit it to use\n * the build-time configuration (`@intlayer/config/built`).\n */\nexport const dictionaryEndpoint = createEndpoint(getDictionaryAPI);\n"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"dictionary.mjs","names":[],"sources":["../../../src/getIntlayerAPI/dictionary.ts"],"sourcesContent":["import type {\n AddDictionaryBody,\n AddDictionaryResult,\n DeleteDictionaryParam,\n DeleteDictionaryResult,\n GetDictionariesByKeysResult,\n GetDictionariesKeysResult,\n GetDictionariesParams,\n GetDictionariesResult,\n GetDictionariesUpdateTimestampResult,\n GetDictionaryParams,\n GetDictionaryQuery,\n GetDictionaryResult,\n PushDictionariesBody,\n PushDictionariesResult,\n UpdateDictionaryBody,\n UpdateDictionaryResult,\n} from '@intlayer/backend';\nimport { editor } from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { createEndpoint } from '../cms/createIntlayerCMS';\nimport { type FetcherOptions, fetcher } from '../fetcher';\n\nexport const getDictionaryAPI = (\n authAPIOptions: FetcherOptions = {},\n intlayerConfig?: IntlayerConfig\n) => {\n const backendURL = intlayerConfig?.editor?.backendURL ?? editor.backendURL;\n\n const PROJECT_API_ROUTE = `${backendURL}/api/dictionary`;\n\n /**\n * Retrieves a list of dictionaries based on filters and pagination.\n * @param filters - Filters and pagination options.\n */\n const getDictionaries = async (\n filters?: GetDictionariesParams,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionariesResult>(\n PROJECT_API_ROUTE,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n // @ts-ignore Number of parameter will be stringified by the fetcher\n params: filters,\n }\n );\n\n /**\n * Retrieves a list of dictionary keys related to the project.\n */\n const getDictionariesKeys = async (otherOptions: FetcherOptions = {}) =>\n await fetcher<GetDictionariesKeysResult>(\n `${PROJECT_API_ROUTE}/keys`,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n }\n );\n\n /**\n * Retrieves a list of dictionary keys related to the project.\n */\n const getDictionariesUpdateTimestamp = async (\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionariesUpdateTimestampResult>(\n `${PROJECT_API_ROUTE}/update`,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n }\n );\n\n /**\n * Retrieves a dictionary by its key and version.\n * @param dictionaryKey - Dictionary key.\n * @param version - Dictionary version of content.\n */\n const getDictionary = async (\n dictionaryKey: GetDictionaryParams['dictionaryKey'],\n version?: GetDictionaryQuery['version'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionaryResult>(\n `${PROJECT_API_ROUTE}/${dictionaryKey}`,\n authAPIOptions,\n otherOptions,\n {\n params: version ? { version: version.toString() } : undefined,\n }\n );\n\n /**\n * Retrieves several dictionaries at once from their keys, in a single\n * request. Keys matching no dictionary are absent from the result, so the\n * caller should reconcile the response against the requested keys.\n *\n * @param dictionaryKeys - Dictionary keys to retrieve.\n * @param version - Dictionary version of content.\n */\n const getDictionariesByKeys = async (\n dictionaryKeys: string[],\n version?: GetDictionaryQuery['version'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDictionariesByKeysResult>(\n `${PROJECT_API_ROUTE}/by-keys`,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n params: {\n keys: dictionaryKeys.join(','),\n version: version?.toString(),\n },\n }\n );\n\n /**\n * Adds a new dictionary to the database.\n * @param dictionary - Dictionary data.\n */\n const addDictionary = async (\n body: AddDictionaryBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AddDictionaryResult>(\n `${PROJECT_API_ROUTE}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'POST',\n body,\n }\n );\n\n const pushDictionaries = async (\n dictionaries: PushDictionariesBody['dictionaries'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<PushDictionariesResult>(\n `${PROJECT_API_ROUTE}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'PATCH',\n body: { dictionaries },\n }\n );\n\n /**\n * Updates an existing dictionary in the database.\n * @param dictionary - Updated dictionary data.\n */\n const updateDictionary = async (\n dictionary: UpdateDictionaryBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<UpdateDictionaryResult>(\n `${PROJECT_API_ROUTE}/${dictionary.id}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'PUT',\n body: dictionary,\n }\n );\n\n /**\n * Deletes a dictionary from the database by its ID.\n * @param id - Dictionary ID.\n */\n const deleteDictionary = async (\n id: DeleteDictionaryParam['dictionaryId'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<DeleteDictionaryResult>(\n `${PROJECT_API_ROUTE}/${id}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'DELETE',\n }\n );\n\n return {\n getDictionaries,\n getDictionariesKeys,\n getDictionariesUpdateTimestamp,\n getDictionary,\n getDictionariesByKeys,\n pushDictionaries,\n addDictionary,\n updateDictionary,\n deleteDictionary,\n };\n};\n\n/**\n * Authenticated `dictionary` endpoint bound to an Intlayer CMS authenticator.\n *\n * Pass an authenticator created with `createIntlayerCMS`, or omit it to use\n * the build-time configuration (`@intlayer/config/built`).\n */\nexport const dictionaryEndpoint = createEndpoint(getDictionaryAPI);\n"],"mappings":";;;;;AAuBA,MAAa,oBACX,iBAAiC,CAAC,GAClC,mBACG;CAGH,MAAM,oBAAoB,GAFP,gBAAgB,QAAQ,cAAc,OAAO,WAExB;;;;;CAMxC,MAAM,kBAAkB,OACtB,SACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,mBACA,gBACA,cACA;EACE,OAAO;EAEP,QAAQ;CACV,CACF;;;;CAKF,MAAM,sBAAsB,OAAO,eAA+B,CAAC,MACjE,MAAM,QACJ,GAAG,kBAAkB,QACrB,gBACA,cACA,EACE,OAAO,WACT,CACF;;;;CAKF,MAAM,iCAAiC,OACrC,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,kBAAkB,UACrB,gBACA,cACA,EACE,OAAO,WACT,CACF;;;;;;CAOF,MAAM,gBAAgB,OACpB,eACA,SACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,kBAAkB,GAAG,iBACxB,gBACA,cACA,EACE,QAAQ,UAAU,EAAE,SAAS,QAAQ,SAAS,EAAE,IAAI,OACtD,CACF;;;;;;;;;CAUF,MAAM,wBAAwB,OAC5B,gBACA,SACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,kBAAkB,WACrB,gBACA,cACA;EACE,OAAO;EACP,QAAQ;GACN,MAAM,eAAe,KAAK,GAAG;GAC7B,SAAS,SAAS,SAAS;EAC7B;CACF,CACF;;;;;CAMF,MAAM,gBAAgB,OACpB,MACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,qBACH,gBACA,cACA;EACE,QAAQ;EACR;CACF,CACF;CAEF,MAAM,mBAAmB,OACvB,cACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,qBACH,gBACA,cACA;EACE,QAAQ;EACR,MAAM,EAAE,aAAa;CACvB,CACF;;;;;CAMF,MAAM,mBAAmB,OACvB,YACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,kBAAkB,GAAG,WAAW,MACnC,gBACA,cACA;EACE,QAAQ;EACR,MAAM;CACR,CACF;;;;;CAMF,MAAM,mBAAmB,OACvB,IACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,kBAAkB,GAAG,MACxB,gBACA,cACA,EACE,QAAQ,SACV,CACF;CAEF,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;;;;;;;AAQA,MAAa,qBAAqB,eAAe,gBAAgB"}
|
package/dist/esm/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { fetcher, fetcherOptions } from "./fetcher.mjs";
|
|
1
|
+
import { FetcherError, fetcher, fetcherOptions } from "./fetcher.mjs";
|
|
2
2
|
import { getOAuthAPI } from "./getIntlayerAPI/oAuth.mjs";
|
|
3
3
|
import { createAuthManager } from "./cms/createAuthManager.mjs";
|
|
4
4
|
import { createEndpoint, createIntlayerCMS } from "./cms/createIntlayerCMS.mjs";
|
|
@@ -28,4 +28,4 @@ import { fetchDistantDictionaries } from "./distantDictionary/fetchDistantDictio
|
|
|
28
28
|
import { fetchDistantDictionary } from "./distantDictionary/fetchDistantDictionary.mjs";
|
|
29
29
|
import { getIntlayerAPI } from "./getIntlayerAPI/index.mjs";
|
|
30
30
|
|
|
31
|
-
export { aiEndpoint, analyticsEndpoint, assetEndpoint, auditEndpoint, bitbucketEndpoint, createAuthManager, createEndpoint, createIntlayerCMS, dictionaryEndpoint, editorEndpoint, environmentEndpoint, fetchDistantDictionaries, fetchDistantDictionary, fetcher, fetcherOptions, getAiAPI, getAnalyticsAPI, getAssetAPI, getAuditAPI, getBitbucketAPI, getDictionaryAPI, getEditorAPI, getEnvironmentAPI, getGithubAPI, getGitlabAPI, getIntlayerAPI, getIntlayerAPIProxy, getNewsletterAPI, getOAuthAPI, getOrganizationAPI, getProjectAPI, getReviewerAPI, getSearchAPI, getShowcaseProjectAPI, getStatusAPI, getStripeAPI, getTagAPI, getTranslateAPI, getUserAPI, githubEndpoint, gitlabEndpoint, newsletterEndpoint, organizationEndpoint, projectEndpoint, reviewerEndpoint, searchEndpoint, showcaseProjectEndpoint, statusEndpoint, stripeEndpoint, tagEndpoint, translateEndpoint, userEndpoint };
|
|
31
|
+
export { FetcherError, aiEndpoint, analyticsEndpoint, assetEndpoint, auditEndpoint, bitbucketEndpoint, createAuthManager, createEndpoint, createIntlayerCMS, dictionaryEndpoint, editorEndpoint, environmentEndpoint, fetchDistantDictionaries, fetchDistantDictionary, fetcher, fetcherOptions, getAiAPI, getAnalyticsAPI, getAssetAPI, getAuditAPI, getBitbucketAPI, getDictionaryAPI, getEditorAPI, getEnvironmentAPI, getGithubAPI, getGitlabAPI, getIntlayerAPI, getIntlayerAPIProxy, getNewsletterAPI, getOAuthAPI, getOrganizationAPI, getProjectAPI, getReviewerAPI, getSearchAPI, getShowcaseProjectAPI, getStatusAPI, getStripeAPI, getTagAPI, getTranslateAPI, getUserAPI, githubEndpoint, gitlabEndpoint, newsletterEndpoint, organizationEndpoint, projectEndpoint, reviewerEndpoint, searchEndpoint, showcaseProjectEndpoint, statusEndpoint, stripeEndpoint, tagEndpoint, translateEndpoint, userEndpoint };
|
package/dist/types/fetcher.d.ts
CHANGED
|
@@ -1,4 +1,24 @@
|
|
|
1
1
|
//#region src/fetcher.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Error thrown when the backend answers with a non-ok response.
|
|
4
|
+
*
|
|
5
|
+
* Carries the HTTP status and the backend error code alongside the message, so
|
|
6
|
+
* callers can tell a transient failure (5xx, network) from a deterministic one
|
|
7
|
+
* (4xx) instead of blindly retrying.
|
|
8
|
+
*/
|
|
9
|
+
declare class FetcherError extends Error {
|
|
10
|
+
/** HTTP status code of the response. */
|
|
11
|
+
readonly status: number;
|
|
12
|
+
/** Error code returned by the backend, when available (ex: `DICTIONARY_NOT_FOUND`). */
|
|
13
|
+
readonly code?: string;
|
|
14
|
+
/** Raw error payload returned by the backend. */
|
|
15
|
+
readonly data?: unknown;
|
|
16
|
+
constructor(message: string, details: {
|
|
17
|
+
status: number;
|
|
18
|
+
code?: string;
|
|
19
|
+
data?: unknown;
|
|
20
|
+
});
|
|
21
|
+
}
|
|
2
22
|
/**
|
|
3
23
|
* Type definition for options used in the fetcher function.
|
|
4
24
|
* Extends the standard RequestInit interface (excluding 'body'),
|
|
@@ -69,5 +89,5 @@ declare const fetcherOptions: FetcherOptions;
|
|
|
69
89
|
*/
|
|
70
90
|
declare const fetcher: <T>(url: string, ...options: FetcherOptions[]) => Promise<T>;
|
|
71
91
|
//#endregion
|
|
72
|
-
export { FetcherOptions, fetcher, fetcherOptions };
|
|
92
|
+
export { FetcherError, FetcherOptions, fetcher, fetcherOptions };
|
|
73
93
|
//# sourceMappingURL=fetcher.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetcher.d.ts","names":[],"sources":["../../src/fetcher.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"fetcher.d.ts","names":[],"sources":["../../src/fetcher.ts"],"mappings":";;;;;;;;cAOa,qBAAqB;;WAEhB;;WAEA;;WAEA;EAEhB,YACE,iBACA;IAAW;IAAgB;IAAe;;;;;;;;KAgBlC,iBAAiB,KAAK;;;;EAIhC,OAAO;;;;EAIP,SACI,2DAEA;;;;;;;cAQO,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA6FhB,UAAiB,GAAC,gBAClB,SACC,qBACX,QAAQ"}
|
|
@@ -9,6 +9,7 @@ declare const getDictionaryAPI: (authAPIOptions?: FetcherOptions, intlayerConfig
|
|
|
9
9
|
getDictionariesKeys: (otherOptions?: FetcherOptions) => Promise<GetDictionariesKeysResult>;
|
|
10
10
|
getDictionariesUpdateTimestamp: (otherOptions?: FetcherOptions) => Promise<GetDictionariesUpdateTimestampResult>;
|
|
11
11
|
getDictionary: (dictionaryKey: GetDictionaryParams['dictionaryKey'], version?: GetDictionaryQuery['version'], otherOptions?: FetcherOptions) => Promise<GetDictionaryResult>;
|
|
12
|
+
getDictionariesByKeys: (dictionaryKeys: string[], version?: GetDictionaryQuery['version'], otherOptions?: FetcherOptions) => Promise<GetDictionariesByKeysResult>;
|
|
12
13
|
pushDictionaries: (dictionaries: PushDictionariesBody['dictionaries'], otherOptions?: FetcherOptions) => Promise<PushDictionariesResult>;
|
|
13
14
|
addDictionary: (body: AddDictionaryBody, otherOptions?: FetcherOptions) => Promise<AddDictionaryResult>;
|
|
14
15
|
updateDictionary: (dictionary: UpdateDictionaryBody, otherOptions?: FetcherOptions) => Promise<UpdateDictionaryResult>;
|
|
@@ -25,6 +26,7 @@ declare const dictionaryEndpoint: CMSEndpoint<{
|
|
|
25
26
|
getDictionariesKeys: (otherOptions?: FetcherOptions) => Promise<GetDictionariesKeysResult>;
|
|
26
27
|
getDictionariesUpdateTimestamp: (otherOptions?: FetcherOptions) => Promise<GetDictionariesUpdateTimestampResult>;
|
|
27
28
|
getDictionary: (dictionaryKey: GetDictionaryParams['dictionaryKey'], version?: GetDictionaryQuery['version'], otherOptions?: FetcherOptions) => Promise<GetDictionaryResult>;
|
|
29
|
+
getDictionariesByKeys: (dictionaryKeys: string[], version?: GetDictionaryQuery['version'], otherOptions?: FetcherOptions) => Promise<GetDictionariesByKeysResult>;
|
|
28
30
|
pushDictionaries: (dictionaries: PushDictionariesBody['dictionaries'], otherOptions?: FetcherOptions) => Promise<PushDictionariesResult>;
|
|
29
31
|
addDictionary: (body: AddDictionaryBody, otherOptions?: FetcherOptions) => Promise<AddDictionaryResult>;
|
|
30
32
|
updateDictionary: (dictionary: UpdateDictionaryBody, otherOptions?: FetcherOptions) => Promise<UpdateDictionaryResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dictionary.d.ts","names":[],"sources":["../../../src/getIntlayerAPI/dictionary.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"dictionary.d.ts","names":[],"sources":["../../../src/getIntlayerAPI/dictionary.ts"],"mappings":";;;;;;cAuBa,mBAAgB,iBACX,gBAAc,iBACb;EAWL,kBAAA,UAAA,uBAAqB,eACjB,mBAAc,QAAA;EAgBmB,sBAAA,eAAA,mBAAc,QAAA;EAc/C,iCAAA,eAAA,mBAAc,QAAA;EAiBb,gBAAA,eAAA,sCAAoC,UACzC,+BAA6B,eACzB,mBAAc,QAAA;EAoBZ,wBAAA,0BAAQ,UACd,+BAA6B,eACzB,mBAAc,QAAA;EAkCd,mBAAA,cAAA,sCAAoC,eACpC,mBAAc,QAAA;EAftB,gBAAA,MAAA,mBAAiB,eACT,mBAAc,QAAA;EA+BhB,mBAAA,YAAA,sBAAoB,eAClB,mBAAc,QAAA;EAiBxB,mBAAA,IAAA,uCAAqC,eAC3B,mBAAc,QAAA;;;;;;;;cA8BnB,oBA9BmB;EA/IlB,kBAAA,UAAA,uBAAqB,eACjB,mBAAc,QAAA;EAgBmB,sBAAA,eAAA,mBAAc,QAAA;EAc/C,iCAAA,eAAA,mBAAc,QAAA;EAiBb,gBAAA,eAAA,sCAAoC,UACzC,+BAA6B,eACzB,mBAAc,QAAA;EAoBZ,wBAAA,0BAAQ,UACd,+BAA6B,eACzB,mBAAc,QAAA;EAkCd,mBAAA,cAAA,sCAAoC,eACpC,mBAAc,QAAA;EAftB,gBAAA,MAAA,mBAAiB,eACT,mBAAc,QAAA;EA+BhB,mBAAA,YAAA,sBAAoB,eAClB,mBAAc,QAAA;EAiBxB,mBAAA,IAAA,uCAAqC,eAC3B,mBAAc,QAAA"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { FetcherOptions, fetcher, fetcherOptions } from "./fetcher.js";
|
|
1
|
+
import { FetcherError, FetcherOptions, fetcher, fetcherOptions } from "./fetcher.js";
|
|
2
2
|
import { AuthManager, AuthManagerOptions, BindSectionOptions, createAuthManager } from "./cms/createAuthManager.js";
|
|
3
3
|
import { CMSEndpoint, IntlayerCMS, IntlayerCMSOptions, createEndpoint, createIntlayerCMS } from "./cms/createIntlayerCMS.js";
|
|
4
4
|
import "./cms/index.js";
|
|
@@ -30,4 +30,4 @@ import { IntlayerAPI, getIntlayerAPI } from "./getIntlayerAPI/index.js";
|
|
|
30
30
|
import { IntlayerAPIProxy, getIntlayerAPIProxy } from "./proxy.js";
|
|
31
31
|
import { AIOptions } from "./types.js";
|
|
32
32
|
import { AskDocQuestionBody, AskDocQuestionResult, AutocompleteBody, ChatBody, ChatResult, ClientAction, aiEndpoint, getAiAPI } from "./getIntlayerAPI/ai.js";
|
|
33
|
-
export { type AIOptions, AskDocQuestionBody, type AskDocQuestionResult, type AuditEvent, AuthManager, AuthManagerOptions, AutocompleteBody, BindSectionOptions, BitbucketAuthCallbackBody, BitbucketAuthCallbackResult, BitbucketCheckConfigBody, BitbucketCheckConfigResult, BitbucketGetAuthUrlResult, BitbucketGetConfigFileBody, BitbucketGetConfigFileResult, BitbucketListReposResult, BitbucketRepository, CMSEndpoint, ChatBody, type ChatResult, ClientAction, DiscoverUrlsParams, DiscoverUrlsResult, FetcherOptions, GetDemoSessionResult, GetRecursiveAuditStatusParams, type GetRecursiveAuditStatusResult, GitHubAuthCallbackBody, GitHubAuthCallbackResult, GitHubCheckConfigBody, GitHubCheckConfigResult, GitHubGetAuthUrlResult, GitHubGetConfigFileBody, GitHubGetConfigFileResult, GitHubGetTokenResult, GitHubListReposResult, GitHubRepository, GitLabAuthCallbackBody, GitLabAuthCallbackResult, GitLabCheckConfigBody, GitLabCheckConfigResult, GitLabGetAuthUrlResult, GitLabGetConfigFileBody, GitLabGetConfigFileResult, GitLabListProjectsResult, GitLabProject, IntlayerAPI, IntlayerAPIProxy, IntlayerCMS, IntlayerCMSOptions, OtherShowcaseProjectsQuery, RecursiveAuditJobParams, ScanUrlBody, ShowcaseProjectsQuery, StartRecursiveAuditBody, type StartRecursiveAuditResult, type TranslateDictionariesBody, type TranslateDictionariesResult, aiEndpoint, analyticsEndpoint, assetEndpoint, auditEndpoint, bitbucketEndpoint, createAuthManager, createEndpoint, createIntlayerCMS, dictionaryEndpoint, editorEndpoint, environmentEndpoint, fetchDistantDictionaries, fetchDistantDictionary, fetcher, fetcherOptions, getAiAPI, getAnalyticsAPI, getAssetAPI, getAuditAPI, getBitbucketAPI, getDictionaryAPI, getEditorAPI, getEnvironmentAPI, getGithubAPI, getGitlabAPI, getIntlayerAPI, getIntlayerAPIProxy, getNewsletterAPI, getOAuthAPI, getOrganizationAPI, getProjectAPI, getReviewerAPI, getSearchAPI, getShowcaseProjectAPI, getStatusAPI, getStripeAPI, getTagAPI, getTranslateAPI, getUserAPI, githubEndpoint, gitlabEndpoint, newsletterEndpoint, organizationEndpoint, projectEndpoint, reviewerEndpoint, searchEndpoint, showcaseProjectEndpoint, statusEndpoint, stripeEndpoint, tagEndpoint, translateEndpoint, userEndpoint };
|
|
33
|
+
export { type AIOptions, AskDocQuestionBody, type AskDocQuestionResult, type AuditEvent, AuthManager, AuthManagerOptions, AutocompleteBody, BindSectionOptions, BitbucketAuthCallbackBody, BitbucketAuthCallbackResult, BitbucketCheckConfigBody, BitbucketCheckConfigResult, BitbucketGetAuthUrlResult, BitbucketGetConfigFileBody, BitbucketGetConfigFileResult, BitbucketListReposResult, BitbucketRepository, CMSEndpoint, ChatBody, type ChatResult, ClientAction, DiscoverUrlsParams, DiscoverUrlsResult, FetcherError, FetcherOptions, GetDemoSessionResult, GetRecursiveAuditStatusParams, type GetRecursiveAuditStatusResult, GitHubAuthCallbackBody, GitHubAuthCallbackResult, GitHubCheckConfigBody, GitHubCheckConfigResult, GitHubGetAuthUrlResult, GitHubGetConfigFileBody, GitHubGetConfigFileResult, GitHubGetTokenResult, GitHubListReposResult, GitHubRepository, GitLabAuthCallbackBody, GitLabAuthCallbackResult, GitLabCheckConfigBody, GitLabCheckConfigResult, GitLabGetAuthUrlResult, GitLabGetConfigFileBody, GitLabGetConfigFileResult, GitLabListProjectsResult, GitLabProject, IntlayerAPI, IntlayerAPIProxy, IntlayerCMS, IntlayerCMSOptions, OtherShowcaseProjectsQuery, RecursiveAuditJobParams, ScanUrlBody, ShowcaseProjectsQuery, StartRecursiveAuditBody, type StartRecursiveAuditResult, type TranslateDictionariesBody, type TranslateDictionariesResult, aiEndpoint, analyticsEndpoint, assetEndpoint, auditEndpoint, bitbucketEndpoint, createAuthManager, createEndpoint, createIntlayerCMS, dictionaryEndpoint, editorEndpoint, environmentEndpoint, fetchDistantDictionaries, fetchDistantDictionary, fetcher, fetcherOptions, getAiAPI, getAnalyticsAPI, getAssetAPI, getAuditAPI, getBitbucketAPI, getDictionaryAPI, getEditorAPI, getEnvironmentAPI, getGithubAPI, getGitlabAPI, getIntlayerAPI, getIntlayerAPIProxy, getNewsletterAPI, getOAuthAPI, getOrganizationAPI, getProjectAPI, getReviewerAPI, getSearchAPI, getShowcaseProjectAPI, getStatusAPI, getStripeAPI, getTagAPI, getTranslateAPI, getUserAPI, githubEndpoint, gitlabEndpoint, newsletterEndpoint, organizationEndpoint, projectEndpoint, reviewerEndpoint, searchEndpoint, showcaseProjectEndpoint, statusEndpoint, stripeEndpoint, tagEndpoint, translateEndpoint, userEndpoint };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ResponseData } from "../utils/responseData.js";
|
|
2
2
|
import { IntlayerConfig } from "@intlayer/types/config";
|
|
3
|
-
import "/Users/aymericpineau/Documents/intlayer_/node_modules/.bun/fastify@5.11.
|
|
3
|
+
import "/Users/aymericpineau/Documents/intlayer_/node_modules/.bun/fastify@5.11.3/node_modules/fastify/fastify.js";
|
|
4
4
|
//#region ../../intlayer-editor/server/dist/controllers/configuration.controller.d.ts
|
|
5
5
|
//#region src/controllers/configuration.controller.d.ts
|
|
6
6
|
type GetConfigurationResult = ResponseData<IntlayerConfig>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ResponseData } from "../utils/responseData.js";
|
|
2
2
|
import { UnmergedDictionaries } from "../../../../@intlayer/unmerged-dictionaries-entry/dist/types/index.js";
|
|
3
|
-
import "/Users/aymericpineau/Documents/intlayer_/node_modules/.bun/fastify@5.11.
|
|
3
|
+
import "/Users/aymericpineau/Documents/intlayer_/node_modules/.bun/fastify@5.11.3/node_modules/fastify/fastify.js";
|
|
4
4
|
import { DictionaryStatus } from "@intlayer/engine/build";
|
|
5
5
|
import { Dictionary } from "@intlayer/types/dictionary";
|
|
6
6
|
//#region ../../intlayer-editor/server/dist/controllers/dictionary.controller.d.ts
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intlayer/api",
|
|
3
|
-
"version": "9.
|
|
3
|
+
"version": "9.3.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "SDK for interacting with the Intlayer API, enabling content auditing, and managing organizations, projects, and users.",
|
|
6
6
|
"keywords": [
|
|
@@ -256,12 +256,12 @@
|
|
|
256
256
|
"typecheck": "tsc --noEmit --project tsconfig.types.json"
|
|
257
257
|
},
|
|
258
258
|
"dependencies": {
|
|
259
|
-
"@intlayer/config": "9.
|
|
260
|
-
"@intlayer/types": "9.
|
|
259
|
+
"@intlayer/config": "9.3.0",
|
|
260
|
+
"@intlayer/types": "9.3.0",
|
|
261
261
|
"defu": "6.1.7"
|
|
262
262
|
},
|
|
263
263
|
"devDependencies": {
|
|
264
|
-
"@types/node": "26.
|
|
264
|
+
"@types/node": "26.2.0",
|
|
265
265
|
"@utils/ts-config": "1.0.4",
|
|
266
266
|
"@utils/ts-config-types": "1.0.4",
|
|
267
267
|
"@utils/tsdown-config": "1.0.4",
|