@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.
- package/LICENSE +21 -0
- package/README.md +98 -2
- package/dist/asset-inspect.mjs +67 -0
- package/dist/author-api.mjs +112 -0
- package/dist/author-reference.mjs +121 -0
- package/dist/build-content.mjs +30 -0
- package/dist/cli.mjs +74 -0
- package/dist/content-query.mjs +283 -0
- package/dist/content-workspace.d.mts +161 -0
- package/dist/content-workspace.mjs +936 -0
- package/dist/debug-environments.mjs +154 -0
- package/dist/demo.mjs +22 -0
- package/dist/environment-rules.d.mts +5 -0
- package/dist/environment-rules.mjs +92 -0
- package/dist/environment.mjs +183 -0
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +1 -0
- package/dist/job-journal.mjs +94 -0
- package/dist/jobs.mjs +579 -0
- package/dist/lib/content.mjs +95 -0
- package/dist/lib/presentation.mjs +240 -0
- package/dist/lib/yaml-sharing.mjs +101 -0
- package/dist/managed-projects.d.mts +35 -0
- package/dist/managed-projects.mjs +303 -0
- package/dist/managed-sources.d.mts +19 -0
- package/dist/managed-sources.mjs +503 -0
- package/dist/mcp-contracts.mjs +153 -0
- package/dist/mcp.mjs +369 -0
- package/dist/pack-project.mjs +156 -0
- package/dist/preview-control.mjs +260 -0
- package/dist/preview.mjs +313 -0
- package/dist/project-teams.mjs +98 -0
- package/dist/project.mjs +140 -0
- package/dist/rename.mjs +112 -0
- package/dist/setup.mjs +134 -0
- package/dist/source-lock.mjs +103 -0
- package/dist/template/LICENSE +21 -0
- package/dist/template/README.md +17 -0
- package/dist/template/arcadia.config.mjs +2 -0
- package/dist/template/assets/marks/slow.png +0 -0
- package/dist/template/assets/pets/frostling-battle.png +0 -0
- package/dist/template/assets/pets/frostling-icon.png +0 -0
- package/dist/template/assets/pets/frostling-portrait.png +0 -0
- package/dist/template/data/marks/slow.yaml +18 -0
- package/dist/template/data/presentations/main.yaml +34 -0
- package/dist/template/data/resources/main.yaml +21 -0
- package/dist/template/data/skills/rest.yaml +6 -0
- package/dist/template/data/skills/strike.yaml +14 -0
- package/dist/template/data/species/pet-swf.yaml +36 -0
- package/dist/template/data/species/pet.yaml +34 -0
- package/dist/template/debug/teams/blue.yaml +25 -0
- package/dist/template/debug/teams/orange.yaml +25 -0
- package/dist/template/docs/presentation.md +21 -0
- package/dist/template/locales/en/mark.yaml +5 -0
- package/dist/template/locales/en/skill.yaml +12 -0
- package/dist/template/locales/en/species.yaml +6 -0
- package/dist/template/locales/zh-CN/mark.yaml +4 -0
- package/dist/template/locales/zh-CN/skill.yaml +10 -0
- package/dist/template/locales/zh-CN/species.yaml +6 -0
- package/dist/template/package.json +44 -0
- package/dist/template/skills/arcadia-content-authoring/SKILL.md +23 -0
- package/dist/template/skills/arcadia-content-authoring/references/project-sources.md +15 -0
- package/dist/template/skills/arcadia-content-authoring/references/tool-workflows.md +37 -0
- package/dist/template/skills/seer2-recreate-pet/SKILL.md +82 -0
- package/dist/template/skills/seer2-recreate-pet/references/mechanics-and-validation.md +47 -0
- package/dist/template/skills/seer2-recreate-pet/references/project-conventions.md +32 -0
- package/dist/template/skills/seer2-recreate-pet/references/testing.md +50 -0
- package/dist/template/src/effects.ts +44 -0
- package/dist/template/test/pack.test.mjs +178 -0
- package/dist/template/tsconfig.json +15 -0
- package/dist/testing.mjs +204 -0
- package/dist/workbench-context.mjs +18 -0
- package/dist/workspace-cli.mjs +60 -0
- package/dist/workspace-materials.mjs +153 -0
- package/dist/workspace.mjs +684 -0
- package/package.json +68 -3
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { EffectModuleContext } from '@arcadia-eternity/content-sdk'
|
|
2
|
+
|
|
3
|
+
/** The host supplies its SDK and canonical prototypes; importing this file registers nothing globally. */
|
|
4
|
+
export function createEffects({ sdk, marks, id }: EffectModuleContext) {
|
|
5
|
+
const { defineCodeEffect, numberParam, targets, ops, EffectTrigger, AddMarkContext } = sdk
|
|
6
|
+
const slow = marks.get(id('slow'))
|
|
7
|
+
if (!slow) throw new Error('Missing slow mark')
|
|
8
|
+
return [
|
|
9
|
+
defineCodeEffect({
|
|
10
|
+
id: id('apply-slow'),
|
|
11
|
+
sourceKind: 'skill',
|
|
12
|
+
triggers: [EffectTrigger.OnHit],
|
|
13
|
+
when: context => context.source === context.parent.skill,
|
|
14
|
+
apply(context) {
|
|
15
|
+
const target = context.parent.actualTarget
|
|
16
|
+
if (target) target.addMark(new AddMarkContext(context, target, slow))
|
|
17
|
+
},
|
|
18
|
+
}),
|
|
19
|
+
defineCodeEffect({
|
|
20
|
+
id: id('speed-penalty'),
|
|
21
|
+
sourceKind: 'petMark',
|
|
22
|
+
build({ effectId }) {
|
|
23
|
+
// This remains a modifiable battle parameter even though there is no editor parameter form.
|
|
24
|
+
const amount = numberParam({ default: -25, tags: [id('slow-amount')] })
|
|
25
|
+
return {
|
|
26
|
+
id: effectId,
|
|
27
|
+
triggers: [EffectTrigger.OnMarkCreated],
|
|
28
|
+
rebindOnOwnerTransfer: true,
|
|
29
|
+
parameters: { amount },
|
|
30
|
+
apply: targets.ownerPet.apply(
|
|
31
|
+
ops.bindAttribute({
|
|
32
|
+
key: 'speed',
|
|
33
|
+
attribute: 'spe',
|
|
34
|
+
operation: 'delta',
|
|
35
|
+
value: amount.follow({ key: 'amount' }),
|
|
36
|
+
lifetime: 'sourceMark',
|
|
37
|
+
missing: 'detach',
|
|
38
|
+
}),
|
|
39
|
+
),
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
}),
|
|
43
|
+
]
|
|
44
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { after, before, test } from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import {
|
|
4
|
+
AttackTargetOpinion,
|
|
5
|
+
EffectContext,
|
|
6
|
+
EffectTrigger,
|
|
7
|
+
RemoveMarkContext,
|
|
8
|
+
attack,
|
|
9
|
+
cancelled,
|
|
10
|
+
nextTurn,
|
|
11
|
+
parameterAddress,
|
|
12
|
+
prepareContentPack,
|
|
13
|
+
runBattle,
|
|
14
|
+
setGlobalLogger,
|
|
15
|
+
} from '@arcadia-eternity/content-sdk/testing'
|
|
16
|
+
setGlobalLogger({ debug() {}, info() {}, warn() {}, error() {} })
|
|
17
|
+
|
|
18
|
+
let example
|
|
19
|
+
before(
|
|
20
|
+
async () => {
|
|
21
|
+
const fetch = globalThis.fetch
|
|
22
|
+
globalThis.fetch = () => {
|
|
23
|
+
throw new Error('Preparing the sample pack must not fetch remote resources')
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
example = await prepareContentPack()
|
|
27
|
+
} finally {
|
|
28
|
+
globalThis.fetch = fetch
|
|
29
|
+
}
|
|
30
|
+
assert.ok(example.files.some(file => file.startsWith('data/species/')))
|
|
31
|
+
assert.ok(!example.files.includes('content.json'))
|
|
32
|
+
},
|
|
33
|
+
{ timeout: 60000 },
|
|
34
|
+
)
|
|
35
|
+
after(async () => {
|
|
36
|
+
await example?.dispose()
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
test('the installed package includes local artwork, remote declarations and both languages', () => {
|
|
40
|
+
for (const file of [
|
|
41
|
+
'dist/presentation.json',
|
|
42
|
+
'docs/presentation.md',
|
|
43
|
+
'assets/pets/frostling-icon.png',
|
|
44
|
+
'assets/pets/frostling-portrait.png',
|
|
45
|
+
'assets/pets/frostling-battle.png',
|
|
46
|
+
'assets/marks/slow.png',
|
|
47
|
+
...['zh-CN', 'en'].flatMap(language =>
|
|
48
|
+
['species', 'skill', 'mark'].map(kind => `locales/${language}/${kind}.yaml`),
|
|
49
|
+
),
|
|
50
|
+
])
|
|
51
|
+
assert.ok(example.files.includes(file), `Missing packaged file: ${file}`)
|
|
52
|
+
const presentation = example.environment.presentation.find(
|
|
53
|
+
item => item.namespace === example.manifest.arcadia.namespace,
|
|
54
|
+
)
|
|
55
|
+
assert.ok(presentation)
|
|
56
|
+
assert.equal(presentation.resources.length, 4, 'only the four packaged images have local file paths')
|
|
57
|
+
const remote = presentation.manifest.resources.filter(resource => resource.kind === 'http')
|
|
58
|
+
assert.equal(remote.length, 3)
|
|
59
|
+
assert.ok(remote.some(resource => resource.mime === 'application/x-shockwave-flash'))
|
|
60
|
+
assert.ok(remote.some(resource => resource.mime === 'audio/mpeg'))
|
|
61
|
+
for (const resource of remote) {
|
|
62
|
+
assert.notEqual(resource.id, resource.source)
|
|
63
|
+
assert.equal('sha256' in resource, false)
|
|
64
|
+
assert.equal('bytes' in resource, false)
|
|
65
|
+
}
|
|
66
|
+
assert.equal(presentation.manifest.version, 2)
|
|
67
|
+
assert.equal(presentation.manifest.bindings.length, 5)
|
|
68
|
+
for (const kind of ['species', 'skills', 'marks'])
|
|
69
|
+
assert.ok(example.environment.data[kind].every(row => !('presentation' in row)))
|
|
70
|
+
assert.equal(presentation.manifest.defaultLocale, 'zh-CN')
|
|
71
|
+
for (const [language, name] of [
|
|
72
|
+
['zh-CN', '霜击'],
|
|
73
|
+
['en', 'Frost Strike'],
|
|
74
|
+
]) {
|
|
75
|
+
const locales = presentation.manifest.locales[language]
|
|
76
|
+
assert.equal(locales.skill.strike.name, name)
|
|
77
|
+
assert.match(locales.skill.strike.description, /\{power, plural,/)
|
|
78
|
+
assert.match(locales.skill.rest.description, /<damage>\{power\}<\/damage>/)
|
|
79
|
+
assert.ok(locales.skill.strike.description.includes(`<mark>${example.manifest.arcadia.namespace}:slow</mark>`))
|
|
80
|
+
assert.ok(locales.species['pet-swf'].name)
|
|
81
|
+
assert.ok(locales.mark.slow.description)
|
|
82
|
+
}
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
test('the installed package handles miss, hit, refresh, parameter updates, transfer and source removal', async () => {
|
|
86
|
+
const battle = await example.createBattle(),
|
|
87
|
+
other = await example.createBattle()
|
|
88
|
+
const a = battle.playerA.activePet,
|
|
89
|
+
b = battle.playerB.activePet
|
|
90
|
+
const speed = b.stat.spe,
|
|
91
|
+
otherSpeed = other.playerB.activePet.stat.spe
|
|
92
|
+
battle.applyEffects(attack(battle), EffectTrigger.OnMiss)
|
|
93
|
+
assert.equal(b.marks.length, 0)
|
|
94
|
+
battle.applyEffects(attack(battle), EffectTrigger.OnHit)
|
|
95
|
+
const mark = b.marks[0]
|
|
96
|
+
assert.equal(mark.duration, 2)
|
|
97
|
+
assert.equal(b.stat.spe, speed - 25)
|
|
98
|
+
mark.duration = 1
|
|
99
|
+
battle.applyEffects(attack(battle), EffectTrigger.OnHit)
|
|
100
|
+
assert.equal(b.marks.length, 1)
|
|
101
|
+
assert.equal(mark.duration, 2)
|
|
102
|
+
assert.equal(mark.stack, 1)
|
|
103
|
+
assert.equal(b.stat.spe, speed - 25)
|
|
104
|
+
const effect = mark.effects[0]
|
|
105
|
+
example
|
|
106
|
+
.contentFor(battle)
|
|
107
|
+
.parametersFor(effect.id)
|
|
108
|
+
.set(battle.configSystem, parameterAddress(effect.id, 'parameters', 'amount'), -40, mark)
|
|
109
|
+
assert.equal(b.stat.spe, speed - 40)
|
|
110
|
+
assert.equal(other.playerB.activePet.stat.spe, otherSpeed)
|
|
111
|
+
assert.equal(other.playerB.activePet.marks.length, 0)
|
|
112
|
+
mark.isSuppressed = true
|
|
113
|
+
assert.equal(b.stat.spe, speed)
|
|
114
|
+
const context = new EffectContext(attack(battle), EffectTrigger.OnHit, a.skills[0])
|
|
115
|
+
const aSpeed = a.stat.spe
|
|
116
|
+
a.transferMarks(context, mark)
|
|
117
|
+
assert.equal(b.stat.spe, speed)
|
|
118
|
+
assert.equal(mark.owner, a)
|
|
119
|
+
assert.equal(a.stat.spe, aSpeed)
|
|
120
|
+
mark.isSuppressed = false
|
|
121
|
+
assert.equal(a.stat.spe, aSpeed - 40)
|
|
122
|
+
battle.removeMark(new RemoveMarkContext(context, mark))
|
|
123
|
+
assert.equal(a.stat.spe, aSpeed)
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
test(
|
|
127
|
+
'JSON waiting-point restoration retains the parameter and natural expiry releases the modifier',
|
|
128
|
+
{ timeout: 20000 },
|
|
129
|
+
async () => {
|
|
130
|
+
let battle = await example.createBattle(),
|
|
131
|
+
running = battle.startBattle().catch(cancelled)
|
|
132
|
+
try {
|
|
133
|
+
await battle.waitForInputReady()
|
|
134
|
+
battle.applyEffects(attack(battle), EffectTrigger.OnHit)
|
|
135
|
+
const speed = battle.playerB.activePet.stat.spe + 25
|
|
136
|
+
const mark = battle.playerB.activePet.marks[0],
|
|
137
|
+
effect = mark.effects[0]
|
|
138
|
+
example
|
|
139
|
+
.contentFor(battle)
|
|
140
|
+
.parametersFor(effect.id)
|
|
141
|
+
.set(battle.configSystem, parameterAddress(effect.id, 'parameters', 'amount'), -30, mark)
|
|
142
|
+
const saved = JSON.parse(JSON.stringify(example.contentFor(battle).snapshot(battle)))
|
|
143
|
+
await battle.cleanup()
|
|
144
|
+
await running
|
|
145
|
+
battle = await example.restoreBattle(saved)
|
|
146
|
+
example.track(battle)
|
|
147
|
+
assert.equal(battle.playerB.activePet.stat.spe, speed - 30)
|
|
148
|
+
assert.equal(battle.playerB.activePet.marks[0].duration, 2)
|
|
149
|
+
running = battle.resumeBattle().catch(cancelled)
|
|
150
|
+
await battle.waitForInputReady()
|
|
151
|
+
for (const remaining of [1, 0]) {
|
|
152
|
+
const next = nextTurn(battle)
|
|
153
|
+
for (const player of [battle.playerA, battle.playerB])
|
|
154
|
+
assert.equal(
|
|
155
|
+
battle.setSelection({
|
|
156
|
+
type: 'use-skill',
|
|
157
|
+
player: player.id,
|
|
158
|
+
skill: player.activePet.skills[1].id,
|
|
159
|
+
target: AttackTargetOpinion.opponent,
|
|
160
|
+
}),
|
|
161
|
+
true,
|
|
162
|
+
)
|
|
163
|
+
await next
|
|
164
|
+
assert.equal(battle.playerB.activePet.marks[0]?.duration ?? 0, remaining)
|
|
165
|
+
}
|
|
166
|
+
assert.equal(battle.playerB.activePet.stat.spe, speed)
|
|
167
|
+
} finally {
|
|
168
|
+
await battle.cleanup()
|
|
169
|
+
await running
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
test('two complete battles reproduce the same result from the same seed', { timeout: 20000 }, async () => {
|
|
175
|
+
const first = await runBattle(await example.createBattle('repeatable-example'))
|
|
176
|
+
const second = await runBattle(await example.createBattle('repeatable-example'))
|
|
177
|
+
assert.deepEqual(first, second)
|
|
178
|
+
})
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"module": "ESNext",
|
|
5
|
+
"moduleResolution": "bundler",
|
|
6
|
+
"strict": true,
|
|
7
|
+
"skipLibCheck": true,
|
|
8
|
+
"rootDir": "src",
|
|
9
|
+
"outDir": "dist",
|
|
10
|
+
"declaration": true,
|
|
11
|
+
"sourceMap": true,
|
|
12
|
+
"inlineSources": true
|
|
13
|
+
},
|
|
14
|
+
"include": ["src/**/*.ts"]
|
|
15
|
+
}
|
package/dist/testing.mjs
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { randomBytes } from 'node:crypto'
|
|
3
|
+
import { join, resolve } from 'node:path'
|
|
4
|
+
import { pathToFileURL } from 'node:url'
|
|
5
|
+
import { prepareBattleEnvironment } from './environment.mjs'
|
|
6
|
+
import { assertEnvironmentTeam, validateEnvironmentRules } from './environment-rules.mjs'
|
|
7
|
+
import { prepareSandboxContent } from '@arcadia-eternity/battle/sandbox/effects'
|
|
8
|
+
import { createNodeBattleWorkerManager } from '@arcadia-eternity/battle/sandbox/node'
|
|
9
|
+
export { prepareBattleEnvironment } from './environment.mjs'
|
|
10
|
+
import { AttackTargetOpinion, BattleMessageType, TurnContext, UseSkillContext } from '@arcadia-eternity/battle/engine'
|
|
11
|
+
export {
|
|
12
|
+
AttackTargetOpinion,
|
|
13
|
+
EffectContext,
|
|
14
|
+
EffectTrigger,
|
|
15
|
+
RemoveMarkContext,
|
|
16
|
+
parameterAddress,
|
|
17
|
+
setGlobalLogger,
|
|
18
|
+
} from '@arcadia-eternity/battle/engine'
|
|
19
|
+
/** Existing package scenarios use the default environment with declared dependencies only. */
|
|
20
|
+
export async function prepareContentPack(root = process.cwd(), options = {}) {
|
|
21
|
+
root = resolve(root)
|
|
22
|
+
const { default: config } = await import(pathToFileURL(join(root, 'arcadia.config.mjs')).href)
|
|
23
|
+
if (
|
|
24
|
+
!Array.isArray(config?.teams) ||
|
|
25
|
+
config.teams.length !== 2 ||
|
|
26
|
+
config.teams.some(id => typeof id !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,79}$/.test(id)) ||
|
|
27
|
+
Object.keys(config).some(key => key !== 'teams')
|
|
28
|
+
)
|
|
29
|
+
throw new Error('arcadia.config.mjs must export exactly two project team IDs in teams')
|
|
30
|
+
const prepared = await prepareBattleEnvironment(root, options)
|
|
31
|
+
const { environment } = prepared
|
|
32
|
+
const environmentRules = validateEnvironmentRules(prepared.environmentDocument.rules)
|
|
33
|
+
// Four automation sessions, one human preview, and room for their validated replacements.
|
|
34
|
+
const workers = createNodeBattleWorkerManager({ maxBattles: 7 })
|
|
35
|
+
function defaultPlayers() {
|
|
36
|
+
return prepared.loadTeams(config.teams)
|
|
37
|
+
}
|
|
38
|
+
function runtimePlayers(supplied, runtimeIds = false) {
|
|
39
|
+
const players = (supplied ?? defaultPlayers()).map(player => ({
|
|
40
|
+
...player,
|
|
41
|
+
id: (runtimeIds ? undefined : player.id) ?? randomBytes(16).toString('base64url').slice(0, 21),
|
|
42
|
+
team: player.team.map(pet => ({
|
|
43
|
+
...pet,
|
|
44
|
+
id: runtimeIds ? randomBytes(16).toString('base64url').slice(0, 21) : pet.id,
|
|
45
|
+
})),
|
|
46
|
+
}))
|
|
47
|
+
for (const player of players) assertEnvironmentTeam(environmentRules, player.team)
|
|
48
|
+
return players
|
|
49
|
+
}
|
|
50
|
+
const referenceContent = new WeakMap()
|
|
51
|
+
function ownBattle(battle, effects) {
|
|
52
|
+
referenceContent.set(battle, effects.content)
|
|
53
|
+
const cleanup = battle.cleanup.bind(battle)
|
|
54
|
+
// Keep the runtime method non-enumerable, like the prototype method: only
|
|
55
|
+
// domain fields belong in snapshots, never this resource-owner callback.
|
|
56
|
+
Object.defineProperty(battle, 'cleanup', {
|
|
57
|
+
configurable: true,
|
|
58
|
+
value: async () => {
|
|
59
|
+
try {
|
|
60
|
+
await cleanup()
|
|
61
|
+
} finally {
|
|
62
|
+
effects.dispose()
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
})
|
|
66
|
+
prepared.track(battle)
|
|
67
|
+
return battle
|
|
68
|
+
}
|
|
69
|
+
/** Explicit trusted introspection entry. Every reference battle owns fresh VMs,
|
|
70
|
+
* just like the Worker entry; preparing an environment never evaluates effects.
|
|
71
|
+
*/
|
|
72
|
+
async function createBattle(
|
|
73
|
+
seed = 'content-pack-template',
|
|
74
|
+
{ ai = false, players: supplied, runtimeIds = false, battleOptions = {} } = {},
|
|
75
|
+
) {
|
|
76
|
+
const input = runtimePlayers(supplied, runtimeIds)
|
|
77
|
+
const effects = await prepareSandboxContent(environment.sandbox)
|
|
78
|
+
try {
|
|
79
|
+
const players = effects.content.parsePlayers(input, { aiPlayerIds: ai ? [input[1]?.id] : [] })
|
|
80
|
+
if (players.length !== 2) throw new Error('The demo requires exactly two players')
|
|
81
|
+
const ids = players.flatMap(player => [player.id, ...player.team.map(pet => pet.id)])
|
|
82
|
+
if (new Set(ids).size !== ids.length) throw new Error('玩家和精灵的编号不能重复')
|
|
83
|
+
return ownBattle(
|
|
84
|
+
effects.content.createBattle(players[0], players[1], {
|
|
85
|
+
...battleOptions,
|
|
86
|
+
rngSeed: seed,
|
|
87
|
+
timerConfig: battleOptions.timerConfig ?? { enabled: false },
|
|
88
|
+
}),
|
|
89
|
+
effects,
|
|
90
|
+
)
|
|
91
|
+
} catch (error) {
|
|
92
|
+
effects.dispose()
|
|
93
|
+
throw error
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
async function restoreBattle(snapshot) {
|
|
97
|
+
const effects = await prepareSandboxContent(environment.sandbox)
|
|
98
|
+
try {
|
|
99
|
+
return ownBattle(effects.content.restore(snapshot), effects)
|
|
100
|
+
} catch (error) {
|
|
101
|
+
effects.dispose()
|
|
102
|
+
throw error
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function contentFor(battle) {
|
|
106
|
+
const content = referenceContent.get(battle)
|
|
107
|
+
if (!content) throw new Error('Battle does not belong to this reference helper')
|
|
108
|
+
return content
|
|
109
|
+
}
|
|
110
|
+
async function createBattleSession(
|
|
111
|
+
seed = 'content-pack-template',
|
|
112
|
+
{ ai = false, players: supplied, runtimeIds = false, battleOptions = {} } = {},
|
|
113
|
+
) {
|
|
114
|
+
const players = runtimePlayers(supplied, runtimeIds)
|
|
115
|
+
const system = await workers.create({
|
|
116
|
+
environment: environment.sandbox,
|
|
117
|
+
players,
|
|
118
|
+
aiPlayerIds: ai ? [players[1]?.id] : [],
|
|
119
|
+
options: { ...battleOptions, rngSeed: seed, timerConfig: battleOptions.timerConfig ?? { enabled: false } },
|
|
120
|
+
hostOptions: { teamSelection: battleOptions.teamSelection },
|
|
121
|
+
})
|
|
122
|
+
return system
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
...prepared,
|
|
126
|
+
createBattle,
|
|
127
|
+
restoreBattle,
|
|
128
|
+
contentFor,
|
|
129
|
+
createBattleSession,
|
|
130
|
+
defaultPlayers,
|
|
131
|
+
async dispose() {
|
|
132
|
+
try {
|
|
133
|
+
await workers.dispose()
|
|
134
|
+
} finally {
|
|
135
|
+
await prepared.dispose()
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function attack(battle) {
|
|
142
|
+
const player = battle.playerA
|
|
143
|
+
const context = new UseSkillContext(
|
|
144
|
+
new TurnContext(battle),
|
|
145
|
+
player,
|
|
146
|
+
player.activePet,
|
|
147
|
+
AttackTargetOpinion.opponent,
|
|
148
|
+
player.activePet.skills[0],
|
|
149
|
+
)
|
|
150
|
+
context.updateActualTarget()
|
|
151
|
+
return context
|
|
152
|
+
}
|
|
153
|
+
export function cancelled(error) {
|
|
154
|
+
if (!(error instanceof Error) || error.message !== 'Battle cancelled') throw error
|
|
155
|
+
}
|
|
156
|
+
export function nextTurn(battle) {
|
|
157
|
+
return new Promise((resolve, reject) => {
|
|
158
|
+
const timeout = setTimeout(() => {
|
|
159
|
+
unsubscribe()
|
|
160
|
+
reject(new Error('Battle did not reach its next input boundary'))
|
|
161
|
+
}, 10000)
|
|
162
|
+
const listener = message => {
|
|
163
|
+
if (message.type !== BattleMessageType.TurnAction) return
|
|
164
|
+
clearTimeout(timeout)
|
|
165
|
+
unsubscribe()
|
|
166
|
+
resolve()
|
|
167
|
+
}
|
|
168
|
+
const unsubscribe = () => battle.unregisterListener(listener)
|
|
169
|
+
battle.registerListener(listener)
|
|
170
|
+
})
|
|
171
|
+
}
|
|
172
|
+
export async function runBattle(battle, onTurn = () => {}) {
|
|
173
|
+
const damage = [],
|
|
174
|
+
failures = []
|
|
175
|
+
battle.registerListener(message => {
|
|
176
|
+
if (message.type === BattleMessageType.Damage) damage.push(message.data.damage)
|
|
177
|
+
if (message.type === BattleMessageType.Error || message.type === BattleMessageType.EffectApplyFail)
|
|
178
|
+
failures.push(message)
|
|
179
|
+
if (message.type === BattleMessageType.TurnEnd) onTurn(battle)
|
|
180
|
+
if (message.type !== BattleMessageType.TurnAction) return
|
|
181
|
+
for (const player of [battle.playerA, battle.playerB]) {
|
|
182
|
+
const selection =
|
|
183
|
+
battle.currentTurn >= 40
|
|
184
|
+
? { type: 'surrender', player: player.id }
|
|
185
|
+
: {
|
|
186
|
+
type: 'use-skill',
|
|
187
|
+
player: player.id,
|
|
188
|
+
skill: player.activePet.skills[0].id,
|
|
189
|
+
target: AttackTargetOpinion.opponent,
|
|
190
|
+
}
|
|
191
|
+
if (!battle.setSelection(selection)) throw new Error('Example selection rejected')
|
|
192
|
+
if (selection.type === 'surrender') break
|
|
193
|
+
}
|
|
194
|
+
})
|
|
195
|
+
await battle.startBattle()
|
|
196
|
+
assert.deepEqual(failures, [], 'the demonstration must not hide effect execution failures')
|
|
197
|
+
assert.ok(battle.currentTurn < 40, 'the demonstration should finish by defeating the opposing pet')
|
|
198
|
+
return {
|
|
199
|
+
winner: battle.victor?.name,
|
|
200
|
+
turns: battle.currentTurn,
|
|
201
|
+
hp: [battle.playerA, battle.playerB].map(player => player.activePet.currentHp),
|
|
202
|
+
damage,
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { readFile, stat } from 'node:fs/promises'
|
|
2
|
+
|
|
3
|
+
/** Ephemeral desktop state is context, never an edit authorization or a disk revision. */
|
|
4
|
+
export async function readWorkbenchContext(file, root, now = Date.now()) {
|
|
5
|
+
if (!file) return { connected: false, reason: 'not-configured' }
|
|
6
|
+
try {
|
|
7
|
+
if ((await stat(file)).size > 4 * 1024 * 1024) throw new Error('Workbench context exceeds 4 MiB')
|
|
8
|
+
const context = JSON.parse(await readFile(file, 'utf8'))
|
|
9
|
+
if (context.protocol !== 'arcadia-workbench-context/v1' || context.root !== root)
|
|
10
|
+
return { connected: false, reason: 'project-mismatch' }
|
|
11
|
+
if (!Number.isFinite(context.updatedAt) || now - context.updatedAt > 90000 || context.updatedAt > now + 5000)
|
|
12
|
+
return { connected: false, reason: 'expired' }
|
|
13
|
+
return { connected: true, ...context }
|
|
14
|
+
} catch (error) {
|
|
15
|
+
if (error.code === 'ENOENT') return { connected: false, reason: 'workbench-closed' }
|
|
16
|
+
throw error
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { openAuthorSession } from './author-api.mjs'
|
|
2
|
+
import { diagnostic } from './workspace.mjs'
|
|
3
|
+
|
|
4
|
+
export async function workspaceCli(args) {
|
|
5
|
+
const [directory, operation = 'describe', ...flags] = args
|
|
6
|
+
let execute = false,
|
|
7
|
+
environmentId
|
|
8
|
+
for (let index = 0; index < flags.length; index++) {
|
|
9
|
+
if (flags[index] === '--execute') execute = true
|
|
10
|
+
else if (flags[index] === '--environment' && operation === 'preview' && flags[index + 1])
|
|
11
|
+
environmentId = flags[++index]
|
|
12
|
+
else throw new Error('Unknown workspace option; use --execute or preview --environment <id>')
|
|
13
|
+
}
|
|
14
|
+
if (!directory)
|
|
15
|
+
throw new Error(
|
|
16
|
+
'Usage: arcadia-content workspace <directory> <operation> [--execute] [--environment <id>]. JSON input on stdin for query/read/write/save.',
|
|
17
|
+
)
|
|
18
|
+
const session = await openAuthorSession(directory, { watch: false, execute })
|
|
19
|
+
const cancel = () => session.close()
|
|
20
|
+
process.once('SIGTERM', cancel)
|
|
21
|
+
process.once('SIGINT', cancel)
|
|
22
|
+
try {
|
|
23
|
+
let result
|
|
24
|
+
if (['check', 'test', 'demo', 'preview', 'pack'].includes(operation)) {
|
|
25
|
+
let job = await session.jobs.start({ kind: operation, ...(environmentId ? { environmentId } : {}) })
|
|
26
|
+
while (['queued', 'running'].includes(job.state)) {
|
|
27
|
+
await new Promise(resolve => setTimeout(resolve, 100))
|
|
28
|
+
job = session.jobs.get(job.jobId)
|
|
29
|
+
}
|
|
30
|
+
result = job
|
|
31
|
+
if (job.state !== 'succeeded' || job.stale) process.exitCode = 1
|
|
32
|
+
if (operation === 'preview' && job.state === 'succeeded' && !job.stale) {
|
|
33
|
+
console.log(JSON.stringify({ result: job }))
|
|
34
|
+
while (!session.jobs.closed && session.jobs.get(job.jobId).state === 'succeeded')
|
|
35
|
+
await new Promise(resolve => setTimeout(resolve, 100))
|
|
36
|
+
const final = session.jobs.get(job.jobId)
|
|
37
|
+
console.log(JSON.stringify({ result: final }))
|
|
38
|
+
if (final.state === 'failed') process.exitCode = 1
|
|
39
|
+
return
|
|
40
|
+
}
|
|
41
|
+
} else {
|
|
42
|
+
let input = ''
|
|
43
|
+
if (operation !== 'describe')
|
|
44
|
+
for await (const chunk of process.stdin) {
|
|
45
|
+
input += chunk
|
|
46
|
+
if (Buffer.byteLength(input) > 3 * 1024 * 1024) throw new Error('JSON input exceeds 3 MiB')
|
|
47
|
+
}
|
|
48
|
+
result = await session.call(operation, input ? JSON.parse(input) : {})
|
|
49
|
+
if (operation === 'save' && !result.complete) process.exitCode = 1
|
|
50
|
+
}
|
|
51
|
+
console.log(JSON.stringify({ result }))
|
|
52
|
+
} catch (error) {
|
|
53
|
+
console.log(JSON.stringify({ error: diagnostic(error) }))
|
|
54
|
+
process.exitCode = 1
|
|
55
|
+
} finally {
|
|
56
|
+
process.removeListener('SIGTERM', cancel)
|
|
57
|
+
process.removeListener('SIGINT', cancel)
|
|
58
|
+
await session.close()
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { lstat, mkdir, readFile, readdir, realpath, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { dirname, isAbsolute, join, relative } from 'node:path'
|
|
3
|
+
|
|
4
|
+
export function contentError(code, message = code) {
|
|
5
|
+
return Object.assign(new Error(message), { code })
|
|
6
|
+
}
|
|
7
|
+
const materialRoots = new Set(['package.json', 'package-lock.json', 'node_modules', 'candidates'])
|
|
8
|
+
const forbidden = new Set(['.git', '.env', '.npmrc', '.arcadia', '.bin'])
|
|
9
|
+
function checkedMaterialPath(value) {
|
|
10
|
+
if (typeof value !== 'string' || !value || value.includes('\\') || value.includes('\0') || isAbsolute(value))
|
|
11
|
+
throw contentError('MATERIAL_PATH_INVALID')
|
|
12
|
+
const parts = value.split('/')
|
|
13
|
+
if (
|
|
14
|
+
parts.some(
|
|
15
|
+
part =>
|
|
16
|
+
!part ||
|
|
17
|
+
part === '.' ||
|
|
18
|
+
part === '..' ||
|
|
19
|
+
forbidden.has(part) ||
|
|
20
|
+
/[<>:"|?*]/.test(part) ||
|
|
21
|
+
[...part].some(character => character.codePointAt(0) < 32) ||
|
|
22
|
+
/[. ]$/.test(part) ||
|
|
23
|
+
/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part),
|
|
24
|
+
) ||
|
|
25
|
+
!materialRoots.has(parts[0])
|
|
26
|
+
)
|
|
27
|
+
throw contentError('MATERIAL_PATH_INVALID')
|
|
28
|
+
return value
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Capture data bytes only. Symlink targets must remain inside the installed project. */
|
|
32
|
+
export async function materialFiles(root, { signal, maxBytes = 256 * 1024 * 1024, maxFiles = 50000, onRead } = {}) {
|
|
33
|
+
root = await realpath(root)
|
|
34
|
+
const result = []
|
|
35
|
+
const captured = []
|
|
36
|
+
let total = 0
|
|
37
|
+
async function walk(path, name, ancestors = new Set()) {
|
|
38
|
+
signal?.throwIfAborted()
|
|
39
|
+
const actual = await realpath(path)
|
|
40
|
+
const rel = relative(root, actual)
|
|
41
|
+
if (isAbsolute(rel) || rel === '..' || rel.startsWith('../')) throw contentError('MATERIAL_PATH_ESCAPE')
|
|
42
|
+
checkedMaterialPath(rel.split('\\').join('/'))
|
|
43
|
+
const info = await lstat(actual)
|
|
44
|
+
captured.push({ path, actual, size: info.size, mtimeMs: info.mtimeMs, ino: info.ino })
|
|
45
|
+
if (info.isDirectory()) {
|
|
46
|
+
if (ancestors.has(actual)) throw contentError('MATERIAL_PATH_CYCLE')
|
|
47
|
+
const next = new Set(ancestors).add(actual)
|
|
48
|
+
for (const child of (await readdir(actual)).sort()) {
|
|
49
|
+
if (forbidden.has(child)) continue
|
|
50
|
+
await walk(join(actual, child), name ? `${name}/${child}` : child, next)
|
|
51
|
+
}
|
|
52
|
+
const after = await lstat(actual)
|
|
53
|
+
if (info.ino !== after.ino || info.mtimeMs !== after.mtimeMs || info.ctimeMs !== after.ctimeMs)
|
|
54
|
+
throw contentError('MATERIAL_SOURCE_CHANGED')
|
|
55
|
+
onRead?.(actual, after)
|
|
56
|
+
return
|
|
57
|
+
}
|
|
58
|
+
if (!info.isFile()) throw contentError('MATERIAL_FILE_INVALID')
|
|
59
|
+
checkedMaterialPath(name)
|
|
60
|
+
total += info.size
|
|
61
|
+
if (total > maxBytes || result.length >= maxFiles) throw contentError('MATERIAL_LIMIT')
|
|
62
|
+
const bytes = await readFile(actual)
|
|
63
|
+
const after = await lstat(actual)
|
|
64
|
+
if (
|
|
65
|
+
info.size !== bytes.length ||
|
|
66
|
+
info.mtimeMs !== after.mtimeMs ||
|
|
67
|
+
info.ctimeMs !== after.ctimeMs ||
|
|
68
|
+
info.ino !== after.ino
|
|
69
|
+
)
|
|
70
|
+
throw contentError('MATERIAL_SOURCE_CHANGED')
|
|
71
|
+
onRead?.(actual, after)
|
|
72
|
+
result.push({ path: name, bytes })
|
|
73
|
+
}
|
|
74
|
+
for (const name of materialRoots) {
|
|
75
|
+
try {
|
|
76
|
+
await lstat(join(root, name))
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (error.code === 'ENOENT' && name !== 'package.json' && name !== 'package-lock.json') continue
|
|
79
|
+
throw error
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
await walk(join(root, name), name)
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (error.code === 'ENOENT') throw contentError('MATERIAL_SOURCE_CHANGED')
|
|
85
|
+
throw error
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
// Verify the whole captured tree after the last read. This detects membership
|
|
89
|
+
// changes and retargeted links without a separate content-hash protocol.
|
|
90
|
+
for (const entry of captured) {
|
|
91
|
+
signal?.throwIfAborted()
|
|
92
|
+
try {
|
|
93
|
+
if ((await realpath(entry.path)) !== entry.actual) throw contentError('MATERIAL_SOURCE_CHANGED')
|
|
94
|
+
const info = await lstat(entry.actual)
|
|
95
|
+
if (entry.size !== info.size || entry.mtimeMs !== info.mtimeMs || entry.ino !== info.ino)
|
|
96
|
+
throw contentError('MATERIAL_SOURCE_CHANGED')
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (error.code === 'ENOENT') throw contentError('MATERIAL_SOURCE_CHANGED')
|
|
99
|
+
throw error
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return result
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export async function writeMaterials(root, files, { signal, maxBytes = 256 * 1024 * 1024, maxFiles = 50000 } = {}) {
|
|
106
|
+
if (!Array.isArray(files) || files.length > maxFiles) throw contentError('MATERIAL_LIMIT')
|
|
107
|
+
const seen = new Set()
|
|
108
|
+
let total = 0
|
|
109
|
+
for (const file of files) {
|
|
110
|
+
signal?.throwIfAborted()
|
|
111
|
+
const path = checkedMaterialPath(file.path)
|
|
112
|
+
// Case aliases are rejected even on case-sensitive machines for portable archives.
|
|
113
|
+
const alias = path.toLowerCase()
|
|
114
|
+
if (seen.has(alias)) throw contentError('MATERIAL_PATH_DUPLICATE')
|
|
115
|
+
seen.add(alias)
|
|
116
|
+
if (
|
|
117
|
+
!Buffer.isBuffer(file.bytes) &&
|
|
118
|
+
(typeof file.data !== 'string' ||
|
|
119
|
+
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(file.data))
|
|
120
|
+
)
|
|
121
|
+
throw contentError('MATERIAL_ENCODING_INVALID')
|
|
122
|
+
const bytes = Buffer.isBuffer(file.bytes) ? file.bytes : Buffer.from(file.data, 'base64')
|
|
123
|
+
total += bytes.length
|
|
124
|
+
if (total > maxBytes) throw contentError('MATERIAL_LIMIT')
|
|
125
|
+
await mkdir(dirname(join(root, path)), { recursive: true })
|
|
126
|
+
await writeFile(join(root, path), bytes, { flag: 'wx', mode: 0o600 })
|
|
127
|
+
}
|
|
128
|
+
if (!seen.has('package.json') || !seen.has('package-lock.json')) throw contentError('MATERIAL_LOCK_REQUIRED')
|
|
129
|
+
// npm may omit this directory for a valid empty dependency graph. Static npm
|
|
130
|
+
// inspection still expects it, including after a file-only archive round trip.
|
|
131
|
+
await mkdir(join(root, 'node_modules'), { recursive: true })
|
|
132
|
+
const lock = JSON.parse(await readFile(join(root, 'package-lock.json'), 'utf8'))
|
|
133
|
+
if (![2, 3].includes(lock.lockfileVersion) || !lock.packages || typeof lock.packages !== 'object')
|
|
134
|
+
throw contentError('MATERIAL_LOCK_INVALID')
|
|
135
|
+
for (const pkg of Object.values(lock.packages)) {
|
|
136
|
+
if (!pkg || typeof pkg !== 'object') throw contentError('MATERIAL_LOCK_INVALID')
|
|
137
|
+
if (pkg.link === true) throw contentError('MATERIAL_LOCK_NOT_PORTABLE')
|
|
138
|
+
if (typeof pkg.resolved === 'string' && /^https?:/.test(pkg.resolved)) {
|
|
139
|
+
const url = new URL(pkg.resolved)
|
|
140
|
+
if (
|
|
141
|
+
url.username ||
|
|
142
|
+
url.password ||
|
|
143
|
+
[...url.searchParams.keys()].some(key => /token|secret|password|credential|authorization/i.test(key))
|
|
144
|
+
)
|
|
145
|
+
throw contentError('MATERIAL_LOCK_CREDENTIALS')
|
|
146
|
+
}
|
|
147
|
+
if (typeof pkg.resolved === 'string' && pkg.resolved.startsWith('file:')) {
|
|
148
|
+
const path = pkg.resolved.slice(5)
|
|
149
|
+
if (!path.startsWith('candidates/')) throw contentError('MATERIAL_LOCK_NOT_PORTABLE')
|
|
150
|
+
checkedMaterialPath(path)
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|