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AQ,EAAkB,CAAC,GAC3E,MAAM,EAAS,IAAK,KAAK,UAAW,GAKpC,IAAI,EAAS,EAAiB,IAJI,KAAK,OAAO,KAAK,IAAU,IACxD,EACH,WAAY,EAAO,iBAyBrB,GAAI,EAAO,kBAAmB,CAC5B,IAAI,EAAU,EAEd,MAAM,EAxBR,SAAS,EAAuB,EAAK,EAAU,GAC7C,MAAM,EAAQ,IAAI,IAElB,IAAK,MAAM,KAAQ,YAAY,GAAM,CACnC,MAAM,EAAW,KAAK,EAAK,GACrB,EAAe,KAAK,SAAS,EAAS,GAG5C,GAFa,SAAS,GAEb,cACP,IAAK,MAAM,KAAO,EAAuB,EAAU,GACjD,EAAM,IAAI,QAGZ,EAAM,IAAI,EAEd,CAEA,OAAO,CACT,CAMwB,CAAuB,EAAO,YAEpD,EAAS,EAAO,QAAQ,IACtB,MAAM,EAAW,GAAG,EAAM,QAAQ,EAAO,SACnC,EAAe,KAAK,UAAU,GAE9B,EAAc,EAAc,IAAI,GAItC,OAHI,GACF,KAEM,CAAW,IAGjB,EAAU,GACZ,QAAQ,KACN,YAAY,IAGlB,CAEA,UACQ,KAAK,cAAc,EAAQ,EACnC,CAAE,MAAO,GACP,QAAQ,MAAM,yBAA0B,EAC1C,CAEA,OAAO,IACT","file":"/npm/figma-export-assets@2.0.0/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/figma-export-assets@2.0.0/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { mkdirp } from \"mkdirp\";\nimport { Readable } from \"node:stream\";\nimport pLimit from \"p-limit\";\nimport { readdirSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * @typedef {Object} Config\n * @property {string} figmaPersonalToken - Personal access token for the Figma API.\n * @property {string} fileId - The ID of the Figma file to export assets from.\n * @property {string} page - The name of the page to export assets from.\n * @property {string} assetsPath - The path to save the exported assets.\n * @property {string} [format='svg'] - The format of the exported assets.\n * @property {number} [scale=1] - The scale at which to export assets.\n * @property {boolean} [exportVariants=true] - Whether to export variants of the assets.\n * @property {string} [frame] - The name of the frame to export assets from.\n * @property {number} [batchSize=100] - The number of assets to export in each batch.\n * @property {number} [concurrencyLimit=5] - The maximum number of concurrent requests.\n * @property {boolean} [skipExistingFiles=false] - Whether to skip existing files.\n*/\n\n/**\n * @typedef {Object} Asset\n * @property {string} id - The ID of the asset.\n * @property {string} name - The name of the asset.\n * @property {string} [url] - The URL of the asset image.\n * @property {string} [assetsPath] - The path to save the asset.\n */\n\nexport default class FigmaExporter {\n  /**\n   * Creates a FigmaExporter.\n   * @param {Config} config\n   *\n   * @property {Array<Asset>} assets - The array of assets to be exported.\n   *\n   * @example\n   * const exporter = new FigmaExporter({\n   *\n   *   // Optional\n   *   baseURL: 'https://api.figma.com/v1',\n   *   format: 'svg',\n   *   scale: 1,\n   *   exportVariants: true,\n   *\n   *   // Required\n   *   figmaPersonalToken: 'your-personal-token',\n   *   fileId: 'your-file-id',\n   *   page: 'your-page-name',\n   *   assetsPath: 'path/to/assets',\n   *\n   *   // Optional\n   *   frame: 'your-frame-name'\n   * });\n   */\n  constructor(config) {\n    this.config = {\n      baseURL: \"https://api.figma.com/v1\",\n      format: \"svg\",\n      scale: 1,\n      exportVariants: true,\n      batchSize: 100,\n      concurrencyLimit: 5,\n      ...config,\n    };\n    this.assets = [];\n  }\n\n  /**\n   * Makes a `GET` request to the Figma API\n   *\n   * @private\n   * @param {string} endpoint - API endpoint\n   * @returns {Promise<any>} Parsed JSON response\n   */\n  async figmaGet(endpoint) {\n    const url = `${this.config.baseURL}${endpoint}`;\n    const response = await fetch(url, {\n      method: \"GET\",\n      headers: {\n        \"Content-Type\": \"application/json\",\n        \"X-Figma-Token\": this.config.figmaPersonalToken,\n      },\n    });\n\n    if (!response.ok) {\n      throw new Error(`HTTP error with status: ${response.status}`);\n    }\n\n    return response.json();\n  }\n\n  /**\n   * Sets the assets by fetching them from the Figma API.\n   *\n   * @returns {Promise<FigmaExporter>} The FigmaExporter instance.\n   */\n  async setAssets() {\n    const res = await this.figmaGet(`/files/${this.config.fileId}`);\n    const page = res.document.children.find(\n      (c) => c.name === this.config.page\n    );\n\n    if (!page)\n      throw new Error(`Cannot find page \"${this.config.page}\", check your settings`);\n\n    let assetsArray = page.children;\n    if (this.config.frame) {\n      const frameRoot = page.children.find(\n        (c) => c.name === this.config.frame\n      );\n      if (!frameRoot)\n        throw new Error(\n          `Cannot find ${this.config.frame} Frame in this Page, check your settings`\n        );\n      assetsArray = frameRoot.children;\n    }\n\n    let assets = assetsArray.flatMap((asset) => {\n      if (!this.config.exportVariants || !asset.children?.length) {\n        return [\n          {\n            id: asset.id,\n            name: asset.name,\n          },\n        ];\n      }\n\n      return asset.children.map((child) => {\n        const variants = child.name\n          .split(\",\")\n          .map((prop) => prop.trim())\n          .join(\"--\");\n        return {\n          id: child.id,\n          name: `${asset.name}/${variants}`,\n        };\n      });\n    });\n\n    const findDuplicates = (key, arr) => {\n      const seen = new Set();\n      return arr.filter((item) => {\n        const value = item[key];\n        if (seen.has(value)) {\n          console.warn(`Duplicate key value found: ${value}`);\n          return false;\n        }\n        seen.add(value);\n        return true;\n      });\n    };\n\n    this.assets = findDuplicates(\"name\", assets);\n\n    return this;\n  }\n\n  async processAssets(config = this.config, assets = this.assets) {\n    // Export step\n    for (let i = 0; i < assets.length; i += config.batchSize) {\n      const batch = assets.slice(i, i + config.batchSize);\n      const assetIds = batch.map((a) => a.id).join(\",\");\n\n      const res = await this.figmaGet(\n        `/images/${config.fileId}?ids=${assetIds}&format=${config.format}&scale=${config.scale}`\n      );\n\n      batch.forEach((asset) => {\n        asset.url = res.images[asset.id];\n      });\n    }\n\n    // Save step\n    const limit = pLimit(config.concurrencyLimit);\n    const tasks = assets\n      .filter((asset) => asset.url)\n      .map((asset) =>\n        limit(async () => {\n          const fileName = `${asset.name}.${config.format}`;\n          const filePath = path.resolve(config.assetsPath, fileName);\n          const dir = path.dirname(filePath);\n\n          if (!fs.existsSync(dir)) mkdirp.sync(dir);\n\n          const res = await fetch(asset.url, {\n            headers: { \"X-Figma-Token\": config.figmaPersonalToken },\n          });\n\n          if (!res.ok) {\n            console.warn(`Download failed: ${fileName} – ${res.status}`);\n            return;\n          }\n\n          const buffer = await res.arrayBuffer();\n          const readable = Readable.from(Buffer.from(buffer));\n          const writer = fs.createWriteStream(filePath);\n\n          return new Promise((resolve, reject) => {\n            readable.pipe(writer);\n            writer.on(\"finish\", resolve);\n            writer.on(\"error\", reject);\n          });\n        })\n      );\n\n    await Promise.allSettled(tasks);\n  }\n\n  /** \n   * Creates assets by asking the Figma API for the assets and saving them to the specified path.\n   *\n   * @param {function} [assetTransformFn] - Callback function to transform the asset names.\n   * @param {Object} [configOverrides] - Overrides for the default configuration.\n   * @returns {Promise<FigmaExporter>} The FigmaExporter instance.\n   */\n  async createAssets(assetTransformFn = (assets) => assets, configOverrides = {}) {\n    const config = { ...this.config, ...configOverrides };\n    const assetsIncludingAssetsPath = this.assets.map((asset) => ({\n      ...asset,\n      assetsPath: config.assetsPath,\n    }));\n    let assets = assetTransformFn([...assetsIncludingAssetsPath]);\n\n    function getAllFilesRecursively(dir, rootDir = dir) {\n      const files = new Set();\n\n      for (const item of readdirSync(dir)) {\n        const fullPath = join(dir, item);\n        const relativePath = path.relative(rootDir, fullPath);\n        const stat = statSync(fullPath);\n\n        if (stat.isDirectory()) {\n          for (const sub of getAllFilesRecursively(fullPath, rootDir)) {\n            files.add(sub);\n          }\n        } else {\n          files.add(relativePath);\n        }\n      }\n\n      return files;\n    }\n\n\n    if (config.skipExistingFiles) {\n      let skipped = 0;\n\n      const existingFiles = getAllFilesRecursively(config.assetsPath);\n\n      assets = assets.filter((asset) => {\n        const fileName = `${asset.name}.${config.format}`;\n        const relativePath = path.normalize(fileName);\n\n        const isDuplicate = existingFiles.has(relativePath);\n        if (isDuplicate) {\n          skipped++;\n        }\n        return !isDuplicate;\n      });\n\n      if (skipped > 0) {\n        console.warn(\n          `Skipped: ${skipped}`\n        );\n      }\n    }\n\n    try {\n      await this.processAssets(config, assets);\n    } catch (err) {\n      console.error(\"createAssets() failed:\", err);\n    }\n\n    return this;\n  }\n}\n"]}