@figma/code-connect 1.3.13 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/commands/connect.d.ts +1 -1
  2. package/dist/commands/connect.d.ts.map +1 -1
  3. package/dist/commands/connect.js +104 -25
  4. package/dist/commands/connect.js.map +1 -1
  5. package/dist/common/error_formatting.d.ts +34 -0
  6. package/dist/common/error_formatting.d.ts.map +1 -0
  7. package/dist/common/error_formatting.js +115 -0
  8. package/dist/common/error_formatting.js.map +1 -0
  9. package/dist/connect/api.d.ts +13 -0
  10. package/dist/connect/api.d.ts.map +1 -1
  11. package/dist/connect/api.js.map +1 -1
  12. package/dist/connect/external_types.d.ts +1 -0
  13. package/dist/connect/external_types.d.ts.map +1 -1
  14. package/dist/connect/external_types.js +4 -0
  15. package/dist/connect/external_types.js.map +1 -1
  16. package/dist/connect/figma_connect.d.ts +3 -1
  17. package/dist/connect/figma_connect.d.ts.map +1 -1
  18. package/dist/connect/figma_connect.js.map +1 -1
  19. package/dist/connect/intrinsics.d.ts +9 -2
  20. package/dist/connect/intrinsics.d.ts.map +1 -1
  21. package/dist/connect/intrinsics.js +19 -0
  22. package/dist/connect/intrinsics.js.map +1 -1
  23. package/dist/connect/label_language_mapping.d.ts +20 -5
  24. package/dist/connect/label_language_mapping.d.ts.map +1 -1
  25. package/dist/connect/label_language_mapping.js +36 -22
  26. package/dist/connect/label_language_mapping.js.map +1 -1
  27. package/dist/connect/migration_helpers.d.ts +22 -2
  28. package/dist/connect/migration_helpers.d.ts.map +1 -1
  29. package/dist/connect/migration_helpers.js +184 -24
  30. package/dist/connect/migration_helpers.js.map +1 -1
  31. package/dist/connect/parser_common.d.ts.map +1 -1
  32. package/dist/connect/parser_common.js +1 -0
  33. package/dist/connect/parser_common.js.map +1 -1
  34. package/dist/connect/parser_executable_types.d.ts +11 -5
  35. package/dist/connect/parser_executable_types.d.ts.map +1 -1
  36. package/dist/connect/parser_executable_types.js +5 -1
  37. package/dist/connect/parser_executable_types.js.map +1 -1
  38. package/dist/connect/project.d.ts +3 -2
  39. package/dist/connect/project.d.ts.map +1 -1
  40. package/dist/connect/project.js +1 -1
  41. package/dist/connect/project.js.map +1 -1
  42. package/dist/connect/upload.d.ts.map +1 -1
  43. package/dist/connect/upload.js +9 -4
  44. package/dist/connect/upload.js.map +1 -1
  45. package/dist/html/external.d.ts +1 -1
  46. package/dist/html/external.d.ts.map +1 -1
  47. package/dist/html/external.js +1 -0
  48. package/dist/html/external.js.map +1 -1
  49. package/dist/html/parser.js +1 -1
  50. package/dist/html/parser.js.map +1 -1
  51. package/dist/react/create.d.ts.map +1 -1
  52. package/dist/react/create.js +3 -0
  53. package/dist/react/create.js.map +1 -1
  54. package/dist/react/external.d.ts +2 -2
  55. package/dist/react/external.d.ts.map +1 -1
  56. package/dist/react/external.js +2 -1
  57. package/dist/react/external.js.map +1 -1
  58. package/dist/react/parser.js +1 -1
  59. package/dist/react/parser.js.map +1 -1
  60. package/dist/react/parser_template_helpers.d.ts.map +1 -1
  61. package/dist/react/parser_template_helpers.js +4 -1
  62. package/dist/react/parser_template_helpers.js.map +1 -1
  63. package/dist/storybook/convert.js +1 -1
  64. package/dist/storybook/convert.js.map +1 -1
  65. package/package.json +4 -2
@@ -1 +1 @@
1
- {"version":3,"file":"upload.js","sourceRoot":"","sources":["../../src/connect/upload.ts"],"names":[],"mappings":";;AA0DA,sCAqBC;AAED,wBAwLC;AAxQD,+CAAgE;AAChE,qDAAwD;AACxD,uCAAmD;AACnD,6CAA6C;AAC7C,2CAAuD;AAsBvD;;;;GAIG;AACH,SAAS,cAAc,CAAC,GAAoB;IAC1C,OAAO,GAAG,IAAA,mBAAS,EAAC,GAAG,CAAC,SAAS,IAAI,EAAE,CAAC,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CA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AACH,CAAC","sourcesContent":["import { CodeConnectJSON } from '../connect/figma_connect'\nimport { logger, underline, highlight } from '../common/logging'\nimport { getApiUrl, getHeaders } from './figma_rest_api'\nimport { exitWithFeedbackMessage } from './helpers'\nimport { parseFigmaNode } from './validation'\nimport { isFetchError, request } from '../common/fetch'\n\ninterface Args {\n accessToken: string\n docs: CodeConnectJSON[]\n batchSize?: number\n verbose: boolean\n apiUrl?: string\n}\n\ninterface UploadResponse {\n status: number\n error: boolean\n meta: {\n success: boolean\n published_count: number\n failed_count: number\n published_nodes: Array<{ figmaNode: string; label: string }>\n failed_nodes: Array<{ figmaNode: string; label: string; reason: string }>\n }\n}\n\n/**\n * Returns a string representation of the code connect JSON\n * @param doc - The code connect JSON\n * @returns A string representation of the code connect JSON\n */\nfunction codeConnectStr(doc: CodeConnectJSON): string {\n return `${highlight(doc.component ?? '')}${doc.variant ? `(${Object.entries(doc.variant).map(([key, value]) => `${key}=${value}`)})` : ''} ${underline(doc.figmaNode)}`\n}\n\n/**\n * Extracts the fileKey and nodeId from the Figma node URL and returns a key in the format of fileKey-nodeId\n * @param figmaNode - The Figma node URL\n * @returns The key in the format of fileKey-nodeId\n */\nfunction getKeyFromFigmaNode(figmaNode: string): string {\n const url = new URL(figmaNode)\n\n // Extract fileKey from path (after /file/ or /design/)\n const pathMatch = url.pathname.match(/\\/(file|design)\\/([A-Za-z0-9]+)/)\n const fileKey = pathMatch ? pathMatch[2] : ''\n\n // Extract nodeId from query parameter and convert format (1-24 -> 1:24)\n const nodeIdParam = url.searchParams.get('node-id') || ''\n const nodeId = nodeIdParam.replace(/-/g, ':')\n\n return `${fileKey}-${nodeId}`\n}\n\n/**\n * Creates a map from fileKey-nodeId to original docs for easy lookup\n */\nexport function createDocsMap(\n docs: CodeConnectJSON[],\n verbose: boolean,\n): Map<string, CodeConnectJSON[]> {\n const docsMap = new Map<string, CodeConnectJSON[]>()\n\n for (const doc of docs) {\n const parsedData = parseFigmaNode(verbose, doc)\n if (!parsedData) {\n continue\n }\n\n const mapKey = `${parsedData.fileKey}-${parsedData.nodeId}`\n if (!docsMap.has(mapKey)) {\n docsMap.set(mapKey, [])\n }\n\n docsMap.get(mapKey)?.push(doc)\n }\n\n return docsMap\n}\n\nexport async function upload({\n accessToken,\n docs,\n batchSize,\n verbose,\n apiUrl: apiUrlOverride,\n}: Args) {\n const apiUrl = getApiUrl(docs?.[0]?.figmaNode ?? '', apiUrlOverride) + '/code_connect'\n\n try {\n logger.info(`Uploading to Figma...`)\n\n // Create a map from fileKey-nodeId to original docs for detailed output\n const docsMap = createDocsMap(docs, verbose)\n\n let allUploadedNodes = new Set<string>()\n let allFailedNodes = new Map<string, string>() // key -> failure reason\n\n if (batchSize) {\n if (typeof batchSize !== 'number') {\n logger.error('Batch size must be a number')\n exitWithFeedbackMessage(1)\n }\n\n // batch together based on fileKey + nodeId as all variants etc of the same node should be uploaded together\n // Otherwise, the server will overwrite the previous upload\n const groupedDocs = docs.reduce(\n (acc, doc) => {\n const parsedData = parseFigmaNode(verbose, doc)\n\n if (!parsedData) {\n exitWithFeedbackMessage(1)\n }\n\n const { fileKey, nodeId } = parsedData\n const accKey = fileKey + ',' + nodeId\n if (!acc[accKey]) {\n acc[accKey] = []\n }\n acc[accKey].push(doc)\n return acc\n },\n {} as Record<string, CodeConnectJSON[]>,\n )\n\n const batchedDocs: CodeConnectJSON[][] = []\n const nodeKeys = Object.keys(groupedDocs)\n\n for (let i = 0; i < nodeKeys.length; i += batchSize) {\n const batch: CodeConnectJSON[] = []\n for (let j = i; j < i + batchSize && j < nodeKeys.length; j++) {\n const nodeKey = nodeKeys[j]\n batch.push(...groupedDocs[nodeKey])\n }\n batchedDocs.push(batch)\n }\n\n let currentBatch = 1\n const noOfBatches = batchedDocs.length\n for (const batch of batchedDocs) {\n process.stderr.write('\\x1b[2K\\x1b[0G')\n process.stderr.write(`Uploading batch ${currentBatch}/${noOfBatches}`)\n\n var size = Buffer.byteLength(JSON.stringify(batch)) / (1024 * 1024)\n\n // Server has a limit of 5mb\n if (size > 5) {\n logger.error(\n `Failed to upload to Figma: The request is too large (${size.toFixed(2)}mb).`,\n )\n logger.error(\n 'Please try reducing the size of uploads by splitting them into smaller requests by running again and decreasing the --batch-size parameter.',\n )\n exitWithFeedbackMessage(1)\n }\n\n logger.debug(`Uploading ${size.toFixed(2)}mb to Figma`)\n\n const response = await request.post<UploadResponse>(apiUrl, batch, {\n headers: getHeaders(accessToken),\n })\n\n const data = response.data\n\n if (data.meta?.published_nodes) {\n data.meta.published_nodes.forEach((node) =>\n allUploadedNodes.add(getKeyFromFigmaNode(node.figmaNode)),\n )\n }\n if (data.meta?.failed_nodes) {\n data.meta.failed_nodes.forEach((node) =>\n allFailedNodes.set(getKeyFromFigmaNode(node.figmaNode), node.reason),\n )\n }\n\n currentBatch++\n }\n process.stderr.write(`\\n`)\n } else {\n var size = Buffer.byteLength(JSON.stringify(docs)) / (1024 * 1024)\n\n // Server has a limit of 5mb\n if (size > 5) {\n logger.error(`Failed to upload to Figma: The request is too large (${size.toFixed(2)}mb).`)\n logger.error(\n 'Please try reducing the size of uploads by splitting them into smaller requests by running again with the --batch-size parameter. You can do also this by running on different subdirectories using the --dir flag or by iteratively adjusting the includes field in the configuration.',\n )\n exitWithFeedbackMessage(1)\n }\n\n logger.debug(`Uploading ${size.toFixed(2)}mb to Figma`)\n logger.info(`uploading to ${apiUrl}`)\n\n const response = await request.post<UploadResponse>(apiUrl, docs, {\n headers: getHeaders(accessToken),\n })\n\n const data = response.data\n\n if (data.meta?.published_nodes) {\n data.meta.published_nodes.forEach((node) =>\n allUploadedNodes.add(getKeyFromFigmaNode(node.figmaNode)),\n )\n }\n if (data.meta?.failed_nodes) {\n data.meta.failed_nodes.forEach((node) =>\n allFailedNodes.set(getKeyFromFigmaNode(node.figmaNode), node.reason),\n )\n }\n }\n\n // Separate successful and failed uploads\n const successfulDocsByLabel: Record<string, CodeConnectJSON[]> = {}\n const failedDocsByLabel: Record<string, Array<{ doc: CodeConnectJSON; reason: string }>> = {}\n\n for (const [mapKey, nodeDocs] of docsMap.entries()) {\n for (const doc of nodeDocs) {\n const label = doc.label\n const docKey = getKeyFromFigmaNode(doc.figmaNode)\n const isUploaded = allUploadedNodes.has(docKey)\n const failureReason = allFailedNodes.get(docKey)\n\n if (isUploaded) {\n if (!successfulDocsByLabel[label]) {\n successfulDocsByLabel[label] = []\n }\n successfulDocsByLabel[label].push(doc)\n } else if (failureReason) {\n if (!failedDocsByLabel[label]) {\n failedDocsByLabel[label] = []\n }\n failedDocsByLabel[label].push({ doc, reason: failureReason })\n }\n }\n }\n\n for (const [label, docs] of Object.entries(successfulDocsByLabel)) {\n logger.info(\n `Successfully uploaded to Figma, for ${label}:\\n${docs.map((doc) => `-> ${codeConnectStr(doc)}`).join('\\n')}`,\n )\n }\n\n if (Object.keys(failedDocsByLabel).length > 0) {\n for (const [label, failedItems] of Object.entries(failedDocsByLabel)) {\n logger.error(\n `Failed to upload to Figma, for ${label}:\\n${failedItems.map((item) => `-> ${codeConnectStr(item.doc)} (${item.reason})`).join('\\n')}`,\n )\n }\n }\n } catch (err) {\n if (isFetchError(err)) {\n if (err.response) {\n logger.error(\n `Failed to upload to Figma (${err.response.status}): ${err.response.status} ${err.data?.message}`,\n )\n } else {\n logger.error(`Failed to upload to Figma: ${err.message}`)\n }\n logger.debug(JSON.stringify(err?.data))\n } else {\n logger.error(`Failed to upload to Figma: ${err}`)\n }\n exitWithFeedbackMessage(1)\n }\n}\n"]}
1
+ {"version":3,"file":"upload.js","sourceRoot":"","sources":["../../src/connect/upload.ts"],"names":[],"mappings":";;AA0DA,sCAqBC;AAED,wBA8LC;AA9QD,+CAAgE;AAChE,qDAAwD;AACxD,uCAAmD;AACnD,6CAA6C;AAC7C,2CAAuD;AAsBvD;;;;GAIG;AACH,SAAS,cAAc,CAAC,GAAoB;IAC1C,OAAO,GAAG,IAAA,mBAAS,EAAC,GAAG,CAAC,SAAS,IAAI,EAAE,CAAC,GAAG,GAAG,CAAC,OAAO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A8B,GAAG,CAAC,OAAO,EAAE,CAAC,CAAA;YAC3D,CAAC;YACD,gBAAM,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAA;QACzC,CAAC;aAAM,CAAC;YACN,gBAAM,CAAC,KAAK,CAAC,8BAA8B,GAAG,EAAE,CAAC,CAAA;QACnD,CAAC;QACD,IAAA,iCAAuB,EAAC,CAAC,CAAC,CAAA;IAC5B,CAAC;AACH,CAAC","sourcesContent":["import { CodeConnectJSON } from '../connect/figma_connect'\nimport { logger, underline, highlight } from '../common/logging'\nimport { getApiUrl, getHeaders } from './figma_rest_api'\nimport { exitWithFeedbackMessage } from './helpers'\nimport { parseFigmaNode } from './validation'\nimport { isFetchError, request } from '../common/fetch'\n\ninterface Args {\n accessToken: string\n docs: CodeConnectJSON[]\n batchSize?: number\n verbose: boolean\n apiUrl?: string\n}\n\ninterface UploadResponse {\n status: number\n error: boolean\n meta: {\n success: boolean\n published_count: number\n failed_count: number\n published_nodes: Array<{ figmaNode: string; label: string }>\n failed_nodes: Array<{ figmaNode: string; label: string; reason: string }>\n }\n}\n\n/**\n * Returns a string representation of the code connect JSON\n * @param doc - The code connect JSON\n * @returns A string representation of the code connect JSON\n */\nfunction codeConnectStr(doc: CodeConnectJSON): string {\n return `${highlight(doc.component ?? '')}${doc.variant ? `(${Object.entries(doc.variant).map(([key, value]) => `${key}=${value}`)})` : ''} ${underline(doc.figmaNode)}`\n}\n\n/**\n * Extracts the fileKey and nodeId from the Figma node URL and returns a key in the format of fileKey-nodeId\n * @param figmaNode - The Figma node URL\n * @returns The key in the format of fileKey-nodeId\n */\nfunction getKeyFromFigmaNode(figmaNode: string): string {\n const url = new URL(figmaNode)\n\n // Extract fileKey from path (after /file/ or /design/)\n const pathMatch = url.pathname.match(/\\/(file|design)\\/([A-Za-z0-9]+)/)\n const fileKey = pathMatch ? pathMatch[2] : ''\n\n // Extract nodeId from query parameter and convert format (1-24 -> 1:24)\n const nodeIdParam = url.searchParams.get('node-id') || ''\n const nodeId = nodeIdParam.replace(/-/g, ':')\n\n return `${fileKey}-${nodeId}`\n}\n\n/**\n * Creates a map from fileKey-nodeId to original docs for easy lookup\n */\nexport function createDocsMap(\n docs: CodeConnectJSON[],\n verbose: boolean,\n): Map<string, CodeConnectJSON[]> {\n const docsMap = new Map<string, CodeConnectJSON[]>()\n\n for (const doc of docs) {\n const parsedData = parseFigmaNode(verbose, doc)\n if (!parsedData) {\n continue\n }\n\n const mapKey = `${parsedData.fileKey}-${parsedData.nodeId}`\n if (!docsMap.has(mapKey)) {\n docsMap.set(mapKey, [])\n }\n\n docsMap.get(mapKey)?.push(doc)\n }\n\n return docsMap\n}\n\nexport async function upload({\n accessToken,\n docs,\n batchSize,\n verbose,\n apiUrl: apiUrlOverride,\n}: Args) {\n const apiUrl = getApiUrl(docs?.[0]?.figmaNode ?? '', apiUrlOverride) + '/code_connect'\n\n // Strip internal fields before uploading to Figma\n const cleanedDocs = docs.map((doc) => {\n const { _codeConnectFilePath, ...cleanDoc } = doc\n return cleanDoc as CodeConnectJSON\n })\n\n try {\n logger.info(`Uploading to Figma...`)\n\n // Create a map from fileKey-nodeId to original docs for detailed output\n const docsMap = createDocsMap(cleanedDocs, verbose)\n\n let allUploadedNodes = new Set<string>()\n let allFailedNodes = new Map<string, string>() // key -> failure reason\n\n if (batchSize) {\n if (typeof batchSize !== 'number') {\n logger.error('Batch size must be a number')\n exitWithFeedbackMessage(1)\n }\n\n // batch together based on fileKey + nodeId as all variants etc of the same node should be uploaded together\n // Otherwise, the server will overwrite the previous upload\n const groupedDocs = cleanedDocs.reduce(\n (acc, doc) => {\n const parsedData = parseFigmaNode(verbose, doc)\n\n if (!parsedData) {\n exitWithFeedbackMessage(1)\n }\n\n const { fileKey, nodeId } = parsedData\n const accKey = fileKey + ',' + nodeId\n if (!acc[accKey]) {\n acc[accKey] = []\n }\n acc[accKey].push(doc)\n return acc\n },\n {} as Record<string, CodeConnectJSON[]>,\n )\n\n const batchedDocs: CodeConnectJSON[][] = []\n const nodeKeys = Object.keys(groupedDocs)\n\n for (let i = 0; i < nodeKeys.length; i += batchSize) {\n const batch: CodeConnectJSON[] = []\n for (let j = i; j < i + batchSize && j < nodeKeys.length; j++) {\n const nodeKey = nodeKeys[j]\n batch.push(...groupedDocs[nodeKey])\n }\n batchedDocs.push(batch)\n }\n\n let currentBatch = 1\n const noOfBatches = batchedDocs.length\n for (const batch of batchedDocs) {\n process.stderr.write('\\x1b[2K\\x1b[0G')\n process.stderr.write(`Uploading batch ${currentBatch}/${noOfBatches}`)\n\n var size = Buffer.byteLength(JSON.stringify(batch)) / (1024 * 1024)\n\n // Server has a limit of 5mb\n if (size > 5) {\n logger.error(\n `Failed to upload to Figma: The request is too large (${size.toFixed(2)}mb).`,\n )\n logger.error(\n 'Please try reducing the size of uploads by splitting them into smaller requests by running again and decreasing the --batch-size parameter.',\n )\n exitWithFeedbackMessage(1)\n }\n\n logger.debug(`Uploading ${size.toFixed(2)}mb to Figma`)\n\n const response = await request.post<UploadResponse>(apiUrl, batch, {\n headers: getHeaders(accessToken),\n })\n\n const data = response.data\n\n if (data.meta?.published_nodes) {\n data.meta.published_nodes.forEach((node) =>\n allUploadedNodes.add(getKeyFromFigmaNode(node.figmaNode)),\n )\n }\n if (data.meta?.failed_nodes) {\n data.meta.failed_nodes.forEach((node) =>\n allFailedNodes.set(getKeyFromFigmaNode(node.figmaNode), node.reason),\n )\n }\n\n currentBatch++\n }\n process.stderr.write(`\\n`)\n } else {\n var size = Buffer.byteLength(JSON.stringify(cleanedDocs)) / (1024 * 1024)\n\n // Server has a limit of 5mb\n if (size > 5) {\n logger.error(`Failed to upload to Figma: The request is too large (${size.toFixed(2)}mb).`)\n logger.error(\n 'Please try reducing the size of uploads by splitting them into smaller requests by running again with the --batch-size parameter. You can do also this by running on different subdirectories using the --dir flag or by iteratively adjusting the includes field in the configuration.',\n )\n exitWithFeedbackMessage(1)\n }\n\n logger.debug(`Uploading ${size.toFixed(2)}mb to Figma`)\n logger.info(`uploading to ${apiUrl}`)\n\n const response = await request.post<UploadResponse>(apiUrl, cleanedDocs, {\n headers: getHeaders(accessToken),\n })\n\n const data = response.data\n\n if (data.meta?.published_nodes) {\n data.meta.published_nodes.forEach((node) =>\n allUploadedNodes.add(getKeyFromFigmaNode(node.figmaNode)),\n )\n }\n if (data.meta?.failed_nodes) {\n data.meta.failed_nodes.forEach((node) =>\n allFailedNodes.set(getKeyFromFigmaNode(node.figmaNode), node.reason),\n )\n }\n }\n\n // Separate successful and failed uploads\n const successfulDocsByLabel: Record<string, CodeConnectJSON[]> = {}\n const failedDocsByLabel: Record<string, Array<{ doc: CodeConnectJSON; reason: string }>> = {}\n\n for (const [mapKey, nodeDocs] of docsMap.entries()) {\n for (const doc of nodeDocs) {\n const label = doc.label\n const docKey = getKeyFromFigmaNode(doc.figmaNode)\n const isUploaded = allUploadedNodes.has(docKey)\n const failureReason = allFailedNodes.get(docKey)\n\n if (isUploaded) {\n if (!successfulDocsByLabel[label]) {\n successfulDocsByLabel[label] = []\n }\n successfulDocsByLabel[label].push(doc)\n } else if (failureReason) {\n if (!failedDocsByLabel[label]) {\n failedDocsByLabel[label] = []\n }\n failedDocsByLabel[label].push({ doc, reason: failureReason })\n }\n }\n }\n\n for (const [label, docs] of Object.entries(successfulDocsByLabel)) {\n logger.info(\n `Successfully uploaded to Figma, for ${label}:\\n${docs.map((doc) => `-> ${codeConnectStr(doc)}`).join('\\n')}`,\n )\n }\n\n if (Object.keys(failedDocsByLabel).length > 0) {\n for (const [label, failedItems] of Object.entries(failedDocsByLabel)) {\n logger.error(\n `Failed to upload to Figma, for ${label}:\\n${failedItems.map((item) => `-> ${codeConnectStr(item.doc)} (${item.reason})`).join('\\n')}`,\n )\n }\n }\n } catch (err) {\n if (isFetchError(err)) {\n if (err.response) {\n logger.error(\n `Failed to upload to Figma (${err.response.status}): ${err.response.status} ${err.data?.message}`,\n )\n } else {\n logger.error(`Failed to upload to Figma: ${err.message}`)\n }\n logger.debug(JSON.stringify(err?.data))\n } else {\n logger.error(`Failed to upload to Figma: ${err}`)\n }\n exitWithFeedbackMessage(1)\n }\n}\n"]}
@@ -4,5 +4,5 @@ import { HtmlMeta } from './types';
4
4
  declare function connectType<P = {}>(_figmaNodeUrl: string, _meta?: HtmlMeta<P>): void;
5
5
  declare function childrenType(_layers: string | string[]): HtmlTemplateString;
6
6
  export declare function instanceType<T = HtmlTemplateString>(_figmaPropName: string): T;
7
- export { booleanType as boolean, enumType as enum, stringType as string, nestedPropsType as nestedProps, classNameType as className, textContentType as textContent, connectType as connect, instanceType as instance, childrenType as children, };
7
+ export { booleanType as boolean, enumType as enum, stringType as string, nestedPropsType as nestedProps, classNameType as className, textContentType as textContent, connectType as connect, instanceType as instance, childrenType as children, instanceType as slot, };
8
8
  //# sourceMappingURL=external.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"external.d.ts","sourceRoot":"","sources":["../../src/html/external.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,QAAQ,EACR,UAAU,EACV,eAAe,EACf,aAAa,EACb,eAAe,EAChB,MAAM,2BAA2B,CAAA;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAA;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAElC,iBAAS,WAAW,CAAC,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,IAAI,CAAG;AAEjF,iBAAS,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,kBAAkB,CAIpE;AAED,wBAAgB,YAAY,CAAC,CAAC,GAAG,kBAAkB,EAAE,cAAc,EAAE,MAAM,GAAG,CAAC,CAI9E;AAED,OAAO,EACL,WAAW,IAAI,OAAO,EACtB,QAAQ,IAAI,IAAI,EAChB,UAAU,IAAI,MAAM,EACpB,eAAe,IAAI,WAAW,EAC9B,aAAa,IAAI,SAAS,EAC1B,eAAe,IAAI,WAAW,EAC9B,WAAW,IAAI,OAAO,EACtB,YAAY,IAAI,QAAQ,EACxB,YAAY,IAAI,QAAQ,GACzB,CAAA"}
1
+ {"version":3,"file":"external.d.ts","sourceRoot":"","sources":["../../src/html/external.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,QAAQ,EACR,UAAU,EACV,eAAe,EACf,aAAa,EACb,eAAe,EAChB,MAAM,2BAA2B,CAAA;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAA;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAElC,iBAAS,WAAW,CAAC,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,IAAI,CAAG;AAEjF,iBAAS,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,kBAAkB,CAIpE;AAED,wBAAgB,YAAY,CAAC,CAAC,GAAG,kBAAkB,EAAE,cAAc,EAAE,MAAM,GAAG,CAAC,CAI9E;AAED,OAAO,EACL,WAAW,IAAI,OAAO,EACtB,QAAQ,IAAI,IAAI,EAChB,UAAU,IAAI,MAAM,EACpB,eAAe,IAAI,WAAW,EAC9B,aAAa,IAAI,SAAS,EAC1B,eAAe,IAAI,WAAW,EAC9B,WAAW,IAAI,OAAO,EACtB,YAAY,IAAI,QAAQ,EACxB,YAAY,IAAI,QAAQ,EACxB,YAAY,IAAI,IAAI,GACrB,CAAA"}
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.textContent = exports.className = exports.nestedProps = exports.string = exports.enum = exports.boolean = void 0;
4
4
  exports.instanceType = instanceType;
5
5
  exports.instance = instanceType;
6
+ exports.slot = instanceType;
6
7
  exports.connect = connectType;
7
8
  exports.children = childrenType;
8
9
  const external_types_1 = require("../connect/external_types");
@@ -1 +1 @@
1
- {"version":3,"file":"external.js","sourceRoot":"","sources":["../../src/html/external.ts"],"names":[],"mappings":";;;AAmBA,oCAIC;AAUiB,gCAAQ;AADT,8BAAO;AAEN,gCAAQ;AAlC1B,8DAOkC;AAmBjB,wFAzBf,4BAAW,OAyBW;AACV,qFAzBZ,yBAAQ,OAyBQ;AACF,uFAzBd,2BAAU,OAyBU;AACD,4FAzBnB,gCAAe,OAyBe;AACb,0FAzBjB,8BAAa,OAyBa;AACP,4FAzBnB,gCAAe,OAyBe;AApBhC,SAAS,WAAW,CAAS,aAAqB,EAAE,KAAmB,IAAS,CAAC;AAEjF,SAAS,YAAY,CAAC,OAA0B;IAC9C,OAAO;QACL,KAAK,EAAE,oBAAoB;KAC5B,CAAA;AACH,CAAC;AAED,SAAgB,YAAY,CAAyB,cAAsB;IACzE,OAAO;QACL,KAAK,EAAE,oBAAoB;KACvB,CAAA;AACR,CAAC","sourcesContent":["import {\n booleanType,\n enumType,\n stringType,\n nestedPropsType,\n classNameType,\n textContentType,\n} from '../connect/external_types'\nimport { HtmlTemplateString } from './template_literal'\nimport { HtmlMeta } from './types'\n\nfunction connectType<P = {}>(_figmaNodeUrl: string, _meta?: HtmlMeta<P>): void {}\n\nfunction childrenType(_layers: string | string[]): HtmlTemplateString {\n return {\n __tag: 'HtmlTemplateString',\n }\n}\n\nexport function instanceType<T = HtmlTemplateString>(_figmaPropName: string): T {\n return {\n __tag: 'HtmlTemplateString',\n } as T\n}\n\nexport {\n booleanType as boolean,\n enumType as enum,\n stringType as string,\n nestedPropsType as nestedProps,\n classNameType as className,\n textContentType as textContent,\n connectType as connect,\n instanceType as instance,\n childrenType as children,\n}\n"]}
1
+ {"version":3,"file":"external.js","sourceRoot":"","sources":["../../src/html/external.ts"],"names":[],"mappings":";;;AAmBA,oCAIC;AAUiB,gCAAQ;AAER,4BAAI;AAHL,8BAAO;AAEN,gCAAQ;AAlC1B,8DAOkC;AAmBjB,wFAzBf,4BAAW,OAyBW;AACV,qFAzBZ,yBAAQ,OAyBQ;AACF,uFAzBd,2BAAU,OAyBU;AACD,4FAzBnB,gCAAe,OAyBe;AACb,0FAzBjB,8BAAa,OAyBa;AACP,4FAzBnB,gCAAe,OAyBe;AApBhC,SAAS,WAAW,CAAS,aAAqB,EAAE,KAAmB,IAAS,CAAC;AAEjF,SAAS,YAAY,CAAC,OAA0B;IAC9C,OAAO;QACL,KAAK,EAAE,oBAAoB;KAC5B,CAAA;AACH,CAAC;AAED,SAAgB,YAAY,CAAyB,cAAsB;IACzE,OAAO;QACL,KAAK,EAAE,oBAAoB;KACvB,CAAA;AACR,CAAC","sourcesContent":["import {\n booleanType,\n enumType,\n stringType,\n nestedPropsType,\n classNameType,\n textContentType,\n} from '../connect/external_types'\nimport { HtmlTemplateString } from './template_literal'\nimport { HtmlMeta } from './types'\n\nfunction connectType<P = {}>(_figmaNodeUrl: string, _meta?: HtmlMeta<P>): void {}\n\nfunction childrenType(_layers: string | string[]): HtmlTemplateString {\n return {\n __tag: 'HtmlTemplateString',\n }\n}\n\nexport function instanceType<T = HtmlTemplateString>(_figmaPropName: string): T {\n return {\n __tag: 'HtmlTemplateString',\n } as T\n}\n\nexport {\n booleanType as boolean,\n enumType as enum,\n stringType as string,\n nestedPropsType as nestedProps,\n classNameType as className,\n textContentType as textContent,\n connectType as connect,\n instanceType as instance,\n childrenType as children,\n instanceType as slot,\n}\n"]}
@@ -512,7 +512,7 @@ async function parseHtmlDoc(node, parserContext, { skipTemplateHelpers }) {
512
512
  return {
513
513
  figmaNode,
514
514
  label: project_1.DEFAULT_LABEL_PER_PARSER.html,
515
- language: label_language_mapping_1.CodeConnectLanguage.HTML,
515
+ language: label_language_mapping_1.SyntaxHighlightLanguage.HTML,
516
516
  component: metadata?.component,
517
517
  source: '',
518
518
  sourceLocation: { line: -1 },
@@ -1 +1 @@
1
- {"version":3,"file":"parser.js","sourceRoot":"","sources":["../../src/html/parser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;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,QAAQ,EAAE,4CAAmB,CAAC,IAAI;QAClC,SAAS,EAAE,QAAQ,EAAE,SAAS;QAC9B,MAAM,EAAE,EAAE;QACV,cAAc,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE;QAC5B,OAAO;QACP,QAAQ;QACR,YAAY,EAAE;YACZ,qEAAqE;YACrE,uDAAuD;YACvD,KAAK;YACL,OAAO;YACP,wEAAwE;YACxE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI;SAC1C;QACD,KAAK;QACL,QAAQ,EAAE;YACR,UAAU,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO;SAClD;KACF,CAAA;AACH,CAAC","sourcesContent":["import ts, { isReturnStatement, isTemplateExpression, SyntaxKind } from 'typescript'\nimport {\n stripQuotesFromNode,\n parsePropertyOfType,\n parseFunctionArgument,\n} from '../typescript/compiler'\nimport { FIGMA_CONNECT_CALL, PropMappings, parsePropsObject } from '../connect/intrinsics'\nimport { CodeConnectJSON } from '../connect/figma_connect'\nimport { getParsedTemplateHelpersString } from './parser_template_helpers'\nimport { JSDOM } from 'jsdom'\nimport { parse } from 'parse5'\nimport {\n makeCreatePropPlaceholder,\n ParserContext,\n visitPropReferencingNode,\n getReferencedPropsForTemplate,\n ParserError,\n parseLinks,\n parseVariant,\n parseImports,\n ParseOptions,\n} from '../connect/parser_common'\nimport { CodeConnectParser, DEFAULT_LABEL_PER_PARSER } from '../connect/project'\nimport { CodeConnectLanguage } from '../connect/label_language_mapping'\nimport { format } from 'prettier'\n\nfunction getHtmlTaggedTemplateNode(node: ts.Node): ts.TaggedTemplateExpression | undefined {\n if (ts.isTaggedTemplateExpression(node)) {\n const tag = node.tag\n if (ts.isIdentifier(tag) && tag.text === 'html') {\n return node\n }\n } else if (\n ts.isBlock(node) &&\n node.statements.length === 1 &&\n ts.isReturnStatement(node.statements[0]) &&\n node.statements[0].expression &&\n ts.isTaggedTemplateExpression(node.statements[0].expression) &&\n ts.isIdentifier(node.statements[0].expression.tag) &&\n node.statements[0].expression.tag.text === 'html'\n ) {\n return node.statements[0].expression\n }\n\n return undefined\n}\n\n/**\n * This function converts the HTML template literal into a DOM (using JSDOM) to\n * extract information which is used in generating the template:\n * 1. A dictionary of template placeholders which correspond to HTML attribute\n * values. The key is the placeholder index, and the value is the attribute\n * name. The attribute name is unused (it used to be used in the output, but\n * we need to preserve case to support Angular, which JSDOM can't do unless\n * you use XHTML mode, and that doesn't support attributes without a value).\n * 2. Whether the template is \"nestable\" or not. A template is considered\n * nestable if it has only one top level element.\n *\n * For finding the attribute placeholders, the algorithm is as follows:\n * 1. Build up a full string from the template literal, replacing any value\n * ${placeholders} with `__FIGMA_PLACEHOLDER_0`, where 0 is the placeholder\n * index. This results in a valid HTML string, with placeholders we can later\n * detect.\n * 2. Use JSDOM to turn this into a DOM.\n * 3. Iterate over every node in the DOM, and if the node has any attributes\n * starting `__FIGMA_PLACEHOLDER`, store the info of these attributes. This\n * allows us to know which template literal placeholders correspond to HTML\n * attributes when we construct the template.\n */\nfunction getInfoFromDom(\n templateExp: ts.TemplateExpression | ts.TaggedTemplateExpression,\n parserContext: ParserContext,\n): {\n attributePlaceholders: Record<number, string>\n nestable: boolean\n} {\n let htmlString: string\n\n if (ts.isTemplateExpression(templateExp)) {\n // If this is a template expression, build up the HTML string with\n // identifiable placeholders as described above\n htmlString = templateExp.head.text\n templateExp.templateSpans.forEach((part, index) => {\n htmlString += `__FIGMA_PLACEHOLDER_${index}` + part.literal.text\n })\n } else if (templateExp.template.kind === ts.SyntaxKind.FirstTemplateToken) {\n // This is just a template literal with no placeholders\n htmlString = templateExp.template.text\n } else {\n // This should never happen as we check the type in the calling function\n throw new Error(`Unsupported template type: ${SyntaxKind[templateExp.template.kind]}`)\n }\n\n // First, check for HTML which we cannot handle. JSDOM is quite forgiving,\n // like a browser, but we need to be stricter\n //\n // Duplicate attribute names are handled gracefully by JSDOM (it just keeps\n // one of the attributes), but this breaks our algorithm because some of the\n // placeholders are no longer in the DOM. JSDOM has no way to detect this, but\n // parse5 (which is a library JSDOM uses under the hood) can detect this. We\n // just thrown an error in this case as there's no use case for doing this.\n parse(htmlString, {\n onParseError: (error) => {\n if (error.code === 'duplicate-attribute') {\n throw new ParserError(`Duplicate attribute name in example HTML`, {\n node: templateExp,\n sourceFile: parserContext.sourceFile,\n })\n }\n },\n })\n\n // Try to format the HTML with prettier, to catch any errors due to invalid\n // HTML which would otherwise result in broken formatting in the UI as\n // prettier is less forgiving\n try {\n // pluginSearchDirs: false is needed as otherwise prettier picks up other\n // prettier plugins in our monorepo and fails on CI\n format(htmlString, { parser: 'html', pluginSearchDirs: false })\n } catch (e) {\n throw new ParserError(`Error parsing example HTML. Check the HTML is valid.`, {\n node: templateExp,\n sourceFile: parserContext.sourceFile,\n })\n }\n\n // Create a DOM with JSDOM.\n //\n // JSDOM doesn't work properly in all cases if we parse a DOM without a full\n // document, e.g. Vue templates - when traversing with NodeIterator, it\n // doesn't find all elements. We create a Fragment then append it to a full\n // DOM to work around this. The extra wrapping elements don't matter, as we're\n // only interested in the attributes.\n const fragment = JSDOM.fragment(htmlString)\n const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>')\n dom.window.document.body.appendChild(fragment)\n\n const document = dom.window.document\n const NodeFilter = dom.window.NodeFilter\n\n const attributePlaceholders: Record<number, string> = {}\n\n function iterateNodeIterator(nodeIterator: NodeIterator) {\n let currentNode: Node | null\n\n while ((currentNode = nodeIterator.nextNode())) {\n // I couldn't work out how to do this in a way which satisfies TypeScript,\n // so using a check and a cast\n if (currentNode.nodeType === dom.window.Node.ELEMENT_NODE) {\n // Check for any attributes which correspond to placeholders in the\n // template literal, and store their index and name\n for (let attr of (currentNode as Element).attributes) {\n if (attr.value.startsWith('__FIGMA_PLACEHOLDER_')) {\n attributePlaceholders[parseInt(attr.value.split('__FIGMA_PLACEHOLDER_')[1])] = attr.name\n }\n }\n }\n\n // <TEMPLATE> nodes are not iterated over by default, as they are a way to\n // store a fragment which is not rendered immediately. These are used in\n // e.g. Vue templates, so we need to iterate over them explicitly.\n if (currentNode.nodeName === 'TEMPLATE') {\n const templateContent = (currentNode as HTMLTemplateElement).content\n const templateNodeIterator = document.createNodeIterator(\n templateContent,\n NodeFilter.SHOW_ELEMENT,\n null,\n )\n iterateNodeIterator(templateNodeIterator)\n }\n }\n }\n\n // Iterate over all the nodes in the DOM\n const nodeIterator = document.createNodeIterator(document.body, NodeFilter.SHOW_ELEMENT, null)\n iterateNodeIterator(nodeIterator)\n\n // We check if there is more than one top level child, as we use this as a\n // signal that the template is not \"nestable\" (and so we render an instance\n // pill rather than render the child's code inline in the UI)\n const topLevelChildrenCount = document.body.children.length\n\n return {\n attributePlaceholders,\n nestable: topLevelChildrenCount === 1,\n }\n}\n\nfunction escapeTemplateString(code: string) {\n return code.replace(/`/g, '\\\\`').replace(/\\$\\{/g, '\\\\${')\n}\n\n/**\n * Parses the example template string passed to `figma.connect()`.\n *\n * @param exp A function or arrow function expression\n * @param parserContext Parser context\n * @param propMappings Prop mappings object as returned by parseProps\n *\n * @returns The code of the render function and a list of imports\n */\nexport function parseExampleTemplate(\n exp: ts.ArrowFunction,\n parserContext: ParserContext,\n propMappings?: PropMappings,\n skipTemplateHelpers?: boolean,\n) {\n const { sourceFile } = parserContext\n\n if (exp.parameters.length > 1) {\n throw new ParserError(\n `Expected a single props parameter for the render function, got ${exp.parameters.length} parameters`,\n { sourceFile, node: exp },\n )\n }\n\n const propsParameter = exp.parameters[0]\n\n if (!exp.body) {\n throw new ParserError(`Expected a body for the render function`, { sourceFile, node: exp })\n }\n\n // If the body is a string literal, we generate a `figma.value` statement instead, which just\n // renders the string as-is in code examples\n if (ts.isStringLiteral(exp.body)) {\n const printer = ts.createPrinter()\n if (!exp.body) {\n throw new ParserError('Expected a function body', {\n sourceFile: parserContext.sourceFile,\n node: exp,\n })\n }\n let exampleCode = printer.printNode(ts.EmitHint.Unspecified, exp.body, sourceFile)\n\n let templateCode = ''\n if (!skipTemplateHelpers) {\n templateCode = getParsedTemplateHelpersString() + '\\n\\n'\n }\n\n templateCode += `const figma = require('figma')\\n\\n`\n\n templateCode += getReferencedPropsForTemplate({\n propMappings,\n exp,\n sourceFile,\n })\n\n exampleCode = exampleCode.replace(/`/g, '\\\\`')\n\n // Body is a string literal, so there aren't any placeholders\n templateCode += `export default figma.value(${exampleCode})\\n`\n\n return {\n code: templateCode,\n nestable: true,\n }\n }\n\n const templateNode = getHtmlTaggedTemplateNode(exp.body)\n\n if (!templateNode) {\n throw new ParserError(\n `Expected only a tagged template literal as the body of the render function`,\n { sourceFile, node: templateNode },\n )\n }\n\n // Keep track of any props which are referenced in the example so that we can\n // insert the appropriate `figma.properties` call in the JS template\n const referencedProps = new Set<string>()\n let exampleCode = ''\n let nestable = true\n\n if (isTemplateExpression(templateNode.template)) {\n // This is a template expression with placeholders\n\n const createPropPlaceholder = makeCreatePropPlaceholder({\n propMappings,\n referencedProps,\n sourceFile,\n })\n\n // Transform the template to replace any props references with placeholder\n // function calls, normalising the different types of props references\n const transformedTemplate = ts.transform(templateNode.template, [\n (context) => (rootNode) => {\n function visit(node: ts.Node): ts.Node {\n if (ts.isTemplateSpan(node)) {\n const visitResult = visitPropReferencingNode({\n propsParameter,\n node: node.expression,\n createPropPlaceholder,\n useJsx: false,\n })\n\n if (visitResult) {\n return ts.factory.createTemplateSpan(visitResult, node.literal)\n }\n }\n\n return ts.visitEachChild(node, visit, context)\n }\n return ts.visitNode(rootNode, visit) as typeof templateNode.template\n },\n ]).transformed[0] as typeof templateNode.template\n\n // Iterate over the template string spans (i.e. the interleaved strings and\n // placeholders) to build up our example code.\n //\n // Each time we encounter a placeholder (which by this point has been\n // normalised to a __PROP__ placeholder function call), we check if it\n // corresponds to a HTML attribute based on our previous DOM analysis (see\n // getInfoFromDom).\n //\n // If it does, we replace it with a call to\n // `_fcc_renderHtmlAttribute(\"attributeName\", propVariableName), otherwise\n // we replace it with a call to `_fcc_renderHtmlValue(propVariableName)`.\n //\n // We have some additional logic to handle cases where the user accidentally\n // writes `attribute=\"${props.prop}\"` rather than `attribute=${props.prop}`\n // (which is what we show in the docs), as it's easy to make this mistake\n // when copy/pasting.\n\n // Keep track of whether we're inside an attribute value that is wrapped in quotes,\n // so that we can strip the trailing quote if we are\n let insideAttributeWithQuotes = false\n\n const infoFromDom = getInfoFromDom(transformedTemplate, parserContext)\n const { attributePlaceholders } = infoFromDom\n nestable = infoFromDom.nestable\n\n // Handle a chunk of HTML, i.e. a text section of the template string. If\n // the next placeholder is an attribute and this chunk ends with a HTML\n // attribute (i.e. matches a regex like ` text=` or ` text=\"`), we remove the\n // attribute name so that it's not present in the low level template before the\n // call to _fcc_renderHtmlAttribute.\n function handleHtmlChunk(html: string, nextPlaceholderIsAttribute: boolean) {\n // If we were previously inside an attribute value placeholder with quotes\n // surrounding it, remove the leading quote. We do it like this rather\n // than always removing the leading quote to avoid situations where we\n // mistakenly remove a quote that is part of the actual content.\n if (insideAttributeWithQuotes) {\n html = html.replace(/^\"/g, '')\n }\n\n // If the next placeholder is an attribute, then match the start of the\n // attribute (`attribute=`) at the end of this chunk, so that we can\n // remove it from the example code and store the attribute name\n const attributeMatches = html.match(/(.*\\s)([^\\s]+)=\"?$/s)\n if (nextPlaceholderIsAttribute && attributeMatches) {\n // attributeMatches should always have matched here, but we check it\n // anyway so we can fail gracefully if not\n\n // Add the code up to the attribute, not including the ` attribute=`\n // part, as _fcc_renderHtmlAttribute is responsible for (maybe)\n // rendering that\n exampleCode += escapeTemplateString(attributeMatches[1])\n\n // If we are in this block, we know that we've matched an attribute, so\n // store whether it ends with a quote\n insideAttributeWithQuotes = html.endsWith('\"')\n\n // Return the attribute name so we can use it to construct the attribute\n // in the output. We do this rather than extract it from the HTML with\n // JSDOM because we want to preserve case, but do not want to parse the\n // doc as XHTML, so there's no way to do it otherwise.\n return attributeMatches[2]\n } else {\n // No attribute to remove, just add the code\n exampleCode += escapeTemplateString(html)\n insideAttributeWithQuotes = false\n }\n }\n\n // Process the first chunk, which is a special case as it is not in templateSpans\n let maybeAttributeName = handleHtmlChunk(\n transformedTemplate.head.text,\n attributePlaceholders[0] !== undefined,\n )\n\n // For each section of the template string, check that the expression is a\n // prop placeholder, then add the appropriate template function call\n transformedTemplate.templateSpans.forEach((part, index) => {\n if (!ts.isCallExpression(part.expression)) {\n throw new ParserError(\n `Expected a call expression as a placeholder in the template, got ${SyntaxKind[part.expression.kind]}`,\n { sourceFile, node: part.expression },\n )\n }\n\n const propNameArg = part.expression.arguments[0]\n if (!ts.isStringLiteral(propNameArg)) {\n throw new ParserError(\n `Expected a string literal as the argument to the placeholder call, got ${SyntaxKind[propNameArg.kind]}`,\n { sourceFile, node: propNameArg },\n )\n }\n\n const propVariableName = propNameArg.text\n\n if (attributePlaceholders[index]) {\n exampleCode += `\\${_fcc_renderHtmlAttribute('${maybeAttributeName}', ${propVariableName})}`\n } else {\n exampleCode += `\\${_fcc_renderHtmlValue(${propVariableName})}`\n }\n\n // Process the next chunk\n maybeAttributeName = handleHtmlChunk(\n part.literal.text,\n attributePlaceholders[index + 1] !== undefined,\n )\n })\n } else if (templateNode.template.kind === ts.SyntaxKind.FirstTemplateToken) {\n // Template string with no placeholders\n nestable = getInfoFromDom(templateNode, parserContext).nestable\n exampleCode = escapeTemplateString(templateNode.template.text)\n } else {\n throw new ParserError(\n `Expected a template expression as the body of the render function, got ${SyntaxKind[(templateNode.template as any).kind]}`,\n { sourceFile, node: templateNode.template },\n )\n }\n\n let templateCode = ''\n if (!skipTemplateHelpers) {\n templateCode = getParsedTemplateHelpersString() + '\\n\\n'\n }\n\n templateCode += `const figma = require('figma')\\n\\n`\n\n templateCode += getReferencedPropsForTemplate({\n propMappings,\n exp,\n sourceFile,\n })\n\n templateCode += `export default figma.html\\`${exampleCode}\\`\\n`\n\n return {\n code: templateCode,\n nestable,\n }\n}\n\nfunction parseFigmaConnectArgs(node: ts.CallExpression, parserContext: ParserContext) {\n const required = true\n\n const figmaNodeUrlArg = parseFunctionArgument(\n node,\n parserContext,\n 0,\n ts.isStringLiteral,\n required,\n `\\`${FIGMA_CONNECT_CALL}\\` must be called with a Figma Component URL as the first argument. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n example: () => html\\`<button />\\`\n})\\``,\n )!\n\n const configObjArg = parseFunctionArgument(\n node,\n parserContext,\n 1,\n ts.isObjectLiteralExpression,\n true,\n `The second argument to ${FIGMA_CONNECT_CALL}() must be an object literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n example: () => html\\`<button />\\`\n})\\``,\n )\n\n return {\n figmaNodeUrlArg,\n configObjArg,\n }\n}\n\nfunction parseConfigObjectArg(\n configArg: ts.ObjectLiteralExpression | undefined,\n parserContext: ParserContext,\n) {\n if (!configArg) {\n return {\n propsArg: undefined,\n exampleArg: undefined,\n variantArg: undefined,\n importsArg: undefined,\n linksArg: undefined,\n }\n }\n\n const propsArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'props',\n predicate: ts.isObjectLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'props' property must be an object literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n props: {\n disabled: figma.boolean('Disabled'),\n text: figma.string('TextContent'),\n },\n example: (props) => html\\`<my-button disabled=\\${props.disabled} label=\\${props.text} />\\`\n})\\``,\n })\n\n const exampleArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'example',\n predicate: ts.isArrowFunction,\n parserContext,\n required: true,\n errorMessage: `The 'example' property must be an arrow function which returns a html tagged template string. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n example: (props) => html\\`<my-button />\\`\n})\\``,\n })\n\n const variantArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'variant',\n predicate: ts.isObjectLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'variant' property must be an object literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n variant: {\n \"Has Icon\": true\n },\n example: (props) => html\\`<my-button />\\`\n})\\``,\n })\n\n const linksArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'links',\n predicate: ts.isArrayLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'links' property must be an array literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n links: [\n { name: 'Storybook', url: 'https://storybook.com' }\n ],\n example: (props) => html\\`<my-button />\\`\n})\\``,\n })\n\n const importsArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'imports',\n predicate: ts.isArrayLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'imports' property must be an array literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n imports: ['import { Button } from \"./Button\"']\n example: (props) => html\\`<my-button />\\`,\n})\\``,\n })\n\n return {\n propsArg,\n exampleArg,\n variantArg,\n linksArg,\n importsArg,\n }\n}\n\nexport async function parseHtmlDoc(\n node: ts.CallExpression,\n parserContext: ParserContext,\n { skipTemplateHelpers }: ParseOptions,\n): Promise<CodeConnectJSON> {\n const { checker, sourceFile, config } = parserContext\n\n // Parse the arguments to the `figma.connect()` call\n const { figmaNodeUrlArg, configObjArg } = parseFigmaConnectArgs(node, parserContext)\n\n const { propsArg, exampleArg, variantArg, linksArg, importsArg } = parseConfigObjectArg(\n configObjArg,\n parserContext,\n )\n\n let figmaNode = stripQuotesFromNode(figmaNodeUrlArg)\n // TODO This logic is duplicated in connect.ts transformDocFromParser due to some type issues\n if (config.documentUrlSubstitutions) {\n Object.entries(config.documentUrlSubstitutions).forEach(([from, to]) => {\n // @ts-expect-error\n figmaNode = figmaNode.replace(from, to)\n })\n }\n\n const metadata: any = undefined\n\n const props = propsArg ? parsePropsObject(propsArg, parserContext) : undefined\n const render = exampleArg\n ? parseExampleTemplate(exampleArg, parserContext, props, skipTemplateHelpers)\n : undefined\n const variant = variantArg ? parseVariant(variantArg, sourceFile, checker) : undefined\n const links = linksArg ? parseLinks(linksArg, parserContext) : undefined\n\n let imports = importsArg ? parseImports(importsArg, parserContext) : undefined\n\n let template\n if (render?.code) {\n template = render.code\n } else {\n throw new ParserError(`${FIGMA_CONNECT_CALL}() requires an example function`, {\n sourceFile,\n node,\n })\n }\n\n return {\n figmaNode,\n label: DEFAULT_LABEL_PER_PARSER.html!,\n language: CodeConnectLanguage.HTML,\n component: metadata?.component,\n source: '',\n sourceLocation: { line: -1 },\n variant,\n template,\n templateData: {\n // TODO: `props` here is currently only used for validation purposes,\n // we should eventually remove it from the JSON payload\n props,\n imports,\n // If there's no render function, the default example is always nestable\n nestable: render ? render.nestable : true,\n },\n links,\n metadata: {\n cliVersion: require('../../package.json').version,\n },\n }\n}\n"]}
1
+ {"version":3,"file":"parser.js","sourceRoot":"","sources":["../../src/html/parser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyMA,oDAiPC;AAiID,oCAmEC;AA9nBD,yDAAoF;AACpF,qDAI+B;AAC/B,sDAA0F;AAE1F,uEAA0E;AAC1E,iCAA6B;AAC7B,mCAA8B;AAC9B,4DAUiC;AACjC,gDAAgF;AAChF,8EAA2E;AAC3E,uCAAiC;AAEjC,SAAS,yBAAyB,CAAC,IAAa;IAC9C,IAAI,oBAAE,CAAC,0BAA0B,CAAC,IAAI,CAAC,EAAE,CAAC;QACxC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAA;QACpB,IAAI,oBAAE,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAChD,OAAO,IAAI,CAAA;QACb,CAAC;IACH,CAAC;SAAM,IACL,oBAAE,CAAC,OAAO,CAAC,IAAI,CAAC;QAChB,IAAI,C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GAAG,UAAU,CAAC,CAAC,CAAC,IAAA,4BAAY,EAAC,UAAU,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;IACtF,MAAM,KAAK,GAAG,QAAQ,CAAC,CAAC,CAAC,IAAA,0BAAU,EAAC,QAAQ,EAAE,aAAa,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;IAExE,IAAI,OAAO,GAAG,UAAU,CAAC,CAAC,CAAC,IAAA,4BAAY,EAAC,UAAU,EAAE,aAAa,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;IAE9E,IAAI,QAAQ,CAAA;IACZ,IAAI,MAAM,EAAE,IAAI,EAAE,CAAC;QACjB,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAA;IACxB,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,2BAAW,CAAC,GAAG,+BAAkB,iCAAiC,EAAE;YAC5E,UAAU;YACV,IAAI;SACL,CAAC,CAAA;IACJ,CAAC;IAED,OAAO;QACL,SAAS;QACT,KAAK,EAAE,kCAAwB,CAAC,IAAK;QACrC,QAAQ,EAAE,gDAAuB,CAAC,IAAI;QACtC,SAAS,EAAE,QAAQ,EAAE,SAAS;QAC9B,MAAM,EAAE,EAAE;QACV,cAAc,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE;QAC5B,OAAO;QACP,QAAQ;QACR,YAAY,EAAE;YACZ,qEAAqE;YACrE,uDAAuD;YACvD,KAAK;YACL,OAAO;YACP,wEAAwE;YACxE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI;SAC1C;QACD,KAAK;QACL,QAAQ,EAAE;YACR,UAAU,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO;SAClD;KACF,CAAA;AACH,CAAC","sourcesContent":["import ts, { isReturnStatement, isTemplateExpression, SyntaxKind } from 'typescript'\nimport {\n stripQuotesFromNode,\n parsePropertyOfType,\n parseFunctionArgument,\n} from '../typescript/compiler'\nimport { FIGMA_CONNECT_CALL, PropMappings, parsePropsObject } from '../connect/intrinsics'\nimport { CodeConnectJSON } from '../connect/figma_connect'\nimport { getParsedTemplateHelpersString } from './parser_template_helpers'\nimport { JSDOM } from 'jsdom'\nimport { parse } from 'parse5'\nimport {\n makeCreatePropPlaceholder,\n ParserContext,\n visitPropReferencingNode,\n getReferencedPropsForTemplate,\n ParserError,\n parseLinks,\n parseVariant,\n parseImports,\n ParseOptions,\n} from '../connect/parser_common'\nimport { CodeConnectParser, DEFAULT_LABEL_PER_PARSER } from '../connect/project'\nimport { SyntaxHighlightLanguage } from '../connect/label_language_mapping'\nimport { format } from 'prettier'\n\nfunction getHtmlTaggedTemplateNode(node: ts.Node): ts.TaggedTemplateExpression | undefined {\n if (ts.isTaggedTemplateExpression(node)) {\n const tag = node.tag\n if (ts.isIdentifier(tag) && tag.text === 'html') {\n return node\n }\n } else if (\n ts.isBlock(node) &&\n node.statements.length === 1 &&\n ts.isReturnStatement(node.statements[0]) &&\n node.statements[0].expression &&\n ts.isTaggedTemplateExpression(node.statements[0].expression) &&\n ts.isIdentifier(node.statements[0].expression.tag) &&\n node.statements[0].expression.tag.text === 'html'\n ) {\n return node.statements[0].expression\n }\n\n return undefined\n}\n\n/**\n * This function converts the HTML template literal into a DOM (using JSDOM) to\n * extract information which is used in generating the template:\n * 1. A dictionary of template placeholders which correspond to HTML attribute\n * values. The key is the placeholder index, and the value is the attribute\n * name. The attribute name is unused (it used to be used in the output, but\n * we need to preserve case to support Angular, which JSDOM can't do unless\n * you use XHTML mode, and that doesn't support attributes without a value).\n * 2. Whether the template is \"nestable\" or not. A template is considered\n * nestable if it has only one top level element.\n *\n * For finding the attribute placeholders, the algorithm is as follows:\n * 1. Build up a full string from the template literal, replacing any value\n * ${placeholders} with `__FIGMA_PLACEHOLDER_0`, where 0 is the placeholder\n * index. This results in a valid HTML string, with placeholders we can later\n * detect.\n * 2. Use JSDOM to turn this into a DOM.\n * 3. Iterate over every node in the DOM, and if the node has any attributes\n * starting `__FIGMA_PLACEHOLDER`, store the info of these attributes. This\n * allows us to know which template literal placeholders correspond to HTML\n * attributes when we construct the template.\n */\nfunction getInfoFromDom(\n templateExp: ts.TemplateExpression | ts.TaggedTemplateExpression,\n parserContext: ParserContext,\n): {\n attributePlaceholders: Record<number, string>\n nestable: boolean\n} {\n let htmlString: string\n\n if (ts.isTemplateExpression(templateExp)) {\n // If this is a template expression, build up the HTML string with\n // identifiable placeholders as described above\n htmlString = templateExp.head.text\n templateExp.templateSpans.forEach((part, index) => {\n htmlString += `__FIGMA_PLACEHOLDER_${index}` + part.literal.text\n })\n } else if (templateExp.template.kind === ts.SyntaxKind.FirstTemplateToken) {\n // This is just a template literal with no placeholders\n htmlString = templateExp.template.text\n } else {\n // This should never happen as we check the type in the calling function\n throw new Error(`Unsupported template type: ${SyntaxKind[templateExp.template.kind]}`)\n }\n\n // First, check for HTML which we cannot handle. JSDOM is quite forgiving,\n // like a browser, but we need to be stricter\n //\n // Duplicate attribute names are handled gracefully by JSDOM (it just keeps\n // one of the attributes), but this breaks our algorithm because some of the\n // placeholders are no longer in the DOM. JSDOM has no way to detect this, but\n // parse5 (which is a library JSDOM uses under the hood) can detect this. We\n // just thrown an error in this case as there's no use case for doing this.\n parse(htmlString, {\n onParseError: (error) => {\n if (error.code === 'duplicate-attribute') {\n throw new ParserError(`Duplicate attribute name in example HTML`, {\n node: templateExp,\n sourceFile: parserContext.sourceFile,\n })\n }\n },\n })\n\n // Try to format the HTML with prettier, to catch any errors due to invalid\n // HTML which would otherwise result in broken formatting in the UI as\n // prettier is less forgiving\n try {\n // pluginSearchDirs: false is needed as otherwise prettier picks up other\n // prettier plugins in our monorepo and fails on CI\n format(htmlString, { parser: 'html', pluginSearchDirs: false })\n } catch (e) {\n throw new ParserError(`Error parsing example HTML. Check the HTML is valid.`, {\n node: templateExp,\n sourceFile: parserContext.sourceFile,\n })\n }\n\n // Create a DOM with JSDOM.\n //\n // JSDOM doesn't work properly in all cases if we parse a DOM without a full\n // document, e.g. Vue templates - when traversing with NodeIterator, it\n // doesn't find all elements. We create a Fragment then append it to a full\n // DOM to work around this. The extra wrapping elements don't matter, as we're\n // only interested in the attributes.\n const fragment = JSDOM.fragment(htmlString)\n const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>')\n dom.window.document.body.appendChild(fragment)\n\n const document = dom.window.document\n const NodeFilter = dom.window.NodeFilter\n\n const attributePlaceholders: Record<number, string> = {}\n\n function iterateNodeIterator(nodeIterator: NodeIterator) {\n let currentNode: Node | null\n\n while ((currentNode = nodeIterator.nextNode())) {\n // I couldn't work out how to do this in a way which satisfies TypeScript,\n // so using a check and a cast\n if (currentNode.nodeType === dom.window.Node.ELEMENT_NODE) {\n // Check for any attributes which correspond to placeholders in the\n // template literal, and store their index and name\n for (let attr of (currentNode as Element).attributes) {\n if (attr.value.startsWith('__FIGMA_PLACEHOLDER_')) {\n attributePlaceholders[parseInt(attr.value.split('__FIGMA_PLACEHOLDER_')[1])] = attr.name\n }\n }\n }\n\n // <TEMPLATE> nodes are not iterated over by default, as they are a way to\n // store a fragment which is not rendered immediately. These are used in\n // e.g. Vue templates, so we need to iterate over them explicitly.\n if (currentNode.nodeName === 'TEMPLATE') {\n const templateContent = (currentNode as HTMLTemplateElement).content\n const templateNodeIterator = document.createNodeIterator(\n templateContent,\n NodeFilter.SHOW_ELEMENT,\n null,\n )\n iterateNodeIterator(templateNodeIterator)\n }\n }\n }\n\n // Iterate over all the nodes in the DOM\n const nodeIterator = document.createNodeIterator(document.body, NodeFilter.SHOW_ELEMENT, null)\n iterateNodeIterator(nodeIterator)\n\n // We check if there is more than one top level child, as we use this as a\n // signal that the template is not \"nestable\" (and so we render an instance\n // pill rather than render the child's code inline in the UI)\n const topLevelChildrenCount = document.body.children.length\n\n return {\n attributePlaceholders,\n nestable: topLevelChildrenCount === 1,\n }\n}\n\nfunction escapeTemplateString(code: string) {\n return code.replace(/`/g, '\\\\`').replace(/\\$\\{/g, '\\\\${')\n}\n\n/**\n * Parses the example template string passed to `figma.connect()`.\n *\n * @param exp A function or arrow function expression\n * @param parserContext Parser context\n * @param propMappings Prop mappings object as returned by parseProps\n *\n * @returns The code of the render function and a list of imports\n */\nexport function parseExampleTemplate(\n exp: ts.ArrowFunction,\n parserContext: ParserContext,\n propMappings?: PropMappings,\n skipTemplateHelpers?: boolean,\n) {\n const { sourceFile } = parserContext\n\n if (exp.parameters.length > 1) {\n throw new ParserError(\n `Expected a single props parameter for the render function, got ${exp.parameters.length} parameters`,\n { sourceFile, node: exp },\n )\n }\n\n const propsParameter = exp.parameters[0]\n\n if (!exp.body) {\n throw new ParserError(`Expected a body for the render function`, { sourceFile, node: exp })\n }\n\n // If the body is a string literal, we generate a `figma.value` statement instead, which just\n // renders the string as-is in code examples\n if (ts.isStringLiteral(exp.body)) {\n const printer = ts.createPrinter()\n if (!exp.body) {\n throw new ParserError('Expected a function body', {\n sourceFile: parserContext.sourceFile,\n node: exp,\n })\n }\n let exampleCode = printer.printNode(ts.EmitHint.Unspecified, exp.body, sourceFile)\n\n let templateCode = ''\n if (!skipTemplateHelpers) {\n templateCode = getParsedTemplateHelpersString() + '\\n\\n'\n }\n\n templateCode += `const figma = require('figma')\\n\\n`\n\n templateCode += getReferencedPropsForTemplate({\n propMappings,\n exp,\n sourceFile,\n })\n\n exampleCode = exampleCode.replace(/`/g, '\\\\`')\n\n // Body is a string literal, so there aren't any placeholders\n templateCode += `export default figma.value(${exampleCode})\\n`\n\n return {\n code: templateCode,\n nestable: true,\n }\n }\n\n const templateNode = getHtmlTaggedTemplateNode(exp.body)\n\n if (!templateNode) {\n throw new ParserError(\n `Expected only a tagged template literal as the body of the render function`,\n { sourceFile, node: templateNode },\n )\n }\n\n // Keep track of any props which are referenced in the example so that we can\n // insert the appropriate `figma.properties` call in the JS template\n const referencedProps = new Set<string>()\n let exampleCode = ''\n let nestable = true\n\n if (isTemplateExpression(templateNode.template)) {\n // This is a template expression with placeholders\n\n const createPropPlaceholder = makeCreatePropPlaceholder({\n propMappings,\n referencedProps,\n sourceFile,\n })\n\n // Transform the template to replace any props references with placeholder\n // function calls, normalising the different types of props references\n const transformedTemplate = ts.transform(templateNode.template, [\n (context) => (rootNode) => {\n function visit(node: ts.Node): ts.Node {\n if (ts.isTemplateSpan(node)) {\n const visitResult = visitPropReferencingNode({\n propsParameter,\n node: node.expression,\n createPropPlaceholder,\n useJsx: false,\n })\n\n if (visitResult) {\n return ts.factory.createTemplateSpan(visitResult, node.literal)\n }\n }\n\n return ts.visitEachChild(node, visit, context)\n }\n return ts.visitNode(rootNode, visit) as typeof templateNode.template\n },\n ]).transformed[0] as typeof templateNode.template\n\n // Iterate over the template string spans (i.e. the interleaved strings and\n // placeholders) to build up our example code.\n //\n // Each time we encounter a placeholder (which by this point has been\n // normalised to a __PROP__ placeholder function call), we check if it\n // corresponds to a HTML attribute based on our previous DOM analysis (see\n // getInfoFromDom).\n //\n // If it does, we replace it with a call to\n // `_fcc_renderHtmlAttribute(\"attributeName\", propVariableName), otherwise\n // we replace it with a call to `_fcc_renderHtmlValue(propVariableName)`.\n //\n // We have some additional logic to handle cases where the user accidentally\n // writes `attribute=\"${props.prop}\"` rather than `attribute=${props.prop}`\n // (which is what we show in the docs), as it's easy to make this mistake\n // when copy/pasting.\n\n // Keep track of whether we're inside an attribute value that is wrapped in quotes,\n // so that we can strip the trailing quote if we are\n let insideAttributeWithQuotes = false\n\n const infoFromDom = getInfoFromDom(transformedTemplate, parserContext)\n const { attributePlaceholders } = infoFromDom\n nestable = infoFromDom.nestable\n\n // Handle a chunk of HTML, i.e. a text section of the template string. If\n // the next placeholder is an attribute and this chunk ends with a HTML\n // attribute (i.e. matches a regex like ` text=` or ` text=\"`), we remove the\n // attribute name so that it's not present in the low level template before the\n // call to _fcc_renderHtmlAttribute.\n function handleHtmlChunk(html: string, nextPlaceholderIsAttribute: boolean) {\n // If we were previously inside an attribute value placeholder with quotes\n // surrounding it, remove the leading quote. We do it like this rather\n // than always removing the leading quote to avoid situations where we\n // mistakenly remove a quote that is part of the actual content.\n if (insideAttributeWithQuotes) {\n html = html.replace(/^\"/g, '')\n }\n\n // If the next placeholder is an attribute, then match the start of the\n // attribute (`attribute=`) at the end of this chunk, so that we can\n // remove it from the example code and store the attribute name\n const attributeMatches = html.match(/(.*\\s)([^\\s]+)=\"?$/s)\n if (nextPlaceholderIsAttribute && attributeMatches) {\n // attributeMatches should always have matched here, but we check it\n // anyway so we can fail gracefully if not\n\n // Add the code up to the attribute, not including the ` attribute=`\n // part, as _fcc_renderHtmlAttribute is responsible for (maybe)\n // rendering that\n exampleCode += escapeTemplateString(attributeMatches[1])\n\n // If we are in this block, we know that we've matched an attribute, so\n // store whether it ends with a quote\n insideAttributeWithQuotes = html.endsWith('\"')\n\n // Return the attribute name so we can use it to construct the attribute\n // in the output. We do this rather than extract it from the HTML with\n // JSDOM because we want to preserve case, but do not want to parse the\n // doc as XHTML, so there's no way to do it otherwise.\n return attributeMatches[2]\n } else {\n // No attribute to remove, just add the code\n exampleCode += escapeTemplateString(html)\n insideAttributeWithQuotes = false\n }\n }\n\n // Process the first chunk, which is a special case as it is not in templateSpans\n let maybeAttributeName = handleHtmlChunk(\n transformedTemplate.head.text,\n attributePlaceholders[0] !== undefined,\n )\n\n // For each section of the template string, check that the expression is a\n // prop placeholder, then add the appropriate template function call\n transformedTemplate.templateSpans.forEach((part, index) => {\n if (!ts.isCallExpression(part.expression)) {\n throw new ParserError(\n `Expected a call expression as a placeholder in the template, got ${SyntaxKind[part.expression.kind]}`,\n { sourceFile, node: part.expression },\n )\n }\n\n const propNameArg = part.expression.arguments[0]\n if (!ts.isStringLiteral(propNameArg)) {\n throw new ParserError(\n `Expected a string literal as the argument to the placeholder call, got ${SyntaxKind[propNameArg.kind]}`,\n { sourceFile, node: propNameArg },\n )\n }\n\n const propVariableName = propNameArg.text\n\n if (attributePlaceholders[index]) {\n exampleCode += `\\${_fcc_renderHtmlAttribute('${maybeAttributeName}', ${propVariableName})}`\n } else {\n exampleCode += `\\${_fcc_renderHtmlValue(${propVariableName})}`\n }\n\n // Process the next chunk\n maybeAttributeName = handleHtmlChunk(\n part.literal.text,\n attributePlaceholders[index + 1] !== undefined,\n )\n })\n } else if (templateNode.template.kind === ts.SyntaxKind.FirstTemplateToken) {\n // Template string with no placeholders\n nestable = getInfoFromDom(templateNode, parserContext).nestable\n exampleCode = escapeTemplateString(templateNode.template.text)\n } else {\n throw new ParserError(\n `Expected a template expression as the body of the render function, got ${SyntaxKind[(templateNode.template as any).kind]}`,\n { sourceFile, node: templateNode.template },\n )\n }\n\n let templateCode = ''\n if (!skipTemplateHelpers) {\n templateCode = getParsedTemplateHelpersString() + '\\n\\n'\n }\n\n templateCode += `const figma = require('figma')\\n\\n`\n\n templateCode += getReferencedPropsForTemplate({\n propMappings,\n exp,\n sourceFile,\n })\n\n templateCode += `export default figma.html\\`${exampleCode}\\`\\n`\n\n return {\n code: templateCode,\n nestable,\n }\n}\n\nfunction parseFigmaConnectArgs(node: ts.CallExpression, parserContext: ParserContext) {\n const required = true\n\n const figmaNodeUrlArg = parseFunctionArgument(\n node,\n parserContext,\n 0,\n ts.isStringLiteral,\n required,\n `\\`${FIGMA_CONNECT_CALL}\\` must be called with a Figma Component URL as the first argument. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n example: () => html\\`<button />\\`\n})\\``,\n )!\n\n const configObjArg = parseFunctionArgument(\n node,\n parserContext,\n 1,\n ts.isObjectLiteralExpression,\n true,\n `The second argument to ${FIGMA_CONNECT_CALL}() must be an object literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n example: () => html\\`<button />\\`\n})\\``,\n )\n\n return {\n figmaNodeUrlArg,\n configObjArg,\n }\n}\n\nfunction parseConfigObjectArg(\n configArg: ts.ObjectLiteralExpression | undefined,\n parserContext: ParserContext,\n) {\n if (!configArg) {\n return {\n propsArg: undefined,\n exampleArg: undefined,\n variantArg: undefined,\n importsArg: undefined,\n linksArg: undefined,\n }\n }\n\n const propsArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'props',\n predicate: ts.isObjectLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'props' property must be an object literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n props: {\n disabled: figma.boolean('Disabled'),\n text: figma.string('TextContent'),\n },\n example: (props) => html\\`<my-button disabled=\\${props.disabled} label=\\${props.text} />\\`\n})\\``,\n })\n\n const exampleArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'example',\n predicate: ts.isArrowFunction,\n parserContext,\n required: true,\n errorMessage: `The 'example' property must be an arrow function which returns a html tagged template string. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n example: (props) => html\\`<my-button />\\`\n})\\``,\n })\n\n const variantArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'variant',\n predicate: ts.isObjectLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'variant' property must be an object literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n variant: {\n \"Has Icon\": true\n },\n example: (props) => html\\`<my-button />\\`\n})\\``,\n })\n\n const linksArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'links',\n predicate: ts.isArrayLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'links' property must be an array literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n links: [\n { name: 'Storybook', url: 'https://storybook.com' }\n ],\n example: (props) => html\\`<my-button />\\`\n})\\``,\n })\n\n const importsArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'imports',\n predicate: ts.isArrayLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'imports' property must be an array literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n imports: ['import { Button } from \"./Button\"']\n example: (props) => html\\`<my-button />\\`,\n})\\``,\n })\n\n return {\n propsArg,\n exampleArg,\n variantArg,\n linksArg,\n importsArg,\n }\n}\n\nexport async function parseHtmlDoc(\n node: ts.CallExpression,\n parserContext: ParserContext,\n { skipTemplateHelpers }: ParseOptions,\n): Promise<CodeConnectJSON> {\n const { checker, sourceFile, config } = parserContext\n\n // Parse the arguments to the `figma.connect()` call\n const { figmaNodeUrlArg, configObjArg } = parseFigmaConnectArgs(node, parserContext)\n\n const { propsArg, exampleArg, variantArg, linksArg, importsArg } = parseConfigObjectArg(\n configObjArg,\n parserContext,\n )\n\n let figmaNode = stripQuotesFromNode(figmaNodeUrlArg)\n // TODO This logic is duplicated in connect.ts transformDocFromParser due to some type issues\n if (config.documentUrlSubstitutions) {\n Object.entries(config.documentUrlSubstitutions).forEach(([from, to]) => {\n // @ts-expect-error\n figmaNode = figmaNode.replace(from, to)\n })\n }\n\n const metadata: any = undefined\n\n const props = propsArg ? parsePropsObject(propsArg, parserContext) : undefined\n const render = exampleArg\n ? parseExampleTemplate(exampleArg, parserContext, props, skipTemplateHelpers)\n : undefined\n const variant = variantArg ? parseVariant(variantArg, sourceFile, checker) : undefined\n const links = linksArg ? parseLinks(linksArg, parserContext) : undefined\n\n let imports = importsArg ? parseImports(importsArg, parserContext) : undefined\n\n let template\n if (render?.code) {\n template = render.code\n } else {\n throw new ParserError(`${FIGMA_CONNECT_CALL}() requires an example function`, {\n sourceFile,\n node,\n })\n }\n\n return {\n figmaNode,\n label: DEFAULT_LABEL_PER_PARSER.html!,\n language: SyntaxHighlightLanguage.HTML,\n component: metadata?.component,\n source: '',\n sourceLocation: { line: -1 },\n variant,\n template,\n templateData: {\n // TODO: `props` here is currently only used for validation purposes,\n // we should eventually remove it from the JSON payload\n props,\n imports,\n // If there's no render function, the default example is always nestable\n nestable: render ? render.nestable : true,\n },\n links,\n metadata: {\n cliVersion: require('../../package.json').version,\n },\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../src/react/create.ts"],"names":[],"mappings":"AAGA,OAAO,CAAC,MAAM,KAAK,CAAA;AACnB,OAAO,EAGL,yBAAyB,EACzB,qBAAqB,EACrB,wBAAwB,EAEzB,MAAM,oCAAoC,CAAA;AAG3C,OAAO,EAAE,SAAS,EAAmC,MAAM,uBAAuB,CAAA;AAIlF,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,WAU9C;AA8CD,wBAAgB,+BAA+B,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,SAAS,GAAG,MAAM,GAAG,KAAK,CAqBzF;AAgCD,wBAAgB,uCAAuC,CAAC,GAAG,EAAE,MAAM,eAWlE;AA4CD,wBAAgB,aAAa,CAAC,SAAS,EAAE,wBAAwB,UAkBhE;AAwED,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,yBAAyB,GACjC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC,CA2HhD"}
1
+ {"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../src/react/create.ts"],"names":[],"mappings":"AAGA,OAAO,CAAC,MAAM,KAAK,CAAA;AACnB,OAAO,EAGL,yBAAyB,EACzB,qBAAqB,EACrB,wBAAwB,EAEzB,MAAM,oCAAoC,CAAA;AAG3C,OAAO,EAAE,SAAS,EAAmC,MAAM,uBAAuB,CAAA;AAIlF,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,WAU9C;AA8CD,wBAAgB,+BAA+B,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,SAAS,GAAG,MAAM,GAAG,KAAK,CAwBzF;AAgCD,wBAAgB,uCAAuC,CAAC,GAAG,EAAE,MAAM,eAWlE;AA4CD,wBAAgB,aAAa,CAAC,SAAS,EAAE,wBAAwB,UAkBhE;AAwED,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,yBAAyB,GACjC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC,CA2HhD"}
@@ -106,6 +106,9 @@ function generateExpressionFromIntrinsic({ kind, args }) {
106
106
  if (kind === intrinsics_1.IntrinsicKind.Instance) {
107
107
  return `figma.instance("${args.figmaPropName}")`;
108
108
  }
109
+ if (kind === intrinsics_1.IntrinsicKind.Slot) {
110
+ return `figma.slot("${args.figmaPropName}")`;
111
+ }
109
112
  if (kind === intrinsics_1.IntrinsicKind.Children) {
110
113
  return `figma.children(${args.layers.length > 1 ? `[${args.layers.map((layer) => `"${layer}"`).join(', ')}]` : `"${args.layers[0]}"`})`;
111
114
  }
@@ -1 +1 @@
1
- {"version":3,"file":"create.js","sourceRoot":"","sources":["../../src/react/create.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,sCAUC;AA8CD,0EAqBC;AAgCD,0FAWC;AA4CD,sCAkBC;AAwED,wDA6HC;AA7YD,mCAAkC;AAClC,mDAAoC;AACpC,4CAAmB;AAUnB,gDAAuB;AACvB,8CAA0D;AAC1D,sDAAkF;AAClF,4DAAyD;AAGzD,SAAgB,aAAa,CAAC,SAAiB;IAC7C,MAAM,UAAU,GAAG,SAAS,CAAC,WAAW,EAAE,CAAA;IAC1C,OAAO,CACL,UAAU,KAAK,MAAM;QACrB,UAAU,KAAK,OAAO;QACtB,UAAU,KAAK,KAAK;QACpB,UAAU,KAAK,IAAI;QACnB,UAAU,KAAK,IAAI;QACnB,UAAU,KAAK,KAAK,CACrB,CAAA;AACH,CAAC;AAED,SAAS,iBAAiB,CAAC,IAAY;IACrC,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAA;AACtC,CAAC;AAED,SAAS,oBAAoB,CAAC,IAAY;IACxC,MAAM,WAAW,GAAG,IAAI;QACtB,iDAAiD;SAChD,OAAO,CAAC,YAAY,EAAE,EAAE,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["import { camelCase } from 'lodash'\nimport * as prettier from 'prettier'\nimport fs from 'fs'\nimport z from 'zod'\nimport {\n ComponentPropertyDefinition,\n CreateRequestPayload,\n CreateRequestPayloadMulti,\n CreateResponsePayload,\n FigmaConnectionComponent,\n PropMapping,\n} from '../connect/parser_executable_types'\nimport path from 'path'\nimport { normalizeComponentName } from '../connect/create'\nimport { Intrinsic, IntrinsicKind, ValueMappingKind } from '../connect/intrinsics'\nimport { getOutFileName } from '../connect/create_common'\nimport { ComponentTypeSignature } from './parser'\n\nexport function isBooleanKind(propValue: string) {\n const normalized = propValue.toLowerCase()\n return (\n normalized === 'true' ||\n normalized === 'false' ||\n normalized === 'yes' ||\n normalized === 'no' ||\n normalized === 'on' ||\n normalized === 'off'\n )\n}\n\nfunction normalizePropName(name: string) {\n return name.replace(/#[0-9:]*/g, '')\n}\n\nfunction generateCodePropName(name: string) {\n const cleanedName = name\n // Remove any #node:id from the end of the string\n .replace(/#[0-9:]+$/g, '')\n // Remove any special characters\n .replace(/[^a-zA-Z0-9\\s]/g, '')\n\n return camelCase(cleanedName)\n}\n\nfunction normalizePropValue(name: string) {\n // Convert the string to kebab-case\n return name.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase()\n}\n\nfunction generateExpressionValueMappingKind(valueMappingKind: ValueMappingKind) {\n if (valueMappingKind && typeof valueMappingKind === 'object' && 'kind' in valueMappingKind) {\n return generateExpressionFromIntrinsic(valueMappingKind)\n }\n if (typeof valueMappingKind === 'string') {\n return `\"${valueMappingKind}\"`\n }\n if (\n typeof valueMappingKind === 'number' ||\n typeof valueMappingKind === 'boolean' ||\n typeof valueMappingKind === 'undefined'\n ) {\n return `${valueMappingKind}`\n }\n}\n\nfunction generateExpressionValueMapping(valueMapping: Record<string, ValueMappingKind>) {\n return `{\n ${Object.entries(valueMapping)\n .map(([k, v]) => `\"${k}\": ${generateExpressionValueMappingKind(v)}`)\n .join(`,\\n`)}\n}`\n}\n\n// Not an exhaustive list of intrinsics but can add others as/when they're supported in prop mapping gen\nexport function generateExpressionFromIntrinsic({ kind, args }: Intrinsic): string | never {\n if (kind === IntrinsicKind.String) {\n return `figma.string(\"${args.figmaPropName}\")`\n }\n if (kind === IntrinsicKind.Boolean) {\n return `figma.boolean(\"${args.figmaPropName}\"${args.valueMapping ? `, ${generateExpressionValueMapping(args.valueMapping)}` : ''})`\n }\n if (kind === IntrinsicKind.Enum) {\n return `figma.enum(\"${args.figmaPropName}\"${args.valueMapping ? `, ${generateExpressionValueMapping(args.valueMapping)}` : ''})`\n }\n if (kind === IntrinsicKind.Instance) {\n return `figma.instance(\"${args.figmaPropName}\")`\n }\n if (kind === IntrinsicKind.Children) {\n return `figma.children(${args.layers.length > 1 ? `[${args.layers.map((layer) => `\"${layer}\"`).join(', ')}]` : `\"${args.layers[0]}\"`})`\n }\n if (kind === IntrinsicKind.TextContent) {\n return `figma.textContent(\"${args.layer}\")`\n }\n // should never reach here as we create prop mappings.\n throw new Error(`kind ${kind} not supported for prop mapping`)\n}\n\nfunction generateSinglePropMappingFromFigmaProp(\n propName: string,\n propDef: ComponentPropertyDefinition,\n) {\n const codePropName = generateCodePropName(propName)\n const figmaPropName = normalizePropName(propName)\n if (propDef.type === 'BOOLEAN') {\n return `\"${codePropName}\": figma.boolean('${figmaPropName}')`\n }\n if (propDef.type === 'TEXT') {\n return `\"${codePropName}\": figma.string('${figmaPropName}')`\n }\n if (propDef.type === 'VARIANT') {\n const isBooleanVariant =\n propDef.variantOptions?.length === 2 && propDef.variantOptions.every(isBooleanKind)\n if (isBooleanVariant) {\n return `\"${codePropName}\": figma.boolean('${figmaPropName}')`\n } else {\n return `\"${codePropName}\": figma.enum('${figmaPropName}', { \\n${propDef.variantOptions\n ?.map((value) => ` \"${value}\": \"${normalizePropValue(value)}\"`)\n .join(',\\n')}\\n})`\n }\n }\n if (propDef.type === 'INSTANCE_SWAP') {\n return `\"${codePropName}\": figma.instance('${figmaPropName}')`\n }\n\n return null\n}\n\nexport function getSetOfAllPropsReferencedInPropMapping(obj: Object) {\n const mappedProps: string[] = []\n Object.entries(obj).forEach(([k, v]) => {\n if (k === 'figmaPropName') {\n mappedProps.push(v)\n }\n if (typeof v === 'object') {\n mappedProps.push(...getSetOfAllPropsReferencedInPropMapping(v))\n }\n })\n return new Set(mappedProps)\n}\n\nfunction generatePropsFromMapping(component: FigmaConnectionComponent, propMapping: PropMapping) {\n const mappedProps: string[] = []\n const unmappedProps: string[] = []\n\n for (const [propName, intrinsic] of Object.entries(propMapping)) {\n const expr = generateExpressionFromIntrinsic(intrinsic)\n if (expr) {\n mappedProps.push(`\"${propName}\": ${expr}`)\n }\n }\n\n const usedFigmaPropsSet = getSetOfAllPropsReferencedInPropMapping(propMapping)\n for (const [propName, propDef] of Object.entries(component.componentPropertyDefinitions || {})) {\n if (!usedFigmaPropsSet.has(propName)) {\n const propMapping = generateSinglePropMappingFromFigmaProp(propName, propDef)\n if (propMapping) {\n unmappedProps.push(propMapping)\n }\n }\n }\n\n return `{\n${\n mappedProps.length\n ? `// These props were automatically mapped based on your linked code:\n ${mappedProps.join(',\\n')},`\n : ''\n}\n ${\n unmappedProps.length\n ? `// No matching props could be found for these Figma properties:\n ${unmappedProps\n .map((prop) => {\n // Comment out to make clear these are suggested. Singly-commented out lines for ease of uncommenting\n return `// ${prop.replace(/\\n/g, '\\n// ')}`\n })\n .join(',\\n')}`\n : ''\n }\n }`\n}\n\nexport function generateProps(component: FigmaConnectionComponent) {\n const props: string[] = []\n if (\n !component.componentPropertyDefinitions ||\n Object.keys(component.componentPropertyDefinitions).length === 0\n ) {\n return `{}`\n }\n\n for (const [propName, propDef] of Object.entries(component.componentPropertyDefinitions)) {\n const propMapping = generateSinglePropMappingFromFigmaProp(propName, propDef)\n if (propMapping) {\n props.push(propMapping)\n }\n }\n return `{\n ${props.join(',\\n ')}\n}`\n}\n\nfunction generateExample(\n component: string,\n signature?: ComponentTypeSignature,\n propMapping?: PropMapping,\n) {\n if (!signature) {\n return `<${component} />`\n }\n const props = Object.entries(signature)\n .map(([propName, propDef]) => {\n // Children are rendered inside of the example body rather than in a prop\n if (propName === 'children') {\n return null\n } else if (propMapping && propMapping[propName]) {\n return `${propName}={props.${propName}}`\n } else if (!propDef.startsWith('?')) {\n return `${propName}={/* TODO */} `\n } else {\n return null\n }\n })\n .filter(Boolean)\n .join('\\n')\n\n // const childProp = propMapping?['children'] ? `{props.${propMapping['children']}}` : null\n\n // Nest child props inside of the element\n if (signature['children'] && propMapping?.['children']) {\n return `<${component}\n ${props}>\n {props.children}\n </${component}>`\n } else {\n return `<${component}\n ${props}/>`\n }\n}\n\n// returns ES-style import path from given system path\nfunction formatImportPath(systemPath: string) {\n // use forward slashes for import paths\n let formattedImportPath = systemPath.replaceAll(path.sep, '/')\n\n // prefix current dir paths with ./ (node path does not)\n if (!formattedImportPath.startsWith('.')) {\n formattedImportPath = `./${formattedImportPath}`\n }\n\n // assume not using ESM imports\n return formattedImportPath.replace(/\\.(jsx|tsx)$/, '')\n}\n\nfunction getImportsPath({\n codeConnectFilePath,\n sourceFilepath,\n normalizedName,\n}: {\n codeConnectFilePath: string\n sourceFilepath?: string\n normalizedName: string\n}) {\n if (!sourceFilepath) {\n return `./${normalizedName}`\n }\n const codeConnectFolder = path.dirname(codeConnectFilePath)\n const pathToComponentFile = path.relative(codeConnectFolder, sourceFilepath)\n\n return formatImportPath(pathToComponentFile)\n}\n\nexport async function createReactCodeConnect(\n payload: CreateRequestPayloadMulti,\n): Promise<z.infer<typeof CreateResponsePayload>> {\n const { figmaConnections, destinationFile, destinationDir, sourceFilepath, normalizedName } =\n payload\n\n const comments = {\n MAPPED_PROPS: `\n * \\`props\\` includes a mapping from your code props to Figma properties.\n * You should check this is correct, and update the \\`example\\` function\n * to return the code example you'd like to see in Figma`,\n NO_MAPPED_PROPS: `\n * None of your props could be automatically mapped to Figma properties.\n * You should update the \\`props\\` object to include a mapping from your\n * code props to Figma properties, and update the \\`example\\` function to\n * return the code example you'd like to see in Figma`,\n DEFAULT: `\n * \\`props\\` includes a mapping from Figma properties and variants to\n * suggested values. You should update this to match the props of your\n * code component, and update the \\`example\\` function to return the\n * code example you'd like to see in Figma`,\n }\n\n const sourceFilename = sourceFilepath\n ? path.parse(sourceFilepath).name.split('.')[0]\n : normalizedName\n\n const filePath = getOutFileName({\n outFile: destinationFile,\n outDir: destinationDir,\n sourceFilename,\n extension: 'tsx',\n })\n\n const importsPath = getImportsPath({\n codeConnectFilePath: filePath,\n sourceFilepath,\n normalizedName,\n })\n\n let defaultImport = ''\n const namedImports: Record<string, string> = {}\n\n for (const figmaConnection of figmaConnections) {\n const { sourceExport, component } = figmaConnection\n\n const importName =\n sourceFilepath && sourceExport\n ? sourceExport === 'default'\n ? normalizeComponentName(sourceFilename)\n : sourceExport\n : normalizedName\n\n if (sourceExport === 'default') {\n defaultImport = importName\n } else {\n namedImports[component.id] = importName\n }\n }\n\n if (defaultImport !== '') {\n defaultImport = Object.values(namedImports).includes(defaultImport)\n ? `${defaultImport}Default`\n : defaultImport\n }\n\n let codeConnectCode = ''\n for (const figmaConnection of figmaConnections) {\n const { propMapping, sourceExport, component, reactTypeSignature } = figmaConnection\n\n const hasAnyMappedProps = propMapping && Object.keys(propMapping).length > 0\n\n const commentType =\n propMapping && hasAnyMappedProps\n ? 'MAPPED_PROPS'\n : propMapping && !hasAnyMappedProps\n ? 'NO_MAPPED_PROPS'\n : 'DEFAULT'\n let comment = comments[commentType]\n\n let componentName = sourceExport === 'default' ? defaultImport : namedImports[component.id]\n\n const snippet = `figma.connect(${componentName}, \"${component.figmaNodeUrl}\", {\n props: ${propMapping ? generatePropsFromMapping(component, propMapping) : generateProps(component)},\n example: (props) => ${generateExample(componentName, reactTypeSignature, propMapping)},\n })`\n\n codeConnectCode += `\n\n /**\n * -- This file was auto-generated by Code Connect --${comment}\n */\n\n ${snippet}\n `\n }\n\n const comma = Object.keys(namedImports).length > 0 && defaultImport ? ',' : ''\n const namedImportList =\n Object.values(namedImports).length > 0 ? `{${Object.values(namedImports).join(',')}}` : ''\n\n let codeConnect = `\nimport React from 'react'\nimport ${defaultImport} ${comma} ${namedImportList} from '${importsPath}'\nimport figma from '@figma/code-connect'\n\n${codeConnectCode}\n`\n\n let formatted = prettier.format(codeConnect, {\n parser: 'typescript',\n semi: false,\n trailingComma: 'all',\n })\n\n if (fs.existsSync(filePath)) {\n return {\n createdFiles: [],\n messages: [{ message: `File ${filePath} already exists, skipping creation`, level: 'ERROR' }],\n }\n }\n fs.mkdirSync(path.dirname(filePath), { recursive: true })\n fs.writeFileSync(filePath, formatted)\n\n return { createdFiles: [{ filePath }], messages: [] }\n}\n"]}
1
+ {"version":3,"file":"create.js","sourceRoot":"","sources":["../../src/react/create.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,sCAUC;AA8CD,0EAwBC;AAgCD,0FAWC;AA4CD,sCAkBC;AAwED,wDA6HC;AAhZD,mCAAkC;AAClC,mDAAoC;AACpC,4CAAmB;AAUnB,gDAAuB;AACvB,8CAA0D;AAC1D,sDAAkF;AAClF,4DAAyD;AAGzD,SAAgB,aAAa,CAAC,SAAiB;IAC7C,MAAM,UAAU,GAAG,SAAS,CAAC,WAAW,EAAE,CAAA;IAC1C,OAAO,CACL,UAAU,KAAK,MAAM;QACrB,UAAU,KAAK,OAAO;QACtB,UAAU,KAAK,KAAK;QACpB,UAAU,KAAK,IAAI;QACnB,UAAU,KAAK,IAAI;QACnB,UAAU,KAAK,KAAK,CACrB,CAAA;AACH,CAAC;AAED,SAAS,iBAAiB,CAAC,IAAY;IACrC,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAA;AACtC,CAAC;AAED,SAAS,oBAAoB,CAAC,IAAY;IACxC,MAAM,WAAW,GAAG,IAAI;QACtB,iDAAiD;SAChD,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC;QAC1B,gCAAgC;SAC/B,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAA;IAEj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AAE,EAAE,CAAA;AACvD,CAAC","sourcesContent":["import { camelCase } from 'lodash'\nimport * as prettier from 'prettier'\nimport fs from 'fs'\nimport z from 'zod'\nimport {\n ComponentPropertyDefinition,\n CreateRequestPayload,\n CreateRequestPayloadMulti,\n CreateResponsePayload,\n FigmaConnectionComponent,\n PropMapping,\n} from '../connect/parser_executable_types'\nimport path from 'path'\nimport { normalizeComponentName } from '../connect/create'\nimport { Intrinsic, IntrinsicKind, ValueMappingKind } from '../connect/intrinsics'\nimport { getOutFileName } from '../connect/create_common'\nimport { ComponentTypeSignature } from './parser'\n\nexport function isBooleanKind(propValue: string) {\n const normalized = propValue.toLowerCase()\n return (\n normalized === 'true' ||\n normalized === 'false' ||\n normalized === 'yes' ||\n normalized === 'no' ||\n normalized === 'on' ||\n normalized === 'off'\n )\n}\n\nfunction normalizePropName(name: string) {\n return name.replace(/#[0-9:]*/g, '')\n}\n\nfunction generateCodePropName(name: string) {\n const cleanedName = name\n // Remove any #node:id from the end of the string\n .replace(/#[0-9:]+$/g, '')\n // Remove any special characters\n .replace(/[^a-zA-Z0-9\\s]/g, '')\n\n return camelCase(cleanedName)\n}\n\nfunction normalizePropValue(name: string) {\n // Convert the string to kebab-case\n return name.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase()\n}\n\nfunction generateExpressionValueMappingKind(valueMappingKind: ValueMappingKind) {\n if (valueMappingKind && typeof valueMappingKind === 'object' && 'kind' in valueMappingKind) {\n return generateExpressionFromIntrinsic(valueMappingKind)\n }\n if (typeof valueMappingKind === 'string') {\n return `\"${valueMappingKind}\"`\n }\n if (\n typeof valueMappingKind === 'number' ||\n typeof valueMappingKind === 'boolean' ||\n typeof valueMappingKind === 'undefined'\n ) {\n return `${valueMappingKind}`\n }\n}\n\nfunction generateExpressionValueMapping(valueMapping: Record<string, ValueMappingKind>) {\n return `{\n ${Object.entries(valueMapping)\n .map(([k, v]) => `\"${k}\": ${generateExpressionValueMappingKind(v)}`)\n .join(`,\\n`)}\n}`\n}\n\n// Not an exhaustive list of intrinsics but can add others as/when they're supported in prop mapping gen\nexport function generateExpressionFromIntrinsic({ kind, args }: Intrinsic): string | never {\n if (kind === IntrinsicKind.String) {\n return `figma.string(\"${args.figmaPropName}\")`\n }\n if (kind === IntrinsicKind.Boolean) {\n return `figma.boolean(\"${args.figmaPropName}\"${args.valueMapping ? `, ${generateExpressionValueMapping(args.valueMapping)}` : ''})`\n }\n if (kind === IntrinsicKind.Enum) {\n return `figma.enum(\"${args.figmaPropName}\"${args.valueMapping ? `, ${generateExpressionValueMapping(args.valueMapping)}` : ''})`\n }\n if (kind === IntrinsicKind.Instance) {\n return `figma.instance(\"${args.figmaPropName}\")`\n }\n if (kind === IntrinsicKind.Slot) {\n return `figma.slot(\"${args.figmaPropName}\")`\n }\n if (kind === IntrinsicKind.Children) {\n return `figma.children(${args.layers.length > 1 ? `[${args.layers.map((layer) => `\"${layer}\"`).join(', ')}]` : `\"${args.layers[0]}\"`})`\n }\n if (kind === IntrinsicKind.TextContent) {\n return `figma.textContent(\"${args.layer}\")`\n }\n // should never reach here as we create prop mappings.\n throw new Error(`kind ${kind} not supported for prop mapping`)\n}\n\nfunction generateSinglePropMappingFromFigmaProp(\n propName: string,\n propDef: ComponentPropertyDefinition,\n) {\n const codePropName = generateCodePropName(propName)\n const figmaPropName = normalizePropName(propName)\n if (propDef.type === 'BOOLEAN') {\n return `\"${codePropName}\": figma.boolean('${figmaPropName}')`\n }\n if (propDef.type === 'TEXT') {\n return `\"${codePropName}\": figma.string('${figmaPropName}')`\n }\n if (propDef.type === 'VARIANT') {\n const isBooleanVariant =\n propDef.variantOptions?.length === 2 && propDef.variantOptions.every(isBooleanKind)\n if (isBooleanVariant) {\n return `\"${codePropName}\": figma.boolean('${figmaPropName}')`\n } else {\n return `\"${codePropName}\": figma.enum('${figmaPropName}', { \\n${propDef.variantOptions\n ?.map((value) => ` \"${value}\": \"${normalizePropValue(value)}\"`)\n .join(',\\n')}\\n})`\n }\n }\n if (propDef.type === 'INSTANCE_SWAP') {\n return `\"${codePropName}\": figma.instance('${figmaPropName}')`\n }\n\n return null\n}\n\nexport function getSetOfAllPropsReferencedInPropMapping(obj: Object) {\n const mappedProps: string[] = []\n Object.entries(obj).forEach(([k, v]) => {\n if (k === 'figmaPropName') {\n mappedProps.push(v)\n }\n if (typeof v === 'object') {\n mappedProps.push(...getSetOfAllPropsReferencedInPropMapping(v))\n }\n })\n return new Set(mappedProps)\n}\n\nfunction generatePropsFromMapping(component: FigmaConnectionComponent, propMapping: PropMapping) {\n const mappedProps: string[] = []\n const unmappedProps: string[] = []\n\n for (const [propName, intrinsic] of Object.entries(propMapping)) {\n const expr = generateExpressionFromIntrinsic(intrinsic)\n if (expr) {\n mappedProps.push(`\"${propName}\": ${expr}`)\n }\n }\n\n const usedFigmaPropsSet = getSetOfAllPropsReferencedInPropMapping(propMapping)\n for (const [propName, propDef] of Object.entries(component.componentPropertyDefinitions || {})) {\n if (!usedFigmaPropsSet.has(propName)) {\n const propMapping = generateSinglePropMappingFromFigmaProp(propName, propDef)\n if (propMapping) {\n unmappedProps.push(propMapping)\n }\n }\n }\n\n return `{\n${\n mappedProps.length\n ? `// These props were automatically mapped based on your linked code:\n ${mappedProps.join(',\\n')},`\n : ''\n}\n ${\n unmappedProps.length\n ? `// No matching props could be found for these Figma properties:\n ${unmappedProps\n .map((prop) => {\n // Comment out to make clear these are suggested. Singly-commented out lines for ease of uncommenting\n return `// ${prop.replace(/\\n/g, '\\n// ')}`\n })\n .join(',\\n')}`\n : ''\n }\n }`\n}\n\nexport function generateProps(component: FigmaConnectionComponent) {\n const props: string[] = []\n if (\n !component.componentPropertyDefinitions ||\n Object.keys(component.componentPropertyDefinitions).length === 0\n ) {\n return `{}`\n }\n\n for (const [propName, propDef] of Object.entries(component.componentPropertyDefinitions)) {\n const propMapping = generateSinglePropMappingFromFigmaProp(propName, propDef)\n if (propMapping) {\n props.push(propMapping)\n }\n }\n return `{\n ${props.join(',\\n ')}\n}`\n}\n\nfunction generateExample(\n component: string,\n signature?: ComponentTypeSignature,\n propMapping?: PropMapping,\n) {\n if (!signature) {\n return `<${component} />`\n }\n const props = Object.entries(signature)\n .map(([propName, propDef]) => {\n // Children are rendered inside of the example body rather than in a prop\n if (propName === 'children') {\n return null\n } else if (propMapping && propMapping[propName]) {\n return `${propName}={props.${propName}}`\n } else if (!propDef.startsWith('?')) {\n return `${propName}={/* TODO */} `\n } else {\n return null\n }\n })\n .filter(Boolean)\n .join('\\n')\n\n // const childProp = propMapping?['children'] ? `{props.${propMapping['children']}}` : null\n\n // Nest child props inside of the element\n if (signature['children'] && propMapping?.['children']) {\n return `<${component}\n ${props}>\n {props.children}\n </${component}>`\n } else {\n return `<${component}\n ${props}/>`\n }\n}\n\n// returns ES-style import path from given system path\nfunction formatImportPath(systemPath: string) {\n // use forward slashes for import paths\n let formattedImportPath = systemPath.replaceAll(path.sep, '/')\n\n // prefix current dir paths with ./ (node path does not)\n if (!formattedImportPath.startsWith('.')) {\n formattedImportPath = `./${formattedImportPath}`\n }\n\n // assume not using ESM imports\n return formattedImportPath.replace(/\\.(jsx|tsx)$/, '')\n}\n\nfunction getImportsPath({\n codeConnectFilePath,\n sourceFilepath,\n normalizedName,\n}: {\n codeConnectFilePath: string\n sourceFilepath?: string\n normalizedName: string\n}) {\n if (!sourceFilepath) {\n return `./${normalizedName}`\n }\n const codeConnectFolder = path.dirname(codeConnectFilePath)\n const pathToComponentFile = path.relative(codeConnectFolder, sourceFilepath)\n\n return formatImportPath(pathToComponentFile)\n}\n\nexport async function createReactCodeConnect(\n payload: CreateRequestPayloadMulti,\n): Promise<z.infer<typeof CreateResponsePayload>> {\n const { figmaConnections, destinationFile, destinationDir, sourceFilepath, normalizedName } =\n payload\n\n const comments = {\n MAPPED_PROPS: `\n * \\`props\\` includes a mapping from your code props to Figma properties.\n * You should check this is correct, and update the \\`example\\` function\n * to return the code example you'd like to see in Figma`,\n NO_MAPPED_PROPS: `\n * None of your props could be automatically mapped to Figma properties.\n * You should update the \\`props\\` object to include a mapping from your\n * code props to Figma properties, and update the \\`example\\` function to\n * return the code example you'd like to see in Figma`,\n DEFAULT: `\n * \\`props\\` includes a mapping from Figma properties and variants to\n * suggested values. You should update this to match the props of your\n * code component, and update the \\`example\\` function to return the\n * code example you'd like to see in Figma`,\n }\n\n const sourceFilename = sourceFilepath\n ? path.parse(sourceFilepath).name.split('.')[0]\n : normalizedName\n\n const filePath = getOutFileName({\n outFile: destinationFile,\n outDir: destinationDir,\n sourceFilename,\n extension: 'tsx',\n })\n\n const importsPath = getImportsPath({\n codeConnectFilePath: filePath,\n sourceFilepath,\n normalizedName,\n })\n\n let defaultImport = ''\n const namedImports: Record<string, string> = {}\n\n for (const figmaConnection of figmaConnections) {\n const { sourceExport, component } = figmaConnection\n\n const importName =\n sourceFilepath && sourceExport\n ? sourceExport === 'default'\n ? normalizeComponentName(sourceFilename)\n : sourceExport\n : normalizedName\n\n if (sourceExport === 'default') {\n defaultImport = importName\n } else {\n namedImports[component.id] = importName\n }\n }\n\n if (defaultImport !== '') {\n defaultImport = Object.values(namedImports).includes(defaultImport)\n ? `${defaultImport}Default`\n : defaultImport\n }\n\n let codeConnectCode = ''\n for (const figmaConnection of figmaConnections) {\n const { propMapping, sourceExport, component, reactTypeSignature } = figmaConnection\n\n const hasAnyMappedProps = propMapping && Object.keys(propMapping).length > 0\n\n const commentType =\n propMapping && hasAnyMappedProps\n ? 'MAPPED_PROPS'\n : propMapping && !hasAnyMappedProps\n ? 'NO_MAPPED_PROPS'\n : 'DEFAULT'\n let comment = comments[commentType]\n\n let componentName = sourceExport === 'default' ? defaultImport : namedImports[component.id]\n\n const snippet = `figma.connect(${componentName}, \"${component.figmaNodeUrl}\", {\n props: ${propMapping ? generatePropsFromMapping(component, propMapping) : generateProps(component)},\n example: (props) => ${generateExample(componentName, reactTypeSignature, propMapping)},\n })`\n\n codeConnectCode += `\n\n /**\n * -- This file was auto-generated by Code Connect --${comment}\n */\n\n ${snippet}\n `\n }\n\n const comma = Object.keys(namedImports).length > 0 && defaultImport ? ',' : ''\n const namedImportList =\n Object.values(namedImports).length > 0 ? `{${Object.values(namedImports).join(',')}}` : ''\n\n let codeConnect = `\nimport React from 'react'\nimport ${defaultImport} ${comma} ${namedImportList} from '${importsPath}'\nimport figma from '@figma/code-connect'\n\n${codeConnectCode}\n`\n\n let formatted = prettier.format(codeConnect, {\n parser: 'typescript',\n semi: false,\n trailingComma: 'all',\n })\n\n if (fs.existsSync(filePath)) {\n return {\n createdFiles: [],\n messages: [{ message: `File ${filePath} already exists, skipping creation`, level: 'ERROR' }],\n }\n }\n fs.mkdirSync(path.dirname(filePath), { recursive: true })\n fs.writeFileSync(filePath, formatted)\n\n return { createdFiles: [{ filePath }], messages: [] }\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  import * as React from 'react';
2
- import { booleanType, enumType, stringType, nestedPropsType, classNameType, textContentType, instanceType } from '../connect/external_types';
2
+ import { booleanType, enumType, stringType, nestedPropsType, classNameType, textContentType, instanceType, slotType } from '../connect/external_types';
3
3
  import { ReactMeta } from './types';
4
4
  declare function connectType<P = {}>(_figmaNodeUrl: string, _meta?: ReactMeta<P>): void;
5
5
  declare function connectType<P = {}>(_component: any, _figmaNodeUrl: string, _meta?: ReactMeta<P>): void;
6
6
  declare function childrenType(_layers: string | string[]): React.DetailedReactHTMLElement<React.HTMLAttributes<HTMLElement>, HTMLElement>;
7
- export { booleanType as boolean, enumType as enum, stringType as string, nestedPropsType as nestedProps, classNameType as className, textContentType as textContent, connectType as connect, instanceType as instance, childrenType as children, };
7
+ export { booleanType as boolean, enumType as enum, stringType as string, nestedPropsType as nestedProps, classNameType as className, textContentType as textContent, connectType as connect, instanceType as instance, childrenType as children, slotType as slot, };
8
8
  //# sourceMappingURL=external.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"external.d.ts","sourceRoot":"","sources":["../../src/react/external.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,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AE,EAAE,UAAU,EAAE,GAAG,EAAE,aAAa,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,IAAI,CAAA;AAGhG,iBAAS,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,kFAE/C;AAED,OAAO,EACL,WAAW,IAAI,OAAO,EACtB,QAAQ,IAAI,IAAI,EAChB,UAAU,IAAI,MAAM,EACpB,eAAe,IAAI,WAAW,EAC9B,aAAa,IAAI,SAAS,EAC1B,eAAe,IAAI,WAAW,EAC9B,WAAW,IAAI,OAAO,EACtB,YAAY,IAAI,QAAQ,EACxB,YAAY,IAAI,QAAQ,EACxB,QAAQ,IAAI,IAAI,GACjB,CAAA"}
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.instance = exports.textContent = exports.className = exports.nestedProps = exports.string = exports.enum = exports.boolean = void 0;
36
+ exports.slot = exports.instance = exports.textContent = exports.className = exports.nestedProps = exports.string = exports.enum = exports.boolean = void 0;
37
37
  exports.connect = connectType;
38
38
  exports.children = childrenType;
39
39
  const React = __importStar(require("react"));
@@ -45,6 +45,7 @@ Object.defineProperty(exports, "nestedProps", { enumerable: true, get: function
45
45
  Object.defineProperty(exports, "className", { enumerable: true, get: function () { return external_types_1.classNameType; } });
46
46
  Object.defineProperty(exports, "textContent", { enumerable: true, get: function () { return external_types_1.textContentType; } });
47
47
  Object.defineProperty(exports, "instance", { enumerable: true, get: function () { return external_types_1.instanceType; } });
48
+ Object.defineProperty(exports, "slot", { enumerable: true, get: function () { return external_types_1.slotType; } });
48
49
  function connectType(_component, _figmaNodeUrl, _meta) { }
49
50
  function childrenType(_layers) {
50
51
  return React.createElement('div');
@@ -1 +1 @@
1
- {"version":3,"file":"external.js","sourceRoot":"","sources":["../../src/react/external.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BiB,8BAAO;AAEN,gCAAQ;AA7B1B,6CAA8B;AAC9B,8DAQkC;AAYjB,wFAnBf,4BAAW,OAmBW;AACV,qFAnBZ,yBAAQ,OAmBQ;AACF,uFAnBd,2BAAU,OAmBU;AACD,4FAnBnB,gCAAe,OAmBe;AACb,0FAnBjB,8BAAa,OAmBa;AACP,4FAnBnB,gCAAe,OAmBe;AAEd,yFApBhB,6BAAY,OAoBY;AAd1B,SAAS,WAAW,CAAC,UAAmB,EAAE,aAAsB,EAAE,KAAe,IAAS,CAAC;AAE3F,SAAS,YAAY,CAAC,OAA0B;IAC9C,OAAO,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,CAAA;AACnC,CAAC","sourcesContent":["import * as React from 'react'\nimport {\n booleanType,\n enumType,\n stringType,\n nestedPropsType,\n classNameType,\n textContentType,\n instanceType,\n} from '../connect/external_types'\nimport { ReactMeta } from './types'\n\nfunction connectType<P = {}>(_figmaNodeUrl: string, _meta?: ReactMeta<P>): void\nfunction connectType<P = {}>(_component: any, _figmaNodeUrl: string, _meta?: ReactMeta<P>): void\nfunction connectType(_component: unknown, _figmaNodeUrl: unknown, _meta?: unknown): void {}\n\nfunction childrenType(_layers: string | string[]) {\n return React.createElement('div')\n}\n\nexport {\n booleanType as boolean,\n enumType as enum,\n stringType as string,\n nestedPropsType as nestedProps,\n classNameType as className,\n textContentType as textContent,\n connectType as connect,\n instanceType as instance,\n childrenType as children,\n}\n"]}
1
+ {"version":3,"file":"external.js","sourceRoot":"","sources":["../../src/react/external.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BiB,8BAAO;AAEN,gCAAQ;AA9B1B,6CAA8B;AAC9B,8DASkC;AAYjB,wFApBf,4BAAW,OAoBW;AACV,qFApBZ,yBAAQ,OAoBQ;AACF,uFApBd,2BAAU,OAoBU;AACD,4FApBnB,gCAAe,OAoBe;AACb,0FApBjB,8BAAa,OAoBa;AACP,4FApBnB,gCAAe,OAoBe;AAEd,yFArBhB,6BAAY,OAqBY;AAEZ,qFAtBZ,yBAAQ,OAsBQ;AAhBlB,SAAS,WAAW,CAAC,UAAmB,EAAE,aAAsB,EAAE,KAAe,IAAS,CAAC;AAE3F,SAAS,YAAY,CAAC,OAA0B;IAC9C,OAAO,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,CAAA;AACnC,CAAC","sourcesContent":["import * as React from 'react'\nimport {\n booleanType,\n enumType,\n stringType,\n nestedPropsType,\n classNameType,\n textContentType,\n instanceType,\n slotType,\n} from '../connect/external_types'\nimport { ReactMeta } from './types'\n\nfunction connectType<P = {}>(_figmaNodeUrl: string, _meta?: ReactMeta<P>): void\nfunction connectType<P = {}>(_component: any, _figmaNodeUrl: string, _meta?: ReactMeta<P>): void\nfunction connectType(_component: unknown, _figmaNodeUrl: unknown, _meta?: unknown): void {}\n\nfunction childrenType(_layers: string | string[]) {\n return React.createElement('div')\n}\n\nexport {\n booleanType as boolean,\n enumType as enum,\n stringType as string,\n nestedPropsType as nestedProps,\n classNameType as className,\n textContentType as textContent,\n connectType as connect,\n instanceType as instance,\n childrenType as children,\n slotType as slot,\n}\n"]}
@@ -732,7 +732,7 @@ async function parseReactDoc(node, parserContext, { repoUrl, silent, skipTemplat
732
732
  return {
733
733
  figmaNode,
734
734
  label: project_1.DEFAULT_LABEL_PER_PARSER.react,
735
- language: label_language_mapping_1.CodeConnectLanguage.TypeScript,
735
+ language: label_language_mapping_1.SyntaxHighlightLanguage.TypeScript,
736
736
  component: metadata?.component,
737
737
  source: metadata?.source ? (0, project_1.getRemoteFileUrl)(metadata.source, repoUrl) : '',
738
738
  sourceLocation: metadata?.line !== undefined ? { line: metadata.line } : { line: -1 },