figma.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. """Read a selected Figma node without treating input URLs as fetch targets."""
  2. from __future__ import annotations
  3. import json
  4. import re
  5. from urllib.parse import parse_qs, urlparse
  6. import httpx
  7. MAX_BYTES = 8 * 1024 * 1024
  8. NODE_ID = re.compile(r"^[0-9]+:[0-9]+$")
  9. def parse_figma_url(url: str, node_id: str | None = None) -> tuple[str, str]:
  10. parsed = urlparse(url.strip())
  11. if parsed.scheme != "https" or parsed.hostname not in {"www.figma.com", "figma.com"}:
  12. raise ValueError("请输入 https://www.figma.com/design/… 格式的 Figma 链接。")
  13. if parsed.username or parsed.password or parsed.port not in (None, 443):
  14. raise ValueError("Figma 链接不能包含登录信息或自定义端口。")
  15. match = re.fullmatch(r"/(?:design|file|proto)/([a-zA-Z0-9]+)(?:/[^/]*)?/?", parsed.path)
  16. if not match:
  17. raise ValueError("链接中缺少合法的 Figma file key。")
  18. selected = (node_id or parse_qs(parsed.query).get("node-id", [""])[0]).replace("-", ":")
  19. if not NODE_ID.fullmatch(selected):
  20. raise ValueError("请在 Figma 选中一个 Frame,复制带 node-id 的链接,或填写节点 ID(如 1:2)。")
  21. return match.group(1), selected
  22. def fetch_figma(url: str, token: str, node_id: str | None = None, *, client=None) -> tuple[dict, str]:
  23. file_key, selected = parse_figma_url(url, node_id)
  24. if not token.strip():
  25. raise ValueError("缺少 FIGMA_ACCESS_TOKEN,请在项目 .env 中配置有 file_content:read 权限的 Token。")
  26. owned = client is None
  27. client = client or httpx.Client(timeout=30, follow_redirects=False)
  28. try:
  29. with client.stream(
  30. "GET", f"https://api.figma.com/v1/files/{file_key}/nodes",
  31. params={"ids": selected}, headers={"X-Figma-Token": token},
  32. ) as response:
  33. if response.status_code in (401, 403):
  34. raise ValueError("Figma 拒绝访问:请检查 Token 是否有效,以及是否有目标文件的读取权限。")
  35. if response.status_code == 404:
  36. raise ValueError("Figma 文件不存在或当前账号不可访问。")
  37. if response.status_code == 429:
  38. retry = response.headers.get("retry-after", "稍后")
  39. retry = retry if retry.isdigit() else "稍后"
  40. raise ValueError(f"Figma 请求达到限流,请稍后重试(Retry-After: {retry})。")
  41. if response.status_code != 200:
  42. raise ValueError(f"Figma API 返回 HTTP {response.status_code},未生成代码。")
  43. chunks, total = [], 0
  44. for chunk in response.iter_bytes():
  45. total += len(chunk)
  46. if total > MAX_BYTES:
  47. raise ValueError("Figma 节点数据超过 8 MB,请选择更小的 Frame。")
  48. chunks.append(chunk)
  49. try:
  50. payload = json.loads(b"".join(chunks))
  51. except (ValueError, UnicodeDecodeError) as exc:
  52. raise ValueError("Figma 返回的数据不是有效 JSON。") from exc
  53. if not isinstance(payload, dict) or not isinstance(payload.get("nodes"), dict):
  54. raise ValueError("Figma 返回的数据缺少 nodes。")
  55. if not payload["nodes"].get(selected):
  56. raise ValueError(f"Figma 中找不到节点 {selected},请重新复制 Frame 链接。")
  57. return payload, selected
  58. except httpx.TimeoutException as exc:
  59. raise ValueError("Figma 请求超时,请检查网络后重试。") from exc
  60. except httpx.HTTPError as exc:
  61. raise ValueError("无法连接 Figma API,请检查网络后重试。") from exc
  62. finally:
  63. if owned:
  64. client.close()