datocms-cli

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

DatoCMS CLI Skill

DatoCMS CLI 技能

You are an expert at using the DatoCMS CLI (
datocms
). Follow these steps in order. Do not skip steps.

你是使用DatoCMS CLI(
datocms
)的专家,请按以下步骤操作,不要跳过任何步骤。

Step 1: Detect Context

步骤1:检测上下文

If the project context is already established in this conversation (CLI package, config file, token, migrations directory, TypeScript setup), skip broad detection below. Re-inspect only when a question cannot be answered from prior context.
CLI + link is a required bootstrap for any repo that interfaces with a DatoCMS project. The
datocms
npm package installed +
datocms login
+
datocms link
is how the agent gets visibility into the live project (models, fields, ids, record state). Missing → fix first, same as
git init
or
npm install
.
如果对话中已经明确了项目上下文(CLI包、配置文件、令牌、迁移目录、TypeScript设置),则跳过下面的通用检测。仅当现有上下文无法回答问题时,才重新检查。
对于任何与DatoCMS项目交互的仓库而言,CLI + 项目关联是必需的初始化步骤。 安装
datocms
npm包 + 执行
datocms login
+
datocms link
是让工具获取项目实时信息(模型、字段、ID、记录状态)的方式。如果缺失,需先修复,这和
git init
npm install
的作用类似。

Detection (do not rely on
which datocms
— the CLI runs via
npx
)

检测方式(不要依赖
which datocms
—— CLI可通过
npx
运行)

  1. datocms
    in
    package.json
    devDependencies → CLI available. If missing, install it (
    npm install --save-dev datocms
    ) — never fall back to pasted tokens or manual Dashboard steps.
  2. datocms.config.json
    with a
    siteId
    on the active profile → linked. If missing, drive the bootstrap below.
  3. npx datocms whoami
    succeeds → OAuth session active.
  4. migrations/
    directory → migrations already scaffolded.
  5. tsconfig.json
    or
    migrations.tsconfig
    → TypeScript migrations convention.
  1. package.json
    的devDependencies中存在
    datocms
    → CLI可用。如果缺失,请安装它(
    npm install --save-dev datocms
    )—— 切勿使用粘贴令牌或手动操作控制台的方式替代。
  2. datocms.config.json
    的活跃配置文件中包含
    siteId
    → 已关联项目。如果缺失,请按照下面的初始化流程操作。
  3. npx datocms whoami
    执行成功 → OAuth会话已激活。
  4. 存在
    migrations/
    目录 → 已搭建迁移脚手架。
  5. 存在
    tsconfig.json
    migrations.tsconfig
    → 遵循TypeScript迁移约定。

Bootstrap flow (CLI available but not linked)

初始化流程(CLI可用但未关联项目)

Only
datocms login
needs a terminal; the rest runs in non-TTY.
bash
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 links
Always confirm the target project with the user before running
datocms link
, even when
projects:list
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 link
without
--site-id
requires a terminal. In non-TTY it now exits cleanly with a suggestion to pass
--site-id
; do not retry without it. Same applies when credentials are missing — ask the user to run
datocms login
first.
只有
datocms login
需要交互式终端;其余步骤可在非TTY环境下运行。
bash
npx datocms login                                   # 用户仅需执行一次,交互式操作
npx datocms projects:list [hint] --json             # 工具自动发现siteId
npx datocms link --site-id=<ID> [--organization-id=<ID>]   # 工具关联项目
在执行
datocms link
前,务必与用户确认目标项目
,即使
projects:list
只返回一个候选项目。展示候选项目的信息(名称、ID、组织)并等待用户明确确认。不要将“仅一个结果”视为同意——用户可能有权访问并非想要关联到当前仓库的项目,后续修正错误关联会非常麻烦。
不带
--site-id
参数执行
datocms link
需要终端环境。在非TTY环境下,该命令会正常退出并提示传入
--site-id
参数;请勿在未传入该参数的情况下重试。当凭据缺失时也是如此——请先让用户执行
datocms login

Authentication policy

认证策略

  • Interactive task (publish, delete, fix, backfill, introspect, etc.): OAuth via
    login
    +
    link
    is the mechanism. Never ask the user to paste a token or add
    DATOCMS_CMA_TOKEN=...
    to
    .env
    for this case.
  • Unattended execution (CI, cron, server-side app, shared scripts without an OAuth session): CMA-enabled token via env var. Read-only CDA tokens (
    DATOCMS_READONLY_API_TOKEN
    ,
    NEXT_PUBLIC_DATOCMS_API_TOKEN
    ) will not work — flag that a separate CMA-enabled token is needed. The agent itself still needs CLI + link at development time for visibility.
Token resolution order the CLI uses:
  • --api-token
    flag
  • Linked project (OAuth-backed, the default after
    login
    +
    link
    )
  • Env var:
    DATOCMS_API_TOKEN
    (default profile),
    DATOCMS_<PROFILE>_PROFILE_API_TOKEN
    (named), or custom
    apiTokenEnvName
  • Profile override via
    DATOCMS_PROFILE

  • 交互式任务(发布、删除、修复、回填、内省等):使用
    login
    +
    link
    的OAuth认证机制。在这种情况下,切勿要求用户粘贴令牌或在
    .env
    中添加
    DATOCMS_CMA_TOKEN=...
  • 无人值守执行(CI、定时任务、服务器端应用、无OAuth会话的共享脚本):通过环境变量使用支持CMA的令牌。只读CDA令牌(
    DATOCMS_READONLY_API_TOKEN
    NEXT_PUBLIC_DATOCMS_API_TOKEN
    )无法生效——需告知用户需要单独的支持CMA的令牌。工具在开发阶段仍需要CLI + 项目关联来获取项目信息。
CLI使用的令牌解析顺序:
  • --api-token
    参数
  • 已关联项目(基于OAuth,
    login
    +
    link
    后的默认方式)
  • 环境变量:
    DATOCMS_API_TOKEN
    (默认配置文件)、
    DATOCMS_<PROFILE>_PROFILE_API_TOKEN
    (命名配置文件)或自定义
    apiTokenEnvName
  • 通过
    DATOCMS_PROFILE
    覆盖配置文件

Step 2: Understand the Task

步骤2:理解任务

Classify the user's task into one or more categories:
CategoryExamples
CLI setupInstall CLI, authenticate (
login
/
logout
/
whoami
), discover accessible projects (
projects:list
), link/unlink projects (
link
/
unlink
), configure profiles,
datocms.config.json
Schema changesAdd, modify, or remove models, fields, fieldsets, or block models — via a migration script (default) or a direct CMA operation against a chosen environment
Creating migrationsScaffold new migration scripts, autogenerate from environment diffs, custom templates (sub-task of schema changes once the migration approach is chosen)
Running migrationsExecute pending migrations, dry-run, fork-and-run, in-place execution
Schema generationRun
schema:generate
, scope output to item types, target a specific environment
Direct CMA callsUse
cma:docs
to browse API reference,
cma:call
for a single call with a shape from the docs,
cma:script
for one-off TypeScript logic that needs loops, branching, or typed
Schema.*
types — stdin-mode for heredocs/pipes, file-mode for longer scripts in a gitignored scratch dir
Environment managementFork, promote, rename, destroy, list environments via CLI commands
Deployment workflowMaintenance mode, safe deployment sequences, CI/CD integration
Multi-project syncShared migrations across blueprint/client projects via CLI profiles
Importing contentWordPress import, Contentful import
CLI plugin managementInstall, remove, update, list, inspect, link, or reset CLI plugins (
plugins:*
commands)

将用户的任务归类为以下一个或多个类别:
类别示例
CLI设置安装CLI、认证(
login
/
logout
/
whoami
)、发现可访问项目(
projects:list
)、关联/取消关联项目(
link
/
unlink
)、配置配置文件、
datocms.config.json
Schema变更添加、修改或删除模型、字段、字段集或区块模型 —— 通过迁移脚本(默认方式)或针对指定环境的直接CMA操作
创建迁移搭建新的迁移脚本、根据环境差异自动生成、自定义模板(选择迁移方式后,属于Schema变更的子任务)
运行迁移执行待处理的迁移、试运行、分支运行、原地执行
Schema生成执行
schema:generate
、将输出范围限定为指定条目类型、针对特定环境
直接CMA调用使用
cma:docs
浏览API参考、使用
cma:call
执行单次调用(请求格式参考文档)、使用
cma:script
编写需要循环、分支或带类型
Schema.*
的一次性TypeScript逻辑 —— 标准输入模式支持 heredoc/管道、文件模式适用于存放在Git忽略目录中的长脚本
环境管理通过CLI命令分支、升级、重命名、销毁、列出环境
部署工作流维护模式、安全部署流程、CI/CD集成
多项目同步通过CLI配置文件在蓝图/客户端项目间共享迁移
内容导入WordPress导入、Contentful导入
CLI插件管理安装、移除、更新、列出、检查、关联或重置CLI插件(
plugins:*
命令)

Step 2.5: Collect Critical Inputs Before You Commit To Commands

步骤2.5:执行命令前收集关键信息

Do not skip questions merely because the category is obvious. Skip follow-up questions only if the request already includes the critical inputs for the relevant category, or the repo inspection answers them safely.
Ask the minimum targeted question set needed to avoid flattening a real workflow decision.
不要仅仅因为类别明确就跳过提问。仅当请求中已包含对应类别所需的关键信息,或仓库检查已安全获取这些信息时,才跳过后续提问。
提出最少的针对性问题,避免简化实际工作流决策。

Category-specific inputs live in the reference files

特定类别的信息参考对应文档

Each category reference loaded in Step 3 opens with an "Inputs to confirm before running commands" section — that is the per-category equivalent of this step. Do not skip loading the reference for the task's category: it carries the workflow decisions this step is designed to protect. If you skip it, you skip the checklist.
步骤3中加载的每个类别参考文档开头都有一个**“执行命令前需确认的信息”**部分——这是对应类别的检查清单。不要跳过加载任务所属类别的参考文档:它包含了本步骤旨在保护的工作流决策逻辑。如果跳过,就等于跳过了检查清单。

Schema changes — decide the approach with the user

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.
SituationWhat it coversApproach
Destructive schema changeDROP a field, DROP a model,
bulk_destroy
records, lossy
field_type
changes (e.g.
string → json
,
json → string
, anything that discards stored values)
Migration via
datocms-cli
(
migrations:new
), against a forked sandbox first. Never run these against a primary environment without explicit, repeated user confirmation.
Reversible schema changeAdd a field, add a model or block, rename a field, toggle
required
, add or tighten a validation, reorder fieldsets
Ask the user. Both approaches are safe; pick by preference and context. Lean to a migration (
datocms-cli
) when the repo already uses a migrations workflow or the user is on a secondary branch — reviewable, reproducible. Direct mutation (
cma:call
,
cma:script
stdin-mode, or
cma:script
file-mode) is fine for quick iteration on a sandbox. Default to migration only when the user has no preference AND the repo shows migration conventions (
migrations/
directory, prior migration commits).
User-requested one-offPhrases 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
cma:call
(single call with shape from
cma:docs
) or
cma:script
(stdin-mode for loops/multi-step, file-mode when the script is long enough that a heredoc hurts). Do not re-suggest migrations unless the change turns out to be a destructive schema change.
Content operationPublish, unpublish, delete individual records, fix slugs, bulk update a field value, re-tag uploadsNo migration needed. Prefer
cma:call
for a single call;
cma:script
stdin-mode for loops, pagination, or multi-step logic;
cma:script
file-mode only when a heredoc becomes painful. Code that needs to be committed and replayed across environments is a migration (
datocms-cli
), not datocms-cma.
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.
  • Destructive schema changes and the migration branch of a reversible schema change are this skill's core:
    migrations:new
    ,
    migrations:run
    , fork-and-run, safe deployment. Stay here and load
    creating-migrations.md
    +
    running-migrations.md
    .
  • User-requested one-offs, content operations, and the direct-mutation branch of a reversible schema change are better covered by datocms-cma. Switch when the user has opted out of migrations, when the task is a content mutation (publish, delete, fix), or when the user wants a
    cma:script
    or a checked-in
    buildClient()
    script. The handoff is loading the sibling skill's references — do not bounce the user.
  • Unattended runtime code (CI, app server, webhook, long-lived automation) is a separate scenario — that is where a checked-in
    buildClient()
    script belongs, and datocms-cma owns that pattern.
DatoCMS的Schema操作分为四类。操作方式不是自动选择的——当请求中无法明确类别时,请询问用户,因为可逆性和工作流偏好比使用哪个工具执行变更更重要。
场景覆盖范围操作方式
破坏性Schema变更删除字段、删除模型、
bulk_destroy
记录、有损字段类型变更(例如
string → json
json → string
以及任何会丢弃存储值的变更)
通过
datocms-cli
执行迁移
migrations:new
),首先在分支沙箱环境中执行。在未获得用户明确、反复确认的情况下,切勿在主环境中执行这些操作。
可逆Schema变更添加字段、添加模型或区块、重命名字段、切换
required
属性、添加或收紧验证规则、调整字段集顺序
询问用户。两种方式都是安全的;根据偏好和上下文选择。当仓库已使用迁移工作流或用户在次要分支上时,优先选择迁移(
datocms-cli
)——可审核、可重现。直接变更(
cma:call
cma:script
标准输入模式或
cma:script
文件模式)适用于在沙箱环境中快速迭代。仅当用户无偏好且仓库显示迁移约定(
migrations/
目录、过往迁移提交)时,默认选择迁移。
用户要求的一次性操作类似“快速操作,无需迁移工作流”、“直接修复这个”、“一次性操作”、“不要搭建迁移脚手架”的表述尊重用户选择。使用
cma:call
(单次调用,格式参考
cma:docs
)或
cma:script
(标准输入模式适用于循环/多步骤逻辑,文件模式适用于长脚本)执行直接变更。除非变更被证明是破坏性Schema变更,否则不要重新建议使用迁移。
内容操作发布、取消发布、删除单个记录、修复别名、批量更新字段值、重新标记上传资源无需迁移。单次调用优先使用
cma:call
;循环、分页或多步骤逻辑优先使用
cma:script
标准输入模式;仅当heredoc难以处理时才使用
cma:script
文件模式。需要提交并在多个环境中重放的代码属于迁移(
datocms-cli
),而非datocms-cma
无论加载的是哪个技能,对于可逆Schema变更,向用户提出的问题都是相同的“你希望将此操作为可审核的迁移,还是直接在沙箱环境中执行变更?” 用户的回答决定后续使用哪个技能——而非最初加载的技能。
跨技能路由
  • 破坏性Schema变更和可逆Schema变更的迁移分支是本技能的核心:
    migrations:new
    migrations:run
    、分支运行、安全部署。留在本技能并加载
    creating-migrations.md
    +
    running-migrations.md
  • 用户要求的一次性操作、内容操作以及可逆Schema变更的直接变更分支更适合使用datocms-cma。当用户选择不使用迁移、任务是内容变更(发布、删除、修复)或用户需要
    cma:script
    或已签入的
    buildClient()
    脚本时,切换到该技能。切换方式为加载对应技能的参考文档——无需让用户重新发起请求。
  • 无人值守运行代码(CI、应用服务器、Webhook、长期自动化)是单独的场景——这种情况下应使用已签入的
    buildClient()
    脚本,由datocms-cma负责该模式。

Destructive and production-sensitive confirmations

破坏性和生产敏感操作的确认

Destructive schema changes always require these confirmations; the list below also covers non-schema destructive commands.
If context is missing, ask for explicit confirmation before proposing final commands for:
  • environments:destroy
  • environments:promote
  • imports into a non-obviously disposable target
  • migrations:run --in-place
    on a primary-like environment
  • maintenance:on --force
  • environments:fork --fast --force
  • cma:call
    with
    destroy
    ,
    bulk_destroy
    , or
    promote
    methods
  • direct schema mutations (via
    cma:call
    or
    cma:script
    ) targeting a primary-like environment instead of a migration on a forked sandbox
  • plugins:reset
    (removes all user-installed and linked CLI plugins)

破坏性Schema变更始终需要以下确认;以下列表也涵盖非Schema的破坏性命令。
如果上下文缺失,在提出最终命令前,请明确确认以下操作:
  • environments:destroy
  • environments:promote
  • 导入到非明显可丢弃的目标环境
  • 在类主环境中执行
    migrations:run --in-place
  • maintenance:on --force
  • environments:fork --fast --force
  • 使用
    destroy
    bulk_destroy
    promote
    方法的
    cma:call
  • 针对类主环境的直接Schema变更(通过
    cma:call
    cma:script
    ),而非在分支沙箱环境中执行迁移
  • plugins:reset
    (移除所有用户安装和关联的CLI插件)

Step 3: Load References

步骤3:加载参考文档

Based on the task classification, read the appropriate reference files from the
references/
directory next to this skill file. Only load what is relevant.
Always load:
  • references/cli-setup.md
    — Installation, configuration, profiles, global flags, token resolution
Load per category:
Task categoryReference file
Creating migrations
references/creating-migrations.md
Running migrations
references/running-migrations.md
Schema generation
references/schema-generate.md
Direct CMA calls
references/direct-cma-calls.md
(for
cma:call
) and/or
references/cma-script.md
(for
cma:script
)
Environment management
references/environment-commands.md
Deployment workflow
references/deployment-workflow.md
Multi-project sync
references/blueprint-sync.md
Importing content
references/importing-content.md
CLI plugin management
references/cli-plugin-management.md
Load cross-cutting references when needed:
  • If creating + running migrations together -> load both
    creating-migrations.md
    and
    running-migrations.md
  • If schema generation is followed by typed CMA code changes -> also load
    datocms-cma
    guidance for consuming the generated types
  • If a direct CMA call grows beyond a one-off command -> switch to
    datocms-cma
    for reusable code
  • If deployment involves environment commands -> also load
    environment-commands.md
  • If multi-project sync involves rollout execution -> also load
    running-migrations.md
  • If a CLI plugin install is specifically for WordPress/Contentful import -> also load
    importing-content.md

根据任务分类,读取本技能文件旁
references/
目录中的对应参考文档。仅加载相关文档。
必须加载:
  • references/cli-setup.md
    —— 安装、配置、配置文件、全局参数、令牌解析
按类别加载:
任务类别参考文档
创建迁移
references/creating-migrations.md
运行迁移
references/running-migrations.md
Schema生成
references/schema-generate.md
直接CMA调用
references/direct-cma-calls.md
(适用于
cma:call
)和/或
references/cma-script.md
(适用于
cma:script
环境管理
references/environment-commands.md
部署工作流
references/deployment-workflow.md
多项目同步
references/blueprint-sync.md
内容导入
references/importing-content.md
CLI插件管理
references/cli-plugin-management.md
按需加载跨领域参考文档:
  • 如果同时创建和运行迁移 -> 同时加载
    creating-migrations.md
    running-migrations.md
  • 如果Schema生成后需要修改带类型的CMA代码 -> 同时加载
    datocms-cma
    关于使用生成类型的指南
  • 如果直接CMA调用超出一次性命令的范围 -> 切换到
    datocms-cma
    编写可复用代码
  • 如果部署涉及环境命令 -> 同时加载
    environment-commands.md
  • 如果多项目同步涉及发布执行 -> 同时加载
    running-migrations.md
  • 如果CLI插件安装是专门用于WordPress/Contentful导入 -> 同时加载
    importing-content.md

Step 4: Generate Code

步骤4:生成代码

Write commands and scripts following these mandatory rules:
遵循以下强制规则编写命令和脚本:

Command Prefix

命令前缀

  • Respect the repo's existing package-manager execution style when one is already established (
    npm run ...
    ,
    pnpm exec ...
    ,
    bunx ...
    )
  • Otherwise default to
    npx datocms
    so the local CLI version is used
  • Example:
    npx datocms migrations:new "add blog model" --ts
  • 当仓库已有明确的包管理器执行风格时,遵循该风格(
    npm run ...
    pnpm exec ...
    bunx ...
  • 否则默认使用
    npx datocms
    ,以确保使用本地CLI版本
  • 示例:
    npx datocms migrations:new "add blog model" --ts

Migration File Templates

迁移文件模板

  • When generating migration file content, use the exact function signatures from the reference files
  • TypeScript:
    export default async function(client: Client): Promise<void>
  • JavaScript:
    module.exports = async (client) => {}
  • Import for TypeScript migrations:
    import { Client } from 'datocms/lib/cma-client-node'
  • 生成迁移文件内容时,使用参考文档中的精确函数签名
  • TypeScript:
    export default async function(client: Client): Promise<void>
  • JavaScript:
    module.exports = async (client) => {}
  • TypeScript迁移的导入语句:
    import { Client } from 'datocms/lib/cma-client-node'

File Naming

文件命名

  • Migration files are automatically named:
    {unix_timestamp}_{camelCaseName}.ts|.js
  • Do not manually create migration files — always use
    npx datocms migrations:new
  • 迁移文件自动命名为:
    {unix_timestamp}_{camelCaseName}.ts|.js
  • 不要手动创建迁移文件 —— 始终使用
    npx datocms migrations:new

Migration Script Bodies

迁移脚本主体

  • For the CMA API calls inside migration scripts (creating models, fields, records, uploads), defer to the datocms-cma reference patterns
  • The
    client
    parameter in migrations is the same CMA client from
    @datocms/cma-client-node
  • 迁移脚本中的CMA API调用(创建模型、字段、记录、上传资源)遵循datocms-cma的参考模式
  • 迁移中的
    client
    参数与
    @datocms/cma-client-node
    中的CMA客户端相同

Schema Generation

Schema生成

  • Use
    npx datocms schema:generate <filename>
    to generate TypeScript schema definitions
  • Use
    --item-types
    to narrow the output when the user only needs specific models
  • Use
    --environment
    when the generated types must reflect a sandbox or staging environment
  • Route the follow-up code changes that consume those types to
    datocms-cma
  • 使用
    npx datocms schema:generate <filename>
    生成TypeScript Schema定义
  • 当用户仅需要特定模型时,使用
    --item-types
    缩小输出范围
  • 当生成的类型必须反映沙箱或 staging 环境时,使用
    --environment
  • 将使用这些类型的后续代码修改任务路由到
    datocms-cma

Direct CMA Calls

直接CMA调用

  • Use
    npx datocms cma:docs <resource> <action>
    to look up endpoint details (request body, parameters, examples) before constructing a command
  • Use
    npx datocms cma:call <resource> <method> [...pathArgs]
    for single-method ad-hoc CMA operations
  • Pass request bodies with
    --data '{...}'
    and query parameters with
    --params '{...}'
  • Add
    --environment
    when the call must target a sandbox environment
  • cma:call
    is positional (
    <RESOURCE> <METHOD>
    + URL placeholders as extra positional args). It is not a REST wrapper: there is no
    --endpoint
    ,
    --method
    ,
    --query-params
    , or
    --body
    flag — do not invent these
Concrete shape, with JSON5 accepted in
--data
/
--params
:
bash
npx datocms cma:call items list --params='{filter: {type: "article"}}'
npx datocms cma:call items find <ITEM_ID>
npx datocms cma:call items update <ITEM_ID> --data='{title: "Updated"}'
npx datocms cma:call items publish <ITEM_ID>
npx datocms cma:call fields create <ITEM_TYPE_ID> --data='{label: "Title", api_key: "title", field_type: "string"}'
Run
npx datocms cma:call --help
for the full list of built-in examples, or
npx datocms cma:docs <resource> <action>
for body schema and required fields.
  • Use
    npx datocms cma:script
    when the task needs loops, branching, multiple dependent calls, or typed
    Schema.*
    records, but the code does not need to live in the repo
  • stdin-mode (heredoc / pipe / redirect): top-level await only, ambient
    client
    and
    Schema
    ,
    tsc --noEmit
    type-checks before execution, pre-installed packages available. Zero setup
  • file-mode (
    .ts
    file on disk):
    • Signature:
      export default async function (client: Client)
      with
      Client
      imported from
      datocms/lib/cma-client-node
      — same import as migrations, so a file-mode script can be promoted with a plain
      mv
      into
      migrations/
      .
    • Validation: no CLI-side typecheck; rely on your editor LSP against your
      tsconfig.json
      , or an explicit
      tsc --noEmit
      . Typed
      Schema.*
      is opt-in via
      datocms schema:generate ./datocms-schema.ts
      .
    • Placement: gitignored scratch dir (
      tmp/scripts/
      ,
      scratch/
      ). Prefer a migration for anything you want to commit, version, and replay across environments.
  • Redirect
    2>/dev/null
    when piping stdin-mode stdout into
    jq
  • Switch to datocms-cma when the task needs reusable code checked into the repo for unattended runtime (CI, app server, webhook, long-lived automation)
  • Schema changes: default to scaffolding a migration. Only propose
    cma:call
    or
    cma:script
    for schema mutations after the user has explicitly opted out of the migration workflow, and never propose a direct schema mutation against a primary-like environment without an explicit confirmation from the user
  • 在构造命令前,使用
    npx datocms cma:docs <resource> <action>
    查看端点详情(请求体、参数、示例)
  • 使用
    npx datocms cma:call <resource> <method> [...pathArgs]
    执行单次临时CMA操作
  • 使用
    --data '{...}'
    传递请求体,使用
    --params '{...}'
    传递查询参数
  • 当调用必须针对沙箱环境时,添加
    --environment
  • cma:call
    位置参数式
    <RESOURCE> <METHOD>
    + URL占位符作为额外位置参数)。它不是REST包装器:没有
    --endpoint
    --method
    --query-params
    --body
    参数 —— 请勿自行添加这些参数
具体格式,
--data
/
--params
中支持JSON5:
bash
npx datocms cma:call items list --params='{filter: {type: "article"}}'
npx datocms cma:call items find <ITEM_ID>
npx datocms cma:call items update <ITEM_ID> --data='{title: "Updated"}'
npx datocms cma:call items publish <ITEM_ID>
npx datocms cma:call fields create <ITEM_TYPE_ID> --data='{label: "Title", api_key: "title", field_type: "string"}'
执行
npx datocms cma:call --help
查看完整内置示例,或执行
npx datocms cma:docs <resource> <action>
查看请求体 Schema 和必填字段。
  • 当任务需要循环、分支、多个依赖调用或带类型
    Schema.*
    记录,但代码无需存入仓库时,使用
    npx datocms cma:script
  • 标准输入模式(heredoc / 管道 / 重定向):仅支持顶层await,提供环境
    client
    Schema
    ,执行前会通过
    tsc --noEmit
    进行类型检查,可使用预安装包。无需任何设置
  • 文件模式(磁盘上的
    .ts
    文件):
    • 签名:
      export default async function (client: Client)
      Client
      datocms/lib/cma-client-node
      导入 —— 与迁移的导入语句相同,因此文件模式脚本可通过简单的
      mv
      命令移入
      migrations/
      目录。
    • 验证:CLI端不进行类型检查;依赖编辑器LSP结合
      tsconfig.json
      ,或显式执行
      tsc --noEmit
      。带类型的
      Schema.*
      需通过
      datocms schema:generate ./datocms-schema.ts
      手动启用。
    • 存放位置:Git忽略的临时目录(
      tmp/scripts/
      scratch/
      )。对于需要提交、版本控制并在多个环境中重放的操作,优先使用迁移。
    • 当将标准输入模式的标准输出通过管道传入
      jq
      时,添加
      2>/dev/null
    • 当任务需要存入仓库的可复用代码用于无人值守运行(CI、应用服务器、Webhook、长期自动化)时,切换到datocms-cma
    • Schema变更:默认搭建迁移。仅当用户明确选择不使用迁移工作流时,才建议使用
      cma:call
      cma:script
      执行Schema变更;且在未获得用户明确确认的情况下,切勿建议针对类主环境执行直接Schema变更

CLI Plugin Commands

CLI插件命令

  • Use
    npx datocms plugins:available
    to discover official CLI plugins before installing
  • Use
    npx datocms plugins:add <PLUGIN>
    to install a CLI plugin by npm package name or GitHub URL
  • Use
    npx datocms plugins:link <PATH>
    only for local plugin development
  • These commands manage CLI extensions, not DatoCMS project plugins — route project plugin work to datocms-plugin-builder
  • 在安装前,使用
    npx datocms plugins:available
    发现官方CLI插件
  • 使用
    npx datocms plugins:add <PLUGIN>
    通过npm包名或GitHub URL安装CLI插件
  • 仅在本地插件开发时使用
    npx datocms plugins:link <PATH>
  • 这些命令用于管理CLI扩展,而非DatoCMS项目插件——项目插件相关工作请路由到datocms-plugin-builder

Environment Safety

环境安全

  • Always specify
    --source
    when running migrations to be explicit about the target
  • Use
    --dry-run
    first to preview changes before applying
  • Prefer fork-and-run (default) over
    --in-place
    for production environments
  • Treat
    --force
    as an explicit override, not a default

  • 运行迁移时始终指定
    --source
    ,明确目标环境
  • 先使用
    --dry-run
    预览变更,再实际应用
  • 对于生产环境,优先选择分支运行(默认方式)而非
    --in-place
  • --force
    视为显式覆盖参数,而非默认参数

Step 5: Verify

步骤5:验证

Before presenting the final commands or scripts:
  1. API token — Confirm a CMA-enabled token is available (via env var or
    --api-token
    flag)
  2. Config file — If using profiles, verify
    datocms.config.json
    exists and has the right profile
  3. Migrations directory — Confirm the migrations directory exists or will be created by the command
  4. TypeScript config — If generating TS migrations, ensure
    tsconfig.json
    exists or
    --migrations-tsconfig
    is set
  5. Schema generation scope — If using
    schema:generate
    , verify the output file path plus any
    --item-types
    /
    --environment
    scope match the request
  6. Direct CMA calls — If using
    cma:call
    , verify positional args,
    --data
    ,
    --params
    , and
    --environment
    align with the targeted method. If using
    cma:script
    , verify the script uses
    Schema.*
    types (not
    any
    /
    unknown
    ), imports only from the pre-installed package list, and targets the intended environment
  7. Environment targeting — Verify the correct
    --source
    /
    --destination
    environment is specified
  8. Safety checks — For destructive operations (promote, destroy, destructive
    cma:call
    usage, risky imports, maintenance-mode force), confirm the user intends to target the right environment. For schema mutations, confirm the chosen approach (migration vs direct) and — if direct — the target environment (sandbox vs primary) before issuing commands
  9. CLI plugin commands — If using
    plugins:*
    commands, verify the plugin name is correct and distinguish CLI plugins from DatoCMS project plugins

在展示最终命令或脚本前:
  1. API令牌 —— 确认支持CMA的令牌可用(通过环境变量或
    --api-token
    参数)
  2. 配置文件 —— 如果使用配置文件,验证
    datocms.config.json
    存在且包含正确的配置文件
  3. 迁移目录 —— 确认迁移目录存在,或命令会自动创建该目录
  4. TypeScript配置 —— 如果生成TS迁移,确保
    tsconfig.json
    存在或已设置
    --migrations-tsconfig
  5. Schema生成范围 —— 如果使用
    schema:generate
    ,验证输出文件路径以及
    --item-types
    /
    --environment
    范围符合请求
  6. 直接CMA调用 —— 如果使用
    cma:call
    ,验证位置参数、
    --data
    --params
    --environment
    与目标方法一致。如果使用
    cma:script
    ,验证脚本使用
    Schema.*
    类型(而非
    any
    /
    unknown
    ),仅从预安装包列表导入,且针对预期环境
  7. 环境目标 —— 验证指定的
    --source
    /
    --destination
    环境正确
  8. 安全检查 —— 对于破坏性操作(升级、销毁、危险的
    cma:call
    使用、高风险导入、强制启用维护模式),确认用户意图针对正确的环境。对于Schema变更,确认选择的操作方式(迁移 vs 直接变更);如果是直接变更,在发布命令前确认目标环境(沙箱 vs 主环境)
  9. CLI插件命令 —— 如果使用
    plugins:*
    命令,验证插件名称正确,并区分CLI插件与DatoCMS项目插件

Cross-Skill Routing

跨技能路由

This skill covers CLI commands, flags, configuration, workflows, and migration file scaffolding. If the task involves any of the following, activate the companion skill:
ConditionRoute to
CMA API calls inside migration script bodies (records, schema, uploads)datocms-cma
Programmatic environment management via
client.environments.*
in code
datocms-cma
Consuming generated schema types inside application code or reusable scriptsdatocms-cma
Querying content with GraphQL for frontend displaydatocms-cda
Setting up framework integration, draft mode, or real-time updatesdatocms-frontend-integrations
Building a DatoCMS plugindatocms-plugin-builder
本技能涵盖CLI命令、参数、配置、工作流以及迁移文件搭建。如果任务涉及以下任何内容,请激活配套技能:
条件路由到
迁移脚本主体中的CMA API调用(记录、Schema、上传资源)datocms-cma
通过代码中的
client.environments.*
进行程序化环境管理
datocms-cma
在应用代码或可复用脚本中使用生成的Schema类型datocms-cma
使用GraphQL查询内容用于前端展示datocms-cda
设置框架集成、草稿模式或实时更新datocms-frontend-integrations
构建DatoCMS插件datocms-plugin-builder