figma-metadata-extractor 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,8 +10,28 @@ npm install figma-metadata-extractor
10
10
 
11
11
  ## Quick Start
12
12
 
13
+ ### Get Metadata with Auto-Downloaded Images (LLM-Ready!)
14
+
13
15
  ```typescript
14
- import { getFigmaMetadata, downloadFigmaImages, downloadFigmaFrameImage } from 'figma-metadata-extractor';
16
+ import { getFigmaMetadata } from 'figma-metadata-extractor';
17
+
18
+ // Extract metadata AND automatically download image assets
19
+ const metadata = await getFigmaMetadata(
20
+ 'https://figma.com/file/ABC123/My-Design',
21
+ {
22
+ apiKey: 'your-figma-api-key',
23
+ outputFormat: 'object',
24
+ downloadImages: true, // Auto-download image assets
25
+ localPath: './assets/images' // Where to save images
26
+ }
27
+ );
28
+
29
+ ```
30
+
31
+ ### Get Metadata Only (No Downloads)
32
+
33
+ ```typescript
34
+ import { getFigmaMetadata } from 'figma-metadata-extractor';
15
35
 
16
36
  // Extract metadata from a Figma file
17
37
  const metadata = await getFigmaMetadata(
@@ -77,9 +97,24 @@ Extracts comprehensive metadata from a Figma file including layout, content, vis
77
97
  - `useOAuth?: boolean` - Whether to use OAuth instead of API key
78
98
  - `outputFormat?: 'json' | 'yaml' | 'object'` - Output format (default: 'object')
79
99
  - `depth?: number` - Maximum depth to traverse the node tree
100
+ - `downloadImages?: boolean` - Automatically download image assets and enrich metadata (default: false)
101
+ - `localPath?: string` - Local path for downloaded images (required if downloadImages is true)
102
+ - `imageFormat?: 'png' | 'svg'` - Image format for downloads (default: 'png')
103
+ - `pngScale?: number` - Export scale for PNG images (default: 2)
80
104
 
81
105
  **Returns:** Promise<FigmaMetadataResult | string>
82
106
 
107
+ When `downloadImages` is true, nodes with image assets will include a `downloadedImage` property:
108
+ ```typescript
109
+ {
110
+ filePath: string; // Absolute path
111
+ relativePath: string; // Relative path for code
112
+ dimensions: { width, height };
113
+ markdown: string; // ![name](path)
114
+ html: string; // <img src="..." />
115
+ }
116
+ ```
117
+
83
118
  ### `downloadFigmaImages(figmaUrl, nodes, options)`
84
119
 
85
120
  Downloads SVG and PNG images from a Figma file.
package/dist/index.cjs CHANGED
@@ -1365,7 +1365,17 @@ function collapseSvgContainers(node, result, children) {
1365
1365
  return children;
1366
1366
  }
1367
1367
  async function getFigmaMetadata(figmaUrl, options = {}) {
1368
- const { apiKey, oauthToken, useOAuth = false, outputFormat = "object", depth } = options;
1368
+ const {
1369
+ apiKey,
1370
+ oauthToken,
1371
+ useOAuth = false,
1372
+ outputFormat = "object",
1373
+ depth,
1374
+ downloadImages = false,
1375
+ localPath,
1376
+ imageFormat = "png",
1377
+ pngScale = 2
1378
+ } = options;
1369
1379
  if (!apiKey && !oauthToken) {
1370
1380
  throw new Error("Either apiKey or oauthToken is required");
1371
1381
  }
@@ -1399,11 +1409,33 @@ async function getFigmaMetadata(figmaUrl, options = {}) {
1399
1409
  `Successfully extracted data: ${simplifiedDesign.nodes.length} nodes, ${Object.keys(simplifiedDesign.globalVars?.styles || {}).length} styles`
1400
1410
  );
1401
1411
  const { nodes, globalVars, ...metadata } = simplifiedDesign;
1402
- const result = {
1412
+ let result = {
1403
1413
  metadata,
1404
1414
  nodes,
1405
1415
  globalVars
1406
1416
  };
1417
+ if (downloadImages) {
1418
+ if (!localPath) {
1419
+ throw new Error("localPath is required when downloadImages is true");
1420
+ }
1421
+ Logger.log("Discovering and downloading image assets...");
1422
+ const imageAssets = findImageAssets(nodes, globalVars);
1423
+ Logger.log(`Found ${imageAssets.length} image assets to download`);
1424
+ if (imageAssets.length > 0) {
1425
+ const imageNodes = imageAssets.map((asset) => ({
1426
+ nodeId: asset.id,
1427
+ fileName: sanitizeFileName(asset.name) + `.${imageFormat}`
1428
+ }));
1429
+ const downloadResults = await figmaService.downloadImages(
1430
+ fileKey,
1431
+ localPath,
1432
+ imageNodes,
1433
+ { pngScale: imageFormat === "png" ? pngScale : void 0 }
1434
+ );
1435
+ result.nodes = enrichNodesWithImages(nodes, imageAssets, downloadResults);
1436
+ Logger.log(`Successfully downloaded and enriched ${downloadResults.length} images`);
1437
+ }
1438
+ }
1407
1439
  if (outputFormat === "json") {
1408
1440
  return JSON.stringify(result, null, 2);
1409
1441
  } else if (outputFormat === "yaml") {
@@ -1497,6 +1529,60 @@ async function downloadFigmaFrameImage(figmaUrl, options) {
1497
1529
  throw new Error(`Failed to download frame image: ${error instanceof Error ? error.message : String(error)}`);
1498
1530
  }
1499
1531
  }
1532
+ function sanitizeFileName(name) {
1533
+ return name.replace(/[^a-z0-9]/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
1534
+ }
1535
+ function findImageAssets(nodes, globalVars) {
1536
+ const images = [];
1537
+ function traverse(node) {
1538
+ const isImageAsset = node.type === "IMAGE-SVG" || hasImageFill(node, globalVars);
1539
+ if (isImageAsset) {
1540
+ images.push(node);
1541
+ }
1542
+ if (node.children && Array.isArray(node.children)) {
1543
+ node.children.forEach(traverse);
1544
+ }
1545
+ }
1546
+ nodes.forEach(traverse);
1547
+ return images;
1548
+ }
1549
+ function hasImageFill(node, globalVars) {
1550
+ if (!node.fills || typeof node.fills !== "string") {
1551
+ return false;
1552
+ }
1553
+ const fillData = globalVars?.styles?.[node.fills];
1554
+ if (!fillData || !Array.isArray(fillData)) {
1555
+ return false;
1556
+ }
1557
+ return fillData.some((fill) => fill?.type === "IMAGE");
1558
+ }
1559
+ function enrichNodesWithImages(nodes, imageAssets, downloadResults) {
1560
+ const imageMap = /* @__PURE__ */ new Map();
1561
+ imageAssets.forEach((asset, index) => {
1562
+ const result = downloadResults[index];
1563
+ if (result) {
1564
+ imageMap.set(asset.id, {
1565
+ filePath: result.filePath,
1566
+ relativePath: result.filePath.replace(process.cwd(), "."),
1567
+ dimensions: result.finalDimensions,
1568
+ wasCropped: result.wasCropped,
1569
+ markdown: `![${asset.name}](${result.filePath.replace(process.cwd(), ".")})`,
1570
+ html: `<img src="${result.filePath.replace(process.cwd(), ".")}" alt="${asset.name}" width="${result.finalDimensions.width}" height="${result.finalDimensions.height}">`
1571
+ });
1572
+ }
1573
+ });
1574
+ function enrichNode(node) {
1575
+ const enriched = { ...node };
1576
+ if (imageMap.has(node.id)) {
1577
+ enriched.downloadedImage = imageMap.get(node.id);
1578
+ }
1579
+ if (node.children && Array.isArray(node.children)) {
1580
+ enriched.children = node.children.map(enrichNode);
1581
+ }
1582
+ return enriched;
1583
+ }
1584
+ return nodes.map(enrichNode);
1585
+ }
1500
1586
  exports.allExtractors = allExtractors;
1501
1587
  exports.collapseSvgContainers = collapseSvgContainers;
1502
1588
  exports.componentExtractor = componentExtractor;
package/dist/index.js CHANGED
@@ -1363,7 +1363,17 @@ function collapseSvgContainers(node, result, children) {
1363
1363
  return children;
1364
1364
  }
1365
1365
  async function getFigmaMetadata(figmaUrl, options = {}) {
1366
- const { apiKey, oauthToken, useOAuth = false, outputFormat = "object", depth } = options;
1366
+ const {
1367
+ apiKey,
1368
+ oauthToken,
1369
+ useOAuth = false,
1370
+ outputFormat = "object",
1371
+ depth,
1372
+ downloadImages = false,
1373
+ localPath,
1374
+ imageFormat = "png",
1375
+ pngScale = 2
1376
+ } = options;
1367
1377
  if (!apiKey && !oauthToken) {
1368
1378
  throw new Error("Either apiKey or oauthToken is required");
1369
1379
  }
@@ -1397,11 +1407,33 @@ async function getFigmaMetadata(figmaUrl, options = {}) {
1397
1407
  `Successfully extracted data: ${simplifiedDesign.nodes.length} nodes, ${Object.keys(simplifiedDesign.globalVars?.styles || {}).length} styles`
1398
1408
  );
1399
1409
  const { nodes, globalVars, ...metadata } = simplifiedDesign;
1400
- const result = {
1410
+ let result = {
1401
1411
  metadata,
1402
1412
  nodes,
1403
1413
  globalVars
1404
1414
  };
1415
+ if (downloadImages) {
1416
+ if (!localPath) {
1417
+ throw new Error("localPath is required when downloadImages is true");
1418
+ }
1419
+ Logger.log("Discovering and downloading image assets...");
1420
+ const imageAssets = findImageAssets(nodes, globalVars);
1421
+ Logger.log(`Found ${imageAssets.length} image assets to download`);
1422
+ if (imageAssets.length > 0) {
1423
+ const imageNodes = imageAssets.map((asset) => ({
1424
+ nodeId: asset.id,
1425
+ fileName: sanitizeFileName(asset.name) + `.${imageFormat}`
1426
+ }));
1427
+ const downloadResults = await figmaService.downloadImages(
1428
+ fileKey,
1429
+ localPath,
1430
+ imageNodes,
1431
+ { pngScale: imageFormat === "png" ? pngScale : void 0 }
1432
+ );
1433
+ result.nodes = enrichNodesWithImages(nodes, imageAssets, downloadResults);
1434
+ Logger.log(`Successfully downloaded and enriched ${downloadResults.length} images`);
1435
+ }
1436
+ }
1405
1437
  if (outputFormat === "json") {
1406
1438
  return JSON.stringify(result, null, 2);
1407
1439
  } else if (outputFormat === "yaml") {
@@ -1495,6 +1527,60 @@ async function downloadFigmaFrameImage(figmaUrl, options) {
1495
1527
  throw new Error(`Failed to download frame image: ${error instanceof Error ? error.message : String(error)}`);
1496
1528
  }
1497
1529
  }
1530
+ function sanitizeFileName(name) {
1531
+ return name.replace(/[^a-z0-9]/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
1532
+ }
1533
+ function findImageAssets(nodes, globalVars) {
1534
+ const images = [];
1535
+ function traverse(node) {
1536
+ const isImageAsset = node.type === "IMAGE-SVG" || hasImageFill(node, globalVars);
1537
+ if (isImageAsset) {
1538
+ images.push(node);
1539
+ }
1540
+ if (node.children && Array.isArray(node.children)) {
1541
+ node.children.forEach(traverse);
1542
+ }
1543
+ }
1544
+ nodes.forEach(traverse);
1545
+ return images;
1546
+ }
1547
+ function hasImageFill(node, globalVars) {
1548
+ if (!node.fills || typeof node.fills !== "string") {
1549
+ return false;
1550
+ }
1551
+ const fillData = globalVars?.styles?.[node.fills];
1552
+ if (!fillData || !Array.isArray(fillData)) {
1553
+ return false;
1554
+ }
1555
+ return fillData.some((fill) => fill?.type === "IMAGE");
1556
+ }
1557
+ function enrichNodesWithImages(nodes, imageAssets, downloadResults) {
1558
+ const imageMap = /* @__PURE__ */ new Map();
1559
+ imageAssets.forEach((asset, index) => {
1560
+ const result = downloadResults[index];
1561
+ if (result) {
1562
+ imageMap.set(asset.id, {
1563
+ filePath: result.filePath,
1564
+ relativePath: result.filePath.replace(process.cwd(), "."),
1565
+ dimensions: result.finalDimensions,
1566
+ wasCropped: result.wasCropped,
1567
+ markdown: `![${asset.name}](${result.filePath.replace(process.cwd(), ".")})`,
1568
+ html: `<img src="${result.filePath.replace(process.cwd(), ".")}" alt="${asset.name}" width="${result.finalDimensions.width}" height="${result.finalDimensions.height}">`
1569
+ });
1570
+ }
1571
+ });
1572
+ function enrichNode(node) {
1573
+ const enriched = { ...node };
1574
+ if (imageMap.has(node.id)) {
1575
+ enriched.downloadedImage = imageMap.get(node.id);
1576
+ }
1577
+ if (node.children && Array.isArray(node.children)) {
1578
+ enriched.children = node.children.map(enrichNode);
1579
+ }
1580
+ return enriched;
1581
+ }
1582
+ return nodes.map(enrichNode);
1583
+ }
1498
1584
  export {
1499
1585
  allExtractors,
1500
1586
  collapseSvgContainers,
package/dist/lib.d.ts CHANGED
@@ -9,6 +9,14 @@ export interface FigmaMetadataOptions {
9
9
  outputFormat?: "json" | "yaml" | "object";
10
10
  /** Maximum depth to traverse the node tree */
11
11
  depth?: number;
12
+ /** Automatically download image assets and enrich metadata with file paths */
13
+ downloadImages?: boolean;
14
+ /** Local path for downloaded images (required if downloadImages is true) */
15
+ localPath?: string;
16
+ /** Image format for downloads (defaults to 'png') */
17
+ imageFormat?: 'png' | 'svg';
18
+ /** Export scale for PNG images (defaults to 2) */
19
+ pngScale?: number;
12
20
  }
13
21
  export interface FigmaImageOptions {
14
22
  /** Export scale for PNG images (defaults to 2) */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "figma-metadata-extractor",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "Extract metadata and download images from Figma files. A standalone library for accessing Figma design data and downloading frame images programmatically.",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",