dsh-artifact-studio 0.9.0 → 0.13.2

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.
@@ -3,10 +3,13 @@ import fs from 'node:fs/promises';
3
3
  import { SceneGraph } from '@open-pencil/scene-graph';
4
4
  import { designJSXRenderer } from '@open-pencil/core/design-jsx';
5
5
  import { fontManager } from '@open-pencil/core/text';
6
+ import { createLinter } from '@open-pencil/core/lint';
6
7
  import { computeContentBounds, headlessRenderNodes } from '@open-pencil/core/io/formats/raster';
7
8
  import { renderNodesToSVG } from '@open-pencil/core/io/formats/svg';
8
- import { exportFigFile } from '@open-pencil/core/io/formats/fig';
9
+ import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig';
10
+ import { selectionToJSX } from '@open-pencil/design-jsx';
9
11
  import { bundledIconProvider } from '../../icon-set.js';
12
+ import { buildPageModel } from './page-model.js';
10
13
  /** Fonts that ship with the package; any other family is substituted. */
11
14
  const BUNDLED_FONTS = new Set(['Inter', 'Noto Naskh Arabic', 'Roboto']);
12
15
  /** The Roboto faces the package ships, by style. */
@@ -70,6 +73,27 @@ function descendants(graph, page) {
70
73
  visit(id);
71
74
  return out;
72
75
  }
76
+ /**
77
+ * The highest design-lint severities, as the summary's warnings.
78
+ * Info rules stay out: token adoption and structure hygiene are suggestions.
79
+ * min-text-size stays out too: mockups legitimately carry small labels as content.
80
+ * A lint failure must never block saving, so any throw returns nothing.
81
+ * @param graph the compiled graph.
82
+ * @returns the warnings.
83
+ */
84
+ function lintWarnings(graph) {
85
+ const LIMIT = 12;
86
+ try {
87
+ const result = createLinter({ preset: 'recommended' }).lintGraph(graph);
88
+ const relevant = result.messages.filter((message) => (message.severity === 'error' || message.severity === 'warning') && message.ruleId !== 'min-text-size');
89
+ const lines = relevant.slice(0, LIMIT).map((message) => `Design issue, ${message.nodePath.join(' / ')}: ${message.message}`);
90
+ const rest = relevant.length - lines.length;
91
+ return rest > 0 ? [...lines, `And ${rest} more design issues.`] : lines;
92
+ }
93
+ catch {
94
+ return [];
95
+ }
96
+ }
73
97
  /**
74
98
  * Count the design's nodes, record its types and fonts, and warn about
75
99
  * families the engine cannot load.
@@ -91,7 +115,43 @@ function summarize(graph, page) {
91
115
  const warnings = sorted
92
116
  .filter((family) => !BUNDLED_FONTS.has(family))
93
117
  .map((family) => `Font "${family}" is not bundled. The preview substitutes a default face.`);
94
- return { pages: graph.getPages().length, nodes: nodes.length, types, fonts: sorted, warnings };
118
+ return { pages: graph.getPages().length, nodes: nodes.length, types, fonts: sorted, warnings: [...warnings, ...lintWarnings(graph)] };
119
+ }
120
+ /**
121
+ * Convert a .fig file into stored Design JSX: the first page that holds elements,
122
+ * serialized like the panel's own save path. Non-empty pages after it are named
123
+ * in warnings, because the stored mockup keeps one page.
124
+ * @param bytes64 the base64 file bytes the host read.
125
+ * @returns the response.
126
+ */
127
+ async function handleImport(bytes64) {
128
+ const bytes = Buffer.from(bytes64, 'base64');
129
+ if (bytes.byteLength === 0) {
130
+ return { ok: false, code: 'artifact/bad-request', message: 'The import received no .fig bytes.' };
131
+ }
132
+ const view = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
133
+ let graph;
134
+ try {
135
+ graph = await parseFigFile(view, { populate: 'all' });
136
+ }
137
+ catch (error) {
138
+ return { ok: false, code: 'artifact/bad-request', message: 'The file is not a readable .fig document: ' + messageOf(error) };
139
+ }
140
+ const pages = graph.getPages();
141
+ const page = pages.find((candidate) => candidate.childIds.length > 0);
142
+ if (page === undefined) {
143
+ return { ok: false, code: 'artifact/bad-request', message: 'The file has no page with elements. Draw the mockup in Figma before exporting it.' };
144
+ }
145
+ const source = selectionToJSX(page.childIds, graph);
146
+ if (source === null) {
147
+ return { ok: false, code: 'artifact/design-render-failed', message: 'The design produced no source.' };
148
+ }
149
+ const info = summarize(graph, page);
150
+ const skipped = pages.filter((candidate) => candidate !== page && candidate.childIds.length > 0).length;
151
+ if (skipped > 0) {
152
+ info.warnings.push(`The file holds ${skipped} more page${skipped === 1 ? '' : 's'}; only "${page.name}" was imported.`);
153
+ }
154
+ return { ok: true, info, source };
95
155
  }
96
156
  /**
97
157
  * Read a PNG's pixel size from its IHDR chunk.
@@ -124,11 +184,13 @@ async function renderPng(compiled, maxSide) {
124
184
  }
125
185
  /**
126
186
  * Answer one request.
127
- * @param source the Design JSX source.
187
+ * @param source the Design JSX source, or the empty string on an import.
128
188
  * @param request the request.
129
189
  * @returns the response.
130
190
  */
131
191
  async function handle(source, request) {
192
+ if (request.action === 'import-fig')
193
+ return handleImport(request.bytes ?? '');
132
194
  let compiled;
133
195
  try {
134
196
  compiled = await compile(source);
@@ -172,6 +234,10 @@ async function handle(source, request) {
172
234
  return { ok: false, code: 'artifact/design-render-failed', message: 'The design produced no SVG.' };
173
235
  return { ok: true, info, mediaType: 'image/svg+xml', data: Buffer.from(svg, 'utf8').toString('base64') };
174
236
  }
237
+ if (request.format === 'html-svg') {
238
+ const model = await buildPageModel(compiled.graph, compiled.page);
239
+ return { ok: true, info, mediaType: 'application/json', data: Buffer.from(JSON.stringify(model), 'utf8').toString('base64') };
240
+ }
175
241
  const png = await renderPng(compiled, 0);
176
242
  if (png === null)
177
243
  return { ok: false, code: 'artifact/design-render-failed', message: 'The design produced no image.' };
@@ -198,7 +264,7 @@ async function readRequest() {
198
264
  throw new Error('The design request has no nonce.');
199
265
  if (typeof fields.source !== 'string')
200
266
  throw new Error('The design request has no source.');
201
- if (fields.action !== 'inspect' && fields.action !== 'preview' && fields.action !== 'export') {
267
+ if (fields.action !== 'inspect' && fields.action !== 'preview' && fields.action !== 'export' && fields.action !== 'import-fig') {
202
268
  throw new Error('The design request has an unknown action.');
203
269
  }
204
270
  return {
@@ -206,7 +272,8 @@ async function readRequest() {
206
272
  action: fields.action,
207
273
  source: fields.source,
208
274
  ...(typeof fields.maxSide === 'number' ? { maxSide: fields.maxSide } : {}),
209
- ...(fields.format === 'png' || fields.format === 'svg' || fields.format === 'fig' ? { format: fields.format } : {}),
275
+ ...(fields.format === 'png' || fields.format === 'svg' || fields.format === 'fig' || fields.format === 'html-svg' ? { format: fields.format } : {}),
276
+ ...(typeof fields.bytes === 'string' ? { bytes: fields.bytes } : {}),
210
277
  };
211
278
  }
212
279
  await loadExtraFonts();
@@ -0,0 +1,169 @@
1
+ import { getWorldMatrix } from '@open-pencil/scene-graph';
2
+ import { SceneGraph } from '@open-pencil/scene-graph';
3
+ import { headlessRenderNodes } from '@open-pencil/core/io/formats/raster';
4
+ import { renderNodesToSVG } from '@open-pencil/core/io/formats/svg';
5
+ /** The default family a text node takes when the design names none. */
6
+ const DEFAULT_FAMILY = 'Inter';
7
+ /** How small the layout raster is; it exists only to fix text heights. */
8
+ const LAYOUT_SCALE = 0.05;
9
+ /**
10
+ * Read the first visible solid fill of a node or a run style.
11
+ * @param fills the fills.
12
+ * @returns the colour and its alpha.
13
+ */
14
+ function paintOf(fills) {
15
+ const fill = fills?.find((entry) => entry.visible !== false && entry.type === 'SOLID');
16
+ if (fill === undefined)
17
+ return { color: '#000000', alpha: 1 };
18
+ const channel = (value) => Math.round(Math.max(0, Math.min(1, value)) * 255).toString(16).padStart(2, '0');
19
+ const alpha = (fill.opacity ?? 1) * (fill.color.a ?? 1);
20
+ return { color: '#' + channel(fill.color.r) + channel(fill.color.g) + channel(fill.color.b), alpha };
21
+ }
22
+ /**
23
+ * The box of the nearest ancestor that clips its content.
24
+ * @param graph the scene graph.
25
+ * @param node the text node.
26
+ * @param pageId the page the text sits on.
27
+ * @returns the clip box, or null.
28
+ */
29
+ function clipOf(graph, node, pageId) {
30
+ let parentId = node.parentId;
31
+ let guard = 0;
32
+ while (parentId !== null && parentId !== pageId && guard < 200) {
33
+ guard += 1;
34
+ const parent = graph.getNode(parentId);
35
+ if (parent === undefined)
36
+ return null;
37
+ if (parent.clipsContent) {
38
+ const bounds = graph.getAbsoluteBounds(parent.id);
39
+ return { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height };
40
+ }
41
+ parentId = parent.parentId;
42
+ }
43
+ return null;
44
+ }
45
+ /**
46
+ * The text split into styled runs. A run that leaves a field out keeps the node's value.
47
+ * @param node the text node.
48
+ * @param base the node's own style.
49
+ * @returns the runs, or an empty list when the text is one style.
50
+ */
51
+ function runsOf(node, base) {
52
+ if (node.styleRuns.length === 0)
53
+ return [];
54
+ const text = node.text;
55
+ const runs = [];
56
+ let cursor = 0;
57
+ const ordered = [...node.styleRuns].sort((left, right) => left.start - right.start);
58
+ for (const run of ordered) {
59
+ if (run.start > cursor)
60
+ runs.push({ ...base, text: text.slice(cursor, run.start) });
61
+ const style = run.style;
62
+ const paint = paintOf(style.fills);
63
+ runs.push({
64
+ text: text.slice(run.start, run.start + run.length),
65
+ size: style.fontSize ?? base.size,
66
+ weight: style.fontWeight ?? base.weight,
67
+ italic: style.italic ?? base.italic,
68
+ letterSpacing: style.letterSpacing ?? base.letterSpacing,
69
+ color: style.fills === undefined ? base.color : paint.color,
70
+ alpha: style.fills === undefined ? base.alpha : paint.alpha,
71
+ });
72
+ cursor = run.start + run.length;
73
+ }
74
+ if (cursor < text.length)
75
+ runs.push({ ...base, text: text.slice(cursor) });
76
+ return runs.filter((run) => run.text !== '');
77
+ }
78
+ /**
79
+ * Every node below the page, depth first.
80
+ * @param graph the graph.
81
+ * @param page the page node.
82
+ * @returns the nodes.
83
+ */
84
+ function descendants(graph, page) {
85
+ const out = [];
86
+ const visit = (id) => {
87
+ const node = graph.getNode(id);
88
+ if (node === undefined)
89
+ return;
90
+ out.push(node);
91
+ for (const child of node.childIds)
92
+ visit(child);
93
+ };
94
+ for (const id of page.childIds)
95
+ visit(id);
96
+ return out;
97
+ }
98
+ /**
99
+ * The page size from the SVG root the engine wrote.
100
+ * @param svg the shapes SVG.
101
+ * @returns the width and height.
102
+ */
103
+ function sizeOfSvg(svg) {
104
+ const match = /<svg[^>]*\swidth="([0-9.]+)"[^>]*\sheight="([0-9.]+)"/.exec(svg);
105
+ if (match === null)
106
+ throw new Error('The rendered SVG has no size.');
107
+ return { width: Number(match[1]), height: Number(match[2]) };
108
+ }
109
+ /**
110
+ * Build the page model: the engine's shapes plus one record per text node, after
111
+ * the layout the panel shows. The raster pass exists only to fix text heights with
112
+ * the engine's own measurer; its pixels are unused.
113
+ * @param graph the compiled scene graph.
114
+ * @param page the page node.
115
+ * @returns the model.
116
+ */
117
+ export async function buildPageModel(graph, page) {
118
+ await headlessRenderNodes(graph, page.id, page.childIds, { scale: LAYOUT_SCALE, format: 'PNG', trimTransparent: true });
119
+ const svg = renderNodesToSVG(graph, page.id, page.childIds, { xmlDeclaration: false });
120
+ if (svg === null)
121
+ throw new Error('The design produced no SVG.');
122
+ const shapes = svg.replace(/<text[^>]*>[\s\S]*?<\/text>/g, '');
123
+ const size = sizeOfSvg(svg);
124
+ const families = new Set();
125
+ const texts = [];
126
+ for (const node of descendants(graph, page)) {
127
+ if (node.type !== 'TEXT')
128
+ continue;
129
+ const text = node.text;
130
+ if (text.trim() === '')
131
+ continue;
132
+ const world = getWorldMatrix(node, graph);
133
+ const at = (index) => world[index] ?? 0;
134
+ const matrix = { a: at(0), b: at(3), c: at(1), d: at(4), e: at(2), f: at(5) };
135
+ const family = (node.fontFamily || DEFAULT_FAMILY).trim();
136
+ const paint = paintOf(node.fills);
137
+ const base = {
138
+ text,
139
+ size: node.fontSize || 14,
140
+ weight: node.fontWeight || 400,
141
+ italic: node.italic,
142
+ letterSpacing: node.letterSpacing || 0,
143
+ color: paint.color,
144
+ alpha: paint.alpha,
145
+ };
146
+ families.add(family);
147
+ texts.push({
148
+ width: node.width,
149
+ height: node.height,
150
+ matrix,
151
+ text,
152
+ family,
153
+ size: base.size,
154
+ weight: base.weight,
155
+ italic: base.italic,
156
+ letterSpacing: base.letterSpacing,
157
+ lineHeight: (node.lineHeight ?? 0) > 0 ? node.lineHeight : null,
158
+ wrap: node.textAutoResize !== 'WIDTH_AND_HEIGHT',
159
+ textCase: node.textCase,
160
+ align: node.textAlignHorizontal,
161
+ verticalAlign: node.textAlignVertical,
162
+ color: base.color,
163
+ alpha: base.alpha,
164
+ runs: runsOf(node, base),
165
+ clip: clipOf(graph, node, page.id),
166
+ });
167
+ }
168
+ return { width: size.width, height: size.height, svg: shapes, texts, families: [...families] };
169
+ }
@@ -203,6 +203,73 @@ function checkColor(raw, at) {
203
203
  return '#' + color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
204
204
  return color;
205
205
  }
206
+ /**
207
+ * Read a normalised hex color as RGB channels.
208
+ * @param value a hex color such as #1f2933.
209
+ * @returns the channels, or undefined for an unreadable value.
210
+ */
211
+ function hexChannels(value) {
212
+ const text = value.trim().toLowerCase();
213
+ const match = /^#?([0-9a-f]{6})$/.exec(text);
214
+ if (match === null)
215
+ return undefined;
216
+ const hex = match[1] ?? '';
217
+ return [Number.parseInt(hex.slice(0, 2), 16), Number.parseInt(hex.slice(2, 4), 16), Number.parseInt(hex.slice(4, 6), 16)];
218
+ }
219
+ /**
220
+ * Relative luminance in sRGB, as used by WCAG contrast.
221
+ * @param channels the RGB channels.
222
+ * @returns the luminance from 0 to 1.
223
+ */
224
+ function luminance(channels) {
225
+ const parts = channels.map((channel) => {
226
+ const value = channel / 255;
227
+ return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
228
+ });
229
+ return 0.2126 * (parts[0] ?? 0) + 0.7152 * (parts[1] ?? 0) + 0.0722 * (parts[2] ?? 0);
230
+ }
231
+ /**
232
+ * Contrast between two colors, from 1 to 21.
233
+ * @param foreground the text color.
234
+ * @param background the fill color.
235
+ * @returns the WCAG contrast ratio.
236
+ */
237
+ export function contrastRatio(foreground, background) {
238
+ const front = hexChannels(foreground);
239
+ const back = hexChannels(background);
240
+ if (front === undefined || back === undefined)
241
+ return 1;
242
+ const bright = Math.max(luminance(front), luminance(back));
243
+ const dark = Math.min(luminance(front), luminance(back));
244
+ return (bright + 0.05) / (dark + 0.05);
245
+ }
246
+ /**
247
+ * Pick a readable default text color for a cell fill. The panel and XLSX use
248
+ * this when a style sets a background but leaves the text color implicit.
249
+ * @param background the cell fill.
250
+ * @returns the darker ink or white, whichever contrasts more.
251
+ */
252
+ export function readableTextColor(background) {
253
+ const dark = '#1f2933';
254
+ const light = '#ffffff';
255
+ return contrastRatio(dark, background) >= contrastRatio(light, background) ? dark : light;
256
+ }
257
+ /**
258
+ * The text color a renderer should use for one style. An explicit color wins
259
+ * only when it is readable on the fill; a missing or low-contrast color falls
260
+ * back to the automatic readable color. Stored content is never changed here.
261
+ * @param style the cell style.
262
+ * @returns the text color, or undefined when the theme default should apply.
263
+ */
264
+ export function effectiveTextColor(style) {
265
+ if (style === undefined)
266
+ return undefined;
267
+ if (style.background === undefined)
268
+ return style.color;
269
+ if (style.color !== undefined && contrastRatio(style.color, style.background) >= 4.5)
270
+ return style.color;
271
+ return readableTextColor(style.background);
272
+ }
206
273
  function checkStyle(raw, at) {
207
274
  if (!isFields(raw))
208
275
  throw new SheetError(at + ' must be an object.');
@@ -3,7 +3,7 @@
3
3
  * export shows, a CSV rendering, a selection quote for an agent request, and
4
4
  * the advisory formula diagnostics a write returns.
5
5
  */
6
- import { SHEET_LIMITS, formatCellRef, formatRangeRef, parseRangeRef, sheetOf, usedBounds } from './model.js';
6
+ import { SHEET_LIMITS, contrastRatio, formatCellRef, formatRangeRef, parseRangeRef, sheetOf, usedBounds } from './model.js';
7
7
  import { evaluateWorkbook } from './formula.js';
8
8
  /**
9
9
  * The used bounds of a sheet as one-based rows and columns.
@@ -131,7 +131,19 @@ export function selectionQuote(workbook, evaluated, sheetName, rangeRef) {
131
131
  * @returns one message per problem, each starting with its code.
132
132
  */
133
133
  export function checkSheetWorkbook(workbook) {
134
- return evaluateWorkbook(workbook).warnings;
134
+ const warnings = evaluateWorkbook(workbook).warnings;
135
+ for (const sheet of workbook.sheets) {
136
+ for (const [ref, cell] of Object.entries(sheet.cells)) {
137
+ const style = cell.style;
138
+ if (style?.background === undefined || style.color === undefined)
139
+ continue;
140
+ const ratio = contrastRatio(style.color, style.background);
141
+ if (ratio < 4.5) {
142
+ warnings.push('low-contrast: ' + sheet.name + '!' + ref + ' text ' + style.color + ' on ' + style.background + ' has a contrast ratio of ' + ratio.toFixed(1) + ':1. Use a darker or lighter text color.');
143
+ }
144
+ }
145
+ }
146
+ return warnings;
135
147
  }
136
148
  /**
137
149
  * Evaluate a workbook once for an export or a print copy.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-artifact-studio",
3
- "version": "0.9.0",
3
+ "version": "0.13.2",
4
4
  "type": "module",
5
5
  "description": "Local-first artifacts for DeepSeek Harness: the agent creates pages, documents, spreadsheets, and mockups as versioned files, and you open, edit, restore, and export them beside the chat.",
6
6
  "keywords": [
@@ -62,11 +62,16 @@
62
62
  "scripts": {
63
63
  "build": "rm -rf dist && tsc -p src/host/tsconfig.json && node scripts/build.mjs",
64
64
  "typecheck": "tsc -p src/host/tsconfig.json --noEmit && tsc -p src/client/tsconfig.json",
65
+ "lint": "eslint .",
66
+ "check": "npm run typecheck && npm run lint && npm test",
65
67
  "test": "npm run build && node --test tests/*.test.mjs",
68
+ "webcheck": "node scripts/dsh-web-check.mjs",
69
+ "knip": "knip --production",
66
70
  "prepack": "node scripts/check-icon.mjs"
67
71
  },
68
72
  "dependencies": {
69
73
  "@open-pencil/core": "0.16.0",
74
+ "@open-pencil/design-jsx": "0.16.0",
70
75
  "@open-pencil/scene-graph": "0.16.0",
71
76
  "docx": "9.15.3",
72
77
  "fast-formula-parser": "^1.0.19",
@@ -75,7 +80,6 @@
75
80
  },
76
81
  "devDependencies": {
77
82
  "@iconify-json/mdi": "1.2.3",
78
- "@open-pencil/design-jsx": "0.16.0",
79
83
  "@open-pencil/vue": "0.16.0",
80
84
  "@tiptap/core": "3.33.1",
81
85
  "@tiptap/extension-list": "^3.33.1",
@@ -88,11 +92,14 @@
88
92
  "@types/react-dom": "^18.3.7",
89
93
  "canvaskit-wasm": "0.41.1",
90
94
  "esbuild": "^0.25.0",
95
+ "eslint": "^9.39.5",
91
96
  "jsdom": "^25.0.1",
97
+ "knip": "^6.47.0",
92
98
  "react": "18.3.1",
93
99
  "react-dom": "18.3.1",
94
100
  "roboto-fontface": "0.10.0",
95
101
  "typescript": "^5.9.3",
102
+ "typescript-eslint": "^8.73.0",
96
103
  "vue": "3.5.41"
97
104
  }
98
105
  }