@arcadia-eternity/content-sdk 0.0.0-stage → 4.3.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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -2
  3. package/dist/asset-inspect.mjs +67 -0
  4. package/dist/author-api.mjs +112 -0
  5. package/dist/author-reference.mjs +121 -0
  6. package/dist/build-content.mjs +30 -0
  7. package/dist/cli.mjs +74 -0
  8. package/dist/content-query.mjs +283 -0
  9. package/dist/content-workspace.d.mts +161 -0
  10. package/dist/content-workspace.mjs +936 -0
  11. package/dist/debug-environments.mjs +154 -0
  12. package/dist/demo.mjs +22 -0
  13. package/dist/environment-rules.d.mts +5 -0
  14. package/dist/environment-rules.mjs +92 -0
  15. package/dist/environment.mjs +183 -0
  16. package/dist/index.d.mts +1 -0
  17. package/dist/index.mjs +1 -0
  18. package/dist/job-journal.mjs +94 -0
  19. package/dist/jobs.mjs +579 -0
  20. package/dist/lib/content.mjs +95 -0
  21. package/dist/lib/presentation.mjs +240 -0
  22. package/dist/lib/yaml-sharing.mjs +101 -0
  23. package/dist/managed-projects.d.mts +35 -0
  24. package/dist/managed-projects.mjs +303 -0
  25. package/dist/managed-sources.d.mts +19 -0
  26. package/dist/managed-sources.mjs +503 -0
  27. package/dist/mcp-contracts.mjs +153 -0
  28. package/dist/mcp.mjs +369 -0
  29. package/dist/pack-project.mjs +156 -0
  30. package/dist/preview-control.mjs +260 -0
  31. package/dist/preview.mjs +313 -0
  32. package/dist/project-teams.mjs +98 -0
  33. package/dist/project.mjs +140 -0
  34. package/dist/rename.mjs +112 -0
  35. package/dist/setup.mjs +134 -0
  36. package/dist/source-lock.mjs +103 -0
  37. package/dist/template/LICENSE +21 -0
  38. package/dist/template/README.md +17 -0
  39. package/dist/template/arcadia.config.mjs +2 -0
  40. package/dist/template/assets/marks/slow.png +0 -0
  41. package/dist/template/assets/pets/frostling-battle.png +0 -0
  42. package/dist/template/assets/pets/frostling-icon.png +0 -0
  43. package/dist/template/assets/pets/frostling-portrait.png +0 -0
  44. package/dist/template/data/marks/slow.yaml +18 -0
  45. package/dist/template/data/presentations/main.yaml +34 -0
  46. package/dist/template/data/resources/main.yaml +21 -0
  47. package/dist/template/data/skills/rest.yaml +6 -0
  48. package/dist/template/data/skills/strike.yaml +14 -0
  49. package/dist/template/data/species/pet-swf.yaml +36 -0
  50. package/dist/template/data/species/pet.yaml +34 -0
  51. package/dist/template/debug/teams/blue.yaml +25 -0
  52. package/dist/template/debug/teams/orange.yaml +25 -0
  53. package/dist/template/docs/presentation.md +21 -0
  54. package/dist/template/locales/en/mark.yaml +5 -0
  55. package/dist/template/locales/en/skill.yaml +12 -0
  56. package/dist/template/locales/en/species.yaml +6 -0
  57. package/dist/template/locales/zh-CN/mark.yaml +4 -0
  58. package/dist/template/locales/zh-CN/skill.yaml +10 -0
  59. package/dist/template/locales/zh-CN/species.yaml +6 -0
  60. package/dist/template/package.json +44 -0
  61. package/dist/template/skills/arcadia-content-authoring/SKILL.md +23 -0
  62. package/dist/template/skills/arcadia-content-authoring/references/project-sources.md +15 -0
  63. package/dist/template/skills/arcadia-content-authoring/references/tool-workflows.md +37 -0
  64. package/dist/template/skills/seer2-recreate-pet/SKILL.md +82 -0
  65. package/dist/template/skills/seer2-recreate-pet/references/mechanics-and-validation.md +47 -0
  66. package/dist/template/skills/seer2-recreate-pet/references/project-conventions.md +32 -0
  67. package/dist/template/skills/seer2-recreate-pet/references/testing.md +50 -0
  68. package/dist/template/src/effects.ts +44 -0
  69. package/dist/template/test/pack.test.mjs +178 -0
  70. package/dist/template/tsconfig.json +15 -0
  71. package/dist/testing.mjs +204 -0
  72. package/dist/workbench-context.mjs +18 -0
  73. package/dist/workspace-cli.mjs +60 -0
  74. package/dist/workspace-materials.mjs +153 -0
  75. package/dist/workspace.mjs +684 -0
  76. package/package.json +68 -3
package/dist/jobs.mjs ADDED
@@ -0,0 +1,579 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { StringDecoder } from 'node:string_decoder'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { cp, mkdir, mkdtemp, rm, symlink, readFile } from 'node:fs/promises'
6
+ import { join, dirname } from 'node:path'
7
+ import { tmpdir } from 'node:os'
8
+ import { AuthorWorkspace, WorkspaceError, diagnostic } from './workspace.mjs'
9
+ import { JobJournal } from './job-journal.mjs'
10
+
11
+ const cli = fileURLToPath(new URL('./cli.mjs', import.meta.url))
12
+ const terminal = new Set(['succeeded', 'failed', 'cancelled', 'interrupted'])
13
+ const outputLimit = 1024 * 1024
14
+ const queryError = message => {
15
+ throw new WorkspaceError('TASK_QUERY_INVALID', message)
16
+ }
17
+ function integer(value, minimum, maximum, name) {
18
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) queryError(`${name} 超出范围`)
19
+ return value
20
+ }
21
+ function outputRange(job) {
22
+ const text = typeof job.output === 'string' ? job.output : ''
23
+ // Receipts written by older versions have no cursor; their retained output starts at zero.
24
+ const end = Number.isSafeInteger(job.outputCursor) ? Math.max(job.outputCursor, text.length) : text.length
25
+ return { text, start: end - text.length, end }
26
+ }
27
+ function resultSummary(result) {
28
+ if (!result || typeof result !== 'object') return undefined
29
+ const summary = {}
30
+ for (const key of [
31
+ 'candidate',
32
+ 'preview',
33
+ 'environmentLock',
34
+ 'sourceRevisions',
35
+ 'filename',
36
+ 'integrity',
37
+ 'shasum',
38
+ 'winner',
39
+ 'turns',
40
+ 'environmentRevision',
41
+ 'packageName',
42
+ ])
43
+ if (result[key] !== undefined) summary[key] = structuredClone(result[key])
44
+ if (Array.isArray(result.files)) summary.fileCount = result.files.length
45
+ return summary
46
+ }
47
+ function jobSummary(job, details = false) {
48
+ const { start, end } = outputRange(job)
49
+ const summary = {
50
+ jobId: job.jobId,
51
+ kind: job.kind,
52
+ state: job.state,
53
+ phase: job.phase ?? job.state,
54
+ stale: !!job.stale,
55
+ sourceRevision: job.sourceRevision,
56
+ contentRevision: job.contentRevision,
57
+ environmentId: job.environmentId,
58
+ createdAt: job.createdAt,
59
+ ...(job.finishedAt ? { finishedAt: job.finishedAt } : {}),
60
+ diagnosticCount: job.diagnostics.length,
61
+ outputStartCursor: start,
62
+ outputCursor: end,
63
+ }
64
+ if (details) {
65
+ summary.diagnostics = job.diagnostics.slice(0, 100).map(item => ({
66
+ ...item,
67
+ message: typeof item.message === 'string' ? item.message.slice(0, 4000) : item.message,
68
+ }))
69
+ summary.diagnosticsTruncated =
70
+ job.diagnostics.length > 100 || job.diagnostics.some(item => item.message?.length > 4000)
71
+ const result = resultSummary(job.result)
72
+ if (result) summary.result = result
73
+ }
74
+ return summary
75
+ }
76
+ /** Fixed author commands; no renderer or MCP-provided executable strings. */
77
+ export class AuthorJobs {
78
+ #jobs = new Map()
79
+ #active
80
+ #closed = false
81
+ #starting
82
+ #changed
83
+ #previews = new Map()
84
+ #journal
85
+ #sync = Promise.resolve()
86
+ #timer
87
+ #waiters = new Set()
88
+ constructor(workspace, { execute = false, env = process.env, executable = process.execPath } = {}) {
89
+ this.workspace = workspace
90
+ this.execute = execute
91
+ this.env = Object.fromEntries(
92
+ Object.entries(env).filter(([key]) =>
93
+ /^(PATH|HOME|USERPROFILE|SystemRoot|WINDIR|TEMP|TMP|TMPDIR|LANG|LC_ALL|ARCADIA_NPM_CLI|ARCADIA_PREVIEW_CLIENT_URL|npm_config_cache)$/i.test(
94
+ key,
95
+ ),
96
+ ),
97
+ )
98
+ this.executable = executable
99
+ this.#changed = ({ file } = {}) => {
100
+ for (const { job } of this.#jobs.values())
101
+ if (
102
+ terminal.has(job.state) &&
103
+ !(job.kind === 'preview' && (file?.startsWith('debug/teams/') || file === job.result?.environmentLock?.file))
104
+ )
105
+ job.stale = true
106
+ this.#notify()
107
+ }
108
+ workspace.on('change', this.#changed)
109
+ if (!workspace.readOnly && workspace.root) this.#journal = new JobJournal(workspace.root)
110
+ }
111
+ get closed() {
112
+ return this.#closed
113
+ }
114
+ get hasLivePreviews() {
115
+ return this.#previews.size > 0
116
+ }
117
+ async initialize() {
118
+ await this.refresh()
119
+ this.#timer = setInterval(() => {
120
+ void this.#checkpoint().catch(() => {})
121
+ }, 250)
122
+ this.#timer.unref()
123
+ }
124
+ #checkpoint() {
125
+ this.#sync = this.#sync
126
+ .catch(() => {})
127
+ .then(async () => {
128
+ if (!this.#journal) return
129
+ for (const { job, controller } of this.#jobs.values()) {
130
+ if (!controller) continue
131
+ if ((!terminal.has(job.state) || this.#previews.has(job.jobId)) && (await this.#journal.cancelled(job.jobId)))
132
+ this.cancel(job.jobId)
133
+ await this.#journal.save(job, this.#previews.has(job.jobId))
134
+ }
135
+ })
136
+ return this.#sync
137
+ }
138
+ async #dependenciesCurrent(job) {
139
+ const revisions = Object.entries(job.result?.sourceRevisions ?? {})
140
+ if (!revisions.length) return true
141
+ try {
142
+ const mappings = JSON.parse(await readFile(join(this.workspace.root, '.arcadia/debug-sources.json'), 'utf8'))
143
+ for (const [name, revision] of revisions) {
144
+ if (typeof mappings[name] !== 'string') return false
145
+ const source = await AuthorWorkspace.open(mappings[name], { watch: false })
146
+ try {
147
+ if ((await source.revision({ contentOnly: true })) !== revision) return false
148
+ } finally {
149
+ await source.close()
150
+ }
151
+ }
152
+ return true
153
+ } catch {
154
+ return false
155
+ }
156
+ }
157
+ async refresh() {
158
+ await this.#checkpoint()
159
+ if (!this.#journal) return
160
+ const revision = await this.workspace.revision()
161
+ const contentRevision = await this.workspace.revision({ contentOnly: true })
162
+ for (const { job } of this.#jobs.values())
163
+ if (terminal.has(job.state))
164
+ job.stale ||=
165
+ job.kind === 'preview'
166
+ ? job.contentRevision !== contentRevision || !(await this.#dependenciesCurrent(job))
167
+ : job.sourceRevision !== revision
168
+ await this.#refreshReceipts({ revision, contentRevision })
169
+ }
170
+ async #refreshReceipts(revisions) {
171
+ if (!this.#journal) return
172
+ const receipts = await this.#journal.read()
173
+ const present = new Set(receipts.map(receipt => receipt.job.jobId))
174
+ for (const [id, control] of this.#jobs) if (!control.controller && !present.has(id)) this.#jobs.delete(id)
175
+ for (const receipt of receipts) {
176
+ if (this.#jobs.get(receipt.job.jobId)?.controller) continue
177
+ receipt.job.stale ||= this.#jobs.get(receipt.job.jobId)?.job.stale ?? false
178
+ if (revisions)
179
+ receipt.job.stale ||=
180
+ receipt.job.kind === 'preview'
181
+ ? receipt.job.contentRevision !== revisions.contentRevision ||
182
+ !(await this.#dependenciesCurrent(receipt.job))
183
+ : receipt.job.sourceRevision !== revisions.revision
184
+ this.#jobs.set(receipt.job.jobId, { job: receipt.job, live: receipt.live })
185
+ }
186
+ }
187
+ async start({ kind, sourceRevision, environmentId = 'default' }) {
188
+ if (this.workspace.assertWritable) await this.workspace.assertWritable()
189
+ if (this.#closed) throw new WorkspaceError('WORKSPACE_CLOSED', '任务宿主已关闭')
190
+ if (!['check', 'test', 'demo', 'preview', 'pack'].includes(kind))
191
+ throw new WorkspaceError('TASK_INVALID', '不支持的作者任务')
192
+ if (kind !== 'check' && !this.execute) throw new WorkspaceError('EXECUTION_DISABLED', '此会话未启用项目代码执行')
193
+ if (this.#active) throw new WorkspaceError('TASK_BUSY', '请等待或取消当前任务')
194
+ if (kind === 'preview' && this.#previews.size >= 4)
195
+ throw new WorkspaceError('PREVIEW_LIMIT', '请先停止一个旧试玩,再准备新候选')
196
+ if (typeof environmentId !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,79}$/.test(environmentId))
197
+ throw new WorkspaceError('ENVIRONMENT_INVALID', '环境标识无效')
198
+ const jobId = randomUUID()
199
+ // Reserve before fingerprinting so concurrent starts cannot race.
200
+ this.#active = jobId
201
+ let started
202
+ this.#starting = new Promise(resolve => {
203
+ started = resolve
204
+ })
205
+ try {
206
+ const revision = await this.workspace.revision()
207
+ if (this.#closed) throw new WorkspaceError('WORKSPACE_CLOSED', '任务宿主已关闭')
208
+ if (sourceRevision && sourceRevision !== revision)
209
+ throw new WorkspaceError('REVISION_CONFLICT', '项目已改变,请重新读取')
210
+ const job = {
211
+ jobId,
212
+ kind,
213
+ sourceRevision: revision,
214
+ contentRevision: await this.workspace.revision({ contentOnly: true }),
215
+ environmentId,
216
+ preparationRevision: await this.workspace.revision({
217
+ contentOnly: true,
218
+ excludeFile:
219
+ environmentId === 'default' ? undefined : `debug/environments/${environmentId}.package-lock.json`,
220
+ }),
221
+ state: 'queued',
222
+ phase: 'queued',
223
+ stale: false,
224
+ output: '',
225
+ outputCursor: 0,
226
+ diagnostics: [],
227
+ createdAt: Date.now(),
228
+ }
229
+ const control = { job, controller: new AbortController() }
230
+ this.#jobs.set(jobId, control)
231
+ for (const [id, value] of this.#jobs) {
232
+ if (this.#jobs.size <= 30) break
233
+ if (terminal.has(value.job.state) && !this.#previews.has(id) && !value.live) {
234
+ this.#jobs.delete(id)
235
+ await this.#journal?.remove(id)
236
+ }
237
+ }
238
+ await this.#checkpoint()
239
+ control.done = this.#run(control).finally(() => {
240
+ this.#active = undefined
241
+ })
242
+ return this.get(jobId)
243
+ } catch (error) {
244
+ this.#jobs.delete(jobId)
245
+ this.#active = undefined
246
+ throw error
247
+ } finally {
248
+ started()
249
+ this.#starting = undefined
250
+ }
251
+ }
252
+ get(jobId) {
253
+ const control = this.#jobs.get(jobId)
254
+ if (!control) throw new WorkspaceError('TASK_UNKNOWN', '任务不存在或已过期')
255
+ return structuredClone(control.job)
256
+ }
257
+ list() {
258
+ return [...this.#jobs.keys()].map(id => this.get(id)).sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0))
259
+ }
260
+ /** Compact task discovery; listing never switches or replaces a desktop preview. */
261
+ async queryJobs({ offset = 0, limit = 20, state, kind } = {}) {
262
+ integer(offset, 0, Number.MAX_SAFE_INTEGER, 'offset')
263
+ integer(limit, 1, 100, 'limit')
264
+ if (state !== undefined && !['queued', 'running', ...terminal].includes(state)) queryError('任务状态无效')
265
+ if (kind !== undefined && !['check', 'test', 'demo', 'preview', 'pack'].includes(kind)) queryError('任务类型无效')
266
+ await this.refresh()
267
+ const rows = [...this.#jobs.values()]
268
+ .map(({ job }) => job)
269
+ .filter(job => (!state || job.state === state) && (!kind || job.kind === kind))
270
+ .sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0) || a.jobId.localeCompare(b.jobId))
271
+ return {
272
+ total: rows.length,
273
+ offset,
274
+ nextOffset: offset + limit < rows.length ? offset + limit : null,
275
+ items: rows.slice(offset, offset + limit).map(job => jobSummary(job)),
276
+ }
277
+ }
278
+ /** Wait for changes without repeatedly hashing every project file. */
279
+ async queryJob({ jobId, waitMs = 0, afterCursor, includeOutput = false, limit = 16384 } = {}) {
280
+ integer(waitMs, 0, 10000, 'waitMs')
281
+ integer(limit, 1, 65536, 'limit')
282
+ if (afterCursor !== undefined) integer(afterCursor, 0, Number.MAX_SAFE_INTEGER, 'afterCursor')
283
+ if (typeof includeOutput !== 'boolean') queryError('includeOutput 需要布尔值')
284
+ await this.refresh()
285
+ let job = this.get(jobId)
286
+ if (afterCursor !== undefined && afterCursor > outputRange(job).end) queryError('日志游标超出当前输出')
287
+ const observed = JSON.stringify(jobSummary(job, true))
288
+ const deadline = Date.now() + waitMs
289
+ while (
290
+ !this.#closed &&
291
+ !terminal.has(job.state) &&
292
+ (afterCursor === undefined || outputRange(job).end <= afterCursor) &&
293
+ JSON.stringify(jobSummary(job, true)) === observed &&
294
+ Date.now() < deadline
295
+ ) {
296
+ await this.#wait(Math.min(250, deadline - Date.now()))
297
+ // Peer receipts are checkpointed by their owner. This does not mutate peer tasks.
298
+ await this.#refreshReceipts()
299
+ job = this.get(jobId)
300
+ }
301
+ const summary = jobSummary(job, true)
302
+ if (includeOutput) summary.output = this.#output(jobId, afterCursor ?? 0, limit)
303
+ return summary
304
+ }
305
+ async readJobOutput({ jobId, cursor = 0, limit = 16384 } = {}) {
306
+ integer(cursor, 0, Number.MAX_SAFE_INTEGER, 'cursor')
307
+ integer(limit, 1, 65536, 'limit')
308
+ await this.#refreshReceipts()
309
+ return this.#output(jobId, cursor, limit)
310
+ }
311
+ #output(jobId, cursor, limit) {
312
+ const { text, start, end } = outputRange(this.get(jobId))
313
+ if (cursor > end) queryError('日志游标超出当前输出')
314
+ const first = Math.max(cursor, start)
315
+ const nextCursor = Math.min(first + limit, end)
316
+ return {
317
+ jobId,
318
+ text: text.slice(first - start, nextCursor - start),
319
+ cursor: first,
320
+ nextCursor,
321
+ endCursor: end,
322
+ truncated: cursor < start,
323
+ hasMore: nextCursor < end,
324
+ unit: 'utf16',
325
+ }
326
+ }
327
+ #notify() {
328
+ for (const wake of this.#waiters) wake()
329
+ }
330
+ #wait(milliseconds) {
331
+ return new Promise(resolve => {
332
+ const wake = () => {
333
+ clearTimeout(timer)
334
+ this.#waiters.delete(wake)
335
+ resolve()
336
+ }
337
+ const timer = setTimeout(wake, milliseconds)
338
+ this.#waiters.add(wake)
339
+ })
340
+ }
341
+ cancel(jobId) {
342
+ const control = this.#jobs.get(jobId)
343
+ if (!control) throw new WorkspaceError('TASK_UNKNOWN', '任务不存在')
344
+ if (!control.controller) {
345
+ if (!terminal.has(control.job.state) || control.live)
346
+ return this.#journal.requestCancel(jobId).then(() => this.get(jobId))
347
+ return this.get(jobId)
348
+ }
349
+ if (!terminal.has(control.job.state) || this.#previews.has(jobId)) {
350
+ control.controller.abort()
351
+ if (this.#previews.has(jobId)) control.job.state = 'cancelled'
352
+ this.#notify()
353
+ }
354
+ return this.get(jobId)
355
+ }
356
+ async #run({ job, controller }) {
357
+ const signal = controller.signal
358
+ const timeout = setTimeout(() => controller.abort(), 180000)
359
+ let state = 'succeeded'
360
+ let capture
361
+ try {
362
+ job.state = 'running'
363
+ job.phase = 'preparing'
364
+ this.#notify()
365
+ if (job.kind === 'preview') {
366
+ capture = await mkdtemp(join(tmpdir(), 'arcadia-author-candidate-'))
367
+ for (const entry of await this.workspace.files()) {
368
+ if (signal.aborted) throw new WorkspaceError('TASK_CANCELLED', '任务已取消')
369
+ if (entry.error) throw new WorkspaceError('SOURCE_INVALID', entry.error, entry.file)
370
+ const target = join(capture, entry.file)
371
+ await mkdir(dirname(target), { recursive: true })
372
+ await cp(await this.workspace.path(entry.file), target)
373
+ }
374
+ await symlink(
375
+ join(this.workspace.root, 'node_modules'),
376
+ join(capture, 'node_modules'),
377
+ process.platform === 'win32' ? 'junction' : 'dir',
378
+ )
379
+ if ((await this.workspace.revision({ contentOnly: true })) !== job.contentRevision)
380
+ throw new WorkspaceError('PREVIEW_STALE', '复制候选期间源码已改变,请重试')
381
+ }
382
+ if (job.kind === 'check') {
383
+ const snapshot = await this.workspace.snapshot()
384
+ job.diagnostics.push(...snapshot.diagnostics)
385
+ if (snapshot.diagnostics.length) throw new WorkspaceError('CHECK_FAILED', '源数据检查失败')
386
+ await this.#process([cli, 'check'], job, signal)
387
+ } else if (job.kind === 'pack') await this.#process([cli, 'pack'], job, signal)
388
+ else {
389
+ await this.#process([cli, 'build'], job, signal, false, capture)
390
+ if (job.kind === 'demo' || job.kind === 'preview')
391
+ await this.#process([cli, job.kind], job, signal, job.kind === 'preview', capture)
392
+ else {
393
+ const files = (await this.workspace.files()).filter(entry =>
394
+ /^(test|tests)\/.+\.test\.(mjs|js|cjs)$/.test(entry.file),
395
+ )
396
+ if (!files.length)
397
+ throw new WorkspaceError('TESTS_MISSING', '未发现 test/ 或 tests/ 下的 *.test.mjs/js/cjs 场景')
398
+ await this.#process(['--test', '--test-reporter=tap', ...files.map(entry => entry.file)], job, signal)
399
+ }
400
+ }
401
+ } catch (error) {
402
+ state = signal.aborted ? 'cancelled' : 'failed'
403
+ job.diagnostics.push(diagnostic(error))
404
+ } finally {
405
+ clearTimeout(timeout)
406
+ try {
407
+ if (job.kind === 'preview' && job.result?.environmentLock) {
408
+ const expected = job.result.environmentLock
409
+ const actual = await this.workspace.read(expected.file)
410
+ const revision = await this.workspace.revision({ contentOnly: true, excludeFile: expected.file })
411
+ if (actual.version === expected.version && revision === job.preparationRevision)
412
+ job.contentRevision = await this.workspace.revision({ contentOnly: true })
413
+ }
414
+ job.stale =
415
+ job.kind === 'preview'
416
+ ? (await this.workspace.revision({ contentOnly: true })) !== job.contentRevision ||
417
+ !(await this.#dependenciesCurrent(job))
418
+ : (await this.workspace.revision()) !== job.sourceRevision
419
+ if (job.stale && job.kind === 'preview') {
420
+ controller.abort()
421
+ state = 'failed'
422
+ job.diagnostics.push(diagnostic(new WorkspaceError('PREVIEW_STALE', '准备期间源码已改变,请重新试玩')))
423
+ }
424
+ } catch (error) {
425
+ job.stale = true
426
+ job.diagnostics.push(diagnostic(error))
427
+ }
428
+ job.finishedAt = new Date().toISOString()
429
+ if (capture && !this.#previews.has(job.jobId)) await rm(capture, { recursive: true, force: true })
430
+ job.state = state
431
+ job.phase = state === 'succeeded' && job.kind === 'preview' ? 'ready' : 'finished'
432
+ this.#notify()
433
+ }
434
+ }
435
+ async #process(args, job, signal, preview = false, capture) {
436
+ if (signal.aborted) throw new WorkspaceError('TASK_CANCELLED', '任务已取消')
437
+ job.phase =
438
+ { check: 'checking', build: 'building', pack: 'packing', preview: 'starting-preview', demo: 'running-demo' }[
439
+ args[1]
440
+ ] ?? 'testing'
441
+ this.#notify()
442
+ await new Promise((resolve, reject) => {
443
+ const child = spawn(this.executable, args, {
444
+ cwd: capture ?? this.workspace.root,
445
+ env: {
446
+ ...this.env,
447
+ ELECTRON_RUN_AS_NODE: '1',
448
+ ARCADIA_AUTHOR_RESULT: '1',
449
+ ...(preview ? { ARCADIA_DEBUG_ENVIRONMENT: job.environmentId, ARCADIA_DEBUG_ROOT: this.workspace.root } : {}),
450
+ },
451
+ stdio: ['ignore', 'pipe', 'pipe', ...(preview ? ['ipc'] : [])],
452
+ windowsHide: true,
453
+ detached: process.platform !== 'win32',
454
+ })
455
+ let killTimer
456
+ const kill = force => {
457
+ try {
458
+ if (process.platform !== 'win32') process.kill(-child.pid, force ? 'SIGKILL' : 'SIGTERM')
459
+ else child.kill(force ? 'SIGKILL' : 'SIGTERM')
460
+ } catch {
461
+ /* Already exited. */
462
+ }
463
+ }
464
+ const abort = () => {
465
+ kill(false)
466
+ killTimer = setTimeout(() => kill(true), 1500)
467
+ }
468
+ signal.addEventListener('abort', abort, { once: true })
469
+ if (signal.aborted) abort()
470
+ let buffer = '',
471
+ ready = false
472
+ const output = text => {
473
+ if (!text) return
474
+ job.outputCursor = outputRange(job).end + text.length
475
+ job.output = (job.output + text).slice(-outputLimit)
476
+ this.#notify()
477
+ if (!preview || ready) return
478
+ buffer += text
479
+ let newline
480
+ while ((newline = buffer.indexOf('\n')) >= 0) {
481
+ const line = buffer.slice(0, newline)
482
+ buffer = buffer.slice(newline + 1)
483
+ if (!line.startsWith('ARCADIA_RESULT=')) continue
484
+ try {
485
+ const result = JSON.parse(line.slice('ARCADIA_RESULT='.length))
486
+ if (!result.preview?.endpoint || signal.aborted) continue
487
+ job.result = result
488
+ ready = true
489
+ resolve()
490
+ } catch {
491
+ /* Preserve incomplete or malformed output for diagnosis. */
492
+ }
493
+ }
494
+ }
495
+ let finished
496
+ if (preview)
497
+ this.#previews.set(
498
+ job.jobId,
499
+ new Promise(resolve => {
500
+ finished = resolve
501
+ }),
502
+ )
503
+ for (const stream of [child.stdout, child.stderr]) {
504
+ const decoder = new StringDecoder('utf8')
505
+ stream.on('data', chunk => output(decoder.write(chunk)))
506
+ stream.on('end', () => output(decoder.end()))
507
+ }
508
+ child.once('error', reject)
509
+ child.once('close', code => {
510
+ if (preview) {
511
+ this.#previews.delete(job.jobId)
512
+ const released = capture ? rm(capture, { recursive: true, force: true }) : Promise.resolve()
513
+ void released.then(finished, error => {
514
+ job.diagnostics.push(diagnostic(error))
515
+ finished()
516
+ })
517
+ if (ready) {
518
+ job.state = signal.aborted ? 'cancelled' : 'failed'
519
+ this.#notify()
520
+ if (!signal.aborted)
521
+ job.diagnostics.push(diagnostic(new WorkspaceError('PREVIEW_EXITED', '试玩进程已退出,请重新准备')))
522
+ }
523
+ }
524
+ clearTimeout(killTimer)
525
+ signal.removeEventListener('abort', abort)
526
+ for (const raw of job.output.split('\n')) {
527
+ const line = raw.replace(/^# /, '')
528
+ if (line.startsWith('ARCADIA_RESULT=')) {
529
+ try {
530
+ job.result = JSON.parse(line.slice('ARCADIA_RESULT='.length))
531
+ } catch {
532
+ /* Keep malformed output in the log. */
533
+ }
534
+ }
535
+ const match = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.+)$/.exec(line)
536
+ if (match)
537
+ job.diagnostics.push({
538
+ code: match[4],
539
+ severity: 'error',
540
+ file: match[1],
541
+ line: Number(match[2]),
542
+ column: Number(match[3]),
543
+ message: match[5],
544
+ })
545
+ }
546
+ if (code === 0 && !signal.aborted) resolve()
547
+ else
548
+ reject(
549
+ new WorkspaceError(
550
+ signal.aborted ? 'TASK_CANCELLED' : 'TASK_FAILED',
551
+ signal.aborted ? '任务已取消或超过三分钟' : `作者命令失败(${code}),请查看诊断与输出`,
552
+ ),
553
+ )
554
+ })
555
+ })
556
+ }
557
+ /** Stop previews owned by this host and wait for their processes and temporary files to be released. */
558
+ async stopPreviews() {
559
+ await this.#starting
560
+ const previews = [...this.#jobs.values()].filter(({ job, controller }) => job.kind === 'preview' && controller)
561
+ const released = [...this.#previews.values()]
562
+ for (const { job } of previews) this.cancel(job.jobId)
563
+ await Promise.allSettled(previews.map(control => control.done))
564
+ await Promise.allSettled([...released, ...this.#previews.values()])
565
+ }
566
+ async close() {
567
+ this.#closed = true
568
+ this.#notify()
569
+ this.workspace.off('change', this.#changed)
570
+ await this.#starting
571
+ clearInterval(this.#timer)
572
+ for (const control of this.#jobs.values())
573
+ if (control.controller && (!terminal.has(control.job.state) || this.#previews.has(control.job.jobId)))
574
+ control.controller.abort()
575
+ await Promise.allSettled([...this.#jobs.values()].map(control => control.done))
576
+ await Promise.allSettled([...this.#previews.values()])
577
+ await this.#checkpoint()
578
+ }
579
+ }
@@ -0,0 +1,95 @@
1
+ import { readFile, readdir } from 'node:fs/promises'
2
+ import { extname, join, relative } from 'node:path'
3
+ import YAML from 'yaml'
4
+ import { isDeepStrictEqual } from 'node:util'
5
+
6
+ const contentKinds = ['species', 'skills', 'marks', 'behaviors']
7
+ const sourceKinds = [...contentKinds, 'presentations', 'resources']
8
+
9
+ async function filesIn(directory) {
10
+ let entries
11
+ try {
12
+ entries = await readdir(directory, { withFileTypes: true })
13
+ } catch (error) {
14
+ if (error.code === 'ENOENT') return []
15
+ throw error
16
+ }
17
+ const files = []
18
+ for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
19
+ if (entry.name.startsWith('.')) continue
20
+ const file = join(directory, entry.name)
21
+ if (entry.isDirectory()) files.push(...(await filesIn(file)))
22
+ else if (entry.isSymbolicLink()) throw new Error(`Content sources must be ordinary files: ${file}`)
23
+ else if (['.json', '.yaml', '.yml'].includes(extname(entry.name))) files.push(file)
24
+ }
25
+ return files
26
+ }
27
+
28
+ /** Editable source files; each file may hold one record or an array of records. */
29
+ export async function readContentSources(root) {
30
+ const directory = join(root, 'data')
31
+ const base = await readFile(join(root, 'pack.json'), 'utf8')
32
+ .then(JSON.parse)
33
+ .catch(error => {
34
+ if (error.code === 'ENOENT') return undefined
35
+ throw error
36
+ })
37
+ const entries = await readdir(directory, { withFileTypes: true })
38
+ for (const entry of entries) {
39
+ if (!base && entry.isDirectory() && !entry.name.startsWith('.') && !sourceKinds.includes(entry.name))
40
+ throw new Error(`Unknown content directory: data/${entry.name}`)
41
+ }
42
+ const sources = []
43
+ for (const kind of sourceKinds) {
44
+ const ids = new Map()
45
+ for (const file of base && contentKinds.includes(kind)
46
+ ? (base.data[kind] ?? []).map(file => join(directory, file))
47
+ : await filesIn(join(directory, kind))) {
48
+ const name = relative(root, file)
49
+ const text = await readFile(file, 'utf8')
50
+ let document, value
51
+ try {
52
+ if (extname(file) === '.json') value = JSON.parse(text)
53
+ else {
54
+ document = YAML.parseDocument(text, { merge: true })
55
+ if (document.errors.length) throw document.errors[0]
56
+ value = document.toJS()
57
+ }
58
+ if (!isDeepStrictEqual(JSON.parse(JSON.stringify(value)), value))
59
+ throw new Error('Content values must be finite JSON-compatible data')
60
+ } catch (error) {
61
+ throw new Error(`Invalid content in ${name}: ${error.message}`, { cause: error })
62
+ }
63
+ const records = Array.isArray(value) ? value : [value]
64
+ for (const record of records) {
65
+ if (
66
+ !record ||
67
+ typeof record !== 'object' ||
68
+ Array.isArray(record) ||
69
+ typeof record.id !== 'string' ||
70
+ !record.id
71
+ )
72
+ throw new Error(`Each record needs an id: ${name}`)
73
+ if (ids.has(record.id)) throw new Error(`Duplicate ${kind} id ${record.id}: ${ids.get(record.id)} and ${name}`)
74
+ ids.set(record.id, name)
75
+ }
76
+ sources.push({ kind, file, text, document, value, records })
77
+ }
78
+ }
79
+ return sources
80
+ }
81
+
82
+ /** File names and grouping do not enter runtime IDs or record ordering. */
83
+ export function assembleContent(sources) {
84
+ return {
85
+ data: Object.fromEntries(
86
+ contentKinds.map(kind => [
87
+ kind,
88
+ sources
89
+ .filter(source => source.kind === kind)
90
+ .flatMap(source => source.records)
91
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)),
92
+ ]),
93
+ ),
94
+ }
95
+ }