@arcadia-eternity/content-sdk 0.0.0-stage → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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
@@ -0,0 +1,240 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { lstat, readdir, readFile } from 'node:fs/promises'
3
+ import { join, relative, extname } from 'node:path'
4
+ import YAML from 'yaml'
5
+
6
+ const maximumBytes = 64 * 1024 * 1024
7
+ const mimeTypes = {
8
+ '.png': 'image/png',
9
+ '.jpg': 'image/jpeg',
10
+ '.jpeg': 'image/jpeg',
11
+ '.webp': 'image/webp',
12
+ '.ogg': 'audio/ogg',
13
+ '.mp3': 'audio/mpeg',
14
+ '.swf': 'application/x-shockwave-flash',
15
+ }
16
+ const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)
17
+ const remote = value => /^https?:\/\//.test(value)
18
+ export function resourceReferences(presentation) {
19
+ if (!presentation) return []
20
+ if (typeof presentation !== 'object' || Array.isArray(presentation)) throw new Error('presentation must be an object')
21
+ const keys = ['icon', 'portrait', 'cry', 'sfx', 'background', 'music', 'battle']
22
+ for (const key of Object.keys(presentation))
23
+ if (!keys.includes(key)) throw new Error(`Unknown presentation field: ${key}`)
24
+ const refs = keys
25
+ .filter(key => key !== 'battle')
26
+ .flatMap(key => (presentation[key] === undefined ? [] : [presentation[key]]))
27
+ if (presentation.battle) {
28
+ const battle = presentation.battle
29
+ if (
30
+ !['image', 'seer2-swf'].includes(battle.renderer) ||
31
+ !battle.source ||
32
+ Object.keys(battle).some(key => !['renderer', 'source', 'fallback'].includes(key))
33
+ )
34
+ throw new Error('Invalid battle presentation')
35
+ refs.push(battle.source)
36
+ if (battle.fallback !== undefined) refs.push(battle.fallback)
37
+ }
38
+ for (const ref of refs) {
39
+ if (typeof ref === 'string' && validResourceId(ref)) continue
40
+ if (
41
+ ref &&
42
+ typeof ref === 'object' &&
43
+ !Array.isArray(ref) &&
44
+ typeof ref.namespace === 'string' &&
45
+ ref.namespace &&
46
+ typeof ref.id === 'string' &&
47
+ validResourceId(ref.id) &&
48
+ Object.keys(ref).every(key => ['namespace', 'id'].includes(key))
49
+ )
50
+ continue
51
+ throw new Error(`Invalid presentation resource: ${JSON.stringify(ref)}`)
52
+ }
53
+ return refs
54
+ }
55
+ export const validResourceId = value => typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/.test(value)
56
+ export function validAssetPath(value) {
57
+ return (
58
+ typeof value === 'string' &&
59
+ !value.startsWith('/') &&
60
+ !value.includes(':') &&
61
+ !value.split('/').some(part => ['node_modules', '.git', '.arcadia', 'dist'].includes(part)) &&
62
+ !value.includes('\\') &&
63
+ !value.includes('\0') &&
64
+ value.split('/').every(part => part && part !== '.' && part !== '..')
65
+ )
66
+ }
67
+ async function files(root, directory) {
68
+ let entries
69
+ try {
70
+ const info = await lstat(directory)
71
+ if (!info.isDirectory() || info.isSymbolicLink())
72
+ throw new Error(`Presentation directory must be an ordinary directory: ${relative(root, directory)}`)
73
+ entries = await readdir(directory, { withFileTypes: true })
74
+ } catch (error) {
75
+ if (error.code === 'ENOENT') return []
76
+ throw error
77
+ }
78
+ const output = []
79
+ for (const entry of entries.sort((a, b) => compare(a.name, b.name))) {
80
+ if (entry.name.startsWith('.')) continue
81
+ const path = join(directory, entry.name)
82
+ if (entry.isSymbolicLink()) throw new Error(`Presentation sources must be ordinary files: ${relative(root, path)}`)
83
+ if (entry.isDirectory()) output.push(...(await files(root, path)))
84
+ else if (entry.isFile()) output.push(path)
85
+ }
86
+ return output
87
+ }
88
+ export function bindingPresentation(binding) {
89
+ const { id: _id, target: _target, ...presentation } = binding
90
+ return presentation
91
+ }
92
+ function validateBinding(binding, sources) {
93
+ if (
94
+ !binding.target ||
95
+ !['species', 'skills', 'marks'].includes(binding.target.kind) ||
96
+ typeof binding.target.id !== 'string' ||
97
+ Object.keys(binding.target).some(key => !['kind', 'id'].includes(key))
98
+ )
99
+ throw new Error(`Invalid presentation target: ${binding.id}`)
100
+ if (
101
+ !sources.some(
102
+ source => source.kind === binding.target.kind && source.records.some(row => row.id === binding.target.id),
103
+ )
104
+ )
105
+ throw new Error(`Missing presentation target: ${binding.target.kind}/${binding.target.id}`)
106
+ return resourceReferences(bindingPresentation(binding))
107
+ }
108
+ /** Read only declared files. References are IDs; locations never become resource identities. */
109
+ export async function buildPresentation(root, sources, { includeLocales = true } = {}) {
110
+ const resources = []
111
+ const definitions = sources.filter(source => source.kind === 'resources')
112
+ for (const source of definitions)
113
+ for (const record of source.records) {
114
+ const { id, source: location, kind, name: _name } = record
115
+ if (
116
+ !validResourceId(id) ||
117
+ !['image', 'audio', 'swf'].includes(kind) ||
118
+ typeof location !== 'string' ||
119
+ Object.keys(record).some(key => !['id', 'source', 'kind', 'name', 'tags'].includes(key)) ||
120
+ (record.name !== undefined && typeof record.name !== 'string') ||
121
+ (record.tags !== undefined && (!Array.isArray(record.tags) || record.tags.some(tag => typeof tag !== 'string')))
122
+ )
123
+ throw new Error(`${relative(root, source.file)}: Invalid resource definition ${id}`)
124
+ const url = remote(location) ? new URL(location) : undefined
125
+ if (url && (url.username || url.password)) throw new Error(`Resource URL must not contain credentials: ${id}`)
126
+ const mime = mimeTypes[extname(url ? url.pathname : location).toLowerCase()]
127
+ if (
128
+ !mime ||
129
+ (kind === 'image'
130
+ ? !mime.startsWith('image/')
131
+ : kind === 'audio'
132
+ ? !mime.startsWith('audio/')
133
+ : mime !== 'application/x-shockwave-flash')
134
+ )
135
+ throw new Error(`Resource type does not match source: ${id}`)
136
+ if (url) {
137
+ resources.push({ kind: 'http', id, source: location, mime, ...(record.tags ? { tags: record.tags } : {}) })
138
+ continue
139
+ }
140
+ if (!validAssetPath(location)) throw new Error(`Invalid resource path: ${id}`)
141
+ let path = root
142
+ for (const part of location.split('/')) {
143
+ path = join(path, part)
144
+ if ((await lstat(path)).isSymbolicLink()) throw new Error(`Resource must not use symbolic links: ${id}`)
145
+ }
146
+ const info = await lstat(path)
147
+ if (!info.isFile() || !info.size || info.size > maximumBytes) throw new Error(`Resource size invalid: ${id}`)
148
+ const bytes = await readFile(path)
149
+ if (!bytes.length || bytes.length > maximumBytes) throw new Error(`Resource size invalid: ${id}`)
150
+ resources.push({
151
+ kind: 'file',
152
+ id,
153
+ source: location,
154
+ sha256: createHash('sha256').update(bytes).digest('hex'),
155
+ bytes: bytes.length,
156
+ mime,
157
+ ...(record.tags ? { tags: record.tags } : {}),
158
+ })
159
+ }
160
+ const ids = new Set(resources.map(row => row.id))
161
+ const kinds = new Map(definitions.flatMap(source => source.records).map(row => [row.id, row.kind]))
162
+ const bindings = []
163
+ const targets = new Set()
164
+ for (const source of sources)
165
+ for (const record of source.records) {
166
+ if (
167
+ !['presentations', 'resources'].includes(source.kind) &&
168
+ ['presentation', 'assetRef', 'iconRef', 'sfxRef'].some(key => key in record)
169
+ )
170
+ throw new Error(
171
+ `${relative(root, source.file)}: Move presentation into data/presentations and resources into data/resources`,
172
+ )
173
+ if (source.kind !== 'presentations') continue
174
+ try {
175
+ const refs = validateBinding(record, sources)
176
+ const target = JSON.stringify([record.target.kind, record.target.id])
177
+ if (targets.has(target)) throw new Error(`Duplicate presentation target: ${target}`)
178
+ targets.add(target)
179
+ for (const ref of refs) if (typeof ref === 'string' && !ids.has(ref)) throw new Error(`Missing resource ${ref}`)
180
+ const kindOf = ref => (typeof ref === 'string' ? kinds.get(ref) : undefined)
181
+ const presentation = bindingPresentation(record)
182
+ for (const [slot, ref] of Object.entries(presentation)) {
183
+ if (slot === 'battle') {
184
+ if (kindOf(ref.source) && kindOf(ref.source) !== (ref.renderer === 'image' ? 'image' : 'swf'))
185
+ throw new Error('Battle resource type mismatch')
186
+ if (kindOf(ref.fallback) && kindOf(ref.fallback) !== 'image') throw new Error('Fallback must be an image')
187
+ } else if (kindOf(ref) && kindOf(ref) !== (['sfx', 'cry', 'music'].includes(slot) ? 'audio' : 'image'))
188
+ throw new Error(`Resource type mismatch: ${slot}`)
189
+ }
190
+ bindings.push(record)
191
+ } catch (error) {
192
+ throw new Error(`${relative(root, source.file)}: ${error.message}`, { cause: error })
193
+ }
194
+ }
195
+ const locales = {}
196
+ for (const file of includeLocales ? await files(root, join(root, 'locales')) : []) {
197
+ const path = relative(join(root, 'locales'), file).split('\\').join('/')
198
+ const match = /^([A-Za-z0-9-]+)\/([A-Za-z0-9_-]+)\.(json|ya?ml)$/.exec(path)
199
+ if (!match) throw new Error(`Expected locales/<language>/<namespace>.json|yaml: ${path}`)
200
+ const [, language, namespace] = match
201
+ const canonicalLanguage = Intl.getCanonicalLocales(language)[0]
202
+ const text = await readFile(file, 'utf8')
203
+ const value = match[3] === 'json' ? JSON.parse(text) : YAML.parse(text, { uniqueKeys: true, merge: true })
204
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`Expected locale object: ${path}`)
205
+ const records = {
206
+ species: 'species',
207
+ skill: 'skills',
208
+ mark: 'marks',
209
+ mark_ability: 'marks',
210
+ mark_emblem: 'marks',
211
+ mark_global: 'marks',
212
+ }[namespace]
213
+ if (!records) throw new Error(`Unsupported content locale namespace: ${path}`)
214
+ const ids = new Set(
215
+ sources.filter(source => source.kind === records).flatMap(source => source.records.map(record => record.id)),
216
+ )
217
+ for (const [id, entry] of Object.entries(value)) {
218
+ if (!ids.has(id)) throw new Error(`${path}: Unknown content ID ${id}`)
219
+ if (
220
+ !entry ||
221
+ typeof entry !== 'object' ||
222
+ Array.isArray(entry) ||
223
+ Object.entries(entry).some(
224
+ ([field, text]) => !['name', 'description'].includes(field) || typeof text !== 'string',
225
+ )
226
+ )
227
+ throw new Error(`${path}: Expected name/description strings for ${id}`)
228
+ }
229
+ const target = (locales[canonicalLanguage] ??= {})
230
+ if (Object.hasOwn(target, namespace)) throw new Error(`Duplicate locale namespace: ${path}`)
231
+ target[namespace] = value
232
+ }
233
+ return {
234
+ version: 2,
235
+ bindings: bindings.sort((a, b) => compare(a.id, b.id)),
236
+ defaultLocale: 'zh-CN',
237
+ resources: resources.sort((a, b) => compare(a.id, b.id)),
238
+ locales,
239
+ }
240
+ }
@@ -0,0 +1,101 @@
1
+ import YAML from 'yaml'
2
+ import { isDeepStrictEqual } from 'node:util'
3
+
4
+ const mergeKey = pair =>
5
+ YAML.isScalar(pair.key) && typeof pair.key.value === 'symbol' && pair.key.value.description === '<<'
6
+ const prefix = (parent, child) => parent.every((part, index) => part === child[index])
7
+
8
+ /** Source-level sharing, before conversion to plain values loses provenance. */
9
+ export function yamlSharing(doc, lineCounter) {
10
+ if (!doc) return []
11
+ const paths = new Map(),
12
+ referenced = new Set(),
13
+ fields = []
14
+ function index(node, path) {
15
+ if (!YAML.isNode(node)) return
16
+ paths.set(node, path)
17
+ if (YAML.isAlias(node)) referenced.add(node.resolve(doc))
18
+ if (YAML.isSeq(node)) node.items.forEach((item, i) => index(item, [...path, i]))
19
+ if (YAML.isMap(node)) for (const pair of node.items) index(pair.value, [...path, String(pair.key.value)])
20
+ }
21
+ index(doc.contents, [])
22
+ function add(path, reason, source) {
23
+ const location = lineCounter && source.range ? lineCounter.linePos(source.range[0]) : undefined
24
+ fields.push({
25
+ path,
26
+ reason,
27
+ anchor: source.anchor ?? '',
28
+ sourcePath: paths.get(source) ?? [],
29
+ ...(location ? { line: location.line, column: location.col } : {}),
30
+ })
31
+ }
32
+ // Merge sequences use the first mapping that supplies a key; local keys win.
33
+ function effective(node, seen = new Set(), origin = node) {
34
+ if (YAML.isAlias(node)) {
35
+ const target = node.resolve(doc)
36
+ return effective(target, seen, target)
37
+ }
38
+ if (YAML.isSeq(node) && !seen.has(node)) {
39
+ const result = new Map()
40
+ for (const item of node.items)
41
+ for (const [key, from] of effective(item, new Set([...seen, node]))) if (!result.has(key)) result.set(key, from)
42
+ return result
43
+ }
44
+ if (!YAML.isMap(node) || seen.has(node)) return new Map()
45
+ seen = new Set([...seen, node])
46
+ const result = new Map()
47
+ for (const pair of node.items.filter(mergeKey)) {
48
+ const sources = YAML.isSeq(pair.value) ? pair.value.items : [pair.value]
49
+ for (const source of sources)
50
+ for (const [key, from] of effective(source, seen)) if (!result.has(key)) result.set(key, from)
51
+ }
52
+ for (const pair of node.items.filter(pair => !mergeKey(pair))) result.set(String(pair.key.value), origin)
53
+ return result
54
+ }
55
+ function walk(node, path) {
56
+ if (YAML.isAlias(node)) {
57
+ add(path, 'alias', node.resolve(doc))
58
+ return
59
+ }
60
+ if (!YAML.isNode(node)) return
61
+ if (node.anchor && referenced.has(node)) {
62
+ add(path, 'anchor', node)
63
+ return
64
+ }
65
+ if (YAML.isSeq(node)) node.items.forEach((item, i) => walk(item, [...path, i]))
66
+ if (YAML.isMap(node)) {
67
+ const local = new Set(node.items.filter(pair => !mergeKey(pair)).map(pair => String(pair.key.value)))
68
+ for (const [key, source] of effective(node)) if (!local.has(key)) add([...path, key], 'merge', source)
69
+ for (const pair of node.items.filter(pair => !mergeKey(pair))) walk(pair.value, [...path, String(pair.key.value)])
70
+ }
71
+ }
72
+ walk(doc.contents, [])
73
+ return fields
74
+ }
75
+
76
+ export function recordSharing(fields, index) {
77
+ const root = index === null ? [] : [index]
78
+ return fields
79
+ .filter(field => prefix(root, field.path) || prefix(field.path, root))
80
+ .map(field => ({
81
+ ...field,
82
+ path: field.path.slice(root.length),
83
+ }))
84
+ }
85
+
86
+ export function changedSharedField(fields, before, after) {
87
+ const at = (value, path) => path.reduce((value, key) => value?.[key], value)
88
+ return fields.find(field => !isDeepStrictEqual(at(before, field.path), at(after, field.path)))
89
+ }
90
+
91
+ /** Detect accidental alias expansion or anchor loss during structural updates. */
92
+ export function sharingSignature(doc) {
93
+ const result = []
94
+ YAML.visit(doc, {
95
+ Node(_key, node) {
96
+ if (node.anchor) result.push(['anchor', node.anchor])
97
+ if (YAML.isAlias(node)) result.push(['alias', node.source])
98
+ },
99
+ })
100
+ return result
101
+ }
@@ -0,0 +1,35 @@
1
+ import type { ContentWorkspace, EnvironmentVersion, StaticPreparer, PrepareVersionInput } from './content-workspace.mjs'
2
+ import type { ManagedSource } from './managed-sources.mjs'
3
+ export interface ManagedProjectsOptions {
4
+ registry?: string
5
+ offline?: boolean
6
+ /** Host permission to acquire metadata/materials; never grants authority to execute them. */
7
+ allowThirdPartyContent?: boolean
8
+ sources?: Record<string, ManagedSource>
9
+ npmUserConfig?: string
10
+ timeoutMs?: number
11
+ maxBytes?: number
12
+ maxFiles?: number
13
+ maxConcurrent?: number
14
+ }
15
+ export class ManagedProjects {
16
+ readonly root: string
17
+ constructor(root: string, options?: ManagedProjectsOptions)
18
+ prepareProject<T>(
19
+ document: unknown,
20
+ input: { signal?: AbortSignal; onProgress?: PrepareVersionInput['onProgress'] },
21
+ consume: (directory: string, signal: AbortSignal) => Promise<T>,
22
+ ): Promise<T>
23
+ prepareVersion(
24
+ workspace: ContentWorkspace,
25
+ input: {
26
+ onProgress?: PrepareVersionInput['onProgress']
27
+ environmentId: string
28
+ expectedRevision: string
29
+ signal?: AbortSignal
30
+ beforeCommit?: () => Promise<void>
31
+ },
32
+ validate: StaticPreparer,
33
+ ): Promise<EnvironmentVersion>
34
+ close(): Promise<void>
35
+ }
@@ -0,0 +1,303 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises'
3
+ import { join, resolve } from 'node:path'
4
+ import { promisify } from 'node:util'
5
+ import { valid, validRange } from 'semver'
6
+ import { inspectNpmProject, resolveNpmInvocation } from '@arcadia-eternity/pack-loader/node'
7
+ import { normalizeEnvironmentDocument } from './debug-environments.mjs'
8
+ import { acquireSource } from './managed-sources.mjs'
9
+ import { contentError, materialFiles } from './workspace-materials.mjs'
10
+
11
+ const execute = promisify(execFile)
12
+ const DEFAULT_TIMEOUT = 120_000
13
+ const DEFAULT_BYTES = 256 * 1024 * 1024
14
+ const packageName = /^(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*$/
15
+
16
+ function limit(value, fallback, maximum) {
17
+ const result = value ?? fallback
18
+ if (!Number.isSafeInteger(result) || result < 1 || result > maximum) throw contentError('INSTALL_LIMIT_INVALID')
19
+ return result
20
+ }
21
+ function registryUrl(value) {
22
+ const url = new URL(value ?? 'https://registry.npmjs.org/')
23
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash)
24
+ throw contentError('INSTALL_REGISTRY_INVALID')
25
+ return url.href
26
+ }
27
+ function checkDependencySpecs(manifest) {
28
+ for (const field of ['dependencies', 'optionalDependencies', 'peerDependencies']) {
29
+ if (manifest[field] === undefined) continue
30
+ if (!manifest[field] || typeof manifest[field] !== 'object' || Array.isArray(manifest[field]))
31
+ throw contentError('INSTALL_DEPENDENCY_INVALID')
32
+ for (const [name, range] of Object.entries(manifest[field])) {
33
+ if (!packageName.test(name) || typeof range !== 'string' || !validRange(range))
34
+ throw contentError('INSTALL_DEPENDENCY_SOURCE_FORBIDDEN')
35
+ }
36
+ }
37
+ }
38
+ function checkLock(lock, candidates = false) {
39
+ if (lock?.lockfileVersion !== 3 || !lock.packages || typeof lock.packages !== 'object')
40
+ throw contentError('INSTALL_LOCK_INVALID')
41
+ for (const [location, entry] of Object.entries(lock.packages)) {
42
+ if (!entry || typeof entry !== 'object' || entry.link) throw contentError('INSTALL_LOCK_INVALID')
43
+ if (
44
+ location &&
45
+ (!location.startsWith('node_modules/') || location.split('/').includes('..') || location.includes('\\'))
46
+ )
47
+ throw contentError('INSTALL_LOCK_INVALID')
48
+ if (typeof entry.resolved !== 'string') continue
49
+ if (candidates && /^file:candidates\/source-[0-9]+\.tgz$/.test(entry.resolved)) continue
50
+ const url = new URL(entry.resolved)
51
+ if (url.protocol !== 'https:' || url.username || url.password)
52
+ throw contentError('INSTALL_DEPENDENCY_SOURCE_FORBIDDEN')
53
+ }
54
+ }
55
+ /** No inherited npm configuration, loader hooks, or author script can alter install behavior. */
56
+ function installationEnvironment(cache, configuration) {
57
+ const result = {}
58
+ for (const key of ['PATH', 'Path', 'SystemRoot', 'WINDIR', 'TEMP', 'TMP', 'TMPDIR', 'HOME', 'USERPROFILE', 'LANG'])
59
+ if (process.env[key]) result[key] = process.env[key]
60
+ if (process.env.ELECTRON_RUN_AS_NODE === '1' || process.versions.electron) result.ELECTRON_RUN_AS_NODE = '1'
61
+ return {
62
+ ...result,
63
+ npm_config_cache: cache,
64
+ npm_config_userconfig: configuration,
65
+ npm_config_globalconfig: configuration + '.global',
66
+ npm_config_ignore_scripts: 'true',
67
+ npm_config_engine_strict: 'true',
68
+ npm_config_strict_peer_deps: 'true',
69
+ npm_config_force: 'false',
70
+ npm_config_legacy_peer_deps: 'false',
71
+ npm_config_audit: 'false',
72
+ npm_config_fund: 'false',
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Resolves a captured draft into a standard installed npm project. Construction and
78
+ * source registration belong to the host, while requests contain only environment IDs.
79
+ * The ContentWorkspace still owns immutable versions, leases, and publication.
80
+ */
81
+ export class ManagedProjects {
82
+ #options
83
+ #controller = new AbortController()
84
+ #pending = new Set()
85
+ #active = 0
86
+ constructor(root, options = {}) {
87
+ this.root = resolve(root)
88
+ if (
89
+ options.sources !== undefined &&
90
+ (!options.sources || typeof options.sources !== 'object' || Array.isArray(options.sources))
91
+ )
92
+ throw contentError('INSTALL_SOURCES_INVALID')
93
+ this.#options = {
94
+ ...options,
95
+ registry: registryUrl(options.registry),
96
+ sources: structuredClone(options.sources ?? {}),
97
+ timeoutMs: limit(options.timeoutMs, DEFAULT_TIMEOUT, 3600_000),
98
+ maxBytes: limit(options.maxBytes, DEFAULT_BYTES, 4 * 1024 * 1024 * 1024),
99
+ maxFiles: limit(options.maxFiles, 50_000, 1_000_000),
100
+ maxConcurrent: limit(options.maxConcurrent, 2, 16),
101
+ }
102
+ for (const name of Object.keys(this.#options.sources))
103
+ if (!packageName.test(name)) throw contentError('INSTALL_SOURCE_NAME_INVALID')
104
+ }
105
+ async #npm(args, cwd, signal) {
106
+ const invocation = await resolveNpmInvocation(args)
107
+ const cache = join(this.root, 'npm-cache')
108
+ const configuration = this.#options.npmUserConfig ?? join(this.root, 'empty.npmrc')
109
+ await mkdir(cache, { recursive: true, mode: 0o700 })
110
+ if (!this.#options.npmUserConfig) {
111
+ await writeFile(configuration, '', { mode: 0o600 })
112
+ await writeFile(configuration + '.global', '', { mode: 0o600 })
113
+ }
114
+ try {
115
+ await execute(invocation.file, invocation.args, {
116
+ cwd,
117
+ signal,
118
+ timeout: this.#options.timeoutMs,
119
+ killSignal: 'SIGTERM',
120
+ maxBuffer: 2 * 1024 * 1024,
121
+ windowsHide: true,
122
+ env: installationEnvironment(cache, configuration),
123
+ })
124
+ } catch (error) {
125
+ signal.throwIfAborted()
126
+ if (typeof error.stderr === 'string' && /\bERESOLVE\b/.test(error.stderr))
127
+ throw contentError('ENVIRONMENT_DEPENDENCY_CONFLICT')
128
+ // Do not include subprocess output/configuration paths in public task errors.
129
+ throw contentError('NPM_INSTALL_FAILED')
130
+ }
131
+ }
132
+ prepareVersion(workspace, input, validate) {
133
+ if (typeof validate !== 'function') return Promise.reject(contentError('STATIC_PREPARER_REQUIRED'))
134
+ return this.#track(
135
+ this.#prepare(
136
+ async () => {
137
+ const draft = await workspace.getDraft(input.environmentId)
138
+ if (draft.revision !== input.expectedRevision) throw contentError('REVISION_CONFLICT')
139
+ return draft.document
140
+ },
141
+ input,
142
+ async (directory, signal) => {
143
+ const current = await workspace.getDraft(input.environmentId)
144
+ if (current.revision !== input.expectedRevision) throw contentError('REVISION_CONFLICT')
145
+ return workspace.prepareVersion({ ...input, projectDirectory: directory, signal }, validate)
146
+ },
147
+ ),
148
+ )
149
+ }
150
+ /** Transfer an installed project to the host's existing library without a second copy. */
151
+ prepareProject(document, input, consume) {
152
+ return this.#track(this.#prepare(async () => document, input ?? {}, consume))
153
+ }
154
+ #track(task) {
155
+ this.#pending.add(task)
156
+ task.finally(() => this.#pending.delete(task)).catch(() => {})
157
+ return task
158
+ }
159
+ async #prepare(readDocument, input, consume) {
160
+ if (this.#controller.signal.aborted) throw contentError('INSTALLER_CLOSED')
161
+ if (this.#active >= this.#options.maxConcurrent) throw contentError('INSTALL_BUSY')
162
+ if (typeof consume !== 'function') throw contentError('PROJECT_CONSUMER_REQUIRED')
163
+ this.#active++
164
+ let directory
165
+ const signal = AbortSignal.any([
166
+ this.#controller.signal,
167
+ ...(input.signal ? [input.signal] : []),
168
+ AbortSignal.timeout(this.#options.timeoutMs),
169
+ ])
170
+ try {
171
+ signal.throwIfAborted()
172
+ await input.onProgress?.({ stage: 'resolving' })
173
+ const document = normalizeEnvironmentDocument(await readDocument())
174
+ if (Object.keys(document.packages).length + document.sources.length > 200)
175
+ throw contentError('INSTALL_PACKAGE_LIMIT')
176
+ const dependencies = {}
177
+ for (const [name, range] of Object.entries(document.packages)) {
178
+ if (typeof range !== 'string' || range.length > 256 || !validRange(range))
179
+ throw contentError('INSTALL_VERSION_INVALID')
180
+ dependencies[name] = range
181
+ }
182
+ // Acquisition approval is separate from any runtime execution policy. This
183
+ // installer never evaluates author modules or invokes lifecycle scripts.
184
+ if (!this.#options.allowThirdPartyContent && (Object.keys(dependencies).length || document.sources.length))
185
+ throw contentError('THIRD_PARTY_CONTENT_NOT_AUTHORIZED')
186
+ await mkdir(join(this.root, 'staging'), { recursive: true, mode: 0o700 })
187
+ directory = await mkdtemp(join(this.root, 'staging', 'prepare-'))
188
+ await mkdir(join(directory, 'candidates'))
189
+ const provenance = {}
190
+ for (const [index, name] of document.sources.entries()) {
191
+ if (Object.hasOwn(dependencies, name)) throw contentError('INSTALL_DUPLICATE_PACKAGE')
192
+ const source = this.#options.sources[name]
193
+ if (!source) throw contentError('INSTALL_SOURCE_NOT_REGISTERED')
194
+ if (this.#options.offline && (source.kind === 'url' || source.kind === 'git'))
195
+ throw contentError('INSTALL_SOURCE_OFFLINE')
196
+ await input.onProgress?.({ stage: 'acquiring', completed: index, total: document.sources.length })
197
+ const captured = await acquireSource(source, {
198
+ destination: join(directory, 'source-' + index),
199
+ signal,
200
+ maxBytes: this.#options.maxBytes,
201
+ maxFiles: this.#options.maxFiles,
202
+ timeoutMs: this.#options.timeoutMs,
203
+ })
204
+ const manifest = JSON.parse(await readFile(join(captured.directory, 'package.json'), 'utf8'))
205
+ if (manifest.name !== name) throw contentError('INSTALL_SOURCE_IDENTITY')
206
+ if (typeof manifest.version !== 'string' || !valid(manifest.version))
207
+ throw contentError('INSTALL_SOURCE_VERSION')
208
+ checkDependencySpecs(manifest)
209
+ try {
210
+ checkLock(JSON.parse(await readFile(join(captured.directory, 'npm-shrinkwrap.json'), 'utf8')))
211
+ } catch (error) {
212
+ if (error.code !== 'ENOENT') throw error
213
+ }
214
+ const output = join(directory, 'packed-' + index)
215
+ await mkdir(output)
216
+ await this.#npm(
217
+ ['pack', '--ignore-scripts', '--json', '--pack-destination', output, '--registry', this.#options.registry],
218
+ captured.directory,
219
+ signal,
220
+ )
221
+ const { readdir } = await import('node:fs/promises')
222
+ const files = await readdir(output)
223
+ if (files.length !== 1 || !files[0].endsWith('.tgz')) throw contentError('INSTALL_PACK_INVALID')
224
+ const filename = 'candidates/source-' + index + '.tgz'
225
+ await rename(join(output, files[0]), join(directory, filename))
226
+ dependencies[name] = 'file:' + filename
227
+ provenance[name] = captured.provenance
228
+ await rm(captured.directory, { recursive: true, force: true })
229
+ await rm(output, { recursive: true, force: true })
230
+ }
231
+ await writeFile(
232
+ join(directory, 'package.json'),
233
+ JSON.stringify(
234
+ {
235
+ name: 'arcadia-managed-environment',
236
+ version: '1.0.0',
237
+ private: true,
238
+ dependencies,
239
+ arcadiaManagedSources: provenance,
240
+ },
241
+ null,
242
+ 2,
243
+ ) + '\n',
244
+ { mode: 0o600 },
245
+ )
246
+ await this.#npm(
247
+ [
248
+ 'install',
249
+ '--package-lock-only',
250
+ '--ignore-scripts',
251
+ '--omit=dev',
252
+ '--package-lock=true',
253
+ '--no-audit',
254
+ '--no-fund',
255
+ '--registry',
256
+ this.#options.registry,
257
+ ...(this.#options.offline ? ['--offline'] : []),
258
+ ],
259
+ directory,
260
+ signal,
261
+ )
262
+ checkLock(JSON.parse(await readFile(join(directory, 'package-lock.json'), 'utf8')), true)
263
+ await input.onProgress?.({ stage: 'installing' })
264
+ await this.#npm(
265
+ [
266
+ 'ci',
267
+ '--ignore-scripts',
268
+ '--omit=dev',
269
+ '--no-audit',
270
+ '--no-fund',
271
+ '--registry',
272
+ this.#options.registry,
273
+ ...(this.#options.offline ? ['--offline'] : []),
274
+ ],
275
+ directory,
276
+ signal,
277
+ )
278
+ await mkdir(join(directory, 'node_modules'), { recursive: true })
279
+ // Standard package/lock validation and bounded material capture before static preparation.
280
+ await input.onProgress?.({ stage: 'verifying' })
281
+ await inspectNpmProject(directory)
282
+ await materialFiles(directory, { signal, maxBytes: this.#options.maxBytes, maxFiles: this.#options.maxFiles })
283
+ signal.throwIfAborted()
284
+ await input.onProgress?.({ stage: 'preparing' })
285
+ return await consume(directory, signal)
286
+ } catch (error) {
287
+ if (error?.name === 'AbortError' || error?.name === 'TimeoutError') throw error
288
+ const code = error?.code ?? error?.diagnostics?.[0]?.code
289
+ if (typeof code === 'string' && /^[A-Z][A-Z0-9_]{2,79}$/.test(code)) throw contentError(code)
290
+ throw contentError('ENVIRONMENT_INSTALL_FAILED')
291
+ } finally {
292
+ try {
293
+ if (directory) await rm(directory, { recursive: true, force: true })
294
+ } finally {
295
+ this.#active--
296
+ }
297
+ }
298
+ }
299
+ async close() {
300
+ this.#controller.abort(contentError('INSTALLER_CLOSED'))
301
+ await Promise.allSettled([...this.#pending])
302
+ }
303
+ }