@payloadcms/figma 1.0.0-beta.0 → 1.0.0-internal.d040868

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/dist/adapters/build-lambda-zip.d.ts +2 -1
  2. package/dist/adapters/build-lambda-zip.js +4 -1
  3. package/dist/adapters/deploy-output/assertDeployableServerActionsKey.d.ts +14 -0
  4. package/dist/adapters/deploy-output/assertDeployableServerActionsKey.js +33 -0
  5. package/dist/commands/upload-schema.js +23 -9
  6. package/dist/content-api/auth.d.ts +34 -0
  7. package/dist/content-api/auth.js +70 -0
  8. package/dist/content-api/awaitWithSignal.d.ts +2 -0
  9. package/dist/content-api/awaitWithSignal.js +27 -0
  10. package/dist/content-api/createContentApiClient.d.ts +18 -0
  11. package/dist/content-api/createContentApiClient.js +90 -0
  12. package/dist/content-api/withRateLimitRetries.d.ts +7 -0
  13. package/dist/content-api/withRateLimitRetries.js +45 -0
  14. package/dist/db-content-api/index.d.ts +5 -5
  15. package/dist/db-content-api/index.js +43 -13
  16. package/dist/index.d.ts +1 -0
  17. package/dist/index.js +1 -0
  18. package/dist/oauth/components/FigmaAvatar/index.js +3 -2
  19. package/dist/oauth/components/FigmaAvatarCell/index.js +3 -1
  20. package/dist/oauth/components/LoginButton/index.js +8 -4
  21. package/dist/oauth/components/LogoutButton/index.js +3 -2
  22. package/dist/oauth/endpoints/getLoginEndpoint.js +2 -5
  23. package/dist/oauth/hooks/me.d.ts +4 -3
  24. package/dist/oauth/hooks/me.js +6 -52
  25. package/dist/oauth/hooks/refresh.js +9 -1
  26. package/dist/oauth/index.js +3 -3
  27. package/dist/oauth/strategy/index.d.ts +3 -0
  28. package/dist/oauth/strategy/index.js +49 -3
  29. package/dist/oauth/utilities/clearCookie.d.ts +1 -0
  30. package/dist/oauth/utilities/clearCookie.js +13 -9
  31. package/dist/oauth/utilities/clearSessionCookies.d.ts +5 -0
  32. package/dist/oauth/utilities/clearSessionCookies.js +17 -0
  33. package/dist/oauth/utilities/mergeHeaders.js +11 -23
  34. package/dist/oauth/utilities/refreshTokens.d.ts +9 -3
  35. package/dist/oauth/utilities/refreshTokens.js +45 -34
  36. package/dist/oauth/utilities/resolvePayloadRedirect.d.ts +13 -0
  37. package/dist/oauth/utilities/resolvePayloadRedirect.js +30 -0
  38. package/dist/plugin/build-config.js +14 -13
  39. package/dist/plugin/cloud-limits/CloudLimitModal/index.js +1 -1
  40. package/dist/plugin/cloud-limits/shared.d.ts +5 -1
  41. package/dist/plugin/cloud-limits/utilities/toasts.d.ts +2 -1
  42. package/dist/plugin/dev-cookie-names.d.ts +4 -1
  43. package/dist/plugin/dev-cookie-names.js +6 -3
  44. package/dist/plugin/environment-error.d.ts +4 -0
  45. package/dist/plugin/environment-error.js +22 -0
  46. package/dist/plugin/sandbox-upload-fetch.d.ts +5 -6
  47. package/dist/plugin/sandbox-upload-fetch.js +22 -14
  48. package/dist/storage-content-api/client.d.ts +3 -3
  49. package/dist/storage-content-api/client.js +13 -35
  50. package/dist/storage-content-api/index.js +20 -21
  51. package/dist/storage-content-api/staticHandler.js +4 -1
  52. package/dist/storage-content-api/types.d.ts +2 -2
  53. package/dist/translations/ar.d.ts +9 -0
  54. package/dist/translations/ar.js +10 -1
  55. package/dist/translations/az.d.ts +9 -0
  56. package/dist/translations/az.js +10 -1
  57. package/dist/translations/bg.d.ts +9 -0
  58. package/dist/translations/bg.js +10 -1
  59. package/dist/translations/bnBd.d.ts +9 -0
  60. package/dist/translations/bnBd.js +10 -1
  61. package/dist/translations/bnIn.d.ts +9 -0
  62. package/dist/translations/bnIn.js +10 -1
  63. package/dist/translations/ca.d.ts +9 -0
  64. package/dist/translations/ca.js +10 -1
  65. package/dist/translations/cs.d.ts +9 -0
  66. package/dist/translations/cs.js +10 -1
  67. package/dist/translations/da.d.ts +9 -0
  68. package/dist/translations/da.js +10 -1
  69. package/dist/translations/de.d.ts +9 -0
  70. package/dist/translations/de.js +10 -1
  71. package/dist/translations/en.d.ts +9 -0
  72. package/dist/translations/en.js +10 -1
  73. package/dist/translations/es.d.ts +9 -0
  74. package/dist/translations/es.js +15 -6
  75. package/dist/translations/et.d.ts +9 -0
  76. package/dist/translations/et.js +10 -1
  77. package/dist/translations/fa.d.ts +9 -0
  78. package/dist/translations/fa.js +10 -1
  79. package/dist/translations/fr.d.ts +9 -0
  80. package/dist/translations/fr.js +10 -1
  81. package/dist/translations/he.d.ts +9 -0
  82. package/dist/translations/he.js +10 -1
  83. package/dist/translations/hr.d.ts +9 -0
  84. package/dist/translations/hr.js +10 -1
  85. package/dist/translations/hu.d.ts +9 -0
  86. package/dist/translations/hu.js +10 -1
  87. package/dist/translations/hy.d.ts +9 -0
  88. package/dist/translations/hy.js +10 -1
  89. package/dist/translations/id.d.ts +9 -0
  90. package/dist/translations/id.js +10 -1
  91. package/dist/translations/index.d.ts +400 -3
  92. package/dist/translations/is.d.ts +9 -0
  93. package/dist/translations/is.js +10 -1
  94. package/dist/translations/it.d.ts +9 -0
  95. package/dist/translations/it.js +10 -1
  96. package/dist/translations/ja.d.ts +9 -0
  97. package/dist/translations/ja.js +14 -5
  98. package/dist/translations/ko.d.ts +9 -0
  99. package/dist/translations/ko.js +16 -7
  100. package/dist/translations/lt.d.ts +9 -0
  101. package/dist/translations/lt.js +10 -1
  102. package/dist/translations/lv.d.ts +9 -0
  103. package/dist/translations/lv.js +10 -1
  104. package/dist/translations/my.d.ts +9 -0
  105. package/dist/translations/my.js +10 -1
  106. package/dist/translations/nb.d.ts +9 -0
  107. package/dist/translations/nb.js +10 -1
  108. package/dist/translations/nl.d.ts +9 -0
  109. package/dist/translations/nl.js +10 -1
  110. package/dist/translations/pl.d.ts +9 -0
  111. package/dist/translations/pl.js +10 -1
  112. package/dist/translations/pt.d.ts +9 -0
  113. package/dist/translations/pt.js +15 -6
  114. package/dist/translations/ro.d.ts +9 -0
  115. package/dist/translations/ro.js +10 -1
  116. package/dist/translations/rs.d.ts +9 -0
  117. package/dist/translations/rs.js +10 -1
  118. package/dist/translations/rsLatin.d.ts +9 -0
  119. package/dist/translations/rsLatin.js +10 -1
  120. package/dist/translations/ru.d.ts +9 -0
  121. package/dist/translations/ru.js +10 -1
  122. package/dist/translations/sk.d.ts +9 -0
  123. package/dist/translations/sk.js +10 -1
  124. package/dist/translations/sl.d.ts +9 -0
  125. package/dist/translations/sl.js +10 -1
  126. package/dist/translations/sv.d.ts +9 -0
  127. package/dist/translations/sv.js +10 -1
  128. package/dist/translations/ta.d.ts +9 -0
  129. package/dist/translations/ta.js +10 -1
  130. package/dist/translations/th.d.ts +9 -0
  131. package/dist/translations/th.js +10 -1
  132. package/dist/translations/tr.d.ts +9 -0
  133. package/dist/translations/tr.js +10 -1
  134. package/dist/translations/uk.d.ts +9 -0
  135. package/dist/translations/uk.js +10 -1
  136. package/dist/translations/vi.d.ts +9 -0
  137. package/dist/translations/vi.js +10 -1
  138. package/dist/translations/zh.d.ts +9 -0
  139. package/dist/translations/zh.js +10 -1
  140. package/dist/translations/zhTw.d.ts +9 -0
  141. package/dist/translations/zhTw.js +10 -1
  142. package/dist/utils/env-management.js +7 -0
  143. package/package.json +1 -1
  144. package/dist/db-content-api/utilities/auth.d.ts +0 -29
  145. 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 or zip creation fails
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 or zip creation fails
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 projectToken = apiKey ? null : await getValidProjectToken({
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 (!apiKey && !projectToken) {
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 response = await fetch(`${contentApiUrl}/api/v0/content_systems/${encodeURIComponent(environment.contentSystemId)}/jsonb_to_index_migration_schema`, {
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,2 @@
1
+ /** Stop this caller's wait without cancelling a promise shared with other callers. */
2
+ export declare function awaitWithSignal<T>(promise: Promise<T>, signal: AbortSignal): Promise<T>;
@@ -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
+ }
@@ -1,11 +1,11 @@
1
1
  import type { BaseDatabaseAdapter, CreateArgs, DatabaseAdapterObj } from 'payload';
2
- import createClient from 'openapi-fetch';
2
+ import type { ContentApiAuth } from '../content-api/auth.js';
3
3
  import type { paths } from './generated/content-api-types.js';
4
- import { type AuthMode } from './utilities/auth.js';
4
+ import { createContentApiClient } from '../content-api/createContentApiClient.js';
5
5
  import { type DocumentSchemaWire } from './utilities/schema/buildDocumentSchema.js';
6
6
  type ContentAPIOptions = {
7
7
  allowIDOnCreate?: boolean;
8
- auth: AuthMode;
8
+ auth: ContentApiAuth;
9
9
  contentSystemId: string;
10
10
  environmentName?: string;
11
11
  notifyLocalJobQueue: boolean;
@@ -24,9 +24,9 @@ export declare const LOCAL_JOB_QUEUE_NOTICE: string;
24
24
  */
25
25
  export declare function maybeNotifyLocalJobQueue(adapter: ContentAPIAdapter, args: CreateArgs): void;
26
26
  export type ContentAPIAdapter = {
27
- auth: AuthMode;
27
+ auth: ContentApiAuth;
28
28
  clearDatabase: () => Promise<void>;
29
- client: ReturnType<typeof createClient<paths>>;
29
+ client: ReturnType<typeof createContentApiClient<paths>>['api'];
30
30
  clientVersionHeaders: Record<string, string>;
31
31
  contentSystemId: string;
32
32
  documentSchema: () => DocumentSchemaWire;
@@ -1,13 +1,13 @@
1
- import createClient from 'openapi-fetch';
1
+ import { isDeepStrictEqual } from 'node:util';
2
2
  import { APIError, createDatabaseAdapter, ValidationError } from 'payload';
3
3
  import { v4 as uuid } from 'uuid';
4
4
  import { FigmaApiError } from '../api/figma-api.js';
5
5
  import { CONTENT_SYSTEM_NOT_FOUND_MESSAGE } from '../constants.js';
6
+ import { createContentApiClient } from '../content-api/createContentApiClient.js';
6
7
  import { redirectInitialAutosaveCreate } from '../plugin/cloud-limits/server/redirectInitialAutosaveCreate.js';
7
8
  import { getGlobalSlug } from './temp-utilities/slug.js';
8
9
  import { addFallbackSort } from './temp-utilities/sorting.js';
9
10
  import { unwrapDocument, unwrapFindResponse } from './temp-utilities/unwrapDocument.js';
10
- import { createAuthMiddleware, createErrorMiddleware } from './utilities/auth.js';
11
11
  import { getClientVersionHeaders } from './utilities/clientVersionHeaders.js';
12
12
  import { dataToContentAPI, resolveVersionContent } from './utilities/data/index.js';
13
13
  import { injectGlobalType } from './utilities/data/injectGlobalType.js';
@@ -573,7 +573,43 @@ export function getClearDatabaseUrl(url, cutoverState) {
573
573
  }
574
574
  return clearDatabaseUrl.toString();
575
575
  }
576
+ async function countJobsForHandleSchedules(args) {
577
+ if (args.collection !== 'payload-jobs') {
578
+ return undefined;
579
+ }
580
+ // Payload's /handle-schedules counts unfinished jobs before queuing another occurrence.
581
+ // Until v1 supports error and meta.scheduled JSON filters, apply those filters locally.
582
+ const countFilters = args.where?.and ?? [];
583
+ const noErrorFilter = countFilters.find((filter)=>isDeepStrictEqual(filter, {
584
+ error: {
585
+ exists: false
586
+ }
587
+ }));
588
+ if (!noErrorFilter) {
589
+ return undefined;
590
+ }
591
+ const onlyScheduledJobsFilter = countFilters.find((filter)=>isDeepStrictEqual(filter, {
592
+ 'meta.scheduled': {
593
+ equals: true
594
+ }
595
+ }));
596
+ const { docs } = await this.find({
597
+ ...args,
598
+ limit: 0,
599
+ where: {
600
+ ...args.where,
601
+ and: countFilters.filter((filter)=>filter !== noErrorFilter && filter !== onlyScheduledJobsFilter)
602
+ }
603
+ });
604
+ return {
605
+ totalDocs: docs.filter((job)=>job.error == null && (!onlyScheduledJobsFilter || job.meta?.scheduled === true)).length
606
+ };
607
+ }
576
608
  async function count(args) {
609
+ const handleSchedulesCount = await countJobsForHandleSchedules.call(this, args);
610
+ if (handleSchedulesCount) {
611
+ return handleSchedulesCount;
612
+ }
577
613
  const locale = addFallbackLocale(args.locale, this.payload);
578
614
  const { data: response, error, response: httpResponse } = await this.client.POST('/api/v1/documents:count', {
579
615
  body: {
@@ -870,25 +906,19 @@ export const contentAPIAdapter = (opts)=>({
870
906
  defaultIDType: 'text',
871
907
  init: ({ payload })=>{
872
908
  const clientVersionHeaders = getClientVersionHeaders();
873
- const client = createClient({
874
- baseUrl: opts.url,
875
- headers: clientVersionHeaders
876
- });
877
- const middlewareOpts = {
909
+ const contentApi = createContentApiClient({
878
910
  auth: opts.auth,
911
+ baseUrl: opts.url,
879
912
  contentSystemId: opts.contentSystemId,
880
- logger: payload.logger,
881
- url: opts.url
882
- };
883
- client.use(createAuthMiddleware(middlewareOpts));
884
- client.use(createErrorMiddleware(middlewareOpts));
913
+ logger: payload.logger
914
+ });
885
915
  return createDatabaseAdapter({
886
916
  name: 'content-api',
887
917
  allowIDOnCreate: opts.allowIDOnCreate ?? false,
888
918
  auth: opts.auth,
889
919
  beginTransaction: ()=>Promise.resolve(null),
890
920
  clearDatabase: clearDatabase,
891
- client,
921
+ client: contentApi.api,
892
922
  clientVersionHeaders,
893
923
  commitTransaction: async ()=>{},
894
924
  connect: connect,
package/dist/index.d.ts CHANGED
@@ -4,4 +4,5 @@ export { figmaContentSystem } from './plugin/adapter.js';
4
4
  export type { FigmaContentSystemOptions } from './plugin/adapter.js';
5
5
  export { buildFigmaConfig } from './plugin/build-config.js';
6
6
  export type { FigmaConfig } from './plugin/build-config.js';
7
+ export { FigmaEnvironmentError } from './plugin/environment-error.js';
7
8
  export { passesMakeViewerWriteGate } from './plugin/make-permission-access/make-permission-access.js';
package/dist/index.js CHANGED
@@ -4,5 +4,6 @@ export { contentAPIAdapter } from './db-content-api/index.js';
4
4
  export { figmaContentSystem } from './plugin/adapter.js';
5
5
  // Export buildConfig wrapper and its config type
6
6
  export { buildFigmaConfig } from './plugin/build-config.js';
7
+ export { FigmaEnvironmentError } from './plugin/environment-error.js';
7
8
  // Export the Make permission predicate for slug-specific baseAccess overrides.
8
9
  export { passesMakeViewerWriteGate } from './plugin/make-permission-access/make-permission-access.js';
@@ -1,12 +1,13 @@
1
1
  'use client';
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
- import { useAuth } from '@payloadcms/ui';
3
+ import { useAuth, useTranslation } from '@payloadcms/ui';
4
4
  import { useState } from 'react';
5
5
  import { FigmaAvatarPlaceholder, isValidImageUrl } from '../FigmaAvatarPlaceholder/index.js';
6
6
  import './index.scss';
7
7
  const baseClass = 'figma-avatar';
8
8
  export const FigmaAvatar = ()=>{
9
9
  const { user } = useAuth();
10
+ const { t } = useTranslation();
10
11
  const [hasError, setHasError] = useState(false);
11
12
  const figmaImageUrl = user?.figmaImageUrl;
12
13
  if (!figmaImageUrl || hasError || !isValidImageUrl(figmaImageUrl)) {
@@ -15,7 +16,7 @@ export const FigmaAvatar = ()=>{
15
16
  });
16
17
  }
17
18
  return /*#__PURE__*/ _jsx("img", {
18
- alt: "Profile",
19
+ alt: t('figma:profile'),
19
20
  className: `${baseClass}__image`,
20
21
  height: 25,
21
22
  onError: ()=>setHasError(true),
@@ -1,10 +1,12 @@
1
1
  'use client';
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { useTranslation } from '@payloadcms/ui';
3
4
  import { useState } from 'react';
4
5
  import { FigmaAvatarPlaceholder, isValidImageUrl } from '../FigmaAvatarPlaceholder/index.js';
5
6
  import './index.scss';
6
7
  const baseClass = 'figma-avatar-cell';
7
8
  export const FigmaAvatarCell = ({ cellData })=>{
9
+ const { t } = useTranslation();
8
10
  const [hasError, setHasError] = useState(false);
9
11
  const figmaImageUrl = cellData;
10
12
  if (!figmaImageUrl || hasError || !isValidImageUrl(figmaImageUrl)) {
@@ -13,7 +15,7 @@ export const FigmaAvatarCell = ({ cellData })=>{
13
15
  });
14
16
  }
15
17
  return /*#__PURE__*/ _jsx("img", {
16
- alt: "Avatar",
18
+ alt: t('figma:avatar'),
17
19
  className: `${baseClass}__image`,
18
20
  height: 20,
19
21
  onError: ()=>setHasError(true),