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.
@@ -1,30 +1,39 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { isDesignInfo, scopeOfId } from '../../contract.js';
1
4
  import { PAGE_CSP, composePage } from '../../render.js';
2
- import { scopeOfId } from '../../contract.js';
5
+ import { DesignRenderer, PREVIEW_MAX_SIDE } from './design-render.js';
3
6
  import { clearWorkspaceDesignSystem, resolveDesignSystem, saveDesignSystem } from './design-system.js';
4
7
  import { ArtifactError } from './errors.js';
8
+ import { acquireEditor, releaseEditor } from './editor-leases.js';
5
9
  import { docToHtml, writeExport } from './export.js';
6
- import { libraryRoot, requireWorkspace, workspaceRoot, workspaceRootExisting } from './paths.js';
7
- import { ArtifactStore } from './store.js';
10
+ import { assertWithin, withLock, writeAtomic } from './fsutil.js';
11
+ import { assertPlainFile, libraryRoot, requireWorkspace, workspaceRoot, workspaceRootExisting } from './paths.js';
12
+ import { ArtifactStore, applyEdits, hashOf } from './store.js';
8
13
  /**
9
- * One facade over the store, the scope roots, the design system, and export.
10
- * The route and the tools both call it, so both scopes share every rule.
14
+ * One facade over the store, the scope roots, the design system, the design
15
+ * renderer, and export. The route and the tools both call it, so both scopes
16
+ * share every rule.
11
17
  */
12
18
  export class ArtifactService {
13
19
  store;
14
20
  config;
15
21
  registry;
16
22
  now;
23
+ designs;
17
24
  /**
18
25
  * @param config root locations.
19
26
  * @param registry the workspace registry.
20
27
  * @param store the store.
21
28
  * @param now the clock.
29
+ * @param designs the design renderer.
22
30
  */
23
- constructor(config, registry, store = new ArtifactStore(), now = () => new Date()) {
31
+ constructor(config, registry, store = new ArtifactStore(), now = () => new Date(), designs = new DesignRenderer()) {
24
32
  this.config = config;
25
33
  this.registry = registry;
26
34
  this.store = store;
27
35
  this.now = now;
36
+ this.designs = designs;
28
37
  }
29
38
  /**
30
39
  * Resolve a scope root. An id decides its own scope; a workspace scope needs a workspace id.
@@ -91,20 +100,100 @@ export class ArtifactService {
91
100
  await clearWorkspaceDesignSystem(await this.root({ ...target, scope: 'workspace' }));
92
101
  return this.designSystem(target);
93
102
  }
103
+ /**
104
+ * Create an artifact. A design is compiled before anything is written, so an
105
+ * invalid source never creates a directory or a version.
106
+ * @param target the caller's context.
107
+ * @param input type, title, content, and source.
108
+ * @returns the manifest.
109
+ */
94
110
  async create(target, input) {
95
- return this.store.create(await this.root(target), input);
111
+ const root = await this.root(target);
112
+ const info = input.type === 'design' ? await this.designs.inspect(input.content) : undefined;
113
+ const manifest = await this.store.create(root, input);
114
+ if (info !== undefined)
115
+ await this.writeInfo(root, manifest.id, input.content, info);
116
+ return manifest;
96
117
  }
118
+ /**
119
+ * Read an artifact. A design carries its compiled summary when one can be
120
+ * produced; a failure there never hides the source.
121
+ * @param target the caller's context.
122
+ * @param id the artifact id.
123
+ * @param version an earlier version, when the caller named one.
124
+ * @returns the payload.
125
+ */
97
126
  async read(target, id, version) {
98
- const result = await this.store.read(await this.root(target, id), id, version);
127
+ const root = await this.root(target, id);
128
+ const result = await this.store.read(root, id, version);
99
129
  const design = await this.designSystem(target);
100
- return { ...result, designCss: design.css, design: design.tokens };
130
+ const payload = {
131
+ ...result,
132
+ designCss: design.css,
133
+ design: design.tokens,
134
+ };
135
+ if (result.manifest.type === 'design') {
136
+ const info = await this.infoFor(root, id, result.content);
137
+ if (info !== undefined)
138
+ payload.designInfo = info;
139
+ }
140
+ return payload;
101
141
  }
142
+ /**
143
+ * Save a new version. A design update resolves the final source first, so
144
+ * edits are validated after they are applied and the committed content is
145
+ * exactly what the renderer accepted.
146
+ * @param target the caller's context.
147
+ * @param id the artifact id.
148
+ * @param input the update.
149
+ * @returns the new manifest.
150
+ */
102
151
  async update(target, id, input) {
103
- return this.store.update(await this.root(target, id), id, input);
152
+ const root = await this.root(target, id);
153
+ const current = await this.store.manifest(root, id);
154
+ if (current.type !== 'design')
155
+ return this.store.update(root, id, input);
156
+ const existing = await this.store.read(root, id);
157
+ let next = input.content;
158
+ if (next === undefined && input.edits !== undefined)
159
+ next = applyEdits(existing.content, input.edits);
160
+ if (next === undefined)
161
+ return this.store.update(root, id, input);
162
+ const info = await this.designs.inspect(next);
163
+ const manifest = await this.store.update(root, id, { ...input, content: next, edits: undefined });
164
+ await this.writeInfo(root, id, next, info);
165
+ return manifest;
104
166
  }
167
+ /**
168
+ * Restore an earlier version.
169
+ * @param target the caller's context.
170
+ * @param id the artifact id.
171
+ * @param version the version to restore.
172
+ * @param source who restored it.
173
+ * @param baseVersion the version the caller saw, if it checks.
174
+ * @returns the new manifest.
175
+ */
105
176
  async restore(target, id, version, source, baseVersion) {
106
177
  return this.store.restore(await this.root(target, id), id, version, source, baseVersion);
107
178
  }
179
+ async openEditor(target, id, token) {
180
+ const root = await this.root(target, id);
181
+ const key = path.join(root.root, id);
182
+ await acquireEditor(key, token, async () => { await this.store.manifest(root, id); });
183
+ }
184
+ async closeEditor(target, id, token) {
185
+ const root = await this.root(target, id);
186
+ await releaseEditor(path.join(root.root, id), token);
187
+ }
188
+ async move(target, id, destinationWorkspaceId, baseVersion, ownToken) {
189
+ if (scopeOfId(id) !== 'workspace' || target.workspaceId === undefined || destinationWorkspaceId === target.workspaceId) {
190
+ throw new ArtifactError('artifact/bad-request', 'Choose a different workspace for a workspace artifact.');
191
+ }
192
+ requireWorkspace(this.registry, destinationWorkspaceId);
193
+ const source = await this.root({ scope: 'workspace', workspaceId: target.workspaceId }, id);
194
+ const destination = await this.root({ scope: 'workspace', workspaceId: destinationWorkspaceId });
195
+ return this.store.move(source, destination, id, baseVersion, ownToken);
196
+ }
108
197
  async history(target, id) {
109
198
  return this.store.history(await this.root(target, id), id);
110
199
  }
@@ -122,15 +211,206 @@ export class ArtifactService {
122
211
  */
123
212
  async printable(target, id, version) {
124
213
  const { manifest, content } = await this.store.read(await this.root(target, id), id, version);
214
+ if (manifest.type === 'design') {
215
+ throw new ArtifactError('artifact/unsupported-format', 'A design cannot be printed.', { type: manifest.type });
216
+ }
125
217
  const design = await this.designSystem(target);
126
218
  return { html: manifest.type === 'page'
127
219
  ? composePage(content, design.css, PAGE_CSP, manifest.title)
128
220
  : docToHtml(manifest.title, content, design.css, true) };
129
221
  }
222
+ /**
223
+ * Export a saved version. A design is rendered from its source at that
224
+ * version; the preview cache is never used as the export source.
225
+ * @param target the caller's context.
226
+ * @param id the artifact id.
227
+ * @param format the format.
228
+ * @param version the version, when the caller named one.
229
+ * @returns the exported file.
230
+ */
130
231
  async export(target, id, format, version) {
131
232
  const root = await this.root(target, id);
132
233
  const { manifest, content, version: readVersion } = await this.store.read(root, id, version);
133
234
  const design = await this.designSystem(target);
134
- return writeExport(root, { ...manifest, version: readVersion }, content, format, design, this.now());
235
+ return writeExport(root, { ...manifest, version: readVersion }, content, format, design, this.now(), this.designs);
236
+ }
237
+ /**
238
+ * Render a design, or return its cached preview for the same source.
239
+ * @param target the caller's context.
240
+ * @param id the artifact id.
241
+ * @param version the version, when the caller named one.
242
+ * @returns the preview.
243
+ */
244
+ async preview(target, id, version) {
245
+ const root = await this.root(target, id);
246
+ const { manifest, content } = await this.store.read(root, id, version);
247
+ if (manifest.type !== 'design') {
248
+ throw new ArtifactError('artifact/unsupported-type', 'Only a design has a rendered preview.', { type: manifest.type });
249
+ }
250
+ const cached = await this.readPreview(root, id, content);
251
+ if (cached !== undefined)
252
+ return cached;
253
+ const rendered = await this.designs.preview(content, PREVIEW_MAX_SIDE);
254
+ await this.writePreview(root, id, content, rendered.info, rendered.width, rendered.height, rendered.bytes);
255
+ return {
256
+ mediaType: 'image/png',
257
+ data: rendered.bytes.toString('base64'),
258
+ width: rendered.width,
259
+ height: rendered.height,
260
+ info: rendered.info,
261
+ };
262
+ }
263
+ /**
264
+ * The cache location of a source's preview.
265
+ * @param root the scope root.
266
+ * @param id the artifact id.
267
+ * @param content the design source.
268
+ * @returns the paths.
269
+ */
270
+ previewPaths(root, id, content) {
271
+ const dir = path.join(root.root, id, 'preview');
272
+ const key = hashOf(content).slice('sha256:'.length);
273
+ return { dir, png: path.join(dir, `${key}.png`), meta: path.join(dir, `${key}.json`) };
274
+ }
275
+ /**
276
+ * Read a cached preview, when both files are plain and agree on the size.
277
+ * @param root the scope root.
278
+ * @param id the artifact id.
279
+ * @param content the design source.
280
+ * @returns the preview, or undefined.
281
+ */
282
+ async readPreview(root, id, content) {
283
+ try {
284
+ const paths = this.previewPaths(root, id, content);
285
+ await assertWithin(root.root, paths.dir);
286
+ if (!(await assertPlainFile(paths.png)) || !(await assertPlainFile(paths.meta)))
287
+ return undefined;
288
+ const parsed = JSON.parse(await fs.readFile(paths.meta, 'utf8'));
289
+ if (parsed === null || typeof parsed !== 'object')
290
+ return undefined;
291
+ const fields = { ...parsed };
292
+ if (!isDesignInfo(fields.info) || typeof fields.width !== 'number' || typeof fields.height !== 'number')
293
+ return undefined;
294
+ const bytes = await fs.readFile(paths.png);
295
+ return {
296
+ mediaType: 'image/png',
297
+ data: bytes.toString('base64'),
298
+ width: fields.width,
299
+ height: fields.height,
300
+ info: fields.info,
301
+ };
302
+ }
303
+ catch {
304
+ return undefined;
305
+ }
306
+ }
307
+ /**
308
+ * The summary of a design, from the cache or a compile.
309
+ * @param root the scope root.
310
+ * @param id the artifact id.
311
+ * @param content the design source.
312
+ * @returns the summary, or undefined when the renderer is unavailable.
313
+ */
314
+ async infoFor(root, id, content) {
315
+ const cached = await this.readCachedInfo(root, id, content);
316
+ if (cached !== undefined)
317
+ return cached;
318
+ try {
319
+ const info = await this.designs.inspect(content);
320
+ await this.writeInfo(root, id, content, info);
321
+ return info;
322
+ }
323
+ catch (error) {
324
+ console.warn('[dsh-artifact-studio] design summary failed', id, error instanceof Error ? error.message : error);
325
+ return undefined;
326
+ }
327
+ }
328
+ /**
329
+ * Read a cached summary.
330
+ * @param root the scope root.
331
+ * @param id the artifact id.
332
+ * @param content the design source.
333
+ * @returns the summary, or undefined.
334
+ */
335
+ async readCachedInfo(root, id, content) {
336
+ try {
337
+ const paths = this.previewPaths(root, id, content);
338
+ await assertWithin(root.root, paths.dir);
339
+ if (!(await assertPlainFile(paths.meta)))
340
+ return undefined;
341
+ const parsed = JSON.parse(await fs.readFile(paths.meta, 'utf8'));
342
+ if (parsed === null || typeof parsed !== 'object')
343
+ return undefined;
344
+ const fields = { ...parsed };
345
+ return isDesignInfo(fields.info) ? fields.info : undefined;
346
+ }
347
+ catch {
348
+ return undefined;
349
+ }
350
+ }
351
+ /**
352
+ * Cache a summary for a source hash.
353
+ * @param root the scope root.
354
+ * @param id the artifact id.
355
+ * @param content the design source.
356
+ * @param info the summary.
357
+ */
358
+ async writeInfo(root, id, content, info) {
359
+ try {
360
+ const paths = this.previewPaths(root, id, content);
361
+ await assertWithin(root.root, paths.dir);
362
+ await withLock(paths.dir, async () => {
363
+ await fs.mkdir(paths.dir, { recursive: true });
364
+ await assertWithin(root.root, paths.meta);
365
+ await writeAtomic(paths.meta, `${JSON.stringify({ info }, null, 2)}\n`);
366
+ await this.prunePreview(paths.dir, path.basename(paths.png));
367
+ });
368
+ }
369
+ catch (error) {
370
+ // The artifact is saved; a cache failure only costs the next reader a compile.
371
+ console.warn('[dsh-artifact-studio] design cache failed', id, error instanceof Error ? error.message : error);
372
+ }
373
+ }
374
+ /**
375
+ * Cache a rendered preview.
376
+ * @param root the scope root.
377
+ * @param id the artifact id.
378
+ * @param content the design source.
379
+ * @param info the summary.
380
+ * @param width the image width.
381
+ * @param height the image height.
382
+ * @param bytes the PNG bytes.
383
+ */
384
+ async writePreview(root, id, content, info, width, height, bytes) {
385
+ try {
386
+ const paths = this.previewPaths(root, id, content);
387
+ await assertWithin(root.root, paths.dir);
388
+ await withLock(paths.dir, async () => {
389
+ await fs.mkdir(paths.dir, { recursive: true });
390
+ await assertWithin(root.root, paths.png);
391
+ await writeAtomic(paths.png, bytes);
392
+ await assertWithin(root.root, paths.meta);
393
+ await writeAtomic(paths.meta, `${JSON.stringify({ info, width, height }, null, 2)}\n`);
394
+ await this.prunePreview(paths.dir, path.basename(paths.png));
395
+ });
396
+ }
397
+ catch (error) {
398
+ console.warn('[dsh-artifact-studio] design preview cache failed', id, error instanceof Error ? error.message : error);
399
+ }
400
+ }
401
+ /**
402
+ * Drop cache files that do not belong to the current source hash.
403
+ * @param dir the preview directory.
404
+ * @param keep the file name to keep.
405
+ */
406
+ async prunePreview(dir, keep) {
407
+ const prefix = keep.replace(/\.png$/, '');
408
+ for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
409
+ if (!entry.isFile() || entry.isSymbolicLink())
410
+ continue;
411
+ if (entry.name.startsWith(prefix))
412
+ continue;
413
+ await fs.rm(path.join(dir, entry.name), { force: true });
414
+ }
135
415
  }
136
416
  }
@@ -5,7 +5,7 @@ Use this before you call \`artifact_create\`, and before an \`artifact_update\`
5
5
 
6
6
  ## When to use an artifact
7
7
 
8
- Use \`artifact_create\` when the user asks for an artifact, an artifact page, or an artifact doc. Pick \`page\` for an artifact page and \`doc\` for an artifact doc. Never write a file in the project instead. Write a project file only when the user asks for a file in the repo.
8
+ Use \`artifact_create\` when the user asks for an artifact, an artifact page, an artifact doc, or an artifact design. Pick \`page\` for an artifact page, \`doc\` for an artifact doc, and \`design\` for an OpenPencil design. Never write a file in the project instead. Write a project file only when the user asks for a file in the repo.
9
9
 
10
10
  ## Precedence
11
11
 
@@ -17,6 +17,25 @@ Use \`artifact_create\` when the user asks for an artifact, an artifact page, or
17
17
 
18
18
  - \`doc\` for prose: reports, briefs, plans, specs, notes. It is Markdown, edited in a rich-text editor, and exported to Word, Markdown, and HTML. Use headings, short paragraphs, lists, tables, task lists, quotes, and fenced code. Do not paste HTML into a doc.
19
19
  - \`page\` for anything visual or interactive: dashboards, one-pagers, explainers, calculators, diagrams, prototypes.
20
+ - \`design\` for a layout the user will open on a canvas: UI mockups, layout explorations, and screens that export as PNG, SVG, or a \`.fig\` document.
21
+
22
+ ## Designs (OpenPencil Design JSX)
23
+
24
+ A design is OpenPencil Design JSX, not React DOM and not HTML. There are no imports, no HTML tags, and no CSS classes. Icons use the bundled Material Design Icons set.
25
+
26
+ Call this artifact a mockup when you talk to the user. The tools still take type \`design\`.
27
+
28
+ - Elements: \`Frame\`, \`Text\`, \`Rectangle\`, \`Ellipse\`, \`Line\`, \`Star\`, \`Polygon\`, \`Vector\`, \`Group\`, \`Section\`.
29
+ - Layout props: \`w\`, \`h\`, \`p\`, \`px\`, \`py\`, \`gap\`, \`flex\` (\`row\` or \`col\`), \`items\`, \`justify\`, \`bg\`, \`rounded\`, \`stroke\`, \`strokeWidth\`, \`opacity\`.
30
+ - Use \`flex\`, not \`dir\`. \`dir\` is accepted and does nothing, so every child sits at the same origin. A frame with \`flex\` sizes itself to its children unless you give it \`w\` or \`h\`.
31
+ - Text props: \`size\`, \`weight\`, \`color\`, \`font\`, \`lineHeight\`, \`letterSpacing\`, \`textAlign\`, \`maxLines\`.
32
+ - Put a background on the outer \`Frame\`; the preview crops transparent space around the content.
33
+ - Example: \`<Frame w={720} p={40} bg="#ffffff" flex="col" gap={12}><Text size={40} weight={700} color="#16181d">Title</Text><Text size={16} color="#5b6170">One line of context.</Text></Frame>\`
34
+ - Icons: \`<Icon name="mdi:home" size={24} color="#1b1712" />\`. Only the \`mdi:\` set is bundled. Common names: \`home\`, \`search\`, \`user\`, \`heart\`, \`star\`, \`check\`, \`close\`, \`plus\`, \`arrow-right\`, \`settings\`, \`bell\`, \`calendar\`, \`mail\`, \`image\`, \`file\`, \`folder\`, \`trash\`, \`edit\`, \`download\`, \`lock\`, \`eye\`, \`cart\`, \`chart-bar\`, \`alert\`, \`clock\`, \`map-marker\`, \`menu\`, \`chevron-right\`. An unknown set or name refuses the save. Icons draw as vectors and keep their 24 unit box.
35
+ - Text uses Inter, Roboto, or Noto Naskh Arabic, which ship with the package. Any other family substitutes a default face and returns a warning.
36
+ - A design has no network and no external images. Use solid and gradient fills, shapes, and text.
37
+ - The stored artifact is the JSX source. Send the complete source as \`content\` when you update a design. The host compiles and validates before saving, so a compile error refuses the write and returns the compiler message.
38
+ - Export is PNG, SVG, or \`.fig\`. The user can open the \`.fig\` in OpenPencil for a full canvas editor.
20
39
 
21
40
  ## The page sandbox
22
41
 
@@ -56,13 +75,23 @@ Dark mode is opt in. Add \`<meta name="color-scheme" content="light dark">\` and
56
75
  - Use one H1 as the title, H2 for sections, and H3 sparingly.
57
76
  - Keep paragraphs to four sentences or fewer. Use a table for comparisons and a list for steps.
58
77
 
78
+ ## Check before you save
79
+
80
+ Every \`artifact_create\` and \`artifact_update\` call writes a new version the user sees in History. Treat each save as a release, not a draft.
81
+
82
+ - Finish the artifact before the first save. Reread the full draft once for broken markup, CSS that hides or overrides elements such as \`[hidden]\`, controls without handlers, placeholder copy, and the sandbox rules above.
83
+ - To check a page visually, render a scratch copy outside the artifact, for example a temporary HTML file in a browser tool. Fix what you find there, then create the artifact once.
84
+ - If a check after saving finds problems, fix all of them in one \`artifact_update\`. Never send one update per finding.
85
+ - Do not run polish passes the user did not ask for. One create, plus at most one corrective update, is the normal result of one request.
86
+
59
87
  ## Updating
60
88
 
61
89
  - Read the artifact first with \`artifact_read\` when the user may have edited it, and pass that version as \`baseVersion\`.
62
90
  - For a few local changes, send \`edits\`. Each \`oldText\` must appear exactly once, so include enough surrounding text.
63
91
  - Send full \`content\` only when you rewrite most of the artifact.
64
92
  - If the update is refused for a stale version, read again and reapply your change. Never overwrite the user's edits.
65
- - When a create or update returns \`warnings\`, fix them in a follow-up update unless the user asked for that behavior.
93
+ - When a create or update returns \`warnings\`, fix all of them in one follow-up update unless the user asked for that behavior.
94
+ - Several changes the user asked for in one message go into one update.
66
95
 
67
96
  ## After writing
68
97
 
@@ -71,7 +100,7 @@ Tell the user in one or two sentences what you made or changed. Do not repeat th
71
100
  /** The artifact design skill, registered by the \`dsh-artifact-studio/skill\` host plugin. */
72
101
  export const ARTIFACT_DESIGN_SKILL = {
73
102
  name: 'artifact-design',
74
- description: 'Design rules for artifact pages and documents: when to use an artifact, precedence, the page sandbox, design tokens, dark mode, layout, typography, and the update rule.',
103
+ description: 'Design rules for artifact pages, documents, and OpenPencil designs: when to use an artifact, precedence, the page sandbox, Design JSX, design tokens, dark mode, layout, typography, and the update rule.',
75
104
  whenToUse: 'Load before artifact_create, when the user asks for an artifact, and before an artifact_update that changes layout or styling.',
76
105
  source: 'bundled',
77
106
  content: CONTENT,
@@ -3,6 +3,7 @@ import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { CONTENT_FILE, ID_PATTERN, MAX_LIST_LIMIT, MAX_TITLE, isArtifactType, isManifest, isVersionSource } from '../../contract.js';
5
5
  import { ArtifactError, errnoCode } from './errors.js';
6
+ import { assertNoEditors } from './editor-leases.js';
6
7
  import { assertWithin, withLock, writeAtomic } from './fsutil.js';
7
8
  import { artifactDir, assertPlainFile } from './paths.js';
8
9
  export const DEFAULT_LIMITS = {
@@ -329,6 +330,15 @@ export class ArtifactStore {
329
330
  }
330
331
  return manifest;
331
332
  }
333
+ /**
334
+ * Read only the manifest, without its content.
335
+ * @param root the scope root.
336
+ * @param id the artifact id.
337
+ * @returns the manifest.
338
+ */
339
+ async manifest(root, id) {
340
+ return this.readManifest(await artifactDir(root, id));
341
+ }
332
342
  /**
333
343
  * Read the manifest and content of the current or an earlier version.
334
344
  * @param root the scope root.
@@ -480,6 +490,53 @@ export class ArtifactStore {
480
490
  const items = filtered.slice(offset, offset + limit);
481
491
  return { items, total: filtered.length, hasMore: offset + items.length < filtered.length, truncated };
482
492
  }
493
+ /** Transfer saved files under source and destination locks. */
494
+ async move(source, destination, id, baseVersion, ownToken) {
495
+ if (source.scope !== 'workspace' || destination.scope !== 'workspace' || source.root === destination.root) {
496
+ throw new ArtifactError('artifact/bad-request', 'Choose a different workspace.');
497
+ }
498
+ const dir = await artifactDir(source, id);
499
+ const target = path.join(destination.root, id);
500
+ await assertWithin(destination.root, target);
501
+ const first = dir < target ? dir : target;
502
+ const second = dir < target ? target : dir;
503
+ return withLock(first, () => withLock(second, async () => {
504
+ await assertNoEditors(dir, ownToken);
505
+ const manifest = await this.readManifest(dir);
506
+ if (manifest.version !== baseVersion) {
507
+ throw new ArtifactError('artifact/stale-version', 'The artifact changed before it could be moved.', { current: manifest.version, baseVersion });
508
+ }
509
+ try {
510
+ await fs.lstat(target);
511
+ throw new ArtifactError('artifact/bad-request', 'The destination already contains this artifact.', { id });
512
+ }
513
+ catch (error) {
514
+ if (error instanceof ArtifactError || errnoCode(error) !== 'ENOENT')
515
+ throw error;
516
+ }
517
+ const inspect = async (entry) => {
518
+ await assertWithin(source.root, entry);
519
+ const stat = await fs.lstat(entry);
520
+ if (stat.isSymbolicLink() || (!stat.isFile() && !stat.isDirectory())) {
521
+ throw new ArtifactError('artifact/forbidden-path', 'An artifact contains an unsafe file.');
522
+ }
523
+ if (stat.isDirectory())
524
+ for (const name of await fs.readdir(entry))
525
+ await inspect(path.join(entry, name));
526
+ };
527
+ await inspect(dir);
528
+ await assertWithin(destination.root, target);
529
+ try {
530
+ await fs.rename(dir, target);
531
+ }
532
+ catch (error) {
533
+ if (errnoCode(error) === 'EXDEV')
534
+ throw new ArtifactError('artifact/storage-failure', 'Source and destination must be on the same filesystem. The artifact was not moved.');
535
+ throw error;
536
+ }
537
+ return manifest;
538
+ }));
539
+ }
483
540
  /**
484
541
  * Move an artifact into the scope's trash, then sweep trash entries past retention.
485
542
  * @param root the scope root.