From 247bcb3a428bd2ca8aa18058d42bcb1405aaa9b6 Mon Sep 17 00:00:00 2001 From: Hebilicious Date: Thu, 19 Nov 2026 09:16:16 +0700 Subject: [PATCH 1/3] feat(sync): sync design tokens with Paper through an inbox The configuration is the source of truth. `cssforge push` sends the tokens it generates to a Paper file; what designers create, change or delete there waits in an inbox until `inbox adopt`, `inbox reject` or `inbox overwrite` settles it. A three-way plan against a committed base in .cssforge/sync/.json decides what to send. The commands are AcidCat capabilities, so they are also MCP tools of `cssforge mcp` and typed library calls. Each design tool sits behind a small adapter; Paper's talks to the MCP server of Paper Desktop (`paper-design mcp`). Every result reports `callsUsed`, because Paper's free plan limits MCP calls, and lists the tokens Paper has no place for. Bumps @acid-cat/core-ts to 0.15.0 for the destructive and idempotent hints and two-word command aliases. --- .changeset/paper-token-sync.md | 12 + README.md | 77 +- packages/cssforge/README.md | 77 +- packages/cssforge/cssforge.acidcat.json | 3090 ++++++++++++++++- packages/cssforge/jsr.json | 2 +- packages/cssforge/package.json | 4 +- packages/cssforge/src/capabilities.ts | 46 +- packages/cssforge/src/forge.ts | 8 + packages/cssforge/src/generator.ts | 49 + packages/cssforge/src/sync/capabilities.ts | 949 +++++ packages/cssforge/src/sync/mcp-client.ts | 159 + packages/cssforge/src/sync/paper.ts | 275 ++ packages/cssforge/src/sync/plan.ts | 383 ++ packages/cssforge/src/sync/remote.ts | 64 + packages/cssforge/src/sync/state.ts | 135 + packages/cssforge/tests/acidcat.test.ts | 21 +- .../cssforge/tests/fixtures/fake-paper-mcp.ts | 99 + packages/cssforge/tests/sync-paper.test.ts | 134 + packages/cssforge/tests/sync.test.ts | 549 +++ pnpm-lock.yaml | 50 +- skills/cssforge/references/cli-reference.md | 34 +- 21 files changed, 6098 insertions(+), 119 deletions(-) create mode 100644 .changeset/paper-token-sync.md create mode 100644 packages/cssforge/src/sync/capabilities.ts create mode 100644 packages/cssforge/src/sync/mcp-client.ts create mode 100644 packages/cssforge/src/sync/paper.ts create mode 100644 packages/cssforge/src/sync/plan.ts create mode 100644 packages/cssforge/src/sync/remote.ts create mode 100644 packages/cssforge/src/sync/state.ts create mode 100644 packages/cssforge/tests/fixtures/fake-paper-mcp.ts create mode 100644 packages/cssforge/tests/sync-paper.test.ts create mode 100644 packages/cssforge/tests/sync.test.ts diff --git a/.changeset/paper-token-sync.md b/.changeset/paper-token-sync.md new file mode 100644 index 0000000..53e0361 --- /dev/null +++ b/.changeset/paper-token-sync.md @@ -0,0 +1,12 @@ +--- +"@hebilicious/cssforge": minor +--- + +Sync the tokens of a design tool with the configuration, starting with Paper. + +- `cssforge remote add --file ` binds a Paper file. `cssforge fetch`, `cssforge plan` and `cssforge push` read the file, show the plan and send it: create, update and delete the tokens that the configuration generates. +- What designers change in the file waits in an inbox: `cssforge inbox`. Settle a new token with `cssforge inbox adopt` (after you add it to the configuration) or `cssforge inbox reject`, and a changed or deleted token with `cssforge inbox overwrite`. +- The state is in `.cssforge/sync/.json`. Commit it. +- Each result lists the tokens that Paper has no place for, with the reason, and the number of requests made to Paper. +- The commands are also MCP tools of `cssforge mcp` and typed calls of `@hebilicious/cssforge/capabilities`. `sync.push` and `tokens.build` are marked destructive for MCP clients, and the read-only tools are marked read-only. +- `@acid-cat/core-ts` is updated to 0.15.0. diff --git a/README.md b/README.md index 033f696..86d5da1 100644 --- a/README.md +++ b/README.md @@ -2218,13 +2218,88 @@ Musea reads `value`, `type`, and `$reference` from this file. Keep the default ` mode: previews and token swatches render from `value`, and `attributes.tailwindVariable` is what lets Musea attribute a `var(--token)` written in an art file back to its token. +## Sync tokens with a design tool + +`cssforge` keeps the tokens of a design file in sync with the configuration. The +configuration is the source of truth: the tokens it generates are pushed to the file, and +what designers change in the file waits in an inbox until you decide what to do with it. +[Paper](https://paper.design) is the first supported design tool; its desktop app serves the +MCP server that `cssforge` talks to (`paper-design mcp`). + +```bash +# Bind a Paper file to the configuration (one request). Writes .cssforge/sync/paper.json. +cssforge remote add --file https://app.paper.design/file/ + +# Read the file and show the plan, without changing it (one request) +cssforge fetch + +# Show the plan again after a change of the config or a decision (no request) +cssforge plan + +# Send the plan: create, update and delete tokens, and carry out the decisions +cssforge push +cssforge push --dry-run + +# The changes designers made in the file +cssforge inbox + +# A token a designer created: add it to the config first, then adopt it under that path. +# The path is the token path, as each pushed token shows it in its description +# (`cssforge: palette.brand.accent`). The next push renames the token in the file to the +# name the config generates. +cssforge inbox adopt --item brand-accent --path palette.brand.accent +# Or delete it from the file at the next push +cssforge inbox reject --item brand-accent + +# A token of the config that a designer changed or deleted: the next push writes the +# config's value again. To keep the designer's value, change the config instead. +cssforge inbox overwrite --item spacing-size-1 +``` + +Commit `.cssforge/sync/.json`: it holds the file id, the tokens as they were after the +last push, and the decisions, so everyone who syncs shares the same base. `--remote ` +selects another remote (the default is `paper`), and `remote add --name ` binds one. + +| Inbox item | What happened in the file | Decisions | +| --- | --- | --- | +| `new` | A designer created a token that the config does not have | `adopt`, `reject` | +| `edited` | A designer changed the value of a config token | `overwrite` | +| `deleted` | A designer deleted a config token | `overwrite` | +| `collision` | The file has a token with the name of a new config token | `overwrite` | + +When `push` renames a token (after `inbox adopt`), the designs that use it keep using it under +the new name. When it deletes a token (after `inbox reject`, or because the token left the +config), Paper replaces each use with the token's last value, so designs keep their look but +lose the link to the token. + +An item without a decision blocks only its own token: `push` sends every other change. A +change that the file refuses stays in the plan, and the next push sends it again. Each result +has `callsUsed`, the number of requests made to the design tool, because Paper's free plan +limits MCP tool calls. A push reads the file once, writes at most twice, and reads the stored +values back once; with nothing to send, it makes one request. + +Not every token has a place in Paper. Each result lists the tokens it leaves out in `skipped`, +with the reason: + +| Token | In Paper | +| --- | --- | +| Palette colors, spacing, fluid type sizes (`clamp()`), font weights | Color, spacing, font size and font weight tokens | +| A token whose value is `var(--other)` | An alias of the other token, when both have the same type | +| Mixed colors (`color-mix()`) and paired themes (`light-dark()`) | Left out: Paper does not take these values | +| Tokens under a selector or an at-rule (themes with a `selector`) | Left out: Paper has no modes | +| The helper tokens of a `pow()` type scale | Left out: the `clamp()` scale is synced | +| Motion, gradients and primitives without a Paper type | Left out | + ## Agentic usage Agents can run the `cssforge` CLI like any other command: an agent gets JSON (`--agent` forces it), and `cssforge list` describes every command and its flags. `cssforge mcp` serves the same commands as MCP tools, through standard input and output: -`tokens.build`, `tokens.generate` and `config.check`, and the event `tokens.built`. Paths +`tokens.build`, `tokens.generate`, `config.check`, the [sync](#sync-tokens-with-a-design-tool) +tools (`sync.fetch`, `sync.push`, `sync.inbox.adopt`, …), and the event `tokens.built`. Each +tool tells the agent whether it changes anything: `sync.push` is marked destructive, so a client +can ask before it runs. Paths resolve against the directory where the agent starts the server, or against the `root` of a call. To add it to Claude Code: diff --git a/packages/cssforge/README.md b/packages/cssforge/README.md index 033f696..86d5da1 100644 --- a/packages/cssforge/README.md +++ b/packages/cssforge/README.md @@ -2218,13 +2218,88 @@ Musea reads `value`, `type`, and `$reference` from this file. Keep the default ` mode: previews and token swatches render from `value`, and `attributes.tailwindVariable` is what lets Musea attribute a `var(--token)` written in an art file back to its token. +## Sync tokens with a design tool + +`cssforge` keeps the tokens of a design file in sync with the configuration. The +configuration is the source of truth: the tokens it generates are pushed to the file, and +what designers change in the file waits in an inbox until you decide what to do with it. +[Paper](https://paper.design) is the first supported design tool; its desktop app serves the +MCP server that `cssforge` talks to (`paper-design mcp`). + +```bash +# Bind a Paper file to the configuration (one request). Writes .cssforge/sync/paper.json. +cssforge remote add --file https://app.paper.design/file/ + +# Read the file and show the plan, without changing it (one request) +cssforge fetch + +# Show the plan again after a change of the config or a decision (no request) +cssforge plan + +# Send the plan: create, update and delete tokens, and carry out the decisions +cssforge push +cssforge push --dry-run + +# The changes designers made in the file +cssforge inbox + +# A token a designer created: add it to the config first, then adopt it under that path. +# The path is the token path, as each pushed token shows it in its description +# (`cssforge: palette.brand.accent`). The next push renames the token in the file to the +# name the config generates. +cssforge inbox adopt --item brand-accent --path palette.brand.accent +# Or delete it from the file at the next push +cssforge inbox reject --item brand-accent + +# A token of the config that a designer changed or deleted: the next push writes the +# config's value again. To keep the designer's value, change the config instead. +cssforge inbox overwrite --item spacing-size-1 +``` + +Commit `.cssforge/sync/.json`: it holds the file id, the tokens as they were after the +last push, and the decisions, so everyone who syncs shares the same base. `--remote ` +selects another remote (the default is `paper`), and `remote add --name ` binds one. + +| Inbox item | What happened in the file | Decisions | +| --- | --- | --- | +| `new` | A designer created a token that the config does not have | `adopt`, `reject` | +| `edited` | A designer changed the value of a config token | `overwrite` | +| `deleted` | A designer deleted a config token | `overwrite` | +| `collision` | The file has a token with the name of a new config token | `overwrite` | + +When `push` renames a token (after `inbox adopt`), the designs that use it keep using it under +the new name. When it deletes a token (after `inbox reject`, or because the token left the +config), Paper replaces each use with the token's last value, so designs keep their look but +lose the link to the token. + +An item without a decision blocks only its own token: `push` sends every other change. A +change that the file refuses stays in the plan, and the next push sends it again. Each result +has `callsUsed`, the number of requests made to the design tool, because Paper's free plan +limits MCP tool calls. A push reads the file once, writes at most twice, and reads the stored +values back once; with nothing to send, it makes one request. + +Not every token has a place in Paper. Each result lists the tokens it leaves out in `skipped`, +with the reason: + +| Token | In Paper | +| --- | --- | +| Palette colors, spacing, fluid type sizes (`clamp()`), font weights | Color, spacing, font size and font weight tokens | +| A token whose value is `var(--other)` | An alias of the other token, when both have the same type | +| Mixed colors (`color-mix()`) and paired themes (`light-dark()`) | Left out: Paper does not take these values | +| Tokens under a selector or an at-rule (themes with a `selector`) | Left out: Paper has no modes | +| The helper tokens of a `pow()` type scale | Left out: the `clamp()` scale is synced | +| Motion, gradients and primitives without a Paper type | Left out | + ## Agentic usage Agents can run the `cssforge` CLI like any other command: an agent gets JSON (`--agent` forces it), and `cssforge list` describes every command and its flags. `cssforge mcp` serves the same commands as MCP tools, through standard input and output: -`tokens.build`, `tokens.generate` and `config.check`, and the event `tokens.built`. Paths +`tokens.build`, `tokens.generate`, `config.check`, the [sync](#sync-tokens-with-a-design-tool) +tools (`sync.fetch`, `sync.push`, `sync.inbox.adopt`, …), and the event `tokens.built`. Each +tool tells the agent whether it changes anything: `sync.push` is marked destructive, so a client +can ask before it runs. Paths resolve against the directory where the agent starts the server, or against the `root` of a call. To add it to Claude Code: diff --git a/packages/cssforge/cssforge.acidcat.json b/packages/cssforge/cssforge.acidcat.json index 536957a..65e453f 100644 --- a/packages/cssforge/cssforge.acidcat.json +++ b/packages/cssforge/cssforge.acidcat.json @@ -1,7 +1,7 @@ { "acidcat": "0.1", "title": "CSS Forge", - "description": "Generate CSS custom properties, JSON, TypeScript and Style Dictionary tokens from a CSS Forge configuration.", + "description": "Generate CSS custom properties, JSON, TypeScript and Style Dictionary tokens from a CSS Forge configuration, and keep the tokens of a design tool in sync with it.", "targets": { "cli": { "bindings": [ @@ -20,30 +20,2934 @@ "check": { "capability": "config.check" }, + "fetch": { + "capability": "sync.fetch" + }, "generate": { "capability": "tokens.generate" + }, + "inbox": { + "capability": "sync.inbox.list" + }, + "inbox adopt": { + "capability": "sync.inbox.adopt" + }, + "inbox overwrite": { + "capability": "sync.inbox.overwrite" + }, + "inbox reject": { + "capability": "sync.inbox.reject" + }, + "plan": { + "capability": "sync.plan" + }, + "push": { + "capability": "sync.push" + }, + "remote add": { + "capability": "sync.remote.add" + } + }, + "default": "build" + } + } + }, + "library": { + "bindings": [ + "typescript" + ], + "description": "Typed calls from code, through @hebilicious/cssforge/capabilities." + }, + "mcp": { + "bindings": [ + "mcp" + ], + "description": "The MCP server of `cssforge mcp`, for agents." + } + }, + "capabilities": { + "config.check": { + "description": "Load and validate a CSS Forge configuration, and give its warnings: values that generate, but likely not as intended. Writes no file.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "color-formats": { + "default": [], + "description": "Extra color formats generated beside oklch(), added to the formats that the configuration declares.", + "items": { + "enum": [ + "hex", + "rgb" + ], + "type": "string" + }, + "type": "array" + }, + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "root": { + "description": "The directory that the relative paths of the input resolve against. The default is the working directory of the tools.", + "minLength": 1, + "type": "string" + } + }, + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "dependencies": { + "description": "The absolute paths of the configuration and the local modules it imports.", + "items": { + "type": "string" + }, + "type": "array" + }, + "diagnostics": { + "items": { + "additionalProperties": false, + "description": "A warning about a value that generates, but likely not as intended.", + "properties": { + "code": { + "description": "A stable identifier of the warning.", + "enum": [ + "typography-static-scale", + "typography-below-legibility-floor", + "motion-long-duration", + "motion-ease-in" + ], + "type": "string" + }, + "message": { + "description": "What is wrong, and how to fix it.", + "type": "string" + }, + "path": { + "description": "The configuration path of the value.", + "type": "string" + }, + "severity": { + "const": "warning", + "type": "string" + } + }, + "required": [ + "code", + "severity", + "path", + "message" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "diagnostics", + "dependencies" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated, or it has no default export object.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "The configuration loaded, but CSS Forge rejects a value in it.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "readOnly": true + }, + "sync.fetch": { + "description": "Read the tokens of the remote (one request), record them in the state file, and report the plan: the changes the next push sends, the inbox of changes the remote made, and the configuration tokens that have no place on the remote. Sends nothing to the remote.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "callsUsed": { + "description": "The requests made to the remote by this call.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "fetchedAt": { + "description": "When the remote tokens were read, as an ISO 8601 time.", + "type": "string" + }, + "file": { + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "id", + "name" + ], + "type": "object" + }, + "inbox": { + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "localValue": { + "type": "string" + }, + "name": { + "type": "string" + }, + "note": { + "type": "string" + }, + "remoteValue": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "name", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "operations": { + "description": "The changes the next push sends, in order.", + "items": { + "description": "A change to send to the remote.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "create", + "type": "string" + }, + "type": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "op", + "name", + "type", + "value", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "update", + "type": "string" + }, + "type": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "op", + "name", + "type", + "value", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "from": { + "type": "string" + }, + "op": { + "const": "rename", + "type": "string" + }, + "to": { + "type": "string" + } + }, + "required": [ + "op", + "from", + "to" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "op": { + "const": "delete", + "type": "string" + } + }, + "required": [ + "op", + "name" + ], + "type": "object" + } + ] + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens that have no place on the remote.", + "items": { + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "remote", + "file", + "fetchedAt", + "operations", + "inbox", + "skipped", + "callsUsed" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteFailed", + "description": "The remote refused a request or answered in an unknown form.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteUnavailable": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteUnavailable", + "description": "The remote cannot be reached: its program is not installed or not running.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "destructive": false, + "idempotent": true + }, + "sync.inbox.adopt": { + "description": "Adopt a token that the remote created: first add it to the configuration at a path of your choice, then record that path here. The next push renames the remote token to the name the configuration generates, and sets the value of the configuration, so designs that use the token keep it. Writes the state file only.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "item": { + "description": "The id of the inbox item: the token name without its leading --.", + "minLength": 1, + "type": "string" + }, + "path": { + "description": "The token path of the configuration token that the item becomes, added to the configuration before this call, e.g. palette.brand.accent. It is the path in the description of each pushed token (cssforge: ).", + "minLength": 1, + "type": "string" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "item", + "path" + ], + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "callsUsed": { + "description": "The requests made to the remote by this call: always 0.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "decision": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "action": { + "const": "adopt", + "type": "string" + }, + "item": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "item", + "action", + "path" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "action": { + "const": "reject", + "type": "string" + }, + "item": { + "type": "string" + } + }, + "required": [ + "item", + "action" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "action": { + "const": "overwrite", + "type": "string" + }, + "item": { + "type": "string" + } + }, + "required": [ + "item", + "action" + ], + "type": "object" + } + ] + }, + "inbox": { + "description": "The items that still wait for a decision.", + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "localValue": { + "type": "string" + }, + "name": { + "type": "string" + }, + "note": { + "type": "string" + }, + "remoteValue": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "name", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens that have no place on the remote.", + "items": { + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "remote", + "decision", + "inbox", + "skipped", + "callsUsed" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidDecision": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidDecision", + "description": "The decision does not settle the item, or the adopted path does not fit.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "NotFetched": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "NotFetched", + "description": "The remote has not been read yet: run `fetch` first.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "UnknownItem": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "UnknownItem", + "description": "The inbox has no item with this id.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "destructive": false, + "idempotent": true + }, + "sync.inbox.list": { + "description": "List the inbox against the last fetch, with no request to the remote: the tokens the remote created, changed or deleted, each with the decisions that settle it. Settle a new token with `inbox adopt` (after adding it to the configuration) or `inbox reject`, and the others with `inbox overwrite`.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "callsUsed": { + "description": "The requests made to the remote by this call.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "fetchedAt": { + "description": "When the remote tokens were read, as an ISO 8601 time.", + "type": "string" + }, + "file": { + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "id", + "name" + ], + "type": "object" + }, + "inbox": { + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "localValue": { + "type": "string" + }, + "name": { + "type": "string" + }, + "note": { + "type": "string" + }, + "remoteValue": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "name", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "operations": { + "description": "The changes the next push sends, in order.", + "items": { + "description": "A change to send to the remote.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "create", + "type": "string" + }, + "type": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "op", + "name", + "type", + "value", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "update", + "type": "string" + }, + "type": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "op", + "name", + "type", + "value", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "from": { + "type": "string" + }, + "op": { + "const": "rename", + "type": "string" + }, + "to": { + "type": "string" + } + }, + "required": [ + "op", + "from", + "to" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "op": { + "const": "delete", + "type": "string" + } + }, + "required": [ + "op", + "name" + ], + "type": "object" + } + ] + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens that have no place on the remote.", + "items": { + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "remote", + "file", + "fetchedAt", + "operations", + "inbox", + "skipped", + "callsUsed" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "NotFetched": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "NotFetched", + "description": "The remote has not been read yet: run `fetch` first.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "readOnly": true + }, + "sync.inbox.overwrite": { + "description": "Settle a token that the remote changed, deleted, or created with the name of a configuration token: the next push writes the value of the configuration. To keep the value of the remote instead, change the configuration to that value; the item then goes away at the next fetch. Writes the state file only.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "item": { + "description": "The id of the inbox item: the token name without its leading --.", + "minLength": 1, + "type": "string" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "item" + ], + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "callsUsed": { + "description": "The requests made to the remote by this call: always 0.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "decision": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "action": { + "const": "adopt", + "type": "string" + }, + "item": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "item", + "action", + "path" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "action": { + "const": "reject", + "type": "string" + }, + "item": { + "type": "string" + } + }, + "required": [ + "item", + "action" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "action": { + "const": "overwrite", + "type": "string" + }, + "item": { + "type": "string" + } + }, + "required": [ + "item", + "action" + ], + "type": "object" + } + ] + }, + "inbox": { + "description": "The items that still wait for a decision.", + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "localValue": { + "type": "string" + }, + "name": { + "type": "string" + }, + "note": { + "type": "string" + }, + "remoteValue": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "name", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens that have no place on the remote.", + "items": { + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "remote", + "decision", + "inbox", + "skipped", + "callsUsed" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidDecision": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidDecision", + "description": "The decision does not settle the item, or the adopted path does not fit.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "NotFetched": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "NotFetched", + "description": "The remote has not been read yet: run `fetch` first.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "UnknownItem": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "UnknownItem", + "description": "The inbox has no item with this id.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "destructive": false, + "idempotent": true + }, + "sync.inbox.reject": { + "description": "Reject a token that the remote created: the next push deletes it from the remote. Writes the state file only.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "item": { + "description": "The id of the inbox item: the token name without its leading --.", + "minLength": 1, + "type": "string" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "item" + ], + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "callsUsed": { + "description": "The requests made to the remote by this call: always 0.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "decision": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "action": { + "const": "adopt", + "type": "string" + }, + "item": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "item", + "action", + "path" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "action": { + "const": "reject", + "type": "string" + }, + "item": { + "type": "string" + } + }, + "required": [ + "item", + "action" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "action": { + "const": "overwrite", + "type": "string" + }, + "item": { + "type": "string" + } + }, + "required": [ + "item", + "action" + ], + "type": "object" + } + ] + }, + "inbox": { + "description": "The items that still wait for a decision.", + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "localValue": { + "type": "string" + }, + "name": { + "type": "string" + }, + "note": { + "type": "string" + }, + "remoteValue": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "name", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens that have no place on the remote.", + "items": { + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "remote", + "decision", + "inbox", + "skipped", + "callsUsed" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidDecision": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidDecision", + "description": "The decision does not settle the item, or the adopted path does not fit.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "NotFetched": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "NotFetched", + "description": "The remote has not been read yet: run `fetch` first.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "UnknownItem": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "UnknownItem", + "description": "The inbox has no item with this id.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "destructive": false, + "idempotent": true + }, + "sync.plan": { + "description": "Report the plan against the tokens of the last fetch, with no request to the remote: the changes the next push sends, the inbox, and the configuration tokens that have no place on the remote. Use it after a change of the configuration or a decision.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "callsUsed": { + "description": "The requests made to the remote by this call.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "fetchedAt": { + "description": "When the remote tokens were read, as an ISO 8601 time.", + "type": "string" + }, + "file": { + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "id", + "name" + ], + "type": "object" + }, + "inbox": { + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "localValue": { + "type": "string" + }, + "name": { + "type": "string" + }, + "note": { + "type": "string" + }, + "remoteValue": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "name", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "operations": { + "description": "The changes the next push sends, in order.", + "items": { + "description": "A change to send to the remote.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "create", + "type": "string" + }, + "type": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "op", + "name", + "type", + "value", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "update", + "type": "string" + }, + "type": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "op", + "name", + "type", + "value", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "from": { + "type": "string" + }, + "op": { + "const": "rename", + "type": "string" + }, + "to": { + "type": "string" + } + }, + "required": [ + "op", + "from", + "to" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "op": { + "const": "delete", + "type": "string" + } + }, + "required": [ + "op", + "name" + ], + "type": "object" + } + ] + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens that have no place on the remote.", + "items": { + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "remote", + "file", + "fetchedAt", + "operations", + "inbox", + "skipped", + "callsUsed" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "NotFetched": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "NotFetched", + "description": "The remote has not been read yet: run `fetch` first.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + } + }, + "readOnly": true + }, + "sync.push": { + "description": "Read the remote, then send the changes of the plan: create and update the tokens of the configuration, delete the ones removed from it, and carry out the decisions on inbox items. Items without a decision stay in the inbox, and their tokens are not changed. One request to read, up to two to write and one to read the stored values back; only the first when the plan is empty.", + "audience": [ + "cli", + "mcp", + "library" + ], + "input": { + "additionalProperties": false, + "properties": { + "config": { + "default": "./cssforge.config.ts", + "description": "The path of the configuration file.", + "minLength": 1, + "type": "string" + }, + "dry-run": { + "default": false, + "description": "Read the remote and report the plan, but send nothing.", + "type": "boolean" + }, + "remote": { + "default": "paper", + "description": "The name of the remote, as `remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, + "root": { + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + "minLength": 1, + "type": "string" + } + }, + "type": "object" + }, + "output": { + "additionalProperties": false, + "properties": { + "applied": { + "description": "What the remote did with each operation. Empty for a dry run.", + "items": { + "additionalProperties": false, + "properties": { + "message": { + "type": "string" + }, + "ok": { + "type": "boolean" + }, + "operation": { + "description": "A change to send to the remote.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "create", + "type": "string" + }, + "type": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "op", + "name", + "type", + "value", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "update", + "type": "string" + }, + "type": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "op", + "name", + "type", + "value", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "from": { + "type": "string" + }, + "op": { + "const": "rename", + "type": "string" + }, + "to": { + "type": "string" + } + }, + "required": [ + "op", + "from", + "to" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "op": { + "const": "delete", + "type": "string" + } + }, + "required": [ + "op", + "name" + ], + "type": "object" + } + ] + } + }, + "required": [ + "operation", + "ok" + ], + "type": "object" + }, + "type": "array" + }, + "callsUsed": { + "description": "The requests made to the remote by this call.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "fetchedAt": { + "description": "When the remote tokens were read, as an ISO 8601 time.", + "type": "string" + }, + "file": { + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "id", + "name" + ], + "type": "object" + }, + "inbox": { + "items": { + "additionalProperties": false, + "description": "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + "properties": { + "actions": { + "items": { + "enum": [ + "adopt", + "reject", + "overwrite" + ], + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "kind": { + "enum": [ + "new", + "edited", + "deleted", + "collision" + ], + "type": "string" + }, + "localValue": { + "type": "string" + }, + "name": { + "type": "string" + }, + "note": { + "type": "string" + }, + "remoteValue": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "kind", + "name", + "type", + "actions" + ], + "type": "object" + }, + "type": "array" + }, + "operations": { + "description": "The changes the next push sends, in order.", + "items": { + "description": "A change to send to the remote.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "create", + "type": "string" + }, + "type": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "op", + "name", + "type", + "value", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "op": { + "const": "update", + "type": "string" + }, + "type": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "op", + "name", + "type", + "value", + "description" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "from": { + "type": "string" + }, + "op": { + "const": "rename", + "type": "string" + }, + "to": { + "type": "string" + } + }, + "required": [ + "op", + "from", + "to" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "op": { + "const": "delete", + "type": "string" + } + }, + "required": [ + "op", + "name" + ], + "type": "object" + } + ] + }, + "type": "array" + }, + "remote": { + "type": "string" + }, + "skipped": { + "description": "Configuration tokens that have no place on the remote.", + "items": { + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "sourcePath", + "reason" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "remote", + "file", + "fetchedAt", + "operations", + "inbox", + "skipped", + "callsUsed", + "applied" + ], + "type": "object" + }, + "failures": { + "ConfigLoadFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "ConfigLoadFailed", + "description": "The configuration file could not be found or evaluated.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" } }, - "default": "build" + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidConfig": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidConfig", + "description": "CSS Forge rejects a value of the configuration.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "InvalidState": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidState", + "description": "The state file of the remote is not valid.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteFailed": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteFailed", + "description": "The remote refused a request or answered in an unknown form.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteNotConfigured": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteNotConfigured", + "description": "The remote has no state file: add it with `remote add`.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "RemoteUnavailable": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "RemoteUnavailable", + "description": "The remote cannot be reached: its program is not installed or not running.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" } - } - }, - "library": { - "bindings": [ - "typescript" - ], - "description": "Typed calls from code, through @hebilicious/cssforge/capabilities." + }, + "destructive": true, + "idempotent": true }, - "mcp": { - "bindings": [ - "mcp" - ], - "description": "The MCP server of `cssforge mcp`, for agents." - } - }, - "capabilities": { - "config.check": { - "description": "Load and validate a CSS Forge configuration, and give its warnings: values that generate, but likely not as intended. Writes no file.", + "sync.remote.add": { + "description": "Bind a file of a design tool to the configuration as a remote, so that the token sync commands read and write that file only. Checks that the remote can open the file (one request), and writes .cssforge/sync/.json. Binding the same file again keeps the sync state; binding another file starts the sync again.", "audience": [ "cli", "mcp", @@ -52,94 +2956,85 @@ "input": { "additionalProperties": false, "properties": { - "color-formats": { - "default": [], - "description": "Extra color formats generated beside oklch(), added to the formats that the configuration declares.", - "items": { - "enum": [ - "hex", - "rgb" - ], - "type": "string" - }, - "type": "array" + "file": { + "description": "The file of the remote that the tokens sync with: its id or its URL.", + "minLength": 1, + "type": "string" }, - "config": { - "default": "./cssforge.config.ts", - "description": "The path of the configuration file.", + "kind": { + "default": "paper", + "description": "The kind of remote, e.g. paper.", "minLength": 1, "type": "string" }, + "name": { + "default": "paper", + "description": "The name of the remote, as `remote add --name` gave it.", + "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", + "type": "string" + }, "root": { - "description": "The directory that the relative paths of the input resolve against. The default is the working directory of the tools.", + "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", "minLength": 1, "type": "string" } }, + "required": [ + "file" + ], "type": "object" }, "output": { "additionalProperties": false, "properties": { - "dependencies": { - "description": "The absolute paths of the configuration and the local modules it imports.", - "items": { - "type": "string" - }, - "type": "array" + "callsUsed": { + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" }, - "diagnostics": { - "items": { - "additionalProperties": false, - "description": "A warning about a value that generates, but likely not as intended.", - "properties": { - "code": { - "description": "A stable identifier of the warning.", - "enum": [ - "typography-static-scale", - "typography-below-legibility-floor", - "motion-long-duration", - "motion-ease-in" - ], - "type": "string" - }, - "message": { - "description": "What is wrong, and how to fix it.", - "type": "string" - }, - "path": { - "description": "The configuration path of the value.", - "type": "string" - }, - "severity": { - "const": "warning", - "type": "string" - } + "file": { + "additionalProperties": false, + "properties": { + "id": { + "type": "string" }, - "required": [ - "code", - "severity", - "path", - "message" - ], - "type": "object" + "name": { + "type": "string" + } }, - "type": "array" + "required": [ + "id", + "name" + ], + "type": "object" + }, + "kind": { + "type": "string" + }, + "remote": { + "type": "string" + }, + "state": { + "description": "The absolute path of the state file.", + "type": "string" } }, "required": [ - "diagnostics", - "dependencies" + "remote", + "kind", + "file", + "state", + "callsUsed" ], "type": "object" }, "failures": { - "ConfigLoadFailed": { + "RemoteFailed": { "additionalProperties": false, "properties": { "_tag": { - "const": "ConfigLoadFailed", - "description": "The configuration file could not be found or evaluated, or it has no default export object.", + "const": "RemoteFailed", + "description": "The remote refused a request or answered in an unknown form.", "type": "string" }, "message": { @@ -156,12 +3051,34 @@ ], "type": "object" }, - "InvalidConfig": { + "RemoteUnavailable": { "additionalProperties": false, "properties": { "_tag": { - "const": "InvalidConfig", - "description": "The configuration loaded, but CSS Forge rejects a value in it.", + "const": "RemoteUnavailable", + "description": "The remote cannot be reached: its program is not installed or not running.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, + "UnknownKind": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "UnknownKind", + "description": "The kind of remote is not known.", "type": "string" }, "message": { @@ -179,7 +3096,8 @@ "type": "object" } }, - "readOnly": true + "destructive": true, + "idempotent": true }, "tokens.build": { "description": "Generate the outputs of a CSS Forge configuration and write them to files: CSS custom properties, JSON, TypeScript and Style Dictionary tokens. Every output is generated before the first file is written, so an invalid configuration leaves the previous files in place. The result lists the files written and the warnings of the configuration.", @@ -412,7 +3330,9 @@ ], "type": "object" } - } + }, + "destructive": true, + "idempotent": true }, "tokens.generate": { "description": "Generate one output of a CSS Forge configuration and give it as text, with the warnings of the configuration. Writes no file.", diff --git a/packages/cssforge/jsr.json b/packages/cssforge/jsr.json index 96c4113..8814822 100644 --- a/packages/cssforge/jsr.json +++ b/packages/cssforge/jsr.json @@ -9,7 +9,7 @@ "./capabilities": "./src/capabilities.ts" }, "imports": { - "@acid-cat/core-ts": "npm:@acid-cat/core-ts@0.13.0", + "@acid-cat/core-ts": "npm:@acid-cat/core-ts@0.15.0", "chokidar": "npm:chokidar@4.0.3", "colorjs.io": "npm:colorjs.io@0.5.2", "utopia-core": "npm:utopia-core@1.6.0", diff --git a/packages/cssforge/package.json b/packages/cssforge/package.json index e42bdd3..e6ef295 100644 --- a/packages/cssforge/package.json +++ b/packages/cssforge/package.json @@ -46,14 +46,14 @@ "cssforge.acidcat.json" ], "dependencies": { - "@acid-cat/core-ts": "0.13.0", + "@acid-cat/core-ts": "0.15.0", "chokidar": "4.0.3", "colorjs.io": "0.5.2", "utopia-core": "1.6.0", "zod": "4.6.7" }, "devDependencies": { - "@acid-cat/cli": "0.13.0", + "@acid-cat/cli": "0.15.0", "@biomejs/biome": "2.4.2", "@types/node": "24.3.0", "mdbox": "0.1.1", diff --git a/packages/cssforge/src/capabilities.ts b/packages/cssforge/src/capabilities.ts index ffcfd79..3223de2 100644 --- a/packages/cssforge/src/capabilities.ts +++ b/packages/cssforge/src/capabilities.ts @@ -65,6 +65,18 @@ import { } from "./forge.ts"; import { type ColorFormat, diagnosticCodes } from "./lib.ts"; import { supportedColorFormats } from "./modules/colors.ts"; +import { + syncCapabilities, + syncFetch, + syncInboxAdopt, + syncInboxList, + syncInboxOverwrite, + syncInboxReject, + syncPlan, + syncPush, + syncRemoteAdd, +} from "./sync/capabilities.ts"; +import type { RemoteAdapter } from "./sync/remote.ts"; /** * `createSession` opens a session on {@link cssforge}, for typed calls from @@ -73,6 +85,24 @@ import { supportedColorFormats } from "./modules/colors.ts"; * cancellation or a defect. */ export { CallFailureError, createSession } from "@acid-cat/core-ts"; +export type { ListedToken, TokenKind } from "./generator.ts"; +export * from "./sync/capabilities.ts"; +export { type PaperOptions, paperAdapter } from "./sync/paper.ts"; +export type { + BaseEntry, + Decision, + InboxItem, + Operation, + RemoteToken, +} from "./sync/plan.ts"; +export type { + ApplyResult, + RemoteAdapter, + RemoteFile, + RemoteSession, + TokenMapping, +} from "./sync/remote.ts"; +export { RemoteError } from "./sync/remote.ts"; /** The JSON Schema of a schema of {@link cssforge}, for the catalog and the bindings. */ export const toJsonSchema: ToJsonSchema = (schema) => { @@ -86,6 +116,8 @@ export const toJsonSchema: ToJsonSchema = (schema) => { export interface ForgeContext { /** The directory that relative paths resolve against, when an input gives no `root`. */ cwd: string; + /** The remotes that token sync knows. The default is the Paper remote. */ + remotes?: readonly RemoteAdapter[]; } // --- Schemas ------------------------------------------------------------------------------- @@ -354,6 +386,8 @@ export const tokensBuild: Capability< description: "Generate the outputs of a CSS Forge configuration and write them to files: CSS custom properties, JSON, TypeScript and Style Dictionary tokens. Every output is generated before the first file is written, so an invalid configuration leaves the previous files in place. The result lists the files written and the warnings of the configuration.", audience: everyone, + destructive: true, + idempotent: true, input: buildInput, output: buildReport, failures: buildFailures, @@ -450,7 +484,7 @@ export const tokensBuilt: EventDefinition< export const cssforge: App = defineApp({ title: "CSS Forge", description: - "Generate CSS custom properties, JSON, TypeScript and Style Dictionary tokens from a CSS Forge configuration.", + "Generate CSS custom properties, JSON, TypeScript and Style Dictionary tokens from a CSS Forge configuration, and keep the tokens of a design tool in sync with it.", targets: { cli: { bindings: ["cli"], @@ -462,6 +496,14 @@ export const cssforge: App = defineApp({ generate: cliAlias(tokensGenerate), check: cliAlias(configCheck), "--watch": cliAlias(tokensBuilt), + "remote add": cliAlias(syncRemoteAdd), + fetch: cliAlias(syncFetch), + plan: cliAlias(syncPlan), + push: cliAlias(syncPush), + inbox: cliAlias(syncInboxList), + "inbox adopt": cliAlias(syncInboxAdopt), + "inbox reject": cliAlias(syncInboxReject), + "inbox overwrite": cliAlias(syncInboxOverwrite), }, }, }, @@ -474,6 +516,6 @@ export const cssforge: App = defineApp({ description: "Typed calls from code, through @hebilicious/cssforge/capabilities.", }, }, - capabilities: [tokensBuild, tokensGenerate, configCheck], + capabilities: [tokensBuild, tokensGenerate, configCheck, ...syncCapabilities], events: [tokensBuilt], }); diff --git a/packages/cssforge/src/forge.ts b/packages/cssforge/src/forge.ts index 23f626b..fb01fbe 100644 --- a/packages/cssforge/src/forge.ts +++ b/packages/cssforge/src/forge.ts @@ -19,6 +19,8 @@ import { generateStyleDictionaryJSON, generateTS, getDiagnostics, + type ListedToken, + listTokens, } from "./generator.ts"; import type { ColorFormat, Diagnostic, GenerateOptions } from "./lib.ts"; import { type LoadedConfig, loadConfig } from "./loader.ts"; @@ -182,6 +184,12 @@ export async function generateOutput( })); } +/** Lists the tokens of the configuration at `configPath`, for token sync. Writes nothing. */ +export async function listConfigTokens(configPath: string): Promise { + const { config, dependencies } = await loadForgeConfig(configPath); + return generating(configPath, dependencies, () => listTokens(config)); +} + /** * Writes a file, creating its parent directory first. The parent comes from the * platform-aware `dirname` of `node:path`, so `C:\project\.cssforge\output.css` diff --git a/packages/cssforge/src/generator.ts b/packages/cssforge/src/generator.ts index 94a0677..5989a95 100644 --- a/packages/cssforge/src/generator.ts +++ b/packages/cssforge/src/generator.ts @@ -508,6 +508,55 @@ export function generateStyleDictionaryJSON( return JSON.stringify(styleDictionaryValues, null, 2); } +/** The kind of a token, as the Style Dictionary output and token sync infer it. */ +export type TokenKind = StyleDictionaryTokenType; + +/** One generated custom property, as token sync reads it. */ +export interface ListedToken { + /** The custom property name, e.g. `--color-red-100`. */ + name: string; + /** The CSS value as generated. It may contain `var(...)` references. */ + value: string; + /** The value with every reference to another token of the configuration substituted. */ + resolvedValue: string; + /** The kind inferred from the path and the resolved value. */ + kind: TokenKind; + /** The configuration path of the token. */ + sourcePath: string; + /** The CSS scope it is emitted into: `:root`, or the wrapper chain of a selector or an at-rule. */ + scope: string; +} + +/** + * Lists every custom property of a configuration in output order, with its + * resolved value and inferred kind, for tools that copy tokens elsewhere. + * @example + * ```ts + * const [token] = listTokens({ spacing: { size: { value: { 1: "4px" } } } }); + * // token.name: "--spacing-size-1", token.kind: "spacing" + * ``` + */ +export function listTokens( + config: Partial, + options: GenerateOptions = {}, +): ListedToken[] { + const resolveMap = collectResolveMap(config, options); + const tokensByCssVariable = new Map( + [...resolveMap.values()].map((token) => [token.key, token]), + ); + return [...resolveMap.values()].map((token) => { + const resolvedValue = resolveTokenValue(token, tokensByCssVariable); + return { + name: token.key, + value: token.value, + resolvedValue, + kind: inferValueKind(token.sourcePath, resolvedValue, token.type), + sourcePath: token.sourcePath, + scope: getTokenScope(token), + }; + }); +} + /** * Generates a JSON string from the CSSForge configuration. * This can be used to create a JSON file with all the design tokens. diff --git a/packages/cssforge/src/sync/capabilities.ts b/packages/cssforge/src/sync/capabilities.ts new file mode 100644 index 0000000..b146e29 --- /dev/null +++ b/packages/cssforge/src/sync/capabilities.ts @@ -0,0 +1,949 @@ +/** + * The token sync capabilities: they keep the tokens of a design tool (a remote) in sync + * with a CSS Forge configuration. The configuration is the source of truth. What the + * remote changes waits in an inbox until a decision settles it. + * + * @module + */ + +import { resolve } from "node:path"; +import type { Capability, Result } from "@acid-cat/core-ts"; +import { capabilitiesFor, fail, ok } from "@acid-cat/core-ts"; +import { z } from "zod"; +import type { ForgeContext } from "../capabilities.ts"; +import { defaultConfigPath, ForgeError, listConfigTokens } from "../forge.ts"; +import type { ListedToken } from "../generator.ts"; +import { paperAdapter } from "./paper.ts"; +import { + type Decision, + type DesiredToken, + type InboxItem, + type Operation, + planSync, + type RemoteToken, + type SyncPlan, +} from "./plan.ts"; +import { + type ApplyResult, + type RemoteAdapter, + RemoteError, + type RemoteSession, +} from "./remote.ts"; +import { + REMOTE_NAME, + readState, + StateError, + type SyncState, + statePath, + writeState, +} from "./state.ts"; + +// --- Types --------------------------------------------------------------------------------- + +/** The members of every sync input, with the defaults filled in. */ +export interface SyncInput { + config: string; + root?: string; + remote: string; +} + +/** The input of `sync.remote.add`. */ +export interface RemoteAddInput { + root?: string; + name: string; + kind: string; + file: string; +} + +/** The input of `sync.push`. */ +export interface PushInput extends SyncInput { + "dry-run": boolean; +} + +/** The input of `sync.inbox.adopt`. */ +export interface AdoptInput extends SyncInput { + item: string; + path: string; +} + +/** The input of `sync.inbox.reject` and `sync.inbox.overwrite`. */ +export interface ItemInput extends SyncInput { + item: string; +} + +/** A configuration token that has no place on the remote. */ +export interface SkippedToken { + name: string; + sourcePath: string; + reason: string; +} + +/** The plan of a sync, as the capabilities report it. */ +export interface SyncReport { + remote: string; + file: { id: string; name: string }; + /** When the remote tokens were read. */ + fetchedAt: string; + /** The changes the next push sends. */ + operations: Operation[]; + inbox: InboxItem[]; + skipped: SkippedToken[]; + /** The requests made to the remote by this call. */ + callsUsed: number; +} + +/** The report of `sync.push`. */ +export interface PushReport extends SyncReport { + /** What the remote did with each operation. Empty for a dry run. */ + applied: ApplyResult[]; +} + +/** The report of `sync.remote.add`. */ +export interface RemoteAddReport { + remote: string; + kind: string; + file: { id: string; name: string }; + /** The absolute path of the state file. */ + state: string; + callsUsed: number; +} + +/** The report of a decision. */ +export interface DecisionReport { + remote: string; + decision: Decision; + /** The items that still wait for a decision. */ + inbox: InboxItem[]; + skipped: SkippedToken[]; + /** The requests made to the remote by this call: always 0. */ + callsUsed: number; +} + +/** A failure of a sync capability. */ +export interface SyncFailure { + _tag: Tag; + message: string; + /** The file that the failure concerns. */ + path?: string; +} + +type ReadTags = + | "ConfigLoadFailed" + | "InvalidConfig" + | "RemoteNotConfigured" + | "InvalidState"; +type RemoteTags = "RemoteUnavailable" | "RemoteFailed"; + +/** The failures of the capabilities that read the configuration and the state. */ +export type SyncReadFailures = { [Tag in ReadTags]: SyncFailure }; +/** The failures of the capabilities that also call the remote. */ +export type SyncRemoteFailures = SyncReadFailures & { + [Tag in RemoteTags]: SyncFailure; +}; +/** The failures of `sync.plan` and `sync.inbox.list`. */ +export type SyncPlanFailures = SyncReadFailures & { + NotFetched: SyncFailure<"NotFetched">; +}; +/** The failures of `sync.remote.add`. */ +export type RemoteAddFailures = { [Tag in RemoteTags | "UnknownKind"]: SyncFailure }; +/** The failures of a decision. */ +export type DecisionFailures = SyncPlanFailures & { + UnknownItem: SyncFailure<"UnknownItem">; + InvalidDecision: SyncFailure<"InvalidDecision">; +}; + +// --- Schemas ------------------------------------------------------------------------------- + +const rootSchema = z + .string() + .min(1) + .optional() + .describe( + "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", + ); + +const remoteSchema = z + .string() + .regex(REMOTE_NAME, "A remote name is lowercase words joined by hyphens, e.g. paper.") + .default("paper") + .describe("The name of the remote, as `remote add --name` gave it."); + +const syncShape = { + config: z + .string() + .min(1) + .default(defaultConfigPath) + .describe("The path of the configuration file."), + root: rootSchema, + remote: remoteSchema, +}; + +const itemSchema = z + .string() + .min(1) + .describe("The id of the inbox item: the token name without its leading --."); + +const syncInput = z.strictObject(syncShape); +const pushInput = z.strictObject({ + ...syncShape, + "dry-run": z + .boolean() + .default(false) + .describe("Read the remote and report the plan, but send nothing."), +}); +const adoptInput = z.strictObject({ + ...syncShape, + item: itemSchema, + path: z + .string() + .min(1) + .describe( + "The token path of the configuration token that the item becomes, added to the configuration before this call, e.g. palette.brand.accent. It is the path in the description of each pushed token (cssforge: ).", + ), +}); +const itemInput = z.strictObject({ ...syncShape, item: itemSchema }); +const remoteAddInput = z.strictObject({ + root: rootSchema, + name: remoteSchema, + kind: z.string().min(1).default("paper").describe("The kind of remote, e.g. paper."), + file: z + .string() + .min(1) + .describe("The file of the remote that the tokens sync with: its id or its URL."), +}); + +const fileSchema = z.strictObject({ id: z.string(), name: z.string() }); + +const operationSchema = z + .discriminatedUnion("op", [ + z.strictObject({ + op: z.literal("create"), + name: z.string(), + type: z.string(), + value: z.string(), + description: z.string(), + }), + z.strictObject({ + op: z.literal("update"), + name: z.string(), + type: z.string(), + value: z.string(), + description: z.string(), + }), + z.strictObject({ op: z.literal("rename"), from: z.string(), to: z.string() }), + z.strictObject({ op: z.literal("delete"), name: z.string() }), + ]) + .describe("A change to send to the remote."); + +const decisionSchema = z.discriminatedUnion("action", [ + z.strictObject({ item: z.string(), action: z.literal("adopt"), path: z.string() }), + z.strictObject({ item: z.string(), action: z.literal("reject") }), + z.strictObject({ item: z.string(), action: z.literal("overwrite") }), +]); + +const inboxItemSchema = z + .strictObject({ + id: z.string(), + kind: z.enum(["new", "edited", "deleted", "collision"]), + name: z.string(), + type: z.string(), + remoteValue: z.string().optional(), + localValue: z.string().optional(), + actions: z.array(z.enum(["adopt", "reject", "overwrite"])), + note: z.string().optional(), + }) + .describe( + "A change of the remote that waits for a decision. new: adopt or reject. edited, deleted and collision: overwrite with the value of the configuration.", + ); + +const reportShape = { + remote: z.string(), + file: fileSchema, + fetchedAt: z + .string() + .describe("When the remote tokens were read, as an ISO 8601 time."), + operations: z + .array(operationSchema) + .describe("The changes the next push sends, in order."), + inbox: z.array(inboxItemSchema), + skipped: z + .array( + z.strictObject({ name: z.string(), sourcePath: z.string(), reason: z.string() }), + ) + .describe("Configuration tokens that have no place on the remote."), + callsUsed: z.number().int().describe("The requests made to the remote by this call."), +}; + +const syncReport = z.strictObject(reportShape); +const pushReport = z.strictObject({ + ...reportShape, + applied: z + .array( + z.strictObject({ + operation: operationSchema, + ok: z.boolean(), + message: z.string().optional(), + }), + ) + .describe("What the remote did with each operation. Empty for a dry run."), +}); +const remoteAddReport = z.strictObject({ + remote: z.string(), + kind: z.string(), + file: fileSchema, + state: z.string().describe("The absolute path of the state file."), + callsUsed: z.number().int(), +}); +const decisionReport = z.strictObject({ + remote: z.string(), + decision: decisionSchema, + inbox: z.array(inboxItemSchema).describe("The items that still wait for a decision."), + skipped: reportShape.skipped, + callsUsed: z + .number() + .int() + .describe("The requests made to the remote by this call: always 0."), +}); + +const failureSchema = (tag: Tag, description: string) => + z.strictObject({ + _tag: z.literal(tag).describe(description), + message: z.string(), + path: z.string().optional().describe("The file that the failure concerns."), + }); + +const readFailures = { + ConfigLoadFailed: failureSchema( + "ConfigLoadFailed", + "The configuration file could not be found or evaluated.", + ), + InvalidConfig: failureSchema( + "InvalidConfig", + "CSS Forge rejects a value of the configuration.", + ), + RemoteNotConfigured: failureSchema( + "RemoteNotConfigured", + "The remote has no state file: add it with `remote add`.", + ), + InvalidState: failureSchema( + "InvalidState", + "The state file of the remote is not valid.", + ), +}; +const remoteFailures = { + RemoteUnavailable: failureSchema( + "RemoteUnavailable", + "The remote cannot be reached: its program is not installed or not running.", + ), + RemoteFailed: failureSchema( + "RemoteFailed", + "The remote refused a request or answered in an unknown form.", + ), +}; +const notFetched = { + NotFetched: failureSchema( + "NotFetched", + "The remote has not been read yet: run `fetch` first.", + ), +}; +const decisionFailures = { + ...readFailures, + ...notFetched, + UnknownItem: failureSchema("UnknownItem", "The inbox has no item with this id."), + InvalidDecision: failureSchema( + "InvalidDecision", + "The decision does not settle the item, or the adopted path does not fit.", + ), +}; + +// --- Operations ---------------------------------------------------------------------------- + +/** The adapters a context gives, or the Paper adapter. */ +const adaptersOf = (context: ForgeContext): readonly RemoteAdapter[] => + context.remotes ?? [paperAdapter()]; + +const rootOf = (context: ForgeContext, input: { root?: string }) => + resolve(context.cwd, input.root ?? "."); + +/** A failure of a sync operation, before it becomes a typed failure. */ +class SyncError extends Error { + readonly tag: string; + + constructor(tag: string, message: string) { + super(message); + this.name = "SyncError"; + this.tag = tag; + } +} + +/** Runs an operation, and gives every known error as a failure. Other errors are defects. */ +async function attempt( + operation: () => Promise, +): Promise> { + try { + return ok(await operation()); + } catch (error) { + if ( + error instanceof ForgeError || + error instanceof StateError || + error instanceof RemoteError || + error instanceof SyncError + ) { + const path = + "path" in error && typeof error.path === "string" ? error.path : undefined; + const failure = { + _tag: error.tag, + message: error.message, + ...(path === undefined ? {} : { path }), + }; + // The tag is only known at run time. Each capability declares every tag its + // operation can throw in its failures schema, and the session validates the + // failure against that schema. + return fail(failure as unknown as Failure); + } + throw error; + } +} + +const adapterOf = (context: ForgeContext, kind: string): RemoteAdapter => { + const adapter = adaptersOf(context).find((candidate) => candidate.kind === kind); + if (!adapter) { + const kinds = adaptersOf(context).map((candidate) => candidate.kind); + throw new SyncError( + "UnknownKind", + `There is no remote kind "${kind}". Known kinds: ${kinds.join(", ")}.`, + ); + } + return adapter; +}; + +const ALIAS = /^var\((--[a-zA-Z0-9_-]+)\)$/; + +/** The configuration tokens that go to the remote, and the ones that have no place there. */ +function desiredTokens(tokens: readonly ListedToken[], adapter: RemoteAdapter) { + const desired: DesiredToken[] = []; + const skipped: SkippedToken[] = []; + for (const token of tokens) { + const mapping = adapter.map(token); + if ("skip" in mapping) { + skipped.push({ + name: token.name, + sourcePath: token.sourcePath, + reason: mapping.skip, + }); + continue; + } + const alias = ALIAS.exec(token.value.trim())?.[1]; + desired.push({ + name: token.name, + type: mapping.type, + value: mapping.value, + ...(alias === undefined ? {} : { alias }), + sourcePath: token.sourcePath, + description: `cssforge: ${token.sourcePath}`, + }); + } + return { desired, skipped }; +} + +interface Loaded { + root: string; + state: SyncState; + adapter: RemoteAdapter; + desired: DesiredToken[]; + skipped: SkippedToken[]; +} + +async function load(context: ForgeContext, input: SyncInput): Promise { + const root = rootOf(context, input); + const state = await readState(root, input.remote); + const adapter = adaptersOf(context).find((candidate) => candidate.kind === state.kind); + if (!adapter) { + throw new StateError( + "InvalidState", + `The state file names the remote kind "${state.kind}", which this version of cssforge does not know.`, + statePath(root, input.remote), + ); + } + const tokens = await listConfigTokens(resolve(root, input.config)); + return { root, state, adapter, ...desiredTokens(tokens, adapter) }; +} + +const fetchedOf = (state: SyncState, remote: string) => { + if (state.fetched === null) { + throw new SyncError( + "NotFetched", + `The remote "${remote}" has not been read yet. Run \`cssforge fetch --remote ${remote}\`.`, + ); + } + return state.fetched; +}; + +const planOf = (loaded: Loaded, remote: readonly RemoteToken[]): SyncPlan => + planSync({ + desired: loaded.desired, + skipped: new Set(loaded.skipped.map((token) => token.name)), + remote, + base: loaded.state.base, + decisions: loaded.state.decisions, + }); + +const reportOf = ( + input: SyncInput, + loaded: Loaded, + plan: SyncPlan, + fetchedAt: string, + callsUsed: number, +): SyncReport => ({ + remote: input.remote, + file: loaded.state.file, + fetchedAt, + operations: plan.operations.map((planned) => planned.operation), + inbox: plan.inbox, + skipped: loaded.skipped, + callsUsed, +}); + +/** Opens a session on the remote, runs `use`, and closes the session. */ +async function withSession( + adapter: RemoteAdapter, + signal: AbortSignal, + use: (session: RemoteSession) => Promise, +): Promise { + const session = await adapter.open(signal); + try { + return await use(session); + } finally { + session.close(); + } +} + +/** Reads the remote and records the fetch in the state. */ +async function fetchRemote(loaded: Loaded, session: RemoteSession, remote: string) { + const tokens = await session.read(loaded.state.file.id); + const fetched = { at: new Date().toISOString(), tokens }; + loaded.state = { ...loaded.state, fetched }; + await writeState(loaded.root, remote, loaded.state); + return fetched; +} + +/** The plan against the last fetch, with no request to the remote. */ +const planFromFetch = (input: SyncInput, context: ForgeContext) => + attempt(async () => { + const loaded = await load(context, input); + const fetched = fetchedOf(loaded.state, input.remote); + return reportOf(input, loaded, planOf(loaded, fetched.tokens), fetched.at, 0); + }); + +// --- Capabilities ---------------------------------------------------------------------------- + +const capability = capabilitiesFor(); +const everyone = ["cli", "mcp", "library"]; + +/** `cssforge remote add`: bind a remote file to the configuration. */ +export const syncRemoteAdd: Capability< + ForgeContext, + RemoteAddInput, + RemoteAddReport, + RemoteAddFailures, + never, + "sync.remote.add", + Partial +> = capability({ + id: "sync.remote.add", + description: + "Bind a file of a design tool to the configuration as a remote, so that the token sync commands read and write that file only. Checks that the remote can open the file (one request), and writes .cssforge/sync/.json. Binding the same file again keeps the sync state; binding another file starts the sync again.", + audience: everyone, + destructive: true, + idempotent: true, + input: remoteAddInput, + output: remoteAddReport, + failures: { + ...remoteFailures, + UnknownKind: failureSchema("UnknownKind", "The kind of remote is not known."), + }, + run: (input, { context, signal }) => + attempt(async () => { + const root = rootOf(context, input); + const adapter = adapterOf(context, input.kind); + return withSession(adapter, signal, async (session) => { + const file = await session.describe(input.file); + const previous = await readState(root, input.name).catch(() => undefined); + const kept = + previous?.kind === input.kind && previous.file.id === file.id + ? previous + : undefined; + const state: SyncState = kept + ? { ...kept, file } + : { + version: 1, + kind: input.kind, + file, + base: [], + fetched: null, + decisions: [], + }; + const path = await writeState(root, input.name, state); + return { + remote: input.name, + kind: input.kind, + file, + state: path, + callsUsed: session.calls, + }; + }); + }), +}); + +/** `cssforge fetch`: read the remote and report the plan. */ +export const syncFetch: Capability< + ForgeContext, + SyncInput, + SyncReport, + SyncRemoteFailures, + never, + "sync.fetch", + Partial +> = capability({ + id: "sync.fetch", + description: + "Read the tokens of the remote (one request), record them in the state file, and report the plan: the changes the next push sends, the inbox of changes the remote made, and the configuration tokens that have no place on the remote. Sends nothing to the remote.", + audience: everyone, + destructive: false, + idempotent: true, + input: syncInput, + output: syncReport, + failures: { ...readFailures, ...remoteFailures }, + run: (input, { context, signal }) => + attempt(async () => { + const loaded = await load(context, input); + return withSession(loaded.adapter, signal, async (session) => { + const fetched = await fetchRemote(loaded, session, input.remote); + return reportOf( + input, + loaded, + planOf(loaded, fetched.tokens), + fetched.at, + session.calls, + ); + }); + }), +}); + +/** `cssforge plan`: the plan against the last fetch, with no request. */ +export const syncPlan: Capability< + ForgeContext, + SyncInput, + SyncReport, + SyncPlanFailures, + never, + "sync.plan", + Partial +> = capability({ + id: "sync.plan", + description: + "Report the plan against the tokens of the last fetch, with no request to the remote: the changes the next push sends, the inbox, and the configuration tokens that have no place on the remote. Use it after a change of the configuration or a decision.", + audience: everyone, + readOnly: true, + input: syncInput, + output: syncReport, + failures: { ...readFailures, ...notFetched }, + run: (input, { context }) => planFromFetch(input, context), +}); + +/** `cssforge push`: read the remote, then send the plan. */ +export const syncPush: Capability< + ForgeContext, + PushInput, + PushReport, + SyncRemoteFailures, + never, + "sync.push", + Partial +> = capability({ + id: "sync.push", + description: + "Read the remote, then send the changes of the plan: create and update the tokens of the configuration, delete the ones removed from it, and carry out the decisions on inbox items. Items without a decision stay in the inbox, and their tokens are not changed. One request to read, up to two to write and one to read the stored values back; only the first when the plan is empty.", + audience: everyone, + destructive: true, + idempotent: true, + input: pushInput, + output: pushReport, + failures: { ...readFailures, ...remoteFailures }, + run: (input, { context, signal }) => + attempt(async () => { + const loaded = await load(context, input); + return withSession(loaded.adapter, signal, async (session) => { + const fetched = await fetchRemote(loaded, session, input.remote); + const plan = planOf(loaded, fetched.tokens); + const operations = plan.operations.map((planned) => planned.operation); + const applied = + input["dry-run"] || operations.length === 0 + ? [] + : await session.apply(loaded.state.file.id, operations); + if (!input["dry-run"] && applied.length === 0) { + const next = settle(loaded.state, plan, applied, fetched.tokens); + await writeState(loaded.root, input.remote, next); + } + if (!input["dry-run"] && applied.length > 0) { + // Record what the remote accepted before anything else can fail. + const accepted = settle(loaded.state, plan, applied, null); + await writeState(loaded.root, input.remote, accepted); + // Then read the tokens back, so that the base records each value as the remote + // stored it. Without this, a change made on the remote before the next fetch + // would read as the remote's own form of the value. + const stored = await session.read(loaded.state.file.id); + const next = settle(loaded.state, plan, applied, stored); + await writeState(loaded.root, input.remote, next); + } + const report = reportOf(input, loaded, plan, fetched.at, session.calls); + return { + ...report, + operations: input["dry-run"] ? report.operations : refused(operations, applied), + applied, + }; + }); + }), +}); + +/** The operations that the remote refused, which the next push sends again. */ +const refused = (operations: readonly Operation[], applied: readonly ApplyResult[]) => + operations.filter((_, index) => applied[index]?.ok !== true); + +/** + * The state after a push. `stored` is the remote read back after the push, or `null` when it + * is not read yet: the stored values stay unknown, and the fetch is cleared because it is + * older than the push. + */ +function settle( + state: SyncState, + plan: SyncPlan, + applied: readonly ApplyResult[], + stored: readonly RemoteToken[] | null, +): SyncState { + const previousByName = new Map(state.base.map((entry) => [entry.name, entry])); + const base = new Map(plan.carried.map((entry) => [entry.name, entry])); + const decisions = [...plan.pending]; + const decisionByItem = new Map( + state.decisions.map((decision) => [decision.item, decision]), + ); + + plan.operations.forEach((planned, index) => { + if (applied[index]?.ok === true) { + if (planned.replaces !== undefined) base.delete(planned.replaces); + if (planned.base) base.set(planned.base.name, planned.base); + return; + } + const { operation } = planned; + const name = operation.op === "rename" ? operation.from : operation.name; + const kept = previousByName.get(name); + if (kept) base.set(kept.name, kept); + const decision = + planned.settles === undefined ? undefined : decisionByItem.get(planned.settles); + if (decision && !decisions.includes(decision)) decisions.push(decision); + }); + + if (stored === null) { + return { ...state, base: [...base.values()], fetched: null, decisions }; + } + const storedByName = new Map(stored.map((token) => [token.name, token.value])); + const recorded = [...base.values()].map((entry) => + entry.stored === null + ? { ...entry, stored: storedByName.get(entry.name) ?? null } + : entry, + ); + return { + ...state, + base: recorded, + fetched: { at: new Date().toISOString(), tokens: [...stored] }, + decisions, + }; +} + +/** `cssforge inbox`: the items that wait for a decision. */ +export const syncInboxList: Capability< + ForgeContext, + SyncInput, + SyncReport, + SyncPlanFailures, + never, + "sync.inbox.list", + Partial +> = capability({ + id: "sync.inbox.list", + description: + "List the inbox against the last fetch, with no request to the remote: the tokens the remote created, changed or deleted, each with the decisions that settle it. Settle a new token with `inbox adopt` (after adding it to the configuration) or `inbox reject`, and the others with `inbox overwrite`.", + audience: everyone, + readOnly: true, + input: syncInput, + output: syncReport, + failures: { ...readFailures, ...notFetched }, + run: (input, { context }) => planFromFetch(input, context), +}); + +/** Records a decision on an item of the inbox of the last fetch. */ +async function decide( + context: ForgeContext, + input: SyncInput & { item: string }, + decision: Decision, + check: (item: InboxItem, loaded: Loaded) => void, +): Promise { + const loaded = await load(context, input); + const fetched = fetchedOf(loaded.state, input.remote); + const plan = planOf(loaded, fetched.tokens); + const item = plan.inbox.find((candidate) => candidate.id === input.item); + if (!item) { + const ids = plan.inbox.map((candidate) => candidate.id); + throw new SyncError( + "UnknownItem", + `The inbox has no item "${input.item}".${ids.length > 0 ? ` Items: ${ids.join(", ")}.` : " The inbox is empty."}`, + ); + } + if (!item.actions.includes(decision.action)) { + throw new SyncError( + "InvalidDecision", + `The ${item.kind} item "${item.id}" is settled with ${item.actions.join(" or ")}, not ${decision.action}.`, + ); + } + check(item, loaded); + const decisions = [ + ...loaded.state.decisions.filter((entry) => entry.item !== item.id), + decision, + ]; + loaded.state = { ...loaded.state, decisions }; + await writeState(loaded.root, input.remote, loaded.state); + const next = planOf(loaded, fetched.tokens); + return { + remote: input.remote, + decision, + inbox: next.inbox, + skipped: loaded.skipped, + callsUsed: 0, + }; +} + +/** `cssforge inbox adopt`: make a new remote token a token of the configuration. */ +export const syncInboxAdopt: Capability< + ForgeContext, + AdoptInput, + DecisionReport, + DecisionFailures, + never, + "sync.inbox.adopt", + Partial +> = capability({ + id: "sync.inbox.adopt", + description: + "Adopt a token that the remote created: first add it to the configuration at a path of your choice, then record that path here. The next push renames the remote token to the name the configuration generates, and sets the value of the configuration, so designs that use the token keep it. Writes the state file only.", + audience: everyone, + destructive: false, + idempotent: true, + input: adoptInput, + output: decisionReport, + failures: decisionFailures, + run: (input, { context }) => + attempt(() => + decide( + context, + input, + { item: input.item, action: "adopt", path: input.path }, + (item, loaded) => { + const target = loaded.desired.find((token) => token.sourcePath === input.path); + if (!target) { + const skipped = loaded.skipped.find( + (token) => token.sourcePath === input.path, + ); + throw new SyncError( + "InvalidDecision", + skipped + ? `The path "${input.path}" generates ${skipped.name}, which has no place on the remote: ${skipped.reason}` + : `The configuration has no token at "${input.path}". Add the token to the configuration first, then adopt it.`, + ); + } + if ( + target.name !== item.name && + loaded.state.fetched?.tokens.some((token) => token.name === target.name) + ) { + throw new SyncError( + "InvalidDecision", + `The path "${input.path}" generates ${target.name}, which the remote already has.`, + ); + } + const taken = loaded.state.decisions.find( + (entry) => + entry.action === "adopt" && + entry.path === input.path && + entry.item !== item.id, + ); + if (taken) { + throw new SyncError( + "InvalidDecision", + `The item "${taken.item}" is already adopted as "${input.path}". Two remote tokens cannot become one configuration token.`, + ); + } + }, + ), + ), +}); + +/** `cssforge inbox reject`: delete a new remote token at the next push. */ +export const syncInboxReject: Capability< + ForgeContext, + ItemInput, + DecisionReport, + DecisionFailures, + never, + "sync.inbox.reject", + Partial +> = capability({ + id: "sync.inbox.reject", + description: + "Reject a token that the remote created: the next push deletes it from the remote. Writes the state file only.", + audience: everyone, + destructive: false, + idempotent: true, + input: itemInput, + output: decisionReport, + failures: decisionFailures, + run: (input, { context }) => + attempt(() => + decide(context, input, { item: input.item, action: "reject" }, () => {}), + ), +}); + +/** `cssforge inbox overwrite`: give the value of the configuration back to the remote. */ +export const syncInboxOverwrite: Capability< + ForgeContext, + ItemInput, + DecisionReport, + DecisionFailures, + never, + "sync.inbox.overwrite", + Partial +> = capability({ + id: "sync.inbox.overwrite", + description: + "Settle a token that the remote changed, deleted, or created with the name of a configuration token: the next push writes the value of the configuration. To keep the value of the remote instead, change the configuration to that value; the item then goes away at the next fetch. Writes the state file only.", + audience: everyone, + destructive: false, + idempotent: true, + input: itemInput, + output: decisionReport, + failures: decisionFailures, + run: (input, { context }) => + attempt(() => + decide(context, input, { item: input.item, action: "overwrite" }, () => {}), + ), +}); + +/** Every sync capability, in the order the help lists them. */ +export const syncCapabilities = [ + syncRemoteAdd, + syncFetch, + syncPlan, + syncPush, + syncInboxList, + syncInboxAdopt, + syncInboxReject, + syncInboxOverwrite, +] as const; diff --git a/packages/cssforge/src/sync/mcp-client.ts b/packages/cssforge/src/sync/mcp-client.ts new file mode 100644 index 0000000..97a982e --- /dev/null +++ b/packages/cssforge/src/sync/mcp-client.ts @@ -0,0 +1,159 @@ +/** + * A minimal MCP client over standard input and output: it starts a server process, makes + * the handshake, and calls tools. Token sync uses it to talk to the MCP server of a + * design tool. It has no dependency beyond Node.js. + * + * @module + */ + +import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process"; +import { createInterface } from "node:readline"; + +/** The MCP revision that the client asks for. */ +const PROTOCOL_VERSION = "2025-06-18"; + +/** A failure to start the server or to get an answer from it. */ +export class McpClientError extends Error { + /** `spawn`: the server did not start. `protocol`: it did not answer as MCP. `tool`: a tool failed. */ + readonly reason: "spawn" | "protocol" | "tool"; + + constructor(message: string, reason: "spawn" | "protocol" | "tool") { + super(message); + this.name = "McpClientError"; + this.reason = reason; + } +} + +/** The text items of a tool result, in order. */ +export type ToolText = string[]; + +interface Pending { + resolve: (message: Record) => void; + reject: (error: Error) => void; +} + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +export interface McpClient { + /** Calls a tool, and gives the text items of its result. A tool error rejects. */ + callTool(name: string, args: Record): Promise; + /** Stops the server process. */ + close(): void; +} + +/** + * Starts `command` with `args` as an MCP server and makes the handshake. Rejects with a + * {@link McpClientError} when the process does not start or does not answer. + */ +export async function connectMcp( + command: string, + args: readonly string[], + signal?: AbortSignal, +): Promise { + const child: ChildProcessWithoutNullStreams = spawn(command, args, { + stdio: ["pipe", "pipe", "pipe"], + }); + const pending = new Map(); + let nextId = 1; + let ended: McpClientError | undefined; + let stderr = ""; + + const fail = (error: McpClientError) => { + ended ??= error; + for (const waiter of pending.values()) waiter.reject(ended); + pending.clear(); + }; + + child.stderr.on("data", (chunk: Buffer) => { + stderr = `${stderr}${chunk.toString()}`.slice(-2000); + }); + child.on("error", (error: NodeJS.ErrnoException) => { + fail( + new McpClientError( + error.code === "ENOENT" + ? `The command "${command}" was not found. Install it, or put it on the PATH.` + : `The command "${command}" did not start: ${error.message}`, + "spawn", + ), + ); + }); + child.on("exit", (code) => { + const detail = stderr.trim() ? `: ${stderr.trim()}` : "."; + fail( + new McpClientError( + `The MCP server "${command}" stopped with code ${code}${detail}`, + "protocol", + ), + ); + }); + + createInterface({ input: child.stdout }).on("line", (line) => { + if (!line.trim()) return; + let message: unknown; + try { + message = JSON.parse(line); + } catch { + return; + } + if (!isRecord(message) || typeof message.id !== "number") return; + const waiter = pending.get(message.id); + if (!waiter) return; + pending.delete(message.id); + waiter.resolve(message); + }); + + const send = (message: Record) => + child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`); + + const request = (method: string, params: Record) => + new Promise>((resolve, reject) => { + if (ended) return reject(ended); + const id = nextId++; + pending.set(id, { resolve, reject }); + send({ id, method, params }); + }).then((message) => { + if (isRecord(message.error)) { + throw new McpClientError( + `The MCP server answered ${method} with an error: ${String(message.error.message)}`, + "protocol", + ); + } + return isRecord(message.result) ? message.result : {}; + }); + + const close = () => { + child.stdin.end(); + child.kill(); + }; + signal?.addEventListener("abort", close, { once: true }); + + try { + await request("initialize", { + protocolVersion: PROTOCOL_VERSION, + capabilities: {}, + clientInfo: { name: "cssforge", version: "0" }, + }); + } catch (error) { + close(); + throw error; + } + send({ method: "notifications/initialized" }); + + return { + close, + async callTool(name, args) { + const result = await request("tools/call", { name, arguments: args }); + const content = Array.isArray(result.content) ? result.content : []; + const text = content.flatMap((item) => + isRecord(item) && item.type === "text" && typeof item.text === "string" + ? [item.text] + : [], + ); + if (result.isError === true) { + throw new McpClientError(`The tool ${name} failed: ${text.join(" ")}`, "tool"); + } + return text; + }, + }; +} diff --git a/packages/cssforge/src/sync/paper.ts b/packages/cssforge/src/sync/paper.ts new file mode 100644 index 0000000..6b5697f --- /dev/null +++ b/packages/cssforge/src/sync/paper.ts @@ -0,0 +1,275 @@ +/** + * The Paper remote (https://paper.design). It talks to the MCP server of Paper Desktop, + * which `paper-design mcp` starts, and uses its token tools: `get_basic_info`, + * `get_tokens`, `create_tokens` and `set_tokens`. + * + * @module + */ + +import { z } from "zod"; +import type { ListedToken, TokenKind } from "../generator.ts"; +import { ROOT_SCOPE } from "../lib.ts"; +import { connectMcp, McpClientError } from "./mcp-client.ts"; +import { type Operation, TOKEN_NAME } from "./plan.ts"; +import { + type ApplyResult, + type RemoteAdapter, + RemoteError, + type RemoteSession, + type TokenMapping, +} from "./remote.ts"; + +/** The token types of Paper. */ +type PaperType = + | "breakpoint" + | "color" + | "container" + | "fontFamily" + | "fontSize" + | "fontWeight" + | "letterSpacing" + | "lineHeight" + | "opacity" + | "radius" + | "spacing"; + +/** The Paper type of each token kind that Paper stores. */ +const paperTypes: Partial> = { + color: "color", + spacing: "spacing", + fontSize: "fontSize", + fontWeight: "fontWeight", + fontFamily: "fontFamily", + lineHeight: "lineHeight", + letterSpacing: "letterSpacing", + borderRadius: "radius", + opacity: "opacity", +}; + +/** + * The typography module emits two kinds under one token kind: the font weights of + * `typography.weight` and the fluid sizes of `typography_fluid`. + */ +const typographyType = (sourcePath: string): PaperType | undefined => { + if (sourcePath.startsWith("typography.weight.")) return "fontWeight"; + if (sourcePath.startsWith("typography_fluid.")) return "fontSize"; + return undefined; +}; + +/** Paper types whose numbers Paper takes as JSON numbers. */ +const numericTypes = new Set(["fontWeight", "lineHeight", "opacity"]); + +const LENGTH = /^-?\d*\.?\d+(?:px|rem|em|%|vw|vh|vmin|vmax|ch|ex)?$/i; +const SIZE_FUNCTION = /^(?:clamp|calc|min|max)\(/i; +/** The helper tokens of a `pow()` type scale: unitless inputs and partial terms. */ +const POW_SCALE_PATH = /\.pow(?:[.@]|$)/; + +/** + * Maps a configuration token to Paper. Paper has no modes, so a token scoped to a selector + * or an at-rule has no place. Paper rejects `color-mix()` and references inside a value. + */ +export function mapToPaper(token: ListedToken): TokenMapping { + if (token.scope !== ROOT_SCOPE) { + return { skip: `It is scoped to ${token.scope}, and Paper has no modes.` }; + } + const type = + token.kind === "typography" + ? typographyType(token.sourcePath) + : paperTypes[token.kind]; + if (type === undefined) return { skip: `Paper has no ${token.kind} tokens.` }; + + const value = token.resolvedValue.trim(); + if (value.includes("var(")) { + return { + skip: "Its value references a custom property that the configuration does not declare.", + }; + } + if (type === "color" && /(?:color-mix|light-dark)\(/i.test(value)) { + return { skip: "Paper does not take color-mix() or light-dark() values." }; + } + if (type === "fontSize") { + if (POW_SCALE_PATH.test(token.sourcePath)) { + return { + skip: "It is part of a pow() type scale; the clamp() scale is synced instead.", + }; + } + if (!LENGTH.test(value) && !SIZE_FUNCTION.test(value)) { + return { skip: "Its value is not a size." }; + } + } + return { type, value }; +} + +// --- MCP results ---------------------------------------------------------------------------- + +/** Each file-scoped Paper tool answers with the file first, then the result. */ +const resultOf = (schema: z.ZodType, text: readonly string[], tool: string): T => { + const body = text.at(-1); + try { + return schema.parse(JSON.parse(body ?? "")); + } catch { + throw new RemoteError( + "RemoteFailed", + `Paper answered ${tool} in a form that cssforge does not read: ${body ?? "(nothing)"}`, + ); + } +}; + +const basicInfo = z.object({ fileName: z.string() }); +const fileHeader = z.object({ file: z.object({ id: z.string(), name: z.string() }) }); +const tokenList = z.object({ + tokens: z.array( + z.object({ + // The rule of the state file, so that a fetch never records a name it cannot read back. + name: z.string().regex(TOKEN_NAME), + type: z.string(), + value: z.union([z.string(), z.number()]), + description: z.string().optional(), + }), + ), +}); +const entryResults = z.object({ + tokens: z.array(z.object({ result: z.string(), message: z.string().optional() })), +}); + +const paperValue = (type: string, value: string): string | number => + numericTypes.has(type) && /^-?\d*\.?\d+$/.test(value) ? Number(value) : value; + +/** An operation that `set_tokens` carries out: everything but a create. */ +type Change = Exclude; + +const isChange = (operation: Operation): operation is Change => operation.op !== "create"; + +/** The `set_tokens` entry of a change. */ +const setTokensEntry = (operation: Change) => { + switch (operation.op) { + case "update": + return { + name: operation.name, + value: paperValue(operation.type, operation.value), + description: operation.description, + }; + case "rename": + return { name: operation.from, newName: operation.to }; + case "delete": + return { name: operation.name, delete: true }; + } +}; + +// --- Adapter -------------------------------------------------------------------------------- + +export interface PaperOptions { + /** The command that serves the MCP server of Paper Desktop. */ + command?: string; + args?: readonly string[]; +} + +/** The Paper remote. */ +export function paperAdapter({ + command = "paper-design", + args = ["mcp"], +}: PaperOptions = {}): RemoteAdapter { + return { + kind: "paper", + map: mapToPaper, + async open(signal) { + const client = await connectMcp(command, args, signal).catch((error: unknown) => { + throw new RemoteError( + "RemoteUnavailable", + error instanceof Error + ? `Paper is not reachable: ${error.message} Start Paper Desktop and open the file.` + : String(error), + ); + }); + let calls = 0; + const call = async (tool: string, input: Record) => { + calls += 1; + try { + return await client.callTool(tool, input); + } catch (error) { + if (error instanceof McpClientError && error.reason === "tool") { + throw new RemoteError("RemoteFailed", error.message); + } + throw new RemoteError( + "RemoteUnavailable", + error instanceof Error ? error.message : String(error), + ); + } + }; + + const session: RemoteSession = { + get calls() { + return calls; + }, + close: () => client.close(), + async describe(file) { + const text = await call("get_basic_info", { fileId: file }); + const header = fileHeader.safeParse(JSON.parse(text[0] ?? "null")); + const info = resultOf(basicInfo, text, "get_basic_info"); + if (!header.success) { + throw new RemoteError( + "RemoteFailed", + "Paper did not say which file it read.", + ); + } + return { id: header.data.file.id, name: info.fileName }; + }, + async read(file) { + const text = await call("get_tokens", { fileId: file, format: "json" }); + return resultOf(tokenList, text, "get_tokens").tokens.map((token) => ({ + name: token.name, + type: token.type, + value: String(token.value), + ...(token.description === undefined + ? {} + : { description: token.description }), + })); + }, + async apply(file, operations) { + const creates = operations.filter((operation) => operation.op === "create"); + const changes = operations.filter(isChange); + const results: ApplyResult[] = []; + + const report = ( + batch: readonly Operation[], + text: readonly string[], + tool: string, + ) => { + const entries = resultOf(entryResults, text, tool).tokens; + batch.forEach((operation, index) => { + const entry = entries[index]; + const ok = entry !== undefined && entry.result !== "error"; + results.push({ + operation, + ok, + ...(ok ? {} : { message: entry?.message ?? "Paper gave no result." }), + }); + }); + }; + + if (creates.length > 0) { + const text = await call("create_tokens", { + fileId: file, + tokens: creates.map((operation) => ({ + type: operation.type, + name: operation.name, + value: paperValue(operation.type, operation.value), + description: operation.description, + })), + }); + report(creates, text, "create_tokens"); + } + if (changes.length > 0) { + const text = await call("set_tokens", { + fileId: file, + tokens: changes.map(setTokensEntry), + }); + report(changes, text, "set_tokens"); + } + return results; + }, + }; + return session; + }, + }; +} diff --git a/packages/cssforge/src/sync/plan.ts b/packages/cssforge/src/sync/plan.ts new file mode 100644 index 0000000..7bf155d --- /dev/null +++ b/packages/cssforge/src/sync/plan.ts @@ -0,0 +1,383 @@ +/** + * The three-way plan of token sync. It compares the tokens that the configuration + * wants on a remote (a design tool), the tokens the remote has now, and the base: the + * tokens as they were after the last push. Writes nothing and calls no remote. + * + * The configuration is the source of truth. A token that only the configuration changed + * is pushed. A token that the remote created, changed or deleted becomes an inbox item, + * and stays one until a decision settles it: `adopt` or `reject` for a new token, + * `overwrite` for the others. + * + * @module + */ + +/** The pattern of a token name on a remote: a CSS custom property, e.g. `--color-primary`. */ +export const TOKEN_NAME = /^--[a-zA-Z0-9_-]+$/; + +/** A token as a remote stores it. */ +export interface RemoteToken { + /** The custom property name, e.g. `--color-primary`. */ + name: string; + /** The token type of the remote, e.g. `color` or `spacing`. */ + type: string; + value: string; + description?: string; +} + +/** A token that the configuration wants on the remote. */ +export interface DesiredToken { + name: string; + type: string; + /** The literal value, with every reference resolved. */ + value: string; + /** The token this one aliases, when its generated value is exactly `var()`. */ + alias?: string; + /** The configuration path of the token. */ + sourcePath: string; + /** A description the remote shows beside the token. */ + description: string; +} + +/** A token the configuration owns on the remote, as it was after the last push. */ +export interface BaseEntry { + name: string; + type: string; + /** The value the last push sent. */ + sent: string; + /** The value as the remote stored it, read back after the push. `null` if the read found no token. */ + stored: string | null; + sourcePath: string; +} + +/** A recorded answer to an inbox item. The item is the token name without its `--`. */ +export type Decision = + | { item: string; action: "adopt"; path: string } + | { item: string; action: "reject" } + | { item: string; action: "overwrite" }; + +/** A change to send to the remote. */ +export type Operation = + | { op: "create"; name: string; type: string; value: string; description: string } + | { op: "update"; name: string; type: string; value: string; description: string } + | { op: "rename"; from: string; to: string } + | { op: "delete"; name: string }; + +/** A change that the remote made, which waits for a decision. */ +export interface InboxItem { + /** The id of the item: the token name without its `--`. */ + id: string; + /** + * `new`: the remote created a token that the configuration does not have. + * `edited`: the remote changed the value of a token that the configuration owns. + * `deleted`: the remote deleted a token that the configuration owns. + * `collision`: the remote has a token with the name of a new configuration token. + */ + kind: "new" | "edited" | "deleted" | "collision"; + name: string; + type: string; + /** The value on the remote, unless the remote deleted the token. */ + remoteValue?: string; + /** The value the configuration wants, unless the configuration does not have the token. */ + localValue?: string; + /** The decisions that settle the item. */ + actions: Decision["action"][]; + /** Why a recorded decision does not apply yet, for example an adopted path that is missing. */ + note?: string; +} + +/** A planned operation with the base entry it gives when the remote accepts it. */ +export interface PlannedOperation { + operation: Operation; + /** The base entry after the operation, or `null` when the operation removes the entry. */ + base: BaseEntry | null; + /** The base entry the operation replaces, removed when the operation succeeds. */ + replaces?: string; + /** The decision that the operation carries out, removed when the operation succeeds. */ + settles?: string; +} + +export interface SyncPlan { + operations: PlannedOperation[]; + inbox: InboxItem[]; + /** The base entries that no operation changes, with the stored values of this fetch. */ + carried: BaseEntry[]; + /** The decisions that still wait: their items are in the inbox. */ + pending: Decision[]; +} + +export interface PlanInput { + desired: readonly DesiredToken[]; + /** + * The names of configuration tokens that have no place on the remote. A pushed token + * that becomes one keeps its remote copy: it is skipped, not removed from the configuration. + */ + skipped?: ReadonlySet; + remote: readonly RemoteToken[]; + base: readonly BaseEntry[]; + decisions: readonly Decision[]; +} + +/** The inbox id of a token name: the name without its `--`. */ +export const itemIdOf = (name: string): string => name.replace(/^--/, ""); + +const byName = (entries: readonly T[]) => + new Map(entries.map((entry) => [entry.name, entry])); + +/** + * Plans a sync. Operations come in the order the remote must apply them: creates first, + * each after the tokens it aliases, then renames, updates and deletes. + */ +export function planSync(input: PlanInput): SyncPlan { + const { remote, base, decisions } = input; + const skipped = input.skipped ?? new Set(); + const desired = withAliases(input.desired); + const desiredByName = byName(desired); + const remoteByName = byName(remote); + const baseByName = byName(base); + const decisionByItem = new Map(decisions.map((decision) => [decision.item, decision])); + + const creates: PlannedOperation[] = []; + const changes: PlannedOperation[] = []; + const inbox: InboxItem[] = []; + const carried: BaseEntry[] = []; + const pending: Decision[] = []; + /** Configuration tokens that an adopted remote token becomes, so they are not created. */ + const adoptedNames = new Set(); + + const decisionFor = (name: string) => decisionByItem.get(itemIdOf(name)); + const settled = (name: string) => itemIdOf(name); + const entryOf = (token: DesiredToken): BaseEntry => ({ + name: token.name, + type: token.type, + sent: token.value, + stored: null, + sourcePath: token.sourcePath, + }); + + // A token that the remote has and the base does not: new, or adopted under a decision. + for (const remoteToken of remote) { + if (baseByName.has(remoteToken.name)) continue; + const wanted = desiredByName.get(remoteToken.name); + const decision = decisionFor(remoteToken.name); + + if (wanted) { + // The configuration wants a token with this name, which it never pushed. + if (decision?.action === "overwrite") { + changes.push({ + operation: update(wanted), + base: entryOf(wanted), + settles: settled(remoteToken.name), + }); + adoptedNames.add(wanted.name); + continue; + } + adoptedNames.add(wanted.name); + if (decision) pending.push(decision); + inbox.push({ + id: itemIdOf(remoteToken.name), + kind: "collision", + name: remoteToken.name, + type: remoteToken.type, + remoteValue: remoteToken.value, + localValue: wanted.value, + actions: ["overwrite"], + }); + continue; + } + + if (decision?.action === "reject") { + changes.push({ + operation: { op: "delete", name: remoteToken.name }, + base: null, + settles: settled(remoteToken.name), + }); + continue; + } + + if (decision?.action === "adopt") { + const target = desired.find((token) => token.sourcePath === decision.path); + const blocked = + target === undefined + ? `The adopted path "${decision.path}" is not in the configuration.` + : remoteByName.has(target.name) || baseByName.has(target.name) + ? `The adopted path "${decision.path}" generates ${target.name}, which the remote already has.` + : adoptedNames.has(target.name) + ? `Another item is already adopted as "${decision.path}".` + : undefined; + if (target && blocked === undefined) { + adoptedNames.add(target.name); + const entry = { ...entryOf(target), sent: remoteToken.value }; + changes.push({ + operation: { op: "rename", from: remoteToken.name, to: target.name }, + base: entry, + settles: settled(remoteToken.name), + }); + if (target.value !== remoteToken.value) { + changes.push({ operation: update(target), base: entryOf(target) }); + } + continue; + } + pending.push(decision); + inbox.push({ + ...newItem(remoteToken), + ...(blocked ? { note: blocked } : {}), + }); + continue; + } + + if (decision) pending.push(decision); + inbox.push(newItem(remoteToken)); + } + + // A token that the base has: the configuration owns it. + for (const entry of base) { + const wanted = desiredByName.get(entry.name); + const remoteToken = remoteByName.get(entry.name); + const decision = decisionFor(entry.name); + + if (!wanted && skipped.has(entry.name)) { + carried.push({ ...entry, stored: entry.stored ?? remoteToken?.value ?? null }); + continue; + } + if (!wanted) { + // Removed from the configuration: delete it from the remote, if it is still there. + if (remoteToken) { + changes.push({ + operation: { op: "delete", name: entry.name }, + base: null, + replaces: entry.name, + }); + } + continue; + } + + if (!remoteToken) { + if (decision?.action === "overwrite") { + creates.push({ + operation: create(wanted), + base: entryOf(wanted), + settles: settled(entry.name), + }); + continue; + } + if (decision) pending.push(decision); + carried.push(entry); + inbox.push({ + id: itemIdOf(entry.name), + kind: "deleted", + name: entry.name, + type: entry.type, + localValue: wanted.value, + actions: ["overwrite"], + }); + continue; + } + + const stored = entry.stored ?? remoteToken.value; + const remoteChanged = remoteToken.value !== stored; + const localChanged = wanted.value !== entry.sent; + + if (remoteChanged) { + if (decision?.action === "overwrite") { + changes.push({ + operation: update(wanted), + base: entryOf(wanted), + settles: settled(entry.name), + }); + continue; + } + if (decision) pending.push(decision); + carried.push({ ...entry, stored }); + inbox.push({ + id: itemIdOf(entry.name), + kind: "edited", + name: entry.name, + type: entry.type, + remoteValue: remoteToken.value, + localValue: wanted.value, + actions: ["overwrite"], + }); + continue; + } + + if (localChanged) { + changes.push({ operation: update(wanted), base: entryOf(wanted) }); + continue; + } + carried.push({ ...entry, stored }); + } + + // A token that only the configuration has: create it. + for (const token of desired) { + if (baseByName.has(token.name) || remoteByName.has(token.name)) continue; + if (adoptedNames.has(token.name)) continue; + creates.push({ operation: create(token), base: entryOf(token) }); + } + + return { + operations: [...orderCreates(creates, desiredByName), ...changes], + inbox, + carried, + pending, + }; +} + +const create = (token: DesiredToken): Operation => ({ + op: "create", + name: token.name, + type: token.type, + value: token.value, + description: token.description, +}); + +const update = (token: DesiredToken): Operation => ({ + op: "update", + name: token.name, + type: token.type, + value: token.value, + description: token.description, +}); + +const newItem = (token: RemoteToken): InboxItem => ({ + id: itemIdOf(token.name), + kind: "new", + name: token.name, + type: token.type, + remoteValue: token.value, + actions: ["adopt", "reject"], +}); + +/** + * Writes a token that aliases another pushed token of the same type as `var(--target)`, + * so that the remote keeps the link. The remote takes an alias only as the whole value, + * and only to a token of the same type; any other token sends its literal value. + */ +function withAliases(desired: readonly DesiredToken[]): DesiredToken[] { + const types = new Map(desired.map((token) => [token.name, token.type])); + return desired.map((token) => + token.alias !== undefined && types.get(token.alias) === token.type + ? { ...token, value: `var(${token.alias})` } + : token, + ); +} + +/** Orders creates so that each comes after the token it aliases. */ +function orderCreates( + creates: readonly PlannedOperation[], + desiredByName: ReadonlyMap, +): PlannedOperation[] { + const pending = new Map(creates.map((planned) => [planned.base?.name ?? "", planned])); + const ordered: PlannedOperation[] = []; + + const visit = (name: string) => { + const planned = pending.get(name); + if (!planned) return; + pending.delete(name); + const alias = desiredByName.get(name)?.alias; + if (alias !== undefined) visit(alias); + ordered.push(planned); + }; + + for (const name of [...pending.keys()]) visit(name); + return ordered; +} diff --git a/packages/cssforge/src/sync/remote.ts b/packages/cssforge/src/sync/remote.ts new file mode 100644 index 0000000..4a494e7 --- /dev/null +++ b/packages/cssforge/src/sync/remote.ts @@ -0,0 +1,64 @@ +/** + * The interface between token sync and a remote: a design tool that stores tokens. Each + * kind of remote (Paper, and later others) has one adapter. + * + * @module + */ + +import type { ListedToken } from "../generator.ts"; +import type { Operation, RemoteToken } from "./plan.ts"; + +/** A file of the remote that the tokens sync with. */ +export interface RemoteFile { + /** The id of the file on the remote. */ + id: string; + /** The name of the file, for people. */ + name: string; +} + +/** What the remote did with one operation. */ +export interface ApplyResult { + operation: Operation; + ok: boolean; + /** Why the remote refused the operation. */ + message?: string; +} + +/** + * A connection to the remote for one capability call. `calls` counts the requests made, + * because some remotes limit them. + */ +export interface RemoteSession { + /** Finds the file from an id or a URL. */ + describe(file: string): Promise; + /** Reads every token of the file. */ + read(file: string): Promise; + /** Sends the operations in order, and reports each one. */ + apply(file: string, operations: readonly Operation[]): Promise; + readonly calls: number; + close(): void; +} + +/** Where a configuration token goes on the remote, or why it has no place there. */ +export type TokenMapping = { type: string; value: string } | { skip: string }; + +/** One kind of remote. */ +export interface RemoteAdapter { + /** The kind, as `remote add --kind` names it, e.g. `paper`. */ + kind: string; + /** Maps a configuration token to the remote. */ + map(token: ListedToken): TokenMapping; + /** Opens a session. Rejects with a {@link RemoteError} when the remote cannot be reached. */ + open(signal: AbortSignal): Promise; +} + +/** A failure of the remote, as a capability failure. */ +export class RemoteError extends Error { + readonly tag: "RemoteUnavailable" | "RemoteFailed"; + + constructor(tag: "RemoteUnavailable" | "RemoteFailed", message: string) { + super(message); + this.name = "RemoteError"; + this.tag = tag; + } +} diff --git a/packages/cssforge/src/sync/state.ts b/packages/cssforge/src/sync/state.ts new file mode 100644 index 0000000..3684132 --- /dev/null +++ b/packages/cssforge/src/sync/state.ts @@ -0,0 +1,135 @@ +/** + * The state of the sync with one remote, in `.cssforge/sync/.json`: the file it + * syncs with, the base (the tokens as they were after the last push), the last fetch, and + * the decisions that wait for the next push. Commit it, so that everyone who syncs shares + * the base. + * + * @module + */ + +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { z } from "zod"; +import { type BaseEntry, type Decision, type RemoteToken, TOKEN_NAME } from "./plan.ts"; + +/** The pattern of a remote name: a word in lowercase, e.g. `paper` or `paper-marketing`. */ +export const REMOTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/; + +export interface SyncState { + version: 1; + /** The kind of remote, e.g. `paper`. */ + kind: string; + /** The file of the remote, by id and name. */ + file: { id: string; name: string }; + base: BaseEntry[]; + /** The remote tokens of the last fetch, or `null` before the first fetch. */ + fetched: { at: string; tokens: RemoteToken[] } | null; + decisions: Decision[]; +} + +const tokenName = z.string().regex(TOKEN_NAME); + +const stateSchema = z.strictObject({ + version: z.literal(1), + kind: z.string().min(1), + file: z.strictObject({ id: z.string().min(1), name: z.string() }), + base: z.array( + z.strictObject({ + name: tokenName, + type: z.string(), + sent: z.string(), + stored: z.string().nullable(), + sourcePath: z.string(), + }), + ), + fetched: z + .strictObject({ + at: z.string(), + tokens: z.array( + z.strictObject({ + name: tokenName, + type: z.string(), + value: z.string(), + description: z.string().optional(), + }), + ), + }) + .nullable(), + decisions: z.array( + z.discriminatedUnion("action", [ + z.strictObject({ item: z.string(), action: z.literal("adopt"), path: z.string() }), + z.strictObject({ item: z.string(), action: z.literal("reject") }), + z.strictObject({ item: z.string(), action: z.literal("overwrite") }), + ]), + ), +}); + +/** The path of the state file of `remote`, under `root`. */ +export const statePath = (root: string, remote: string): string => + join(root, ".cssforge", "sync", `${remote}.json`); + +/** A state file that is missing, or that is not a valid state. */ +export class StateError extends Error { + readonly tag: "RemoteNotConfigured" | "InvalidState"; + /** The state file. */ + readonly path: string; + + constructor( + tag: "RemoteNotConfigured" | "InvalidState", + message: string, + path: string, + ) { + super(message); + this.name = "StateError"; + this.tag = tag; + this.path = path; + } +} + +/** Reads and validates the state of `remote`. */ +export async function readState(root: string, remote: string): Promise { + const path = statePath(root, remote); + let text: string; + try { + text = await readFile(path, "utf8"); + } catch { + throw new StateError( + "RemoteNotConfigured", + `There is no remote "${remote}". Add it with \`cssforge remote add --name ${remote} --kind paper --file \`.`, + path, + ); + } + let data: unknown; + try { + data = JSON.parse(text); + } catch (error) { + throw new StateError( + "InvalidState", + `The state file is not JSON: ${String(error)}`, + path, + ); + } + const parsed = stateSchema.safeParse(data); + if (!parsed.success) { + throw new StateError( + "InvalidState", + `The state file is not valid: ${z.prettifyError(parsed.error)}`, + path, + ); + } + return parsed.data; +} + +/** Writes the state of `remote` in one step: a reader never sees half a file. */ +export async function writeState( + root: string, + remote: string, + state: SyncState, +): Promise { + const path = statePath(root, remote); + await mkdir(dirname(path), { recursive: true }); + const temporary = `${path}.${process.pid}.tmp`; + await writeFile(temporary, `${JSON.stringify(state, null, "\t")}\n`, "utf8"); + await rename(temporary, path); + return path; +} diff --git a/packages/cssforge/tests/acidcat.test.ts b/packages/cssforge/tests/acidcat.test.ts index 175f9db..cfb15b2 100644 --- a/packages/cssforge/tests/acidcat.test.ts +++ b/packages/cssforge/tests/acidcat.test.ts @@ -141,12 +141,31 @@ test("mcp - cssforge mcp serves the capabilities as tools", async () => { send({ jsonrpc: "2.0", method: "notifications/initialized" }); send({ jsonrpc: "2.0", id: 2, method: "tools/list" }); - const listed = (await nextLine()).result as { tools: { name: string }[] }; + const listed = (await nextLine()).result as { + tools: { name: string; annotations?: Record }[]; + }; expect(listed.tools.map((tool) => tool.name).sort()).toEqual([ "config.check", + "sync.fetch", + "sync.inbox.adopt", + "sync.inbox.list", + "sync.inbox.overwrite", + "sync.inbox.reject", + "sync.plan", + "sync.push", + "sync.remote.add", "tokens.build", "tokens.generate", ]); + // An agent client asks before a destructive tool, and not before a read-only one. + const annotations = (name: string) => + listed.tools.find((tool) => tool.name === name)?.annotations; + expect(annotations("sync.push")).toMatchObject({ + destructiveHint: true, + idempotentHint: true, + }); + expect(annotations("sync.inbox.reject")).toMatchObject({ destructiveHint: false }); + expect(annotations("sync.plan")).toMatchObject({ readOnlyHint: true }); send({ jsonrpc: "2.0", diff --git a/packages/cssforge/tests/fixtures/fake-paper-mcp.ts b/packages/cssforge/tests/fixtures/fake-paper-mcp.ts new file mode 100644 index 0000000..fc46d6e --- /dev/null +++ b/packages/cssforge/tests/fixtures/fake-paper-mcp.ts @@ -0,0 +1,99 @@ +/** + * A stand-in for the MCP server of Paper Desktop (`paper-design mcp`), in the wire form + * of Paper 0.5.19: each file tool answers with a text item that names the file, then a + * text item with the result as JSON. It serves the token tools that sync uses. + * + * FAKE_PAPER_STATE is a JSON file with the tokens of the file, kept between processes. + * FAKE_PAPER_LOG gets one JSON line for each tool call: `{ name, arguments }`. + */ +import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs"; +import { createInterface } from "node:readline"; + +interface Token { + name: string; + type: string; + value: string | number; + description?: string; +} + +const statePath = process.env.FAKE_PAPER_STATE ?? ""; +const logPath = process.env.FAKE_PAPER_LOG ?? ""; +const file = { id: "01FAKE", name: "Fake file" }; + +const readTokens = (): Token[] => + existsSync(statePath) ? (JSON.parse(readFileSync(statePath, "utf8")) as Token[]) : []; +const writeTokens = (tokens: Token[]) => writeFileSync(statePath, JSON.stringify(tokens)); + +const answer = (id: unknown, result: unknown) => + process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`); +const toolResult = (body: unknown) => ({ + content: [ + { type: "text", text: JSON.stringify({ file, contentHash: { tokens: "0" } }) }, + { type: "text", text: JSON.stringify(body) }, + ], +}); + +const tools: Record) => unknown> = { + get_basic_info: () => ({ fileName: file.name, tokens: { items: [] } }), + get_tokens: () => ({ + tokens: readTokens().map((token) => ({ ...token, value: String(token.value) })), + }), + create_tokens: (args) => { + const tokens = readTokens(); + const results = (args.tokens as Token[]).map((token) => { + tokens.push(token); + return { name: token.name, result: "created" }; + }); + writeTokens(tokens); + return { tokens: results, count: results.length }; + }, + set_tokens: (args) => { + let tokens = readTokens(); + const edits = args.tokens as { + name: string; + newName?: string; + value?: string; + delete?: boolean; + }[]; + const results = edits.map((edit) => { + const token = tokens.find((candidate) => candidate.name === edit.name); + if (!token) return { result: "error", message: `Token not found: "${edit.name}".` }; + if (edit.delete) { + tokens = tokens.filter((candidate) => candidate !== token); + return { name: edit.name, result: "deleted" }; + } + if (edit.newName) token.name = edit.newName; + if (edit.value !== undefined) token.value = edit.value; + return { name: edit.name, result: "updated" }; + }); + writeTokens(tokens); + return { tokens: results, count: results.length }; + }, +}; + +createInterface({ input: process.stdin }).on("line", (line) => { + const message = JSON.parse(line) as { + id?: unknown; + method: string; + params?: Record; + }; + if (message.method === "initialize") { + answer(message.id, { + protocolVersion: "2025-06-18", + capabilities: { tools: {} }, + serverInfo: { name: "paper-desktop", version: "0.0.1" }, + }); + return; + } + if (message.method !== "tools/call") return; + const name = String(message.params?.name); + const args = (message.params?.arguments ?? {}) as Record; + appendFileSync(logPath, `${JSON.stringify({ name, arguments: args })}\n`); + const tool = tools[name]; + answer( + message.id, + tool + ? toolResult(tool(args)) + : { isError: true, content: [{ type: "text", text: `Unknown tool ${name}.` }] }, + ); +}); diff --git a/packages/cssforge/tests/sync-paper.test.ts b/packages/cssforge/tests/sync-paper.test.ts new file mode 100644 index 0000000..9696912 --- /dev/null +++ b/packages/cssforge/tests/sync-paper.test.ts @@ -0,0 +1,134 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createSession } from "@acid-cat/core-ts"; +import { afterEach, beforeEach, expect, test } from "vitest"; +import { + cssforge, + paperAdapter, + syncFetch, + syncPlan, + syncPush, + syncRemoteAdd, + toJsonSchema, +} from "../src/capabilities.ts"; + +const fakePaper = fileURLToPath(new URL("./fixtures/fake-paper-mcp.ts", import.meta.url)); + +let projectDir = ""; +let logPath = ""; + +beforeEach(async () => { + projectDir = await mkdtemp(join(tmpdir(), "cssforge-sync-paper-")); + logPath = join(projectDir, "paper.log"); + await writeFile(logPath, "", "utf8"); + process.env.FAKE_PAPER_STATE = join(projectDir, "paper.json"); + process.env.FAKE_PAPER_LOG = logPath; + await writeFile( + join(projectDir, "cssforge.config.ts"), + `export default ${JSON.stringify({ + colors: { palette: { value: { brand: { 500: "oklch(60% 0.2 250)" } } } }, + typography: { weight: { body: { value: { bold: "700" } } } }, + })};\n`, + "utf8", + ); +}); + +afterEach(async () => { + delete process.env.FAKE_PAPER_STATE; + delete process.env.FAKE_PAPER_LOG; + await rm(projectDir, { recursive: true, force: true }); +}); + +const openSession = (command: string, args: string[]) => + createSession(cssforge, { + target: "library", + context: { cwd: projectDir, remotes: [paperAdapter({ command, args })] }, + toJsonSchema, + }); + +const toolCalls = async () => + (await readFile(logPath, "utf8")) + .split("\n") + .filter(Boolean) + .map( + (line) => JSON.parse(line) as { name: string; arguments: Record }, + ); + +test("paper - remote add binds the file id that Paper reports for a file URL", async () => { + await using session = openSession(process.execPath, [fakePaper]); + + const result = await session.call(syncRemoteAdd, { + file: "https://app.paper.design/file/01FAKE/p-1-0", + }); + + expect(result.ok, JSON.stringify(result)).toEqual(true); + if (!result.ok) return; + expect(result.value.file).toEqual({ id: "01FAKE", name: "Fake file" }); + expect(await toolCalls()).toEqual([ + { + name: "get_basic_info", + arguments: { fileId: "https://app.paper.design/file/01FAKE/p-1-0" }, + }, + ]); +}); + +test("paper - push sends Paper's token types, a font weight as a number, and reads the values back", async () => { + await using session = openSession(process.execPath, [fakePaper]); + await session.call(syncRemoteAdd, { file: "01FAKE" }); + + const result = await session.call(syncPush, {}); + + expect(result.ok, JSON.stringify(result)).toEqual(true); + expect((await toolCalls()).slice(1)).toEqual([ + { name: "get_tokens", arguments: { fileId: "01FAKE", format: "json" } }, + { + name: "create_tokens", + arguments: { + fileId: "01FAKE", + tokens: [ + { + type: "color", + name: "--palette-brand-500", + value: "oklch(60% 0.2 250)", + description: "cssforge: palette.brand.500", + }, + { + type: "fontWeight", + name: "--typography-weight-body-bold", + value: 700, + description: "cssforge: typography.weight.body.bold", + }, + ], + }, + }, + { name: "get_tokens", arguments: { fileId: "01FAKE", format: "json" } }, + ]); + if (result.ok) expect(result.value.callsUsed).toEqual(3); +}); + +test("paper - a missing paper-design command fails as RemoteUnavailable", async () => { + await using session = openSession(join(projectDir, "no-such-paper-design"), ["mcp"]); + + const result = await session.call(syncRemoteAdd, { file: "01FAKE" }); + + expect(result.ok ? undefined : result.error._tag).toEqual("RemoteUnavailable"); + if (!result.ok) expect(result.error.message).toContain("was not found"); +}); + +test("paper - a token name the state cannot hold fails the fetch and leaves the state readable", async () => { + await using session = openSession(process.execPath, [fakePaper]); + await session.call(syncRemoteAdd, { file: "01FAKE" }); + await writeFile( + process.env.FAKE_PAPER_STATE ?? "", + JSON.stringify([{ name: "brand", type: "color", value: "#ff0000" }]), + "utf8", + ); + + const fetched = await session.call(syncFetch, {}); + const planned = await session.call(syncPlan, {}); + + expect(fetched.ok ? undefined : fetched.error._tag).toEqual("RemoteFailed"); + expect(planned.ok ? undefined : planned.error._tag).toEqual("NotFetched"); +}); diff --git a/packages/cssforge/tests/sync.test.ts b/packages/cssforge/tests/sync.test.ts new file mode 100644 index 0000000..edb519b --- /dev/null +++ b/packages/cssforge/tests/sync.test.ts @@ -0,0 +1,549 @@ +import { spawnSync } from "node:child_process"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createSession } from "@acid-cat/core-ts"; +import { afterEach, beforeEach, expect, test } from "vitest"; +import { + type ApplyResult, + cssforge, + type Operation, + paperAdapter, + type RemoteAdapter, + RemoteError, + type RemoteToken, + syncFetch, + syncInboxAdopt, + syncInboxOverwrite, + syncInboxReject, + syncPlan, + syncPush, + syncRemoteAdd, + toJsonSchema, +} from "../src/capabilities.ts"; +import { childEnv } from "./helpers.ts"; + +/** + * An in-memory Paper file. It keeps the rules of Paper that sync depends on: an alias + * must name an existing token of the same type, `set_tokens` targets an existing name, + * and duplicate names are allowed. `store` changes a value as Paper normalizes it. + */ +class FakePaper { + tokens: RemoteToken[] = []; + requests = 0; + /** Names whose create or update the remote refuses. */ + refuse = new Set(); + store = (value: string) => value; + /** The number of reads that succeed before every later read fails. */ + readsBeforeFailure = Number.POSITIVE_INFINITY; + + readonly adapter: RemoteAdapter = { + kind: "paper", + // The mapping of the real Paper remote: only the transport is fake. + map: paperAdapter().map, + open: async () => { + let calls = 0; + const request = () => { + calls += 1; + this.requests += 1; + }; + return { + get calls() { + return calls; + }, + close: () => {}, + describe: async (file) => { + request(); + return { id: file.replace(/^.*\/file\//, ""), name: "Tokens" }; + }, + read: async () => { + request(); + if (this.readsBeforeFailure <= 0) { + throw new RemoteError("RemoteUnavailable", "Paper stopped."); + } + this.readsBeforeFailure -= 1; + return this.tokens.map((token) => ({ ...token })); + }, + apply: async (_file, operations) => { + request(); + return operations.map((operation) => this.apply(operation)); + }, + }; + }, + }; + + private find = (name: string) => this.tokens.find((token) => token.name === name); + + private apply(operation: Operation): ApplyResult { + const refused = (message: string): ApplyResult => ({ operation, ok: false, message }); + switch (operation.op) { + case "create": { + if (this.refuse.has(operation.name)) return refused("Refused."); + const alias = /^var\((--[\w-]+)\)$/.exec(operation.value)?.[1]; + if (alias && this.find(alias)?.type !== operation.type) { + return refused(`Invalid value "${operation.value}".`); + } + this.tokens.push({ + name: operation.name, + type: operation.type, + value: this.store(operation.value), + description: operation.description, + }); + return { operation, ok: true }; + } + case "update": { + const token = this.find(operation.name); + if (!token || this.refuse.has(operation.name)) return refused("Refused."); + token.value = this.store(operation.value); + return { operation, ok: true }; + } + case "rename": { + const token = this.find(operation.from); + if (!token) return refused("Token not found."); + token.name = operation.to; + return { operation, ok: true }; + } + case "delete": { + if (!this.find(operation.name)) return refused("Token not found."); + this.tokens = this.tokens.filter((token) => token.name !== operation.name); + return { operation, ok: true }; + } + } + } + + value = (name: string) => this.find(name)?.value; +} + +/** A palette color, an alias to it, two sizes, and three tokens Paper has no place for. */ +const baseConfig = { + colors: { + palette: { + value: { + brand: { + 500: "oklch(60% 0.2 250)", + 600: { mix: { from: "palette.brand.500", with: "black", amount: 20 } }, + }, + }, + }, + theme: { + value: { + light: { + value: { + surface: { + value: { accent: "var(--brand)" }, + variables: { brand: "palette.brand.500" }, + }, + }, + }, + dark: { + value: { surface: { value: { accent: "oklch(30% 0.1 250)" } } }, + settings: { selector: ".dark" }, + }, + }, + }, + }, + spacing: { custom: { size: { value: { 1: "4px", 2: "8px" } } } }, + motion: { duration: { ui: { value: { press: "120ms" } } } }, +}; + +let projectDir = ""; +let paper: FakePaper; + +const writeConfig = (config: unknown) => + writeFile( + join(projectDir, "cssforge.config.ts"), + `export default ${JSON.stringify(config)};\n`, + "utf8", + ); + +const withSpacing = (sizes: Record) => ({ + ...baseConfig, + spacing: { custom: { size: { value: sizes } } }, +}); + +const withAccent = (accent: string) => ({ + ...baseConfig, + colors: { + ...baseConfig.colors, + palette: { + value: { brand: { ...baseConfig.colors.palette.value.brand, accent } }, + }, + }, +}); + +beforeEach(async () => { + projectDir = await mkdtemp(join(tmpdir(), "cssforge-sync-")); + paper = new FakePaper(); + await writeConfig(baseConfig); +}); + +afterEach(async () => { + await rm(projectDir, { recursive: true, force: true }); +}); + +const openSession = () => + createSession(cssforge, { + target: "library", + context: { cwd: projectDir, remotes: [paper.adapter] }, + toJsonSchema, + }); + +/** Calls a capability, and gives its value, or fails the test with its failure. */ +const expectValue = async ( + result: Promise<{ ok: true; value: T } | { ok: false; error: unknown }>, +) => { + const settled = await result; + if (!settled.ok) + throw new Error(`Expected a value. Received ${JSON.stringify(settled.error)}`); + return settled.value; +}; + +/** A session with the remote added and the configuration pushed once. */ +const pushedSession = async () => { + const session = openSession(); + await expectValue( + session.call(syncRemoteAdd, { file: "https://app.paper.design/file/F1" }), + ); + await expectValue(session.call(syncPush, {})); + return session; +}; + +test("push - creates the configuration tokens on an empty remote, each alias after its target", async () => { + await using session = openSession(); + await expectValue( + session.call(syncRemoteAdd, { file: "https://app.paper.design/file/F1" }), + ); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied.map(({ operation, ok }) => ({ ...operation, ok }))).toEqual([ + { + op: "create", + name: "--palette-brand-500", + type: "color", + value: "oklch(60% 0.2 250)", + description: "cssforge: palette.brand.500", + ok: true, + }, + { + op: "create", + name: "--theme-light-surface-accent", + type: "color", + value: "var(--palette-brand-500)", + description: "cssforge: theme.light.surface.accent", + ok: true, + }, + { + op: "create", + name: "--spacing-size-1", + type: "spacing", + value: "0.25rem", + description: "cssforge: spacing.custom.size.1", + ok: true, + }, + { + op: "create", + name: "--spacing-size-2", + type: "spacing", + value: "0.5rem", + description: "cssforge: spacing.custom.size.2", + ok: true, + }, + ]); + expect(report.operations).toEqual([]); + expect(report.file).toEqual({ id: "F1", name: "Tokens" }); +}); + +test("push - reports each configuration token that has no place on Paper, with the reason", async () => { + await using session = openSession(); + await expectValue(session.call(syncRemoteAdd, { file: "F1" })); + + const report = await expectValue(session.call(syncPush, { "dry-run": true })); + + expect(report.skipped).toEqual([ + { + name: "--palette-brand-600", + sourcePath: "palette.brand.600", + reason: "Paper does not take color-mix() or light-dark() values.", + }, + { + name: "--theme-dark-surface-accent", + sourcePath: "theme.dark.surface.accent", + reason: "It is scoped to |.dark, and Paper has no modes.", + }, + { + name: "--motion-duration-ui-press", + sourcePath: "motion.duration.ui.press", + reason: "Paper has no duration tokens.", + }, + ]); + expect(report.applied).toEqual([]); + expect(paper.tokens).toEqual([]); +}); + +test("push - a push with no change reads the remote once and sends nothing", async () => { + await using session = await pushedSession(); + paper.requests = 0; + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied).toEqual([]); + expect(report.callsUsed).toEqual(paper.requests); + expect(paper.requests).toEqual(1); +}); + +test("push - updates a changed token and deletes a token removed from the configuration", async () => { + await using session = await pushedSession(); + await writeConfig(withSpacing({ 1: "6px" })); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied.map(({ operation }) => operation)).toEqual([ + { + op: "update", + name: "--spacing-size-1", + type: "spacing", + value: "0.375rem", + description: "cssforge: spacing.custom.size.1", + }, + { op: "delete", name: "--spacing-size-2" }, + ]); + expect(paper.value("--spacing-size-1")).toEqual("0.375rem"); + expect(paper.value("--spacing-size-2")).toBeUndefined(); +}); + +test("fetch - a value the remote stores in another form is not a change", async () => { + paper.store = (value) => value.replace("oklch(60% 0.2 250)", "oklch(60.0% 0.200 250)"); + await using session = await pushedSession(); + + const report = await expectValue(session.call(syncFetch, {})); + + expect(report.operations).toEqual([]); + expect(report.inbox).toEqual([]); +}); + +test("inbox - a value edited on the remote waits until overwrite gives the configuration value back", async () => { + await using session = await pushedSession(); + const edited = paper.tokens.find((token) => token.name === "--spacing-size-1"); + if (edited) edited.value = "12px"; + + const held = await expectValue(session.call(syncPush, {})); + + expect(held.applied).toEqual([]); + expect(held.inbox).toEqual([ + { + id: "spacing-size-1", + kind: "edited", + name: "--spacing-size-1", + type: "spacing", + remoteValue: "12px", + localValue: "0.25rem", + actions: ["overwrite"], + }, + ]); + expect(paper.value("--spacing-size-1")).toEqual("12px"); + + await expectValue(session.call(syncInboxOverwrite, { item: "spacing-size-1" })); + const restored = await expectValue(session.call(syncPush, {})); + + expect(paper.value("--spacing-size-1")).toEqual("0.25rem"); + expect(restored.inbox).toEqual([]); +}); + +test("inbox - a token the remote created is deleted by the push after a reject", async () => { + await using session = await pushedSession(); + paper.tokens.push({ + name: "--brand-accent", + type: "color", + value: "oklch(70% 0.2 30)", + }); + + const fetched = await expectValue(session.call(syncFetch, {})); + expect(fetched.inbox).toEqual([ + { + id: "brand-accent", + kind: "new", + name: "--brand-accent", + type: "color", + remoteValue: "oklch(70% 0.2 30)", + actions: ["adopt", "reject"], + }, + ]); + + const decided = await expectValue( + session.call(syncInboxReject, { item: "brand-accent" }), + ); + expect(decided.callsUsed).toEqual(0); + expect(decided.skipped.map((token) => token.name)).toEqual([ + "--palette-brand-600", + "--theme-dark-surface-accent", + "--motion-duration-ui-press", + ]); + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied.map(({ operation }) => operation)).toEqual([ + { op: "delete", name: "--brand-accent" }, + ]); + expect(paper.value("--brand-accent")).toBeUndefined(); + expect(report.inbox).toEqual([]); +}); + +test("inbox - adopt renames a token the remote created to the name the configuration gives it", async () => { + await using session = await pushedSession(); + paper.tokens.push({ + name: "--brand-accent", + type: "color", + value: "oklch(70% 0.2 30)", + }); + await expectValue(session.call(syncFetch, {})); + + const early = await session.call(syncInboxAdopt, { + item: "brand-accent", + path: "palette.brand.accent", + }); + expect(early.ok).toEqual(false); + if (!early.ok) expect(early.error._tag).toEqual("InvalidDecision"); + + await writeConfig(withAccent("oklch(70% 0.2 30)")); + await expectValue( + session.call(syncInboxAdopt, { item: "brand-accent", path: "palette.brand.accent" }), + ); + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied.map(({ operation }) => operation)).toEqual([ + { op: "rename", from: "--brand-accent", to: "--palette-brand-accent" }, + ]); + expect(paper.value("--palette-brand-accent")).toEqual("oklch(70% 0.2 30)"); + expect(paper.value("--brand-accent")).toBeUndefined(); + + const after = await expectValue(session.call(syncPush, {})); + expect(after.applied).toEqual([]); + expect(after.inbox).toEqual([]); +}); + +test("push - an operation the remote refuses is reported and sent again at the next push", async () => { + await using session = openSession(); + await expectValue(session.call(syncRemoteAdd, { file: "F1" })); + paper.refuse.add("--spacing-size-2"); + + const first = await expectValue(session.call(syncPush, {})); + + expect(first.applied.find(({ ok }) => !ok)).toEqual({ + operation: { + op: "create", + name: "--spacing-size-2", + type: "spacing", + value: "0.5rem", + description: "cssforge: spacing.custom.size.2", + }, + ok: false, + message: "Refused.", + }); + expect(first.operations.map((operation) => operation.op)).toEqual(["create"]); + + paper.refuse.clear(); + const second = await expectValue(session.call(syncPush, {})); + + expect(second.applied.map(({ operation, ok }) => [operation.op, ok])).toEqual([ + ["create", true], + ]); + expect(paper.value("--spacing-size-2")).toEqual("0.5rem"); +}); + +test("plan - fails with RemoteNotConfigured before remote add, and NotFetched before a fetch", async () => { + await using session = openSession(); + + const unbound = await session.call(syncPlan, {}); + expect(unbound.ok ? undefined : unbound.error._tag).toEqual("RemoteNotConfigured"); + + await expectValue(session.call(syncRemoteAdd, { file: "F1" })); + const unread = await session.call(syncPlan, {}); + expect(unread.ok ? undefined : unread.error._tag).toEqual("NotFetched"); +}); + +test("remote add - binding the same file keeps the sync state, binding another file starts again", async () => { + await using session = await pushedSession(); + + await expectValue(session.call(syncRemoteAdd, { file: "F1" })); + const kept = await expectValue(session.call(syncPlan, {})); + expect(kept.operations).toEqual([]); + + await expectValue(session.call(syncRemoteAdd, { file: "F2" })); + const restarted = await session.call(syncPlan, {}); + expect(restarted.ok ? undefined : restarted.error._tag).toEqual("NotFetched"); +}); + +test("cli - the sync aliases run their capabilities and give failures as JSON", () => { + const cliPath = fileURLToPath(new URL("../src/cli.ts", import.meta.url)); + + const plan = spawnSync(process.execPath, [cliPath, "plan", "--agent"], { + cwd: projectDir, + encoding: "utf8", + env: childEnv, + }); + + expect(plan.status).toEqual(1); + expect(JSON.parse(plan.stdout)).toMatchObject({ _tag: "RemoteNotConfigured" }); +}); + +test("push - a pushed token whose new value has no place on Paper keeps its Paper copy", async () => { + await using session = await pushedSession(); + await writeConfig({ + ...baseConfig, + colors: { + ...baseConfig.colors, + palette: { + value: { + brand: { + 400: "oklch(50% 0.2 250)", + 500: { mix: { from: "palette.brand.400", with: "black", amount: 10 } }, + }, + }, + }, + }, + }); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied.map(({ operation }) => operation.op)).toEqual(["create"]); + expect(report.skipped.map((token) => token.name)).toContain("--palette-brand-500"); + expect(paper.value("--palette-brand-500")).toEqual("oklch(60% 0.2 250)"); + expect(paper.value("--theme-light-surface-accent")).toEqual("var(--palette-brand-500)"); +}); + +test("inbox - two remote tokens cannot be adopted as the same configuration token", async () => { + await using session = await pushedSession(); + paper.tokens.push( + { name: "--brand-accent", type: "color", value: "oklch(70% 0.2 30)" }, + { name: "--accent", type: "color", value: "oklch(70% 0.2 30)" }, + ); + await expectValue(session.call(syncFetch, {})); + await writeConfig(withAccent("oklch(70% 0.2 30)")); + await expectValue( + session.call(syncInboxAdopt, { item: "brand-accent", path: "palette.brand.accent" }), + ); + + const second = await session.call(syncInboxAdopt, { + item: "accent", + path: "palette.brand.accent", + }); + + expect(second.ok ? undefined : second.error._tag).toEqual("InvalidDecision"); +}); + +test("push - tokens the remote accepted stay owned when the read-back after the push fails", async () => { + await using session = openSession(); + await expectValue(session.call(syncRemoteAdd, { file: "F1" })); + paper.readsBeforeFailure = 1; + + const failed = await session.call(syncPush, {}); + expect(failed.ok ? undefined : failed.error._tag).toEqual("RemoteUnavailable"); + expect(paper.tokens.map((token) => token.name)).toHaveLength(4); + + paper.readsBeforeFailure = Number.POSITIVE_INFINITY; + const next = await expectValue(session.call(syncPush, {})); + + expect(next.applied).toEqual([]); + expect(next.inbox).toEqual([]); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 699d64d..3de83cf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -288,8 +288,8 @@ importers: packages/cssforge: dependencies: '@acid-cat/core-ts': - specifier: 0.13.0 - version: 0.13.0 + specifier: 0.15.0 + version: 0.15.0 chokidar: specifier: 4.0.3 version: 4.0.3 @@ -304,8 +304,8 @@ importers: version: 4.6.7 devDependencies: '@acid-cat/cli': - specifier: 0.13.0 - version: 0.13.0(redis@6.3.1) + specifier: 0.15.0 + version: 0.15.0(redis@6.3.1) '@biomejs/biome': specifier: 2.4.2 version: 2.4.2 @@ -377,12 +377,12 @@ packages: resolution: {integrity: sha512-fNdBOb3MgDz/1UCIoeY4wDuGbp+/3s5y6UrsyfMabECbh/CVycj7Er33JXqSxRwxrRKXcGE1Jipuq/1mODInsQ==} engines: {node: '>=11'} - '@acid-cat/catalog@0.13.0': - resolution: {integrity: sha512-KD67iK20urO4DMES5GaMDdd+KPzFQASiiEijfKyKWCM7JxmWm54Q9b5en2j57TgrnxXZ5cQAACRT5BTDM8WZjw==} + '@acid-cat/catalog@0.15.0': + resolution: {integrity: sha512-O3Nt8YaJTaCK2tqMyLloZDEdHz1qJw6tNAJSCvwEcH8cjuN/re7AJ6r5GgBLlu1G9R5+DW8okW2BwCYgWEsxwA==} engines: {node: '>=24'} - '@acid-cat/cli@0.13.0': - resolution: {integrity: sha512-2jAo9UazEbb4vHGX3A0PIFIsLX3NxXuqVtfokOThrvGCAM7toKhXrDz5myfjJp2oHSkN3FPqLiipy/dM3xEu7w==} + '@acid-cat/cli@0.15.0': + resolution: {integrity: sha512-sGEu2ejkuscyefaKQXFjlFYDVctEnx45DcxAF/02ElnWvHkytsfblxJCjjRtE6DnPKHH8ZMwEbgH8DH5ZaV4uQ==} engines: {node: '>=24'} hasBin: true peerDependencies: @@ -391,16 +391,16 @@ packages: playwright: optional: true - '@acid-cat/core-ts@0.13.0': - resolution: {integrity: sha512-Vg7yHQQc9I+0oKSSAvScdgQLXCzYBDeiWZB77xrzN+AeD3w+cwvNFYtC7eON1umgmMCbV0pwCEa9g8QbQvvs+w==} + '@acid-cat/core-ts@0.15.0': + resolution: {integrity: sha512-dZzqijq6TVKDdRa5tgImyhQeKeFmcpuODb2wEzulSaUO30SF4JbF0mUtgrQptyJoTpzlEErrqbDF/KVj8dvFRA==} engines: {node: '>=24'} - '@acid-cat/mcp-handshake@0.13.0': - resolution: {integrity: sha512-F9ddrvktaJPNFK5MmLfilcn0RZYeronzrgw9FEzj99QBGJlT/zGr7T+oDAk1uPvbJso7nklAF07lRalh3xpuQQ==} + '@acid-cat/mcp-handshake@0.15.0': + resolution: {integrity: sha512-O+zuySXjrUF9kuYEV7Sqebzvef9PMa8dXD11D5B7aQPU+D5wvRYVLH15Ehcbl1SnkQLHVbe8NHtR+Cb7op59gw==} engines: {node: '>=24'} - '@acid-cat/spec-ts@0.13.0': - resolution: {integrity: sha512-4N2eDx+3YIR4L3gpjHLeNsmrcvO3uwgLNBTSNteuualoAq+Z/TBFKnbpweUgZZAqqDHEYYrrblIdut+mzQSBJw==} + '@acid-cat/spec-ts@0.15.0': + resolution: {integrity: sha512-cv9U8JuI059xSJuvk4vvZZv41m7VPDWnhTTzK+fmw0Pz5qurDgaHIeUUunlFbCvp08XL+9P0Fm2CLomL1KC9hg==} engines: {node: '>=24'} '@algolia/abtesting@1.15.0': @@ -7685,12 +7685,12 @@ snapshots: js-yaml: 4.3.1 section-matter: 1.0.0 - '@acid-cat/catalog@0.13.0': {} + '@acid-cat/catalog@0.15.0': {} - '@acid-cat/cli@0.13.0(redis@6.3.1)': + '@acid-cat/cli@0.15.0(redis@6.3.1)': dependencies: - '@acid-cat/catalog': 0.13.0 - '@acid-cat/spec-ts': 0.13.0 + '@acid-cat/catalog': 0.15.0 + '@acid-cat/spec-ts': 0.15.0 '@effect/platform-node': 4.1.4(effect@4.1.4)(redis@6.3.1) '@effect/platform-node-shared': 4.1.4(effect@4.1.4) '@modelcontextprotocol/client': 2.4.0 @@ -7701,17 +7701,17 @@ snapshots: - redis - utf-8-validate - '@acid-cat/core-ts@0.13.0': + '@acid-cat/core-ts@0.15.0': dependencies: - '@acid-cat/catalog': 0.13.0 - '@acid-cat/mcp-handshake': 0.13.0 - '@acid-cat/spec-ts': 0.13.0 + '@acid-cat/catalog': 0.15.0 + '@acid-cat/mcp-handshake': 0.15.0 + '@acid-cat/spec-ts': 0.15.0 - '@acid-cat/mcp-handshake@0.13.0': + '@acid-cat/mcp-handshake@0.15.0': dependencies: - '@acid-cat/spec-ts': 0.13.0 + '@acid-cat/spec-ts': 0.15.0 - '@acid-cat/spec-ts@0.13.0': {} + '@acid-cat/spec-ts@0.15.0': {} '@algolia/abtesting@1.15.0': dependencies: diff --git a/skills/cssforge/references/cli-reference.md b/skills/cssforge/references/cli-reference.md index ae265b0..c1552ba 100644 --- a/skills/cssforge/references/cli-reference.md +++ b/skills/cssforge/references/cli-reference.md @@ -21,9 +21,41 @@ On a terminal, each command writes text for a person. For a script, in CI or for - `cssforge --watch [flags]` (`--watch` first): build now and after each change of the config or a local module it imports. One JSON line per build: `{ data: { ok: true, files, … } }` or `{ data: { ok: false, failure } }`. Exits with `130` when interrupted. -- `cssforge mcp`: serve the same capabilities as MCP tools through stdio. +- `cssforge mcp`: serve the same capabilities as MCP tools through stdio. `sync.push` and + `tokens.build` are marked destructive; `sync.plan`, `sync.inbox.list`, `tokens.generate` + and `config.check` read only. - `cssforge list`: every command with its flags. +## Token sync + +Sync keeps the tokens of a design file (Paper, through `paper-design mcp`) in sync with the +config. The config is the source of truth; what the file changes waits in an inbox. The +capabilities are in `packages/cssforge/src/sync/capabilities.ts`, the three-way plan in +`packages/cssforge/src/sync/plan.ts`, and the Paper mapping in `packages/cssforge/src/sync/paper.ts`. +State: `.cssforge/sync/.json` (commit it). Every command takes `--remote` (default `paper`). + +- `cssforge remote add --file [--name] [--kind paper]` (`sync remote add`): bind the file. 1 request. +- `cssforge fetch` (`sync fetch`): read the file, record it, report the plan. 1 request. +- `cssforge plan` (`sync plan`): the plan against the last fetch. No request. +- `cssforge push [--dry-run]` (`sync push`): read, send the plan, read back. 1 to 4 requests. +- `cssforge inbox` (`sync inbox list`): the items of the last fetch. No request. +- `cssforge inbox adopt --item --path `: a `new` item becomes the config token at + the path (add it to the config first). The next push renames it in the file. +- `cssforge inbox reject --item `: the next push deletes a `new` item from the file. Paper + replaces each use of a deleted token with its last value; a renamed token keeps its uses. +- `cssforge inbox overwrite --item `: the next push writes the config value for an `edited`, + `deleted` or `collision` item. To keep the file's value, change the config instead. + +Results: `{ remote, file, fetchedAt, operations, inbox, skipped, callsUsed }`, and `applied` for +`push`. An item id is the token name without `--`. A token path is the path in each pushed token's +description (`cssforge: palette.brand.500`). Failure tags: `RemoteNotConfigured`, `InvalidState`, +`RemoteUnavailable`, `RemoteFailed`, `NotFetched`, `UnknownItem`, `InvalidDecision`, +`UnknownKind`. Paper's free plan limits MCP calls: prefer `plan` and `inbox` (no request) after +one `fetch`. + +Agent loop: `fetch` → read `inbox` → edit the config → `inbox adopt|reject|overwrite` → +`plan` → `push`. + ## Flags - `--config`: config path (default `./cssforge.config.ts`) From 54dcabc26cfb6741cdf0a72dc5626198ed7b5e20 Mon Sep 17 00:00:00 2001 From: Hebilicious Date: Thu, 19 Nov 2026 09:32:36 +0700 Subject: [PATCH 2/3] refactor(sync): drop the sync aliases for the sync namespace Every sync command already has a path under `sync` from its capability id: `cssforge sync push`, `cssforge sync inbox adopt`. The top-level aliases (`push`, `plan`, `inbox`, ...) put them beside `build` and `check`, where they do not say what they act on. --- .changeset/paper-token-sync.md | 4 +- README.md | 26 ++++---- packages/cssforge/README.md | 26 ++++---- packages/cssforge/cssforge.acidcat.json | 66 +++++++-------------- packages/cssforge/src/capabilities.ts | 20 +------ packages/cssforge/src/sync/capabilities.ts | 26 ++++---- packages/cssforge/src/sync/state.ts | 2 +- packages/cssforge/tests/sync.test.ts | 4 +- skills/cssforge/references/cli-reference.md | 24 ++++---- 9 files changed, 78 insertions(+), 120 deletions(-) diff --git a/.changeset/paper-token-sync.md b/.changeset/paper-token-sync.md index 53e0361..ee35e61 100644 --- a/.changeset/paper-token-sync.md +++ b/.changeset/paper-token-sync.md @@ -4,8 +4,8 @@ Sync the tokens of a design tool with the configuration, starting with Paper. -- `cssforge remote add --file ` binds a Paper file. `cssforge fetch`, `cssforge plan` and `cssforge push` read the file, show the plan and send it: create, update and delete the tokens that the configuration generates. -- What designers change in the file waits in an inbox: `cssforge inbox`. Settle a new token with `cssforge inbox adopt` (after you add it to the configuration) or `cssforge inbox reject`, and a changed or deleted token with `cssforge inbox overwrite`. +- `cssforge sync remote add --file ` binds a Paper file. `cssforge sync fetch`, `cssforge sync plan` and `cssforge sync push` read the file, show the plan and send it: create, update and delete the tokens that the configuration generates. +- What designers change in the file waits in an inbox: `cssforge sync inbox list`. Settle a new token with `cssforge sync inbox adopt` (after you add it to the configuration) or `cssforge sync inbox reject`, and a changed or deleted token with `cssforge sync inbox overwrite`. - The state is in `.cssforge/sync/.json`. Commit it. - Each result lists the tokens that Paper has no place for, with the reason, and the number of requests made to Paper. - The commands are also MCP tools of `cssforge mcp` and typed calls of `@hebilicious/cssforge/capabilities`. `sync.push` and `tokens.build` are marked destructive for MCP clients, and the read-only tools are marked read-only. diff --git a/README.md b/README.md index 86d5da1..77eebd7 100644 --- a/README.md +++ b/README.md @@ -2228,37 +2228,37 @@ MCP server that `cssforge` talks to (`paper-design mcp`). ```bash # Bind a Paper file to the configuration (one request). Writes .cssforge/sync/paper.json. -cssforge remote add --file https://app.paper.design/file/ +cssforge sync remote add --file https://app.paper.design/file/ # Read the file and show the plan, without changing it (one request) -cssforge fetch +cssforge sync fetch # Show the plan again after a change of the config or a decision (no request) -cssforge plan +cssforge sync plan # Send the plan: create, update and delete tokens, and carry out the decisions -cssforge push -cssforge push --dry-run +cssforge sync push +cssforge sync push --dry-run # The changes designers made in the file -cssforge inbox +cssforge sync inbox list # A token a designer created: add it to the config first, then adopt it under that path. # The path is the token path, as each pushed token shows it in its description # (`cssforge: palette.brand.accent`). The next push renames the token in the file to the # name the config generates. -cssforge inbox adopt --item brand-accent --path palette.brand.accent +cssforge sync inbox adopt --item brand-accent --path palette.brand.accent # Or delete it from the file at the next push -cssforge inbox reject --item brand-accent +cssforge sync inbox reject --item brand-accent # A token of the config that a designer changed or deleted: the next push writes the # config's value again. To keep the designer's value, change the config instead. -cssforge inbox overwrite --item spacing-size-1 +cssforge sync inbox overwrite --item spacing-size-1 ``` Commit `.cssforge/sync/.json`: it holds the file id, the tokens as they were after the last push, and the decisions, so everyone who syncs shares the same base. `--remote ` -selects another remote (the default is `paper`), and `remote add --name ` binds one. +selects another remote (the default is `paper`), and `sync remote add --name ` binds one. | Inbox item | What happened in the file | Decisions | | --- | --- | --- | @@ -2267,12 +2267,12 @@ selects another remote (the default is `paper`), and `remote add --name ` | `deleted` | A designer deleted a config token | `overwrite` | | `collision` | The file has a token with the name of a new config token | `overwrite` | -When `push` renames a token (after `inbox adopt`), the designs that use it keep using it under -the new name. When it deletes a token (after `inbox reject`, or because the token left the +When `sync push` renames a token (after `sync inbox adopt`), the designs that use it keep using it under +the new name. When it deletes a token (after `sync inbox reject`, or because the token left the config), Paper replaces each use with the token's last value, so designs keep their look but lose the link to the token. -An item without a decision blocks only its own token: `push` sends every other change. A +An item without a decision blocks only its own token: `sync push` sends every other change. A change that the file refuses stays in the plan, and the next push sends it again. Each result has `callsUsed`, the number of requests made to the design tool, because Paper's free plan limits MCP tool calls. A push reads the file once, writes at most twice, and reads the stored diff --git a/packages/cssforge/README.md b/packages/cssforge/README.md index 86d5da1..77eebd7 100644 --- a/packages/cssforge/README.md +++ b/packages/cssforge/README.md @@ -2228,37 +2228,37 @@ MCP server that `cssforge` talks to (`paper-design mcp`). ```bash # Bind a Paper file to the configuration (one request). Writes .cssforge/sync/paper.json. -cssforge remote add --file https://app.paper.design/file/ +cssforge sync remote add --file https://app.paper.design/file/ # Read the file and show the plan, without changing it (one request) -cssforge fetch +cssforge sync fetch # Show the plan again after a change of the config or a decision (no request) -cssforge plan +cssforge sync plan # Send the plan: create, update and delete tokens, and carry out the decisions -cssforge push -cssforge push --dry-run +cssforge sync push +cssforge sync push --dry-run # The changes designers made in the file -cssforge inbox +cssforge sync inbox list # A token a designer created: add it to the config first, then adopt it under that path. # The path is the token path, as each pushed token shows it in its description # (`cssforge: palette.brand.accent`). The next push renames the token in the file to the # name the config generates. -cssforge inbox adopt --item brand-accent --path palette.brand.accent +cssforge sync inbox adopt --item brand-accent --path palette.brand.accent # Or delete it from the file at the next push -cssforge inbox reject --item brand-accent +cssforge sync inbox reject --item brand-accent # A token of the config that a designer changed or deleted: the next push writes the # config's value again. To keep the designer's value, change the config instead. -cssforge inbox overwrite --item spacing-size-1 +cssforge sync inbox overwrite --item spacing-size-1 ``` Commit `.cssforge/sync/.json`: it holds the file id, the tokens as they were after the last push, and the decisions, so everyone who syncs shares the same base. `--remote ` -selects another remote (the default is `paper`), and `remote add --name ` binds one. +selects another remote (the default is `paper`), and `sync remote add --name ` binds one. | Inbox item | What happened in the file | Decisions | | --- | --- | --- | @@ -2267,12 +2267,12 @@ selects another remote (the default is `paper`), and `remote add --name ` | `deleted` | A designer deleted a config token | `overwrite` | | `collision` | The file has a token with the name of a new config token | `overwrite` | -When `push` renames a token (after `inbox adopt`), the designs that use it keep using it under -the new name. When it deletes a token (after `inbox reject`, or because the token left the +When `sync push` renames a token (after `sync inbox adopt`), the designs that use it keep using it under +the new name. When it deletes a token (after `sync inbox reject`, or because the token left the config), Paper replaces each use with the token's last value, so designs keep their look but lose the link to the token. -An item without a decision blocks only its own token: `push` sends every other change. A +An item without a decision blocks only its own token: `sync push` sends every other change. A change that the file refuses stays in the plan, and the next push sends it again. Each result has `callsUsed`, the number of requests made to the design tool, because Paper's free plan limits MCP tool calls. A push reads the file once, writes at most twice, and reads the stored diff --git a/packages/cssforge/cssforge.acidcat.json b/packages/cssforge/cssforge.acidcat.json index 65e453f..fec1512 100644 --- a/packages/cssforge/cssforge.acidcat.json +++ b/packages/cssforge/cssforge.acidcat.json @@ -20,32 +20,8 @@ "check": { "capability": "config.check" }, - "fetch": { - "capability": "sync.fetch" - }, "generate": { "capability": "tokens.generate" - }, - "inbox": { - "capability": "sync.inbox.list" - }, - "inbox adopt": { - "capability": "sync.inbox.adopt" - }, - "inbox overwrite": { - "capability": "sync.inbox.overwrite" - }, - "inbox reject": { - "capability": "sync.inbox.reject" - }, - "plan": { - "capability": "sync.plan" - }, - "push": { - "capability": "sync.push" - }, - "remote add": { - "capability": "sync.remote.add" } }, "default": "build" @@ -223,7 +199,7 @@ }, "remote": { "default": "paper", - "description": "The name of the remote, as `remote add --name` gave it.", + "description": "The name of the remote, as `sync remote add --name` gave it.", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", "type": "string" }, @@ -557,7 +533,7 @@ "properties": { "_tag": { "const": "RemoteNotConfigured", - "description": "The remote has no state file: add it with `remote add`.", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", "type": "string" }, "message": { @@ -628,7 +604,7 @@ }, "remote": { "default": "paper", - "description": "The name of the remote, as `remote add --name` gave it.", + "description": "The name of the remote, as `sync remote add --name` gave it.", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", "type": "string" }, @@ -899,7 +875,7 @@ "properties": { "_tag": { "const": "NotFetched", - "description": "The remote has not been read yet: run `fetch` first.", + "description": "The remote has not been read yet: run `cssforge sync fetch` first.", "type": "string" }, "message": { @@ -921,7 +897,7 @@ "properties": { "_tag": { "const": "RemoteNotConfigured", - "description": "The remote has no state file: add it with `remote add`.", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", "type": "string" }, "message": { @@ -965,7 +941,7 @@ "idempotent": true }, "sync.inbox.list": { - "description": "List the inbox against the last fetch, with no request to the remote: the tokens the remote created, changed or deleted, each with the decisions that settle it. Settle a new token with `inbox adopt` (after adding it to the configuration) or `inbox reject`, and the others with `inbox overwrite`.", + "description": "List the inbox against the last fetch, with no request to the remote: the tokens the remote created, changed or deleted, each with the decisions that settle it. Settle a new token with `sync inbox adopt` (after adding it to the configuration) or `sync inbox reject`, and the others with `sync inbox overwrite`.", "audience": [ "cli", "mcp", @@ -982,7 +958,7 @@ }, "remote": { "default": "paper", - "description": "The name of the remote, as `remote add --name` gave it.", + "description": "The name of the remote, as `sync remote add --name` gave it.", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", "type": "string" }, @@ -1294,7 +1270,7 @@ "properties": { "_tag": { "const": "NotFetched", - "description": "The remote has not been read yet: run `fetch` first.", + "description": "The remote has not been read yet: run `cssforge sync fetch` first.", "type": "string" }, "message": { @@ -1316,7 +1292,7 @@ "properties": { "_tag": { "const": "RemoteNotConfigured", - "description": "The remote has no state file: add it with `remote add`.", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", "type": "string" }, "message": { @@ -1359,7 +1335,7 @@ }, "remote": { "default": "paper", - "description": "The name of the remote, as `remote add --name` gave it.", + "description": "The name of the remote, as `sync remote add --name` gave it.", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", "type": "string" }, @@ -1629,7 +1605,7 @@ "properties": { "_tag": { "const": "NotFetched", - "description": "The remote has not been read yet: run `fetch` first.", + "description": "The remote has not been read yet: run `cssforge sync fetch` first.", "type": "string" }, "message": { @@ -1651,7 +1627,7 @@ "properties": { "_tag": { "const": "RemoteNotConfigured", - "description": "The remote has no state file: add it with `remote add`.", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", "type": "string" }, "message": { @@ -1717,7 +1693,7 @@ }, "remote": { "default": "paper", - "description": "The name of the remote, as `remote add --name` gave it.", + "description": "The name of the remote, as `sync remote add --name` gave it.", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", "type": "string" }, @@ -1987,7 +1963,7 @@ "properties": { "_tag": { "const": "NotFetched", - "description": "The remote has not been read yet: run `fetch` first.", + "description": "The remote has not been read yet: run `cssforge sync fetch` first.", "type": "string" }, "message": { @@ -2009,7 +1985,7 @@ "properties": { "_tag": { "const": "RemoteNotConfigured", - "description": "The remote has no state file: add it with `remote add`.", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", "type": "string" }, "message": { @@ -2070,7 +2046,7 @@ }, "remote": { "default": "paper", - "description": "The name of the remote, as `remote add --name` gave it.", + "description": "The name of the remote, as `sync remote add --name` gave it.", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", "type": "string" }, @@ -2382,7 +2358,7 @@ "properties": { "_tag": { "const": "NotFetched", - "description": "The remote has not been read yet: run `fetch` first.", + "description": "The remote has not been read yet: run `cssforge sync fetch` first.", "type": "string" }, "message": { @@ -2404,7 +2380,7 @@ "properties": { "_tag": { "const": "RemoteNotConfigured", - "description": "The remote has no state file: add it with `remote add`.", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", "type": "string" }, "message": { @@ -2447,7 +2423,7 @@ }, "remote": { "default": "paper", - "description": "The name of the remote, as `remote add --name` gave it.", + "description": "The name of the remote, as `sync remote add --name` gave it.", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", "type": "string" }, @@ -2903,7 +2879,7 @@ "properties": { "_tag": { "const": "RemoteNotConfigured", - "description": "The remote has no state file: add it with `remote add`.", + "description": "The remote has no state file: add it with `cssforge sync remote add`.", "type": "string" }, "message": { @@ -2969,7 +2945,7 @@ }, "name": { "default": "paper", - "description": "The name of the remote, as `remote add --name` gave it.", + "description": "The name of the remote, as `sync remote add --name` gave it.", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", "type": "string" }, diff --git a/packages/cssforge/src/capabilities.ts b/packages/cssforge/src/capabilities.ts index 3223de2..974d53a 100644 --- a/packages/cssforge/src/capabilities.ts +++ b/packages/cssforge/src/capabilities.ts @@ -65,17 +65,7 @@ import { } from "./forge.ts"; import { type ColorFormat, diagnosticCodes } from "./lib.ts"; import { supportedColorFormats } from "./modules/colors.ts"; -import { - syncCapabilities, - syncFetch, - syncInboxAdopt, - syncInboxList, - syncInboxOverwrite, - syncInboxReject, - syncPlan, - syncPush, - syncRemoteAdd, -} from "./sync/capabilities.ts"; +import { syncCapabilities } from "./sync/capabilities.ts"; import type { RemoteAdapter } from "./sync/remote.ts"; /** @@ -496,14 +486,6 @@ export const cssforge: App = defineApp({ generate: cliAlias(tokensGenerate), check: cliAlias(configCheck), "--watch": cliAlias(tokensBuilt), - "remote add": cliAlias(syncRemoteAdd), - fetch: cliAlias(syncFetch), - plan: cliAlias(syncPlan), - push: cliAlias(syncPush), - inbox: cliAlias(syncInboxList), - "inbox adopt": cliAlias(syncInboxAdopt), - "inbox reject": cliAlias(syncInboxReject), - "inbox overwrite": cliAlias(syncInboxOverwrite), }, }, }, diff --git a/packages/cssforge/src/sync/capabilities.ts b/packages/cssforge/src/sync/capabilities.ts index b146e29..80f3d1a 100644 --- a/packages/cssforge/src/sync/capabilities.ts +++ b/packages/cssforge/src/sync/capabilities.ts @@ -166,7 +166,7 @@ const remoteSchema = z .string() .regex(REMOTE_NAME, "A remote name is lowercase words joined by hyphens, e.g. paper.") .default("paper") - .describe("The name of the remote, as `remote add --name` gave it."); + .describe("The name of the remote, as `sync remote add --name` gave it."); const syncShape = { config: z @@ -323,7 +323,7 @@ const readFailures = { ), RemoteNotConfigured: failureSchema( "RemoteNotConfigured", - "The remote has no state file: add it with `remote add`.", + "The remote has no state file: add it with `cssforge sync remote add`.", ), InvalidState: failureSchema( "InvalidState", @@ -343,7 +343,7 @@ const remoteFailures = { const notFetched = { NotFetched: failureSchema( "NotFetched", - "The remote has not been read yet: run `fetch` first.", + "The remote has not been read yet: run `cssforge sync fetch` first.", ), }; const decisionFailures = { @@ -473,7 +473,7 @@ const fetchedOf = (state: SyncState, remote: string) => { if (state.fetched === null) { throw new SyncError( "NotFetched", - `The remote "${remote}" has not been read yet. Run \`cssforge fetch --remote ${remote}\`.`, + `The remote "${remote}" has not been read yet. Run \`cssforge sync fetch --remote ${remote}\`.`, ); } return state.fetched; @@ -540,7 +540,7 @@ const planFromFetch = (input: SyncInput, context: ForgeContext) => const capability = capabilitiesFor(); const everyone = ["cli", "mcp", "library"]; -/** `cssforge remote add`: bind a remote file to the configuration. */ +/** `cssforge sync remote add`: bind a remote file to the configuration. */ export const syncRemoteAdd: Capability< ForgeContext, RemoteAddInput, @@ -595,7 +595,7 @@ export const syncRemoteAdd: Capability< }), }); -/** `cssforge fetch`: read the remote and report the plan. */ +/** `cssforge sync fetch`: read the remote and report the plan. */ export const syncFetch: Capability< ForgeContext, SyncInput, @@ -630,7 +630,7 @@ export const syncFetch: Capability< }), }); -/** `cssforge plan`: the plan against the last fetch, with no request. */ +/** `cssforge sync plan`: the plan against the last fetch, with no request. */ export const syncPlan: Capability< ForgeContext, SyncInput, @@ -651,7 +651,7 @@ export const syncPlan: Capability< run: (input, { context }) => planFromFetch(input, context), }); -/** `cssforge push`: read the remote, then send the plan. */ +/** `cssforge sync push`: read the remote, then send the plan. */ export const syncPush: Capability< ForgeContext, PushInput, @@ -760,7 +760,7 @@ function settle( }; } -/** `cssforge inbox`: the items that wait for a decision. */ +/** `cssforge sync inbox list`: the items that wait for a decision. */ export const syncInboxList: Capability< ForgeContext, SyncInput, @@ -772,7 +772,7 @@ export const syncInboxList: Capability< > = capability({ id: "sync.inbox.list", description: - "List the inbox against the last fetch, with no request to the remote: the tokens the remote created, changed or deleted, each with the decisions that settle it. Settle a new token with `inbox adopt` (after adding it to the configuration) or `inbox reject`, and the others with `inbox overwrite`.", + "List the inbox against the last fetch, with no request to the remote: the tokens the remote created, changed or deleted, each with the decisions that settle it. Settle a new token with `sync inbox adopt` (after adding it to the configuration) or `sync inbox reject`, and the others with `sync inbox overwrite`.", audience: everyone, readOnly: true, input: syncInput, @@ -822,7 +822,7 @@ async function decide( }; } -/** `cssforge inbox adopt`: make a new remote token a token of the configuration. */ +/** `cssforge sync inbox adopt`: make a new remote token a token of the configuration. */ export const syncInboxAdopt: Capability< ForgeContext, AdoptInput, @@ -886,7 +886,7 @@ export const syncInboxAdopt: Capability< ), }); -/** `cssforge inbox reject`: delete a new remote token at the next push. */ +/** `cssforge sync inbox reject`: delete a new remote token at the next push. */ export const syncInboxReject: Capability< ForgeContext, ItemInput, @@ -911,7 +911,7 @@ export const syncInboxReject: Capability< ), }); -/** `cssforge inbox overwrite`: give the value of the configuration back to the remote. */ +/** `cssforge sync inbox overwrite`: give the value of the configuration back to the remote. */ export const syncInboxOverwrite: Capability< ForgeContext, ItemInput, diff --git a/packages/cssforge/src/sync/state.ts b/packages/cssforge/src/sync/state.ts index 3684132..c48e495 100644 --- a/packages/cssforge/src/sync/state.ts +++ b/packages/cssforge/src/sync/state.ts @@ -95,7 +95,7 @@ export async function readState(root: string, remote: string): Promise\`.`, + `There is no remote "${remote}". Add it with \`cssforge sync remote add --name ${remote} --kind paper --file \`.`, path, ); } diff --git a/packages/cssforge/tests/sync.test.ts b/packages/cssforge/tests/sync.test.ts index edb519b..1a29835 100644 --- a/packages/cssforge/tests/sync.test.ts +++ b/packages/cssforge/tests/sync.test.ts @@ -474,10 +474,10 @@ test("remote add - binding the same file keeps the sync state, binding another f expect(restarted.ok ? undefined : restarted.error._tag).toEqual("NotFetched"); }); -test("cli - the sync aliases run their capabilities and give failures as JSON", () => { +test("cli - cssforge sync plan runs its capability and gives a failure as JSON", () => { const cliPath = fileURLToPath(new URL("../src/cli.ts", import.meta.url)); - const plan = spawnSync(process.execPath, [cliPath, "plan", "--agent"], { + const plan = spawnSync(process.execPath, [cliPath, "sync", "plan", "--agent"], { cwd: projectDir, encoding: "utf8", env: childEnv, diff --git a/skills/cssforge/references/cli-reference.md b/skills/cssforge/references/cli-reference.md index c1552ba..4a91304 100644 --- a/skills/cssforge/references/cli-reference.md +++ b/skills/cssforge/references/cli-reference.md @@ -34,27 +34,27 @@ capabilities are in `packages/cssforge/src/sync/capabilities.ts`, the three-way `packages/cssforge/src/sync/plan.ts`, and the Paper mapping in `packages/cssforge/src/sync/paper.ts`. State: `.cssforge/sync/.json` (commit it). Every command takes `--remote` (default `paper`). -- `cssforge remote add --file [--name] [--kind paper]` (`sync remote add`): bind the file. 1 request. -- `cssforge fetch` (`sync fetch`): read the file, record it, report the plan. 1 request. -- `cssforge plan` (`sync plan`): the plan against the last fetch. No request. -- `cssforge push [--dry-run]` (`sync push`): read, send the plan, read back. 1 to 4 requests. -- `cssforge inbox` (`sync inbox list`): the items of the last fetch. No request. -- `cssforge inbox adopt --item --path `: a `new` item becomes the config token at +- `cssforge sync remote add --file [--name] [--kind paper]`: bind the file. 1 request. +- `cssforge sync fetch`: read the file, record it, report the plan. 1 request. +- `cssforge sync plan`: the plan against the last fetch. No request. +- `cssforge sync push [--dry-run]`: read, send the plan, read back. 1 to 4 requests. +- `cssforge sync inbox list`: the items of the last fetch. No request. +- `cssforge sync inbox adopt --item --path `: a `new` item becomes the config token at the path (add it to the config first). The next push renames it in the file. -- `cssforge inbox reject --item `: the next push deletes a `new` item from the file. Paper +- `cssforge sync inbox reject --item `: the next push deletes a `new` item from the file. Paper replaces each use of a deleted token with its last value; a renamed token keeps its uses. -- `cssforge inbox overwrite --item `: the next push writes the config value for an `edited`, +- `cssforge sync inbox overwrite --item `: the next push writes the config value for an `edited`, `deleted` or `collision` item. To keep the file's value, change the config instead. Results: `{ remote, file, fetchedAt, operations, inbox, skipped, callsUsed }`, and `applied` for `push`. An item id is the token name without `--`. A token path is the path in each pushed token's description (`cssforge: palette.brand.500`). Failure tags: `RemoteNotConfigured`, `InvalidState`, `RemoteUnavailable`, `RemoteFailed`, `NotFetched`, `UnknownItem`, `InvalidDecision`, -`UnknownKind`. Paper's free plan limits MCP calls: prefer `plan` and `inbox` (no request) after -one `fetch`. +`UnknownKind`. Paper's free plan limits MCP calls: prefer `sync plan` and `sync inbox list` (no request) +after one `sync fetch`. -Agent loop: `fetch` → read `inbox` → edit the config → `inbox adopt|reject|overwrite` → -`plan` → `push`. +Agent loop: `sync fetch` → read `sync inbox list` → edit the config → +`sync inbox adopt|reject|overwrite` → `sync plan` → `sync push`. ## Flags From 5bdf1405971e1e2f0aeacda77face6402fda3cbd Mon Sep 17 00:00:00 2001 From: Hebilicious Date: Thu, 19 Nov 2026 10:05:01 +0700 Subject: [PATCH 3/3] refactor(sync): make the sync interface provider-neutral Prepare token sync for design tools beyond Paper, such as Figma. - Identity: a remote token has a key (Paper: its name; other tools: an id), a label and an optional custom property. The base records each token's remote key, operations address the remote by key, and decisions are bound to keys, so a renamed or relabelled token keeps its link. - Options: `sync remote add --options ` passes options to the adapter, which checks them before any request and resolves the target (file, modes, options). Paper takes none. - Modes: tokens carry a value per mode: `default` at :root, `light` and `dark` for values that depend on the color scheme (each with its own branch of every light-dark()), and the selector or at-rule of other scopes. The target lists the modes it holds; the rest are skipped with the mode. Paper holds only `default`. Scopes are now encoded so that a selector with a `|` stays whole. --- .changeset/paper-token-sync.md | 1 + README.md | 35 +- packages/cssforge/README.md | 35 +- packages/cssforge/cssforge.acidcat.json | 828 +++++++++++++++----- packages/cssforge/src/capabilities.ts | 5 +- packages/cssforge/src/lib.ts | 21 + packages/cssforge/src/modules/colors.ts | 4 +- packages/cssforge/src/sync/capabilities.ts | 332 +++++--- packages/cssforge/src/sync/modes.ts | 179 +++++ packages/cssforge/src/sync/paper.ts | 100 ++- packages/cssforge/src/sync/plan.ts | 321 +++++--- packages/cssforge/src/sync/remote.ts | 64 +- packages/cssforge/src/sync/state.ts | 58 +- packages/cssforge/tests/sync-paper.test.ts | 107 ++- packages/cssforge/tests/sync.test.ts | 628 +++++++++++---- skills/cssforge/references/cli-reference.md | 10 +- 16 files changed, 2091 insertions(+), 637 deletions(-) create mode 100644 packages/cssforge/src/sync/modes.ts diff --git a/.changeset/paper-token-sync.md b/.changeset/paper-token-sync.md index ee35e61..8065290 100644 --- a/.changeset/paper-token-sync.md +++ b/.changeset/paper-token-sync.md @@ -7,6 +7,7 @@ Sync the tokens of a design tool with the configuration, starting with Paper. - `cssforge sync remote add --file ` binds a Paper file. `cssforge sync fetch`, `cssforge sync plan` and `cssforge sync push` read the file, show the plan and send it: create, update and delete the tokens that the configuration generates. - What designers change in the file waits in an inbox: `cssforge sync inbox list`. Settle a new token with `cssforge sync inbox adopt` (after you add it to the configuration) or `cssforge sync inbox reject`, and a changed or deleted token with `cssforge sync inbox overwrite`. - The state is in `.cssforge/sync/.json`. Commit it. +- Each design tool is an adapter. Tokens have a value per mode (`default`, `light` and `dark` from `light-dark()`, or a selector such as `.dark`), a remote token has its own key, and `sync remote add --options` passes options to the adapter, so a tool with modes and ids, such as Figma, fits the same commands. Paper holds only the `default` mode. - Each result lists the tokens that Paper has no place for, with the reason, and the number of requests made to Paper. - The commands are also MCP tools of `cssforge mcp` and typed calls of `@hebilicious/cssforge/capabilities`. `sync.push` and `tokens.build` are marked destructive for MCP clients, and the read-only tools are marked read-only. - `@acid-cat/core-ts` is updated to 0.15.0. diff --git a/README.md b/README.md index 77eebd7..59a17fb 100644 --- a/README.md +++ b/README.md @@ -2224,7 +2224,8 @@ lets Musea attribute a `var(--token)` written in an art file back to its token. configuration is the source of truth: the tokens it generates are pushed to the file, and what designers change in the file waits in an inbox until you decide what to do with it. [Paper](https://paper.design) is the first supported design tool; its desktop app serves the -MCP server that `cssforge` talks to (`paper-design mcp`). +MCP server that `cssforge` talks to (`paper-design mcp`). Each design tool is an adapter +behind the same commands, so others (Figma) can follow. ```bash # Bind a Paper file to the configuration (one request). Writes .cssforge/sync/paper.json. @@ -2256,9 +2257,31 @@ cssforge sync inbox reject --item brand-accent cssforge sync inbox overwrite --item spacing-size-1 ``` -Commit `.cssforge/sync/.json`: it holds the file id, the tokens as they were after the -last push, and the decisions, so everyone who syncs shares the same base. `--remote ` -selects another remote (the default is `paper`), and `sync remote add --name ` binds one. +Commit `.cssforge/sync/.json`: it holds the target (the file, its modes and the +options), the tokens as they were after the last push with the key the design tool gave each +one, and the decisions, so everyone who syncs shares the same base. `--remote ` selects +another remote (the default is `paper`), and `sync remote add --name ` binds one. +`sync remote add --options '{"collection":"Tokens"}'` passes options to the kind of remote; +Paper takes none. + +### Modes + +A design tool can hold a value for each mode of a token, as a Figma collection does. Sync +gives each token one value per mode: + +| Token in the config | Mode | +| --- | --- | +| At `:root` | `default` | +| A `light-dark(light, dark)` value at `:root`, or a value built from one (a mix of a paired color) | `light` and `dark`, each with its own branch of every `light-dark()` | +| Under a selector or an at-rule, e.g. a theme with `selector: ".dark"` | The selector or at-rule: `.dark` | + +Tokens with the same custom property in several scopes (themes with `variantNameOnly`) are one +token with a value for each of its modes. The target says which modes it holds; a mode it does +not hold is listed in `skipped` with the mode. Paper holds only `default`. + +A token is identified by its custom property in the config and by its key in the design tool: +the name on Paper, an id on a tool that has ids. A designer who renames a token on such a tool +keeps its link to the config. | Inbox item | What happened in the file | Decisions | | --- | --- | --- | @@ -2285,8 +2308,8 @@ with the reason: | --- | --- | | Palette colors, spacing, fluid type sizes (`clamp()`), font weights | Color, spacing, font size and font weight tokens | | A token whose value is `var(--other)` | An alias of the other token, when both have the same type | -| Mixed colors (`color-mix()`) and paired themes (`light-dark()`) | Left out: Paper does not take these values | -| Tokens under a selector or an at-rule (themes with a `selector`) | Left out: Paper has no modes | +| Mixed colors (`color-mix()`) | Left out: Paper does not take these values | +| Paired themes (`light-dark()`) and tokens under a selector or an at-rule | Left out: Paper holds only the `default` mode | | The helper tokens of a `pow()` type scale | Left out: the `clamp()` scale is synced | | Motion, gradients and primitives without a Paper type | Left out | diff --git a/packages/cssforge/README.md b/packages/cssforge/README.md index 77eebd7..59a17fb 100644 --- a/packages/cssforge/README.md +++ b/packages/cssforge/README.md @@ -2224,7 +2224,8 @@ lets Musea attribute a `var(--token)` written in an art file back to its token. configuration is the source of truth: the tokens it generates are pushed to the file, and what designers change in the file waits in an inbox until you decide what to do with it. [Paper](https://paper.design) is the first supported design tool; its desktop app serves the -MCP server that `cssforge` talks to (`paper-design mcp`). +MCP server that `cssforge` talks to (`paper-design mcp`). Each design tool is an adapter +behind the same commands, so others (Figma) can follow. ```bash # Bind a Paper file to the configuration (one request). Writes .cssforge/sync/paper.json. @@ -2256,9 +2257,31 @@ cssforge sync inbox reject --item brand-accent cssforge sync inbox overwrite --item spacing-size-1 ``` -Commit `.cssforge/sync/.json`: it holds the file id, the tokens as they were after the -last push, and the decisions, so everyone who syncs shares the same base. `--remote ` -selects another remote (the default is `paper`), and `sync remote add --name ` binds one. +Commit `.cssforge/sync/.json`: it holds the target (the file, its modes and the +options), the tokens as they were after the last push with the key the design tool gave each +one, and the decisions, so everyone who syncs shares the same base. `--remote ` selects +another remote (the default is `paper`), and `sync remote add --name ` binds one. +`sync remote add --options '{"collection":"Tokens"}'` passes options to the kind of remote; +Paper takes none. + +### Modes + +A design tool can hold a value for each mode of a token, as a Figma collection does. Sync +gives each token one value per mode: + +| Token in the config | Mode | +| --- | --- | +| At `:root` | `default` | +| A `light-dark(light, dark)` value at `:root`, or a value built from one (a mix of a paired color) | `light` and `dark`, each with its own branch of every `light-dark()` | +| Under a selector or an at-rule, e.g. a theme with `selector: ".dark"` | The selector or at-rule: `.dark` | + +Tokens with the same custom property in several scopes (themes with `variantNameOnly`) are one +token with a value for each of its modes. The target says which modes it holds; a mode it does +not hold is listed in `skipped` with the mode. Paper holds only `default`. + +A token is identified by its custom property in the config and by its key in the design tool: +the name on Paper, an id on a tool that has ids. A designer who renames a token on such a tool +keeps its link to the config. | Inbox item | What happened in the file | Decisions | | --- | --- | --- | @@ -2285,8 +2308,8 @@ with the reason: | --- | --- | | Palette colors, spacing, fluid type sizes (`clamp()`), font weights | Color, spacing, font size and font weight tokens | | A token whose value is `var(--other)` | An alias of the other token, when both have the same type | -| Mixed colors (`color-mix()`) and paired themes (`light-dark()`) | Left out: Paper does not take these values | -| Tokens under a selector or an at-rule (themes with a `selector`) | Left out: Paper has no modes | +| Mixed colors (`color-mix()`) | Left out: Paper does not take these values | +| Paired themes (`light-dark()`) and tokens under a selector or an at-rule | Left out: Paper holds only the `default` mode | | The helper tokens of a `pow()` type scale | Left out: the `clamp()` scale is synced | | Motion, gradients and primitives without a Paper type | Left out | diff --git a/packages/cssforge/cssforge.acidcat.json b/packages/cssforge/cssforge.acidcat.json index fec1512..6193c8d 100644 --- a/packages/cssforge/cssforge.acidcat.json +++ b/packages/cssforge/cssforge.acidcat.json @@ -224,22 +224,6 @@ "description": "When the remote tokens were read, as an ISO 8601 time.", "type": "string" }, - "file": { - "additionalProperties": false, - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - }, - "required": [ - "id", - "name" - ], - "type": "object" - }, "inbox": { "items": { "additionalProperties": false, @@ -259,6 +243,10 @@ "id": { "type": "string" }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, "kind": { "enum": [ "new", @@ -268,17 +256,32 @@ ], "type": "string" }, - "localValue": { + "label": { + "description": "The name of the token on the remote.", "type": "string" }, - "name": { - "type": "string" + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "note": { "type": "string" }, - "remoteValue": { - "type": "string" + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "type": { "type": "string" @@ -287,7 +290,8 @@ "required": [ "id", "kind", - "name", + "key", + "label", "type", "actions" ], @@ -298,7 +302,7 @@ "operations": { "description": "The changes the next push sends, in order.", "items": { - "description": "A change to send to the remote.", + "description": "A change to send to the remote, which addresses a remote token by its key.", "oneOf": [ { "additionalProperties": false, @@ -316,15 +320,22 @@ "type": { "type": "string" }, - "value": { - "type": "string" + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" } }, "required": [ "op", "name", "type", - "value", + "values", "description" ], "type": "object" @@ -335,6 +346,9 @@ "description": { "type": "string" }, + "key": { + "type": "string" + }, "name": { "type": "string" }, @@ -345,15 +359,23 @@ "type": { "type": "string" }, - "value": { - "type": "string" + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" } }, "required": [ "op", + "key", "name", "type", - "value", + "values", "description" ], "type": "object" @@ -364,6 +386,9 @@ "from": { "type": "string" }, + "key": { + "type": "string" + }, "op": { "const": "rename", "type": "string" @@ -374,6 +399,7 @@ }, "required": [ "op", + "key", "from", "to" ], @@ -382,7 +408,10 @@ { "additionalProperties": false, "properties": { - "name": { + "key": { + "type": "string" + }, + "label": { "type": "string" }, "op": { @@ -392,7 +421,8 @@ }, "required": [ "op", - "name" + "key", + "label" ], "type": "object" } @@ -404,10 +434,13 @@ "type": "string" }, "skipped": { - "description": "Configuration tokens that have no place on the remote.", + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", "items": { "additionalProperties": false, "properties": { + "mode": { + "type": "string" + }, "name": { "type": "string" }, @@ -426,11 +459,47 @@ "type": "object" }, "type": "array" + }, + "target": { + "additionalProperties": false, + "description": "The part of the remote the tokens sync with.", + "properties": { + "file": { + "description": "The id of the file on the remote.", + "type": "string" + }, + "fileName": { + "type": "string" + }, + "modes": { + "description": "The modes the target holds.", + "items": { + "type": "string" + }, + "type": "array" + }, + "options": { + "additionalProperties": { + "type": "string" + }, + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "file", + "fileName", + "modes", + "options" + ], + "type": "object" } }, "required": [ "remote", - "file", + "target", "fetchedAt", "operations", "inbox", @@ -593,7 +662,7 @@ "type": "string" }, "item": { - "description": "The id of the inbox item: the token name without its leading --.", + "description": "The id of the inbox item, made from the name of the token on the remote: brand-accent for --brand-accent.", "minLength": 1, "type": "string" }, @@ -641,12 +710,16 @@ "item": { "type": "string" }, + "key": { + "type": "string" + }, "path": { "type": "string" } }, "required": [ "item", + "key", "action", "path" ], @@ -661,10 +734,14 @@ }, "item": { "type": "string" + }, + "key": { + "type": "string" } }, "required": [ "item", + "key", "action" ], "type": "object" @@ -678,10 +755,14 @@ }, "item": { "type": "string" + }, + "key": { + "type": "string" } }, "required": [ "item", + "key", "action" ], "type": "object" @@ -708,6 +789,10 @@ "id": { "type": "string" }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, "kind": { "enum": [ "new", @@ -717,17 +802,32 @@ ], "type": "string" }, - "localValue": { + "label": { + "description": "The name of the token on the remote.", "type": "string" }, - "name": { - "type": "string" + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "note": { "type": "string" }, - "remoteValue": { - "type": "string" + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "type": { "type": "string" @@ -736,7 +836,8 @@ "required": [ "id", "kind", - "name", + "key", + "label", "type", "actions" ], @@ -748,10 +849,13 @@ "type": "string" }, "skipped": { - "description": "Configuration tokens that have no place on the remote.", + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", "items": { "additionalProperties": false, "properties": { + "mode": { + "type": "string" + }, "name": { "type": "string" }, @@ -983,22 +1087,6 @@ "description": "When the remote tokens were read, as an ISO 8601 time.", "type": "string" }, - "file": { - "additionalProperties": false, - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - }, - "required": [ - "id", - "name" - ], - "type": "object" - }, "inbox": { "items": { "additionalProperties": false, @@ -1018,6 +1106,10 @@ "id": { "type": "string" }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, "kind": { "enum": [ "new", @@ -1027,17 +1119,32 @@ ], "type": "string" }, - "localValue": { + "label": { + "description": "The name of the token on the remote.", "type": "string" }, - "name": { - "type": "string" + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "note": { "type": "string" }, - "remoteValue": { - "type": "string" + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "type": { "type": "string" @@ -1046,7 +1153,8 @@ "required": [ "id", "kind", - "name", + "key", + "label", "type", "actions" ], @@ -1057,7 +1165,7 @@ "operations": { "description": "The changes the next push sends, in order.", "items": { - "description": "A change to send to the remote.", + "description": "A change to send to the remote, which addresses a remote token by its key.", "oneOf": [ { "additionalProperties": false, @@ -1075,15 +1183,22 @@ "type": { "type": "string" }, - "value": { - "type": "string" + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" } }, "required": [ "op", "name", "type", - "value", + "values", "description" ], "type": "object" @@ -1094,6 +1209,9 @@ "description": { "type": "string" }, + "key": { + "type": "string" + }, "name": { "type": "string" }, @@ -1104,15 +1222,23 @@ "type": { "type": "string" }, - "value": { - "type": "string" + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" } }, "required": [ "op", + "key", "name", "type", - "value", + "values", "description" ], "type": "object" @@ -1123,6 +1249,9 @@ "from": { "type": "string" }, + "key": { + "type": "string" + }, "op": { "const": "rename", "type": "string" @@ -1133,6 +1262,7 @@ }, "required": [ "op", + "key", "from", "to" ], @@ -1141,7 +1271,10 @@ { "additionalProperties": false, "properties": { - "name": { + "key": { + "type": "string" + }, + "label": { "type": "string" }, "op": { @@ -1151,7 +1284,8 @@ }, "required": [ "op", - "name" + "key", + "label" ], "type": "object" } @@ -1163,10 +1297,13 @@ "type": "string" }, "skipped": { - "description": "Configuration tokens that have no place on the remote.", + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", "items": { "additionalProperties": false, "properties": { + "mode": { + "type": "string" + }, "name": { "type": "string" }, @@ -1185,11 +1322,47 @@ "type": "object" }, "type": "array" + }, + "target": { + "additionalProperties": false, + "description": "The part of the remote the tokens sync with.", + "properties": { + "file": { + "description": "The id of the file on the remote.", + "type": "string" + }, + "fileName": { + "type": "string" + }, + "modes": { + "description": "The modes the target holds.", + "items": { + "type": "string" + }, + "type": "array" + }, + "options": { + "additionalProperties": { + "type": "string" + }, + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "file", + "fileName", + "modes", + "options" + ], + "type": "object" } }, "required": [ "remote", - "file", + "target", "fetchedAt", "operations", "inbox", @@ -1329,7 +1502,7 @@ "type": "string" }, "item": { - "description": "The id of the inbox item: the token name without its leading --.", + "description": "The id of the inbox item, made from the name of the token on the remote: brand-accent for --brand-accent.", "minLength": 1, "type": "string" }, @@ -1371,12 +1544,16 @@ "item": { "type": "string" }, + "key": { + "type": "string" + }, "path": { "type": "string" } }, "required": [ "item", + "key", "action", "path" ], @@ -1391,10 +1568,14 @@ }, "item": { "type": "string" + }, + "key": { + "type": "string" } }, "required": [ "item", + "key", "action" ], "type": "object" @@ -1408,10 +1589,14 @@ }, "item": { "type": "string" + }, + "key": { + "type": "string" } }, "required": [ "item", + "key", "action" ], "type": "object" @@ -1438,6 +1623,10 @@ "id": { "type": "string" }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, "kind": { "enum": [ "new", @@ -1447,17 +1636,32 @@ ], "type": "string" }, - "localValue": { + "label": { + "description": "The name of the token on the remote.", "type": "string" }, - "name": { - "type": "string" + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "note": { "type": "string" }, - "remoteValue": { - "type": "string" + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "type": { "type": "string" @@ -1466,7 +1670,8 @@ "required": [ "id", "kind", - "name", + "key", + "label", "type", "actions" ], @@ -1478,10 +1683,13 @@ "type": "string" }, "skipped": { - "description": "Configuration tokens that have no place on the remote.", + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", "items": { "additionalProperties": false, "properties": { + "mode": { + "type": "string" + }, "name": { "type": "string" }, @@ -1687,7 +1895,7 @@ "type": "string" }, "item": { - "description": "The id of the inbox item: the token name without its leading --.", + "description": "The id of the inbox item, made from the name of the token on the remote: brand-accent for --brand-accent.", "minLength": 1, "type": "string" }, @@ -1729,12 +1937,16 @@ "item": { "type": "string" }, + "key": { + "type": "string" + }, "path": { "type": "string" } }, "required": [ "item", + "key", "action", "path" ], @@ -1749,10 +1961,14 @@ }, "item": { "type": "string" + }, + "key": { + "type": "string" } }, "required": [ "item", + "key", "action" ], "type": "object" @@ -1766,10 +1982,14 @@ }, "item": { "type": "string" + }, + "key": { + "type": "string" } }, "required": [ "item", + "key", "action" ], "type": "object" @@ -1796,6 +2016,10 @@ "id": { "type": "string" }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, "kind": { "enum": [ "new", @@ -1805,17 +2029,32 @@ ], "type": "string" }, - "localValue": { + "label": { + "description": "The name of the token on the remote.", "type": "string" }, - "name": { - "type": "string" + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "note": { "type": "string" }, - "remoteValue": { - "type": "string" + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "type": { "type": "string" @@ -1824,7 +2063,8 @@ "required": [ "id", "kind", - "name", + "key", + "label", "type", "actions" ], @@ -1836,10 +2076,13 @@ "type": "string" }, "skipped": { - "description": "Configuration tokens that have no place on the remote.", + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", "items": { "additionalProperties": false, "properties": { + "mode": { + "type": "string" + }, "name": { "type": "string" }, @@ -2071,22 +2314,6 @@ "description": "When the remote tokens were read, as an ISO 8601 time.", "type": "string" }, - "file": { - "additionalProperties": false, - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - }, - "required": [ - "id", - "name" - ], - "type": "object" - }, "inbox": { "items": { "additionalProperties": false, @@ -2106,6 +2333,10 @@ "id": { "type": "string" }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, "kind": { "enum": [ "new", @@ -2115,17 +2346,32 @@ ], "type": "string" }, - "localValue": { + "label": { + "description": "The name of the token on the remote.", "type": "string" }, - "name": { - "type": "string" + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "note": { "type": "string" }, - "remoteValue": { - "type": "string" + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "type": { "type": "string" @@ -2134,7 +2380,8 @@ "required": [ "id", "kind", - "name", + "key", + "label", "type", "actions" ], @@ -2145,7 +2392,7 @@ "operations": { "description": "The changes the next push sends, in order.", "items": { - "description": "A change to send to the remote.", + "description": "A change to send to the remote, which addresses a remote token by its key.", "oneOf": [ { "additionalProperties": false, @@ -2163,15 +2410,22 @@ "type": { "type": "string" }, - "value": { - "type": "string" + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" } }, "required": [ "op", "name", "type", - "value", + "values", "description" ], "type": "object" @@ -2182,6 +2436,9 @@ "description": { "type": "string" }, + "key": { + "type": "string" + }, "name": { "type": "string" }, @@ -2192,15 +2449,23 @@ "type": { "type": "string" }, - "value": { - "type": "string" + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" } }, "required": [ "op", + "key", "name", "type", - "value", + "values", "description" ], "type": "object" @@ -2211,6 +2476,9 @@ "from": { "type": "string" }, + "key": { + "type": "string" + }, "op": { "const": "rename", "type": "string" @@ -2221,6 +2489,7 @@ }, "required": [ "op", + "key", "from", "to" ], @@ -2229,7 +2498,10 @@ { "additionalProperties": false, "properties": { - "name": { + "key": { + "type": "string" + }, + "label": { "type": "string" }, "op": { @@ -2239,7 +2511,8 @@ }, "required": [ "op", - "name" + "key", + "label" ], "type": "object" } @@ -2251,10 +2524,13 @@ "type": "string" }, "skipped": { - "description": "Configuration tokens that have no place on the remote.", + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", "items": { "additionalProperties": false, "properties": { + "mode": { + "type": "string" + }, "name": { "type": "string" }, @@ -2273,11 +2549,47 @@ "type": "object" }, "type": "array" + }, + "target": { + "additionalProperties": false, + "description": "The part of the remote the tokens sync with.", + "properties": { + "file": { + "description": "The id of the file on the remote.", + "type": "string" + }, + "fileName": { + "type": "string" + }, + "modes": { + "description": "The modes the target holds.", + "items": { + "type": "string" + }, + "type": "array" + }, + "options": { + "additionalProperties": { + "type": "string" + }, + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "file", + "fileName", + "modes", + "options" + ], + "type": "object" } }, "required": [ "remote", - "file", + "target", "fetchedAt", "operations", "inbox", @@ -2443,6 +2755,10 @@ "items": { "additionalProperties": false, "properties": { + "key": { + "description": "The key of the token after the operation.", + "type": "string" + }, "message": { "type": "string" }, @@ -2450,7 +2766,7 @@ "type": "boolean" }, "operation": { - "description": "A change to send to the remote.", + "description": "A change to send to the remote, which addresses a remote token by its key.", "oneOf": [ { "additionalProperties": false, @@ -2468,15 +2784,22 @@ "type": { "type": "string" }, - "value": { - "type": "string" + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" } }, "required": [ "op", "name", "type", - "value", + "values", "description" ], "type": "object" @@ -2487,6 +2810,9 @@ "description": { "type": "string" }, + "key": { + "type": "string" + }, "name": { "type": "string" }, @@ -2497,15 +2823,23 @@ "type": { "type": "string" }, - "value": { - "type": "string" + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" } }, "required": [ "op", + "key", "name", "type", - "value", + "values", "description" ], "type": "object" @@ -2516,6 +2850,9 @@ "from": { "type": "string" }, + "key": { + "type": "string" + }, "op": { "const": "rename", "type": "string" @@ -2526,6 +2863,7 @@ }, "required": [ "op", + "key", "from", "to" ], @@ -2534,7 +2872,10 @@ { "additionalProperties": false, "properties": { - "name": { + "key": { + "type": "string" + }, + "label": { "type": "string" }, "op": { @@ -2544,7 +2885,8 @@ }, "required": [ "op", - "name" + "key", + "label" ], "type": "object" } @@ -2569,22 +2911,6 @@ "description": "When the remote tokens were read, as an ISO 8601 time.", "type": "string" }, - "file": { - "additionalProperties": false, - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - }, - "required": [ - "id", - "name" - ], - "type": "object" - }, "inbox": { "items": { "additionalProperties": false, @@ -2604,6 +2930,10 @@ "id": { "type": "string" }, + "key": { + "description": "The key of the token on the remote, or the key a deleted token had.", + "type": "string" + }, "kind": { "enum": [ "new", @@ -2613,17 +2943,32 @@ ], "type": "string" }, - "localValue": { + "label": { + "description": "The name of the token on the remote.", "type": "string" }, - "name": { - "type": "string" + "localValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "note": { "type": "string" }, - "remoteValue": { - "type": "string" + "remoteValues": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" }, "type": { "type": "string" @@ -2632,7 +2977,8 @@ "required": [ "id", "kind", - "name", + "key", + "label", "type", "actions" ], @@ -2643,7 +2989,7 @@ "operations": { "description": "The changes the next push sends, in order.", "items": { - "description": "A change to send to the remote.", + "description": "A change to send to the remote, which addresses a remote token by its key.", "oneOf": [ { "additionalProperties": false, @@ -2661,15 +3007,22 @@ "type": { "type": "string" }, - "value": { - "type": "string" + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" } }, "required": [ "op", "name", "type", - "value", + "values", "description" ], "type": "object" @@ -2680,6 +3033,9 @@ "description": { "type": "string" }, + "key": { + "type": "string" + }, "name": { "type": "string" }, @@ -2690,15 +3046,23 @@ "type": { "type": "string" }, - "value": { - "type": "string" + "values": { + "additionalProperties": { + "type": "string" + }, + "description": "A value for each mode: default for :root, light and dark, or a selector.", + "propertyNames": { + "type": "string" + }, + "type": "object" } }, "required": [ "op", + "key", "name", "type", - "value", + "values", "description" ], "type": "object" @@ -2709,6 +3073,9 @@ "from": { "type": "string" }, + "key": { + "type": "string" + }, "op": { "const": "rename", "type": "string" @@ -2719,6 +3086,7 @@ }, "required": [ "op", + "key", "from", "to" ], @@ -2727,7 +3095,10 @@ { "additionalProperties": false, "properties": { - "name": { + "key": { + "type": "string" + }, + "label": { "type": "string" }, "op": { @@ -2737,7 +3108,8 @@ }, "required": [ "op", - "name" + "key", + "label" ], "type": "object" } @@ -2749,10 +3121,13 @@ "type": "string" }, "skipped": { - "description": "Configuration tokens that have no place on the remote.", + "description": "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", "items": { "additionalProperties": false, "properties": { + "mode": { + "type": "string" + }, "name": { "type": "string" }, @@ -2771,11 +3146,47 @@ "type": "object" }, "type": "array" + }, + "target": { + "additionalProperties": false, + "description": "The part of the remote the tokens sync with.", + "properties": { + "file": { + "description": "The id of the file on the remote.", + "type": "string" + }, + "fileName": { + "type": "string" + }, + "modes": { + "description": "The modes the target holds.", + "items": { + "type": "string" + }, + "type": "array" + }, + "options": { + "additionalProperties": { + "type": "string" + }, + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "required": [ + "file", + "fileName", + "modes", + "options" + ], + "type": "object" } }, "required": [ "remote", - "file", + "target", "fetchedAt", "operations", "inbox", @@ -2923,7 +3334,7 @@ "idempotent": true }, "sync.remote.add": { - "description": "Bind a file of a design tool to the configuration as a remote, so that the token sync commands read and write that file only. Checks that the remote can open the file (one request), and writes .cssforge/sync/.json. Binding the same file again keeps the sync state; binding another file starts the sync again.", + "description": "Bind a file of a design tool to the configuration as a remote, so that the token sync commands read and write that file only. Checks that the remote can open the file with the options (one request), and writes .cssforge/sync/.json. Binding the same file with the same options again keeps the sync state; binding another target starts the sync again.", "audience": [ "cli", "mcp", @@ -2949,6 +3360,17 @@ "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", "type": "string" }, + "options": { + "additionalProperties": { + "type": "string" + }, + "default": {}, + "description": "The options of the kind of remote, as JSON, e.g. {\"collection\":\"Tokens\"}. Paper takes none.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, "root": { "description": "The directory that the configuration path and the state directory .cssforge/sync resolve against. The default is the working directory.", "minLength": 1, @@ -2968,43 +3390,85 @@ "minimum": -9007199254740991, "type": "integer" }, - "file": { + "kind": { + "type": "string" + }, + "remote": { + "type": "string" + }, + "state": { + "description": "The absolute path of the state file.", + "type": "string" + }, + "target": { "additionalProperties": false, + "description": "The part of the remote the tokens sync with.", "properties": { - "id": { + "file": { + "description": "The id of the file on the remote.", "type": "string" }, - "name": { + "fileName": { "type": "string" + }, + "modes": { + "description": "The modes the target holds.", + "items": { + "type": "string" + }, + "type": "array" + }, + "options": { + "additionalProperties": { + "type": "string" + }, + "propertyNames": { + "type": "string" + }, + "type": "object" } }, "required": [ - "id", - "name" + "file", + "fileName", + "modes", + "options" ], "type": "object" - }, - "kind": { - "type": "string" - }, - "remote": { - "type": "string" - }, - "state": { - "description": "The absolute path of the state file.", - "type": "string" } }, "required": [ "remote", "kind", - "file", + "target", "state", "callsUsed" ], "type": "object" }, "failures": { + "InvalidOptions": { + "additionalProperties": false, + "properties": { + "_tag": { + "const": "InvalidOptions", + "description": "The kind of remote does not take the options.", + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "The file that the failure concerns.", + "type": "string" + } + }, + "required": [ + "_tag", + "message" + ], + "type": "object" + }, "RemoteFailed": { "additionalProperties": false, "properties": { diff --git a/packages/cssforge/src/capabilities.ts b/packages/cssforge/src/capabilities.ts index 974d53a..add4fc2 100644 --- a/packages/cssforge/src/capabilities.ts +++ b/packages/cssforge/src/capabilities.ts @@ -82,14 +82,17 @@ export type { BaseEntry, Decision, InboxItem, + ModeValues, Operation, RemoteToken, } from "./sync/plan.ts"; +export { DEFAULT_MODE } from "./sync/plan.ts"; export type { ApplyResult, RemoteAdapter, - RemoteFile, + RemoteOptions, RemoteSession, + RemoteTarget, TokenMapping, } from "./sync/remote.ts"; export { RemoteError } from "./sync/remote.ts"; diff --git a/packages/cssforge/src/lib.ts b/packages/cssforge/src/lib.ts index d553ea8..b1d2395 100644 --- a/packages/cssforge/src/lib.ts +++ b/packages/cssforge/src/lib.ts @@ -66,6 +66,27 @@ export interface TokenMetadata { */ export const ROOT_SCOPE = ":root"; +/** The wrappers of a scope: an at-rule, a selector, or both. An empty string is no wrapper. */ +export interface ScopeParts { + atRule: string; + selector: string; +} + +/** + * The scope of a declaration under `atRule` and `selector`. Both are kept whole, in a form + * that never confuses them: a selector may contain any character, `|` included + * (`[lang|=en]`). No wrapper gives `ROOT_SCOPE`. + */ +export const scopeOf = ({ atRule, selector }: ScopeParts): string => + !atRule && !selector ? ROOT_SCOPE : JSON.stringify([atRule, selector]); + +/** The wrappers of a scope that {@link scopeOf} made. `ROOT_SCOPE` has none. */ +export const scopeParts = (scope: string): ScopeParts => { + if (scope === ROOT_SCOPE) return { atRule: "", selector: "" }; + const [atRule, selector] = JSON.parse(scope) as [string, string]; + return { atRule, selector }; +}; + export interface ResolvedToken extends TokenMetadata { /** CSS custom property name, e.g. `--theme-light-content-primary`. */ key: string; diff --git a/packages/cssforge/src/modules/colors.ts b/packages/cssforge/src/modules/colors.ts index 7536898..9a1edb8 100644 --- a/packages/cssforge/src/modules/colors.ts +++ b/packages/cssforge/src/modules/colors.ts @@ -24,6 +24,7 @@ import { ROOT_SCOPE, resolveValue, resolveVariable, + scopeOf, withTokenScope, } from "../lib.ts"; @@ -48,8 +49,7 @@ const describeScope = (settings: WithCondition | undefined): string => { const { atRule, selector } = readCondition(settings); const scopedSelector = selector === ROOT_SCOPE ? "" : selector; - if (!atRule && !scopedSelector) return ROOT_SCOPE; - return `${atRule}|${scopedSelector}`; + return scopeOf({ atRule, selector: scopedSelector }); }; type ExactlyOne = { diff --git a/packages/cssforge/src/sync/capabilities.ts b/packages/cssforge/src/sync/capabilities.ts index 80f3d1a..e2e14e7 100644 --- a/packages/cssforge/src/sync/capabilities.ts +++ b/packages/cssforge/src/sync/capabilities.ts @@ -12,9 +12,10 @@ import { capabilitiesFor, fail, ok } from "@acid-cat/core-ts"; import { z } from "zod"; import type { ForgeContext } from "../capabilities.ts"; import { defaultConfigPath, ForgeError, listConfigTokens } from "../forge.ts"; -import type { ListedToken } from "../generator.ts"; +import { desiredTokens, type SkippedToken } from "./modes.ts"; import { paperAdapter } from "./paper.ts"; import { + type BaseEntry, type Decision, type DesiredToken, type InboxItem, @@ -27,7 +28,9 @@ import { type ApplyResult, type RemoteAdapter, RemoteError, + type RemoteOptions, type RemoteSession, + type RemoteTarget, } from "./remote.ts"; import { REMOTE_NAME, @@ -53,6 +56,7 @@ export interface RemoteAddInput { name: string; kind: string; file: string; + options: RemoteOptions; } /** The input of `sync.push`. */ @@ -71,17 +75,12 @@ export interface ItemInput extends SyncInput { item: string; } -/** A configuration token that has no place on the remote. */ -export interface SkippedToken { - name: string; - sourcePath: string; - reason: string; -} +export type { SkippedToken }; /** The plan of a sync, as the capabilities report it. */ export interface SyncReport { remote: string; - file: { id: string; name: string }; + target: RemoteTarget; /** When the remote tokens were read. */ fetchedAt: string; /** The changes the next push sends. */ @@ -102,7 +101,7 @@ export interface PushReport extends SyncReport { export interface RemoteAddReport { remote: string; kind: string; - file: { id: string; name: string }; + target: RemoteTarget; /** The absolute path of the state file. */ state: string; callsUsed: number; @@ -145,7 +144,9 @@ export type SyncPlanFailures = SyncReadFailures & { NotFetched: SyncFailure<"NotFetched">; }; /** The failures of `sync.remote.add`. */ -export type RemoteAddFailures = { [Tag in RemoteTags | "UnknownKind"]: SyncFailure }; +export type RemoteAddFailures = { + [Tag in RemoteTags | "UnknownKind" | "InvalidOptions"]: SyncFailure; +}; /** The failures of a decision. */ export type DecisionFailures = SyncPlanFailures & { UnknownItem: SyncFailure<"UnknownItem">; @@ -181,7 +182,9 @@ const syncShape = { const itemSchema = z .string() .min(1) - .describe("The id of the inbox item: the token name without its leading --."); + .describe( + "The id of the inbox item, made from the name of the token on the remote: brand-accent for --brand-accent.", + ); const syncInput = z.strictObject(syncShape); const pushInput = z.strictObject({ @@ -210,9 +213,26 @@ const remoteAddInput = z.strictObject({ .string() .min(1) .describe("The file of the remote that the tokens sync with: its id or its URL."), + options: z + .record(z.string(), z.string()) + .default({}) + .describe( + 'The options of the kind of remote, as JSON, e.g. {"collection":"Tokens"}. Paper takes none.', + ), }); -const fileSchema = z.strictObject({ id: z.string(), name: z.string() }); +const modeValuesSchema = z + .record(z.string(), z.string()) + .describe("A value for each mode: default for :root, light and dark, or a selector."); + +const targetSchema = z + .strictObject({ + file: z.string().describe("The id of the file on the remote."), + fileName: z.string(), + modes: z.array(z.string()).describe("The modes the target holds."), + options: z.record(z.string(), z.string()), + }) + .describe("The part of the remote the tokens sync with."); const operationSchema = z .discriminatedUnion("op", [ @@ -220,35 +240,49 @@ const operationSchema = z op: z.literal("create"), name: z.string(), type: z.string(), - value: z.string(), + values: modeValuesSchema, description: z.string(), }), z.strictObject({ op: z.literal("update"), + key: z.string(), name: z.string(), type: z.string(), - value: z.string(), + values: modeValuesSchema, description: z.string(), }), - z.strictObject({ op: z.literal("rename"), from: z.string(), to: z.string() }), - z.strictObject({ op: z.literal("delete"), name: z.string() }), + z.strictObject({ + op: z.literal("rename"), + key: z.string(), + from: z.string(), + to: z.string(), + }), + z.strictObject({ op: z.literal("delete"), key: z.string(), label: z.string() }), ]) - .describe("A change to send to the remote."); + .describe("A change to send to the remote, which addresses a remote token by its key."); const decisionSchema = z.discriminatedUnion("action", [ - z.strictObject({ item: z.string(), action: z.literal("adopt"), path: z.string() }), - z.strictObject({ item: z.string(), action: z.literal("reject") }), - z.strictObject({ item: z.string(), action: z.literal("overwrite") }), + z.strictObject({ + item: z.string(), + key: z.string(), + action: z.literal("adopt"), + path: z.string(), + }), + z.strictObject({ item: z.string(), key: z.string(), action: z.literal("reject") }), + z.strictObject({ item: z.string(), key: z.string(), action: z.literal("overwrite") }), ]); const inboxItemSchema = z .strictObject({ id: z.string(), kind: z.enum(["new", "edited", "deleted", "collision"]), - name: z.string(), + key: z + .string() + .describe("The key of the token on the remote, or the key a deleted token had."), + label: z.string().describe("The name of the token on the remote."), type: z.string(), - remoteValue: z.string().optional(), - localValue: z.string().optional(), + remoteValues: modeValuesSchema.optional(), + localValues: modeValuesSchema.optional(), actions: z.array(z.enum(["adopt", "reject", "overwrite"])), note: z.string().optional(), }) @@ -258,7 +292,7 @@ const inboxItemSchema = z const reportShape = { remote: z.string(), - file: fileSchema, + target: targetSchema, fetchedAt: z .string() .describe("When the remote tokens were read, as an ISO 8601 time."), @@ -268,9 +302,16 @@ const reportShape = { inbox: z.array(inboxItemSchema), skipped: z .array( - z.strictObject({ name: z.string(), sourcePath: z.string(), reason: z.string() }), + z.strictObject({ + name: z.string(), + sourcePath: z.string(), + mode: z.string().optional(), + reason: z.string(), + }), ) - .describe("Configuration tokens that have no place on the remote."), + .describe( + "Configuration tokens, or modes of them, that have no place on the remote. A token with a mode listed here still syncs its other modes.", + ), callsUsed: z.number().int().describe("The requests made to the remote by this call."), }; @@ -283,6 +324,7 @@ const pushReport = z.strictObject({ operation: operationSchema, ok: z.boolean(), message: z.string().optional(), + key: z.string().optional().describe("The key of the token after the operation."), }), ) .describe("What the remote did with each operation. Empty for a dry run."), @@ -290,7 +332,7 @@ const pushReport = z.strictObject({ const remoteAddReport = z.strictObject({ remote: z.string(), kind: z.string(), - file: fileSchema, + target: targetSchema, state: z.string().describe("The absolute path of the state file."), callsUsed: z.number().int(), }); @@ -417,35 +459,6 @@ const adapterOf = (context: ForgeContext, kind: string): RemoteAdapter => { return adapter; }; -const ALIAS = /^var\((--[a-zA-Z0-9_-]+)\)$/; - -/** The configuration tokens that go to the remote, and the ones that have no place there. */ -function desiredTokens(tokens: readonly ListedToken[], adapter: RemoteAdapter) { - const desired: DesiredToken[] = []; - const skipped: SkippedToken[] = []; - for (const token of tokens) { - const mapping = adapter.map(token); - if ("skip" in mapping) { - skipped.push({ - name: token.name, - sourcePath: token.sourcePath, - reason: mapping.skip, - }); - continue; - } - const alias = ALIAS.exec(token.value.trim())?.[1]; - desired.push({ - name: token.name, - type: mapping.type, - value: mapping.value, - ...(alias === undefined ? {} : { alias }), - sourcePath: token.sourcePath, - description: `cssforge: ${token.sourcePath}`, - }); - } - return { desired, skipped }; -} - interface Loaded { root: string; state: SyncState; @@ -466,7 +479,7 @@ async function load(context: ForgeContext, input: SyncInput): Promise { ); } const tokens = await listConfigTokens(resolve(root, input.config)); - return { root, state, adapter, ...desiredTokens(tokens, adapter) }; + return { root, state, adapter, ...desiredTokens(tokens, adapter, state.target.modes) }; } const fetchedOf = (state: SyncState, remote: string) => { @@ -482,12 +495,20 @@ const fetchedOf = (state: SyncState, remote: string) => { const planOf = (loaded: Loaded, remote: readonly RemoteToken[]): SyncPlan => planSync({ desired: loaded.desired, - skipped: new Set(loaded.skipped.map((token) => token.name)), + skipped: skippedNames(loaded), remote, base: loaded.state.base, decisions: loaded.state.decisions, }); +/** The configuration tokens that have no mode on the remote at all. */ +const skippedNames = (loaded: Loaded): Set => { + const desired = new Set(loaded.desired.map((token) => token.name)); + return new Set( + loaded.skipped.flatMap((token) => (desired.has(token.name) ? [] : [token.name])), + ); +}; + const reportOf = ( input: SyncInput, loaded: Loaded, @@ -496,7 +517,7 @@ const reportOf = ( callsUsed: number, ): SyncReport => ({ remote: input.remote, - file: loaded.state.file, + target: loaded.state.target, fetchedAt, operations: plan.operations.map((planned) => planned.operation), inbox: plan.inbox, @@ -520,7 +541,7 @@ async function withSession( /** Reads the remote and records the fetch in the state. */ async function fetchRemote(loaded: Loaded, session: RemoteSession, remote: string) { - const tokens = await session.read(loaded.state.file.id); + const tokens = await session.read(loaded.state.target); const fetched = { at: new Date().toISOString(), tokens }; loaded.state = { ...loaded.state, fetched }; await writeState(loaded.root, remote, loaded.state); @@ -552,7 +573,7 @@ export const syncRemoteAdd: Capability< > = capability({ id: "sync.remote.add", description: - "Bind a file of a design tool to the configuration as a remote, so that the token sync commands read and write that file only. Checks that the remote can open the file (one request), and writes .cssforge/sync/.json. Binding the same file again keeps the sync state; binding another file starts the sync again.", + "Bind a file of a design tool to the configuration as a remote, so that the token sync commands read and write that file only. Checks that the remote can open the file with the options (one request), and writes .cssforge/sync/.json. Binding the same file with the same options again keeps the sync state; binding another target starts the sync again.", audience: everyone, destructive: true, idempotent: true, @@ -561,24 +582,29 @@ export const syncRemoteAdd: Capability< failures: { ...remoteFailures, UnknownKind: failureSchema("UnknownKind", "The kind of remote is not known."), + InvalidOptions: failureSchema( + "InvalidOptions", + "The kind of remote does not take the options.", + ), }, run: (input, { context, signal }) => attempt(async () => { const root = rootOf(context, input); const adapter = adapterOf(context, input.kind); + adapter.checkOptions(input.options); return withSession(adapter, signal, async (session) => { - const file = await session.describe(input.file); + const target = await session.resolve(input.file, input.options); const previous = await readState(root, input.name).catch(() => undefined); const kept = - previous?.kind === input.kind && previous.file.id === file.id + previous?.kind === input.kind && sameTarget(previous.target, target) ? previous : undefined; const state: SyncState = kept - ? { ...kept, file } + ? { ...kept, target } : { version: 1, kind: input.kind, - file, + target, base: [], fetched: null, decisions: [], @@ -587,7 +613,7 @@ export const syncRemoteAdd: Capability< return { remote: input.name, kind: input.kind, - file, + target, state: path, callsUsed: session.calls, }; @@ -680,7 +706,13 @@ export const syncPush: Capability< const applied = input["dry-run"] || operations.length === 0 ? [] - : await session.apply(loaded.state.file.id, operations); + : withKeys( + await session.apply( + loaded.state.target, + operations, + keysOf(loaded.state), + ), + ); if (!input["dry-run"] && applied.length === 0) { const next = settle(loaded.state, plan, applied, fetched.tokens); await writeState(loaded.root, input.remote, next); @@ -692,7 +724,7 @@ export const syncPush: Capability< // Then read the tokens back, so that the base records each value as the remote // stored it. Without this, a change made on the remote before the next fetch // would read as the remote's own form of the value. - const stored = await session.read(loaded.state.file.id); + const stored = await session.read(loaded.state.target); const next = settle(loaded.state, plan, applied, stored); await writeState(loaded.root, input.remote, next); } @@ -710,6 +742,44 @@ export const syncPush: Capability< const refused = (operations: readonly Operation[], applied: readonly ApplyResult[]) => operations.filter((_, index) => applied[index]?.ok !== true); +/** The key of each custom property the remote has: from the fetch, then from the base. */ +const keysOf = (state: SyncState): Map => { + const keys = new Map(); + for (const token of state.fetched?.tokens ?? []) { + if (token.name !== undefined) keys.set(token.name, token.key); + } + for (const entry of state.base) keys.set(entry.name, entry.key); + return keys; +}; + +/** + * The results of a push, with each create or rename that the remote accepted without a key + * counted as refused: without the key, the configuration cannot own the token. The next fetch + * shows such a token as a collision. + */ +const withKeys = (applied: readonly ApplyResult[]): ApplyResult[] => + applied.map((result) => + result.ok && + (result.operation.op === "create" || result.operation.op === "rename") && + !result.key + ? { + operation: result.operation, + ok: false, + message: "The remote accepted the change but gave no key for the token.", + } + : result, + ); + +/** Whether two targets are the same file with the same options. */ +const sameTarget = (left: RemoteTarget, right: RemoteTarget): boolean => + left.file === right.file && + JSON.stringify(Object.entries(left.options).sort()) === + JSON.stringify(Object.entries(right.options).sort()); + +/** The key of the remote token that an operation addresses, before it runs. */ +const keyOf = (operation: Operation): string | undefined => + operation.op === "create" ? undefined : operation.key; + /** * The state after a push. `stored` is the remote read back after the push, or `null` when it * is not read yet: the stored values stay unknown, and the fetch is cleared because it is @@ -722,34 +792,45 @@ function settle( stored: readonly RemoteToken[] | null, ): SyncState { const previousByName = new Map(state.base.map((entry) => [entry.name, entry])); + const previousByKey = new Map(state.base.map((entry) => [entry.key, entry])); const base = new Map(plan.carried.map((entry) => [entry.name, entry])); const decisions = [...plan.pending]; - const decisionByItem = new Map( - state.decisions.map((decision) => [decision.item, decision]), + const decisionByKey = new Map( + state.decisions.map((decision) => [decision.key, decision]), ); + /** The key each token has after the operations so far, for a result that gives none. */ + const keyByName = new Map(); plan.operations.forEach((planned, index) => { - if (applied[index]?.ok === true) { + const result = applied[index]; + if (result?.ok === true) { if (planned.replaces !== undefined) base.delete(planned.replaces); - if (planned.base) base.set(planned.base.name, planned.base); + if (planned.base) { + const key = result.key ?? keyByName.get(planned.base.name) ?? planned.base.key; + keyByName.set(planned.base.name, key); + base.set(planned.base.name, { ...planned.base, key }); + } return; } - const { operation } = planned; - const name = operation.op === "rename" ? operation.from : operation.name; - const kept = previousByName.get(name); + const key = keyOf(planned.operation); + const kept = + (planned.replaces === undefined + ? undefined + : previousByName.get(planned.replaces)) ?? + (key === undefined ? undefined : previousByKey.get(key)); if (kept) base.set(kept.name, kept); const decision = - planned.settles === undefined ? undefined : decisionByItem.get(planned.settles); + planned.settles === undefined ? undefined : decisionByKey.get(planned.settles); if (decision && !decisions.includes(decision)) decisions.push(decision); }); if (stored === null) { return { ...state, base: [...base.values()], fetched: null, decisions }; } - const storedByName = new Map(stored.map((token) => [token.name, token.value])); + const storedByKey = new Map(stored.map((token) => [token.key, token.values])); const recorded = [...base.values()].map((entry) => entry.stored === null - ? { ...entry, stored: storedByName.get(entry.name) ?? null } + ? { ...entry, stored: storedByKey.get(entry.key) ?? null } : entry, ); return { @@ -781,11 +862,17 @@ export const syncInboxList: Capability< run: (input, { context }) => planFromFetch(input, context), }); +/** An answer to an inbox item, before it is recorded with the item's id and key. */ +type Answer = + | { action: "adopt"; path: string } + | { action: "reject" } + | { action: "overwrite" }; + /** Records a decision on an item of the inbox of the last fetch. */ async function decide( context: ForgeContext, input: SyncInput & { item: string }, - decision: Decision, + answer: Answer, check: (item: InboxItem, loaded: Loaded) => void, ): Promise { const loaded = await load(context, input); @@ -799,15 +886,16 @@ async function decide( `The inbox has no item "${input.item}".${ids.length > 0 ? ` Items: ${ids.join(", ")}.` : " The inbox is empty."}`, ); } - if (!item.actions.includes(decision.action)) { + if (!item.actions.includes(answer.action)) { throw new SyncError( "InvalidDecision", - `The ${item.kind} item "${item.id}" is settled with ${item.actions.join(" or ")}, not ${decision.action}.`, + `The ${item.kind} item "${item.id}" is settled with ${item.actions.join(" or ")}, not ${answer.action}.`, ); } check(item, loaded); + const decision: Decision = { item: item.id, key: item.key, ...answer }; const decisions = [ - ...loaded.state.decisions.filter((entry) => entry.item !== item.id), + ...loaded.state.decisions.filter((entry) => entry.key !== item.key), decision, ]; loaded.state = { ...loaded.state, decisions }; @@ -843,46 +931,40 @@ export const syncInboxAdopt: Capability< failures: decisionFailures, run: (input, { context }) => attempt(() => - decide( - context, - input, - { item: input.item, action: "adopt", path: input.path }, - (item, loaded) => { - const target = loaded.desired.find((token) => token.sourcePath === input.path); - if (!target) { - const skipped = loaded.skipped.find( - (token) => token.sourcePath === input.path, - ); - throw new SyncError( - "InvalidDecision", - skipped - ? `The path "${input.path}" generates ${skipped.name}, which has no place on the remote: ${skipped.reason}` - : `The configuration has no token at "${input.path}". Add the token to the configuration first, then adopt it.`, - ); - } - if ( - target.name !== item.name && - loaded.state.fetched?.tokens.some((token) => token.name === target.name) - ) { - throw new SyncError( - "InvalidDecision", - `The path "${input.path}" generates ${target.name}, which the remote already has.`, - ); - } - const taken = loaded.state.decisions.find( - (entry) => - entry.action === "adopt" && - entry.path === input.path && - entry.item !== item.id, + decide(context, input, { action: "adopt", path: input.path }, (item, loaded) => { + const target = loaded.desired.find((token) => token.sourcePath === input.path); + if (!target) { + const skipped = loaded.skipped.find((token) => token.sourcePath === input.path); + throw new SyncError( + "InvalidDecision", + skipped + ? `The path "${input.path}" generates ${skipped.name}, which has no place on the remote: ${skipped.reason}` + : `The configuration has no token at "${input.path}". Add the token to the configuration first, then adopt it.`, + ); + } + if ( + loaded.state.fetched?.tokens.some( + (token) => token.name === target.name && token.key !== item.key, + ) + ) { + throw new SyncError( + "InvalidDecision", + `The path "${input.path}" generates ${target.name}, which the remote already has.`, + ); + } + const taken = loaded.state.decisions.find( + (entry) => + entry.action === "adopt" && + entry.path === input.path && + entry.key !== item.key, + ); + if (taken) { + throw new SyncError( + "InvalidDecision", + `The item "${taken.item}" is already adopted as "${input.path}". Two remote tokens cannot become one configuration token.`, ); - if (taken) { - throw new SyncError( - "InvalidDecision", - `The item "${taken.item}" is already adopted as "${input.path}". Two remote tokens cannot become one configuration token.`, - ); - } - }, - ), + } + }), ), }); @@ -906,9 +988,7 @@ export const syncInboxReject: Capability< output: decisionReport, failures: decisionFailures, run: (input, { context }) => - attempt(() => - decide(context, input, { item: input.item, action: "reject" }, () => {}), - ), + attempt(() => decide(context, input, { action: "reject" }, () => {})), }); /** `cssforge sync inbox overwrite`: give the value of the configuration back to the remote. */ @@ -931,9 +1011,7 @@ export const syncInboxOverwrite: Capability< output: decisionReport, failures: decisionFailures, run: (input, { context }) => - attempt(() => - decide(context, input, { item: input.item, action: "overwrite" }, () => {}), - ), + attempt(() => decide(context, input, { action: "overwrite" }, () => {})), }); /** Every sync capability, in the order the help lists them. */ diff --git a/packages/cssforge/src/sync/modes.ts b/packages/cssforge/src/sync/modes.ts new file mode 100644 index 0000000..aed84ab --- /dev/null +++ b/packages/cssforge/src/sync/modes.ts @@ -0,0 +1,179 @@ +/** + * The modes of the configuration tokens. The generator emits a token once for each scope + * it lives in; a remote with modes (a Figma collection) holds one token with a value for + * each mode. This module makes the one from the other, and asks the adapter where each + * mode of each token goes. + * + * - A token at `:root` has the mode `default`. + * - A `light-dark(light, dark)` value at `:root` has the modes `light` and `dark`. + * - A token under a selector or an at-rule has the mode named after it, e.g. `.dark`. + * + * Tokens with the same custom property in several scopes are one token with several modes. + * + * @module + */ + +import type { ListedToken } from "../generator.ts"; +import { ROOT_SCOPE, scopeParts } from "../lib.ts"; +import { DEFAULT_MODE, type DesiredToken, type ModeValues } from "./plan.ts"; +import type { RemoteAdapter } from "./remote.ts"; + +/** A configuration token, or one mode of it, that has no place on the remote. */ +export interface SkippedToken { + name: string; + sourcePath: string; + /** The mode that has no place, when the token has others that do. */ + mode?: string; + reason: string; +} + +/** The mode of a scope: `default` for `:root`, else the at-rule and the selector it is under. */ +export const modeOfScope = (scope: string): string => { + if (scope === ROOT_SCOPE) return DEFAULT_MODE; + const { atRule, selector } = scopeParts(scope); + return [atRule, selector].filter(Boolean).join(" "); +}; + +/** The two arguments of a `light-dark()` value, split at its top-level comma. */ +export const lightDarkArguments = (value: string): [string, string] | undefined => { + const trimmed = value.trim(); + if (!/^light-dark\(/i.test(trimmed) || !trimmed.endsWith(")")) return undefined; + const inner = trimmed.slice("light-dark(".length, -1); + let depth = 0; + for (let index = 0; index < inner.length; index++) { + const character = inner[index]; + if (character === "(") depth++; + else if (character === ")") depth--; + else if (character === "," && depth === 0) { + return [inner.slice(0, index).trim(), inner.slice(index + 1).trim()]; + } + } + return undefined; +}; + +const ALIAS = /^var\((--[a-zA-Z0-9_-]+)\)$/; + +const withoutMode = ({ mode: _mode, ...entry }: SkippedToken): SkippedToken => entry; + +/** One mode of a listed token: its generated value and its resolved value. */ +interface ModeValue { + mode: string; + value: string; + resolvedValue: string; +} + +/** + * A value as one color scheme computes it: each `light-dark(light, dark)` in it, at any depth, + * becomes its light or its dark argument. + */ +export const inScheme = (value: string, scheme: "light" | "dark"): string => { + const start = value.search(/light-dark\(/i); + if (start === -1) return value; + const open = start + "light-dark(".length; + let depth = 1; + let end = open; + while (end < value.length && depth > 0) { + if (value[end] === "(") depth++; + else if (value[end] === ")") depth--; + end++; + } + const pair = lightDarkArguments(value.slice(start, end)); + if (pair === undefined) return value; + const chosen = scheme === "light" ? pair[0] : pair[1]; + return inScheme(`${value.slice(0, start)}${chosen}${value.slice(end)}`, scheme); +}; + +/** + * The modes of a listed token. A token at `:root` whose value depends on the color scheme + * (a `light-dark()` value, or a value built from one) has the modes `light` and `dark`, each + * with its own branch of every `light-dark()`. + */ +const modeValuesOf = (token: ListedToken): ModeValue[] => { + const mode = modeOfScope(token.scope); + if (mode === DEFAULT_MODE && /light-dark\(/i.test(token.resolvedValue)) { + return (["light", "dark"] as const).map((scheme) => ({ + mode: scheme, + value: inScheme(token.value, scheme), + resolvedValue: inScheme(token.resolvedValue, scheme), + })); + } + return [{ mode, value: token.value, resolvedValue: token.resolvedValue }]; +}; + +/** + * The configuration tokens that go to the remote, with a value for each mode the target + * holds, and the tokens and modes that have no place there. + */ +export function desiredTokens( + tokens: readonly ListedToken[], + adapter: RemoteAdapter, + modes: readonly string[], +): { desired: DesiredToken[]; skipped: SkippedToken[] } { + const held = new Set(modes); + const groups = new Map(); + for (const token of tokens) + groups.set(token.name, [...(groups.get(token.name) ?? []), token]); + + const desired: DesiredToken[] = []; + const skipped: SkippedToken[] = []; + + for (const [name, scoped] of groups) { + const values: ModeValues = {}; + const aliases: ModeValues = {}; + const types = new Set(); + const modeSkips: (SkippedToken & { unheld: boolean })[] = []; + const main = scoped.find((token) => token.scope === ROOT_SCOPE) ?? scoped[0]; + if (main === undefined) continue; + + for (const token of scoped) { + for (const { mode, value, resolvedValue } of modeValuesOf(token)) { + const skip = (reason: string, unheld = false) => + modeSkips.push({ name, sourcePath: token.sourcePath, mode, reason, unheld }); + if (!held.has(mode)) { + skip(`The remote has no mode "${mode}". It holds: ${modes.join(", ")}.`, true); + continue; + } + const mapping = adapter.map({ ...token, value, resolvedValue }); + if ("skip" in mapping) { + skip(mapping.skip); + continue; + } + types.add(mapping.type); + values[mode] = mapping.value; + const alias = ALIAS.exec(value.trim())?.[1]; + if (alias !== undefined) aliases[mode] = alias; + } + } + + if (types.size > 1) { + skipped.push({ + name, + sourcePath: main.sourcePath, + reason: `Its modes map to different types on the remote: ${[...types].join(", ")}.`, + }); + continue; + } + const [type] = types; + if (type === undefined) { + // No mode has a place: the token is skipped, with the reason of each mode. The mode + // is named when it is the reason, or when the token has several. + skipped.push( + ...modeSkips.map(({ unheld, ...entry }) => + unheld || modeSkips.length > 1 ? entry : withoutMode(entry), + ), + ); + continue; + } + skipped.push(...modeSkips.map(({ unheld: _unheld, ...entry }) => entry)); + desired.push({ + name, + type, + values, + ...(Object.keys(aliases).length > 0 ? { aliases } : {}), + sourcePath: main.sourcePath, + description: `cssforge: ${main.sourcePath}`, + }); + } + + return { desired, skipped }; +} diff --git a/packages/cssforge/src/sync/paper.ts b/packages/cssforge/src/sync/paper.ts index 6b5697f..5bcdd0b 100644 --- a/packages/cssforge/src/sync/paper.ts +++ b/packages/cssforge/src/sync/paper.ts @@ -8,13 +8,18 @@ import { z } from "zod"; import type { ListedToken, TokenKind } from "../generator.ts"; -import { ROOT_SCOPE } from "../lib.ts"; import { connectMcp, McpClientError } from "./mcp-client.ts"; -import { type Operation, TOKEN_NAME } from "./plan.ts"; +import { + CUSTOM_PROPERTY, + DEFAULT_MODE, + type ModeValues, + type Operation, +} from "./plan.ts"; import { type ApplyResult, type RemoteAdapter, RemoteError, + type RemoteOptions, type RemoteSession, type TokenMapping, } from "./remote.ts"; @@ -65,13 +70,10 @@ const SIZE_FUNCTION = /^(?:clamp|calc|min|max)\(/i; const POW_SCALE_PATH = /\.pow(?:[.@]|$)/; /** - * Maps a configuration token to Paper. Paper has no modes, so a token scoped to a selector - * or an at-rule has no place. Paper rejects `color-mix()` and references inside a value. + * Maps a configuration token to Paper. Paper has no modes: token sync only asks for the + * `default` mode. Paper rejects `color-mix()` and references inside a value. */ export function mapToPaper(token: ListedToken): TokenMapping { - if (token.scope !== ROOT_SCOPE) { - return { skip: `It is scoped to ${token.scope}, and Paper has no modes.` }; - } const type = token.kind === "typography" ? typographyType(token.sourcePath) @@ -85,7 +87,7 @@ export function mapToPaper(token: ListedToken): TokenMapping { }; } if (type === "color" && /(?:color-mix|light-dark)\(/i.test(value)) { - return { skip: "Paper does not take color-mix() or light-dark() values." }; + return { skip: "Paper does not take color-mix() values." }; } if (type === "fontSize") { if (POW_SCALE_PATH.test(token.sourcePath)) { @@ -121,7 +123,7 @@ const tokenList = z.object({ tokens: z.array( z.object({ // The rule of the state file, so that a fetch never records a name it cannot read back. - name: z.string().regex(TOKEN_NAME), + name: z.string().regex(CUSTOM_PROPERTY), type: z.string(), value: z.union([z.string(), z.number()]), description: z.string().optional(), @@ -140,19 +142,38 @@ type Change = Exclude; const isChange = (operation: Operation): operation is Change => operation.op !== "create"; -/** The `set_tokens` entry of a change. */ -const setTokensEntry = (operation: Change) => { +/** The value of the one mode Paper holds. */ +const defaultValue = (values: ModeValues): string => values[DEFAULT_MODE] ?? ""; + +/** + * The `set_tokens` entry of a change. A Paper key is the token name, so a rename changes + * it: `renamed` maps the keys renamed earlier in the batch to their new names. + */ +const setTokensEntry = (operation: Change, renamed: Map) => { + const name = renamed.get(operation.key) ?? operation.key; switch (operation.op) { case "update": return { - name: operation.name, - value: paperValue(operation.type, operation.value), + name, + value: paperValue(operation.type, defaultValue(operation.values)), description: operation.description, }; case "rename": - return { name: operation.from, newName: operation.to }; + renamed.set(operation.key, operation.to); + return { name, newName: operation.to }; case "delete": - return { name: operation.name, delete: true }; + return { name, delete: true }; + } +}; + +/** Paper takes no options. */ +const checkPaperOptions = (options: RemoteOptions): void => { + const names = Object.keys(options); + if (names.length > 0) { + throw new RemoteError( + "InvalidOptions", + `Paper takes no options. Received: ${names.join(", ")}.`, + ); } }; @@ -172,6 +193,7 @@ export function paperAdapter({ return { kind: "paper", map: mapToPaper, + checkOptions: checkPaperOptions, async open(signal) { const client = await connectMcp(command, args, signal).catch((error: unknown) => { throw new RemoteError( @@ -202,7 +224,8 @@ export function paperAdapter({ return calls; }, close: () => client.close(), - async describe(file) { + async resolve(file, options) { + checkPaperOptions(options); const text = await call("get_basic_info", { fileId: file }); const header = fileHeader.safeParse(JSON.parse(text[0] ?? "null")); const info = resultOf(basicInfo, text, "get_basic_info"); @@ -212,24 +235,34 @@ export function paperAdapter({ "Paper did not say which file it read.", ); } - return { id: header.data.file.id, name: info.fileName }; + return { + file: header.data.file.id, + fileName: info.fileName, + modes: [DEFAULT_MODE], + options: {}, + }; }, - async read(file) { - const text = await call("get_tokens", { fileId: file, format: "json" }); + async read(target) { + const text = await call("get_tokens", { fileId: target.file, format: "json" }); return resultOf(tokenList, text, "get_tokens").tokens.map((token) => ({ + key: token.name, + label: token.name, name: token.name, type: token.type, - value: String(token.value), + values: { [DEFAULT_MODE]: String(token.value) }, ...(token.description === undefined ? {} : { description: token.description }), })); }, - async apply(file, operations) { + async apply(target, operations) { const creates = operations.filter((operation) => operation.op === "create"); const changes = operations.filter(isChange); const results: ApplyResult[] = []; + const renamed = new Map(); + /** The key each operation leaves its token with, in the order sent. */ + const keys = new Map(); const report = ( batch: readonly Operation[], text: readonly string[], @@ -242,27 +275,42 @@ export function paperAdapter({ results.push({ operation, ok, - ...(ok ? {} : { message: entry?.message ?? "Paper gave no result." }), + ...(ok + ? { key: keys.get(operation) ?? "" } + : { message: entry?.message ?? "Paper gave no result." }), }); }); }; if (creates.length > 0) { + // A Paper key is the name. + for (const operation of creates) keys.set(operation, operation.name); const text = await call("create_tokens", { - fileId: file, + fileId: target.file, tokens: creates.map((operation) => ({ type: operation.type, name: operation.name, - value: paperValue(operation.type, operation.value), + value: paperValue(operation.type, defaultValue(operation.values)), description: operation.description, })), }); report(creates, text, "create_tokens"); } if (changes.length > 0) { + const entries = changes.map((operation) => { + const entry = setTokensEntry(operation, renamed); + // A Paper key is the name: the name after this entry, renamed or not. + keys.set( + operation, + operation.op === "rename" + ? operation.to + : (renamed.get(operation.key) ?? operation.key), + ); + return entry; + }); const text = await call("set_tokens", { - fileId: file, - tokens: changes.map(setTokensEntry), + fileId: target.file, + tokens: entries, }); report(changes, text, "set_tokens"); } diff --git a/packages/cssforge/src/sync/plan.ts b/packages/cssforge/src/sync/plan.ts index 7bf155d..55ab76f 100644 --- a/packages/cssforge/src/sync/plan.ts +++ b/packages/cssforge/src/sync/plan.ts @@ -8,30 +8,46 @@ * and stays one until a decision settles it: `adopt` or `reject` for a new token, * `overwrite` for the others. * + * Two identities meet here. The configuration names a token by its custom property + * (`--palette-brand-500`). A remote has its own key for it: the same name on Paper, a + * variable id on Figma. The base records both, so a remote that renames or re-keys a + * token keeps the link. + * * @module */ -/** The pattern of a token name on a remote: a CSS custom property, e.g. `--color-primary`. */ -export const TOKEN_NAME = /^--[a-zA-Z0-9_-]+$/; +/** The pattern of a custom property name, e.g. `--color-primary`. */ +export const CUSTOM_PROPERTY = /^--[a-zA-Z0-9_-]+$/; + +/** The mode of a token emitted at `:root`. */ +export const DEFAULT_MODE = "default"; + +/** The values of a token, one for each mode, e.g. `{ default: "8px" }` or `{ light, dark }`. */ +export type ModeValues = Record; /** A token as a remote stores it. */ export interface RemoteToken { - /** The custom property name, e.g. `--color-primary`. */ - name: string; + /** The identity of the token on the remote: a name or an id that only the remote assigns. */ + key: string; + /** The name people see on the remote, e.g. `--brand-accent` or `color/brand/accent`. */ + label: string; + /** The custom property the token stands for, when the remote records one. */ + name?: string; /** The token type of the remote, e.g. `color` or `spacing`. */ type: string; - value: string; + values: ModeValues; description?: string; } /** A token that the configuration wants on the remote. */ export interface DesiredToken { + /** The custom property name, e.g. `--palette-brand-500`. */ name: string; type: string; - /** The literal value, with every reference resolved. */ - value: string; - /** The token this one aliases, when its generated value is exactly `var()`. */ - alias?: string; + /** The literal value of each mode, with every reference resolved. */ + values: ModeValues; + /** For each mode whose generated value is exactly `var()`, the aliased token. */ + aliases?: ModeValues; /** The configuration path of the token. */ sourcePath: string; /** A description the remote shows beside the token. */ @@ -40,31 +56,47 @@ export interface DesiredToken { /** A token the configuration owns on the remote, as it was after the last push. */ export interface BaseEntry { + /** The custom property name. */ name: string; + /** The key of the token on the remote. */ + key: string; type: string; - /** The value the last push sent. */ - sent: string; - /** The value as the remote stored it, read back after the push. `null` if the read found no token. */ - stored: string | null; + /** The values the last push sent. */ + sent: ModeValues; + /** The values as the remote stored them, read back after the push. `null` until read. */ + stored: ModeValues | null; sourcePath: string; } -/** A recorded answer to an inbox item. The item is the token name without its `--`. */ +/** + * A recorded answer to an inbox item. `key` is the remote key of the token it settles, which + * stays the same when labels repeat or change; `item` is the id the answer was given for. + */ export type Decision = - | { item: string; action: "adopt"; path: string } - | { item: string; action: "reject" } - | { item: string; action: "overwrite" }; + | { item: string; key: string; action: "adopt"; path: string } + | { item: string; key: string; action: "reject" } + | { item: string; key: string; action: "overwrite" }; -/** A change to send to the remote. */ +/** A change to send to the remote. A remote token is addressed by its key. */ export type Operation = - | { op: "create"; name: string; type: string; value: string; description: string } - | { op: "update"; name: string; type: string; value: string; description: string } - | { op: "rename"; from: string; to: string } - | { op: "delete"; name: string }; + | { op: "create"; name: string; type: string; values: ModeValues; description: string } + | { + op: "update"; + key: string; + name: string; + type: string; + values: ModeValues; + description: string; + } + | { op: "rename"; key: string; from: string; to: string } + | { op: "delete"; key: string; label: string }; /** A change that the remote made, which waits for a decision. */ export interface InboxItem { - /** The id of the item: the token name without its `--`. */ + /** + * The id of the item, made from the label: `brand-accent` for `--brand-accent`. When two + * items share a label, each id ends with `#` and the key. + */ id: string; /** * `new`: the remote created a token that the configuration does not have. @@ -73,12 +105,15 @@ export interface InboxItem { * `collision`: the remote has a token with the name of a new configuration token. */ kind: "new" | "edited" | "deleted" | "collision"; - name: string; + /** The key of the token on the remote, or the key it had before the remote deleted it. */ + key: string; + /** The name of the token on the remote, or the custom property of a deleted token. */ + label: string; type: string; - /** The value on the remote, unless the remote deleted the token. */ - remoteValue?: string; - /** The value the configuration wants, unless the configuration does not have the token. */ - localValue?: string; + /** The values on the remote, unless the remote deleted the token. */ + remoteValues?: ModeValues; + /** The values the configuration wants, unless the configuration does not have the token. */ + localValues?: ModeValues; /** The decisions that settle the item. */ actions: Decision["action"][]; /** Why a recorded decision does not apply yet, for example an adopted path that is missing. */ @@ -88,11 +123,14 @@ export interface InboxItem { /** A planned operation with the base entry it gives when the remote accepts it. */ export interface PlannedOperation { operation: Operation; - /** The base entry after the operation, or `null` when the operation removes the entry. */ + /** + * The base entry after the operation, or `null` when the operation removes the entry. + * The remote may give the token a new key; the push records it. + */ base: BaseEntry | null; - /** The base entry the operation replaces, removed when the operation succeeds. */ + /** The name of the base entry the operation removes when it succeeds. */ replaces?: string; - /** The decision that the operation carries out, removed when the operation succeeds. */ + /** The key of the decision that the operation carries out, removed when it succeeds. */ settles?: string; } @@ -117,11 +155,17 @@ export interface PlanInput { decisions: readonly Decision[]; } -/** The inbox id of a token name: the name without its `--`. */ -export const itemIdOf = (name: string): string => name.replace(/^--/, ""); +/** The inbox id of a label: `brand-accent` for `--brand-accent`, `color/brand` as it is. */ +export const itemIdOf = (label: string): string => label.replace(/^--/, ""); -const byName = (entries: readonly T[]) => - new Map(entries.map((entry) => [entry.name, entry])); +/** Whether two sets of mode values are the same. */ +export const sameValues = (left: ModeValues, right: ModeValues): boolean => { + const modes = Object.keys(left); + return ( + modes.length === Object.keys(right).length && + modes.every((mode) => Object.hasOwn(right, mode) && right[mode] === left[mode]) + ); +}; /** * Plans a sync. Operations come in the order the remote must apply them: creates first, @@ -131,55 +175,65 @@ export function planSync(input: PlanInput): SyncPlan { const { remote, base, decisions } = input; const skipped = input.skipped ?? new Set(); const desired = withAliases(input.desired); - const desiredByName = byName(desired); - const remoteByName = byName(remote); - const baseByName = byName(base); - const decisionByItem = new Map(decisions.map((decision) => [decision.item, decision])); + const desiredByName = new Map(desired.map((token) => [token.name, token])); + const remoteByKey = new Map(remote.map((token) => [token.key, token])); + const baseKeys = new Set(base.map((entry) => entry.key)); + const baseNames = new Set(base.map((entry) => entry.name)); + /** The custom properties the remote already has a token for. */ + const remoteNames = new Set( + remote.flatMap((token) => (token.name === undefined ? [] : [token.name])), + ); + const decisionByKey = new Map(decisions.map((decision) => [decision.key, decision])); const creates: PlannedOperation[] = []; const changes: PlannedOperation[] = []; const inbox: InboxItem[] = []; const carried: BaseEntry[] = []; const pending: Decision[] = []; - /** Configuration tokens that an adopted remote token becomes, so they are not created. */ - const adoptedNames = new Set(); + /** Configuration tokens that a remote token becomes or collides with, so they are not created. */ + const claimedNames = new Set(); - const decisionFor = (name: string) => decisionByItem.get(itemIdOf(name)); - const settled = (name: string) => itemIdOf(name); - const entryOf = (token: DesiredToken): BaseEntry => ({ + const entryOf = (token: DesiredToken, key: string): BaseEntry => ({ name: token.name, + key, type: token.type, - sent: token.value, + sent: token.values, stored: null, sourcePath: token.sourcePath, }); + const hold = (decision: Decision | undefined) => { + if (decision) pending.push(decision); + }; // A token that the remote has and the base does not: new, or adopted under a decision. for (const remoteToken of remote) { - if (baseByName.has(remoteToken.name)) continue; - const wanted = desiredByName.get(remoteToken.name); - const decision = decisionFor(remoteToken.name); - - if (wanted) { + if (baseKeys.has(remoteToken.key)) continue; + const id = itemIdOf(remoteToken.label); + const decision = decisionByKey.get(remoteToken.key); + const settles = remoteToken.key; + const wanted = + remoteToken.name === undefined ? undefined : desiredByName.get(remoteToken.name); + + if (wanted && !baseNames.has(wanted.name)) { // The configuration wants a token with this name, which it never pushed. + claimedNames.add(wanted.name); if (decision?.action === "overwrite") { changes.push({ - operation: update(wanted), - base: entryOf(wanted), - settles: settled(remoteToken.name), + operation: update(wanted, remoteToken.key), + base: entryOf(wanted, remoteToken.key), + settles, }); - adoptedNames.add(wanted.name); continue; } - adoptedNames.add(wanted.name); - if (decision) pending.push(decision); + hold(decision); inbox.push({ - id: itemIdOf(remoteToken.name), + id, kind: "collision", - name: remoteToken.name, + key: remoteToken.key, + label: remoteToken.label, type: remoteToken.type, - remoteValue: remoteToken.value, - localValue: wanted.value, + remoteValues: remoteToken.values, + localValues: wanted.values, actions: ["overwrite"], }); continue; @@ -187,9 +241,9 @@ export function planSync(input: PlanInput): SyncPlan { if (decision?.action === "reject") { changes.push({ - operation: { op: "delete", name: remoteToken.name }, + operation: { op: "delete", key: remoteToken.key, label: remoteToken.label }, base: null, - settles: settled(remoteToken.name), + settles, }); continue; } @@ -199,51 +253,58 @@ export function planSync(input: PlanInput): SyncPlan { const blocked = target === undefined ? `The adopted path "${decision.path}" is not in the configuration.` - : remoteByName.has(target.name) || baseByName.has(target.name) + : remoteNames.has(target.name) || baseNames.has(target.name) ? `The adopted path "${decision.path}" generates ${target.name}, which the remote already has.` - : adoptedNames.has(target.name) + : claimedNames.has(target.name) ? `Another item is already adopted as "${decision.path}".` : undefined; if (target && blocked === undefined) { - adoptedNames.add(target.name); - const entry = { ...entryOf(target), sent: remoteToken.value }; + claimedNames.add(target.name); changes.push({ - operation: { op: "rename", from: remoteToken.name, to: target.name }, - base: entry, - settles: settled(remoteToken.name), + operation: { + op: "rename", + key: remoteToken.key, + from: remoteToken.label, + to: target.name, + }, + base: { ...entryOf(target, remoteToken.key), sent: remoteToken.values }, + settles, }); - if (target.value !== remoteToken.value) { - changes.push({ operation: update(target), base: entryOf(target) }); + if (!sameValues(target.values, remoteToken.values)) { + // The key after the rename is not known yet: the push sends the update with it. + changes.push({ + operation: update(target, remoteToken.key), + base: entryOf(target, remoteToken.key), + }); } continue; } pending.push(decision); - inbox.push({ - ...newItem(remoteToken), - ...(blocked ? { note: blocked } : {}), - }); + inbox.push({ ...newItem(remoteToken), ...(blocked ? { note: blocked } : {}) }); continue; } - if (decision) pending.push(decision); + hold(decision); inbox.push(newItem(remoteToken)); } // A token that the base has: the configuration owns it. for (const entry of base) { const wanted = desiredByName.get(entry.name); - const remoteToken = remoteByName.get(entry.name); - const decision = decisionFor(entry.name); + const remoteToken = remoteByKey.get(entry.key); + const id = itemIdOf(remoteToken?.label ?? entry.name); + const decision = decisionByKey.get(entry.key); + const settles = entry.key; if (!wanted && skipped.has(entry.name)) { - carried.push({ ...entry, stored: entry.stored ?? remoteToken?.value ?? null }); + carried.push({ ...entry, stored: entry.stored ?? remoteToken?.values ?? null }); continue; } if (!wanted) { // Removed from the configuration: delete it from the remote, if it is still there. if (remoteToken) { changes.push({ - operation: { op: "delete", name: entry.name }, + operation: { op: "delete", key: entry.key, label: remoteToken.label }, base: null, replaces: entry.name, }); @@ -255,113 +316,133 @@ export function planSync(input: PlanInput): SyncPlan { if (decision?.action === "overwrite") { creates.push({ operation: create(wanted), - base: entryOf(wanted), - settles: settled(entry.name), + base: entryOf(wanted, entry.key), + replaces: entry.name, + settles, }); continue; } - if (decision) pending.push(decision); + hold(decision); carried.push(entry); inbox.push({ - id: itemIdOf(entry.name), + id, kind: "deleted", - name: entry.name, + key: entry.key, + label: entry.name, type: entry.type, - localValue: wanted.value, + localValues: wanted.values, actions: ["overwrite"], }); continue; } - const stored = entry.stored ?? remoteToken.value; - const remoteChanged = remoteToken.value !== stored; - const localChanged = wanted.value !== entry.sent; + const stored = entry.stored ?? remoteToken.values; + const remoteChanged = !sameValues(remoteToken.values, stored); + const localChanged = !sameValues(wanted.values, entry.sent); if (remoteChanged) { if (decision?.action === "overwrite") { changes.push({ - operation: update(wanted), - base: entryOf(wanted), - settles: settled(entry.name), + operation: update(wanted, entry.key), + base: entryOf(wanted, entry.key), + settles, }); continue; } - if (decision) pending.push(decision); + hold(decision); carried.push({ ...entry, stored }); inbox.push({ - id: itemIdOf(entry.name), + id, kind: "edited", - name: entry.name, + key: entry.key, + label: remoteToken.label, type: entry.type, - remoteValue: remoteToken.value, - localValue: wanted.value, + remoteValues: remoteToken.values, + localValues: wanted.values, actions: ["overwrite"], }); continue; } if (localChanged) { - changes.push({ operation: update(wanted), base: entryOf(wanted) }); + changes.push({ + operation: update(wanted, entry.key), + base: entryOf(wanted, entry.key), + }); continue; } carried.push({ ...entry, stored }); } - // A token that only the configuration has: create it. + // A token that only the configuration has: create it. The remote gives it its key. for (const token of desired) { - if (baseByName.has(token.name) || remoteByName.has(token.name)) continue; - if (adoptedNames.has(token.name)) continue; - creates.push({ operation: create(token), base: entryOf(token) }); + if (baseNames.has(token.name) || claimedNames.has(token.name)) continue; + creates.push({ operation: create(token), base: entryOf(token, "") }); } return { operations: [...orderCreates(creates, desiredByName), ...changes], - inbox, + inbox: withUniqueIds(inbox), carried, pending, }; } +/** Gives the items that share an id a suffix with their key, so that each id names one item. */ +function withUniqueIds(inbox: readonly InboxItem[]): InboxItem[] { + const counts = new Map(); + for (const item of inbox) counts.set(item.id, (counts.get(item.id) ?? 0) + 1); + return inbox.map((item) => + (counts.get(item.id) ?? 0) > 1 ? { ...item, id: `${item.id}#${item.key}` } : item, + ); +} + const create = (token: DesiredToken): Operation => ({ op: "create", name: token.name, type: token.type, - value: token.value, + values: token.values, description: token.description, }); -const update = (token: DesiredToken): Operation => ({ +const update = (token: DesiredToken, key: string): Operation => ({ op: "update", + key, name: token.name, type: token.type, - value: token.value, + values: token.values, description: token.description, }); const newItem = (token: RemoteToken): InboxItem => ({ - id: itemIdOf(token.name), + id: itemIdOf(token.label), kind: "new", - name: token.name, + key: token.key, + label: token.label, type: token.type, - remoteValue: token.value, + remoteValues: token.values, actions: ["adopt", "reject"], }); /** - * Writes a token that aliases another pushed token of the same type as `var(--target)`, - * so that the remote keeps the link. The remote takes an alias only as the whole value, - * and only to a token of the same type; any other token sends its literal value. + * Writes each mode that aliases another pushed token of the same type as `var(--target)`, + * so that the remote keeps the link. Any other mode sends its literal value. */ function withAliases(desired: readonly DesiredToken[]): DesiredToken[] { const types = new Map(desired.map((token) => [token.name, token.type])); - return desired.map((token) => - token.alias !== undefined && types.get(token.alias) === token.type - ? { ...token, value: `var(${token.alias})` } - : token, - ); + return desired.map((token) => { + if (token.aliases === undefined) return token; + const values = { ...token.values }; + for (const [mode, target] of Object.entries(token.aliases)) { + if (types.get(target) === token.type && Object.hasOwn(values, mode)) { + values[mode] = `var(${target})`; + } + } + return { ...token, values }; + }); } -/** Orders creates so that each comes after the token it aliases. */ +/** Orders creates so that each comes after the tokens it aliases. */ function orderCreates( creates: readonly PlannedOperation[], desiredByName: ReadonlyMap, @@ -373,8 +454,8 @@ function orderCreates( const planned = pending.get(name); if (!planned) return; pending.delete(name); - const alias = desiredByName.get(name)?.alias; - if (alias !== undefined) visit(alias); + for (const alias of Object.values(desiredByName.get(name)?.aliases ?? {})) + visit(alias); ordered.push(planned); }; diff --git a/packages/cssforge/src/sync/remote.ts b/packages/cssforge/src/sync/remote.ts index 4a494e7..212adef 100644 --- a/packages/cssforge/src/sync/remote.ts +++ b/packages/cssforge/src/sync/remote.ts @@ -1,6 +1,7 @@ /** * The interface between token sync and a remote: a design tool that stores tokens. Each - * kind of remote (Paper, and later others) has one adapter. + * kind of remote (Paper, and later others such as Figma) has one adapter. Token sync knows + * nothing else about a remote. * * @module */ @@ -8,12 +9,23 @@ import type { ListedToken } from "../generator.ts"; import type { Operation, RemoteToken } from "./plan.ts"; -/** A file of the remote that the tokens sync with. */ -export interface RemoteFile { +/** The options of a remote, as `sync remote add --options` gives them, e.g. a Figma collection. */ +export type RemoteOptions = Record; + +/** The part of a remote that the tokens sync with, as the adapter resolved it. */ +export interface RemoteTarget { /** The id of the file on the remote. */ - id: string; + file: string; /** The name of the file, for people. */ - name: string; + fileName: string; + /** + * The modes the target holds, by the names token sync uses: `default` for tokens at + * `:root`, `light` and `dark` for `light-dark()` values, and the selector or at-rule of + * any other scope, e.g. `.dark`. A remote with no modes holds only `default`. + */ + modes: string[]; + /** The options, as the adapter normalized them, e.g. a collection name resolved to an id. */ + options: RemoteOptions; } /** What the remote did with one operation. */ @@ -22,6 +34,8 @@ export interface ApplyResult { ok: boolean; /** Why the remote refused the operation. */ message?: string; + /** The key of the token after the operation: the key a create gives, or a rename changes. */ + key?: string; } /** @@ -29,34 +43,52 @@ export interface ApplyResult { * because some remotes limit them. */ export interface RemoteSession { - /** Finds the file from an id or a URL. */ - describe(file: string): Promise; - /** Reads every token of the file. */ - read(file: string): Promise; - /** Sends the operations in order, and reports each one. */ - apply(file: string, operations: readonly Operation[]): Promise; + /** Finds the target from a file id or URL and the options. */ + resolve(file: string, options: RemoteOptions): Promise; + /** Reads every token of the target. */ + read(target: RemoteTarget): Promise; + /** + * Sends the operations in order, and reports each one. A `var(--name)` value aliases the + * token with that custom property; `keys` gives the key of each one the remote has. + */ + apply( + target: RemoteTarget, + operations: readonly Operation[], + keys: ReadonlyMap, + ): Promise; readonly calls: number; close(): void; } -/** Where a configuration token goes on the remote, or why it has no place there. */ +/** Where a configuration token goes on the remote in one mode, or why it has no place there. */ export type TokenMapping = { type: string; value: string } | { skip: string }; /** One kind of remote. */ export interface RemoteAdapter { - /** The kind, as `remote add --kind` names it, e.g. `paper`. */ + /** The kind, as `sync remote add --kind` names it, e.g. `paper`. */ kind: string; - /** Maps a configuration token to the remote. */ + /** + * Maps a configuration token in one mode to the remote. `token.resolvedValue` is the + * value of that mode. + */ map(token: ListedToken): TokenMapping; + /** + * Checks the options of `sync remote add` before any request, and throws a + * {@link RemoteError} `InvalidOptions` for options this kind does not take. + */ + checkOptions(options: RemoteOptions): void; /** Opens a session. Rejects with a {@link RemoteError} when the remote cannot be reached. */ open(signal: AbortSignal): Promise; } /** A failure of the remote, as a capability failure. */ export class RemoteError extends Error { - readonly tag: "RemoteUnavailable" | "RemoteFailed"; + readonly tag: "RemoteUnavailable" | "RemoteFailed" | "InvalidOptions"; - constructor(tag: "RemoteUnavailable" | "RemoteFailed", message: string) { + constructor( + tag: "RemoteUnavailable" | "RemoteFailed" | "InvalidOptions", + message: string, + ) { super(message); this.name = "RemoteError"; this.tag = tag; diff --git a/packages/cssforge/src/sync/state.ts b/packages/cssforge/src/sync/state.ts index c48e495..b92cb22 100644 --- a/packages/cssforge/src/sync/state.ts +++ b/packages/cssforge/src/sync/state.ts @@ -1,6 +1,6 @@ /** - * The state of the sync with one remote, in `.cssforge/sync/.json`: the file it - * syncs with, the base (the tokens as they were after the last push), the last fetch, and + * The state of the sync with one remote, in `.cssforge/sync/.json`: the target it + * syncs with (the file, its modes and the options), the base (the tokens as they were after the last push), the last fetch, and * the decisions that wait for the next push. Commit it, so that everyone who syncs shares * the base. * @@ -10,7 +10,13 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { z } from "zod"; -import { type BaseEntry, type Decision, type RemoteToken, TOKEN_NAME } from "./plan.ts"; +import { + type BaseEntry, + CUSTOM_PROPERTY, + type Decision, + type RemoteToken, +} from "./plan.ts"; +import type { RemoteTarget } from "./remote.ts"; /** The pattern of a remote name: a word in lowercase, e.g. `paper` or `paper-marketing`. */ export const REMOTE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/; @@ -19,26 +25,33 @@ export interface SyncState { version: 1; /** The kind of remote, e.g. `paper`. */ kind: string; - /** The file of the remote, by id and name. */ - file: { id: string; name: string }; + /** The part of the remote the tokens sync with: the file, its modes and the options. */ + target: RemoteTarget; base: BaseEntry[]; /** The remote tokens of the last fetch, or `null` before the first fetch. */ fetched: { at: string; tokens: RemoteToken[] } | null; decisions: Decision[]; } -const tokenName = z.string().regex(TOKEN_NAME); +const customProperty = z.string().regex(CUSTOM_PROPERTY); +const modeValues = z.record(z.string(), z.string()); const stateSchema = z.strictObject({ version: z.literal(1), kind: z.string().min(1), - file: z.strictObject({ id: z.string().min(1), name: z.string() }), + target: z.strictObject({ + file: z.string().min(1), + fileName: z.string(), + modes: z.array(z.string()).min(1), + options: z.record(z.string(), z.string()), + }), base: z.array( z.strictObject({ - name: tokenName, + name: customProperty, + key: z.string().min(1), type: z.string(), - sent: z.string(), - stored: z.string().nullable(), + sent: modeValues, + stored: modeValues.nullable(), sourcePath: z.string(), }), ), @@ -47,9 +60,11 @@ const stateSchema = z.strictObject({ at: z.string(), tokens: z.array( z.strictObject({ - name: tokenName, + key: z.string().min(1), + label: z.string().min(1), + name: customProperty.optional(), type: z.string(), - value: z.string(), + values: modeValues, description: z.string().optional(), }), ), @@ -57,9 +72,22 @@ const stateSchema = z.strictObject({ .nullable(), decisions: z.array( z.discriminatedUnion("action", [ - z.strictObject({ item: z.string(), action: z.literal("adopt"), path: z.string() }), - z.strictObject({ item: z.string(), action: z.literal("reject") }), - z.strictObject({ item: z.string(), action: z.literal("overwrite") }), + z.strictObject({ + item: z.string(), + key: z.string().min(1), + action: z.literal("adopt"), + path: z.string(), + }), + z.strictObject({ + item: z.string(), + key: z.string().min(1), + action: z.literal("reject"), + }), + z.strictObject({ + item: z.string(), + key: z.string().min(1), + action: z.literal("overwrite"), + }), ]), ), }); diff --git a/packages/cssforge/tests/sync-paper.test.ts b/packages/cssforge/tests/sync-paper.test.ts index 9696912..a89761d 100644 --- a/packages/cssforge/tests/sync-paper.test.ts +++ b/packages/cssforge/tests/sync-paper.test.ts @@ -8,6 +8,7 @@ import { cssforge, paperAdapter, syncFetch, + syncInboxAdopt, syncPlan, syncPush, syncRemoteAdd, @@ -65,7 +66,12 @@ test("paper - remote add binds the file id that Paper reports for a file URL", a expect(result.ok, JSON.stringify(result)).toEqual(true); if (!result.ok) return; - expect(result.value.file).toEqual({ id: "01FAKE", name: "Fake file" }); + expect(result.value.target).toEqual({ + file: "01FAKE", + fileName: "Fake file", + modes: ["default"], + options: {}, + }); expect(await toolCalls()).toEqual([ { name: "get_basic_info", @@ -132,3 +138,102 @@ test("paper - a token name the state cannot hold fails the fetch and leaves the expect(fetched.ok ? undefined : fetched.error._tag).toEqual("RemoteFailed"); expect(planned.ok ? undefined : planned.error._tag).toEqual("NotFetched"); }); + +test("paper - remote add refuses options before it starts Paper", async () => { + await using session = openSession(join(projectDir, "no-such-paper-design"), ["mcp"]); + + const result = await session.call(syncRemoteAdd, { + file: "01FAKE", + options: { collection: "Tokens" }, + }); + + expect(result.ok ? undefined : result.error._tag).toEqual("InvalidOptions"); +}); + +test("paper - adopting a token with a new value renames it, then updates it under the new name", async () => { + await using session = openSession(process.execPath, [fakePaper]); + await session.call(syncRemoteAdd, { file: "01FAKE" }); + await session.call(syncPush, {}); + await writeFile( + process.env.FAKE_PAPER_STATE ?? "", + JSON.stringify([ + ...JSON.parse(await readFile(process.env.FAKE_PAPER_STATE ?? "", "utf8")), + { name: "--brand-accent", type: "color", value: "oklch(70% 0.2 30)" }, + ]), + "utf8", + ); + await session.call(syncFetch, {}); + await writeFile( + join(projectDir, "cssforge.config.ts"), + `export default ${JSON.stringify({ + colors: { + palette: { + value: { brand: { 500: "oklch(60% 0.2 250)", accent: "oklch(72% 0.2 30)" } }, + }, + }, + typography: { weight: { body: { value: { bold: "700" } } } }, + })};\n`, + "utf8", + ); + await session.call(syncInboxAdopt, { + item: "brand-accent", + path: "palette.brand.accent", + }); + await writeFile(logPath, "", "utf8"); + + const result = await session.call(syncPush, {}); + + expect(result.ok, JSON.stringify(result)).toEqual(true); + const setTokens = (await toolCalls()).find((call) => call.name === "set_tokens"); + expect(setTokens?.arguments.tokens).toEqual([ + { name: "--brand-accent", newName: "--palette-brand-accent" }, + { + name: "--palette-brand-accent", + value: "oklch(72% 0.2 30)", + description: "cssforge: palette.brand.accent", + }, + ]); +}); + +test("paper - each result gives the key its token has after that operation", async () => { + await writeFile( + process.env.FAKE_PAPER_STATE ?? "", + JSON.stringify([{ name: "--old", type: "spacing", value: "4px" }]), + "utf8", + ); + const session = await paperAdapter({ + command: process.execPath, + args: [fakePaper], + }).open(new AbortController().signal); + try { + const target = { + file: "01FAKE", + fileName: "Fake file", + modes: ["default"], + options: {}, + }; + + const results = await session.apply( + target, + [ + { + op: "update", + key: "--old", + name: "--old", + type: "spacing", + values: { default: "8px" }, + description: "", + }, + { op: "rename", key: "--old", from: "--old", to: "--new" }, + ], + new Map(), + ); + + expect(results.map(({ ok, key }) => [ok, key])).toEqual([ + [true, "--old"], + [true, "--new"], + ]); + } finally { + session.close(); + } +}); diff --git a/packages/cssforge/tests/sync.test.ts b/packages/cssforge/tests/sync.test.ts index 1a29835..1a62a37 100644 --- a/packages/cssforge/tests/sync.test.ts +++ b/packages/cssforge/tests/sync.test.ts @@ -8,10 +8,12 @@ import { afterEach, beforeEach, expect, test } from "vitest"; import { type ApplyResult, cssforge, + type ModeValues, type Operation, paperAdapter, type RemoteAdapter, RemoteError, + type RemoteOptions, type RemoteToken, syncFetch, syncInboxAdopt, @@ -24,12 +26,24 @@ import { } from "../src/capabilities.ts"; import { childEnv } from "./helpers.ts"; +interface FakeRemoteSettings { + kind: string; + /** The modes the target holds. */ + modes: string[]; + /** `name`: the key is the custom property, as on Paper. `id`: the remote assigns an id. */ + keys: "name" | "id"; + /** The mapping of the remote. The default is Paper's. */ + map?: RemoteAdapter["map"]; +} + /** - * An in-memory Paper file. It keeps the rules of Paper that sync depends on: an alias - * must name an existing token of the same type, `set_tokens` targets an existing name, - * and duplicate names are allowed. `store` changes a value as Paper normalizes it. + * An in-memory design file. It keeps the rules that sync depends on: an alias must name an + * existing token of the same type, a change addresses an existing key, and duplicate names + * are allowed. With `keys: "name"` it behaves as Paper, whose key is the token name; with + * `keys: "id"` it assigns ids and keeps them across renames. `store` changes a value as the + * remote normalizes it. */ -class FakePaper { +class FakeRemote { tokens: RemoteToken[] = []; requests = 0; /** Names whose create or update the remote refuses. */ @@ -37,82 +51,125 @@ class FakePaper { store = (value: string) => value; /** The number of reads that succeed before every later read fails. */ readsBeforeFailure = Number.POSITIVE_INFINITY; + /** The options of the last `resolve`. */ + options: RemoteOptions | undefined; + /** Accept creates without giving their key, as a faulty adapter would. */ + omitKeys = false; + private nextId = 1; + private readonly settings: FakeRemoteSettings; + readonly adapter: RemoteAdapter; + + constructor(settings: FakeRemoteSettings) { + this.settings = settings; + this.adapter = { + kind: settings.kind, + // The mapping of the real Paper remote: only the transport is fake. + map: settings.map ?? paperAdapter().map, + // A fake of a kind with options takes any. + checkOptions: () => {}, + open: async () => { + let calls = 0; + const request = () => { + calls += 1; + this.requests += 1; + }; + return { + get calls() { + return calls; + }, + close: () => {}, + resolve: async (file, options) => { + request(); + this.options = options; + return { + file: file.replace(/^.*\/file\//, ""), + fileName: "Tokens", + modes: settings.modes, + options, + }; + }, + read: async () => { + request(); + if (this.readsBeforeFailure <= 0) { + throw new RemoteError("RemoteUnavailable", "The remote stopped."); + } + this.readsBeforeFailure -= 1; + return this.tokens.map((token) => ({ + ...token, + values: { ...token.values }, + })); + }, + apply: async (_target, operations) => { + request(); + const renamed = new Map(); + return operations.map((operation) => this.apply(operation, renamed)); + }, + }; + }, + }; + } - readonly adapter: RemoteAdapter = { - kind: "paper", - // The mapping of the real Paper remote: only the transport is fake. - map: paperAdapter().map, - open: async () => { - let calls = 0; - const request = () => { - calls += 1; - this.requests += 1; - }; - return { - get calls() { - return calls; - }, - close: () => {}, - describe: async (file) => { - request(); - return { id: file.replace(/^.*\/file\//, ""), name: "Tokens" }; - }, - read: async () => { - request(); - if (this.readsBeforeFailure <= 0) { - throw new RemoteError("RemoteUnavailable", "Paper stopped."); - } - this.readsBeforeFailure -= 1; - return this.tokens.map((token) => ({ ...token })); - }, - apply: async (_file, operations) => { - request(); - return operations.map((operation) => this.apply(operation)); - }, - }; - }, - }; + /** Adds a token as a designer would. A tool with ids may record no custom property. */ + add(name: string, type: string, values: ModeValues, label = name) { + const key = this.settings.keys === "name" ? name : `V${this.nextId++}`; + this.tokens.push({ key, label, ...(name ? { name } : {}), type, values }); + } + + byKey = (key: string) => this.tokens.find((token) => token.key === key); - private find = (name: string) => this.tokens.find((token) => token.name === name); + private find = (key: string) => this.tokens.find((token) => token.key === key); - private apply(operation: Operation): ApplyResult { + private stored = (values: ModeValues): ModeValues => + Object.fromEntries( + Object.entries(values).map(([mode, value]) => [mode, this.store(value)]), + ); + + private apply(operation: Operation, renamed: Map): ApplyResult { const refused = (message: string): ApplyResult => ({ operation, ok: false, message }); - switch (operation.op) { - case "create": { - if (this.refuse.has(operation.name)) return refused("Refused."); - const alias = /^var\((--[\w-]+)\)$/.exec(operation.value)?.[1]; - if (alias && this.find(alias)?.type !== operation.type) { - return refused(`Invalid value "${operation.value}".`); + if (operation.op === "create") { + if (this.refuse.has(operation.name)) return refused("Refused."); + for (const value of Object.values(operation.values)) { + const alias = /^var\((--[\w-]+)\)$/.exec(value)?.[1]; + const target = this.tokens.find((token) => token.name === alias); + if (alias && target?.type !== operation.type) { + return refused(`Invalid value "${value}".`); } - this.tokens.push({ - name: operation.name, - type: operation.type, - value: this.store(operation.value), - description: operation.description, - }); - return { operation, ok: true }; - } - case "update": { - const token = this.find(operation.name); - if (!token || this.refuse.has(operation.name)) return refused("Refused."); - token.value = this.store(operation.value); - return { operation, ok: true }; } + const key = this.settings.keys === "name" ? operation.name : `V${this.nextId++}`; + this.tokens.push({ + key, + label: operation.name, + name: operation.name, + type: operation.type, + values: this.stored(operation.values), + description: operation.description, + }); + return this.omitKeys ? { operation, ok: true } : { operation, ok: true, key }; + } + const token = this.find(renamed.get(operation.key) ?? operation.key); + if (!token) return refused("Token not found."); + switch (operation.op) { + case "update": + if (this.refuse.has(operation.name)) return refused("Refused."); + token.values = this.stored(operation.values); + return { operation, ok: true, key: token.key }; case "rename": { - const token = this.find(operation.from); - if (!token) return refused("Token not found."); + token.label = operation.to; token.name = operation.to; - return { operation, ok: true }; + if (this.settings.keys === "name") { + renamed.set(token.key, operation.to); + token.key = operation.to; + } + return { operation, ok: true, key: token.key }; } - case "delete": { - if (!this.find(operation.name)) return refused("Token not found."); - this.tokens = this.tokens.filter((token) => token.name !== operation.name); + case "delete": + this.tokens = this.tokens.filter((candidate) => candidate !== token); return { operation, ok: true }; - } } } - value = (name: string) => this.find(name)?.value; + byName = (name: string) => this.tokens.find((token) => token.name === name); + value = (name: string) => this.byName(name)?.values.default; } /** A palette color, an alias to it, two sizes, and three tokens Paper has no place for. */ @@ -147,8 +204,40 @@ const baseConfig = { motion: { duration: { ui: { value: { press: "120ms" } } } }, }; +/** One color with a `.dark` override, and one `light-dark()` pair. */ +const themedConfig = { + colors: { + palette: { value: { brand: { 500: "oklch(60% 0.2 250)" } } }, + theme: { + value: { + base: { + value: { + surface: { + value: { accent: "var(--brand)" }, + variables: { brand: "palette.brand.500" }, + settings: { variantNameOnly: true }, + }, + }, + }, + night: { + value: { + surface: { + value: { accent: "oklch(30% 0.1 250)" }, + settings: { variantNameOnly: true }, + }, + }, + settings: { selector: ".dark" }, + }, + light: { value: { text: { value: { body: "oklch(20% 0 0)" } } } }, + dark: { value: { text: { value: { body: "oklch(95% 0 0)" } } } }, + }, + settings: { lightDark: { light: "light", dark: "dark" } }, + }, + }, +}; + let projectDir = ""; -let paper: FakePaper; +let paper: FakeRemote; const writeConfig = (config: unknown) => writeFile( @@ -162,6 +251,11 @@ const withSpacing = (sizes: Record) => ({ spacing: { custom: { size: { value: sizes } } }, }); +/** One spacing token, for remotes whose keys the test counts. */ +const spacingOnly = (size: string) => ({ + spacing: { custom: { size: { value: { 1: size } } } }, +}); + const withAccent = (accent: string) => ({ ...baseConfig, colors: { @@ -174,7 +268,7 @@ const withAccent = (accent: string) => ({ beforeEach(async () => { projectDir = await mkdtemp(join(tmpdir(), "cssforge-sync-")); - paper = new FakePaper(); + paper = new FakeRemote({ kind: "paper", modes: ["default"], keys: "name" }); await writeConfig(baseConfig); }); @@ -182,10 +276,10 @@ afterEach(async () => { await rm(projectDir, { recursive: true, force: true }); }); -const openSession = () => +const openSession = (remotes: RemoteAdapter[] = [paper.adapter]) => createSession(cssforge, { target: "library", - context: { cwd: projectDir, remotes: [paper.adapter] }, + context: { cwd: projectDir, remotes }, toJsonSchema, }); @@ -209,6 +303,14 @@ const pushedSession = async () => { return session; }; +const created = (name: string, type: string, value: string, sourcePath: string) => ({ + op: "create", + name, + type, + values: { default: value }, + description: `cssforge: ${sourcePath}`, +}); + test("push - creates the configuration tokens on an empty remote, each alias after its target", async () => { await using session = openSession(); await expectValue( @@ -217,42 +319,55 @@ test("push - creates the configuration tokens on an empty remote, each alias aft const report = await expectValue(session.call(syncPush, {})); - expect(report.applied.map(({ operation, ok }) => ({ ...operation, ok }))).toEqual([ + expect(report.applied).toEqual([ { - op: "create", - name: "--palette-brand-500", - type: "color", - value: "oklch(60% 0.2 250)", - description: "cssforge: palette.brand.500", + operation: created( + "--palette-brand-500", + "color", + "oklch(60% 0.2 250)", + "palette.brand.500", + ), ok: true, + key: "--palette-brand-500", }, { - op: "create", - name: "--theme-light-surface-accent", - type: "color", - value: "var(--palette-brand-500)", - description: "cssforge: theme.light.surface.accent", + operation: created( + "--theme-light-surface-accent", + "color", + "var(--palette-brand-500)", + "theme.light.surface.accent", + ), ok: true, + key: "--theme-light-surface-accent", }, { - op: "create", - name: "--spacing-size-1", - type: "spacing", - value: "0.25rem", - description: "cssforge: spacing.custom.size.1", + operation: created( + "--spacing-size-1", + "spacing", + "0.25rem", + "spacing.custom.size.1", + ), ok: true, + key: "--spacing-size-1", }, { - op: "create", - name: "--spacing-size-2", - type: "spacing", - value: "0.5rem", - description: "cssforge: spacing.custom.size.2", + operation: created( + "--spacing-size-2", + "spacing", + "0.5rem", + "spacing.custom.size.2", + ), ok: true, + key: "--spacing-size-2", }, ]); expect(report.operations).toEqual([]); - expect(report.file).toEqual({ id: "F1", name: "Tokens" }); + expect(report.target).toEqual({ + file: "F1", + fileName: "Tokens", + modes: ["default"], + options: {}, + }); }); test("push - reports each configuration token that has no place on Paper, with the reason", async () => { @@ -265,12 +380,13 @@ test("push - reports each configuration token that has no place on Paper, with t { name: "--palette-brand-600", sourcePath: "palette.brand.600", - reason: "Paper does not take color-mix() or light-dark() values.", + reason: "Paper does not take color-mix() values.", }, { name: "--theme-dark-surface-accent", sourcePath: "theme.dark.surface.accent", - reason: "It is scoped to |.dark, and Paper has no modes.", + mode: ".dark", + reason: 'The remote has no mode ".dark". It holds: default.', }, { name: "--motion-duration-ui-press", @@ -302,15 +418,16 @@ test("push - updates a changed token and deletes a token removed from the config expect(report.applied.map(({ operation }) => operation)).toEqual([ { op: "update", + key: "--spacing-size-1", name: "--spacing-size-1", type: "spacing", - value: "0.375rem", + values: { default: "0.375rem" }, description: "cssforge: spacing.custom.size.1", }, - { op: "delete", name: "--spacing-size-2" }, + { op: "delete", key: "--spacing-size-2", label: "--spacing-size-2" }, ]); expect(paper.value("--spacing-size-1")).toEqual("0.375rem"); - expect(paper.value("--spacing-size-2")).toBeUndefined(); + expect(paper.byName("--spacing-size-2")).toBeUndefined(); }); test("fetch - a value the remote stores in another form is not a change", async () => { @@ -325,8 +442,8 @@ test("fetch - a value the remote stores in another form is not a change", async test("inbox - a value edited on the remote waits until overwrite gives the configuration value back", async () => { await using session = await pushedSession(); - const edited = paper.tokens.find((token) => token.name === "--spacing-size-1"); - if (edited) edited.value = "12px"; + const edited = paper.byName("--spacing-size-1"); + if (edited) edited.values = { default: "12px" }; const held = await expectValue(session.call(syncPush, {})); @@ -335,10 +452,11 @@ test("inbox - a value edited on the remote waits until overwrite gives the confi { id: "spacing-size-1", kind: "edited", - name: "--spacing-size-1", + key: "--spacing-size-1", + label: "--spacing-size-1", type: "spacing", - remoteValue: "12px", - localValue: "0.25rem", + remoteValues: { default: "12px" }, + localValues: { default: "0.25rem" }, actions: ["overwrite"], }, ]); @@ -353,20 +471,17 @@ test("inbox - a value edited on the remote waits until overwrite gives the confi test("inbox - a token the remote created is deleted by the push after a reject", async () => { await using session = await pushedSession(); - paper.tokens.push({ - name: "--brand-accent", - type: "color", - value: "oklch(70% 0.2 30)", - }); + paper.add("--brand-accent", "color", { default: "oklch(70% 0.2 30)" }); const fetched = await expectValue(session.call(syncFetch, {})); expect(fetched.inbox).toEqual([ { id: "brand-accent", kind: "new", - name: "--brand-accent", + key: "--brand-accent", + label: "--brand-accent", type: "color", - remoteValue: "oklch(70% 0.2 30)", + remoteValues: { default: "oklch(70% 0.2 30)" }, actions: ["adopt", "reject"], }, ]); @@ -383,19 +498,15 @@ test("inbox - a token the remote created is deleted by the push after a reject", const report = await expectValue(session.call(syncPush, {})); expect(report.applied.map(({ operation }) => operation)).toEqual([ - { op: "delete", name: "--brand-accent" }, + { op: "delete", key: "--brand-accent", label: "--brand-accent" }, ]); - expect(paper.value("--brand-accent")).toBeUndefined(); + expect(paper.byName("--brand-accent")).toBeUndefined(); expect(report.inbox).toEqual([]); }); test("inbox - adopt renames a token the remote created to the name the configuration gives it", async () => { await using session = await pushedSession(); - paper.tokens.push({ - name: "--brand-accent", - type: "color", - value: "oklch(70% 0.2 30)", - }); + paper.add("--brand-accent", "color", { default: "oklch(70% 0.2 30)" }); await expectValue(session.call(syncFetch, {})); const early = await session.call(syncInboxAdopt, { @@ -412,16 +523,41 @@ test("inbox - adopt renames a token the remote created to the name the configura const report = await expectValue(session.call(syncPush, {})); expect(report.applied.map(({ operation }) => operation)).toEqual([ - { op: "rename", from: "--brand-accent", to: "--palette-brand-accent" }, + { + op: "rename", + key: "--brand-accent", + from: "--brand-accent", + to: "--palette-brand-accent", + }, ]); expect(paper.value("--palette-brand-accent")).toEqual("oklch(70% 0.2 30)"); - expect(paper.value("--brand-accent")).toBeUndefined(); + expect(paper.byName("--brand-accent")).toBeUndefined(); const after = await expectValue(session.call(syncPush, {})); expect(after.applied).toEqual([]); expect(after.inbox).toEqual([]); }); +test("inbox - adopt with a new value renames the token, then updates it under its new key", async () => { + await using session = await pushedSession(); + paper.add("--brand-accent", "color", { default: "oklch(70% 0.2 30)" }); + await expectValue(session.call(syncFetch, {})); + await writeConfig(withAccent("oklch(72% 0.2 30)")); + await expectValue( + session.call(syncInboxAdopt, { item: "brand-accent", path: "palette.brand.accent" }), + ); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied.map(({ operation, ok }) => [operation.op, ok])).toEqual([ + ["rename", true], + ["update", true], + ]); + expect(paper.value("--palette-brand-accent")).toEqual("oklch(72% 0.2 30)"); + const after = await expectValue(session.call(syncPush, {})); + expect(after.applied).toEqual([]); +}); + test("push - an operation the remote refuses is reported and sent again at the next push", async () => { await using session = openSession(); await expectValue(session.call(syncRemoteAdd, { file: "F1" })); @@ -430,13 +566,7 @@ test("push - an operation the remote refuses is reported and sent again at the n const first = await expectValue(session.call(syncPush, {})); expect(first.applied.find(({ ok }) => !ok)).toEqual({ - operation: { - op: "create", - name: "--spacing-size-2", - type: "spacing", - value: "0.5rem", - description: "cssforge: spacing.custom.size.2", - }, + operation: created("--spacing-size-2", "spacing", "0.5rem", "spacing.custom.size.2"), ok: false, message: "Refused.", }); @@ -462,14 +592,32 @@ test("plan - fails with RemoteNotConfigured before remote add, and NotFetched be expect(unread.ok ? undefined : unread.error._tag).toEqual("NotFetched"); }); -test("remote add - binding the same file keeps the sync state, binding another file starts again", async () => { +test("remote add - binding the same target again keeps the sync state", async () => { await using session = await pushedSession(); await expectValue(session.call(syncRemoteAdd, { file: "F1" })); + const kept = await expectValue(session.call(syncPlan, {})); expect(kept.operations).toEqual([]); +}); + +test("remote add - binding another file starts the sync again", async () => { + await using session = await pushedSession(); await expectValue(session.call(syncRemoteAdd, { file: "F2" })); + + const restarted = await session.call(syncPlan, {}); + expect(restarted.ok ? undefined : restarted.error._tag).toEqual("NotFetched"); +}); + +test("remote add - binding the same file with other options starts the sync again", async () => { + await using session = await pushedSession(); + + await expectValue( + session.call(syncRemoteAdd, { file: "F1", options: { collection: "Brand" } }), + ); + + expect(paper.options).toEqual({ collection: "Brand" }); const restarted = await session.call(syncPlan, {}); expect(restarted.ok ? undefined : restarted.error._tag).toEqual("NotFetched"); }); @@ -514,10 +662,8 @@ test("push - a pushed token whose new value has no place on Paper keeps its Pape test("inbox - two remote tokens cannot be adopted as the same configuration token", async () => { await using session = await pushedSession(); - paper.tokens.push( - { name: "--brand-accent", type: "color", value: "oklch(70% 0.2 30)" }, - { name: "--accent", type: "color", value: "oklch(70% 0.2 30)" }, - ); + paper.add("--brand-accent", "color", { default: "oklch(70% 0.2 30)" }); + paper.add("--accent", "color", { default: "oklch(70% 0.2 30)" }); await expectValue(session.call(syncFetch, {})); await writeConfig(withAccent("oklch(70% 0.2 30)")); await expectValue( @@ -539,7 +685,7 @@ test("push - tokens the remote accepted stay owned when the read-back after the const failed = await session.call(syncPush, {}); expect(failed.ok ? undefined : failed.error._tag).toEqual("RemoteUnavailable"); - expect(paper.tokens.map((token) => token.name)).toHaveLength(4); + expect(paper.tokens).toHaveLength(4); paper.readsBeforeFailure = Number.POSITIVE_INFINITY; const next = await expectValue(session.call(syncPush, {})); @@ -547,3 +693,221 @@ test("push - tokens the remote accepted stay owned when the read-back after the expect(next.applied).toEqual([]); expect(next.inbox).toEqual([]); }); + +test("modes - a remote with modes gets one token per custom property, with a value for each mode", async () => { + const figma = new FakeRemote({ + kind: "figma", + modes: ["default", ".dark", "light", "dark"], + keys: "id", + }); + await writeConfig(themedConfig); + await using session = openSession([figma.adapter]); + await expectValue( + session.call(syncRemoteAdd, { + kind: "figma", + file: "F1", + options: { collection: "Tokens" }, + }), + ); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied).toEqual([ + { + operation: created( + "--palette-brand-500", + "color", + "oklch(60% 0.2 250)", + "palette.brand.500", + ), + ok: true, + key: "V1", + }, + { + operation: { + op: "create", + name: "--accent", + type: "color", + values: { default: "var(--palette-brand-500)", ".dark": "oklch(30% 0.1 250)" }, + description: "cssforge: theme.base.surface.accent", + }, + ok: true, + key: "V2", + }, + { + operation: { + op: "create", + name: "--theme-text-body", + type: "color", + values: { light: "oklch(20% 0 0)", dark: "oklch(95% 0 0)" }, + description: "cssforge: theme.text.body", + }, + ok: true, + key: "V3", + }, + ]); + expect(report.skipped).toEqual([]); + expect(report.target.options).toEqual({ collection: "Tokens" }); + const after = await expectValue(session.call(syncPush, {})); + expect(after.applied).toEqual([]); +}); + +test("modes - a token a designer renames keeps its link to the configuration through its key", async () => { + const figma = new FakeRemote({ kind: "figma", modes: ["default"], keys: "id" }); + await writeConfig(spacingOnly("4px")); + await using session = openSession([figma.adapter]); + await expectValue(session.call(syncRemoteAdd, { kind: "figma", file: "F1" })); + await expectValue(session.call(syncPush, {})); + const token = figma.byName("--spacing-size-1"); + if (token) { + token.label = "spacing/size/1"; + delete token.name; + } + await writeConfig(spacingOnly("6px")); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.inbox).toEqual([]); + expect(report.applied.map(({ operation }) => operation)).toEqual([ + { + op: "update", + key: "V1", + name: "--spacing-size-1", + type: "spacing", + values: { default: "0.375rem" }, + description: "cssforge: spacing.custom.size.1", + }, + ]); + expect(figma.byKey("V1")?.values).toEqual({ default: "0.375rem" }); +}); + +test("inbox - items that share a label get distinct ids, and a decision settles only its own", async () => { + const figma = new FakeRemote({ kind: "figma", modes: ["default"], keys: "id" }); + await writeConfig(spacingOnly("4px")); + await using session = openSession([figma.adapter]); + await expectValue(session.call(syncRemoteAdd, { kind: "figma", file: "F1" })); + await expectValue(session.call(syncPush, {})); + figma.add("", "color", { default: "#ff0000" }, "brand"); + figma.add("", "color", { default: "#00ff00" }, "brand"); + + const fetched = await expectValue(session.call(syncFetch, {})); + expect(fetched.inbox.map((item) => item.id)).toEqual(["brand#V2", "brand#V3"]); + + await expectValue(session.call(syncInboxReject, { item: "brand#V2" })); + await expectValue(session.call(syncPush, {})); + + expect(figma.byKey("V2")).toBeUndefined(); + expect(figma.byKey("V3")?.values).toEqual({ default: "#00ff00" }); +}); + +test("push - a create the remote accepts without a key is refused, and the state stays readable", async () => { + await using session = openSession(); + await expectValue(session.call(syncRemoteAdd, { file: "F1" })); + paper.omitKeys = true; + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.applied.every(({ ok }) => !ok)).toEqual(true); + expect(report.applied[0]?.message).toEqual( + "The remote accepted the change but gave no key for the token.", + ); + paper.omitKeys = false; + const next = await expectValue(session.call(syncFetch, {})); + expect(next.inbox.map((item) => item.kind)).toEqual([ + "collision", + "collision", + "collision", + "collision", + ]); +}); + +test("modes - a selector with a | is a mode name kept whole", async () => { + const figma = new FakeRemote({ + kind: "figma", + modes: ["default", "[lang|=en]"], + keys: "id", + }); + await writeConfig({ + colors: { + palette: { value: {} }, + theme: { + value: { + base: { + value: { + surface: { + value: { accent: "#000000" }, + settings: { variantNameOnly: true }, + }, + }, + }, + english: { + value: { + surface: { + value: { accent: "#ffffff" }, + settings: { variantNameOnly: true }, + }, + }, + settings: { selector: "[lang|=en]" }, + }, + }, + }, + }, + }); + await using session = openSession([figma.adapter]); + await expectValue(session.call(syncRemoteAdd, { kind: "figma", file: "F1" })); + + const report = await expectValue(session.call(syncPush, {})); + + expect(report.skipped).toEqual([]); + expect(figma.byName("--accent")?.values).toEqual({ + default: "#000000", + "[lang|=en]": "#ffffff", + }); +}); + +test("modes - each mode of a paired color gets its own branch of every light-dark() it builds on", async () => { + const figma = new FakeRemote({ + kind: "figma", + modes: ["default", "light", "dark"], + keys: "id", + map: (token) => ({ type: "color", value: token.resolvedValue }), + }); + const hover = { mix: { from: "theme.background.primary", with: "black", amount: 5 } }; + await writeConfig({ + colors: { + palette: { + value: { base: { white: "oklch(100% 0 0)", ink: "oklch(14.5% 0 0)" } }, + }, + theme: { + value: { + light: { + value: { + background: { + value: { primary: "var(--white)", hover }, + variables: { white: "palette.base.white" }, + }, + }, + }, + dark: { + value: { + background: { + value: { primary: "var(--ink)", hover }, + variables: { ink: "palette.base.ink" }, + }, + }, + }, + }, + settings: { lightDark: { light: "light", dark: "dark" } }, + }, + }, + }); + await using session = openSession([figma.adapter]); + await expectValue(session.call(syncRemoteAdd, { kind: "figma", file: "F1" })); + + await expectValue(session.call(syncPush, {})); + + expect(figma.byName("--theme-background-hover")?.values).toEqual({ + light: "color-mix(in oklch, oklch(100% 0 none), black 5%)", + dark: "color-mix(in oklch, oklch(14.5% 0 none), black 5%)", + }); +}); diff --git a/skills/cssforge/references/cli-reference.md b/skills/cssforge/references/cli-reference.md index 4a91304..f379737 100644 --- a/skills/cssforge/references/cli-reference.md +++ b/skills/cssforge/references/cli-reference.md @@ -46,11 +46,15 @@ State: `.cssforge/sync/.json` (commit it). Every command takes `--remote - `cssforge sync inbox overwrite --item `: the next push writes the config value for an `edited`, `deleted` or `collision` item. To keep the file's value, change the config instead. -Results: `{ remote, file, fetchedAt, operations, inbox, skipped, callsUsed }`, and `applied` for -`push`. An item id is the token name without `--`. A token path is the path in each pushed token's +Results: `{ remote, target, fetchedAt, operations, inbox, skipped, callsUsed }`, and `applied` +for `push`. Values are per mode (`{ default: "8px" }`): `default` at `:root`, `light` and `dark` +for `light-dark()`, the selector or at-rule for other scopes. The target lists the modes it holds +(Paper: `default`); the others are in `skipped` with `mode`. A remote token has a `key` (Paper: its +name; other tools: an id) and a `label`; operations address it by key. +`sync remote add --options ''` passes adapter options (Paper takes none: `InvalidOptions`). An item id is the token name without `--`. A token path is the path in each pushed token's description (`cssforge: palette.brand.500`). Failure tags: `RemoteNotConfigured`, `InvalidState`, `RemoteUnavailable`, `RemoteFailed`, `NotFetched`, `UnknownItem`, `InvalidDecision`, -`UnknownKind`. Paper's free plan limits MCP calls: prefer `sync plan` and `sync inbox list` (no request) +`UnknownKind`, `InvalidOptions`. Paper's free plan limits MCP calls: prefer `sync plan` and `sync inbox list` (no request) after one `sync fetch`. Agent loop: `sync fetch` → read `sync inbox list` → edit the config →