contentful-management
Version:
Client for Contentful's Content Management API
1,368 lines (1,314 loc) • 560 kB
JavaScript
'use strict';
var contentfulSdkCore = require('contentful-sdk-core');
var axios = require('axios');
var copy = require('fast-copy');
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
var axios__default = /*#__PURE__*/_interopDefault(axios);
var copy__default = /*#__PURE__*/_interopDefault(copy);
/* eslint-disable @typescript-eslint/no-explicit-any */
function getBaseUrl$r(http) {
return http.defaults.baseURL?.split('/spaces')[0];
}
function get$14(http, url, config) {
return http
.get(url, {
baseURL: getBaseUrl$r(http),
...config,
})
.then((response) => response.data, contentfulSdkCore.errorHandler);
}
function patch$5(http, url, payload, config) {
return http
.patch(url, payload, {
baseURL: getBaseUrl$r(http),
...config,
})
.then((response) => response.data, contentfulSdkCore.errorHandler);
}
function post$1(http, url, payload, config) {
return http
.post(url, payload, {
baseURL: getBaseUrl$r(http),
...config,
})
.then((response) => response.data, contentfulSdkCore.errorHandler);
}
function put$1(http, url, payload, config) {
return http
.put(url, payload, {
baseURL: getBaseUrl$r(http),
...config,
})
.then((response) => response.data, contentfulSdkCore.errorHandler);
}
function del$H(http, url, config) {
return http
.delete(url, {
baseURL: getBaseUrl$r(http),
...config,
})
.then((response) => response.data, contentfulSdkCore.errorHandler);
}
function http(http, url, config) {
return http(url, {
baseURL: getBaseUrl$r(http),
...config,
}).then((response) => response.data, contentfulSdkCore.errorHandler);
}
const get$13 = (http, params, headers) => {
return get$14(http, `/spaces/${params.spaceId}/ai/actions/${params.aiActionId}`, {
headers,
});
};
const getMany$O = (http, params, headers) => {
return get$14(http, `/spaces/${params.spaceId}/ai/actions`, {
params: params.query,
headers,
});
};
const create$F = (http, params, data, headers) => {
return post$1(http, `/spaces/${params.spaceId}/ai/actions`, data, { headers });
};
const update$z = (http, params, rawData, headers) => {
const data = copy__default.default(rawData);
const { sys, ...payload } = data;
return put$1(http, `/spaces/${params.spaceId}/ai/actions/${params.aiActionId}`, payload, {
headers: {
'X-Contentful-Version': rawData.sys.version ?? 0,
...headers,
},
});
};
const del$G = (http, params, headers) => {
return del$H(http, `/spaces/${params.spaceId}/ai/actions/${params.aiActionId}`, { headers });
};
const publish$5 = (http, params, rawData, headers) => {
return put$1(http, `/spaces/${params.spaceId}/ai/actions/${params.aiActionId}/published`, null, {
headers: {
'X-Contentful-Version': params.version,
...headers,
},
});
};
const unpublish$5 = (http, params, headers) => {
return del$H(http, `/spaces/${params.spaceId}/ai/actions/${params.aiActionId}/published`, {
headers,
});
};
const invoke = (http, params, data, headers) => {
return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/actions/${params.aiActionId}/invoke`, data, { headers, params: params.query });
};
var AiAction = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create$F,
del: del$G,
get: get$13,
getMany: getMany$O,
invoke: invoke,
publish: publish$5,
unpublish: unpublish$5,
update: update$z
});
const get$12 = (http, params, headers) => {
return get$14(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/actions/${params.aiActionId}/invocations/${params.invocationId}`, { headers });
};
var AiActionInvocation = /*#__PURE__*/Object.freeze({
__proto__: null,
get: get$12
});
const AgentAlphaHeaders = {
'x-contentful-enable-alpha-feature': 'agents-api',
};
const get$11 = (http, params, headers) => {
return get$14(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/agents/${params.agentId}`, {
headers: {
...AgentAlphaHeaders,
...headers,
},
});
};
const getMany$N = (http, params, headers) => {
return get$14(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/agents`, {
headers: {
...AgentAlphaHeaders,
...headers,
},
});
};
const generate = (http, params, data, headers) => {
return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/agents/${params.agentId}/generate`, data, {
headers: {
...AgentAlphaHeaders,
...headers,
},
});
};
var Agent = /*#__PURE__*/Object.freeze({
__proto__: null,
generate: generate,
get: get$11,
getMany: getMany$N
});
const AgentRunAlphaHeaders = {
'x-contentful-enable-alpha-feature': 'agents-api',
};
const get$10 = (http, params, headers) => {
return get$14(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/agents/runs/${params.runId}`, {
headers: {
...AgentRunAlphaHeaders,
...headers,
},
});
};
const getMany$M = (http, params, headers) => {
return get$14(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/agents/runs`, {
params: params.query,
headers: {
...AgentRunAlphaHeaders,
...headers,
},
});
};
var AgentRun = /*#__PURE__*/Object.freeze({
__proto__: null,
get: get$10,
getMany: getMany$M
});
/**
* Retrieves an access token by its unique token ID for the currently authenticated user.
*
* @param {AxiosInstance} http - An Axios HTTP client instance.
* @param {Object} params - Parameters for the request.
* @param {string} params.tokenId - The unique token ID of the access token to retrieve.
* @returns {Promise<AccessTokenProps>} A Promise that resolves with the retrieved access token information.
* @example ```javascript
* const contentful = require('contentful-management')
*
* const plainClient = contentful.createClient(
* {
* accessToken: '<content_management_api_key>'
* },
* { type: 'plain' }
* )
* plainClient.get({tokenId: 'TestTokenTd'})
* .then(token => console.log(token))
* .catch(console.error)
* ```
*/
const get$$ = (http, params) => {
return get$14(http, `/users/me/access_tokens/${params.tokenId}`);
};
/**
* Retrieves multiple access tokens associated with the currently authenticated user.
*
* @param {AxiosInstance} http - An Axios HTTP client instance.
* @param {QueryParams} params - Query parameters to filter and customize the request.
* @returns {Promise<CollectionProp<AccessTokenProps>>} A Promise that resolves with a collection of access token properties.
* @example ```javascript
* const contentful = require('contentful-management')
*
* const plainClient = contentful.createClient(
* {
* accessToken: '<content_management_api_key>'
* },
* { type: 'plain' }
* )
* plainClient.getMany()
* .then(result => console.log(result.items))
* .catch(console.error)
* ```
*/
const getMany$L = (http, params) => {
return get$14(http, '/users/me/access_tokens', {
params: params.query,
});
};
/**
* Creates a personal access token for the currently authenticated user.
*
* @param {AxiosInstance} http - Axios instance for making the HTTP request.
* @param {Object} _params - Unused parameters (can be an empty object).
* @param {CreatePersonalAccessTokenProps} rawData - Data for creating the personal access token.
* @param {RawAxiosRequestHeaders} [headers] - Optional HTTP headers for the request.
* @returns {Promise<AccessTokenProps>} A Promise that resolves with the created personal access token.
* @example ```javascript
* const contentful = require('contentful-management')
*
* const plainClient = contentful.createClient(
* {
* accessToken: '<content_management_api_key>',
* },
* { type: 'plain' }
* )
* plainClient.createPersonalAccessToken({name: 'Test-Name', scope: ['content_management_manage'], expiresIn: 777596.92})
* .then(token => console.log(token))
* .catch(console.error)
* ```
*/
const createPersonalAccessToken = (http, _params, rawData, headers) => {
return post$1(http, '/users/me/access_tokens', rawData, {
headers,
});
};
/**
* Revokes an access token associated with the currently authenticated user.
*
* @param {AxiosInstance} http - The Axios HTTP client instance.
* @param {Object} params - The parameters for revoking the access token.
* @param {string} params.tokenId - The unique identifier of the access token to revoke.
* @returns {Promise<AccessTokenProps>} A Promise that resolves with the updated access token information after revocation.
* @example ```javascript
* const contentful = require('contentful-management')
*
* const plainClient = contentful.createClient(
* {
* accessToken: '<content_management_api_key>'
* },
* { type: 'plain' }
* )
* plainClient.revoke({tokenId: 'TestTokenTd'})
* .then(token => console.log(token))
* .catch(console.error)
* ```
*/
const revoke$1 = (http, params) => {
return put$1(http, `/users/me/access_tokens/${params.tokenId}/revoked`, null);
};
/**
* Retrieves a list of redacted versions of access tokens for an organization, accessible to owners or administrators of an organization.
*
* @param {AxiosInstance} http - The Axios HTTP client instance.
* @param {GetOrganizationParams & QueryParams} params - Parameters for the request, including organization ID and query parameters.
* @param {string} params.organizationId - The unique identifier of the organization.
* @returns {Promise<CollectionProp<AccessTokenProps>>} A promise that resolves to a collection of access tokens.
* @example ```javascript
* const contentful = require('contentful-management')
*
* const plainClient = contentful.createClient(
* {
* accessToken: '<content_management_api_key>'
* },
* { type: 'plain' }
* )
* plainClient.getManyForOrganization({organizationId: 'OrgId'})
* .then(result => console.log(result.items))
* .catch(console.error)
* ```
*/
const getManyForOrganization$7 = (http, params) => {
return get$14(http, `/organizations/${params.organizationId}/access_tokens`, {
params: params.query,
});
};
var AccessToken = /*#__PURE__*/Object.freeze({
__proto__: null,
createPersonalAccessToken: createPersonalAccessToken,
get: get$$,
getMany: getMany$L,
getManyForOrganization: getManyForOrganization$7,
revoke: revoke$1
});
const getBaseUrl$q = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/automation_definitions`;
const getAutomationDefinitionUrl = (params) => `${getBaseUrl$q(params)}/${params.automationDefinitionId}`;
const get$_ = (http, params, headers) => get$14(http, getAutomationDefinitionUrl(params), {
headers,
});
const getMany$K = (http, params, headers) => get$14(http, getBaseUrl$q(params), {
headers,
params: params.query,
});
const create$E = (http, params, rawData, headers) => {
const data = copy__default.default(rawData);
return post$1(http, getBaseUrl$q(params), data, {
headers,
});
};
const update$y = (http, params, rawData, headers) => {
const data = copy__default.default(rawData);
delete data.sys;
return put$1(http, getAutomationDefinitionUrl(params), data, {
headers: {
'X-Contentful-Version': rawData.sys.version ?? 0,
...headers,
},
});
};
const del$F = (http, params, headers) => {
return del$H(http, getAutomationDefinitionUrl(params), {
headers: { 'X-Contentful-Version': params.version, ...headers },
});
};
var AutomationDefinition = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create$E,
del: del$F,
get: get$_,
getMany: getMany$K,
update: update$y
});
const getBaseUrl$p = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/automation_executions`;
const getAutomationExecutionUrl = (params) => `${getBaseUrl$p(params)}/${params.automationExecutionId}`;
const getExecutionsByDefinitionUrl = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/automation_definitions/${params.automationDefinitionId}/automation_executions`;
const get$Z = (http, params, headers) => get$14(http, getAutomationExecutionUrl(params), {
headers,
});
const getMany$J = (http, params, headers) => get$14(http, getBaseUrl$p(params), {
headers,
params: params.query,
});
const getForAutomationDefinition = (http, params, headers) => get$14(http, getExecutionsByDefinitionUrl(params), {
headers,
params: params.query,
});
var AutomationExecution = /*#__PURE__*/Object.freeze({
__proto__: null,
get: get$Z,
getForAutomationDefinition: getForAutomationDefinition,
getMany: getMany$J
});
const get$Y = (http, params) => {
return get$14(http, `/spaces/${params.spaceId}/api_keys/${params.apiKeyId}`);
};
const getMany$I = (http, params) => {
return get$14(http, `/spaces/${params.spaceId}/api_keys`, {
params: params.query,
});
};
const create$D = (http, params, data, headers) => {
return post$1(http, `/spaces/${params.spaceId}/api_keys`, data, { headers });
};
const createWithId$e = (http, params, data, headers) => {
return put$1(http, `/spaces/${params.spaceId}/api_keys/${params.apiKeyId}`, data, {
headers,
});
};
const update$x = (http, params, rawData, headers) => {
const data = copy__default.default(rawData);
if ('accessToken' in data) {
delete data.accessToken;
}
if ('preview_api_key' in data) {
delete data.preview_api_key;
}
if ('policies' in data) {
delete data.policies;
}
delete data.sys;
return put$1(http, `/spaces/${params.spaceId}/api_keys/${params.apiKeyId}`, data, {
headers: {
'X-Contentful-Version': rawData.sys.version ?? 0,
...headers,
},
});
};
const del$E = (http, params) => {
return del$H(http, `/spaces/${params.spaceId}/api_keys/${params.apiKeyId}`);
};
var ApiKey = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create$D,
createWithId: createWithId$e,
del: del$E,
get: get$Y,
getMany: getMany$I,
update: update$x
});
const create$C = (http, params, data) => {
return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/access_tokens`, undefined, { headers: { Authorization: `Bearer ${data.jwt}` } });
};
var AppAccessToken = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create$C
});
function normalizeSelect(query) {
if (query && query.select && !/sys/i.test(query.select)) {
return {
...query,
select: query.select + ',sys',
};
}
return query;
}
function normalizeSpaceId(query) {
if (query && query.spaceId) {
const { spaceId, ...rest } = query;
return {
...rest,
'sys.space.sys.id[in]': spaceId,
};
}
return query;
}
const getBaseUrl$o = (params) => `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/actions`;
const getAppActionUrl = (params) => `${getBaseUrl$o(params)}/${params.appActionId}`;
const getAppActionsEnvUrl = (params) => {
if (params.environmentId) {
return `/spaces/${params.spaceId}/environments/${params.environmentId}/actions`;
}
return `/spaces/${params.spaceId}/actions`;
};
const get$X = (http, params) => {
return get$14(http, getAppActionUrl(params));
};
const getMany$H = (http, params) => {
return get$14(http, getBaseUrl$o(params), {
params: normalizeSelect(params.query),
});
};
const getManyForEnvironment$2 = (http, params) => {
return get$14(http, getAppActionsEnvUrl(params), {
params: normalizeSelect(params.query),
});
};
const del$D = (http, params) => {
return del$H(http, getAppActionUrl(params));
};
const create$B = (http, params, data) => {
return post$1(http, getBaseUrl$o(params), data);
};
const update$w = (http, params, data) => {
return put$1(http, getAppActionUrl(params), data);
};
var AppAction = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create$B,
del: del$D,
get: get$X,
getMany: getMany$H,
getManyForEnvironment: getManyForEnvironment$2,
update: update$w
});
/**
* @internal
*/
const wrapCollection = (fn) => (makeRequest, data, ...rest) => {
const collectionData = contentfulSdkCore.toPlainObject(copy__default.default(data));
// @ts-expect-error toPlainObject adds non-enumerable toPlainObject method that would be lost with spread
collectionData.items = collectionData.items.map((entity) => fn(makeRequest, entity, ...rest));
// @ts-expect-error
return collectionData;
};
const wrapCursorPaginatedCollection = (fn) => (makeRequest, data, ...rest) => {
const collectionData = contentfulSdkCore.toPlainObject(copy__default.default(data));
// @ts-expect-error toPlainObject adds non-enumerable toPlainObject method that would be lost with spread
collectionData.items = collectionData.items.map((entity) => fn(makeRequest, entity, ...rest));
// @ts-expect-error
return collectionData;
};
function isSuccessful(statusCode) {
return statusCode < 300;
}
function shouldRePoll(statusCode) {
return [404, 422, 429, 400].includes(statusCode);
}
async function waitFor(ms = 1000) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function normalizeCursorPaginationParameters(query) {
const { pagePrev, pageNext, ...rest } = query;
return {
...rest,
cursor: true,
// omit pagePrev and pageNext if the value is falsy
...(pagePrev ? { pagePrev } : null),
...(pageNext ? { pageNext } : null),
};
}
function extractQueryParam(key, url) {
if (!url)
return;
const queryIndex = url.indexOf('?');
if (queryIndex === -1)
return;
const queryString = url.slice(queryIndex + 1);
return new URLSearchParams(queryString).get(key) ?? undefined;
}
const Pages = {
prev: 'pagePrev',
next: 'pageNext',
};
const PAGE_KEYS = ['prev', 'next'];
function normalizeCursorPaginationResponse(data) {
const pages = {};
for (const key of PAGE_KEYS) {
const token = extractQueryParam(Pages[key], data.pages?.[key]);
if (token)
pages[key] = token;
}
return {
...data,
pages,
};
}
const create$A = (http, params, data) => {
return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/actions/${params.appActionId}/calls`, data);
};
const getCallDetails$1 = (http, params) => {
return get$14(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/actions/${params.appActionId}/calls/${params.callId}`);
};
const APP_ACTION_CALL_RETRY_INTERVAL = 2000;
const APP_ACTION_CALL_RETRIES = 15;
async function callAppActionResult(http, params, { callId, }) {
let checkCount = 1;
const retryInterval = params.retryInterval || APP_ACTION_CALL_RETRY_INTERVAL;
const retries = params.retries || APP_ACTION_CALL_RETRIES;
return new Promise((resolve, reject) => {
const poll = async () => {
try {
const result = await getCallDetails$1(http, { ...params, callId: callId });
// The lambda failed or returned a 404, so we shouldn't re-poll anymore
if (result?.response?.statusCode && !isSuccessful(result?.response?.statusCode)) {
const error = new Error('App action not found or lambda fails');
reject(error);
}
else if (isSuccessful(result.statusCode)) {
resolve(result);
}
// The logs are not ready yet. Continue waiting for them
else if (shouldRePoll(result.statusCode) && checkCount < retries) {
checkCount++;
await waitFor(retryInterval);
poll();
}
// If the response status code is not successful and is not a status code that should be repolled, reject with an error immediately
else {
const error = new Error('The app action response is taking longer than expected to process.');
reject(error);
}
}
catch (error) {
checkCount++;
if (checkCount > retries) {
reject(new Error('The app action response is taking longer than expected to process.'));
return;
}
// If `appActionCalls.getCallDetails` throws, we re-poll as it might mean that the lambda result is not available in the webhook logs yet
await waitFor(retryInterval);
poll();
}
};
poll();
});
}
const createWithResponse = async (http, params, data) => {
const createResponse = await post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/actions/${params.appActionId}/calls`, data);
const callId = createResponse.sys.id;
return callAppActionResult(http, params, { callId });
};
// Get structured AppActionCall (status/result/error) via new route that includes app installation context
const get$W = (http, params) => {
return get$14(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/actions/${params.appActionId}/calls/${params.callId}`);
};
// Get raw AppActionCall response (headers/body) for a completed call
const getResponse = (http, params) => {
return get$14(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/actions/${params.appActionId}/calls/${params.callId}/response`);
};
async function pollStructuredAppActionCall(http, params, { callId }) {
let checkCount = 1;
const retryInterval = params.retryInterval || APP_ACTION_CALL_RETRY_INTERVAL;
const retries = params.retries || APP_ACTION_CALL_RETRIES;
return new Promise((resolve, reject) => {
const poll = async () => {
try {
const result = await get$W(http, { ...params, callId });
// If backend has not yet written the record, keep polling up to retries
// Otherwise, resolve when status is terminal
if (result?.sys.status === 'succeeded' || result?.sys.status === 'failed') {
resolve(result);
}
else if (result?.sys.status === 'processing' && checkCount < retries) {
checkCount++;
await waitFor(retryInterval);
poll();
}
else {
// Status not terminal and no more retries
reject(new Error('The app action result is taking longer than expected to process.'));
}
}
catch (error) {
checkCount++;
if (checkCount > retries) {
reject(new Error('The app action result is taking longer than expected to process.'));
return;
}
// Similar to legacy behavior: transient errors (e.g., 404 during propagation) → re-poll
await waitFor(retryInterval);
poll();
}
};
poll();
});
}
// Create and poll the structured AppActionCall until completion (succeeded/failed)
const createWithResult = async (http, params, data) => {
const createResponse = await post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/actions/${params.appActionId}/calls`, data);
const callId = createResponse.sys.id;
return pollStructuredAppActionCall(http, params, { callId });
};
var AppActionCall = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create$A,
createWithResponse: createWithResponse,
createWithResult: createWithResult,
get: get$W,
getCallDetails: getCallDetails$1,
getResponse: getResponse
});
const getBaseUrl$n = (params) => `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/app_bundles`;
const getAppBundleUrl = (params) => `${getBaseUrl$n(params)}/${params.appBundleId}`;
const get$V = (http, params) => {
return get$14(http, getAppBundleUrl(params));
};
const getMany$G = (http, params) => {
return get$14(http, getBaseUrl$n(params), {
params: normalizeSelect(params.query),
});
};
const del$C = (http, params) => {
return del$H(http, getAppBundleUrl(params));
};
const create$z = (http, params, payload) => {
const { appUploadId, comment, actions, functions } = payload;
const data = {
upload: {
sys: {
type: 'Link',
linkType: 'AppUpload',
id: appUploadId,
},
},
comment,
actions,
functions,
};
return post$1(http, getBaseUrl$n(params), data);
};
var AppBundle = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create$z,
del: del$C,
get: get$V,
getMany: getMany$G
});
const getBaseUrl$m = (params) => `/organizations/${params.organizationId}/app_definitions`;
const getAppDefinitionUrl = (params) => getBaseUrl$m(params) + `/${params.appDefinitionId}`;
const getBaseUrlForOrgInstallations$1 = (params) => `/app_definitions/${params.appDefinitionId}/app_installations`;
const get$U = (http, params) => {
return get$14(http, getAppDefinitionUrl(params), {
params: normalizeSelect(params.query),
});
};
const getMany$F = (http, params) => {
return get$14(http, getBaseUrl$m(params), {
params: params.query,
});
};
const create$y = (http, params, rawData) => {
const data = copy__default.default(rawData);
return post$1(http, getBaseUrl$m(params), data);
};
const update$v = (http, params, rawData, headers) => {
const data = copy__default.default(rawData);
delete data.sys;
return put$1(http, getAppDefinitionUrl(params), data, {
headers: {
'X-Contentful-Version': rawData.sys.version ?? 0,
...headers,
},
});
};
const del$B = (http, params) => {
return del$H(http, getAppDefinitionUrl(params));
};
const getInstallationsForOrg = (http, params) => {
return get$14(http, getBaseUrlForOrgInstallations$1(params), {
params: {
...normalizeSpaceId(normalizeSelect(params.query)),
'sys.organization.sys.id[in]': params.organizationId,
},
});
};
var AppDefinition = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create$y,
del: del$B,
get: get$U,
getAppDefinitionUrl: getAppDefinitionUrl,
getInstallationsForOrg: getInstallationsForOrg,
getMany: getMany$F,
update: update$v
});
const get$T = (http, params) => {
return get$14(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/details`);
};
const upsert$5 = (http, params, data) => {
return put$1(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/details`, data);
};
const del$A = (http, params) => {
return del$H(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/details`);
};
var AppDetails = /*#__PURE__*/Object.freeze({
__proto__: null,
del: del$A,
get: get$T,
upsert: upsert$5
});
const get$S = (http, params) => {
return get$14(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/event_subscription`);
};
const upsert$4 = (http, params, data) => {
return put$1(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/event_subscription`, data);
};
const del$z = (http, params) => {
return del$H(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/event_subscription`);
};
var AppEventSubscription = /*#__PURE__*/Object.freeze({
__proto__: null,
del: del$z,
get: get$S,
upsert: upsert$4
});
const getBaseUrl$l = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations`;
const getBaseUrlForOrgInstallations = (params) => `/app_definitions/${params.appDefinitionId}/app_installations`;
const getAppInstallationUrl = (params) => getBaseUrl$l(params) + `/${params.appDefinitionId}`;
const get$R = (http, params) => {
return get$14(http, getAppInstallationUrl(params), {
params: normalizeSelect(params.query),
});
};
const getMany$E = (http, params) => {
return get$14(http, getBaseUrl$l(params), {
params: normalizeSelect(params.query),
});
};
const upsert$3 = (http, params, rawData, headers) => {
const data = copy__default.default(rawData);
return put$1(http, getAppInstallationUrl(params), data, {
headers: {
...headers,
...(params.acceptAllTerms && {
'X-Contentful-Marketplace': 'i-accept-end-user-license-agreement,i-accept-marketplace-terms-of-service,i-accept-privacy-policy',
}),
},
});
};
const del$y = (http, params) => {
return del$H(http, getAppInstallationUrl(params));
};
const getForOrganization$3 = (http, params) => {
return get$14(http, getBaseUrlForOrgInstallations(params), {
params: {
...normalizeSpaceId(normalizeSelect(params.query)),
'sys.organization.sys.id[in]': params.organizationId,
},
});
};
var AppInstallation = /*#__PURE__*/Object.freeze({
__proto__: null,
del: del$y,
get: get$R,
getAppInstallationUrl: getAppInstallationUrl,
getForOrganization: getForOrganization$3,
getMany: getMany$E,
upsert: upsert$3
});
const get$Q = (http, params) => {
return get$14(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/keys/${params.fingerprint}`);
};
const getMany$D = (http, params) => {
return get$14(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/keys`);
};
const create$x = (http, params, data) => {
return post$1(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/keys`, data);
};
const del$x = (http, params) => {
return del$H(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/keys/${params.fingerprint}`);
};
var AppKey = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create$x,
del: del$x,
get: get$Q,
getMany: getMany$D
});
const create$w = (http, params, data) => {
return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/signed_requests`, data);
};
var AppSignedRequest = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create$w
});
const get$P = (http, params) => {
return get$14(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/signing_secret`);
};
const upsert$2 = (http, params, data) => {
return put$1(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/signing_secret`, data);
};
const del$w = (http, params) => {
return del$H(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/signing_secret`);
};
var AppSigningSecret = /*#__PURE__*/Object.freeze({
__proto__: null,
del: del$w,
get: get$P,
upsert: upsert$2
});
/**
* @internal
*/
function getUploadHttpClient(http, options) {
const { hostUpload, defaultHostnameUpload, timeout } = http.httpClientParams;
const uploadHttp = http.cloneWithNewParams({
host: hostUpload || defaultHostnameUpload,
// Using client presets, options or 5 minute default timeout
timeout: timeout ?? options?.uploadTimeout ?? 300000,
});
return uploadHttp;
}
const getBaseUrl$k = (params) => `/organizations/${params.organizationId}/app_uploads`;
const getAppUploadUrl = (params) => `${getBaseUrl$k(params)}/${params.appUploadId}`;
const get$O = (http, params) => {
const httpUpload = getUploadHttpClient(http);
return get$14(httpUpload, getAppUploadUrl(params));
};
const del$v = (http, params) => {
const httpUpload = getUploadHttpClient(http);
return del$H(httpUpload, getAppUploadUrl(params));
};
const create$v = (http, params, payload) => {
const httpUpload = getUploadHttpClient(http);
const { file } = payload;
return post$1(httpUpload, getBaseUrl$k(params), file, {
headers: {
'Content-Type': 'application/octet-stream',
},
});
};
var AppUpload = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create$v,
del: del$v,
get: get$O
});
const getBaseUploadUrl = (params) => {
const spacePath = `/spaces/${params.spaceId}/uploads`;
const environmentPath = `/spaces/${params.spaceId}/environments/${params.environmentId}/uploads`;
const path = params.environmentId ? environmentPath : spacePath;
return path;
};
const getEntityUploadUrl = (params) => {
const path = getBaseUploadUrl(params);
return path + `/${params.uploadId}`;
};
const create$u = (http, params, data) => {
const httpUpload = getUploadHttpClient(http);
const { file } = data;
if (!file) {
return Promise.reject(new Error('Unable to locate a file to upload.'));
}
const path = getBaseUploadUrl(params);
return post$1(httpUpload, path, file, {
headers: {
'Content-Type': 'application/octet-stream',
},
});
};
const del$u = (http, params) => {
const httpUpload = getUploadHttpClient(http);
const path = getEntityUploadUrl(params);
return del$H(httpUpload, path);
};
const get$N = (http, params) => {
const httpUpload = getUploadHttpClient(http);
const path = getEntityUploadUrl(params);
return get$14(httpUpload, path);
};
var Upload = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create$u,
del: del$u,
get: get$N
});
const get$M = (http, params, rawData, headers) => {
return get$14(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/assets/${params.assetId}`, {
params: normalizeSelect(params.query),
headers: headers ? { ...headers } : undefined,
});
};
const getMany$C = (http, params, rawData, headers) => {
return get$14(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/assets`, {
params: normalizeSelect(params.query),
headers: headers ? { ...headers } : undefined,
});
};
const update$u = (http, params, rawData, headers) => {
const data = copy__default.default(rawData);
delete data.sys;
return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/assets/${params.assetId}`, data, {
headers: {
'X-Contentful-Version': rawData.sys.version ?? 0,
...headers,
},
});
};
const create$t = (http, params, rawData, headers) => {
const data = copy__default.default(rawData);
return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/assets`, data, {
headers,
});
};
const createWithId$d = (http, params, rawData, headers) => {
const data = copy__default.default(rawData);
return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/assets/${params.assetId}`, data, {
headers,
});
};
const createFromFiles$1 = async (http, params, data) => {
const httpUpload = getUploadHttpClient(http, { uploadTimeout: params.uploadTimeout });
const { file } = data.fields;
return Promise.all(Object.keys(file).map(async (locale) => {
const { contentType, fileName } = file[locale];
return create$u(httpUpload, params, file[locale]).then((upload) => {
return {
[locale]: {
contentType,
fileName,
uploadFrom: {
sys: {
type: 'Link',
linkType: 'Upload',
id: upload.sys.id,
},
},
},
};
});
}))
.then((uploads) => {
const file = uploads.reduce((fieldsData, upload) => ({ ...fieldsData, ...upload }), {});
const asset = {
...data,
fields: {
...data.fields,
file,
},
};
return create$t(http, params, asset, {});
})
.catch(contentfulSdkCore.errorHandler);
};
/**
* Asset processing
*/
const ASSET_PROCESSING_CHECK_WAIT$1 = 3000;
const ASSET_PROCESSING_CHECK_RETRIES$1 = 10;
async function checkIfAssetHasUrl$1(http, params, { resolve, reject, locale, processingCheckWait = ASSET_PROCESSING_CHECK_WAIT$1, processingCheckRetries = ASSET_PROCESSING_CHECK_RETRIES$1, checkCount = 0, }) {
return get$M(http, params).then((asset) => {
if (asset.fields.file[locale].url) {
resolve(asset);
}
else if (checkCount === processingCheckRetries) {
const error = new Error();
error.name = 'AssetProcessingTimeout';
error.message = 'Asset is taking longer then expected to process.';
reject(error);
}
else {
checkCount++;
setTimeout(() => checkIfAssetHasUrl$1(http, params, {
resolve: resolve,
reject: reject,
locale: locale,
checkCount: checkCount,
processingCheckWait,
processingCheckRetries,
}), processingCheckWait);
}
});
}
const processForLocale$1 = async (http, { asset, locale, options: { processingCheckRetries, processingCheckWait } = {}, ...params }) => {
return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${asset.sys.release.sys.id}/assets/${asset.sys.id}/files/${locale}/process`, null, {
headers: {
'X-Contentful-Version': asset.sys.version,
},
})
.then(() => {
return new Promise((resolve, reject) => checkIfAssetHasUrl$1(http, {
spaceId: params.spaceId,
environmentId: params.environmentId,
assetId: asset.sys.id,
releaseId: asset.sys.release.sys.id,
}, {
resolve,
reject,
locale,
processingCheckWait,
processingCheckRetries,
}));
});
};
const processForAllLocales$1 = async (http, { asset, options = {}, ...params }) => {
const locales = Object.keys(asset.fields.file || {});
let mostUpToDateAssetVersion = asset;
// Let all the locales process
// Since they all resolve at different times,
// we need to pick the last resolved value
// to reflect the most recent state
const allProcessingLocales = locales.map((locale) => processForLocale$1(http, { ...params, asset, locale, options }).then((result) => {
// Side effect of always setting the most up to date asset version
// The last one to call this will be the last one that finished
// and thus the most up to date
mostUpToDateAssetVersion = result;
}));
return Promise.all(allProcessingLocales).then(() => mostUpToDateAssetVersion);
};
var ReleaseAsset = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create$t,
createFromFiles: createFromFiles$1,
createWithId: createWithId$d,
get: get$M,
getMany: getMany$C,
processForAllLocales: processForAllLocales$1,
processForLocale: processForLocale$1,
update: update$u
});
const get$L = (http, params, rawData, headers) => {
if (params.releaseId) {
return get$M(http, params);
}
return get$14(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}`, {
params: normalizeSelect(params.query),
headers: headers ? { ...headers } : undefined,
});
};
const getPublished$1 = (http, params, rawData, headers) => {
return get$14(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/public/assets`, {
params: normalizeSelect(params.query),
headers: headers ? { ...headers } : undefined,
});
};
const getMany$B = (http, params, rawData, headers) => {
if (params.releaseId) {
return getMany$C(http, params);
}
return get$14(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets`, {
params: normalizeSelect(params.query),
headers: headers ? { ...headers } : undefined,
});
};
const update$t = (http, params, rawData, headers) => {
if (params.releaseId) {
return update$u(http, params, rawData, headers ?? {});
}
const data = copy__default.default(rawData);
delete data.sys;
return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}`, data, {
headers: {
'X-Contentful-Version': rawData.sys.version ?? 0,
...headers,
},
});
};
const del$t = (http, params) => {
return del$H(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}`);
};
const publish$4 = (http, params, rawData) => {
const payload = params.locales?.length ? { add: { fields: { '*': params.locales } } } : null;
return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/published`, payload, {
headers: {
'X-Contentful-Version': rawData.sys.version ?? 0,
},
});
};
const unpublish$4 = (http, params, rawData) => {
if (params.locales?.length) {
const payload = { remove: { fields: { '*': params.locales } } };
return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/published`, payload, {
headers: {
'X-Contentful-Version': rawData?.sys.version,
},
});
}
else {
return del$H(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/published`);
}
};
const archive$2 = (http, params) => {
return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/archived`);
};
const unarchive$2 = (http, params) => {
return del$H(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/archived`);
};
const create$s = (http, params, rawData) => {
if (params.releaseId) {
return create$t(http, params, rawData, {});
}
const data = copy__default.default(rawData);
return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets`, data);
};
const createWithId$c = (http, params, rawData) => {
if (params.releaseId) {
return createWithId$d(http, params, rawData, {});
}
const data = copy__default.default(rawData);
return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}`, data);
};
const createFromFiles = async (http, params, data) => {
if (params.releaseId) {
return createFromFiles$1(http, params, data);
}
const httpUpload = getUploadHttpClient(http, { uploadTimeout: params.uploadTimeout });
const { file } = data.fields;
return Promise.all(Object.keys(file).map(async (locale) => {
const { contentType, fileName } = file[locale];
return create$u(httpUpload, params, file[locale]).then((upload) => {
return {
[locale]: {
contentType,
fileName,
uploadFrom: {
sys: {
type: 'Link',
linkType: 'Upload',
id: upload.sys.id,
},
},
},
};
});
}))
.then((uploads) => {
const file = uploads.reduce((fieldsData, upload) => ({ ...fieldsData, ...upload }), {});
const asset = {
...data,
fields: {
...data.fields,
file,
},
};
return create$s(http, params, asset);
})
.catch(contentfulSdkCore.errorHandler);
};
/**
* Asset processing
*/
const ASSET_PROCESSING_CHECK_WAIT = 3000;
const ASSET_PROCESSING_CHECK_RETRIES = 10;
async function checkIfAssetHasUrl(http, params, { resolve, reject, locale, processingCheckWait = ASSET_PROCESSING_CHECK_WAIT, processingCheckRetries = ASSET_PROCESSING_CHECK_RETRIES, checkCount = 0, }) {
return get$L(http, params).then((asset) => {
if (asset.fields.file[locale].url) {
resolve(asset);
}
else if (checkCount === processingCheckRetries) {
const error = new Error();
error.name = 'AssetProcessingTimeout';
error.message = 'Asset is taking longer then expected to process.';
reject(error);
}
else {
checkCount++;
setTimeout(() => checkIfAssetHasUrl(http, params, {
resolve: resolve,
reject: reject,
locale: locale,
checkCount: checkCount,
processingCheckWait,
processingCheckRetries,
}), processingCheckWait);
}
});
}
const processForLocale = async (http, { asset, locale, options: { processingCheckRetries, processingCheckWait } = {}, ...params }) => {
if (asset.sys.release) {
return processForLocale$1(http, {
asset: asset,
locale,
options: { processingCheckRetries, processingCheckWait },
...params,
});
}
return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${asset.sys.id}/files/${locale}/process`, null, {
headers: {
'X-Contentful-Version': asset.sys.version,
},
})
.then(() => {
return new Promise((resolve, reject) => checkIfAssetHasUrl(http, {
spaceId: params.spaceId,
environmentId: params.environmentId,
assetId: asset.sys.id,
}, {
resolve,
reject,
locale,
processingCheckWait,
processingCheckRetries,
}));
});
};
const processForAllLocales = async (http, { asset, options = {}, ...params }) => {
if (asset.sys.release) {
return processForAllLocales$1(http, {
asset: asset,
options,
...params,
});
}
const locales = Object.keys(asset.fields.file || {});
let mostUpToDateAssetVersion = asset;
// Let all the locales process
// Since they all resolve at different times,
// we need to pick the last resolved value
// to reflect the most recent state
const allProcessingLocales = locales.map((locale) => processForLocale(http, { ...params, asset, locale, options }).then((result) => {
// Side effect of always setting the most up to date asset version
// The last one to call this will be the last one that finished
// and thus the most up to date
mostUpToDateAssetVersion = result;
}));
return Promise.all(allProcessingLocales).then(() => mostUpToDateAssetVersion);
};
var Asset = /*#__PURE__*/Object.freeze({
__proto__: null,
archive: archive$2,
create: create$s,
createFromFiles: createFromFiles,
createWithId: createWithId$c,
del: del$t,
get: get$L,
getMany: getMany$B,
getPublished: getPublished$1,
processForAllLocales: processForAllLocales,
processForLocale: processForLocale,
publish: publish$4,
unarchive: unarchive$2,
unpublish: unpublish$4,
update: update$t
});
const ASSET_KEY_MAX_LIFETIME = 48 * 60 * 60;
class ValidationError extends Error {
constructor(name, message) {
super(`Invalid "${name}" provided, ` + message);
this.name = 'ValidationError';
}
}
const validateTimestamp = (name, timestamp, options) => {
options = options || {};
if (typeof timestamp !== 'number') {
throw new ValidationError(name, `only numeric values are allowed for timestamps, provided type was "${typeof timestamp}"`);
}
if (options.maximum && timestamp > options.maximum) {
throw new ValidationError(name, `value (${timestamp}) cannot be further in the future than expected maximum (${options.maximum})`);
}
if (options.now && timestamp < options.now) {
throw new ValidationError(name, `value (${timestamp}) cannot be in the past, current time was ${options.now}`);
}
};
const create$r = (http, params, data) => {
const expiresAt = data.expiresAt;
const now = Math.floor(Date.now() / 1000);
const currentMaxLifetime = now + ASSET_KEY_MAX_LIFETIME;
validateTimestamp('expiresAt', expiresAt, { maximum: currentMaxLifetime,