datocms-cma
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDatoCMS Content Management API Skill
DatoCMS内容管理API(CMA)技能
You are an expert at writing code that interacts with the DatoCMS Content Management API (CMA). Use this workflow as a default. Reorder or skip steps when the task is purely diagnostic, advisory, or the user only needs an explanation.
A short, imperative request in mid-conversation ("publish them",
"delete those", "fix the slugs", "check how many drafts I have") that
follows earlier DatoCMS context is still a DatoCMS task — do not lose
the context just because the latest message is short. Signals that
you are on a DatoCMS-connected repo: packages in
, env vars, ,
.
@datocms/*package.jsonDATOCMS_*datocms.config.jsoncma-types.ts您是编写与DatoCMS内容管理API(CMA)交互代码的专家。请将此工作流作为默认流程。当任务仅为诊断、咨询或用户仅需要解释时,可重新排序或跳过步骤。
对话中途的简短命令式请求(如“发布它们”“删除那些内容”“修复slug”“查看我有多少草稿”),如果之前已有DatoCMS相关上下文,仍属于DatoCMS任务——不要因为最新消息简短而丢失上下文。表明当前仓库已关联DatoCMS的信号包括:中的包、环境变量、、。
package.json@datocms/*DATOCMS_*datocms.config.jsoncma-types.tsStep 1: Detect Context
步骤1:检测上下文
If the project context is already established in this conversation (client
package, authentication approach, environment targeting), skip broad
detection below. Re-inspect only when a question cannot be answered from
prior context.
如果对话中已确立项目上下文(客户端包、认证方式、目标环境),可跳过以下宽泛检测步骤。仅当现有上下文无法回答问题时,才重新检查。
Step 1a — Bootstrap project awareness (CLI + datocms link
is mandatory)
datocms link步骤1a — 初始化项目感知(CLI + datocms link
是必需步骤)
datocms linkAny CMA work on a DatoCMS-connected repo requires agent-side visibility
into the live project (models, fields, ids, record state).
installed + + is that bootstrap — treat it
like or : missing → fix first, do not route around.
datocmsdatocms logindatocms linkgit initnpm installBootstrap flow (only needs an interactive terminal;
the rest the agent drives in non-TTY):
datocms loginbash
npm install --save-dev datocms # if missing
npx datocms login # user, one-time, interactive
npx datocms projects:list [hint] --json # agent discovers siteId
npx datocms link --site-id=<ID> [--organization-id=<ID>] # agent linksAlways confirm the target project with the user before running , even when returns a single candidate. Show the
candidate(s) (name, id, organization) and wait for an explicit yes. Do not
treat "only one result" as consent — the user may have access to a project
they did not mean to wire to this repo, and fixing a mis-linked project
later is painful.
datocms linkprojects:listDetection hints (do not rely on — the CLI runs via
):
which datocmsnpx- in
datocmsdevDependencies → CLI availablepackage.json - with a
datocms.config.jsonon the active profile → linkedsiteId - succeeds → OAuth session active
npx datocms whoami - none of the above → drive the bootstrap above
Token-in- is the exception. An explicit is
only for runtimes that cannot use OAuth: CI, server-side application code,
cron, webhooks, shared repo scripts. Even there, the agent still needs
CLI + link during development for project visibility.
.envDATOCMS_API_TOKENLearning the project's shape. Once linked, run
(optionally with a model API key, id, or
display name) to see the real models, blocks, fields, validators,
fieldsets, nested blocks, and relationships — TOON output by default,
for . Use this any time the agent or user needs to
understand the project structure before writing code, choosing the right
field for a mutation, or deciding which model to query. Prefer it to
composing / by hand. Reference:
.
npx datocms schema:inspect--json| jqcma:call item_types listfields list../datocms-cli/references/schema-inspect.mdRed flag: if you are about to say "paste a CMA token" or "add
to " for a task the user is running
interactively, stop. The right answer is the bootstrap above + the
actual operation expressed as a / invocation
(shapes in Step 4).
DATOCMS_CMA_TOKEN=....envcma:callcma:script任何在已关联DatoCMS的仓库中进行的CMA工作,都需要Agent能够感知项目的实时状态(模型、字段、ID、记录状态)。安装 + + 是初始化流程——将其视为或:缺失则先修复,不要绕过。
datocmsdatocms logindatocms linkgit initnpm install初始化流程(仅需要交互式终端;其余步骤Agent可在非TTY环境下执行):
datocms loginbash
npm install --save-dev datocms # 若未安装
npx datocms login # 用户需执行一次交互式登录
npx datocms projects:list [hint] --json # Agent自动发现siteId
npx datocms link --site-id=<ID> [--organization-id=<ID>] # Agent关联项目在运行前,务必与用户确认目标项目,即使仅返回一个候选项目。展示候选项目的名称、ID、所属组织,等待用户明确确认。不要将“仅一个结果”视为同意——用户可能有权访问并非当前仓库目标的项目,后续修复关联错误会非常麻烦。
datocms linkprojects:list检测提示(不要依赖——CLI可通过运行):
which datocmsnpx- 的devDependencies中存在
package.json→ CLI可用datocms - 的活跃配置文件中包含
datocms.config.json→ 已关联项目siteId - 执行成功 → OAuth会话已激活
npx datocms whoami - 以上均不满足 → 执行上述初始化流程
.envDATOCMS_API_TOKEN了解项目结构。关联项目后,运行(可选择传入模型API密钥、ID或显示名称)查看真实的模型、区块、字段、验证器、字段集、嵌套区块及关联关系——默认输出TOON格式,添加参数可配合使用。每当Agent或用户需要在编写代码、选择变更字段、确定查询模型前了解项目结构时,都应使用该命令。优先使用此命令,而非手动组合/。参考文档:。
npx datocms schema:inspect--json| jqcma:call item_types listfields list../datocms-cli/references/schema-inspect.md警示:如果您打算让用户“粘贴CMA令牌”或“在中添加”来完成交互式任务,请停止。正确的做法是先执行上述初始化流程,再通过/调用完成实际操作(格式见步骤4)。
.envDATOCMS_CMA_TOKEN=...cma:callcma:scriptStep 1b — Package and project detection
步骤1b — 包与项目检测
Once the auth approach is chosen, examine the project to determine the
runtime and which CMA client package is available.
-
Readand check for these packages (in priority order):
package.json- — Universal/isomorphic package. Recommended for most cases. Works in any environment with native
@datocms/cma-client. Only provide afetchif your runtime lacks native Fetch API.fetchFn - — Node.js-optimized. Adds upload helpers (
@datocms/cma-client-node,createFromLocalFile). Use when you need file-system upload convenience methods.createFromUrl - — Browser-optimized. Adds
@datocms/cma-client-browserfor File/Blob uploads.createFromFileOrBlob()
-
If none is installed and the task requirescode, recommend the appropriate package:
buildClient()- General / universal →
@datocms/cma-client - Node.js project needing upload helpers →
@datocms/cma-client-node - Browser-only project needing File/Blob uploads →
@datocms/cma-client-browser
(For pure OAuth-path work via/cma:call, none of these need to be installed — the CLI workspace ships its own client.)cma:script - General / universal →
-
Search for existingcalls to understand how the project already configures the client (API token source, environment targeting, etc.).
buildClient() -
Only if the deliverable is unattended runtime code (see Step 1a): check for aor
.envfile and see whether a CMA-enabled.env.local(or similar) is already defined. If the only variable present is something read-only (DATOCMS_API_TOKEN,DATOCMS_READONLY_API_TOKEN, a CDA token), flag that a separate CMA-enabled token is needed for that specific runtime — not for the agent's own introspection, which must go through CLI + link regardless.NEXT_PUBLIC_DATOCMS_API_TOKEN -
Check for an existingfile to determine if CMA type generation is already set up. Do not proactively suggest setting up type generation. For
cma-types.tslookups,cma:docs, andcma:callthis skill owns the execution shape directly — see the cheat sheets in Step 4. For schema-change requests, see the decision tree in Step 2.5 — it covers when this skill owns the work directly and when it routes to datocms-cli migrations. Otherwise route to datocms-cli for CLI-workflow topics (cma:script, environment operations, imports, plugin management, multi-project sync, CI/CD).schema:generate
Token scope reminder (only when an unattended runtime genuinely needs one): the token must have and a role with the permissions the task requires (publishing, editing schema, etc.). It does not need to be "full-access" — it should be scoped to the smallest set of models, actions, and environments that the runtime actually needs.
can_access_cma: true确定认证方式后,检查项目以确定运行环境及可用的CMA客户端包。
-
读取,按优先级检查以下包:
package.json- — 通用/同构包。推荐用于大多数场景。适用于任何支持原生
@datocms/cma-client的环境。仅当运行环境缺少原生Fetch API时,才需要提供fetch。fetchFn - — 针对Node.js优化的包。新增上传辅助方法(
@datocms/cma-client-node、createFromLocalFile)。当需要文件系统上传便捷方法时使用。createFromUrl - — 针对浏览器优化的包。新增
@datocms/cma-client-browser方法用于File/Blob上传。createFromFileOrBlob()
-
如果未安装任何上述包且任务需要代码,推荐合适的包:
buildClient()- 通用场景 →
@datocms/cma-client - 需要上传辅助方法的Node.js项目 →
@datocms/cma-client-node - 需要File/Blob上传的纯浏览器项目 →
@datocms/cma-client-browser
(对于通过/cma:call完成的纯OAuth路径工作,无需安装上述任何包——CLI工作区已自带客户端。)cma:script - 通用场景 →
-
搜索现有调用,了解项目当前如何配置客户端(API令牌来源、目标环境等)。
buildClient() -
仅当交付物为无人值守运行时代码时(见步骤1a):检查或
.env文件,确认是否已定义支持CMA的.env.local(或类似变量)。如果仅存在只读变量(如DATOCMS_API_TOKEN、DATOCMS_READONLY_API_TOKEN或CDA令牌),则需标记该运行环境需要单独的支持CMA的令牌——Agent自身的项目感知仍需通过CLI + link完成。NEXT_PUBLIC_DATOCMS_API_TOKEN -
检查是否存在文件,确定是否已设置CMA类型生成。不要主动建议设置类型生成。对于
cma-types.ts查询、cma:docs和cma:call,本技能直接控制执行格式——见步骤4的速查表。对于schema变更请求,见步骤2.5中的决策树——该树明确了本技能直接处理的场景,以及需要路由到datocms-cli迁移的场景。其他CLI工作流相关主题(cma:script、环境操作、导入、插件管理、多项目同步、CI/CD)则路由到datocms-cli。schema:generate
令牌范围提醒(仅当无人值守运行环境确实需要时):令牌必须具备,且角色拥有任务所需权限(发布、编辑schema等)。无需设置为“完全访问”——应将范围限定为运行环境实际需要的最小模型、操作和环境集合。
can_access_cma: trueStep 2: Understand the Task
步骤2:理解任务
Classify the user's task into one or more categories. Ask follow-up questions only when the request is ambiguous or the risk of a wrong assumption is high.
- Content operations — Create, read, update, delete, publish, or unpublish records
- Upload operations — Upload files, manage assets, update metadata, bulk tag
- Schema operations — Create or modify models, fields, fieldsets, block models
- Filtering & querying — Search records, filter by fields, paginate large collections
- Localization — Work with localized field values and multi-locale content
- Blocks & modular content — Modular content fields, single-block fields, nested block payloads
- Structured text & block tooling — DAST payloads, embedded blocks, block traversal, debugging helpers
- Environment operations — Fork, promote, rename, delete sandbox environments
- Webhook & deploy operations — Configure webhooks, build triggers, deploy management
- Access control — Create roles, manage API tokens, invite users
- Scheduling — Schedule publish/unpublish, manage workflows
- Migration & scripting — Bulk data operations, content seeding, field migrations
- Type generation — Consume generated CMA schema types or wire typed record operations
- Dashboard & schema menu management — Organize navigation sidebar items, group models in menus
- Plugin management — Install, configure, or audit plugins programmatically
- Project settings & usage — Site settings, maintenance mode, subscription limits, usage tracking, white-label
- Saved filters — Create or manage saved record/upload filter views
- Audit & debugging — Query audit logs, inspect async job results, CMA-side search
If the user's request is clear and falls into an obvious category, skip the clarifying questions and proceed directly.
将用户任务分类为一个或多个类别。仅当请求模糊或错误假设风险较高时,才提出跟进问题。
- 内容操作 — 创建、读取、更新、删除、发布或取消发布记录
- 上传操作 — 上传文件、管理资源、更新元数据、批量打标签
- Schema操作 — 创建或修改模型、字段、字段集、区块模型
- 筛选与查询 — 搜索记录、按字段筛选、大型集合分页
- 本地化 — 处理本地化字段值与多语言内容
- 区块与模块化内容 — 模块化内容字段、单区块字段、嵌套区块负载
- 结构化文本与区块工具 — DAST负载、嵌入区块、区块遍历、调试辅助工具
- 环境操作 — 复制、升级、重命名、删除沙箱环境
- Webhook与部署操作 — 配置Webhook、构建触发器、部署管理
- 访问控制 — 创建角色、管理API令牌、邀请用户
- 定时任务 — 定时发布/取消发布、管理工作流
- 迁移与脚本 — 批量数据操作、内容填充、字段迁移
- 类型生成 — 使用生成的CMA schema类型或实现类型化记录操作
- 仪表盘与schema菜单管理 — 组织导航侧边栏项、在菜单中分组模型
- 插件管理 — 程序化安装、配置或审计插件
- 项目设置与使用情况 — 站点设置、维护模式、订阅限制、使用跟踪、白标配置
- 已保存筛选器 — 创建或管理已保存的记录/上传筛选视图
- 审计与调试 — 查询审计日志、检查异步任务结果、CMA端搜索
如果用户请求明确且属于明显类别,可跳过澄清问题直接执行。
Step 2.5: Schema changes — decide the approach with the user
步骤2.5:Schema变更——与用户确定处理方式
DatoCMS schema operations fall into four buckets. The choice of approach
is not automatic — ask the user when the bucket is not obvious from the
request, because reversibility and workflow preference matter more than
which tool performs the mutation.
| Situation | What it covers | Approach |
|---|---|---|
| Destructive schema change | DROP a field, DROP a model, | Migration via |
| Reversible schema change | Add a field, add a model or block, rename a field, toggle | Ask the user. Both approaches are safe; pick by preference and context. Lean to a migration ( |
| User-requested one-off | Phrases like "quickly, without a migrations workflow", "just patch this", "one-off", "don't scaffold migrations for this" | Honor the opt-out. Use direct mutation via |
| Content operation | Publish, unpublish, delete individual records, fix slugs, bulk update a field value, re-tag uploads | No migration needed. Prefer |
Regardless of which skill is loaded, the question to ask the user is
the same for a reversible schema change: "Do you want this as a
reviewable migration, or a direct mutation against a sandbox?" The
answer determines which skill owns the follow-up — not which skill was
loaded first.
Cross-skill routing.
- User-requested one-offs, content operations, and the direct-mutation
branch of a reversible schema change are this skill's core:
,
cma:callstdin-mode, andcma:scriptfile-mode. Stay here and load the references in Step 3.cma:script - Destructive schema changes, the migration branch of a reversible
schema change, and anything that must be committed/versioned/replayed
across environments are better covered by datocms-cli
(,
migrations:new). Switch when the change is destructive, when the repo already uses a migrations workflow, or when the user wants the change as a reviewable migration. The handoff is loading the sibling skill's references — do not bounce the user.migrations:run - Unattended runtime code (CI, app server, webhook, long-lived
automation) is a separate scenario — that is where a checked-in
script belongs. See Step 4 ("Client Setup").
buildClient()
DatoCMS的Schema操作分为四类。处理方式并非自动确定——当场景无法从请求中明确时,需询问用户,因为可逆性和工作流偏好比工具选择更重要。
| 场景 | 涵盖内容 | 处理方式 |
|---|---|---|
| 破坏性schema变更 | 删除字段、删除模型、 | 迁移:通过 |
| 可逆schema变更 | 添加字段、添加模型或区块、重命名字段、切换 | 询问用户。两种方式均安全,根据偏好和上下文选择。当仓库已使用迁移工作流或用户处于次要分支时,优先选择迁移( |
| 用户请求的一次性操作 | 类似“快速完成,无需迁移工作流”“直接修复”“一次性操作”“不要为此生成迁移脚手架”的表述 | 尊重用户选择退出迁移的需求。通过 |
| 内容操作 | 发布、取消发布、删除单个记录、修复slug、批量更新字段值、重新标记上传内容 | 无需迁移。单次调用优先使用 |
无论加载哪个技能,对于可逆schema变更,向用户提出的问题都是相同的:“您希望将此变更作为可评审的迁移,还是直接在沙箱环境中执行变更?” 用户的回答决定后续由哪个技能处理——与初始加载的技能无关。
跨技能路由
- 用户请求的一次性操作、内容操作,以及可逆schema变更中的直接变更分支,均为本技能的核心场景:、
cma:call标准输入模式和文件模式。继续使用本技能并加载步骤3中的参考文档。cma:script - 破坏性schema变更、可逆schema变更中的迁移分支,以及任何需要提交/版本化/跨环境重放的变更,更适合由datocms-cli(、
migrations:new)处理。当变更具有破坏性、仓库已使用迁移工作流,或用户希望将变更作为可评审迁移时,切换到该技能。切换时只需加载关联技能的参考文档——无需让用户跳转。migrations:run - 无人值守运行时代码(CI、应用服务器、Webhook、长期自动化)属于单独场景——此类场景应使用已提交的脚本。见步骤4(“客户端设置”)。
buildClient()
Step 3: Load References
步骤3:加载参考文档
Two documentation sources are available — pick the right one for the question:
- is the live, always-up-to-date source for endpoint shapes, payload attributes, validators, and client TypeScript signatures. Always reflects the installed client version — never stale. Use it as the default for every "what does this endpoint accept / return" question.
npx datocms cma:docs <resource> <action> - The reference files in this directory carry opinionated mental models, decision trees, cross-cutting workflows, and pattern ordering invariants — things doesn't know. Use them for the "how should I approach this" questions.
cma:docs
is a CLI command — its full surface (flags, naming convention, when to passcma:docs) lives in the sibling skill. Load the datocms-cli skill and read--expand-types§ cma:docs the first time this skill needs to consult endpoint documentation. That file is the single source of truth for the command; do not re-derive the flags from this skill.../datocms-cli/references/direct-cma-calls.md
When writing typed code (, , …), consider passing (or higher) to surface a deeper "Not expanded" type list, or to inline a single declaration. Reach for only as a last resort — its output is verbose.
buildBlockRecord<Schema.X>client.items.create<Schema.X>--types-depth 2--expand-types <SpecificType>--expand-types "*"Always load:
- — Package choice, client setup, token/environment config, error handling
references/client-setup-and-errors.md
Routing per task category — same two-step routine for every row:
- Run to fetch the live endpoint shape, payload attributes, and TS signatures.
npx datocms cma:docs <resource> <action> - Then load the reference listed below for the workflow, mental model, ordering invariants, and gotchas doesn't carry.
cma:docs
Each reference opens with a reminder of the specific to consult — never re-derive endpoint shapes from prose, always pull them live.
cma:docs <resource>| Task category | Reference |
|---|---|
| Content operations | |
| Upload operations | |
| Schema operations | |
| Filtering & querying | |
| Localization | |
| Blocks & modular content | |
| Structured text & block tooling | |
| Environment operations | |
| Access control | |
| Migration & scripting | |
| Type generation | |
| Project settings & usage | |
| Webhook & deploy operations | |
| Scheduling | |
| Dashboard & schema menu management | |
| Plugin management | |
| Saved filters | |
| Audit & debugging | |
Load cross-cutting references when needed:
- If the task involves localized fields in any context → also load
references/localization.md - If the task uses methods, generated CMA types, advanced client behavior, or platform limits → also load
raw*()references/client-types-and-behaviors.md - If the task involves modular content, single-block fields, DAST structured text, block traversal, or any per-locale backfill → also load
references/editing-records.md - If the task involves listing many records → also load
references/filtering-and-pagination.md - If the task is a migration script → also load plus whatever domain refs are needed
references/migration-patterns.md - If the task involves video upload subtitles/tracks or upload tag management → also load § Upload tracks and tags
references/resource-gotchas.md - If the task involves maintenance mode before a migration → also load
references/project-settings-and-usage.md - If the task involves checking subscription limits before bulk operations → also load
references/project-settings-and-usage.md
有两类文档源可供选择——根据问题选择合适的来源:
- 是端点格式、负载属性、验证器和客户端TypeScript签名的实时、始终更新的来源。始终反映已安装的客户端版本——不会过时。将其作为所有“此端点接受/返回什么内容”问题的默认来源。
npx datocms cma:docs <resource> <action> - 本目录中的参考文件包含经验性思维模型、决策树、跨领域工作流和模式排序规则——这些是未涵盖的内容。将其用于“我应如何处理此问题”类问题。
cma:docs
是一个CLI命令——其完整功能(标志、命名约定、何时传递cma:docs)由关联技能定义。 首次需要查阅端点文档时,加载datocms-cli技能并阅读--expand-types中的../datocms-cli/references/direct-cma-calls.md章节。该文件是此命令的唯一权威来源——不要从本技能中推导标志。cma:docs
编写类型化代码(、等)时,可考虑传递(或更高值)以显示更深层次的“未展开”类型列表,或传递以内联单个类型声明。仅在万不得已时使用——其输出过于冗长。
buildBlockRecord<Schema.X>client.items.create<Schema.X>--types-depth 2--expand-types <SpecificType>--expand-types "*"必须加载的文档:
- — 包选择、客户端设置、令牌/环境配置、错误处理
references/client-setup-and-errors.md
按任务类别路由——每一行均遵循两步流程:
- 运行获取实时端点格式、负载属性和TS签名。
npx datocms cma:docs <resource> <action> - 然后加载下方列出的参考文档,获取未涵盖的工作流、思维模型、排序规则和注意事项。
cma:docs
每个参考文档开头都会提醒需查阅的特定——永远不要从 prose 中推导端点格式,始终实时获取。
cma:docs <resource>| 任务类别 | 参考文档 |
|---|---|
| 内容操作 | |
| 上传操作 | |
| Schema操作 | |
| 筛选与查询 | |
| 本地化 | |
| 区块与模块化内容 | |
| 结构化文本与区块工具 | |
| 环境操作 | |
| 访问控制 | |
| 迁移与脚本 | |
| 类型生成 | |
| 项目设置与使用情况 | |
| Webhook与部署操作 | |
| 定时任务 | |
| 仪表盘与schema菜单管理 | |
| 插件管理 | |
| 已保存筛选器 | |
| 审计与调试 | |
必要时加载跨领域参考文档:
- 如果任务涉及任何本地化字段 → 同时加载
references/localization.md - 如果任务使用方法、生成的CMA类型、高级客户端行为或平台限制 → 同时加载
raw*()references/client-types-and-behaviors.md - 如果任务涉及模块化内容、单区块字段、DAST结构化文本、区块遍历或任何按语言环境回填 → 同时加载
references/editing-records.md - 如果任务涉及列出大量记录 → 同时加载
references/filtering-and-pagination.md - 如果任务是迁移脚本 → 同时加载及相关领域参考文档
references/migration-patterns.md - 如果任务涉及视频上传字幕/轨道或上传标签管理 → 同时加载章节:Upload tracks and tags
references/resource-gotchas.md - 如果任务涉及迁移前的维护模式 → 同时加载
references/project-settings-and-usage.md - 如果任务涉及批量操作前检查订阅限制 → 同时加载
references/project-settings-and-usage.md
Step 4: Generate the Solution
步骤4:生成解决方案
When the response includes code, follow these default rules:
当响应包含代码时,请遵循以下默认规则:
Authentication (respect the Step 1a bootstrap)
认证(遵循步骤1a的初始化流程)
- CLI + link is a prerequisite of Step 4, not a choice. If the project is not yet linked, fix that first (propose install + login + link) before writing any solution code.
- For interactive / one-off work (the majority of CMA tasks), do not write code at all — output a
buildClient({ apiToken: ... })invocation (single call with shape fromcma:call) or acma:docsinvocation (stdin-mode for loops/multi-step, file-mode when a heredoc becomes painful) using the shapes below. The CLI handles auth silently via the linked project; no cross-skill hop needed.cma:script - Only when the deliverable is unattended runtime code (CI, server-side app, long-lived automation, repo-committed shared scripts) should the response include + env-var token code.
buildClient()
- CLI + link是步骤4的先决条件,而非可选步骤。如果项目尚未关联,先修复此问题(建议安装+登录+关联),再编写任何解决方案代码。
- 对于交互式/一次性工作(大多数CMA任务),完全无需编写代码——输出
buildClient({ apiToken: ... })调用(使用cma:call中的格式进行单次调用)或cma:docs调用(循环/多步骤逻辑使用标准输入模式,脚本过长导致 heredoc 不便时使用文件模式),格式如下。CLI会通过关联的项目静默处理认证——无需跨技能跳转。cma:script - 仅当交付物为无人值守运行时代码(CI、服务器端应用、长期自动化、仓库提交的共享脚本)时,响应中才应包含+ 环境变量令牌代码。
buildClient()
cma:call
shape — do not invent REST-style flags
cma:callcma:call
格式——不要自定义REST风格标志
cma:callcma:call<RESOURCE> <METHOD>--data--params--endpoint--method--query-params--bodybash
undefinedcma:call<RESOURCE> <METHOD>--data--params--endpoint--method--query-params--bodybash
undefinedList + filter
列表 + 筛选
npx datocms cma:call items list --params='{filter: {type: "article"}}'
npx datocms cma:call items list --params='{filter: {type: "article"}}'
Single resource
单个资源
npx datocms cma:call items find <ITEM_ID>
npx datocms cma:call items find <ITEM_ID>
Mutate (confirm environment first)
变更(先确认环境)
npx datocms cma:call items update <ITEM_ID> --data='{title: "Updated"}'
npx datocms cma:call items publish <ITEM_ID>
npx datocms cma:call items update <ITEM_ID> --data='{title: "Updated"}'
npx datocms cma:call items publish <ITEM_ID>
Schema (prefer a migration unless the user opted out)
Schema变更(除非用户选择退出,否则优先使用迁移)
npx datocms cma:call fields create <ITEM_TYPE_ID> --data='{label: "Title", api_key: "title", field_type: "string"}'
`--data` / `--params` accept JSON5 (unquoted keys, single-quoted wrapping), which
keeps shell escaping sane. If unsure about the exact resource/method/body shape,
run `npx datocms cma:docs <resource> <action>` — that is the authoritative
source.npx datocms cma:call fields create <ITEM_TYPE_ID> --data='{label: "Title", api_key: "title", field_type: "string"}'
`--data`/`--params`接受JSON5(无引号键、单引号包裹),可避免shell转义问题。如果不确定确切的资源/方法/体格式,运行`npx datocms cma:docs <resource> <action>`——这是权威来源。cma:script
shape — typed one-off TypeScript, two modes
cma:scriptcma:script
格式——类型化一次性TypeScript,两种模式
cma:scriptUse when a one-off task needs loops, branching, multiple dependent
calls, or typed record payloads. It has two modes with different
ergonomics — pick by how the script is delivered, not by how "complex" it is.
cma:scriptSchema.*stdin-mode — top-level await, piped or heredoc. Zero setup.
(pre-authenticated) and (project record types) are ambient globals
inside a CLI-bundled workspace; type-checks before execution;
and are rejected. Pre-installed packages available without
install: , , .
is not supported here — use file-mode if you want a function.
clientSchematsc --noEmitanyunknown@datocms/cma-client-nodedatocms-structured-text-*parse5export defaultbash
npx datocms cma:script <<'EOF'
const items = await client.items.list({ filter: { type: 'article' } });
console.log(items.length);
EOFfile-mode — in a
file on disk. Runs in the user's own TypeScript context (validation via
editor LSP against your , or an explicit ;
no CLI-side typecheck). Same throwaway scenario
as stdin-mode — this is not "code to commit"; use it when a heredoc becomes
painful (long script, fragile quoting with /backticks, local helper
imports, or you want to rerun by filename).
export default async function(client: Client).tstsconfig.jsontsc --noEmit$ts
// tmp/scripts/publish-drafts.ts
import type { Client } from 'datocms/lib/cma-client-node';
// Optional typed project schema — run once next to the script:
// npx datocms schema:generate ./datocms-schema.ts
// import * as Schema from './datocms-schema';
export default async function (client: Client): Promise<void> {
for await (const draft of client.items.listPagedIterator({
filter: { fields: { _status: { eq: 'draft' } } },
})) {
await client.items.publish(draft.id);
}
}bash
npx datocms cma:script tmp/scripts/publish-drafts.ts [--environment <env>]Rules of thumb:
- Use first for a single call with a shape you can read from
cma:call. Reach forcma:docsonly when the task needs loops, pagination, branching, dependent calls, or typedcma:scriptpayloads.Schema.* - stdin-mode for quick hacks: pipes, heredocs, one-liners. No file on disk, no project prerequisites.
- file-mode when a heredoc hurts: long script, nested quoting, local
helper imports, or you want to rerun the file by name. Requires
reachable in
datocmsfrom the file's directory; place the file in a gitignored scratch dir (node_modules,tmp/scripts/,scratch/). Prefer a migration for code you want to commit, version, and replay across environments, and do not put file-mode scripts under~/scratch/dato/— that directory is owned bymigrations/.migrations:run - Typed in file-mode is opt-in: run
Schema.*next to the script andnpx datocms schema:generate ./datocms-schema.ts. In stdin-modeimport * as Schema from './datocms-schema'is ambient — no generation needed.Schema.* - Import path matters for promotion: file-mode imports from
Client— the same import migrations use, so a file-mode script can be promoted into a migration with a plaindatocms/lib/cma-client-nodeintomv(signature matches too).migrations/ - Redirect when piping stdin-mode stdout into
2>/dev/null.jq - Pre-installed packages are stdin-only. In file-mode, install what
you need into your own .
package.json - Reach for a checked-in script only when the code must run unattended (CI, app server, webhook, long-lived automation). See "Client Setup" below.
buildClient()
For advanced patterns (workspace flags, stdout shaping, long-running scripts),
consult the datocms-cli skill.
当一次性任务需要循环、分支、多个依赖调用或类型化记录负载时,使用。它有两种模式,各有不同的易用性——根据脚本交付方式选择,而非复杂程度。
Schema.*cma:script标准输入模式——顶级await,通过管道或heredoc传递。零配置。(已预认证)和(项目记录类型)是CLI捆绑工作区中的全局变量;执行前会通过进行类型检查;拒绝和类型。无需安装即可使用预安装包:、、。不支持——如果需要函数,请使用文件模式。
clientSchematsc --noEmitanyunknown@datocms/cma-client-nodedatocms-structured-text-*parse5export defaultbash
npx datocms cma:script <<'EOF'
const items = await client.items.list({ filter: { type: 'article' } });
console.log(items.length);
EOF文件模式——在磁盘上的文件中编写。在用户自己的TypeScript上下文中运行(通过编辑器LSP根据验证,或显式执行;无CLI端类型检查)。与标准输入模式一样属于一次性场景——这不是“需要提交的代码”;当heredoc不便时(脚本过长、/反引号导致引用脆弱、本地辅助函数导入,或希望通过文件名重新运行)使用此模式。
.tsexport default async function(client: Client)tsconfig.jsontsc --noEmit$ts
// tmp/scripts/publish-drafts.ts
import type { Client } from 'datocms/lib/cma-client-node';
// 可选类型化项目schema——在脚本旁运行一次:
// npx datocms schema:generate ./datocms-schema.ts
// import * as Schema from './datocms-schema';
export default async function (client: Client): Promise<void> {
for await (const draft of client.items.listPagedIterator({
filter: { fields: { _status: { eq: 'draft' } } },
})) {
await client.items.publish(draft.id);
}
}bash
npx datocms cma:script tmp/scripts/publish-drafts.ts [--environment <env>]经验法则:
- **优先使用**处理可从
cma:call获取格式的单次调用。仅当任务需要循环、分页、分支、依赖调用或类型化cma:docs负载时,才使用Schema.*。cma:script - 标准输入模式适用于快速临时操作:管道、heredoc、单行脚本。无需磁盘文件,无项目先决条件。
- 文件模式适用于heredoc不便的场景:长脚本、嵌套引用、本地辅助函数导入,或希望通过文件名重新运行。要求从文件目录可在中找到
node_modules;将文件放在git忽略的临时目录(datocms、tmp/scripts/、scratch/)。对于需要提交、版本化并跨环境重放的代码,优先使用迁移,不要将文件模式脚本放在~/scratch/dato/目录下——该目录由migrations/管理。migrations:run - 文件模式中的类型化是可选的:在脚本旁运行
Schema.*并npx datocms schema:generate ./datocms-schema.ts。标准输入模式中import * as Schema from './datocms-schema'是全局变量——无需生成。Schema.* - 导入路径对升级很重要:文件模式从导入
datocms/lib/cma-client-node——与迁移使用的导入路径相同,因此文件模式脚本可通过简单Client到mv目录升级为迁移(签名也匹配)。migrations/ - 将标准输入模式的stdout管道到时,重定向
jq。2>/dev/null - 预安装包仅适用于标准输入模式。文件模式下,需将所需包安装到自己的中。
package.json - 仅当代码必须无人值守运行时(CI、应用服务器、Webhook、长期自动化),才使用已提交的脚本。见下方“客户端设置”。
buildClient()
如需高级模式(工作区标志、stdout格式化、长运行脚本),请查阅datocms-cli技能。
Client Setup (unattended-runtime code only)
客户端设置(仅适用于无人值守运行时代码)
- Default to from the detected package (Step 1b)
buildClient() - Read the API token from an environment variable; never hardcode it and never ask the user to paste it into the chat
- Set the option when working with sandbox environments
environment
- 默认使用步骤1b中检测到的包的
buildClient() - 从环境变量读取API令牌;永远不要硬编码令牌,也不要让用户将令牌粘贴到聊天中
- 处理沙箱环境时,设置选项
environment
API Surface
API接口
- Default to the simplified API (e.g., ) because it handles serialization/deserialization automatically
client.items.create() - Switch to methods only when the task explicitly needs raw JSON:API payloads, relationship metadata, or generated CMA schema types are intentionally part of the solution
raw*()
- 默认使用简化API(例如),因为它会自动处理序列化/反序列化
client.items.create() - 仅当任务明确需要原始JSON:API负载、关联元数据,或生成的CMA schema类型是解决方案的有意组成部分时,才切换到方法
raw*()
Pagination
分页
- Prefer (for example
*.listPagedIterator()) when iterating over collectionsclient.items.listPagedIterator() - Avoid manual offset/limit pagination loops unless a resource genuinely lacks an iterator
- Use to consume async iterators
for await...of
- 遍历集合时,优先使用(例如
*.listPagedIterator())client.items.listPagedIterator() - 除非资源确实缺少迭代器,否则避免手动offset/limit分页循环
- 使用消费异步迭代器
for await...of
Blocks
区块
- Prefer when creating block records for the simplified API
buildBlockRecord() - Import it from the same package as
buildClient
- 使用简化API创建区块记录时,优先使用
buildBlockRecord() - 从与相同的包中导入该方法
buildClient
Error Handling
错误处理
- Catch for API failures — it provides
ApiErrorgetter and.errorsmethod.findError() - Catch for request timeouts in long-running or request-heavy flows
TimeoutError - Import both from the same package as
buildClient
- 捕获处理API失败——它提供
ApiErrorgetter和.errors方法.findError() - 在长运行或请求密集型流程中,捕获处理请求超时
TimeoutError - 从与相同的包中导入这两个错误类型
buildClient
TypeScript
TypeScript
- Follow the TypeScript strictness rules: no , no unnecessary
as unknown ascastsas - Let TypeScript infer types wherever possible
- Use for type-only imports
import type { ... }
- 遵循TypeScript严格规则:不使用,不使用不必要的
as unknown as类型转换as - 尽可能让TypeScript推断类型
- 使用进行仅类型导入
import type { ... }
Step 5: Verify
步骤5:验证
Before presenting the final code:
- Project-awareness bootstrap — Confirm the repo has the npm package installed and the project is linked (
datocmswith adatocms.config.json,siteIdsucceeds). If not, the final proposal must include the install + login + link sequence before any CMA operation. For interactive / one-off tasks the deliverable should be anpx datocms whoami/cma:callinvocation (shapes in Step 4), not acma:scriptscript that requires a token inbuildClient(). Only when the code will run unattended (CI, server-side app, long-lived automation) should a token-in-env solution be presented — and in that case the token must have CMA access enabled and the role permissions the task needs. Schema changes require a role with.env.can_edit_schema: true - Environment targeting — If working with a sandbox, ensure the config option is set
environment - Error handling — Ensure is caught at appropriate boundaries
ApiError - Pagination — If the solution iterates a collection that could exceed a single page, prefer
listPagedIterator() - Type safety — Ensure no type assertions () are used to silence errors
as - Imports — Ensure all imports come from the correct package (the one detected in Step 1)
- Generated types — If the solution intentionally uses generated CMA types (), ensure the chosen path is typed end to end: simplified API generics by default, or
cma-types.ts/raw*()only when raw payload access is intentionalRawApiTypes.Item<>
If the generated code is a script (migration, seeding, etc.), wrap it in an async function with proper error handling and progress reporting.
展示最终代码前:
- 项目感知初始化 — 确认仓库已安装npm包且项目已关联(
datocms包含datocms.config.json,siteId执行成功)。如果未满足,最终方案必须包含安装+登录+关联序列,再执行任何CMA操作。对于交互式/一次性任务,交付物应为npx datocms whoami/cma:call调用(格式见步骤4),而非需要cma:script中存储令牌的.env脚本。仅当代码将无人值守运行时(CI、服务器端应用、长期自动化),才提供令牌存储在环境变量中的解决方案——此时令牌必须启用CMA访问并具备任务所需的角色权限。Schema变更需要角色具备buildClient()权限。can_edit_schema: true - 目标环境 — 如果处理沙箱环境,确保已设置配置选项
environment - 错误处理 — 确保在适当的边界捕获
ApiError - 分页 — 如果解决方案遍历的集合可能超过单页,优先使用
listPagedIterator() - 类型安全 — 确保未使用类型断言()来掩盖错误
as - 导入 — 确保所有导入来自步骤1中检测到的正确包
- 生成的类型 — 如果解决方案有意使用生成的CMA类型(),确保所选路径全程类型化:默认使用简化API泛型,仅当需要原始负载访问时才使用
cma-types.ts/raw*()RawApiTypes.Item<>
如果生成的代码是脚本(迁移、填充等),将其包装在带有适当错误处理和进度报告的异步函数中。
Cross-Skill Routing
跨技能路由
This skill covers content management via the REST CMA (mutations, schema, uploads, webhooks, scripts). If the task involves any of the following, activate the companion skill:
| Condition | Route to |
|---|---|
CLI-workflow topics: migrations (creating, running, autogenerate), | datocms-cli |
| Querying content with GraphQL for frontend display | datocms-cda |
| Setting up draft mode, Web Previews, Content Link, real-time subscriptions, or framework integration | datocms-frontend-integrations |
| Building a DatoCMS plugin | datocms-plugin-builder |
本技能涵盖通过REST CMA进行内容管理(变更、schema、上传、Webhook、脚本)。如果任务涉及以下任何内容,请激活关联技能:
| 条件 | 路由到 |
|---|---|
CLI工作流主题:迁移(创建、运行、自动生成)、 | datocms-cli |
| 使用GraphQL查询内容用于前端展示 | datocms-cda |
| 设置草稿模式、Web预览、内容链接、实时订阅或框架集成 | datocms-frontend-integrations |
| 构建DatoCMS插件 | datocms-plugin-builder |