@figma/code-connect 1.4.5 → 1.4.8
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/cli.js +0 -1
- package/dist/cli.js.map +1 -1
- package/dist/client/figma_client.d.ts +6 -6
- package/dist/commands/connect.d.ts +4 -1
- package/dist/commands/connect.d.ts.map +1 -1
- package/dist/commands/connect.js +107 -25
- package/dist/commands/connect.js.map +1 -1
- package/dist/commands/connect_template.d.ts +2 -2
- package/dist/commands/connect_template.d.ts.map +1 -1
- package/dist/commands/connect_template.js +11 -2
- package/dist/commands/connect_template.js.map +1 -1
- package/dist/commands/filter_project_info.d.ts +3 -3
- package/dist/commands/filter_project_info.d.ts.map +1 -1
- package/dist/commands/filter_project_info.js +18 -12
- package/dist/commands/filter_project_info.js.map +1 -1
- package/dist/common/logging.d.ts.map +1 -1
- package/dist/common/logging.js +13 -6
- package/dist/common/logging.js.map +1 -1
- package/dist/common/updates.d.ts.map +1 -1
- package/dist/common/updates.js +2 -2
- package/dist/common/updates.js.map +1 -1
- package/dist/connect/migration_batch_helpers.d.ts +45 -0
- package/dist/connect/migration_batch_helpers.d.ts.map +1 -0
- package/dist/connect/migration_batch_helpers.js +439 -0
- package/dist/connect/migration_batch_helpers.js.map +1 -0
- package/dist/connect/migration_helpers.d.ts +4 -0
- package/dist/connect/migration_helpers.d.ts.map +1 -1
- package/dist/connect/migration_helpers.js +29 -5
- package/dist/connect/migration_helpers.js.map +1 -1
- package/dist/connect/parser_executable_types.d.ts +60 -60
- package/dist/connect/project.d.ts +2 -1
- package/dist/connect/project.d.ts.map +1 -1
- package/dist/connect/project.js +26 -24
- package/dist/connect/project.js.map +1 -1
- package/dist/connect/raw_templates.d.ts +10 -0
- package/dist/connect/raw_templates.d.ts.map +1 -1
- package/dist/connect/raw_templates.js +48 -14
- package/dist/connect/raw_templates.js.map +1 -1
- package/dist/connect/upload.d.ts.map +1 -1
- package/dist/connect/upload.js +24 -8
- package/dist/connect/upload.js.map +1 -1
- package/dist/connect/wizard/helpers.d.ts.map +1 -1
- package/dist/connect/wizard/helpers.js +7 -2
- package/dist/connect/wizard/helpers.js.map +1 -1
- package/figma-types.d.ts +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project.js","sourceRoot":"","sources":["../../src/connect/project.ts"],"names":[],"mappings":";;;;;;AAwJA,gEAyBC;AAgFD,8DAuCC;AA0ID,0CAWC;AAKD,wDAkBC;AAKD,kEA8CC;AAQD,4CAmDC;AAED,0CAoBC;AAiCD,oDAEC;AAED,gCAEC;AAED,wDA6CC;AAKD,kDAoCC;AASD,4DAkEC;AA2BD,wCAWC;AAED,kDASC;AAED,oCAcC;AAUD,sCAoDC;AAYD,gDAuBC;AAp8BD,iDAAyC;AACzC,+BAA+B;AAC/B,gDAAuB;AACvB,4CAAmB;AACnB,4DAA2B;AAC3B,+CAAyD;AACzD,kDAAyB;AACzB,wDAA+B;AAC/B,yEAAyE;AACzE,sDAA4B;AAC5B,uCAAmD;AACnD,qEAAoF;AAEpF,MAAM,wBAAwB,GAAG,mBAAmB,CAAA;AACpD,MAAM,aAAa,GAAG,MAAM,CAAA;AAEf,QAAA,+BAA+B,GAAG;IAC7C,KAAK,EAAE,CAAC,gBAAgB,CAAC;IACzB,IAAI,EAAE,CAAC,cAAc,CAAC;IACtB,KAAK,EAAE,CAAC,YAAY,CAAC;IACrB,OAAO,EAAE,CAAC,SAAS,CAAC;IACpB,iEAAiE;IACjE,MAAM,EAAE,SAAS;IACjB,aAAa,EAAE,CAAC,EAAE,CAAC;CACpB,CAAA;AAEY,QAAA,wBAAwB,GAA+C;IAClF,KAAK,EAAE,yCAAgB,CAAC,KAAK;IAC7B,IAAI,EAAE,yCAAgB,CAAC,aAAa;CACrC,CAAA;AA2HD,SAAgB,0BAA0B,CACxC,GAAW,EACX,WAAW,GAAG,IAAI,EAClB,kBAAkB,GAAG,KAAK;IAE1B,IAAI,kBAAkB,EAA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S,EAAE,CAAC;gBAC3B,MAAM,GAAG,WAAW,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;YAC7C,CAAC;YACD,OAAO,MAAM,CAAA;QACf,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC","sourcesContent":["import { spawnSync } from 'child_process'\nimport { globSync } from 'glob'\nimport path from 'path'\nimport fs from 'fs'\nimport ts from 'typescript'\nimport { exitWithError, logger } from '../common/logging'\nimport chalk from 'chalk'\nimport readline from 'readline'\n// We use an old version of this dep as I couldn't get ES modules working\nimport findUp from 'find-up'\nimport { exitWithFeedbackMessage } from './helpers'\nimport { CodeConnectLabel, SyntaxHighlightLanguage } from './label_language_mapping'\n\nconst DEFAULT_CONFIG_FILE_NAME = 'figma.config.json'\nconst ENV_FILE_NAME = '.env'\n\nexport const DEFAULT_INCLUDE_GLOBS_BY_PARSER = {\n react: [`**/*.{tsx,jsx}`],\n html: [`**/*.{ts,js}`],\n swift: ['**/*.swift'],\n compose: ['**/*.kt'],\n // include globs should be included in configs for custom parsers\n custom: undefined,\n __unit_test__: [''],\n}\n\nexport const DEFAULT_LABEL_PER_PARSER: Partial<Record<CodeConnectParser, string>> = {\n react: CodeConnectLabel.React,\n html: CodeConnectLabel.WebComponents,\n}\n\n// First party parsers which call into parser executables\nexport type CodeConnectExecutableParser = 'swift' | 'compose' | 'custom' | '__unit_test__'\n\n// React is a special case for now as we call it directly from the CLI rather\n// than via an executable for legacy reasons. We will migrate it to the\n// parser executable model.\nexport type CodeConnectParser = 'react' | 'html' | CodeConnectExecutableParser\n\nexport type BaseCodeConnectConfig = {\n /**\n * Specify glob patterns for files (relative to the project root) to be\n * included when looking for source files. If not specified, all files\n * (except any specified in `exclude`) will be included.\n */\n include?: string[]\n /**\n * Specify glob patterns for files (relative to the project root) to be\n * excluded when looking for source files. If not specified, only\n * `node_modules` will be excluded.\n */\n exclude?: string[]\n /**\n * Optional object of substitutions applied to document URLs (in the format {\n * fromString, toString }) for testing (e.g. remapping a production URL to a\n * staging URL). Not publicly documented.\n */\n documentUrlSubstitutions?: Record<string, string>\n /**\n * The parser name, if using an internal parser.\n */\n parser?: CodeConnectParser\n\n /**\n * Label to use for the uploaded code examples\n */\n label?: string\n\n /**\n * Language to use for syntax highlighting in the uploaded code examples.\n * If not specified, language is inferred from the label or parser type.\n */\n language?: SyntaxHighlightLanguage\n\n /**\n * The URL of the Figma file to use during the interactive setup wizard for connecting code components to Figma components.\n */\n interactiveSetupFigmaFileUrl?: string\n\n /**\n * Custom Figma API URL to use instead of https://api.figma.com/v1\n */\n apiUrl?: string\n\n /**\n * The default branch name for your repository. Code Connect uses this when generating source code\n * links in Figma. If not specified, Code Connect will attempt to determine this automatically.\n */\n defaultBranch?: string\n}\n\nexport type CodeConnectExecutableParserConfig = BaseCodeConnectConfig & {\n parser: CodeConnectExecutableParser\n}\n\nexport type CodeConnectCustomExecutableParserConfig = BaseCodeConnectConfig & {\n parser: 'custom'\n parserCommand: string\n}\n\n/**\n * React specific configuration\n */\nexport type CodeConnectReactConfig = BaseCodeConnectConfig & {\n parser: 'react'\n /**\n * Maps imports from their path on disk to the specified path.\n * This will rewrite the imports in generated code examples, so it works with\n * relative imports such as `import { Button } from \"./\"`.\n *\n * Example: { \"src/components/*\": \"@ui/components\" }\n * Would rewrite imports for components located in `src/components` to `@ui/components` in\n * generated code examples.\n * `import { Button } from \"./\"` -> `import { Button } from \"@ui/components/Button\"`\n */\n importPaths?: Record<string, string>\n /**\n * For import resolution - this is a temporary solution to support projects that use\n * pnpm workspaces, as the compiler doesn't seem to be able to resolve imports when\n * the package in node_modules is a symlink. Need to look into this more and find a\n * better solution.\n */\n paths?: Record<string, string[]>\n /**\n * Storybook specific configuration\n */\n storybook?: {\n /**\n * The URL of the Storybook instance for the project\n */\n url: string\n }\n}\n\nexport type CodeConnectHtmlConfig = BaseCodeConnectConfig & {}\n\nexport type CodeConnectParserlessConfig = BaseCodeConnectConfig & {\n parser: undefined\n}\n\nexport type CodeConnectConfig =\n | CodeConnectReactConfig\n | CodeConnectExecutableParserConfig\n | CodeConnectCustomExecutableParserConfig\n | CodeConnectHtmlConfig\n | BaseCodeConnectConfig\n | CodeConnectParserlessConfig\n\ninterface FigmaConfig {\n codeConnect?: CodeConnectConfig\n}\n\nexport function determineConfigFromProject(\n dir: string,\n exitOnError = true,\n isTemplatesOnlyCLI = false,\n): FigmaConfig | undefined {\n if (isTemplatesOnlyCLI) {\n const label = determineLabelFromProject(dir)\n return { codeConnect: label ? { label } : {} }\n }\n\n const parser = determineParserFromProject(dir)\n if (parser) {\n const label = determineLabelFromProject(dir)\n if (label) {\n return { codeConnect: { parser, label } }\n }\n\n return { codeConnect: { parser } }\n }\n\n if (exitOnError) {\n exitWithError(\n `Code Connect was not able to determine your project type, and no config file was found. Please ensure you are running Code Connect from your project root. You may need to create a config file specifying which parser to use. See https://github.com/figma/code-connect/ for instructions.`,\n )\n }\n}\n\nfunction showParserMessage(message: string) {\n logger.info(\n message +\n '. If this is incorrect, please check you are running Code Connect from your project root, or add a `parser` key to your config file. See https://github.com/figma/code-connect for more information.',\n )\n}\n\nfunction packageJsonContains(packageJson: any, dependency: string) {\n return (\n (packageJson.dependencies && packageJson.dependencies[dependency]) ||\n (packageJson.peerDependencies && packageJson.peerDependencies[dependency]) ||\n (packageJson.devDependencies && packageJson.devDependencies[dependency])\n )\n}\n\n// Walk up from the given directory looking for the first directory which\n// matches heuristics for the platforms we support. This means that e.g. if you\n// have a Swift project inside a React project, we'll detect Swift. This enables\n// users to run commands from anywhere inside their project, rather than having\n// to run from the root (the same way npm works).\nfunction determineParserFromProject(dir: string): CodeConnectParser | undefined {\n let parser: CodeConnectParser | undefined\n\n findUp.sync(\n (currentDir) => {\n const packageJsonPath = path.join(currentDir, 'package.json')\n\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n if (packageJsonContains(packageJson, 'react')) {\n showParserMessage(\n `Using \"react\" parser as package.json containing a \"react\" ${\n packageJson.dependencies && packageJson.dependencies['react']\n ? 'dependency'\n : 'peer dependency'\n } was found in ${currentDir}`,\n )\n parser = 'react'\n return findUp.stop\n } else {\n showParserMessage(\n `Using \"html\" parser as package.json containing no other supported web frameworks was found in ${currentDir}`,\n )\n parser = 'html'\n return findUp.stop\n }\n } else {\n if (globSync([`${currentDir}/*.xcodeproj`, `${currentDir}/Package.swift`]).length > 0) {\n showParserMessage(\n `Using \"swift\" parser as a file matching *.xcodeproj or Package.swift was found in ${currentDir}`,\n )\n parser = 'swift'\n return findUp.stop\n } else if (globSync([`${currentDir}/build.gradle.kts`]).length > 0) {\n showParserMessage(\n `Using \"compose\" parser as a file matching build.gradle.kts was found in ${currentDir}`,\n )\n parser = 'compose'\n return findUp.stop\n } else if (globSync([`${currentDir}/build.gradle`]).length > 0) {\n showParserMessage(\n `Using \"compose\" parser as a file matching build.gradle was found in ${currentDir}`,\n )\n parser = 'compose'\n return findUp.stop\n }\n }\n },\n { cwd: dir },\n )\n\n return parser\n}\n\n// Similarly to determineParserFromProject, this walks up looking for a\n// package.json containing a library which we support and we set a specific\n// label for. An example is Angular, which is detected as 'html' parser, but we\n// set a different label for it.\nexport function determineLabelFromProject(dir: string): string | undefined {\n function showMessage(\n libraryName: string,\n moduleName: string,\n packageJson: any,\n currentDir: string,\n ) {\n showParserMessage(\n `Using \"${libraryName}\" label as package.json containing a \"${moduleName}\" ${\n packageJson.dependencies && packageJson.dependencies[moduleName]\n ? 'dependency'\n : 'peer dependency'\n } was found in ${currentDir}`,\n )\n }\n\n let label: string | undefined\n\n findUp.sync(\n (currentDir) => {\n const packageJsonPath = path.join(currentDir, 'package.json')\n\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n if (packageJsonContains(packageJson, 'angular')) {\n showMessage('Angular', 'angular', packageJson, currentDir)\n label = CodeConnectLabel.Angular\n return findUp.stop\n } else if (packageJsonContains(packageJson, 'vue')) {\n showMessage('Vue', 'vue', packageJson, currentDir)\n label = CodeConnectLabel.Vue\n return findUp.stop\n }\n }\n },\n { cwd: dir },\n )\n\n return label\n}\n\nasync function checkForLegacyConfig(\n config: FigmaConfig & { codeConnect: { swift?: any; react?: any } },\n configFilePath: string,\n): Promise<FigmaConfig> | never {\n const { codeConnect } = config\n\n const newConfigBase = {\n ...(codeConnect.include ? { include: codeConnect.include } : {}),\n ...(codeConnect.exclude ? { exclude: codeConnect.exclude } : {}),\n ...(codeConnect.documentUrlSubstitutions\n ? { documentUrlSubstitutions: codeConnect.documentUrlSubstitutions }\n : {}),\n }\n const maybeNewReactConfig = {\n codeConnect: { parser: 'react', ...codeConnect.react, ...newConfigBase },\n }\n const maybeNewSwiftConfig = {\n codeConnect: { parser: 'swift', ...codeConnect.swift, ...newConfigBase },\n }\n\n if (codeConnect.react && codeConnect.swift) {\n logger.error(`${chalk.bold('⚠️ Your Code Connect configuration needs to be updated\\n')}`)\n\n logger.infoForce(`Code Connect is migrating from a single configuration file for all supported languages, to individual configuration files for each language.\n\nAs part of this change, your Code Connect configuration file needs to be split into two configuration files, one for React and one for Swift.\n\nThe React ${chalk.bold(\n 'figma.config.json',\n )} should be located in your React project root and contain:\n\n${JSON.stringify(maybeNewReactConfig, null, 2)}\n\nThe Swift ${chalk.bold(\n 'figma.config.json',\n )} should be located in your Swift project root and contain:\n\n${JSON.stringify(maybeNewSwiftConfig, null, 2)}\n\nYou will need to check any include/exclude paths are correct relative to the new locations.`)\n exitWithFeedbackMessage(1)\n }\n\n if (codeConnect.react || codeConnect.swift) {\n const platform = codeConnect.react ? 'React' : 'Swift'\n const newConfig = codeConnect.react ? maybeNewReactConfig : maybeNewSwiftConfig\n\n logger.infoForce(\n `${chalk.bold('⚠️ Your Code Connect configuration needs to be updated')}\n\nCode Connect is migrating from a single configuration file for all supported languages, to individual configuration files for each language.\n\nAs part of this change, your Code Connect configuration file needs to be updated to remove the ${chalk.bold(\n platform.toLowerCase(),\n )} key and add ${chalk.bold(`{ parser: \"${platform.toLowerCase()}\" }`)}:\n\n${JSON.stringify(newConfig, null, 2)}\n\nCode Connect can make this change for you automatically, or you can do it manually.\n\nPlease also ensure your configuration file is located in your ${platform} project root. If you move the configuration file, you will need to check any include/exclude paths are correct relative to the new location.\n\nPlease raise an issue at https://github.com/figma/code-connect/issues if you have any problems.\n\n---\n`,\n )\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stderr,\n })\n\n const updateConfig = await new Promise<string>((resolve) => {\n rl.question(\n 'Would you like Code Connect to update your configuration file for you? (y/n) ',\n (answer) => {\n resolve(answer)\n },\n )\n })\n rl.close()\n\n if (updateConfig.toLowerCase() === 'y') {\n fs.writeFileSync(configFilePath, JSON.stringify(newConfig, null, 2))\n logger.infoForce(`\\nConfiguration file updated`)\n return newConfig\n } else {\n exitWithError(`\\nPlease update your configuration file manually`)\n }\n }\n\n return config\n}\n\nasync function parseConfig(\n configFilePath: string,\n dir: string,\n isTemplatesOnlyCLI = false,\n): Promise<FigmaConfig | undefined> {\n try {\n const rawData = fs.readFileSync(configFilePath, 'utf-8')\n const rawConfig = JSON.parse(rawData)\n const config = await checkForLegacyConfig(rawConfig, configFilePath)\n\n if (!isTemplatesOnlyCLI && !config.codeConnect?.parser) {\n const parser = determineParserFromProject(dir)\n\n if (!parser) {\n logger.error(\n `Code Connect was not able to determine your project type, and no \\`parser\\` was specified. Please ensure you are running Code Connect from your project root. You may need to add a \\`parser\\` key to your config file, specifying which parser to use. See https://github.com/figma/code-connect/ for instructions.`,\n )\n exitWithFeedbackMessage(1)\n }\n\n if (!config.codeConnect) {\n config.codeConnect = { parser }\n }\n // TS errors if this is in an else\n config.codeConnect.parser = parser\n }\n\n if (!config.codeConnect?.label) {\n const label = determineLabelFromProject(dir)\n if (label) {\n config.codeConnect = { ...config.codeConnect, label }\n }\n }\n\n return config\n } catch (error) {\n console.error('Error parsing config file:', error)\n return undefined\n }\n}\n\nexport function getGitRemoteURL(repoPath: string) {\n try {\n const spawn = spawnSync('git', ['config', '--get', 'remote.origin.url'], {\n cwd: repoPath,\n })\n const output = spawn.stdout\n return (output || '').toString().trim()\n } catch (error) {\n console.error('Error getting git remote URL:', error)\n return ''\n }\n}\n\n/**\n * Uses `git rev-parse` to find absolute path to the root of the git repository\n */\nexport function getGitRepoAbsolutePath(filePath: string) {\n try {\n const dirPath = fs.statSync(filePath).isDirectory() ? filePath : path.dirname(filePath)\n const spawn = spawnSync('git', ['rev-parse', '--show-toplevel'], {\n cwd: dirPath,\n })\n const output = spawn.stdout\n return (\n (output || '')\n .toString()\n // git always uses /, but other Node API use \\ on Windows\n .replaceAll('/', path.sep)\n .trim()\n )\n } catch (error: any) {\n console.error('Error running `git rev-parse`:', error.toString().split('\\n')[0])\n return ''\n }\n}\n\n/**\n * Find the default branch name for the git repository\n */\nexport function getGitRepoDefaultBranchName(repoPath: string, configDefaultBranch?: string) {\n const DEFAULT_BRANCH_NAME = 'master'\n\n if (configDefaultBranch) {\n return configDefaultBranch\n }\n\n try {\n const symbolicRefResult = spawnSync('git', ['symbolic-ref', 'refs/remotes/origin/HEAD'], {\n cwd: repoPath,\n })\n\n if (symbolicRefResult.status === 0 && symbolicRefResult.stdout) {\n const ref = symbolicRefResult.stdout.toString().trim()\n // Output format: \"refs/remotes/origin/<branch>\" – take the last segment\n const branch = ref.split('/').pop()\n if (branch) {\n return branch\n }\n }\n\n // Fall back to scanning remote branches for known default branch names\n const gitBranchResult = spawnSync('git', ['branch', '-r'], {\n cwd: repoPath,\n })\n\n if (!gitBranchResult.stdout) {\n return DEFAULT_BRANCH_NAME\n }\n\n const branches = gitBranchResult.stdout\n .toString()\n .trim()\n .split('\\n')\n .map((s) => s.trim())\n\n // Check if origin/main exists, otherwise assume master\n if (branches.includes('origin/main')) {\n return 'main'\n } else {\n return DEFAULT_BRANCH_NAME\n }\n } catch (error: any) {\n console.error('Error getting git default branch name:', error.toString().split('\\n')[0])\n return DEFAULT_BRANCH_NAME\n }\n}\n\n/**\n * Finds the URL of a remote file\n * @param filePath absolute file path on disk\n * @param repoURL remote URL, can be a GitHub, GitLab, Bitbucket, etc. URL.\n * @returns\n */\nexport function getRemoteFileUrl(filePath: string, repoURL?: string, defaultBranch?: string) {\n if (!repoURL) {\n return ''\n }\n\n filePath = filePath.replaceAll(path.sep, '/')\n\n let url = repoURL.trim()\n if (url.startsWith('git@')) {\n url = url.replace(':', '/')\n url = url.replace('git@', 'https://')\n }\n url = url.replace(/\\.git$/, '')\n\n // the folder of the git repo on disk could be named differently,\n // so we need to find the relative path of the file to the root of the repo\n // and append that to the remote URL\n const repoAbsPath = getGitRepoAbsolutePath(filePath)\n // Windows uses \\ as the path separator, so replace with /\n .replaceAll(path.sep, '/')\n\n const resolvedDefaultBranch = getGitRepoDefaultBranchName(repoAbsPath, defaultBranch)\n const index = filePath.indexOf(repoAbsPath)\n if (index === -1) {\n return ''\n }\n\n const relativeFilePath = filePath.substring(index + repoAbsPath.length)\n\n if (url.includes('github.com')) {\n return `${url}/blob/${resolvedDefaultBranch}${relativeFilePath}`\n } else if (url.includes('gitlab.com')) {\n return `${url}/-/blob/${resolvedDefaultBranch}${relativeFilePath}`\n } else if (url.includes('bitbucket.org')) {\n return `${url}/src/${resolvedDefaultBranch}${relativeFilePath}`\n } else if (url.includes('dev.azure.com')) {\n // `git config --get remote.origin.url` for azure repos will return different strings depending on if it was\n // cloned with https or ssh. We need to convert this to a valid URL like \"https://dev.azure.com/org/repo/_git/repo?path=/\"\n if (repoURL.startsWith('git@')) {\n // ssh: \"git@ssh.dev.azure.com:v3/org/repo/repo\"\n const [org, project1, project2] = repoURL.split('/').slice(-3)\n return `https://dev.azure.com/${org}/${project1}/_git/${project2}?path=${relativeFilePath}&branch=${resolvedDefaultBranch}`\n } else {\n // https: \"https://org@dev.azure.com/org/repo/_git/repo\"\n const [_, url] = repoURL.split('@')\n return `https://${url}?path=${relativeFilePath}&branch=${resolvedDefaultBranch}`\n }\n } else {\n logger.debug('Unknown remote URL - assuming GitHub Enterprise', url)\n return `${url}/blob/${resolvedDefaultBranch}${relativeFilePath}`\n }\n}\n\nexport function getStorybookUrl(filePath: string, storybookUrl: string) {\n // the folder of the git repo on disk could be named differently,\n // so we need to find the relative path of the file to the root of the repo\n // and append that to the remote URL\n const repoAbsPath = getGitRepoAbsolutePath(filePath).replaceAll(path.sep, '/')\n const index = filePath.indexOf(repoAbsPath)\n if (index === -1) {\n return ''\n }\n\n const relativeFilePath = filePath.substring(index + repoAbsPath.length + 1) // +1 to remove the leading slash\n const storybookComponentPath = relativeFilePath\n .trim()\n .replace(/[\\s|_]/g, '-')\n .replace(/\\.[jt]sx?$/, '')\n .replaceAll('\\\\', '/')\n .split('/')\n .join('-')\n\n return `${storybookUrl}/?path=/docs/${storybookComponentPath}`\n}\n\nexport type ProjectInfo<ConfigT = CodeConnectConfig> = {\n /**\n * Absolute path of the project directory\n */\n absPath: string\n /**\n * An array of all tsx files in the project\n */\n files: string[]\n /**\n * The git remote URL of the project\n */\n remoteUrl: string\n /**\n * The parsed Code Connect config file\n */\n config: ConfigT\n}\n\nexport type ReactProjectInfo = ProjectInfo<CodeConnectReactConfig> & {\n /**\n * TS program containing all tsx files in the project\n */\n tsProgram: ts.Program\n}\n\nfunction mapToAbsolutePaths(globPaths: string[], absPath: string) {\n // glob doesn't like Windows paths so convert to *nix format\n return globPaths.map((globPath) => `${absPath.replaceAll(path.sep, '/')}/${globPath}`)\n}\n\nexport function getDefaultConfigPath(dir: string) {\n return path.resolve(path.join(dir, DEFAULT_CONFIG_FILE_NAME))\n}\n\nexport function getEnvPath(dir: string) {\n return path.resolve(path.join(dir, ENV_FILE_NAME))\n}\n\nexport async function parseOrDetermineConfig(\n dir: string,\n configPath: string,\n isTemplatesOnlyCLI = false,\n) {\n const configFilePath = configPath ? path.resolve(configPath) : getDefaultConfigPath(dir)\n\n const hasConfigFile = fs.existsSync(configFilePath)\n\n if (!hasConfigFile) {\n if (configPath) {\n logger.warn(`${configPath} does not exist, proceeding with default options`)\n } else {\n logger.info(`No config file found in ${dir}, proceeding with default options`)\n }\n }\n\n const globalConfig = hasConfigFile\n ? await parseConfig(configFilePath, dir, isTemplatesOnlyCLI)\n : determineConfigFromProject(dir, true, isTemplatesOnlyCLI)\n\n if (!globalConfig) {\n throw new Error(`Error parsing config file: ${configFilePath}`)\n }\n\n if (!globalConfig.codeConnect) {\n throw new Error(`No options specified under 'codeConnect' in config file: ${configFilePath}`)\n }\n\n const config = globalConfig.codeConnect\n\n if (hasConfigFile) {\n if (!config) {\n logger.info(`Config file found, but no options specified under 'codeConnect'. Parsing ${dir}`)\n } else if (config && !config.include) {\n logger.info(`Config file found, but no include globs specified. Parsing ${dir}`)\n } else {\n logger.info(`Config file found, parsing ${dir} using specified include globs`)\n }\n }\n\n return {\n config,\n hasConfigFile,\n }\n}\n\n/**\n * Check if a .env file exists in the provided directory and if it contains a FIGMA_ACCESS_TOKEN.\n */\nexport async function checkForEnvAndToken(dir: string) {\n // Scan the provided directory for a .env file\n const envPath = await findUp('.env', { cwd: dir })\n\n if (!envPath) {\n // No .env file found\n return {\n hasEnvFile: false,\n envHasFigmaToken: false,\n }\n }\n\n // Read the contents of the .env file\n const envContents = fs.readFileSync(envPath, 'utf-8')\n\n // Determine if the .env file contains a FIGMA_ACCESS_TOKEN\n const envVars = envContents.split('\\n').reduce(\n (\n acc: {\n [key: string]: string\n },\n line,\n ) => {\n const [key, value] = line.split('=')\n acc[key] = value\n return acc\n },\n {},\n )\n\n const figmaAccessToken = envVars['FIGMA_ACCESS_TOKEN']\n\n return {\n hasEnvFile: true,\n envHasFigmaToken: !!figmaAccessToken,\n }\n}\n\n/**\n * Gets information about a project from config.\n *\n * @param dir Directory containing the project\n * @param config Code Connect config\n * @returns Object containing information about the project\n */\nexport async function getProjectInfoFromConfig(\n dir: string,\n config: CodeConnectConfig,\n isTemplatesOnlyCLI = false,\n): Promise<ProjectInfo> {\n const absPath = path.resolve(dir)\n const remoteUrl = getGitRemoteURL(absPath)\n\n const defaultIncludeGlobs = isTemplatesOnlyCLI\n ? [\n '**/*.figma.ts',\n '**/*.figma.js',\n '**/*.figma.template.ts',\n '**/*.figma.template.js',\n '**/*.figma.batch.json',\n ]\n : config.parser\n ? DEFAULT_INCLUDE_GLOBS_BY_PARSER[config.parser]\n : undefined\n\n // always ignore node_modules; for parsers, apply parser-specific exclusions\n const defaultExcludeGlobs = isTemplatesOnlyCLI\n ? ['node_modules/**']\n : config.parser\n ? ({\n react: ['node_modules/**'],\n html: ['node_modules/**'],\n swift: ['**/__test__/**'],\n compose: [],\n custom: [],\n __unit_test__: [],\n }[config.parser] ?? [])\n : []\n\n const includeGlobs = config.include || defaultIncludeGlobs\n const excludeGlobs = config.exclude\n ? [...config.exclude, ...defaultExcludeGlobs]\n : defaultExcludeGlobs\n\n if (config.parser === 'custom' && (!includeGlobs || includeGlobs.length === 0)) {\n exitWithError('Include globs must specified in config file for custom parsers')\n }\n\n if (!includeGlobs) {\n exitWithError('No include globs specified in config file')\n }\n\n const files = globSync(mapToAbsolutePaths(includeGlobs, absPath), {\n nodir: true,\n ignore: mapToAbsolutePaths(excludeGlobs, absPath),\n // Otherwise this is true on *nix and false on Windows\n absolute: true,\n })\n\n if (files.length > 10000) {\n logger.warn(\n `Matching number of files was excessively large (${files.length}) - consider using more specific include/exclude globs in your config file.`,\n )\n }\n\n return {\n absPath,\n remoteUrl,\n config,\n files,\n }\n}\n\n/**\n * Validates the language field in the config.\n * Throws an error if the language is invalid.\n *\n * @param language The language string to validate\n */\nfunction validateLanguage(language: SyntaxHighlightLanguage | undefined): void {\n if (!language) return\n\n const validLanguages = Object.values(SyntaxHighlightLanguage)\n if (!validLanguages.includes(language)) {\n throw new Error(\n `Invalid language \"${language}\" in figma.config.json. ` +\n `Valid values are: ${validLanguages.join(', ')}`,\n )\n }\n}\n\n/**\n * Gets information about a project from a directory.\n *\n * @param dir Directory containing the project\n * @param configPath Optional path to Code Connect config file\n * @returns Object containing information about the project\n */\nexport async function getProjectInfo(\n dir: string,\n configPath: string,\n isTemplatesOnlyCLI = false,\n): Promise<ProjectInfo> {\n const { config } = await parseOrDetermineConfig(dir, configPath, isTemplatesOnlyCLI)\n\n // Validate language field if present\n validateLanguage(config.language)\n\n return getProjectInfoFromConfig(dir, config, isTemplatesOnlyCLI)\n}\n\nexport function getReactProjectInfo(\n projectInfo: ProjectInfo<CodeConnectReactConfig>,\n): ReactProjectInfo {\n const tsProgram = getTsProgram(projectInfo)\n\n return {\n ...projectInfo,\n tsProgram,\n }\n}\n\nexport function getTsProgram(projectInfo: ProjectInfo<CodeConnectConfig>): ts.Program {\n const compilerOptions: ts.CompilerOptions = {\n // This ensures the compiler can resolve imports such as \"ui/button\" when a\n // baseUrl is configured in the tsconfig of the project. We probably want a more\n // sophisticated way to parse the users tsconfig and pass it to the compiler eventually.\n baseUrl: projectInfo.absPath,\n // TODO: not sure why Node10 is needed her, but otherwise module resolution for\n // pnpm workspaces won't work\n moduleResolution: ts.ModuleResolutionKind.Node10,\n paths: 'paths' in projectInfo.config ? (projectInfo.config.paths ?? {}) : {},\n allowJs: true,\n }\n\n return ts.createProgram(projectInfo.files, compilerOptions)\n}\n\n/**\n * Change an imported path for a component like `./button` to e.g `@ui/button`, based on the config file.\n * Note that `filePath` here is the path to the source file on disk, not the module specifier.\n *\n * @param filePath\n * @param config\n * @returns\n */\nexport function mapImportPath(filePath: string, config: CodeConnectReactConfig): string | null {\n // Takes the reversed path and pattern parts and check if they match\n function isMatch(patternParts: string[], pathParts: string[]) {\n if (patternParts[0] === '*') {\n // if the path is just a wildcard and nothing else, match any import\n if (patternParts.length === 1) {\n return true\n }\n\n // if the _next_ part in the pattern does not exist in the path, it's not\n // a match.\n const index = pathParts.indexOf(patternParts[1])\n if (index === -1) {\n return false\n }\n\n // Skip to the matching part in the path and match the rest of\n // the pattern. E.g if the pattern is `*/ui/src` (reversed) and the path is\n // `button.tsx/components/ui/src`, we skip to `ui` and match the rest of the\n // pattern.\n patternParts = patternParts.slice(1)\n pathParts = pathParts.slice(index)\n }\n\n for (let i = 0; i < patternParts.length; i++) {\n if (patternParts[i] !== pathParts[i]) {\n return false\n }\n }\n return true\n }\n\n for (const [key, value] of Object.entries(config.importPaths || {})) {\n // Do a partial match from the end of the path\n const patternParts = key.split('/').reverse()\n const pathParts = filePath.split('/').reverse()\n if (pathParts.length < patternParts.length) {\n continue\n }\n\n // If the mapped path ends with a wildcard we want to keep the filename in\n // the final path\n if (isMatch(patternParts, pathParts)) {\n if (value.endsWith('*')) {\n const filename = pathParts[0].split('.')[0]\n return `${value.slice(0, -1)}${filename}`\n }\n return value\n }\n }\n\n return null\n}\n\n/**\n * Transform an import specifier (the path in the import statement) using importPaths config.\n * This works directly on the module specifier from the source code, preserving the user's intent.\n *\n * E.g., '@/AlertTitle' with config { \"@/*\": \"@acme/package/*\" } → '@acme/package/AlertTitle'\n *\n * @param specifier The original import specifier from the source file (e.g., '@/AlertTitle', './Button')\n * @param config The Code Connect config containing importPaths\n * @returns The transformed import path, or null if no mapping matched\n */\nexport function mapImportSpecifier(\n specifier: string,\n config: CodeConnectReactConfig,\n): string | null {\n for (const [pattern, replacement] of Object.entries(config.importPaths || {})) {\n // Convert glob pattern to regex: @/* → ^@/(.*)$\n // First escape special regex chars, then convert * to capture group\n const regexPattern = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&') // Escape special chars except *\n .replace(/\\*/g, '(.*)') // Convert * to capture group\n const regex = new RegExp(`^${regexPattern}$`)\n const match = specifier.match(regex)\n\n if (match) {\n // Replace * in replacement with captured group\n let result = replacement\n if (match[1] !== undefined) {\n result = replacement.replace('*', match[1])\n }\n return result\n }\n }\n return null\n}\n"]}
|
|
1
|
+
{"version":3,"file":"project.js","sourceRoot":"","sources":["../../src/connect/project.ts"],"names":[],"mappings":";;;;;;AAkKA,gEAmBC;AAgFD,8DAuCC;AAuID,0CAWC;AAKD,wDAkBC;AAKD,kEA8CC;AAQD,4CAmDC;AAED,0CAoBC;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glob'\nimport path from 'path'\nimport fs from 'fs'\nimport ts from 'typescript'\nimport { exitWithError, logger } from '../common/logging'\nimport chalk from 'chalk'\nimport readline from 'readline'\n// We use an old version of this dep as I couldn't get ES modules working\nimport findUp from 'find-up'\nimport { exitWithFeedbackMessage } from './helpers'\nimport { CodeConnectLabel, SyntaxHighlightLanguage } from './label_language_mapping'\n\nconst DEFAULT_CONFIG_FILE_NAME = 'figma.config.json'\nconst ENV_FILE_NAME = '.env'\n\nexport const DEFAULT_INCLUDE_GLOBS_BY_PARSER = {\n react: [`**/*.{tsx,jsx}`],\n html: [`**/*.{ts,js}`],\n swift: ['**/*.swift'],\n compose: ['**/*.kt'],\n // include globs should be included in configs for custom parsers\n custom: undefined,\n __unit_test__: [''],\n}\n\nexport const DEFAULT_PARSERLESS_INCLUDE_GLOBS = [\n '**/*.figma.ts',\n '**/*.figma.js',\n '**/*.figma.template.ts',\n '**/*.figma.template.js',\n '**/*.figma.batch.json',\n]\n\nconst DEFAULT_PARSERLESS_EXCLUDE_GLOBS = ['node_modules/**']\n\nexport const DEFAULT_LABEL_PER_PARSER: Partial<Record<CodeConnectParser, string>> = {\n react: CodeConnectLabel.React,\n html: CodeConnectLabel.WebComponents,\n}\n\n// First party parsers which call into parser executables\nexport type CodeConnectExecutableParser = 'swift' | 'compose' | 'custom' | '__unit_test__'\n\n// React is a special case for now as we call it directly from the CLI rather\n// than via an executable for legacy reasons. We will migrate it to the\n// parser executable model.\nexport type CodeConnectParser = 'react' | 'html' | CodeConnectExecutableParser\n\nexport type BaseCodeConnectConfig = {\n /**\n * Specify glob patterns for files (relative to the project root) to be\n * included when looking for source files. If not specified, all files\n * (except any specified in `exclude`) will be included.\n */\n include?: string[]\n /**\n * Specify glob patterns for files (relative to the project root) to be\n * excluded when looking for source files. If not specified, only\n * `node_modules` will be excluded.\n */\n exclude?: string[]\n /**\n * Optional object of substitutions applied to document URLs (in the format {\n * fromString, toString }) for testing (e.g. remapping a production URL to a\n * staging URL). Not publicly documented.\n */\n documentUrlSubstitutions?: Record<string, string>\n /**\n * The parser name, if using an internal parser.\n */\n parser?: CodeConnectParser\n\n /**\n * Label to use for the uploaded code examples\n */\n label?: string\n\n /**\n * Language to use for syntax highlighting in the uploaded code examples.\n * If not specified, language is inferred from the label or parser type.\n */\n language?: SyntaxHighlightLanguage\n\n /**\n * The URL of the Figma file to use during the interactive setup wizard for connecting code components to Figma components.\n */\n interactiveSetupFigmaFileUrl?: string\n\n /**\n * Custom Figma API URL to use instead of https://api.figma.com/v1\n */\n apiUrl?: string\n\n /**\n * The default branch name for your repository. Code Connect uses this when generating source code\n * links in Figma. If not specified, Code Connect will attempt to determine this automatically.\n */\n defaultBranch?: string\n}\n\nexport type CodeConnectExecutableParserConfig = BaseCodeConnectConfig & {\n parser: CodeConnectExecutableParser\n}\n\nexport type CodeConnectCustomExecutableParserConfig = BaseCodeConnectConfig & {\n parser: 'custom'\n parserCommand: string\n}\n\n/**\n * React specific configuration\n */\nexport type CodeConnectReactConfig = BaseCodeConnectConfig & {\n parser: 'react'\n /**\n * Maps imports from their path on disk to the specified path.\n * This will rewrite the imports in generated code examples, so it works with\n * relative imports such as `import { Button } from \"./\"`.\n *\n * Example: { \"src/components/*\": \"@ui/components\" }\n * Would rewrite imports for components located in `src/components` to `@ui/components` in\n * generated code examples.\n * `import { Button } from \"./\"` -> `import { Button } from \"@ui/components/Button\"`\n */\n importPaths?: Record<string, string>\n /**\n * For import resolution - this is a temporary solution to support projects that use\n * pnpm workspaces, as the compiler doesn't seem to be able to resolve imports when\n * the package in node_modules is a symlink. Need to look into this more and find a\n * better solution.\n */\n paths?: Record<string, string[]>\n /**\n * Storybook specific configuration\n */\n storybook?: {\n /**\n * The URL of the Storybook instance for the project\n */\n url: string\n }\n}\n\nexport type CodeConnectHtmlConfig = BaseCodeConnectConfig & {}\n\nexport type CodeConnectParserlessConfig = BaseCodeConnectConfig & {\n parser: undefined\n}\n\nexport type CodeConnectConfig =\n | CodeConnectReactConfig\n | CodeConnectExecutableParserConfig\n | CodeConnectCustomExecutableParserConfig\n | CodeConnectHtmlConfig\n | BaseCodeConnectConfig\n | CodeConnectParserlessConfig\n\ninterface FigmaConfig {\n codeConnect?: CodeConnectConfig\n}\n\nexport function determineConfigFromProject(dir: string, isTemplatesOnlyCLI = false): FigmaConfig {\n if (isTemplatesOnlyCLI) {\n const label = determineLabelFromProject(dir)\n return { codeConnect: label ? { label } : {} }\n }\n\n const parser = determineParserFromProject(dir)\n const label = determineLabelFromProject(dir)\n if (parser) {\n if (label) {\n return { codeConnect: { parser, label } }\n }\n\n return { codeConnect: { parser } }\n }\n\n logger.info(`Can't determine parser from project. Proceeding without a parser.`)\n\n return { codeConnect: label ? { label } : {} }\n}\n\nfunction showParserMessage(message: string) {\n logger.info(\n message +\n '. If this is incorrect, please check you are running Code Connect from your project root, or add a `parser` key to your config file. See https://github.com/figma/code-connect for more information.',\n )\n}\n\nfunction packageJsonContains(packageJson: any, dependency: string) {\n return (\n (packageJson.dependencies && packageJson.dependencies[dependency]) ||\n (packageJson.peerDependencies && packageJson.peerDependencies[dependency]) ||\n (packageJson.devDependencies && packageJson.devDependencies[dependency])\n )\n}\n\n// Walk up from the given directory looking for the first directory which\n// matches heuristics for the platforms we support. This means that e.g. if you\n// have a Swift project inside a React project, we'll detect Swift. This enables\n// users to run commands from anywhere inside their project, rather than having\n// to run from the root (the same way npm works).\nfunction determineParserFromProject(dir: string): CodeConnectParser | undefined {\n let parser: CodeConnectParser | undefined\n\n findUp.sync(\n (currentDir) => {\n const packageJsonPath = path.join(currentDir, 'package.json')\n\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n if (packageJsonContains(packageJson, 'react')) {\n showParserMessage(\n `Using \"react\" parser as package.json containing a \"react\" ${\n packageJson.dependencies && packageJson.dependencies['react']\n ? 'dependency'\n : 'peer dependency'\n } was found in ${currentDir}`,\n )\n parser = 'react'\n return findUp.stop\n } else {\n showParserMessage(\n `Using \"html\" parser as package.json containing no other supported web frameworks was found in ${currentDir}`,\n )\n parser = 'html'\n return findUp.stop\n }\n } else {\n if (globSync([`${currentDir}/*.xcodeproj`, `${currentDir}/Package.swift`]).length > 0) {\n showParserMessage(\n `Using \"swift\" parser as a file matching *.xcodeproj or Package.swift was found in ${currentDir}`,\n )\n parser = 'swift'\n return findUp.stop\n } else if (globSync([`${currentDir}/build.gradle.kts`]).length > 0) {\n showParserMessage(\n `Using \"compose\" parser as a file matching build.gradle.kts was found in ${currentDir}`,\n )\n parser = 'compose'\n return findUp.stop\n } else if (globSync([`${currentDir}/build.gradle`]).length > 0) {\n showParserMessage(\n `Using \"compose\" parser as a file matching build.gradle was found in ${currentDir}`,\n )\n parser = 'compose'\n return findUp.stop\n }\n }\n },\n { cwd: dir },\n )\n\n return parser\n}\n\n// Similarly to determineParserFromProject, this walks up looking for a\n// package.json containing a library which we support and we set a specific\n// label for. An example is Angular, which is detected as 'html' parser, but we\n// set a different label for it.\nexport function determineLabelFromProject(dir: string): string | undefined {\n function showMessage(\n libraryName: string,\n moduleName: string,\n packageJson: any,\n currentDir: string,\n ) {\n showParserMessage(\n `Using \"${libraryName}\" label as package.json containing a \"${moduleName}\" ${\n packageJson.dependencies && packageJson.dependencies[moduleName]\n ? 'dependency'\n : 'peer dependency'\n } was found in ${currentDir}`,\n )\n }\n\n let label: string | undefined\n\n findUp.sync(\n (currentDir) => {\n const packageJsonPath = path.join(currentDir, 'package.json')\n\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n if (packageJsonContains(packageJson, 'angular')) {\n showMessage('Angular', 'angular', packageJson, currentDir)\n label = CodeConnectLabel.Angular\n return findUp.stop\n } else if (packageJsonContains(packageJson, 'vue')) {\n showMessage('Vue', 'vue', packageJson, currentDir)\n label = CodeConnectLabel.Vue\n return findUp.stop\n }\n }\n },\n { cwd: dir },\n )\n\n return label\n}\n\nasync function checkForLegacyConfig(\n config: FigmaConfig & { codeConnect: { swift?: any; react?: any } },\n configFilePath: string,\n): Promise<FigmaConfig> | never {\n const { codeConnect } = config\n\n const newConfigBase = {\n ...(codeConnect.include ? { include: codeConnect.include } : {}),\n ...(codeConnect.exclude ? { exclude: codeConnect.exclude } : {}),\n ...(codeConnect.documentUrlSubstitutions\n ? { documentUrlSubstitutions: codeConnect.documentUrlSubstitutions }\n : {}),\n }\n const maybeNewReactConfig = {\n codeConnect: { parser: 'react', ...codeConnect.react, ...newConfigBase },\n }\n const maybeNewSwiftConfig = {\n codeConnect: { parser: 'swift', ...codeConnect.swift, ...newConfigBase },\n }\n\n if (codeConnect.react && codeConnect.swift) {\n logger.error(`${chalk.bold('⚠️ Your Code Connect configuration needs to be updated\\n')}`)\n\n logger.infoForce(`Code Connect is migrating from a single configuration file for all supported languages, to individual configuration files for each language.\n\nAs part of this change, your Code Connect configuration file needs to be split into two configuration files, one for React and one for Swift.\n\nThe React ${chalk.bold(\n 'figma.config.json',\n )} should be located in your React project root and contain:\n\n${JSON.stringify(maybeNewReactConfig, null, 2)}\n\nThe Swift ${chalk.bold(\n 'figma.config.json',\n )} should be located in your Swift project root and contain:\n\n${JSON.stringify(maybeNewSwiftConfig, null, 2)}\n\nYou will need to check any include/exclude paths are correct relative to the new locations.`)\n exitWithFeedbackMessage(1)\n }\n\n if (codeConnect.react || codeConnect.swift) {\n const platform = codeConnect.react ? 'React' : 'Swift'\n const newConfig = codeConnect.react ? maybeNewReactConfig : maybeNewSwiftConfig\n\n logger.infoForce(\n `${chalk.bold('⚠️ Your Code Connect configuration needs to be updated')}\n\nCode Connect is migrating from a single configuration file for all supported languages, to individual configuration files for each language.\n\nAs part of this change, your Code Connect configuration file needs to be updated to remove the ${chalk.bold(\n platform.toLowerCase(),\n )} key and add ${chalk.bold(`{ parser: \"${platform.toLowerCase()}\" }`)}:\n\n${JSON.stringify(newConfig, null, 2)}\n\nCode Connect can make this change for you automatically, or you can do it manually.\n\nPlease also ensure your configuration file is located in your ${platform} project root. If you move the configuration file, you will need to check any include/exclude paths are correct relative to the new location.\n\nPlease raise an issue at https://github.com/figma/code-connect/issues if you have any problems.\n\n---\n`,\n )\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stderr,\n })\n\n const updateConfig = await new Promise<string>((resolve) => {\n rl.question(\n 'Would you like Code Connect to update your configuration file for you? (y/n) ',\n (answer) => {\n resolve(answer)\n },\n )\n })\n rl.close()\n\n if (updateConfig.toLowerCase() === 'y') {\n fs.writeFileSync(configFilePath, JSON.stringify(newConfig, null, 2))\n logger.infoForce(`\\nConfiguration file updated`)\n return newConfig\n } else {\n exitWithError(`\\nPlease update your configuration file manually`)\n }\n }\n\n return config\n}\n\nasync function parseConfig(\n configFilePath: string,\n dir: string,\n isTemplatesOnlyCLI = false,\n): Promise<FigmaConfig | undefined> {\n try {\n const rawData = fs.readFileSync(configFilePath, 'utf-8')\n const rawConfig = JSON.parse(rawData)\n const config = await checkForLegacyConfig(rawConfig, configFilePath)\n\n if (!isTemplatesOnlyCLI && !config.codeConnect?.parser) {\n const parser = determineParserFromProject(dir)\n\n if (parser) {\n if (!config.codeConnect) {\n config.codeConnect = { parser }\n }\n // TS errors if this is in an else\n config.codeConnect.parser = parser\n } else {\n logger.info(`Can't determine parser from project. Proceeding without a parser.`)\n }\n }\n\n if (!config.codeConnect?.label) {\n const label = determineLabelFromProject(dir)\n if (label) {\n config.codeConnect = { ...config.codeConnect, label }\n }\n }\n\n return config\n } catch (error) {\n console.error('Error parsing config file:', error)\n return undefined\n }\n}\n\nexport function getGitRemoteURL(repoPath: string) {\n try {\n const spawn = spawnSync('git', ['config', '--get', 'remote.origin.url'], {\n cwd: repoPath,\n })\n const output = spawn.stdout\n return (output || '').toString().trim()\n } catch (error) {\n console.error('Error getting git remote URL:', error)\n return ''\n }\n}\n\n/**\n * Uses `git rev-parse` to find absolute path to the root of the git repository\n */\nexport function getGitRepoAbsolutePath(filePath: string) {\n try {\n const dirPath = fs.statSync(filePath).isDirectory() ? filePath : path.dirname(filePath)\n const spawn = spawnSync('git', ['rev-parse', '--show-toplevel'], {\n cwd: dirPath,\n })\n const output = spawn.stdout\n return (\n (output || '')\n .toString()\n // git always uses /, but other Node API use \\ on Windows\n .replaceAll('/', path.sep)\n .trim()\n )\n } catch (error: any) {\n console.error('Error running `git rev-parse`:', error.toString().split('\\n')[0])\n return ''\n }\n}\n\n/**\n * Find the default branch name for the git repository\n */\nexport function getGitRepoDefaultBranchName(repoPath: string, configDefaultBranch?: string) {\n const DEFAULT_BRANCH_NAME = 'master'\n\n if (configDefaultBranch) {\n return configDefaultBranch\n }\n\n try {\n const symbolicRefResult = spawnSync('git', ['symbolic-ref', 'refs/remotes/origin/HEAD'], {\n cwd: repoPath,\n })\n\n if (symbolicRefResult.status === 0 && symbolicRefResult.stdout) {\n const ref = symbolicRefResult.stdout.toString().trim()\n // Output format: \"refs/remotes/origin/<branch>\" – take the last segment\n const branch = ref.split('/').pop()\n if (branch) {\n return branch\n }\n }\n\n // Fall back to scanning remote branches for known default branch names\n const gitBranchResult = spawnSync('git', ['branch', '-r'], {\n cwd: repoPath,\n })\n\n if (!gitBranchResult.stdout) {\n return DEFAULT_BRANCH_NAME\n }\n\n const branches = gitBranchResult.stdout\n .toString()\n .trim()\n .split('\\n')\n .map((s) => s.trim())\n\n // Check if origin/main exists, otherwise assume master\n if (branches.includes('origin/main')) {\n return 'main'\n } else {\n return DEFAULT_BRANCH_NAME\n }\n } catch (error: any) {\n console.error('Error getting git default branch name:', error.toString().split('\\n')[0])\n return DEFAULT_BRANCH_NAME\n }\n}\n\n/**\n * Finds the URL of a remote file\n * @param filePath absolute file path on disk\n * @param repoURL remote URL, can be a GitHub, GitLab, Bitbucket, etc. URL.\n * @returns\n */\nexport function getRemoteFileUrl(filePath: string, repoURL?: string, defaultBranch?: string) {\n if (!repoURL) {\n return ''\n }\n\n filePath = filePath.replaceAll(path.sep, '/')\n\n let url = repoURL.trim()\n if (url.startsWith('git@')) {\n url = url.replace(':', '/')\n url = url.replace('git@', 'https://')\n }\n url = url.replace(/\\.git$/, '')\n\n // the folder of the git repo on disk could be named differently,\n // so we need to find the relative path of the file to the root of the repo\n // and append that to the remote URL\n const repoAbsPath = getGitRepoAbsolutePath(filePath)\n // Windows uses \\ as the path separator, so replace with /\n .replaceAll(path.sep, '/')\n\n const resolvedDefaultBranch = getGitRepoDefaultBranchName(repoAbsPath, defaultBranch)\n const index = filePath.indexOf(repoAbsPath)\n if (index === -1) {\n return ''\n }\n\n const relativeFilePath = filePath.substring(index + repoAbsPath.length)\n\n if (url.includes('github.com')) {\n return `${url}/blob/${resolvedDefaultBranch}${relativeFilePath}`\n } else if (url.includes('gitlab.com')) {\n return `${url}/-/blob/${resolvedDefaultBranch}${relativeFilePath}`\n } else if (url.includes('bitbucket.org')) {\n return `${url}/src/${resolvedDefaultBranch}${relativeFilePath}`\n } else if (url.includes('dev.azure.com')) {\n // `git config --get remote.origin.url` for azure repos will return different strings depending on if it was\n // cloned with https or ssh. We need to convert this to a valid URL like \"https://dev.azure.com/org/repo/_git/repo?path=/\"\n if (repoURL.startsWith('git@')) {\n // ssh: \"git@ssh.dev.azure.com:v3/org/repo/repo\"\n const [org, project1, project2] = repoURL.split('/').slice(-3)\n return `https://dev.azure.com/${org}/${project1}/_git/${project2}?path=${relativeFilePath}&branch=${resolvedDefaultBranch}`\n } else {\n // https: \"https://org@dev.azure.com/org/repo/_git/repo\"\n const [_, url] = repoURL.split('@')\n return `https://${url}?path=${relativeFilePath}&branch=${resolvedDefaultBranch}`\n }\n } else {\n logger.debug('Unknown remote URL - assuming GitHub Enterprise', url)\n return `${url}/blob/${resolvedDefaultBranch}${relativeFilePath}`\n }\n}\n\nexport function getStorybookUrl(filePath: string, storybookUrl: string) {\n // the folder of the git repo on disk could be named differently,\n // so we need to find the relative path of the file to the root of the repo\n // and append that to the remote URL\n const repoAbsPath = getGitRepoAbsolutePath(filePath).replaceAll(path.sep, '/')\n const index = filePath.indexOf(repoAbsPath)\n if (index === -1) {\n return ''\n }\n\n const relativeFilePath = filePath.substring(index + repoAbsPath.length + 1) // +1 to remove the leading slash\n const storybookComponentPath = relativeFilePath\n .trim()\n .replace(/[\\s|_]/g, '-')\n .replace(/\\.[jt]sx?$/, '')\n .replaceAll('\\\\', '/')\n .split('/')\n .join('-')\n\n return `${storybookUrl}/?path=/docs/${storybookComponentPath}`\n}\n\nexport type ProjectInfo<ConfigT = CodeConnectConfig> = {\n /**\n * Absolute path of the project directory\n */\n absPath: string\n /**\n * An array of all tsx files in the project\n */\n files: string[]\n /**\n * The git remote URL of the project\n */\n remoteUrl: string\n /**\n * The parsed Code Connect config file\n */\n config: ConfigT\n}\n\nexport type ReactProjectInfo = ProjectInfo<CodeConnectReactConfig> & {\n /**\n * TS program containing all tsx files in the project\n */\n tsProgram: ts.Program\n}\n\nfunction mapToAbsolutePaths(globPaths: string[], absPath: string) {\n // glob doesn't like Windows paths so convert to *nix format\n return globPaths.map((globPath) => `${absPath.replaceAll(path.sep, '/')}/${globPath}`)\n}\n\nexport function getDefaultConfigPath(dir: string) {\n return path.resolve(path.join(dir, DEFAULT_CONFIG_FILE_NAME))\n}\n\nexport function getEnvPath(dir: string) {\n return path.resolve(path.join(dir, ENV_FILE_NAME))\n}\n\nexport async function parseOrDetermineConfig(\n dir: string,\n configPath: string,\n isTemplatesOnlyCLI = false,\n) {\n const configFilePath = configPath ? path.resolve(configPath) : getDefaultConfigPath(dir)\n\n const hasConfigFile = fs.existsSync(configFilePath)\n\n if (!hasConfigFile) {\n if (configPath) {\n logger.warn(`${configPath} does not exist, proceeding with default options`)\n } else {\n logger.info(`No config file found in ${dir}, proceeding with default options`)\n }\n }\n\n const globalConfig = hasConfigFile\n ? await parseConfig(configFilePath, dir, isTemplatesOnlyCLI)\n : determineConfigFromProject(dir, isTemplatesOnlyCLI)\n\n if (!globalConfig) {\n throw new Error(`Error parsing config file: ${configFilePath}`)\n }\n\n if (!globalConfig.codeConnect) {\n throw new Error(`No options specified under 'codeConnect' in config file: ${configFilePath}`)\n }\n\n const config = globalConfig.codeConnect\n\n if (hasConfigFile) {\n if (!config) {\n logger.info(`Config file found, but no options specified under 'codeConnect'. Parsing ${dir}`)\n } else if (config && !config.include) {\n logger.info(`Config file found, but no include globs specified. Parsing ${dir}`)\n } else {\n logger.info(`Config file found, parsing ${dir} using specified include globs`)\n }\n }\n\n return {\n config,\n hasConfigFile,\n }\n}\n\n/**\n * Check if a .env file exists in the provided directory and if it contains a FIGMA_ACCESS_TOKEN.\n */\nexport async function checkForEnvAndToken(dir: string) {\n // Scan the provided directory for a .env file\n const envPath = await findUp('.env', { cwd: dir })\n\n if (!envPath) {\n // No .env file found\n return {\n hasEnvFile: false,\n envHasFigmaToken: false,\n }\n }\n\n // Read the contents of the .env file\n const envContents = fs.readFileSync(envPath, 'utf-8')\n\n // Determine if the .env file contains a FIGMA_ACCESS_TOKEN\n const envVars = envContents.split('\\n').reduce(\n (\n acc: {\n [key: string]: string\n },\n line,\n ) => {\n const [key, value] = line.split('=')\n acc[key] = value\n return acc\n },\n {},\n )\n\n const figmaAccessToken = envVars['FIGMA_ACCESS_TOKEN']\n\n return {\n hasEnvFile: true,\n envHasFigmaToken: !!figmaAccessToken,\n }\n}\n\n/**\n * Gets information about a project from config.\n *\n * @param dir Directory containing the project\n * @param config Code Connect config\n * @returns Object containing information about the project\n */\nexport async function getProjectInfoFromConfig(\n dir: string,\n config: CodeConnectConfig,\n isTemplatesOnlyCLI = false,\n): Promise<ProjectInfo> {\n const absPath = path.resolve(dir)\n const remoteUrl = getGitRemoteURL(absPath)\n\n const defaultIncludeGlobs = isTemplatesOnlyCLI\n ? DEFAULT_PARSERLESS_INCLUDE_GLOBS\n : config.parser\n ? DEFAULT_INCLUDE_GLOBS_BY_PARSER[config.parser]\n : DEFAULT_PARSERLESS_INCLUDE_GLOBS\n\n // always ignore node_modules; for parsers, apply parser-specific exclusions\n const defaultExcludeGlobs = isTemplatesOnlyCLI\n ? DEFAULT_PARSERLESS_EXCLUDE_GLOBS\n : config.parser\n ? ({\n react: ['node_modules/**'],\n html: ['node_modules/**'],\n swift: ['**/__test__/**'],\n compose: [],\n custom: [],\n __unit_test__: [],\n }[config.parser] ?? [])\n : DEFAULT_PARSERLESS_EXCLUDE_GLOBS\n\n const includeGlobs = config.include || defaultIncludeGlobs\n const excludeGlobs = config.exclude\n ? [...config.exclude, ...defaultExcludeGlobs]\n : defaultExcludeGlobs\n\n if (config.parser === 'custom' && (!includeGlobs || includeGlobs.length === 0)) {\n exitWithError('Include globs must specified in config file for custom parsers')\n }\n\n if (!includeGlobs) {\n exitWithError('No include globs specified in config file')\n }\n\n const files = globSync(mapToAbsolutePaths(includeGlobs, absPath), {\n nodir: true,\n ignore: mapToAbsolutePaths(excludeGlobs, absPath),\n // Otherwise this is true on *nix and false on Windows\n absolute: true,\n })\n\n if (files.length > 10000) {\n logger.warn(\n `Matching number of files was excessively large (${files.length}) - consider using more specific include/exclude globs in your config file.`,\n )\n }\n\n return {\n absPath,\n remoteUrl,\n config,\n files,\n }\n}\n\n/**\n * Validates the language field in the config.\n * Throws an error if the language is invalid.\n *\n * @param language The language string to validate\n */\nfunction validateLanguage(language: SyntaxHighlightLanguage | undefined): void {\n if (!language) return\n\n const validLanguages = Object.values(SyntaxHighlightLanguage)\n if (!validLanguages.includes(language)) {\n throw new Error(\n `Invalid language \"${language}\" in figma.config.json. ` +\n `Valid values are: ${validLanguages.join(', ')}`,\n )\n }\n}\n\n/**\n * Gets information about a project from a directory.\n *\n * @param dir Directory containing the project\n * @param configPath Optional path to Code Connect config file\n * @returns Object containing information about the project\n */\nexport async function getProjectInfo(\n dir: string,\n configPath: string,\n isTemplatesOnlyCLI = false,\n): Promise<ProjectInfo> {\n const { config } = await parseOrDetermineConfig(dir, configPath, isTemplatesOnlyCLI)\n\n // Validate language field if present\n validateLanguage(config.language)\n\n return getProjectInfoFromConfig(dir, config, isTemplatesOnlyCLI)\n}\n\nexport function getReactProjectInfo(\n projectInfo: ProjectInfo<CodeConnectReactConfig>,\n): ReactProjectInfo {\n const tsProgram = getTsProgram(projectInfo)\n\n return {\n ...projectInfo,\n tsProgram,\n }\n}\n\nexport function getTsProgram(projectInfo: ProjectInfo<CodeConnectConfig>): ts.Program {\n const compilerOptions: ts.CompilerOptions = {\n // This ensures the compiler can resolve imports such as \"ui/button\" when a\n // baseUrl is configured in the tsconfig of the project. We probably want a more\n // sophisticated way to parse the users tsconfig and pass it to the compiler eventually.\n baseUrl: projectInfo.absPath,\n // TODO: not sure why Node10 is needed her, but otherwise module resolution for\n // pnpm workspaces won't work\n moduleResolution: ts.ModuleResolutionKind.Node10,\n paths: 'paths' in projectInfo.config ? (projectInfo.config.paths ?? {}) : {},\n allowJs: true,\n }\n\n return ts.createProgram(projectInfo.files, compilerOptions)\n}\n\n/**\n * Change an imported path for a component like `./button` to e.g `@ui/button`, based on the config file.\n * Note that `filePath` here is the path to the source file on disk, not the module specifier.\n *\n * @param filePath\n * @param config\n * @returns\n */\nexport function mapImportPath(filePath: string, config: CodeConnectReactConfig): string | null {\n // Takes the reversed path and pattern parts and check if they match\n function isMatch(patternParts: string[], pathParts: string[]) {\n if (patternParts[0] === '*') {\n // if the path is just a wildcard and nothing else, match any import\n if (patternParts.length === 1) {\n return true\n }\n\n // if the _next_ part in the pattern does not exist in the path, it's not\n // a match.\n const index = pathParts.indexOf(patternParts[1])\n if (index === -1) {\n return false\n }\n\n // Skip to the matching part in the path and match the rest of\n // the pattern. E.g if the pattern is `*/ui/src` (reversed) and the path is\n // `button.tsx/components/ui/src`, we skip to `ui` and match the rest of the\n // pattern.\n patternParts = patternParts.slice(1)\n pathParts = pathParts.slice(index)\n }\n\n for (let i = 0; i < patternParts.length; i++) {\n if (patternParts[i] !== pathParts[i]) {\n return false\n }\n }\n return true\n }\n\n for (const [key, value] of Object.entries(config.importPaths || {})) {\n // Do a partial match from the end of the path\n const patternParts = key.split('/').reverse()\n const pathParts = filePath.split('/').reverse()\n if (pathParts.length < patternParts.length) {\n continue\n }\n\n // If the mapped path ends with a wildcard we want to keep the filename in\n // the final path\n if (isMatch(patternParts, pathParts)) {\n if (value.endsWith('*')) {\n const filename = pathParts[0].split('.')[0]\n return `${value.slice(0, -1)}${filename}`\n }\n return value\n }\n }\n\n return null\n}\n\n/**\n * Transform an import specifier (the path in the import statement) using importPaths config.\n * This works directly on the module specifier from the source code, preserving the user's intent.\n *\n * E.g., '@/AlertTitle' with config { \"@/*\": \"@acme/package/*\" } → '@acme/package/AlertTitle'\n *\n * @param specifier The original import specifier from the source file (e.g., '@/AlertTitle', './Button')\n * @param config The Code Connect config containing importPaths\n * @returns The transformed import path, or null if no mapping matched\n */\nexport function mapImportSpecifier(\n specifier: string,\n config: CodeConnectReactConfig,\n): string | null {\n for (const [pattern, replacement] of Object.entries(config.importPaths || {})) {\n // Convert glob pattern to regex: @/* → ^@/(.*)$\n // First escape special regex chars, then convert * to capture group\n const regexPattern = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&') // Escape special chars except *\n .replace(/\\*/g, '(.*)') // Convert * to capture group\n const regex = new RegExp(`^${regexPattern}$`)\n const match = specifier.match(regex)\n\n if (match) {\n // Replace * in replacement with captured group\n let result = replacement\n if (match[1] !== undefined) {\n result = replacement.replace('*', match[1])\n }\n return result\n }\n }\n return null\n}\n"]}
|
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
import { CodeConnectJSON } from './figma_connect';
|
|
2
2
|
import { CodeConnectConfig } from './project';
|
|
3
|
+
/**
|
|
4
|
+
* Thrown when a raw template file has no `// url=` directive but contains the
|
|
5
|
+
* string `codeProperties`. These files (e.g. Make's code component property
|
|
6
|
+
* definitions) are not Code Connect, so callers skip them with a log instead of
|
|
7
|
+
* failing. Every other file is handled exactly as before — a missing url is
|
|
8
|
+
* still a hard error.
|
|
9
|
+
*/
|
|
10
|
+
export declare class CodePropertiesError extends Error {
|
|
11
|
+
constructor(message: string);
|
|
12
|
+
}
|
|
3
13
|
/**
|
|
4
14
|
* Returns true if the file content looks like a raw template file, i.e. its
|
|
5
15
|
* leading comment block contains a `// url=`, `// component=`, or `// source=`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"raw_templates.d.ts","sourceRoot":"","sources":["../../src/connect/raw_templates.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAA;AAI7C;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAatD;
|
|
1
|
+
{"version":3,"file":"raw_templates.d.ts","sourceRoot":"","sources":["../../src/connect/raw_templates.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAA;AAI7C;;;;;;GAMG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;gBAChC,OAAO,EAAE,MAAM;CAI5B;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAatD;AAsFD,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAA;IACX,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC9B,aAAa,EAAE,MAAM,CAAA;CACtB;AAED,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,MAAM,CAAC,EAAE,iBAAiB,EAC1B,GAAG,CAAC,EAAE,MAAM,EACZ,cAAc,CAAC,EAAE,cAAc,GAC9B,eAAe,CAgGjB"}
|
|
@@ -3,12 +3,27 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.CodePropertiesError = void 0;
|
|
6
7
|
exports.isRawTemplate = isRawTemplate;
|
|
7
8
|
exports.parseRawFile = parseRawFile;
|
|
8
9
|
const fs_1 = __importDefault(require("fs"));
|
|
9
10
|
const typescript_1 = __importDefault(require("typescript"));
|
|
10
11
|
const label_language_mapping_1 = require("./label_language_mapping");
|
|
11
12
|
const helpers_1 = require("./helpers");
|
|
13
|
+
/**
|
|
14
|
+
* Thrown when a raw template file has no `// url=` directive but contains the
|
|
15
|
+
* string `codeProperties`. These files (e.g. Make's code component property
|
|
16
|
+
* definitions) are not Code Connect, so callers skip them with a log instead of
|
|
17
|
+
* failing. Every other file is handled exactly as before — a missing url is
|
|
18
|
+
* still a hard error.
|
|
19
|
+
*/
|
|
20
|
+
class CodePropertiesError extends Error {
|
|
21
|
+
constructor(message) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.name = 'CodePropertiesError';
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
exports.CodePropertiesError = CodePropertiesError;
|
|
12
27
|
/**
|
|
13
28
|
* Returns true if the file content looks like a raw template file, i.e. its
|
|
14
29
|
* leading comment block contains a `// url=`, `// component=`, or `// source=`
|
|
@@ -29,20 +44,21 @@ function isRawTemplate(content) {
|
|
|
29
44
|
}
|
|
30
45
|
return false;
|
|
31
46
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
//
|
|
47
|
+
// Convert ESM import of 'figma' to require syntax. Supports: import figma from 'figma'
|
|
48
|
+
const figmaImportRegex = /^import\s+figma\s+from\s+['"]figma['"]\s*;?\s*$/m;
|
|
49
|
+
/**
|
|
50
|
+
* Throws if the file imports from anything other than 'figma'. Type-only imports
|
|
51
|
+
* (`import type`) are erased by the TS compiler and are fine; the `figma` default
|
|
52
|
+
* import is the one supported module (no bundling in Phase 1). This runs BEFORE
|
|
53
|
+
* the `codeProperties` skip guard so an unsupported import is always a hard error,
|
|
54
|
+
* even in a file that would otherwise be skipped.
|
|
55
|
+
*/
|
|
56
|
+
function assertOnlyFigmaImports(filePath, fileContent) {
|
|
57
|
+
// Ignore the supported `import figma from 'figma'` form before scanning.
|
|
58
|
+
const withoutFigmaImport = fileContent.replace(figmaImportRegex, '');
|
|
43
59
|
const importRegex = /^import\s+(?!type\s)/m;
|
|
44
|
-
if (importRegex.test(
|
|
45
|
-
const match =
|
|
60
|
+
if (importRegex.test(withoutFigmaImport)) {
|
|
61
|
+
const match = withoutFigmaImport.match(/^(import\s+.+)$/m);
|
|
46
62
|
const importLine = match ? match[1] : 'import ...';
|
|
47
63
|
throw new Error(`TypeScript template files only support importing from 'figma'.\n` +
|
|
48
64
|
`Found in ${filePath}:\n` +
|
|
@@ -50,6 +66,11 @@ function transpileTypeScriptTemplate(filePath, fileContent) {
|
|
|
50
66
|
`Use "const figma = require('figma')" or "import figma from 'figma'" to access the Figma API.\n` +
|
|
51
67
|
`Other module imports will be supported in a future version.`);
|
|
52
68
|
}
|
|
69
|
+
}
|
|
70
|
+
function transpileTypeScriptTemplate(filePath, fileContent) {
|
|
71
|
+
if (figmaImportRegex.test(fileContent)) {
|
|
72
|
+
fileContent = fileContent.replace(figmaImportRegex, "const figma = require('figma')");
|
|
73
|
+
}
|
|
53
74
|
const result = typescript_1.default.transpileModule(fileContent, {
|
|
54
75
|
compilerOptions: {
|
|
55
76
|
module: typescript_1.default.ModuleKind.ESNext,
|
|
@@ -99,13 +120,26 @@ function parseRawFile(filePath, label, config, dir, batchOverrides) {
|
|
|
99
120
|
// Extract metadata fields BEFORE transpilation to avoid losing comments
|
|
100
121
|
// that appear before type-only imports (which TypeScript erases)
|
|
101
122
|
const { fields, templateStartLine } = extractMetadataFields(fileContent);
|
|
123
|
+
const figmaUrl = batchOverrides?.url || fields.url;
|
|
124
|
+
// An unsupported (non-figma) import is always a hard error, even in a file that
|
|
125
|
+
// would otherwise be skipped as a `codeProperties` file below. Checked first so
|
|
126
|
+
// an import mistake is never silently swallowed by the skip guard.
|
|
127
|
+
if (filePath.endsWith('.ts')) {
|
|
128
|
+
assertOnlyFigmaImports(filePath, fileContent);
|
|
129
|
+
}
|
|
130
|
+
// A file with no // url= directive that contains the string `codeProperties`
|
|
131
|
+
// is not Code Connect (e.g. Make's code component property definitions). Skip
|
|
132
|
+
// it (callers log and continue) instead of failing. Every other file is
|
|
133
|
+
// handled exactly as before.
|
|
134
|
+
if (!figmaUrl && fileContent.includes('codeProperties')) {
|
|
135
|
+
throw new CodePropertiesError(`Skipping ${filePath}: file has no // url= directive and contains "codeProperties", so it is not treated as a Code Connect file.`);
|
|
136
|
+
}
|
|
102
137
|
if (filePath.endsWith('.ts')) {
|
|
103
138
|
fileContent = transpileTypeScriptTemplate(filePath, fileContent);
|
|
104
139
|
}
|
|
105
140
|
// For batch templates, metadata comes from the batch entry instead of comments
|
|
106
141
|
const component = batchOverrides?.component || fields.component;
|
|
107
142
|
const source = batchOverrides?.source || fields.source || '';
|
|
108
|
-
const figmaUrl = batchOverrides?.url || fields.url;
|
|
109
143
|
if (!figmaUrl) {
|
|
110
144
|
throw new Error(batchOverrides
|
|
111
145
|
? `Missing required "url" field in ${batchOverrides.batchFilePath}. Please add "url" to each entry in your .figma.batch.json file.`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"raw_templates.js","sourceRoot":"","sources":["../../src/connect/raw_templates.ts"],"names":[],"mappings":";;;;;AAaA,sCAaC;AAuFD,oCAoFC;AArMD,4CAAmB;AACnB,4DAA2B;AAG3B,qEAAsF;AACtF,uCAAyD;AAEzD;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,OAAe;IAC3C,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QACvC,MAAM,OAAO,GAAG,IAA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odeConnectConfig } from './project'\nimport { CodeConnectLabel, getInferredLanguageForRaw } from './label_language_mapping'\nimport { applyDocumentUrlSubstitutions } from './helpers'\n\n/**\n * Returns true if the file content looks like a raw template file, i.e. its\n * leading comment block contains a `// url=`, `// component=`, or `// source=`\n * directive. Used to distinguish raw `.figma.ts` templates from React/HTML\n * Code Connect files that share the same extension.\n */\nexport function isRawTemplate(content: string): boolean {\n for (const line of content.split('\\n')) {\n const trimmed = line.trim()\n if (trimmed === '' || trimmed.startsWith('//')) {\n if (/^\\/\\/\\s*(url|component|source)=/.test(trimmed)) {\n return true\n }\n continue\n }\n // First non-comment, non-blank line reached without finding a known directive — not a raw template\n break\n }\n return false\n}\n\nfunction transpileTypeScriptTemplate(filePath: string, fileContent: string): string {\n // Convert ESM import of 'figma' to require syntax\n // Supports: import figma from 'figma'\n const figmaImportRegex = /^import\\s+figma\\s+from\\s+['\"]figma['\"]\\s*;?\\s*$/m\n if (figmaImportRegex.test(fileContent)) {\n fileContent = fileContent.replace(figmaImportRegex, \"const figma = require('figma')\")\n }\n\n // Detect any remaining non-type import statements. Type-only imports (`import type`)\n // are erased by the TS compiler and are fine. Regular imports (except the figma\n // import we just converted) are not supported in Phase 1 (no bundling), so we show\n // a helpful error.\n const importRegex = /^import\\s+(?!type\\s)/m\n if (importRegex.test(fileContent)) {\n const match = fileContent.match(/^(import\\s+.+)$/m)\n const importLine = match ? match[1] : 'import ...'\n throw new Error(\n `TypeScript template files only support importing from 'figma'.\\n` +\n `Found in ${filePath}:\\n` +\n ` ${importLine}\\n\\n` +\n `Use \"const figma = require('figma')\" or \"import figma from 'figma'\" to access the Figma API.\\n` +\n `Other module imports will be supported in a future version.`,\n )\n }\n\n const result = ts.transpileModule(fileContent, {\n compilerOptions: {\n module: ts.ModuleKind.ESNext,\n target: ts.ScriptTarget.ES2021,\n removeComments: false,\n },\n })\n\n return result.outputText\n}\n\n/**\n * Extracts metadata fields (url, component, source) from the leading comments\n * of a raw template file. This must be done before transpilation because\n * TypeScript can remove comments that appear before type-only imports.\n */\nfunction extractMetadataFields(fileContent: string): {\n fields: { url?: string; component?: string; source?: string }\n templateStartLine: number\n} {\n const lines = fileContent.split('\\n')\n const fields: { url?: string; component?: string; source?: string } = {}\n let templateStartLine = 0\n\n // Parse consecutive comment lines at the start of the file\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim()\n // Match pattern: // fieldName=value\n const match = line.match(/^\\/\\/\\s*(\\w+)=(.+)$/)\n if (match) {\n const [, fieldName, fieldValue] = match\n const normalizedFieldName = fieldName.toLowerCase()\n if (\n normalizedFieldName === 'url' ||\n normalizedFieldName === 'component' ||\n normalizedFieldName === 'source'\n ) {\n fields[normalizedFieldName] = fieldValue.trim()\n }\n templateStartLine = i + 1\n } else if (line === '' || line.startsWith('//')) {\n // Allow blank lines or other comments, but don't increment template start\n continue\n } else {\n // First non-comment line found\n break\n }\n }\n\n return { fields, templateStartLine }\n}\n\nexport interface BatchOverrides {\n url: string\n source?: string\n component?: string\n batchData: Record<string, any>\n batchFilePath: string\n}\n\nexport function parseRawFile(\n filePath: string,\n label: string | undefined,\n config?: CodeConnectConfig,\n dir?: string,\n batchOverrides?: BatchOverrides,\n): CodeConnectJSON {\n let fileContent = fs.readFileSync(filePath, 'utf-8')\n\n // Extract metadata fields BEFORE transpilation to avoid losing comments\n // that appear before type-only imports (which TypeScript erases)\n const { fields, templateStartLine } = extractMetadataFields(fileContent)\n\n if (filePath.endsWith('.ts')) {\n fileContent = transpileTypeScriptTemplate(filePath, fileContent)\n }\n\n // For batch templates, metadata comes from the batch entry instead of comments\n const component = batchOverrides?.component || fields.component\n const source = batchOverrides?.source || fields.source || ''\n\n const figmaUrl = batchOverrides?.url || fields.url\n if (!figmaUrl) {\n throw new Error(\n batchOverrides\n ? `Missing required \"url\" field in ${batchOverrides.batchFilePath}. Please add \"url\" to each entry in your .figma.batch.json file.`\n : `Missing required url field in ${filePath}. Please add a // url=... comment to the top of the file.`,\n )\n }\n let figmaNodeUrl = figmaUrl\n\n // Extract template from the transpiled content, starting at the line\n // where the metadata comments ended in the original source\n const transpiledLines = fileContent.split('\\n')\n let templateStartIndex = 0\n\n // Skip lines until we've passed the original metadata comment section\n for (let i = 0; i < transpiledLines.length; i++) {\n const line = transpiledLines[i].trim()\n // Skip blank lines and comments at the start\n if (line === '' || line.startsWith('//')) {\n continue\n }\n // First non-comment line in transpiled output\n templateStartIndex = i\n break\n }\n\n let template = transpiledLines.slice(templateStartIndex).join('\\n')\n\n // For batch templates, set globalThis['__FIGMA_BATCH'] so the runtime exposes it as\n // figma.batch. Using globalThis rather than a const so it's accessible from\n // __FIGMA_CODE_CONNECT_REQUIRE's closure regardless of where require('figma') is called.\n // (globalThis works in both browser and Node.js, unlike window.)\n if (batchOverrides) {\n template = `globalThis['__FIGMA_BATCH'] = ${JSON.stringify(batchOverrides.batchData)}\\n${template}`\n }\n\n // Apply documentUrlSubstitutions if provided\n if (config?.documentUrlSubstitutions) {\n figmaNodeUrl = applyDocumentUrlSubstitutions(figmaNodeUrl, config.documentUrlSubstitutions)\n }\n\n // Determine effective label from parameter, config, or default\n const effectiveLabel = label || config?.label || CodeConnectLabel.Code\n\n const language = config?.language || getInferredLanguageForRaw(effectiveLabel)\n\n return {\n figmaNode: figmaNodeUrl,\n component,\n template,\n // nestable by default unless user specifies in template\n // (templateData.nestable AND template.metadata.nestable need to\n // be true for instance to be nested)\n templateData: { nestable: true, isParserless: true },\n language,\n label: effectiveLabel,\n source,\n sourceLocation: { line: -1 },\n metadata: {\n cliVersion: require('../../package.json').version,\n },\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"raw_templates.js","sourceRoot":"","sources":["../../src/connect/raw_templates.ts"],"names":[],"mappings":";;;;;;AA2BA,sCAaC;AA8FD,oCAsGC;AA5OD,4CAAmB;AACnB,4DAA2B;AAG3B,qEAAsF;AACtF,uCAAyD;AAEzD;;;;;;GAMG;AACH,MAAa,mBAAoB,SAAQ,KAAK;IAC5C,YAAY,OAAe;QACz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AwB,EAAE,CAAC;QACrC,YAAY,GAAG,IAAA,uCAA6B,EAAC,YAAY,EAAE,MAAM,CAAC,wBAAwB,CAAC,CAAA;IAC7F,CAAC;IAED,+DAA+D;IAC/D,MAAM,cAAc,GAAG,KAAK,IAAI,MAAM,EAAE,KAAK,IAAI,yCAAgB,CAAC,IAAI,CAAA;IAEtE,MAAM,QAAQ,GAAG,MAAM,EAAE,QAAQ,IAAI,IAAA,kDAAyB,EAAC,cAAc,CAAC,CAAA;IAE9E,OAAO;QACL,SAAS,EAAE,YAAY;QACvB,SAAS;QACT,QAAQ;QACR,wDAAwD;QACxD,gEAAgE;QAChE,qCAAqC;QACrC,YAAY,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE;QACpD,QAAQ;QACR,KAAK,EAAE,cAAc;QACrB,MAAM;QACN,cAAc,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE;QAC5B,QAAQ,EAAE;YACR,UAAU,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO;SAClD;KACF,CAAA;AACH,CAAC","sourcesContent":["import fs from 'fs'\nimport ts from 'typescript'\nimport { CodeConnectJSON } from './figma_connect'\nimport { CodeConnectConfig } from './project'\nimport { CodeConnectLabel, getInferredLanguageForRaw } from './label_language_mapping'\nimport { applyDocumentUrlSubstitutions } from './helpers'\n\n/**\n * Thrown when a raw template file has no `// url=` directive but contains the\n * string `codeProperties`. These files (e.g. Make's code component property\n * definitions) are not Code Connect, so callers skip them with a log instead of\n * failing. Every other file is handled exactly as before — a missing url is\n * still a hard error.\n */\nexport class CodePropertiesError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'CodePropertiesError'\n }\n}\n\n/**\n * Returns true if the file content looks like a raw template file, i.e. its\n * leading comment block contains a `// url=`, `// component=`, or `// source=`\n * directive. Used to distinguish raw `.figma.ts` templates from React/HTML\n * Code Connect files that share the same extension.\n */\nexport function isRawTemplate(content: string): boolean {\n for (const line of content.split('\\n')) {\n const trimmed = line.trim()\n if (trimmed === '' || trimmed.startsWith('//')) {\n if (/^\\/\\/\\s*(url|component|source)=/.test(trimmed)) {\n return true\n }\n continue\n }\n // First non-comment, non-blank line reached without finding a known directive — not a raw template\n break\n }\n return false\n}\n\n// Convert ESM import of 'figma' to require syntax. Supports: import figma from 'figma'\nconst figmaImportRegex = /^import\\s+figma\\s+from\\s+['\"]figma['\"]\\s*;?\\s*$/m\n\n/**\n * Throws if the file imports from anything other than 'figma'. Type-only imports\n * (`import type`) are erased by the TS compiler and are fine; the `figma` default\n * import is the one supported module (no bundling in Phase 1). This runs BEFORE\n * the `codeProperties` skip guard so an unsupported import is always a hard error,\n * even in a file that would otherwise be skipped.\n */\nfunction assertOnlyFigmaImports(filePath: string, fileContent: string): void {\n // Ignore the supported `import figma from 'figma'` form before scanning.\n const withoutFigmaImport = fileContent.replace(figmaImportRegex, '')\n const importRegex = /^import\\s+(?!type\\s)/m\n if (importRegex.test(withoutFigmaImport)) {\n const match = withoutFigmaImport.match(/^(import\\s+.+)$/m)\n const importLine = match ? match[1] : 'import ...'\n throw new Error(\n `TypeScript template files only support importing from 'figma'.\\n` +\n `Found in ${filePath}:\\n` +\n ` ${importLine}\\n\\n` +\n `Use \"const figma = require('figma')\" or \"import figma from 'figma'\" to access the Figma API.\\n` +\n `Other module imports will be supported in a future version.`,\n )\n }\n}\n\nfunction transpileTypeScriptTemplate(filePath: string, fileContent: string): string {\n if (figmaImportRegex.test(fileContent)) {\n fileContent = fileContent.replace(figmaImportRegex, \"const figma = require('figma')\")\n }\n\n const result = ts.transpileModule(fileContent, {\n compilerOptions: {\n module: ts.ModuleKind.ESNext,\n target: ts.ScriptTarget.ES2021,\n removeComments: false,\n },\n })\n\n return result.outputText\n}\n\n/**\n * Extracts metadata fields (url, component, source) from the leading comments\n * of a raw template file. This must be done before transpilation because\n * TypeScript can remove comments that appear before type-only imports.\n */\nfunction extractMetadataFields(fileContent: string): {\n fields: { url?: string; component?: string; source?: string }\n templateStartLine: number\n} {\n const lines = fileContent.split('\\n')\n const fields: { url?: string; component?: string; source?: string } = {}\n let templateStartLine = 0\n\n // Parse consecutive comment lines at the start of the file\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim()\n // Match pattern: // fieldName=value\n const match = line.match(/^\\/\\/\\s*(\\w+)=(.+)$/)\n if (match) {\n const [, fieldName, fieldValue] = match\n const normalizedFieldName = fieldName.toLowerCase()\n if (\n normalizedFieldName === 'url' ||\n normalizedFieldName === 'component' ||\n normalizedFieldName === 'source'\n ) {\n fields[normalizedFieldName] = fieldValue.trim()\n }\n templateStartLine = i + 1\n } else if (line === '' || line.startsWith('//')) {\n // Allow blank lines or other comments, but don't increment template start\n continue\n } else {\n // First non-comment line found\n break\n }\n }\n\n return { fields, templateStartLine }\n}\n\nexport interface BatchOverrides {\n url: string\n source?: string\n component?: string\n batchData: Record<string, any>\n batchFilePath: string\n}\n\nexport function parseRawFile(\n filePath: string,\n label: string | undefined,\n config?: CodeConnectConfig,\n dir?: string,\n batchOverrides?: BatchOverrides,\n): CodeConnectJSON {\n let fileContent = fs.readFileSync(filePath, 'utf-8')\n\n // Extract metadata fields BEFORE transpilation to avoid losing comments\n // that appear before type-only imports (which TypeScript erases)\n const { fields, templateStartLine } = extractMetadataFields(fileContent)\n\n const figmaUrl = batchOverrides?.url || fields.url\n\n // An unsupported (non-figma) import is always a hard error, even in a file that\n // would otherwise be skipped as a `codeProperties` file below. Checked first so\n // an import mistake is never silently swallowed by the skip guard.\n if (filePath.endsWith('.ts')) {\n assertOnlyFigmaImports(filePath, fileContent)\n }\n\n // A file with no // url= directive that contains the string `codeProperties`\n // is not Code Connect (e.g. Make's code component property definitions). Skip\n // it (callers log and continue) instead of failing. Every other file is\n // handled exactly as before.\n if (!figmaUrl && fileContent.includes('codeProperties')) {\n throw new CodePropertiesError(\n `Skipping ${filePath}: file has no // url= directive and contains \"codeProperties\", so it is not treated as a Code Connect file.`,\n )\n }\n\n if (filePath.endsWith('.ts')) {\n fileContent = transpileTypeScriptTemplate(filePath, fileContent)\n }\n\n // For batch templates, metadata comes from the batch entry instead of comments\n const component = batchOverrides?.component || fields.component\n const source = batchOverrides?.source || fields.source || ''\n\n if (!figmaUrl) {\n throw new Error(\n batchOverrides\n ? `Missing required \"url\" field in ${batchOverrides.batchFilePath}. Please add \"url\" to each entry in your .figma.batch.json file.`\n : `Missing required url field in ${filePath}. Please add a // url=... comment to the top of the file.`,\n )\n }\n let figmaNodeUrl = figmaUrl\n\n // Extract template from the transpiled content, starting at the line\n // where the metadata comments ended in the original source\n const transpiledLines = fileContent.split('\\n')\n let templateStartIndex = 0\n\n // Skip lines until we've passed the original metadata comment section\n for (let i = 0; i < transpiledLines.length; i++) {\n const line = transpiledLines[i].trim()\n // Skip blank lines and comments at the start\n if (line === '' || line.startsWith('//')) {\n continue\n }\n // First non-comment line in transpiled output\n templateStartIndex = i\n break\n }\n\n let template = transpiledLines.slice(templateStartIndex).join('\\n')\n\n // For batch templates, set globalThis['__FIGMA_BATCH'] so the runtime exposes it as\n // figma.batch. Using globalThis rather than a const so it's accessible from\n // __FIGMA_CODE_CONNECT_REQUIRE's closure regardless of where require('figma') is called.\n // (globalThis works in both browser and Node.js, unlike window.)\n if (batchOverrides) {\n template = `globalThis['__FIGMA_BATCH'] = ${JSON.stringify(batchOverrides.batchData)}\\n${template}`\n }\n\n // Apply documentUrlSubstitutions if provided\n if (config?.documentUrlSubstitutions) {\n figmaNodeUrl = applyDocumentUrlSubstitutions(figmaNodeUrl, config.documentUrlSubstitutions)\n }\n\n // Determine effective label from parameter, config, or default\n const effectiveLabel = label || config?.label || CodeConnectLabel.Code\n\n const language = config?.language || getInferredLanguageForRaw(effectiveLabel)\n\n return {\n figmaNode: figmaNodeUrl,\n component,\n template,\n // nestable by default unless user specifies in template\n // (templateData.nestable AND template.metadata.nestable need to\n // be true for instance to be nested)\n templateData: { nestable: true, isParserless: true },\n language,\n label: effectiveLabel,\n source,\n sourceLocation: { line: -1 },\n metadata: {\n cliVersion: require('../../package.json').version,\n },\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../../src/connect/upload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;
|
|
1
|
+
{"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../../src/connect/upload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAyD1D,UAAU,IAAI;IACZ,WAAW,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,IAAI,EAAE,eAAe,EAAE,CAAA;IACvB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,KAAK,CAAC,EAAE,OAAO,CAAA;CAChB;AA0CD;;GAEG;AACH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,eAAe,EAAE,EACvB,OAAO,EAAE,OAAO,GACf,GAAG,CAAC,MAAM,EAAE,eAAe,EAAE,CAAC,CAkBhC;AAED,wBAAsB,MAAM,CAAC,EAC3B,WAAW,EACX,QAAgB,EAChB,IAAI,EACJ,SAAS,EACT,OAAO,EACP,MAAM,EAAE,cAAc,EACtB,KAAK,GACN,EAAE,IAAI,iBAuNN"}
|
package/dist/connect/upload.js
CHANGED
|
@@ -8,30 +8,46 @@ const helpers_1 = require("./helpers");
|
|
|
8
8
|
const validation_1 = require("./validation");
|
|
9
9
|
const fetch_1 = require("../common/fetch");
|
|
10
10
|
const COMPONENT_BROWSER_CONFLICT_REASON = 'Code Connect UI mapping already exists';
|
|
11
|
-
|
|
11
|
+
// 429 (rate limit): extended schedule, ignore Retry-After to keep waits predictable.
|
|
12
|
+
const RETRY_DELAYS_MS_429 = [5_000, 15_000, 30_000, 45_000, 60_000, 75_000];
|
|
13
|
+
// 5xx (server error): original shorter schedule, still honoring Retry-After if provided.
|
|
14
|
+
const RETRY_DELAYS_MS_5XX = [5_000, 15_000, 30_000];
|
|
12
15
|
async function postWithRetry(apiUrl, batch, accessToken, useOAuth = false) {
|
|
13
|
-
|
|
16
|
+
let attempt429 = 0;
|
|
17
|
+
let attempt5xx = 0;
|
|
18
|
+
// eslint-disable-next-line no-constant-condition
|
|
19
|
+
while (true) {
|
|
14
20
|
try {
|
|
15
21
|
return await fetch_1.request.post(apiUrl, batch, { headers: (0, figma_rest_api_1.getHeaders)(accessToken, useOAuth) });
|
|
16
22
|
}
|
|
17
23
|
catch (err) {
|
|
18
|
-
if ((0, fetch_1.isFetchError)(err)
|
|
19
|
-
|
|
24
|
+
if (!(0, fetch_1.isFetchError)(err))
|
|
25
|
+
throw err;
|
|
26
|
+
const status = err.response.status;
|
|
27
|
+
if (status === 429) {
|
|
28
|
+
if (attempt429 === RETRY_DELAYS_MS_429.length)
|
|
29
|
+
throw err;
|
|
30
|
+
const delayMs = RETRY_DELAYS_MS_429[attempt429];
|
|
31
|
+
logging_1.logger.warn(`Received 429, retrying in ${delayMs / 1000}s (attempt ${attempt429 + 1}/${RETRY_DELAYS_MS_429.length})...`);
|
|
32
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
33
|
+
attempt429++;
|
|
34
|
+
}
|
|
35
|
+
else if (status >= 500) {
|
|
36
|
+
if (attempt5xx === RETRY_DELAYS_MS_5XX.length)
|
|
20
37
|
throw err;
|
|
21
|
-
}
|
|
22
38
|
const retryAfterSec = err.response.headers.get('Retry-After');
|
|
23
39
|
const delayMs = retryAfterSec
|
|
24
40
|
? parseInt(retryAfterSec, 10) * 1_000
|
|
25
|
-
:
|
|
26
|
-
logging_1.logger.warn(`Received ${
|
|
41
|
+
: RETRY_DELAYS_MS_5XX[attempt5xx];
|
|
42
|
+
logging_1.logger.warn(`Received ${status}, retrying in ${delayMs / 1000}s (attempt ${attempt5xx + 1}/${RETRY_DELAYS_MS_5XX.length})...`);
|
|
27
43
|
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
44
|
+
attempt5xx++;
|
|
28
45
|
}
|
|
29
46
|
else {
|
|
30
47
|
throw err;
|
|
31
48
|
}
|
|
32
49
|
}
|
|
33
50
|
}
|
|
34
|
-
throw new Error('Unreachable');
|
|
35
51
|
}
|
|
36
52
|
/**
|
|
37
53
|
* Returns a string representation of the code connect JSON
|