@payloadcms/figma 0.0.1-alpha.2 → 0.0.1-alpha.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/control-plane.d.ts +1 -1
- package/dist/api/control-plane.d.ts.map +1 -1
- package/dist/api/control-plane.js +9 -5
- package/dist/api/control-plane.js.map +1 -1
- package/dist/api/figma-api.d.ts.map +1 -1
- package/dist/api/figma-api.js +33 -10
- package/dist/api/figma-api.js.map +1 -1
- package/dist/auth/crypto-utils.d.ts.map +1 -1
- package/dist/auth/crypto-utils.js +5 -5
- package/dist/auth/crypto-utils.js.map +1 -1
- package/dist/auth/oauth-flow.js +3 -3
- package/dist/auth/oauth-flow.js.map +1 -1
- package/dist/auth/project-token.d.ts.map +1 -1
- package/dist/auth/project-token.js +9 -4
- package/dist/auth/project-token.js.map +1 -1
- package/dist/auth/token-store.d.ts +10 -0
- package/dist/auth/token-store.d.ts.map +1 -1
- package/dist/auth/token-store.js +20 -0
- package/dist/auth/token-store.js.map +1 -1
- package/dist/cli.js +1 -0
- package/dist/cli.js.map +1 -1
- package/dist/commands/deploy.d.ts +2 -0
- package/dist/commands/deploy.d.ts.map +1 -1
- package/dist/commands/deploy.js +16 -34
- package/dist/commands/deploy.js.map +1 -1
- package/dist/commands/init.d.ts +1 -5
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +35 -86
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/list-tokens.js +2 -2
- package/dist/commands/list-tokens.js.map +1 -1
- package/dist/commands/login.d.ts +8 -1
- package/dist/commands/login.d.ts.map +1 -1
- package/dist/commands/login.js +12 -6
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/logout.js +2 -2
- package/dist/commands/logout.js.map +1 -1
- package/dist/config/oauth.d.ts.map +1 -1
- package/dist/config/oauth.js +3 -3
- package/dist/config/oauth.js.map +1 -1
- package/dist/db-adapter.d.ts +17 -0
- package/dist/db-adapter.d.ts.map +1 -0
- package/dist/db-adapter.js +760 -0
- package/dist/db-adapter.js.map +1 -0
- package/dist/endpoints/health.d.ts +3 -0
- package/dist/endpoints/health.d.ts.map +1 -0
- package/dist/endpoints/health.js +11 -0
- package/dist/endpoints/health.js.map +1 -0
- package/dist/exports/client.d.ts +3 -0
- package/dist/exports/client.d.ts.map +1 -0
- package/dist/exports/client.js +4 -0
- package/dist/exports/client.js.map +1 -0
- package/dist/oauth/components/LoginButton/index.d.ts.map +1 -1
- package/dist/oauth/components/LoginButton/index.js +50 -6
- package/dist/oauth/components/LoginButton/index.js.map +1 -1
- package/dist/oauth/components/LoginButton/index.scss +50 -3
- package/dist/oauth/components/LogoutButton/index.d.ts.map +1 -1
- package/dist/oauth/components/LogoutButton/index.js +0 -1
- package/dist/oauth/components/LogoutButton/index.js.map +1 -1
- package/dist/oauth/endpoints/getLoginEndpoint.d.ts.map +1 -1
- package/dist/oauth/endpoints/getLoginEndpoint.js +1 -1
- package/dist/oauth/endpoints/getLoginEndpoint.js.map +1 -1
- package/dist/oauth/index.d.ts.map +1 -1
- package/dist/oauth/index.js +30 -6
- package/dist/oauth/index.js.map +1 -1
- package/dist/oauth/strategy/index.d.ts.map +1 -1
- package/dist/oauth/strategy/index.js.map +1 -1
- package/dist/oauth/types.d.ts +1 -1
- package/dist/oauth/types.d.ts.map +1 -1
- package/dist/oauth/types.js.map +1 -1
- package/dist/oauth/utilities/createCookieOptions.d.ts.map +1 -1
- package/dist/oauth/utilities/createCookieOptions.js.map +1 -1
- package/dist/oauth/utilities/refreshTokens.d.ts.map +1 -1
- package/dist/oauth/utilities/refreshTokens.js +1 -1
- package/dist/oauth/utilities/refreshTokens.js.map +1 -1
- package/dist/plugin/build-config.d.ts +20 -6
- package/dist/plugin/build-config.d.ts.map +1 -1
- package/dist/plugin/build-config.js +33 -14
- package/dist/plugin/build-config.js.map +1 -1
- package/dist/utils/env-management.d.ts +4 -11
- package/dist/utils/env-management.d.ts.map +1 -1
- package/dist/utils/env-management.js +46 -79
- package/dist/utils/env-management.js.map +1 -1
- package/dist/utils/messages.d.ts.map +1 -1
- package/dist/utils/messages.js +5 -7
- package/dist/utils/messages.js.map +1 -1
- package/dist/utils/payload-config-ast.d.ts +2 -3
- package/dist/utils/payload-config-ast.d.ts.map +1 -1
- package/dist/utils/payload-config-ast.js +34 -18
- package/dist/utils/payload-config-ast.js.map +1 -1
- package/dist/utils/project.d.ts.map +1 -1
- package/dist/utils/project.js +1 -3
- package/dist/utils/project.js.map +1 -1
- package/dist/utils/s3-upload.d.ts +0 -1
- package/dist/utils/s3-upload.d.ts.map +1 -1
- package/dist/utils/s3-upload.js +10 -3
- package/dist/utils/s3-upload.js.map +1 -1
- package/package.json +10 -5
|
@@ -1,97 +1,64 @@
|
|
|
1
|
-
import { randomBytes } from 'crypto';
|
|
2
1
|
import fs from 'fs/promises';
|
|
3
2
|
import path from 'path';
|
|
4
3
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* @returns 24-character hexadecimal string
|
|
8
|
-
*/ export function generateSecret() {
|
|
9
|
-
return randomBytes(32).toString('hex').slice(0, 24);
|
|
10
|
-
}
|
|
11
|
-
/**
|
|
12
|
-
* Sanitize and process environment file contents
|
|
13
|
-
*
|
|
14
|
-
* @param contents - Raw .env file contents
|
|
15
|
-
* @param payloadSecret - Secret to use for PAYLOAD_SECRET
|
|
16
|
-
* @returns Processed .env contents
|
|
17
|
-
*/ function sanitizeEnv(contents, payloadSecret) {
|
|
18
|
-
const lines = contents.split('\n');
|
|
19
|
-
const seenKeys = new Set();
|
|
20
|
-
const processedLines = [];
|
|
21
|
-
for (const line of lines){
|
|
22
|
-
// Skip empty lines and comments
|
|
23
|
-
if (!line.trim() || line.trim().startsWith('#')) {
|
|
24
|
-
processedLines.push(line);
|
|
25
|
-
continue;
|
|
26
|
-
}
|
|
27
|
-
// Skip lines without =
|
|
28
|
-
if (!line.includes('=')) {
|
|
29
|
-
processedLines.push(line);
|
|
30
|
-
continue;
|
|
31
|
-
}
|
|
32
|
-
const [key] = line.split('=');
|
|
33
|
-
const trimmedKey = key.trim();
|
|
34
|
-
// Skip duplicate keys
|
|
35
|
-
if (seenKeys.has(trimmedKey)) {
|
|
36
|
-
continue;
|
|
37
|
-
}
|
|
38
|
-
seenKeys.add(trimmedKey);
|
|
39
|
-
// Replace PAYLOAD_SECRET with actual value
|
|
40
|
-
if (trimmedKey === 'PAYLOAD_SECRET' || trimmedKey === 'PAYLOAD_SECRET_KEY') {
|
|
41
|
-
processedLines.push(`PAYLOAD_SECRET=${payloadSecret}`);
|
|
42
|
-
} else {
|
|
43
|
-
processedLines.push(line);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
// Add PAYLOAD_SECRET if not present
|
|
47
|
-
if (!seenKeys.has('PAYLOAD_SECRET') && !seenKeys.has('PAYLOAD_SECRET_KEY')) {
|
|
48
|
-
processedLines.push(`PAYLOAD_SECRET=${payloadSecret}`);
|
|
49
|
-
}
|
|
50
|
-
return processedLines.join('\n');
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Manage environment files for a new project
|
|
54
|
-
*
|
|
55
|
-
* Creates .env from .env.example (if exists) and populates PAYLOAD_SECRET
|
|
4
|
+
* Add or update an environment variable in .env file
|
|
56
5
|
*
|
|
57
6
|
* @param projectPath - Path to project directory
|
|
58
|
-
* @
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
const envExamplePath = path.join(projectPath, '.env.example');
|
|
7
|
+
* @param key - Environment variable name
|
|
8
|
+
* @param value - Environment variable value
|
|
9
|
+
*/ export async function addOrUpdateEnvVar(projectPath, key, value) {
|
|
62
10
|
const envPath = path.join(projectPath, '.env');
|
|
63
11
|
try {
|
|
64
|
-
|
|
65
|
-
let envExampleContents = '';
|
|
66
|
-
try {
|
|
67
|
-
envExampleContents = await fs.readFile(envExamplePath, 'utf-8');
|
|
68
|
-
} catch {
|
|
69
|
-
// No .env.example, create minimal .env
|
|
70
|
-
envExampleContents = '';
|
|
71
|
-
}
|
|
72
|
-
// Check if .env already exists
|
|
12
|
+
let contents = '';
|
|
73
13
|
let envExists = false;
|
|
14
|
+
// Try to read existing .env file
|
|
74
15
|
try {
|
|
75
|
-
await fs.
|
|
16
|
+
contents = await fs.readFile(envPath, 'utf-8');
|
|
76
17
|
envExists = true;
|
|
77
18
|
} catch {
|
|
78
|
-
// .env doesn't exist
|
|
19
|
+
// .env doesn't exist, will create it
|
|
79
20
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
//
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
const sanitized = sanitizeEnv(existingContents, payloadSecret);
|
|
89
|
-
await fs.writeFile(envPath, sanitized, 'utf-8');
|
|
21
|
+
const lines = contents.split('\n');
|
|
22
|
+
const seenKeys = new Set();
|
|
23
|
+
const processedLines = [];
|
|
24
|
+
let keyUpdated = false;
|
|
25
|
+
for (const line of lines){
|
|
26
|
+
// Skip empty lines at start if file didn't exist
|
|
27
|
+
if (!envExists && !line.trim()) {
|
|
28
|
+
continue;
|
|
90
29
|
}
|
|
30
|
+
// Preserve empty lines and comments
|
|
31
|
+
if (!line.trim() || line.trim().startsWith('#')) {
|
|
32
|
+
processedLines.push(line);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
// Skip lines without =
|
|
36
|
+
if (!line.includes('=')) {
|
|
37
|
+
processedLines.push(line);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
const [lineKey] = line.split('=');
|
|
41
|
+
const trimmedKey = lineKey.trim();
|
|
42
|
+
// Skip duplicate keys (keep first occurrence)
|
|
43
|
+
if (seenKeys.has(trimmedKey)) {
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
seenKeys.add(trimmedKey);
|
|
47
|
+
// Update or keep the line
|
|
48
|
+
if (trimmedKey === key) {
|
|
49
|
+
processedLines.push(`${key}=${value}`);
|
|
50
|
+
keyUpdated = true;
|
|
51
|
+
} else {
|
|
52
|
+
processedLines.push(line);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
// Add key if not present
|
|
56
|
+
if (!keyUpdated) {
|
|
57
|
+
processedLines.push(`${key}=${value}`);
|
|
91
58
|
}
|
|
92
|
-
|
|
59
|
+
await fs.writeFile(envPath, processedLines.join('\n'), 'utf-8');
|
|
93
60
|
} catch (error) {
|
|
94
|
-
throw new Error(`Failed to
|
|
61
|
+
throw new Error(`Failed to update .env file: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
95
62
|
}
|
|
96
63
|
}
|
|
97
64
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/env-management.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"sources":["../../src/utils/env-management.ts"],"sourcesContent":["import fs from 'fs/promises'\nimport path from 'path'\n\n/**\n * Add or update an environment variable in .env file\n *\n * @param projectPath - Path to project directory\n * @param key - Environment variable name\n * @param value - Environment variable value\n */\nexport async function addOrUpdateEnvVar(\n projectPath: string,\n key: string,\n value: string,\n): Promise<void> {\n const envPath = path.join(projectPath, '.env')\n\n try {\n let contents = ''\n let envExists = false\n\n // Try to read existing .env file\n try {\n contents = await fs.readFile(envPath, 'utf-8')\n envExists = true\n } catch {\n // .env doesn't exist, will create it\n }\n\n const lines = contents.split('\\n')\n const seenKeys = new Set<string>()\n const processedLines: string[] = []\n let keyUpdated = false\n\n for (const line of lines) {\n // Skip empty lines at start if file didn't exist\n if (!envExists && !line.trim()) {\n continue\n }\n\n // Preserve empty lines and comments\n if (!line.trim() || line.trim().startsWith('#')) {\n processedLines.push(line)\n continue\n }\n\n // Skip lines without =\n if (!line.includes('=')) {\n processedLines.push(line)\n continue\n }\n\n const [lineKey] = line.split('=')\n const trimmedKey = lineKey.trim()\n\n // Skip duplicate keys (keep first occurrence)\n if (seenKeys.has(trimmedKey)) {\n continue\n }\n seenKeys.add(trimmedKey)\n\n // Update or keep the line\n if (trimmedKey === key) {\n processedLines.push(`${key}=${value}`)\n keyUpdated = true\n } else {\n processedLines.push(line)\n }\n }\n\n // Add key if not present\n if (!keyUpdated) {\n processedLines.push(`${key}=${value}`)\n }\n\n await fs.writeFile(envPath, processedLines.join('\\n'), 'utf-8')\n } catch (error) {\n throw new Error(\n `Failed to update .env file: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n}\n"],"names":["fs","path","addOrUpdateEnvVar","projectPath","key","value","envPath","join","contents","envExists","readFile","lines","split","seenKeys","Set","processedLines","keyUpdated","line","trim","startsWith","push","includes","lineKey","trimmedKey","has","add","writeFile","error","Error","message"],"mappings":"AAAA,OAAOA,QAAQ,cAAa;AAC5B,OAAOC,UAAU,OAAM;AAEvB;;;;;;CAMC,GACD,OAAO,eAAeC,kBACpBC,WAAmB,EACnBC,GAAW,EACXC,KAAa;IAEb,MAAMC,UAAUL,KAAKM,IAAI,CAACJ,aAAa;IAEvC,IAAI;QACF,IAAIK,WAAW;QACf,IAAIC,YAAY;QAEhB,iCAAiC;QACjC,IAAI;YACFD,WAAW,MAAMR,GAAGU,QAAQ,CAACJ,SAAS;YACtCG,YAAY;QACd,EAAE,OAAM;QACN,qCAAqC;QACvC;QAEA,MAAME,QAAQH,SAASI,KAAK,CAAC;QAC7B,MAAMC,WAAW,IAAIC;QACrB,MAAMC,iBAA2B,EAAE;QACnC,IAAIC,aAAa;QAEjB,KAAK,MAAMC,QAAQN,MAAO;YACxB,iDAAiD;YACjD,IAAI,CAACF,aAAa,CAACQ,KAAKC,IAAI,IAAI;gBAC9B;YACF;YAEA,oCAAoC;YACpC,IAAI,CAACD,KAAKC,IAAI,MAAMD,KAAKC,IAAI,GAAGC,UAAU,CAAC,MAAM;gBAC/CJ,eAAeK,IAAI,CAACH;gBACpB;YACF;YAEA,uBAAuB;YACvB,IAAI,CAACA,KAAKI,QAAQ,CAAC,MAAM;gBACvBN,eAAeK,IAAI,CAACH;gBACpB;YACF;YAEA,MAAM,CAACK,QAAQ,GAAGL,KAAKL,KAAK,CAAC;YAC7B,MAAMW,aAAaD,QAAQJ,IAAI;YAE/B,8CAA8C;YAC9C,IAAIL,SAASW,GAAG,CAACD,aAAa;gBAC5B;YACF;YACAV,SAASY,GAAG,CAACF;YAEb,0BAA0B;YAC1B,IAAIA,eAAenB,KAAK;gBACtBW,eAAeK,IAAI,CAAC,GAAGhB,IAAI,CAAC,EAAEC,OAAO;gBACrCW,aAAa;YACf,OAAO;gBACLD,eAAeK,IAAI,CAACH;YACtB;QACF;QAEA,yBAAyB;QACzB,IAAI,CAACD,YAAY;YACfD,eAAeK,IAAI,CAAC,GAAGhB,IAAI,CAAC,EAAEC,OAAO;QACvC;QAEA,MAAML,GAAG0B,SAAS,CAACpB,SAASS,eAAeR,IAAI,CAAC,OAAO;IACzD,EAAE,OAAOoB,OAAO;QACd,MAAM,IAAIC,MACR,CAAC,4BAA4B,EAAED,iBAAiBC,QAAQD,MAAME,OAAO,GAAG,iBAAiB;IAE7F;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/utils/messages.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAIjD,wBAAgB,WAAW,IAAI,IAAI,
|
|
1
|
+
{"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/utils/messages.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAIjD,wBAAgB,WAAW,IAAI,IAAI,CAyClC;AASD,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,cAAc,EAAE,cAAc,GAAG,MAAM,CAiBzF;AAED,wBAAgB,kBAAkB,IAAI,MAAM,CAO3C;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAgBpF;AAED,wBAAgB,aAAa,IAAI,MAAM,CAEtC"}
|
package/dist/utils/messages.js
CHANGED
|
@@ -29,16 +29,14 @@ export function helpMessage() {
|
|
|
29
29
|
|
|
30
30
|
${pc.bold('INIT COMMAND')}
|
|
31
31
|
|
|
32
|
-
${pc.cyan('@payloadcms/figma init --id <
|
|
33
|
-
${pc.cyan('@payloadcms/figma init')}
|
|
34
|
-
${pc.cyan('@payloadcms/figma init --
|
|
35
|
-
${pc.cyan('@payloadcms/figma init --force')} Force reconfiguration of existing project
|
|
36
|
-
${pc.cyan('@payloadcms/figma init --skip-auth')} Skip authentication (testing only)
|
|
32
|
+
${pc.cyan('@payloadcms/figma init --id <content-system-id>')} Initialize project with Content System ID
|
|
33
|
+
${pc.cyan('@payloadcms/figma init --force')} Force reconfiguration of existing project
|
|
34
|
+
${pc.cyan('@payloadcms/figma init --skip-auth')} Skip authentication (testing only)
|
|
37
35
|
|
|
38
36
|
${pc.bold('DEPLOY COMMAND')}
|
|
39
37
|
|
|
40
|
-
${pc.cyan('@payloadcms/figma deploy')}
|
|
41
|
-
${pc.dim('--yes, -y')}
|
|
38
|
+
${pc.cyan('@payloadcms/figma deploy --id <tenant-id>')} Deploy your project to Figma
|
|
39
|
+
${pc.dim('--yes, -y')} Skip confirmation prompts
|
|
42
40
|
|
|
43
41
|
${pc.bold('DOCUMENTATION')}
|
|
44
42
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/messages.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport path from 'path'\nimport pc from 'picocolors'\nimport terminalLink from 'terminal-link'\n\nimport type { PackageManager } from '../types.js'\n\nconst header = (message: string): string => pc.bold(message)\n\nexport function helpMessage(): void {\n console.log(`\n ${pc.bold('USAGE')}\n\n ${pc.dim('@payloadcms/figma <command> [options]')}\n\n ${pc.bold('COMMANDS')}\n\n ${pc.cyan('login')} Authenticate with Figma OAuth2\n ${pc.cyan('logout')} Clear all stored tokens\n ${pc.cyan('list-tokens')} Show stored token information\n ${pc.cyan('init')} Initialize a Figma CMS project\n ${pc.cyan('deploy')} Deploy your project to Figma\n\n ${pc.bold('OPTIONS')}\n\n ${pc.dim('-h, --help Show help')}\n ${pc.dim('--debug Enable debug logging')}\n\n ${pc.bold('AUTHENTICATION')}\n\n ${pc.cyan('@payloadcms/figma login')} Authenticate with Figma\n ${pc.cyan('@payloadcms/figma logout')} Clear all tokens (with confirmation)\n ${pc.cyan('@payloadcms/figma list-tokens')} Display stored OAuth and project tokens\n\n ${pc.bold('INIT COMMAND')}\n\n ${pc.cyan('@payloadcms/figma init --id <
|
|
1
|
+
{"version":3,"sources":["../../src/utils/messages.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport path from 'path'\nimport pc from 'picocolors'\nimport terminalLink from 'terminal-link'\n\nimport type { PackageManager } from '../types.js'\n\nconst header = (message: string): string => pc.bold(message)\n\nexport function helpMessage(): void {\n console.log(`\n ${pc.bold('USAGE')}\n\n ${pc.dim('@payloadcms/figma <command> [options]')}\n\n ${pc.bold('COMMANDS')}\n\n ${pc.cyan('login')} Authenticate with Figma OAuth2\n ${pc.cyan('logout')} Clear all stored tokens\n ${pc.cyan('list-tokens')} Show stored token information\n ${pc.cyan('init')} Initialize a Figma CMS project\n ${pc.cyan('deploy')} Deploy your project to Figma\n\n ${pc.bold('OPTIONS')}\n\n ${pc.dim('-h, --help Show help')}\n ${pc.dim('--debug Enable debug logging')}\n\n ${pc.bold('AUTHENTICATION')}\n\n ${pc.cyan('@payloadcms/figma login')} Authenticate with Figma\n ${pc.cyan('@payloadcms/figma logout')} Clear all tokens (with confirmation)\n ${pc.cyan('@payloadcms/figma list-tokens')} Display stored OAuth and project tokens\n\n ${pc.bold('INIT COMMAND')}\n\n ${pc.cyan('@payloadcms/figma init --id <content-system-id>')} Initialize project with Content System ID\n ${pc.cyan('@payloadcms/figma init --force')} Force reconfiguration of existing project\n ${pc.cyan('@payloadcms/figma init --skip-auth')} Skip authentication (testing only)\n\n ${pc.bold('DEPLOY COMMAND')}\n\n ${pc.cyan('@payloadcms/figma deploy --id <tenant-id>')} Deploy your project to Figma\n ${pc.dim('--yes, -y')} Skip confirmation prompts\n\n ${pc.bold('DOCUMENTATION')}\n\n ${createTerminalLink('Getting Started', 'https://payloadcms.com/docs/getting-started/what-is-payload')}\n ${createTerminalLink('Figma CMS Docs', 'https://www.figma.com/developers/api')}\n`)\n}\n\n// Create terminalLink with fallback for unsupported terminals\nfunction createTerminalLink(text: string, url: string) {\n return terminalLink(text, url, {\n fallback: (text, url) => `${text}: ${url}`,\n })\n}\n\nexport function successMessage(projectDir: string, packageManager: PackageManager): string {\n const relativePath = path.relative(process.cwd(), projectDir)\n return `\n${header('Launch Application:')}\n\n - cd ./${relativePath}\n - ${packageManager === 'npm' ? 'npm run' : packageManager} dev or follow directions in README.md\n\n${header('Documentation:')}\n\n - ${createTerminalLink(\n 'Getting Started',\n 'https://payloadcms.com/docs/getting-started/what-is-payload',\n )}\n - ${createTerminalLink('Configuration', 'https://payloadcms.com/docs/configuration/overview')}\n\n`\n}\n\nexport function successfulNextInit(): string {\n return `- ${createTerminalLink(\n 'Getting Started',\n 'https://payloadcms.com/docs/getting-started/what-is-payload',\n )}\n- ${createTerminalLink('Configuration', 'https://payloadcms.com/docs/configuration/overview')}\n`\n}\n\nexport function moveMessage(args: { nextAppDir: string; projectDir: string }): string {\n const relativeAppDir = path.relative(process.cwd(), args.nextAppDir)\n return `\n${header('Next Steps:')}\n\nPayload does not support a top-level layout.tsx file in the app directory.\n\n${pc.bold('To continue:')}\n\n- Create a new directory in ./${relativeAppDir} such as ./${relativeAppDir}/${pc.bold('(app)')}\n- Move all files from ./${relativeAppDir} into that directory\n\nIt is recommended to do this from your IDE if your app has existing file references.\n\nOnce moved, rerun the @payloadcms/figma command again.\n`\n}\n\nexport function feedbackOutro(): string {\n return `${pc.bgCyan(pc.black(' Have feedback? '))} Visit us on ${createTerminalLink('GitHub', 'https://github.com/payloadcms/payload')}.`\n}\n"],"names":["path","pc","terminalLink","header","message","bold","helpMessage","console","log","dim","cyan","createTerminalLink","text","url","fallback","successMessage","projectDir","packageManager","relativePath","relative","process","cwd","successfulNextInit","moveMessage","args","relativeAppDir","nextAppDir","feedbackOutro","bgCyan","black"],"mappings":"AAAA,6BAA6B,GAC7B,OAAOA,UAAU,OAAM;AACvB,OAAOC,QAAQ,aAAY;AAC3B,OAAOC,kBAAkB,gBAAe;AAIxC,MAAMC,SAAS,CAACC,UAA4BH,GAAGI,IAAI,CAACD;AAEpD,OAAO,SAASE;IACdC,QAAQC,GAAG,CAAC,CAAC;EACb,EAAEP,GAAGI,IAAI,CAAC,SAAS;;MAEf,EAAEJ,GAAGQ,GAAG,CAAC,yCAAyC;;EAEtD,EAAER,GAAGI,IAAI,CAAC,YAAY;;MAElB,EAAEJ,GAAGS,IAAI,CAAC,SAAS;MACnB,EAAET,GAAGS,IAAI,CAAC,UAAU;MACpB,EAAET,GAAGS,IAAI,CAAC,eAAe;MACzB,EAAET,GAAGS,IAAI,CAAC,QAAQ;MAClB,EAAET,GAAGS,IAAI,CAAC,UAAU;;EAExB,EAAET,GAAGI,IAAI,CAAC,WAAW;;MAEjB,EAAEJ,GAAGQ,GAAG,CAAC,iCAAiC;MAC1C,EAAER,GAAGQ,GAAG,CAAC,4CAA4C;;EAEzD,EAAER,GAAGI,IAAI,CAAC,kBAAkB;;MAExB,EAAEJ,GAAGS,IAAI,CAAC,2BAA2B;MACrC,EAAET,GAAGS,IAAI,CAAC,4BAA4B;MACtC,EAAET,GAAGS,IAAI,CAAC,iCAAiC;;EAE/C,EAAET,GAAGI,IAAI,CAAC,gBAAgB;;MAEtB,EAAEJ,GAAGS,IAAI,CAAC,mDAAmD;MAC7D,EAAET,GAAGS,IAAI,CAAC,kCAAkC;MAC5C,EAAET,GAAGS,IAAI,CAAC,sCAAsC;;EAEpD,EAAET,GAAGI,IAAI,CAAC,kBAAkB;;MAExB,EAAEJ,GAAGS,IAAI,CAAC,6CAA6C;MACvD,EAAET,GAAGQ,G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AAyC,CAAC,CAAC;AAC3I"}
|
|
@@ -29,9 +29,8 @@ export type ASTModificationResult = {
|
|
|
29
29
|
*/
|
|
30
30
|
export declare function applyModifications(sourceFile: SourceFile, detection: DetectionResult): ASTModificationResult;
|
|
31
31
|
export type FigmaPropertyConfig = {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
useContentSystem: boolean;
|
|
32
|
+
contentSystemId: string;
|
|
33
|
+
useContentSystem?: boolean;
|
|
35
34
|
};
|
|
36
35
|
/**
|
|
37
36
|
* Add figma property to buildConfig if it doesn't exist
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payload-config-ast.d.ts","sourceRoot":"","sources":["../../src/utils/payload-config-ast.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAM1C,MAAM,MAAM,eAAe,GAAG;IAC5B,UAAU,CAAC,EAAE;QACX,OAAO,EAAE,MAAM,CAAA;QACf,YAAY,EAAE,MAAM,CAAA;KACrB,CAAA;IACD,cAAc,CAAC,EAAE;QACf,YAAY,EAAE,MAAM,CAAA;QACpB,SAAS,EAAE,OAAO,CAAA;KACnB,CAAA;IACD,iBAAiB,EAAE,OAAO,CAAA;IAC1B,QAAQ,EAAE,OAAO,CAAA;IACjB,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,sBAAsB,EAAE,OAAO,CAAA;IAC/B,iBAAiB,EAAE,OAAO,CAAA;IAC1B,cAAc,CAAC,EAAE,OAAO,CAAA;CACzB,CAAA;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,UAAU,GAAG,eAAe,CAiJ7E;AAED,MAAM,MAAM,qBAAqB,GAAG;IAClC,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,QAAQ,EAAE,OAAO,CAAA;CAClB,CAAA;AA0CD;;;GAGG;AACH,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,UAAU,EACtB,SAAS,EAAE,eAAe,GACzB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AAG,IAAI,CA4ElF"}
|
|
@@ -336,15 +336,19 @@ import * as log from './log.js';
|
|
|
336
336
|
};
|
|
337
337
|
}
|
|
338
338
|
// Add figma property
|
|
339
|
+
// Note: useContentSystem is optional and defaults to true, so we don't generate it during init
|
|
340
|
+
// contentSystemId is stored in .env file and referenced via process.env with non-null assertion
|
|
341
|
+
const figmaObj = config.useContentSystem === false ? `{
|
|
342
|
+
contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!,
|
|
343
|
+
useContentSystem: false,
|
|
344
|
+
}` : `{
|
|
345
|
+
contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!,
|
|
346
|
+
}`;
|
|
339
347
|
configArg.addPropertyAssignment({
|
|
340
348
|
name: 'figma',
|
|
341
|
-
initializer:
|
|
342
|
-
region: '${config.region}',
|
|
343
|
-
tenantId: '${config.tenantId}',
|
|
344
|
-
useContentSystem: ${config.useContentSystem},
|
|
345
|
-
}`
|
|
349
|
+
initializer: figmaObj
|
|
346
350
|
});
|
|
347
|
-
changes.push(`Added figma property (
|
|
351
|
+
changes.push(`Added figma property (contentSystemId: ${config.contentSystemId})`);
|
|
348
352
|
modified = true;
|
|
349
353
|
return {
|
|
350
354
|
changes,
|
|
@@ -385,25 +389,37 @@ import * as log from './log.js';
|
|
|
385
389
|
return null;
|
|
386
390
|
}
|
|
387
391
|
// Extract values
|
|
388
|
-
const
|
|
389
|
-
const tenantIdProp = initializer.getProperty('tenantId');
|
|
392
|
+
const contentSystemIdProp = initializer.getProperty('contentSystemId');
|
|
390
393
|
const useContentSystemProp = initializer.getProperty('useContentSystem');
|
|
391
|
-
if (!
|
|
392
|
-
log.debug('Missing required figma
|
|
394
|
+
if (!contentSystemIdProp) {
|
|
395
|
+
log.debug('Missing required figma property: contentSystemId');
|
|
393
396
|
return null;
|
|
394
397
|
}
|
|
395
|
-
// Extract
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
398
|
+
// Extract contentSystemId - support both literal strings and env var references
|
|
399
|
+
let contentSystemId;
|
|
400
|
+
if (Node.isPropertyAssignment(contentSystemIdProp)) {
|
|
401
|
+
const initializer = contentSystemIdProp.getInitializer();
|
|
402
|
+
const text = initializer?.getText() || '';
|
|
403
|
+
// Support both patterns:
|
|
404
|
+
// 1. Literal string: 'cms_abc123' or "cms_abc123"
|
|
405
|
+
// 2. Environment variable: process.env.FIGMA_CONTENT_SYSTEM_ID
|
|
406
|
+
if (text.includes('process.env.FIGMA_CONTENT_SYSTEM_ID')) {
|
|
407
|
+
// For env var reference, return a marker that indicates it's from env
|
|
408
|
+
// The actual value will be read at runtime
|
|
409
|
+
contentSystemId = 'process.env.FIGMA_CONTENT_SYSTEM_ID';
|
|
410
|
+
} else {
|
|
411
|
+
// Remove quotes for literal strings
|
|
412
|
+
contentSystemId = text.replace(/['"]/g, '');
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
const useContentSystem = Node.isPropertyAssignment(useContentSystemProp) ? useContentSystemProp.getInitializer()?.getText() === 'true' : undefined // Optional: undefined if not specified
|
|
399
416
|
;
|
|
400
|
-
if (!
|
|
401
|
-
log.debug('Could not extract
|
|
417
|
+
if (!contentSystemId) {
|
|
418
|
+
log.debug('Could not extract contentSystemId value');
|
|
402
419
|
return null;
|
|
403
420
|
}
|
|
404
421
|
return {
|
|
405
|
-
|
|
406
|
-
tenantId,
|
|
422
|
+
contentSystemId,
|
|
407
423
|
useContentSystem
|
|
408
424
|
};
|
|
409
425
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/payload-config-ast.ts"],"sourcesContent":["import type { SourceFile } from 'ts-morph'\n\nimport { Node, SyntaxKind } from 'ts-morph'\n\nimport * as log from './log.js'\n\nexport type DetectionResult = {\n dbProperty?: {\n adapter: string\n importSource: string\n }\n editorProperty?: {\n importSource: string\n isDefault: boolean\n }\n figmaObjectExists: boolean\n hasAlias: boolean\n hasBuildConfig?: boolean\n hasOtherPayloadImports: boolean\n needsImportChange: boolean\n secretProperty?: boolean\n}\n\n/**\n * Detect what changes are needed in the payload config file\n */\nexport function detectRequiredChanges(sourceFile: SourceFile): DetectionResult {\n const result: DetectionResult = {\n figmaObjectExists: false,\n hasAlias: false,\n hasOtherPayloadImports: false,\n needsImportChange: false,\n }\n\n // Find buildConfig import\n const imports = sourceFile.getImportDeclarations()\n const payloadImport = imports.find(\n (imp) =>\n imp.getModuleSpecifierValue() === 'payload' ||\n imp.getModuleSpecifierValue() === '@payloadcms/figma',\n )\n\n if (!payloadImport) {\n log.debug('No payload or @payloadcms/figma import found')\n result.hasBuildConfig = false\n return result\n }\n\n log.debug(`Found import from: ${payloadImport.getModuleSpecifierValue()}`)\n\n const moduleSpecifier = payloadImport.getModuleSpecifierValue()\n const namedImports = payloadImport.getNamedImports()\n\n // Check if buildConfig is imported\n const buildConfigImport = namedImports.find((ni) => ni.getName() === 'buildConfig')\n\n if (!buildConfigImport) {\n result.hasBuildConfig = false\n return result\n }\n\n // Check for alias and get the actual name used in code\n const aliasNode = buildConfigImport.getAliasNode()\n const buildConfigName = aliasNode ? aliasNode.getText() : 'buildConfig'\n if (aliasNode) {\n result.hasAlias = true\n }\n\n // Check if import needs change\n if (moduleSpecifier === 'payload') {\n result.needsImportChange = true\n\n // Check if there are other imports from payload\n if (namedImports.length > 1) {\n result.hasOtherPayloadImports = true\n }\n }\n\n // Find buildConfig call in export default\n // First try to find export default with the buildConfig call\n const exportAssignment = sourceFile.getFirstDescendantByKind(SyntaxKind.ExportAssignment)\n let buildConfigCall = null\n\n if (exportAssignment) {\n // Look for buildConfig call in the export default\n const callExpressions = exportAssignment.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n // If not found in export default, search all call expressions\n if (!buildConfigCall) {\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n if (!buildConfigCall) {\n result.hasBuildConfig = false\n return result\n }\n\n // Get config object\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n return result\n }\n\n // Check for db property\n const dbProperty = configArg.getProperty('db')\n if (dbProperty) {\n const dbValue = dbProperty.getChildrenOfKind(SyntaxKind.CallExpression)[0]\n if (dbValue) {\n const adapterName = dbValue.getExpression().getText()\n\n // Find the import source for this adapter\n const adapterImport = imports.find((imp) =>\n imp.getNamedImports().some((ni) => ni.getName() === adapterName),\n )\n\n if (adapterImport) {\n result.dbProperty = {\n adapter: adapterName,\n importSource: adapterImport.getModuleSpecifierValue(),\n }\n }\n }\n }\n\n // Check for secret property\n const secretProperty = configArg.getProperty('secret')\n if (secretProperty) {\n result.secretProperty = true\n }\n\n // Check for editor property\n const editorProperty = configArg.getProperty('editor')\n if (editorProperty) {\n const editorValue = editorProperty.getChildrenOfKind(SyntaxKind.CallExpression)[0]\n if (editorValue) {\n const editorName = editorValue.getExpression().getText()\n\n // Find the import source\n const editorImport = imports.find((imp) =>\n imp.getNamedImports().some((ni) => ni.getName() === editorName),\n )\n\n if (editorImport && editorName === 'lexicalEditor') {\n // Check if it has arguments\n const args = editorValue.getArguments()\n const isDefault = args.length === 0\n\n result.editorProperty = {\n importSource: editorImport.getModuleSpecifierValue(),\n isDefault,\n }\n }\n }\n }\n\n // Check for figma property\n const figmaProperty = configArg.getProperty('figma')\n if (figmaProperty) {\n result.figmaObjectExists = true\n }\n\n return result\n}\n\nexport type ASTModificationResult = {\n changes: string[]\n modified: boolean\n}\n\n/**\n * Remove all comments\n * @returns true if any comments were removed\n */\nfunction removeAllComments(sourceFile: SourceFile): boolean {\n const ranges: Array<[number, number]> = []\n\n // Recursively collect comments from node and ALL children (including tokens)\n const collectComments = (node: Node) => {\n node.getLeadingCommentRanges().forEach((range) => {\n ranges.push([range.getPos(), range.getEnd()])\n })\n node.getTrailingCommentRanges().forEach((range) => {\n ranges.push([range.getPos(), range.getEnd()])\n })\n\n // Process ALL children including token nodes (commas, braces, etc.)\n node.getChildren().forEach(collectComments)\n }\n\n collectComments(sourceFile)\n\n if (ranges.length === 0) {\n return false\n }\n\n // Remove duplicates and sort in reverse order to avoid position shifts\n const uniqueRanges = Array.from(new Set(ranges.map((r) => JSON.stringify(r)))).map(\n (r) => JSON.parse(r) as [number, number],\n )\n uniqueRanges.sort((a, b) => b[0] - a[0])\n\n // Remove each comment range\n for (const [pos, end] of uniqueRanges) {\n sourceFile.removeText(pos, end)\n }\n\n return true\n}\n\n/**\n * Apply modifications to the source file based on detection result\n * Modifies the AST in memory - caller must call sourceFile.save()\n */\nexport function applyModifications(\n sourceFile: SourceFile,\n detection: DetectionResult,\n): ASTModificationResult {\n const changes: string[] = []\n let modified = false\n\n if (detection.hasBuildConfig === false || detection.hasAlias) {\n log.debug(\n `Skipping modifications: hasBuildConfig=${detection.hasBuildConfig}, hasAlias=${detection.hasAlias}`,\n )\n return { changes: [], modified: false }\n }\n\n // 1. Remove all comments FIRST (before AST modifications that might shift positions)\n const hadComments = removeAllComments(sourceFile)\n if (hadComments) {\n changes.push('Removed comments')\n modified = true\n }\n\n // Find the import declarations\n const imports = sourceFile.getImportDeclarations()\n const payloadImport = imports.find((imp) => imp.getModuleSpecifierValue() === 'payload')\n\n // Get the buildConfig name (could be aliased)\n let buildConfigName = 'buildConfig'\n if (payloadImport) {\n const buildConfigImport = payloadImport\n .getNamedImports()\n .find((ni) => ni.getName() === 'buildConfig')\n if (buildConfigImport) {\n const aliasNode = buildConfigImport.getAliasNode()\n buildConfigName = aliasNode ? aliasNode.getText() : 'buildConfig'\n }\n }\n\n // Find buildConfig call in export default (prefer export default)\n const exportAssignment = sourceFile.getFirstDescendantByKind(SyntaxKind.ExportAssignment)\n let buildConfigCall = null\n\n if (exportAssignment) {\n const callExpressions = exportAssignment.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n // If not found in export default, search all call expressions\n if (!buildConfigCall) {\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n if (!buildConfigCall) {\n return { changes: [], modified: false }\n }\n\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n return { changes: [], modified: false }\n }\n\n // 1. Remove db property\n if (detection.dbProperty) {\n const dbProperty = configArg.getProperty('db')\n if (dbProperty) {\n dbProperty.remove()\n changes.push('Removed db property')\n modified = true\n }\n }\n\n // 2. Remove secret property\n if (detection.secretProperty) {\n const secretProperty = configArg.getProperty('secret')\n if (secretProperty) {\n secretProperty.remove()\n changes.push('Removed secret property')\n modified = true\n }\n }\n\n // 3. Remove editor if default\n if (detection.editorProperty?.isDefault) {\n const editorProperty = configArg.getProperty('editor')\n if (editorProperty) {\n editorProperty.remove()\n changes.push('Removed default editor property')\n modified = true\n }\n }\n\n // 4. Update buildConfig import\n if (detection.needsImportChange) {\n if (payloadImport) {\n if (detection.hasOtherPayloadImports) {\n // Remove buildConfig from payload import, add new figma import\n const namedImports = payloadImport.getNamedImports()\n const buildConfigImport = namedImports.find((ni) => ni.getName() === 'buildConfig')\n if (buildConfigImport) {\n buildConfigImport.remove()\n\n // If payload import is now empty, remove it\n if (payloadImport.getNamedImports().length === 0) {\n payloadImport.remove()\n }\n }\n\n // Add new import at the top\n sourceFile.addImportDeclaration({\n moduleSpecifier: '@payloadcms/figma',\n namedImports: ['buildConfig'],\n })\n\n changes.push('Split buildConfig import to @payloadcms/figma')\n } else {\n // Replace entire import\n payloadImport.setModuleSpecifier('@payloadcms/figma')\n changes.push('Changed buildConfig import to @payloadcms/figma')\n }\n modified = true\n }\n }\n\n // 5. Remove orphaned imports\n // Re-fetch imports after each removal to avoid stale references\n if (detection.dbProperty) {\n const currentImports = sourceFile.getImportDeclarations()\n const dbImport = currentImports.find(\n (imp) => imp.getModuleSpecifierValue() === detection.dbProperty?.importSource,\n )\n if (dbImport) {\n dbImport.remove()\n changes.push(`Removed ${detection.dbProperty.adapter} import`)\n modified = true\n }\n }\n\n if (detection.editorProperty?.isDefault) {\n const currentImports = sourceFile.getImportDeclarations()\n const editorImport = currentImports.find(\n (imp) => imp.getModuleSpecifierValue() === detection.editorProperty?.importSource,\n )\n if (editorImport) {\n editorImport.remove()\n changes.push('Removed lexicalEditor import')\n modified = true\n }\n }\n\n return { changes, modified }\n}\n\nexport type FigmaPropertyConfig = {\n region: string\n tenantId: string\n useContentSystem: boolean\n}\n\n/**\n * Add figma property to buildConfig if it doesn't exist\n * Modifies the AST in memory - caller must call sourceFile.save()\n */\nexport function addFigmaProperty(\n sourceFile: SourceFile,\n config: FigmaPropertyConfig,\n): ASTModificationResult {\n const changes: string[] = []\n let modified = false\n\n // Find buildConfig call\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n const buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n const text = expr.getText()\n return text === 'buildConfig' || text.endsWith('.buildConfig')\n })\n\n if (!buildConfigCall) {\n log.debug('No buildConfig call found')\n return { changes: [], modified: false }\n }\n\n // Get config object argument\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n log.debug('buildConfig argument is not an object literal')\n return { changes: [], modified: false }\n }\n\n // Check if figma property already exists\n const existingFigmaProperty = configArg.getProperty('figma')\n if (existingFigmaProperty) {\n log.debug('figma property already exists, skipping')\n return { changes: ['Skipped: figma property already exists'], modified: false }\n }\n\n // Add figma property\n configArg.addPropertyAssignment({\n name: 'figma',\n initializer: `{\n region: '${config.region}',\n tenantId: '${config.tenantId}',\n useContentSystem: ${config.useContentSystem},\n }`,\n })\n\n changes.push(\n `Added figma property (region: ${config.region}, tenantId: ${config.tenantId}, useContentSystem: ${config.useContentSystem})`,\n )\n modified = true\n\n return { changes, modified }\n}\n\n/**\n * Read figma configuration from payload.config.ts\n * Returns the figma object if it exists, null otherwise\n */\nexport function readFigmaConfig(sourceFile: SourceFile): FigmaPropertyConfig | null {\n // Find buildConfig call\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n const buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n const text = expr.getText()\n return text === 'buildConfig' || text.endsWith('.buildConfig')\n })\n\n if (!buildConfigCall) {\n log.debug('No buildConfig call found')\n return null\n }\n\n // Get config object argument\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n log.debug('buildConfig argument is not an object literal')\n return null\n }\n\n // Find figma property\n const figmaProperty = configArg.getProperty('figma')\n if (!figmaProperty || !Node.isPropertyAssignment(figmaProperty)) {\n log.debug('No figma property found in buildConfig')\n return null\n }\n\n // Get initializer (the object value)\n const initializer = figmaProperty.getInitializer()\n if (!initializer || !Node.isObjectLiteralExpression(initializer)) {\n log.debug('figma property is not an object literal')\n return null\n }\n\n // Extract values\n const regionProp = initializer.getProperty('region')\n const tenantIdProp = initializer.getProperty('tenantId')\n const useContentSystemProp = initializer.getProperty('useContentSystem')\n\n if (!regionProp || !tenantIdProp) {\n log.debug('Missing required figma properties (region or tenantId)')\n return null\n }\n\n // Extract string values (remove quotes)\n const region = Node.isPropertyAssignment(regionProp)\n ? regionProp\n .getInitializer()\n ?.getText()\n .replace(/['\"]/g, '')\n : undefined\n\n const tenantId = Node.isPropertyAssignment(tenantIdProp)\n ? tenantIdProp\n .getInitializer()\n ?.getText()\n .replace(/['\"]/g, '')\n : undefined\n\n const useContentSystem = Node.isPropertyAssignment(useContentSystemProp)\n ? useContentSystemProp.getInitializer()?.getText() === 'true'\n : true // Default to true if not specified\n\n if (!region || !tenantId) {\n log.debug('Could not extract region or tenantId values')\n return null\n }\n\n return {\n region,\n tenantId,\n useContentSystem,\n }\n}\n"],"names":["Node","SyntaxKind","log","detectRequiredChanges","sourceFile","result","figmaObjectExists","hasAlias","hasOtherPayloadImports","needsImportChange","imports","getImportDeclarations","payloadImport","find","imp","getModuleSpecifierValue","debug","hasBuildConfig","moduleSpecifier","namedImports","getNamedImports","buildConfigImport","ni","getName","aliasNode","getAliasNode","buildConfigName","getText","length","exportAssignment","getFirstDescendantByKind","ExportAssignment","buildConfigCall","callExpressions","getDescendantsOfKind","CallExpression","ce","expr","getExpression","configArg","getArguments","isObjectLiteralExpression","dbProperty","getProperty","dbValue","getChildrenOfKind","adapterName","adapterImport","some","adapter","importSource","secretProperty","editorProperty","editorValue","editorName","editorImport","args","isDefault","figmaProperty","removeAllComments","ranges","collectComments","node","getLeadingCommentRanges","forEach","range","push","getPos","getEnd","getTrailingCommentRanges","getChildren","uniqueRanges","Array","from","Set","map","r","JSON","stringify","parse","sort","a","b","pos","end","removeText","applyModifications","detection","changes","modified","hadComments","remove","addImportDeclaration","setModuleSpecifier","currentImports","dbImport","addFigmaProperty","config","text","endsWith","existingFigmaProperty","addPropertyAssignment","name","initializer","region","tenantId","useContentSystem","readFigmaConfig","isPropertyAssignment","getInitializer","regionProp","tenantIdProp","useContentSystemProp","replace","undefined"],"mappings":"AAEA,SAASA,IAAI,EAAEC,UAAU,QAAQ,WAAU;AAE3C,YAAYC,SAAS,WAAU;AAmB/B;;CAEC,GACD,OAAO,SAASC,sBAAsBC,UAAsB;IAC1D,MAAMC,SAA0B;QAC9BC,mBAAmB;QACnBC,UAAU;QACVC,wBAAwB;QACxBC,mBAAmB;IACrB;IAEA,0BAA0B;IAC1B,MAAMC,UAAUN,WAAWO,qBAAqB;IAChD,MAAMC,gBAAgBF,QAAQG,IAAI,CAChC,CAACC,MACCA,IAAIC,uBAAuB,OAAO,aAClCD,IAAIC,uBAAuB,OAAO;IAGtC,IAAI,CAACH,eAAe;QAClBV,IAAIc,KAAK,CAAC;QACVX,OAAOY,cAAc,GAAG;QACxB,OAAOZ;IACT;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cAAc,IAAIlF,cAAc,SACrD,KAAK,mCAAmC;;IAE5C,IAAI,CAAC6E,UAAU,CAACC,UAAU;QACxBvG,IAAIc,KAAK,CAAC;QACV,OAAO;IACT;IAEA,OAAO;QACLwF;QACAC;QACAC;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/payload-config-ast.ts"],"sourcesContent":["import type { SourceFile } from 'ts-morph'\n\nimport { Node, SyntaxKind } from 'ts-morph'\n\nimport * as log from './log.js'\n\nexport type DetectionResult = {\n dbProperty?: {\n adapter: string\n importSource: string\n }\n editorProperty?: {\n importSource: string\n isDefault: boolean\n }\n figmaObjectExists: boolean\n hasAlias: boolean\n hasBuildConfig?: boolean\n hasOtherPayloadImports: boolean\n needsImportChange: boolean\n secretProperty?: boolean\n}\n\n/**\n * Detect what changes are needed in the payload config file\n */\nexport function detectRequiredChanges(sourceFile: SourceFile): DetectionResult {\n const result: DetectionResult = {\n figmaObjectExists: false,\n hasAlias: false,\n hasOtherPayloadImports: false,\n needsImportChange: false,\n }\n\n // Find buildConfig import\n const imports = sourceFile.getImportDeclarations()\n const payloadImport = imports.find(\n (imp) =>\n imp.getModuleSpecifierValue() === 'payload' ||\n imp.getModuleSpecifierValue() === '@payloadcms/figma',\n )\n\n if (!payloadImport) {\n log.debug('No payload or @payloadcms/figma import found')\n result.hasBuildConfig = false\n return result\n }\n\n log.debug(`Found import from: ${payloadImport.getModuleSpecifierValue()}`)\n\n const moduleSpecifier = payloadImport.getModuleSpecifierValue()\n const namedImports = payloadImport.getNamedImports()\n\n // Check if buildConfig is imported\n const buildConfigImport = namedImports.find((ni) => ni.getName() === 'buildConfig')\n\n if (!buildConfigImport) {\n result.hasBuildConfig = false\n return result\n }\n\n // Check for alias and get the actual name used in code\n const aliasNode = buildConfigImport.getAliasNode()\n const buildConfigName = aliasNode ? aliasNode.getText() : 'buildConfig'\n if (aliasNode) {\n result.hasAlias = true\n }\n\n // Check if import needs change\n if (moduleSpecifier === 'payload') {\n result.needsImportChange = true\n\n // Check if there are other imports from payload\n if (namedImports.length > 1) {\n result.hasOtherPayloadImports = true\n }\n }\n\n // Find buildConfig call in export default\n // First try to find export default with the buildConfig call\n const exportAssignment = sourceFile.getFirstDescendantByKind(SyntaxKind.ExportAssignment)\n let buildConfigCall = null\n\n if (exportAssignment) {\n // Look for buildConfig call in the export default\n const callExpressions = exportAssignment.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n // If not found in export default, search all call expressions\n if (!buildConfigCall) {\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n if (!buildConfigCall) {\n result.hasBuildConfig = false\n return result\n }\n\n // Get config object\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n return result\n }\n\n // Check for db property\n const dbProperty = configArg.getProperty('db')\n if (dbProperty) {\n const dbValue = dbProperty.getChildrenOfKind(SyntaxKind.CallExpression)[0]\n if (dbValue) {\n const adapterName = dbValue.getExpression().getText()\n\n // Find the import source for this adapter\n const adapterImport = imports.find((imp) =>\n imp.getNamedImports().some((ni) => ni.getName() === adapterName),\n )\n\n if (adapterImport) {\n result.dbProperty = {\n adapter: adapterName,\n importSource: adapterImport.getModuleSpecifierValue(),\n }\n }\n }\n }\n\n // Check for secret property\n const secretProperty = configArg.getProperty('secret')\n if (secretProperty) {\n result.secretProperty = true\n }\n\n // Check for editor property\n const editorProperty = configArg.getProperty('editor')\n if (editorProperty) {\n const editorValue = editorProperty.getChildrenOfKind(SyntaxKind.CallExpression)[0]\n if (editorValue) {\n const editorName = editorValue.getExpression().getText()\n\n // Find the import source\n const editorImport = imports.find((imp) =>\n imp.getNamedImports().some((ni) => ni.getName() === editorName),\n )\n\n if (editorImport && editorName === 'lexicalEditor') {\n // Check if it has arguments\n const args = editorValue.getArguments()\n const isDefault = args.length === 0\n\n result.editorProperty = {\n importSource: editorImport.getModuleSpecifierValue(),\n isDefault,\n }\n }\n }\n }\n\n // Check for figma property\n const figmaProperty = configArg.getProperty('figma')\n if (figmaProperty) {\n result.figmaObjectExists = true\n }\n\n return result\n}\n\nexport type ASTModificationResult = {\n changes: string[]\n modified: boolean\n}\n\n/**\n * Remove all comments\n * @returns true if any comments were removed\n */\nfunction removeAllComments(sourceFile: SourceFile): boolean {\n const ranges: Array<[number, number]> = []\n\n // Recursively collect comments from node and ALL children (including tokens)\n const collectComments = (node: Node) => {\n node.getLeadingCommentRanges().forEach((range) => {\n ranges.push([range.getPos(), range.getEnd()])\n })\n node.getTrailingCommentRanges().forEach((range) => {\n ranges.push([range.getPos(), range.getEnd()])\n })\n\n // Process ALL children including token nodes (commas, braces, etc.)\n node.getChildren().forEach(collectComments)\n }\n\n collectComments(sourceFile)\n\n if (ranges.length === 0) {\n return false\n }\n\n // Remove duplicates and sort in reverse order to avoid position shifts\n const uniqueRanges = Array.from(new Set(ranges.map((r) => JSON.stringify(r)))).map(\n (r) => JSON.parse(r) as [number, number],\n )\n uniqueRanges.sort((a, b) => b[0] - a[0])\n\n // Remove each comment range\n for (const [pos, end] of uniqueRanges) {\n sourceFile.removeText(pos, end)\n }\n\n return true\n}\n\n/**\n * Apply modifications to the source file based on detection result\n * Modifies the AST in memory - caller must call sourceFile.save()\n */\nexport function applyModifications(\n sourceFile: SourceFile,\n detection: DetectionResult,\n): ASTModificationResult {\n const changes: string[] = []\n let modified = false\n\n if (detection.hasBuildConfig === false || detection.hasAlias) {\n log.debug(\n `Skipping modifications: hasBuildConfig=${detection.hasBuildConfig}, hasAlias=${detection.hasAlias}`,\n )\n return { changes: [], modified: false }\n }\n\n // 1. Remove all comments FIRST (before AST modifications that might shift positions)\n const hadComments = removeAllComments(sourceFile)\n if (hadComments) {\n changes.push('Removed comments')\n modified = true\n }\n\n // Find the import declarations\n const imports = sourceFile.getImportDeclarations()\n const payloadImport = imports.find((imp) => imp.getModuleSpecifierValue() === 'payload')\n\n // Get the buildConfig name (could be aliased)\n let buildConfigName = 'buildConfig'\n if (payloadImport) {\n const buildConfigImport = payloadImport\n .getNamedImports()\n .find((ni) => ni.getName() === 'buildConfig')\n if (buildConfigImport) {\n const aliasNode = buildConfigImport.getAliasNode()\n buildConfigName = aliasNode ? aliasNode.getText() : 'buildConfig'\n }\n }\n\n // Find buildConfig call in export default (prefer export default)\n const exportAssignment = sourceFile.getFirstDescendantByKind(SyntaxKind.ExportAssignment)\n let buildConfigCall = null\n\n if (exportAssignment) {\n const callExpressions = exportAssignment.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n // If not found in export default, search all call expressions\n if (!buildConfigCall) {\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n if (!buildConfigCall) {\n return { changes: [], modified: false }\n }\n\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n return { changes: [], modified: false }\n }\n\n // 1. Remove db property\n if (detection.dbProperty) {\n const dbProperty = configArg.getProperty('db')\n if (dbProperty) {\n dbProperty.remove()\n changes.push('Removed db property')\n modified = true\n }\n }\n\n // 2. Remove secret property\n if (detection.secretProperty) {\n const secretProperty = configArg.getProperty('secret')\n if (secretProperty) {\n secretProperty.remove()\n changes.push('Removed secret property')\n modified = true\n }\n }\n\n // 3. Remove editor if default\n if (detection.editorProperty?.isDefault) {\n const editorProperty = configArg.getProperty('editor')\n if (editorProperty) {\n editorProperty.remove()\n changes.push('Removed default editor property')\n modified = true\n }\n }\n\n // 4. Update buildConfig import\n if (detection.needsImportChange) {\n if (payloadImport) {\n if (detection.hasOtherPayloadImports) {\n // Remove buildConfig from payload import, add new figma import\n const namedImports = payloadImport.getNamedImports()\n const buildConfigImport = namedImports.find((ni) => ni.getName() === 'buildConfig')\n if (buildConfigImport) {\n buildConfigImport.remove()\n\n // If payload import is now empty, remove it\n if (payloadImport.getNamedImports().length === 0) {\n payloadImport.remove()\n }\n }\n\n // Add new import at the top\n sourceFile.addImportDeclaration({\n moduleSpecifier: '@payloadcms/figma',\n namedImports: ['buildConfig'],\n })\n\n changes.push('Split buildConfig import to @payloadcms/figma')\n } else {\n // Replace entire import\n payloadImport.setModuleSpecifier('@payloadcms/figma')\n changes.push('Changed buildConfig import to @payloadcms/figma')\n }\n modified = true\n }\n }\n\n // 5. Remove orphaned imports\n // Re-fetch imports after each removal to avoid stale references\n if (detection.dbProperty) {\n const currentImports = sourceFile.getImportDeclarations()\n const dbImport = currentImports.find(\n (imp) => imp.getModuleSpecifierValue() === detection.dbProperty?.importSource,\n )\n if (dbImport) {\n dbImport.remove()\n changes.push(`Removed ${detection.dbProperty.adapter} import`)\n modified = true\n }\n }\n\n if (detection.editorProperty?.isDefault) {\n const currentImports = sourceFile.getImportDeclarations()\n const editorImport = currentImports.find(\n (imp) => imp.getModuleSpecifierValue() === detection.editorProperty?.importSource,\n )\n if (editorImport) {\n editorImport.remove()\n changes.push('Removed lexicalEditor import')\n modified = true\n }\n }\n\n return { changes, modified }\n}\n\nexport type FigmaPropertyConfig = {\n contentSystemId: string\n useContentSystem?: boolean\n}\n\n/**\n * Add figma property to buildConfig if it doesn't exist\n * Modifies the AST in memory - caller must call sourceFile.save()\n */\nexport function addFigmaProperty(\n sourceFile: SourceFile,\n config: FigmaPropertyConfig,\n): ASTModificationResult {\n const changes: string[] = []\n let modified = false\n\n // Find buildConfig call\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n const buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n const text = expr.getText()\n return text === 'buildConfig' || text.endsWith('.buildConfig')\n })\n\n if (!buildConfigCall) {\n log.debug('No buildConfig call found')\n return { changes: [], modified: false }\n }\n\n // Get config object argument\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n log.debug('buildConfig argument is not an object literal')\n return { changes: [], modified: false }\n }\n\n // Check if figma property already exists\n const existingFigmaProperty = configArg.getProperty('figma')\n if (existingFigmaProperty) {\n log.debug('figma property already exists, skipping')\n return { changes: ['Skipped: figma property already exists'], modified: false }\n }\n\n // Add figma property\n // Note: useContentSystem is optional and defaults to true, so we don't generate it during init\n // contentSystemId is stored in .env file and referenced via process.env with non-null assertion\n const figmaObj =\n config.useContentSystem === false\n ? `{\n contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!,\n useContentSystem: false,\n }`\n : `{\n contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!,\n }`\n\n configArg.addPropertyAssignment({\n name: 'figma',\n initializer: figmaObj,\n })\n\n changes.push(`Added figma property (contentSystemId: ${config.contentSystemId})`)\n modified = true\n\n return { changes, modified }\n}\n\n/**\n * Read figma configuration from payload.config.ts\n * Returns the figma object if it exists, null otherwise\n */\nexport function readFigmaConfig(sourceFile: SourceFile): FigmaPropertyConfig | null {\n // Find buildConfig call\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n const buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n const text = expr.getText()\n return text === 'buildConfig' || text.endsWith('.buildConfig')\n })\n\n if (!buildConfigCall) {\n log.debug('No buildConfig call found')\n return null\n }\n\n // Get config object argument\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n log.debug('buildConfig argument is not an object literal')\n return null\n }\n\n // Find figma property\n const figmaProperty = configArg.getProperty('figma')\n if (!figmaProperty || !Node.isPropertyAssignment(figmaProperty)) {\n log.debug('No figma property found in buildConfig')\n return null\n }\n\n // Get initializer (the object value)\n const initializer = figmaProperty.getInitializer()\n if (!initializer || !Node.isObjectLiteralExpression(initializer)) {\n log.debug('figma property is not an object literal')\n return null\n }\n\n // Extract values\n const contentSystemIdProp = initializer.getProperty('contentSystemId')\n const useContentSystemProp = initializer.getProperty('useContentSystem')\n\n if (!contentSystemIdProp) {\n log.debug('Missing required figma property: contentSystemId')\n return null\n }\n\n // Extract contentSystemId - support both literal strings and env var references\n let contentSystemId: string | undefined\n if (Node.isPropertyAssignment(contentSystemIdProp)) {\n const initializer = contentSystemIdProp.getInitializer()\n const text = initializer?.getText() || ''\n\n // Support both patterns:\n // 1. Literal string: 'cms_abc123' or \"cms_abc123\"\n // 2. Environment variable: process.env.FIGMA_CONTENT_SYSTEM_ID\n if (text.includes('process.env.FIGMA_CONTENT_SYSTEM_ID')) {\n // For env var reference, return a marker that indicates it's from env\n // The actual value will be read at runtime\n contentSystemId = 'process.env.FIGMA_CONTENT_SYSTEM_ID'\n } else {\n // Remove quotes for literal strings\n contentSystemId = text.replace(/['\"]/g, '')\n }\n }\n\n const useContentSystem = Node.isPropertyAssignment(useContentSystemProp)\n ? useContentSystemProp.getInitializer()?.getText() === 'true'\n : undefined // Optional: undefined if not specified\n\n if (!contentSystemId) {\n log.debug('Could not extract contentSystemId value')\n return null\n }\n\n return {\n contentSystemId,\n useContentSystem,\n }\n}\n"],"names":["Node","SyntaxKind","log","detectRequiredChanges","sourceFile","result","figmaObjectExists","hasAlias","hasOtherPayloadImports","needsImportChange","imports","getImportDeclarations","payloadImport","find","imp","getModuleSpecifierValue","debug","hasBuildConfig","moduleSpecifier","namedImports","getNamedImports","buildConfigImport","ni","getName","aliasNode","getAliasNode","buildConfigName","getText","length","exportAssignment","getFirstDescendantByKind","ExportAssignment","buildConfigCall","callExpressions","getDescendantsOfKind","CallExpression","ce","expr","getExpression","configArg","getArguments","isObjectLiteralExpression","dbProperty","getProperty","dbValue","getChildrenOfKind","adapterName","adapterImport","some","adapter","importSource","secretProperty","editorProperty","editorValue","editorName","editorImport","args","isDefault","figmaProperty","removeAllComments","ranges","collectComments","node","getLeadingCommentRanges","forEach","range","push","getPos","getEnd","getTrailingCommentRanges","getChildren","uniqueRanges","Array","from","Set","map","r","JSON","stringify","parse","sort","a","b","pos","end","removeText","applyModifications","detection","changes","modified","hadComments","remove","addImportDeclaration","setModuleSpecifier","currentImports","dbImport","addFigmaProperty","config","text","endsWith","existingFigmaProperty","figmaObj","useContentSystem","addPropertyAssignment","name","initializer","contentSystemId","readFigmaConfig","isPropertyAssignment","getInitializer","contentSystemIdProp","useContentSystemProp","includes","replace","undefined"],"mappings":"AAEA,SAASA,IAAI,EAAEC,UAAU,QAAQ,WAAU;AAE3C,YAAYC,SAAS,WAAU;AAmB/B;;CAEC,GACD,OAAO,SAASC,sBAAsBC,UAAsB;IAC1D,MAAMC,SAA0B;QAC9BC,mBAAmB;QACnBC,UAAU;QACVC,wBAAwB;QACxBC,mBAAmB;IACrB;IAEA,0BAA0B;IAC1B,MAAMC,UAAUN,WAAWO,qBAAqB;IAChD,MAAMC,gBAAgBF,QAAQG,IAAI,CAChC,CAACC,MACCA,IAAIC,uBAAuB,OAAO,aAClCD,IAAIC,uBAAuB,OAAO;IAGtC,IAAI,CAACH,eAAe;QAClBV,IAAIc,KAAK,CAAC;QACVX,OAAOY,cAAc,GAAG;QACxB,OAAOZ;IACT;IAEAH,IAAIc,KAAK,CAAC,CAAC,mBAAmB,EAAEJ,cAAcG,uBAAuB,IAAI;IAEzE,MAAMG,kBAAkBN,cAAcG,uBAAuB;IAC7D,MAAMI,eAAeP,cAAcQ,eAAe;IAElD,mCAAmC;IACnC,MAAMC,oBAAoBF,aAAaN,IAAI,CAAC,CAACS,KAAOA,GAAGC,OAAO,OAAO;IAErE,IAAI,CAACF,mBAAmB;QACtBhB,OAAOY,cAAc,GAAG;QACxB,OAAOZ;IACT;IAEA,uDAAuD;IACvD,MAAMmB,YAAYH,kBAAkBI,YAAY;IAChD,MAAMC,kBAAkBF,YAAYA,UAAUG,OAAO,KAAK;IAC1D,IAAIH,WAAW;QACbnB,O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AAoB,CAAClD,gBAAgB;QAC/DxD,IAAIc,KAAK,CAAC;QACV,OAAO;IACT;IAEA,qCAAqC;IACrC,MAAMyF,cAAc/C,cAAcmD,cAAc;IAChD,IAAI,CAACJ,eAAe,CAACzG,KAAKyC,yBAAyB,CAACgE,cAAc;QAChEvG,IAAIc,KAAK,CAAC;QACV,OAAO;IACT;IAEA,iBAAiB;IACjB,MAAM8F,sBAAsBL,YAAY9D,WAAW,CAAC;IACpD,MAAMoE,uBAAuBN,YAAY9D,WAAW,CAAC;IAErD,IAAI,CAACmE,qBAAqB;QACxB5G,IAAIc,KAAK,CAAC;QACV,OAAO;IACT;IAEA,gFAAgF;IAChF,IAAI0F;IACJ,IAAI1G,KAAK4G,oBAAoB,CAACE,sBAAsB;QAClD,MAAML,cAAcK,oBAAoBD,cAAc;QACtD,MAAMX,OAAOO,aAAa9E,aAAa;QAEvC,yBAAyB;QACzB,kDAAkD;QAClD,+DAA+D;QAC/D,IAAIuE,KAAKc,QAAQ,CAAC,wCAAwC;YACxD,sEAAsE;YACtE,2CAA2C;YAC3CN,kBAAkB;QACpB,OAAO;YACL,oCAAoC;YACpCA,kBAAkBR,KAAKe,OAAO,CAAC,SAAS;QAC1C;IACF;IAEA,MAAMX,mBAAmBtG,KAAK4G,oBAAoB,CAACG,wBAC/CA,qBAAqBF,cAAc,IAAIlF,cAAc,SACrDuF,UAAU,uCAAuC;;IAErD,IAAI,CAACR,iBAAiB;QACpBxG,IAAIc,KAAK,CAAC;QACV,OAAO;IACT;IAEA,OAAO;QACL0F;QACAJ;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project.d.ts","sourceRoot":"","sources":["../../src/utils/project.ts"],"names":[],"mappings":"AAAA;;GAEG;AAMH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAA;
|
|
1
|
+
{"version":3,"file":"project.d.ts","sourceRoot":"","sources":["../../src/utils/project.ts"],"names":[],"mappings":"AAAA;;GAEG;AAMH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAA;AAOrD;;;;;GAKG;AACH,wBAAsB,oBAAoB,CACxC,WAAW,GAAE,MAAsB,GAClC,OAAO,CAAC,WAAW,CAAC,CAwCtB;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAS/D;AAiED;;;;;GAKG;AACH,wBAAsB,eAAe,CAAC,WAAW,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAwC7F;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAE3D;AAED;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CACvC,WAAW,EAAE,MAAM,EACnB,cAAc,GAAE,KAAK,GAAG,MAAM,GAAG,MAAc,GAC9C,OAAO,CAAC,IAAI,CAAC,CAsCf;AAED;;;;;GAKG;AACH,wBAAsB,uBAAuB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAenF;AAED;;;;;;;GAOG;AACH,wBAAsB,oBAAoB,CAAC,WAAW,GAAE,MAAsB,GAAG,OAAO,CAAC,OAAO,CAAC,CAQhG"}
|
package/dist/utils/project.js
CHANGED
|
@@ -5,7 +5,6 @@ import fs from 'fs/promises';
|
|
|
5
5
|
import path from 'path';
|
|
6
6
|
import { ensureGitignore } from './config.js';
|
|
7
7
|
import { downloadTemplateFromGitHub } from './download-template.js';
|
|
8
|
-
import { manageEnvFiles } from './env-management.js';
|
|
9
8
|
import { tryInitRepoAndCommit } from './git.js';
|
|
10
9
|
import { applyLambdaModifications } from './lambda-config.js';
|
|
11
10
|
/**
|
|
@@ -151,9 +150,8 @@ import { applyLambdaModifications } from './lambda-config.js';
|
|
|
151
150
|
// Replace workspace:* versions with actual versions
|
|
152
151
|
replaceWorkspaceVersions(packageJson, latestVersion);
|
|
153
152
|
await fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\n', 'utf-8');
|
|
154
|
-
// Manage environment files (generate PAYLOAD_SECRET)
|
|
155
|
-
await manageEnvFiles(projectPath);
|
|
156
153
|
// Ensure .gitignore has required entries
|
|
154
|
+
// Note: .env file is created by init command with FIGMA_CONTENT_SYSTEM_ID
|
|
157
155
|
await ensureGitignore(projectPath, [
|
|
158
156
|
'.env',
|
|
159
157
|
'.env.local',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/project.ts"],"sourcesContent":["/**\n * Project detection and scaffolding utilities\n */\n\nimport { spawn } from 'child_process'\nimport fs from 'fs/promises'\nimport path from 'path'\n\nimport type { ProjectInfo } from '../types/config.js'\n\nimport { ensureGitignore } from './config.js'\nimport { downloadTemplateFromGitHub } from './download-template.js'\nimport { manageEnvFiles } from './env-management.js'\nimport { tryInitRepoAndCommit } from './git.js'\nimport { applyLambdaModifications } from './lambda-config.js'\n\n/**\n * Detect if current directory has a Payload project\n *\n * @param projectPath - Path to check (defaults to cwd)\n * @returns Project information\n */\nexport async function detectPayloadProject(\n projectPath: string = process.cwd(),\n): Promise<ProjectInfo> {\n const packageJsonPath = path.join(projectPath, 'package.json')\n\n try {\n const content = await fs.readFile(packageJsonPath, 'utf-8')\n const packageJson = JSON.parse(content)\n\n // Check for payload in dependencies or devDependencies\n const payloadVersion = packageJson.dependencies?.payload || packageJson.devDependencies?.payload\n\n // Detect package manager\n let packageManager: 'npm' | 'pnpm' | 'yarn' = 'npm'\n try {\n await fs.access(path.join(projectPath, 'pnpm-lock.yaml'))\n packageManager = 'pnpm'\n } catch {\n try {\n await fs.access(path.join(projectPath, 'yarn.lock'))\n packageManager = 'yarn'\n } catch {\n packageManager = 'npm'\n }\n }\n\n return {\n hasPayload: !!payloadVersion,\n packageManager,\n path: projectPath,\n payloadVersion: payloadVersion || undefined,\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // No package.json found\n return {\n hasPayload: false,\n path: projectPath,\n }\n }\n throw new Error(`Failed to read package.json: ${(error as Error).message}`)\n }\n}\n\n/**\n * Validate Payload version (must be 3.x)\n *\n * @param version - Version string from package.json\n * @returns True if version is valid\n */\nexport function validatePayloadVersion(version: string): boolean {\n // Extract major version (handle ^3.0.0, ~3.0.0, 3.0.0, etc.)\n const match = version.match(/(\\d+)/)\n if (!match) {\n return false\n }\n\n const majorVersion = parseInt(match[1], 10)\n return majorVersion === 3\n}\n\n/**\n * Fetch the latest version of a package from npm registry\n *\n * @param packageName - Package name to fetch version for\n * @returns Latest version string\n */\nasync function getLatestPackageVersion(packageName: string): Promise<string> {\n const response = await fetch(`https://registry.npmjs.org/-/package/${packageName}/dist-tags`)\n\n if (!response.ok) {\n throw new Error(`Failed to fetch version for ${packageName}: ${response.statusText}`)\n }\n\n const data = (await response.json()) as Record<string, unknown>\n\n if (typeof data.latest !== 'string') {\n throw new Error(`Invalid version data received for ${packageName}`)\n }\n\n return data.latest\n}\n\n/**\n * Replace workspace versions in package.json with actual versions\n *\n * @param packageJson - Package JSON object to update\n * @param latestVersion - Latest Payload version to use\n */\nfunction replaceWorkspaceVersions(\n packageJson: Record<string, unknown>,\n latestVersion: string,\n): void {\n const deps = packageJson.dependencies as Record<string, string> | undefined\n if (!deps) {\n return\n }\n\n for (const [key, value] of Object.entries(deps)) {\n // Replace workspace:* or workspace:^ with actual version\n if (typeof value === 'string' && value.startsWith('workspace:')) {\n deps[key] = latestVersion\n }\n // Ensure all payload packages use the same version\n else if (key === 'payload' || key.startsWith('@payloadcms/')) {\n deps[key] = latestVersion\n }\n }\n\n // Also handle devDependencies if present\n const devDeps = packageJson.devDependencies as Record<string, string> | undefined\n if (!devDeps) {\n return\n }\n\n for (const [key, value] of Object.entries(devDeps)) {\n if (typeof value === 'string' && value.startsWith('workspace:')) {\n devDeps[key] = latestVersion\n } else if (key === 'payload' || key.startsWith('@payloadcms/')) {\n devDeps[key] = latestVersion\n }\n }\n}\n\n/**\n * Scaffold a new Payload project from GitHub template\n *\n * @param projectPath - Path where to create the project\n * @param projectName - Name for the project\n */\nexport async function scaffoldProject(projectPath: string, projectName: string): Promise<void> {\n // Create project directory if it doesn't exist\n await fs.mkdir(projectPath, { recursive: true })\n\n // Download template from GitHub\n await downloadTemplateFromGitHub(projectPath)\n\n // Apply Lambda modifications BEFORE updating package.json\n // This ensures we don't overwrite version replacements\n await applyLambdaModifications(projectPath)\n\n // Get latest Payload version from npm\n const latestVersion = await getLatestPackageVersion('payload')\n\n // Delete any existing lock files from template (they reference workspace:* versions)\n // This ensures pnpm install creates a fresh lock file with actual versions\n const lockFiles = ['pnpm-lock.yaml', 'yarn.lock', 'package-lock.json']\n for (const lockFile of lockFiles) {\n try {\n await fs.unlink(path.join(projectPath, lockFile))\n } catch {\n // File doesn't exist, ignore\n }\n }\n\n // Update package.json: set name, replace workspace versions\n // This must come AFTER applyLambdaModifications to ensure we have final versions\n const packageJsonPath = path.join(projectPath, 'package.json')\n const packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8')\n const packageJson = JSON.parse(packageJsonContent) as Record<string, unknown>\n packageJson.name = projectName\n\n // Replace workspace:* versions with actual versions\n replaceWorkspaceVersions(packageJson, latestVersion)\n\n await fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\\n', 'utf-8')\n\n // Manage environment files (generate PAYLOAD_SECRET)\n await manageEnvFiles(projectPath)\n\n // Ensure .gitignore has required entries\n await ensureGitignore(projectPath, ['.env', '.env.local', 'lambda.zip'])\n}\n\n/**\n * Initialize git repository after all setup is complete\n *\n * This should be called AFTER installDependencies so that lock files are included\n *\n * @param projectPath - Path to project directory\n */\nexport function initializeGitRepo(projectPath: string): void {\n tryInitRepoAndCommit(projectPath)\n}\n\n/**\n * Install dependencies using the detected package manager\n *\n * @param projectPath - Path to project\n * @param packageManager - Package manager to use\n * @returns Promise that resolves when installation completes\n */\nexport async function installDependencies(\n projectPath: string,\n packageManager: 'npm' | 'pnpm' | 'yarn' = 'npm',\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(packageManager, ['install'], {\n cwd: projectPath,\n shell: true,\n stdio: 'pipe', // Capture output to avoid interfering with spinner\n })\n\n let stdout = ''\n let stderr = ''\n\n // Capture stdout\n child.stdout?.on('data', (data) => {\n stdout += data.toString()\n })\n\n // Capture stderr\n child.stderr?.on('data', (data) => {\n stderr += data.toString()\n })\n\n child.on('close', (code) => {\n if (code === 0) {\n resolve()\n } else {\n // Show captured output on error\n const output = [stdout, stderr].filter(Boolean).join('\\n\\n')\n const errorMessage = output\n ? `${packageManager} install failed with code ${code}\\n\\nOutput:\\n${output}`\n : `${packageManager} install failed with code ${code}`\n reject(new Error(errorMessage))\n }\n })\n\n child.on('error', (error) => {\n reject(new Error(`Failed to run ${packageManager} install: ${error.message}`))\n })\n })\n}\n\n/**\n * Check if required dependencies are installed\n *\n * @param projectPath - Path to project\n * @returns True if all required dependencies exist\n */\nexport async function hasRequiredDependencies(projectPath: string): Promise<boolean> {\n const packageJsonPath = path.join(projectPath, 'package.json')\n\n try {\n const content = await fs.readFile(packageJsonPath, 'utf-8')\n const packageJson = JSON.parse(content)\n\n // Check for Payload and Next.js\n const hasPayload = packageJson.dependencies?.payload || packageJson.devDependencies?.payload\n const hasNext = packageJson.dependencies?.next || packageJson.devDependencies?.next\n\n return !!(hasPayload && hasNext)\n } catch {\n return false\n }\n}\n\n/**\n * Check if current directory is a project directory\n *\n * A project directory has package.json\n *\n * @param projectPath - Path to check (defaults to cwd)\n * @returns True if in project directory\n */\nexport async function isInProjectDirectory(projectPath: string = process.cwd()): Promise<boolean> {\n try {\n // Check for package.json\n await fs.access(path.join(projectPath, 'package.json'))\n return true\n } catch {\n return false\n }\n}\n"],"names":["spawn","fs","path","ensureGitignore","downloadTemplateFromGitHub","manageEnvFiles","tryInitRepoAndCommit","applyLambdaModifications","detectPayloadProject","projectPath","process","cwd","packageJsonPath","join","content","readFile","packageJson","JSON","parse","payloadVersion","dependencies","payload","devDependencies","packageManager","access","hasPayload","undefined","error","code","Error","message","validatePayloadVersion","version","match","majorVersion","parseInt","getLatestPackageVersion","packageName","response","fetch","ok","statusText","data","json","latest","replaceWorkspaceVersions","latestVersion","deps","key","value","Object","entries","startsWith","devDeps","scaffoldProject","projectName","mkdir","recursive","lockFiles","lockFile","unlink","packageJsonContent","name","writeFile","stringify","initializeGitRepo","installDependencies","Promise","resolve","reject","child","shell","stdio","stdout","stderr","on","toString","output","filter","Boolean","errorMessage","hasRequiredDependencies","hasNext","next","isInProjectDirectory"],"mappings":"AAAA;;CAEC,GAED,SAASA,KAAK,QAAQ,gBAAe;AACrC,OAAOC,QAAQ,cAAa;AAC5B,OAAOC,UAAU,OAAM;AAIvB,SAASC,eAAe,QAAQ,cAAa;AAC7C,SAASC,0BAA0B,QAAQ,yBAAwB;AACnE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,oBAAoB,QAAQ,WAAU;AAC/C,SAASC,wBAAwB,QAAQ,qBAAoB;AAE7D;;;;;CAKC,GACD,OAAO,eAAeC,qBACpBC,cAAsBC,QAAQC,GAAG,EAAE;IAEnC,MAAMC,kBAAkBV,KAAKW,IAAI,CAACJ,aAAa;IAE/C,IAAI;QACF,MAAMK,UAAU,MAAMb,GAAGc,QAAQ,CAACH,iBAAiB;QACnD,MAAMI,cAAcC,KAAKC,KAAK,CAACJ;QAE/B,uDAAuD;QACvD,MAAMK,iBAAiBH,YAAYI,YAAY,EAAEC,WAAWL,YAAYM,eAAe,EAAED;QAEzF,yBAAyB;QACzB,IAAIE,iBAA0C;QAC9C,IAAI;YACF,MAAMtB,GAAGuB,MAAM,CAACtB,KAAKW,IAAI,CAACJ,aAAa;YACvCc,iBAAiB;QACnB,EAAE,OAAM;YACN,IAAI;gBACF,MAAMtB,GAAGuB,MAAM,CAACtB,KAAKW,IAAI,CAACJ,aAAa;gBACvCc,iBAAiB;YACnB,EAAE,OAAM;gBACNA,iBAAiB;YACnB;QACF;QAEA,OAAO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,EAAEI,MAAMG,OAAO,EAAE;QAC9E;IACF;AACF;AAEA;;;;;CAKC,GACD,OAAO,eAAemD,wBAAwBxE,WAAmB;IAC/D,MAAMG,kBAAkBV,KAAKW,IAAI,CAACJ,aAAa;IAE/C,IAAI;QACF,MAAMK,UAAU,MAAMb,GAAGc,QAAQ,CAACH,iBAAiB;QACnD,MAAMI,cAAcC,KAAKC,KAAK,CAACJ;QAE/B,gCAAgC;QAChC,MAAMW,aAAaT,YAAYI,YAAY,EAAEC,WAAWL,YAAYM,eAAe,EAAED;QACrF,MAAM6D,UAAUlE,YAAYI,YAAY,EAAE+D,QAAQnE,YAAYM,eAAe,EAAE6D;QAE/E,OAAO,CAAC,CAAE1D,CAAAA,cAAcyD,OAAM;IAChC,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeE,qBAAqB3E,cAAsBC,QAAQC,GAAG,EAAE;IAC5E,IAAI;QACF,yBAAyB;QACzB,MAAMV,GAAGuB,MAAM,CAACtB,KAAKW,IAAI,CAACJ,aAAa;QACvC,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/project.ts"],"sourcesContent":["/**\n * Project detection and scaffolding utilities\n */\n\nimport { spawn } from 'child_process'\nimport fs from 'fs/promises'\nimport path from 'path'\n\nimport type { ProjectInfo } from '../types/config.js'\n\nimport { ensureGitignore } from './config.js'\nimport { downloadTemplateFromGitHub } from './download-template.js'\nimport { tryInitRepoAndCommit } from './git.js'\nimport { applyLambdaModifications } from './lambda-config.js'\n\n/**\n * Detect if current directory has a Payload project\n *\n * @param projectPath - Path to check (defaults to cwd)\n * @returns Project information\n */\nexport async function detectPayloadProject(\n projectPath: string = process.cwd(),\n): Promise<ProjectInfo> {\n const packageJsonPath = path.join(projectPath, 'package.json')\n\n try {\n const content = await fs.readFile(packageJsonPath, 'utf-8')\n const packageJson = JSON.parse(content)\n\n // Check for payload in dependencies or devDependencies\n const payloadVersion = packageJson.dependencies?.payload || packageJson.devDependencies?.payload\n\n // Detect package manager\n let packageManager: 'npm' | 'pnpm' | 'yarn' = 'npm'\n try {\n await fs.access(path.join(projectPath, 'pnpm-lock.yaml'))\n packageManager = 'pnpm'\n } catch {\n try {\n await fs.access(path.join(projectPath, 'yarn.lock'))\n packageManager = 'yarn'\n } catch {\n packageManager = 'npm'\n }\n }\n\n return {\n hasPayload: !!payloadVersion,\n packageManager,\n path: projectPath,\n payloadVersion: payloadVersion || undefined,\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // No package.json found\n return {\n hasPayload: false,\n path: projectPath,\n }\n }\n throw new Error(`Failed to read package.json: ${(error as Error).message}`)\n }\n}\n\n/**\n * Validate Payload version (must be 3.x)\n *\n * @param version - Version string from package.json\n * @returns True if version is valid\n */\nexport function validatePayloadVersion(version: string): boolean {\n // Extract major version (handle ^3.0.0, ~3.0.0, 3.0.0, etc.)\n const match = version.match(/(\\d+)/)\n if (!match) {\n return false\n }\n\n const majorVersion = parseInt(match[1], 10)\n return majorVersion === 3\n}\n\n/**\n * Fetch the latest version of a package from npm registry\n *\n * @param packageName - Package name to fetch version for\n * @returns Latest version string\n */\nasync function getLatestPackageVersion(packageName: string): Promise<string> {\n const response = await fetch(`https://registry.npmjs.org/-/package/${packageName}/dist-tags`)\n\n if (!response.ok) {\n throw new Error(`Failed to fetch version for ${packageName}: ${response.statusText}`)\n }\n\n const data = (await response.json()) as Record<string, unknown>\n\n if (typeof data.latest !== 'string') {\n throw new Error(`Invalid version data received for ${packageName}`)\n }\n\n return data.latest\n}\n\n/**\n * Replace workspace versions in package.json with actual versions\n *\n * @param packageJson - Package JSON object to update\n * @param latestVersion - Latest Payload version to use\n */\nfunction replaceWorkspaceVersions(\n packageJson: Record<string, unknown>,\n latestVersion: string,\n): void {\n const deps = packageJson.dependencies as Record<string, string> | undefined\n if (!deps) {\n return\n }\n\n for (const [key, value] of Object.entries(deps)) {\n // Replace workspace:* or workspace:^ with actual version\n if (typeof value === 'string' && value.startsWith('workspace:')) {\n deps[key] = latestVersion\n }\n // Ensure all payload packages use the same version\n else if (key === 'payload' || key.startsWith('@payloadcms/')) {\n deps[key] = latestVersion\n }\n }\n\n // Also handle devDependencies if present\n const devDeps = packageJson.devDependencies as Record<string, string> | undefined\n if (!devDeps) {\n return\n }\n\n for (const [key, value] of Object.entries(devDeps)) {\n if (typeof value === 'string' && value.startsWith('workspace:')) {\n devDeps[key] = latestVersion\n } else if (key === 'payload' || key.startsWith('@payloadcms/')) {\n devDeps[key] = latestVersion\n }\n }\n}\n\n/**\n * Scaffold a new Payload project from GitHub template\n *\n * @param projectPath - Path where to create the project\n * @param projectName - Name for the project\n */\nexport async function scaffoldProject(projectPath: string, projectName: string): Promise<void> {\n // Create project directory if it doesn't exist\n await fs.mkdir(projectPath, { recursive: true })\n\n // Download template from GitHub\n await downloadTemplateFromGitHub(projectPath)\n\n // Apply Lambda modifications BEFORE updating package.json\n // This ensures we don't overwrite version replacements\n await applyLambdaModifications(projectPath)\n\n // Get latest Payload version from npm\n const latestVersion = await getLatestPackageVersion('payload')\n\n // Delete any existing lock files from template (they reference workspace:* versions)\n // This ensures pnpm install creates a fresh lock file with actual versions\n const lockFiles = ['pnpm-lock.yaml', 'yarn.lock', 'package-lock.json']\n for (const lockFile of lockFiles) {\n try {\n await fs.unlink(path.join(projectPath, lockFile))\n } catch {\n // File doesn't exist, ignore\n }\n }\n\n // Update package.json: set name, replace workspace versions\n // This must come AFTER applyLambdaModifications to ensure we have final versions\n const packageJsonPath = path.join(projectPath, 'package.json')\n const packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8')\n const packageJson = JSON.parse(packageJsonContent) as Record<string, unknown>\n packageJson.name = projectName\n\n // Replace workspace:* versions with actual versions\n replaceWorkspaceVersions(packageJson, latestVersion)\n\n await fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\\n', 'utf-8')\n\n // Ensure .gitignore has required entries\n // Note: .env file is created by init command with FIGMA_CONTENT_SYSTEM_ID\n await ensureGitignore(projectPath, ['.env', '.env.local', 'lambda.zip'])\n}\n\n/**\n * Initialize git repository after all setup is complete\n *\n * This should be called AFTER installDependencies so that lock files are included\n *\n * @param projectPath - Path to project directory\n */\nexport function initializeGitRepo(projectPath: string): void {\n tryInitRepoAndCommit(projectPath)\n}\n\n/**\n * Install dependencies using the detected package manager\n *\n * @param projectPath - Path to project\n * @param packageManager - Package manager to use\n * @returns Promise that resolves when installation completes\n */\nexport async function installDependencies(\n projectPath: string,\n packageManager: 'npm' | 'pnpm' | 'yarn' = 'npm',\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(packageManager, ['install'], {\n cwd: projectPath,\n shell: true,\n stdio: 'pipe', // Capture output to avoid interfering with spinner\n })\n\n let stdout = ''\n let stderr = ''\n\n // Capture stdout\n child.stdout?.on('data', (data) => {\n stdout += data.toString()\n })\n\n // Capture stderr\n child.stderr?.on('data', (data) => {\n stderr += data.toString()\n })\n\n child.on('close', (code) => {\n if (code === 0) {\n resolve()\n } else {\n // Show captured output on error\n const output = [stdout, stderr].filter(Boolean).join('\\n\\n')\n const errorMessage = output\n ? `${packageManager} install failed with code ${code}\\n\\nOutput:\\n${output}`\n : `${packageManager} install failed with code ${code}`\n reject(new Error(errorMessage))\n }\n })\n\n child.on('error', (error) => {\n reject(new Error(`Failed to run ${packageManager} install: ${error.message}`))\n })\n })\n}\n\n/**\n * Check if required dependencies are installed\n *\n * @param projectPath - Path to project\n * @returns True if all required dependencies exist\n */\nexport async function hasRequiredDependencies(projectPath: string): Promise<boolean> {\n const packageJsonPath = path.join(projectPath, 'package.json')\n\n try {\n const content = await fs.readFile(packageJsonPath, 'utf-8')\n const packageJson = JSON.parse(content)\n\n // Check for Payload and Next.js\n const hasPayload = packageJson.dependencies?.payload || packageJson.devDependencies?.payload\n const hasNext = packageJson.dependencies?.next || packageJson.devDependencies?.next\n\n return !!(hasPayload && hasNext)\n } catch {\n return false\n }\n}\n\n/**\n * Check if current directory is a project directory\n *\n * A project directory has package.json\n *\n * @param projectPath - Path to check (defaults to cwd)\n * @returns True if in project directory\n */\nexport async function isInProjectDirectory(projectPath: string = process.cwd()): Promise<boolean> {\n try {\n // Check for package.json\n await fs.access(path.join(projectPath, 'package.json'))\n return true\n } catch {\n return false\n }\n}\n"],"names":["spawn","fs","path","ensureGitignore","downloadTemplateFromGitHub","tryInitRepoAndCommit","applyLambdaModifications","detectPayloadProject","projectPath","process","cwd","packageJsonPath","join","content","readFile","packageJson","JSON","parse","payloadVersion","dependencies","payload","devDependencies","packageManager","access","hasPayload","undefined","error","code","Error","message","validatePayloadVersion","version","match","majorVersion","parseInt","getLatestPackageVersion","packageName","response","fetch","ok","statusText","data","json","latest","replaceWorkspaceVersions","latestVersion","deps","key","value","Object","entries","startsWith","devDeps","scaffoldProject","projectName","mkdir","recursive","lockFiles","lockFile","unlink","packageJsonContent","name","writeFile","stringify","initializeGitRepo","installDependencies","Promise","resolve","reject","child","shell","stdio","stdout","stderr","on","toString","output","filter","Boolean","errorMessage","hasRequiredDependencies","hasNext","next","isInProjectDirectory"],"mappings":"AAAA;;CAEC,GAED,SAASA,KAAK,QAAQ,gBAAe;AACrC,OAAOC,QAAQ,cAAa;AAC5B,OAAOC,UAAU,OAAM;AAIvB,SAASC,eAAe,QAAQ,cAAa;AAC7C,SAASC,0BAA0B,QAAQ,yBAAwB;AACnE,SAASC,oBAAoB,QAAQ,WAAU;AAC/C,SAASC,wBAAwB,QAAQ,qBAAoB;AAE7D;;;;;CAKC,GACD,OAAO,eAAeC,qBACpBC,cAAsBC,QAAQC,GAAG,EAAE;IAEnC,MAAMC,kBAAkBT,KAAKU,IAAI,CAACJ,aAAa;IAE/C,IAAI;QACF,MAAMK,UAAU,MAAMZ,GAAGa,QAAQ,CAACH,iBAAiB;QACnD,MAAMI,cAAcC,KAAKC,KAAK,CAACJ;QAE/B,uDAAuD;QACvD,MAAMK,iBAAiBH,YAAY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AAO,CAACI,MAAM,CAACC,SAASlE,IAAI,CAAC;gBACrD,MAAMmE,eAAeH,SACjB,GAAGtD,eAAe,0BAA0B,EAAEK,KAAK,aAAa,EAAEiD,QAAQ,GAC1E,GAAGtD,eAAe,0BAA0B,EAAEK,MAAM;gBACxDyC,OAAO,IAAIxC,MAAMmD;YACnB;QACF;QAEAV,MAAMK,EAAE,CAAC,SAAS,CAAChD;YACjB0C,OAAO,IAAIxC,MAAM,CAAC,cAAc,EAAEN,eAAe,UAAU,EAAEI,MAAMG,OAAO,EAAE;QAC9E;IACF;AACF;AAEA;;;;;CAKC,GACD,OAAO,eAAemD,wBAAwBxE,WAAmB;IAC/D,MAAMG,kBAAkBT,KAAKU,IAAI,CAACJ,aAAa;IAE/C,IAAI;QACF,MAAMK,UAAU,MAAMZ,GAAGa,QAAQ,CAACH,iBAAiB;QACnD,MAAMI,cAAcC,KAAKC,KAAK,CAACJ;QAE/B,gCAAgC;QAChC,MAAMW,aAAaT,YAAYI,YAAY,EAAEC,WAAWL,YAAYM,eAAe,EAAED;QACrF,MAAM6D,UAAUlE,YAAYI,YAAY,EAAE+D,QAAQnE,YAAYM,eAAe,EAAE6D;QAE/E,OAAO,CAAC,CAAE1D,CAAAA,cAAcyD,OAAM;IAChC,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeE,qBAAqB3E,cAAsBC,QAAQC,GAAG,EAAE;IAC5E,IAAI;QACF,yBAAyB;QACzB,MAAMT,GAAGsB,MAAM,CAACrB,KAAKU,IAAI,CAACJ,aAAa;QACvC,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
|
|
@@ -18,7 +18,6 @@ export interface UploadResults {
|
|
|
18
18
|
*
|
|
19
19
|
* @param filePath - Absolute path to file to upload
|
|
20
20
|
* @param signedUrl - Signed S3 upload URL
|
|
21
|
-
* @param contentType - MIME type (optional)
|
|
22
21
|
* @throws Error if upload fails after retries
|
|
23
22
|
*/
|
|
24
23
|
export declare function uploadFile(filePath: string, signedUrl: string, contentType?: string): Promise<void>;
|