@payloadcms/figma 1.0.0-beta.0 → 1.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/build-lambda-zip.d.ts +2 -1
- package/dist/adapters/build-lambda-zip.js +4 -1
- package/dist/adapters/deploy-output/assertDeployableServerActionsKey.d.ts +14 -0
- package/dist/adapters/deploy-output/assertDeployableServerActionsKey.js +33 -0
- package/dist/commands/upload-schema.js +23 -9
- package/dist/content-api/auth.d.ts +34 -0
- package/dist/content-api/auth.js +70 -0
- package/dist/content-api/awaitWithSignal.d.ts +2 -0
- package/dist/content-api/awaitWithSignal.js +27 -0
- package/dist/content-api/createContentApiClient.d.ts +18 -0
- package/dist/content-api/createContentApiClient.js +90 -0
- package/dist/content-api/withRateLimitRetries.d.ts +7 -0
- package/dist/content-api/withRateLimitRetries.js +45 -0
- package/dist/db-content-api/generated/content-api-types.d.ts +247 -0
- package/dist/db-content-api/index.d.ts +5 -5
- package/dist/db-content-api/index.js +46 -16
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/oauth/components/FigmaAvatar/index.js +3 -2
- package/dist/oauth/components/FigmaAvatarCell/index.js +3 -1
- package/dist/oauth/components/LoginButton/index.js +8 -4
- package/dist/oauth/components/LogoutButton/index.js +3 -2
- package/dist/oauth/defaults.js +2 -2
- package/dist/oauth/endpoints/getLoginEndpoint.js +2 -5
- package/dist/oauth/hooks/me.d.ts +4 -3
- package/dist/oauth/hooks/me.js +6 -52
- package/dist/oauth/hooks/refresh.js +9 -1
- package/dist/oauth/index.js +3 -3
- package/dist/oauth/strategy/index.d.ts +3 -0
- package/dist/oauth/strategy/index.js +49 -3
- package/dist/oauth/utilities/clearCookie.d.ts +1 -0
- package/dist/oauth/utilities/clearCookie.js +13 -9
- package/dist/oauth/utilities/clearSessionCookies.d.ts +5 -0
- package/dist/oauth/utilities/clearSessionCookies.js +17 -0
- package/dist/oauth/utilities/getAuthorizeURL.js +1 -2
- package/dist/oauth/utilities/mergeHeaders.js +11 -23
- package/dist/oauth/utilities/refreshTokens.d.ts +9 -3
- package/dist/oauth/utilities/refreshTokens.js +45 -34
- package/dist/oauth/utilities/resolvePayloadRedirect.d.ts +13 -0
- package/dist/oauth/utilities/resolvePayloadRedirect.js +30 -0
- package/dist/plugin/build-config.js +16 -13
- package/dist/plugin/cloud-limits/CloudLimitModal/index.js +1 -1
- package/dist/plugin/cloud-limits/shared.d.ts +5 -1
- package/dist/plugin/cloud-limits/utilities/toasts.d.ts +2 -1
- package/dist/plugin/dev-cookie-names.d.ts +4 -1
- package/dist/plugin/dev-cookie-names.js +6 -3
- package/dist/plugin/environment-error.d.ts +4 -0
- package/dist/plugin/environment-error.js +22 -0
- package/dist/plugin/mcp-oauth.d.ts +10 -0
- package/dist/plugin/mcp-oauth.js +24 -0
- package/dist/plugin/sandbox-upload-fetch.d.ts +5 -6
- package/dist/plugin/sandbox-upload-fetch.js +22 -14
- package/dist/scss.d.js +1 -1
- package/dist/storage-content-api/api-types.d.ts +22 -1
- package/dist/storage-content-api/api-types.js +2 -1
- package/dist/storage-content-api/client.d.ts +3 -3
- package/dist/storage-content-api/client.js +13 -35
- package/dist/storage-content-api/index.js +20 -21
- package/dist/storage-content-api/staticHandler.js +4 -1
- package/dist/storage-content-api/types.d.ts +2 -2
- package/dist/translations/ar.d.ts +9 -0
- package/dist/translations/ar.js +10 -1
- package/dist/translations/az.d.ts +9 -0
- package/dist/translations/az.js +10 -1
- package/dist/translations/bg.d.ts +9 -0
- package/dist/translations/bg.js +10 -1
- package/dist/translations/bnBd.d.ts +9 -0
- package/dist/translations/bnBd.js +10 -1
- package/dist/translations/bnIn.d.ts +9 -0
- package/dist/translations/bnIn.js +10 -1
- package/dist/translations/ca.d.ts +9 -0
- package/dist/translations/ca.js +10 -1
- package/dist/translations/cs.d.ts +9 -0
- package/dist/translations/cs.js +10 -1
- package/dist/translations/da.d.ts +9 -0
- package/dist/translations/da.js +10 -1
- package/dist/translations/de.d.ts +9 -0
- package/dist/translations/de.js +10 -1
- package/dist/translations/en.d.ts +9 -0
- package/dist/translations/en.js +10 -1
- package/dist/translations/es.d.ts +9 -0
- package/dist/translations/es.js +15 -6
- package/dist/translations/et.d.ts +9 -0
- package/dist/translations/et.js +10 -1
- package/dist/translations/fa.d.ts +9 -0
- package/dist/translations/fa.js +10 -1
- package/dist/translations/fr.d.ts +9 -0
- package/dist/translations/fr.js +10 -1
- package/dist/translations/he.d.ts +9 -0
- package/dist/translations/he.js +10 -1
- package/dist/translations/hr.d.ts +9 -0
- package/dist/translations/hr.js +10 -1
- package/dist/translations/hu.d.ts +9 -0
- package/dist/translations/hu.js +10 -1
- package/dist/translations/hy.d.ts +9 -0
- package/dist/translations/hy.js +10 -1
- package/dist/translations/id.d.ts +9 -0
- package/dist/translations/id.js +10 -1
- package/dist/translations/index.d.ts +400 -3
- package/dist/translations/is.d.ts +9 -0
- package/dist/translations/is.js +10 -1
- package/dist/translations/it.d.ts +9 -0
- package/dist/translations/it.js +10 -1
- package/dist/translations/ja.d.ts +9 -0
- package/dist/translations/ja.js +14 -5
- package/dist/translations/ko.d.ts +9 -0
- package/dist/translations/ko.js +16 -7
- package/dist/translations/lt.d.ts +9 -0
- package/dist/translations/lt.js +10 -1
- package/dist/translations/lv.d.ts +9 -0
- package/dist/translations/lv.js +10 -1
- package/dist/translations/my.d.ts +9 -0
- package/dist/translations/my.js +10 -1
- package/dist/translations/nb.d.ts +9 -0
- package/dist/translations/nb.js +10 -1
- package/dist/translations/nl.d.ts +9 -0
- package/dist/translations/nl.js +10 -1
- package/dist/translations/pl.d.ts +9 -0
- package/dist/translations/pl.js +10 -1
- package/dist/translations/pt.d.ts +9 -0
- package/dist/translations/pt.js +15 -6
- package/dist/translations/ro.d.ts +9 -0
- package/dist/translations/ro.js +10 -1
- package/dist/translations/rs.d.ts +9 -0
- package/dist/translations/rs.js +10 -1
- package/dist/translations/rsLatin.d.ts +9 -0
- package/dist/translations/rsLatin.js +10 -1
- package/dist/translations/ru.d.ts +9 -0
- package/dist/translations/ru.js +10 -1
- package/dist/translations/sk.d.ts +9 -0
- package/dist/translations/sk.js +10 -1
- package/dist/translations/sl.d.ts +9 -0
- package/dist/translations/sl.js +10 -1
- package/dist/translations/sv.d.ts +9 -0
- package/dist/translations/sv.js +10 -1
- package/dist/translations/ta.d.ts +9 -0
- package/dist/translations/ta.js +10 -1
- package/dist/translations/th.d.ts +9 -0
- package/dist/translations/th.js +10 -1
- package/dist/translations/tr.d.ts +9 -0
- package/dist/translations/tr.js +10 -1
- package/dist/translations/uk.d.ts +9 -0
- package/dist/translations/uk.js +10 -1
- package/dist/translations/vi.d.ts +9 -0
- package/dist/translations/vi.js +10 -1
- package/dist/translations/zh.d.ts +9 -0
- package/dist/translations/zh.js +10 -1
- package/dist/translations/zhTw.d.ts +9 -0
- package/dist/translations/zhTw.js +10 -1
- package/dist/utils/env-management.js +7 -0
- package/package.json +20 -22
- package/dist/db-content-api/utilities/auth.d.ts +0 -29
- package/dist/db-content-api/utilities/auth.js +0 -82
|
@@ -19,7 +19,8 @@ export declare const LAMBDA_MAX_UNZIPPED_BYTES: number;
|
|
|
19
19
|
*
|
|
20
20
|
* @param projectPath - Path to project root
|
|
21
21
|
* @returns The built bundle: its unzipped byte size and the absolute zip path.
|
|
22
|
-
* @throws Error if standalone directory missing
|
|
22
|
+
* @throws Error if standalone directory missing, the build embeds an undeployable Server
|
|
23
|
+
* Actions key, or zip creation fails
|
|
23
24
|
*/
|
|
24
25
|
export declare function buildLambdaZip(projectPath: string, output?: string, options?: {
|
|
25
26
|
logger?: AdapterLogger;
|
|
@@ -3,6 +3,7 @@ import { createWriteStream } from 'fs';
|
|
|
3
3
|
import fs from 'fs/promises';
|
|
4
4
|
import path from 'path';
|
|
5
5
|
import { configureNextjsCache } from './configureNextjsCache.js';
|
|
6
|
+
import { assertDeployableServerActionsKey } from './deploy-output/assertDeployableServerActionsKey.js';
|
|
6
7
|
import { inspectNextjsOutput } from './deploy-output/inspectNextjsOutput.js';
|
|
7
8
|
import { resolveOutputPath } from './deploy-output/resolveOutputPath.js';
|
|
8
9
|
import { walkBundleFiles } from './fs-utils.js';
|
|
@@ -26,13 +27,15 @@ import { isBundlableFile } from './secret-files.js';
|
|
|
26
27
|
*
|
|
27
28
|
* @param projectPath - Path to project root
|
|
28
29
|
* @returns The built bundle: its unzipped byte size and the absolute zip path.
|
|
29
|
-
* @throws Error if standalone directory missing
|
|
30
|
+
* @throws Error if standalone directory missing, the build embeds an undeployable Server
|
|
31
|
+
* Actions key, or zip creation fails
|
|
30
32
|
*/ export async function buildLambdaZip(projectPath, output, options = {}) {
|
|
31
33
|
const outputPath = resolveOutputPath(projectPath, 'nextjs', output);
|
|
32
34
|
const layout = await inspectNextjsOutput(outputPath);
|
|
33
35
|
if (!layout) {
|
|
34
36
|
throw new Error(`Standalone build not found at ${outputPath}`);
|
|
35
37
|
}
|
|
38
|
+
await assertDeployableServerActionsKey(outputPath);
|
|
36
39
|
const files = (await walkBundleFiles(layout.standalonePath)).filter((file)=>isBundlableFile(file.relativePath));
|
|
37
40
|
// Override archive entries in memory without changing Next's standalone output.
|
|
38
41
|
const bundleFileOverrides = await createBundleFileOverrides(layout.standalonePath, layout.serverEntryPath, options.logger);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Throws when a Next.js build output embeds a Server Actions key that must not
|
|
3
|
+
* be deployed.
|
|
4
|
+
*
|
|
5
|
+
* Next writes the key to `server/server-reference-manifest.json`, and the
|
|
6
|
+
* deployed server uses it to encrypt the values Server Actions close over.
|
|
7
|
+
* Next does not validate a key supplied through
|
|
8
|
+
* `NEXT_SERVER_ACTIONS_ENCRYPTION_KEY`, so a malformed one only fails at
|
|
9
|
+
* runtime. Reproducible builds may pin it to a public sentinel such as
|
|
10
|
+
* `AAAA…=` (32 zero bytes), which is safe for testing but publishes the key if
|
|
11
|
+
* deployed. A generated key never has every byte equal, so that is the
|
|
12
|
+
* sentinel test.
|
|
13
|
+
*/
|
|
14
|
+
export declare function assertDeployableServerActionsKey(outputPath: string): Promise<void>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import { readJson } from './readJson.js';
|
|
3
|
+
const AES_KEY_BYTE_LENGTHS = [
|
|
4
|
+
16,
|
|
5
|
+
24,
|
|
6
|
+
32
|
|
7
|
+
];
|
|
8
|
+
/**
|
|
9
|
+
* Throws when a Next.js build output embeds a Server Actions key that must not
|
|
10
|
+
* be deployed.
|
|
11
|
+
*
|
|
12
|
+
* Next writes the key to `server/server-reference-manifest.json`, and the
|
|
13
|
+
* deployed server uses it to encrypt the values Server Actions close over.
|
|
14
|
+
* Next does not validate a key supplied through
|
|
15
|
+
* `NEXT_SERVER_ACTIONS_ENCRYPTION_KEY`, so a malformed one only fails at
|
|
16
|
+
* runtime. Reproducible builds may pin it to a public sentinel such as
|
|
17
|
+
* `AAAA…=` (32 zero bytes), which is safe for testing but publishes the key if
|
|
18
|
+
* deployed. A generated key never has every byte equal, so that is the
|
|
19
|
+
* sentinel test.
|
|
20
|
+
*/ export async function assertDeployableServerActionsKey(outputPath) {
|
|
21
|
+
const manifestPath = path.join(outputPath, 'server', 'server-reference-manifest.json');
|
|
22
|
+
const key = (await readJson(manifestPath))?.encryptionKey;
|
|
23
|
+
if (typeof key !== 'string') {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const bytes = Buffer.from(key, 'base64');
|
|
27
|
+
if (bytes.toString('base64').replace(/=+$/, '') !== key.replace(/=+$/, '') || !AES_KEY_BYTE_LENGTHS.includes(bytes.length)) {
|
|
28
|
+
throw new Error(`Refusing to deploy: the Server Actions encryptionKey in ${manifestPath} is not a base64-encoded 16, 24, or 32 byte AES key.`);
|
|
29
|
+
}
|
|
30
|
+
if (bytes.every((byte)=>byte === bytes[0])) {
|
|
31
|
+
throw new Error(`Refusing to deploy: ${manifestPath} embeds a sentinel Server Actions encryptionKey. ` + 'Rebuild with a secret NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, or unset it so Next generates one.');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -4,10 +4,12 @@ import { getBootstrapInfo } from '../api/control-plane.js';
|
|
|
4
4
|
import { tryGetCredential } from '../auth/oauth-flow.js';
|
|
5
5
|
import { getValidProjectToken } from '../auth/project-token.js';
|
|
6
6
|
import { getTokenStore } from '../auth/token-store.js';
|
|
7
|
+
import { createContentApiClient } from '../content-api/createContentApiClient.js';
|
|
7
8
|
import { buildDocumentSchema } from '../db-content-api/utilities/schema/buildDocumentSchema.js';
|
|
8
9
|
import { cacheAllEnvironments } from '../utils/cache-bootstrap.js';
|
|
9
10
|
import { getEnvVar } from '../utils/env-management.js';
|
|
10
11
|
import { loadPayloadConfig } from '../utils/load-payload-config.js';
|
|
12
|
+
import { warning } from '../utils/log.js';
|
|
11
13
|
import { resolveEnvironment } from '../utils/resolve-environment.js';
|
|
12
14
|
import { loginCommand } from './login.js';
|
|
13
15
|
/** Upload the current Payload collection schema for Content API migration tooling. */ export async function uploadSchemaCommand(options = {}) {
|
|
@@ -46,15 +48,24 @@ import { loginCommand } from './login.js';
|
|
|
46
48
|
const documentSchema = buildDocumentSchema(config);
|
|
47
49
|
spinner.message('Uploading collection schema...');
|
|
48
50
|
const apiKey = process.env.FIGMA_CONTENT_API_ACCESS_KEY;
|
|
49
|
-
const
|
|
51
|
+
const auth = apiKey ? {
|
|
52
|
+
apiKey,
|
|
53
|
+
mode: 'apiKey'
|
|
54
|
+
} : {
|
|
55
|
+
mode: 'tokenStore',
|
|
50
56
|
projectInfo: {
|
|
51
57
|
environmentName: environment.name,
|
|
52
58
|
projectId
|
|
53
59
|
},
|
|
60
|
+
tokenStore
|
|
61
|
+
};
|
|
62
|
+
// Preserve the CLI's auth error before URL validation. The client reuses the cached token.
|
|
63
|
+
const tokenStoreMissingTokenCheck = auth.mode === 'tokenStore' && !await getValidProjectToken({
|
|
64
|
+
projectInfo: auth.projectInfo,
|
|
54
65
|
tenantId: environment.contentSystemId,
|
|
55
66
|
tokenStore
|
|
56
67
|
});
|
|
57
|
-
if (
|
|
68
|
+
if (tokenStoreMissingTokenCheck) {
|
|
58
69
|
throw new Error('Could not get a project token. Run `@payloadcms/figma login` and retry.');
|
|
59
70
|
}
|
|
60
71
|
// The bootstrap environment carries its regional Content API URL.
|
|
@@ -62,17 +73,20 @@ import { loginCommand } from './login.js';
|
|
|
62
73
|
if (!contentApiUrl) {
|
|
63
74
|
throw new Error(`No Content API URL returned for environment "${environment.name}".`);
|
|
64
75
|
}
|
|
65
|
-
const
|
|
76
|
+
const contentApi = createContentApiClient({
|
|
77
|
+
auth,
|
|
78
|
+
baseUrl: contentApiUrl,
|
|
79
|
+
contentSystemId: environment.contentSystemId,
|
|
80
|
+
logger: {
|
|
81
|
+
warn: warning
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
const response = await contentApi.request(`/api/v0/content_systems/${encodeURIComponent(environment.contentSystemId)}/jsonb_to_index_migration_schema`, {
|
|
66
85
|
body: JSON.stringify({
|
|
67
86
|
documentSchema
|
|
68
87
|
}),
|
|
69
88
|
headers: {
|
|
70
|
-
'Content-Type': 'application/json'
|
|
71
|
-
...apiKey ? {
|
|
72
|
-
'X-Api-Key': apiKey
|
|
73
|
-
} : {
|
|
74
|
-
Authorization: `Bearer ${projectToken}`
|
|
75
|
-
}
|
|
89
|
+
'Content-Type': 'application/json'
|
|
76
90
|
},
|
|
77
91
|
method: 'PUT'
|
|
78
92
|
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { TokenStore } from '../auth/token-store.js';
|
|
2
|
+
import type { ProjectStoreScope } from '../auth/types.js';
|
|
3
|
+
export type ContentApiAuth = {
|
|
4
|
+
apiKey: string;
|
|
5
|
+
mode: 'apiKey';
|
|
6
|
+
} | {
|
|
7
|
+
mode: 'devJwt';
|
|
8
|
+
} | {
|
|
9
|
+
mode: 'tokenStore';
|
|
10
|
+
projectInfo?: ProjectStoreScope;
|
|
11
|
+
tokenStore: TokenStore;
|
|
12
|
+
};
|
|
13
|
+
export type ContentApiLogger = {
|
|
14
|
+
error?: (details: {
|
|
15
|
+
msg: string;
|
|
16
|
+
status: number;
|
|
17
|
+
statusText: string;
|
|
18
|
+
}) => void;
|
|
19
|
+
info?: (message: string) => void;
|
|
20
|
+
warn: (message: string) => void;
|
|
21
|
+
};
|
|
22
|
+
export declare function invalidateDevJwt(baseUrl: string, contentSystemId: string): void;
|
|
23
|
+
export declare function getDevJwt({ baseUrl, contentSystemId, logger, signal, }: {
|
|
24
|
+
baseUrl: string;
|
|
25
|
+
contentSystemId: string;
|
|
26
|
+
logger: ContentApiLogger;
|
|
27
|
+
signal: AbortSignal;
|
|
28
|
+
}): Promise<string>;
|
|
29
|
+
export declare function applyContentApiAuth(request: Request, options: {
|
|
30
|
+
auth: ContentApiAuth;
|
|
31
|
+
baseUrl: string;
|
|
32
|
+
contentSystemId: string;
|
|
33
|
+
logger: ContentApiLogger;
|
|
34
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { getValidProjectToken } from '../auth/project-token.js';
|
|
2
|
+
import { awaitWithSignal } from './awaitWithSignal.js';
|
|
3
|
+
import { withRateLimitRetries } from './withRateLimitRetries.js';
|
|
4
|
+
const devJwtCache = new Map();
|
|
5
|
+
function devJwtCacheKey(baseUrl, contentSystemId) {
|
|
6
|
+
return `${baseUrl}::${contentSystemId}`;
|
|
7
|
+
}
|
|
8
|
+
export function invalidateDevJwt(baseUrl, contentSystemId) {
|
|
9
|
+
devJwtCache.delete(devJwtCacheKey(baseUrl, contentSystemId));
|
|
10
|
+
}
|
|
11
|
+
export async function getDevJwt({ baseUrl, contentSystemId, logger, signal }) {
|
|
12
|
+
signal.throwIfAborted();
|
|
13
|
+
const cacheKey = devJwtCacheKey(baseUrl, contentSystemId);
|
|
14
|
+
const cached = devJwtCache.get(cacheKey);
|
|
15
|
+
if (cached) {
|
|
16
|
+
return cached;
|
|
17
|
+
}
|
|
18
|
+
const usesSuperUser = !contentSystemId || contentSystemId === 'test-system' || contentSystemId === '*';
|
|
19
|
+
const fetchWithRetries = withRateLimitRetries({
|
|
20
|
+
fetchImplementation: fetch,
|
|
21
|
+
warn: (message)=>logger.warn(message)
|
|
22
|
+
});
|
|
23
|
+
const response = await fetchWithRetries(new URL('/dev/jwt', baseUrl), {
|
|
24
|
+
body: JSON.stringify({
|
|
25
|
+
content_system_id: usesSuperUser ? '*' : contentSystemId
|
|
26
|
+
}),
|
|
27
|
+
headers: {
|
|
28
|
+
'Content-Type': 'application/json'
|
|
29
|
+
},
|
|
30
|
+
method: 'POST',
|
|
31
|
+
signal
|
|
32
|
+
});
|
|
33
|
+
if (!response.ok) {
|
|
34
|
+
throw new Error(`Failed to get dev JWT: ${response.status} ${response.statusText}`);
|
|
35
|
+
}
|
|
36
|
+
const { token } = await awaitWithSignal(response.json(), signal);
|
|
37
|
+
signal.throwIfAborted();
|
|
38
|
+
devJwtCache.set(cacheKey, token);
|
|
39
|
+
logger.info?.(`Dev JWT acquired for content system: ${contentSystemId}`);
|
|
40
|
+
return token;
|
|
41
|
+
}
|
|
42
|
+
export async function applyContentApiAuth(request, options) {
|
|
43
|
+
const { auth, baseUrl, contentSystemId, logger } = options;
|
|
44
|
+
request.signal.throwIfAborted();
|
|
45
|
+
if (auth.mode === 'apiKey') {
|
|
46
|
+
request.headers.set('X-Api-Key', auth.apiKey);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (auth.mode === 'tokenStore') {
|
|
50
|
+
const token = await awaitWithSignal(getValidProjectToken({
|
|
51
|
+
...auth.projectInfo ? {
|
|
52
|
+
projectInfo: auth.projectInfo
|
|
53
|
+
} : {},
|
|
54
|
+
tenantId: contentSystemId,
|
|
55
|
+
tokenStore: auth.tokenStore
|
|
56
|
+
}), request.signal);
|
|
57
|
+
request.signal.throwIfAborted();
|
|
58
|
+
if (!token) {
|
|
59
|
+
throw new Error('Authentication required. Run `npx @payloadcms/figma login` to authenticate.');
|
|
60
|
+
}
|
|
61
|
+
request.headers.set('Authorization', `Bearer ${token}`);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
request.headers.set('Authorization', `Bearer ${await getDevJwt({
|
|
65
|
+
baseUrl,
|
|
66
|
+
contentSystemId,
|
|
67
|
+
logger,
|
|
68
|
+
signal: request.signal
|
|
69
|
+
})}`);
|
|
70
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Stop this caller's wait without cancelling a promise shared with other callers. */ export async function awaitWithSignal(promise, signal) {
|
|
2
|
+
let onAbort;
|
|
3
|
+
const cancellation = new Promise((_resolve, reject)=>{
|
|
4
|
+
onAbort = ()=>{
|
|
5
|
+
const reason = signal.reason;
|
|
6
|
+
reject(reason instanceof Error ? reason : new DOMException('The operation was aborted', 'AbortError'));
|
|
7
|
+
};
|
|
8
|
+
if (signal.aborted) {
|
|
9
|
+
onAbort();
|
|
10
|
+
} else {
|
|
11
|
+
signal.addEventListener('abort', onAbort, {
|
|
12
|
+
once: true
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
try {
|
|
17
|
+
// Observe the shared promise even if cancellation has already occurred.
|
|
18
|
+
return await Promise.race([
|
|
19
|
+
cancellation,
|
|
20
|
+
promise
|
|
21
|
+
]);
|
|
22
|
+
} finally{
|
|
23
|
+
if (onAbort) {
|
|
24
|
+
signal.removeEventListener('abort', onAbort);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ContentApiAuth, ContentApiLogger } from './auth.js';
|
|
2
|
+
export type ContentApiClientOptions = {
|
|
3
|
+
auth: ContentApiAuth;
|
|
4
|
+
baseUrl: string;
|
|
5
|
+
contentSystemId: string;
|
|
6
|
+
logger: ContentApiLogger;
|
|
7
|
+
/** Optional deadline across authentication and retries, ending when response headers arrive. */
|
|
8
|
+
requestTimeoutMs?: number;
|
|
9
|
+
};
|
|
10
|
+
type RawRequestOptions = {
|
|
11
|
+
unauthenticatedDevEndpoint?: boolean;
|
|
12
|
+
};
|
|
13
|
+
/** The sole request entry point for Content API endpoints in the Payload plugin. */
|
|
14
|
+
export declare function createContentApiClient<Paths extends Record<string, Record<string, unknown>>>(options: ContentApiClientOptions): {
|
|
15
|
+
api: import("openapi-fetch").Client<Paths, `${string}/${string}`>;
|
|
16
|
+
request(path: string, init?: RequestInit, rawOptions?: RawRequestOptions): Promise<Response>;
|
|
17
|
+
};
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import createClient from 'openapi-fetch';
|
|
2
|
+
import { getClientVersionHeaders } from '../db-content-api/utilities/clientVersionHeaders.js';
|
|
3
|
+
import { applyContentApiAuth, getDevJwt, invalidateDevJwt } from './auth.js';
|
|
4
|
+
import { withRateLimitRetries } from './withRateLimitRetries.js';
|
|
5
|
+
/** The sole request entry point for Content API endpoints in the Payload plugin. */ export function createContentApiClient(options) {
|
|
6
|
+
const baseUrl = new URL(options.baseUrl);
|
|
7
|
+
if (options.requestTimeoutMs !== undefined && (!Number.isFinite(options.requestTimeoutMs) || options.requestTimeoutMs <= 0 || options.requestTimeoutMs > 2_147_483_647)) {
|
|
8
|
+
throw new RangeError('requestTimeoutMs must be between 0 (exclusive) and 2147483647 milliseconds');
|
|
9
|
+
}
|
|
10
|
+
const versionHeaders = getClientVersionHeaders();
|
|
11
|
+
const fetchWithRetries = withRateLimitRetries({
|
|
12
|
+
fetchImplementation: fetch,
|
|
13
|
+
warn: (message)=>options.logger.warn(message)
|
|
14
|
+
});
|
|
15
|
+
async function send(input, init, rawOptions) {
|
|
16
|
+
const original = new Request(input, init);
|
|
17
|
+
if (new URL(original.url).origin !== baseUrl.origin) {
|
|
18
|
+
throw new Error('Content API client cannot request a different origin');
|
|
19
|
+
}
|
|
20
|
+
if (rawOptions?.unauthenticatedDevEndpoint && !new URL(original.url).pathname.startsWith('/dev/')) {
|
|
21
|
+
throw new Error('Unauthenticated Content API requests are only allowed for dev endpoints');
|
|
22
|
+
}
|
|
23
|
+
original.signal.throwIfAborted();
|
|
24
|
+
const deadlineController = new AbortController();
|
|
25
|
+
const signal = AbortSignal.any([
|
|
26
|
+
original.signal,
|
|
27
|
+
deadlineController.signal
|
|
28
|
+
]);
|
|
29
|
+
const timeout = options.requestTimeoutMs === undefined ? undefined : globalThis.setTimeout(()=>deadlineController.abort(new DOMException('Content API request timed out', 'TimeoutError')), options.requestTimeoutMs);
|
|
30
|
+
try {
|
|
31
|
+
const request = new Request(original.clone(), {
|
|
32
|
+
signal
|
|
33
|
+
});
|
|
34
|
+
for (const [name, value] of Object.entries(versionHeaders)){
|
|
35
|
+
request.headers.set(name, value);
|
|
36
|
+
}
|
|
37
|
+
if (!rawOptions?.unauthenticatedDevEndpoint) {
|
|
38
|
+
await applyContentApiAuth(request, options);
|
|
39
|
+
}
|
|
40
|
+
signal.throwIfAborted();
|
|
41
|
+
let response = await fetchWithRetries(request);
|
|
42
|
+
signal.throwIfAborted();
|
|
43
|
+
if (response.status === 401 && options.auth.mode === 'devJwt' && !rawOptions?.unauthenticatedDevEndpoint) {
|
|
44
|
+
options.logger.info?.('Dev JWT expired, refreshing...');
|
|
45
|
+
invalidateDevJwt(options.baseUrl, options.contentSystemId);
|
|
46
|
+
const refreshedToken = await getDevJwt({
|
|
47
|
+
baseUrl: options.baseUrl,
|
|
48
|
+
contentSystemId: options.contentSystemId,
|
|
49
|
+
logger: options.logger,
|
|
50
|
+
signal
|
|
51
|
+
});
|
|
52
|
+
signal.throwIfAborted();
|
|
53
|
+
const retryRequest = new Request(original.clone(), {
|
|
54
|
+
signal
|
|
55
|
+
});
|
|
56
|
+
for (const [name, value] of Object.entries(versionHeaders)){
|
|
57
|
+
retryRequest.headers.set(name, value);
|
|
58
|
+
}
|
|
59
|
+
retryRequest.headers.set('Authorization', `Bearer ${refreshedToken}`);
|
|
60
|
+
response = await fetchWithRetries(retryRequest);
|
|
61
|
+
}
|
|
62
|
+
signal.throwIfAborted();
|
|
63
|
+
if (!response.ok && response.status !== 429) {
|
|
64
|
+
options.logger.error?.({
|
|
65
|
+
msg: `HTTP ${response.status} from ${request.url}`,
|
|
66
|
+
status: response.status,
|
|
67
|
+
statusText: response.statusText
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return response;
|
|
71
|
+
} catch (error) {
|
|
72
|
+
// Node's abortable waits may wrap the original timeout/cancellation reason in AbortError.
|
|
73
|
+
signal.throwIfAborted();
|
|
74
|
+
throw error;
|
|
75
|
+
} finally{
|
|
76
|
+
globalThis.clearTimeout(timeout);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const api = createClient({
|
|
80
|
+
baseUrl: options.baseUrl,
|
|
81
|
+
fetch: send
|
|
82
|
+
});
|
|
83
|
+
return {
|
|
84
|
+
api,
|
|
85
|
+
request (path, init, rawOptions) {
|
|
86
|
+
const url = new URL(path, baseUrl);
|
|
87
|
+
return send(url, init, rawOptions);
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
interface WithRateLimitRetriesArgs {
|
|
2
|
+
fetchImplementation: typeof fetch;
|
|
3
|
+
warn: (message: string) => void;
|
|
4
|
+
}
|
|
5
|
+
/** The retry budget starts after the first 429; caller aborts and other errors propagate. */
|
|
6
|
+
export declare function withRateLimitRetries({ fetchImplementation, warn, }: WithRateLimitRetriesArgs): typeof fetch;
|
|
7
|
+
export {};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { setTimeout as wait } from 'node:timers/promises';
|
|
2
|
+
const INITIAL_BACKOFF_MS = 200;
|
|
3
|
+
const MAX_RETRY_DURATION_MS = 30_000;
|
|
4
|
+
/** The retry budget starts after the first 429; caller aborts and other errors propagate. */ export function withRateLimitRetries({ fetchImplementation, warn }) {
|
|
5
|
+
return async (input, init)=>{
|
|
6
|
+
const request = input instanceof Request && init == null ? input.clone() : new Request(input, init);
|
|
7
|
+
request.signal.throwIfAborted();
|
|
8
|
+
let response = await fetchImplementation(request.clone());
|
|
9
|
+
if (response.status !== 429) {
|
|
10
|
+
return response;
|
|
11
|
+
}
|
|
12
|
+
const timeoutReason = new DOMException('Rate-limit retry budget exhausted', 'TimeoutError');
|
|
13
|
+
const retryController = new AbortController();
|
|
14
|
+
const signal = AbortSignal.any([
|
|
15
|
+
request.signal,
|
|
16
|
+
retryController.signal
|
|
17
|
+
]);
|
|
18
|
+
const timeout = globalThis.setTimeout(()=>retryController.abort(timeoutReason), MAX_RETRY_DURATION_MS);
|
|
19
|
+
let attempt = 0;
|
|
20
|
+
try {
|
|
21
|
+
while(response.status === 429){
|
|
22
|
+
signal.throwIfAborted();
|
|
23
|
+
const backoffMs = INITIAL_BACKOFF_MS * 2 ** attempt;
|
|
24
|
+
const delayMs = backoffMs + Math.random() * backoffMs;
|
|
25
|
+
warn(`HTTP 429 from ${request.url}; retrying in ${Math.round(delayMs)}ms`);
|
|
26
|
+
await wait(delayMs, undefined, {
|
|
27
|
+
signal
|
|
28
|
+
});
|
|
29
|
+
signal.throwIfAborted();
|
|
30
|
+
// Only the caller can abort an in-flight request: a retry may have already written data.
|
|
31
|
+
response = await fetchImplementation(request.clone());
|
|
32
|
+
attempt += 1;
|
|
33
|
+
}
|
|
34
|
+
return response;
|
|
35
|
+
} catch (error) {
|
|
36
|
+
const isRetryTimeout = error === timeoutReason || error instanceof Error && error.name === 'AbortError' && error.cause === timeoutReason;
|
|
37
|
+
if (isRetryTimeout && !request.signal.aborted) {
|
|
38
|
+
return response;
|
|
39
|
+
}
|
|
40
|
+
throw error;
|
|
41
|
+
} finally{
|
|
42
|
+
globalThis.clearTimeout(timeout);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|