dsh-artifact-studio 0.3.1 → 0.7.1
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/README.md +6 -4
- package/THIRD_PARTY_NOTICES.md +296 -0
- package/assets/canvas.engine.js +6601 -0
- package/assets/canvaskit.wasm +0 -0
- package/assets/fonts/Inter-Bold.ttf +0 -0
- package/assets/fonts/Inter-ExtraBold.ttf +0 -0
- package/assets/fonts/Inter-Medium.ttf +0 -0
- package/assets/fonts/Inter-Regular.ttf +0 -0
- package/assets/fonts/Inter-SemiBold.ttf +0 -0
- package/assets/fonts/NotoNaskhArabic-Regular.ttf +0 -0
- package/assets/fonts/Roboto-Bold.woff2 +0 -0
- package/assets/fonts/Roboto-Medium.woff2 +0 -0
- package/assets/fonts/Roboto-Regular.woff2 +0 -0
- package/assets/icons.json +42204 -0
- package/client.canvas.js +11 -0
- package/client.js +154 -17
- package/dist/contract.js +22 -2
- package/dist/host/index.js +2 -0
- package/dist/host/lib/assets.js +88 -0
- package/dist/host/lib/design-render.js +254 -0
- package/dist/host/lib/editor-leases.js +63 -0
- package/dist/host/lib/export.js +21 -3
- package/dist/host/lib/fsutil.js +4 -1
- package/dist/host/lib/rpc.js +14 -0
- package/dist/host/lib/service.js +291 -11
- package/dist/host/lib/skill.js +32 -3
- package/dist/host/lib/store.js +57 -0
- package/dist/host/lib/tools.js +63 -18
- package/dist/host/worker/design-worker.js +215 -0
- package/dist/host/worker/protocol.js +1 -0
- package/dist/icon-set.js +81 -0
- package/package.json +12 -3
package/dist/contract.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Wire shapes shared by the host route, the tools, and the browser client. */
|
|
2
|
-
export const ARTIFACT_TYPES = ['page', 'doc'];
|
|
2
|
+
export const ARTIFACT_TYPES = ['page', 'doc', 'design'];
|
|
3
3
|
/**
|
|
4
4
|
* Tell an artifact type from an unknown string without widening to string[].
|
|
5
5
|
* @param value a candidate type.
|
|
@@ -9,21 +9,41 @@ export function isArtifactType(value) {
|
|
|
9
9
|
return ARTIFACT_TYPES.some((type) => type === value);
|
|
10
10
|
}
|
|
11
11
|
export const SCOPES = ['workspace', 'library'];
|
|
12
|
-
export const EXPORT_FORMATS = ['html', 'md', 'docx'];
|
|
12
|
+
export const EXPORT_FORMATS = ['html', 'md', 'docx', 'png', 'svg', 'fig'];
|
|
13
13
|
/** Which exporters each type supports. */
|
|
14
14
|
export const FORMATS_BY_TYPE = {
|
|
15
15
|
page: ['html'],
|
|
16
16
|
doc: ['md', 'docx', 'html'],
|
|
17
|
+
design: ['png', 'svg', 'fig'],
|
|
17
18
|
};
|
|
18
19
|
/** Content file name inside `content/`, by type. */
|
|
19
20
|
export const CONTENT_FILE = {
|
|
20
21
|
page: 'index.html',
|
|
21
22
|
doc: 'document.md',
|
|
23
|
+
design: 'design.jsx',
|
|
22
24
|
};
|
|
23
25
|
export const ID_PATTERN = /^art_(ws|lib)_[a-z0-9]{10,32}$/;
|
|
24
26
|
export const MAX_TITLE = 120;
|
|
25
27
|
export const MAX_LIST_LIMIT = 50;
|
|
26
28
|
export const COLOR_ROLES = ['primary', 'accent', 'surface', 'text', 'muted'];
|
|
29
|
+
/**
|
|
30
|
+
* Narrow a design summary read from the wire or a cache file.
|
|
31
|
+
* @param value the value.
|
|
32
|
+
* @returns whether it is a design summary.
|
|
33
|
+
*/
|
|
34
|
+
export function isDesignInfo(value) {
|
|
35
|
+
if (value === null || typeof value !== 'object')
|
|
36
|
+
return false;
|
|
37
|
+
const record = { ...value };
|
|
38
|
+
return (typeof record.pages === 'number' &&
|
|
39
|
+
typeof record.nodes === 'number' &&
|
|
40
|
+
record.types !== null &&
|
|
41
|
+
typeof record.types === 'object' &&
|
|
42
|
+
Array.isArray(record.fonts) &&
|
|
43
|
+
record.fonts.every((font) => typeof font === 'string') &&
|
|
44
|
+
Array.isArray(record.warnings) &&
|
|
45
|
+
record.warnings.every((warning) => typeof warning === 'string'));
|
|
46
|
+
}
|
|
27
47
|
/**
|
|
28
48
|
* Narrow a version source read from disk or the wire.
|
|
29
49
|
* @param value the parsed value.
|
package/dist/host/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { registerCanvasAssetsRoute } from './lib/assets.js';
|
|
1
2
|
import { registerArtifactsRoute } from './lib/http.js';
|
|
2
3
|
import { createHandler } from './lib/rpc.js';
|
|
3
4
|
import { createService } from './lib/setup.js';
|
|
@@ -11,4 +12,5 @@ export const inject = ['workspaceRegistry', 'connection', 'webServer'];
|
|
|
11
12
|
export function apply(ctx) {
|
|
12
13
|
const handler = createHandler(createService(ctx.workspaceRegistry));
|
|
13
14
|
ctx.effect(() => registerArtifactsRoute(ctx, handler), 'dsh-artifact-studio: authenticated artifact channel');
|
|
15
|
+
ctx.effect(() => registerCanvasAssetsRoute(ctx), 'dsh-artifact-studio: engine assets');
|
|
14
16
|
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
/** The URL prefix the canvas fetches engine files from. */
|
|
5
|
+
export const ASSET_PREFIX = '/artifacts-canvas';
|
|
6
|
+
/** The engine files the route serves, relative to the package's assets directory, with their media types. */
|
|
7
|
+
export const ASSET_FILES = new Map([
|
|
8
|
+
['canvas.engine.js', 'text/javascript'],
|
|
9
|
+
['icons.json', 'application/json'],
|
|
10
|
+
['canvaskit.wasm', 'application/wasm'],
|
|
11
|
+
['fonts/Inter-Regular.ttf', 'font/ttf'],
|
|
12
|
+
['fonts/Inter-Medium.ttf', 'font/ttf'],
|
|
13
|
+
['fonts/Inter-SemiBold.ttf', 'font/ttf'],
|
|
14
|
+
['fonts/Inter-Bold.ttf', 'font/ttf'],
|
|
15
|
+
['fonts/Inter-ExtraBold.ttf', 'font/ttf'],
|
|
16
|
+
['fonts/NotoNaskhArabic-Regular.ttf', 'font/ttf'],
|
|
17
|
+
['fonts/Roboto-Regular.woff2', 'font/woff2'],
|
|
18
|
+
['fonts/Roboto-Medium.woff2', 'font/woff2'],
|
|
19
|
+
['fonts/Roboto-Bold.woff2', 'font/woff2'],
|
|
20
|
+
]);
|
|
21
|
+
/** Where the build copies the engine files, beside the compiled host. */
|
|
22
|
+
const ASSET_ROOT = fileURLToPath(new URL('../../../assets/', import.meta.url));
|
|
23
|
+
/**
|
|
24
|
+
* Answer one request for an engine file. The name must match the fixed list;
|
|
25
|
+
* nothing from the request reaches the filesystem path.
|
|
26
|
+
* @param root the assets directory.
|
|
27
|
+
* @returns the route handler.
|
|
28
|
+
*/
|
|
29
|
+
export function createCanvasAssetHandler(root = ASSET_ROOT) {
|
|
30
|
+
return async (request, response) => {
|
|
31
|
+
const method = request.method ?? 'GET';
|
|
32
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
33
|
+
response.writeHead(405, { allow: 'GET, HEAD' });
|
|
34
|
+
response.end();
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
let name;
|
|
38
|
+
try {
|
|
39
|
+
const url = new URL(request.url ?? '/', 'http://localhost');
|
|
40
|
+
if (!url.pathname.startsWith(ASSET_PREFIX + '/')) {
|
|
41
|
+
missing(response);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
name = decodeURIComponent(url.pathname.slice(ASSET_PREFIX.length + 1));
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
missing(response);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const mediaType = ASSET_FILES.get(name);
|
|
51
|
+
if (mediaType === undefined) {
|
|
52
|
+
missing(response);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
let body;
|
|
56
|
+
try {
|
|
57
|
+
body = await fs.readFile(path.join(root, name));
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
missing(response);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
response.writeHead(200, {
|
|
64
|
+
'content-type': mediaType,
|
|
65
|
+
'content-length': body.byteLength,
|
|
66
|
+
'cache-control': 'public, max-age=31536000, immutable',
|
|
67
|
+
'x-content-type-options': 'nosniff',
|
|
68
|
+
});
|
|
69
|
+
response.end(method === 'HEAD' ? undefined : body);
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Register the engine asset route.
|
|
74
|
+
* @param ctx the host context.
|
|
75
|
+
* @returns the route disposer.
|
|
76
|
+
*/
|
|
77
|
+
export function registerCanvasAssetsRoute(ctx) {
|
|
78
|
+
const route = { kind: 'prefix', path: ASSET_PREFIX, handler: createCanvasAssetHandler() };
|
|
79
|
+
return ctx.webServer.register(route);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Refuse an unknown file.
|
|
83
|
+
* @param response the response.
|
|
84
|
+
*/
|
|
85
|
+
function missing(response) {
|
|
86
|
+
response.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' });
|
|
87
|
+
response.end('not found');
|
|
88
|
+
}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { ArtifactError } from './errors.js';
|
|
7
|
+
/** How long one render may take before the child is killed. */
|
|
8
|
+
const TIMEOUT_MS = 20_000;
|
|
9
|
+
/** Stdout above this size means something is wrong with the child. */
|
|
10
|
+
const MAX_STDOUT = 64 * 1024 * 1024;
|
|
11
|
+
/** Stderr kept for a failure message. */
|
|
12
|
+
const MAX_STDERR = 8 * 1024;
|
|
13
|
+
/** Workers that may run at once; each peaks near 250 MB. */
|
|
14
|
+
const MAX_CONCURRENT = 2;
|
|
15
|
+
/** Longest side of a preview image. */
|
|
16
|
+
export const PREVIEW_MAX_SIDE = 1600;
|
|
17
|
+
const WORKER = fileURLToPath(new URL('../worker/design-worker.js', import.meta.url));
|
|
18
|
+
const PLUGIN_ROOT = fileURLToPath(new URL('../../../', import.meta.url));
|
|
19
|
+
const resolveFrom = createRequire(import.meta.url);
|
|
20
|
+
const NODE_MAJOR = Number.parseInt(process.versions.node.split('.')[0] ?? '0', 10);
|
|
21
|
+
const PERMISSION_FLAG = NODE_MAJOR >= 23 ? '--permission' : undefined;
|
|
22
|
+
/**
|
|
23
|
+
* The nearest ancestor that is a node_modules directory, which is the tree the
|
|
24
|
+
* engine and its dependencies were installed into.
|
|
25
|
+
* @param file a file inside the tree.
|
|
26
|
+
* @returns the directory, or the file's own directory when there is none.
|
|
27
|
+
*/
|
|
28
|
+
function nearestNodeModules(file) {
|
|
29
|
+
let dir = path.dirname(file);
|
|
30
|
+
for (;;) {
|
|
31
|
+
if (path.basename(dir) === 'node_modules')
|
|
32
|
+
return dir;
|
|
33
|
+
const parent = path.dirname(dir);
|
|
34
|
+
if (parent === dir)
|
|
35
|
+
return path.dirname(file);
|
|
36
|
+
dir = parent;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Every directory the worker may read: its own package and the installed
|
|
41
|
+
* engine. Nothing else, so a design cannot read a workspace or a home file.
|
|
42
|
+
*/
|
|
43
|
+
function readRoots() {
|
|
44
|
+
const roots = new Set([PLUGIN_ROOT]);
|
|
45
|
+
try {
|
|
46
|
+
roots.add(nearestNodeModules(resolveFrom.resolve('@open-pencil/core/package.json')));
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
// Left to the worker to resolve; a missing engine fails there with a clear message.
|
|
50
|
+
}
|
|
51
|
+
return [...roots];
|
|
52
|
+
}
|
|
53
|
+
const READ_ROOTS = readRoots();
|
|
54
|
+
/**
|
|
55
|
+
* The child environment. Under Electron the binary only runs Node with this
|
|
56
|
+
* flag, and Node options from the host must not leak into the worker.
|
|
57
|
+
* @returns the environment.
|
|
58
|
+
*/
|
|
59
|
+
function workerEnv() {
|
|
60
|
+
const env = { ...process.env };
|
|
61
|
+
if (process.versions.electron !== undefined)
|
|
62
|
+
env['ELECTRON_RUN_AS_NODE'] = '1';
|
|
63
|
+
delete env['NODE_OPTIONS'];
|
|
64
|
+
return env;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The command line for one worker run.
|
|
68
|
+
* @returns the arguments, before the worker script.
|
|
69
|
+
*/
|
|
70
|
+
function workerArgs() {
|
|
71
|
+
if (PERMISSION_FLAG === undefined) {
|
|
72
|
+
throw new ArtifactError('artifact/design-unavailable', 'Design rendering needs Node 23 or newer for its sandbox. Upgrade the Harness runtime.');
|
|
73
|
+
}
|
|
74
|
+
return [PERMISSION_FLAG, ...READ_ROOTS.map((root) => `--allow-fs-read=${root}`), WORKER];
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Tell a design summary from an unknown value.
|
|
78
|
+
* @param value the value.
|
|
79
|
+
* @returns whether it is a summary.
|
|
80
|
+
*/
|
|
81
|
+
function isInfo(value) {
|
|
82
|
+
if (value === null || typeof value !== 'object')
|
|
83
|
+
return false;
|
|
84
|
+
const fields = { ...value };
|
|
85
|
+
return (typeof fields.pages === 'number' &&
|
|
86
|
+
typeof fields.nodes === 'number' &&
|
|
87
|
+
fields.types !== null &&
|
|
88
|
+
typeof fields.types === 'object' &&
|
|
89
|
+
Array.isArray(fields.fonts) &&
|
|
90
|
+
Array.isArray(fields.warnings));
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Tell a worker response from an unknown value.
|
|
94
|
+
* @param value the value.
|
|
95
|
+
* @returns whether it is a response.
|
|
96
|
+
*/
|
|
97
|
+
function isResponse(value) {
|
|
98
|
+
if (value === null || typeof value !== 'object')
|
|
99
|
+
return false;
|
|
100
|
+
const fields = { ...value };
|
|
101
|
+
if (fields.ok === false)
|
|
102
|
+
return typeof fields.code === 'string' && typeof fields.message === 'string';
|
|
103
|
+
return fields.ok === true && isInfo(fields.info);
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Runs Design JSX in a separate, sandboxed Node process. Every call compiles
|
|
107
|
+
* and renders from scratch; the caller caches what it needs.
|
|
108
|
+
*/
|
|
109
|
+
export class DesignRenderer {
|
|
110
|
+
active = 0;
|
|
111
|
+
waiting = [];
|
|
112
|
+
/**
|
|
113
|
+
* Compile and summarize a source without rasterizing it.
|
|
114
|
+
* @param source the Design JSX source.
|
|
115
|
+
* @returns the summary.
|
|
116
|
+
*/
|
|
117
|
+
async inspect(source) {
|
|
118
|
+
return (await this.request(source, { action: 'inspect' })).info;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Compile and rasterize a source.
|
|
122
|
+
* @param source the Design JSX source.
|
|
123
|
+
* @param maxSide the longest side in pixels; zero keeps the design's own size.
|
|
124
|
+
* @returns the image and summary.
|
|
125
|
+
*/
|
|
126
|
+
async preview(source, maxSide) {
|
|
127
|
+
const response = await this.request(source, { action: 'preview', maxSide });
|
|
128
|
+
if (typeof response.data !== 'string' || typeof response.width !== 'number' || typeof response.height !== 'number') {
|
|
129
|
+
throw new ArtifactError('artifact/design-render-failed', 'The design renderer returned no image.');
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
bytes: Buffer.from(response.data, 'base64'),
|
|
133
|
+
width: response.width,
|
|
134
|
+
height: response.height,
|
|
135
|
+
info: response.info,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Compile and export a source.
|
|
140
|
+
* @param source the Design JSX source.
|
|
141
|
+
* @param format the output format.
|
|
142
|
+
* @returns the file bytes and media type.
|
|
143
|
+
*/
|
|
144
|
+
async exportContent(source, format) {
|
|
145
|
+
const response = await this.request(source, { action: 'export', format });
|
|
146
|
+
if (typeof response.data !== 'string' || typeof response.mediaType !== 'string') {
|
|
147
|
+
throw new ArtifactError('artifact/design-render-failed', 'The design renderer returned no file.');
|
|
148
|
+
}
|
|
149
|
+
return { bytes: Buffer.from(response.data, 'base64'), mediaType: response.mediaType };
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Run a task with at most two children alive.
|
|
153
|
+
* @param task the work.
|
|
154
|
+
* @returns the task result.
|
|
155
|
+
*/
|
|
156
|
+
async run(task) {
|
|
157
|
+
if (this.active >= MAX_CONCURRENT)
|
|
158
|
+
await new Promise((resolve) => this.waiting.push(resolve));
|
|
159
|
+
this.active += 1;
|
|
160
|
+
try {
|
|
161
|
+
return await task();
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
this.active -= 1;
|
|
165
|
+
this.waiting.shift()?.();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Send one request to a fresh child and wait for its marked line.
|
|
170
|
+
* @param source the Design JSX source.
|
|
171
|
+
* @param partial the action and its options.
|
|
172
|
+
* @returns the response.
|
|
173
|
+
*/
|
|
174
|
+
async request(source, partial) {
|
|
175
|
+
return this.run(async () => {
|
|
176
|
+
const nonce = randomBytes(12).toString('hex');
|
|
177
|
+
const response = await this.spawnAndWait({ nonce, source, ...partial });
|
|
178
|
+
if (!response.ok)
|
|
179
|
+
throw new ArtifactError(response.code, response.message);
|
|
180
|
+
return response;
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Spawn the worker, write the request, and read the marked response.
|
|
185
|
+
* @param request the request.
|
|
186
|
+
* @returns the response.
|
|
187
|
+
*/
|
|
188
|
+
spawnAndWait(request) {
|
|
189
|
+
const args = workerArgs();
|
|
190
|
+
return new Promise((resolve, reject) => {
|
|
191
|
+
let stdout = '';
|
|
192
|
+
let stderr = '';
|
|
193
|
+
let settled = false;
|
|
194
|
+
let timedOut = false;
|
|
195
|
+
const child = spawn(process.execPath, args, { env: workerEnv(), stdio: ['pipe', 'pipe', 'pipe'] });
|
|
196
|
+
const timer = setTimeout(() => {
|
|
197
|
+
timedOut = true;
|
|
198
|
+
child.kill('SIGKILL');
|
|
199
|
+
}, TIMEOUT_MS);
|
|
200
|
+
const finish = (settle) => {
|
|
201
|
+
if (settled)
|
|
202
|
+
return;
|
|
203
|
+
settled = true;
|
|
204
|
+
clearTimeout(timer);
|
|
205
|
+
settle();
|
|
206
|
+
};
|
|
207
|
+
const fail = (code, message) => {
|
|
208
|
+
finish(() => reject(new ArtifactError(code, message)));
|
|
209
|
+
};
|
|
210
|
+
child.on('error', (error) => fail('artifact/design-render-failed', `The design renderer did not start: ${error.message}`));
|
|
211
|
+
child.stdout.on('data', (chunk) => {
|
|
212
|
+
stdout += chunk.toString('utf8');
|
|
213
|
+
if (stdout.length > MAX_STDOUT) {
|
|
214
|
+
child.kill('SIGKILL');
|
|
215
|
+
fail('artifact/design-render-failed', 'The design renderer produced too much output.');
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
child.stderr.on('data', (chunk) => {
|
|
219
|
+
if (stderr.length < MAX_STDERR)
|
|
220
|
+
stderr += chunk.toString('utf8');
|
|
221
|
+
});
|
|
222
|
+
child.on('close', (code, signal) => {
|
|
223
|
+
if (settled)
|
|
224
|
+
return;
|
|
225
|
+
if (timedOut) {
|
|
226
|
+
fail('artifact/design-timeout', 'The design took too long to render and was stopped.');
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const line = stdout.split('\n').find((item) => item.startsWith(request.nonce));
|
|
230
|
+
if (line === undefined) {
|
|
231
|
+
const detail = stderr.trim().slice(0, 400);
|
|
232
|
+
const status = code === null ? String(signal ?? 'unknown') : String(code);
|
|
233
|
+
fail('artifact/design-render-failed', `The design renderer stopped (exit ${status}).${detail === '' ? '' : ' ' + detail}`);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
let parsed;
|
|
237
|
+
try {
|
|
238
|
+
parsed = JSON.parse(line.slice(request.nonce.length));
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
fail('artifact/design-render-failed', 'The design renderer returned invalid JSON.');
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (!isResponse(parsed)) {
|
|
245
|
+
fail('artifact/design-render-failed', 'The design renderer returned an unexpected shape.');
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
finish(() => resolve(parsed));
|
|
249
|
+
});
|
|
250
|
+
child.stdin.on('error', () => undefined);
|
|
251
|
+
child.stdin.end(JSON.stringify(request));
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { ArtifactError } from './errors.js';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { assertWithin, withLock } from './fsutil.js';
|
|
5
|
+
export async function acquireEditor(key, token, check) {
|
|
6
|
+
await withLock(key, async () => {
|
|
7
|
+
await check();
|
|
8
|
+
if (!/^[a-zA-Z0-9-]{1,100}$/.test(token))
|
|
9
|
+
throw new ArtifactError('artifact/bad-request', 'Invalid editor token.');
|
|
10
|
+
const leaseDir = path.join(key, '.editors');
|
|
11
|
+
await assertWithin(key, leaseDir);
|
|
12
|
+
await fs.mkdir(leaseDir, { recursive: true });
|
|
13
|
+
const artifactDirectory = await fs.open(key, 'r');
|
|
14
|
+
try {
|
|
15
|
+
await artifactDirectory.sync();
|
|
16
|
+
}
|
|
17
|
+
finally {
|
|
18
|
+
await artifactDirectory.close();
|
|
19
|
+
}
|
|
20
|
+
const marker = path.join(leaseDir, token);
|
|
21
|
+
await assertWithin(key, marker);
|
|
22
|
+
const handle = await fs.open(marker, 'a', 0o600);
|
|
23
|
+
try {
|
|
24
|
+
await handle.sync();
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
await handle.close();
|
|
28
|
+
}
|
|
29
|
+
const directory = await fs.open(leaseDir, 'r');
|
|
30
|
+
try {
|
|
31
|
+
await directory.sync();
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
await directory.close();
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
export async function releaseEditor(key, token) {
|
|
39
|
+
await withLock(key, async () => {
|
|
40
|
+
if (!/^[a-zA-Z0-9-]{1,100}$/.test(token))
|
|
41
|
+
throw new ArtifactError('artifact/bad-request', 'Invalid editor token.');
|
|
42
|
+
const marker = path.join(key, '.editors', token);
|
|
43
|
+
await assertWithin(key, marker);
|
|
44
|
+
await fs.rm(marker, { force: true });
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
/** Call only while holding the same artifact lock as acquireEditor. */
|
|
48
|
+
export async function assertNoEditors(key, ownToken) {
|
|
49
|
+
const directory = path.join(key, '.editors');
|
|
50
|
+
await assertWithin(key, directory);
|
|
51
|
+
let holders;
|
|
52
|
+
try {
|
|
53
|
+
holders = await fs.readdir(directory);
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT')
|
|
57
|
+
throw error;
|
|
58
|
+
holders = [];
|
|
59
|
+
}
|
|
60
|
+
if ((ownToken !== undefined && !holders.includes(ownToken)) || holders.some(token => token !== ownToken)) {
|
|
61
|
+
throw new ArtifactError('artifact/editor-open', 'Close all open editors for this artifact before moving it.');
|
|
62
|
+
}
|
|
63
|
+
}
|
package/dist/host/lib/export.js
CHANGED
|
@@ -10,6 +10,9 @@ const MEDIA_TYPES = {
|
|
|
10
10
|
html: 'text/html',
|
|
11
11
|
md: 'text/markdown',
|
|
12
12
|
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
13
|
+
png: 'image/png',
|
|
14
|
+
svg: 'image/svg+xml',
|
|
15
|
+
fig: 'application/octet-stream',
|
|
13
16
|
};
|
|
14
17
|
const MARKED_TYPES = new Set([
|
|
15
18
|
'blockquote', 'br', 'checkbox', 'code', 'codespan', 'def', 'del', 'em', 'escape', 'heading', 'hr', 'html',
|
|
@@ -289,16 +292,31 @@ export async function docToDocx(title, markdown, design) {
|
|
|
289
292
|
* @param format the requested format.
|
|
290
293
|
* @param design the resolved design system.
|
|
291
294
|
* @param now the clock value.
|
|
295
|
+
* @param designs the design renderer, needed for a design's derived formats.
|
|
292
296
|
* @returns the written file and its bytes, base64 encoded for a browser download.
|
|
293
297
|
*/
|
|
294
|
-
export async function writeExport(root, manifest, content, format, design, now) {
|
|
298
|
+
export async function writeExport(root, manifest, content, format, design, now, designs) {
|
|
295
299
|
if (!FORMATS_BY_TYPE[manifest.type].includes(format)) {
|
|
296
300
|
throw new ArtifactError('artifact/unsupported-format', `A ${manifest.type} cannot be exported as ${format}.`, {
|
|
297
301
|
supported: FORMATS_BY_TYPE[manifest.type],
|
|
298
302
|
});
|
|
299
303
|
}
|
|
300
304
|
let data;
|
|
301
|
-
|
|
305
|
+
let mediaType = MEDIA_TYPES[format];
|
|
306
|
+
if (manifest.type === 'design') {
|
|
307
|
+
if (designs === undefined) {
|
|
308
|
+
throw new ArtifactError('artifact/design-unavailable', 'The design renderer is not available.', {});
|
|
309
|
+
}
|
|
310
|
+
if (format !== 'png' && format !== 'svg' && format !== 'fig') {
|
|
311
|
+
throw new ArtifactError('artifact/unsupported-format', `A design cannot be exported as ${format}.`, {
|
|
312
|
+
supported: FORMATS_BY_TYPE.design,
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
const rendered = await designs.exportContent(content, format);
|
|
316
|
+
data = rendered.bytes;
|
|
317
|
+
mediaType = rendered.mediaType;
|
|
318
|
+
}
|
|
319
|
+
else if (format === 'docx')
|
|
302
320
|
data = await docToDocx(manifest.title, content, design.tokens);
|
|
303
321
|
else if (format === 'md')
|
|
304
322
|
data = Buffer.from(content, 'utf8');
|
|
@@ -315,5 +333,5 @@ export async function writeExport(root, manifest, content, format, design, now)
|
|
|
315
333
|
await assertWithin(root.root, file);
|
|
316
334
|
await fs.writeFile(file, data, { flag: 'wx' });
|
|
317
335
|
});
|
|
318
|
-
return { path: file, bytes: data.length, fileName, mediaType
|
|
336
|
+
return { path: file, bytes: data.length, fileName, mediaType, data: data.toString('base64') };
|
|
319
337
|
}
|
package/dist/host/lib/fsutil.js
CHANGED
|
@@ -36,7 +36,10 @@ export async function writeAtomic(file, data) {
|
|
|
36
36
|
try {
|
|
37
37
|
const handle = await fs.open(temp, 'wx');
|
|
38
38
|
try {
|
|
39
|
-
|
|
39
|
+
if (typeof data === 'string')
|
|
40
|
+
await handle.writeFile(data, 'utf8');
|
|
41
|
+
else
|
|
42
|
+
await handle.writeFile(data);
|
|
40
43
|
await handle.sync();
|
|
41
44
|
}
|
|
42
45
|
finally {
|
package/dist/host/lib/rpc.js
CHANGED
|
@@ -4,6 +4,9 @@ import { fieldsOf, optionalEdits, optionalInteger, optionalScope, optionalString
|
|
|
4
4
|
export const ENDPOINTS = [
|
|
5
5
|
'list',
|
|
6
6
|
'get',
|
|
7
|
+
'openEditor',
|
|
8
|
+
'closeEditor',
|
|
9
|
+
'move',
|
|
7
10
|
'create',
|
|
8
11
|
'update',
|
|
9
12
|
'delete',
|
|
@@ -14,6 +17,7 @@ export const ENDPOINTS = [
|
|
|
14
17
|
'designSystem',
|
|
15
18
|
'saveDesignSystem',
|
|
16
19
|
'clearDesignSystem',
|
|
20
|
+
'preview',
|
|
17
21
|
];
|
|
18
22
|
/**
|
|
19
23
|
* The scope context of a request. A library request may carry a workspace id;
|
|
@@ -49,6 +53,14 @@ async function dispatch(service, endpoint, fields) {
|
|
|
49
53
|
});
|
|
50
54
|
case 'get':
|
|
51
55
|
return service.read(target, requiredString(fields, 'id'), optionalInteger(fields, 'version'));
|
|
56
|
+
case 'openEditor':
|
|
57
|
+
await service.openEditor(target, requiredString(fields, 'id'), requiredString(fields, 'token'));
|
|
58
|
+
return { ok: true };
|
|
59
|
+
case 'closeEditor':
|
|
60
|
+
await service.closeEditor(target, requiredString(fields, 'id'), requiredString(fields, 'token'));
|
|
61
|
+
return { ok: true };
|
|
62
|
+
case 'move':
|
|
63
|
+
return { manifest: await service.move(target, requiredString(fields, 'id'), requiredString(fields, 'destinationWorkspaceId'), requiredInteger(fields, 'baseVersion'), requiredString(fields, 'token')) };
|
|
52
64
|
case 'create':
|
|
53
65
|
return {
|
|
54
66
|
manifest: await service.create(target, {
|
|
@@ -86,6 +98,8 @@ async function dispatch(service, endpoint, fields) {
|
|
|
86
98
|
return service.saveDesignSystem(target, fields.tokens);
|
|
87
99
|
case 'clearDesignSystem':
|
|
88
100
|
return service.clearWorkspaceDesignSystem(target);
|
|
101
|
+
case 'preview':
|
|
102
|
+
return service.preview(target, requiredString(fields, 'id'), optionalInteger(fields, 'version'));
|
|
89
103
|
default: {
|
|
90
104
|
const unreachable = endpoint;
|
|
91
105
|
throw new ArtifactError('artifact/not-found', `Unknown endpoint ${String(unreachable)}.`);
|