@dsh-agentic-roleplay/core 0.3.4 → 0.3.5
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/lib/authoring.js +5 -3
- package/lib/client.js +1964 -473
- package/lib/client.js.map +1 -1
- package/lib/{deliver-CpZOxBX5.js → deliver-Cl6bjp7g.js} +3 -2
- package/lib/doctor.js +3 -3
- package/lib/{gallery-CtFDL22W.js → gallery-DIEgETzU.js} +2 -2
- package/lib/generator-DJ48HxPI.js +145 -0
- package/lib/{hooks-KTCR3fNJ.js → hooks-DdO_tNhu.js} +3 -3
- package/lib/images.js +4 -3
- package/lib/index.js +522 -51
- package/lib/language-BgyxtB2h.js +38 -0
- package/lib/{generator-B6FxlKOV.js → library-9JB9zw5a.js} +2 -143
- package/lib/{language-DWVwi1R7.js → load-Clkl0T7C.js} +6 -40
- package/lib/orchestration.js +22 -14
- package/lib/pack-jail-ClMpVc__.js +1979 -0
- package/lib/{packs-BYjrAen6.js → packs-BC2A3geF.js} +3 -29
- package/lib/{presenter-agent-CiEVKcjJ.js → presenter-agent-DnNEG_Mn.js} +4 -3
- package/lib/{pack-jail-CybSNzxr.js → preset-ClQm7KPQ.js} +22 -2048
- package/lib/preset-author-tools-Dibp-LY9.js +270 -0
- package/lib/preset-authoring.js +53 -0
- package/lib/presets-DNjNxQL5.js +335 -0
- package/lib/{reflection-waxFg1x-.js → reflection-Bju_LPFn.js} +130 -8
- package/package.json +3 -2
- package/prompts/en/preset/persona.md +1 -0
- package/prompts/en/preset/procedure.md +1 -0
- package/prompts/en/preset/welcome.md +1 -0
- package/prompts/zh/preset/persona.md +1 -0
- package/prompts/zh/preset/procedure.md +1 -0
- package/prompts/zh/preset/welcome.md +1 -0
|
@@ -0,0 +1,1979 @@
|
|
|
1
|
+
import { $ as LOCATION_FILE_NAME, B as FACTIONS_DIR, D as loadTriggers, E as TRIGGERS_FILE_NAME, F as loadLore, G as extractStyleFrom, H as CHARACTERS_DIR, I as LOCATIONS_DIR, J as loadVariables, K as withPlayer, L as loadLocations, M as loadCalendar, P as LORE_DIR, Q as parseLoreFile, R as ITEMS_DIR, U as loadCharacters, V as loadFactions, W as subfolders, Z as LORE_FILE_NAME, a as worldOf, at as CHARACTER_FILE_NAME, b as populateLocations, et as parseLocationFile, f as loadValidatedWorld, it as parseFactionFile, m as populateCharacters, mt as InvalidEditProblems, n as contextOf, nt as parseItemFile, o as authoredWorldOf, ot as parseCharacterFile, rt as FACTION_FILE_NAME, st as IMPORT_FOLDER, t as readPreset, tt as ITEM_FILE_NAME, v as populateItems, w as populateVariables, z as loadItems } from "./preset-ClQm7KPQ.js";
|
|
2
|
+
import { _ as writeWorldPrompt } from "./presets-DNjNxQL5.js";
|
|
3
|
+
import { S as InvalidWorldError, _ as shippedLanguages, c as formatIssue, i as plotReferenceProblems, n as loadPlots, r as parsePlotsFile, t as PLOTS_FILE_NAME, u as PROMPTS_FOLDER } from "./load-Clkl0T7C.js";
|
|
4
|
+
import { c as referenceImagePath, v as mapLimit } from "./library-9JB9zw5a.js";
|
|
5
|
+
import { i as textLanguage, n as STORY_LANGUAGES, r as isStoryLanguage, t as LANGUAGE_NAMES } from "./language-BgyxtB2h.js";
|
|
6
|
+
import { _ as API_PREFIX, a as packIds, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId } from "./packs-BC2A3geF.js";
|
|
7
|
+
import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-DJ48HxPI.js";
|
|
8
|
+
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
9
|
+
import { existsSync, lstatSync, statSync } from "node:fs";
|
|
10
|
+
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
12
|
+
import { chmod, cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
13
|
+
import { createSessionStore, readTriggerDefinition, triggerReferenceProblems, writeCalendar } from "@dsh-agentic-roleplay/state";
|
|
14
|
+
//#region src/host/translate/terms.ts
|
|
15
|
+
const STOP = /* @__PURE__ */ new Set([
|
|
16
|
+
"the",
|
|
17
|
+
"and",
|
|
18
|
+
"for",
|
|
19
|
+
"with",
|
|
20
|
+
"from",
|
|
21
|
+
"that",
|
|
22
|
+
"this",
|
|
23
|
+
"his",
|
|
24
|
+
"her",
|
|
25
|
+
"their",
|
|
26
|
+
"she",
|
|
27
|
+
"he",
|
|
28
|
+
"they",
|
|
29
|
+
"you",
|
|
30
|
+
"your",
|
|
31
|
+
"but",
|
|
32
|
+
"not",
|
|
33
|
+
"when",
|
|
34
|
+
"where",
|
|
35
|
+
"what",
|
|
36
|
+
"who",
|
|
37
|
+
"one",
|
|
38
|
+
"two",
|
|
39
|
+
"its",
|
|
40
|
+
"has",
|
|
41
|
+
"had",
|
|
42
|
+
"was",
|
|
43
|
+
"were",
|
|
44
|
+
"are",
|
|
45
|
+
"there",
|
|
46
|
+
"then",
|
|
47
|
+
"now",
|
|
48
|
+
"at",
|
|
49
|
+
"in",
|
|
50
|
+
"on",
|
|
51
|
+
"of",
|
|
52
|
+
"to",
|
|
53
|
+
"a",
|
|
54
|
+
"an"
|
|
55
|
+
]);
|
|
56
|
+
const MAX_TERMS = 40;
|
|
57
|
+
const MIN_USES = 3;
|
|
58
|
+
const capitalised = (word) => /^\p{Lu}[\p{L}'’-]{2,}$/u.test(word) && !STOP.has(word.toLowerCase());
|
|
59
|
+
/** The parts of a name written "Place - Room": each part is a name of its own, and so is the whole. */
|
|
60
|
+
function partsOfName(name) {
|
|
61
|
+
return name.split(/\s+[-–—]\s+/).map((part) => part.trim()).filter((part) => part !== "");
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Words of the world that recur inside other names and texts and so have to be rendered once: the parts of names ("Iron Stag Inn" in "Iron Stag Inn - Bar") and capitalised
|
|
65
|
+
* phrases of two or three words that the texts use again and again ("Iron Stag"). The most used come first; names are not repeated here.
|
|
66
|
+
*/
|
|
67
|
+
function recurringTerms(names, texts) {
|
|
68
|
+
const known = new Set(names);
|
|
69
|
+
const found = /* @__PURE__ */ new Map();
|
|
70
|
+
const add = (term, uses) => {
|
|
71
|
+
if (!known.has(term)) found.set(term, (found.get(term) ?? 0) + uses);
|
|
72
|
+
};
|
|
73
|
+
for (const name of names) for (const part of partsOfName(name)) if (part !== name) add(part, MIN_USES);
|
|
74
|
+
const counts = /* @__PURE__ */ new Map();
|
|
75
|
+
for (const text of [...names, ...texts]) {
|
|
76
|
+
const words = text.split(/[^\p{L}'’-]+/u);
|
|
77
|
+
for (let at = 0; at < words.length; at += 1) for (const size of [2, 3]) {
|
|
78
|
+
const phrase = words.slice(at, at + size);
|
|
79
|
+
if (phrase.length !== size || !phrase.every((word) => capitalised(word.replace(/['’]s$/, "")))) continue;
|
|
80
|
+
const key = phrase.join(" ").replace(/['’]s$/, "");
|
|
81
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
for (const [phrase, uses] of counts) if (uses >= MIN_USES) add(phrase, uses);
|
|
85
|
+
return [...found].sort((a, b) => b[1] - a[1]).slice(0, MAX_TERMS).map(([term]) => term);
|
|
86
|
+
}
|
|
87
|
+
/** Whether `text` uses `term` as a word of its own (case as written). */
|
|
88
|
+
function usesTerm(text, term) {
|
|
89
|
+
const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
90
|
+
return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "u").test(text);
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/host/translate/prose.ts
|
|
94
|
+
const rooted = (roots, paths) => roots.flatMap((root) => paths.map((path) => `${root}${path}`));
|
|
95
|
+
const INTENT = [
|
|
96
|
+
".name",
|
|
97
|
+
".description",
|
|
98
|
+
".plan[]",
|
|
99
|
+
".open_threads[]",
|
|
100
|
+
".constraints[]"
|
|
101
|
+
];
|
|
102
|
+
const FIELDS$1 = {
|
|
103
|
+
world: {
|
|
104
|
+
names: ["name"],
|
|
105
|
+
text: [
|
|
106
|
+
"description",
|
|
107
|
+
"rules[]",
|
|
108
|
+
"metadata.tags[]",
|
|
109
|
+
"opening_message",
|
|
110
|
+
"opening_message[].text",
|
|
111
|
+
"alternate_openings[].title",
|
|
112
|
+
"alternate_openings[].text"
|
|
113
|
+
]
|
|
114
|
+
},
|
|
115
|
+
calendar: {
|
|
116
|
+
names: ["holidays[].name"],
|
|
117
|
+
text: []
|
|
118
|
+
},
|
|
119
|
+
variables: {
|
|
120
|
+
names: [],
|
|
121
|
+
text: rooted(["[]", "variables[]"], [
|
|
122
|
+
".name",
|
|
123
|
+
".description",
|
|
124
|
+
".bands[].label"
|
|
125
|
+
])
|
|
126
|
+
},
|
|
127
|
+
triggers: {
|
|
128
|
+
names: [],
|
|
129
|
+
text: rooted(["[]", "triggers[]"], [
|
|
130
|
+
".name",
|
|
131
|
+
".announce.text",
|
|
132
|
+
".effects[].text",
|
|
133
|
+
".effects[].edit.events[].text"
|
|
134
|
+
])
|
|
135
|
+
},
|
|
136
|
+
plots: {
|
|
137
|
+
names: [],
|
|
138
|
+
text: [
|
|
139
|
+
"plots[].name",
|
|
140
|
+
"plots[].premise",
|
|
141
|
+
"plots[].themes[]",
|
|
142
|
+
"plots[].stakes[]",
|
|
143
|
+
"plots[].resolutions[]",
|
|
144
|
+
...["hooks", "developments"].flatMap((list) => [
|
|
145
|
+
`plots[].${list}[].text`,
|
|
146
|
+
`plots[].${list}[].prerequisites[]`,
|
|
147
|
+
`plots[].${list}[].guidance`,
|
|
148
|
+
`plots[].${list}[].avoid[]`
|
|
149
|
+
])
|
|
150
|
+
]
|
|
151
|
+
},
|
|
152
|
+
character: {
|
|
153
|
+
names: ["name", "aliases[]"],
|
|
154
|
+
text: [
|
|
155
|
+
"age",
|
|
156
|
+
"gender",
|
|
157
|
+
"summary",
|
|
158
|
+
"personality",
|
|
159
|
+
"background",
|
|
160
|
+
"appearance",
|
|
161
|
+
"speech.style",
|
|
162
|
+
"speech.examples[]",
|
|
163
|
+
"start.public_state",
|
|
164
|
+
"start.inner_state",
|
|
165
|
+
"start.activity",
|
|
166
|
+
...INTENT.map((path) => `start.intents[]${path}`),
|
|
167
|
+
"relationships[].label",
|
|
168
|
+
"relationships[].summary",
|
|
169
|
+
"routine[].activity",
|
|
170
|
+
"visual_identity.description"
|
|
171
|
+
]
|
|
172
|
+
},
|
|
173
|
+
location: {
|
|
174
|
+
names: ["name", "features[].name"],
|
|
175
|
+
text: [
|
|
176
|
+
"description",
|
|
177
|
+
"features[].description",
|
|
178
|
+
"exits[].description",
|
|
179
|
+
"exits[].note",
|
|
180
|
+
"exits[].back_description",
|
|
181
|
+
"visual_identity.description"
|
|
182
|
+
]
|
|
183
|
+
},
|
|
184
|
+
item: {
|
|
185
|
+
names: ["name"],
|
|
186
|
+
text: [
|
|
187
|
+
"description",
|
|
188
|
+
"quality",
|
|
189
|
+
"visual_identity.description"
|
|
190
|
+
]
|
|
191
|
+
},
|
|
192
|
+
faction: {
|
|
193
|
+
names: ["name", "aliases[]"],
|
|
194
|
+
text: [
|
|
195
|
+
"summary",
|
|
196
|
+
"description",
|
|
197
|
+
"values[]",
|
|
198
|
+
"structure",
|
|
199
|
+
"start.public_state",
|
|
200
|
+
"start.inner_state",
|
|
201
|
+
...INTENT.map((path) => `start.goals[]${path}`),
|
|
202
|
+
"members[].role",
|
|
203
|
+
"members[].rank",
|
|
204
|
+
"relationships[].label",
|
|
205
|
+
"relationships[].summary"
|
|
206
|
+
]
|
|
207
|
+
},
|
|
208
|
+
lore: {
|
|
209
|
+
names: [],
|
|
210
|
+
text: [
|
|
211
|
+
"title",
|
|
212
|
+
"summary",
|
|
213
|
+
"body"
|
|
214
|
+
]
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
/** The strings of a document that are words for a reader, in document order; strings with no letters need no translation and are left out. */
|
|
218
|
+
function leavesOf(kind, document) {
|
|
219
|
+
const fields = FIELDS$1[kind];
|
|
220
|
+
const names = new Set(fields.names);
|
|
221
|
+
const text = new Set(fields.text);
|
|
222
|
+
const leaves = [];
|
|
223
|
+
const visit = (value, pattern, path) => {
|
|
224
|
+
if (typeof value === "string") {
|
|
225
|
+
const name = names.has(pattern);
|
|
226
|
+
if ((name || text.has(pattern)) && /\p{L}/u.test(value)) leaves.push({
|
|
227
|
+
path,
|
|
228
|
+
text: value,
|
|
229
|
+
name
|
|
230
|
+
});
|
|
231
|
+
} else if (Array.isArray(value)) value.forEach((entry, index) => {
|
|
232
|
+
visit(entry, `${pattern}[]`, [...path, index]);
|
|
233
|
+
});
|
|
234
|
+
else if (typeof value === "object" && value !== null) for (const [key, entry] of Object.entries(value)) visit(entry, pattern === "" ? key : `${pattern}.${key}`, [...path, key]);
|
|
235
|
+
};
|
|
236
|
+
visit(document, "", []);
|
|
237
|
+
return leaves;
|
|
238
|
+
}
|
|
239
|
+
/** Puts `text` where `path` points in the document. */
|
|
240
|
+
function setLeaf(document, path, text) {
|
|
241
|
+
let at = document;
|
|
242
|
+
for (const step of path.slice(0, -1)) at = at[step];
|
|
243
|
+
at[path[path.length - 1]] = text;
|
|
244
|
+
}
|
|
245
|
+
const ROOT_FILES = [
|
|
246
|
+
["world.json", "world"],
|
|
247
|
+
["calendar.json", "calendar"],
|
|
248
|
+
["variables.json", "variables"],
|
|
249
|
+
["triggers.json", "triggers"],
|
|
250
|
+
["plots.json", "plots"]
|
|
251
|
+
];
|
|
252
|
+
const ENTITIES = [
|
|
253
|
+
[
|
|
254
|
+
"characters",
|
|
255
|
+
"character.json",
|
|
256
|
+
"character"
|
|
257
|
+
],
|
|
258
|
+
[
|
|
259
|
+
"locations",
|
|
260
|
+
"location.json",
|
|
261
|
+
"location"
|
|
262
|
+
],
|
|
263
|
+
[
|
|
264
|
+
"items",
|
|
265
|
+
"item.json",
|
|
266
|
+
"item"
|
|
267
|
+
],
|
|
268
|
+
[
|
|
269
|
+
"factions",
|
|
270
|
+
"faction.json",
|
|
271
|
+
"faction"
|
|
272
|
+
],
|
|
273
|
+
[
|
|
274
|
+
"lore",
|
|
275
|
+
"lore.json",
|
|
276
|
+
"lore"
|
|
277
|
+
]
|
|
278
|
+
];
|
|
279
|
+
async function readIfThere(file) {
|
|
280
|
+
try {
|
|
281
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
282
|
+
} catch (error) {
|
|
283
|
+
if (error.code === "ENOENT") return void 0;
|
|
284
|
+
throw new Error(`${file} cannot be read: ${error instanceof Error ? error.message : String(error)}`);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
/** Every file of a world that holds words for a reader. A file that does not parse stops the read: a world with a broken file is not translated. */
|
|
288
|
+
async function readWorldDocuments(directory) {
|
|
289
|
+
const found = [];
|
|
290
|
+
for (const [file, kind] of ROOT_FILES) {
|
|
291
|
+
const document = await readIfThere(join(directory, file));
|
|
292
|
+
if (document !== void 0) found.push({
|
|
293
|
+
file,
|
|
294
|
+
kind,
|
|
295
|
+
document
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
for (const [folder, name, kind] of ENTITIES) {
|
|
299
|
+
let entries;
|
|
300
|
+
try {
|
|
301
|
+
entries = (await readdir(join(directory, folder), { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
|
|
302
|
+
} catch (error) {
|
|
303
|
+
if (error.code === "ENOENT") continue;
|
|
304
|
+
throw error;
|
|
305
|
+
}
|
|
306
|
+
for (const entry of entries) {
|
|
307
|
+
const file = join(folder, entry, name);
|
|
308
|
+
const document = await readIfThere(join(directory, file));
|
|
309
|
+
if (document !== void 0) found.push({
|
|
310
|
+
file,
|
|
311
|
+
kind,
|
|
312
|
+
document
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return found;
|
|
317
|
+
}
|
|
318
|
+
//#endregion
|
|
319
|
+
//#region src/host/translate/translate-world.ts
|
|
320
|
+
/** What is not carried over to a translation: the removed things of the editor and the card import's working files. */
|
|
321
|
+
const NOT_COPIED = /* @__PURE__ */ new Set([".trash", ".import"]);
|
|
322
|
+
const TERMS_PER_JOB = 40;
|
|
323
|
+
const TEXTS_PER_JOB = 30;
|
|
324
|
+
const CHARS_PER_JOB = 5e3;
|
|
325
|
+
const GLOSSARY_SHOWN = 60;
|
|
326
|
+
/** A text with fewer letters than this is too short to check which language it came out in. */
|
|
327
|
+
const CHECKED_LETTERS = 40;
|
|
328
|
+
/** A name shorter than this is too likely to be an ordinary word to be held to the glossary. */
|
|
329
|
+
const MIN_TERM = 4;
|
|
330
|
+
var TranslationRefusedError = class extends Error {};
|
|
331
|
+
const STRINGS = {
|
|
332
|
+
type: "array",
|
|
333
|
+
items: { type: "string" }
|
|
334
|
+
};
|
|
335
|
+
const GLOSSARY_SCHEMA = {
|
|
336
|
+
type: "object",
|
|
337
|
+
properties: { terms: {
|
|
338
|
+
type: "array",
|
|
339
|
+
items: {
|
|
340
|
+
type: "object",
|
|
341
|
+
properties: {
|
|
342
|
+
source: { type: "string" },
|
|
343
|
+
target: { type: "string" }
|
|
344
|
+
},
|
|
345
|
+
required: ["source", "target"],
|
|
346
|
+
additionalProperties: false
|
|
347
|
+
},
|
|
348
|
+
description: "One entry for each name given, in the same order, with the source exactly as given."
|
|
349
|
+
} },
|
|
350
|
+
required: ["terms"],
|
|
351
|
+
additionalProperties: false
|
|
352
|
+
};
|
|
353
|
+
const TEXTS_SCHEMA = {
|
|
354
|
+
type: "object",
|
|
355
|
+
properties: { translations: {
|
|
356
|
+
...STRINGS,
|
|
357
|
+
description: "The translation of each text, in the order given."
|
|
358
|
+
} },
|
|
359
|
+
required: ["translations"],
|
|
360
|
+
additionalProperties: false
|
|
361
|
+
};
|
|
362
|
+
const BRACED = /\$?\{[^{}]*\}/g;
|
|
363
|
+
const braces = (text) => (text.match(BRACED) ?? []).sort().join("\0");
|
|
364
|
+
const letters = (text) => text.match(/\p{L}/gu)?.length ?? 0;
|
|
365
|
+
/** The language the world is written in, from the words of all its files; nothing when there are too few to tell. */
|
|
366
|
+
function languageOfDocuments(documents) {
|
|
367
|
+
return textLanguage(documents.flatMap((entry) => leavesOf(entry.kind, entry.document).map((leaf) => leaf.text)).join("\n"));
|
|
368
|
+
}
|
|
369
|
+
function batches(items, size, maxItems, maxSize) {
|
|
370
|
+
const out = [];
|
|
371
|
+
let current = [];
|
|
372
|
+
let used = 0;
|
|
373
|
+
for (const item of items) {
|
|
374
|
+
if (current.length > 0 && (current.length >= maxItems || used + size(item) > maxSize)) {
|
|
375
|
+
out.push(current);
|
|
376
|
+
current = [];
|
|
377
|
+
used = 0;
|
|
378
|
+
}
|
|
379
|
+
current.push(item);
|
|
380
|
+
used += size(item);
|
|
381
|
+
}
|
|
382
|
+
if (current.length > 0) out.push(current);
|
|
383
|
+
return out;
|
|
384
|
+
}
|
|
385
|
+
/** Why a set of translations cannot be used, or nothing. A text left in the language it was written in is not a translation. */
|
|
386
|
+
function problemWith(sources, from, translations, glossary) {
|
|
387
|
+
if (translations.length !== sources.length) return `${sources.length} texts were given and ${translations.length} translations came back: give exactly one for each, in order`;
|
|
388
|
+
for (const [index, source] of sources.entries()) {
|
|
389
|
+
const text = translations[index];
|
|
390
|
+
if (text.trim() === "") return `translation ${index + 1} is empty`;
|
|
391
|
+
if (braces(source) !== braces(text)) return `translation ${index + 1} must keep the text in curly braces exactly as it is: ${(source.match(BRACED) ?? []).join(" ")}`;
|
|
392
|
+
if (letters(source) >= CHECKED_LETTERS && textLanguage(source) === from && textLanguage(text) === from) return `translation ${index + 1} is still in the original language`;
|
|
393
|
+
for (const [term, rendering] of glossary) if (term.length >= MIN_TERM && rendering !== term && !rendering.includes(term) && usesTerm(source, term) && usesTerm(text, term)) return `translation ${index + 1} still has "${term}": the glossary renders it "${rendering}"`;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
async function glossaryOf(ctx, names, vars, known = /* @__PURE__ */ new Map()) {
|
|
397
|
+
const jobs = batches(names, () => 1, TERMS_PER_JOB, TERMS_PER_JOB);
|
|
398
|
+
const parts = await mapLimit(jobs, ctx.concurrency, async (terms) => {
|
|
399
|
+
const job = {
|
|
400
|
+
persona: ctx.text("translate/glossary", vars),
|
|
401
|
+
prompt: JSON.stringify({
|
|
402
|
+
known: Object.fromEntries([...known].filter(([source]) => terms.some((term) => term.toLowerCase().includes(source.toLowerCase())))),
|
|
403
|
+
names: terms
|
|
404
|
+
}),
|
|
405
|
+
result: GLOSSARY_SCHEMA,
|
|
406
|
+
check: (value) => {
|
|
407
|
+
if (value.terms.length !== terms.length) return `${terms.length} names were given and ${value.terms.length} came back: one for each, in order`;
|
|
408
|
+
const wrong = terms.findIndex((term, index) => value.terms[index].source !== term || value.terms[index].target.trim() === "");
|
|
409
|
+
return wrong === -1 ? void 0 : `entry ${wrong + 1} must repeat "${terms[wrong]}" exactly and have a translation`;
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
return (await ctx.run(job)).terms;
|
|
413
|
+
});
|
|
414
|
+
return new Map(parts.flat().map((term) => [term.source, term.target.trim()]));
|
|
415
|
+
}
|
|
416
|
+
async function translated(ctx, texts, glossary, from, vars) {
|
|
417
|
+
return (await mapLimit(batches(texts, (text) => text.length, TEXTS_PER_JOB, CHARS_PER_JOB), ctx.concurrency, async (group) => {
|
|
418
|
+
const haystack = group.join("\n").toLowerCase();
|
|
419
|
+
const shown = [...glossary].filter(([source]) => haystack.includes(source.toLowerCase())).slice(0, GLOSSARY_SHOWN);
|
|
420
|
+
const relevant = new Map(shown);
|
|
421
|
+
const job = {
|
|
422
|
+
persona: ctx.text("translate/document", vars),
|
|
423
|
+
prompt: JSON.stringify({
|
|
424
|
+
glossary: Object.fromEntries(shown),
|
|
425
|
+
texts: group.map((text, index) => ({
|
|
426
|
+
n: index + 1,
|
|
427
|
+
text
|
|
428
|
+
}))
|
|
429
|
+
}),
|
|
430
|
+
result: TEXTS_SCHEMA,
|
|
431
|
+
check: (value) => problemWith(group, from, value.translations, relevant)
|
|
432
|
+
};
|
|
433
|
+
return (await ctx.run(job)).translations;
|
|
434
|
+
})).flat();
|
|
435
|
+
}
|
|
436
|
+
async function freeFolder(directory, suffix) {
|
|
437
|
+
for (let n = 1;; n += 1) {
|
|
438
|
+
const candidate = join(dirname(directory), `${basename(directory)} ${suffix}${n === 1 ? "" : ` ${n}`}`);
|
|
439
|
+
try {
|
|
440
|
+
await stat(candidate);
|
|
441
|
+
} catch (error) {
|
|
442
|
+
if (error.code === "ENOENT") return candidate;
|
|
443
|
+
throw error;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
/** The ids of the Markdown prompt files under a world's prompt folder for one language (`roleplay/style`), or none when it has none. */
|
|
448
|
+
async function promptIds(folder, prefix = "") {
|
|
449
|
+
let entries;
|
|
450
|
+
try {
|
|
451
|
+
entries = await readdir(join(folder, prefix), { withFileTypes: true });
|
|
452
|
+
} catch (error) {
|
|
453
|
+
if (error.code === "ENOENT") return [];
|
|
454
|
+
throw error;
|
|
455
|
+
}
|
|
456
|
+
const ids = [];
|
|
457
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
458
|
+
const id = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
|
|
459
|
+
if (entry.isDirectory()) ids.push(...await promptIds(folder, id));
|
|
460
|
+
else if (entry.isFile() && entry.name.endsWith(".md")) ids.push(id.slice(0, -3));
|
|
461
|
+
}
|
|
462
|
+
return ids;
|
|
463
|
+
}
|
|
464
|
+
async function listedIn(directory, names) {
|
|
465
|
+
const present = new Set(await readdir(directory));
|
|
466
|
+
return names.filter((name) => present.has(name));
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Makes a copy of a world in another language, next to it: the names first, so that every file calls each person, place and thing the same, then the words of each file.
|
|
470
|
+
* The original is never changed. The copy gets an id of its own and is checked as a story start would check it.
|
|
471
|
+
*/
|
|
472
|
+
async function translateWorld(ctx, worlds, source, to, told) {
|
|
473
|
+
const documents = await readWorldDocuments(source.directory);
|
|
474
|
+
const from = languageOfDocuments(documents);
|
|
475
|
+
if (from === void 0) throw new TranslationRefusedError("there is too little text in this world to tell which language it is written in");
|
|
476
|
+
if (from === to) throw new TranslationRefusedError(`this world is already written in ${LANGUAGE_NAMES[to].en}`);
|
|
477
|
+
const vars = {
|
|
478
|
+
from: LANGUAGE_NAMES[from][told],
|
|
479
|
+
to: LANGUAGE_NAMES[to][told]
|
|
480
|
+
};
|
|
481
|
+
const leaves = documents.map((entry) => ({
|
|
482
|
+
entry,
|
|
483
|
+
leaves: leavesOf(entry.kind, entry.document)
|
|
484
|
+
}));
|
|
485
|
+
const names = [...new Set(leaves.flatMap((item) => item.leaves.filter((leaf) => leaf.name).map((leaf) => leaf.text)))];
|
|
486
|
+
ctx.say(`translating ${names.length} names`);
|
|
487
|
+
const prose = leaves.flatMap((item) => item.leaves.filter((leaf) => !leaf.name).map((leaf) => leaf.text));
|
|
488
|
+
const recurring = from === "en" ? recurringTerms(names, prose) : [];
|
|
489
|
+
const parts = await glossaryOf(ctx, recurring, vars);
|
|
490
|
+
const glossary = await glossaryOf(ctx, names, vars, parts);
|
|
491
|
+
for (const [term, rendering] of parts) glossary.set(term, rendering);
|
|
492
|
+
let texts = 0;
|
|
493
|
+
for (const { entry, leaves: own } of leaves) {
|
|
494
|
+
const words = own.filter((leaf) => !leaf.name);
|
|
495
|
+
for (const leaf of own.filter((item) => item.name)) setLeaf(entry.document, leaf.path, glossary.get(leaf.text) ?? leaf.text);
|
|
496
|
+
if (words.length === 0) continue;
|
|
497
|
+
ctx.say(`translating ${entry.file}`);
|
|
498
|
+
const result = await translated(ctx, words.map((leaf) => leaf.text), glossary, from, vars);
|
|
499
|
+
for (const [index, leaf] of words.entries()) setLeaf(entry.document, leaf.path, result[index]);
|
|
500
|
+
texts += words.length;
|
|
501
|
+
}
|
|
502
|
+
for (const { entry, leaves: own } of leaves) {
|
|
503
|
+
const document = entry.document;
|
|
504
|
+
if (entry.kind !== "character" && entry.kind !== "faction") continue;
|
|
505
|
+
const original = own.find((leaf) => leaf.name && leaf.path.length === 1 && leaf.path[0] === "name")?.text;
|
|
506
|
+
const aliases = Array.isArray(document["aliases"]) ? document["aliases"] : [];
|
|
507
|
+
if (original !== void 0 && original !== document["name"] && !aliases.includes(original)) document["aliases"] = [...aliases, original];
|
|
508
|
+
}
|
|
509
|
+
const own = await promptIds(join(source.directory, "prompts", from));
|
|
510
|
+
const present = new Set(await promptIds(join(source.directory, "prompts", to)));
|
|
511
|
+
const owed = own.filter((prompt) => !present.has(prompt));
|
|
512
|
+
const written = [];
|
|
513
|
+
if (owed.length > 0) {
|
|
514
|
+
ctx.say(`translating ${owed.length} prompt files`);
|
|
515
|
+
const result = await translated(ctx, await Promise.all(owed.map((prompt) => readFile(join(source.directory, "prompts", from, `${prompt}.md`), "utf8"))), glossary, from, vars);
|
|
516
|
+
for (const [index, prompt] of owed.entries()) written.push({
|
|
517
|
+
id: prompt,
|
|
518
|
+
text: result[index]
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
const id = randomUUID();
|
|
522
|
+
const destination = await freeFolder(source.directory, to);
|
|
523
|
+
await cp(source.directory, destination, {
|
|
524
|
+
recursive: true,
|
|
525
|
+
filter: (path) => !NOT_COPIED.has(relative(source.directory, path).split(sep)[0])
|
|
526
|
+
});
|
|
527
|
+
for (const entry of documents) {
|
|
528
|
+
const document = entry.kind === "world" ? (({ id: _old, ...rest }) => ({
|
|
529
|
+
id,
|
|
530
|
+
...rest
|
|
531
|
+
}))(entry.document) : entry.document;
|
|
532
|
+
await writeFile(join(destination, entry.file), `${JSON.stringify(document, null, 2)}\n`);
|
|
533
|
+
}
|
|
534
|
+
for (const prompt of written) {
|
|
535
|
+
const file = join(destination, "prompts", to, `${prompt.id}.md`);
|
|
536
|
+
await mkdir(dirname(file), { recursive: true });
|
|
537
|
+
await writeFile(file, prompt.text.endsWith("\n") ? prompt.text : `${prompt.text}\n`);
|
|
538
|
+
}
|
|
539
|
+
const payload = await worlds.list({ refresh: true });
|
|
540
|
+
const made = payload.worlds.find((world) => world.id === id);
|
|
541
|
+
if (made === void 0) throw new Error(`the translated world was written to ${destination} but the catalogue does not list it: ${payload.problems.map((problem) => problem.message).join("; ")}`);
|
|
542
|
+
const record = await worlds.find(id);
|
|
543
|
+
const problems = [];
|
|
544
|
+
if (record !== void 0) try {
|
|
545
|
+
await loadValidatedWorld(record);
|
|
546
|
+
} catch (error) {
|
|
547
|
+
if (!(error instanceof InvalidWorldError)) throw error;
|
|
548
|
+
problems.push(...error.problems.map((problem) => `${relative(destination, problem.path) || "."}: ${problem.message}`));
|
|
549
|
+
}
|
|
550
|
+
return {
|
|
551
|
+
worldId: id,
|
|
552
|
+
name: made.name,
|
|
553
|
+
folder: basename(destination),
|
|
554
|
+
documents: documents.length,
|
|
555
|
+
texts,
|
|
556
|
+
names: names.length + recurring.length,
|
|
557
|
+
problems,
|
|
558
|
+
prompts: written.map((prompt) => prompt.id),
|
|
559
|
+
copiedAsIs: await listedIn(source.directory, [
|
|
560
|
+
"ui",
|
|
561
|
+
"images",
|
|
562
|
+
"media"
|
|
563
|
+
])
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
//#endregion
|
|
567
|
+
//#region src/host/translate/tools.ts
|
|
568
|
+
const TRANSLATE_TOOL = "translate_world";
|
|
569
|
+
/** The message that has the authoring chat translate its world, in the language of the person who asked. */
|
|
570
|
+
function translateMessage(text, to, language) {
|
|
571
|
+
return text("translate/notice", {
|
|
572
|
+
tool: TRANSLATE_TOOL,
|
|
573
|
+
code: to,
|
|
574
|
+
to: to === "zh" ? language === "zh" ? "中文" : "Chinese" : language === "zh" ? "英文" : "English"
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
/** The tool of the authoring chat that translates the chat's world into a copy in another language. */
|
|
578
|
+
function translateTools(worlds, settings, prompting) {
|
|
579
|
+
return [defineTool({
|
|
580
|
+
name: TRANSLATE_TOOL,
|
|
581
|
+
description: "Makes a translated copy of this world, next to it, in another language: its names first, so every file calls each person, place and thing the same, then the words of every file. The world itself is not changed. Takes several minutes. Use it only when the person asked for a translation.",
|
|
582
|
+
parameters: { language: {
|
|
583
|
+
type: "string",
|
|
584
|
+
required: true,
|
|
585
|
+
enum: [...STORY_LANGUAGES],
|
|
586
|
+
description: "The language to translate into: en or zh."
|
|
587
|
+
} },
|
|
588
|
+
output: {
|
|
589
|
+
schema: { type: "json" },
|
|
590
|
+
render: (_args, value) => [{
|
|
591
|
+
type: "text",
|
|
592
|
+
text: JSON.stringify(value, null, 1)
|
|
593
|
+
}]
|
|
594
|
+
},
|
|
595
|
+
isConcurrencySafe: () => false,
|
|
596
|
+
async execute(args, exec) {
|
|
597
|
+
if (!isStoryLanguage(args.language)) throw new Error(`language must be one of: ${STORY_LANGUAGES.join(", ")}`);
|
|
598
|
+
const world = await worldOf(worlds, exec);
|
|
599
|
+
const told = prompting.languages().get(world.id);
|
|
600
|
+
const text = (id, variables) => prompting.prompts().text(id, told, variables);
|
|
601
|
+
const report = await translateWorld(contextOf(exec, settings(), text), worlds, world, args.language, told.startsWith("zh") ? "zh" : "en");
|
|
602
|
+
return JSON.parse(JSON.stringify(report));
|
|
603
|
+
}
|
|
604
|
+
})];
|
|
605
|
+
}
|
|
606
|
+
//#endregion
|
|
607
|
+
//#region src/host/import/preset-tools.ts
|
|
608
|
+
const PRESET_TOOL = "import_preset";
|
|
609
|
+
const PRESET_FILE = "preset.json";
|
|
610
|
+
const PRESET_PATH = `${IMPORT_FOLDER}/${PRESET_FILE}`;
|
|
611
|
+
/** The command that has the authoring chat apply a preset that was uploaded to the world. */
|
|
612
|
+
const presetMessage = () => `Apply the narration preset I uploaded to this world: call ${PRESET_TOOL} with file ${PRESET_PATH}.`;
|
|
613
|
+
/** The tool that turns an uploaded narration preset into the world's prose prompts; every call asks the person first. */
|
|
614
|
+
function presetTools(worlds, settings, prompting) {
|
|
615
|
+
return [defineTool({
|
|
616
|
+
name: PRESET_TOOL,
|
|
617
|
+
description: `Turn the narration preset the person uploaded to this world (${PRESET_PATH}) into the world's prose prompts: how the narration is written and how the characters speak and behave. Rules of the game, formats and scripts in the preset are not carried. It replaces the world's own versions of those prompts, so the person is asked first.`,
|
|
618
|
+
parameters: { file: {
|
|
619
|
+
type: "string",
|
|
620
|
+
required: true,
|
|
621
|
+
description: `The preset: ${PRESET_PATH}.`
|
|
622
|
+
} },
|
|
623
|
+
output: {
|
|
624
|
+
schema: { type: "json" },
|
|
625
|
+
render: (_args, value) => [{
|
|
626
|
+
type: "text",
|
|
627
|
+
text: JSON.stringify(value, null, 1)
|
|
628
|
+
}]
|
|
629
|
+
},
|
|
630
|
+
isConcurrencySafe: () => false,
|
|
631
|
+
async execute(args, exec) {
|
|
632
|
+
if (args.file.trim() !== PRESET_PATH) throw new Error(`the preset is ${PRESET_PATH}`);
|
|
633
|
+
const world = await worldOf(worlds, exec);
|
|
634
|
+
const file = join(world.directory, IMPORT_FOLDER, PRESET_FILE);
|
|
635
|
+
const preset = readPreset(await readFile(file).catch(() => {
|
|
636
|
+
throw new Error("no preset was uploaded to this world");
|
|
637
|
+
}), "preset");
|
|
638
|
+
const language = prompting.languages().get(world.id);
|
|
639
|
+
const text = (id, variables) => prompting.prompts().text(id, language, variables);
|
|
640
|
+
const made = await extractStyleFrom(contextOf(exec, settings(), text), preset.name, preset.pieces);
|
|
641
|
+
for (const { id, text: body } of made.prompts) for (const tag of shippedLanguages()) await writeWorldPrompt(world.directory, tag, id, withPlayer(body));
|
|
642
|
+
await rm(file, { force: true });
|
|
643
|
+
const written = made.prompts.map((entry) => entry.id);
|
|
644
|
+
return JSON.parse(JSON.stringify({
|
|
645
|
+
preset: preset.name,
|
|
646
|
+
written,
|
|
647
|
+
folder: `${PROMPTS_FOLDER}/<language>/`,
|
|
648
|
+
notes: made.notes,
|
|
649
|
+
next: written.length === 0 ? "Nothing in the preset was about how to write the story, so no prompt was changed: tell the person." : "Tell the person which prompts were written (they can read and edit them in the world's Prompts section) and what was not carried over."
|
|
650
|
+
}));
|
|
651
|
+
}
|
|
652
|
+
})];
|
|
653
|
+
}
|
|
654
|
+
//#endregion
|
|
655
|
+
//#region src/host/triggers/parts.ts
|
|
656
|
+
/** What the files of a world say it has, for checking what a trigger names. @throws {InvalidEditProblems} when those files have problems of their own: they are fixed first. */
|
|
657
|
+
async function loadWorldParts(directory) {
|
|
658
|
+
const { characters, problems: characterProblems } = await loadCharacters(directory);
|
|
659
|
+
const { locations, problems: locationProblems } = await loadLocations(directory);
|
|
660
|
+
const { items, slots, problems: itemProblems } = await loadItems(directory, {
|
|
661
|
+
characters: characters.map((character) => character.id),
|
|
662
|
+
locations
|
|
663
|
+
});
|
|
664
|
+
const { defs, problems: variableProblems } = await loadVariables(directory);
|
|
665
|
+
const { calendar, problems: calendarProblems } = await loadCalendar(directory);
|
|
666
|
+
const problems = [
|
|
667
|
+
...characterProblems,
|
|
668
|
+
...locationProblems,
|
|
669
|
+
...itemProblems,
|
|
670
|
+
...variableProblems,
|
|
671
|
+
...calendarProblems
|
|
672
|
+
];
|
|
673
|
+
if (problems.length > 0) throw new InvalidEditProblems([`the world's other files have problems that come first: ${problems.map((problem) => `${problem.path}: ${problem.message}`).join("; ")}`]);
|
|
674
|
+
return {
|
|
675
|
+
characters,
|
|
676
|
+
locations,
|
|
677
|
+
items,
|
|
678
|
+
slots,
|
|
679
|
+
variables: defs,
|
|
680
|
+
calendar
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
//#endregion
|
|
684
|
+
//#region src/host/triggers/check.ts
|
|
685
|
+
/**
|
|
686
|
+
* What each trigger names that the world does not have (a character, place, item or variable in its condition, its cues or the words of a
|
|
687
|
+
* cue), found as a session start finds it: against a scratch story made from the world's files. Triggers that wait for each other count
|
|
688
|
+
* as there. @returns the problems by trigger key; a trigger with none is not in it.
|
|
689
|
+
*/
|
|
690
|
+
function triggerProblemsOf(parts, definitions) {
|
|
691
|
+
const found = /* @__PURE__ */ new Map();
|
|
692
|
+
if (definitions.length === 0) return found;
|
|
693
|
+
const scratch = createSessionStore(":memory:", {
|
|
694
|
+
id: "scratch",
|
|
695
|
+
name: "scratch",
|
|
696
|
+
world: {
|
|
697
|
+
id: "scratch",
|
|
698
|
+
name: "scratch"
|
|
699
|
+
}
|
|
700
|
+
}, { vectors: false });
|
|
701
|
+
try {
|
|
702
|
+
const session = scratch;
|
|
703
|
+
if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
|
|
704
|
+
populateLocations(session, parts.locations);
|
|
705
|
+
populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
|
|
706
|
+
populateItems(session, parts.items, parts.slots, parts.locations);
|
|
707
|
+
populateVariables(session, parts.variables, {
|
|
708
|
+
characters: parts.characters,
|
|
709
|
+
items: parts.items,
|
|
710
|
+
locations: parts.locations,
|
|
711
|
+
values: void 0
|
|
712
|
+
});
|
|
713
|
+
const keys = definitions.map((definition) => definition.key);
|
|
714
|
+
for (const definition of definitions) {
|
|
715
|
+
const problems = triggerReferenceProblems(scratch, definition, keys).map((problem) => problem.slice(definition.key.length + 2));
|
|
716
|
+
if (problems.length > 0) found.set(definition.key, problems);
|
|
717
|
+
}
|
|
718
|
+
} finally {
|
|
719
|
+
scratch.close();
|
|
720
|
+
}
|
|
721
|
+
return found;
|
|
722
|
+
}
|
|
723
|
+
//#endregion
|
|
724
|
+
//#region src/host/triggers/files.ts
|
|
725
|
+
/** The fields of a trigger in the file; any other is a mistake that would otherwise be dropped without a word. */
|
|
726
|
+
const FIELDS = /* @__PURE__ */ new Set([
|
|
727
|
+
"key",
|
|
728
|
+
"name",
|
|
729
|
+
"when",
|
|
730
|
+
"effects",
|
|
731
|
+
"repeat",
|
|
732
|
+
"cooldown_seconds",
|
|
733
|
+
"chance",
|
|
734
|
+
"priority",
|
|
735
|
+
"expires",
|
|
736
|
+
"announce"
|
|
737
|
+
]);
|
|
738
|
+
const isDocument = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
739
|
+
/** The documents of `<world>/triggers.json` as written; none when the file is not there. @throws {InvalidEditProblems} when it is not a list of objects. */
|
|
740
|
+
async function readTriggerDocuments(directory) {
|
|
741
|
+
let text;
|
|
742
|
+
try {
|
|
743
|
+
text = await readFile(join(directory, TRIGGERS_FILE_NAME), "utf8");
|
|
744
|
+
} catch (error) {
|
|
745
|
+
if (error.code === "ENOENT") return [];
|
|
746
|
+
throw error;
|
|
747
|
+
}
|
|
748
|
+
let data;
|
|
749
|
+
try {
|
|
750
|
+
data = JSON.parse(text.replace(/^/, ""));
|
|
751
|
+
} catch (error) {
|
|
752
|
+
throw new InvalidEditProblems([`triggers.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`]);
|
|
753
|
+
}
|
|
754
|
+
if (!Array.isArray(data) || !data.every(isDocument)) throw new InvalidEditProblems(["triggers.json is not a list of triggers"]);
|
|
755
|
+
return data;
|
|
756
|
+
}
|
|
757
|
+
async function writeDocuments(directory, documents) {
|
|
758
|
+
const file = join(directory, TRIGGERS_FILE_NAME);
|
|
759
|
+
const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
|
|
760
|
+
try {
|
|
761
|
+
const mode = await stat(file).then((value) => value.mode, () => void 0);
|
|
762
|
+
await writeFile(temporary, `${JSON.stringify(documents, null, 2)}\n`, mode === void 0 ? {} : { mode });
|
|
763
|
+
await rename(temporary, file);
|
|
764
|
+
} catch (error) {
|
|
765
|
+
await rm(temporary, { force: true });
|
|
766
|
+
throw error;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
/** The keys of the triggers a condition waits for. */
|
|
770
|
+
function waitsFor(condition) {
|
|
771
|
+
switch (condition.type) {
|
|
772
|
+
case "fired": return [condition.trigger];
|
|
773
|
+
case "all":
|
|
774
|
+
case "any": return condition.conditions.flatMap(waitsFor);
|
|
775
|
+
case "not": return waitsFor(condition.condition);
|
|
776
|
+
default: return [];
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* Makes or replaces one trigger of the world, by key, from a complete document in the file format. It is read as a session start reads it, and
|
|
781
|
+
* what it names that the world does not have is refused, with every problem; nothing is written then.
|
|
782
|
+
* @throws {InvalidEditProblems}
|
|
783
|
+
*/
|
|
784
|
+
async function writeTriggerDocument(directory, parts, key, document) {
|
|
785
|
+
if (!isDocument(document)) throw new InvalidEditProblems(["document must be a JSON object"]);
|
|
786
|
+
const unknown = Object.keys(document).filter((field) => !FIELDS.has(field));
|
|
787
|
+
if (unknown.length > 0) throw new InvalidEditProblems(unknown.map((field) => `"${field}" is not a field of a trigger (${[...FIELDS].join(", ")})`));
|
|
788
|
+
const written = {
|
|
789
|
+
...document,
|
|
790
|
+
key
|
|
791
|
+
};
|
|
792
|
+
const parsed = readTriggerDefinition(written, "trigger");
|
|
793
|
+
if ("problems" in parsed) throw new InvalidEditProblems(parsed.problems);
|
|
794
|
+
const documents = await readTriggerDocuments(directory);
|
|
795
|
+
const at = documents.findIndex((entry) => entry["key"] === key);
|
|
796
|
+
const problems = triggerProblemsOf(parts, [...documents.filter((_, index) => index !== at).flatMap((entry) => {
|
|
797
|
+
const read = readTriggerDefinition(entry, "trigger");
|
|
798
|
+
return "definition" in read ? [read.definition] : [];
|
|
799
|
+
}), parsed.definition]).get(key) ?? [];
|
|
800
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
801
|
+
await writeDocuments(directory, at < 0 ? [...documents, written] : documents.map((entry, index) => index === at ? written : entry));
|
|
802
|
+
return at < 0 ? "created" : "replaced";
|
|
803
|
+
}
|
|
804
|
+
/**
|
|
805
|
+
* Removes one trigger from the world's file, keeping its document in `.trash/triggers` so that it can be put back. A trigger that others wait for
|
|
806
|
+
* cannot be removed.
|
|
807
|
+
* @returns where the document was kept.
|
|
808
|
+
* @throws {InvalidEditProblems}
|
|
809
|
+
*/
|
|
810
|
+
async function deleteTriggerDocument(directory, key) {
|
|
811
|
+
const documents = await readTriggerDocuments(directory);
|
|
812
|
+
const found = documents.find((entry) => entry["key"] === key);
|
|
813
|
+
if (found === void 0) throw new InvalidEditProblems([`there is no trigger "${key}"`]);
|
|
814
|
+
const waiting = documents.flatMap((entry) => {
|
|
815
|
+
const read = readTriggerDefinition(entry, "trigger");
|
|
816
|
+
return "definition" in read && read.definition.key !== key && waitsFor(read.definition.condition).includes(key) ? [read.definition.key] : [];
|
|
817
|
+
});
|
|
818
|
+
if (waiting.length > 0) throw new InvalidEditProblems([`${waiting.join(", ")} wait${waiting.length === 1 ? "s" : ""} for "${key}" to fire; change ${waiting.length === 1 ? "it" : "them"} first`]);
|
|
819
|
+
const trash = join(directory, ".trash", "triggers");
|
|
820
|
+
await mkdir(trash, { recursive: true });
|
|
821
|
+
const kept = join(trash, `${key}-${Date.now()}-${randomUUID()}.json`);
|
|
822
|
+
await writeFile(kept, `${JSON.stringify(found, null, 2)}\n`, { flag: "wx" });
|
|
823
|
+
await writeDocuments(directory, documents.filter((entry) => entry !== found));
|
|
824
|
+
return kept;
|
|
825
|
+
}
|
|
826
|
+
//#endregion
|
|
827
|
+
//#region src/host/worlds/world-editor.ts
|
|
828
|
+
function stateOf(world, definition, names) {
|
|
829
|
+
const { start } = definition;
|
|
830
|
+
const portrait = referenceImagePath(world.directory, {
|
|
831
|
+
kind: "character",
|
|
832
|
+
localId: definition.id,
|
|
833
|
+
...definition.visualIdentity?.globalId === void 0 ? {} : { globalId: definition.visualIdentity.globalId }
|
|
834
|
+
});
|
|
835
|
+
return {
|
|
836
|
+
key: definition.id,
|
|
837
|
+
name: definition.name,
|
|
838
|
+
aliases: definition.aliases,
|
|
839
|
+
role: definition.role,
|
|
840
|
+
tier: definition.tier,
|
|
841
|
+
kind: definition.kind,
|
|
842
|
+
control: definition.role === "playable" ? "player" : "agent",
|
|
843
|
+
...definition.age === void 0 ? {} : { age: definition.age },
|
|
844
|
+
...definition.gender === void 0 ? {} : { gender: definition.gender },
|
|
845
|
+
...definition.pronouns === void 0 ? {} : { pronouns: definition.pronouns },
|
|
846
|
+
summary: definition.summary,
|
|
847
|
+
personality: definition.personality,
|
|
848
|
+
background: definition.background,
|
|
849
|
+
appearance: definition.appearance,
|
|
850
|
+
speech: definition.speech,
|
|
851
|
+
...definition.voice === void 0 ? {} : { voice: definition.voice },
|
|
852
|
+
...definition.visualIdentity === void 0 ? {} : { visualIdentity: definition.visualIdentity },
|
|
853
|
+
...existsSync(portrait) ? { portrait: `/${API_PREFIX}/worlds/state/character/portrait/file?id=${encodeURIComponent(world.id)}&key=${encodeURIComponent(definition.id)}&v=${statSync(portrait).mtimeMs}` } : {},
|
|
854
|
+
state: {
|
|
855
|
+
publicState: start.publicState,
|
|
856
|
+
innerState: start.innerState,
|
|
857
|
+
activity: start.activity
|
|
858
|
+
},
|
|
859
|
+
...start.place === void 0 ? {} : { place: {
|
|
860
|
+
key: start.place.location,
|
|
861
|
+
name: names.get(start.place.location) ?? start.place.location,
|
|
862
|
+
...start.place.position === void 0 ? {} : { position: start.place.position }
|
|
863
|
+
} },
|
|
864
|
+
goals: start.intents.map((intent, index) => ({
|
|
865
|
+
ref: String(index),
|
|
866
|
+
name: intent.name,
|
|
867
|
+
description: intent.description,
|
|
868
|
+
status: intent.status,
|
|
869
|
+
priority: intent.priority
|
|
870
|
+
}))
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
/** The triggers of the world's file as the editor shows them, with what each names that the world does not have; or why the file cannot be shown. */
|
|
874
|
+
function triggersOf(parts, scripted) {
|
|
875
|
+
if (scripted.problems.length > 0) return {
|
|
876
|
+
triggers: [],
|
|
877
|
+
triggersProblem: scripted.problems.map((problem) => problem.message).join("; ")
|
|
878
|
+
};
|
|
879
|
+
const view = (problems) => scripted.triggers.map((definition) => ({
|
|
880
|
+
key: definition.key,
|
|
881
|
+
name: definition.name,
|
|
882
|
+
when: definition.condition,
|
|
883
|
+
effects: definition.effects,
|
|
884
|
+
repeat: definition.repeat,
|
|
885
|
+
priority: definition.priority,
|
|
886
|
+
...definition.cooldownSeconds === void 0 ? {} : { cooldownSeconds: definition.cooldownSeconds },
|
|
887
|
+
...definition.chance === void 0 ? {} : { chance: definition.chance },
|
|
888
|
+
...definition.expires === void 0 ? {} : { expires: definition.expires },
|
|
889
|
+
announced: definition.announce !== void 0,
|
|
890
|
+
problems: problems.get(definition.key) ?? []
|
|
891
|
+
}));
|
|
892
|
+
try {
|
|
893
|
+
return { triggers: view(triggerProblemsOf(parts, scripted.triggers)) };
|
|
894
|
+
} catch (error) {
|
|
895
|
+
return {
|
|
896
|
+
triggers: view(/* @__PURE__ */ new Map()),
|
|
897
|
+
triggersProblem: `what the triggers name could not be checked, because the rest of the world has a problem: ${error instanceof Error ? error.message : String(error)}`
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
/** The characters of a world as they start, and the places they can start in. */
|
|
902
|
+
async function readWorldEditor(world) {
|
|
903
|
+
const [{ characters }, { locations }, { factions }, { lore }, { plots }] = await Promise.all([
|
|
904
|
+
loadCharacters(world.directory),
|
|
905
|
+
loadLocations(world.directory),
|
|
906
|
+
loadFactions(world.directory),
|
|
907
|
+
loadLore(world.directory),
|
|
908
|
+
loadPlots(world.directory)
|
|
909
|
+
]);
|
|
910
|
+
const { items, slots } = await loadItems(world.directory, {
|
|
911
|
+
characters: characters.map((character) => character.id),
|
|
912
|
+
locations
|
|
913
|
+
});
|
|
914
|
+
const scripted = await loadTriggers(world.directory);
|
|
915
|
+
const declared = await loadVariables(world.directory);
|
|
916
|
+
const { calendar } = await loadCalendar(world.directory);
|
|
917
|
+
const { triggers, triggersProblem } = triggersOf({
|
|
918
|
+
characters,
|
|
919
|
+
locations,
|
|
920
|
+
items,
|
|
921
|
+
slots,
|
|
922
|
+
variables: declared.defs,
|
|
923
|
+
calendar
|
|
924
|
+
}, scripted);
|
|
925
|
+
const names = new Map(locations.map((location) => [location.id, location.name]));
|
|
926
|
+
const characterNames = new Map(characters.map((character) => [character.id, character.name]));
|
|
927
|
+
const itemNames = new Map(items.map((item) => [item.id, item.name]));
|
|
928
|
+
const holder = (item) => item.start.kind === "location" ? names.get(item.start.location) ?? item.start.location : item.start.kind === "inside" ? itemNames.get(item.start.item) ?? item.start.item : characterNames.get(item.start.character) ?? item.start.character;
|
|
929
|
+
const entity = (kind, key, name) => ({
|
|
930
|
+
kind,
|
|
931
|
+
key,
|
|
932
|
+
name
|
|
933
|
+
});
|
|
934
|
+
const characterEntity = (key) => entity("character", key, characterNames.get(key) ?? key);
|
|
935
|
+
const factionNames = new Map(factions.map((faction) => [faction.id, faction.name]));
|
|
936
|
+
const relations = [];
|
|
937
|
+
for (const character of characters) {
|
|
938
|
+
for (const relation of character.relationships ?? []) relations.push({
|
|
939
|
+
key: relationKey("character", character.id, relation.to),
|
|
940
|
+
kind: "character",
|
|
941
|
+
from: characterEntity(character.id),
|
|
942
|
+
to: characterEntity(relation.to),
|
|
943
|
+
label: relation.label,
|
|
944
|
+
summary: relation.summary,
|
|
945
|
+
familiarity: relation.familiarity,
|
|
946
|
+
trust: relation.trust,
|
|
947
|
+
affinity: relation.affinity,
|
|
948
|
+
tension: relation.tension
|
|
949
|
+
});
|
|
950
|
+
for (const location of character.knowledge?.locations ?? []) relations.push({
|
|
951
|
+
key: relationKey("knowledge", character.id, "location", location),
|
|
952
|
+
kind: "knowledge",
|
|
953
|
+
from: characterEntity(character.id),
|
|
954
|
+
to: entity("location", location, names.get(location) ?? location),
|
|
955
|
+
observed: false
|
|
956
|
+
});
|
|
957
|
+
for (const item of character.knowledge?.items ?? []) relations.push({
|
|
958
|
+
key: relationKey("knowledge", character.id, "item", item),
|
|
959
|
+
kind: "knowledge",
|
|
960
|
+
from: characterEntity(character.id),
|
|
961
|
+
to: entity("item", item, itemNames.get(item) ?? item),
|
|
962
|
+
observed: false
|
|
963
|
+
});
|
|
964
|
+
for (const exit of character.knowledge?.exits ?? []) relations.push({
|
|
965
|
+
key: relationKey("knowledge", character.id, "exit", exit.from, exit.to),
|
|
966
|
+
kind: "knowledge",
|
|
967
|
+
from: characterEntity(character.id),
|
|
968
|
+
to: entity("exit", `${exit.from}>${exit.to}`, `${names.get(exit.from) ?? exit.from} → ${names.get(exit.to) ?? exit.to}`),
|
|
969
|
+
observed: false
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
for (const location of locations) for (const exit of location.exits) relations.push({
|
|
973
|
+
key: relationKey("exit", location.id, exit.to),
|
|
974
|
+
kind: "exit",
|
|
975
|
+
from: entity("location", location.id, location.name),
|
|
976
|
+
to: entity("location", exit.to, names.get(exit.to) ?? exit.to),
|
|
977
|
+
description: exit.description,
|
|
978
|
+
...exit.travelSeconds === void 0 ? {} : { travelSeconds: exit.travelSeconds },
|
|
979
|
+
state: exit.state,
|
|
980
|
+
note: exit.note,
|
|
981
|
+
oneWay: exit.oneWay
|
|
982
|
+
});
|
|
983
|
+
for (const faction of factions) {
|
|
984
|
+
for (const member of faction.members) relations.push({
|
|
985
|
+
key: relationKey("membership", faction.id, member.character),
|
|
986
|
+
kind: "membership",
|
|
987
|
+
from: characterEntity(member.character),
|
|
988
|
+
to: entity("faction", faction.id, faction.name),
|
|
989
|
+
role: member.role,
|
|
990
|
+
rank: member.rank,
|
|
991
|
+
status: member.status,
|
|
992
|
+
public: member.public,
|
|
993
|
+
commitment: member.commitment
|
|
994
|
+
});
|
|
995
|
+
for (const relation of faction.relationships) {
|
|
996
|
+
const targetName = relation.to.kind === "faction" ? factionNames.get(relation.to.id) ?? relation.to.id : characterNames.get(relation.to.id) ?? relation.to.id;
|
|
997
|
+
relations.push({
|
|
998
|
+
key: relationKey("social", "faction", faction.id, relation.to.kind, relation.to.id),
|
|
999
|
+
kind: "social",
|
|
1000
|
+
from: entity("faction", faction.id, faction.name),
|
|
1001
|
+
to: entity(relation.to.kind, relation.to.id, targetName),
|
|
1002
|
+
label: relation.label,
|
|
1003
|
+
summary: relation.summary ?? "",
|
|
1004
|
+
familiarity: relation.familiarity ?? 0,
|
|
1005
|
+
trust: relation.trust ?? 0,
|
|
1006
|
+
affinity: relation.affinity ?? 0,
|
|
1007
|
+
tension: relation.tension ?? 0
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
const worldDocument = JSON.parse(await readFile(join(world.directory, "world.json"), "utf8"));
|
|
1012
|
+
const narrationVoice = typeof worldDocument["narration_voice"] === "string" ? worldDocument["narration_voice"] : void 0;
|
|
1013
|
+
return {
|
|
1014
|
+
...narrationVoice === void 0 ? {} : { narrationVoice },
|
|
1015
|
+
characters: characters.map((character) => stateOf(world, character, names)),
|
|
1016
|
+
places: locations.map((location) => ({
|
|
1017
|
+
key: location.id,
|
|
1018
|
+
name: location.name,
|
|
1019
|
+
description: location.description,
|
|
1020
|
+
...imageOf(world, "place", location.id, location.visualIdentity?.globalId),
|
|
1021
|
+
...location.parent === void 0 ? {} : { parent: {
|
|
1022
|
+
key: location.parent,
|
|
1023
|
+
name: names.get(location.parent) ?? location.parent
|
|
1024
|
+
} },
|
|
1025
|
+
features: location.features,
|
|
1026
|
+
...location.visualIdentity === void 0 ? {} : { visualIdentity: location.visualIdentity }
|
|
1027
|
+
})),
|
|
1028
|
+
things: items.map((item) => ({
|
|
1029
|
+
key: item.id,
|
|
1030
|
+
name: item.name,
|
|
1031
|
+
description: item.description,
|
|
1032
|
+
...imageOf(world, "thing", item.id, item.visualIdentity?.globalId),
|
|
1033
|
+
quantity: item.quantity,
|
|
1034
|
+
unique: item.unique,
|
|
1035
|
+
quality: item.quality,
|
|
1036
|
+
notable: item.notable,
|
|
1037
|
+
hidden: item.hidden,
|
|
1038
|
+
...item.wearable === void 0 ? {} : { wearable: item.wearable },
|
|
1039
|
+
...item.container === void 0 ? {} : { containerState: item.container.state },
|
|
1040
|
+
...item.owner === void 0 ? {} : { owner: {
|
|
1041
|
+
key: item.owner,
|
|
1042
|
+
name: characterNames.get(item.owner) ?? item.owner
|
|
1043
|
+
} },
|
|
1044
|
+
holder: holder(item),
|
|
1045
|
+
...item.visualIdentity === void 0 ? {} : { visualIdentity: item.visualIdentity }
|
|
1046
|
+
})),
|
|
1047
|
+
factions: factions.map((faction) => ({
|
|
1048
|
+
key: faction.id,
|
|
1049
|
+
name: faction.name,
|
|
1050
|
+
aliases: faction.aliases,
|
|
1051
|
+
summary: faction.summary,
|
|
1052
|
+
description: faction.description,
|
|
1053
|
+
values: faction.values,
|
|
1054
|
+
structure: faction.structure,
|
|
1055
|
+
state: {
|
|
1056
|
+
publicState: faction.start.publicState,
|
|
1057
|
+
innerState: faction.start.innerState
|
|
1058
|
+
},
|
|
1059
|
+
goals: faction.start.goals.map((goal, index) => ({
|
|
1060
|
+
ref: String(index),
|
|
1061
|
+
name: goal.name,
|
|
1062
|
+
description: goal.description,
|
|
1063
|
+
status: goal.status,
|
|
1064
|
+
priority: goal.priority
|
|
1065
|
+
})),
|
|
1066
|
+
members: faction.members.map((member) => ({
|
|
1067
|
+
...member,
|
|
1068
|
+
name: characterNames.get(member.character) ?? member.character
|
|
1069
|
+
})),
|
|
1070
|
+
relationships: faction.relationships.map((relationship) => ({
|
|
1071
|
+
target: `${relationship.to.kind}:${relationship.to.id}`,
|
|
1072
|
+
label: relationship.label,
|
|
1073
|
+
summary: relationship.summary ?? ""
|
|
1074
|
+
}))
|
|
1075
|
+
})),
|
|
1076
|
+
lore: lore.map((entry) => ({
|
|
1077
|
+
key: entry.id,
|
|
1078
|
+
title: entry.title,
|
|
1079
|
+
kind: entry.kind,
|
|
1080
|
+
summary: entry.summary,
|
|
1081
|
+
body: entry.body,
|
|
1082
|
+
...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
|
|
1083
|
+
...entry.endsAt === void 0 ? {} : { endsAt: entry.endsAt },
|
|
1084
|
+
subjects: entry.subjects.map((subject) => ({
|
|
1085
|
+
kind: subject.kind,
|
|
1086
|
+
key: subject.id,
|
|
1087
|
+
name: subject.kind === "character" ? characterNames.get(subject.id) ?? subject.id : subject.kind === "faction" ? factionNames.get(subject.id) ?? subject.id : subject.kind === "location" ? names.get(subject.id) ?? subject.id : subject.kind === "item" ? itemNames.get(subject.id) ?? subject.id : lore.find((candidate) => candidate.id === subject.id)?.title ?? subject.id
|
|
1088
|
+
})),
|
|
1089
|
+
related: entry.related.map((key) => ({
|
|
1090
|
+
key,
|
|
1091
|
+
title: lore.find((candidate) => candidate.id === key)?.title ?? key
|
|
1092
|
+
})),
|
|
1093
|
+
sources: entry.sources
|
|
1094
|
+
})),
|
|
1095
|
+
triggers,
|
|
1096
|
+
...triggersProblem === void 0 ? {} : { triggersProblem },
|
|
1097
|
+
plots: plots.map((definition) => ({ definition })),
|
|
1098
|
+
relations
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
async function editWorldPlots(world, edit) {
|
|
1102
|
+
const parsed = parsePlotsFile(JSON.stringify(edit.plots));
|
|
1103
|
+
if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
|
|
1104
|
+
const state = await readWorldEditor(world);
|
|
1105
|
+
const references = plotReferenceProblems(parsed.value, [
|
|
1106
|
+
...state.characters.map((entry) => entry.key),
|
|
1107
|
+
...state.factions.map((entry) => entry.key),
|
|
1108
|
+
...state.places.map((entry) => entry.key),
|
|
1109
|
+
...state.things.map((entry) => entry.key),
|
|
1110
|
+
...(state.lore ?? []).map((entry) => entry.key)
|
|
1111
|
+
]);
|
|
1112
|
+
if (references.length > 0) throw new InvalidEditProblems(references);
|
|
1113
|
+
const document = parsed.value.map((plot) => ({
|
|
1114
|
+
...plot,
|
|
1115
|
+
pacing: {
|
|
1116
|
+
quiet_turns: plot.pacing.quietTurns,
|
|
1117
|
+
cooldown_turns: plot.pacing.cooldownTurns,
|
|
1118
|
+
cooldown_days: plot.pacing.cooldownDays
|
|
1119
|
+
}
|
|
1120
|
+
}));
|
|
1121
|
+
await replaceFile$1(join(world.directory, PLOTS_FILE_NAME), JSON.stringify(document, null, 2) + "\n");
|
|
1122
|
+
return await readWorldEditor(world);
|
|
1123
|
+
}
|
|
1124
|
+
async function editWorldLore(world, key, edit) {
|
|
1125
|
+
return await editEntityFile(world, LORE_DIR, LORE_FILE_NAME, key, parseLoreFile, (document) => {
|
|
1126
|
+
if (edit.title !== void 0) document["title"] = edit.title;
|
|
1127
|
+
if (edit.kind !== void 0) document["kind"] = edit.kind;
|
|
1128
|
+
if (edit.summary !== void 0) setOptional(document, "summary", edit.summary);
|
|
1129
|
+
if (edit.body !== void 0) setOptional(document, "body", edit.body);
|
|
1130
|
+
if (edit.sources !== void 0) document["sources"] = edit.sources;
|
|
1131
|
+
if (edit.startsAt !== void 0) {
|
|
1132
|
+
if (edit.startsAt === null) delete document["starts_at"];
|
|
1133
|
+
else document["starts_at"] = new Date(edit.startsAt).toISOString();
|
|
1134
|
+
}
|
|
1135
|
+
if (edit.endsAt !== void 0) {
|
|
1136
|
+
if (edit.endsAt === null) delete document["ends_at"];
|
|
1137
|
+
else document["ends_at"] = new Date(edit.endsAt).toISOString();
|
|
1138
|
+
}
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1141
|
+
async function editWorldNarrationVoice(world, voice) {
|
|
1142
|
+
const file = join(world.directory, "world.json");
|
|
1143
|
+
const text = await readFile(file, "utf8");
|
|
1144
|
+
const document = JSON.parse(text);
|
|
1145
|
+
if (voice.trim() === "") delete document["narration_voice"];
|
|
1146
|
+
else document["narration_voice"] = voice.trim();
|
|
1147
|
+
await replaceFile$1(file, JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : ""));
|
|
1148
|
+
return await readWorldEditor(world);
|
|
1149
|
+
}
|
|
1150
|
+
const relationKey = (...parts) => parts.map((part) => encodeURIComponent(part)).join(":");
|
|
1151
|
+
const relationParts = (key) => key.split(":").map((part) => decodeURIComponent(part));
|
|
1152
|
+
/** The folder of a character by its id: the id is the folder's name unless the file says another. */
|
|
1153
|
+
async function folderOf$1(worldDirectory, key) {
|
|
1154
|
+
const root = join(worldDirectory, CHARACTERS_DIR);
|
|
1155
|
+
for (const folder of await subfolders(root)) try {
|
|
1156
|
+
const parsed = parseCharacterFile(await readFile(join(root, folder, CHARACTER_FILE_NAME), "utf8"), folder);
|
|
1157
|
+
if (parsed.ok && parsed.value.id === key) return folder;
|
|
1158
|
+
} catch (error) {
|
|
1159
|
+
if (error.code !== "ENOENT") throw error;
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
const object = (parent, key) => {
|
|
1163
|
+
const found = parent[key];
|
|
1164
|
+
if (typeof found === "object" && found !== null && !Array.isArray(found)) return found;
|
|
1165
|
+
const made = {};
|
|
1166
|
+
parent[key] = made;
|
|
1167
|
+
return made;
|
|
1168
|
+
};
|
|
1169
|
+
/** A blank optional text is taken out of the file instead of being written empty. */
|
|
1170
|
+
function setOptional(target, key, value) {
|
|
1171
|
+
if (value === void 0) return;
|
|
1172
|
+
if (value.trim() === "") delete target[key];
|
|
1173
|
+
else target[key] = value.trim();
|
|
1174
|
+
}
|
|
1175
|
+
/** Puts the edit into the document of a character file; the fields it does not name, and every field the editor does not know, stay as they are. */
|
|
1176
|
+
function apply(document, edit, problems) {
|
|
1177
|
+
if (edit.name !== void 0) document["name"] = edit.name;
|
|
1178
|
+
if (edit.aliases !== void 0) document["aliases"] = edit.aliases.map((alias) => alias.trim()).filter((alias) => alias !== "");
|
|
1179
|
+
for (const key of [
|
|
1180
|
+
"age",
|
|
1181
|
+
"gender",
|
|
1182
|
+
"pronouns"
|
|
1183
|
+
]) setOptional(document, key, edit[key]);
|
|
1184
|
+
for (const key of [
|
|
1185
|
+
"role",
|
|
1186
|
+
"tier",
|
|
1187
|
+
"kind",
|
|
1188
|
+
"summary",
|
|
1189
|
+
"personality",
|
|
1190
|
+
"background",
|
|
1191
|
+
"appearance"
|
|
1192
|
+
]) if (edit[key] !== void 0) document[key] = edit[key];
|
|
1193
|
+
if (edit.visualIdentity === null) delete document["visual_identity"];
|
|
1194
|
+
else if (edit.visualIdentity !== void 0) document["visual_identity"] = {
|
|
1195
|
+
description: edit.visualIdentity.description,
|
|
1196
|
+
tags: edit.visualIdentity.tags,
|
|
1197
|
+
negative_tags: edit.visualIdentity.negativeTags,
|
|
1198
|
+
...edit.visualIdentity.globalId === void 0 ? {} : { global_id: edit.visualIdentity.globalId }
|
|
1199
|
+
};
|
|
1200
|
+
if (edit.speech !== void 0) {
|
|
1201
|
+
const speech = object(document, "speech");
|
|
1202
|
+
if (edit.speech.style !== void 0) speech["style"] = edit.speech.style;
|
|
1203
|
+
if (edit.speech.examples !== void 0) speech["examples"] = edit.speech.examples.map((example) => example.trim()).filter((example) => example !== "");
|
|
1204
|
+
}
|
|
1205
|
+
setOptional(document, "voice", edit.voice);
|
|
1206
|
+
const start = object(document, "start");
|
|
1207
|
+
if (edit.state !== void 0) {
|
|
1208
|
+
if (edit.state.publicState !== void 0) start["public_state"] = edit.state.publicState;
|
|
1209
|
+
if (edit.state.innerState !== void 0) start["inner_state"] = edit.state.innerState;
|
|
1210
|
+
if (edit.state.activity !== void 0) start["activity"] = edit.state.activity;
|
|
1211
|
+
}
|
|
1212
|
+
if (edit.place !== void 0) {
|
|
1213
|
+
if (start["location"] !== edit.place.location) delete start["feature"];
|
|
1214
|
+
start["location"] = edit.place.location;
|
|
1215
|
+
setOptional(start, "position", edit.place.position ?? "");
|
|
1216
|
+
}
|
|
1217
|
+
if (edit.goals !== void 0) {
|
|
1218
|
+
const intents = Array.isArray(start["intents"]) ? start["intents"] : [];
|
|
1219
|
+
for (const goal of edit.goals) {
|
|
1220
|
+
const intent = intents[Number(goal.ref)];
|
|
1221
|
+
if (intent === void 0 || typeof intent !== "object" || intent === null) {
|
|
1222
|
+
problems.push(`there is no goal "${goal.ref}"`);
|
|
1223
|
+
continue;
|
|
1224
|
+
}
|
|
1225
|
+
if (goal.name !== void 0) intent["name"] = goal.name;
|
|
1226
|
+
if (goal.description !== void 0) intent["description"] = goal.description;
|
|
1227
|
+
if (goal.status !== void 0) intent["status"] = goal.status;
|
|
1228
|
+
if (goal.priority !== void 0) intent["priority"] = goal.priority;
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
/** Written in one step, so an interruption cannot leave a character file half written. */
|
|
1233
|
+
async function replaceFile$1(file, text) {
|
|
1234
|
+
const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
|
|
1235
|
+
try {
|
|
1236
|
+
const mode = await stat(file).then((value) => value.mode, (error) => {
|
|
1237
|
+
if (error.code === "ENOENT") return 420;
|
|
1238
|
+
throw error;
|
|
1239
|
+
});
|
|
1240
|
+
await writeFile(temporary, text, { mode });
|
|
1241
|
+
await chmod(temporary, mode);
|
|
1242
|
+
await rename(temporary, file);
|
|
1243
|
+
} catch (error) {
|
|
1244
|
+
await rm(temporary, { force: true });
|
|
1245
|
+
throw error;
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* Change a character in a world's files: the file is read, changed and checked as a whole (it has to read as a valid character, and the place has to be a place of
|
|
1250
|
+
* the world) before it is written, so a refused edit changes nothing. Whatever the file holds that the editor does not know stays.
|
|
1251
|
+
* @throws {InvalidEditProblems} when the character is not there, or the result would not be a valid character.
|
|
1252
|
+
*/
|
|
1253
|
+
async function editWorldCharacter(world, key, edit) {
|
|
1254
|
+
const folder = await folderOf$1(world.directory, key);
|
|
1255
|
+
if (folder === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
|
|
1256
|
+
const file = join(world.directory, CHARACTERS_DIR, folder, CHARACTER_FILE_NAME);
|
|
1257
|
+
const text = (await readFile(file, "utf8")).replace(/^/, "");
|
|
1258
|
+
const document = JSON.parse(text);
|
|
1259
|
+
const problems = [];
|
|
1260
|
+
if (edit.place !== void 0) {
|
|
1261
|
+
const { locations } = await loadLocations(world.directory);
|
|
1262
|
+
if (!locations.some((location) => location.id === edit.place?.location)) problems.push(`there is no place "${edit.place.location}"`);
|
|
1263
|
+
}
|
|
1264
|
+
apply(document, edit, problems);
|
|
1265
|
+
const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
|
|
1266
|
+
const parsed = parseCharacterFile(next, folder);
|
|
1267
|
+
if (!parsed.ok) problems.push(...parsed.issues.map(formatIssue));
|
|
1268
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
1269
|
+
await replaceFile$1(file, next);
|
|
1270
|
+
return await readWorldEditor(world);
|
|
1271
|
+
}
|
|
1272
|
+
async function entityFolder(worldDirectory, directory, fileName, key, parse) {
|
|
1273
|
+
for (const folder of await subfolders(join(worldDirectory, directory))) try {
|
|
1274
|
+
const parsed = parse(await readFile(join(worldDirectory, directory, folder, fileName), "utf8"), folder);
|
|
1275
|
+
if (parsed.ok && parsed.value?.id === key) return folder;
|
|
1276
|
+
} catch (error) {
|
|
1277
|
+
if (error.code !== "ENOENT") throw error;
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
function setVisualIdentity(document, identity) {
|
|
1281
|
+
if (identity === null) delete document["visual_identity"];
|
|
1282
|
+
else if (identity !== void 0) document["visual_identity"] = {
|
|
1283
|
+
description: identity.description,
|
|
1284
|
+
tags: identity.tags,
|
|
1285
|
+
negative_tags: identity.negativeTags,
|
|
1286
|
+
...identity.globalId === void 0 ? {} : { global_id: identity.globalId }
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
1289
|
+
async function editEntityFile(world, directory, fileName, key, parse, mutate) {
|
|
1290
|
+
const folder = await entityFolder(world.directory, directory, fileName, key, parse);
|
|
1291
|
+
if (folder === void 0) throw new InvalidEditProblems([`there is no entity "${key}"`]);
|
|
1292
|
+
const file = join(world.directory, directory, folder, fileName);
|
|
1293
|
+
const text = (await readFile(file, "utf8")).replace(/^/, "");
|
|
1294
|
+
const document = JSON.parse(text);
|
|
1295
|
+
mutate(document);
|
|
1296
|
+
const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
|
|
1297
|
+
const parsed = parse(next, folder);
|
|
1298
|
+
if (!parsed.ok) throw new InvalidEditProblems((parsed.issues ?? []).map(formatIssue));
|
|
1299
|
+
await replaceFile$1(file, next);
|
|
1300
|
+
return await readWorldEditor(world);
|
|
1301
|
+
}
|
|
1302
|
+
async function editWorldPlace(world, key, edit) {
|
|
1303
|
+
if (edit.parent !== void 0 && edit.parent !== null) {
|
|
1304
|
+
const places = (await readWorldEditor(world)).places;
|
|
1305
|
+
if (!places.some((place) => place.key === edit.parent)) throw new InvalidEditProblems([`there is no place "${edit.parent}" to put it in`]);
|
|
1306
|
+
const parents = new Map(places.map((place) => [place.key, place.parent?.key]));
|
|
1307
|
+
for (let at = edit.parent; at !== void 0; at = parents.get(at)) if (at === key) throw new InvalidEditProblems(["a place cannot be inside itself or a place within it"]);
|
|
1308
|
+
}
|
|
1309
|
+
return await editEntityFile(world, LOCATIONS_DIR, LOCATION_FILE_NAME, key, parseLocationFile, (document) => {
|
|
1310
|
+
if (edit.name !== void 0) document["name"] = edit.name;
|
|
1311
|
+
if (edit.description !== void 0) document["description"] = edit.description;
|
|
1312
|
+
if (edit.features !== void 0) document["features"] = edit.features.map((feature) => ({
|
|
1313
|
+
id: feature.key,
|
|
1314
|
+
name: feature.name,
|
|
1315
|
+
description: feature.description
|
|
1316
|
+
}));
|
|
1317
|
+
if (edit.parent === null) delete document["parent"];
|
|
1318
|
+
else if (edit.parent !== void 0) document["parent"] = edit.parent;
|
|
1319
|
+
setVisualIdentity(document, edit.visualIdentity);
|
|
1320
|
+
});
|
|
1321
|
+
}
|
|
1322
|
+
async function editWorldThing(world, key, edit) {
|
|
1323
|
+
if (edit.owner !== void 0 && edit.owner !== null && !(await readWorldEditor(world)).characters.some((character) => character.key === edit.owner)) throw new InvalidEditProblems([`there is no character "${edit.owner}" to own it`]);
|
|
1324
|
+
return await editEntityFile(world, ITEMS_DIR, ITEM_FILE_NAME, key, parseItemFile, (document) => {
|
|
1325
|
+
for (const field of [
|
|
1326
|
+
"name",
|
|
1327
|
+
"description",
|
|
1328
|
+
"quantity",
|
|
1329
|
+
"quality",
|
|
1330
|
+
"notable",
|
|
1331
|
+
"hidden"
|
|
1332
|
+
]) if (edit[field] !== void 0) document[field] = edit[field];
|
|
1333
|
+
if (edit.containerState !== void 0) object(document, "container")["state"] = edit.containerState;
|
|
1334
|
+
if (edit.owner === null) delete document["owner"];
|
|
1335
|
+
else if (edit.owner !== void 0) document["owner"] = edit.owner;
|
|
1336
|
+
setVisualIdentity(document, edit.visualIdentity);
|
|
1337
|
+
});
|
|
1338
|
+
}
|
|
1339
|
+
async function editWorldFaction(world, key, edit) {
|
|
1340
|
+
return await editEntityFile(world, FACTIONS_DIR, FACTION_FILE_NAME, key, parseFactionFile, (document) => {
|
|
1341
|
+
for (const field of [
|
|
1342
|
+
"name",
|
|
1343
|
+
"aliases",
|
|
1344
|
+
"summary",
|
|
1345
|
+
"description",
|
|
1346
|
+
"values",
|
|
1347
|
+
"structure"
|
|
1348
|
+
]) if (edit[field] !== void 0) document[field] = edit[field];
|
|
1349
|
+
const start = object(document, "start");
|
|
1350
|
+
if (edit.state?.publicState !== void 0) start["public_state"] = edit.state.publicState;
|
|
1351
|
+
if (edit.state?.innerState !== void 0) start["inner_state"] = edit.state.innerState;
|
|
1352
|
+
if (edit.goals !== void 0) {
|
|
1353
|
+
const goals = Array.isArray(start["goals"]) ? start["goals"] : [];
|
|
1354
|
+
for (const goal of edit.goals) {
|
|
1355
|
+
const target = goals[Number(goal.ref)];
|
|
1356
|
+
if (target === void 0) continue;
|
|
1357
|
+
for (const field of [
|
|
1358
|
+
"name",
|
|
1359
|
+
"description",
|
|
1360
|
+
"status",
|
|
1361
|
+
"priority"
|
|
1362
|
+
]) if (goal[field] !== void 0) target[field] = goal[field];
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
});
|
|
1366
|
+
}
|
|
1367
|
+
async function createWorldRelation(world, edit) {
|
|
1368
|
+
if (edit.kind === "character" || edit.kind === "knowledge") return await editEntityFile(world, CHARACTERS_DIR, CHARACTER_FILE_NAME, edit.from, parseCharacterFile, (document) => {
|
|
1369
|
+
if (edit.kind === "character") {
|
|
1370
|
+
const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
|
|
1371
|
+
if (relationships.some((entry) => entry?.["to"] === edit.to)) throw new InvalidEditProblems(["that relationship already exists"]);
|
|
1372
|
+
relationships.push({
|
|
1373
|
+
to: edit.to,
|
|
1374
|
+
label: edit.label,
|
|
1375
|
+
summary: edit.summary ?? "",
|
|
1376
|
+
familiarity: edit.familiarity ?? 0,
|
|
1377
|
+
trust: edit.trust ?? 0,
|
|
1378
|
+
affinity: edit.affinity ?? 0,
|
|
1379
|
+
tension: edit.tension ?? 0
|
|
1380
|
+
});
|
|
1381
|
+
document["relationships"] = relationships;
|
|
1382
|
+
} else {
|
|
1383
|
+
const knowledge = object(document, "knowledge");
|
|
1384
|
+
const field = edit.toKind === "location" ? "locations" : edit.toKind === "item" ? "items" : "exits";
|
|
1385
|
+
const entries = Array.isArray(knowledge[field]) ? knowledge[field] : [];
|
|
1386
|
+
if (edit.toKind === "exit") {
|
|
1387
|
+
const [from, to] = edit.to.split(">");
|
|
1388
|
+
if (from === void 0 || to === void 0) throw new InvalidEditProblems(["the route key is invalid"]);
|
|
1389
|
+
if (entries.some((entry) => typeof entry === "object" && entry !== null && entry["from"] === from && entry["to"] === to)) throw new InvalidEditProblems(["that knowledge relation already exists"]);
|
|
1390
|
+
entries.push({
|
|
1391
|
+
from,
|
|
1392
|
+
to
|
|
1393
|
+
});
|
|
1394
|
+
} else {
|
|
1395
|
+
if (entries.includes(edit.to)) throw new InvalidEditProblems(["that knowledge relation already exists"]);
|
|
1396
|
+
entries.push(edit.to);
|
|
1397
|
+
}
|
|
1398
|
+
knowledge[field] = entries;
|
|
1399
|
+
}
|
|
1400
|
+
});
|
|
1401
|
+
if (edit.kind === "exit") return await editEntityFile(world, LOCATIONS_DIR, LOCATION_FILE_NAME, edit.from, parseLocationFile, (document) => {
|
|
1402
|
+
const exits = Array.isArray(document["exits"]) ? document["exits"] : [];
|
|
1403
|
+
if (exits.some((entry) => entry?.["to"] === edit.to)) throw new InvalidEditProblems(["that route already exists"]);
|
|
1404
|
+
exits.push({
|
|
1405
|
+
to: edit.to,
|
|
1406
|
+
description: edit.description,
|
|
1407
|
+
...edit.travelSeconds === void 0 ? {} : { travel_time_seconds: edit.travelSeconds },
|
|
1408
|
+
state: edit.state ?? "open",
|
|
1409
|
+
note: edit.note ?? ""
|
|
1410
|
+
});
|
|
1411
|
+
document["exits"] = exits;
|
|
1412
|
+
});
|
|
1413
|
+
const faction = edit.kind === "membership" ? edit.to : edit.from;
|
|
1414
|
+
if (edit.kind === "social" && edit.fromKind !== "faction") throw new InvalidEditProblems(["authored social relationships must start from a faction"]);
|
|
1415
|
+
return await editEntityFile(world, FACTIONS_DIR, FACTION_FILE_NAME, faction, parseFactionFile, (document) => {
|
|
1416
|
+
if (edit.kind === "membership") {
|
|
1417
|
+
const members = Array.isArray(document["members"]) ? document["members"] : [];
|
|
1418
|
+
if (members.some((entry) => entry?.["character"] === edit.from)) throw new InvalidEditProblems(["that membership already exists"]);
|
|
1419
|
+
members.push({
|
|
1420
|
+
character: edit.from,
|
|
1421
|
+
role: edit.role,
|
|
1422
|
+
rank: edit.rank ?? "",
|
|
1423
|
+
status: edit.status ?? "active",
|
|
1424
|
+
public: edit.public ?? true,
|
|
1425
|
+
commitment: edit.commitment ?? .5
|
|
1426
|
+
});
|
|
1427
|
+
document["members"] = members;
|
|
1428
|
+
} else {
|
|
1429
|
+
const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
|
|
1430
|
+
if (relationships.some((entry) => typeof entry?.["to"] === "object" && entry["to"] !== null && entry["to"]["kind"] === edit.toKind && entry["to"]["id"] === edit.to)) throw new InvalidEditProblems(["that relationship already exists"]);
|
|
1431
|
+
relationships.push({
|
|
1432
|
+
to: {
|
|
1433
|
+
kind: edit.toKind,
|
|
1434
|
+
id: edit.to
|
|
1435
|
+
},
|
|
1436
|
+
label: edit.label,
|
|
1437
|
+
summary: edit.summary ?? "",
|
|
1438
|
+
familiarity: edit.familiarity ?? 0,
|
|
1439
|
+
trust: edit.trust ?? 0,
|
|
1440
|
+
affinity: edit.affinity ?? 0,
|
|
1441
|
+
tension: edit.tension ?? 0
|
|
1442
|
+
});
|
|
1443
|
+
document["relationships"] = relationships;
|
|
1444
|
+
}
|
|
1445
|
+
});
|
|
1446
|
+
}
|
|
1447
|
+
const isNewRelation = (edit) => "create" in edit && edit.create === true;
|
|
1448
|
+
async function editWorldRelation(world, edit) {
|
|
1449
|
+
if (isNewRelation(edit)) return await createWorldRelation(world, edit);
|
|
1450
|
+
const parts = relationParts(edit.key);
|
|
1451
|
+
if (parts[0] !== edit.kind) throw new InvalidEditProblems([`the relation key "${edit.key}" is not a ${edit.kind} key: copy it exactly from list_relationships ("${edit.kind}:..."), or to make a new one send create: true with from and to and no key`]);
|
|
1452
|
+
if (edit.kind === "character" || edit.kind === "knowledge") {
|
|
1453
|
+
const character = parts[1];
|
|
1454
|
+
if (character === void 0) throw new InvalidEditProblems(["the relation key is invalid"]);
|
|
1455
|
+
if (await folderOf$1(world.directory, character) === void 0) throw new InvalidEditProblems([`there is no character "${character}"`]);
|
|
1456
|
+
return await editEntityFile(world, CHARACTERS_DIR, CHARACTER_FILE_NAME, character, parseCharacterFile, (document) => {
|
|
1457
|
+
if (edit.kind === "character") {
|
|
1458
|
+
const target = parts[2];
|
|
1459
|
+
const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
|
|
1460
|
+
const index = relationships.findIndex((entry) => entry?.["to"] === target);
|
|
1461
|
+
if (index < 0) throw new InvalidEditProblems(["the relationship no longer exists"]);
|
|
1462
|
+
if (edit.remove === true) relationships.splice(index, 1);
|
|
1463
|
+
else for (const field of [
|
|
1464
|
+
"label",
|
|
1465
|
+
"summary",
|
|
1466
|
+
"familiarity",
|
|
1467
|
+
"trust",
|
|
1468
|
+
"affinity",
|
|
1469
|
+
"tension"
|
|
1470
|
+
]) if (edit[field] !== void 0) relationships[index][field] = edit[field];
|
|
1471
|
+
document["relationships"] = relationships;
|
|
1472
|
+
} else {
|
|
1473
|
+
const subjectKind = parts[2];
|
|
1474
|
+
const one = parts[3];
|
|
1475
|
+
const two = parts[4];
|
|
1476
|
+
const knowledge = object(document, "knowledge");
|
|
1477
|
+
const field = subjectKind === "location" ? "locations" : subjectKind === "item" ? "items" : "exits";
|
|
1478
|
+
const entries = Array.isArray(knowledge[field]) ? knowledge[field] : [];
|
|
1479
|
+
const index = subjectKind === "exit" ? entries.findIndex((entry) => typeof entry === "object" && entry !== null && entry["from"] === one && entry["to"] === two) : entries.indexOf(one);
|
|
1480
|
+
if (index < 0) throw new InvalidEditProblems(["the knowledge relation no longer exists"]);
|
|
1481
|
+
entries.splice(index, 1);
|
|
1482
|
+
knowledge[field] = entries;
|
|
1483
|
+
}
|
|
1484
|
+
});
|
|
1485
|
+
}
|
|
1486
|
+
if (edit.kind === "exit") {
|
|
1487
|
+
const from = parts[1];
|
|
1488
|
+
const to = parts[2];
|
|
1489
|
+
if (from === void 0 || to === void 0) throw new InvalidEditProblems(["the exit key is invalid"]);
|
|
1490
|
+
return await editEntityFile(world, LOCATIONS_DIR, LOCATION_FILE_NAME, from, parseLocationFile, (document) => {
|
|
1491
|
+
const exits = Array.isArray(document["exits"]) ? document["exits"] : [];
|
|
1492
|
+
const index = exits.findIndex((entry) => entry?.["to"] === to);
|
|
1493
|
+
if (index < 0) throw new InvalidEditProblems(["the exit no longer exists"]);
|
|
1494
|
+
if (edit.remove === true) exits.splice(index, 1);
|
|
1495
|
+
else {
|
|
1496
|
+
for (const field of [
|
|
1497
|
+
"description",
|
|
1498
|
+
"state",
|
|
1499
|
+
"note"
|
|
1500
|
+
]) if (edit[field] !== void 0) exits[index][field] = edit[field];
|
|
1501
|
+
if (edit.travelSeconds === null) delete exits[index]["travel_time_seconds"];
|
|
1502
|
+
else if (edit.travelSeconds !== void 0) exits[index]["travel_time_seconds"] = edit.travelSeconds;
|
|
1503
|
+
}
|
|
1504
|
+
document["exits"] = exits;
|
|
1505
|
+
});
|
|
1506
|
+
}
|
|
1507
|
+
const faction = edit.kind === "membership" ? parts[1] : parts[2];
|
|
1508
|
+
if (faction === void 0) throw new InvalidEditProblems(["the relation key is invalid"]);
|
|
1509
|
+
return await editEntityFile(world, FACTIONS_DIR, FACTION_FILE_NAME, faction, parseFactionFile, (document) => {
|
|
1510
|
+
if (edit.kind === "membership") {
|
|
1511
|
+
const character = parts[2];
|
|
1512
|
+
const members = Array.isArray(document["members"]) ? document["members"] : [];
|
|
1513
|
+
const index = members.findIndex((entry) => entry?.["character"] === character);
|
|
1514
|
+
if (index < 0) throw new InvalidEditProblems(["the membership no longer exists"]);
|
|
1515
|
+
if (edit.remove === true) members.splice(index, 1);
|
|
1516
|
+
else for (const field of [
|
|
1517
|
+
"role",
|
|
1518
|
+
"rank",
|
|
1519
|
+
"status",
|
|
1520
|
+
"public",
|
|
1521
|
+
"commitment"
|
|
1522
|
+
]) if (edit[field] !== void 0) members[index][field] = edit[field];
|
|
1523
|
+
document["members"] = members;
|
|
1524
|
+
} else {
|
|
1525
|
+
const targetKind = parts[3];
|
|
1526
|
+
const target = parts[4];
|
|
1527
|
+
const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
|
|
1528
|
+
const index = relationships.findIndex((entry) => typeof entry?.["to"] === "object" && entry["to"] !== null && entry["to"]["kind"] === targetKind && entry["to"]["id"] === target);
|
|
1529
|
+
if (index < 0) throw new InvalidEditProblems(["the relationship no longer exists"]);
|
|
1530
|
+
if (edit.remove === true) relationships.splice(index, 1);
|
|
1531
|
+
else for (const field of [
|
|
1532
|
+
"label",
|
|
1533
|
+
"summary",
|
|
1534
|
+
"familiarity",
|
|
1535
|
+
"trust",
|
|
1536
|
+
"affinity",
|
|
1537
|
+
"tension"
|
|
1538
|
+
]) if (edit[field] !== void 0) relationships[index][field] = edit[field];
|
|
1539
|
+
document["relationships"] = relationships;
|
|
1540
|
+
}
|
|
1541
|
+
});
|
|
1542
|
+
}
|
|
1543
|
+
async function characterOf(world, key) {
|
|
1544
|
+
const { characters } = await loadCharacters(world.directory);
|
|
1545
|
+
const character = characters.find((candidate) => candidate.id === key);
|
|
1546
|
+
if (character === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
|
|
1547
|
+
return character;
|
|
1548
|
+
}
|
|
1549
|
+
/** What kinds of things besides characters have a reference picture, and what the images call them. */
|
|
1550
|
+
const IMAGE_SUBJECT = {
|
|
1551
|
+
place: "location",
|
|
1552
|
+
thing: "item"
|
|
1553
|
+
};
|
|
1554
|
+
function imageOf(world, kind, id, globalId) {
|
|
1555
|
+
const file = referenceImagePath(world.directory, {
|
|
1556
|
+
kind: IMAGE_SUBJECT[kind],
|
|
1557
|
+
localId: id,
|
|
1558
|
+
...globalId === void 0 ? {} : { globalId }
|
|
1559
|
+
});
|
|
1560
|
+
return existsSync(file) ? { image: `/${API_PREFIX}/worlds/state/${kind}/image/file?id=${encodeURIComponent(world.id)}&key=${encodeURIComponent(id)}&v=${statSync(file).mtimeMs}` } : {};
|
|
1561
|
+
}
|
|
1562
|
+
async function imageSubjectOf(world, kind, key) {
|
|
1563
|
+
if (kind === "place") {
|
|
1564
|
+
const { locations } = await loadLocations(world.directory);
|
|
1565
|
+
const found = locations.find((candidate) => candidate.id === key);
|
|
1566
|
+
if (found === void 0) throw new InvalidEditProblems([`there is no place "${key}"`]);
|
|
1567
|
+
return {
|
|
1568
|
+
id: found.id,
|
|
1569
|
+
name: found.name,
|
|
1570
|
+
...found.visualIdentity === void 0 ? {} : { identity: found.visualIdentity }
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
const { characters } = await loadCharacters(world.directory);
|
|
1574
|
+
const { locations } = await loadLocations(world.directory);
|
|
1575
|
+
const { items } = await loadItems(world.directory, {
|
|
1576
|
+
characters: characters.map((character) => character.id),
|
|
1577
|
+
locations
|
|
1578
|
+
});
|
|
1579
|
+
const found = items.find((candidate) => candidate.id === key);
|
|
1580
|
+
if (found === void 0) throw new InvalidEditProblems([`there is no thing "${key}"`]);
|
|
1581
|
+
return {
|
|
1582
|
+
id: found.id,
|
|
1583
|
+
name: found.name,
|
|
1584
|
+
...found.visualIdentity === void 0 ? {} : { identity: found.visualIdentity }
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
/** Generate or replace the reference picture of an authored place or thing from its visual identity. */
|
|
1588
|
+
async function generateWorldEntityImage(world, kind, key, service) {
|
|
1589
|
+
const subject = await imageSubjectOf(world, kind, key);
|
|
1590
|
+
if (subject.identity === void 0) throw new InvalidEditProblems([`${subject.name} needs a visual identity before a picture can be generated`]);
|
|
1591
|
+
await generateReferenceImage(service, {
|
|
1592
|
+
root: world.directory,
|
|
1593
|
+
subject: {
|
|
1594
|
+
kind: IMAGE_SUBJECT[kind],
|
|
1595
|
+
localId: subject.id,
|
|
1596
|
+
name: subject.name,
|
|
1597
|
+
...subject.identity.globalId === void 0 ? {} : { globalId: subject.identity.globalId }
|
|
1598
|
+
},
|
|
1599
|
+
identity: {
|
|
1600
|
+
...subject.identity,
|
|
1601
|
+
subjectKind: IMAGE_SUBJECT[kind],
|
|
1602
|
+
subjectId: 0,
|
|
1603
|
+
version: 1,
|
|
1604
|
+
updatedAt: ""
|
|
1605
|
+
}
|
|
1606
|
+
});
|
|
1607
|
+
return await readWorldEditor(world);
|
|
1608
|
+
}
|
|
1609
|
+
/** The picture the author brought becomes the place's or thing's reference picture. */
|
|
1610
|
+
async function uploadWorldEntityImage(world, kind, key, png, originalName) {
|
|
1611
|
+
const subject = await imageSubjectOf(world, kind, key);
|
|
1612
|
+
try {
|
|
1613
|
+
await uploadReferenceImage({
|
|
1614
|
+
root: world.directory,
|
|
1615
|
+
subject: {
|
|
1616
|
+
kind: IMAGE_SUBJECT[kind],
|
|
1617
|
+
localId: subject.id,
|
|
1618
|
+
name: subject.name,
|
|
1619
|
+
...subject.identity?.globalId === void 0 ? {} : { globalId: subject.identity.globalId }
|
|
1620
|
+
},
|
|
1621
|
+
png,
|
|
1622
|
+
...originalName === void 0 ? {} : { originalName }
|
|
1623
|
+
});
|
|
1624
|
+
} catch (error) {
|
|
1625
|
+
throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
|
|
1626
|
+
}
|
|
1627
|
+
return await readWorldEditor(world);
|
|
1628
|
+
}
|
|
1629
|
+
/** Resolve the picture through authored data so request parameters cannot select arbitrary files. */
|
|
1630
|
+
async function worldEntityImageFile(world, kind, key) {
|
|
1631
|
+
const subject = await imageSubjectOf(world, kind, key);
|
|
1632
|
+
const file = referenceImagePath(world.directory, {
|
|
1633
|
+
kind: IMAGE_SUBJECT[kind],
|
|
1634
|
+
localId: subject.id,
|
|
1635
|
+
...subject.identity?.globalId === void 0 ? {} : { globalId: subject.identity.globalId }
|
|
1636
|
+
});
|
|
1637
|
+
return {
|
|
1638
|
+
file,
|
|
1639
|
+
size: (await stat(file)).size
|
|
1640
|
+
};
|
|
1641
|
+
}
|
|
1642
|
+
/** Generate or replace the authored character's stable reference portrait. */
|
|
1643
|
+
async function generateWorldCharacterPortrait(world, key, service) {
|
|
1644
|
+
const character = await characterOf(world, key);
|
|
1645
|
+
const identity = character.visualIdentity;
|
|
1646
|
+
if (identity === void 0) throw new InvalidEditProblems([`${character.name} needs a visual identity before a portrait can be generated`]);
|
|
1647
|
+
await generateReferenceImage(service, {
|
|
1648
|
+
root: world.directory,
|
|
1649
|
+
subject: {
|
|
1650
|
+
kind: "character",
|
|
1651
|
+
localId: character.id,
|
|
1652
|
+
name: character.name,
|
|
1653
|
+
...identity.globalId === void 0 ? {} : { globalId: identity.globalId }
|
|
1654
|
+
},
|
|
1655
|
+
identity: {
|
|
1656
|
+
...identity,
|
|
1657
|
+
subjectKind: "character",
|
|
1658
|
+
subjectId: 0,
|
|
1659
|
+
version: 1,
|
|
1660
|
+
updatedAt: ""
|
|
1661
|
+
}
|
|
1662
|
+
});
|
|
1663
|
+
return await readWorldEditor(world);
|
|
1664
|
+
}
|
|
1665
|
+
/** The picture the author brought becomes the character's portrait. */
|
|
1666
|
+
async function uploadWorldCharacterPortrait(world, key, png, originalName) {
|
|
1667
|
+
const character = await characterOf(world, key);
|
|
1668
|
+
try {
|
|
1669
|
+
await uploadReferenceImage({
|
|
1670
|
+
root: world.directory,
|
|
1671
|
+
subject: {
|
|
1672
|
+
kind: "character",
|
|
1673
|
+
localId: character.id,
|
|
1674
|
+
name: character.name,
|
|
1675
|
+
...character.visualIdentity?.globalId === void 0 ? {} : { globalId: character.visualIdentity.globalId }
|
|
1676
|
+
},
|
|
1677
|
+
png,
|
|
1678
|
+
...originalName === void 0 ? {} : { originalName }
|
|
1679
|
+
});
|
|
1680
|
+
} catch (error) {
|
|
1681
|
+
throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
|
|
1682
|
+
}
|
|
1683
|
+
return await readWorldEditor(world);
|
|
1684
|
+
}
|
|
1685
|
+
/** Resolve a portrait through authored data so request parameters cannot select arbitrary files. */
|
|
1686
|
+
async function worldCharacterPortraitFile(world, key) {
|
|
1687
|
+
const character = await characterOf(world, key);
|
|
1688
|
+
const file = referenceImagePath(world.directory, {
|
|
1689
|
+
kind: "character",
|
|
1690
|
+
localId: character.id,
|
|
1691
|
+
...character.visualIdentity?.globalId === void 0 ? {} : { globalId: character.visualIdentity.globalId }
|
|
1692
|
+
});
|
|
1693
|
+
return {
|
|
1694
|
+
file,
|
|
1695
|
+
size: (await stat(file)).size
|
|
1696
|
+
};
|
|
1697
|
+
}
|
|
1698
|
+
/** The document of one trigger as the world's file has it, for editing. */
|
|
1699
|
+
async function readWorldTrigger(world, key) {
|
|
1700
|
+
const found = (await readTriggerDocuments(world.directory)).find((entry) => entry["key"] === key);
|
|
1701
|
+
if (found === void 0) throw new InvalidEditProblems([`there is no trigger "${key}"`]);
|
|
1702
|
+
return found;
|
|
1703
|
+
}
|
|
1704
|
+
/** Makes or replaces one trigger from a complete document, checked as a story start checks it, and answers the world as it stands. */
|
|
1705
|
+
async function writeWorldTrigger(world, key, document) {
|
|
1706
|
+
await writeTriggerDocument(world.directory, await loadWorldParts(world.directory), key, document);
|
|
1707
|
+
return await readWorldEditor(world);
|
|
1708
|
+
}
|
|
1709
|
+
/** Removes one trigger, keeping its document in the world's trash, and answers the world as it stands. */
|
|
1710
|
+
async function removeWorldTrigger(world, key) {
|
|
1711
|
+
await deleteTriggerDocument(world.directory, key);
|
|
1712
|
+
return await readWorldEditor(world);
|
|
1713
|
+
}
|
|
1714
|
+
//#endregion
|
|
1715
|
+
//#region src/host/authoring/documents.ts
|
|
1716
|
+
const AUTHORED_ENTITY_KINDS = [
|
|
1717
|
+
"character",
|
|
1718
|
+
"location",
|
|
1719
|
+
"item",
|
|
1720
|
+
"faction",
|
|
1721
|
+
"lore"
|
|
1722
|
+
];
|
|
1723
|
+
const formats = {
|
|
1724
|
+
character: {
|
|
1725
|
+
directory: CHARACTERS_DIR,
|
|
1726
|
+
file: CHARACTER_FILE_NAME,
|
|
1727
|
+
parse: parseCharacterFile
|
|
1728
|
+
},
|
|
1729
|
+
location: {
|
|
1730
|
+
directory: LOCATIONS_DIR,
|
|
1731
|
+
file: LOCATION_FILE_NAME,
|
|
1732
|
+
parse: parseLocationFile
|
|
1733
|
+
},
|
|
1734
|
+
item: {
|
|
1735
|
+
directory: ITEMS_DIR,
|
|
1736
|
+
file: ITEM_FILE_NAME,
|
|
1737
|
+
parse: parseItemFile
|
|
1738
|
+
},
|
|
1739
|
+
faction: {
|
|
1740
|
+
directory: FACTIONS_DIR,
|
|
1741
|
+
file: FACTION_FILE_NAME,
|
|
1742
|
+
parse: parseFactionFile
|
|
1743
|
+
},
|
|
1744
|
+
lore: {
|
|
1745
|
+
directory: LORE_DIR,
|
|
1746
|
+
file: LORE_FILE_NAME,
|
|
1747
|
+
parse: parseLoreFile
|
|
1748
|
+
}
|
|
1749
|
+
};
|
|
1750
|
+
/** Keys become folder names and image paths: letters (any script), digits, marks, `.`, `_` and `-`, starting with a letter or digit. */
|
|
1751
|
+
const NEW_KEY = /^[\p{L}\p{N}][\p{L}\p{N}\p{M}._-]{0,99}$/u;
|
|
1752
|
+
function validNewKey(key) {
|
|
1753
|
+
return NEW_KEY.test(key);
|
|
1754
|
+
}
|
|
1755
|
+
async function find(world, kind, key) {
|
|
1756
|
+
const format = formats[kind];
|
|
1757
|
+
const root = join(world.directory, format.directory);
|
|
1758
|
+
for (const folder of await subfolders(root)) {
|
|
1759
|
+
const file = join(root, folder, format.file);
|
|
1760
|
+
try {
|
|
1761
|
+
const parsed = format.parse(await readFile(file, "utf8"), folder);
|
|
1762
|
+
if (parsed.ok && parsed.value.id === key) return {
|
|
1763
|
+
folder,
|
|
1764
|
+
file
|
|
1765
|
+
};
|
|
1766
|
+
} catch (error) {
|
|
1767
|
+
if (error.code !== "ENOENT") throw error;
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
function serializeDocument(kind, key, value) {
|
|
1772
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["document must be a JSON object"]);
|
|
1773
|
+
const document = {
|
|
1774
|
+
...value,
|
|
1775
|
+
id: key
|
|
1776
|
+
};
|
|
1777
|
+
const text = `${JSON.stringify(document, null, 2)}\n`;
|
|
1778
|
+
const parsed = formats[kind].parse(text, key);
|
|
1779
|
+
if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
|
|
1780
|
+
return text;
|
|
1781
|
+
}
|
|
1782
|
+
async function replaceFile(file, text) {
|
|
1783
|
+
const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
|
|
1784
|
+
try {
|
|
1785
|
+
const mode = await stat(file).then((value) => value.mode);
|
|
1786
|
+
await writeFile(temporary, text, { mode });
|
|
1787
|
+
await rename(temporary, file);
|
|
1788
|
+
} catch (error) {
|
|
1789
|
+
await rm(temporary, { force: true });
|
|
1790
|
+
throw error;
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
async function readAuthoredEntityDocument(world, kind, key) {
|
|
1794
|
+
const found = await find(world, kind, key);
|
|
1795
|
+
if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
|
|
1796
|
+
return JSON.parse((await readFile(found.file, "utf8")).replace(/^/, ""));
|
|
1797
|
+
}
|
|
1798
|
+
async function createAuthoredEntity(world, kind, key, document) {
|
|
1799
|
+
if (!validNewKey(key)) throw new InvalidEditProblems(["key must be letters (any script), digits, \".\", \"_\" or \"-\", starting with a letter or digit, at most 100 characters (no brackets, spaces or slashes)"]);
|
|
1800
|
+
if (await find(world, kind, key) !== void 0) throw new InvalidEditProblems([`the ${kind} "${key}" already exists`]);
|
|
1801
|
+
const format = formats[kind];
|
|
1802
|
+
const root = join(world.directory, format.directory);
|
|
1803
|
+
const folder = join(root, key);
|
|
1804
|
+
const text = serializeDocument(kind, key, document);
|
|
1805
|
+
await mkdir(root, { recursive: true });
|
|
1806
|
+
await mkdir(folder, { recursive: false });
|
|
1807
|
+
try {
|
|
1808
|
+
await writeFile(join(folder, format.file), text, { flag: "wx" });
|
|
1809
|
+
} catch (error) {
|
|
1810
|
+
await rm(folder, {
|
|
1811
|
+
recursive: true,
|
|
1812
|
+
force: true
|
|
1813
|
+
});
|
|
1814
|
+
throw error;
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
async function replaceAuthoredEntity(world, kind, key, document) {
|
|
1818
|
+
const found = await find(world, kind, key);
|
|
1819
|
+
if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
|
|
1820
|
+
await replaceFile(found.file, serializeDocument(kind, key, document));
|
|
1821
|
+
}
|
|
1822
|
+
/** Deletions remain recoverable without making the trash visible to the world loaders. */
|
|
1823
|
+
async function deleteAuthoredEntity(world, kind, key) {
|
|
1824
|
+
const found = await find(world, kind, key);
|
|
1825
|
+
if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
|
|
1826
|
+
const trash = join(world.directory, ".trash", formats[kind].directory);
|
|
1827
|
+
await mkdir(trash, { recursive: true });
|
|
1828
|
+
const destination = join(trash, `${found.folder}-${Date.now()}-${randomUUID()}`);
|
|
1829
|
+
await rename(dirname(found.file), destination);
|
|
1830
|
+
return destination;
|
|
1831
|
+
}
|
|
1832
|
+
//#endregion
|
|
1833
|
+
//#region src/host/interface/world-packs.ts
|
|
1834
|
+
/** The kinds of file an assistant may write, as text. */
|
|
1835
|
+
const TEXT_EXTENSIONS = [
|
|
1836
|
+
"html",
|
|
1837
|
+
"css",
|
|
1838
|
+
"js",
|
|
1839
|
+
"json",
|
|
1840
|
+
"txt",
|
|
1841
|
+
"svg"
|
|
1842
|
+
];
|
|
1843
|
+
const folderOf = (directory, pack) => join(directory, "ui", pack);
|
|
1844
|
+
function checked(directory, pack) {
|
|
1845
|
+
if (!isPackId(pack)) throw new Error(`"${pack}" is not a usable pack name (letters, digits, "-" and "_")`);
|
|
1846
|
+
return folderOf(directory, pack);
|
|
1847
|
+
}
|
|
1848
|
+
/** What every pack the world carries holds and what is wrong with it. */
|
|
1849
|
+
function listWorldPacks(directory) {
|
|
1850
|
+
return packIds(directory).map((id) => {
|
|
1851
|
+
const { pack, problems } = readPack(folderOf(directory, id), id, (file) => file);
|
|
1852
|
+
const files = pack === void 0 ? [] : [...pack.files.keys()];
|
|
1853
|
+
return {
|
|
1854
|
+
id,
|
|
1855
|
+
name: pack?.manifest.name ?? id,
|
|
1856
|
+
problems,
|
|
1857
|
+
files
|
|
1858
|
+
};
|
|
1859
|
+
});
|
|
1860
|
+
}
|
|
1861
|
+
/** What is wrong with a pack (nothing when it can be used). */
|
|
1862
|
+
function checkWorldPack(directory, pack) {
|
|
1863
|
+
const folder = checked(directory, pack);
|
|
1864
|
+
if (!existsSync(folder)) throw new Error(`the world carries no pack "${pack}"`);
|
|
1865
|
+
return readPack(folder, pack, (file) => file).problems;
|
|
1866
|
+
}
|
|
1867
|
+
/** Moves a file of a pack into the world's `.trash`. @returns where it went, and what is wrong with the pack now. */
|
|
1868
|
+
async function deleteWorldPackFile(directory, pack, path) {
|
|
1869
|
+
const relative = packPath(path);
|
|
1870
|
+
if (relative === void 0 || !(extname(relative).slice(1).toLowerCase() in PACK_MEDIA_TYPES)) throw new Error(`"${path}" is not a file of a pack`);
|
|
1871
|
+
const folder = checked(directory, pack);
|
|
1872
|
+
const file = join(folder, ...relative.split("/"));
|
|
1873
|
+
if (!existsSync(file)) throw new Error(`the pack "${pack}" has no file "${path}"`);
|
|
1874
|
+
const aside = join(directory, ".trash", "ui", pack, `${relative.replaceAll("/", "__")}.${Date.now()}`);
|
|
1875
|
+
await mkdir(dirname(aside), { recursive: true });
|
|
1876
|
+
await rename(file, aside);
|
|
1877
|
+
return {
|
|
1878
|
+
trashPath: aside,
|
|
1879
|
+
problems: existsSync(join(folder, "pack.json")) ? readPack(folder, pack, (address) => address).problems : [{
|
|
1880
|
+
file: "pack.json",
|
|
1881
|
+
message: "the pack has no pack.json"
|
|
1882
|
+
}]
|
|
1883
|
+
};
|
|
1884
|
+
}
|
|
1885
|
+
//#endregion
|
|
1886
|
+
//#region src/host/authoring/pack-jail.ts
|
|
1887
|
+
/** DSH's own file tools, which the world authoring chat uses on the interface packs and nothing else. */
|
|
1888
|
+
const PACK_FILE_TOOLS = [
|
|
1889
|
+
"read",
|
|
1890
|
+
"write",
|
|
1891
|
+
"edit"
|
|
1892
|
+
];
|
|
1893
|
+
const WRITING = ["write", "edit"];
|
|
1894
|
+
/** The most text a call may carry. */
|
|
1895
|
+
const MAX_PACK_TEXT = 204800;
|
|
1896
|
+
function unsafePath(ui, path) {
|
|
1897
|
+
const parts = relative(ui, path).split(sep);
|
|
1898
|
+
let current = ui;
|
|
1899
|
+
for (const part of ["", ...parts]) {
|
|
1900
|
+
if (part !== "") current = join(current, part);
|
|
1901
|
+
try {
|
|
1902
|
+
if (lstatSync(current).isSymbolicLink()) return `the path passes through the symbolic link ${current}`;
|
|
1903
|
+
} catch (error) {
|
|
1904
|
+
if (error.code === "ENOENT") break;
|
|
1905
|
+
if (error.code === "ENOTDIR") return `${current} cannot be traversed as a folder`;
|
|
1906
|
+
throw error;
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
/**
|
|
1911
|
+
* Why a call of a file tool is not one on an interface pack of the world, or nothing when it is: the file must be a text
|
|
1912
|
+
* file of a pack folder `<world>/ui/<pack>/`, and a write must not carry more text than a pack file may hold.
|
|
1913
|
+
* @param path - the absolute path asked for.
|
|
1914
|
+
* @param world - the world's folder.
|
|
1915
|
+
*/
|
|
1916
|
+
function packFileProblem(tool, path, world, texts = []) {
|
|
1917
|
+
const ui = join(world, "ui");
|
|
1918
|
+
const inside = relative(ui, path);
|
|
1919
|
+
const segments = inside.split(sep);
|
|
1920
|
+
const hint = `in this chat the file tools reach only the text files of the world's interface packs, ${join(ui, "<pack>", "<file>")}. Nothing, not another path and not sandbox_permissions, lifts that: do not try again for this file, tell the person that it cannot be changed from here`;
|
|
1921
|
+
if (inside === "" || inside.startsWith("..") || isAbsolute(inside) || segments.length < 2) return `${path} is not a file of an interface pack: ${hint}`;
|
|
1922
|
+
if (!isPackId(segments[0])) return `"${segments[0]}" is not a usable pack name (letters, digits, "-" and "_"): ${hint}`;
|
|
1923
|
+
if (segments.some((segment) => segment.startsWith("."))) return `${path}: names may not start with a dot`;
|
|
1924
|
+
if (!TEXT_EXTENSIONS.includes(extname(path).slice(1).toLowerCase())) return `${path} is not a text file of a pack (${TEXT_EXTENSIONS.join(", ")}); pictures and other files are added by hand`;
|
|
1925
|
+
const unsafe = unsafePath(ui, path);
|
|
1926
|
+
if (unsafe !== void 0) return `${path}: ${unsafe}; file tools do not follow symbolic links in interface packs`;
|
|
1927
|
+
if (WRITING.includes(tool) && texts.some((text) => Buffer.byteLength(text) > 204800)) return `a call may carry at most ${MAX_PACK_TEXT / 1024} KB of text`;
|
|
1928
|
+
}
|
|
1929
|
+
const textOf = (value) => typeof value === "string" ? [value] : [];
|
|
1930
|
+
/**
|
|
1931
|
+
* Keeps DSH's `read`, `write` and `edit` on the interface packs of the world in an authoring chat, and asks the person before
|
|
1932
|
+
* any change. It stands first in the chain, so that what it refuses cannot be let through by a listener after it; and what a
|
|
1933
|
+
* later listener decides still stands: a plugin that denies or asks keeps doing so, and only a plain allow becomes an ask.
|
|
1934
|
+
*/
|
|
1935
|
+
async function packJail(exec, next, deps) {
|
|
1936
|
+
const chat = exec.agent?.session.id;
|
|
1937
|
+
if (!PACK_FILE_TOOLS.includes(exec.name) || chat === void 0 || authoredWorldOf(chat) === void 0) return await next();
|
|
1938
|
+
const world = await deps.worldDirectory(chat);
|
|
1939
|
+
if (world === void 0) return {
|
|
1940
|
+
kind: "deny",
|
|
1941
|
+
reason: "the world of this chat no longer exists"
|
|
1942
|
+
};
|
|
1943
|
+
const args = exec.arguments;
|
|
1944
|
+
const requested = args["file_path"];
|
|
1945
|
+
if (typeof requested !== "string" || requested === "" || requested.startsWith("~")) return {
|
|
1946
|
+
kind: "deny",
|
|
1947
|
+
reason: "file_path must be a path of an interface pack of this world"
|
|
1948
|
+
};
|
|
1949
|
+
const path = resolve(exec.agent?.session.header.cwd ?? world, requested);
|
|
1950
|
+
const problem = packFileProblem(exec.name, path, world, [...textOf(args["content"]), ...textOf(args["new_string"])]);
|
|
1951
|
+
if (problem !== void 0) return {
|
|
1952
|
+
kind: "deny",
|
|
1953
|
+
reason: problem
|
|
1954
|
+
};
|
|
1955
|
+
const writing = WRITING.includes(exec.name);
|
|
1956
|
+
if (writing && await deps.reviewing(chat)) return {
|
|
1957
|
+
kind: "deny",
|
|
1958
|
+
reason: "an import does not write interface packs; they are left to the person"
|
|
1959
|
+
};
|
|
1960
|
+
const decision = await next();
|
|
1961
|
+
if (!writing || decision.kind !== "allow") return decision;
|
|
1962
|
+
const target = `“${relative(join(world, "ui"), path)}”`;
|
|
1963
|
+
return {
|
|
1964
|
+
kind: "ask",
|
|
1965
|
+
reason: `${exec.name} interface pack file ${target}`,
|
|
1966
|
+
displayReason: {
|
|
1967
|
+
en: `${exec.name === "write" ? "Write" : "Edit"} ${target} of an interface pack in the world files?`,
|
|
1968
|
+
zh: `${exec.name === "write" ? "写入" : "编辑"}世界文件中界面包的文件${target}?`
|
|
1969
|
+
}
|
|
1970
|
+
};
|
|
1971
|
+
}
|
|
1972
|
+
/** Puts the jail first in the chain of `tools/pre-execute`: what it refuses cannot be let through by a listener after it. */
|
|
1973
|
+
function registerPackJail(ctx, deps) {
|
|
1974
|
+
ctx.on("tools/pre-execute", (exec, next) => packJail(exec, next, deps), { prepend: true });
|
|
1975
|
+
}
|
|
1976
|
+
//#endregion
|
|
1977
|
+
export { worldEntityImageFile as A, translateTools as B, readWorldEditor as C, uploadWorldCharacterPortrait as D, replaceFile$1 as E, loadWorldParts as F, readWorldDocuments as H, PRESET_FILE as I, presetMessage as L, deleteTriggerDocument as M, readTriggerDocuments as N, uploadWorldEntityImage as O, writeTriggerDocument as P, presetTools as R, generateWorldEntityImage as S, removeWorldTrigger as T, languageOfDocuments as V, editWorldPlots as _, deleteWorldPackFile as a, entityFolder as b, createAuthoredEntity as c, replaceAuthoredEntity as d, editWorldCharacter as f, editWorldPlace as g, editWorldNarrationVoice as h, checkWorldPack as i, writeWorldTrigger as j, worldCharacterPortraitFile as k, deleteAuthoredEntity as l, editWorldLore as m, packFileProblem as n, listWorldPacks as o, editWorldFaction as p, registerPackJail as r, AUTHORED_ENTITY_KINDS as s, MAX_PACK_TEXT as t, readAuthoredEntityDocument as u, editWorldRelation as v, readWorldTrigger as w, generateWorldCharacterPortrait as x, editWorldThing as y, translateMessage as z };
|
|
1978
|
+
|
|
1979
|
+
//# sourceMappingURL=pack-jail-ClMpVc__.js.map
|