cortico-world-fun 0.7.7 → 0.8.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/CHANGELOG.md +37 -0
- package/README.md +28 -28
- package/describe.json +124 -337
- package/dist/webui.js +491 -362
- package/package.json +5 -5
- package/src/ENV_PROMPT.md +15 -14
- package/src/config.js +52 -50
- package/src/definition.js +6 -48
- package/src/state.js +30 -8
- package/src/story-dm.js +63 -32
- package/src/story-examples.js +15 -0
- package/src/story-free.js +88 -22
- package/src/story-library.js +355 -316
- package/src/story-packs.js +753 -745
- package/src/story-panel.js +11 -4
- package/src/story-read.js +4 -4
- package/src/story-reliability.js +19 -3
- package/src/story-secrets.js +29 -0
- package/src/world.js +568 -511
- package/src/aquarium.js +0 -27
- package/src/branches.js +0 -62
- package/src/choices.js +0 -54
package/src/story-packs.js
CHANGED
|
@@ -1,745 +1,753 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
|
-
import { areasNow, phaseAt } from './phases.js';
|
|
3
|
-
import { hoursState } from './venues.js';
|
|
4
|
-
import { DEFAULT_STORY_NODE_LIMIT, isValidStoryNodeLimit } from './story-node-limit.js';
|
|
5
|
-
|
|
6
|
-
const MAX_RAW_BYTES = 32 * 1024;
|
|
7
|
-
const ID_RE = /^[a-z0-9_-]{1,24}$/;
|
|
8
|
-
const PLACE_ID_RE = /^[a-z0-9_-]{1,40}$/;
|
|
9
|
-
const TIME_RE = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
|
|
10
|
-
const UNSAFE_TEXT_RE = /(?:https?:\/\/|ftp:\/\/|file:\/\/|javascript:|data:|vbscript:|<|>|(?:^|\s)(?:\/|\\\\|\.\.?(?:\/|\\)|[A-Za-z]:[\\/])|(?:^|\s)[\w.-]+(?:[\\/][\w.-]+)+|(?:^|[^\w])(?:eval|Function|fetch|XMLHttpRequest|require|import)\s*\()/i;
|
|
11
|
-
|
|
12
|
-
function isRecord(value) {
|
|
13
|
-
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
14
|
-
const proto = Object.getPrototypeOf(value);
|
|
15
|
-
return proto === Object.prototype || proto === null;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
function addUnknownKeys(value, allowed, path, errors) {
|
|
19
|
-
for (const key of Object.keys(value)) {
|
|
20
|
-
if (!allowed.has(key)) errors.push(`${path}.${key}: unsupported field`);
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function textValue(value, path, max, errors, { required = true } = {}) {
|
|
25
|
-
if (value === undefined && !required) return undefined;
|
|
26
|
-
if (typeof value !== 'string') {
|
|
27
|
-
errors.push(`${path}: must be a string`);
|
|
28
|
-
return undefined;
|
|
29
|
-
}
|
|
30
|
-
const normalized = value.replace(/\r\n?/g, '\n').replace(/[\t\n ]+/g, ' ').trim();
|
|
31
|
-
if (required && !normalized) errors.push(`${path}: must not be empty`);
|
|
32
|
-
if (normalized.length > max) errors.push(`${path}: exceeds ${max} characters`);
|
|
33
|
-
if (UNSAFE_TEXT_RE.test(normalized)) errors.push(`${path}: executable or network/path content is not allowed`);
|
|
34
|
-
return normalized;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function validId(value, path, errors) {
|
|
38
|
-
if (typeof value !== 'string' || !ID_RE.test(value)) {
|
|
39
|
-
errors.push(`${path}: must match [a-z0-9_-]{1,24}`);
|
|
40
|
-
return undefined;
|
|
41
|
-
}
|
|
42
|
-
return value;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function canonicalRevision(content) {
|
|
46
|
-
return createHash('sha256').update(JSON.stringify(content), 'utf8').digest('hex').slice(0, 32);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
function parseRaw(raw, errors) {
|
|
50
|
-
let value = raw;
|
|
51
|
-
if (typeof raw === 'string') {
|
|
52
|
-
if (Buffer.byteLength(raw, 'utf8') > MAX_RAW_BYTES) {
|
|
53
|
-
errors.push('root: JSON exceeds 32 KB');
|
|
54
|
-
return null;
|
|
55
|
-
}
|
|
56
|
-
try {
|
|
57
|
-
value = JSON.parse(raw);
|
|
58
|
-
} catch {
|
|
59
|
-
errors.push('root: invalid JSON');
|
|
60
|
-
return null;
|
|
61
|
-
}
|
|
62
|
-
} else {
|
|
63
|
-
try {
|
|
64
|
-
const encoded = JSON.stringify(raw);
|
|
65
|
-
if (typeof encoded !== 'string' || Buffer.byteLength(encoded, 'utf8') > MAX_RAW_BYTES) {
|
|
66
|
-
errors.push('root: JSON exceeds 32 KB or is not serializable');
|
|
67
|
-
return null;
|
|
68
|
-
}
|
|
69
|
-
} catch {
|
|
70
|
-
errors.push('root: value is not serializable JSON');
|
|
71
|
-
return null;
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
return value;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function normalizeWhen(raw, path, errors) {
|
|
78
|
-
if (raw === undefined) return undefined;
|
|
79
|
-
if (!isRecord(raw)) {
|
|
80
|
-
errors.push(`${path}: must be an object`);
|
|
81
|
-
return undefined;
|
|
82
|
-
}
|
|
83
|
-
addUnknownKeys(raw, new Set(['from', 'to', 'phases', 'minVisits']), path, errors);
|
|
84
|
-
const out = {};
|
|
85
|
-
if ((raw.from === undefined) !== (raw.to === undefined)) {
|
|
86
|
-
errors.push(`${path}: from and to must be supplied together`);
|
|
87
|
-
}
|
|
88
|
-
if (raw.from !== undefined) {
|
|
89
|
-
if (typeof raw.from !== 'string' || !TIME_RE.test(raw.from)) errors.push(`${path}.from: must be HH:MM`);
|
|
90
|
-
else out.from = raw.from;
|
|
91
|
-
}
|
|
92
|
-
if (raw.to !== undefined) {
|
|
93
|
-
if (typeof raw.to !== 'string' || !TIME_RE.test(raw.to)) errors.push(`${path}.to: must be HH:MM`);
|
|
94
|
-
else out.to = raw.to;
|
|
95
|
-
}
|
|
96
|
-
if (out.from !== undefined && out.to !== undefined && out.from === out.to) {
|
|
97
|
-
errors.push(`${path}: from and to must describe a non-empty time window`);
|
|
98
|
-
}
|
|
99
|
-
if (raw.phases !== undefined) {
|
|
100
|
-
if (!Array.isArray(raw.phases) || raw.phases.length > 16) {
|
|
101
|
-
errors.push(`${path}.phases: must be an array of at most 16 phase ids`);
|
|
102
|
-
} else {
|
|
103
|
-
const phases = [];
|
|
104
|
-
for (const [index, phase] of raw.phases.entries()) {
|
|
105
|
-
const id = validId(phase, `${path}.phases[${index}]`, errors);
|
|
106
|
-
if (id !== undefined) phases.push(id);
|
|
107
|
-
}
|
|
108
|
-
if (new Set(phases).size !== phases.length) errors.push(`${path}.phases: ids must be unique`);
|
|
109
|
-
out.phases = phases;
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
if (raw.minVisits !== undefined) {
|
|
113
|
-
if (!Number.isInteger(raw.minVisits) || raw.minVisits < 0 || raw.minVisits > 100000) {
|
|
114
|
-
errors.push(`${path}.minVisits: must be an integer from 0 to 100000`);
|
|
115
|
-
} else out.minVisits = raw.minVisits;
|
|
116
|
-
}
|
|
117
|
-
return out;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function normalizeReferences(raw, nodes, errors) {
|
|
121
|
-
if (raw === undefined) return [];
|
|
122
|
-
if (!Array.isArray(raw) || raw.length > 24) {
|
|
123
|
-
errors.push('references: must be an array of at most 24 entries');
|
|
124
|
-
return [];
|
|
125
|
-
}
|
|
126
|
-
return raw.flatMap((item, i) => {
|
|
127
|
-
const path = `references[${i}]`;
|
|
128
|
-
if (!isRecord(item)) { errors.push(`${path}: must be an object`); return []; }
|
|
129
|
-
addUnknownKeys(item, new Set(['area', 'afterNode', 'afterChoice', 'audience', 'text']), path, errors);
|
|
130
|
-
const area = textValue(item.area, `${path}.area`, 80, errors);
|
|
131
|
-
const afterNode = validId(item.afterNode, `${path}.afterNode`, errors);
|
|
132
|
-
const afterChoice = item.afterChoice === undefined ? undefined : validId(item.afterChoice, `${path}.afterChoice`, errors);
|
|
133
|
-
const node = nodes.find((entry) => afterNode && entry.id === afterNode);
|
|
134
|
-
if (!node) errors.push(`${path}.afterNode: node does not exist`);
|
|
135
|
-
if (!nodes.some((entry) => entry.area === area)) errors.push(`${path}.area: must be an authored story area`);
|
|
136
|
-
if (afterChoice && !node?.choices?.some((choice) => choice.id === afterChoice)) errors.push(`${path}.afterChoice: must be a choice of afterNode`);
|
|
137
|
-
if (!['player', 'fish', 'dm'].includes(item.audience)) errors.push(`${path}.audience: must be player, fish, or dm`);
|
|
138
|
-
const text = textValue(item.text, `${path}.text`, 240, errors);
|
|
139
|
-
return [{ area, afterNode, ...(afterChoice ? { afterChoice } : {}), audience: item.audience, text }];
|
|
140
|
-
});
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/** Only send unlocked references for this audience; never send the conditions or other text. */
|
|
144
|
-
export function storyReferences(pack, outing, audience) {
|
|
145
|
-
const progress = outing?.storyProgress?.find((entry) => entry.packId === pack?.id && entry.revision === pack?.revision);
|
|
146
|
-
const area = outing?.visited?.at(-1)?.area;
|
|
147
|
-
if (!area || !progress?.triggered?.length) return [];
|
|
148
|
-
return (pack.references ?? []).filter((item) => item.audience === audience && item.area === area
|
|
149
|
-
&& progress.triggered.includes(item.afterNode)
|
|
150
|
-
&& (!item.afterChoice || (outing.choices ?? []).some((choice) => choice.option === item.afterChoice)))
|
|
151
|
-
.slice(0, 6).map((item) => item.text);
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/** Validate and canonicalize an authored version-1 or version-2 story pack. */
|
|
155
|
-
export function validateStoryPack(raw, options = {}) {
|
|
156
|
-
const requestedLimit = options?.maxNodes;
|
|
157
|
-
const maxNodes = requestedLimit === undefined ? DEFAULT_STORY_NODE_LIMIT
|
|
158
|
-
: isValidStoryNodeLimit(requestedLimit) ? requestedLimit : DEFAULT_STORY_NODE_LIMIT;
|
|
159
|
-
const errors = [];
|
|
160
|
-
const value = parseRaw(raw, errors);
|
|
161
|
-
if (!isRecord(value)) {
|
|
162
|
-
if (value !== null) errors.push('root: must be an object');
|
|
163
|
-
return { ok: false, pack: null, errors };
|
|
164
|
-
}
|
|
165
|
-
// 自由模式(场景包)与选项图是两套内容形态,走各自的校验,互不影响。
|
|
166
|
-
if (value.version === 3) return validateFreePack(value, errors);
|
|
167
|
-
if (![1, 2].includes(value.version)) errors.push('version: must equal 1 or 2');
|
|
168
|
-
const version = value.version;
|
|
169
|
-
const rootKeys = new Set(['version', 'id', 'title', 'description', 'placeId', 'start', 'nodes', ...(version === 2 ? ['metadata', 'references'] : [])]);
|
|
170
|
-
addUnknownKeys(value, rootKeys, '$', errors);
|
|
171
|
-
const id = validId(value.id, 'id', errors);
|
|
172
|
-
let placeId;
|
|
173
|
-
if (typeof value.placeId !== 'string' || !PLACE_ID_RE.test(value.placeId)) {
|
|
174
|
-
errors.push('placeId: must match [a-z0-9_-]{1,40}');
|
|
175
|
-
} else placeId = value.placeId;
|
|
176
|
-
const start = validId(value.start, 'start', errors);
|
|
177
|
-
const title = textValue(value.title, 'title', 80, errors);
|
|
178
|
-
const description = textValue(value.description, 'description', 240, errors, { required: false });
|
|
179
|
-
let metadata;
|
|
180
|
-
if (version === 2) {
|
|
181
|
-
if (!isRecord(value.metadata)) {
|
|
182
|
-
errors.push('metadata: must be an object for version 2');
|
|
183
|
-
} else {
|
|
184
|
-
const rawMetadata = value.metadata;
|
|
185
|
-
addUnknownKeys(rawMetadata, new Set(['author', 'release', 'genre', 'synopsis', 'participation', 'durationMinutes', 'requirements', 'seriesId', 'chapter', 'requiresCompleted', 'jointResolution']), 'metadata', errors);
|
|
186
|
-
const author = textValue(rawMetadata.author, 'metadata.author', 80, errors);
|
|
187
|
-
const release = textValue(rawMetadata.release, 'metadata.release', 24, errors);
|
|
188
|
-
if (release && !/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,23}$/.test(release)) errors.push('metadata.release: must be a short version label');
|
|
189
|
-
const genre = textValue(rawMetadata.genre, 'metadata.genre', 40, errors);
|
|
190
|
-
const synopsis = textValue(rawMetadata.synopsis, 'metadata.synopsis', 240, errors);
|
|
191
|
-
const participation = rawMetadata.participation;
|
|
192
|
-
if (!['solo', 'duo'].includes(participation)) errors.push('metadata.participation: must be solo or duo');
|
|
193
|
-
let jointResolution;
|
|
194
|
-
if (rawMetadata.jointResolution !== undefined) {
|
|
195
|
-
if (!['require-agreement', 'owner-final', 'fish-final'].includes(rawMetadata.jointResolution)) errors.push('metadata.jointResolution: must be require-agreement, owner-final, or fish-final');
|
|
196
|
-
else jointResolution = rawMetadata.jointResolution;
|
|
197
|
-
}
|
|
198
|
-
let durationMinutes;
|
|
199
|
-
if (rawMetadata.durationMinutes !== undefined) {
|
|
200
|
-
if (!Number.isInteger(rawMetadata.durationMinutes) || rawMetadata.durationMinutes < 1 || rawMetadata.durationMinutes > 600) errors.push('metadata.durationMinutes: must be an integer from 1 to 600');
|
|
201
|
-
else durationMinutes = rawMetadata.durationMinutes;
|
|
202
|
-
}
|
|
203
|
-
let requirements = [];
|
|
204
|
-
if (rawMetadata.requirements !== undefined) {
|
|
205
|
-
if (!Array.isArray(rawMetadata.requirements) || rawMetadata.requirements.length > 8) errors.push('metadata.requirements: must be an array of at most 8 items');
|
|
206
|
-
else requirements = rawMetadata.requirements.map((item, index) => textValue(item, `metadata.requirements[${index}]`, 80, errors));
|
|
207
|
-
}
|
|
208
|
-
let seriesId;
|
|
209
|
-
if (rawMetadata.seriesId !== undefined) seriesId = validId(rawMetadata.seriesId, 'metadata.seriesId', errors);
|
|
210
|
-
let chapter;
|
|
211
|
-
if (rawMetadata.chapter !== undefined) {
|
|
212
|
-
if (!Number.isInteger(rawMetadata.chapter) || rawMetadata.chapter < 1 || rawMetadata.chapter > 1000) errors.push('metadata.chapter: must be an integer from 1 to 1000');
|
|
213
|
-
else chapter = rawMetadata.chapter;
|
|
214
|
-
}
|
|
215
|
-
if ((seriesId === undefined) !== (chapter === undefined)) errors.push('metadata.seriesId and metadata.chapter must be supplied together');
|
|
216
|
-
let requiresCompleted = [];
|
|
217
|
-
if (rawMetadata.requiresCompleted !== undefined) {
|
|
218
|
-
if (!Array.isArray(rawMetadata.requiresCompleted) || rawMetadata.requiresCompleted.length > 8) errors.push('metadata.requiresCompleted: must be an array of at most 8 story ids');
|
|
219
|
-
else requiresCompleted = rawMetadata.requiresCompleted.map((item, index) => validId(item, `metadata.requiresCompleted[${index}]`, errors)).filter(Boolean);
|
|
220
|
-
if (new Set(requiresCompleted).size !== requiresCompleted.length) errors.push('metadata.requiresCompleted: ids must be unique');
|
|
221
|
-
}
|
|
222
|
-
if (participation === 'duo' && !jointResolution) errors.push('metadata.jointResolution: required for duo stories');
|
|
223
|
-
if (participation === 'solo' && jointResolution) errors.push('metadata.jointResolution: only valid for duo stories');
|
|
224
|
-
metadata = { author, release, genre, synopsis, participation, ...(jointResolution ? { jointResolution } : {}), ...(durationMinutes !== undefined ? { durationMinutes } : {}), requirements,
|
|
225
|
-
...(seriesId !== undefined ? { seriesId, chapter } : {}), ...(requiresCompleted.length ? { requiresCompleted } : {}) };
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
const nodes = [];
|
|
230
|
-
const rawNodes = value.nodes;
|
|
231
|
-
if (!Array.isArray(rawNodes) || rawNodes.length < 1 || (maxNodes !== 0 && rawNodes.length > maxNodes)) {
|
|
232
|
-
errors.push(maxNodes === 0 ? 'nodes: must contain at least 1 node' : `nodes: must contain 1 to ${maxNodes} nodes`);
|
|
233
|
-
} else {
|
|
234
|
-
for (const [index, rawNode] of rawNodes.entries()) {
|
|
235
|
-
const path = `nodes[${index}]`;
|
|
236
|
-
if (!isRecord(rawNode)) {
|
|
237
|
-
errors.push(`${path}: must be an object`);
|
|
238
|
-
continue;
|
|
239
|
-
}
|
|
240
|
-
addUnknownKeys(rawNode, new Set(['id', 'area', 'event', 'prompt', 'when', 'choices', 'next', ...(version === 2 ? ['actor'] : [])]), path, errors);
|
|
241
|
-
const nodeId = validId(rawNode.id, `${path}.id`, errors);
|
|
242
|
-
const area = textValue(rawNode.area, `${path}.area`, 80, errors);
|
|
243
|
-
const event = textValue(rawNode.event, `${path}.event`, 120, errors);
|
|
244
|
-
const prompt = textValue(rawNode.prompt, `${path}.prompt`, 160, errors, { required: false });
|
|
245
|
-
const when = normalizeWhen(rawNode.when, `${path}.when`, errors);
|
|
246
|
-
let actor;
|
|
247
|
-
if (version === 2 && rawNode.choices !== undefined) {
|
|
248
|
-
actor = rawNode.actor;
|
|
249
|
-
if (metadata?.participation === 'duo') {
|
|
250
|
-
if (!['owner', 'fish', 'joint'].includes(actor)) errors.push(`${path}.actor: duo choice nodes require owner, fish, or joint`);
|
|
251
|
-
} else if (actor !== undefined && actor !== 'owner') errors.push(`${path}.actor: solo stories cannot declare a fish or joint turn`);
|
|
252
|
-
if (metadata?.participation === 'solo') actor = undefined;
|
|
253
|
-
} else if (version === 2 && rawNode.actor !== undefined) {
|
|
254
|
-
errors.push(`${path}.actor: only choice nodes may declare an actor`);
|
|
255
|
-
}
|
|
256
|
-
if (version === 1 && rawNode.actor !== undefined) errors.push(`${path}.actor: requires version 2`);
|
|
257
|
-
let next;
|
|
258
|
-
if (rawNode.next !== undefined) next = validId(rawNode.next, `${path}.next`, errors);
|
|
259
|
-
|
|
260
|
-
let choices;
|
|
261
|
-
if (rawNode.choices !== undefined) {
|
|
262
|
-
if (!Array.isArray(rawNode.choices) || rawNode.choices.length < 2 || rawNode.choices.length > 4) {
|
|
263
|
-
errors.push(`${path}.choices: must contain 2 to 4 options`);
|
|
264
|
-
} else {
|
|
265
|
-
choices = [];
|
|
266
|
-
for (const [choiceIndex, rawChoice] of rawNode.choices.entries()) {
|
|
267
|
-
const choicePath = `${path}.choices[${choiceIndex}]`;
|
|
268
|
-
if (!isRecord(rawChoice)) {
|
|
269
|
-
errors.push(`${choicePath}: must be an object`);
|
|
270
|
-
continue;
|
|
271
|
-
}
|
|
272
|
-
addUnknownKeys(rawChoice, new Set(['id', 'label', 'result', 'next']), choicePath, errors);
|
|
273
|
-
const choiceId = validId(rawChoice.id, `${choicePath}.id`, errors);
|
|
274
|
-
if (choiceId === 'skip') errors.push(`${choicePath}.id: skip is reserved`);
|
|
275
|
-
const label = textValue(rawChoice.label, `${choicePath}.label`, 160, errors);
|
|
276
|
-
const result = textValue(rawChoice.result, `${choicePath}.result`, 160, errors);
|
|
277
|
-
let choiceNext;
|
|
278
|
-
if (rawChoice.next !== undefined) choiceNext = validId(rawChoice.next, `${choicePath}.next`, errors);
|
|
279
|
-
choices.push({ id: choiceId, label, result, ...(choiceNext !== undefined ? { next: choiceNext } : {}) });
|
|
280
|
-
}
|
|
281
|
-
if (choices.length === rawNode.choices.length && new Set(choices.map((choice) => choice.id)).size !== choices.length) {
|
|
282
|
-
errors.push(`${path}.choices: ids must be unique`);
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
if (rawNode.next !== undefined) errors.push(`${path}: use either choices or next, not both`);
|
|
286
|
-
}
|
|
287
|
-
nodes.push({
|
|
288
|
-
id: nodeId,
|
|
289
|
-
area,
|
|
290
|
-
event,
|
|
291
|
-
...(prompt !== undefined ? { prompt } : {}),
|
|
292
|
-
...(when !== undefined ? { when } : {}),
|
|
293
|
-
...(choices !== undefined ? { choices } : {}),
|
|
294
|
-
...(next !== undefined ? { next } : {}),
|
|
295
|
-
...(actor !== undefined && ['owner', 'fish', 'joint'].includes(actor) ? { actor } : {}),
|
|
296
|
-
});
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
if (nodes.length === rawNodes?.length) {
|
|
301
|
-
const ids = nodes.map((node) => node.id);
|
|
302
|
-
if (new Set(ids).size !== ids.length) errors.push('nodes: ids must be unique');
|
|
303
|
-
const nodeIds = new Set(ids);
|
|
304
|
-
if (start !== undefined && !nodeIds.has(start)) errors.push('start: node does not exist');
|
|
305
|
-
const choiceIds = new Set();
|
|
306
|
-
for (const node of nodes) {
|
|
307
|
-
if (node.choices) {
|
|
308
|
-
for (const choice of node.choices) {
|
|
309
|
-
if (choice.id !== undefined) choiceIds.add(choice.id);
|
|
310
|
-
if (choice.next !== undefined && !nodeIds.has(choice.next)) errors.push(`nodes.${node.id}.choices.${choice.id}: next node does not exist`);
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
if (node.next !== undefined && !nodeIds.has(node.next)) errors.push(`nodes.${node.id}.next: node does not exist`);
|
|
314
|
-
}
|
|
315
|
-
if (choiceIds.size < nodes.flatMap((node) => node.choices ?? []).length) errors.push('choices: ids must be unique within a pack');
|
|
316
|
-
|
|
317
|
-
if (start !== undefined && nodeIds.has(start)) {
|
|
318
|
-
const byId = new Map(nodes.map((node) => [node.id, node]));
|
|
319
|
-
const reached = new Set();
|
|
320
|
-
const visiting = new Set();
|
|
321
|
-
const visited = new Set();
|
|
322
|
-
let cycle = false;
|
|
323
|
-
const visit = (nodeId) => {
|
|
324
|
-
if (visiting.has(nodeId)) { cycle = true; return; }
|
|
325
|
-
if (visited.has(nodeId)) return;
|
|
326
|
-
const node = byId.get(nodeId);
|
|
327
|
-
if (!node) return;
|
|
328
|
-
visiting.add(nodeId);
|
|
329
|
-
reached.add(nodeId);
|
|
330
|
-
const edges = node.choices ? node.choices.map((choice) => choice.next).filter(Boolean) : (node.next ? [node.next] : []);
|
|
331
|
-
for (const target of edges) visit(target);
|
|
332
|
-
visiting.delete(nodeId);
|
|
333
|
-
visited.add(nodeId);
|
|
334
|
-
};
|
|
335
|
-
visit(start);
|
|
336
|
-
if (cycle) errors.push('nodes: graph must not contain cycles');
|
|
337
|
-
if (reached.size !== nodes.length) errors.push('nodes: every node must be reachable from start');
|
|
338
|
-
const hasTerminal = nodes.some((node) => reached.has(node.id) && (
|
|
339
|
-
node.choices ? node.choices.some((choice) => !choice.next) : !node.next
|
|
340
|
-
));
|
|
341
|
-
if (!hasTerminal) errors.push('nodes: graph must have a terminal path');
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
const references = version === 2 ? normalizeReferences(value.references, nodes, errors) : [];
|
|
346
|
-
if (errors.length) return { ok: false, pack: null, errors };
|
|
347
|
-
const content = {
|
|
348
|
-
version,
|
|
349
|
-
id,
|
|
350
|
-
title,
|
|
351
|
-
...(description !== undefined ? { description } : {}),
|
|
352
|
-
...(version === 2 ? { metadata } : {}),
|
|
353
|
-
...(references.length ? { references } : {}),
|
|
354
|
-
placeId,
|
|
355
|
-
start,
|
|
356
|
-
nodes,
|
|
357
|
-
};
|
|
358
|
-
const pack = { ...content, revision: canonicalRevision(content) };
|
|
359
|
-
return { ok: true, pack, errors: [] };
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
const FREE_STATE_ID = /^[a-z0-9_-]{1,24}$/;
|
|
363
|
-
const FREE_WHEN_KEYS = new Set(['all', 'any', 'flag', 'counter', 'fact', 'gte', 'lte', 'equals']);
|
|
364
|
-
|
|
365
|
-
function textList(raw, path, maxItems, maxChars, errors) {
|
|
366
|
-
if (raw === undefined) return [];
|
|
367
|
-
if (!Array.isArray(raw) || raw.length > maxItems) {
|
|
368
|
-
errors.push(`${path}: must be an array of at most ${maxItems} strings`);
|
|
369
|
-
return [];
|
|
370
|
-
}
|
|
371
|
-
return raw.map((item, index) => textValue(item, `${path}[${index}]`, maxChars, errors)).filter((item) => item !== undefined);
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
function freeIds(raw, path, maxItems, build, errors) {
|
|
375
|
-
if (!Array.isArray(raw) || raw.length > maxItems) {
|
|
376
|
-
errors.push(`${path}: must be an array of at most ${maxItems} entries`);
|
|
377
|
-
return [];
|
|
378
|
-
}
|
|
379
|
-
const out = [];
|
|
380
|
-
for (const [index, item] of raw.entries()) {
|
|
381
|
-
const itemPath = `${path}[${index}]`;
|
|
382
|
-
if (!isRecord(item)) { errors.push(`${itemPath}: must be an object`); continue; }
|
|
383
|
-
out.push(build(item, itemPath, errors));
|
|
384
|
-
}
|
|
385
|
-
const ids = out.map((entry) => entry?.id).filter(Boolean);
|
|
386
|
-
if (new Set(ids).size !== ids.length) errors.push(`${path}: ids must be unique`);
|
|
387
|
-
return out.filter(Boolean);
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
/** 自由模式的判定条件:all / any / flag / counter / fact,只引用已登记的状态 id。 */
|
|
391
|
-
function normalizeFreeWhen(raw, path, errors, stateIds) {
|
|
392
|
-
if (raw === undefined) return undefined;
|
|
393
|
-
if (!isRecord(raw)) { errors.push(`${path}: must be an object`); return undefined; }
|
|
394
|
-
addUnknownKeys(raw, FREE_WHEN_KEYS, path, errors);
|
|
395
|
-
const keys = Object.keys(raw).filter((key) => ['all', 'any', 'flag', 'counter', 'fact'].includes(key));
|
|
396
|
-
if (keys.length !== 1) { errors.push(`${path}: must contain exactly one of all, any, flag, counter, fact`); return undefined; }
|
|
397
|
-
const key = keys[0];
|
|
398
|
-
if (key === 'all' || key === 'any') {
|
|
399
|
-
if (!Array.isArray(raw[key]) || raw[key].length < 1 || raw[key].length > 8) {
|
|
400
|
-
errors.push(`${path}.${key}: must be an array of 1 to 8 conditions`);
|
|
401
|
-
return undefined;
|
|
402
|
-
}
|
|
403
|
-
const clauses = raw[key].map((item, index) => normalizeFreeWhen(item, `${path}.${key}[${index}]`, errors, stateIds)).filter(Boolean);
|
|
404
|
-
return { [key]: clauses };
|
|
405
|
-
}
|
|
406
|
-
if (key === 'flag') {
|
|
407
|
-
if (typeof raw.flag !== 'string' || !stateIds.flags.has(raw.flag)) { errors.push(`${path}.flag: unknown flag id`); return undefined; }
|
|
408
|
-
return { flag: raw.flag };
|
|
409
|
-
}
|
|
410
|
-
if (key === 'counter') {
|
|
411
|
-
if (typeof raw.counter !== 'string' || !stateIds.counters.has(raw.counter)) { errors.push(`${path}.counter: unknown counter id`); return undefined; }
|
|
412
|
-
const clause = { counter: raw.counter };
|
|
413
|
-
for (const field of ['gte', 'lte']) {
|
|
414
|
-
if (raw[field] === undefined) continue;
|
|
415
|
-
if (!Number.isSafeInteger(raw[field])) { errors.push(`${path}.${field}: must be an integer`); continue; }
|
|
416
|
-
clause[field] = raw[field];
|
|
417
|
-
}
|
|
418
|
-
if (clause.gte === undefined && clause.lte === undefined) { errors.push(`${path}: counter condition needs gte or lte`); return undefined; }
|
|
419
|
-
return clause;
|
|
420
|
-
}
|
|
421
|
-
if (typeof raw.fact !== 'string' || !stateIds.facts.has(raw.fact)) { errors.push(`${path}.fact: unknown fact id`); return undefined; }
|
|
422
|
-
if (typeof raw.equals !== 'string') { errors.push(`${path}.equals: must be a string`); return undefined; }
|
|
423
|
-
return { fact: raw.fact, equals: raw.equals.slice(0, 200) };
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
function normalizeFreeSetting(raw, errors) {
|
|
427
|
-
if (!isRecord(raw)) { errors.push('setting: must be an object for version 3'); return undefined; }
|
|
428
|
-
addUnknownKeys(raw, new Set(['premise', 'canon', 'forbidden', 'cast', 'locations', 'opening', 'flags', 'counters', 'facts', 'goals', 'ends', 'beats']), 'setting', errors);
|
|
429
|
-
const premise = textValue(raw.premise, 'setting.premise', 240, errors);
|
|
430
|
-
const opening = textValue(raw.opening, 'setting.opening', 400, errors);
|
|
431
|
-
const canon = textList(raw.canon, 'setting.canon', 12, 120, errors);
|
|
432
|
-
if (canon.length < 3) errors.push('setting.canon: needs at least 3 fixed facts');
|
|
433
|
-
const forbidden = textList(raw.forbidden, 'setting.forbidden', 8, 120, errors);
|
|
434
|
-
const beats = textList(raw.beats, 'setting.beats', 6, 60, errors);
|
|
435
|
-
|
|
436
|
-
const cast = freeIds(raw.cast, 'setting.cast', 8, (item, path) => ({
|
|
437
|
-
id: validId(item.id, `${path}.id`, errors),
|
|
438
|
-
name: textValue(item.name, `${path}.name`, 40, errors),
|
|
439
|
-
role: textValue(item.role, `${path}.role`, 120, errors, { required: false }) ?? '',
|
|
440
|
-
secret: textValue(item.secret, `${path}.secret`, 120, errors, { required: false }) ?? '',
|
|
441
|
-
}), errors);
|
|
442
|
-
const locations = freeIds(raw.locations, 'setting.locations', 8, (item, path) => ({
|
|
443
|
-
id: validId(item.id, `${path}.id`, errors),
|
|
444
|
-
name: textValue(item.name, `${path}.name`, 40, errors),
|
|
445
|
-
desc: textValue(item.desc, `${path}.desc`, 160, errors, { required: false }) ?? '',
|
|
446
|
-
}), errors);
|
|
447
|
-
const flags = freeIds(raw.flags, 'setting.flags', 12, (item, path) => ({
|
|
448
|
-
id: validId(item.id, `${path}.id`, errors),
|
|
449
|
-
label: textValue(item.label, `${path}.label`, 40, errors, { required: false }) ?? '',
|
|
450
|
-
initial: item.initial === true,
|
|
451
|
-
}), errors);
|
|
452
|
-
const facts = freeIds(raw.facts, 'setting.facts', 12, (item, path) => ({
|
|
453
|
-
id: validId(item.id, `${path}.id`, errors),
|
|
454
|
-
label: textValue(item.label, `${path}.label`, 40, errors, { required: false }) ?? '',
|
|
455
|
-
initial: textValue(item.initial, `${path}.initial`, 200, errors, { required: false }) ?? '',
|
|
456
|
-
}), errors);
|
|
457
|
-
const counters = freeIds(raw.counters, 'setting.counters', 8, (item, path) => {
|
|
458
|
-
const min = Number.isSafeInteger(item.min) ? item.min : 0;
|
|
459
|
-
const max = Number.isSafeInteger(item.max) ? item.max : 10;
|
|
460
|
-
if (min < 0 || max > 100 || min >= max) errors.push(`${path}: needs 0 <= min < max <= 100`);
|
|
461
|
-
const initial = Number.isSafeInteger(item.initial) ? item.initial : min;
|
|
462
|
-
if (initial < min || initial > max) errors.push(`${path}.initial: must be within min..max`);
|
|
463
|
-
return { id: validId(item.id, `${path}.id`, errors), label: textValue(item.label, `${path}.label`, 40, errors, { required: false }) ?? '', min, max, initial };
|
|
464
|
-
}, errors);
|
|
465
|
-
|
|
466
|
-
// 三个状态区共用一个 id 空间:delta 里写的是哪个区都不许含糊。
|
|
467
|
-
const stateIds = {
|
|
468
|
-
flags: new Set(flags.map((item) => item.id)),
|
|
469
|
-
counters: new Set(counters.map((item) => item.id)),
|
|
470
|
-
facts: new Set(facts.map((item) => item.id)),
|
|
471
|
-
};
|
|
472
|
-
const allStateIds = new Set([...stateIds.flags, ...stateIds.counters, ...stateIds.facts]);
|
|
473
|
-
if (allStateIds.size !== stateIds.flags.size + stateIds.counters.size + stateIds.facts.size) errors.push('setting: flag/counter/fact ids must not repeat across sections');
|
|
474
|
-
|
|
475
|
-
const goals = freeIds(raw.goals, 'setting.goals', 4, (item, path) => ({
|
|
476
|
-
id: validId(item.id, `${path}.id`, errors),
|
|
477
|
-
text: textValue(item.text, `${path}.text`, 120, errors),
|
|
478
|
-
when: normalizeFreeWhen(item.when, `${path}.when`, errors, stateIds),
|
|
479
|
-
}), errors);
|
|
480
|
-
const ends = freeIds(raw.ends, 'setting.ends', 4, (item, path) => {
|
|
481
|
-
const when = normalizeFreeWhen(item.when, `${path}.when`, errors, stateIds);
|
|
482
|
-
if (when === undefined) errors.push(`${path}.when: endings need a condition`);
|
|
483
|
-
return { id: validId(item.id, `${path}.id`, errors), text: textValue(item.text, `${path}.text`, 120, errors), when };
|
|
484
|
-
}, errors);
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
const
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
const
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
const
|
|
517
|
-
const
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
const
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
const
|
|
539
|
-
const
|
|
540
|
-
|
|
541
|
-
const
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
const
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
const
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
if (
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
}
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
const
|
|
602
|
-
if (!
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
if (
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
return
|
|
642
|
-
}
|
|
643
|
-
if (
|
|
644
|
-
return
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
return
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
const
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
if (
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
entry.waitingChoiceId
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
}
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
}
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
}
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { areasNow, phaseAt } from './phases.js';
|
|
3
|
+
import { hoursState } from './venues.js';
|
|
4
|
+
import { DEFAULT_STORY_NODE_LIMIT, isValidStoryNodeLimit } from './story-node-limit.js';
|
|
5
|
+
|
|
6
|
+
const MAX_RAW_BYTES = 32 * 1024;
|
|
7
|
+
const ID_RE = /^[a-z0-9_-]{1,24}$/;
|
|
8
|
+
const PLACE_ID_RE = /^[a-z0-9_-]{1,40}$/;
|
|
9
|
+
const TIME_RE = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
|
|
10
|
+
const UNSAFE_TEXT_RE = /(?:https?:\/\/|ftp:\/\/|file:\/\/|javascript:|data:|vbscript:|<|>|(?:^|\s)(?:\/|\\\\|\.\.?(?:\/|\\)|[A-Za-z]:[\\/])|(?:^|\s)[\w.-]+(?:[\\/][\w.-]+)+|(?:^|[^\w])(?:eval|Function|fetch|XMLHttpRequest|require|import)\s*\()/i;
|
|
11
|
+
|
|
12
|
+
function isRecord(value) {
|
|
13
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
14
|
+
const proto = Object.getPrototypeOf(value);
|
|
15
|
+
return proto === Object.prototype || proto === null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function addUnknownKeys(value, allowed, path, errors) {
|
|
19
|
+
for (const key of Object.keys(value)) {
|
|
20
|
+
if (!allowed.has(key)) errors.push(`${path}.${key}: unsupported field`);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function textValue(value, path, max, errors, { required = true } = {}) {
|
|
25
|
+
if (value === undefined && !required) return undefined;
|
|
26
|
+
if (typeof value !== 'string') {
|
|
27
|
+
errors.push(`${path}: must be a string`);
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
const normalized = value.replace(/\r\n?/g, '\n').replace(/[\t\n ]+/g, ' ').trim();
|
|
31
|
+
if (required && !normalized) errors.push(`${path}: must not be empty`);
|
|
32
|
+
if (normalized.length > max) errors.push(`${path}: exceeds ${max} characters`);
|
|
33
|
+
if (UNSAFE_TEXT_RE.test(normalized)) errors.push(`${path}: executable or network/path content is not allowed`);
|
|
34
|
+
return normalized;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function validId(value, path, errors) {
|
|
38
|
+
if (typeof value !== 'string' || !ID_RE.test(value)) {
|
|
39
|
+
errors.push(`${path}: must match [a-z0-9_-]{1,24}`);
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function canonicalRevision(content) {
|
|
46
|
+
return createHash('sha256').update(JSON.stringify(content), 'utf8').digest('hex').slice(0, 32);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function parseRaw(raw, errors) {
|
|
50
|
+
let value = raw;
|
|
51
|
+
if (typeof raw === 'string') {
|
|
52
|
+
if (Buffer.byteLength(raw, 'utf8') > MAX_RAW_BYTES) {
|
|
53
|
+
errors.push('root: JSON exceeds 32 KB');
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
value = JSON.parse(raw);
|
|
58
|
+
} catch {
|
|
59
|
+
errors.push('root: invalid JSON');
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
} else {
|
|
63
|
+
try {
|
|
64
|
+
const encoded = JSON.stringify(raw);
|
|
65
|
+
if (typeof encoded !== 'string' || Buffer.byteLength(encoded, 'utf8') > MAX_RAW_BYTES) {
|
|
66
|
+
errors.push('root: JSON exceeds 32 KB or is not serializable');
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
} catch {
|
|
70
|
+
errors.push('root: value is not serializable JSON');
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return value;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function normalizeWhen(raw, path, errors) {
|
|
78
|
+
if (raw === undefined) return undefined;
|
|
79
|
+
if (!isRecord(raw)) {
|
|
80
|
+
errors.push(`${path}: must be an object`);
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
addUnknownKeys(raw, new Set(['from', 'to', 'phases', 'minVisits']), path, errors);
|
|
84
|
+
const out = {};
|
|
85
|
+
if ((raw.from === undefined) !== (raw.to === undefined)) {
|
|
86
|
+
errors.push(`${path}: from and to must be supplied together`);
|
|
87
|
+
}
|
|
88
|
+
if (raw.from !== undefined) {
|
|
89
|
+
if (typeof raw.from !== 'string' || !TIME_RE.test(raw.from)) errors.push(`${path}.from: must be HH:MM`);
|
|
90
|
+
else out.from = raw.from;
|
|
91
|
+
}
|
|
92
|
+
if (raw.to !== undefined) {
|
|
93
|
+
if (typeof raw.to !== 'string' || !TIME_RE.test(raw.to)) errors.push(`${path}.to: must be HH:MM`);
|
|
94
|
+
else out.to = raw.to;
|
|
95
|
+
}
|
|
96
|
+
if (out.from !== undefined && out.to !== undefined && out.from === out.to) {
|
|
97
|
+
errors.push(`${path}: from and to must describe a non-empty time window`);
|
|
98
|
+
}
|
|
99
|
+
if (raw.phases !== undefined) {
|
|
100
|
+
if (!Array.isArray(raw.phases) || raw.phases.length > 16) {
|
|
101
|
+
errors.push(`${path}.phases: must be an array of at most 16 phase ids`);
|
|
102
|
+
} else {
|
|
103
|
+
const phases = [];
|
|
104
|
+
for (const [index, phase] of raw.phases.entries()) {
|
|
105
|
+
const id = validId(phase, `${path}.phases[${index}]`, errors);
|
|
106
|
+
if (id !== undefined) phases.push(id);
|
|
107
|
+
}
|
|
108
|
+
if (new Set(phases).size !== phases.length) errors.push(`${path}.phases: ids must be unique`);
|
|
109
|
+
out.phases = phases;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (raw.minVisits !== undefined) {
|
|
113
|
+
if (!Number.isInteger(raw.minVisits) || raw.minVisits < 0 || raw.minVisits > 100000) {
|
|
114
|
+
errors.push(`${path}.minVisits: must be an integer from 0 to 100000`);
|
|
115
|
+
} else out.minVisits = raw.minVisits;
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function normalizeReferences(raw, nodes, errors) {
|
|
121
|
+
if (raw === undefined) return [];
|
|
122
|
+
if (!Array.isArray(raw) || raw.length > 24) {
|
|
123
|
+
errors.push('references: must be an array of at most 24 entries');
|
|
124
|
+
return [];
|
|
125
|
+
}
|
|
126
|
+
return raw.flatMap((item, i) => {
|
|
127
|
+
const path = `references[${i}]`;
|
|
128
|
+
if (!isRecord(item)) { errors.push(`${path}: must be an object`); return []; }
|
|
129
|
+
addUnknownKeys(item, new Set(['area', 'afterNode', 'afterChoice', 'audience', 'text']), path, errors);
|
|
130
|
+
const area = textValue(item.area, `${path}.area`, 80, errors);
|
|
131
|
+
const afterNode = validId(item.afterNode, `${path}.afterNode`, errors);
|
|
132
|
+
const afterChoice = item.afterChoice === undefined ? undefined : validId(item.afterChoice, `${path}.afterChoice`, errors);
|
|
133
|
+
const node = nodes.find((entry) => afterNode && entry.id === afterNode);
|
|
134
|
+
if (!node) errors.push(`${path}.afterNode: node does not exist`);
|
|
135
|
+
if (!nodes.some((entry) => entry.area === area)) errors.push(`${path}.area: must be an authored story area`);
|
|
136
|
+
if (afterChoice && !node?.choices?.some((choice) => choice.id === afterChoice)) errors.push(`${path}.afterChoice: must be a choice of afterNode`);
|
|
137
|
+
if (!['player', 'fish', 'dm'].includes(item.audience)) errors.push(`${path}.audience: must be player, fish, or dm`);
|
|
138
|
+
const text = textValue(item.text, `${path}.text`, 240, errors);
|
|
139
|
+
return [{ area, afterNode, ...(afterChoice ? { afterChoice } : {}), audience: item.audience, text }];
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Only send unlocked references for this audience; never send the conditions or other text. */
|
|
144
|
+
export function storyReferences(pack, outing, audience) {
|
|
145
|
+
const progress = outing?.storyProgress?.find((entry) => entry.packId === pack?.id && entry.revision === pack?.revision);
|
|
146
|
+
const area = outing?.visited?.at(-1)?.area;
|
|
147
|
+
if (!area || !progress?.triggered?.length) return [];
|
|
148
|
+
return (pack.references ?? []).filter((item) => item.audience === audience && item.area === area
|
|
149
|
+
&& progress.triggered.includes(item.afterNode)
|
|
150
|
+
&& (!item.afterChoice || (outing.choices ?? []).some((choice) => choice.option === item.afterChoice)))
|
|
151
|
+
.slice(0, 6).map((item) => item.text);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Validate and canonicalize an authored version-1 or version-2 story pack. */
|
|
155
|
+
export function validateStoryPack(raw, options = {}) {
|
|
156
|
+
const requestedLimit = options?.maxNodes;
|
|
157
|
+
const maxNodes = requestedLimit === undefined ? DEFAULT_STORY_NODE_LIMIT
|
|
158
|
+
: isValidStoryNodeLimit(requestedLimit) ? requestedLimit : DEFAULT_STORY_NODE_LIMIT;
|
|
159
|
+
const errors = [];
|
|
160
|
+
const value = parseRaw(raw, errors);
|
|
161
|
+
if (!isRecord(value)) {
|
|
162
|
+
if (value !== null) errors.push('root: must be an object');
|
|
163
|
+
return { ok: false, pack: null, errors };
|
|
164
|
+
}
|
|
165
|
+
// 自由模式(场景包)与选项图是两套内容形态,走各自的校验,互不影响。
|
|
166
|
+
if (value.version === 3) return validateFreePack(value, errors);
|
|
167
|
+
if (![1, 2].includes(value.version)) errors.push('version: must equal 1 or 2');
|
|
168
|
+
const version = value.version;
|
|
169
|
+
const rootKeys = new Set(['version', 'id', 'title', 'description', 'placeId', 'start', 'nodes', ...(version === 2 ? ['metadata', 'references'] : [])]);
|
|
170
|
+
addUnknownKeys(value, rootKeys, '$', errors);
|
|
171
|
+
const id = validId(value.id, 'id', errors);
|
|
172
|
+
let placeId;
|
|
173
|
+
if (typeof value.placeId !== 'string' || !PLACE_ID_RE.test(value.placeId)) {
|
|
174
|
+
errors.push('placeId: must match [a-z0-9_-]{1,40}');
|
|
175
|
+
} else placeId = value.placeId;
|
|
176
|
+
const start = validId(value.start, 'start', errors);
|
|
177
|
+
const title = textValue(value.title, 'title', 80, errors);
|
|
178
|
+
const description = textValue(value.description, 'description', 240, errors, { required: false });
|
|
179
|
+
let metadata;
|
|
180
|
+
if (version === 2) {
|
|
181
|
+
if (!isRecord(value.metadata)) {
|
|
182
|
+
errors.push('metadata: must be an object for version 2');
|
|
183
|
+
} else {
|
|
184
|
+
const rawMetadata = value.metadata;
|
|
185
|
+
addUnknownKeys(rawMetadata, new Set(['author', 'release', 'genre', 'synopsis', 'participation', 'durationMinutes', 'requirements', 'seriesId', 'chapter', 'requiresCompleted', 'jointResolution']), 'metadata', errors);
|
|
186
|
+
const author = textValue(rawMetadata.author, 'metadata.author', 80, errors);
|
|
187
|
+
const release = textValue(rawMetadata.release, 'metadata.release', 24, errors);
|
|
188
|
+
if (release && !/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,23}$/.test(release)) errors.push('metadata.release: must be a short version label');
|
|
189
|
+
const genre = textValue(rawMetadata.genre, 'metadata.genre', 40, errors);
|
|
190
|
+
const synopsis = textValue(rawMetadata.synopsis, 'metadata.synopsis', 240, errors);
|
|
191
|
+
const participation = rawMetadata.participation;
|
|
192
|
+
if (!['solo', 'duo'].includes(participation)) errors.push('metadata.participation: must be solo or duo');
|
|
193
|
+
let jointResolution;
|
|
194
|
+
if (rawMetadata.jointResolution !== undefined) {
|
|
195
|
+
if (!['require-agreement', 'owner-final', 'fish-final'].includes(rawMetadata.jointResolution)) errors.push('metadata.jointResolution: must be require-agreement, owner-final, or fish-final');
|
|
196
|
+
else jointResolution = rawMetadata.jointResolution;
|
|
197
|
+
}
|
|
198
|
+
let durationMinutes;
|
|
199
|
+
if (rawMetadata.durationMinutes !== undefined) {
|
|
200
|
+
if (!Number.isInteger(rawMetadata.durationMinutes) || rawMetadata.durationMinutes < 1 || rawMetadata.durationMinutes > 600) errors.push('metadata.durationMinutes: must be an integer from 1 to 600');
|
|
201
|
+
else durationMinutes = rawMetadata.durationMinutes;
|
|
202
|
+
}
|
|
203
|
+
let requirements = [];
|
|
204
|
+
if (rawMetadata.requirements !== undefined) {
|
|
205
|
+
if (!Array.isArray(rawMetadata.requirements) || rawMetadata.requirements.length > 8) errors.push('metadata.requirements: must be an array of at most 8 items');
|
|
206
|
+
else requirements = rawMetadata.requirements.map((item, index) => textValue(item, `metadata.requirements[${index}]`, 80, errors));
|
|
207
|
+
}
|
|
208
|
+
let seriesId;
|
|
209
|
+
if (rawMetadata.seriesId !== undefined) seriesId = validId(rawMetadata.seriesId, 'metadata.seriesId', errors);
|
|
210
|
+
let chapter;
|
|
211
|
+
if (rawMetadata.chapter !== undefined) {
|
|
212
|
+
if (!Number.isInteger(rawMetadata.chapter) || rawMetadata.chapter < 1 || rawMetadata.chapter > 1000) errors.push('metadata.chapter: must be an integer from 1 to 1000');
|
|
213
|
+
else chapter = rawMetadata.chapter;
|
|
214
|
+
}
|
|
215
|
+
if ((seriesId === undefined) !== (chapter === undefined)) errors.push('metadata.seriesId and metadata.chapter must be supplied together');
|
|
216
|
+
let requiresCompleted = [];
|
|
217
|
+
if (rawMetadata.requiresCompleted !== undefined) {
|
|
218
|
+
if (!Array.isArray(rawMetadata.requiresCompleted) || rawMetadata.requiresCompleted.length > 8) errors.push('metadata.requiresCompleted: must be an array of at most 8 story ids');
|
|
219
|
+
else requiresCompleted = rawMetadata.requiresCompleted.map((item, index) => validId(item, `metadata.requiresCompleted[${index}]`, errors)).filter(Boolean);
|
|
220
|
+
if (new Set(requiresCompleted).size !== requiresCompleted.length) errors.push('metadata.requiresCompleted: ids must be unique');
|
|
221
|
+
}
|
|
222
|
+
if (participation === 'duo' && !jointResolution) errors.push('metadata.jointResolution: required for duo stories');
|
|
223
|
+
if (participation === 'solo' && jointResolution) errors.push('metadata.jointResolution: only valid for duo stories');
|
|
224
|
+
metadata = { author, release, genre, synopsis, participation, ...(jointResolution ? { jointResolution } : {}), ...(durationMinutes !== undefined ? { durationMinutes } : {}), requirements,
|
|
225
|
+
...(seriesId !== undefined ? { seriesId, chapter } : {}), ...(requiresCompleted.length ? { requiresCompleted } : {}) };
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const nodes = [];
|
|
230
|
+
const rawNodes = value.nodes;
|
|
231
|
+
if (!Array.isArray(rawNodes) || rawNodes.length < 1 || (maxNodes !== 0 && rawNodes.length > maxNodes)) {
|
|
232
|
+
errors.push(maxNodes === 0 ? 'nodes: must contain at least 1 node' : `nodes: must contain 1 to ${maxNodes} nodes`);
|
|
233
|
+
} else {
|
|
234
|
+
for (const [index, rawNode] of rawNodes.entries()) {
|
|
235
|
+
const path = `nodes[${index}]`;
|
|
236
|
+
if (!isRecord(rawNode)) {
|
|
237
|
+
errors.push(`${path}: must be an object`);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
addUnknownKeys(rawNode, new Set(['id', 'area', 'event', 'prompt', 'when', 'choices', 'next', ...(version === 2 ? ['actor'] : [])]), path, errors);
|
|
241
|
+
const nodeId = validId(rawNode.id, `${path}.id`, errors);
|
|
242
|
+
const area = textValue(rawNode.area, `${path}.area`, 80, errors);
|
|
243
|
+
const event = textValue(rawNode.event, `${path}.event`, 120, errors);
|
|
244
|
+
const prompt = textValue(rawNode.prompt, `${path}.prompt`, 160, errors, { required: false });
|
|
245
|
+
const when = normalizeWhen(rawNode.when, `${path}.when`, errors);
|
|
246
|
+
let actor;
|
|
247
|
+
if (version === 2 && rawNode.choices !== undefined) {
|
|
248
|
+
actor = rawNode.actor;
|
|
249
|
+
if (metadata?.participation === 'duo') {
|
|
250
|
+
if (!['owner', 'fish', 'joint'].includes(actor)) errors.push(`${path}.actor: duo choice nodes require owner, fish, or joint`);
|
|
251
|
+
} else if (actor !== undefined && actor !== 'owner') errors.push(`${path}.actor: solo stories cannot declare a fish or joint turn`);
|
|
252
|
+
if (metadata?.participation === 'solo') actor = undefined;
|
|
253
|
+
} else if (version === 2 && rawNode.actor !== undefined) {
|
|
254
|
+
errors.push(`${path}.actor: only choice nodes may declare an actor`);
|
|
255
|
+
}
|
|
256
|
+
if (version === 1 && rawNode.actor !== undefined) errors.push(`${path}.actor: requires version 2`);
|
|
257
|
+
let next;
|
|
258
|
+
if (rawNode.next !== undefined) next = validId(rawNode.next, `${path}.next`, errors);
|
|
259
|
+
|
|
260
|
+
let choices;
|
|
261
|
+
if (rawNode.choices !== undefined) {
|
|
262
|
+
if (!Array.isArray(rawNode.choices) || rawNode.choices.length < 2 || rawNode.choices.length > 4) {
|
|
263
|
+
errors.push(`${path}.choices: must contain 2 to 4 options`);
|
|
264
|
+
} else {
|
|
265
|
+
choices = [];
|
|
266
|
+
for (const [choiceIndex, rawChoice] of rawNode.choices.entries()) {
|
|
267
|
+
const choicePath = `${path}.choices[${choiceIndex}]`;
|
|
268
|
+
if (!isRecord(rawChoice)) {
|
|
269
|
+
errors.push(`${choicePath}: must be an object`);
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
addUnknownKeys(rawChoice, new Set(['id', 'label', 'result', 'next']), choicePath, errors);
|
|
273
|
+
const choiceId = validId(rawChoice.id, `${choicePath}.id`, errors);
|
|
274
|
+
if (choiceId === 'skip') errors.push(`${choicePath}.id: skip is reserved`);
|
|
275
|
+
const label = textValue(rawChoice.label, `${choicePath}.label`, 160, errors);
|
|
276
|
+
const result = textValue(rawChoice.result, `${choicePath}.result`, 160, errors);
|
|
277
|
+
let choiceNext;
|
|
278
|
+
if (rawChoice.next !== undefined) choiceNext = validId(rawChoice.next, `${choicePath}.next`, errors);
|
|
279
|
+
choices.push({ id: choiceId, label, result, ...(choiceNext !== undefined ? { next: choiceNext } : {}) });
|
|
280
|
+
}
|
|
281
|
+
if (choices.length === rawNode.choices.length && new Set(choices.map((choice) => choice.id)).size !== choices.length) {
|
|
282
|
+
errors.push(`${path}.choices: ids must be unique`);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (rawNode.next !== undefined) errors.push(`${path}: use either choices or next, not both`);
|
|
286
|
+
}
|
|
287
|
+
nodes.push({
|
|
288
|
+
id: nodeId,
|
|
289
|
+
area,
|
|
290
|
+
event,
|
|
291
|
+
...(prompt !== undefined ? { prompt } : {}),
|
|
292
|
+
...(when !== undefined ? { when } : {}),
|
|
293
|
+
...(choices !== undefined ? { choices } : {}),
|
|
294
|
+
...(next !== undefined ? { next } : {}),
|
|
295
|
+
...(actor !== undefined && ['owner', 'fish', 'joint'].includes(actor) ? { actor } : {}),
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
if (nodes.length === rawNodes?.length) {
|
|
301
|
+
const ids = nodes.map((node) => node.id);
|
|
302
|
+
if (new Set(ids).size !== ids.length) errors.push('nodes: ids must be unique');
|
|
303
|
+
const nodeIds = new Set(ids);
|
|
304
|
+
if (start !== undefined && !nodeIds.has(start)) errors.push('start: node does not exist');
|
|
305
|
+
const choiceIds = new Set();
|
|
306
|
+
for (const node of nodes) {
|
|
307
|
+
if (node.choices) {
|
|
308
|
+
for (const choice of node.choices) {
|
|
309
|
+
if (choice.id !== undefined) choiceIds.add(choice.id);
|
|
310
|
+
if (choice.next !== undefined && !nodeIds.has(choice.next)) errors.push(`nodes.${node.id}.choices.${choice.id}: next node does not exist`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
if (node.next !== undefined && !nodeIds.has(node.next)) errors.push(`nodes.${node.id}.next: node does not exist`);
|
|
314
|
+
}
|
|
315
|
+
if (choiceIds.size < nodes.flatMap((node) => node.choices ?? []).length) errors.push('choices: ids must be unique within a pack');
|
|
316
|
+
|
|
317
|
+
if (start !== undefined && nodeIds.has(start)) {
|
|
318
|
+
const byId = new Map(nodes.map((node) => [node.id, node]));
|
|
319
|
+
const reached = new Set();
|
|
320
|
+
const visiting = new Set();
|
|
321
|
+
const visited = new Set();
|
|
322
|
+
let cycle = false;
|
|
323
|
+
const visit = (nodeId) => {
|
|
324
|
+
if (visiting.has(nodeId)) { cycle = true; return; }
|
|
325
|
+
if (visited.has(nodeId)) return;
|
|
326
|
+
const node = byId.get(nodeId);
|
|
327
|
+
if (!node) return;
|
|
328
|
+
visiting.add(nodeId);
|
|
329
|
+
reached.add(nodeId);
|
|
330
|
+
const edges = node.choices ? node.choices.map((choice) => choice.next).filter(Boolean) : (node.next ? [node.next] : []);
|
|
331
|
+
for (const target of edges) visit(target);
|
|
332
|
+
visiting.delete(nodeId);
|
|
333
|
+
visited.add(nodeId);
|
|
334
|
+
};
|
|
335
|
+
visit(start);
|
|
336
|
+
if (cycle) errors.push('nodes: graph must not contain cycles');
|
|
337
|
+
if (reached.size !== nodes.length) errors.push('nodes: every node must be reachable from start');
|
|
338
|
+
const hasTerminal = nodes.some((node) => reached.has(node.id) && (
|
|
339
|
+
node.choices ? node.choices.some((choice) => !choice.next) : !node.next
|
|
340
|
+
));
|
|
341
|
+
if (!hasTerminal) errors.push('nodes: graph must have a terminal path');
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const references = version === 2 ? normalizeReferences(value.references, nodes, errors) : [];
|
|
346
|
+
if (errors.length) return { ok: false, pack: null, errors };
|
|
347
|
+
const content = {
|
|
348
|
+
version,
|
|
349
|
+
id,
|
|
350
|
+
title,
|
|
351
|
+
...(description !== undefined ? { description } : {}),
|
|
352
|
+
...(version === 2 ? { metadata } : {}),
|
|
353
|
+
...(references.length ? { references } : {}),
|
|
354
|
+
placeId,
|
|
355
|
+
start,
|
|
356
|
+
nodes,
|
|
357
|
+
};
|
|
358
|
+
const pack = { ...content, revision: canonicalRevision(content) };
|
|
359
|
+
return { ok: true, pack, errors: [] };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const FREE_STATE_ID = /^[a-z0-9_-]{1,24}$/;
|
|
363
|
+
const FREE_WHEN_KEYS = new Set(['all', 'any', 'flag', 'counter', 'fact', 'gte', 'lte', 'equals']);
|
|
364
|
+
|
|
365
|
+
function textList(raw, path, maxItems, maxChars, errors) {
|
|
366
|
+
if (raw === undefined) return [];
|
|
367
|
+
if (!Array.isArray(raw) || raw.length > maxItems) {
|
|
368
|
+
errors.push(`${path}: must be an array of at most ${maxItems} strings`);
|
|
369
|
+
return [];
|
|
370
|
+
}
|
|
371
|
+
return raw.map((item, index) => textValue(item, `${path}[${index}]`, maxChars, errors)).filter((item) => item !== undefined);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function freeIds(raw, path, maxItems, build, errors) {
|
|
375
|
+
if (!Array.isArray(raw) || raw.length > maxItems) {
|
|
376
|
+
errors.push(`${path}: must be an array of at most ${maxItems} entries`);
|
|
377
|
+
return [];
|
|
378
|
+
}
|
|
379
|
+
const out = [];
|
|
380
|
+
for (const [index, item] of raw.entries()) {
|
|
381
|
+
const itemPath = `${path}[${index}]`;
|
|
382
|
+
if (!isRecord(item)) { errors.push(`${itemPath}: must be an object`); continue; }
|
|
383
|
+
out.push(build(item, itemPath, errors));
|
|
384
|
+
}
|
|
385
|
+
const ids = out.map((entry) => entry?.id).filter(Boolean);
|
|
386
|
+
if (new Set(ids).size !== ids.length) errors.push(`${path}: ids must be unique`);
|
|
387
|
+
return out.filter(Boolean);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** 自由模式的判定条件:all / any / flag / counter / fact,只引用已登记的状态 id。 */
|
|
391
|
+
function normalizeFreeWhen(raw, path, errors, stateIds) {
|
|
392
|
+
if (raw === undefined) return undefined;
|
|
393
|
+
if (!isRecord(raw)) { errors.push(`${path}: must be an object`); return undefined; }
|
|
394
|
+
addUnknownKeys(raw, FREE_WHEN_KEYS, path, errors);
|
|
395
|
+
const keys = Object.keys(raw).filter((key) => ['all', 'any', 'flag', 'counter', 'fact'].includes(key));
|
|
396
|
+
if (keys.length !== 1) { errors.push(`${path}: must contain exactly one of all, any, flag, counter, fact`); return undefined; }
|
|
397
|
+
const key = keys[0];
|
|
398
|
+
if (key === 'all' || key === 'any') {
|
|
399
|
+
if (!Array.isArray(raw[key]) || raw[key].length < 1 || raw[key].length > 8) {
|
|
400
|
+
errors.push(`${path}.${key}: must be an array of 1 to 8 conditions`);
|
|
401
|
+
return undefined;
|
|
402
|
+
}
|
|
403
|
+
const clauses = raw[key].map((item, index) => normalizeFreeWhen(item, `${path}.${key}[${index}]`, errors, stateIds)).filter(Boolean);
|
|
404
|
+
return { [key]: clauses };
|
|
405
|
+
}
|
|
406
|
+
if (key === 'flag') {
|
|
407
|
+
if (typeof raw.flag !== 'string' || !stateIds.flags.has(raw.flag)) { errors.push(`${path}.flag: unknown flag id`); return undefined; }
|
|
408
|
+
return { flag: raw.flag };
|
|
409
|
+
}
|
|
410
|
+
if (key === 'counter') {
|
|
411
|
+
if (typeof raw.counter !== 'string' || !stateIds.counters.has(raw.counter)) { errors.push(`${path}.counter: unknown counter id`); return undefined; }
|
|
412
|
+
const clause = { counter: raw.counter };
|
|
413
|
+
for (const field of ['gte', 'lte']) {
|
|
414
|
+
if (raw[field] === undefined) continue;
|
|
415
|
+
if (!Number.isSafeInteger(raw[field])) { errors.push(`${path}.${field}: must be an integer`); continue; }
|
|
416
|
+
clause[field] = raw[field];
|
|
417
|
+
}
|
|
418
|
+
if (clause.gte === undefined && clause.lte === undefined) { errors.push(`${path}: counter condition needs gte or lte`); return undefined; }
|
|
419
|
+
return clause;
|
|
420
|
+
}
|
|
421
|
+
if (typeof raw.fact !== 'string' || !stateIds.facts.has(raw.fact)) { errors.push(`${path}.fact: unknown fact id`); return undefined; }
|
|
422
|
+
if (typeof raw.equals !== 'string') { errors.push(`${path}.equals: must be a string`); return undefined; }
|
|
423
|
+
return { fact: raw.fact, equals: raw.equals.slice(0, 200) };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function normalizeFreeSetting(raw, errors) {
|
|
427
|
+
if (!isRecord(raw)) { errors.push('setting: must be an object for version 3'); return undefined; }
|
|
428
|
+
addUnknownKeys(raw, new Set(['premise', 'canon', 'forbidden', 'cast', 'locations', 'opening', 'flags', 'counters', 'facts', 'goals', 'ends', 'beats']), 'setting', errors);
|
|
429
|
+
const premise = textValue(raw.premise, 'setting.premise', 240, errors);
|
|
430
|
+
const opening = textValue(raw.opening, 'setting.opening', 400, errors);
|
|
431
|
+
const canon = textList(raw.canon, 'setting.canon', 12, 120, errors);
|
|
432
|
+
if (canon.length < 3) errors.push('setting.canon: needs at least 3 fixed facts');
|
|
433
|
+
const forbidden = textList(raw.forbidden, 'setting.forbidden', 8, 120, errors);
|
|
434
|
+
const beats = textList(raw.beats, 'setting.beats', 6, 60, errors);
|
|
435
|
+
|
|
436
|
+
const cast = freeIds(raw.cast, 'setting.cast', 8, (item, path) => ({
|
|
437
|
+
id: validId(item.id, `${path}.id`, errors),
|
|
438
|
+
name: textValue(item.name, `${path}.name`, 40, errors),
|
|
439
|
+
role: textValue(item.role, `${path}.role`, 120, errors, { required: false }) ?? '',
|
|
440
|
+
secret: textValue(item.secret, `${path}.secret`, 120, errors, { required: false }) ?? '',
|
|
441
|
+
}), errors);
|
|
442
|
+
const locations = freeIds(raw.locations, 'setting.locations', 8, (item, path) => ({
|
|
443
|
+
id: validId(item.id, `${path}.id`, errors),
|
|
444
|
+
name: textValue(item.name, `${path}.name`, 40, errors),
|
|
445
|
+
desc: textValue(item.desc, `${path}.desc`, 160, errors, { required: false }) ?? '',
|
|
446
|
+
}), errors);
|
|
447
|
+
const flags = freeIds(raw.flags === undefined ? [] : raw.flags, 'setting.flags', 12, (item, path) => ({
|
|
448
|
+
id: validId(item.id, `${path}.id`, errors),
|
|
449
|
+
label: textValue(item.label, `${path}.label`, 40, errors, { required: false }) ?? '',
|
|
450
|
+
initial: item.initial === true,
|
|
451
|
+
}), errors);
|
|
452
|
+
const facts = freeIds(raw.facts === undefined ? [] : raw.facts, 'setting.facts', 12, (item, path) => ({
|
|
453
|
+
id: validId(item.id, `${path}.id`, errors),
|
|
454
|
+
label: textValue(item.label, `${path}.label`, 40, errors, { required: false }) ?? '',
|
|
455
|
+
initial: textValue(item.initial, `${path}.initial`, 200, errors, { required: false }) ?? '',
|
|
456
|
+
}), errors);
|
|
457
|
+
const counters = freeIds(raw.counters === undefined ? [] : raw.counters, 'setting.counters', 8, (item, path) => {
|
|
458
|
+
const min = Number.isSafeInteger(item.min) ? item.min : 0;
|
|
459
|
+
const max = Number.isSafeInteger(item.max) ? item.max : 10;
|
|
460
|
+
if (min < 0 || max > 100 || min >= max) errors.push(`${path}: needs 0 <= min < max <= 100`);
|
|
461
|
+
const initial = Number.isSafeInteger(item.initial) ? item.initial : min;
|
|
462
|
+
if (initial < min || initial > max) errors.push(`${path}.initial: must be within min..max`);
|
|
463
|
+
return { id: validId(item.id, `${path}.id`, errors), label: textValue(item.label, `${path}.label`, 40, errors, { required: false }) ?? '', min, max, initial };
|
|
464
|
+
}, errors);
|
|
465
|
+
|
|
466
|
+
// 三个状态区共用一个 id 空间:delta 里写的是哪个区都不许含糊。
|
|
467
|
+
const stateIds = {
|
|
468
|
+
flags: new Set(flags.map((item) => item.id)),
|
|
469
|
+
counters: new Set(counters.map((item) => item.id)),
|
|
470
|
+
facts: new Set(facts.map((item) => item.id)),
|
|
471
|
+
};
|
|
472
|
+
const allStateIds = new Set([...stateIds.flags, ...stateIds.counters, ...stateIds.facts]);
|
|
473
|
+
if (allStateIds.size !== stateIds.flags.size + stateIds.counters.size + stateIds.facts.size) errors.push('setting: flag/counter/fact ids must not repeat across sections');
|
|
474
|
+
|
|
475
|
+
const goals = freeIds(raw.goals === undefined ? [] : raw.goals, 'setting.goals', 4, (item, path) => ({
|
|
476
|
+
id: validId(item.id, `${path}.id`, errors),
|
|
477
|
+
text: textValue(item.text, `${path}.text`, 120, errors),
|
|
478
|
+
when: normalizeFreeWhen(item.when, `${path}.when`, errors, stateIds),
|
|
479
|
+
}), errors);
|
|
480
|
+
const ends = freeIds(raw.ends === undefined ? [] : raw.ends, 'setting.ends', 4, (item, path) => {
|
|
481
|
+
const when = normalizeFreeWhen(item.when, `${path}.when`, errors, stateIds);
|
|
482
|
+
if (when === undefined) errors.push(`${path}.when: endings need a condition`);
|
|
483
|
+
return { id: validId(item.id, `${path}.id`, errors), text: textValue(item.text, `${path}.text`, 120, errors), when };
|
|
484
|
+
}, errors);
|
|
485
|
+
|
|
486
|
+
return { premise, canon, ...(forbidden.length ? { forbidden } : {}), cast, locations, opening, flags, counters, facts, goals, ends, ...(beats.length ? { beats } : {}) };
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
function normalizeFreeMetadata(raw, errors) {
|
|
490
|
+
if (!isRecord(raw)) { errors.push('metadata: must be an object for version 3'); return undefined; }
|
|
491
|
+
addUnknownKeys(raw, new Set(['mode', 'author', 'release', 'genre', 'synopsis', 'participation', 'durationMinutes', 'maxTurns']), 'metadata', errors);
|
|
492
|
+
if (raw.mode !== 'free') errors.push('metadata.mode: must equal free for version 3');
|
|
493
|
+
const author = textValue(raw.author, 'metadata.author', 80, errors);
|
|
494
|
+
const release = textValue(raw.release, 'metadata.release', 24, errors);
|
|
495
|
+
if (release && !/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,23}$/.test(release)) errors.push('metadata.release: must be a short version label');
|
|
496
|
+
const genre = textValue(raw.genre, 'metadata.genre', 40, errors, { required: false }) ?? '';
|
|
497
|
+
const synopsis = textValue(raw.synopsis, 'metadata.synopsis', 240, errors);
|
|
498
|
+
if (!['solo', 'duo', 'group'].includes(raw.participation)) errors.push('metadata.participation: must be solo, duo, or group');
|
|
499
|
+
let durationMinutes;
|
|
500
|
+
if (raw.durationMinutes !== undefined) {
|
|
501
|
+
if (!Number.isInteger(raw.durationMinutes) || raw.durationMinutes < 1 || raw.durationMinutes > 600) errors.push('metadata.durationMinutes: must be an integer from 1 to 600');
|
|
502
|
+
else durationMinutes = raw.durationMinutes;
|
|
503
|
+
}
|
|
504
|
+
let maxTurns;
|
|
505
|
+
if (raw.maxTurns !== undefined) {
|
|
506
|
+
if (!Number.isInteger(raw.maxTurns) || raw.maxTurns < 1 || raw.maxTurns > 200) errors.push('metadata.maxTurns: must be an integer from 1 to 200');
|
|
507
|
+
else maxTurns = raw.maxTurns;
|
|
508
|
+
}
|
|
509
|
+
return { mode: 'free', author, release, genre, synopsis, participation: raw.participation, ...(durationMinutes ? { durationMinutes } : {}), ...(maxTurns ? { maxTurns } : {}) };
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** version 3:只写设定与判定条件,不写节点、不写选项。 */
|
|
513
|
+
function validateFreePack(value, errors) {
|
|
514
|
+
addUnknownKeys(value, new Set(['version', 'id', 'title', 'description', 'placeId', 'metadata', 'setting']), '$', errors);
|
|
515
|
+
const id = validId(value.id, 'id', errors);
|
|
516
|
+
const title = textValue(value.title, 'title', 80, errors);
|
|
517
|
+
const description = textValue(value.description, 'description', 240, errors, { required: false });
|
|
518
|
+
let placeId;
|
|
519
|
+
if (typeof value.placeId !== 'string' || !PLACE_ID_RE.test(value.placeId)) errors.push('placeId: must match [a-z0-9_-]{1,40}');
|
|
520
|
+
else placeId = value.placeId;
|
|
521
|
+
const metadata = normalizeFreeMetadata(value.metadata, errors);
|
|
522
|
+
const setting = normalizeFreeSetting(value.setting, errors);
|
|
523
|
+
if (errors.length) return { ok: false, pack: null, errors };
|
|
524
|
+
const content = { version: 3, id, title, ...(description !== undefined ? { description } : {}), metadata, placeId, setting };
|
|
525
|
+
return { ok: true, pack: { ...content, revision: canonicalRevision(content) }, errors: [] };
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* Check whether a structurally valid pack can be used with a venue catalog.
|
|
530
|
+
*
|
|
531
|
+
* 每条警告都直接说明「差什么、去哪儿补」:这里的中文会原样出现在故事工坊的作品卡和
|
|
532
|
+
* `fun_story` 的列表回执里,玩家就是靠它判断「导进去了为什么一直不触发」。
|
|
533
|
+
* `placeMissing` / `missingAreas` 另给一份结构化结果,面板据此直接摆出「绑定到现有地点」,
|
|
534
|
+
* 不必去解析文案。
|
|
535
|
+
*/
|
|
536
|
+
export function storyAvailability(pack, venues, completedStoryIds = []) {
|
|
537
|
+
const warnings = [];
|
|
538
|
+
const venueList = Array.isArray(venues) ? venues : (venues ? [venues] : []);
|
|
539
|
+
const placeId = typeof pack?.placeId === 'string' ? pack.placeId : '';
|
|
540
|
+
const venue = venueList.find((item) => item?.id === placeId);
|
|
541
|
+
const placeName = typeof venue?.name === 'string' ? venue.name : placeId;
|
|
542
|
+
if (!venue) {
|
|
543
|
+
warnings.push(`这处地点「${placeId}」在地点册里没有。先新建它,或把故事包绑到已有地点。`);
|
|
544
|
+
return { available: false, placeMissing: true, placeId, placeName, warnings };
|
|
545
|
+
}
|
|
546
|
+
const venueAreas = new Set(Array.isArray(venue.areas) ? venue.areas : []);
|
|
547
|
+
const missingAreas = [...new Set((Array.isArray(pack.nodes) ? pack.nodes : []).map((node) => node?.area).filter((area) => typeof area === 'string' && !venueAreas.has(area)))];
|
|
548
|
+
if (missingAreas.length) warnings.push(`「${placeName}」缺少故事要用的区域:${missingAreas.join('、')}。在地点册的「能逛的」里补上同名的区域。`);
|
|
549
|
+
const phases = new Set(Array.isArray(venue.phases) ? venue.phases.map((phase) => phase?.key).filter((key) => typeof key === 'string') : []);
|
|
550
|
+
const referencedPhases = [...new Set((Array.isArray(pack.nodes) ? pack.nodes : []).flatMap((node) => node?.when?.phases ?? []))];
|
|
551
|
+
const missingPhases = referencedPhases.filter((key) => !phases.has(key));
|
|
552
|
+
if (missingPhases.length) warnings.push(`「${placeName}」没有故事要用的时段:${missingPhases.join('、')}。`);
|
|
553
|
+
const completed = completedStoryIds instanceof Set ? completedStoryIds : new Set(Array.isArray(completedStoryIds) ? completedStoryIds : []);
|
|
554
|
+
const missingStoryIds = (pack?.metadata?.requiresCompleted ?? []).filter((id) => !completed.has(id));
|
|
555
|
+
if (missingStoryIds.length) warnings.push(`要先完成这些故事:${missingStoryIds.join('、')}。`);
|
|
556
|
+
return { available: warnings.length === 0, placeMissing: false, placeId, placeName, warnings, ...(missingAreas.length ? { missingAreas } : {}), ...(missingStoryIds.length ? { missingStoryIds } : {}) };
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
function progressId(value) {
|
|
560
|
+
return typeof value === 'string' && ID_RE.test(value) ? value : null;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** Keep only the small JSON-safe cursor snapshots needed to resume a story. */
|
|
564
|
+
export function normalizeStoryProgress(raw) {
|
|
565
|
+
if (!Array.isArray(raw)) return [];
|
|
566
|
+
const out = [];
|
|
567
|
+
for (const item of raw) {
|
|
568
|
+
if (out.length >= 32) break;
|
|
569
|
+
if (!isRecord(item)) continue;
|
|
570
|
+
const packId = progressId(item.packId);
|
|
571
|
+
const nodeId = progressId(item.nodeId);
|
|
572
|
+
const revision = typeof item.revision === 'string' && item.revision.length > 0 && item.revision.length <= 100 && /^[A-Za-z0-9_-]+$/.test(item.revision)
|
|
573
|
+
? item.revision : null;
|
|
574
|
+
if (!packId || !nodeId || !revision || typeof item.done !== 'boolean') continue;
|
|
575
|
+
const waitingChoiceId = item.waitingChoiceId === null || item.waitingChoiceId === undefined
|
|
576
|
+
? null
|
|
577
|
+
: (typeof item.waitingChoiceId === 'string' && /^[A-Za-z0-9:_-]{1,100}$/.test(item.waitingChoiceId) ? item.waitingChoiceId : null);
|
|
578
|
+
if (item.waitingChoiceId != null && waitingChoiceId === null) continue;
|
|
579
|
+
if (!Array.isArray(item.options) || item.options.length > 4) continue;
|
|
580
|
+
const options = [];
|
|
581
|
+
let invalidOptions = false;
|
|
582
|
+
for (const option of item.options) {
|
|
583
|
+
if (!isRecord(option) || !progressId(option.id)) { invalidOptions = true; break; }
|
|
584
|
+
if (option.next !== null && option.next !== undefined && !progressId(option.next)) { invalidOptions = true; break; }
|
|
585
|
+
options.push({ id: option.id, next: option.next ?? null });
|
|
586
|
+
}
|
|
587
|
+
if (invalidOptions || new Set(options.map((option) => option.id)).size !== options.length) continue;
|
|
588
|
+
if (waitingChoiceId && (options.length < 2 || options.length > 4 || item.done)) continue;
|
|
589
|
+
if (!waitingChoiceId && options.length) continue;
|
|
590
|
+
const triggered = Array.isArray(item.triggered) ? [...new Set(item.triggered.filter((id) => typeof id === 'string' && ID_RE.test(id)))].slice(0, 16) : [];
|
|
591
|
+
out.push({ packId, revision, nodeId, waitingChoiceId, options, done: item.done, ...(triggered.length ? { triggered } : {}) });
|
|
592
|
+
}
|
|
593
|
+
return out;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
function inWindow(from, to, nowMin) {
|
|
597
|
+
if (from === undefined || to === undefined) return true;
|
|
598
|
+
const parse = (value) => Number(value.slice(0, 2)) * 60 + Number(value.slice(3, 5));
|
|
599
|
+
const start = parse(from);
|
|
600
|
+
const end = parse(to);
|
|
601
|
+
const now = Number(nowMin);
|
|
602
|
+
if (!Number.isFinite(now)) return false;
|
|
603
|
+
return end > start ? now >= start && now < end : now >= start || now < end;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function nodeMatches(node, venue, area, nowMin, visits) {
|
|
607
|
+
if (node.area !== area || hoursState(venue, nowMin) === 'closed') return false;
|
|
608
|
+
if (!areasNow(venue, nowMin).includes(area)) return false;
|
|
609
|
+
const when = node.when;
|
|
610
|
+
if (!when) return true;
|
|
611
|
+
if (!inWindow(when.from, when.to, nowMin)) return false;
|
|
612
|
+
if (when.minVisits !== undefined && !(Number(visits) >= when.minVisits)) return false;
|
|
613
|
+
if (when.phases?.length) {
|
|
614
|
+
const phaseKey = phaseAt(venue, nowMin).phase?.key;
|
|
615
|
+
if (!phaseKey || !when.phases.includes(phaseKey)) return false;
|
|
616
|
+
}
|
|
617
|
+
return true;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* 说出「这一步为什么走不动」——比笼统的「不满足条件」有用得多。
|
|
622
|
+
* 只在 `pickStory` 已经判否之后调用,所以这里只解释原因,不做判定。
|
|
623
|
+
*/
|
|
624
|
+
export function storyStepBlock(pack, node, venue, nowMin, visits = 0) {
|
|
625
|
+
if (!node || !venue) return '';
|
|
626
|
+
const hhmm = (value) => `${String(Math.floor(Number(value) / 60)).padStart(2, '0')}:${String(Number(value) % 60).padStart(2, '0')}`;
|
|
627
|
+
const currentPhase = phaseAt(venue, nowMin)?.phase;
|
|
628
|
+
const phaseName = currentPhase?.label ?? '';
|
|
629
|
+
const when = node.when;
|
|
630
|
+
if (when?.from !== undefined && !inWindow(when.from, when.to, nowMin)) {
|
|
631
|
+
return `这一步要等到 ${when.from}–${when.to} 才会触发;现在是 ${hhmm(nowMin)}。可以先接着逛别的,或按已有记录回家。`;
|
|
632
|
+
}
|
|
633
|
+
if (when?.phases?.length) {
|
|
634
|
+
const key = currentPhase?.key;
|
|
635
|
+
if (!key || !when.phases.includes(key)) {
|
|
636
|
+
const labels = (venue.phases ?? []).filter((phase) => when.phases.includes(phase.key)).map((phase) => `${phase.label}(${phase.from}–${phase.to})`);
|
|
637
|
+
return `这一步只在${labels.join('、') || when.phases.join('、')}触发;现在是${phaseName || hhmm(nowMin)}。`;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
if (when?.minVisits !== undefined && !(Number(visits) >= when.minVisits)) {
|
|
641
|
+
return `这一步要来这处至少 ${when.minVisits} 次之后才会触发;现在已经来过 ${Number(visits) || 0} 次。`;
|
|
642
|
+
}
|
|
643
|
+
if (!Array.isArray(venue.areas) || !venue.areas.includes(node.area)) {
|
|
644
|
+
return `故事要去的「${node.area}」不在这处地点里。请在从0开始的肥鱼大冒险核对故事包绑定的区域和地点。`;
|
|
645
|
+
}
|
|
646
|
+
if (!areasNow(venue, nowMin).includes(node.area)) {
|
|
647
|
+
const windows = (venue.phases ?? []).filter((phase) => (phase.areas ?? []).includes(node.area))
|
|
648
|
+
.map((phase) => `${phase.label}(${phase.from}–${phase.to})`);
|
|
649
|
+
return `下一处「${node.area}」这会儿没开:它只在${windows.join('、') || '别的时段'}开放,现在是${phaseName || hhmm(nowMin)}(${hhmm(nowMin)})。可以等到那时候,或按已有记录回家。`;
|
|
650
|
+
}
|
|
651
|
+
if (hoursState(venue, nowMin) === 'closed') {
|
|
652
|
+
return `这处地点已经过了开放时段(${venue.hours?.open ?? ''}–${venue.hours?.close ?? ''})。可以改天再来,或按已有记录回家。`;
|
|
653
|
+
}
|
|
654
|
+
return '';
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function validatedPack(raw, maxNodes = 0) {
|
|
658
|
+
if (!isRecord(raw)) return null;
|
|
659
|
+
const { revision, ...content } = raw;
|
|
660
|
+
const result = validateStoryPack(content, { maxNodes });
|
|
661
|
+
if (!result.ok || (revision !== undefined && revision !== result.pack.revision)) return null;
|
|
662
|
+
return result.pack;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/** Select the one matching story step, returning a cloned next progress snapshot. */
|
|
666
|
+
export function pickStory(catalog, venue, area, nowMin, session, visits, completedStoryIds = []) {
|
|
667
|
+
if (!Array.isArray(catalog) || !venue || typeof area !== 'string' || !Number.isFinite(Number(nowMin)) || Number(nowMin) < 0 || Number(nowMin) >= 1440 || hoursState(venue, nowMin) === 'closed') return null;
|
|
668
|
+
const current = normalizeStoryProgress(session?.storyProgress);
|
|
669
|
+
const candidates = [];
|
|
670
|
+
for (const row of catalog) {
|
|
671
|
+
if (!row || row.enabled !== true || !row.pack) continue;
|
|
672
|
+
const pack = validatedPack(row.pack);
|
|
673
|
+
if (!pack || pack.version === 3) continue; // 自由模式没有区域节点,不会被游逛自动触发
|
|
674
|
+
if (pack.placeId !== venue.id || !storyAvailability(pack, [venue], completedStoryIds).available) continue;
|
|
675
|
+
const existingIndex = current.findIndex((entry) => entry.packId === pack.id);
|
|
676
|
+
const existing = existingIndex >= 0 ? current[existingIndex] : null;
|
|
677
|
+
// A cursor from another revision is deliberately paused, never silently restarted.
|
|
678
|
+
if (existing && existing.revision !== pack.revision) continue;
|
|
679
|
+
if (existing && (existing.done || existing.waitingChoiceId)) continue;
|
|
680
|
+
candidates.push({
|
|
681
|
+
pack,
|
|
682
|
+
existingIndex,
|
|
683
|
+
existing,
|
|
684
|
+
active: Boolean(existing && !existing.done && !existing.waitingChoiceId),
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
candidates.sort((left, right) => Number(right.active) - Number(left.active));
|
|
688
|
+
|
|
689
|
+
for (const candidate of candidates) {
|
|
690
|
+
const { pack, existingIndex, existing } = candidate;
|
|
691
|
+
const cursor = existing?.nodeId ?? pack.start;
|
|
692
|
+
const node = pack.nodes.find((candidate) => candidate.id === cursor);
|
|
693
|
+
if (!node || !nodeMatches(node, venue, area, nowMin, visits)) continue;
|
|
694
|
+
|
|
695
|
+
const progress = current.map((entry) => ({ ...entry, options: entry.options.map((option) => ({ ...option })) }));
|
|
696
|
+
let entry;
|
|
697
|
+
if (existingIndex >= 0) entry = progress[existingIndex];
|
|
698
|
+
else {
|
|
699
|
+
if (progress.length >= 32) continue;
|
|
700
|
+
entry = { packId: pack.id, revision: pack.revision, nodeId: node.id, waitingChoiceId: null, options: [], done: false };
|
|
701
|
+
progress.push(entry);
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
if (pack.references?.length) entry.triggered = [...new Set([...(entry.triggered ?? []), node.id])];
|
|
705
|
+
let choice = null;
|
|
706
|
+
if (node.choices) {
|
|
707
|
+
const choiceId = `story:${pack.id}:${pack.revision}:${node.id}`;
|
|
708
|
+
entry.waitingChoiceId = choiceId;
|
|
709
|
+
entry.options = node.choices.map((option) => ({ id: option.id, next: option.next ?? null }));
|
|
710
|
+
choice = {
|
|
711
|
+
id: choiceId,
|
|
712
|
+
event: node.event,
|
|
713
|
+
area: node.area,
|
|
714
|
+
prompt: node.prompt ?? node.event,
|
|
715
|
+
options: node.choices.map(({ id, label, result }) => ({ id, label, result })),
|
|
716
|
+
...(pack.version === 2 && pack.metadata.participation === 'duo'
|
|
717
|
+
? { actor: node.actor, jointResolution: pack.metadata.jointResolution ?? null } : {}),
|
|
718
|
+
};
|
|
719
|
+
} else if (node.next) {
|
|
720
|
+
entry.nodeId = node.next;
|
|
721
|
+
entry.waitingChoiceId = null;
|
|
722
|
+
entry.options = [];
|
|
723
|
+
} else {
|
|
724
|
+
entry.done = true;
|
|
725
|
+
entry.waitingChoiceId = null;
|
|
726
|
+
entry.options = [];
|
|
727
|
+
}
|
|
728
|
+
return { event: node.event, choice, progress };
|
|
729
|
+
}
|
|
730
|
+
return null;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/** Resolve an offered choice using its serialized edge snapshot (or finish on skip). */
|
|
734
|
+
export function advanceStoryChoice(rawProgress, choiceId, optionId) {
|
|
735
|
+
const progress = normalizeStoryProgress(rawProgress).map((entry) => ({ ...entry, options: entry.options.map((option) => ({ ...option })) }));
|
|
736
|
+
const index = progress.findIndex((entry) => entry.waitingChoiceId === choiceId);
|
|
737
|
+
if (index < 0) return progress;
|
|
738
|
+
const entry = progress[index];
|
|
739
|
+
const selected = entry.options.find((option) => option.id === optionId);
|
|
740
|
+
const skip = optionId === null || optionId === undefined || optionId === 'skip';
|
|
741
|
+
if (skip) {
|
|
742
|
+
entry.done = true;
|
|
743
|
+
} else if (!selected) {
|
|
744
|
+
return progress;
|
|
745
|
+
} else if (selected.next) {
|
|
746
|
+
entry.nodeId = selected.next;
|
|
747
|
+
} else {
|
|
748
|
+
entry.done = true;
|
|
749
|
+
}
|
|
750
|
+
entry.waitingChoiceId = null;
|
|
751
|
+
entry.options = [];
|
|
752
|
+
return progress;
|
|
753
|
+
}
|