@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,174 @@
1
+ import { deserialize, serialize } from 'node:v8';
2
+ export function createNextjsCacheHandler(deserializeValue, serializeValue) {
3
+ const MAX_CACHE_BYTES = 8 * 1024 * 1024;
4
+ // Approximate Map entry and metadata overhead; actual heap use can differ.
5
+ const ESTIMATED_ENTRY_OVERHEAD_BYTES = 64;
6
+ const cache = new Map();
7
+ let cacheBytes = 0;
8
+ // Tag invalidation advances this counter to reject writes from earlier requests.
9
+ let tagVersion = 0;
10
+ /**
11
+ * A process-local, fresh-only Next.js cacheHandler. The CDN owns stale serving.
12
+ * No filesystem access: Lambda's code directory is read-only. Each cold process
13
+ * starts empty; Gatekeeper serves the separately uploaded static assets.
14
+ */ class NextjsCacheHandler {
15
+ constructor(){
16
+ this.tagVersion = tagVersion;
17
+ }
18
+ async get(key, context = {}) {
19
+ const cacheKey = getCacheKey(key, context.kind === 'FETCH');
20
+ const entry = cache.get(cacheKey);
21
+ if (!entry) {
22
+ observe('miss', context.kind);
23
+ return null;
24
+ }
25
+ const effectiveTTL = context.kind === 'FETCH' && context.revalidate !== undefined ? Math.min(entry.seconds, lifetime(context.revalidate)) : entry.seconds;
26
+ const ageMs = Math.max(0, Date.now() - entry.lastModified);
27
+ if (ageMs >= effectiveTTL * 1000) {
28
+ if (ageMs >= entry.seconds * 1000) {
29
+ remove(cacheKey);
30
+ }
31
+ observe('expired', context.kind);
32
+ return null;
33
+ }
34
+ // Clone cached buffers/maps so a caller cannot mutate the stored value.
35
+ // V8 can return Buffer views into its input, so copy the serialized bytes.
36
+ const value = deserializeValue(Buffer.from(entry.data));
37
+ if (value && [
38
+ 'APP_PAGE',
39
+ 'APP_ROUTE',
40
+ 'PAGES'
41
+ ].includes(value.kind)) {
42
+ value.headers = withoutAge(value.headers);
43
+ value.headers.Age = String(Math.floor(ageMs / 1000));
44
+ }
45
+ cache.delete(cacheKey);
46
+ cache.set(cacheKey, entry);
47
+ observe('hit', context.kind);
48
+ return {
49
+ value,
50
+ lastModified: entry.lastModified
51
+ };
52
+ }
53
+ async set(key, value, context = {}) {
54
+ // A render that overlaps invalidation must not restore an old value.
55
+ if (this.tagVersion !== tagVersion) {
56
+ return;
57
+ }
58
+ const cacheKey = getCacheKey(key, context.fetchCache);
59
+ remove(cacheKey);
60
+ const seconds = lifetime(context.fetchCache ? value?.revalidate : context.cacheControl?.revalidate);
61
+ if (seconds === 0) {
62
+ return;
63
+ }
64
+ let data;
65
+ try {
66
+ data = serializeValue(value);
67
+ } catch {
68
+ observe('unsupported', value?.kind);
69
+ return;
70
+ }
71
+ const size = data.byteLength + Buffer.byteLength(cacheKey) + ESTIMATED_ENTRY_OVERHEAD_BYTES;
72
+ if (size > MAX_CACHE_BYTES) {
73
+ observe('oversized', value?.kind);
74
+ return;
75
+ }
76
+ // Preserve an upstream Age, including a previous cached response that Next
77
+ // attempts to write again after an unsuccessful on-demand revalidation.
78
+ const age = responseAge(value);
79
+ if (age >= seconds) {
80
+ return;
81
+ }
82
+ while(cacheBytes + size > MAX_CACHE_BYTES){
83
+ remove(cache.keys().next().value);
84
+ }
85
+ cache.set(cacheKey, {
86
+ data,
87
+ size,
88
+ seconds,
89
+ lastModified: Date.now() - age * 1000
90
+ });
91
+ cacheBytes += size;
92
+ }
93
+ /**
94
+ * The revalidateTag function allows invalidating cached data on-demand based
95
+ * on the specified tags. For our purposes, since we are currently doing a
96
+ * local in-memory, per-process lambda cache, we can just go ahead and clear
97
+ * the cache. Eventually we will want to support doing tag invalidation at the
98
+ * CDN layer.
99
+ */ async revalidateTag(tags, _durations = {}) {
100
+ const tagsArr = Array.isArray(tags) ? tags : [
101
+ tags
102
+ ];
103
+ const hasValidTag = tagsArr.some((tag)=>typeof tag === 'string' && tag.length);
104
+ if (!hasValidTag) {
105
+ return;
106
+ }
107
+ cache.clear();
108
+ cacheBytes = 0;
109
+ tagVersion += 1;
110
+ observe('invalidated', 'local');
111
+ }
112
+ // Outstanding writes still belong to the request that started before invalidation.
113
+ resetRequestCache() {}
114
+ }
115
+ function getCacheKey(key, fetchCache) {
116
+ return `${fetchCache ? 'fetch' : 'route'}:${key}`;
117
+ }
118
+ function lifetime(revalidate) {
119
+ if (revalidate === false) {
120
+ return Infinity;
121
+ }
122
+ return Number.isSafeInteger(revalidate) && revalidate > 0 ? revalidate : 0;
123
+ }
124
+ function remove(key) {
125
+ const entry = cache.get(key);
126
+ if (entry) {
127
+ cacheBytes -= entry.size;
128
+ }
129
+ cache.delete(key);
130
+ }
131
+ function withoutAge(headers) {
132
+ return Object.fromEntries(Object.entries(headers ?? {}).filter(([name])=>name.toLowerCase() !== 'age'));
133
+ }
134
+ function responseAge(value) {
135
+ if (!value || value.kind === 'FETCH') {
136
+ return 0;
137
+ }
138
+ const age = Object.entries(value.headers ?? {}).find(([name])=>name.toLowerCase() === 'age')?.[1];
139
+ if (age === undefined) {
140
+ return 0;
141
+ }
142
+ if (typeof age !== 'number' && (typeof age !== 'string' || !/^\d+$/.test(age))) {
143
+ return Infinity;
144
+ }
145
+ const seconds = Number(age);
146
+ return Number.isSafeInteger(seconds) && seconds >= 0 ? seconds : Infinity;
147
+ }
148
+ function observe(result, kind) {
149
+ if (![
150
+ 'APP_PAGE',
151
+ 'APP_ROUTE',
152
+ 'PAGES',
153
+ 'local'
154
+ ].includes(kind)) {
155
+ return;
156
+ }
157
+ // Bounded fields only: never log cache keys, URLs, values, or tags.
158
+ console.info(JSON.stringify({
159
+ event: 'figma_nextjs_cache',
160
+ result,
161
+ kind
162
+ }));
163
+ }
164
+ return NextjsCacheHandler;
165
+ }
166
+ export function createNextjsCacheHandlerSource() {
167
+ return [
168
+ "import { deserialize, serialize } from 'node:v8'",
169
+ `const createNextjsCacheHandler = ${createNextjsCacheHandler.toString()}`,
170
+ 'export default createNextjsCacheHandler(deserialize, serialize)',
171
+ ''
172
+ ].join('\n');
173
+ }
174
+ export default createNextjsCacheHandler(deserialize, serialize);
@@ -0,0 +1,12 @@
1
+ import type { AdapterLogger, AssetCollection, DeployAdapter, LambdaBundle, PageCollection, PrepareLambdaBundleOptions } from './types.js';
2
+ export declare class NextjsAdapter implements DeployAdapter {
3
+ private readonly logger?;
4
+ name: "nextjs";
5
+ constructor(options?: {
6
+ logger?: AdapterLogger;
7
+ });
8
+ collectAssets(projectPath: string, output?: string): Promise<AssetCollection>;
9
+ collectPages(projectPath: string, output?: string): Promise<PageCollection>;
10
+ prepareLambdaBundle(projectPath: string, output?: string, options?: PrepareLambdaBundleOptions): Promise<LambdaBundle>;
11
+ }
12
+ export declare const nextjsAdapter: NextjsAdapter;
@@ -0,0 +1,67 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import { collectSSGAssets, collectStaticAssets, collectStaticMetadataAssets } from './asset-collection.js';
4
+ import { buildLambdaZip } from './build-lambda-zip.js';
5
+ import { resolveOutputPath } from './deploy-output/resolveOutputPath.js';
6
+ import { collectFilesRecursive } from './fs-utils.js';
7
+ import { isPublishableAsset } from './secret-files.js';
8
+ export class NextjsAdapter {
9
+ logger;
10
+ name = 'nextjs';
11
+ constructor(options = {}){
12
+ this.logger = options.logger;
13
+ }
14
+ async collectAssets(projectPath, output) {
15
+ // Bundle assets: .next/static/ → _next/static/
16
+ const staticAssets = (await collectStaticAssets(projectPath, output, this.logger)).filter(isPublishableAsset);
17
+ const outputPath = resolveOutputPath(projectPath, 'nextjs', output);
18
+ // A normal Next build keeps public/ beside .next. A prebuilt artifact can
19
+ // instead include it in the supplied output directory, which is necessary
20
+ // when the artifact is isolated from the source project (for example Bazel).
21
+ const artifactPublicDir = path.join(outputPath, 'public');
22
+ const publicDir = await fs.stat(artifactPublicDir).then((stat)=>stat.isDirectory()).catch(()=>false) ? artifactPublicDir : path.join(projectPath, 'public');
23
+ let publicAssets = [];
24
+ try {
25
+ await fs.stat(publicDir);
26
+ publicAssets = (await collectFilesRecursive(publicDir, publicDir)).filter(isPublishableAsset);
27
+ } catch {
28
+ // No public directory
29
+ }
30
+ const metadataAssets = await collectStaticMetadataAssets(projectPath, output);
31
+ const pathMap = {};
32
+ for (const key of staticAssets){
33
+ pathMap[key] = path.relative(projectPath, path.join(outputPath, key.replace(/^_next\//, '')));
34
+ }
35
+ for (const key of publicAssets){
36
+ pathMap[key] = path.relative(projectPath, path.join(publicDir, key));
37
+ }
38
+ for (const key of metadataAssets.keys.filter(isPublishableAsset)){
39
+ pathMap[key] = metadataAssets.pathMap[key];
40
+ }
41
+ const uploadKeys = Object.keys(pathMap);
42
+ return {
43
+ pathMap,
44
+ routes: uploadKeys.map((key)=>`/${key}`),
45
+ uploadKeys
46
+ };
47
+ }
48
+ async collectPages(projectPath, output) {
49
+ const ssg = await collectSSGAssets(projectPath, output, this.logger);
50
+ // collectSSGAssets records each key's manifest route while scanning the
51
+ // output, preserving the existing mapping for HTML/RSC/meta files while
52
+ // supporting segment keys whose nested names do not encode the page route.
53
+ return {
54
+ pathMap: ssg.pathMap,
55
+ routeAssetMap: ssg.routeAssetMap,
56
+ routes: Object.keys(ssg.routeAssetMap),
57
+ uploadKeys: ssg.keys
58
+ };
59
+ }
60
+ async prepareLambdaBundle(projectPath, output, options) {
61
+ return buildLambdaZip(projectPath, output, {
62
+ ...options,
63
+ logger: this.logger
64
+ });
65
+ }
66
+ }
67
+ export const nextjsAdapter = new NextjsAdapter();
@@ -1,8 +1,8 @@
1
- import type { AssetCollection, DeployAdapter, LambdaBundle, PageCollection } from '../deploy-adapter.js';
1
+ import type { AssetCollection, DeployAdapter, LambdaBundle, PageCollection, PrepareLambdaBundleOptions } from './types.js';
2
2
  export declare class NitroAdapter implements DeployAdapter {
3
3
  name: "nitro";
4
4
  collectAssets(projectPath: string, output?: string): Promise<AssetCollection>;
5
5
  collectPages(projectPath: string, output?: string): Promise<PageCollection>;
6
- prepareLambdaBundle(projectPath: string, output?: string): Promise<LambdaBundle>;
6
+ prepareLambdaBundle(projectPath: string, output?: string, options?: PrepareLambdaBundleOptions): Promise<LambdaBundle>;
7
7
  }
8
8
  export declare const nitroAdapter: NitroAdapter;
@@ -1,10 +1,11 @@
1
1
  import archiver from 'archiver';
2
- import { createWriteStream, statSync } from 'fs';
2
+ import { createWriteStream } from 'fs';
3
3
  import fs from 'fs/promises';
4
4
  import path from 'path';
5
- import { resolveNitroOutputLayout } from '../deploy-output/resolveNitroOutputLayout.js';
6
- import { resolveOutputPath } from '../deploy-output/resolveOutputPath.js';
7
- import { collectFilesRecursive, getDirectorySize } from '../fs-utils.js';
5
+ import { resolveNitroOutputLayout } from './deploy-output/resolveNitroOutputLayout.js';
6
+ import { resolveOutputPath } from './deploy-output/resolveOutputPath.js';
7
+ import { collectFilesRecursive, EscapingSymlinkError, walkBundleFiles } from './fs-utils.js';
8
+ import { isBundlableFile, isPublishableAsset } from './secret-files.js';
8
9
  /** Framework asset directories that are not pre-rendered pages. */ const NON_PAGE_DIRS = new Set([
9
10
  '_build',
10
11
  '_nuxt',
@@ -15,7 +16,7 @@ export class NitroAdapter {
15
16
  async collectAssets(projectPath, output) {
16
17
  const { publicPath } = await getLayout(projectPath, output);
17
18
  const pageKeys = new Set((await scanForPages(publicPath, publicPath)).map(toPageUploadKey));
18
- const assets = (await collectFilesRecursive(publicPath, publicPath)).filter((file)=>!pageKeys.has(file));
19
+ const assets = (await collectFilesRecursive(publicPath, publicPath)).filter((file)=>!pageKeys.has(file) && isPublishableAsset(file));
19
20
  const pathMap = Object.fromEntries(assets.map((file)=>[
20
21
  file,
21
22
  path.relative(projectPath, path.join(publicPath, file))
@@ -28,7 +29,7 @@ export class NitroAdapter {
28
29
  }
29
30
  async collectPages(projectPath, output) {
30
31
  const { publicPath } = await getLayout(projectPath, output);
31
- const pages = await scanForPages(publicPath, publicPath);
32
+ const pages = (await scanForPages(publicPath, publicPath)).filter((page)=>isPublishableAsset(toPageUploadKey(page)));
32
33
  const routes = pages.map((p)=>p === 'index' ? '/' : `/${p}`);
33
34
  const uploadKeys = pages.map(toPageUploadKey);
34
35
  const pathMap = {};
@@ -46,7 +47,7 @@ export class NitroAdapter {
46
47
  uploadKeys
47
48
  };
48
49
  }
49
- async prepareLambdaBundle(projectPath, output) {
50
+ async prepareLambdaBundle(projectPath, output, options = {}) {
50
51
  const layout = await getLayout(projectPath, output);
51
52
  try {
52
53
  const stat = await fs.stat(layout.serverEntryPath);
@@ -57,31 +58,46 @@ export class NitroAdapter {
57
58
  throw new Error(`Nitro server build not found at ${layout.outputPath}`);
58
59
  }
59
60
  const serverDir = path.dirname(layout.serverEntryPath);
60
- const serverPrefix = path.relative(layout.outputPath, serverDir).split(path.sep).join('/');
61
- const publicPrefix = path.relative(layout.outputPath, layout.publicPath).split(path.sep).join('/');
61
+ const serverPrefix = zipPrefix(path.relative(layout.outputPath, serverDir).split(path.sep).join('/'));
62
+ const publicPrefix = zipPrefix(path.relative(layout.outputPath, layout.publicPath).split(path.sep).join('/'));
62
63
  const serverEntry = path.relative(layout.outputPath, layout.serverEntryPath).split(path.sep).join('/');
63
64
  const runShPath = path.join(layout.outputPath, 'run.sh');
64
65
  await fs.writeFile(runShPath, createRunScript(serverEntry), {
65
66
  mode: 0o755
66
67
  });
67
- const zipPath = path.join(projectPath, 'lambda.zip');
68
+ const artifactDir = options.artifactDir ?? projectPath;
69
+ await fs.mkdir(artifactDir, {
70
+ recursive: true
71
+ });
72
+ const zipPath = path.join(artifactDir, 'lambda.zip');
68
73
  try {
74
+ const runShStat = await fs.stat(runShPath);
75
+ const [allServerFiles, publicFiles] = await Promise.all([
76
+ walkBundleFiles(serverDir),
77
+ walkPublicBundleFiles(layout.publicPath)
78
+ ]);
79
+ const bundlableServerFiles = allServerFiles.filter((file)=>isBundlableFile(file.relativePath));
80
+ const unzippedBytes = bundlableServerFiles.reduce((total, file)=>total + file.size, 0) + publicFiles.reduce((total, file)=>total + file.size, 0) + runShStat.size;
69
81
  await createZip(zipPath, [
70
82
  {
71
- prefix: `${serverPrefix}/`,
72
- source: serverDir
83
+ files: bundlableServerFiles,
84
+ prefix: serverPrefix
73
85
  },
74
86
  {
75
- prefix: `${publicPrefix}/`,
76
- source: layout.publicPath
87
+ files: publicFiles,
88
+ prefix: publicPrefix
77
89
  },
78
90
  {
79
- prefix: '',
80
- source: runShPath
91
+ files: [
92
+ {
93
+ relativePath: 'run.sh',
94
+ size: runShStat.size,
95
+ sourcePath: runShPath
96
+ }
97
+ ],
98
+ prefix: ''
81
99
  }
82
100
  ]);
83
- const runShStat = await fs.stat(runShPath);
84
- const unzippedBytes = await getDirectorySize(serverDir) + await getDirectorySize(layout.publicPath) + runShStat.size;
85
101
  return {
86
102
  unzippedBytes,
87
103
  zipPath
@@ -135,9 +151,25 @@ NODE_ENV=production exec node '${escapedEntry}'
135
151
  }
136
152
  return pages;
137
153
  }
154
+ function zipPrefix(relativeDir) {
155
+ return relativeDir ? `${relativeDir}/` : '';
156
+ }
138
157
  function toPageUploadKey(page) {
139
158
  return page === 'index' ? 'index.html' : `${page}/index.html`;
140
159
  }
160
+ async function walkPublicBundleFiles(publicPath) {
161
+ try {
162
+ // The Nitro server serves this tree statically, so secrets copied into the
163
+ // public directory must not reach the Lambda bundle either.
164
+ const files = await walkBundleFiles(publicPath);
165
+ return files.filter((file)=>isPublishableAsset(file.relativePath));
166
+ } catch (error) {
167
+ if (error instanceof EscapingSymlinkError) {
168
+ throw error;
169
+ }
170
+ return [];
171
+ }
172
+ }
141
173
  async function createZip(zipPath, entries) {
142
174
  return new Promise((resolve, reject)=>{
143
175
  const output = createWriteStream(zipPath);
@@ -150,17 +182,10 @@ async function createZip(zipPath, entries) {
150
182
  archive.on('error', (err)=>reject(err));
151
183
  archive.pipe(output);
152
184
  for (const entry of entries){
153
- try {
154
- const stat = statSync(entry.source);
155
- if (stat.isDirectory()) {
156
- archive.directory(entry.source, entry.prefix.replace(/\/$/, '') || false);
157
- } else {
158
- archive.file(entry.source, {
159
- name: entry.prefix + path.basename(entry.source)
160
- });
161
- }
162
- } catch {
163
- // Skip missing entries
185
+ for (const file of entry.files){
186
+ archive.file(file.sourcePath, {
187
+ name: entry.prefix + file.relativePath
188
+ });
164
189
  }
165
190
  }
166
191
  void archive.finalize();
@@ -0,0 +1,25 @@
1
+ /**
2
+ * True when a forward-slash asset key holds no secret or private-history path
3
+ * segment.
4
+ *
5
+ * A deploy can point `--output` at a directory that also holds those files (a
6
+ * buildless static root, or a framework output folder that copied them in).
7
+ * Every collected asset becomes a publicly reachable route, so `node_modules`
8
+ * is excluded here too.
9
+ */
10
+ export declare function isPublishableAsset(key: string): boolean;
11
+ /**
12
+ * True when a forward-slash bundle path belongs in a Lambda zip.
13
+ *
14
+ * A server bundle needs its `node_modules`, but never the project's `.env`
15
+ * files or credentials: a deployed function reads its configuration from
16
+ * deploy environment variables, and a packed secret only widens the blast
17
+ * radius of any later path that serves bundle files. `.env.production` is the
18
+ * deliberate exception, an escape hatch for configuration too large for the
19
+ * Lambda environment-variable limit.
20
+ *
21
+ * Paths inside `node_modules` are kept as-is. A dependency's own dotfiles are
22
+ * not the developer's secrets, and removing files a package may read at
23
+ * runtime would break the bundle.
24
+ */
25
+ export declare function isBundlableFile(relativePath: string): boolean;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Local secrets and private history that must never leave the developer's
3
+ * machine: environment files, git history, and credential files.
4
+ */ const SECRET_NAMES = new Set([
5
+ '.git',
6
+ '.netrc',
7
+ '.npmrc',
8
+ '.ssh'
9
+ ]);
10
+ /** Installed dependencies: private for static hosting, required by a server bundle. */ const DEPENDENCY_DIR = 'node_modules';
11
+ /**
12
+ * The one environment file a Lambda zip may carry. AWS caps a function's
13
+ * environment variables at 4 KB total, so a project with more configuration
14
+ * than that has no way to pass it except inside the bundle. It is still never
15
+ * publishable: `isPublishableAsset` rejects it like any other `.env` file.
16
+ */ const BUNDLABLE_ENV_FILE = '.env.production';
17
+ /**
18
+ * True when a forward-slash asset key holds no secret or private-history path
19
+ * segment.
20
+ *
21
+ * A deploy can point `--output` at a directory that also holds those files (a
22
+ * buildless static root, or a framework output folder that copied them in).
23
+ * Every collected asset becomes a publicly reachable route, so `node_modules`
24
+ * is excluded here too.
25
+ */ export function isPublishableAsset(key) {
26
+ return key.split('/').every((segment)=>segment !== DEPENDENCY_DIR && !isSecretName(segment));
27
+ }
28
+ /**
29
+ * True when a forward-slash bundle path belongs in a Lambda zip.
30
+ *
31
+ * A server bundle needs its `node_modules`, but never the project's `.env`
32
+ * files or credentials: a deployed function reads its configuration from
33
+ * deploy environment variables, and a packed secret only widens the blast
34
+ * radius of any later path that serves bundle files. `.env.production` is the
35
+ * deliberate exception, an escape hatch for configuration too large for the
36
+ * Lambda environment-variable limit.
37
+ *
38
+ * Paths inside `node_modules` are kept as-is. A dependency's own dotfiles are
39
+ * not the developer's secrets, and removing files a package may read at
40
+ * runtime would break the bundle.
41
+ */ export function isBundlableFile(relativePath) {
42
+ const segments = relativePath.split('/');
43
+ if (segments.includes(DEPENDENCY_DIR)) {
44
+ return true;
45
+ }
46
+ return segments.every((segment)=>segment === BUNDLABLE_ENV_FILE || !isSecretName(segment));
47
+ }
48
+ function isSecretName(segment) {
49
+ return SECRET_NAMES.has(segment) || segment.startsWith('.env');
50
+ }
@@ -0,0 +1,42 @@
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 AdapterLogger {
21
+ info(message: string): void;
22
+ warning(message: string): void;
23
+ }
24
+ export interface LambdaBundle {
25
+ /** Total size in bytes of the bundle contents before compression. */
26
+ unzippedBytes: number;
27
+ /** Absolute path to the built lambda.zip. */
28
+ zipPath: string;
29
+ }
30
+ export interface PrepareLambdaBundleOptions {
31
+ /** Directory where lambda.zip is written. Defaults to the project root. */
32
+ artifactDir?: string;
33
+ }
34
+ export interface DeployAdapter {
35
+ collectAssets(projectPath: string, output?: string): Promise<AssetCollection>;
36
+ collectPages(projectPath: string, output?: string): Promise<PageCollection>;
37
+ /** SPA fallback path (e.g., "/index.html"). Undefined for SSR/SSG apps. */
38
+ fallback?: string;
39
+ name: AdapterName;
40
+ /** Assembles and zips the server bundle. Returns null if the adapter has no server. */
41
+ prepareLambdaBundle(projectPath: string, output?: string, options?: PrepareLambdaBundleOptions): Promise<LambdaBundle | null>;
42
+ }
@@ -0,0 +1 @@
1
+ export { };
@@ -1,4 +1,4 @@
1
- import type { AssetCollection, DeployAdapter, LambdaBundle, PageCollection } from '../deploy-adapter.js';
1
+ import type { AssetCollection, DeployAdapter, LambdaBundle, PageCollection } from './types.js';
2
2
  export declare class ViteAdapter implements DeployAdapter {
3
3
  fallback: string;
4
4
  name: "vite";
@@ -1,12 +1,13 @@
1
1
  import path from 'path';
2
- import { resolveOutputPath } from '../deploy-output/resolveOutputPath.js';
3
- import { collectFilesRecursive } from '../fs-utils.js';
2
+ import { resolveOutputPath } from './deploy-output/resolveOutputPath.js';
3
+ import { collectFilesRecursive } from './fs-utils.js';
4
+ import { isPublishableAsset } from './secret-files.js';
4
5
  export class ViteAdapter {
5
6
  fallback = '/index.html';
6
7
  name = 'vite';
7
8
  async collectAssets(projectPath, output) {
8
9
  const outputPath = resolveOutputPath(projectPath, 'vite', output);
9
- const files = await collectFilesRecursive(outputPath, outputPath);
10
+ const files = (await collectFilesRecursive(outputPath, outputPath)).filter(isPublishableAsset);
10
11
  const pathMap = Object.fromEntries(files.map((file)=>[
11
12
  file,
12
13
  path.relative(projectPath, path.join(outputPath, file))
@@ -132,6 +132,8 @@ export declare function performDeployment(credential: AuthCredential, tenantId:
132
132
  * A single environment returned by the bootstrap endpoint
133
133
  */
134
134
  export type BootstrapEnvironment = {
135
+ /** Regional Content API base URL. Absent when the server predates the field. */
136
+ contentApiUrl?: string;
135
137
  contentSystemId: string;
136
138
  name: string;
137
139
  tenantInstanceId: string;
@@ -155,6 +157,15 @@ export type BootstrapInfo = {
155
157
  * @param environmentName - Optional environment name filter
156
158
  */
157
159
  export declare function getBootstrapInfo(credential: AuthCredential, cmsResourceId: string, environmentName?: string): Promise<BootstrapInfo>;
160
+ /**
161
+ * Fetch the decrypted value of a tenant environment variable by name.
162
+ * Maps to: GET /v1/environments/:tenant_instance_id/environment_variables/by_name?name=...
163
+ *
164
+ * Only variables with `user_visibility: name_and_value` are returned; the
165
+ * endpoint answers 404 otherwise. Used by init and buildFigmaConfig to
166
+ * resolve PAYLOAD_SECRET on developer machines.
167
+ */
168
+ export declare function getEnvironmentVariableByName(credential: AuthCredential, tenantInstanceId: string, name: string): Promise<string>;
158
169
  /**
159
170
  * Resolve a CMS Resource ID from a legacy dataset (content system) ID.
160
171
  * Maps to: GET /v1/cms/dataset/:datasetId
@@ -278,6 +278,7 @@ import { controlPlaneFetch } from './control-plane-fetch.js';
278
278
  return {
279
279
  environments: data.meta.environments.map((env)=>({
280
280
  name: env.name,
281
+ contentApiUrl: env.content_api_url,
281
282
  contentSystemId: env.content_system_id,
282
283
  tenantInstanceId: env.tenant_instance_id
283
284
  })),
@@ -287,6 +288,31 @@ import { controlPlaneFetch } from './control-plane-fetch.js';
287
288
  }
288
289
  };
289
290
  }
291
+ /**
292
+ * Fetch the decrypted value of a tenant environment variable by name.
293
+ * Maps to: GET /v1/environments/:tenant_instance_id/environment_variables/by_name?name=...
294
+ *
295
+ * Only variables with `user_visibility: name_and_value` are returned; the
296
+ * endpoint answers 404 otherwise. Used by init and buildFigmaConfig to
297
+ * resolve PAYLOAD_SECRET on developer machines.
298
+ */ export async function getEnvironmentVariableByName(credential, tenantInstanceId, name) {
299
+ const shouldMock = process.env.FIGMA_MOCK_CONTROL_PLANE === 'true';
300
+ if (shouldMock) {
301
+ log.debug('Using mock Control Plane API for getEnvironmentVariableByName (FIGMA_MOCK_CONTROL_PLANE === "true")');
302
+ return `mock-${name.toLowerCase()}-${tenantInstanceId}`;
303
+ }
304
+ const url = `${getControlPlaneBaseUrl()}/v1/environments/${encodeURIComponent(tenantInstanceId)}` + `/environment_variables/by_name?name=${encodeURIComponent(name)}`;
305
+ log.debug(`Calling getEnvironmentVariableByName API at ${url}`);
306
+ const response = await controlPlaneFetch({
307
+ context: `get environment variable ${name}`,
308
+ options: {
309
+ headers: getAuthHeaders(credential)
310
+ },
311
+ url
312
+ });
313
+ const data = await response.json();
314
+ return data.meta.value;
315
+ }
290
316
  /**
291
317
  * Resolve a CMS Resource ID from a legacy dataset (content system) ID.
292
318
  * Maps to: GET /v1/cms/dataset/:datasetId
@@ -4,6 +4,7 @@ import { buildAuthorizationUrl } from './browser.js';
4
4
  import { parsePastedCode } from './paste-code.js';
5
5
  import { generatePKCEPair } from './pkce.js';
6
6
  import { exchangeCodeForTokens } from './refresh.js';
7
+ import { hasRequestedScopes } from './requested-scopes.js';
7
8
  const HEADLESS_OAUTH_SESSION_TTL_MS = 10 * 60 * 1000;
8
9
  export class HeadlessOAuthFlowError extends Error {
9
10
  constructor(message){
@@ -58,6 +59,9 @@ export class HeadlessOAuthFlowError extends Error {
58
59
  }
59
60
  const code = parsePastedCode(callbackUrl, session.state);
60
61
  const tokens = await exchangeCodeForTokens(code, session.codeVerifier, session.redirectUri, session.clientId);
62
+ if (!hasRequestedScopes(tokens.scopes, getOAuthConfig().scopes)) {
63
+ throw new HeadlessOAuthFlowError('Authorization did not grant all requested Cloud scopes');
64
+ }
61
65
  tokenStore.setTokens(tokens);
62
66
  return {
63
67
  tokens,