@payloadcms/figma 0.1.0-internal.10c3b07 → 0.1.0-internal.fbdc0d3

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 (149) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/{utils → adapters}/asset-collection.d.ts +10 -4
  3. package/dist/{utils → adapters}/asset-collection.js +58 -17
  4. package/dist/{utils → adapters}/build-lambda-zip.d.ts +4 -2
  5. package/dist/adapters/build-lambda-zip.js +111 -0
  6. package/dist/adapters/configureNextjsCache.d.ts +8 -0
  7. package/dist/adapters/configureNextjsCache.js +55 -0
  8. package/dist/{utils → adapters}/deploy-output/resolveOutputPath.d.ts +1 -1
  9. package/dist/adapters/fs-utils.d.ts +39 -0
  10. package/dist/adapters/fs-utils.js +135 -0
  11. package/dist/adapters/index.d.ts +4 -0
  12. package/dist/adapters/index.js +3 -0
  13. package/dist/adapters/lambda-runtime/nextjs-cache.d.ts +40 -0
  14. package/dist/adapters/lambda-runtime/nextjs-cache.js +174 -0
  15. package/dist/adapters/nextjs.d.ts +12 -0
  16. package/dist/adapters/nextjs.js +67 -0
  17. package/dist/{utils/adapters → adapters}/nitro.d.ts +2 -2
  18. package/dist/{utils/adapters → adapters}/nitro.js +54 -29
  19. package/dist/adapters/secret-files.d.ts +25 -0
  20. package/dist/adapters/secret-files.js +50 -0
  21. package/dist/adapters/types.d.ts +42 -0
  22. package/dist/adapters/types.js +1 -0
  23. package/dist/{utils/adapters → adapters}/vite.d.ts +1 -1
  24. package/dist/{utils/adapters → adapters}/vite.js +4 -3
  25. package/dist/api/control-plane.d.ts +11 -0
  26. package/dist/api/control-plane.js +26 -0
  27. package/dist/auth/headless-oauth-flow.js +4 -0
  28. package/dist/auth/oauth-flow.js +17 -0
  29. package/dist/auth/refresh.js +12 -12
  30. package/dist/auth/requested-scopes.d.ts +1 -0
  31. package/dist/auth/requested-scopes.js +3 -0
  32. package/dist/auth/token-store.d.ts +16 -0
  33. package/dist/auth/token-store.js +33 -0
  34. package/dist/auth/types.d.ts +5 -3
  35. package/dist/commands/bootstrap.js +3 -0
  36. package/dist/commands/build-lambda-zip.js +1 -1
  37. package/dist/commands/deploy.js +2 -2
  38. package/dist/commands/init.js +72 -2
  39. package/dist/commands/upgrade.js +65 -1
  40. package/dist/commands/upload-schema.js +3 -4
  41. package/dist/config/oauth.js +6 -1
  42. package/dist/constants.d.ts +0 -2
  43. package/dist/constants.js +0 -3
  44. package/dist/db-content-api/generated/content-api-types.d.ts +6 -2
  45. package/dist/db-content-api/utilities/auth.d.ts +1 -4
  46. package/dist/db-content-api/utilities/auth.js +1 -1
  47. package/dist/db-content-api/utilities/data/index.js +8 -2
  48. package/dist/db-content-api/utilities/data/removeVirtualFields.d.ts +3 -11
  49. package/dist/db-content-api/utilities/data/removeVirtualFields.js +12 -50
  50. package/dist/db-content-api/utilities/schema/buildDocumentSchema.js +9 -4
  51. package/dist/index.d.ts +1 -0
  52. package/dist/index.js +2 -0
  53. package/dist/next/image-loader.d.ts +6 -0
  54. package/dist/next/image-loader.js +14 -0
  55. package/dist/oauth/components/LoginButton/index.js +66 -19
  56. package/dist/oauth/components/LoginButton/index.scss +121 -15
  57. package/dist/oauth/defaults.js +4 -1
  58. package/dist/plugin/build-config.d.ts +13 -3
  59. package/dist/plugin/build-config.js +198 -59
  60. package/dist/plugin/cache-revalidation-hooks.d.ts +6 -0
  61. package/dist/plugin/cache-revalidation-hooks.js +69 -0
  62. package/dist/plugin/cloud-limits/CloudLimitModal/index.d.ts +2 -1
  63. package/dist/plugin/cloud-limits/icons/ExternalLinkIcon.d.ts +2 -1
  64. package/dist/plugin/make-permission-access/make-permission-access.d.ts +8 -0
  65. package/dist/plugin/make-permission-access/make-permission-access.js +24 -0
  66. package/dist/storage-content-api/api-types.d.ts +5 -2
  67. package/dist/storage-content-api/buildBaseMediaResponseHeaders.d.ts +1 -1
  68. package/dist/storage-content-api/buildBaseMediaResponseHeaders.js +3 -1
  69. package/dist/storage-content-api/buildClientUploadFetchBackHeaders.d.ts +8 -6
  70. package/dist/storage-content-api/buildClientUploadFetchBackHeaders.js +17 -12
  71. package/dist/storage-content-api/buildMediaRequestHeaders.d.ts +1 -0
  72. package/dist/storage-content-api/buildMediaRequestHeaders.js +14 -0
  73. package/dist/storage-content-api/buildMediaResponseHeaders.d.ts +3 -3
  74. package/dist/storage-content-api/buildMediaResponseHeaders.js +25 -18
  75. package/dist/storage-content-api/client-uploads/generate.d.ts +7 -3
  76. package/dist/storage-content-api/client-uploads/generate.js +22 -21
  77. package/dist/storage-content-api/client.d.ts +0 -2
  78. package/dist/storage-content-api/client.js +2 -2
  79. package/dist/storage-content-api/copyFile.d.ts +16 -0
  80. package/dist/storage-content-api/copyFile.js +90 -0
  81. package/dist/storage-content-api/deleteFile.d.ts +8 -0
  82. package/dist/storage-content-api/deleteFile.js +18 -0
  83. package/dist/storage-content-api/getDownloadResponseHeaderPolicy.d.ts +11 -0
  84. package/dist/storage-content-api/getDownloadResponseHeaderPolicy.js +33 -0
  85. package/dist/storage-content-api/getMediaType.d.ts +1 -0
  86. package/dist/storage-content-api/getMediaType.js +3 -0
  87. package/dist/storage-content-api/handleUpload.d.ts +1 -2
  88. package/dist/storage-content-api/handleUpload.js +13 -157
  89. package/dist/storage-content-api/hasSupportedContentEncoding.d.ts +1 -1
  90. package/dist/storage-content-api/hasSupportedContentEncoding.js +4 -2
  91. package/dist/storage-content-api/index.js +17 -8
  92. package/dist/storage-content-api/mediaErrorResponse.d.ts +1 -1
  93. package/dist/storage-content-api/mediaErrorResponse.js +2 -2
  94. package/dist/storage-content-api/resolveDownloadResponseHeaders.d.ts +5 -0
  95. package/dist/storage-content-api/resolveDownloadResponseHeaders.js +13 -0
  96. package/dist/storage-content-api/shouldAttachMedia.d.ts +1 -0
  97. package/dist/storage-content-api/{getInlineContentType.js → shouldAttachMedia.js} +8 -7
  98. package/dist/storage-content-api/staticHandler.d.ts +2 -1
  99. package/dist/storage-content-api/staticHandler.js +47 -53
  100. package/dist/storage-content-api/types.d.ts +4 -1
  101. package/dist/storage-content-api/uploadFileData.d.ts +10 -0
  102. package/dist/storage-content-api/uploadFileData.js +145 -0
  103. package/dist/utils/build-detection.js +3 -3
  104. package/dist/utils/cache-bootstrap.js +1 -0
  105. package/dist/utils/deploy-adapter.d.ts +2 -34
  106. package/dist/utils/deploy-adapter.js +16 -9
  107. package/dist/utils/env-management.d.ts +15 -0
  108. package/dist/utils/env-management.js +47 -0
  109. package/dist/utils/lambda-config.js +14 -9
  110. package/dist/utils/load-payload-config.js +1 -6
  111. package/dist/utils/next-image-loader-config.d.ts +2 -0
  112. package/dist/utils/next-image-loader-config.js +63 -0
  113. package/dist/utils/next-image-loader-file.d.ts +2 -0
  114. package/dist/utils/next-image-loader-file.js +11 -0
  115. package/dist/utils/payload-config-ast.d.ts +5 -0
  116. package/dist/utils/payload-config-ast.js +73 -4
  117. package/dist/utils/payload-config-modifier.js +3 -0
  118. package/dist/utils/payload-secret.d.ts +28 -0
  119. package/dist/utils/payload-secret.js +34 -0
  120. package/package.json +22 -10
  121. package/dist/storage-content-api/getInlineContentType.d.ts +0 -1
  122. package/dist/storage-content-api/handleDelete.d.ts +0 -7
  123. package/dist/storage-content-api/handleDelete.js +0 -15
  124. package/dist/storage-content-api/utilities/getSafeFilename.d.ts +0 -11
  125. package/dist/storage-content-api/utilities/getSafeFilename.js +0 -59
  126. package/dist/storage-content-api/utilities/index.d.ts +0 -2
  127. package/dist/storage-content-api/utilities/index.js +0 -2
  128. package/dist/storage-content-api/utilities/parseUploadReference.d.ts +0 -17
  129. package/dist/storage-content-api/utilities/parseUploadReference.js +0 -27
  130. package/dist/utils/adapters/nextjs.d.ts +0 -8
  131. package/dist/utils/adapters/nextjs.js +0 -64
  132. package/dist/utils/build-lambda-zip.js +0 -73
  133. package/dist/utils/fs-utils.d.ts +0 -12
  134. package/dist/utils/fs-utils.js +0 -55
  135. /package/dist/{utils → adapters}/deploy-output/inspectNextjsOutput/getNextRelativeAppDir.d.ts +0 -0
  136. /package/dist/{utils → adapters}/deploy-output/inspectNextjsOutput/getNextRelativeAppDir.js +0 -0
  137. /package/dist/{utils → adapters}/deploy-output/inspectNextjsOutput.d.ts +0 -0
  138. /package/dist/{utils → adapters}/deploy-output/inspectNextjsOutput.js +0 -0
  139. /package/dist/{utils → adapters}/deploy-output/inspectNitroOutput.d.ts +0 -0
  140. /package/dist/{utils → adapters}/deploy-output/inspectNitroOutput.js +0 -0
  141. /package/dist/{utils → adapters}/deploy-output/isFile.d.ts +0 -0
  142. /package/dist/{utils → adapters}/deploy-output/isFile.js +0 -0
  143. /package/dist/{utils → adapters}/deploy-output/readJson.d.ts +0 -0
  144. /package/dist/{utils → adapters}/deploy-output/readJson.js +0 -0
  145. /package/dist/{utils → adapters}/deploy-output/resolveNitroOutputLayout.d.ts +0 -0
  146. /package/dist/{utils → adapters}/deploy-output/resolveNitroOutputLayout.js +0 -0
  147. /package/dist/{utils → adapters}/deploy-output/resolveOutputPath.js +0 -0
  148. /package/dist/{utils → adapters}/deploy-output/resolveWithin.d.ts +0 -0
  149. /package/dist/{utils → adapters}/deploy-output/resolveWithin.js +0 -0
@@ -0,0 +1,5 @@
1
+ import type { CollectionConfig } from 'payload';
2
+ export declare const resolveDownloadResponseHeaders: ({ collection, payloadResponseHeaders, }: {
3
+ collection: CollectionConfig;
4
+ payloadResponseHeaders: Headers | undefined;
5
+ }) => Headers;
@@ -0,0 +1,13 @@
1
+ import { DEFAULT_MEDIA_CACHE_CONTROL } from './getDownloadResponseHeaderPolicy.js';
2
+ export const resolveDownloadResponseHeaders = ({ collection, payloadResponseHeaders })=>{
3
+ let headers = new Headers(payloadResponseHeaders);
4
+ if (!headers.has('Cache-Control')) {
5
+ headers.set('Cache-Control', DEFAULT_MEDIA_CACHE_CONTROL);
6
+ }
7
+ if (collection.upload && typeof collection.upload === 'object' && typeof collection.upload.modifyResponseHeaders === 'function') {
8
+ headers = collection.upload.modifyResponseHeaders({
9
+ headers
10
+ }) || headers;
11
+ }
12
+ return headers;
13
+ };
@@ -0,0 +1 @@
1
+ export declare function shouldAttachMedia(upstreamHeaders: Headers): boolean;
@@ -1,6 +1,7 @@
1
- // Keep this allowlist aligned with Gatekeeper's presignedMediaHeaders.ts. The plugin cannot
2
- // import the private Gatekeeper service, but both same-origin media proxies need the same policy.
3
- const INLINE_CONTENT_TYPES = new Set([
1
+ import { getMediaType } from './getMediaType.js';
2
+ // Only these media types may render inline on the application's origin.
3
+ // Unknown or active content must download as an attachment.
4
+ const INLINE_MEDIA_TYPES = new Set([
4
5
  'application/font-woff',
5
6
  'audio/aac',
6
7
  'audio/flac',
@@ -27,7 +28,7 @@ const INLINE_CONTENT_TYPES = new Set([
27
28
  'video/quicktime',
28
29
  'video/webm'
29
30
  ]);
30
- export const getInlineContentType = (value)=>{
31
- const normalized = value?.split(';', 1).at(0)?.trim().toLowerCase();
32
- return normalized && INLINE_CONTENT_TYPES.has(normalized) ? normalized : null;
33
- };
31
+ export function shouldAttachMedia(upstreamHeaders) {
32
+ const mediaType = getMediaType(upstreamHeaders);
33
+ return !mediaType || !INLINE_MEDIA_TYPES.has(mediaType);
34
+ }
@@ -4,6 +4,7 @@ import type { StorageClient } from './client.js';
4
4
  type Args = {
5
5
  client: StorageClient;
6
6
  collection: CollectionConfig;
7
+ prefix?: string;
7
8
  };
8
- export declare const getHandler: ({ client, collection }: Args) => StaticHandler;
9
+ export declare const getHandler: ({ client, collection, prefix }: Args) => StaticHandler;
9
10
  export {};
@@ -1,44 +1,43 @@
1
- import { getFilePrefix } from '@payloadcms/plugin-cloud-storage/utilities';
2
- import path from 'path';
3
- import { isImage } from 'payload/shared';
1
+ import { buildStoragePathData, getFilePrefix } from '@payloadcms/plugin-cloud-storage/utilities';
4
2
  import { buildClientUploadFetchBackHeaders } from './buildClientUploadFetchBackHeaders.js';
3
+ import { buildMediaRequestHeaders } from './buildMediaRequestHeaders.js';
5
4
  import { buildMediaResponseHeaders } from './buildMediaResponseHeaders.js';
5
+ import { getDownloadResponseHeaderPolicy } from './getDownloadResponseHeaderPolicy.js';
6
6
  import { hasSupportedContentEncoding } from './hasSupportedContentEncoding.js';
7
7
  import { mediaErrorResponse } from './mediaErrorResponse.js';
8
- import { parseUploadReference } from './utilities/index.js';
9
- const isRunningInLambda = ()=>process.env.AWS_EXECUTION_ENV?.startsWith('AWS_Lambda_') === true;
10
- const shouldReturnRedirect = ({ uploadReference })=>{
11
- if (!isRunningInLambda()) {
12
- return false;
13
- }
14
- if (!uploadReference) {
15
- return true;
16
- }
17
- const { mimeType } = parseUploadReference(uploadReference);
18
- return Boolean(mimeType && !isImage(mimeType));
19
- };
20
- const cancelResponseBody = async (response)=>{
21
- try {
22
- await response.body?.cancel();
23
- } catch {
24
- // The response will not be consumed after an error; cancellation is best-effort cleanup.
25
- }
26
- };
27
- export const getHandler = ({ client, collection })=>{
28
- return async (req, { params: { filename, uploadReference } })=>{
8
+ import { resolveDownloadResponseHeaders } from './resolveDownloadResponseHeaders.js';
9
+ const PRESIGNED_DOWNLOAD_URL_EXPIRES_IN_SECONDS = 300;
10
+ export const getHandler = ({ client, collection, prefix = '' })=>{
11
+ return async (req, { doc, headers, params: { filename, operation, uploadReference } })=>{
29
12
  try {
30
- const prefix = await getFilePrefix({
13
+ const prefixArgs = {
31
14
  collection,
15
+ collectionPrefix: prefix,
16
+ doc,
32
17
  filename,
33
18
  req,
34
19
  uploadReference
20
+ };
21
+ const docPrefix = await getFilePrefix(prefixArgs);
22
+ const { storageFilePath: key } = buildStoragePathData({
23
+ collectionPrefix: prefix,
24
+ docPrefix,
25
+ filename
26
+ });
27
+ const resolvedResponseHeaders = resolveDownloadResponseHeaders({
28
+ collection,
29
+ payloadResponseHeaders: headers
30
+ });
31
+ const responseHeaderPolicy = getDownloadResponseHeaderPolicy({
32
+ logger: req.payload.logger,
33
+ responseHeaders: resolvedResponseHeaders
35
34
  });
36
- const key = path.posix.join(prefix, filename);
37
35
  const { data, error } = await client.POST('/api/v0/uploads/download/sign', {
38
36
  body: {
39
37
  collectionId: collection.slug,
40
- expiresIn: 7200,
41
- filename: key
38
+ expiresIn: PRESIGNED_DOWNLOAD_URL_EXPIRES_IN_SECONDS,
39
+ filename: key,
40
+ responseHeaders: responseHeaderPolicy
42
41
  }
43
42
  });
44
43
  if (error || !data) {
@@ -47,27 +46,13 @@ export const getHandler = ({ client, collection })=>{
47
46
  status: 500
48
47
  });
49
48
  }
50
- // Lambda responses have a 6 MB limit, so deployed apps redirect to Gatekeeper, which
51
- // validates the signed URL and streams the file. Other runtimes do not have Gatekeeper
52
- // in front of them and must stream the file through Payload instead.
53
- // An image uploadReference marks an internal, one-time fetch-back. Payload core consumes
54
- // the body to size the image, so a redirect would leave it empty even in Lambda.
55
- if (shouldReturnRedirect({
56
- uploadReference
57
- })) {
49
+ const isClientUpload = Boolean(uploadReference);
50
+ // Lambda responses have a 6 MB limit, so redirect normal media to its signed storage URL.
51
+ // Payload reads client uploads and transform sources itself, so they need a response body.
52
+ if (isRunningInLambda() && !isClientUpload && operation !== 'transform') {
58
53
  return Response.redirect(data.url, 302);
59
54
  }
60
- const requestHeaders = new Headers({
61
- 'Accept-Encoding': 'identity'
62
- });
63
- const range = req.headers.get('Range');
64
- if (range) {
65
- requestHeaders.set('Range', range);
66
- const ifRange = req.headers.get('If-Range');
67
- if (ifRange) {
68
- requestHeaders.set('If-Range', ifRange);
69
- }
70
- }
55
+ const requestHeaders = buildMediaRequestHeaders(req.headers);
71
56
  let fileResponse;
72
57
  try {
73
58
  fileResponse = await fetch(data.url, {
@@ -78,10 +63,11 @@ export const getHandler = ({ client, collection })=>{
78
63
  signal: req.signal
79
64
  });
80
65
  } catch {
66
+ // Fetch errors can contain the signed URL; log only a fixed message to avoid exposing it.
81
67
  req.payload.logger.error('Failed to fetch file from storage');
82
68
  return mediaErrorResponse(500, 'Internal Server Error');
83
69
  }
84
- if (fileResponse.status === 416 && range) {
70
+ if (fileResponse.status === 416 && requestHeaders.has('Range')) {
85
71
  await cancelResponseBody(fileResponse);
86
72
  return mediaErrorResponse(416, 'Range Not Satisfiable', fileResponse.headers.get('Content-Range') ?? undefined);
87
73
  }
@@ -95,14 +81,12 @@ export const getHandler = ({ client, collection })=>{
95
81
  req.payload.logger.error('Unsupported Content-Encoding from storage');
96
82
  return mediaErrorResponse(502, 'Bad Gateway');
97
83
  }
98
- const clientUploadMimeType = uploadReference ? parseUploadReference(uploadReference).mimeType : undefined;
99
- const responseHeaders = uploadReference ? buildClientUploadFetchBackHeaders({
100
- fallbackContentType: clientUploadMimeType,
84
+ const responseHeaders = isClientUpload ? buildClientUploadFetchBackHeaders({
101
85
  filename,
102
- upstream: fileResponse.headers
86
+ upstreamHeaders: fileResponse.headers
103
87
  }) : buildMediaResponseHeaders({
104
88
  filename,
105
- upstream: fileResponse.headers
89
+ upstreamHeaders: fileResponse.headers
106
90
  });
107
91
  return new Response(fileResponse.body, {
108
92
  headers: responseHeaders,
@@ -120,3 +104,13 @@ export const getHandler = ({ client, collection })=>{
120
104
  }
121
105
  };
122
106
  };
107
+ function isRunningInLambda() {
108
+ return process.env.AWS_EXECUTION_ENV?.startsWith('AWS_Lambda_') === true;
109
+ }
110
+ async function cancelResponseBody(response) {
111
+ try {
112
+ await response.body?.cancel();
113
+ } catch {
114
+ // The response will not be consumed after an error; cancellation is best-effort cleanup.
115
+ }
116
+ }
@@ -1,9 +1,12 @@
1
+ import type { UploadInstructionsAccess } from 'payload';
1
2
  import type { AuthMode } from '../db-content-api/utilities/auth.js';
2
3
  export type StorageClientConfig = {
4
+ uploadInstructionsAccess?: UploadInstructionsAccess;
5
+ } & ({
3
6
  auth: AuthMode;
4
7
  baseUrl: string;
5
8
  contentSystemId: string;
6
9
  } | {
7
10
  baseUrl: string;
8
11
  contentApiKey: string;
9
- };
12
+ });
@@ -0,0 +1,10 @@
1
+ import type { StorageClient } from './client.js';
2
+ /** Uploads file bytes to `fileKey`, with a multipart upload for large files. */
3
+ export declare function uploadFileData({ client, collectionId, fileData, fileKey, fileSize, mimeType, }: {
4
+ client: StorageClient;
5
+ collectionId: string;
6
+ fileData: Buffer;
7
+ fileKey: string;
8
+ fileSize?: number;
9
+ mimeType: string;
10
+ }): Promise<void>;
@@ -0,0 +1,145 @@
1
+ import { APIError } from 'payload';
2
+ const PART_SIZE = 64 * 1024 * 1024 // 64MB per part
3
+ ;
4
+ const MAX_FILE_SIZE_BEFORE_MULTIPART = 100 * 1024 * 1024 // 100MB
5
+ ;
6
+ /** Uploads file bytes to `fileKey`, with a multipart upload for large files. */ export async function uploadFileData({ client, collectionId, fileData, fileKey, fileSize = fileData.length, mimeType }) {
7
+ if (fileSize > MAX_FILE_SIZE_BEFORE_MULTIPART) {
8
+ await uploadMultipart({
9
+ client,
10
+ collectionId,
11
+ fileData,
12
+ fileKey,
13
+ mimeType
14
+ });
15
+ } else {
16
+ await uploadSingleFile({
17
+ client,
18
+ collectionId,
19
+ fileData,
20
+ fileKey,
21
+ mimeType
22
+ });
23
+ }
24
+ }
25
+ async function uploadSingleFile({ client, collectionId, fileData, fileKey, mimeType }) {
26
+ const { data, error, response } = await client.POST('/api/v0/uploads/sign', {
27
+ body: {
28
+ collectionId,
29
+ contentType: mimeType,
30
+ expiresIn: 3600,
31
+ filename: fileKey
32
+ }
33
+ });
34
+ if (error) {
35
+ throw new APIError(`Failed to get presigned upload URL: ${error.message}`, response.status, {
36
+ code: error.code
37
+ });
38
+ }
39
+ if (!data) {
40
+ throw new Error('No response while getting presigned upload URL');
41
+ }
42
+ const uploadResponse = await fetch(data.url, {
43
+ // TS's BodyInit type rejects Buffer<ArrayBufferLike>; wrap as Uint8Array
44
+ // (a valid ArrayBufferView) — byte-identical.
45
+ body: new Uint8Array(fileData),
46
+ headers: {
47
+ 'Content-Type': mimeType
48
+ },
49
+ method: 'PUT'
50
+ });
51
+ if (!uploadResponse.ok) {
52
+ throw new Error(`Failed to upload to S3: ${uploadResponse.status} ${uploadResponse.statusText}`);
53
+ }
54
+ }
55
+ async function uploadMultipart({ client, collectionId, fileData, fileKey, mimeType }) {
56
+ const { data: initiateData, error: initiateError, response: initiateResponse } = await client.POST('/api/v0/uploads/multipart/initiate', {
57
+ body: {
58
+ collectionId,
59
+ contentType: mimeType,
60
+ filename: fileKey
61
+ }
62
+ });
63
+ if (initiateError) {
64
+ throw new APIError(`Failed to initiate multipart upload: ${initiateError.message}`, initiateResponse.status, {
65
+ code: initiateError.code
66
+ });
67
+ }
68
+ if (!initiateData) {
69
+ throw new Error('No response while initiating multipart upload');
70
+ }
71
+ const { uploadId } = initiateData;
72
+ try {
73
+ const numParts = Math.ceil(fileData.length / PART_SIZE);
74
+ const partNumbers = Array.from({
75
+ length: numParts
76
+ }, (_, i)=>i + 1);
77
+ const { data: partsData, error: partsError, response: partsResponse } = await client.POST('/api/v0/uploads/multipart/parts', {
78
+ body: {
79
+ collectionId,
80
+ expiresIn: 3600,
81
+ filename: fileKey,
82
+ partNumbers,
83
+ uploadId
84
+ }
85
+ });
86
+ if (partsError) {
87
+ throw new APIError(`Failed to get part URLs: ${partsError.message}`, partsResponse.status, {
88
+ code: partsError.code
89
+ });
90
+ }
91
+ if (!partsData) {
92
+ throw new Error('No response while getting part URLs');
93
+ }
94
+ const { parts } = partsData;
95
+ if (!parts || !Array.isArray(parts)) {
96
+ throw new Error('Invalid response from part URLs endpoint: parts is not an array');
97
+ }
98
+ const uploadedParts = await Promise.all(parts.map(async ({ partNumber, url })=>{
99
+ const start = (partNumber - 1) * PART_SIZE;
100
+ const end = Math.min(start + PART_SIZE, fileData.length);
101
+ const partData = fileData.slice(start, end);
102
+ const uploadResponse = await fetch(url, {
103
+ body: partData,
104
+ headers: {
105
+ 'Content-Type': mimeType
106
+ },
107
+ method: 'PUT'
108
+ });
109
+ const etag = uploadResponse.headers.get('ETag');
110
+ if (!etag) {
111
+ throw new Error(`No ETag returned for part ${partNumber}`);
112
+ }
113
+ return {
114
+ ETag: etag,
115
+ PartNumber: partNumber
116
+ };
117
+ }));
118
+ const { error: completeError, response: completeResponse } = await client.POST('/api/v0/uploads/multipart/complete', {
119
+ body: {
120
+ collectionId,
121
+ filename: fileKey,
122
+ parts: uploadedParts,
123
+ uploadId
124
+ }
125
+ });
126
+ if (completeError) {
127
+ throw new APIError(`Failed to complete multipart upload: ${completeError.message}`, completeResponse.status, {
128
+ code: completeError.code
129
+ });
130
+ }
131
+ } catch (error) {
132
+ try {
133
+ await client.POST('/api/v0/uploads/multipart/abort', {
134
+ body: {
135
+ collectionId,
136
+ filename: fileKey,
137
+ uploadId
138
+ }
139
+ });
140
+ } catch {
141
+ // Ignore abort errors
142
+ }
143
+ throw error;
144
+ }
145
+ }
@@ -1,9 +1,9 @@
1
1
  import fs from 'fs/promises';
2
2
  import path from 'path';
3
+ import { inspectNextjsOutput } from '../adapters/deploy-output/inspectNextjsOutput.js';
4
+ import { inspectNitroOutput } from '../adapters/deploy-output/inspectNitroOutput.js';
5
+ import { resolveOutputPath } from '../adapters/deploy-output/resolveOutputPath.js';
3
6
  import { assertNever } from './assert-never.js';
4
- import { inspectNextjsOutput } from './deploy-output/inspectNextjsOutput.js';
5
- import { inspectNitroOutput } from './deploy-output/inspectNitroOutput.js';
6
- import { resolveOutputPath } from './deploy-output/resolveOutputPath.js';
7
7
  /**
8
8
  * Detect a valid build across supported frameworks.
9
9
  * Tries NextJS, then Nitro, then Vite. Returns the first match.
@@ -6,6 +6,7 @@ import * as log from './log.js';
6
6
  const { oauthCredentials } = bootstrapInfo;
7
7
  for (const env of bootstrapInfo.environments){
8
8
  tokenStore.setBootstrapData(projectId, env.name, {
9
+ contentApiUrl: env.contentApiUrl,
9
10
  contentSystemId: env.contentSystemId,
10
11
  oauthClientId: oauthCredentials.oauthClientId,
11
12
  oauthClientSecret: oauthCredentials.oauthClientSecret,
@@ -1,37 +1,5 @@
1
- export interface PageCollection {
2
- /** S3 key → relative filesystem path from project root */
3
- pathMap: Record<string, string>;
4
- /** Route → S3 upload keys for that route (e.g., { "/products": ["products.html", "products.rsc"] }) */
5
- routeAssetMap: Record<string, string[]>;
6
- /** Route paths for the manifest pages array (e.g., ["/products", "/blog"]) */
7
- routes: string[];
8
- /** S3 keys to upload (e.g., ["products.html", "products.rsc", "products.meta"]) */
9
- uploadKeys: string[];
10
- }
11
- export interface AssetCollection {
12
- /** S3 key → relative filesystem path from project root */
13
- pathMap: Record<string, string>;
14
- /** Route paths for the manifest assets array (e.g., ["/favicon.ico"]) */
15
- routes: string[];
16
- /** S3 keys to upload (same as routes for assets, without leading slash) */
17
- uploadKeys: string[];
18
- }
19
- export type AdapterName = 'nextjs' | 'nitro' | 'vite';
20
- export interface LambdaBundle {
21
- /** Total size in bytes of the bundle contents before compression. */
22
- unzippedBytes: number;
23
- /** Absolute path to the built lambda.zip. */
24
- zipPath: string;
25
- }
26
- export interface DeployAdapter {
27
- collectAssets(projectPath: string, output?: string): Promise<AssetCollection>;
28
- collectPages(projectPath: string, output?: string): Promise<PageCollection>;
29
- /** SPA fallback path (e.g., "/index.html"). Undefined for SSR/SSG apps. */
30
- fallback?: string;
31
- name: AdapterName;
32
- /** Assembles and zips the server bundle. Returns the bundle, or null if no server (e.g., Vite SPA). */
33
- prepareLambdaBundle(projectPath: string, output?: string): Promise<LambdaBundle | null>;
34
- }
1
+ import type { AdapterName, DeployAdapter } from '../adapters/types.js';
2
+ export type { AdapterLogger, AdapterName, AssetCollection, DeployAdapter, LambdaBundle, PageCollection, PrepareLambdaBundleOptions, } from '../adapters/types.js';
35
3
  /**
36
4
  * Auto-detect the framework adapter based on build output.
37
5
  *
@@ -1,8 +1,13 @@
1
1
  import fs from 'fs/promises';
2
2
  import path from 'path';
3
- import { inspectNextjsOutput } from './deploy-output/inspectNextjsOutput.js';
4
- import { inspectNitroOutput } from './deploy-output/inspectNitroOutput.js';
5
- import { resolveOutputPath } from './deploy-output/resolveOutputPath.js';
3
+ import { inspectNextjsOutput } from '../adapters/deploy-output/inspectNextjsOutput.js';
4
+ import { inspectNitroOutput } from '../adapters/deploy-output/inspectNitroOutput.js';
5
+ import { resolveOutputPath } from '../adapters/deploy-output/resolveOutputPath.js';
6
+ import * as log from './log.js';
7
+ const adapterLogger = {
8
+ info: log.info,
9
+ warning: log.warning
10
+ };
6
11
  /**
7
12
  * Auto-detect the framework adapter based on build output.
8
13
  *
@@ -35,18 +40,20 @@ async function loadAdapter(name) {
35
40
  switch(name){
36
41
  case 'nextjs':
37
42
  {
38
- const mod = await import('./adapters/nextjs.js');
39
- return mod.nextjsAdapter;
43
+ const mod = await import('../adapters/nextjs.js');
44
+ return new mod.NextjsAdapter({
45
+ logger: adapterLogger
46
+ });
40
47
  }
41
48
  case 'nitro':
42
49
  {
43
- const mod = await import('./adapters/nitro.js');
44
- return mod.nitroAdapter;
50
+ const mod = await import('../adapters/nitro.js');
51
+ return new mod.NitroAdapter();
45
52
  }
46
53
  case 'vite':
47
54
  {
48
- const mod = await import('./adapters/vite.js');
49
- return mod.viteAdapter;
55
+ const mod = await import('../adapters/vite.js');
56
+ return new mod.ViteAdapter();
50
57
  }
51
58
  }
52
59
  }
@@ -14,6 +14,8 @@ export declare function getEnvVar(projectPath: string, key: string): Promise<nul
14
14
  * @returns The value if found, null otherwise
15
15
  */
16
16
  export declare function getEnvVarSync(projectPath: string, key: string): null | string;
17
+ /** Read a dotenv-parsed value without populating process.env. */
18
+ export declare function getParsedEnvVarSync(projectPath: string, key: string): null | string;
17
19
  /**
18
20
  * Add or update an environment variable in .env file
19
21
  *
@@ -22,6 +24,19 @@ export declare function getEnvVarSync(projectPath: string, key: string): null |
22
24
  * @param value - Environment variable value
23
25
  */
24
26
  export declare function addOrUpdateEnvVar(projectPath: string, key: string, value: string): Promise<void>;
27
+ /**
28
+ * Comment out an environment variable in .env file by prepending `# ` to any
29
+ * assignment line for the given key. Preserves the value so the developer can
30
+ * uncomment it later (or move it to another env file). No-op if the key is
31
+ * absent or every occurrence is already commented.
32
+ *
33
+ * @param projectPath - Path to project directory
34
+ * @param key - Environment variable name to disable
35
+ * @param annotation - Optional trailing comment appended to each disabled
36
+ * line, so the developer knows why it was disabled
37
+ * @returns true if at least one line was commented out, false otherwise
38
+ */
39
+ export declare function commentOutEnvVar(projectPath: string, key: string, annotation?: string): Promise<boolean>;
25
40
  /**
26
41
  * Remove an environment variable from .env file
27
42
  *
@@ -1,3 +1,4 @@
1
+ import { parse } from 'dotenv';
1
2
  import fs from 'fs/promises';
2
3
  import fsSync from 'node:fs';
3
4
  import path from 'path';
@@ -54,6 +55,14 @@ import path from 'path';
54
55
  return null;
55
56
  }
56
57
  }
58
+ /** Read a dotenv-parsed value without populating process.env. */ export function getParsedEnvVarSync(projectPath, key) {
59
+ try {
60
+ const contents = fsSync.readFileSync(path.join(projectPath, '.env'), 'utf-8');
61
+ return parse(contents)[key] ?? null;
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
57
66
  /**
58
67
  * Add or update an environment variable in .env file
59
68
  *
@@ -115,6 +124,44 @@ import path from 'path';
115
124
  throw new Error(`Failed to update .env file: ${error instanceof Error ? error.message : 'Unknown error'}`);
116
125
  }
117
126
  }
127
+ /**
128
+ * Comment out an environment variable in .env file by prepending `# ` to any
129
+ * assignment line for the given key. Preserves the value so the developer can
130
+ * uncomment it later (or move it to another env file). No-op if the key is
131
+ * absent or every occurrence is already commented.
132
+ *
133
+ * @param projectPath - Path to project directory
134
+ * @param key - Environment variable name to disable
135
+ * @param annotation - Optional trailing comment appended to each disabled
136
+ * line, so the developer knows why it was disabled
137
+ * @returns true if at least one line was commented out, false otherwise
138
+ */ export async function commentOutEnvVar(projectPath, key, annotation) {
139
+ const envPath = path.join(projectPath, '.env');
140
+ try {
141
+ const contents = await fs.readFile(envPath, 'utf-8');
142
+ const lines = contents.split(/\r?\n/);
143
+ let changed = false;
144
+ const updated = lines.map((line)=>{
145
+ if (!line.includes('=') || line.trim().startsWith('#')) {
146
+ return line;
147
+ }
148
+ const equalsIndex = line.indexOf('=');
149
+ const lineKey = line.substring(0, equalsIndex).trim();
150
+ if (lineKey !== key) {
151
+ return line;
152
+ }
153
+ changed = true;
154
+ const suffix = annotation ? ` # ${annotation}` : '';
155
+ return `# ${line}${suffix}`;
156
+ });
157
+ if (changed) {
158
+ await fs.writeFile(envPath, updated.join('\n'), 'utf-8');
159
+ }
160
+ return changed;
161
+ } catch {
162
+ return false;
163
+ }
164
+ }
118
165
  /**
119
166
  * Remove an environment variable from .env file
120
167
  *
@@ -1,6 +1,8 @@
1
1
  import fs from 'fs/promises';
2
2
  import path from 'path';
3
3
  import { IndentationText, Node, Project, SyntaxKind } from 'ts-morph';
4
+ import { addFigmaImageLoaderConfig } from './next-image-loader-config.js';
5
+ import { writeFigmaImageLoaderFile } from './next-image-loader-file.js';
4
6
  import { ensurePnpmWorkspace } from './pnpm-builds.js';
5
7
  const RUN_SH_CONTENT = `#!/bin/bash -x
6
8
 
@@ -18,8 +20,9 @@ NODE_ENV=production exec node server.js
18
20
  const runShPath = path.join(projectPath, 'run.sh');
19
21
  await fs.writeFile(runShPath, RUN_SH_CONTENT, 'utf-8');
20
22
  await fs.chmod(runShPath, 0o755);
21
- // 2. Modify next config to add standalone output
23
+ // 2. Add Next.js-specific configuration.
22
24
  await addNextConfigProperties(projectPath);
25
+ await writeFigmaImageLoaderFile(projectPath);
23
26
  // 3. Add lambda:buildzip script to package.json
24
27
  await addLambdaBuildScript(projectPath, packageManager);
25
28
  // 4. Write pnpm-workspace.yaml (hoisted linker + build approvals)
@@ -48,6 +51,7 @@ NODE_ENV=production exec node server.js
48
51
  /**
49
52
  * Add required Next.js config properties using ts-morph AST parsing
50
53
  * - output: 'standalone' (for Lambda deployment)
54
+ * - images.loader: 'custom' and images.loaderFile for Payload media
51
55
  */ async function addNextConfigProperties(projectPath) {
52
56
  const nextConfigPath = await findNextConfigPath(projectPath);
53
57
  const project = new Project({
@@ -65,15 +69,16 @@ NODE_ENV=production exec node server.js
65
69
  if (!configObject) {
66
70
  throw new Error(`Could not find Next.js config object in ${path.basename(nextConfigPath)}. ` + `Expected either 'export default { ... }' or 'export default wrapper(configVar, ...)'`);
67
71
  }
68
- const hasOutput = configObject.getProperty('output') !== undefined;
69
- if (hasOutput) {
70
- return;
72
+ if (configObject.getProperty('output') === undefined) {
73
+ configObject.addPropertyAssignment({
74
+ name: 'output',
75
+ initializer: "'standalone'"
76
+ });
77
+ }
78
+ addFigmaImageLoaderConfig(configObject);
79
+ if (!sourceFile.isSaved()) {
80
+ await sourceFile.save();
71
81
  }
72
- configObject.addPropertyAssignment({
73
- name: 'output',
74
- initializer: "'standalone'"
75
- });
76
- await sourceFile.save();
77
82
  }
78
83
  /**
79
84
  * Find the config object literal from either:
@@ -1,4 +1,3 @@
1
- import { createRequire } from 'node:module';
2
1
  import path from 'node:path';
3
2
  import { pathToFileURL } from 'node:url';
4
3
  import { findPayloadConfig } from './payload-config-finder.js';
@@ -16,11 +15,7 @@ import { findPayloadConfig } from './payload-config-finder.js';
16
15
  const absoluteConfigPath = path.resolve(projectPath, configPath);
17
16
  const { loadEnv } = await import('payload/node');
18
17
  loadEnv();
19
- const requireFromProject = createRequire(path.join(projectPath, 'package.json'));
20
- const payloadEntryPath = requireFromProject.resolve('payload');
21
- const requireFromPayload = createRequire(payloadEntryPath);
22
- const tsxApiPath = requireFromPayload.resolve('tsx/esm/api');
23
- const { tsImport } = await import(pathToFileURL(tsxApiPath).href);
18
+ const tsImport = (await import('tsx/esm/api')).tsImport;
24
19
  const parentURL = pathToFileURL(`${projectPath}${path.sep}`).href;
25
20
  const imported = await tsImport(absoluteConfigPath, parentURL);
26
21
  return await (imported.default ?? imported);
@@ -0,0 +1,2 @@
1
+ import type { ObjectLiteralExpression } from 'ts-morph';
2
+ export declare function addFigmaImageLoaderConfig(configObject: ObjectLiteralExpression): void;