@x-cmd/draw 0.0.0-stage → 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.
Files changed (106) hide show
  1. package/LICENSE +228 -0
  2. package/README.cn.md +235 -0
  3. package/README.md +235 -2
  4. package/dist/lib.d.ts +25 -0
  5. package/dist/lib.js +50 -0
  6. package/dist/node/cli.d.ts +2 -0
  7. package/dist/node/cli.js +79 -0
  8. package/dist/render/area.d.ts +8 -0
  9. package/dist/render/area.js +414 -0
  10. package/dist/render/bar-grid.d.ts +3 -0
  11. package/dist/render/bar-grid.js +52 -0
  12. package/dist/render/bar-grouped.d.ts +3 -0
  13. package/dist/render/bar-grouped.js +131 -0
  14. package/dist/render/bar-stacked.d.ts +3 -0
  15. package/dist/render/bar-stacked.js +142 -0
  16. package/dist/render/bar.d.ts +3 -0
  17. package/dist/render/bar.js +74 -0
  18. package/dist/render/combo.d.ts +3 -0
  19. package/dist/render/combo.js +256 -0
  20. package/dist/render/dispatch.d.ts +3 -0
  21. package/dist/render/dispatch.js +69 -0
  22. package/dist/render/gauge.d.ts +3 -0
  23. package/dist/render/gauge.js +216 -0
  24. package/dist/render/hbar-spec.d.ts +7 -0
  25. package/dist/render/hbar-spec.js +265 -0
  26. package/dist/render/hbar.d.ts +3 -0
  27. package/dist/render/hbar.js +55 -0
  28. package/dist/render/line-multi.d.ts +3 -0
  29. package/dist/render/line-multi.js +89 -0
  30. package/dist/render/line.d.ts +11 -0
  31. package/dist/render/line.js +123 -0
  32. package/dist/render/measure.d.ts +60 -0
  33. package/dist/render/measure.js +75 -0
  34. package/dist/render/pie.d.ts +5 -0
  35. package/dist/render/pie.js +439 -0
  36. package/dist/render/qr.d.ts +8 -0
  37. package/dist/render/qr.js +52 -0
  38. package/dist/render/query.d.ts +14 -0
  39. package/dist/render/query.js +220 -0
  40. package/dist/render/radar.d.ts +5 -0
  41. package/dist/render/radar.js +221 -0
  42. package/dist/render/sankey.d.ts +3 -0
  43. package/dist/render/sankey.js +280 -0
  44. package/dist/render/scatter.d.ts +3 -0
  45. package/dist/render/scatter.js +98 -0
  46. package/dist/render/svg.d.ts +93 -0
  47. package/dist/render/svg.js +471 -0
  48. package/dist/specs/base.d.ts +34 -0
  49. package/dist/specs/base.js +159 -0
  50. package/dist/specs/combo.d.ts +15 -0
  51. package/dist/specs/combo.js +135 -0
  52. package/dist/specs/csv.d.ts +1 -0
  53. package/dist/specs/csv.js +40 -0
  54. package/dist/specs/gauge.d.ts +15 -0
  55. package/dist/specs/gauge.js +108 -0
  56. package/dist/specs/index.d.ts +8 -0
  57. package/dist/specs/index.js +9 -0
  58. package/dist/specs/input.d.ts +11 -0
  59. package/dist/specs/input.js +33 -0
  60. package/dist/specs/multi.d.ts +12 -0
  61. package/dist/specs/multi.js +112 -0
  62. package/dist/specs/sankey.d.ts +13 -0
  63. package/dist/specs/sankey.js +112 -0
  64. package/dist/specs/scatter.d.ts +20 -0
  65. package/dist/specs/scatter.js +121 -0
  66. package/dist/store.d.ts +15 -0
  67. package/dist/store.js +121 -0
  68. package/dist/styles/area.d.ts +2 -0
  69. package/dist/styles/area.js +106 -0
  70. package/dist/styles/bar.d.ts +2 -0
  71. package/dist/styles/bar.js +52 -0
  72. package/dist/styles/combo.d.ts +2 -0
  73. package/dist/styles/combo.js +37 -0
  74. package/dist/styles/common.d.ts +34 -0
  75. package/dist/styles/common.js +259 -0
  76. package/dist/styles/gauge.d.ts +2 -0
  77. package/dist/styles/gauge.js +51 -0
  78. package/dist/styles/handlee.d.ts +1 -0
  79. package/dist/styles/handlee.js +2 -0
  80. package/dist/styles/hbar.d.ts +2 -0
  81. package/dist/styles/hbar.js +66 -0
  82. package/dist/styles/index.d.ts +7 -0
  83. package/dist/styles/index.js +79 -0
  84. package/dist/styles/inter.d.ts +3 -0
  85. package/dist/styles/inter.js +10 -0
  86. package/dist/styles/line.d.ts +2 -0
  87. package/dist/styles/line.js +97 -0
  88. package/dist/styles/pie.d.ts +2 -0
  89. package/dist/styles/pie.js +163 -0
  90. package/dist/styles/qr.d.ts +2 -0
  91. package/dist/styles/qr.js +12 -0
  92. package/dist/styles/radar.d.ts +2 -0
  93. package/dist/styles/radar.js +50 -0
  94. package/dist/styles/sankey.d.ts +2 -0
  95. package/dist/styles/sankey.js +29 -0
  96. package/dist/styles/scatter.d.ts +2 -0
  97. package/dist/styles/scatter.js +21 -0
  98. package/dist/styles/types.d.ts +105 -0
  99. package/dist/styles/types.js +70 -0
  100. package/dist/theme.d.ts +3 -0
  101. package/dist/theme.js +11 -0
  102. package/dist/types.d.ts +17 -0
  103. package/dist/types.js +1 -0
  104. package/dist/version.d.ts +6 -0
  105. package/dist/version.js +16 -0
  106. package/package.json +53 -4
package/README.md CHANGED
@@ -1,3 +1,236 @@
1
- # Temporary Holding Version
1
+ # draw
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > English | [中文](README.cn.md)
4
+
5
+ SVG chart generation for the AI era. One endpoint — `/draw?type=...` — with the data in the URL, machine-readable `<metadata>` embedded in every output, and SVG rendered directly by TypeScript. The style system mirrors a designer spec (13 SVGs), with multiple style variants per chart type.
6
+
7
+ ## Three ways to use it (one render core)
8
+
9
+ **Hosted service** (zero install): just build a URL — `https://x-cmd.com/draw?type=pie&labels=A,B&values=3,2`
10
+
11
+ **npm library** (offline/embedded, synchronous, no network; params identical to the URL):
12
+
13
+ ```sh
14
+ npm install @x-cmd/draw
15
+ ```
16
+ ```ts
17
+ import { draw } from '@x-cmd/draw';
18
+ const { svg } = draw({ type: 'pie', labels: 'A,B', values: '3,2', t: 'evil', scheme: 'dark' });
19
+ // also accepts a query string: draw('?type=bar&labels=Mon,Tue&values=3,5')
20
+ // array values = repeated params (when labels contain commas):
21
+ draw({ type: 'bar', labels: ['Q1, 2024', 'Q2'], values: [1, 2] })
22
+ ```
23
+
24
+ **CLI** (after `npm i -g @x-cmd/draw`, or via `npx`):
25
+
26
+ ```sh
27
+ draw --type pie --labels "TypeScript,Python,Go" --values "4821,2312,980" --out pie.svg
28
+ draw --type hbar --labels a,b,c --values 3,2,1 --theme xcmd # long flags (--theme/--width/--height)
29
+ draw "?type=hbar&labels=a,b,c&values=3,2,1&t=xcmd" # bare query string, same params as the URL
30
+ ```
31
+
32
+ **Self-host** — pick any entry point:
33
+
34
+ ```sh
35
+ git clone https://github.com/x-cmd/draw && cd draw && npm install
36
+ npm run serve # local Node server (http://localhost:8787/draw, demo page included)
37
+ npm run dev # Cloudflare wrangler local dev
38
+ bash scripts/setup.sh # one-shot deploy to your own Cloudflare account
39
+ ```
40
+
41
+ Environment variables (Node server): `PORT` (default 8787) · `BASE_PATH` · `DATA_REPO`/`DATA_BRANCH`/`GITHUB_TOKEN` (set these to enable POST short links; unset degrades gracefully, exactly like self-deployed workers).
42
+
43
+ **Deno** (native TS; the render core is pure — no network, no files — so the zero-permission sandbox is the security boundary):
44
+
45
+ ```ts
46
+ import { draw } from "jsr:@x-cmd/draw"; // JSR (Deno's native registry)
47
+ // or npm: import { draw } from "npm:@x-cmd/draw";
48
+ const { svg } = draw({ type: "pie", labels: "A,B", values: "3,2" });
49
+ ```
50
+
51
+ ```sh
52
+ deno add jsr:@x-cmd/draw
53
+ # run straight from source inside the repo (no build):
54
+ deno task cli --type pie --labels A,B --values 3,2 --out pie.svg # only needs --allow-write
55
+ deno task serve # local server (same as npm run serve)
56
+ # proof of zero permissions: deno eval defaults to no grants — importing and rendering just works
57
+ ```
58
+
59
+ ## Endpoints
60
+
61
+ **`GET /draw?type=<pie|bar|hbar|line|area|radar|gauge|scatter|combo|sankey|qr>`** — render a chart
62
+
63
+ | type | chart | limits |
64
+ |---|---|---|
65
+ | `pie` | donut; `donut=0` for a solid pie | ≤100 categories (>9 auto-merge into Other) |
66
+ | `bar` | grouped columns; multi-series with `stack=1` for stacked | ≤30 groups |
67
+ | `hbar` | horizontal bars (rankings; labels left, values right) | ≤30 bars, single series (some styles take two) |
68
+ | `line` | smooth line + gradient area / multi-line | ≤60 points |
69
+ | `area` | area / multi-series area (gradient fill) | ≤60 points |
70
+ | `radar` | radar chart | 3–12 axes |
71
+ | `gauge` | gauge (240° arc + center value) | `value`+`max` (default 100), value ≤ max; multi-ring ≤8 |
72
+ | `scatter` | scatter (two numeric axes, negatives supported; no value labels by default) | `x=&y=`, ≤200 points |
73
+ | `combo` | bars (`series=`) + line (`line=`) in one chart; `stack=1` to stack the bars | ≤30 groups, ≤6 series total |
74
+ | `sankey` | flow diagram with weighted bands | `labels=`+`links=A>B:30`, ≤24 nodes/60 links |
75
+ | `qr` | QR code | `d`=text (≤1000 chars), `fg`/`bg` colors, `title`/`unit` captions |
76
+
77
+ **`GET /draw`** (no params) or `?tab=pie` — the demo page (11 chart types, all style variants, dual URL forms)
78
+ **`POST /draw?type=...`** — submit a JSON/CSV body to create a permanent short link
79
+ **`GET /draw/c/<hash>`** — short-link render (immutable)
80
+
81
+ Common parameters:
82
+
83
+ - `t` style family (per chart type, see below; falls back to default when not built for that type)
84
+ - `scheme` `auto` (default, follows system) / `dark` / `light`
85
+ - `v` pin a version; `w`/`h` size (200–1600 / 140–1200; qr is 120–1000 / 140–1000)
86
+ - `num` value labels: `all` / `peak` (highest only) / `none`. Defaults follow the style; applies to pie/bar/hbar/line/area/scatter/combo (radar/gauge/sankey/qr ignore it)
87
+ - `subtitle` editorial subtitle (only rendered by area's editorial style `t=opendata`), `source` data-source footnote (area only, any `t`); other types parse but ignore these
88
+
89
+ ## Styles (`?t=`)
90
+
91
+ Per chart type, with automatic light/dark palettes:
92
+
93
+ | type | available families |
94
+ |---|---|
95
+ | `pie` | `opendata` (default, all labels outside), `evil` (rounded ring + inner values), `evil-mono` (solid pie + leader lines), `market-mono` (grayscale + ring total), `progress` (dotted progress ring), `revenue` (gradient wedges + dashed inner ring) |
96
+ | `bar` | `evil` (default, grouped), `base` (card), `grid` (table bars) |
97
+ | `hbar` | `base` (default), `opendata` (supports `ref=`/`reflabel=` reference line), `xcmd` (pixel bars, %), `xcmd-issue` (two-series butterfly), `rank` (two-series solid + hatching) |
98
+ | `line` | `shadcn` (default), `evil`, `evil-glow` (glow), `evil-mono`, `opendata` (line-end labels) |
99
+ | `area` | `evil` (default, two-series dashed areas), `star` (hand-drawn), `opendata` (dense gradient + editorial title), `pixel`, `polka` |
100
+ | `radar` | `base` (default), `evil` (multi-series), `xcmd` |
101
+ | `sankey` | `base` (default), `fund`, `pipeline` |
102
+ | `gauge` | `base` (default), `gradient`, `reliability` (zoned ring gauge) |
103
+ | `scatter` / `combo` / `qr` | `base` (combo also has `evil`) |
104
+
105
+ ## Two ways to pass data
106
+
107
+ **Flat params** (URL stays readable — recommended):
108
+
109
+ ```
110
+ /draw?type=pie&title=Stars by language&unit=stars&labels=TypeScript,Python,Go,Rust&values=4821,2312,980,645
111
+ /draw?type=bar&title=Weekly downloads&labels=Mon,Tue&values=1200,1800
112
+ ```
113
+
114
+ When labels contain commas, use repeated params: `labels=Q1, 2024&labels=Q2&values=1&values=2`
115
+
116
+ **Multi-series comparison** (type=bar grouped/stacked, type=line, type=area, ≤6 series):
117
+
118
+ ```
119
+ /draw?type=area&labels=Mon,Tue,Wed&series=Desktop:120,180,150&series=Mobile:80,90,85
120
+ ```
121
+
122
+ **JSON form** (complex data): `?d=` + URL-encoded JSON:
123
+
124
+ ```json
125
+ {"title":"Stars by language","unit":"stars","data":[{"label":"TypeScript","value":4821},{"label":"Python","value":2312}]}
126
+ ```
127
+
128
+ Multi-series JSON: `{"labels":["Mon","Tue"],"series":[{"name":"draw","values":[120,180]},{"name":"qc","values":[80,90]}]}`
129
+
130
+ QR code: `/draw?type=qr&d=https://github.com/tzw&fg=%236366f1`
131
+
132
+ Gauge: `/draw?type=gauge&title=Build pass rate&value=87&max=100`
133
+
134
+ Scatter: `/draw?type=scatter&x=10,20,30&y=5,8,7`
135
+
136
+ Combo: `/draw?type=combo&labels=Mon,Tue&series=dl:120,180&line=growth:5,8` (dual y-axes kick in automatically when bars and lines differ by >5×)
137
+
138
+ ## Short links (data stored in a GitHub repo; content-addressed, never expires)
139
+
140
+ ```
141
+ POST /draw?type=pie body = chart spec JSON
142
+ POST /draw?type=bar&t=evil body = CSV (text/csv, header row)
143
+ → 201 {"hash":"a3f9c2d4e5f60718","url":"https://x-cmd.com/draw/c/a3f9c2d4e5f60718"}
144
+
145
+ GET /draw/c/<hash> → SVG, cached immutable forever
146
+ ```
147
+
148
+ - The fingerprint is the first 16 hex chars of SHA-256 over canonicalized data (template+theme+spec, keys recursively sorted); identical data → identical short link (dedup, idempotent). On read the fingerprint is re-verified — tampered archives are rejected
149
+ - Multi-series is supported for bar/line/area/radar, plus hbar (only `t=xcmd-issue`/`t=rank`, exactly 2 series); other types reject multi-series bodies with 400. POST is rate-limited to 30/min/IP
150
+ - Server-side config: `DATA_REPO` (public repo, `owner/name`, in wrangler.jsonc) and `GITHUB_TOKEN` (secret; fine-grained PAT with **Contents: write** on that repo only — reads go through raw, tokenless). Data files live at `charts/<hash>.json`
151
+ - Visibility: the data repo is public and browsable — **do not create short links with sensitive data** (private storage is planned, as a paid feature)
152
+ - Compared to quickchart: their short links expire (6 months / days); ours never do
153
+
154
+ ## Version semantics
155
+
156
+ - No `v`: renders the **latest** version, `Cache-Control: max-age=300` (output changes as the service upgrades)
157
+ - `?v=1`: pins a version, `Cache-Control: max-age=86400` (1 day; rendering still evolves with deploys — not frozen forever). `v` accepts 1..current; out of range → 400
158
+ - `immutable` is reserved for short links `/c/<hash>` (content-addressed, truly unchanging; `v` is ignored there)
159
+
160
+ ## AI-friendly
161
+
162
+ Every SVG embeds `<metadata>` (escaped JSON): `{generator, template, version, spec}` — data and params round-trip directly. All text is real `<text>` elements.
163
+
164
+ ## Project structure
165
+
166
+ A request flows **handler.ts (HTTP routing) → render/query.ts (params → render core) → specs/ (parse) → styles/ (pick skin) → render/ (geometry → SVG)**. The render core is pure functions shared by three runtimes: the Cloudflare Worker (index.ts thin shell), the Node server (node/server.ts), and the npm/JSR library + CLI (lib.ts + node/cli.ts).
167
+
168
+ ```
169
+ src/
170
+ ├── index.ts Cloudflare Workers entry (thin shell: edge cache, rate-limit binding, waitUntil)
171
+ ├── handler.ts shared HTTP layer: routing, POST short-link creation, short-link render, demo page, error wrapper
172
+ ├── lib.ts npm/JSR library entry (barrel + high-level synchronous draw())
173
+ ├── demo.ts demo page (type tabs, style variants, dual URL forms)
174
+ ├── theme.ts skin → CSS variables (:root + dark media query)
175
+ ├── store.ts short-link storage (GitHub repo read/write, fingerprint, idempotency)
176
+ ├── version.ts version numbers and cache semantics
177
+ ├── types.ts cross-runtime structural types (DrawEnv/Platform)
178
+ │
179
+ ├── specs/ [parse] URL params → strongly-typed spec (validation, clipping, limits)
180
+ │ ├── base.ts ChartSpec + both flat-params and JSON forms
181
+ │ ├── multi.ts multi-series (series=) parsing
182
+ │ └── gauge/scatter/combo/csv.ts per-type parsers
183
+ │
184
+ ├── render/ [render] spec + skin → SVG string (pure computation, no layout engine)
185
+ │ ├── svg.ts shared helpers: layout geometry, scales, grid, legend, label collision, text measurement
186
+ │ ├── query.ts params→SVG synchronous core (GET dispatch + short-link segment; shared by lib and HTTP)
187
+ │ ├── dispatch.ts stored chart → renderer template dispatch
188
+ │ ├── pie/line/line-multi/area/… one file per chart type (bar ×3, line ×2)
189
+ │ └── qr.ts QR codes
190
+ │
191
+ ├── styles/ [style] designer-spec SVGs turned into rules
192
+ │ ├── types.ts Rules vocabulary + defaults (orientation/radius/legend/dash/labels…)
193
+ │ ├── pie/line/area/… per-type variants (light+dark palettes + rule deltas + spec canvas size)
194
+ │ ├── common.ts spec palette constants
195
+ │ ├── handlee.ts hand-drawn font, base64 (star style)
196
+ │ └── index.ts resolveSkin: type + ?t= + scheme → skin
197
+ │
198
+ └── node/ [Node] server.ts local server · cli.ts draw CLI
199
+
200
+ test/ vitest (parsing + renderers + shared HTTP layer + library API)
201
+ wrangler.jsonc deploy config (route x-cmd.com/draw*)
202
+ deno.json JSR publishing + Deno tasks
203
+ ```
204
+
205
+ Adding a chart type = one file each in `specs/xxx.ts` + `render/xxx.ts` + `styles/xxx.ts`, plus one registration line each in `render/dispatch.ts` and `render/query.ts`.
206
+
207
+ ## One-shot self-deploy
208
+
209
+ Deploy your own draw to your Cloudflare account (free tier works; you just need a CF account):
210
+
211
+ ```sh
212
+ curl -fsSL https://raw.githubusercontent.com/x-cmd/draw/main/scripts/setup.sh | bash
213
+ ```
214
+
215
+ The script: clones the repo → browser login for wrangler → deploys → smoke test → prints your `*.workers.dev` URL. All GET rendering (11 chart types, every style) works out of the box.
216
+
217
+ - **Short links (POST) are not enabled by default** — calls return a "not configured" message. To enable: create a public data repo → set `DATA_REPO=owner/name` in the local wrangler.jsonc vars → `npx wrangler secret put GITHUB_TOKEN` (fine-grained PAT, Contents: write on that repo only) → redeploy
218
+ - Already cloned the repo? Run `npm run setup` inside it (skips the clone)
219
+ - Path prefix auto-adapts: both the workers.dev root and a `/draw` sub-route work with zero code changes; or pin it explicitly with the `BASE_PATH` var
220
+ - Custom domain: dashboard → Workers → Settings → Domains & Routes, add a route (any path prefix)
221
+ - On Windows, run under WSL or Git Bash
222
+
223
+ ## Development
224
+
225
+ ```sh
226
+ npm install
227
+ npm run dev # wrangler dev, local server
228
+ npm test # vitest
229
+ npm run check # tsc --noEmit × 3 (worker / node / build)
230
+ npm run build # emit dist/ (npm library + CLI)
231
+ npm run deploy # wrangler deploy
232
+ ```
233
+
234
+ ## License
235
+
236
+ Code is [Apache-2.0](LICENSE). Bundled fonts keep their own licenses: Inter (OFL, full text in `src/styles/inter-OFL.txt`) and Handlee (OFL).
package/dist/lib.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ export * from './specs/index.js';
2
+ export * from './styles/index.js';
3
+ export { CURRENT_VERSION, resolveVersion, type VersionInfo } from './version.js';
4
+ export { renderPie } from './render/pie.js';
5
+ export { renderBar } from './render/bar.js';
6
+ export { renderBarGrid } from './render/bar-grid.js';
7
+ export { renderBarMulti } from './render/bar-grouped.js';
8
+ export { renderBarStacked } from './render/bar-stacked.js';
9
+ export { renderLine } from './render/line.js';
10
+ export { renderLineMulti } from './render/line-multi.js';
11
+ export { renderAreaByMode } from './render/area.js';
12
+ export { renderRadarByMode } from './render/radar.js';
13
+ export { renderHbarByMode } from './render/hbar-spec.js';
14
+ export { renderGauge } from './render/gauge.js';
15
+ export { renderScatter } from './render/scatter.js';
16
+ export { renderCombo } from './render/combo.js';
17
+ export { renderQR } from './render/qr.js';
18
+ export { renderSankey } from './render/sankey.js';
19
+ export { renderStored } from './render/dispatch.js';
20
+ export type { RenderOpts } from './render/svg.js';
21
+ import { type DrawResult } from './render/query.js';
22
+ export { renderFromUrl, renderStoredFromUrl } from './render/query.js';
23
+ export type { DrawResult } from './render/query.js';
24
+ export { CHART_TEMPLATES, fingerprint, canonicalJson, type ChartTemplate, type StoredChart, } from './store.js';
25
+ export declare function draw(params: Record<string, string | string[]> | URLSearchParams | string): DrawResult;
package/dist/lib.js ADDED
@@ -0,0 +1,50 @@
1
+ // npm 库入口(@x-cmd/draw):
2
+ // import { draw } from '@x-cmd/draw';
3
+ // const { svg } = draw({ type: 'pie', labels: 'A,B', values: '3,2' });
4
+ // 高层 draw() 同步渲染,与 GET /draw?type=... 完全同参同输出,无需网络。
5
+ // 亦可直接使用下层解析/渲染/皮肤 API(与线上服务同一套代码)。
6
+ export * from './specs/index.js';
7
+ export * from './styles/index.js';
8
+ export { CURRENT_VERSION, resolveVersion } from './version.js';
9
+ export { renderPie } from './render/pie.js';
10
+ export { renderBar } from './render/bar.js';
11
+ export { renderBarGrid } from './render/bar-grid.js';
12
+ export { renderBarMulti } from './render/bar-grouped.js';
13
+ export { renderBarStacked } from './render/bar-stacked.js';
14
+ export { renderLine } from './render/line.js';
15
+ export { renderLineMulti } from './render/line-multi.js';
16
+ export { renderAreaByMode } from './render/area.js';
17
+ export { renderRadarByMode } from './render/radar.js';
18
+ export { renderHbarByMode } from './render/hbar-spec.js';
19
+ export { renderGauge } from './render/gauge.js';
20
+ export { renderScatter } from './render/scatter.js';
21
+ export { renderCombo } from './render/combo.js';
22
+ export { renderQR } from './render/qr.js';
23
+ export { renderSankey } from './render/sankey.js';
24
+ export { renderStored } from './render/dispatch.js';
25
+ import { renderFromUrl } from './render/query.js';
26
+ export { renderFromUrl, renderStoredFromUrl } from './render/query.js';
27
+ export { CHART_TEMPLATES, fingerprint, canonicalJson, } from './store.js';
28
+ // 对象/查询串/URLSearchParams → DrawResult(同步)。
29
+ // 对象值支持数组(重复参数,labels 含逗号时用):
30
+ // draw({ type: 'bar', labels: ['Q1, 2024', 'Q2'], values: [1, 2] })
31
+ function toSearchParams(o) {
32
+ const sp = new URLSearchParams();
33
+ for (const [k, v] of Object.entries(o)) {
34
+ if (Array.isArray(v))
35
+ for (const item of v)
36
+ sp.append(k, item);
37
+ else
38
+ sp.append(k, v);
39
+ }
40
+ return sp;
41
+ }
42
+ export function draw(params) {
43
+ const sp = typeof params === 'string'
44
+ ? new URLSearchParams(params.startsWith('?') ? params.slice(1) : params)
45
+ : params instanceof URLSearchParams
46
+ ? params
47
+ : toSearchParams(params);
48
+ // renderFromUrl 只读 searchParams;host 用占位符,不发起任何网络请求
49
+ return renderFromUrl(new URL(`https://draw.local/?${sp.toString()}`));
50
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ // CLI:把查询参数渲染成 SVG,写 stdout 或 --out 文件。
3
+ // draw --type pie --labels "A,B" --values "3,2" --out pie.svg
4
+ // draw "?type=bar&labels=Mon,Tue&values=3,5&scheme=dark" # 裸查询串(与 URL 同参)
5
+ // 未知 flag 透传为查询参数(--ref 5 → ref=5);重复 flag → 重复参数(labels 含逗号时用)。
6
+ // 参数语义与 GET /draw 完全一致,见 README 或 x-cmd.com/draw 演示页。
7
+ import { writeFileSync } from 'node:fs';
8
+ import { draw } from '../lib.js';
9
+ import { ApiError } from '../specs/index.js';
10
+ // 长 flag → 查询参数名(单字母直写也依然有效,经透传)
11
+ const ALIASES = { theme: 't', width: 'w', height: 'h' };
12
+ const HELP = `usage: draw --type <pie|bar|hbar|line|area|radar|gauge|scatter|combo|sankey|qr> [params] [--out <file.svg>]
13
+
14
+ params are the same as GET /draw query params:
15
+ --labels "A,B" --values "3,2" data (repeated flags = repeated params)
16
+ --theme <family> --scheme <auto|dark|light> --width 560 --height 300 --num all
17
+ --title "Stars by language" --unit stars
18
+ (single-letter query names also pass through: --t evil --w 560)
19
+ or pass one bare query string:
20
+ draw "?type=pie&labels=A,B&values=3,2"
21
+
22
+ examples:
23
+ draw --type pie --labels "TypeScript,Python,Go" --values "4821,2312,980" --out pie.svg
24
+ draw "?type=hbar&labels=a,b,c&values=3,2,1&t=xcmd" | open -f -a Safari`;
25
+ function fail(msg) {
26
+ console.error(`draw: ${msg}\n\n${HELP}`);
27
+ process.exit(1);
28
+ }
29
+ const args = process.argv.slice(2);
30
+ if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
31
+ console.log(HELP);
32
+ process.exit(0);
33
+ }
34
+ const sp = new URLSearchParams();
35
+ let out;
36
+ for (let i = 0; i < args.length; i++) {
37
+ const a = args[i];
38
+ if (a === '--out' || a === '-o') {
39
+ out = args[++i];
40
+ if (out === undefined)
41
+ fail('--out requires a file path');
42
+ continue;
43
+ }
44
+ if (a.startsWith('--')) {
45
+ const key = ALIASES[a.slice(2)] ?? a.slice(2);
46
+ const next = args[i + 1];
47
+ if (next === undefined || next.startsWith('--')) {
48
+ sp.set(key, '1'); // 无值 flag → 布尔(--stack → stack=1)
49
+ continue;
50
+ }
51
+ sp.append(key, next);
52
+ i++;
53
+ continue;
54
+ }
55
+ if (a.includes('=')) {
56
+ const qs = new URLSearchParams(a.startsWith('?') ? a.slice(1) : a);
57
+ for (const [k, v] of qs)
58
+ sp.append(k, v);
59
+ continue;
60
+ }
61
+ fail(`unexpected argument: ${a}`);
62
+ }
63
+ try {
64
+ const { svg } = draw(sp);
65
+ if (out !== undefined) {
66
+ writeFileSync(out, svg);
67
+ console.error(`wrote ${out} (${svg.length} bytes)`);
68
+ }
69
+ else {
70
+ process.stdout.write(svg);
71
+ }
72
+ }
73
+ catch (e) {
74
+ if (e instanceof ApiError) {
75
+ console.error(`draw: ${e.message}`);
76
+ process.exit(1);
77
+ }
78
+ throw e;
79
+ }
@@ -0,0 +1,8 @@
1
+ import { type ChartSpec, type MultiSpec } from '../specs/index.js';
2
+ import { type RenderOpts } from './svg.js';
3
+ export declare function renderArea(spec: ChartSpec, o: RenderOpts): string;
4
+ export declare function renderAreaMulti(spec: MultiSpec, o: RenderOpts): string;
5
+ export declare function renderAreaByMode(input: {
6
+ multi: boolean;
7
+ spec: ChartSpec | MultiSpec;
8
+ }, o: RenderOpts): string;