diagram-contracts 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -4,157 +4,33 @@
4
4
  import { Command } from "commander";
5
5
 
6
6
  // src/generated/contract.ts
7
- var CONTRACT_YAML = `cli_contracts: 0.1.0
8
-
9
- info:
10
- title: diagram-contracts
11
- version: 0.1.0
12
- description: Convert Layout IR to SVG.
13
-
14
- command_sets:
15
- diagram-contracts:
16
- summary: DSL-to-SVG diagram tool.
17
-
18
- commands:
19
- render:
20
- summary: Render Layout IR to SVG.
21
- description: Reads Layout IR JSON from a file or stdin and outputs SVG.
22
- arguments:
23
- - name: input
24
- index: 0
25
- required: false
26
- description: Input IR JSON file. Reads from stdin if omitted.
27
- schema:
28
- type: string
29
- file:
30
- mode: read
31
- exists: true
32
- options:
33
- - name: output
34
- aliases: [o]
35
- description: Output SVG file. Writes to stdout if omitted.
36
- schema:
37
- type: string
38
- - name: theme
39
- description: Theme YAML file path.
40
- schema:
41
- type: string
42
- file:
43
- mode: read
44
- exists: true
45
- - name: tokens
46
- description: Tokens YAML file path.
47
- schema:
48
- type: string
49
- file:
50
- mode: read
51
- exists: true
52
- - name: font-file
53
- description: Font file(s) for text measurement (.woff/.ttf/.otf). Comma-separated entries, each a path or <weight>=<path> (e.g. "400=inter.woff,700=inter-bold.woff"). Overrides font-family based resolution.
54
- schema:
55
- type: string
56
- exits:
57
- '0':
58
- description: SVG rendered successfully.
59
- '1':
60
- description: IR validation error.
61
- stderr:
62
- format: text
63
- '2':
64
- description: File I/O error.
65
- stderr:
66
- format: text
67
-
68
- validate:
69
- summary: Validate Layout IR JSON.
70
- description: Validates IR JSON against the schema without rendering.
71
- arguments:
72
- - name: input
73
- index: 0
74
- required: false
75
- description: Input IR JSON file. Reads from stdin if omitted.
76
- schema:
77
- type: string
78
- file:
79
- mode: read
80
- exists: true
81
- exits:
82
- '0':
83
- description: IR is valid.
84
- stdout:
85
- format: text
86
- '1':
87
- description: Validation error.
88
- stderr:
89
- format: text
90
-
91
- ir:
92
- summary: Output normalized IR or resolved artifact as JSON.
93
- description: Reads Layout IR JSON input and outputs the normalized IR or resolved layout artifact.
94
- arguments:
95
- - name: input
96
- index: 0
97
- required: false
98
- description: Input IR JSON file. Reads from stdin if omitted.
99
- schema:
100
- type: string
101
- file:
102
- mode: read
103
- exists: true
104
- options:
105
- - name: output
106
- aliases: [o]
107
- description: Output JSON file. Writes to stdout if omitted.
108
- schema:
109
- type: string
110
- - name: theme
111
- description: Theme YAML file path.
112
- schema:
113
- type: string
114
- file:
115
- mode: read
116
- exists: true
117
- - name: tokens
118
- description: Tokens YAML file path.
119
- schema:
120
- type: string
121
- file:
122
- mode: read
123
- exists: true
124
- - name: stage
125
- aliases: [s]
126
- description: Output stage.
127
- schema:
128
- type: string
129
- enum: [normalized, artifact]
130
- default: artifact
131
- exits:
132
- '0':
133
- description: Success.
134
- '1':
135
- description: IR validation error.
136
- stderr:
137
- format: text
138
- '2':
139
- description: File I/O error.
140
- stderr:
141
- format: text
142
- `;
143
- var CONTRACT_JSON_STR = '{\n "cli_contracts": "0.1.0",\n "info": {\n "title": "diagram-contracts",\n "version": "0.1.0",\n "description": "Convert Layout IR to SVG."\n },\n "command_sets": {\n "diagram-contracts": {\n "summary": "DSL-to-SVG diagram tool.",\n "commands": {\n "render": {\n "summary": "Render Layout IR to SVG.",\n "description": "Reads Layout IR JSON from a file or stdin and outputs SVG.",\n "arguments": [\n {\n "name": "input",\n "index": 0,\n "required": false,\n "description": "Input IR JSON file. Reads from stdin if omitted.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n }\n ],\n "options": [\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Output SVG file. Writes to stdout if omitted.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "theme",\n "description": "Theme YAML file path.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n },\n {\n "name": "tokens",\n "description": "Tokens YAML file path.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n },\n {\n "name": "font-file",\n "description": "Font file(s) for text measurement (.woff/.ttf/.otf). Comma-separated entries, each a path or <weight>=<path> (e.g. \\"400=inter.woff,700=inter-bold.woff\\"). Overrides font-family based resolution.",\n "schema": {\n "type": "string"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "SVG rendered successfully."\n },\n "1": {\n "description": "IR validation error.",\n "stderr": {\n "format": "text"\n }\n },\n "2": {\n "description": "File I/O error.",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "validate": {\n "summary": "Validate Layout IR JSON.",\n "description": "Validates IR JSON against the schema without rendering.",\n "arguments": [\n {\n "name": "input",\n "index": 0,\n "required": false,\n "description": "Input IR JSON file. Reads from stdin if omitted.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n }\n ],\n "exits": {\n "0": {\n "description": "IR is valid.",\n "stdout": {\n "format": "text"\n }\n },\n "1": {\n "description": "Validation error.",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "ir": {\n "summary": "Output normalized IR or resolved artifact as JSON.",\n "description": "Reads Layout IR JSON input and outputs the normalized IR or resolved layout artifact.",\n "arguments": [\n {\n "name": "input",\n "index": 0,\n "required": false,\n "description": "Input IR JSON file. Reads from stdin if omitted.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n }\n ],\n "options": [\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Output JSON file. Writes to stdout if omitted.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "theme",\n "description": "Theme YAML file path.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n },\n {\n "name": "tokens",\n "description": "Tokens YAML file path.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n },\n {\n "name": "stage",\n "aliases": [\n "s"\n ],\n "description": "Output stage.",\n "schema": {\n "type": "string",\n "enum": [\n "normalized",\n "artifact"\n ],\n "default": "artifact"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Success."\n },\n "1": {\n "description": "IR validation error.",\n "stderr": {\n "format": "text"\n }\n },\n "2": {\n "description": "File I/O error.",\n "stderr": {\n "format": "text"\n }\n }\n }\n }\n }\n }\n }\n}';
7
+ var CONTRACT_YAML = "cli_contracts: 0.1.0\n\ninfo:\n title: diagram-contracts\n version: 0.1.0\n description: Convert Layout IR to SVG.\n\ncommand_sets:\n diagram-contracts:\n summary: DSL-to-SVG diagram tool.\n\n # Parent-group descriptions for the nested subcommand groups (spec #62 /\n # #71). cli-contracts@0.33.15 emits these as `.description(...)` on the\n # generated `program.command(<group>)`, so the group help lines live in the\n # contract SSoT rather than in hand-written cli.ts (cli-contracts#77).\n groups:\n components:\n description: Component Pack tooling.\n icons:\n description: Icon provider tooling.\n\n commands:\n render:\n summary: Render Layout IR to SVG.\n description: Reads Layout IR JSON from a file or stdin and outputs SVG. A .md/.markdown file input renders each ```draw / ```mermaid fenced block to its own SVG (spec \xA78, stretch); with -o, per-block files (out.svg -> out.1.svg, out.2.svg, ...); without -o, blocks concatenate to stdout separated by <!-- draw-block N --> comments.\n arguments:\n - name: input\n index: 0\n required: false\n description: Input IR JSON file (or Draw Text / .draw.tsx / .md source). Reads from stdin if omitted.\n schema:\n type: string\n file:\n mode: read\n exists: true\n options:\n - name: output\n aliases: [o]\n description: Output SVG file. Writes to stdout if omitted.\n schema:\n type: string\n - name: theme\n description: Theme YAML file path.\n schema:\n type: string\n file:\n mode: read\n exists: true\n - name: tokens\n description: Tokens YAML file path.\n schema:\n type: string\n file:\n mode: read\n exists: true\n - name: font-file\n description: Font file(s) for text measurement (.woff/.ttf/.otf). Comma-separated entries, each a path or <weight>=<path> (e.g. \"400=inter.woff,700=inter-bold.woff\"). Overrides font-family based resolution.\n schema:\n type: string\n - name: config\n description: draw.config.yaml file (project-level bindings/props/doc/theme + icon providers, spec \xA75). Merged under inline %%@ directives.\n schema:\n type: string\n file:\n mode: read\n exists: true\n exits:\n '0':\n description: SVG rendered successfully.\n '1':\n description: IR validation error.\n stderr:\n format: text\n '2':\n description: File I/O error.\n stderr:\n format: text\n\n convert:\n summary: Eject Draw Text to Draw TSX (spec \xA78.1).\n description: Parses a Draw Text source to the Draw DSL tree (post-bind, pre-expansion) and serializes it as readable Draw TSX. The output compiled via the TSX path renders byte-identical SVG to rendering the Draw Text source directly.\n arguments:\n - name: input\n index: 0\n required: false\n description: Input Draw Text file. Reads from stdin if omitted.\n schema:\n type: string\n file:\n mode: read\n exists: true\n options:\n - name: output\n aliases: [o]\n description: Output .draw.tsx file. Writes to stdout if omitted.\n schema:\n type: string\n - name: config\n description: draw.config.yaml file (project-level bindings/props/doc/theme + icon providers, spec \xA75). Merged under inline %%@ directives.\n schema:\n type: string\n file:\n mode: read\n exists: true\n exits:\n '0':\n description: Draw TSX emitted successfully.\n '1':\n description: Parse / bind diagnostic error.\n stderr:\n format: text\n '2':\n description: File I/O error.\n stderr:\n format: text\n\n validate:\n summary: Validate Layout IR JSON.\n description: Validates IR JSON against the schema without rendering.\n arguments:\n - name: input\n index: 0\n required: false\n description: Input IR JSON file. Reads from stdin if omitted.\n schema:\n type: string\n file:\n mode: read\n exists: true\n exits:\n '0':\n description: IR is valid.\n stdout:\n format: text\n '1':\n description: Validation error.\n stderr:\n format: text\n\n ir:\n summary: Output normalized IR or resolved artifact as JSON.\n description: Reads Layout IR JSON input and outputs the normalized IR or resolved layout artifact.\n arguments:\n - name: input\n index: 0\n required: false\n description: Input IR JSON file. Reads from stdin if omitted.\n schema:\n type: string\n file:\n mode: read\n exists: true\n options:\n - name: output\n aliases: [o]\n description: Output JSON file. Writes to stdout if omitted.\n schema:\n type: string\n - name: theme\n description: Theme YAML file path.\n schema:\n type: string\n file:\n mode: read\n exists: true\n - name: tokens\n description: Tokens YAML file path.\n schema:\n type: string\n file:\n mode: read\n exists: true\n - name: stage\n aliases: [s]\n description: Output stage.\n schema:\n type: string\n enum: [normalized, artifact]\n default: artifact\n exits:\n '0':\n description: Success.\n '1':\n description: IR validation error.\n stderr:\n format: text\n '2':\n description: File I/O error.\n stderr:\n format: text\n\n # Nested subcommands (`<group> <verb>`, spec #62 / #71). The map key uses\n # dot notation, which cli-contracts splits into an invocation path\n # (`components build`) and a camelCase handler name (`componentsBuild`).\n components.build:\n summary: Build a Component Pack from a .draw.tsx entry.\n arguments:\n - name: entry\n index: 0\n required: true\n description: Entry .draw.tsx file whose exported/imported components are packed.\n schema:\n type: string\n file:\n mode: read\n exists: true\n options:\n - name: output\n aliases: [o]\n description: Output pack JSON file. Writes to stdout if omitted.\n schema:\n type: string\n - name: icons\n description: Comma-separated qualified icon names to embed offline (e.g. aws:ecs,aws:rds). Explicit list only \u2014 no template scan. A name that does not resolve at build time is an error.\n schema:\n type: string\n exits:\n '0':\n description: Component Pack built successfully.\n '1':\n description: Extraction / icon-resolution diagnostic error.\n stderr:\n format: text\n '2':\n description: File I/O error.\n stderr:\n format: text\n\n icons.export:\n summary: Export built-in provider icons as static SVG files.\n arguments:\n - name: provider\n index: 0\n required: true\n description: Icon provider (e.g. aws).\n schema:\n type: string\n options:\n - name: names\n description: Comma-separated icon short names to export (e.g. ecs,rds,vpc-group).\n schema:\n type: string\n - name: output\n aliases: [o]\n description: Output directory (created if missing).\n schema:\n type: string\n exits:\n '0':\n description: Icons exported successfully.\n '1':\n description: Icon-resolution error.\n stderr:\n format: text\n '2':\n description: File I/O error.\n stderr:\n format: text\n";
8
+ var CONTRACT_JSON_STR = '{\n "cli_contracts": "0.1.0",\n "info": {\n "title": "diagram-contracts",\n "version": "0.1.0",\n "description": "Convert Layout IR to SVG."\n },\n "command_sets": {\n "diagram-contracts": {\n "summary": "DSL-to-SVG diagram tool.",\n "groups": {\n "components": {\n "description": "Component Pack tooling."\n },\n "icons": {\n "description": "Icon provider tooling."\n }\n },\n "commands": {\n "render": {\n "summary": "Render Layout IR to SVG.",\n "description": "Reads Layout IR JSON from a file or stdin and outputs SVG. A .md/.markdown file input renders each ```draw / ```mermaid fenced block to its own SVG (spec \xA78, stretch); with -o, per-block files (out.svg -> out.1.svg, out.2.svg, ...); without -o, blocks concatenate to stdout separated by <!-- draw-block N --> comments.",\n "arguments": [\n {\n "name": "input",\n "index": 0,\n "required": false,\n "description": "Input IR JSON file (or Draw Text / .draw.tsx / .md source). Reads from stdin if omitted.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n }\n ],\n "options": [\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Output SVG file. Writes to stdout if omitted.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "theme",\n "description": "Theme YAML file path.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n },\n {\n "name": "tokens",\n "description": "Tokens YAML file path.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n },\n {\n "name": "font-file",\n "description": "Font file(s) for text measurement (.woff/.ttf/.otf). Comma-separated entries, each a path or <weight>=<path> (e.g. \\"400=inter.woff,700=inter-bold.woff\\"). Overrides font-family based resolution.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "config",\n "description": "draw.config.yaml file (project-level bindings/props/doc/theme + icon providers, spec \xA75). Merged under inline %%@ directives.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n }\n ],\n "exits": {\n "0": {\n "description": "SVG rendered successfully."\n },\n "1": {\n "description": "IR validation error.",\n "stderr": {\n "format": "text"\n }\n },\n "2": {\n "description": "File I/O error.",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "convert": {\n "summary": "Eject Draw Text to Draw TSX (spec \xA78.1).",\n "description": "Parses a Draw Text source to the Draw DSL tree (post-bind, pre-expansion) and serializes it as readable Draw TSX. The output compiled via the TSX path renders byte-identical SVG to rendering the Draw Text source directly.",\n "arguments": [\n {\n "name": "input",\n "index": 0,\n "required": false,\n "description": "Input Draw Text file. Reads from stdin if omitted.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n }\n ],\n "options": [\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Output .draw.tsx file. Writes to stdout if omitted.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "config",\n "description": "draw.config.yaml file (project-level bindings/props/doc/theme + icon providers, spec \xA75). Merged under inline %%@ directives.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Draw TSX emitted successfully."\n },\n "1": {\n "description": "Parse / bind diagnostic error.",\n "stderr": {\n "format": "text"\n }\n },\n "2": {\n "description": "File I/O error.",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "validate": {\n "summary": "Validate Layout IR JSON.",\n "description": "Validates IR JSON against the schema without rendering.",\n "arguments": [\n {\n "name": "input",\n "index": 0,\n "required": false,\n "description": "Input IR JSON file. Reads from stdin if omitted.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n }\n ],\n "exits": {\n "0": {\n "description": "IR is valid.",\n "stdout": {\n "format": "text"\n }\n },\n "1": {\n "description": "Validation error.",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "ir": {\n "summary": "Output normalized IR or resolved artifact as JSON.",\n "description": "Reads Layout IR JSON input and outputs the normalized IR or resolved layout artifact.",\n "arguments": [\n {\n "name": "input",\n "index": 0,\n "required": false,\n "description": "Input IR JSON file. Reads from stdin if omitted.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n }\n ],\n "options": [\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Output JSON file. Writes to stdout if omitted.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "theme",\n "description": "Theme YAML file path.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n },\n {\n "name": "tokens",\n "description": "Tokens YAML file path.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n },\n {\n "name": "stage",\n "aliases": [\n "s"\n ],\n "description": "Output stage.",\n "schema": {\n "type": "string",\n "enum": [\n "normalized",\n "artifact"\n ],\n "default": "artifact"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Success."\n },\n "1": {\n "description": "IR validation error.",\n "stderr": {\n "format": "text"\n }\n },\n "2": {\n "description": "File I/O error.",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "components.build": {\n "summary": "Build a Component Pack from a .draw.tsx entry.",\n "arguments": [\n {\n "name": "entry",\n "index": 0,\n "required": true,\n "description": "Entry .draw.tsx file whose exported/imported components are packed.",\n "schema": {\n "type": "string"\n },\n "file": {\n "mode": "read",\n "exists": true\n }\n }\n ],\n "options": [\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Output pack JSON file. Writes to stdout if omitted.",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "icons",\n "description": "Comma-separated qualified icon names to embed offline (e.g. aws:ecs,aws:rds). Explicit list only \u2014 no template scan. A name that does not resolve at build time is an error.",\n "schema": {\n "type": "string"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Component Pack built successfully."\n },\n "1": {\n "description": "Extraction / icon-resolution diagnostic error.",\n "stderr": {\n "format": "text"\n }\n },\n "2": {\n "description": "File I/O error.",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "icons.export": {\n "summary": "Export built-in provider icons as static SVG files.",\n "arguments": [\n {\n "name": "provider",\n "index": 0,\n "required": true,\n "description": "Icon provider (e.g. aws).",\n "schema": {\n "type": "string"\n }\n }\n ],\n "options": [\n {\n "name": "names",\n "description": "Comma-separated icon short names to export (e.g. ecs,rds,vpc-group).",\n "schema": {\n "type": "string"\n }\n },\n {\n "name": "output",\n "aliases": [\n "o"\n ],\n "description": "Output directory (created if missing).",\n "schema": {\n "type": "string"\n }\n }\n ],\n "exits": {\n "0": {\n "description": "Icons exported successfully."\n },\n "1": {\n "description": "Icon-resolution error.",\n "stderr": {\n "format": "text"\n }\n },\n "2": {\n "description": "File I/O error.",\n "stderr": {\n "format": "text"\n }\n }\n }\n }\n }\n }\n }\n}';
144
9
 
145
10
  // src/generated/program.ts
146
11
  function createProgram(handlers2, version) {
147
12
  const program2 = new Command();
148
13
  program2.name("diagram-contracts").version(version, "-V, --version").description("DSL-to-SVG diagram tool.");
149
- program2.command("render").description("Render Layout IR to SVG.").argument("[input]", "Input IR JSON file. Reads from stdin if omitted.").option("-o, --output <value>", "Output SVG file. Writes to stdout if omitted.").option("--theme <value>", "Theme YAML file path.").option("--tokens <value>", "Tokens YAML file path.").option("--font-file <value>", 'Font file(s) for text measurement (.woff/.ttf/.otf). Comma-separated entries, each a path or <weight>=<path> (e.g. "400=inter.woff,700=inter-bold.woff"). Overrides font-family based resolution.').action(async (input, opts, cmd) => {
14
+ program2.command("render").description("Render Layout IR to SVG.").argument("[input]", "Input IR JSON file (or Draw Text / .draw.tsx / .md source). Reads from stdin if omitted.").option("-o, --output <value>", "Output SVG file. Writes to stdout if omitted.").option("--theme <value>", "Theme YAML file path.").option("--tokens <value>", "Tokens YAML file path.").option("--font-file <value>", 'Font file(s) for text measurement (.woff/.ttf/.otf). Comma-separated entries, each a path or <weight>=<path> (e.g. "400=inter.woff,700=inter-bold.woff"). Overrides font-family based resolution.').option("--config <value>", "draw.config.yaml file (project-level bindings/props/doc/theme + icon providers, spec \xA75). Merged under inline %%@ directives.").action(async (input, opts, cmd) => {
150
15
  await handlers2.render(input, opts, cmd.optsWithGlobals());
151
16
  });
17
+ program2.command("convert").description("Eject Draw Text to Draw TSX (spec \xA78.1).").argument("[input]", "Input Draw Text file. Reads from stdin if omitted.").option("-o, --output <value>", "Output .draw.tsx file. Writes to stdout if omitted.").option("--config <value>", "draw.config.yaml file (project-level bindings/props/doc/theme + icon providers, spec \xA75). Merged under inline %%@ directives.").action(async (input, opts, cmd) => {
18
+ await handlers2.convert(input, opts, cmd.optsWithGlobals());
19
+ });
152
20
  program2.command("validate").description("Validate Layout IR JSON.").argument("[input]", "Input IR JSON file. Reads from stdin if omitted.").action(async (input, opts, cmd) => {
153
21
  await handlers2.validate(input, {}, cmd.optsWithGlobals());
154
22
  });
155
23
  program2.command("ir").description("Output normalized IR or resolved artifact as JSON.").argument("[input]", "Input IR JSON file. Reads from stdin if omitted.").option("-o, --output <value>", "Output JSON file. Writes to stdout if omitted.").option("--theme <value>", "Theme YAML file path.").option("--tokens <value>", "Tokens YAML file path.").option("-s, --stage <value>", "Output stage.", "artifact").action(async (input, opts, cmd) => {
156
24
  await handlers2.ir(input, opts, cmd.optsWithGlobals());
157
25
  });
26
+ const __cmd_components = program2.command("components").description("Component Pack tooling.");
27
+ __cmd_components.command("build").description("Build a Component Pack from a .draw.tsx entry.").argument("<entry>", "Entry .draw.tsx file whose exported/imported components are packed.").option("-o, --output <value>", "Output pack JSON file. Writes to stdout if omitted.").option("--icons <value>", "Comma-separated qualified icon names to embed offline (e.g. aws:ecs,aws:rds). Explicit list only \u2014 no template scan. A name that does not resolve at build time is an error.").action(async (entry, opts, cmd) => {
28
+ await handlers2.componentsBuild(entry, opts, cmd.optsWithGlobals());
29
+ });
30
+ const __cmd_icons = program2.command("icons").description("Icon provider tooling.");
31
+ __cmd_icons.command("export").description("Export built-in provider icons as static SVG files.").argument("<provider>", "Icon provider (e.g. aws).").option("--names <value>", "Comma-separated icon short names to export (e.g. ecs,rds,vpc-group).").option("-o, --output <value>", "Output directory (created if missing).").action(async (provider, opts, cmd) => {
32
+ await handlers2.iconsExport(provider, opts, cmd.optsWithGlobals());
33
+ });
158
34
  program2.command("extract").description("Extract contract specification for this CLI tool.").argument("[commands...]", "Command IDs to extract. Use dot notation.").option("-a, --all", "Extract all commands.", false).option("--include-meta", "Include extraction metadata.", true).option("-F, --format <format>", "Output format (yaml or json).", "yaml").action(async (commands, opts, cmd) => {
159
35
  if (commands.length === 0 && !opts.all) {
160
36
  process.stderr.write(JSON.stringify({ code: "INVALID_ARGS", message: "Specify command IDs or use --all" }) + "\n");
@@ -172,7 +48,7 @@ function createProgram(handlers2, version) {
172
48
  type: "cli-contracts/extract",
173
49
  extractedAt: (/* @__PURE__ */ new Date()).toISOString(),
174
50
  specVersion: doc.cli_contracts ?? "0.1.0",
175
- commands: ["diagram-contracts.render", "diagram-contracts.validate", "diagram-contracts.ir"]
51
+ commands: ["diagram-contracts.render", "diagram-contracts.convert", "diagram-contracts.validate", "diagram-contracts.ir", "diagram-contracts.components.build", "diagram-contracts.icons.export"]
176
52
  };
177
53
  }
178
54
  Object.assign(out, doc);
@@ -189,7 +65,7 @@ function createProgram(handlers2, version) {
189
65
  yamlLines.push("extractedAt: " + (/* @__PURE__ */ new Date()).toISOString());
190
66
  yamlLines.push("spec_version: " + (doc.cli_contracts ?? "0.1.0"));
191
67
  yamlLines.push("commands:");
192
- for (const id of ["diagram-contracts.render", "diagram-contracts.validate", "diagram-contracts.ir"]) {
68
+ for (const id of ["diagram-contracts.render", "diagram-contracts.convert", "diagram-contracts.validate", "diagram-contracts.ir", "diagram-contracts.components.build", "diagram-contracts.icons.export"]) {
193
69
  yamlLines.push(" - " + id);
194
70
  }
195
71
  }
@@ -231,6 +107,7 @@ function createProgram(handlers2, version) {
231
107
  // src/commands/render.ts
232
108
  import { readFileSync as readFileSync4, existsSync } from "fs";
233
109
  import { resolve, dirname } from "path";
110
+ import ts2 from "typescript";
234
111
 
235
112
  // src/commands/io.ts
236
113
  import { readFileSync, writeFileSync } from "fs";
@@ -3142,6 +3019,7 @@ function parseIr(json) {
3142
3019
  }
3143
3020
 
3144
3021
  // src/parser/tokenizer.ts
3022
+ var DEFERRED_VERBS = /* @__PURE__ */ new Set(["config"]);
3145
3023
  var SHAPE_PATTERNS = [
3146
3024
  { shape: "capsule", open: "([", close: "])" },
3147
3025
  { shape: "cylinder", open: "[(", close: ")]" },
@@ -3237,6 +3115,15 @@ function parseNodeRef(s) {
3237
3115
  function tokenizeLine(line, lineNum) {
3238
3116
  const trimmed = line.trim();
3239
3117
  if (trimmed === "") return null;
3118
+ if (trimmed.startsWith("%%@")) {
3119
+ const directive = parseCommentDirective(trimmed, line, lineNum);
3120
+ if (directive) return directive;
3121
+ const verb = trimmed.slice(3).trim().split(/[\s:]/, 1)[0];
3122
+ if (verb && DEFERRED_VERBS.has(verb)) {
3123
+ return { type: "comment", raw: line, line: lineNum };
3124
+ }
3125
+ return { type: "unknownDirective", raw: line, line: lineNum, verb };
3126
+ }
3240
3127
  if (trimmed.startsWith("%%")) {
3241
3128
  return { type: "comment", raw: line, line: lineNum };
3242
3129
  }
@@ -3249,14 +3136,15 @@ function tokenizeLine(line, lineNum) {
3249
3136
  }
3250
3137
  return { type: "direction", raw: line, line: lineNum, dir };
3251
3138
  }
3252
- const subMatch = trimmed.match(/^subgraph\s+(\S+)(?:\s+\[([^\]]*)\])?\s*$/);
3139
+ const subMatch = trimmed.match(/^subgraph\s+([^\s:]+)(?:\s+\[([^\]]*)\])?(?::::([a-zA-Z_][a-zA-Z0-9_-]*))?\s*$/);
3253
3140
  if (subMatch) {
3254
3141
  return {
3255
3142
  type: "subgraphStart",
3256
3143
  raw: line,
3257
3144
  line: lineNum,
3258
3145
  subgraphId: subMatch[1],
3259
- label: subMatch[2] ?? void 0
3146
+ label: subMatch[2] ?? void 0,
3147
+ variant: subMatch[3] ?? void 0
3260
3148
  };
3261
3149
  }
3262
3150
  if (trimmed === "end") {
@@ -3279,12 +3167,12 @@ function tokenizeLine(line, lineNum) {
3279
3167
  };
3280
3168
  }
3281
3169
  if (trimmed.startsWith("@")) {
3282
- return parseDirective(trimmed, line, lineNum);
3170
+ return parseDirective(trimmed, line, lineNum, true);
3283
3171
  }
3284
3172
  return parseEdgeOrNodeLine(trimmed, line, lineNum);
3285
3173
  }
3286
3174
  var SAME_SIZE_DEFAULT_STRATEGY = "max";
3287
- function parseDirective(trimmed, raw, lineNum) {
3175
+ function parseDirective(trimmed, raw, lineNum, deprecated) {
3288
3176
  const sameWidthMatch = trimmed.match(/^@same-width(?:\s+(\w+))?:\s*(.+)$/);
3289
3177
  if (sameWidthMatch) {
3290
3178
  const strategy = sameWidthMatch[1] ?? SAME_SIZE_DEFAULT_STRATEGY;
@@ -3295,7 +3183,8 @@ function parseDirective(trimmed, raw, lineNum) {
3295
3183
  line: lineNum,
3296
3184
  directiveType: "same-width",
3297
3185
  strategy,
3298
- targets
3186
+ targets,
3187
+ deprecated
3299
3188
  };
3300
3189
  }
3301
3190
  const sameHeightMatch = trimmed.match(/^@same-height(?:\s+(\w+))?:\s*(.+)$/);
@@ -3308,7 +3197,8 @@ function parseDirective(trimmed, raw, lineNum) {
3308
3197
  line: lineNum,
3309
3198
  directiveType: "same-height",
3310
3199
  strategy,
3311
- targets
3200
+ targets,
3201
+ deprecated
3312
3202
  };
3313
3203
  }
3314
3204
  const gapMatch = trimmed.match(/^@gap\s+min=(\d+):\s*(.+)$/);
@@ -3321,7 +3211,8 @@ function parseDirective(trimmed, raw, lineNum) {
3321
3211
  line: lineNum,
3322
3212
  directiveType: "gap",
3323
3213
  min,
3324
- targets
3214
+ targets,
3215
+ deprecated
3325
3216
  };
3326
3217
  }
3327
3218
  const moverMatch = trimmed.match(/^@mover\s+(\S+):\s*(.+)$/);
@@ -3334,11 +3225,216 @@ function parseDirective(trimmed, raw, lineNum) {
3334
3225
  line: lineNum,
3335
3226
  directiveType: "mover",
3336
3227
  moverId,
3337
- targets
3228
+ targets,
3229
+ deprecated
3230
+ };
3231
+ }
3232
+ return null;
3233
+ }
3234
+ function parseCommentDirective(trimmed, raw, lineNum) {
3235
+ const body = trimmed.slice(3).trim();
3236
+ const useMatch = body.match(/^use\s+(.+)$/);
3237
+ if (useMatch) {
3238
+ return {
3239
+ type: "bindingDirective",
3240
+ raw,
3241
+ line: lineNum,
3242
+ verb: "use",
3243
+ specifier: useMatch[1].trim()
3244
+ };
3245
+ }
3246
+ const bindMatch = body.match(/^bind\s+(.+?)\s*=\s*(.+)$/);
3247
+ if (bindMatch) {
3248
+ const selector = parseSelector(bindMatch[1].trim());
3249
+ if (!selector) return null;
3250
+ const call = parseComponentCall(bindMatch[2].trim());
3251
+ if (!call) return null;
3252
+ return {
3253
+ type: "bindingDirective",
3254
+ raw,
3255
+ line: lineNum,
3256
+ verb: "bind",
3257
+ selector,
3258
+ component: call.component,
3259
+ props: call.props
3260
+ };
3261
+ }
3262
+ const propsMatch = body.match(/^props\s+(.+?):\s*(.+)$/);
3263
+ if (propsMatch) {
3264
+ const selector = parseSelector(propsMatch[1].trim());
3265
+ if (!selector) return null;
3266
+ return {
3267
+ type: "bindingDirective",
3268
+ raw,
3269
+ line: lineNum,
3270
+ verb: "props",
3271
+ selector,
3272
+ props: parseStyleProps(propsMatch[2])
3338
3273
  };
3339
3274
  }
3275
+ const sameSizeMatch = body.match(/^same-size\s+(width|height)(?:\s+(\w+))?:\s*(.+)$/);
3276
+ if (sameSizeMatch) {
3277
+ const dim = sameSizeMatch[1];
3278
+ const strategyToken = sameSizeMatch[2] ? ` ${sameSizeMatch[2]}` : "";
3279
+ const bare = `@same-${dim}${strategyToken}: ${sameSizeMatch[3]}`;
3280
+ return parseDirective(bare, raw, lineNum, false);
3281
+ }
3282
+ if (body.startsWith("gap") || body.startsWith("mover")) {
3283
+ return parseDirective(`@${body}`, raw, lineNum, false);
3284
+ }
3285
+ const themeMatch = body.match(/^theme\s+(.+)$/);
3286
+ if (themeMatch) {
3287
+ return {
3288
+ type: "styleDirective",
3289
+ raw,
3290
+ line: lineNum,
3291
+ verb: "theme",
3292
+ name: themeMatch[1].trim()
3293
+ };
3294
+ }
3295
+ const docMatch = body.match(/^doc\s+(.+)$/);
3296
+ if (docMatch) {
3297
+ return {
3298
+ type: "styleDirective",
3299
+ raw,
3300
+ line: lineNum,
3301
+ verb: "doc",
3302
+ // `doc` uses space-separated pairs (`padding=20 fontFamily="…"`); `style`
3303
+ // uses comma-separated pairs (§3.1 examples).
3304
+ props: parseStyleProps(docMatch[1], "space")
3305
+ };
3306
+ }
3307
+ const variantMatch = body.match(/^variant\s+(.+?):\s*(.+)$/);
3308
+ if (variantMatch) {
3309
+ const selector = parseSelector(variantMatch[1].trim());
3310
+ if (!selector) return null;
3311
+ return {
3312
+ type: "styleDirective",
3313
+ raw,
3314
+ line: lineNum,
3315
+ verb: "variant",
3316
+ selector,
3317
+ name: variantMatch[2].trim()
3318
+ };
3319
+ }
3320
+ const styleMatch = body.match(/^style\s+(.+?):\s*(.+)$/);
3321
+ if (styleMatch) {
3322
+ const selector = parseSelector(styleMatch[1].trim());
3323
+ if (!selector) return null;
3324
+ return {
3325
+ type: "styleDirective",
3326
+ raw,
3327
+ line: lineNum,
3328
+ verb: "style",
3329
+ selector,
3330
+ props: parseStyleProps(styleMatch[2])
3331
+ };
3332
+ }
3333
+ return null;
3334
+ }
3335
+ function parseSelector(raw) {
3336
+ const s = raw.trim();
3337
+ if (s === "*") return { kind: "all" };
3338
+ const subgraphMatch = s.match(/^subgraph\(\s*(.+?)\s*\)$/);
3339
+ if (subgraphMatch) {
3340
+ return { kind: "subgraph", ref: subgraphMatch[1] };
3341
+ }
3342
+ const shapeMatch = s.match(/^shape\(\s*([a-zA-Z_][a-zA-Z0-9_-]*)\s*\)$/);
3343
+ if (shapeMatch) {
3344
+ return { kind: "shape", name: shapeMatch[1] };
3345
+ }
3346
+ if (s.startsWith(".")) {
3347
+ const classMatch = s.match(/^\.([a-zA-Z_][a-zA-Z0-9_-]*)$/);
3348
+ if (!classMatch) return null;
3349
+ return { kind: "class", name: classMatch[1] };
3350
+ }
3351
+ if (s.startsWith("#")) {
3352
+ const ids = s.split(",").map((part) => part.trim()).map((part) => part.startsWith("#") ? part.slice(1).trim() : "").filter(Boolean);
3353
+ if (ids.length === 0) return null;
3354
+ return { kind: "id", ids };
3355
+ }
3340
3356
  return null;
3341
3357
  }
3358
+ function parseComponentCall(raw) {
3359
+ const s = raw.trim();
3360
+ const bare = s.match(/^([A-Za-z_][A-Za-z0-9_]*)$/);
3361
+ if (bare) return { component: bare[1], props: [] };
3362
+ const call = s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*\(\s*(.*?)\s*\)$/);
3363
+ if (!call) return null;
3364
+ const component = call[1];
3365
+ const props = [];
3366
+ for (const part of splitTopLevel(call[2], "comma")) {
3367
+ const eq = part.indexOf("=");
3368
+ if (eq === -1) return null;
3369
+ const param = part.slice(0, eq).trim();
3370
+ const rawValue = part.slice(eq + 1).trim();
3371
+ if (!param) return null;
3372
+ props.push({ param, value: parseBindValue(rawValue) });
3373
+ }
3374
+ return { component, props };
3375
+ }
3376
+ function parseBindValue(raw) {
3377
+ if (raw.startsWith("@")) {
3378
+ const ref = raw.slice(1);
3379
+ if (ref === "label") return { kind: "source", source: "label" };
3380
+ if (ref === "id") return { kind: "source", source: "id" };
3381
+ if (ref === "shape") return { kind: "source", source: "shape" };
3382
+ const propsMatch = ref.match(/^props\.([A-Za-z_][A-Za-z0-9_-]*)$/);
3383
+ if (propsMatch) return { kind: "source", source: "props", key: propsMatch[1] };
3384
+ return { kind: "literal", value: raw };
3385
+ }
3386
+ return { kind: "literal", value: coerceValue(raw) };
3387
+ }
3388
+ function parseStyleProps(input, sep = "comma") {
3389
+ const props = [];
3390
+ for (const part of splitTopLevel(input, sep)) {
3391
+ const eq = part.indexOf("=");
3392
+ if (eq === -1) continue;
3393
+ const key = part.slice(0, eq).trim();
3394
+ const rawValue = part.slice(eq + 1).trim();
3395
+ if (!key) continue;
3396
+ props.push({ key, value: coerceValue(rawValue), rawValue });
3397
+ }
3398
+ return props;
3399
+ }
3400
+ function splitTopLevel(input, sep) {
3401
+ const parts = [];
3402
+ let depth = 0;
3403
+ let quote = null;
3404
+ let current = "";
3405
+ const isSep = (ch) => sep === "comma" ? ch === "," : /\s/.test(ch);
3406
+ for (const ch of input) {
3407
+ if (quote) {
3408
+ current += ch;
3409
+ if (ch === quote) quote = null;
3410
+ continue;
3411
+ }
3412
+ if (ch === '"' || ch === "'") {
3413
+ quote = ch;
3414
+ current += ch;
3415
+ continue;
3416
+ }
3417
+ if (ch === "{") depth++;
3418
+ else if (ch === "}") depth = Math.max(0, depth - 1);
3419
+ if (isSep(ch) && depth === 0) {
3420
+ if (current.trim()) parts.push(current.trim());
3421
+ current = "";
3422
+ continue;
3423
+ }
3424
+ current += ch;
3425
+ }
3426
+ if (current.trim()) parts.push(current.trim());
3427
+ return parts;
3428
+ }
3429
+ function coerceValue(raw) {
3430
+ if (/^-?\d+(\.\d+)?$/.test(raw)) {
3431
+ return Number(raw);
3432
+ }
3433
+ if (raw.startsWith('"') && raw.endsWith('"') || raw.startsWith("'") && raw.endsWith("'")) {
3434
+ return raw.slice(1, -1);
3435
+ }
3436
+ return raw;
3437
+ }
3342
3438
  function parseEdgeOrNodeLine(trimmed, raw, lineNum) {
3343
3439
  const firstRef = parseNodeRef(trimmed);
3344
3440
  if (!firstRef) return null;
@@ -3429,84 +3525,625 @@ function tokenize(source) {
3429
3525
  return tokens;
3430
3526
  }
3431
3527
 
3432
- // src/parser/parser.ts
3433
- function parseDrawText(source) {
3434
- const diagnostics = [];
3435
- const tokens = tokenize(source);
3436
- let rootDirection = "TD";
3437
- const nodeMap = /* @__PURE__ */ new Map();
3438
- const connectors = [];
3439
- const constraints = [];
3440
- const classDefMap = /* @__PURE__ */ new Map();
3441
- const scopeStack = [];
3442
- const groups = [];
3443
- const rootNodeIds = [];
3444
- function currentDirection() {
3445
- for (let i = scopeStack.length - 1; i >= 0; i--) {
3446
- if (scopeStack[i].direction) return scopeStack[i].direction;
3447
- }
3448
- return rootDirection;
3449
- }
3450
- function registerNode(id, label, shape, variant) {
3451
- if (!nodeMap.has(id)) {
3452
- nodeMap.set(id, { id, label, shape, variant });
3453
- }
3454
- if (scopeStack.length > 0) {
3455
- const top = scopeStack[scopeStack.length - 1];
3456
- if (!top.nodeIds.includes(id)) top.nodeIds.push(id);
3457
- } else {
3458
- if (!rootNodeIds.includes(id)) rootNodeIds.push(id);
3459
- }
3528
+ // src/component/expand.ts
3529
+ function isParamRef(v) {
3530
+ return typeof v === "object" && v !== null && v.__paramRef === true;
3531
+ }
3532
+ function isTemplateRef(v) {
3533
+ return typeof v === "object" && v !== null && v.__templateRef === true;
3534
+ }
3535
+ function isExprRef(v) {
3536
+ return typeof v === "object" && v !== null && v.__exprRef === true;
3537
+ }
3538
+ function isDeferred(v) {
3539
+ return isParamRef(v) || isExprRef(v);
3540
+ }
3541
+ var NOT_SET = /* @__PURE__ */ Symbol("diagram-contracts.notSet");
3542
+ function foldBinary(op, left, right, report) {
3543
+ if (left === NOT_SET || right === NOT_SET) {
3544
+ report?.(
3545
+ `operator '${op}' cannot be applied to null/undefined \u2014 null/undefined is only valid as the entire prop value ("prop not set")`
3546
+ );
3547
+ return void 0;
3460
3548
  }
3461
- function ensureNode(id) {
3462
- if (nodeMap.has(id)) return;
3463
- nodeMap.set(id, { id, label: id, shape: "roundedRect" });
3464
- if (scopeStack.length > 0) {
3465
- const top = scopeStack[scopeStack.length - 1];
3466
- if (!top.nodeIds.includes(id)) top.nodeIds.push(id);
3467
- } else {
3468
- if (!rootNodeIds.includes(id)) rootNodeIds.push(id);
3549
+ if (left === void 0 || right === void 0) return void 0;
3550
+ if (isDeferred(left) || isDeferred(right)) {
3551
+ for (const operand of [left, right]) {
3552
+ if (!isDeferred(operand) && typeof operand !== "number" && typeof operand !== "string") {
3553
+ report?.(`operator '${op}' does not support ${typeof operand} operands`);
3554
+ return void 0;
3555
+ }
3469
3556
  }
3557
+ return { __exprRef: true, op, left, right };
3470
3558
  }
3471
- for (const token of tokens) {
3472
- switch (token.type) {
3473
- case "comment":
3559
+ if (typeof left === "number" && typeof right === "number") {
3560
+ let result;
3561
+ switch (op) {
3562
+ case "+":
3563
+ result = left + right;
3474
3564
  break;
3475
- case "direction":
3476
- rootDirection = token.dir;
3565
+ case "-":
3566
+ result = left - right;
3477
3567
  break;
3478
- case "nodeDef": {
3479
- const t = token;
3480
- registerNode(t.nodeId, t.label, t.shape, t.variant);
3568
+ case "*":
3569
+ result = left * right;
3481
3570
  break;
3482
- }
3483
- case "edge": {
3484
- const t = token;
3485
- for (const seg of t.segments) {
3486
- processEdgeSegment(seg);
3487
- }
3571
+ case "/":
3572
+ result = left / right;
3573
+ break;
3574
+ case "%":
3575
+ result = left % right;
3488
3576
  break;
3577
+ }
3578
+ if (!Number.isFinite(result)) {
3579
+ report?.(`arithmetic result is not a finite number (${left} ${op} ${right}) \u2014 division by zero?`);
3580
+ return void 0;
3581
+ }
3582
+ return result;
3583
+ }
3584
+ if (op === "+" && typeof left === "string" && typeof right === "string") {
3585
+ return left + right;
3586
+ }
3587
+ report?.(
3588
+ `operator '${op}' requires two numbers${op === "+" ? " or two strings" : ""} (got ${typeof left} and ${typeof right})`
3589
+ );
3590
+ return void 0;
3591
+ }
3592
+ function foldUnaryMinus(operand, report) {
3593
+ if (operand === NOT_SET) {
3594
+ report?.(
3595
+ `unary minus cannot be applied to null/undefined \u2014 null/undefined is only valid as the entire prop value ("prop not set")`
3596
+ );
3597
+ return void 0;
3598
+ }
3599
+ if (operand === void 0) return void 0;
3600
+ if (typeof operand === "number") {
3601
+ return -operand;
3602
+ }
3603
+ if (isDeferred(operand)) {
3604
+ return { __exprRef: true, op: "neg", left: operand };
3605
+ }
3606
+ report?.(`unary minus requires a numeric operand (got ${typeof operand})`);
3607
+ return void 0;
3608
+ }
3609
+ function substituteValue(value, paramValues, report, only) {
3610
+ if (isParamRef(value)) {
3611
+ if (only && !only.has(value.name)) return value;
3612
+ return paramValues[value.name];
3613
+ }
3614
+ if (isExprRef(value)) {
3615
+ const substituteOperand = (operand) => {
3616
+ const resolved = substituteValue(operand, paramValues, report, only);
3617
+ if (resolved === void 0 && isParamRef(operand) && (!only || only.has(operand.name))) {
3618
+ report?.(`cannot evaluate expression \u2014 prop "${operand.name}" was not provided`);
3489
3619
  }
3490
- case "invisibleEdge": {
3491
- const t = token;
3492
- for (const seg of t.segments) {
3493
- ensureNode(seg.fromId);
3494
- ensureNode(seg.toId);
3620
+ return resolved;
3621
+ };
3622
+ const left = substituteOperand(value.left);
3623
+ if (value.op === "neg") {
3624
+ return foldUnaryMinus(left, report);
3625
+ }
3626
+ const right = substituteOperand(value.right);
3627
+ return foldBinary(value.op, left, right, report);
3628
+ }
3629
+ if (isTemplateRef(value)) {
3630
+ const newParts = [];
3631
+ for (const part of value.parts) {
3632
+ if (isParamRef(part)) {
3633
+ if (only && !only.has(part.name)) {
3634
+ newParts.push(part);
3635
+ continue;
3495
3636
  }
3496
- const dir = currentDirection();
3497
- const allIds = /* @__PURE__ */ new Set();
3498
- for (const seg of t.segments) {
3499
- allIds.add(seg.fromId);
3500
- allIds.add(seg.toId);
3637
+ const resolved = paramValues[part.name];
3638
+ if (resolved === void 0) {
3639
+ } else if (typeof resolved === "string") {
3640
+ newParts.push(resolved);
3641
+ } else if (isParamRef(resolved) || isExprRef(resolved)) {
3642
+ newParts.push(resolved);
3643
+ } else if (isTemplateRef(resolved)) {
3644
+ newParts.push(...resolved.parts);
3645
+ } else {
3646
+ newParts.push(String(resolved));
3501
3647
  }
3502
- constraints.push(buildAlignConstraint([...allIds], dir));
3503
- break;
3648
+ } else if (isExprRef(part)) {
3649
+ const resolved = substituteValue(part, paramValues, report, only);
3650
+ if (resolved === void 0) {
3651
+ } else if (isDeferred(resolved)) {
3652
+ newParts.push(resolved);
3653
+ } else {
3654
+ newParts.push(String(resolved));
3655
+ }
3656
+ } else {
3657
+ newParts.push(part);
3658
+ }
3659
+ }
3660
+ const allStrings = newParts.every((p) => typeof p === "string");
3661
+ if (allStrings) {
3662
+ return newParts.join("");
3663
+ }
3664
+ return { __templateRef: true, parts: newParts };
3665
+ }
3666
+ if (Array.isArray(value)) {
3667
+ return value.map((item) => substituteValue(item, paramValues, report, only));
3668
+ }
3669
+ if (typeof value === "object" && value !== null) {
3670
+ const result = {};
3671
+ for (const [k, v] of Object.entries(value)) {
3672
+ result[k] = substituteValue(v, paramValues, report, only);
3673
+ }
3674
+ return result;
3675
+ }
3676
+ return value;
3677
+ }
3678
+ function deepCloneAndSubstitute(node, paramValues, compiledChildren, diagnostics, componentName, only) {
3679
+ const cloned = { kind: node.kind, props: {} };
3680
+ if (node.id) cloned.id = node.id;
3681
+ const makeReporter = (propName) => (message) => {
3682
+ diagnostics.push({
3683
+ level: "error",
3684
+ message: `<${componentName}> (expanding <${node.kind}> prop "${propName}"): ${message}`,
3685
+ path: componentName
3686
+ });
3687
+ };
3688
+ for (const [key, value] of Object.entries(node.props)) {
3689
+ if (key === "__childrenSlot") continue;
3690
+ if (key === "__idParam") {
3691
+ const resolved = substituteValue(value, paramValues, makeReporter("id"), only);
3692
+ if (typeof resolved === "string") {
3693
+ cloned.id = resolved;
3694
+ } else if (isParamRef(resolved) || isTemplateRef(resolved) || isExprRef(resolved)) {
3695
+ cloned.props["__idParam"] = resolved;
3696
+ }
3697
+ continue;
3698
+ }
3699
+ const substituted = substituteValue(value, paramValues, makeReporter(key), only);
3700
+ if (substituted !== void 0) {
3701
+ cloned.props[key] = substituted;
3702
+ }
3703
+ }
3704
+ if (node.children) {
3705
+ const newChildren = [];
3706
+ for (const child of node.children) {
3707
+ if (child.props.__childrenSlot === true) {
3708
+ newChildren.push(...compiledChildren);
3709
+ } else {
3710
+ newChildren.push(deepCloneAndSubstitute(child, paramValues, compiledChildren, diagnostics, componentName, only));
3711
+ }
3712
+ }
3713
+ if (newChildren.length > 0) cloned.children = newChildren;
3714
+ }
3715
+ return cloned;
3716
+ }
3717
+ function expandComponent(def, paramValues, compiledChildren, diagnostics, extraProps, id, idIsParam) {
3718
+ const expanded = deepCloneAndSubstitute(def.template, paramValues, compiledChildren, diagnostics, def.name);
3719
+ Object.assign(expanded.props, extraProps);
3720
+ if (id && !idIsParam) expanded.id = id;
3721
+ return expanded;
3722
+ }
3723
+ function componentDefToJSON(def) {
3724
+ return {
3725
+ name: def.name,
3726
+ paramNames: [...def.paramNames].sort(),
3727
+ template: def.template
3728
+ };
3729
+ }
3730
+ function componentDefFromJSON(json) {
3731
+ return {
3732
+ name: json.name,
3733
+ paramNames: new Set(json.paramNames),
3734
+ template: json.template
3735
+ };
3736
+ }
3737
+
3738
+ // src/binding/index.ts
3739
+ var COMPONENT_TAG_KIND = "component";
3740
+ function isComponentTag(node) {
3741
+ return node.kind === COMPONENT_TAG_KIND && typeof node.props.__component === "string";
3742
+ }
3743
+ function selectorMatchesNode(selector, node) {
3744
+ switch (selector.kind) {
3745
+ case "id":
3746
+ return selector.ids.includes(node.id);
3747
+ case "class":
3748
+ return node.variant === selector.name;
3749
+ case "shape":
3750
+ return node.shape === selector.name;
3751
+ case "all":
3752
+ return true;
3753
+ case "subgraph":
3754
+ return false;
3755
+ }
3756
+ }
3757
+ function selectorMatchesGroup(selector, group) {
3758
+ if (selector.kind !== "subgraph") return false;
3759
+ const ref = selector.ref.trim();
3760
+ if (ref.startsWith("#")) return group.id === ref.slice(1).trim();
3761
+ if (ref.startsWith(".")) return group.variant === ref.slice(1).trim();
3762
+ return group.id === ref;
3763
+ }
3764
+ function bindSpecificity(selector) {
3765
+ switch (selector.kind) {
3766
+ case "id":
3767
+ return 4;
3768
+ case "subgraph":
3769
+ return selector.ref.trim().startsWith("#") ? 4 : 3;
3770
+ case "class":
3771
+ return 3;
3772
+ case "shape":
3773
+ return 2;
3774
+ case "all":
3775
+ return 1;
3776
+ }
3777
+ }
3778
+ function pickBind(binds, matches) {
3779
+ let winner;
3780
+ let winnerSpec = -1;
3781
+ binds.forEach((b) => {
3782
+ if (!matches(b.selector)) return;
3783
+ const spec = bindSpecificity(b.selector);
3784
+ if (spec >= winnerSpec) {
3785
+ winner = b;
3786
+ winnerSpec = spec;
3787
+ }
3788
+ });
3789
+ return winner;
3790
+ }
3791
+ function resolvePropValue(prop, target, componentName, line, diagnostics) {
3792
+ const v = prop.value;
3793
+ if (v.kind === "literal") return v.value;
3794
+ switch (v.source) {
3795
+ case "label":
3796
+ return target.label;
3797
+ case "id":
3798
+ return target.id;
3799
+ case "shape":
3800
+ return target.shape;
3801
+ case "props": {
3802
+ const key = v.key;
3803
+ const found = target.propsMap?.[key];
3804
+ if (found === void 0) {
3805
+ diagnostics.push({
3806
+ level: "warning",
3807
+ message: `bind ${componentName}(${prop.param}=@props.${key}): node '${target.id}' has no '%%@ props' value for '${key}'; the param is left unset.`,
3808
+ path: `line:${line}`
3809
+ });
3810
+ return void 0;
3811
+ }
3812
+ return found;
3813
+ }
3814
+ }
3815
+ }
3816
+ function buildResolvedProps(bind, def, target, diagnostics) {
3817
+ const resolved = {};
3818
+ const mapped = /* @__PURE__ */ new Set();
3819
+ for (const prop of bind.props) {
3820
+ if (!def.paramNames.has(prop.param)) {
3821
+ const allowed = [...def.paramNames].filter((p) => p !== "children").sort().join(", ") || "(none)";
3822
+ diagnostics.push({
3823
+ level: "warning",
3824
+ message: `bind <${bind.component}>: unknown prop '${prop.param}' \u2014 <${bind.component}> declares: ${allowed}. Ignored.`,
3825
+ path: `line:${bind.line}`
3826
+ });
3827
+ continue;
3828
+ }
3829
+ const value = resolvePropValue(prop, target, bind.component, bind.line, diagnostics);
3830
+ if (value !== void 0) {
3831
+ resolved[prop.param] = value;
3832
+ mapped.add(prop.param);
3833
+ }
3834
+ }
3835
+ if (def.paramNames.has("id") && !mapped.has("id")) {
3836
+ resolved.id = target.id;
3837
+ }
3838
+ if (def.paramNames.has("label") && !mapped.has("label")) {
3839
+ resolved.label = target.label;
3840
+ }
3841
+ return resolved;
3842
+ }
3843
+ function buildBoxNode(node) {
3844
+ const props = { shape: node.shape };
3845
+ if (node.variant) props.variant = node.variant;
3846
+ if (node.styleProps) Object.assign(props, node.styleProps);
3847
+ return {
3848
+ kind: "box",
3849
+ id: node.id,
3850
+ props,
3851
+ children: [{ kind: "text", props: { text: node.label } }]
3852
+ };
3853
+ }
3854
+ function styleOverlayFor(variant, styleProps, resolvedProps) {
3855
+ const overlay = {};
3856
+ if (variant !== void 0 && !("variant" in resolvedProps)) {
3857
+ overlay.variant = variant;
3858
+ }
3859
+ if (styleProps) {
3860
+ for (const [key, value] of Object.entries(styleProps)) {
3861
+ if (!(key in resolvedProps)) overlay[key] = value;
3862
+ }
3863
+ }
3864
+ return overlay;
3865
+ }
3866
+ function buildComponentTag(componentName, id, resolvedProps, children, styleOverlay) {
3867
+ const node = {
3868
+ kind: COMPONENT_TAG_KIND,
3869
+ id,
3870
+ props: { __component: componentName, ...resolvedProps, ...styleOverlay }
3871
+ };
3872
+ if (children && children.length > 0) node.children = children;
3873
+ return node;
3874
+ }
3875
+ function buildLeafNode(node, ctx) {
3876
+ const bind = pickBind(ctx.binds, (sel) => selectorMatchesNode(sel, node));
3877
+ if (!bind) return buildBoxNode(node);
3878
+ const def = ctx.components.get(bind.component);
3879
+ if (!def) {
3880
+ ctx.diagnostics.push({
3881
+ level: "warning",
3882
+ message: `bind <${bind.component}>: component '${bind.component}' is not in scope (no matching '%%@ use'); rendering '${node.id}' as a plain box.`,
3883
+ path: `line:${bind.line}`
3884
+ });
3885
+ return buildBoxNode(node);
3886
+ }
3887
+ const resolved = buildResolvedProps(
3888
+ bind,
3889
+ def,
3890
+ { id: node.id, label: node.label, shape: node.shape, propsMap: node.propsMap },
3891
+ ctx.diagnostics
3892
+ );
3893
+ const overlay = styleOverlayFor(node.variant, node.styleProps, resolved);
3894
+ return buildComponentTag(bind.component, node.id, resolved, void 0, overlay);
3895
+ }
3896
+ function buildGroupNode(group, ctx, model) {
3897
+ const dir = group.direction ?? model.rootDirection;
3898
+ const innerKind = dir === "LR" ? "hstack" : "vstack";
3899
+ const innerChildren = [];
3900
+ for (const childId of group.childIds) {
3901
+ const childGroup = model.groups.get(childId);
3902
+ if (childGroup) {
3903
+ innerChildren.push(buildGroupNode(childGroup, ctx, model));
3904
+ } else {
3905
+ const childNode = model.nodeMap.get(childId);
3906
+ if (childNode) innerChildren.push(buildLeafNode(childNode, ctx));
3907
+ }
3908
+ }
3909
+ const innerStack = {
3910
+ kind: innerKind,
3911
+ props: { gap: 60, align: "center" },
3912
+ children: innerChildren
3913
+ };
3914
+ const bind = pickBind(ctx.binds, (sel) => selectorMatchesGroup(sel, group));
3915
+ if (bind) {
3916
+ const def = ctx.components.get(bind.component);
3917
+ if (!def) {
3918
+ ctx.diagnostics.push({
3919
+ level: "warning",
3920
+ message: `bind <${bind.component}>: component '${bind.component}' is not in scope (no matching '%%@ use'); rendering subgraph '${group.id}' as a plain group.`,
3921
+ path: `line:${bind.line}`
3922
+ });
3923
+ } else if (!def.paramNames.has("children")) {
3924
+ ctx.diagnostics.push({
3925
+ level: "warning",
3926
+ message: `bind subgraph \u2192 <${bind.component}>: component '${bind.component}' has no 'children' slot; a container component is required for a subgraph. Rendering subgraph '${group.id}' as a plain group.`,
3927
+ path: `line:${bind.line}`
3928
+ });
3929
+ } else {
3930
+ const resolved = buildResolvedProps(
3931
+ bind,
3932
+ def,
3933
+ { id: group.id, label: group.label ?? group.id, shape: "rect", propsMap: group.propsMap },
3934
+ ctx.diagnostics
3935
+ );
3936
+ const overlay = styleOverlayFor(group.variant, void 0, resolved);
3937
+ return buildComponentTag(bind.component, group.id, resolved, [innerStack], overlay);
3938
+ }
3939
+ }
3940
+ const groupNode = {
3941
+ kind: "group",
3942
+ id: group.id,
3943
+ props: {},
3944
+ children: [innerStack]
3945
+ };
3946
+ return groupNode;
3947
+ }
3948
+ function buildDslTree(model, ctx) {
3949
+ const stackKind = model.rootDirection === "LR" ? "hstack" : "vstack";
3950
+ const rootChildren = [];
3951
+ for (const id of model.rootNodeIds) {
3952
+ const group = model.groups.get(id);
3953
+ if (group) {
3954
+ rootChildren.push(buildGroupNode(group, ctx, model));
3955
+ } else {
3956
+ const node = model.nodeMap.get(id);
3957
+ if (node) rootChildren.push(buildLeafNode(node, ctx));
3958
+ }
3959
+ }
3960
+ const rootStack = {
3961
+ kind: stackKind,
3962
+ props: { gap: 60, align: "center" },
3963
+ children: rootChildren
3964
+ };
3965
+ warnZeroMatchBinds(model, ctx);
3966
+ return {
3967
+ kind: "document",
3968
+ props: { padding: 20, ...model.docProps },
3969
+ children: [rootStack, ...model.connectors, ...model.constraints]
3970
+ };
3971
+ }
3972
+ function warnZeroMatchBinds(model, ctx) {
3973
+ for (const bind of ctx.binds) {
3974
+ if (bind.line === 0) continue;
3975
+ let matched = false;
3976
+ for (const node of model.nodeMap.values()) {
3977
+ if (selectorMatchesNode(bind.selector, node)) {
3978
+ matched = true;
3979
+ break;
3980
+ }
3981
+ }
3982
+ if (!matched) {
3983
+ for (const group of model.groups.values()) {
3984
+ if (selectorMatchesGroup(bind.selector, group)) {
3985
+ matched = true;
3986
+ break;
3987
+ }
3988
+ }
3989
+ }
3990
+ if (!matched) {
3991
+ ctx.diagnostics.push({
3992
+ level: "warning",
3993
+ message: `Selector '${bind.raw.trim()}' (%%@ bind) matched no nodes.`,
3994
+ path: `line:${bind.line}`
3995
+ });
3996
+ }
3997
+ }
3998
+ }
3999
+ function expandDsl(node, components, diagnostics, expandingStack = /* @__PURE__ */ new Set()) {
4000
+ const expandedChildren = node.children?.map(
4001
+ (c) => expandDsl(c, components, diagnostics, expandingStack)
4002
+ );
4003
+ if (isComponentTag(node)) {
4004
+ const componentName = node.props.__component;
4005
+ const def = components.get(componentName);
4006
+ if (!def) {
4007
+ diagnostics.push({
4008
+ level: "error",
4009
+ message: `Internal: component tag <${componentName}> reached expansion with no definition.`,
4010
+ path: componentName
4011
+ });
4012
+ return { kind: "group", props: {}, children: expandedChildren ?? [] };
4013
+ }
4014
+ if (expandingStack.has(componentName)) {
4015
+ diagnostics.push({
4016
+ level: "error",
4017
+ message: `Circular component reference: ${componentName}`,
4018
+ path: componentName
4019
+ });
4020
+ return { kind: "group", props: {}, children: expandedChildren ?? [] };
4021
+ }
4022
+ expandingStack.add(componentName);
4023
+ const id = node.id;
4024
+ const idIsParam = def.paramNames.has("id");
4025
+ const paramValues = {};
4026
+ const extraProps = {};
4027
+ for (const [key, value] of Object.entries(node.props)) {
4028
+ if (key === "__component") continue;
4029
+ if (def.paramNames.has(key)) {
4030
+ paramValues[key] = value;
4031
+ } else {
4032
+ extraProps[key] = value;
4033
+ }
4034
+ }
4035
+ const expanded = expandComponent(
4036
+ def,
4037
+ paramValues,
4038
+ expandedChildren ?? [],
4039
+ /* fallback-ok: a leaf component tag has no children (undefined) → an empty children list is the correct "no {children} slot content" passed to the shared expander */
4040
+ diagnostics,
4041
+ extraProps,
4042
+ id,
4043
+ idIsParam
4044
+ );
4045
+ expandingStack.delete(componentName);
4046
+ return expanded;
4047
+ }
4048
+ const cloned = { kind: node.kind, props: { ...node.props } };
4049
+ if (node.id) cloned.id = node.id;
4050
+ if (expandedChildren) cloned.children = expandedChildren;
4051
+ return cloned;
4052
+ }
4053
+
4054
+ // src/parser/parser.ts
4055
+ var SELECTOR_SPECIFICITY = {
4056
+ id: 4,
4057
+ class: 3,
4058
+ shape: 2,
4059
+ subgraph: 3,
4060
+ // reserved for #61; ranked with `.class` but not yet applied
4061
+ all: 1
4062
+ };
4063
+ function parseDrawText(source, options) {
4064
+ const diagnostics = [];
4065
+ const tokens = tokenize(source);
4066
+ let rootDirection = "TD";
4067
+ const nodeMap = /* @__PURE__ */ new Map();
4068
+ const connectors = [];
4069
+ const constraints = [];
4070
+ const classDefMap = /* @__PURE__ */ new Map();
4071
+ const scopeStack = [];
4072
+ const groups = [];
4073
+ const rootNodeIds = [];
4074
+ const styleDirectives = [];
4075
+ const useDirectives = [];
4076
+ const bindDirectives = [];
4077
+ const propsDirectives = [];
4078
+ const docProps = { ...options?.doc ?? {} };
4079
+ let theme;
4080
+ function currentDirection() {
4081
+ for (let i = scopeStack.length - 1; i >= 0; i--) {
4082
+ if (scopeStack[i].direction) return scopeStack[i].direction;
4083
+ }
4084
+ return rootDirection;
4085
+ }
4086
+ function registerNode(id, label, shape, variant) {
4087
+ if (!nodeMap.has(id)) {
4088
+ nodeMap.set(id, { id, label, shape, variant });
4089
+ }
4090
+ if (scopeStack.length > 0) {
4091
+ const top = scopeStack[scopeStack.length - 1];
4092
+ if (!top.nodeIds.includes(id)) top.nodeIds.push(id);
4093
+ } else {
4094
+ if (!rootNodeIds.includes(id)) rootNodeIds.push(id);
4095
+ }
4096
+ }
4097
+ function ensureNode(id) {
4098
+ if (nodeMap.has(id)) return;
4099
+ nodeMap.set(id, { id, label: id, shape: "roundedRect" });
4100
+ if (scopeStack.length > 0) {
4101
+ const top = scopeStack[scopeStack.length - 1];
4102
+ if (!top.nodeIds.includes(id)) top.nodeIds.push(id);
4103
+ } else {
4104
+ if (!rootNodeIds.includes(id)) rootNodeIds.push(id);
4105
+ }
4106
+ }
4107
+ for (const token of tokens) {
4108
+ switch (token.type) {
4109
+ case "comment":
4110
+ break;
4111
+ case "direction":
4112
+ rootDirection = token.dir;
4113
+ break;
4114
+ case "nodeDef": {
4115
+ const t = token;
4116
+ registerNode(t.nodeId, t.label, t.shape, t.variant);
4117
+ break;
4118
+ }
4119
+ case "edge": {
4120
+ const t = token;
4121
+ for (const seg of t.segments) {
4122
+ processEdgeSegment(seg);
4123
+ }
4124
+ break;
4125
+ }
4126
+ case "invisibleEdge": {
4127
+ const t = token;
4128
+ for (const seg of t.segments) {
4129
+ ensureNode(seg.fromId);
4130
+ ensureNode(seg.toId);
4131
+ }
4132
+ const dir = currentDirection();
4133
+ const allIds = /* @__PURE__ */ new Set();
4134
+ for (const seg of t.segments) {
4135
+ allIds.add(seg.fromId);
4136
+ allIds.add(seg.toId);
4137
+ }
4138
+ constraints.push(buildAlignConstraint([...allIds], dir));
4139
+ break;
3504
4140
  }
3505
4141
  case "subgraphStart": {
3506
4142
  const t = token;
3507
4143
  scopeStack.push({
3508
4144
  id: t.subgraphId,
3509
4145
  label: t.label,
4146
+ variant: t.variant,
3510
4147
  nodeIds: []
3511
4148
  });
3512
4149
  break;
@@ -3546,9 +4183,67 @@ function parseDrawText(source) {
3546
4183
  }
3547
4184
  case "directive": {
3548
4185
  const t = token;
4186
+ if (t.deprecated) {
4187
+ diagnostics.push({
4188
+ level: "warning",
4189
+ message: `Bare '@${t.directiveType}' directive is deprecated; use the Mermaid-safe '%%@ ${deprecatedReplacement(t)}' comment form instead (bare '@' lines break vanilla Mermaid).`,
4190
+ path: `line:${t.line}`
4191
+ });
4192
+ }
3549
4193
  processDirective(t);
3550
4194
  break;
3551
4195
  }
4196
+ case "styleDirective": {
4197
+ const t = token;
4198
+ processStyleDirective(t);
4199
+ break;
4200
+ }
4201
+ case "bindingDirective": {
4202
+ const t = token;
4203
+ switch (t.verb) {
4204
+ case "use":
4205
+ useDirectives.push(t);
4206
+ break;
4207
+ case "bind":
4208
+ bindDirectives.push(t);
4209
+ break;
4210
+ case "props":
4211
+ propsDirectives.push(t);
4212
+ break;
4213
+ }
4214
+ break;
4215
+ }
4216
+ case "unknownDirective": {
4217
+ const t = token;
4218
+ diagnostics.push({
4219
+ level: "warning",
4220
+ message: (t.verb ? `Unknown directive verb "${t.verb}"` : "Malformed '%%@' directive") + ` in '${t.raw.trim()}'. Known verbs: style, variant, doc, theme, same-size, gap, mover.`,
4221
+ path: `line:${t.line}`
4222
+ });
4223
+ break;
4224
+ }
4225
+ }
4226
+ }
4227
+ function processStyleDirective(t) {
4228
+ switch (t.verb) {
4229
+ case "theme":
4230
+ theme = t.name;
4231
+ break;
4232
+ case "doc": {
4233
+ const allowed = getAllowedProps("document");
4234
+ for (const p of t.props ?? []) {
4235
+ if (allowed && !allowed.has(p.key)) {
4236
+ diagnostics.push(unknownPropDiagnostic("doc", "document", p.key, t.line, allowed));
4237
+ continue;
4238
+ }
4239
+ docProps[p.key] = p.value;
4240
+ }
4241
+ break;
4242
+ }
4243
+ case "style":
4244
+ case "variant":
4245
+ styleDirectives.push(t);
4246
+ break;
3552
4247
  }
3553
4248
  }
3554
4249
  function processEdgeSegment(seg) {
@@ -3631,77 +4326,217 @@ function parseDrawText(source) {
3631
4326
  }
3632
4327
  }
3633
4328
  }
3634
- const stackKind = rootDirection === "LR" ? "hstack" : "vstack";
3635
- const groupNodes = /* @__PURE__ */ new Map();
3636
- for (const g of groups) {
3637
- const dir = g.frame.direction ?? rootDirection;
3638
- const innerKind = dir === "LR" ? "hstack" : "vstack";
3639
- const groupChildren = [];
3640
- const innerStack = {
3641
- kind: innerKind,
3642
- props: { gap: 60, align: "center" },
3643
- children: []
3644
- };
3645
- for (const childId of g.children) {
3646
- const childGroup = groupNodes.get(childId);
3647
- if (childGroup) {
3648
- innerStack.children.push(childGroup);
4329
+ applyStyleDirectives();
4330
+ function selectorMatches(selector, node) {
4331
+ switch (selector.kind) {
4332
+ case "id":
4333
+ return selector.ids.includes(node.id);
4334
+ case "class":
4335
+ return node.variant === selector.name;
4336
+ case "shape":
4337
+ return node.shape === selector.name;
4338
+ case "all":
4339
+ return true;
4340
+ case "subgraph":
4341
+ return false;
4342
+ }
4343
+ }
4344
+ function applyStyleDirectives() {
4345
+ if (styleDirectives.length === 0) return;
4346
+ const styleAllowed = getAllowedProps("box");
4347
+ const winners = /* @__PURE__ */ new Map();
4348
+ styleDirectives.forEach((t, order) => {
4349
+ const selector = t.selector;
4350
+ const specificity = SELECTOR_SPECIFICITY[selector.kind];
4351
+ if (selector.kind === "subgraph") {
4352
+ diagnostics.push({
4353
+ level: "warning",
4354
+ message: `Selector 'subgraph(${selector.ref})' is not supported for '%%@ ${t.verb}' (subgraph selectors bind container components via '%%@ bind'); directive ignored.`,
4355
+ path: `line:${t.line}`
4356
+ });
4357
+ return;
4358
+ }
4359
+ const validProps = [];
4360
+ if (t.verb === "style") {
4361
+ for (const p of t.props ?? []) {
4362
+ if (styleAllowed && !styleAllowed.has(p.key)) {
4363
+ diagnostics.push(unknownPropDiagnostic("style", "box", p.key, t.line, styleAllowed));
4364
+ continue;
4365
+ }
4366
+ validProps.push({ key: p.key, value: p.value });
4367
+ }
3649
4368
  } else {
3650
- const node = nodeMap.get(childId);
3651
- if (node) {
3652
- innerStack.children.push(buildBox(node));
4369
+ validProps.push({ key: "variant", value: t.name });
4370
+ }
4371
+ let matched = false;
4372
+ for (const node of nodeMap.values()) {
4373
+ if (!selectorMatches(selector, node)) continue;
4374
+ matched = true;
4375
+ let nodeWinners = winners.get(node.id);
4376
+ if (!nodeWinners) {
4377
+ nodeWinners = /* @__PURE__ */ new Map();
4378
+ winners.set(node.id, nodeWinners);
3653
4379
  }
4380
+ for (const { key, value } of validProps) {
4381
+ const prev = nodeWinners.get(key);
4382
+ if (prev && prev.specificity > specificity) continue;
4383
+ nodeWinners.set(key, { specificity, order });
4384
+ if (key === "variant") {
4385
+ node.variant = value;
4386
+ } else {
4387
+ (node.styleProps ??= {})[key] = value;
4388
+ }
4389
+ }
4390
+ }
4391
+ if (!matched) {
4392
+ diagnostics.push({
4393
+ level: "warning",
4394
+ message: `Selector '${t.raw.trim()}' matched no nodes.`,
4395
+ path: `line:${t.line}`
4396
+ });
4397
+ }
4398
+ });
4399
+ }
4400
+ applyPropsDirectives();
4401
+ function applyPropsDirectives() {
4402
+ for (const t of propsDirectives) {
4403
+ let matched = false;
4404
+ for (const node of nodeMap.values()) {
4405
+ if (!selectorMatchesNode(t.selector, nodeToModel(node))) continue;
4406
+ matched = true;
4407
+ const map = node.propsMap ??= {};
4408
+ for (const p of t.props) map[p.key] = p.value;
4409
+ }
4410
+ for (const g of groups) {
4411
+ if (!selectorMatchesGroup(t.selector, frameToGroupModel(g))) continue;
4412
+ matched = true;
4413
+ const map = g.frame.propsMap ??= {};
4414
+ for (const p of t.props) map[p.key] = p.value;
4415
+ }
4416
+ if (!matched) {
4417
+ diagnostics.push({
4418
+ level: "warning",
4419
+ message: `Selector '${t.raw.trim()}' (%%@ props) matched no nodes.`,
4420
+ path: `line:${t.line}`
4421
+ });
3654
4422
  }
3655
4423
  }
3656
- groupChildren.push(innerStack);
3657
- const groupNode = {
3658
- kind: "group",
3659
- id: g.frame.id,
3660
- props: {},
3661
- children: groupChildren
3662
- };
3663
- if (g.frame.label) {
3664
- groupNode.props.label = g.frame.label;
4424
+ }
4425
+ const components = new Map(options?.components);
4426
+ for (const u of useDirectives) {
4427
+ if (u.specifier.endsWith(".draw.tsx") && components.size === 0) {
4428
+ diagnostics.push({
4429
+ level: "warning",
4430
+ message: `%%@ use ${u.specifier}: '.draw.tsx' sources are resolved by the CLI/Node host (compiled via the Draw TSX compiler) and are not available to the browser bundle; pass a Component Pack instead. No components loaded here.`,
4431
+ path: `line:${u.line}`
4432
+ });
3665
4433
  }
3666
- groupNodes.set(g.frame.id, groupNode);
3667
4434
  }
3668
- const rootChildren = [];
3669
- for (const id of rootNodeIds) {
3670
- const groupNode = groupNodes.get(id);
3671
- if (groupNode) {
3672
- rootChildren.push(groupNode);
3673
- } else {
3674
- const node = nodeMap.get(id);
3675
- if (node) {
3676
- rootChildren.push(buildBox(node));
4435
+ const binds = [];
4436
+ if (options?.bindings) {
4437
+ for (const [selectorText, callText] of Object.entries(options.bindings)) {
4438
+ const selector = parseSelector(selectorText);
4439
+ const call = parseComponentCall(callText);
4440
+ if (!selector || !call) {
4441
+ diagnostics.push({
4442
+ level: "warning",
4443
+ message: `API default binding '${selectorText} = ${callText}' is malformed; ignored.`,
4444
+ path: "options.bindings"
4445
+ });
4446
+ continue;
3677
4447
  }
4448
+ binds.push({
4449
+ type: "bindingDirective",
4450
+ raw: `${selectorText} = ${callText}`,
4451
+ line: 0,
4452
+ verb: "bind",
4453
+ selector,
4454
+ component: call.component,
4455
+ props: call.props
4456
+ });
3678
4457
  }
3679
4458
  }
3680
- const rootStack = {
3681
- kind: stackKind,
3682
- props: { gap: 60, align: "center" },
3683
- children: rootChildren
3684
- };
3685
- const documentChildren = [rootStack, ...connectors, ...constraints];
3686
- const document = {
3687
- kind: "document",
3688
- props: { padding: 20 },
3689
- children: documentChildren
4459
+ binds.push(...bindDirectives);
4460
+ if (options?.props) {
4461
+ for (const [selectorText, kv] of Object.entries(options.props)) {
4462
+ const selector = parseSelector(selectorText);
4463
+ if (!selector) continue;
4464
+ for (const node of nodeMap.values()) {
4465
+ if (!selectorMatchesNode(selector, nodeToModel(node))) continue;
4466
+ const map = node.propsMap ??= {};
4467
+ for (const [k, v] of Object.entries(kv)) if (!(k in map)) map[k] = v;
4468
+ }
4469
+ for (const g of groups) {
4470
+ if (!selectorMatchesGroup(selector, frameToGroupModel(g))) continue;
4471
+ const map = g.frame.propsMap ??= {};
4472
+ for (const [k, v] of Object.entries(kv)) if (!(k in map)) map[k] = v;
4473
+ }
4474
+ }
4475
+ }
4476
+ const model = {
4477
+ rootDirection,
4478
+ rootNodeIds,
4479
+ nodeMap: mapNodeModels(),
4480
+ groups: mapGroupModels(),
4481
+ connectors,
4482
+ constraints,
4483
+ docProps
3690
4484
  };
3691
- return { ir: document, diagnostics };
4485
+ const bindingCtx = { components, binds, diagnostics };
4486
+ const dsl = buildDslTree(model, bindingCtx);
4487
+ const ir = expandDsl(dsl, components, diagnostics);
4488
+ function nodeToModel(n) {
4489
+ return {
4490
+ id: n.id,
4491
+ label: n.label,
4492
+ shape: n.shape,
4493
+ variant: n.variant,
4494
+ styleProps: n.styleProps,
4495
+ propsMap: n.propsMap
4496
+ };
4497
+ }
4498
+ function frameToGroupModel(g) {
4499
+ return {
4500
+ id: g.frame.id,
4501
+ label: g.frame.label,
4502
+ direction: g.frame.direction,
4503
+ childIds: g.children,
4504
+ variant: g.frame.variant,
4505
+ propsMap: g.frame.propsMap
4506
+ };
4507
+ }
4508
+ function mapNodeModels() {
4509
+ const m = /* @__PURE__ */ new Map();
4510
+ for (const [id, n] of nodeMap) m.set(id, nodeToModel(n));
4511
+ return m;
4512
+ }
4513
+ function mapGroupModels() {
4514
+ const m = /* @__PURE__ */ new Map();
4515
+ for (const g of groups) m.set(g.frame.id, frameToGroupModel(g));
4516
+ return m;
4517
+ }
4518
+ const result = { ir, dsl, diagnostics };
4519
+ if (theme !== void 0) result.theme = theme;
4520
+ return result;
3692
4521
  }
3693
- function buildBox(node) {
3694
- const props = { shape: node.shape };
3695
- if (node.variant) {
3696
- props.variant = node.variant;
4522
+ function deprecatedReplacement(t) {
4523
+ switch (t.directiveType) {
4524
+ case "same-width":
4525
+ return "same-size width: \u2026";
4526
+ case "same-height":
4527
+ return "same-size height: \u2026";
4528
+ case "gap":
4529
+ return "gap min=\u2026: \u2026";
4530
+ case "mover":
4531
+ return "mover \u2026: \u2026";
3697
4532
  }
4533
+ }
4534
+ function unknownPropDiagnostic(verb, kind, prop, line, allowed) {
4535
+ const list = [...allowed].filter((k) => k !== "id" && k !== "geometry").sort().join(", ");
3698
4536
  return {
3699
- kind: "box",
3700
- id: node.id,
3701
- props,
3702
- children: [
3703
- { kind: "text", props: { text: node.label } }
3704
- ]
4537
+ level: "warning",
4538
+ message: `Unknown property "${prop}" in '%%@ ${verb}' for <${kind}>. Allowed: ${list}`,
4539
+ path: `line:${line}`
3705
4540
  };
3706
4541
  }
3707
4542
  function buildAlignConstraint(targets, direction) {
@@ -3718,16 +4553,6 @@ function buildAlignConstraint(targets, direction) {
3718
4553
 
3719
4554
  // src/compiler/compiler.ts
3720
4555
  import ts from "typescript";
3721
- function isParamRef(v) {
3722
- return typeof v === "object" && v !== null && v.__paramRef === true;
3723
- }
3724
- function isTemplateRef(v) {
3725
- return typeof v === "object" && v !== null && v.__templateRef === true;
3726
- }
3727
- function isExprRef(v) {
3728
- return typeof v === "object" && v !== null && v.__exprRef === true;
3729
- }
3730
- var NOT_SET = /* @__PURE__ */ Symbol("diagram-contracts.notSet");
3731
4556
  var TSX_TO_IR = {
3732
4557
  Document: "document",
3733
4558
  Group: "group",
@@ -3772,96 +4597,26 @@ function extractParamNames(params) {
3772
4597
  names.add(el.name.text);
3773
4598
  }
3774
4599
  }
3775
- return names;
3776
- }
3777
- function findReturnJsx(body) {
3778
- if (!body) return void 0;
3779
- for (const stmt of body.statements) {
3780
- if (ts.isReturnStatement(stmt) && stmt.expression) {
3781
- let expr = stmt.expression;
3782
- while (ts.isParenthesizedExpression(expr)) expr = expr.expression;
3783
- if (ts.isJsxElement(expr) || ts.isJsxSelfClosingElement(expr)) return expr;
3784
- }
3785
- }
3786
- return void 0;
3787
- }
3788
- var BINARY_OPS = /* @__PURE__ */ new Map([
3789
- [ts.SyntaxKind.PlusToken, "+"],
3790
- [ts.SyntaxKind.MinusToken, "-"],
3791
- [ts.SyntaxKind.AsteriskToken, "*"],
3792
- [ts.SyntaxKind.SlashToken, "/"],
3793
- [ts.SyntaxKind.PercentToken, "%"]
3794
- ]);
3795
- function isDeferred(v) {
3796
- return isParamRef(v) || isExprRef(v);
3797
- }
3798
- function foldBinary(op, left, right, report) {
3799
- if (left === NOT_SET || right === NOT_SET) {
3800
- report?.(
3801
- `operator '${op}' cannot be applied to null/undefined \u2014 null/undefined is only valid as the entire prop value ("prop not set")`
3802
- );
3803
- return void 0;
3804
- }
3805
- if (left === void 0 || right === void 0) return void 0;
3806
- if (isDeferred(left) || isDeferred(right)) {
3807
- for (const operand of [left, right]) {
3808
- if (!isDeferred(operand) && typeof operand !== "number" && typeof operand !== "string") {
3809
- report?.(`operator '${op}' does not support ${typeof operand} operands`);
3810
- return void 0;
3811
- }
3812
- }
3813
- return { __exprRef: true, op, left, right };
3814
- }
3815
- if (typeof left === "number" && typeof right === "number") {
3816
- let result;
3817
- switch (op) {
3818
- case "+":
3819
- result = left + right;
3820
- break;
3821
- case "-":
3822
- result = left - right;
3823
- break;
3824
- case "*":
3825
- result = left * right;
3826
- break;
3827
- case "/":
3828
- result = left / right;
3829
- break;
3830
- case "%":
3831
- result = left % right;
3832
- break;
3833
- }
3834
- if (!Number.isFinite(result)) {
3835
- report?.(`arithmetic result is not a finite number (${left} ${op} ${right}) \u2014 division by zero?`);
3836
- return void 0;
3837
- }
3838
- return result;
3839
- }
3840
- if (op === "+" && typeof left === "string" && typeof right === "string") {
3841
- return left + right;
3842
- }
3843
- report?.(
3844
- `operator '${op}' requires two numbers${op === "+" ? " or two strings" : ""} (got ${typeof left} and ${typeof right})`
3845
- );
3846
- return void 0;
3847
- }
3848
- function foldUnaryMinus(operand, report) {
3849
- if (operand === NOT_SET) {
3850
- report?.(
3851
- `unary minus cannot be applied to null/undefined \u2014 null/undefined is only valid as the entire prop value ("prop not set")`
3852
- );
3853
- return void 0;
3854
- }
3855
- if (operand === void 0) return void 0;
3856
- if (typeof operand === "number") {
3857
- return -operand;
3858
- }
3859
- if (isDeferred(operand)) {
3860
- return { __exprRef: true, op: "neg", left: operand };
3861
- }
3862
- report?.(`unary minus requires a numeric operand (got ${typeof operand})`);
4600
+ return names;
4601
+ }
4602
+ function findReturnJsx(body) {
4603
+ if (!body) return void 0;
4604
+ for (const stmt of body.statements) {
4605
+ if (ts.isReturnStatement(stmt) && stmt.expression) {
4606
+ let expr = stmt.expression;
4607
+ while (ts.isParenthesizedExpression(expr)) expr = expr.expression;
4608
+ if (ts.isJsxElement(expr) || ts.isJsxSelfClosingElement(expr)) return expr;
4609
+ }
4610
+ }
3863
4611
  return void 0;
3864
4612
  }
4613
+ var BINARY_OPS = /* @__PURE__ */ new Map([
4614
+ [ts.SyntaxKind.PlusToken, "+"],
4615
+ [ts.SyntaxKind.MinusToken, "-"],
4616
+ [ts.SyntaxKind.AsteriskToken, "*"],
4617
+ [ts.SyntaxKind.SlashToken, "/"],
4618
+ [ts.SyntaxKind.PercentToken, "%"]
4619
+ ]);
3865
4620
  function evaluateExpression(expr, paramNames, report) {
3866
4621
  if (ts.isNumericLiteral(expr)) {
3867
4622
  const n = Number(expr.text);
@@ -4116,120 +4871,18 @@ function expandComponentTag(tagName, props, childNodes, ctx) {
4116
4871
  extraProps[key] = value;
4117
4872
  }
4118
4873
  }
4119
- const expanded = deepCloneAndSubstitute(def.template, paramValues, compiledChildren, ctx, tagName);
4120
- Object.assign(expanded.props, extraProps);
4121
- if (id && !idIsParam) expanded.id = id;
4874
+ const expanded = expandComponent(
4875
+ def,
4876
+ paramValues,
4877
+ compiledChildren,
4878
+ ctx.diagnostics,
4879
+ extraProps,
4880
+ id,
4881
+ idIsParam
4882
+ );
4122
4883
  ctx.expandingStack.delete(tagName);
4123
4884
  return expanded;
4124
4885
  }
4125
- function deepCloneAndSubstitute(node, paramValues, compiledChildren, ctx, componentName, only) {
4126
- const cloned = { kind: node.kind, props: {} };
4127
- if (node.id) cloned.id = node.id;
4128
- const makeReporter = (propName) => (message) => {
4129
- ctx.diagnostics.push({
4130
- level: "error",
4131
- message: `<${componentName}> (expanding <${node.kind}> prop "${propName}"): ${message}`,
4132
- path: componentName
4133
- });
4134
- };
4135
- for (const [key, value] of Object.entries(node.props)) {
4136
- if (key === "__childrenSlot") continue;
4137
- if (key === "__idParam") {
4138
- const resolved = substituteValue(value, paramValues, makeReporter("id"), only);
4139
- if (typeof resolved === "string") {
4140
- cloned.id = resolved;
4141
- } else if (isParamRef(resolved) || isTemplateRef(resolved) || isExprRef(resolved)) {
4142
- cloned.props["__idParam"] = resolved;
4143
- }
4144
- continue;
4145
- }
4146
- const substituted = substituteValue(value, paramValues, makeReporter(key), only);
4147
- if (substituted !== void 0) {
4148
- cloned.props[key] = substituted;
4149
- }
4150
- }
4151
- if (node.children) {
4152
- const newChildren = [];
4153
- for (const child of node.children) {
4154
- if (child.props.__childrenSlot === true) {
4155
- newChildren.push(...compiledChildren);
4156
- } else {
4157
- newChildren.push(deepCloneAndSubstitute(child, paramValues, compiledChildren, ctx, componentName, only));
4158
- }
4159
- }
4160
- if (newChildren.length > 0) cloned.children = newChildren;
4161
- }
4162
- return cloned;
4163
- }
4164
- function substituteValue(value, paramValues, report, only) {
4165
- if (isParamRef(value)) {
4166
- if (only && !only.has(value.name)) return value;
4167
- return paramValues[value.name];
4168
- }
4169
- if (isExprRef(value)) {
4170
- const substituteOperand = (operand) => {
4171
- const resolved = substituteValue(operand, paramValues, report, only);
4172
- if (resolved === void 0 && isParamRef(operand) && (!only || only.has(operand.name))) {
4173
- report?.(`cannot evaluate expression \u2014 prop "${operand.name}" was not provided`);
4174
- }
4175
- return resolved;
4176
- };
4177
- const left = substituteOperand(value.left);
4178
- if (value.op === "neg") {
4179
- return foldUnaryMinus(left, report);
4180
- }
4181
- const right = substituteOperand(value.right);
4182
- return foldBinary(value.op, left, right, report);
4183
- }
4184
- if (isTemplateRef(value)) {
4185
- const newParts = [];
4186
- for (const part of value.parts) {
4187
- if (isParamRef(part)) {
4188
- if (only && !only.has(part.name)) {
4189
- newParts.push(part);
4190
- continue;
4191
- }
4192
- const resolved = paramValues[part.name];
4193
- if (resolved === void 0) {
4194
- } else if (typeof resolved === "string") {
4195
- newParts.push(resolved);
4196
- } else if (isParamRef(resolved) || isExprRef(resolved)) {
4197
- newParts.push(resolved);
4198
- } else if (isTemplateRef(resolved)) {
4199
- newParts.push(...resolved.parts);
4200
- } else {
4201
- newParts.push(String(resolved));
4202
- }
4203
- } else if (isExprRef(part)) {
4204
- const resolved = substituteValue(part, paramValues, report, only);
4205
- if (resolved === void 0) {
4206
- } else if (isDeferred(resolved)) {
4207
- newParts.push(resolved);
4208
- } else {
4209
- newParts.push(String(resolved));
4210
- }
4211
- } else {
4212
- newParts.push(part);
4213
- }
4214
- }
4215
- const allStrings = newParts.every((p) => typeof p === "string");
4216
- if (allStrings) {
4217
- return newParts.join("");
4218
- }
4219
- return { __templateRef: true, parts: newParts };
4220
- }
4221
- if (Array.isArray(value)) {
4222
- return value.map((item) => substituteValue(item, paramValues, report, only));
4223
- }
4224
- if (typeof value === "object" && value !== null) {
4225
- const result = {};
4226
- for (const [k, v] of Object.entries(value)) {
4227
- result[k] = substituteValue(v, paramValues, report, only);
4228
- }
4229
- return result;
4230
- }
4231
- return value;
4232
- }
4233
4886
  function resolveImports(sourceFile, resolveImport, diagnostics, fromFile, fileCache) {
4234
4887
  const allDefs = /* @__PURE__ */ new Map();
4235
4888
  const cache = fileCache ?? /* @__PURE__ */ new Map();
@@ -4320,7 +4973,7 @@ function expandMapChildren(jsxExpr, ctx) {
4320
4973
  const paramValues = {};
4321
4974
  if (itemName) paramValues[itemName] = item;
4322
4975
  if (indexName) paramValues[indexName] = i;
4323
- out.push(deepCloneAndSubstitute(template, paramValues, [], ctx, "map iteration", mapParams));
4976
+ out.push(deepCloneAndSubstitute(template, paramValues, [], ctx.diagnostics, "map iteration", mapParams));
4324
4977
  });
4325
4978
  return out;
4326
4979
  }
@@ -5152,17 +5805,7 @@ function renderIcon(node, registry) {
5152
5805
  if (svgContent) {
5153
5806
  return renderInlineSvg(node.id, r, svgContent);
5154
5807
  }
5155
- const fg = node.styles.foreground ?? RENDER_DEFAULTS.icon.foreground;
5156
- const fontSize = Math.min(r.width, r.height) * 0.35;
5157
- const shortLabel = name.includes(":") ? name.split(":")[1] : name;
5158
- const cx = r.x + r.width / 2;
5159
- const cy = r.y + r.height / 2;
5160
- return [
5161
- `<g id="${escId(node.id)}">`,
5162
- `<rect x="${r.x}" y="${r.y}" width="${r.width}" height="${r.height}" fill="#f5f5f5" stroke="#ddd" stroke-width="1" rx="4"/>`,
5163
- `<text x="${cx}" y="${cy}" text-anchor="middle" dominant-baseline="central" font-size="${fontSize}" fill="${fg}">${escText(shortLabel)}</text>`,
5164
- `</g>`
5165
- ].join("");
5808
+ return `<g id="${escId(node.id)}"><rect x="${r.x}" y="${r.y}" width="${r.width}" height="${r.height}" fill="none" stroke="#ddd" stroke-width="1" stroke-dasharray="4 2"/></g>`;
5166
5809
  }
5167
5810
  function renderSvgAsset(node) {
5168
5811
  const r = node.worldRect;
@@ -5187,9 +5830,6 @@ function renderInlineSvg(id, r, svgContent) {
5187
5830
  function escAttr(s) {
5188
5831
  return String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5189
5832
  }
5190
- function escText(s) {
5191
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5192
- }
5193
5833
  var iconRegistry;
5194
5834
  function renderNode(node) {
5195
5835
  const parts = [];
@@ -5361,6 +6001,7 @@ var SHORT_NAME_MAP = {
5361
6001
  eks: "architecture-service/AmazonElasticKubernetesService",
5362
6002
  fargate: "architecture-service/AWSFargate",
5363
6003
  elasticloadbalancing: "architecture-service/ElasticLoadBalancing",
6004
+ "elastic-load-balancing": "architecture-service/ElasticLoadBalancing",
5364
6005
  cloudwatch: "architecture-service/AmazonCloudWatch",
5365
6006
  iam: "architecture-service/AWSIdentityandAccessManagement",
5366
6007
  route53: "architecture-service/AmazonRoute53",
@@ -5433,6 +6074,265 @@ function createAwsIconPack() {
5433
6074
  };
5434
6075
  }
5435
6076
 
6077
+ // src/pack/index.ts
6078
+ var PACK_VERSION = 1;
6079
+ var REF_KEYS = ["__paramRef", "__templateRef", "__exprRef"];
6080
+ function isPlainObject(v) {
6081
+ return typeof v === "object" && v !== null && !Array.isArray(v);
6082
+ }
6083
+ function validateTemplate(node, path, push) {
6084
+ if (!isPlainObject(node)) {
6085
+ push(`${path}: template node must be an object, got ${node === null ? "null" : typeof node}`);
6086
+ return;
6087
+ }
6088
+ if (typeof node.kind !== "string" || node.kind === "") {
6089
+ push(`${path}: template node is missing a string "kind"`);
6090
+ return;
6091
+ }
6092
+ if (!isPlainObject(node.props)) {
6093
+ push(`${path}: template node <${String(node.kind)}> is missing a "props" object`);
6094
+ return;
6095
+ }
6096
+ validateRefs(node.props, `${path}.props`, push);
6097
+ if (node.children !== void 0) {
6098
+ if (!Array.isArray(node.children)) {
6099
+ push(`${path}: template node <${String(node.kind)}> has a non-array "children"`);
6100
+ return;
6101
+ }
6102
+ node.children.forEach((child, i) => validateTemplate(child, `${path}.children[${i}]`, push));
6103
+ }
6104
+ }
6105
+ function validateRefs(value, path, push) {
6106
+ if (Array.isArray(value)) {
6107
+ value.forEach((v, i) => validateRefs(v, `${path}[${i}]`, push));
6108
+ return;
6109
+ }
6110
+ if (!isPlainObject(value)) return;
6111
+ const refKey = REF_KEYS.find((k) => k in value);
6112
+ if (refKey === "__paramRef" && typeof value.name !== "string") {
6113
+ push(`${path}: __paramRef marker is missing a string "name"`);
6114
+ } else if (refKey === "__templateRef" && !Array.isArray(value.parts)) {
6115
+ push(`${path}: __templateRef marker is missing a "parts" array`);
6116
+ } else if (refKey === "__exprRef" && typeof value.op !== "string") {
6117
+ push(`${path}: __exprRef marker is missing a string "op"`);
6118
+ }
6119
+ for (const [k, v] of Object.entries(value)) {
6120
+ if (REF_KEYS.includes(k)) continue;
6121
+ validateRefs(v, `${path}.${k}`, push);
6122
+ }
6123
+ }
6124
+ function validateComponentPack(value) {
6125
+ const errors = [];
6126
+ const push = (message) => errors.push({ message });
6127
+ if (!isPlainObject(value)) {
6128
+ push(`pack must be a JSON object, got ${value === null ? "null" : typeof value}`);
6129
+ return errors;
6130
+ }
6131
+ const meta = value.diagramContracts;
6132
+ if (!isPlainObject(meta)) {
6133
+ push(`pack is missing the "diagramContracts" metadata object`);
6134
+ } else if (meta.packVersion === void 0) {
6135
+ push(`pack is missing "diagramContracts.packVersion"`);
6136
+ } else if (meta.packVersion !== PACK_VERSION) {
6137
+ push(
6138
+ `unsupported packVersion ${JSON.stringify(meta.packVersion)} \u2014 this build understands packVersion ${PACK_VERSION}`
6139
+ );
6140
+ }
6141
+ if (!Array.isArray(value.components)) {
6142
+ push(`pack "components" must be an array`);
6143
+ } else {
6144
+ value.components.forEach((comp, i) => {
6145
+ const label = `components[${i}]`;
6146
+ if (!isPlainObject(comp)) {
6147
+ push(`${label} must be an object`);
6148
+ return;
6149
+ }
6150
+ if (typeof comp.name !== "string" || comp.name === "") {
6151
+ push(`${label} is missing a string "name"`);
6152
+ }
6153
+ if (!Array.isArray(comp.params) || !comp.params.every((p) => typeof p === "string")) {
6154
+ push(`${label} ("${String(comp.name)}") is missing a string[] "params"`);
6155
+ }
6156
+ if (comp.template === void 0) {
6157
+ push(`${label} ("${String(comp.name)}") is missing a "template"`);
6158
+ } else {
6159
+ validateTemplate(comp.template, `${label} ("${String(comp.name)}").template`, push);
6160
+ }
6161
+ });
6162
+ }
6163
+ if (value.icons !== void 0) {
6164
+ if (!isPlainObject(value.icons)) {
6165
+ push(`pack "icons" must be an object mapping qualified name \u2192 SVG string`);
6166
+ } else {
6167
+ for (const [name, svg] of Object.entries(value.icons)) {
6168
+ if (typeof svg !== "string") {
6169
+ push(`icons["${name}"] must be a string SVG, got ${typeof svg}`);
6170
+ }
6171
+ }
6172
+ }
6173
+ }
6174
+ return errors;
6175
+ }
6176
+ function loadPack(pack) {
6177
+ const components = pack.components.map((c) => {
6178
+ const wire = c;
6179
+ const paramNames = wire.params !== void 0 ? wire.params : wire.paramNames;
6180
+ return componentDefFromJSON({
6181
+ name: c.name,
6182
+ paramNames,
6183
+ template: c.template
6184
+ });
6185
+ });
6186
+ return { components, icons: pack.icons ?? {} };
6187
+ }
6188
+ function buildComponentPack(defs, icons) {
6189
+ const components = [...defs].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map((def) => {
6190
+ const json = componentDefToJSON(def);
6191
+ return {
6192
+ name: json.name,
6193
+ // Emit the spec's `params` key (the ComponentDefJSON `paramNames` is
6194
+ // the same sorted string[]).
6195
+ params: json.paramNames,
6196
+ template: json.template
6197
+ };
6198
+ });
6199
+ const pack = {
6200
+ diagramContracts: { packVersion: PACK_VERSION },
6201
+ components
6202
+ };
6203
+ const iconKeys = Object.keys(icons).sort();
6204
+ if (iconKeys.length > 0) {
6205
+ const sorted = {};
6206
+ for (const k of iconKeys) sorted[k] = icons[k];
6207
+ pack.icons = sorted;
6208
+ }
6209
+ return pack;
6210
+ }
6211
+ function serializePack(pack) {
6212
+ return JSON.stringify(pack, null, 2) + "\n";
6213
+ }
6214
+
6215
+ // src/config/index.ts
6216
+ import { load as load3 } from "js-yaml";
6217
+ var KNOWN_KEYS = /* @__PURE__ */ new Set([
6218
+ "components",
6219
+ "theme",
6220
+ "doc",
6221
+ "bindings",
6222
+ "props",
6223
+ "icons"
6224
+ ]);
6225
+ function isPlainObject2(v) {
6226
+ return typeof v === "object" && v !== null && !Array.isArray(v);
6227
+ }
6228
+ function parseDrawConfig(text, format, path = "draw.config") {
6229
+ const diagnostics = [];
6230
+ const config = {};
6231
+ let raw;
6232
+ try {
6233
+ raw = format === "json" ? JSON.parse(text) : load3(text);
6234
+ } catch (e) {
6235
+ diagnostics.push({
6236
+ level: "error",
6237
+ message: `could not parse config (${format}): ${e.message}`,
6238
+ path
6239
+ });
6240
+ return { config, diagnostics };
6241
+ }
6242
+ if (!isPlainObject2(raw)) {
6243
+ diagnostics.push({
6244
+ level: "error",
6245
+ message: `config must be a mapping of keys \u2192 values, got ${raw === null ? "null" : typeof raw}`,
6246
+ path
6247
+ });
6248
+ return { config, diagnostics };
6249
+ }
6250
+ for (const key of Object.keys(raw)) {
6251
+ if (!KNOWN_KEYS.has(key)) {
6252
+ diagnostics.push({
6253
+ level: "warning",
6254
+ message: `unknown config key "${key}" (known: ${[...KNOWN_KEYS].sort().join(", ")}); ignored.`,
6255
+ path
6256
+ });
6257
+ }
6258
+ }
6259
+ if (raw.components !== void 0) {
6260
+ const list = Array.isArray(raw.components) ? raw.components : [raw.components];
6261
+ const specs = [];
6262
+ for (const s of list) {
6263
+ if (typeof s === "string") specs.push(s);
6264
+ else diagnostics.push({ level: "warning", message: `config "components" entry must be a string, got ${typeof s}; ignored.`, path });
6265
+ }
6266
+ if (specs.length > 0) config.components = specs;
6267
+ }
6268
+ if (raw.theme !== void 0) {
6269
+ if (typeof raw.theme === "string") config.theme = raw.theme;
6270
+ else diagnostics.push({ level: "warning", message: `config "theme" must be a string; ignored.`, path });
6271
+ }
6272
+ if (raw.doc !== void 0) {
6273
+ if (isPlainObject2(raw.doc)) config.doc = { ...raw.doc };
6274
+ else diagnostics.push({ level: "warning", message: `config "doc" must be a mapping; ignored.`, path });
6275
+ }
6276
+ if (raw.bindings !== void 0) {
6277
+ if (isPlainObject2(raw.bindings)) {
6278
+ const bindings = {};
6279
+ for (const [sel, call] of Object.entries(raw.bindings)) {
6280
+ if (typeof call === "string") bindings[sel] = call;
6281
+ else diagnostics.push({ level: "warning", message: `config binding "${sel}" must be a "Component(propMap)" string; ignored.`, path });
6282
+ }
6283
+ if (Object.keys(bindings).length > 0) config.bindings = bindings;
6284
+ } else {
6285
+ diagnostics.push({ level: "warning", message: `config "bindings" must be a mapping of selector \u2192 string; ignored.`, path });
6286
+ }
6287
+ }
6288
+ if (raw.props !== void 0) {
6289
+ if (isPlainObject2(raw.props)) {
6290
+ const props = {};
6291
+ for (const [sel, kv] of Object.entries(raw.props)) {
6292
+ if (isPlainObject2(kv)) props[sel] = { ...kv };
6293
+ else diagnostics.push({ level: "warning", message: `config props "${sel}" must be a mapping of key \u2192 value; ignored.`, path });
6294
+ }
6295
+ if (Object.keys(props).length > 0) config.props = props;
6296
+ } else {
6297
+ diagnostics.push({ level: "warning", message: `config "props" must be a mapping; ignored.`, path });
6298
+ }
6299
+ }
6300
+ if (raw.icons !== void 0) {
6301
+ if (isPlainObject2(raw.icons)) {
6302
+ const icons = {};
6303
+ for (const [provider, loc] of Object.entries(raw.icons)) {
6304
+ if (typeof loc === "string") icons[provider] = loc;
6305
+ else diagnostics.push({ level: "warning", message: `config icons "${provider}" must be a location string; ignored.`, path });
6306
+ }
6307
+ if (Object.keys(icons).length > 0) config.icons = icons;
6308
+ } else {
6309
+ diagnostics.push({ level: "warning", message: `config "icons" must be a mapping of provider \u2192 location; ignored.`, path });
6310
+ }
6311
+ }
6312
+ return { config, diagnostics };
6313
+ }
6314
+ function scanConfigDirectives(source) {
6315
+ const out = [];
6316
+ source.split("\n").forEach((line, i) => {
6317
+ const m = line.trim().match(/^%%@\s*config\s+(.+)$/);
6318
+ if (m) out.push({ specifier: m[1].trim(), line: i + 1 });
6319
+ });
6320
+ return out;
6321
+ }
6322
+ function configToParseOptions(config) {
6323
+ const out = {};
6324
+ if (config.bindings) out.bindings = config.bindings;
6325
+ if (config.props) out.props = config.props;
6326
+ if (config.doc) out.doc = config.doc;
6327
+ return out;
6328
+ }
6329
+
6330
+ // src/icons/providers.ts
6331
+ function iconResourceFor(location, short) {
6332
+ const base = location.endsWith("/") ? location.slice(0, -1) : location;
6333
+ return `${base}/${short}.svg`;
6334
+ }
6335
+
5436
6336
  // src/graph/resolver.ts
5437
6337
  var PRIORITY_RANK = {
5438
6338
  required: 4,
@@ -6340,16 +7240,134 @@ function initFontMeasurer(fontFamily, fontFiles) {
6340
7240
  }
6341
7241
  }
6342
7242
  }
6343
-
6344
- // src/pipeline.ts
6345
- function layout(ir, options) {
6346
- const { ir: normalizedIr, diagnostics: normDiag } = normalize(ir, options);
6347
- const graph = createGraph();
6348
- const { artifact, diagnostics: evalDiag } = evaluate(graph, normalizedIr);
6349
- return {
6350
- artifact,
6351
- diagnostics: [...normDiag, ...evalDiag]
6352
- };
7243
+
7244
+ // src/pipeline.ts
7245
+ function layout(ir, options) {
7246
+ const { ir: normalizedIr, diagnostics: normDiag } = normalize(ir, options);
7247
+ const graph = createGraph();
7248
+ const { artifact, diagnostics: evalDiag } = evaluate(graph, normalizedIr);
7249
+ return {
7250
+ artifact,
7251
+ diagnostics: [...normDiag, ...evalDiag]
7252
+ };
7253
+ }
7254
+
7255
+ // src/emitter/index.ts
7256
+ var IR_TO_TSX = Object.fromEntries(
7257
+ Object.entries(TSX_TO_IR).map(([tag, kind]) => [kind, tag])
7258
+ );
7259
+ var COMPONENT_MARKER = "__component";
7260
+ var TEXT_KINDS2 = /* @__PURE__ */ new Set(["text", "label"]);
7261
+ var INDENT = " ";
7262
+ function emitDrawTsx(root) {
7263
+ return emitNode(root, 0) + "\n";
7264
+ }
7265
+ function tagNameFor(node) {
7266
+ if (isComponentTag(node)) {
7267
+ const name = node.props[COMPONENT_MARKER];
7268
+ if (typeof name !== "string" || name === "") {
7269
+ throw new Error(
7270
+ `emitDrawTsx: component tag is missing its '${COMPONENT_MARKER}' name (id=${node.id ?? "?"})`
7271
+ );
7272
+ }
7273
+ return name;
7274
+ }
7275
+ const tag = IR_TO_TSX[node.kind];
7276
+ if (!tag) {
7277
+ throw new Error(
7278
+ `emitDrawTsx: no Draw TSX element name for IR kind '${node.kind}'`
7279
+ );
7280
+ }
7281
+ return tag;
7282
+ }
7283
+ function attributeEntries(node) {
7284
+ const isText = TEXT_KINDS2.has(node.kind);
7285
+ const entries = [];
7286
+ for (const [key, value] of Object.entries(node.props)) {
7287
+ if (key === COMPONENT_MARKER) continue;
7288
+ if (key === "id") continue;
7289
+ if (isText && key === "text") continue;
7290
+ if (value === void 0) continue;
7291
+ entries.push([key, value]);
7292
+ }
7293
+ return entries;
7294
+ }
7295
+ function textContentOf(node) {
7296
+ if (!TEXT_KINDS2.has(node.kind)) return void 0;
7297
+ const text = node.props.text;
7298
+ return typeof text === "string" ? text : void 0;
7299
+ }
7300
+ function emitNode(node, depth) {
7301
+ const pad = INDENT.repeat(depth);
7302
+ const tag = tagNameFor(node);
7303
+ const attrs = renderAttributes(node);
7304
+ const text = textContentOf(node);
7305
+ const children = node.children ?? [];
7306
+ if (children.length === 0 && (text === void 0 || text === "")) {
7307
+ return `${pad}<${tag}${attrs} />`;
7308
+ }
7309
+ if (children.length === 0 && text !== void 0) {
7310
+ return `${pad}<${tag}${attrs}>${escapeJsxText(text)}</${tag}>`;
7311
+ }
7312
+ const lines = [`${pad}<${tag}${attrs}>`];
7313
+ if (text !== void 0 && text !== "") {
7314
+ lines.push(`${INDENT.repeat(depth + 1)}${escapeJsxText(text)}`);
7315
+ }
7316
+ for (const child of children) {
7317
+ lines.push(emitNode(child, depth + 1));
7318
+ }
7319
+ lines.push(`${pad}</${tag}>`);
7320
+ return lines.join("\n");
7321
+ }
7322
+ function renderAttributes(node) {
7323
+ const parts = [];
7324
+ if (typeof node.id === "string" && node.id !== "") {
7325
+ parts.push(`id=${formatStringAttr(node.id)}`);
7326
+ }
7327
+ for (const [key, value] of attributeEntries(node)) {
7328
+ parts.push(`${key}=${formatAttrValue(value)}`);
7329
+ }
7330
+ return parts.length === 0 ? "" : " " + parts.join(" ");
7331
+ }
7332
+ function formatAttrValue(value) {
7333
+ if (typeof value === "string") return formatStringAttr(value);
7334
+ return `{${formatExpression(value)}}`;
7335
+ }
7336
+ function formatStringAttr(value) {
7337
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
7338
+ }
7339
+ function formatExpression(value) {
7340
+ if (value === null) return "null";
7341
+ if (typeof value === "number") {
7342
+ if (!Number.isFinite(value)) {
7343
+ throw new Error(`emitDrawTsx: cannot serialize non-finite number ${value}`);
7344
+ }
7345
+ return String(value);
7346
+ }
7347
+ if (typeof value === "boolean") return String(value);
7348
+ if (typeof value === "string") return formatStringLiteralInExpr(value);
7349
+ if (Array.isArray(value)) {
7350
+ return `[${value.map((v) => formatExpression(v)).join(", ")}]`;
7351
+ }
7352
+ if (typeof value === "object") {
7353
+ const entries = Object.entries(value).filter(
7354
+ ([, v]) => v !== void 0
7355
+ );
7356
+ return `{ ${entries.map(([k, v]) => `${formatObjectKey(k)}: ${formatExpression(v)}`).join(", ")} }`;
7357
+ }
7358
+ throw new Error(
7359
+ `emitDrawTsx: cannot serialize value of type ${typeof value} in an expression attribute`
7360
+ );
7361
+ }
7362
+ function formatStringLiteralInExpr(value) {
7363
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
7364
+ }
7365
+ function formatObjectKey(key) {
7366
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : formatStringLiteralInExpr(key);
7367
+ }
7368
+ function escapeJsxText(text) {
7369
+ if (!/[<>{}]/.test(text)) return text;
7370
+ return `{${formatStringLiteralInExpr(text)}}`;
6353
7371
  }
6354
7372
 
6355
7373
  // src/commands/render.ts
@@ -6357,10 +7375,202 @@ function isDrawText(raw) {
6357
7375
  const trimmed = raw.trimStart();
6358
7376
  return trimmed.startsWith("flowchart ") || trimmed.startsWith("graph ");
6359
7377
  }
7378
+ function resolveUseDirectives(raw, baseDir, diagnostics) {
7379
+ const components = /* @__PURE__ */ new Map();
7380
+ const lines = raw.split("\n");
7381
+ lines.forEach((line, i) => {
7382
+ const m = line.trim().match(/^%%@\s*use\s+(.+)$/);
7383
+ if (!m) return;
7384
+ resolveComponentSpecifier(m[1].trim(), baseDir, components, `line:${i + 1}`, "%%@ use", diagnostics);
7385
+ });
7386
+ return components;
7387
+ }
7388
+ function resolveConfigComponents(specifiers, baseDir, components, diagnostics) {
7389
+ if (!specifiers) return;
7390
+ for (const specifier of specifiers) {
7391
+ resolveComponentSpecifier(specifier, baseDir, components, "config.components", "config components", diagnostics);
7392
+ }
7393
+ }
7394
+ function resolveComponentSpecifier(specifier, baseDir, components, origin, verb, diagnostics) {
7395
+ const path = resolve(baseDir, specifier);
7396
+ if (!existsSync(path)) {
7397
+ diagnostics.push({
7398
+ level: "warning",
7399
+ message: `${verb} ${specifier}: file not found (${path}); bindings referencing its components fall back to plain boxes.`,
7400
+ path: origin
7401
+ });
7402
+ return;
7403
+ }
7404
+ if (specifier.endsWith(".pack.json") || specifier.endsWith(".json")) {
7405
+ try {
7406
+ const json = JSON.parse(readFileSync4(path, "utf-8"));
7407
+ const errors = validateComponentPack(json);
7408
+ if (errors.length > 0) {
7409
+ diagnostics.push({
7410
+ level: "error",
7411
+ message: `${verb} ${specifier}: invalid component pack: ${errors.map((e) => e.message).join("; ")}`,
7412
+ path: origin
7413
+ });
7414
+ return;
7415
+ }
7416
+ const loaded = loadPack(json);
7417
+ for (const def of loaded.components) components.set(def.name, def);
7418
+ } catch (e) {
7419
+ diagnostics.push({
7420
+ level: "error",
7421
+ message: `${verb} ${specifier}: failed to read pack: ${e.message}`,
7422
+ path: origin
7423
+ });
7424
+ }
7425
+ return;
7426
+ }
7427
+ try {
7428
+ const source = readFileSync4(path, "utf-8");
7429
+ const sourceFile = ts2.createSourceFile(path, source, ts2.ScriptTarget.Latest, true, ts2.ScriptKind.TSX);
7430
+ const fileDir = dirname(path);
7431
+ const resolveImport = (spec, fromFile) => {
7432
+ const base = fromFile ? dirname(resolve(fileDir, fromFile)) : fileDir;
7433
+ const resolved = resolve(base, spec);
7434
+ if (existsSync(resolved)) return readFileSync4(resolved, "utf-8");
7435
+ return void 0;
7436
+ };
7437
+ const importDefs = resolveImports(sourceFile, resolveImport, diagnostics);
7438
+ for (const [name, def] of importDefs) components.set(name, def);
7439
+ const inlineDefs = extractComponentDefs(sourceFile, diagnostics, components);
7440
+ for (const [name, def] of inlineDefs) components.set(name, def);
7441
+ } catch (e) {
7442
+ diagnostics.push({
7443
+ level: "error",
7444
+ message: `${verb} ${specifier}: failed to compile: ${e.message}`,
7445
+ path: origin
7446
+ });
7447
+ }
7448
+ }
6360
7449
  function isDrawTsx(raw) {
6361
7450
  const trimmed = raw.trimStart();
6362
7451
  return trimmed.startsWith("<") || trimmed.includes("<Document");
6363
7452
  }
7453
+ function loadConfigs(raw, cliConfigPath, baseDir, diagnostics) {
7454
+ const merged = {};
7455
+ const paths = [];
7456
+ if (cliConfigPath) paths.push(resolve(process.cwd(), cliConfigPath));
7457
+ for (const d of scanConfigDirectives(raw)) {
7458
+ paths.push(resolve(baseDir, d.specifier));
7459
+ }
7460
+ for (const path of paths) {
7461
+ if (!existsSync(path)) {
7462
+ diagnostics.push({
7463
+ level: "warning",
7464
+ message: `config not found (${path}); skipped.`,
7465
+ path
7466
+ });
7467
+ continue;
7468
+ }
7469
+ let text;
7470
+ try {
7471
+ text = readFileSync4(path, "utf-8");
7472
+ } catch (e) {
7473
+ diagnostics.push({ level: "warning", message: `config unreadable (${path}): ${e.message}; skipped.`, path });
7474
+ continue;
7475
+ }
7476
+ const { config, diagnostics: cfgDiag } = parseDrawConfig(text, "yaml", path);
7477
+ for (const d of cfgDiag) diagnostics.push({ level: d.level, message: d.message, path: d.path });
7478
+ if (config.icons) {
7479
+ const cfgDir = dirname(path);
7480
+ const resolved = {};
7481
+ for (const [provider, location] of Object.entries(config.icons)) {
7482
+ resolved[provider] = resolve(cfgDir, location);
7483
+ }
7484
+ config.icons = resolved;
7485
+ }
7486
+ mergeConfig(merged, config);
7487
+ }
7488
+ return merged;
7489
+ }
7490
+ function mergeConfig(dst, src) {
7491
+ if (src.components) dst.components = [...dst.components ?? [], ...src.components];
7492
+ if (src.theme !== void 0) dst.theme = src.theme;
7493
+ if (src.doc) dst.doc = { ...dst.doc ?? {}, ...src.doc };
7494
+ if (src.bindings) dst.bindings = { ...dst.bindings ?? {}, ...src.bindings };
7495
+ if (src.props) dst.props = { ...dst.props ?? {}, ...src.props };
7496
+ if (src.icons) dst.icons = { ...dst.icons ?? {}, ...src.icons };
7497
+ }
7498
+ function createDirIconPack(provider, dir) {
7499
+ const cache = /* @__PURE__ */ new Map();
7500
+ return {
7501
+ provider,
7502
+ resolve(name) {
7503
+ if (cache.has(name)) return cache.get(name);
7504
+ const file = iconResourceFor(dir, name);
7505
+ let svg;
7506
+ try {
7507
+ svg = existsSync(file) ? readFileSync4(file, "utf-8") : void 0;
7508
+ } catch {
7509
+ svg = void 0;
7510
+ }
7511
+ cache.set(name, svg);
7512
+ return svg;
7513
+ },
7514
+ list() {
7515
+ return [];
7516
+ }
7517
+ };
7518
+ }
7519
+ function buildCliIconRegistry(icons, baseDir) {
7520
+ const registry = createIconRegistry();
7521
+ registry.register(createAwsIconPack());
7522
+ if (icons) {
7523
+ for (const [provider, location] of Object.entries(icons)) {
7524
+ registry.register(createDirIconPack(provider, resolve(baseDir, location)));
7525
+ }
7526
+ }
7527
+ return registry;
7528
+ }
7529
+ function extractFencedBlocks(markdown) {
7530
+ const blocks = [];
7531
+ const lines = markdown.split("\n");
7532
+ let inBlock = false;
7533
+ let capture = false;
7534
+ let fence = "";
7535
+ let lang = "";
7536
+ let buf = [];
7537
+ for (const line of lines) {
7538
+ if (!inBlock) {
7539
+ const m = line.match(/^(\s*)(`{3,}|~{3,})\s*([^\s`~]*)/);
7540
+ if (m) {
7541
+ inBlock = true;
7542
+ fence = m[2];
7543
+ lang = m[3].toLowerCase();
7544
+ capture = lang === "draw" || lang === "mermaid";
7545
+ buf = [];
7546
+ }
7547
+ continue;
7548
+ }
7549
+ const close = line.match(/^\s*(`{3,}|~{3,})\s*$/);
7550
+ if (close && close[1][0] === fence[0] && close[1].length >= fence.length) {
7551
+ if (capture) blocks.push(buf.join("\n"));
7552
+ inBlock = false;
7553
+ capture = false;
7554
+ continue;
7555
+ }
7556
+ if (capture) buf.push(line);
7557
+ }
7558
+ const unterminatedLang = inBlock && capture ? lang : void 0;
7559
+ return { blocks, unterminatedLang };
7560
+ }
7561
+ function isMarkdownInput(input) {
7562
+ if (!input) return false;
7563
+ const lower = input.toLowerCase();
7564
+ return lower.endsWith(".md") || lower.endsWith(".markdown");
7565
+ }
7566
+ function blockOutputPath(output, index) {
7567
+ const dot = output.lastIndexOf(".");
7568
+ const slash = Math.max(output.lastIndexOf("/"), output.lastIndexOf("\\"));
7569
+ if (dot > slash) {
7570
+ return `${output.slice(0, dot)}.${index}${output.slice(dot)}`;
7571
+ }
7572
+ return `${output}.${index}`;
7573
+ }
6364
7574
  async function handleRender(input, options, _parentOpts) {
6365
7575
  let raw;
6366
7576
  try {
@@ -6370,28 +7580,99 @@ async function handleRender(input, options, _parentOpts) {
6370
7580
  `);
6371
7581
  return void process.exit(2);
6372
7582
  }
7583
+ if (isMarkdownInput(input)) {
7584
+ return void await handleMarkdownRender(raw, input, options);
7585
+ }
7586
+ const single = renderSource(raw, input ? dirname(resolve(input)) : process.cwd(), options);
7587
+ if (!single.ok) return void process.exit(single.code);
7588
+ try {
7589
+ writeOutput(single.payload, options.output);
7590
+ } catch (e) {
7591
+ process.stderr.write(`File I/O error: ${e.message}
7592
+ `);
7593
+ return void process.exit(2);
7594
+ }
7595
+ }
7596
+ async function handleMarkdownRender(raw, input, options) {
7597
+ const baseDir = dirname(resolve(input));
7598
+ const scan = extractFencedBlocks(raw);
7599
+ if (scan.unterminatedLang) {
7600
+ process.stderr.write(
7601
+ `[warning] unterminated \`\`\`${scan.unterminatedLang} fenced block at end of ${input}; skipped.
7602
+ `
7603
+ );
7604
+ }
7605
+ const blocks = scan.blocks.filter((b) => b.trim() !== "");
7606
+ if (blocks.length === 0) {
7607
+ process.stderr.write(`No \`\`\`draw or \`\`\`mermaid fenced blocks found in ${input}; nothing to render.
7608
+ `);
7609
+ return;
7610
+ }
7611
+ const payloads = [];
7612
+ for (const block of blocks) {
7613
+ const result = renderSource(block, baseDir, options);
7614
+ if (!result.ok) return void process.exit(result.code);
7615
+ payloads.push(result.payload);
7616
+ }
7617
+ try {
7618
+ if (options.output) {
7619
+ payloads.forEach((payload, i) => {
7620
+ writeOutput(payload, blockOutputPath(options.output, i + 1));
7621
+ });
7622
+ } else {
7623
+ payloads.forEach((payload, i) => {
7624
+ writeOutput(`<!-- draw-block ${i + 1} -->
7625
+ ${payload}`, void 0);
7626
+ });
7627
+ }
7628
+ } catch (e) {
7629
+ process.stderr.write(`File I/O error: ${e.message}
7630
+ `);
7631
+ return void process.exit(2);
7632
+ }
7633
+ }
7634
+ function renderSource(raw, baseDir, options) {
7635
+ const emit = options.emit ?? "svg";
7636
+ let config = {};
7637
+ const configDiagnostics = [];
6373
7638
  let ir;
6374
7639
  try {
6375
7640
  if (isDrawText(raw)) {
6376
- const result = parseDrawText(raw);
6377
- if (reportDiagnostics(result.diagnostics)) {
6378
- return void process.exit(1);
7641
+ config = loadConfigs(raw, options.config, baseDir, configDiagnostics);
7642
+ const useDiagnostics = [...configDiagnostics];
7643
+ const components = resolveUseDirectives(raw, baseDir, useDiagnostics);
7644
+ resolveConfigComponents(config.components, baseDir, components, useDiagnostics);
7645
+ const result = parseDrawText(raw, { components, ...configToParseOptions(config) });
7646
+ const allDiagnostics = [...useDiagnostics, ...result.diagnostics];
7647
+ if (emit === "dsl" || emit === "tsx") {
7648
+ if (reportDiagnostics(allDiagnostics)) {
7649
+ return { ok: false, code: 1 };
7650
+ }
7651
+ let payload;
7652
+ try {
7653
+ payload = emit === "tsx" ? emitDrawTsx(result.dsl) : JSON.stringify(result.dsl, null, 2) + "\n";
7654
+ } catch (e) {
7655
+ process.stderr.write(`Convert error: ${e.message}
7656
+ `);
7657
+ return { ok: false, code: 1 };
7658
+ }
7659
+ return { ok: true, payload };
7660
+ }
7661
+ if (reportDiagnostics(allDiagnostics)) {
7662
+ return { ok: false, code: 1 };
6379
7663
  }
6380
7664
  ir = result.ir;
6381
7665
  } else if (isDrawTsx(raw)) {
6382
7666
  const compileOpts = {};
6383
- if (input) {
6384
- const baseDir = dirname(resolve(input));
6385
- compileOpts.resolveImport = (specifier, fromFile) => {
6386
- const base = fromFile ? dirname(resolve(baseDir, fromFile)) : baseDir;
6387
- const resolved = resolve(base, specifier);
6388
- if (existsSync(resolved)) return readFileSync4(resolved, "utf-8");
6389
- return void 0;
6390
- };
6391
- }
7667
+ compileOpts.resolveImport = (specifier, fromFile) => {
7668
+ const base = fromFile ? dirname(resolve(baseDir, fromFile)) : baseDir;
7669
+ const resolved = resolve(base, specifier);
7670
+ if (existsSync(resolved)) return readFileSync4(resolved, "utf-8");
7671
+ return void 0;
7672
+ };
6392
7673
  const result = compileDrawTsx(raw, compileOpts);
6393
7674
  if (reportDiagnostics(result.diagnostics)) {
6394
- return void process.exit(1);
7675
+ return { ok: false, code: 1 };
6395
7676
  }
6396
7677
  ir = result.ir;
6397
7678
  } else {
@@ -6400,21 +7681,22 @@ async function handleRender(input, options, _parentOpts) {
6400
7681
  } catch (e) {
6401
7682
  process.stderr.write(`IR validation error: ${e.message}
6402
7683
  `);
6403
- return void process.exit(1);
7684
+ return { ok: false, code: 1 };
6404
7685
  }
6405
7686
  let tokens = defaultTokens();
6406
7687
  let theme = defaultTheme();
7688
+ const themeSpec = options.theme ?? config.theme;
6407
7689
  try {
6408
7690
  if (options.tokens) {
6409
7691
  tokens = parseTokens(readFileSync4(options.tokens, "utf-8"));
6410
7692
  }
6411
- if (options.theme) {
6412
- theme = parseTheme(readFileSync4(options.theme, "utf-8"));
7693
+ if (themeSpec) {
7694
+ theme = parseTheme(readFileSync4(themeSpec, "utf-8"));
6413
7695
  }
6414
7696
  } catch (e) {
6415
7697
  process.stderr.write(`File I/O error: ${e.message}
6416
7698
  `);
6417
- return void process.exit(2);
7699
+ return { ok: false, code: 2 };
6418
7700
  }
6419
7701
  {
6420
7702
  let fontFiles;
@@ -6424,7 +7706,7 @@ async function handleRender(input, options, _parentOpts) {
6424
7706
  if (!existsSync(entry.path)) {
6425
7707
  process.stderr.write(`File I/O error: font file not found: ${entry.path}
6426
7708
  `);
6427
- return void process.exit(2);
7709
+ return { ok: false, code: 2 };
6428
7710
  }
6429
7711
  }
6430
7712
  }
@@ -6441,31 +7723,176 @@ async function handleRender(input, options, _parentOpts) {
6441
7723
  } catch (e) {
6442
7724
  process.stderr.write(`File I/O error: ${e.message}
6443
7725
  `);
6444
- return void process.exit(2);
7726
+ return { ok: false, code: 2 };
6445
7727
  }
6446
7728
  }
6447
- const registry = createIconRegistry();
6448
- registry.register(createAwsIconPack());
7729
+ const registry = buildCliIconRegistry(config.icons, baseDir);
6449
7730
  let svg;
6450
7731
  try {
6451
7732
  const { artifact, diagnostics } = layout(ir, { tokens, theme });
6452
7733
  if (reportDiagnostics(diagnostics)) {
6453
- return void process.exit(1);
7734
+ return { ok: false, code: 1 };
6454
7735
  }
6455
7736
  svg = renderSvg(artifact, { iconRegistry: registry });
6456
7737
  } catch (e) {
6457
7738
  process.stderr.write(`Layout error: ${e.message}
7739
+ `);
7740
+ return { ok: false, code: 1 };
7741
+ }
7742
+ return { ok: true, payload: svg };
7743
+ }
7744
+
7745
+ // src/commands/convert.ts
7746
+ import { readFileSync as readFileSync5, existsSync as existsSync2 } from "fs";
7747
+ import { resolve as resolve2, dirname as dirname2 } from "path";
7748
+ import ts3 from "typescript";
7749
+ async function handleConvert(input, options, _parentOpts) {
7750
+ let raw;
7751
+ try {
7752
+ raw = readInput(input);
7753
+ } catch (e) {
7754
+ process.stderr.write(`File I/O error: ${e.message}
7755
+ `);
7756
+ return void process.exit(2);
7757
+ }
7758
+ const baseDir = input ? dirname2(resolve2(input)) : process.cwd();
7759
+ const diagnostics = [];
7760
+ const config = loadConfigs2(raw, options.config, baseDir, diagnostics);
7761
+ const components = resolveUseDirectives2(raw, baseDir, diagnostics);
7762
+ resolveConfigComponents2(config.components, baseDir, components, diagnostics);
7763
+ const result = parseDrawText(raw, { components, ...configToParseOptions(config) });
7764
+ const allDiagnostics = [...diagnostics, ...result.diagnostics];
7765
+ if (reportDiagnostics(allDiagnostics)) {
7766
+ return void process.exit(1);
7767
+ }
7768
+ let tsx;
7769
+ try {
7770
+ tsx = emitDrawTsx(result.dsl);
7771
+ } catch (e) {
7772
+ process.stderr.write(`Convert error: ${e.message}
6458
7773
  `);
6459
7774
  return void process.exit(1);
6460
7775
  }
6461
7776
  try {
6462
- writeOutput(svg, options.output);
7777
+ writeOutput(tsx, options.output);
6463
7778
  } catch (e) {
6464
7779
  process.stderr.write(`File I/O error: ${e.message}
6465
7780
  `);
6466
7781
  return void process.exit(2);
6467
7782
  }
6468
7783
  }
7784
+ function resolveUseDirectives2(raw, baseDir, diagnostics) {
7785
+ const components = /* @__PURE__ */ new Map();
7786
+ const lines = raw.split("\n");
7787
+ lines.forEach((line, i) => {
7788
+ const m = line.trim().match(/^%%@\s*use\s+(.+)$/);
7789
+ if (!m) return;
7790
+ resolveComponentSpecifier2(m[1].trim(), baseDir, components, `line:${i + 1}`, "%%@ use", diagnostics);
7791
+ });
7792
+ return components;
7793
+ }
7794
+ function resolveConfigComponents2(specifiers, baseDir, components, diagnostics) {
7795
+ if (!specifiers) return;
7796
+ for (const specifier of specifiers) {
7797
+ resolveComponentSpecifier2(specifier, baseDir, components, "config.components", "config components", diagnostics);
7798
+ }
7799
+ }
7800
+ function resolveComponentSpecifier2(specifier, baseDir, components, origin, verb, diagnostics) {
7801
+ const path = resolve2(baseDir, specifier);
7802
+ if (!existsSync2(path)) {
7803
+ diagnostics.push({
7804
+ level: "warning",
7805
+ message: `${verb} ${specifier}: file not found (${path}); bindings referencing its components fall back to plain boxes.`,
7806
+ path: origin
7807
+ });
7808
+ return;
7809
+ }
7810
+ if (specifier.endsWith(".pack.json") || specifier.endsWith(".json")) {
7811
+ try {
7812
+ const json = JSON.parse(readFileSync5(path, "utf-8"));
7813
+ const errors = validateComponentPack(json);
7814
+ if (errors.length > 0) {
7815
+ diagnostics.push({
7816
+ level: "error",
7817
+ message: `${verb} ${specifier}: invalid component pack: ${errors.map((e) => e.message).join("; ")}`,
7818
+ path: origin
7819
+ });
7820
+ return;
7821
+ }
7822
+ const loaded = loadPack(json);
7823
+ for (const def of loaded.components) components.set(def.name, def);
7824
+ } catch (e) {
7825
+ diagnostics.push({
7826
+ level: "error",
7827
+ message: `${verb} ${specifier}: failed to read pack: ${e.message}`,
7828
+ path: origin
7829
+ });
7830
+ }
7831
+ return;
7832
+ }
7833
+ try {
7834
+ const source = readFileSync5(path, "utf-8");
7835
+ const sourceFile = ts3.createSourceFile(path, source, ts3.ScriptTarget.Latest, true, ts3.ScriptKind.TSX);
7836
+ const fileDir = dirname2(path);
7837
+ const resolveImport = (spec, fromFile) => {
7838
+ const base = fromFile ? dirname2(resolve2(fileDir, fromFile)) : fileDir;
7839
+ const resolved = resolve2(base, spec);
7840
+ if (existsSync2(resolved)) return readFileSync5(resolved, "utf-8");
7841
+ return void 0;
7842
+ };
7843
+ const importDefs = resolveImports(sourceFile, resolveImport, diagnostics);
7844
+ for (const [name, def] of importDefs) components.set(name, def);
7845
+ const inlineDefs = extractComponentDefs(sourceFile, diagnostics, components);
7846
+ for (const [name, def] of inlineDefs) components.set(name, def);
7847
+ } catch (e) {
7848
+ diagnostics.push({
7849
+ level: "error",
7850
+ message: `${verb} ${specifier}: failed to compile: ${e.message}`,
7851
+ path: origin
7852
+ });
7853
+ }
7854
+ }
7855
+ function loadConfigs2(raw, cliConfigPath, baseDir, diagnostics) {
7856
+ const merged = {};
7857
+ const paths = [];
7858
+ if (cliConfigPath) paths.push(resolve2(process.cwd(), cliConfigPath));
7859
+ for (const d of scanConfigDirectives(raw)) {
7860
+ paths.push(resolve2(baseDir, d.specifier));
7861
+ }
7862
+ for (const path of paths) {
7863
+ if (!existsSync2(path)) {
7864
+ diagnostics.push({ level: "warning", message: `config not found (${path}); skipped.`, path });
7865
+ continue;
7866
+ }
7867
+ let text;
7868
+ try {
7869
+ text = readFileSync5(path, "utf-8");
7870
+ } catch (e) {
7871
+ diagnostics.push({ level: "warning", message: `config unreadable (${path}): ${e.message}; skipped.`, path });
7872
+ continue;
7873
+ }
7874
+ const { config, diagnostics: cfgDiag } = parseDrawConfig(text, "yaml", path);
7875
+ for (const d of cfgDiag) diagnostics.push({ level: d.level, message: d.message, path: d.path });
7876
+ if (config.icons) {
7877
+ const cfgDir = dirname2(path);
7878
+ const resolved = {};
7879
+ for (const [provider, location] of Object.entries(config.icons)) {
7880
+ resolved[provider] = resolve2(cfgDir, location);
7881
+ }
7882
+ config.icons = resolved;
7883
+ }
7884
+ mergeConfig2(merged, config);
7885
+ }
7886
+ return merged;
7887
+ }
7888
+ function mergeConfig2(dst, src) {
7889
+ if (src.components) dst.components = [...dst.components ?? [], ...src.components];
7890
+ if (src.theme !== void 0) dst.theme = src.theme;
7891
+ if (src.doc) dst.doc = { ...dst.doc ?? {}, ...src.doc };
7892
+ if (src.bindings) dst.bindings = { ...dst.bindings ?? {}, ...src.bindings };
7893
+ if (src.props) dst.props = { ...dst.props ?? {}, ...src.props };
7894
+ if (src.icons) dst.icons = { ...dst.icons ?? {}, ...src.icons };
7895
+ }
6469
7896
 
6470
7897
  // src/commands/validate.ts
6471
7898
  async function handleValidate(input, _options, _parentOpts) {
@@ -6488,7 +7915,7 @@ async function handleValidate(input, _options, _parentOpts) {
6488
7915
  }
6489
7916
 
6490
7917
  // src/commands/ir.ts
6491
- import { readFileSync as readFileSync5 } from "fs";
7918
+ import { readFileSync as readFileSync6 } from "fs";
6492
7919
  async function handleIr(input, options, _parentOpts) {
6493
7920
  let raw;
6494
7921
  try {
@@ -6510,10 +7937,10 @@ async function handleIr(input, options, _parentOpts) {
6510
7937
  let theme = defaultTheme();
6511
7938
  try {
6512
7939
  if (options.tokens) {
6513
- tokens = parseTokens(readFileSync5(options.tokens, "utf-8"));
7940
+ tokens = parseTokens(readFileSync6(options.tokens, "utf-8"));
6514
7941
  }
6515
7942
  if (options.theme) {
6516
- theme = parseTheme(readFileSync5(options.theme, "utf-8"));
7943
+ theme = parseTheme(readFileSync6(options.theme, "utf-8"));
6517
7944
  }
6518
7945
  } catch (e) {
6519
7946
  process.stderr.write(`File I/O error: ${e.message}
@@ -6545,11 +7972,167 @@ async function handleIr(input, options, _parentOpts) {
6545
7972
  }
6546
7973
  }
6547
7974
 
7975
+ // src/commands/components.ts
7976
+ import { readFileSync as readFileSync7, existsSync as existsSync3, writeFileSync as writeFileSync2 } from "fs";
7977
+ import { resolve as resolve3, dirname as dirname3 } from "path";
7978
+ import ts4 from "typescript";
7979
+ function collectComponentDefs(entryPath, diagnostics) {
7980
+ const source = readFileSync7(entryPath, "utf-8");
7981
+ const baseDir = dirname3(resolve3(entryPath));
7982
+ const resolveImport = (specifier, fromFile) => {
7983
+ const base = fromFile ? dirname3(resolve3(baseDir, fromFile)) : baseDir;
7984
+ const resolved = resolve3(base, specifier);
7985
+ if (existsSync3(resolved)) return readFileSync7(resolved, "utf-8");
7986
+ return void 0;
7987
+ };
7988
+ const sourceFile = ts4.createSourceFile(
7989
+ entryPath,
7990
+ source,
7991
+ ts4.ScriptTarget.Latest,
7992
+ true,
7993
+ ts4.ScriptKind.TSX
7994
+ );
7995
+ const registry = /* @__PURE__ */ new Map();
7996
+ const importDefs = resolveImports(sourceFile, resolveImport, diagnostics);
7997
+ for (const [name, def] of importDefs) registry.set(name, def);
7998
+ const inlineDefs = extractComponentDefs(sourceFile, diagnostics, registry);
7999
+ for (const [name, def] of inlineDefs) registry.set(name, def);
8000
+ return registry;
8001
+ }
8002
+ async function handleComponentsBuild(entry, options, _parentOpts) {
8003
+ if (!entry) {
8004
+ process.stderr.write("File I/O error: an entry .draw.tsx file is required\n");
8005
+ return void process.exit(2);
8006
+ }
8007
+ if (!existsSync3(entry)) {
8008
+ process.stderr.write(`File I/O error: entry file not found: ${entry}
8009
+ `);
8010
+ return void process.exit(2);
8011
+ }
8012
+ const diagnostics = [];
8013
+ let defs;
8014
+ try {
8015
+ defs = collectComponentDefs(entry, diagnostics);
8016
+ } catch (e) {
8017
+ process.stderr.write(`File I/O error: ${e.message}
8018
+ `);
8019
+ return void process.exit(2);
8020
+ }
8021
+ if (reportDiagnostics(diagnostics)) {
8022
+ return void process.exit(1);
8023
+ }
8024
+ const icons = {};
8025
+ if (options.icons !== void 0 && options.icons.trim() !== "") {
8026
+ const registry = createIconRegistry();
8027
+ registry.register(createAwsIconPack());
8028
+ const names = options.icons.split(",").map((n) => n.trim()).filter((n) => n !== "");
8029
+ const unresolved = [];
8030
+ for (const qualified of names) {
8031
+ const svg = registry.resolveQualified(qualified);
8032
+ if (svg === void 0) {
8033
+ unresolved.push(qualified);
8034
+ } else {
8035
+ icons[qualified] = svg;
8036
+ }
8037
+ }
8038
+ if (unresolved.length > 0) {
8039
+ process.stderr.write(
8040
+ `[error] --icons: could not resolve ${unresolved.length} icon(s) at build time: ${unresolved.join(", ")}
8041
+ `
8042
+ );
8043
+ return void process.exit(1);
8044
+ }
8045
+ }
8046
+ const pack = buildComponentPack([...defs.values()], icons);
8047
+ const json = serializePack(pack);
8048
+ try {
8049
+ if (options.output) {
8050
+ writeFileSync2(options.output, json, "utf-8");
8051
+ } else {
8052
+ process.stdout.write(json);
8053
+ }
8054
+ } catch (e) {
8055
+ process.stderr.write(`File I/O error: ${e.message}
8056
+ `);
8057
+ return void process.exit(2);
8058
+ }
8059
+ }
8060
+
8061
+ // src/commands/icons.ts
8062
+ import { writeFileSync as writeFileSync3, mkdirSync, existsSync as existsSync4, statSync } from "fs";
8063
+ import { join } from "path";
8064
+ function buildRegistry() {
8065
+ const registry = createIconRegistry();
8066
+ registry.register(createAwsIconPack());
8067
+ return registry;
8068
+ }
8069
+ async function handleIconsExport(provider, options, _parentOpts) {
8070
+ if (!provider) {
8071
+ process.stderr.write("File I/O error: a provider (e.g. 'aws') is required\n");
8072
+ return void process.exit(2);
8073
+ }
8074
+ const outDir = options.output;
8075
+ if (!outDir) {
8076
+ process.stderr.write("File I/O error: an output directory (-o <dir>) is required\n");
8077
+ return void process.exit(2);
8078
+ }
8079
+ const names = options.names === void 0 ? [] : options.names.split(",").map((n) => n.trim()).filter((n) => n !== "");
8080
+ if (names.length === 0) {
8081
+ process.stderr.write("File I/O error: --names must list at least one icon short name\n");
8082
+ return void process.exit(2);
8083
+ }
8084
+ const registry = buildRegistry();
8085
+ const resolved = /* @__PURE__ */ new Map();
8086
+ const unresolved = [];
8087
+ for (const name of names) {
8088
+ const svg = registry.resolve(provider, name);
8089
+ if (svg === void 0) {
8090
+ unresolved.push(name);
8091
+ } else {
8092
+ resolved.set(name, svg);
8093
+ }
8094
+ }
8095
+ if (unresolved.length > 0) {
8096
+ process.stderr.write(
8097
+ `[error] icons export: provider "${provider}" could not resolve: ${unresolved.join(", ")}
8098
+ `
8099
+ );
8100
+ return void process.exit(1);
8101
+ }
8102
+ try {
8103
+ if (!existsSync4(outDir)) {
8104
+ mkdirSync(outDir, { recursive: true });
8105
+ } else if (!statSync(outDir).isDirectory()) {
8106
+ process.stderr.write(`File I/O error: output path is not a directory: ${outDir}
8107
+ `);
8108
+ return void process.exit(2);
8109
+ }
8110
+ for (const [name, svg] of resolved) {
8111
+ writeFileSync3(join(outDir, `${name}.svg`), svg, "utf-8");
8112
+ }
8113
+ } catch (e) {
8114
+ process.stderr.write(`File I/O error: ${e.message}
8115
+ `);
8116
+ return void process.exit(2);
8117
+ }
8118
+ }
8119
+
6548
8120
  // src/cli.ts
6549
8121
  var handlers = {
6550
8122
  render: handleRender,
8123
+ convert: handleConvert,
6551
8124
  validate: handleValidate,
6552
- ir: handleIr
8125
+ ir: handleIr,
8126
+ componentsBuild: handleComponentsBuild,
8127
+ iconsExport: handleIconsExport
6553
8128
  };
6554
8129
  var program = createProgram(handlers, "0.1.0");
8130
+ var renderCmd = program.commands.find((c) => c.name() === "render");
8131
+ if (renderCmd) {
8132
+ renderCmd.option(
8133
+ "--emit <value>",
8134
+ "Output stage: 'svg' (default), 'dsl' (the intermediate Draw DSL tree JSON, spec \xA78.1), or 'tsx' (that same DSL tree serialized as Draw TSX, the #66 emitter \u2014 same output `convert` produces).",
8135
+ "svg"
8136
+ );
8137
+ }
6555
8138
  program.parse();