@dsh-agentic-roleplay/core 0.7.3 → 0.8.1
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/README.md +1 -1
- package/lib/{authoring-tools-CIsWbq0B.js → authoring-tools-DNnx0Nts.js} +1774 -4517
- package/lib/authoring.js +51 -9
- package/lib/{child-CyCViUKa.js → child-D6mpkkCE.js} +130 -6
- package/lib/client.js +661 -427
- package/lib/client.js.map +1 -1
- package/lib/compaction.js +2 -2
- package/lib/doctor.js +2 -2
- package/lib/{gallery-DmBZ2L5l.js → gallery-D9nG3C78.js} +2 -2
- package/lib/{generator-BmdoTIL2.js → generator-r1Czm7oi.js} +2 -2
- package/lib/helper.js +1 -1
- package/lib/{hooks-C8eELrni.js → hooks-BQCzgggH.js} +92 -8
- package/lib/images.js +4 -4
- package/lib/index.js +920 -739
- package/lib/{library-lVNf9qG_.js → library-zI-2tG7h.js} +25 -8
- package/lib/{lorebook-author-tools-BDOs4i5C.js → lorebook-author-tools-ywaYicwd.js} +7 -7
- package/lib/lorebook-authoring.js +4 -4
- package/lib/{narration-DvFBqmqe.js → narration-CnBlVure.js} +52 -8
- package/lib/orchestration.js +95 -18
- package/lib/{pack-jail-DeTscGT2.js → pack-jail-5EJ-WYyW.js} +30 -68
- package/lib/{packs-CY8ms8v_.js → packs-Cv8hanXJ.js} +2 -2
- package/lib/{presenter-agent-cFR4sos3.js → presenter-agent-BSaMSd3G.js} +6 -6
- package/lib/{preset-n4-j6k4S.js → preset-CWI3-0r1.js} +4 -3
- package/lib/{preset-author-tools-2m4BLtws.js → preset-author-tools-BrJYa2cr.js} +7 -7
- package/lib/preset-authoring.js +5 -5
- package/lib/presets-MwOSMMyu.js +3998 -0
- package/lib/{reflection-CJB5s0ip.js → reflection-zSaMsjKj.js} +127 -127
- package/lib/{text-Cwl5s0j0.js → text-BzudpQLS.js} +9 -1
- package/lib/{turn-guard-BvCs1VxB.js → turn-guard-Cv8pfHEA.js} +6 -2
- package/package.json +2 -2
- package/prompts/en/import/casting.md +14 -0
- package/prompts/en/import/classifier.md +9 -0
- package/prompts/en/import/finish-draft.md +1 -0
- package/prompts/en/import/generator.md +8 -0
- package/prompts/en/import/notice-repair.md +4 -0
- package/prompts/en/import/repair-again.md +3 -0
- package/prompts/en/import/roster.md +1 -0
- package/prompts/en/import/variables.md +1 -0
- package/prompts/en/roleplay/game-master.md +3 -0
- package/prompts/en/roleplay/standing.md +1 -0
- package/prompts/en/world/author.md +1 -1
- package/prompts/zh/import/casting.md +14 -0
- package/prompts/zh/import/classifier.md +9 -0
- package/prompts/zh/import/finish-draft.md +1 -0
- package/prompts/zh/import/generator.md +8 -0
- package/prompts/zh/import/notice-repair.md +4 -0
- package/prompts/zh/import/repair-again.md +3 -0
- package/prompts/zh/import/roster.md +1 -0
- package/prompts/zh/import/variables.md +1 -0
- package/prompts/zh/roleplay/game-master.md +3 -0
- package/prompts/zh/roleplay/standing.md +1 -0
- package/prompts/zh/world/author.md +1 -1
- package/lib/route-C6SHz9j2.js +0 -518
package/lib/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
import { a as chatSessionId, i as VARIABLE_VISIBILITIES, n as VARIABLE_KINDS, o as roleplaySessionOf, r as VARIABLE_SUBJECTS } from "./access-DtOxFKBK.js";
|
|
2
|
-
import { $ as
|
|
3
|
-
import { a as lorebookImportMessage, c as readLorebook, d as lorebookOfChat, l as selectEntries, s as previewLorebook, t as LOREBOOK_UPLOAD, u as lorebookChatSessionId } from "./lorebook-author-tools-
|
|
4
|
-
import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-
|
|
5
|
-
import {
|
|
6
|
-
import { c as
|
|
7
|
-
import { a as liveSettings, c as writeSettings, d as
|
|
8
|
-
import {
|
|
9
|
-
import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-
|
|
10
|
-
import { A as worldEntityImageFile, B as readWorldInfo, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as loadWorldParts, G as findTargets, I as PRESET_FILE$1, J as revertUpdate, L as presetMessage, O as uploadWorldEntityImage, S as generateWorldEntityImage, T as removeWorldTrigger, U as languageOfDocuments, V as translateMessage, W as readWorldDocuments, X as updateStatus, Y as startUpdate, _ as editWorldPlots$1, a as deleteWorldPackFile, at as authoringTitle, b as entityFolder, c as createAuthoredEntity, ct as ensureAgentChat, dt as appendNarratedTurn, f as editWorldCharacter$1, ft as storeAuthoringOpening, g as editWorldPlace$1, h as editWorldNarrationVoice, it as AuthoringSessions, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, lt as isStored, m as editWorldLore$1, n as packFileProblem, ot as AgentSessions, p as editWorldFaction$1, pt as storeDoctorOpening, st as agentServicesOf, t as MAX_PACK_TEXT, u as readAuthoredEntityDocument, ut as appendEmptyTurn, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1, z as editWorldInfo } from "./pack-jail-
|
|
11
|
-
import { d as sharedSamplingOf, i as childSamplingOf, u as parseSampling } from "./child-
|
|
12
|
-
import { S as slug, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath, w as uniqueKey } from "./library-
|
|
13
|
-
import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-
|
|
2
|
+
import { $ as knowsCharacter, At as loadCharacters, B as deleteLorebook, Bt as authoredWorldOf, Ct as DICE_FILE_NAME, D as guardedLookup, Dt as loadCalendar, Et as CALENDAR_FILE_NAME, F as WORLD_FILE_NAME, Ft as pictureOf, G as loadLorebook, H as entriesOf, I as parseWorldFile, It as readCard, J as reserveLorebook, K as lorebookDirectory, L as parseWorldInfoEdit, Lt as DICE_COMPARISONS, Mt as knownOutputCeiling, Nt as ImportCardError, Ot as parseCalendarFile, Pt as isPng, Q as loadValidatedWorld, R as addLorebookEntries, Rt as DICE_READINGS, S as CatalogueError, Tt as parseDiceFile, U as isLorebookName, V as deleteLorebookEntry, W as listLorebooks, X as writeLorebookEntry, Y as updateLorebookInfo, Z as checkWorld, _ as hashWorld, at as populateItems, b as readOrigin, bt as loadItems, c as importPhase, ct as populateLore, d as markReady, dt as populateVariables, et as populateCalendar, f as settleDraft, ft as routineProblems, g as describeChanges, it as populateFactions, jt as subfolders, k as vetUrl, kt as CHARACTERS_DIR, lt as populateRoutines, nt as populateClock, ot as populateKnowledge, pt as TRIGGERS_FILE_NAME, rt as populateDice, st as populateLocations, t as AuthoringTools, tt as populateCharacters, u as keepDraft, ut as populateTriggers, v as isUnchanged, vt as loadLocations, wt as loadDice, x as writeOrigin, y as localChanges, z as createLorebook, zt as DICE_RESULTS } from "./authoring-tools-DNnx0Nts.js";
|
|
3
|
+
import { a as lorebookImportMessage, c as readLorebook, d as lorebookOfChat, l as selectEntries, s as previewLorebook, t as LOREBOOK_UPLOAD, u as lorebookChatSessionId } from "./lorebook-author-tools-ywaYicwd.js";
|
|
4
|
+
import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-BrJYa2cr.js";
|
|
5
|
+
import { B as readWorldPrompt, Ct as parseLoreEdit, Dt as LORE_KINDS, Et as parseThingEdit, G as withPlayer, J as ImportStore, K as IMPORT_FOLDER, Ot as LORE_SCOPES, R as deleteWorldPrompt, St as parseFactionEdit, Tt as parseRelationEdit, V as writeWorldPrompt, W as partsOf, Z as parseChoices, _t as parseCharacterFile, a as isPresetName, at as variableProblems, bt as InvalidEditProblems, c as presetDirectory, d as savePresetFromWorld, et as IMPORT_COMMAND, gt as CHARACTER_FILE_NAME, i as deletePreset, it as parseVariablesFile, nt as VARIABLES_FILE_NAME, o as listPresets, p as updatePresetInfo, q as ImportNotFoundError, r as createPresetFromShipped, rt as loadVariables, s as loadPreset, t as PRESET_FILE, u as reservePreset, wt as parsePlaceEdit, xt as parseCharacterEdit, z as listWorldPrompts } from "./presets-MwOSMMyu.js";
|
|
6
|
+
import { c as readTimeline, d as copyPreset, f as presetStatus, h as defaultBoundaries, i as reflectionStatus, l as writeTimeline, m as switchPreset, o as TimelineError, p as recordPreset, u as pathTo } from "./reflection-zSaMsjKj.js";
|
|
7
|
+
import { a as liveSettings, c as writeSettings, d as DEFAULT_SETTINGS, f as SETTINGS_SPEC, h as WORLD_RULES_KEY, i as InvalidSettingsError, l as atomicWrite, o as readSettings, p as parseSettings, s as useChildReasoning } from "./narration-CnBlVure.js";
|
|
8
|
+
import { $ as copyWorldPrompts, C as notesOfSession, H as parsePlotsFile, J as formatIssue, K as readDocument, M as PLOTS_METADATA_KEY, N as plotProgressOf, P as populatePlots, Q as PromptLibrary, S as addToNote, T as observeAsPlayer, U as plotReferenceProblems, W as COMMANDS_KEY, Y as errorMessage, _ as readActivity, ct as InvalidStartError, dt as SessionArchivedError, ft as SessionNotFoundError, g as readDecisionStats, h as readUsage, i as externalTools, it as shippedLanguages, k as zoneOf, lt as InvalidWorldError, pt as WorldNotFoundError, st as AgentUnavailableError, tt as languageOf, ut as ReflectionRefusedError, v as readRunDetail, w as readNotes, x as readWithdrawn } from "./hooks-BQCzgggH.js";
|
|
9
|
+
import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-BzudpQLS.js";
|
|
10
|
+
import { A as worldEntityImageFile, B as readWorldInfo, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as loadWorldParts, G as findTargets, I as PRESET_FILE$1, J as revertUpdate, L as presetMessage, O as uploadWorldEntityImage, S as generateWorldEntityImage, T as removeWorldTrigger, U as languageOfDocuments, V as translateMessage, W as readWorldDocuments, X as updateStatus, Y as startUpdate, _ as editWorldPlots$1, a as deleteWorldPackFile, at as authoringTitle, b as entityFolder, c as createAuthoredEntity, ct as ensureAgentChat, dt as appendNarratedTurn, f as editWorldCharacter$1, ft as storeAuthoringOpening, g as editWorldPlace$1, h as editWorldNarrationVoice, it as AuthoringSessions, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, lt as isStored, m as editWorldLore$1, n as packFileProblem, ot as AgentSessions, p as editWorldFaction$1, pt as storeDoctorOpening, st as agentServicesOf, t as MAX_PACK_TEXT, u as readAuthoredEntityDocument, ut as appendEmptyTurn, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1, z as editWorldInfo } from "./pack-jail-5EJ-WYyW.js";
|
|
11
|
+
import { d as sharedSamplingOf, i as childSamplingOf, u as parseSampling } from "./child-D6mpkkCE.js";
|
|
12
|
+
import { S as slug, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath, w as uniqueKey } from "./library-zI-2tG7h.js";
|
|
13
|
+
import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-CWI3-0r1.js";
|
|
14
14
|
import { t as doctorChatSessionId } from "./doctor-chat-ByDfCMeo.js";
|
|
15
|
-
import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-
|
|
16
|
-
import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-
|
|
17
|
-
import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-
|
|
15
|
+
import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-Cv8hanXJ.js";
|
|
16
|
+
import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-r1Czm7oi.js";
|
|
17
|
+
import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-D9nG3C78.js";
|
|
18
18
|
import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
|
|
19
19
|
import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
20
20
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
21
|
+
import { copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
21
22
|
import { Session, SessionId } from "@deepseek-ai/dsh-session";
|
|
22
23
|
import { inflateRawSync } from "node:zlib";
|
|
23
24
|
import { fileURLToPath } from "node:url";
|
|
24
25
|
import { Service } from "@deepseek-ai/cordis";
|
|
25
|
-
import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
26
26
|
import { addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
|
|
27
27
|
import { request } from "node:http";
|
|
28
28
|
import { request as request$1 } from "node:https";
|
|
@@ -77,6 +77,17 @@ var RoleplayImport = class extends Service {
|
|
|
77
77
|
}
|
|
78
78
|
};
|
|
79
79
|
//#endregion
|
|
80
|
+
//#region src/host/worlds/draft.ts
|
|
81
|
+
/** Whether the world is an import that was written but would not start yet: its import state (kept in the world's `.import` folder) says it is being repaired. */
|
|
82
|
+
async function isDraftWorld(directory) {
|
|
83
|
+
try {
|
|
84
|
+
return JSON.parse(await readFile(join(directory, ".import", "state.json"), "utf8")).phase === "repair";
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (error.code === "ENOENT") return false;
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
//#endregion
|
|
80
91
|
//#region src/host/worlds/create-world.ts
|
|
81
92
|
const FOLDER = /^[\p{L}\p{N}][\p{L}\p{N}._ -]{0,99}$/u;
|
|
82
93
|
var WorldFolderExistsError = class extends Error {};
|
|
@@ -135,6 +146,30 @@ function importMessage(language) {
|
|
|
135
146
|
return `${IMPORT_COMMAND} ${IMPORT_FOLDER}/card.json ${tr("Import this card into this newly created world.")}`;
|
|
136
147
|
}
|
|
137
148
|
/**
|
|
149
|
+
* Has the chat of a world whose import stopped before it was done carry on from the step it reached (the import hooks tell the chat which step that is). An import is lost
|
|
150
|
+
* to a server restart, a refused finish or a chat that ended early; the card and what was extracted stay in the world's import folder.
|
|
151
|
+
* @throws {WorldNotFoundError} when the world is gone. @throws {InvalidEditProblems} when no import is waiting in it.
|
|
152
|
+
*/
|
|
153
|
+
async function resumeImport(deps, worldId, language) {
|
|
154
|
+
const record = await deps.worlds.find(worldId);
|
|
155
|
+
if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
|
|
156
|
+
const phase = await importPhase(record.directory);
|
|
157
|
+
if (phase === void 0 || phase === "done") throw new InvalidEditProblems(["no import is waiting in this world"]);
|
|
158
|
+
const chatSessionId = await deps.authoring.ensure(record.summary.id, record.summary.name, authoringTitle(record.summary.name, language), language);
|
|
159
|
+
let failure;
|
|
160
|
+
try {
|
|
161
|
+
await deps.authoring.send(chatSessionId, importMessage(language));
|
|
162
|
+
} catch (error) {
|
|
163
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
worldId: record.summary.id,
|
|
167
|
+
chatSessionId,
|
|
168
|
+
started: failure === void 0,
|
|
169
|
+
...failure === void 0 ? {} : { failure }
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
138
173
|
* Turns an uploaded card into a new empty world with its authoring chat, and has the chat start importing it on the person's behalf.
|
|
139
174
|
* @throws {InvalidEditProblems} when the choices cannot be used. @throws {ImportNotFoundError} when the upload is gone.
|
|
140
175
|
*/
|
|
@@ -172,6 +207,56 @@ async function startImport(deps, id, choices, language) {
|
|
|
172
207
|
};
|
|
173
208
|
}
|
|
174
209
|
//#endregion
|
|
210
|
+
//#region src/host/import/draft.ts
|
|
211
|
+
async function draftOf(worlds, worldId) {
|
|
212
|
+
const record = await worlds.find(worldId);
|
|
213
|
+
if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
|
|
214
|
+
return record;
|
|
215
|
+
}
|
|
216
|
+
async function draftStatus(worlds, worldId) {
|
|
217
|
+
const record = await draftOf(worlds, worldId);
|
|
218
|
+
if (!await isDraftWorld(record.directory)) return { draft: false };
|
|
219
|
+
if (await settleDraft(record.directory)) {
|
|
220
|
+
await worlds.list({ refresh: true });
|
|
221
|
+
return { draft: false };
|
|
222
|
+
}
|
|
223
|
+
return {
|
|
224
|
+
draft: true,
|
|
225
|
+
check: await checkWorld({
|
|
226
|
+
directory: record.directory,
|
|
227
|
+
summary: record.summary,
|
|
228
|
+
...record.variables === void 0 ? {} : { variables: record.variables }
|
|
229
|
+
})
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* What the person decides about a draft: have the assistant try again (with the card at hand), keep it as it is (an ordinary world that cannot be played until it is mended),
|
|
234
|
+
* or discard it (the folder goes to the root's trash, where it can still be found).
|
|
235
|
+
* @throws {InvalidEditProblems} when the world is not a draft.
|
|
236
|
+
*/
|
|
237
|
+
async function actOnDraft(deps, worldId, action, language) {
|
|
238
|
+
const record = await draftOf(deps.worlds, worldId);
|
|
239
|
+
if (!await isDraftWorld(record.directory)) throw new InvalidEditProblems(["this world is not a draft"]);
|
|
240
|
+
if (action === "ask") return {
|
|
241
|
+
action,
|
|
242
|
+
started: await resumeImport(deps, worldId, language)
|
|
243
|
+
};
|
|
244
|
+
if (action === "keep") {
|
|
245
|
+
await keepDraft(record.directory);
|
|
246
|
+
await deps.worlds.list({ refresh: true });
|
|
247
|
+
return { action };
|
|
248
|
+
}
|
|
249
|
+
const trash = join(deps.root(), ".trash", "worlds");
|
|
250
|
+
await mkdir(trash, { recursive: true });
|
|
251
|
+
const destination = join(trash, `${basename(record.directory)}-${Date.now()}`);
|
|
252
|
+
await rename(record.directory, destination);
|
|
253
|
+
await deps.worlds.list({ refresh: true });
|
|
254
|
+
return {
|
|
255
|
+
action,
|
|
256
|
+
keptIn: relative(deps.root(), destination)
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
//#endregion
|
|
175
260
|
//#region src/host/translate/service.ts
|
|
176
261
|
async function recordOf(worlds, id) {
|
|
177
262
|
const record = await worlds.find(id);
|
|
@@ -808,438 +893,46 @@ var RoleplayOrchestration = class extends Service {
|
|
|
808
893
|
}
|
|
809
894
|
};
|
|
810
895
|
//#endregion
|
|
811
|
-
//#region src/
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
"
|
|
815
|
-
"
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
"compare",
|
|
821
|
-
"modifier",
|
|
822
|
-
"bands"
|
|
823
|
-
];
|
|
824
|
-
const BAND_FIELDS = [
|
|
825
|
-
"min",
|
|
826
|
-
"max",
|
|
827
|
-
"label",
|
|
828
|
-
"result",
|
|
829
|
-
"critical"
|
|
830
|
-
];
|
|
831
|
-
/** Reads a body that came from the browser: the shape of every field is checked here, and what the checks mean when the world is validated. */
|
|
832
|
-
function parseDiceEdit(value) {
|
|
833
|
-
const problems = [];
|
|
834
|
-
if (!isObject$1(value) || !Array.isArray(value["checks"])) throw new InvalidEditProblems(["the dice must be { checks: [...] }"]);
|
|
835
|
-
const checks = value["checks"].map((entry, index) => {
|
|
836
|
-
const at = `checks[${index}]`;
|
|
837
|
-
const empty = {
|
|
838
|
-
key: "",
|
|
839
|
-
name: "",
|
|
840
|
-
use: "",
|
|
841
|
-
dice: "",
|
|
842
|
-
bands: []
|
|
843
|
-
};
|
|
844
|
-
if (!isObject$1(entry)) {
|
|
845
|
-
problems.push(`${at} must be an object`);
|
|
846
|
-
return empty;
|
|
847
|
-
}
|
|
848
|
-
for (const key of Object.keys(entry)) if (!CHECK_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a check`);
|
|
849
|
-
for (const key of [
|
|
850
|
-
"key",
|
|
851
|
-
"name",
|
|
852
|
-
"use",
|
|
853
|
-
"dice"
|
|
854
|
-
]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
855
|
-
if (entry["reading"] !== void 0 && !DICE_READINGS.includes(entry["reading"])) problems.push(`${at}.reading must be one of: ${DICE_READINGS.join(", ")}`);
|
|
856
|
-
if (entry["compare"] !== void 0 && !DICE_COMPARISONS.includes(entry["compare"])) problems.push(`${at}.compare must be one of: ${DICE_COMPARISONS.join(", ")}`);
|
|
857
|
-
if (entry["hit"] !== void 0 && (typeof entry["hit"] !== "number" || !Number.isInteger(entry["hit"]))) problems.push(`${at}.hit must be a whole number`);
|
|
858
|
-
if (entry["modifier"] !== void 0 && typeof entry["modifier"] !== "string") problems.push(`${at}.modifier must be text`);
|
|
859
|
-
const bands = Array.isArray(entry["bands"]) ? entry["bands"] : void 0;
|
|
860
|
-
if (bands === void 0) problems.push(`${at}.bands must be a list`);
|
|
861
|
-
const text = (field) => typeof field === "string" ? field.trim() : "";
|
|
862
|
-
const hit = entry["hit"];
|
|
863
|
-
return {
|
|
864
|
-
key: text(entry["key"]),
|
|
865
|
-
name: text(entry["name"]),
|
|
866
|
-
use: text(entry["use"]),
|
|
867
|
-
dice: text(entry["dice"]),
|
|
868
|
-
...entry["reading"] === void 0 ? {} : { reading: entry["reading"] },
|
|
869
|
-
...typeof hit === "number" ? { hit } : {},
|
|
870
|
-
...entry["compare"] === void 0 ? {} : { compare: entry["compare"] },
|
|
871
|
-
...text(entry["modifier"]) === "" ? {} : { modifier: text(entry["modifier"]) },
|
|
872
|
-
bands: (bands ?? []).map((band, bandIndex) => {
|
|
873
|
-
const where = `${at}.bands[${bandIndex}]`;
|
|
874
|
-
if (!isObject$1(band)) {
|
|
875
|
-
problems.push(`${where} must be an object`);
|
|
876
|
-
return {
|
|
877
|
-
label: "",
|
|
878
|
-
result: "failed"
|
|
879
|
-
};
|
|
880
|
-
}
|
|
881
|
-
for (const key of Object.keys(band)) if (!BAND_FIELDS.includes(key)) problems.push(`${where}.${key} is not a field of a band`);
|
|
882
|
-
for (const key of ["min", "max"]) if (band[key] !== void 0 && (typeof band[key] !== "number" || !Number.isFinite(band[key]))) problems.push(`${where}.${key} must be a number`);
|
|
883
|
-
if (typeof band["label"] !== "string") problems.push(`${where}.label must be text`);
|
|
884
|
-
if (!DICE_RESULTS.includes(band["result"])) problems.push(`${where}.result must be one of: ${DICE_RESULTS.join(", ")}`);
|
|
885
|
-
const min = band["min"];
|
|
886
|
-
const max = band["max"];
|
|
887
|
-
return {
|
|
888
|
-
label: text(band["label"]),
|
|
889
|
-
result: band["result"],
|
|
890
|
-
...typeof min === "number" ? { min } : {},
|
|
891
|
-
...typeof max === "number" ? { max } : {},
|
|
892
|
-
...band["critical"] === true ? { critical: true } : {}
|
|
893
|
-
};
|
|
894
|
-
})
|
|
895
|
-
};
|
|
896
|
-
});
|
|
897
|
-
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
898
|
-
return { checks };
|
|
896
|
+
//#region src/host/http/respond.ts
|
|
897
|
+
function sendJson(res, status, payload) {
|
|
898
|
+
res.statusCode = status;
|
|
899
|
+
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
900
|
+
res.setHeader("cache-control", "no-store");
|
|
901
|
+
res.end(JSON.stringify(payload));
|
|
902
|
+
}
|
|
903
|
+
function sendError(res, status, message) {
|
|
904
|
+
sendJson(res, status, { message });
|
|
899
905
|
}
|
|
906
|
+
/** A failure with the status the client should see. */
|
|
907
|
+
var HttpError = class extends Error {
|
|
908
|
+
status;
|
|
909
|
+
constructor(status, message) {
|
|
910
|
+
super(message);
|
|
911
|
+
this.status = status;
|
|
912
|
+
}
|
|
913
|
+
};
|
|
900
914
|
//#endregion
|
|
901
|
-
//#region src/
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
const problems = [];
|
|
920
|
-
const list = isObject(value) && Array.isArray(value["windows"]) ? value["windows"] : void 0;
|
|
921
|
-
if (list === void 0) throw new InvalidEditProblems(["the day must be { windows: [...] }"]);
|
|
922
|
-
const windows = list.map((entry, index) => {
|
|
923
|
-
const at = `windows[${index}]`;
|
|
924
|
-
if (!isObject(entry)) {
|
|
925
|
-
problems.push(`${at} must be an object`);
|
|
926
|
-
return {
|
|
927
|
-
days: [],
|
|
928
|
-
from: "",
|
|
929
|
-
to: "",
|
|
930
|
-
activity: "",
|
|
931
|
-
interruptible: true
|
|
932
|
-
};
|
|
933
|
-
}
|
|
934
|
-
for (const key of Object.keys(entry)) if (!ROUTINE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a window`);
|
|
935
|
-
for (const key of [
|
|
936
|
-
"from",
|
|
937
|
-
"to",
|
|
938
|
-
"activity"
|
|
939
|
-
]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
940
|
-
for (const key of [
|
|
941
|
-
"location",
|
|
942
|
-
"feature",
|
|
943
|
-
"position"
|
|
944
|
-
]) if (entry[key] !== void 0 && typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
945
|
-
if (entry["days"] !== void 0 && !(Array.isArray(entry["days"]) && entry["days"].every((day) => typeof day === "string"))) problems.push(`${at}.days must be a list of days`);
|
|
946
|
-
if (entry["interruptible"] !== void 0 && typeof entry["interruptible"] !== "boolean") problems.push(`${at}.interruptible must be true or false`);
|
|
947
|
-
const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
|
|
915
|
+
//#region src/host/presets/service.ts
|
|
916
|
+
/** The story's prompts cannot change right now. */
|
|
917
|
+
var PresetBusyError = class extends Error {};
|
|
918
|
+
/** The preset library and the presets of stories. Refusals are plain `Error`s with the reason; unknown stories and worlds are not-found errors. */
|
|
919
|
+
var Presets = class {
|
|
920
|
+
deps;
|
|
921
|
+
constructor(deps) {
|
|
922
|
+
this.deps = deps;
|
|
923
|
+
}
|
|
924
|
+
get maxUploadBytes() {
|
|
925
|
+
return this.deps.maxUploadBytes;
|
|
926
|
+
}
|
|
927
|
+
list() {
|
|
928
|
+
return listPresets(this.deps.root()).map((entry) => entry.summary);
|
|
929
|
+
}
|
|
930
|
+
/** A preset with the text of each prompt it carries, keyed `<language>/<id>`. */
|
|
931
|
+
read(name) {
|
|
932
|
+
const loaded = loadPreset(this.deps.root(), name);
|
|
948
933
|
return {
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
from: text("from"),
|
|
952
|
-
to: text("to"),
|
|
953
|
-
activity: text("activity"),
|
|
954
|
-
...text("location") === "" ? {} : { location: text("location") },
|
|
955
|
-
...text("feature") === "" ? {} : { feature: text("feature") },
|
|
956
|
-
...text("position") === "" ? {} : { position: text("position") },
|
|
957
|
-
interruptible: entry["interruptible"] !== false
|
|
958
|
-
};
|
|
959
|
-
});
|
|
960
|
-
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
961
|
-
return windows;
|
|
962
|
-
}
|
|
963
|
-
const VARIABLE_FIELDS = [
|
|
964
|
-
"key",
|
|
965
|
-
"name",
|
|
966
|
-
"kind",
|
|
967
|
-
"subject",
|
|
968
|
-
"visibility",
|
|
969
|
-
"description",
|
|
970
|
-
"min",
|
|
971
|
-
"max",
|
|
972
|
-
"integer",
|
|
973
|
-
"baseline",
|
|
974
|
-
"always",
|
|
975
|
-
"default",
|
|
976
|
-
"only",
|
|
977
|
-
"options",
|
|
978
|
-
"bands"
|
|
979
|
-
];
|
|
980
|
-
/**
|
|
981
|
-
* The declarations as the browser sends them, with empty fields left out. Whether they are acceptable together is checked against the world's files.
|
|
982
|
-
* @throws {InvalidEditProblems} naming every field that has the wrong shape.
|
|
983
|
-
*/
|
|
984
|
-
function parseVariablesEdit(value) {
|
|
985
|
-
const problems = [];
|
|
986
|
-
const list = isObject(value) && Array.isArray(value["variables"]) ? value["variables"] : void 0;
|
|
987
|
-
if (list === void 0) throw new InvalidEditProblems(["the variables must be { variables: [...] }"]);
|
|
988
|
-
const declarations = list.flatMap((entry, index) => {
|
|
989
|
-
const at = `variables[${index}]`;
|
|
990
|
-
if (!isObject(entry)) {
|
|
991
|
-
problems.push(`${at} must be an object`);
|
|
992
|
-
return [];
|
|
993
|
-
}
|
|
994
|
-
for (const key of Object.keys(entry)) if (!VARIABLE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a variable`);
|
|
995
|
-
const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
|
|
996
|
-
const number = (key) => {
|
|
997
|
-
if (entry[key] === void 0 || entry[key] === null || entry[key] === "") return void 0;
|
|
998
|
-
if (typeof entry[key] !== "number" || !Number.isFinite(entry[key])) {
|
|
999
|
-
problems.push(`${at}.${key} must be a number`);
|
|
1000
|
-
return;
|
|
1001
|
-
}
|
|
1002
|
-
return entry[key];
|
|
1003
|
-
};
|
|
1004
|
-
const flag = (key) => {
|
|
1005
|
-
if (entry[key] === void 0) return void 0;
|
|
1006
|
-
if (typeof entry[key] !== "boolean") {
|
|
1007
|
-
problems.push(`${at}.${key} must be true or false`);
|
|
1008
|
-
return;
|
|
1009
|
-
}
|
|
1010
|
-
return entry[key];
|
|
1011
|
-
};
|
|
1012
|
-
const strings = (key) => {
|
|
1013
|
-
if (entry[key] === void 0) return [];
|
|
1014
|
-
if (!(Array.isArray(entry[key]) && entry[key].every((item) => typeof item === "string"))) {
|
|
1015
|
-
problems.push(`${at}.${key} must be a list of text`);
|
|
1016
|
-
return [];
|
|
1017
|
-
}
|
|
1018
|
-
return entry[key].map((item) => item.trim()).filter((item) => item !== "");
|
|
1019
|
-
};
|
|
1020
|
-
const bands = Array.isArray(entry["bands"]) ? entry["bands"].flatMap((band) => isObject(band) && typeof band["up_to"] === "number" && typeof band["label"] === "string" && band["label"].trim() !== "" ? [{
|
|
1021
|
-
up_to: band["up_to"],
|
|
1022
|
-
label: band["label"].trim()
|
|
1023
|
-
}] : (problems.push(`${at}.bands needs { up_to, label } entries`), [])) : [];
|
|
1024
|
-
const rawDefault = entry["default"];
|
|
1025
|
-
if (rawDefault !== void 0 && rawDefault !== null && rawDefault !== "" && typeof rawDefault !== "number" && typeof rawDefault !== "boolean" && typeof rawDefault !== "string") problems.push(`${at}.default must be a number, true or false, or text`);
|
|
1026
|
-
for (const [key, allowed] of [
|
|
1027
|
-
["kind", VARIABLE_KINDS],
|
|
1028
|
-
["subject", VARIABLE_SUBJECTS],
|
|
1029
|
-
["visibility", VARIABLE_VISIBILITIES]
|
|
1030
|
-
]) if (!allowed.includes(text(key))) problems.push(`${at}.${key} must be one of: ${allowed.join(", ")}`);
|
|
1031
|
-
const [min, max] = [number("min"), number("max")];
|
|
1032
|
-
const [integer, baseline, always] = [
|
|
1033
|
-
flag("integer"),
|
|
1034
|
-
flag("baseline"),
|
|
1035
|
-
flag("always")
|
|
1036
|
-
];
|
|
1037
|
-
const only = strings("only");
|
|
1038
|
-
const options = strings("options");
|
|
1039
|
-
return [{
|
|
1040
|
-
key: text("key"),
|
|
1041
|
-
name: text("name"),
|
|
1042
|
-
kind: text("kind"),
|
|
1043
|
-
subject: text("subject"),
|
|
1044
|
-
visibility: text("visibility"),
|
|
1045
|
-
...text("description") === "" ? {} : { description: text("description") },
|
|
1046
|
-
...min === void 0 ? {} : { min },
|
|
1047
|
-
...max === void 0 ? {} : { max },
|
|
1048
|
-
...integer === true ? { integer } : {},
|
|
1049
|
-
...baseline === true ? { baseline } : {},
|
|
1050
|
-
...always === true ? { always } : {},
|
|
1051
|
-
...rawDefault === void 0 || rawDefault === null || rawDefault === "" ? {} : { default: rawDefault },
|
|
1052
|
-
...only.length === 0 ? {} : { only },
|
|
1053
|
-
...options.length === 0 ? {} : { options },
|
|
1054
|
-
...bands.length === 0 ? {} : { bands }
|
|
1055
|
-
}];
|
|
1056
|
-
});
|
|
1057
|
-
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
1058
|
-
return declarations;
|
|
1059
|
-
}
|
|
1060
|
-
/**
|
|
1061
|
-
* The calendar as the browser sends it.
|
|
1062
|
-
* @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the days and ids are acceptable is checked as the file is read.
|
|
1063
|
-
*/
|
|
1064
|
-
function parseCalendarEdit(value) {
|
|
1065
|
-
const problems = [];
|
|
1066
|
-
if (!isObject(value)) throw new InvalidEditProblems(["the calendar must be { hemisphere, holidays: [...] }"]);
|
|
1067
|
-
if (value["hemisphere"] !== "north" && value["hemisphere"] !== "south") problems.push("hemisphere must be \"north\" or \"south\"");
|
|
1068
|
-
const list = Array.isArray(value["holidays"]) ? value["holidays"] : void 0;
|
|
1069
|
-
if (list === void 0) problems.push("holidays must be a list");
|
|
1070
|
-
const holidays = (list ?? []).map((entry, index) => {
|
|
1071
|
-
const at = `holidays[${index}]`;
|
|
1072
|
-
if (!isObject(entry)) {
|
|
1073
|
-
problems.push(`${at} must be an object`);
|
|
1074
|
-
return {
|
|
1075
|
-
id: "",
|
|
1076
|
-
name: "",
|
|
1077
|
-
on: []
|
|
1078
|
-
};
|
|
1079
|
-
}
|
|
1080
|
-
for (const key of Object.keys(entry)) if (![
|
|
1081
|
-
"id",
|
|
1082
|
-
"name",
|
|
1083
|
-
"on"
|
|
1084
|
-
].includes(key)) problems.push(`${at}.${key} is not a field of a holiday`);
|
|
1085
|
-
for (const key of ["id", "name"]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
1086
|
-
if (!(Array.isArray(entry["on"]) && entry["on"].every((day) => typeof day === "string"))) problems.push(`${at}.on must be a list of days`);
|
|
1087
|
-
return {
|
|
1088
|
-
id: typeof entry["id"] === "string" ? entry["id"].trim() : "",
|
|
1089
|
-
name: typeof entry["name"] === "string" ? entry["name"].trim() : "",
|
|
1090
|
-
on: Array.isArray(entry["on"]) ? entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") : []
|
|
1091
|
-
};
|
|
1092
|
-
});
|
|
1093
|
-
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
1094
|
-
return {
|
|
1095
|
-
hemisphere: value["hemisphere"],
|
|
1096
|
-
holidays
|
|
1097
|
-
};
|
|
1098
|
-
}
|
|
1099
|
-
//#endregion
|
|
1100
|
-
//#region src/host/worlds/starter.ts
|
|
1101
|
-
const STARTER_FOLDER = "starter-worlds";
|
|
1102
|
-
/** Names a starter world that the package does not ship. */
|
|
1103
|
-
var UnknownStarterError = class extends Error {};
|
|
1104
|
-
/** The folder of the worlds that ship with the package, found from this module so that it works from source and from the build. */
|
|
1105
|
-
function starterDirectory(from = dirname(fileURLToPath(import.meta.url))) {
|
|
1106
|
-
for (let directory = from;; directory = dirname(directory)) {
|
|
1107
|
-
const candidate = join(directory, STARTER_FOLDER);
|
|
1108
|
-
if (existsSync(join(directory, "package.json")) && existsSync(candidate)) return candidate;
|
|
1109
|
-
if (dirname(directory) === directory) throw new Error("the starter worlds shipped with the package were not found");
|
|
1110
|
-
}
|
|
1111
|
-
}
|
|
1112
|
-
async function shipped(directory) {
|
|
1113
|
-
const found = [];
|
|
1114
|
-
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
1115
|
-
if (!entry.isDirectory()) continue;
|
|
1116
|
-
const document = JSON.parse(await readFile(join(directory, entry.name, WORLD_FILE_NAME), "utf8"));
|
|
1117
|
-
if (typeof document.id !== "string" || typeof document.name !== "string") throw new Error(`the starter world "${entry.name}" has no id or name`);
|
|
1118
|
-
found.push({
|
|
1119
|
-
folder: entry.name,
|
|
1120
|
-
id: document.id,
|
|
1121
|
-
name: document.name,
|
|
1122
|
-
description: typeof document.description === "string" ? document.description : "",
|
|
1123
|
-
tags: Array.isArray(document.metadata?.tags) ? document.metadata.tags.filter((tag) => typeof tag === "string") : []
|
|
1124
|
-
});
|
|
1125
|
-
}
|
|
1126
|
-
return found.sort((a, b) => a.folder.localeCompare(b.folder));
|
|
1127
|
-
}
|
|
1128
|
-
/** The worlds the package ships, each with whether the person's worlds have it already. */
|
|
1129
|
-
async function listStarterWorlds(catalog, directory = starterDirectory()) {
|
|
1130
|
-
const known = await catalog.list();
|
|
1131
|
-
return (await shipped(directory)).map(({ id, ...world }) => ({
|
|
1132
|
-
...world,
|
|
1133
|
-
installed: known.worlds.some((existing) => existing.id === id) || existsSync(join(catalog.directory, world.folder))
|
|
1134
|
-
}));
|
|
1135
|
-
}
|
|
1136
|
-
/**
|
|
1137
|
-
* Copies a shipped world into the person's worlds, as a world of their own to play and edit, and makes the catalogue see it. Nothing is overwritten.
|
|
1138
|
-
* @throws {UnknownStarterError} when the package ships no such world.
|
|
1139
|
-
* @throws {WorldFolderExistsError} when the person already has that folder or a world with the same id.
|
|
1140
|
-
*/
|
|
1141
|
-
async function addStarterWorld(catalog, folder, directory = starterDirectory()) {
|
|
1142
|
-
const world = (await shipped(directory)).find((candidate) => candidate.folder === folder);
|
|
1143
|
-
if (world === void 0) throw new UnknownStarterError(`there is no starter world "${folder}"`);
|
|
1144
|
-
if ((await catalog.list({ refresh: true })).worlds.some((existing) => existing.id === world.id)) throw new WorldFolderExistsError(`you already have "${world.name}"`);
|
|
1145
|
-
const target = join(catalog.directory, world.folder);
|
|
1146
|
-
if (existsSync(target)) throw new WorldFolderExistsError(`a world folder named "${world.folder}" already exists`);
|
|
1147
|
-
await mkdir(catalog.directory, { recursive: true });
|
|
1148
|
-
try {
|
|
1149
|
-
await cp(join(directory, world.folder), target, {
|
|
1150
|
-
recursive: true,
|
|
1151
|
-
errorOnExist: true,
|
|
1152
|
-
force: false
|
|
1153
|
-
});
|
|
1154
|
-
} catch (error) {
|
|
1155
|
-
await rm(target, {
|
|
1156
|
-
recursive: true,
|
|
1157
|
-
force: true
|
|
1158
|
-
});
|
|
1159
|
-
throw error;
|
|
1160
|
-
}
|
|
1161
|
-
const added = (await catalog.list({ refresh: true })).worlds.find((candidate) => candidate.id === world.id);
|
|
1162
|
-
if (added === void 0) throw new Error(`added "${world.name}" but it was not found when the catalogue refreshed`);
|
|
1163
|
-
return added;
|
|
1164
|
-
}
|
|
1165
|
-
//#endregion
|
|
1166
|
-
//#region src/host/http/respond.ts
|
|
1167
|
-
function sendJson(res, status, payload) {
|
|
1168
|
-
res.statusCode = status;
|
|
1169
|
-
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
1170
|
-
res.setHeader("cache-control", "no-store");
|
|
1171
|
-
res.end(JSON.stringify(payload));
|
|
1172
|
-
}
|
|
1173
|
-
function sendError(res, status, message) {
|
|
1174
|
-
sendJson(res, status, { message });
|
|
1175
|
-
}
|
|
1176
|
-
/** A failure with the status the client should see. */
|
|
1177
|
-
var HttpError = class extends Error {
|
|
1178
|
-
status;
|
|
1179
|
-
constructor(status, message) {
|
|
1180
|
-
super(message);
|
|
1181
|
-
this.status = status;
|
|
1182
|
-
}
|
|
1183
|
-
};
|
|
1184
|
-
//#endregion
|
|
1185
|
-
//#region src/host/http/body.ts
|
|
1186
|
-
/** Request bodies here are small JSON objects; anything larger is not one. */
|
|
1187
|
-
const MAX_BODY_BYTES = 16384;
|
|
1188
|
-
/** Read a request body that must be a JSON object. */
|
|
1189
|
-
async function readJsonBody(req) {
|
|
1190
|
-
if (String(req.headers["content-type"] ?? "").split(";", 1)[0]?.trim().toLowerCase() !== "application/json") throw new HttpError(415, "content-type must be application/json");
|
|
1191
|
-
const chunks = [];
|
|
1192
|
-
let size = 0;
|
|
1193
|
-
for await (const chunk of req) {
|
|
1194
|
-
size += chunk.length;
|
|
1195
|
-
if (size > MAX_BODY_BYTES) throw new HttpError(413, "request body is too large");
|
|
1196
|
-
chunks.push(chunk);
|
|
1197
|
-
}
|
|
1198
|
-
let body;
|
|
1199
|
-
try {
|
|
1200
|
-
body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
1201
|
-
} catch {
|
|
1202
|
-
throw new HttpError(400, "request body is not valid JSON");
|
|
1203
|
-
}
|
|
1204
|
-
if (typeof body !== "object" || body === null || Array.isArray(body)) throw new HttpError(400, "request body must be a JSON object");
|
|
1205
|
-
return body;
|
|
1206
|
-
}
|
|
1207
|
-
/** Reads a request body of any kind up to `limit` bytes; a larger one is refused as soon as it is known to be, without being read. */
|
|
1208
|
-
async function readBinaryBody(req, limit) {
|
|
1209
|
-
const declared = Number(req.headers["content-length"]);
|
|
1210
|
-
if (Number.isFinite(declared) && declared > limit) throw new HttpError(413, `the upload is larger than ${Math.round(limit / 1024 / 1024)} MB`);
|
|
1211
|
-
const chunks = [];
|
|
1212
|
-
let size = 0;
|
|
1213
|
-
for await (const chunk of req) {
|
|
1214
|
-
size += chunk.length;
|
|
1215
|
-
if (size > limit) throw new HttpError(413, `the upload is larger than ${Math.round(limit / 1024 / 1024)} MB`);
|
|
1216
|
-
chunks.push(chunk);
|
|
1217
|
-
}
|
|
1218
|
-
if (size === 0) throw new HttpError(400, "the upload is empty");
|
|
1219
|
-
return Buffer.concat(chunks);
|
|
1220
|
-
}
|
|
1221
|
-
//#endregion
|
|
1222
|
-
//#region src/host/presets/service.ts
|
|
1223
|
-
/** The story's prompts cannot change right now. */
|
|
1224
|
-
var PresetBusyError = class extends Error {};
|
|
1225
|
-
/** The preset library and the presets of stories. Refusals are plain `Error`s with the reason; unknown stories and worlds are not-found errors. */
|
|
1226
|
-
var Presets = class {
|
|
1227
|
-
deps;
|
|
1228
|
-
constructor(deps) {
|
|
1229
|
-
this.deps = deps;
|
|
1230
|
-
}
|
|
1231
|
-
get maxUploadBytes() {
|
|
1232
|
-
return this.deps.maxUploadBytes;
|
|
1233
|
-
}
|
|
1234
|
-
list() {
|
|
1235
|
-
return listPresets(this.deps.root()).map((entry) => entry.summary);
|
|
1236
|
-
}
|
|
1237
|
-
/** A preset with the text of each prompt it carries, keyed `<language>/<id>`. */
|
|
1238
|
-
read(name) {
|
|
1239
|
-
const loaded = loadPreset(this.deps.root(), name);
|
|
1240
|
-
return {
|
|
1241
|
-
summary: loaded.summary,
|
|
1242
|
-
prompts: Object.fromEntries([...loaded.files].map(([path, text]) => [path.slice(0, -3), text]))
|
|
934
|
+
summary: loaded.summary,
|
|
935
|
+
prompts: Object.fromEntries([...loaded.files].map(([path, text]) => [path.slice(0, -3), text]))
|
|
1243
936
|
};
|
|
1244
937
|
}
|
|
1245
938
|
async saveFromWorld(request) {
|
|
@@ -1368,15 +1061,52 @@ var Presets = class {
|
|
|
1368
1061
|
}
|
|
1369
1062
|
};
|
|
1370
1063
|
//#endregion
|
|
1371
|
-
//#region src/host/
|
|
1372
|
-
/**
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
if (
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1064
|
+
//#region src/host/http/body.ts
|
|
1065
|
+
/** Request bodies here are small JSON objects; anything larger is not one. */
|
|
1066
|
+
const MAX_BODY_BYTES = 16384;
|
|
1067
|
+
/** Read a request body that must be a JSON object. */
|
|
1068
|
+
async function readJsonBody(req) {
|
|
1069
|
+
if (String(req.headers["content-type"] ?? "").split(";", 1)[0]?.trim().toLowerCase() !== "application/json") throw new HttpError(415, "content-type must be application/json");
|
|
1070
|
+
const chunks = [];
|
|
1071
|
+
let size = 0;
|
|
1072
|
+
for await (const chunk of req) {
|
|
1073
|
+
size += chunk.length;
|
|
1074
|
+
if (size > MAX_BODY_BYTES) throw new HttpError(413, "request body is too large");
|
|
1075
|
+
chunks.push(chunk);
|
|
1076
|
+
}
|
|
1077
|
+
let body;
|
|
1078
|
+
try {
|
|
1079
|
+
body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
1080
|
+
} catch {
|
|
1081
|
+
throw new HttpError(400, "request body is not valid JSON");
|
|
1082
|
+
}
|
|
1083
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) throw new HttpError(400, "request body must be a JSON object");
|
|
1084
|
+
return body;
|
|
1085
|
+
}
|
|
1086
|
+
/** Reads a request body of any kind up to `limit` bytes; a larger one is refused as soon as it is known to be, without being read. */
|
|
1087
|
+
async function readBinaryBody(req, limit) {
|
|
1088
|
+
const declared = Number(req.headers["content-length"]);
|
|
1089
|
+
if (Number.isFinite(declared) && declared > limit) throw new HttpError(413, `the upload is larger than ${Math.round(limit / 1024 / 1024)} MB`);
|
|
1090
|
+
const chunks = [];
|
|
1091
|
+
let size = 0;
|
|
1092
|
+
for await (const chunk of req) {
|
|
1093
|
+
size += chunk.length;
|
|
1094
|
+
if (size > limit) throw new HttpError(413, `the upload is larger than ${Math.round(limit / 1024 / 1024)} MB`);
|
|
1095
|
+
chunks.push(chunk);
|
|
1096
|
+
}
|
|
1097
|
+
if (size === 0) throw new HttpError(400, "the upload is empty");
|
|
1098
|
+
return Buffer.concat(chunks);
|
|
1099
|
+
}
|
|
1100
|
+
//#endregion
|
|
1101
|
+
//#region src/host/presets/routes.ts
|
|
1102
|
+
/** Not found is 404 and a request the library refuses is 422 with its reason; anything else is a fault. */
|
|
1103
|
+
function failure$2(res, error) {
|
|
1104
|
+
if (error instanceof ImportNotFoundError) return sendError(res, 404, error.message);
|
|
1105
|
+
if (error instanceof SessionNotFoundError || error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
1106
|
+
if (error instanceof PresetBusyError) return sendError(res, 409, error.message);
|
|
1107
|
+
if (error instanceof Error) return sendError(res, 422, error.message);
|
|
1108
|
+
throw error;
|
|
1109
|
+
}
|
|
1380
1110
|
function samplingOf(value) {
|
|
1381
1111
|
const problems = [];
|
|
1382
1112
|
const sampling = parseSampling(value, "sampling", problems);
|
|
@@ -1739,20 +1469,6 @@ function lorebookRoutes(api) {
|
|
|
1739
1469
|
};
|
|
1740
1470
|
}
|
|
1741
1471
|
//#endregion
|
|
1742
|
-
//#region src/host/sync/errors.ts
|
|
1743
|
-
/** A run, or a choice, cannot be made now. */
|
|
1744
|
-
var SyncRefusedError = class extends Error {};
|
|
1745
|
-
/** rclone could not be started or reported a failure. */
|
|
1746
|
-
var RcloneError = class extends Error {
|
|
1747
|
-
code;
|
|
1748
|
-
constructor(message, code) {
|
|
1749
|
-
super(message);
|
|
1750
|
-
this.code = code;
|
|
1751
|
-
}
|
|
1752
|
-
};
|
|
1753
|
-
/** The unit is being synced: nothing may write to it or read from it until the run is over. */
|
|
1754
|
-
var UnitLockedError = class extends Error {};
|
|
1755
|
-
//#endregion
|
|
1756
1472
|
//#region src/shared/catalogue.ts
|
|
1757
1473
|
/** What a credential reference is: letters, digits and `_`, not starting with a digit (DSH's grammar). */
|
|
1758
1474
|
const CREDENTIAL_REF = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
@@ -1769,6 +1485,20 @@ const CATALOGUE_PRESET_TYPE = "sillytavern/preset";
|
|
|
1769
1485
|
const CATALOGUE_LOREBOOK_TYPE = "sillytavern/lorebook";
|
|
1770
1486
|
const CATALOGUE_WORLD_TYPE = "dsh-agentic-roleplay/world";
|
|
1771
1487
|
//#endregion
|
|
1488
|
+
//#region src/host/sync/errors.ts
|
|
1489
|
+
/** A run, or a choice, cannot be made now. */
|
|
1490
|
+
var SyncRefusedError = class extends Error {};
|
|
1491
|
+
/** rclone could not be started or reported a failure. */
|
|
1492
|
+
var RcloneError = class extends Error {
|
|
1493
|
+
code;
|
|
1494
|
+
constructor(message, code) {
|
|
1495
|
+
super(message);
|
|
1496
|
+
this.code = code;
|
|
1497
|
+
}
|
|
1498
|
+
};
|
|
1499
|
+
/** The unit is being synced: nothing may write to it or read from it until the run is over. */
|
|
1500
|
+
var UnitLockedError = class extends Error {};
|
|
1501
|
+
//#endregion
|
|
1772
1502
|
//#region src/host/sync/routes.ts
|
|
1773
1503
|
function failure(res, error) {
|
|
1774
1504
|
if (error instanceof UnitLockedError) return sendError(res, 423, error.message);
|
|
@@ -2575,7 +2305,97 @@ async function sendPackFile(api, path, res) {
|
|
|
2575
2305
|
await pipeline(createReadStream(file.file), res);
|
|
2576
2306
|
}
|
|
2577
2307
|
//#endregion
|
|
2578
|
-
//#region src/host/http/
|
|
2308
|
+
//#region src/host/http/routes/speech.ts
|
|
2309
|
+
/** The routes of the API for speech. */
|
|
2310
|
+
function speechRoutes({ speech }) {
|
|
2311
|
+
return {
|
|
2312
|
+
"/speech/capabilities": { GET: async (_req, res) => {
|
|
2313
|
+
sendJson(res, 200, { streaming: speech.streaming() });
|
|
2314
|
+
} },
|
|
2315
|
+
"/speech/voices": { GET: async (_req, res) => {
|
|
2316
|
+
sendJson(res, 200, await speech.voices());
|
|
2317
|
+
} },
|
|
2318
|
+
"/speech/synthesize": { POST: async (req, res) => {
|
|
2319
|
+
const body = await readJsonBody(req);
|
|
2320
|
+
if (!Array.isArray(body.parts)) return sendError(res, 400, "parts must be a list");
|
|
2321
|
+
const parts = body.parts.filter((part) => typeof part === "object" && part !== null && typeof part.text === "string");
|
|
2322
|
+
if (parts.length !== body.parts.length) return sendError(res, 400, "each speech part needs text");
|
|
2323
|
+
const audio = await speech.speak(parts);
|
|
2324
|
+
res.statusCode = 200;
|
|
2325
|
+
res.setHeader("content-type", audio.mediaType);
|
|
2326
|
+
res.setHeader("content-length", audio.bytes.length);
|
|
2327
|
+
res.end(audio.bytes);
|
|
2328
|
+
} }
|
|
2329
|
+
};
|
|
2330
|
+
}
|
|
2331
|
+
//#endregion
|
|
2332
|
+
//#region src/host/worlds/starter.ts
|
|
2333
|
+
const STARTER_FOLDER = "starter-worlds";
|
|
2334
|
+
/** Names a starter world that the package does not ship. */
|
|
2335
|
+
var UnknownStarterError = class extends Error {};
|
|
2336
|
+
/** The folder of the worlds that ship with the package, found from this module so that it works from source and from the build. */
|
|
2337
|
+
function starterDirectory(from = dirname(fileURLToPath(import.meta.url))) {
|
|
2338
|
+
for (let directory = from;; directory = dirname(directory)) {
|
|
2339
|
+
const candidate = join(directory, STARTER_FOLDER);
|
|
2340
|
+
if (existsSync(join(directory, "package.json")) && existsSync(candidate)) return candidate;
|
|
2341
|
+
if (dirname(directory) === directory) throw new Error("the starter worlds shipped with the package were not found");
|
|
2342
|
+
}
|
|
2343
|
+
}
|
|
2344
|
+
async function shipped(directory) {
|
|
2345
|
+
const found = [];
|
|
2346
|
+
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
2347
|
+
if (!entry.isDirectory()) continue;
|
|
2348
|
+
const document = JSON.parse(await readFile(join(directory, entry.name, WORLD_FILE_NAME), "utf8"));
|
|
2349
|
+
if (typeof document.id !== "string" || typeof document.name !== "string") throw new Error(`the starter world "${entry.name}" has no id or name`);
|
|
2350
|
+
found.push({
|
|
2351
|
+
folder: entry.name,
|
|
2352
|
+
id: document.id,
|
|
2353
|
+
name: document.name,
|
|
2354
|
+
description: typeof document.description === "string" ? document.description : "",
|
|
2355
|
+
tags: Array.isArray(document.metadata?.tags) ? document.metadata.tags.filter((tag) => typeof tag === "string") : []
|
|
2356
|
+
});
|
|
2357
|
+
}
|
|
2358
|
+
return found.sort((a, b) => a.folder.localeCompare(b.folder));
|
|
2359
|
+
}
|
|
2360
|
+
/** The worlds the package ships, each with whether the person's worlds have it already. */
|
|
2361
|
+
async function listStarterWorlds(catalog, directory = starterDirectory()) {
|
|
2362
|
+
const known = await catalog.list();
|
|
2363
|
+
return (await shipped(directory)).map(({ id, ...world }) => ({
|
|
2364
|
+
...world,
|
|
2365
|
+
installed: known.worlds.some((existing) => existing.id === id) || existsSync(join(catalog.directory, world.folder))
|
|
2366
|
+
}));
|
|
2367
|
+
}
|
|
2368
|
+
/**
|
|
2369
|
+
* Copies a shipped world into the person's worlds, as a world of their own to play and edit, and makes the catalogue see it. Nothing is overwritten.
|
|
2370
|
+
* @throws {UnknownStarterError} when the package ships no such world.
|
|
2371
|
+
* @throws {WorldFolderExistsError} when the person already has that folder or a world with the same id.
|
|
2372
|
+
*/
|
|
2373
|
+
async function addStarterWorld(catalog, folder, directory = starterDirectory()) {
|
|
2374
|
+
const world = (await shipped(directory)).find((candidate) => candidate.folder === folder);
|
|
2375
|
+
if (world === void 0) throw new UnknownStarterError(`there is no starter world "${folder}"`);
|
|
2376
|
+
if ((await catalog.list({ refresh: true })).worlds.some((existing) => existing.id === world.id)) throw new WorldFolderExistsError(`you already have "${world.name}"`);
|
|
2377
|
+
const target = join(catalog.directory, world.folder);
|
|
2378
|
+
if (existsSync(target)) throw new WorldFolderExistsError(`a world folder named "${world.folder}" already exists`);
|
|
2379
|
+
await mkdir(catalog.directory, { recursive: true });
|
|
2380
|
+
try {
|
|
2381
|
+
await cp(join(directory, world.folder), target, {
|
|
2382
|
+
recursive: true,
|
|
2383
|
+
errorOnExist: true,
|
|
2384
|
+
force: false
|
|
2385
|
+
});
|
|
2386
|
+
} catch (error) {
|
|
2387
|
+
await rm(target, {
|
|
2388
|
+
recursive: true,
|
|
2389
|
+
force: true
|
|
2390
|
+
});
|
|
2391
|
+
throw error;
|
|
2392
|
+
}
|
|
2393
|
+
const added = (await catalog.list({ refresh: true })).worlds.find((candidate) => candidate.id === world.id);
|
|
2394
|
+
if (added === void 0) throw new Error(`added "${world.name}" but it was not found when the catalogue refreshed`);
|
|
2395
|
+
return added;
|
|
2396
|
+
}
|
|
2397
|
+
//#endregion
|
|
2398
|
+
//#region src/host/http/routes/shared.ts
|
|
2579
2399
|
/** The largest picture that can be added to a gallery. */
|
|
2580
2400
|
const MAX_UPLOAD_BYTES = 20971520;
|
|
2581
2401
|
/** The changes to a picture's metadata a body asks for, or what is wrong with it. */
|
|
@@ -2635,7 +2455,6 @@ function importFailure(res, error) {
|
|
|
2635
2455
|
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
2636
2456
|
throw error;
|
|
2637
2457
|
}
|
|
2638
|
-
/** Build the request handler mounted at `/${API_PREFIX}`. */
|
|
2639
2458
|
/** The language a client says it is using, or nothing when it says none. */
|
|
2640
2459
|
function languageField(value) {
|
|
2641
2460
|
if (value === void 0) return void 0;
|
|
@@ -2646,25 +2465,11 @@ function languageField(value) {
|
|
|
2646
2465
|
throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
|
|
2647
2466
|
}
|
|
2648
2467
|
}
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
"/speech/voices": { GET: async (_req, res) => {
|
|
2655
|
-
sendJson(res, 200, await speech.voices());
|
|
2656
|
-
} },
|
|
2657
|
-
"/speech/synthesize": { POST: async (req, res) => {
|
|
2658
|
-
const body = await readJsonBody(req);
|
|
2659
|
-
if (!Array.isArray(body.parts)) return sendError(res, 400, "parts must be a list");
|
|
2660
|
-
const parts = body.parts.filter((part) => typeof part === "object" && part !== null && typeof part.text === "string");
|
|
2661
|
-
if (parts.length !== body.parts.length) return sendError(res, 400, "each speech part needs text");
|
|
2662
|
-
const audio = await speech.speak(parts);
|
|
2663
|
-
res.statusCode = 200;
|
|
2664
|
-
res.setHeader("content-type", audio.mediaType);
|
|
2665
|
-
res.setHeader("content-length", audio.bytes.length);
|
|
2666
|
-
res.end(audio.bytes);
|
|
2667
|
-
} },
|
|
2468
|
+
//#endregion
|
|
2469
|
+
//#region src/host/http/routes/worlds.ts
|
|
2470
|
+
/** The routes of the API for worlds. */
|
|
2471
|
+
function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, avatars }) {
|
|
2472
|
+
return {
|
|
2668
2473
|
"/worlds": {
|
|
2669
2474
|
GET: async (_req, res) => {
|
|
2670
2475
|
sendJson(res, 200, await worlds.list());
|
|
@@ -2689,65 +2494,185 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
2689
2494
|
}
|
|
2690
2495
|
}
|
|
2691
2496
|
},
|
|
2692
|
-
"/
|
|
2693
|
-
|
|
2694
|
-
sendJson(res, 200, await
|
|
2695
|
-
} catch (error) {
|
|
2696
|
-
return catalogueFailure(res, error);
|
|
2697
|
-
}
|
|
2698
|
-
} },
|
|
2699
|
-
"/catalogue/key": {
|
|
2700
|
-
GET: async (_req, res, url) => {
|
|
2701
|
-
try {
|
|
2702
|
-
sendJson(res, 200, await catalogue.describeKey(url.searchParams.get("ref") ?? ""));
|
|
2703
|
-
} catch (error) {
|
|
2704
|
-
return catalogueFailure(res, error);
|
|
2705
|
-
}
|
|
2497
|
+
"/worlds/starter": {
|
|
2498
|
+
GET: async (_req, res) => {
|
|
2499
|
+
sendJson(res, 200, await starter.list());
|
|
2706
2500
|
},
|
|
2707
|
-
|
|
2708
|
-
const
|
|
2709
|
-
if (typeof
|
|
2501
|
+
POST: async (req, res) => {
|
|
2502
|
+
const body = await readJsonBody(req);
|
|
2503
|
+
if (typeof body.folder !== "string") return sendError(res, 400, "folder must be text");
|
|
2710
2504
|
try {
|
|
2711
|
-
sendJson(res,
|
|
2505
|
+
sendJson(res, 201, await starter.add(body.folder));
|
|
2712
2506
|
} catch (error) {
|
|
2713
|
-
return
|
|
2507
|
+
if (error instanceof UnknownStarterError) return sendError(res, 404, error.message);
|
|
2508
|
+
if (error instanceof WorldFolderExistsError) return sendError(res, 409, error.message);
|
|
2509
|
+
throw error;
|
|
2714
2510
|
}
|
|
2715
2511
|
}
|
|
2716
2512
|
},
|
|
2717
|
-
"/
|
|
2718
|
-
|
|
2719
|
-
|
|
2513
|
+
"/worlds/refresh": { POST: async (_req, res) => {
|
|
2514
|
+
sendJson(res, 200, await worlds.list({ refresh: true }));
|
|
2515
|
+
} },
|
|
2516
|
+
"/worlds/authoring": { POST: async (req, res, url) => {
|
|
2517
|
+
const body = await readJsonBody(req);
|
|
2518
|
+
if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
|
|
2720
2519
|
try {
|
|
2721
|
-
sendJson(res, 200, await
|
|
2722
|
-
kind: [
|
|
2723
|
-
"card",
|
|
2724
|
-
"preset",
|
|
2725
|
-
"lorebook"
|
|
2726
|
-
].find((entry) => entry === url.searchParams.get("kind")) ?? "world",
|
|
2727
|
-
search: url.searchParams.get("search") ?? "",
|
|
2728
|
-
offset: Number.isFinite(offset) ? offset : 0,
|
|
2729
|
-
sort
|
|
2730
|
-
}));
|
|
2520
|
+
sendJson(res, 200, await authorWorld(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language)));
|
|
2731
2521
|
} catch (error) {
|
|
2732
|
-
return
|
|
2522
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
2523
|
+
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
2524
|
+
throw error;
|
|
2733
2525
|
}
|
|
2734
2526
|
} },
|
|
2735
|
-
"/
|
|
2527
|
+
"/worlds/language": { GET: async (_req, res, url) => {
|
|
2736
2528
|
try {
|
|
2737
|
-
sendJson(res, 200, await
|
|
2529
|
+
sendJson(res, 200, { language: await translation.language(url.searchParams.get("id") ?? "") ?? null });
|
|
2738
2530
|
} catch (error) {
|
|
2739
|
-
return
|
|
2531
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
2532
|
+
throw error;
|
|
2740
2533
|
}
|
|
2741
2534
|
} },
|
|
2742
|
-
"/
|
|
2535
|
+
"/worlds/translate": { POST: async (req, res, url) => {
|
|
2536
|
+
const body = await readJsonBody(req);
|
|
2537
|
+
if (body.to !== "en" && body.to !== "zh") return sendError(res, 400, "to must be \"en\" or \"zh\"");
|
|
2538
|
+
if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
|
|
2743
2539
|
try {
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
res
|
|
2747
|
-
res
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2540
|
+
sendJson(res, 200, await translation.start(url.searchParams.get("id") ?? "", body.to, body.title.trim(), languageField(body.language) ?? "en"));
|
|
2541
|
+
} catch (error) {
|
|
2542
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
2543
|
+
if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
|
|
2544
|
+
message: error.message,
|
|
2545
|
+
problems: error.problems
|
|
2546
|
+
});
|
|
2547
|
+
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
2548
|
+
throw error;
|
|
2549
|
+
}
|
|
2550
|
+
} },
|
|
2551
|
+
"/avatars": {
|
|
2552
|
+
POST: async (req, res) => {
|
|
2553
|
+
const body = await readJsonBody(req);
|
|
2554
|
+
if (typeof body.name !== "string" || body.name.trim() === "") return sendError(res, 400, "name must be text");
|
|
2555
|
+
try {
|
|
2556
|
+
sendJson(res, 201, { key: await avatars.create(body.name) });
|
|
2557
|
+
} catch (error) {
|
|
2558
|
+
if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
|
|
2559
|
+
message: error.message,
|
|
2560
|
+
problems: error.problems
|
|
2561
|
+
});
|
|
2562
|
+
throw error;
|
|
2563
|
+
}
|
|
2564
|
+
},
|
|
2565
|
+
DELETE: async (_req, res, url) => {
|
|
2566
|
+
try {
|
|
2567
|
+
await avatars.remove(url.searchParams.get("key") ?? "");
|
|
2568
|
+
sendJson(res, 200, { deleted: true });
|
|
2569
|
+
} catch (error) {
|
|
2570
|
+
if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
|
|
2571
|
+
message: error.message,
|
|
2572
|
+
problems: error.problems
|
|
2573
|
+
});
|
|
2574
|
+
throw error;
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2577
|
+
},
|
|
2578
|
+
"/worlds/avatars": { POST: async (req, res, url) => {
|
|
2579
|
+
const body = await readJsonBody(req);
|
|
2580
|
+
if (!Array.isArray(body.avatars) || body.avatars.length === 0 || !body.avatars.every((key) => typeof key === "string")) return sendError(res, 400, "avatars must be a list of keys");
|
|
2581
|
+
try {
|
|
2582
|
+
sendJson(res, 200, { added: await avatars.addToWorld(url.searchParams.get("id") ?? "", body.avatars) });
|
|
2583
|
+
} catch (error) {
|
|
2584
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
2585
|
+
if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
|
|
2586
|
+
message: error.message,
|
|
2587
|
+
problems: error.problems
|
|
2588
|
+
});
|
|
2589
|
+
throw error;
|
|
2590
|
+
}
|
|
2591
|
+
} },
|
|
2592
|
+
"/worlds/characters": { GET: async (_req, res, url) => {
|
|
2593
|
+
try {
|
|
2594
|
+
sendJson(res, 200, await worldCharacters(url.searchParams.get("id") ?? ""));
|
|
2595
|
+
} catch (error) {
|
|
2596
|
+
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
2597
|
+
throw error;
|
|
2598
|
+
}
|
|
2599
|
+
} },
|
|
2600
|
+
"/worlds/cover": { GET: async (_req, res, url) => {
|
|
2601
|
+
const cover = await worlds.cover(url.searchParams.get("id") ?? "");
|
|
2602
|
+
if (cover === void 0) return sendError(res, 404, "no cover");
|
|
2603
|
+
res.statusCode = 200;
|
|
2604
|
+
res.setHeader("content-type", cover.contentType);
|
|
2605
|
+
res.setHeader("content-length", cover.size);
|
|
2606
|
+
res.setHeader("x-content-type-options", "nosniff");
|
|
2607
|
+
res.setHeader("cache-control", cover.version === url.searchParams.get("v") ? "private, max-age=31536000, immutable" : "no-cache");
|
|
2608
|
+
await pipeline(createReadStream(cover.file), res);
|
|
2609
|
+
} }
|
|
2610
|
+
};
|
|
2611
|
+
}
|
|
2612
|
+
//#endregion
|
|
2613
|
+
//#region src/host/http/routes/catalogue.ts
|
|
2614
|
+
/** The routes of the API for catalogue. */
|
|
2615
|
+
function catalogueRoutes({ catalogue }) {
|
|
2616
|
+
return {
|
|
2617
|
+
"/catalogue/sources": { GET: async (_req, res) => {
|
|
2618
|
+
try {
|
|
2619
|
+
sendJson(res, 200, await catalogue.sources());
|
|
2620
|
+
} catch (error) {
|
|
2621
|
+
return catalogueFailure(res, error);
|
|
2622
|
+
}
|
|
2623
|
+
} },
|
|
2624
|
+
"/catalogue/key": {
|
|
2625
|
+
GET: async (_req, res, url) => {
|
|
2626
|
+
try {
|
|
2627
|
+
sendJson(res, 200, await catalogue.describeKey(url.searchParams.get("ref") ?? ""));
|
|
2628
|
+
} catch (error) {
|
|
2629
|
+
return catalogueFailure(res, error);
|
|
2630
|
+
}
|
|
2631
|
+
},
|
|
2632
|
+
PUT: async (req, res) => {
|
|
2633
|
+
const { ref, value } = await readJsonBody(req);
|
|
2634
|
+
if (typeof ref !== "string" || typeof value !== "string") return sendError(res, 400, "\"ref\" and \"value\" must be text");
|
|
2635
|
+
try {
|
|
2636
|
+
sendJson(res, 200, await catalogue.keepKey(ref, value));
|
|
2637
|
+
} catch (error) {
|
|
2638
|
+
return catalogueFailure(res, error);
|
|
2639
|
+
}
|
|
2640
|
+
}
|
|
2641
|
+
},
|
|
2642
|
+
"/catalogue/worlds": { GET: async (_req, res, url) => {
|
|
2643
|
+
const offset = Number(url.searchParams.get("offset") ?? 0);
|
|
2644
|
+
const sort = url.searchParams.get("sort") === "popular" ? "popular" : "recent";
|
|
2645
|
+
try {
|
|
2646
|
+
sendJson(res, 200, await catalogue.worlds(url.searchParams.get("source") ?? "", {
|
|
2647
|
+
kind: [
|
|
2648
|
+
"card",
|
|
2649
|
+
"preset",
|
|
2650
|
+
"lorebook"
|
|
2651
|
+
].find((entry) => entry === url.searchParams.get("kind")) ?? "world",
|
|
2652
|
+
search: url.searchParams.get("search") ?? "",
|
|
2653
|
+
offset: Number.isFinite(offset) ? offset : 0,
|
|
2654
|
+
sort
|
|
2655
|
+
}));
|
|
2656
|
+
} catch (error) {
|
|
2657
|
+
return catalogueFailure(res, error);
|
|
2658
|
+
}
|
|
2659
|
+
} },
|
|
2660
|
+
"/catalogue/world": { GET: async (_req, res, url) => {
|
|
2661
|
+
try {
|
|
2662
|
+
sendJson(res, 200, await catalogue.world(url.searchParams.get("source") ?? "", url.searchParams.get("id") ?? ""));
|
|
2663
|
+
} catch (error) {
|
|
2664
|
+
return catalogueFailure(res, error);
|
|
2665
|
+
}
|
|
2666
|
+
} },
|
|
2667
|
+
"/catalogue/cover": { GET: async (_req, res, url) => {
|
|
2668
|
+
try {
|
|
2669
|
+
const cover = await catalogue.cover(url.searchParams.get("source") ?? "", url.searchParams.get("id") ?? "");
|
|
2670
|
+
res.statusCode = 200;
|
|
2671
|
+
res.setHeader("content-type", cover.type);
|
|
2672
|
+
res.setHeader("content-length", cover.body.length);
|
|
2673
|
+
res.setHeader("x-content-type-options", "nosniff");
|
|
2674
|
+
res.setHeader("cache-control", "private, no-cache");
|
|
2675
|
+
res.end(cover.body);
|
|
2751
2676
|
} catch (error) {
|
|
2752
2677
|
return catalogueFailure(res, error);
|
|
2753
2678
|
}
|
|
@@ -2865,23 +2790,14 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
2865
2790
|
} catch (error) {
|
|
2866
2791
|
return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
|
|
2867
2792
|
}
|
|
2868
|
-
} }
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
|
|
2876
|
-
try {
|
|
2877
|
-
sendJson(res, 201, await starter.add(body.folder));
|
|
2878
|
-
} catch (error) {
|
|
2879
|
-
if (error instanceof UnknownStarterError) return sendError(res, 404, error.message);
|
|
2880
|
-
if (error instanceof WorldFolderExistsError) return sendError(res, 409, error.message);
|
|
2881
|
-
throw error;
|
|
2882
|
-
}
|
|
2883
|
-
}
|
|
2884
|
-
},
|
|
2793
|
+
} }
|
|
2794
|
+
};
|
|
2795
|
+
}
|
|
2796
|
+
//#endregion
|
|
2797
|
+
//#region src/host/http/routes/imports.ts
|
|
2798
|
+
/** The routes of the API for imports. */
|
|
2799
|
+
function importsRoutes({ importer }) {
|
|
2800
|
+
return {
|
|
2885
2801
|
"/worlds/import/card": { POST: async (req, res, url) => {
|
|
2886
2802
|
const name = decodeURIComponent(String(req.headers["x-file-name"] ?? url.searchParams.get("name") ?? "card"));
|
|
2887
2803
|
try {
|
|
@@ -2993,92 +2909,335 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
2993
2909
|
return importFailure(res, error);
|
|
2994
2910
|
}
|
|
2995
2911
|
} },
|
|
2996
|
-
"/worlds/import/
|
|
2997
|
-
|
|
2998
|
-
await sendImage(res, await importer.picture(url.searchParams.get("id") ?? ""));
|
|
2999
|
-
} catch (error) {
|
|
3000
|
-
return sendError(res, 404, error instanceof Error ? error.message : String(error));
|
|
3001
|
-
}
|
|
3002
|
-
} },
|
|
3003
|
-
"/worlds/refresh": { POST: async (_req, res) => {
|
|
3004
|
-
sendJson(res, 200, await worlds.list({ refresh: true }));
|
|
3005
|
-
} },
|
|
3006
|
-
"/worlds/authoring": { POST: async (req, res, url) => {
|
|
3007
|
-
const body = await readJsonBody(req);
|
|
3008
|
-
if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
|
|
3009
|
-
try {
|
|
3010
|
-
sendJson(res, 200, await authorWorld(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language)));
|
|
3011
|
-
} catch (error) {
|
|
3012
|
-
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
3013
|
-
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
3014
|
-
throw error;
|
|
3015
|
-
}
|
|
3016
|
-
} },
|
|
3017
|
-
"/worlds/language": { GET: async (_req, res, url) => {
|
|
3018
|
-
try {
|
|
3019
|
-
sendJson(res, 200, { language: await translation.language(url.searchParams.get("id") ?? "") ?? null });
|
|
3020
|
-
} catch (error) {
|
|
3021
|
-
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
3022
|
-
throw error;
|
|
3023
|
-
}
|
|
3024
|
-
} },
|
|
3025
|
-
"/worlds/translate": { POST: async (req, res, url) => {
|
|
3026
|
-
const body = await readJsonBody(req);
|
|
3027
|
-
if (body.to !== "en" && body.to !== "zh") return sendError(res, 400, "to must be \"en\" or \"zh\"");
|
|
3028
|
-
if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
|
|
3029
|
-
try {
|
|
3030
|
-
sendJson(res, 200, await translation.start(url.searchParams.get("id") ?? "", body.to, body.title.trim(), languageField(body.language) ?? "en"));
|
|
3031
|
-
} catch (error) {
|
|
3032
|
-
if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
|
|
3033
|
-
if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
|
|
3034
|
-
message: error.message,
|
|
3035
|
-
problems: error.problems
|
|
3036
|
-
});
|
|
3037
|
-
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
3038
|
-
throw error;
|
|
3039
|
-
}
|
|
3040
|
-
} },
|
|
3041
|
-
"/avatars": {
|
|
3042
|
-
POST: async (req, res) => {
|
|
3043
|
-
const body = await readJsonBody(req);
|
|
3044
|
-
if (typeof body.name !== "string" || body.name.trim() === "") return sendError(res, 400, "name must be text");
|
|
2912
|
+
"/worlds/import/draft": {
|
|
2913
|
+
GET: async (_req, res, url) => {
|
|
3045
2914
|
try {
|
|
3046
|
-
sendJson(res,
|
|
2915
|
+
sendJson(res, 200, await importer.draftStatus(url.searchParams.get("id") ?? ""));
|
|
3047
2916
|
} catch (error) {
|
|
3048
|
-
|
|
3049
|
-
message: error.message,
|
|
3050
|
-
problems: error.problems
|
|
3051
|
-
});
|
|
3052
|
-
throw error;
|
|
2917
|
+
return importFailure(res, error);
|
|
3053
2918
|
}
|
|
3054
2919
|
},
|
|
3055
|
-
|
|
2920
|
+
POST: async (req, res, url) => {
|
|
3056
2921
|
try {
|
|
3057
|
-
await
|
|
3058
|
-
|
|
2922
|
+
const body = await readJsonBody(req);
|
|
2923
|
+
if (body.action !== "ask" && body.action !== "keep" && body.action !== "discard") return sendError(res, 400, "\"action\" must be ask, keep or discard");
|
|
2924
|
+
sendJson(res, 200, await importer.actOnDraft(url.searchParams.get("id") ?? "", body.action, languageField(body.language)));
|
|
3059
2925
|
} catch (error) {
|
|
3060
|
-
|
|
3061
|
-
message: error.message,
|
|
3062
|
-
problems: error.problems
|
|
3063
|
-
});
|
|
3064
|
-
throw error;
|
|
2926
|
+
return importFailure(res, error);
|
|
3065
2927
|
}
|
|
3066
2928
|
}
|
|
3067
2929
|
},
|
|
3068
|
-
"/worlds/
|
|
3069
|
-
const body = await readJsonBody(req);
|
|
3070
|
-
if (!Array.isArray(body.avatars) || body.avatars.length === 0 || !body.avatars.every((key) => typeof key === "string")) return sendError(res, 400, "avatars must be a list of keys");
|
|
2930
|
+
"/worlds/import/resume": { POST: async (req, res, url) => {
|
|
3071
2931
|
try {
|
|
3072
|
-
|
|
2932
|
+
const body = await readJsonBody(req);
|
|
2933
|
+
sendJson(res, 200, await importer.resume(url.searchParams.get("id") ?? "", languageField(body.language)));
|
|
3073
2934
|
} catch (error) {
|
|
3074
|
-
|
|
3075
|
-
if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
|
|
3076
|
-
message: error.message,
|
|
3077
|
-
problems: error.problems
|
|
3078
|
-
});
|
|
3079
|
-
throw error;
|
|
2935
|
+
return importFailure(res, error);
|
|
3080
2936
|
}
|
|
3081
2937
|
} },
|
|
2938
|
+
"/worlds/import/picture": { GET: async (_req, res, url) => {
|
|
2939
|
+
try {
|
|
2940
|
+
await sendImage(res, await importer.picture(url.searchParams.get("id") ?? ""));
|
|
2941
|
+
} catch (error) {
|
|
2942
|
+
return sendError(res, 404, error instanceof Error ? error.message : String(error));
|
|
2943
|
+
}
|
|
2944
|
+
} }
|
|
2945
|
+
};
|
|
2946
|
+
}
|
|
2947
|
+
//#endregion
|
|
2948
|
+
//#region src/shared/world-dice.ts
|
|
2949
|
+
const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2950
|
+
const CHECK_FIELDS = [
|
|
2951
|
+
"key",
|
|
2952
|
+
"name",
|
|
2953
|
+
"use",
|
|
2954
|
+
"dice",
|
|
2955
|
+
"reading",
|
|
2956
|
+
"hit",
|
|
2957
|
+
"compare",
|
|
2958
|
+
"modifier",
|
|
2959
|
+
"bands"
|
|
2960
|
+
];
|
|
2961
|
+
const BAND_FIELDS = [
|
|
2962
|
+
"min",
|
|
2963
|
+
"max",
|
|
2964
|
+
"label",
|
|
2965
|
+
"result",
|
|
2966
|
+
"critical"
|
|
2967
|
+
];
|
|
2968
|
+
/** Reads a body that came from the browser: the shape of every field is checked here, and what the checks mean when the world is validated. */
|
|
2969
|
+
function parseDiceEdit(value) {
|
|
2970
|
+
const problems = [];
|
|
2971
|
+
if (!isObject$1(value) || !Array.isArray(value["checks"])) throw new InvalidEditProblems(["the dice must be { checks: [...] }"]);
|
|
2972
|
+
const checks = value["checks"].map((entry, index) => {
|
|
2973
|
+
const at = `checks[${index}]`;
|
|
2974
|
+
const empty = {
|
|
2975
|
+
key: "",
|
|
2976
|
+
name: "",
|
|
2977
|
+
use: "",
|
|
2978
|
+
dice: "",
|
|
2979
|
+
bands: []
|
|
2980
|
+
};
|
|
2981
|
+
if (!isObject$1(entry)) {
|
|
2982
|
+
problems.push(`${at} must be an object`);
|
|
2983
|
+
return empty;
|
|
2984
|
+
}
|
|
2985
|
+
for (const key of Object.keys(entry)) if (!CHECK_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a check`);
|
|
2986
|
+
for (const key of [
|
|
2987
|
+
"key",
|
|
2988
|
+
"name",
|
|
2989
|
+
"use",
|
|
2990
|
+
"dice"
|
|
2991
|
+
]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
2992
|
+
if (entry["reading"] !== void 0 && !DICE_READINGS.includes(entry["reading"])) problems.push(`${at}.reading must be one of: ${DICE_READINGS.join(", ")}`);
|
|
2993
|
+
if (entry["compare"] !== void 0 && !DICE_COMPARISONS.includes(entry["compare"])) problems.push(`${at}.compare must be one of: ${DICE_COMPARISONS.join(", ")}`);
|
|
2994
|
+
if (entry["hit"] !== void 0 && (typeof entry["hit"] !== "number" || !Number.isInteger(entry["hit"]))) problems.push(`${at}.hit must be a whole number`);
|
|
2995
|
+
if (entry["modifier"] !== void 0 && typeof entry["modifier"] !== "string") problems.push(`${at}.modifier must be text`);
|
|
2996
|
+
const bands = Array.isArray(entry["bands"]) ? entry["bands"] : void 0;
|
|
2997
|
+
if (bands === void 0) problems.push(`${at}.bands must be a list`);
|
|
2998
|
+
const text = (field) => typeof field === "string" ? field.trim() : "";
|
|
2999
|
+
const hit = entry["hit"];
|
|
3000
|
+
return {
|
|
3001
|
+
key: text(entry["key"]),
|
|
3002
|
+
name: text(entry["name"]),
|
|
3003
|
+
use: text(entry["use"]),
|
|
3004
|
+
dice: text(entry["dice"]),
|
|
3005
|
+
...entry["reading"] === void 0 ? {} : { reading: entry["reading"] },
|
|
3006
|
+
...typeof hit === "number" ? { hit } : {},
|
|
3007
|
+
...entry["compare"] === void 0 ? {} : { compare: entry["compare"] },
|
|
3008
|
+
...text(entry["modifier"]) === "" ? {} : { modifier: text(entry["modifier"]) },
|
|
3009
|
+
bands: (bands ?? []).map((band, bandIndex) => {
|
|
3010
|
+
const where = `${at}.bands[${bandIndex}]`;
|
|
3011
|
+
if (!isObject$1(band)) {
|
|
3012
|
+
problems.push(`${where} must be an object`);
|
|
3013
|
+
return {
|
|
3014
|
+
label: "",
|
|
3015
|
+
result: "failed"
|
|
3016
|
+
};
|
|
3017
|
+
}
|
|
3018
|
+
for (const key of Object.keys(band)) if (!BAND_FIELDS.includes(key)) problems.push(`${where}.${key} is not a field of a band`);
|
|
3019
|
+
for (const key of ["min", "max"]) if (band[key] !== void 0 && (typeof band[key] !== "number" || !Number.isFinite(band[key]))) problems.push(`${where}.${key} must be a number`);
|
|
3020
|
+
if (typeof band["label"] !== "string") problems.push(`${where}.label must be text`);
|
|
3021
|
+
if (!DICE_RESULTS.includes(band["result"])) problems.push(`${where}.result must be one of: ${DICE_RESULTS.join(", ")}`);
|
|
3022
|
+
const min = band["min"];
|
|
3023
|
+
const max = band["max"];
|
|
3024
|
+
return {
|
|
3025
|
+
label: text(band["label"]),
|
|
3026
|
+
result: band["result"],
|
|
3027
|
+
...typeof min === "number" ? { min } : {},
|
|
3028
|
+
...typeof max === "number" ? { max } : {},
|
|
3029
|
+
...band["critical"] === true ? { critical: true } : {}
|
|
3030
|
+
};
|
|
3031
|
+
})
|
|
3032
|
+
};
|
|
3033
|
+
});
|
|
3034
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
3035
|
+
return { checks };
|
|
3036
|
+
}
|
|
3037
|
+
//#endregion
|
|
3038
|
+
//#region src/shared/world-daily.ts
|
|
3039
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3040
|
+
const ROUTINE_FIELDS = [
|
|
3041
|
+
"days",
|
|
3042
|
+
"on",
|
|
3043
|
+
"from",
|
|
3044
|
+
"to",
|
|
3045
|
+
"activity",
|
|
3046
|
+
"location",
|
|
3047
|
+
"feature",
|
|
3048
|
+
"position",
|
|
3049
|
+
"interruptible"
|
|
3050
|
+
];
|
|
3051
|
+
/**
|
|
3052
|
+
* The windows of a day as the browser sends them.
|
|
3053
|
+
* @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the times and places are acceptable is checked when the file is read back.
|
|
3054
|
+
*/
|
|
3055
|
+
function parseRoutineEdit(value) {
|
|
3056
|
+
const problems = [];
|
|
3057
|
+
const list = isObject(value) && Array.isArray(value["windows"]) ? value["windows"] : void 0;
|
|
3058
|
+
if (list === void 0) throw new InvalidEditProblems(["the day must be { windows: [...] }"]);
|
|
3059
|
+
const windows = list.map((entry, index) => {
|
|
3060
|
+
const at = `windows[${index}]`;
|
|
3061
|
+
if (!isObject(entry)) {
|
|
3062
|
+
problems.push(`${at} must be an object`);
|
|
3063
|
+
return {
|
|
3064
|
+
days: [],
|
|
3065
|
+
from: "",
|
|
3066
|
+
to: "",
|
|
3067
|
+
activity: "",
|
|
3068
|
+
interruptible: true
|
|
3069
|
+
};
|
|
3070
|
+
}
|
|
3071
|
+
for (const key of Object.keys(entry)) if (!ROUTINE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a window`);
|
|
3072
|
+
for (const key of [
|
|
3073
|
+
"from",
|
|
3074
|
+
"to",
|
|
3075
|
+
"activity"
|
|
3076
|
+
]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
3077
|
+
for (const key of [
|
|
3078
|
+
"location",
|
|
3079
|
+
"feature",
|
|
3080
|
+
"position"
|
|
3081
|
+
]) if (entry[key] !== void 0 && typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
3082
|
+
if (entry["days"] !== void 0 && !(Array.isArray(entry["days"]) && entry["days"].every((day) => typeof day === "string"))) problems.push(`${at}.days must be a list of days`);
|
|
3083
|
+
if (entry["interruptible"] !== void 0 && typeof entry["interruptible"] !== "boolean") problems.push(`${at}.interruptible must be true or false`);
|
|
3084
|
+
const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
|
|
3085
|
+
return {
|
|
3086
|
+
days: Array.isArray(entry["days"]) ? entry["days"].map((day) => day.trim().toLowerCase()).filter((day) => day !== "") : [],
|
|
3087
|
+
...Array.isArray(entry["on"]) && entry["on"].length > 0 ? { on: entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") } : {},
|
|
3088
|
+
from: text("from"),
|
|
3089
|
+
to: text("to"),
|
|
3090
|
+
activity: text("activity"),
|
|
3091
|
+
...text("location") === "" ? {} : { location: text("location") },
|
|
3092
|
+
...text("feature") === "" ? {} : { feature: text("feature") },
|
|
3093
|
+
...text("position") === "" ? {} : { position: text("position") },
|
|
3094
|
+
interruptible: entry["interruptible"] !== false
|
|
3095
|
+
};
|
|
3096
|
+
});
|
|
3097
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
3098
|
+
return windows;
|
|
3099
|
+
}
|
|
3100
|
+
const VARIABLE_FIELDS = [
|
|
3101
|
+
"key",
|
|
3102
|
+
"name",
|
|
3103
|
+
"kind",
|
|
3104
|
+
"subject",
|
|
3105
|
+
"visibility",
|
|
3106
|
+
"description",
|
|
3107
|
+
"min",
|
|
3108
|
+
"max",
|
|
3109
|
+
"integer",
|
|
3110
|
+
"baseline",
|
|
3111
|
+
"always",
|
|
3112
|
+
"default",
|
|
3113
|
+
"only",
|
|
3114
|
+
"options",
|
|
3115
|
+
"bands"
|
|
3116
|
+
];
|
|
3117
|
+
/**
|
|
3118
|
+
* The declarations as the browser sends them, with empty fields left out. Whether they are acceptable together is checked against the world's files.
|
|
3119
|
+
* @throws {InvalidEditProblems} naming every field that has the wrong shape.
|
|
3120
|
+
*/
|
|
3121
|
+
function parseVariablesEdit(value) {
|
|
3122
|
+
const problems = [];
|
|
3123
|
+
const list = isObject(value) && Array.isArray(value["variables"]) ? value["variables"] : void 0;
|
|
3124
|
+
if (list === void 0) throw new InvalidEditProblems(["the variables must be { variables: [...] }"]);
|
|
3125
|
+
const declarations = list.flatMap((entry, index) => {
|
|
3126
|
+
const at = `variables[${index}]`;
|
|
3127
|
+
if (!isObject(entry)) {
|
|
3128
|
+
problems.push(`${at} must be an object`);
|
|
3129
|
+
return [];
|
|
3130
|
+
}
|
|
3131
|
+
for (const key of Object.keys(entry)) if (!VARIABLE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a variable`);
|
|
3132
|
+
const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
|
|
3133
|
+
const number = (key) => {
|
|
3134
|
+
if (entry[key] === void 0 || entry[key] === null || entry[key] === "") return void 0;
|
|
3135
|
+
if (typeof entry[key] !== "number" || !Number.isFinite(entry[key])) {
|
|
3136
|
+
problems.push(`${at}.${key} must be a number`);
|
|
3137
|
+
return;
|
|
3138
|
+
}
|
|
3139
|
+
return entry[key];
|
|
3140
|
+
};
|
|
3141
|
+
const flag = (key) => {
|
|
3142
|
+
if (entry[key] === void 0) return void 0;
|
|
3143
|
+
if (typeof entry[key] !== "boolean") {
|
|
3144
|
+
problems.push(`${at}.${key} must be true or false`);
|
|
3145
|
+
return;
|
|
3146
|
+
}
|
|
3147
|
+
return entry[key];
|
|
3148
|
+
};
|
|
3149
|
+
const strings = (key) => {
|
|
3150
|
+
if (entry[key] === void 0) return [];
|
|
3151
|
+
if (!(Array.isArray(entry[key]) && entry[key].every((item) => typeof item === "string"))) {
|
|
3152
|
+
problems.push(`${at}.${key} must be a list of text`);
|
|
3153
|
+
return [];
|
|
3154
|
+
}
|
|
3155
|
+
return entry[key].map((item) => item.trim()).filter((item) => item !== "");
|
|
3156
|
+
};
|
|
3157
|
+
const bands = Array.isArray(entry["bands"]) ? entry["bands"].flatMap((band) => isObject(band) && typeof band["up_to"] === "number" && typeof band["label"] === "string" && band["label"].trim() !== "" ? [{
|
|
3158
|
+
up_to: band["up_to"],
|
|
3159
|
+
label: band["label"].trim()
|
|
3160
|
+
}] : (problems.push(`${at}.bands needs { up_to, label } entries`), [])) : [];
|
|
3161
|
+
const rawDefault = entry["default"];
|
|
3162
|
+
if (rawDefault !== void 0 && rawDefault !== null && rawDefault !== "" && typeof rawDefault !== "number" && typeof rawDefault !== "boolean" && typeof rawDefault !== "string") problems.push(`${at}.default must be a number, true or false, or text`);
|
|
3163
|
+
for (const [key, allowed] of [
|
|
3164
|
+
["kind", VARIABLE_KINDS],
|
|
3165
|
+
["subject", VARIABLE_SUBJECTS],
|
|
3166
|
+
["visibility", VARIABLE_VISIBILITIES]
|
|
3167
|
+
]) if (!allowed.includes(text(key))) problems.push(`${at}.${key} must be one of: ${allowed.join(", ")}`);
|
|
3168
|
+
const [min, max] = [number("min"), number("max")];
|
|
3169
|
+
const [integer, baseline, always] = [
|
|
3170
|
+
flag("integer"),
|
|
3171
|
+
flag("baseline"),
|
|
3172
|
+
flag("always")
|
|
3173
|
+
];
|
|
3174
|
+
const only = strings("only");
|
|
3175
|
+
const options = strings("options");
|
|
3176
|
+
return [{
|
|
3177
|
+
key: text("key"),
|
|
3178
|
+
name: text("name"),
|
|
3179
|
+
kind: text("kind"),
|
|
3180
|
+
subject: text("subject"),
|
|
3181
|
+
visibility: text("visibility"),
|
|
3182
|
+
...text("description") === "" ? {} : { description: text("description") },
|
|
3183
|
+
...min === void 0 ? {} : { min },
|
|
3184
|
+
...max === void 0 ? {} : { max },
|
|
3185
|
+
...integer === true ? { integer } : {},
|
|
3186
|
+
...baseline === true ? { baseline } : {},
|
|
3187
|
+
...always === true ? { always } : {},
|
|
3188
|
+
...rawDefault === void 0 || rawDefault === null || rawDefault === "" ? {} : { default: rawDefault },
|
|
3189
|
+
...only.length === 0 ? {} : { only },
|
|
3190
|
+
...options.length === 0 ? {} : { options },
|
|
3191
|
+
...bands.length === 0 ? {} : { bands }
|
|
3192
|
+
}];
|
|
3193
|
+
});
|
|
3194
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
3195
|
+
return declarations;
|
|
3196
|
+
}
|
|
3197
|
+
/**
|
|
3198
|
+
* The calendar as the browser sends it.
|
|
3199
|
+
* @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the days and ids are acceptable is checked as the file is read.
|
|
3200
|
+
*/
|
|
3201
|
+
function parseCalendarEdit(value) {
|
|
3202
|
+
const problems = [];
|
|
3203
|
+
if (!isObject(value)) throw new InvalidEditProblems(["the calendar must be { hemisphere, holidays: [...] }"]);
|
|
3204
|
+
if (value["hemisphere"] !== "north" && value["hemisphere"] !== "south") problems.push("hemisphere must be \"north\" or \"south\"");
|
|
3205
|
+
const list = Array.isArray(value["holidays"]) ? value["holidays"] : void 0;
|
|
3206
|
+
if (list === void 0) problems.push("holidays must be a list");
|
|
3207
|
+
const holidays = (list ?? []).map((entry, index) => {
|
|
3208
|
+
const at = `holidays[${index}]`;
|
|
3209
|
+
if (!isObject(entry)) {
|
|
3210
|
+
problems.push(`${at} must be an object`);
|
|
3211
|
+
return {
|
|
3212
|
+
id: "",
|
|
3213
|
+
name: "",
|
|
3214
|
+
on: []
|
|
3215
|
+
};
|
|
3216
|
+
}
|
|
3217
|
+
for (const key of Object.keys(entry)) if (![
|
|
3218
|
+
"id",
|
|
3219
|
+
"name",
|
|
3220
|
+
"on"
|
|
3221
|
+
].includes(key)) problems.push(`${at}.${key} is not a field of a holiday`);
|
|
3222
|
+
for (const key of ["id", "name"]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
|
|
3223
|
+
if (!(Array.isArray(entry["on"]) && entry["on"].every((day) => typeof day === "string"))) problems.push(`${at}.on must be a list of days`);
|
|
3224
|
+
return {
|
|
3225
|
+
id: typeof entry["id"] === "string" ? entry["id"].trim() : "",
|
|
3226
|
+
name: typeof entry["name"] === "string" ? entry["name"].trim() : "",
|
|
3227
|
+
on: Array.isArray(entry["on"]) ? entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") : []
|
|
3228
|
+
};
|
|
3229
|
+
});
|
|
3230
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
3231
|
+
return {
|
|
3232
|
+
hemisphere: value["hemisphere"],
|
|
3233
|
+
holidays
|
|
3234
|
+
};
|
|
3235
|
+
}
|
|
3236
|
+
//#endregion
|
|
3237
|
+
//#region src/host/http/routes/worldFiles.ts
|
|
3238
|
+
/** The routes of the API for worldFiles. */
|
|
3239
|
+
function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
|
|
3240
|
+
return {
|
|
3082
3241
|
"/worlds/state": { GET: async (_req, res, url) => {
|
|
3083
3242
|
try {
|
|
3084
3243
|
sendJson(res, 200, await worldEditor.read(url.searchParams.get("id") ?? ""));
|
|
@@ -3568,15 +3727,14 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
3568
3727
|
return sendError(res, 404, error instanceof Error ? error.message : String(error));
|
|
3569
3728
|
}
|
|
3570
3729
|
} }]
|
|
3571
|
-
]))
|
|
3572
|
-
|
|
3573
|
-
|
|
3574
|
-
|
|
3575
|
-
|
|
3576
|
-
|
|
3577
|
-
|
|
3578
|
-
|
|
3579
|
-
} },
|
|
3730
|
+
]))
|
|
3731
|
+
};
|
|
3732
|
+
}
|
|
3733
|
+
//#endregion
|
|
3734
|
+
//#region src/host/http/routes/sessions.ts
|
|
3735
|
+
/** The routes of the API for sessions. */
|
|
3736
|
+
function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
|
|
3737
|
+
return {
|
|
3580
3738
|
"/sessions": {
|
|
3581
3739
|
GET: async (_req, res) => {
|
|
3582
3740
|
sendJson(res, 200, sessions.list());
|
|
@@ -3793,6 +3951,83 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
3793
3951
|
res.statusCode = 204;
|
|
3794
3952
|
res.end();
|
|
3795
3953
|
} },
|
|
3954
|
+
"/sessions/activity/run": { GET: async (_req, res, url) => {
|
|
3955
|
+
try {
|
|
3956
|
+
const detail = sessions.activityRun(url.searchParams.get("id") ?? "", url.searchParams.get("run") ?? "");
|
|
3957
|
+
if (detail === void 0) return sendError(res, 404, "this run was not kept, or has been dropped to make room");
|
|
3958
|
+
sendJson(res, 200, detail);
|
|
3959
|
+
} catch (error) {
|
|
3960
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
3961
|
+
if (error instanceof RangeError) return sendError(res, 400, error.message);
|
|
3962
|
+
throw error;
|
|
3963
|
+
}
|
|
3964
|
+
} },
|
|
3965
|
+
"/sessions/doctor": { POST: async (req, res, url) => {
|
|
3966
|
+
const body = await readJsonBody(req);
|
|
3967
|
+
if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
|
|
3968
|
+
try {
|
|
3969
|
+
sendJson(res, 200, await sessions.doctor(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language) ?? "en"));
|
|
3970
|
+
} catch (error) {
|
|
3971
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
3972
|
+
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
3973
|
+
throw error;
|
|
3974
|
+
}
|
|
3975
|
+
} },
|
|
3976
|
+
"/sessions/reflect": { POST: async (_req, res, url) => {
|
|
3977
|
+
try {
|
|
3978
|
+
await sessions.reflect(url.searchParams.get("id") ?? "");
|
|
3979
|
+
} catch (error) {
|
|
3980
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
3981
|
+
if (error instanceof ReflectionRefusedError) return sendError(res, 409, error.message);
|
|
3982
|
+
throw error;
|
|
3983
|
+
}
|
|
3984
|
+
res.statusCode = 202;
|
|
3985
|
+
res.end();
|
|
3986
|
+
} },
|
|
3987
|
+
"/sessions/vectors/reset": { POST: async (_req, res, url) => {
|
|
3988
|
+
try {
|
|
3989
|
+
sessions.resetVectors(url.searchParams.get("id") ?? "");
|
|
3990
|
+
} catch (error) {
|
|
3991
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
3992
|
+
throw error;
|
|
3993
|
+
}
|
|
3994
|
+
res.statusCode = 204;
|
|
3995
|
+
res.end();
|
|
3996
|
+
} },
|
|
3997
|
+
"/sessions/rename": { POST: async (req, res, url) => {
|
|
3998
|
+
const body = await readJsonBody(req);
|
|
3999
|
+
const name = typeof body === "object" && body !== null ? body.name : void 0;
|
|
4000
|
+
if (typeof name !== "string") return sendError(res, 400, "the request needs a \"name\"");
|
|
4001
|
+
try {
|
|
4002
|
+
await sessions.rename(url.searchParams.get("id") ?? "", name);
|
|
4003
|
+
} catch (error) {
|
|
4004
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
4005
|
+
if (error instanceof InvalidStartError) return sendError(res, 422, error.message);
|
|
4006
|
+
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
4007
|
+
throw error;
|
|
4008
|
+
}
|
|
4009
|
+
res.statusCode = 204;
|
|
4010
|
+
res.end();
|
|
4011
|
+
} },
|
|
4012
|
+
"/sessions/item": { DELETE: async (_req, res, url) => {
|
|
4013
|
+
try {
|
|
4014
|
+
await sessions.delete(url.searchParams.get("id") ?? "", url.searchParams.get("everywhere") === "true");
|
|
4015
|
+
} catch (error) {
|
|
4016
|
+
if (error instanceof SyncRefusedError || error instanceof RcloneError) return failure(res, error);
|
|
4017
|
+
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
4018
|
+
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
4019
|
+
throw error;
|
|
4020
|
+
}
|
|
4021
|
+
res.statusCode = 204;
|
|
4022
|
+
res.end();
|
|
4023
|
+
} }
|
|
4024
|
+
};
|
|
4025
|
+
}
|
|
4026
|
+
//#endregion
|
|
4027
|
+
//#region src/host/http/routes/sessionWorld.ts
|
|
4028
|
+
/** The routes of the API for sessionWorld. */
|
|
4029
|
+
function sessionWorldRoutes({ sessions }) {
|
|
4030
|
+
return {
|
|
3796
4031
|
"/sessions/world": { GET: async (_req, res, url) => {
|
|
3797
4032
|
try {
|
|
3798
4033
|
sendJson(res, 200, sessions.world(url.searchParams.get("id") ?? ""));
|
|
@@ -3923,91 +4158,26 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
|
|
|
3923
4158
|
} catch (error) {
|
|
3924
4159
|
return sendError(res, 404, error instanceof Error ? error.message : String(error));
|
|
3925
4160
|
}
|
|
3926
|
-
} }
|
|
3927
|
-
|
|
3928
|
-
|
|
3929
|
-
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
3933
|
-
|
|
3934
|
-
|
|
3935
|
-
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
3939
|
-
|
|
3940
|
-
|
|
3941
|
-
|
|
3942
|
-
sendJson(res, 200, await sessions.doctor(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language) ?? "en"));
|
|
3943
|
-
} catch (error) {
|
|
3944
|
-
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
3945
|
-
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
3946
|
-
throw error;
|
|
3947
|
-
}
|
|
3948
|
-
} },
|
|
3949
|
-
"/sessions/reflect": { POST: async (_req, res, url) => {
|
|
3950
|
-
try {
|
|
3951
|
-
await sessions.reflect(url.searchParams.get("id") ?? "");
|
|
3952
|
-
} catch (error) {
|
|
3953
|
-
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
3954
|
-
if (error instanceof ReflectionRefusedError) return sendError(res, 409, error.message);
|
|
3955
|
-
throw error;
|
|
3956
|
-
}
|
|
3957
|
-
res.statusCode = 202;
|
|
3958
|
-
res.end();
|
|
3959
|
-
} },
|
|
3960
|
-
"/sessions/vectors/reset": { POST: async (_req, res, url) => {
|
|
3961
|
-
try {
|
|
3962
|
-
sessions.resetVectors(url.searchParams.get("id") ?? "");
|
|
3963
|
-
} catch (error) {
|
|
3964
|
-
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
3965
|
-
throw error;
|
|
3966
|
-
}
|
|
3967
|
-
res.statusCode = 204;
|
|
3968
|
-
res.end();
|
|
3969
|
-
} },
|
|
3970
|
-
"/sessions/rename": { POST: async (req, res, url) => {
|
|
3971
|
-
const body = await readJsonBody(req);
|
|
3972
|
-
const name = typeof body === "object" && body !== null ? body.name : void 0;
|
|
3973
|
-
if (typeof name !== "string") return sendError(res, 400, "the request needs a \"name\"");
|
|
3974
|
-
try {
|
|
3975
|
-
await sessions.rename(url.searchParams.get("id") ?? "", name);
|
|
3976
|
-
} catch (error) {
|
|
3977
|
-
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
3978
|
-
if (error instanceof InvalidStartError) return sendError(res, 422, error.message);
|
|
3979
|
-
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
3980
|
-
throw error;
|
|
3981
|
-
}
|
|
3982
|
-
res.statusCode = 204;
|
|
3983
|
-
res.end();
|
|
3984
|
-
} },
|
|
3985
|
-
"/sessions/item": { DELETE: async (_req, res, url) => {
|
|
3986
|
-
try {
|
|
3987
|
-
await sessions.delete(url.searchParams.get("id") ?? "", url.searchParams.get("everywhere") === "true");
|
|
3988
|
-
} catch (error) {
|
|
3989
|
-
if (error instanceof SyncRefusedError || error instanceof RcloneError) return failure(res, error);
|
|
3990
|
-
if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
|
|
3991
|
-
if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
|
|
3992
|
-
throw error;
|
|
3993
|
-
}
|
|
3994
|
-
res.statusCode = 204;
|
|
3995
|
-
res.end();
|
|
3996
|
-
} },
|
|
4161
|
+
} }
|
|
4162
|
+
};
|
|
4163
|
+
}
|
|
4164
|
+
//#endregion
|
|
4165
|
+
//#region src/host/http/api.ts
|
|
4166
|
+
/** Build the request handler mounted at `/${API_PREFIX}`. */
|
|
4167
|
+
function createApiHandler(deps) {
|
|
4168
|
+
const { packs, presets, lorebooks, sync, locked, anyLocked, connection } = deps;
|
|
4169
|
+
const routes = {
|
|
4170
|
+
...speechRoutes(deps),
|
|
4171
|
+
...worldsRoutes(deps),
|
|
4172
|
+
...catalogueRoutes(deps),
|
|
4173
|
+
...importsRoutes(deps),
|
|
4174
|
+
...worldFilesRoutes(deps),
|
|
4175
|
+
...sessionsRoutes(deps),
|
|
4176
|
+
...sessionWorldRoutes(deps),
|
|
3997
4177
|
...interfaceRoutes(packs),
|
|
3998
4178
|
...presetRoutes(presets),
|
|
3999
4179
|
...lorebookRoutes(lorebooks),
|
|
4000
|
-
...syncRoutes(sync)
|
|
4001
|
-
"/worlds/cover": { GET: async (_req, res, url) => {
|
|
4002
|
-
const cover = await worlds.cover(url.searchParams.get("id") ?? "");
|
|
4003
|
-
if (cover === void 0) return sendError(res, 404, "no cover");
|
|
4004
|
-
res.statusCode = 200;
|
|
4005
|
-
res.setHeader("content-type", cover.contentType);
|
|
4006
|
-
res.setHeader("content-length", cover.size);
|
|
4007
|
-
res.setHeader("x-content-type-options", "nosniff");
|
|
4008
|
-
res.setHeader("cache-control", cover.version === url.searchParams.get("v") ? "private, max-age=31536000, immutable" : "no-cache");
|
|
4009
|
-
await pipeline(createReadStream(cover.file), res);
|
|
4010
|
-
} }
|
|
4180
|
+
...syncRoutes(sync)
|
|
4011
4181
|
};
|
|
4012
4182
|
return async (req, res) => {
|
|
4013
4183
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
@@ -5383,7 +5553,7 @@ function worldFindings(session) {
|
|
|
5383
5553
|
async function startSession(deps, request) {
|
|
5384
5554
|
const world = await deps.worlds.find(request.worldId);
|
|
5385
5555
|
if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${request.worldId}"`);
|
|
5386
|
-
const { characters: authored, factions, locations, items, slots, authoredLore, declared, scripted, authoredPlots, calendar, checks } = await loadValidatedWorld(world);
|
|
5556
|
+
const { characters: authored, factions, locations, items, slots, authoredLore, declared, scripted, authoredPlots, calendar, checks, commands } = await loadValidatedWorld(world);
|
|
5387
5557
|
if (request.opening !== void 0 && (!Number.isInteger(request.opening) || request.opening < 0 || request.opening >= (world.alternateOpenings?.length ?? 0))) throw new InvalidStartError(`the world has no alternate opening ${String(request.opening)}`);
|
|
5388
5558
|
const opening = request.opening === void 0 ? openingOf(world, authored) : [{
|
|
5389
5559
|
type: "narration",
|
|
@@ -5498,6 +5668,7 @@ async function startSession(deps, request) {
|
|
|
5498
5668
|
populateTriggers(session, scripted.triggers);
|
|
5499
5669
|
populatePlots(session.metadata, authoredPlots.plots);
|
|
5500
5670
|
populateClock(session, settings.clock, startsAt === void 0 ? void 0 : { startingTime: startsAt }, (deps.now ?? Date.now)());
|
|
5671
|
+
if (commands.length > 0) session.metadata.setValue(COMMANDS_KEY, commands.map((command) => ({ ...command })));
|
|
5501
5672
|
if (world.rules !== void 0) session.metadata.setValue(WORLD_RULES_KEY, world.rules);
|
|
5502
5673
|
if (world.narrationVoice !== void 0) session.metadata.setValue("roleplay.tts.narrationVoice", world.narrationVoice);
|
|
5503
5674
|
});
|
|
@@ -5777,15 +5948,7 @@ async function readWorldPackFile(directory, pack, path) {
|
|
|
5777
5948
|
async function writeWorldPackFile(directory, pack, path, text) {
|
|
5778
5949
|
if (Buffer.byteLength(text) > 204800) throw new InvalidEditProblems([`a file holds at most ${MAX_PACK_TEXT / 1024} KB of text`]);
|
|
5779
5950
|
const file = placeOf(directory, pack, path, "write", text);
|
|
5780
|
-
await
|
|
5781
|
-
const temporary = join(dirname(file), `.${process.pid}.${randomUUID()}.tmp`);
|
|
5782
|
-
try {
|
|
5783
|
-
await writeFile(temporary, text);
|
|
5784
|
-
await rename(temporary, file);
|
|
5785
|
-
} catch (error) {
|
|
5786
|
-
await rm(temporary, { force: true });
|
|
5787
|
-
throw error;
|
|
5788
|
-
}
|
|
5951
|
+
await atomicWrite(file, text, { createDirectory: true });
|
|
5789
5952
|
return problemsOf(directory, pack);
|
|
5790
5953
|
}
|
|
5791
5954
|
/** Makes a pack with a manifest that names it and nothing else yet. @throws {InvalidEditProblems} when the name is not usable or the pack exists. */
|
|
@@ -6017,16 +6180,7 @@ function withWorldId(text, id) {
|
|
|
6017
6180
|
*/
|
|
6018
6181
|
async function assignWorldId(file) {
|
|
6019
6182
|
const id = randomUUID();
|
|
6020
|
-
|
|
6021
|
-
try {
|
|
6022
|
-
const { mode } = await stat(file);
|
|
6023
|
-
await writeFile(temporary, withWorldId(await readFile(file, "utf8"), id), { mode });
|
|
6024
|
-
await chmod(temporary, mode);
|
|
6025
|
-
await rename(temporary, file);
|
|
6026
|
-
} catch (error) {
|
|
6027
|
-
await rm(temporary, { force: true });
|
|
6028
|
-
throw error;
|
|
6029
|
-
}
|
|
6183
|
+
await atomicWrite(file, withWorldId(await readFile(file, "utf8"), id));
|
|
6030
6184
|
return id;
|
|
6031
6185
|
}
|
|
6032
6186
|
//#endregion
|
|
@@ -6113,7 +6267,8 @@ async function loadWorld(folder, dir, file, problems) {
|
|
|
6113
6267
|
description: world.description,
|
|
6114
6268
|
tags: world.tags,
|
|
6115
6269
|
...world.author === void 0 ? {} : { author: world.author },
|
|
6116
|
-
...world.version === void 0 ? {} : { version: world.version }
|
|
6270
|
+
...world.version === void 0 ? {} : { version: world.version },
|
|
6271
|
+
...await isDraftWorld(dir) ? { draft: true } : {}
|
|
6117
6272
|
},
|
|
6118
6273
|
...world.opening === void 0 ? {} : { opening: world.opening },
|
|
6119
6274
|
...world.clock === void 0 ? {} : { clock: world.clock },
|
|
@@ -7232,11 +7387,23 @@ function spawnRclone(setup) {
|
|
|
7232
7387
|
child.stdin.end(options.input ?? "");
|
|
7233
7388
|
}) };
|
|
7234
7389
|
}
|
|
7235
|
-
|
|
7390
|
+
const CHANGED_IN_TRANSIT = /corrupted on transfer: sizes? differ/;
|
|
7391
|
+
/** The files rclone named as arriving a different size than the server listed, up to a few. */
|
|
7392
|
+
function changedFiles(lines) {
|
|
7393
|
+
const names = lines.flatMap((line) => {
|
|
7394
|
+
const found = /^ERROR\s*: (.+?): .*corrupted on transfer/.exec(line);
|
|
7395
|
+
return found === null ? [] : [found[1]];
|
|
7396
|
+
});
|
|
7397
|
+
return [...new Set(names)].slice(0, 3);
|
|
7398
|
+
}
|
|
7399
|
+
/** What rclone said went wrong: its last error line, without the time and the colours, cut short. A file that arrives a different size than the server listed says what usually causes it. */
|
|
7236
7400
|
function why(result) {
|
|
7237
7401
|
const lines = (result.stderr || result.stdout).split("\n").map((line) => line.replace(/\u001b\[[0-9;]*m/g, "").replace(/^\d{4}\/\d\d\/\d\d \d\d:\d\d:\d\d /, "").trim()).filter((line) => line !== "");
|
|
7238
7402
|
const line = lines.findLast((entry) => /^(ERROR|NOTICE: Failed|CRITICAL)/.test(entry)) ?? lines.at(-1) ?? `rclone stopped with code ${result.code}`;
|
|
7239
|
-
|
|
7403
|
+
const shown = line.length > 300 ? `${line.slice(0, 300)}…` : line;
|
|
7404
|
+
if (!CHANGED_IN_TRANSIT.test(line)) return shown;
|
|
7405
|
+
const files = changedFiles(lines);
|
|
7406
|
+
return `${shown} — something between this device and the server changes files on the way${files.length === 0 ? "" : ` (${files.join(", ")})`}; a proxy or CDN that adds content to HTML pages is the usual cause: turn off its response rewriting for the server, or reach the server directly`;
|
|
7240
7407
|
}
|
|
7241
7408
|
//#endregion
|
|
7242
7409
|
//#region src/host/sync/state.ts
|
|
@@ -8143,7 +8310,9 @@ const Config = z.object({
|
|
|
8143
8310
|
importReasoning: z.string().default("").volatile(),
|
|
8144
8311
|
childReasoning: z.string().default("").volatile(),
|
|
8145
8312
|
importModel: z.string().default("").volatile(),
|
|
8146
|
-
|
|
8313
|
+
importStructuredOutput: z.union(["tool", "schema"]).default("tool").volatile(),
|
|
8314
|
+
importMaxTokens: z.number().min(0).max(1e6).default(0).volatile(),
|
|
8315
|
+
importVariablesPerRequest: z.number().min(5).max(500).default(25).volatile(),
|
|
8147
8316
|
importTemperature: z.number().min(0).max(2).default(.2).volatile(),
|
|
8148
8317
|
importTimeoutMinutes: z.number().min(0).max(240).default(15).volatile(),
|
|
8149
8318
|
importDecisions: z.union([z.const("llm"), z.const("decision")]).default("llm").volatile(),
|
|
@@ -8167,7 +8336,7 @@ function apply(ctx, config) {
|
|
|
8167
8336
|
const helper = childSamplingOf(id);
|
|
8168
8337
|
if (helper !== void 0) return helper;
|
|
8169
8338
|
if (authoredWorldOf(id) !== void 0 || presetOfChat(id) !== void 0 || lorebookOfChat(id) !== void 0) return {
|
|
8170
|
-
maxTokens: config.importMaxTokens.get(),
|
|
8339
|
+
maxTokens: knownOutputCeiling(config.importMaxTokens.get()),
|
|
8171
8340
|
priority: "foreground"
|
|
8172
8341
|
};
|
|
8173
8342
|
const session = roleplaySessionOf(id);
|
|
@@ -8207,6 +8376,8 @@ function apply(ctx, config) {
|
|
|
8207
8376
|
reasoning: config.importReasoning.get() || config.childReasoning.get(),
|
|
8208
8377
|
model: config.importModel.get(),
|
|
8209
8378
|
maxTokens: config.importMaxTokens.get(),
|
|
8379
|
+
variablesPerRequest: config.importVariablesPerRequest.get(),
|
|
8380
|
+
structured: config.importStructuredOutput.get(),
|
|
8210
8381
|
temperature: config.importTemperature.get(),
|
|
8211
8382
|
timeoutMinutes: config.importTimeoutMinutes.get(),
|
|
8212
8383
|
decisions: config.importDecisions.get() === "decision" ? "decision" : "llm",
|
|
@@ -8369,6 +8540,16 @@ function apply(ctx, config) {
|
|
|
8369
8540
|
discard: (id) => imports.discard(id),
|
|
8370
8541
|
start: begin,
|
|
8371
8542
|
picture: (id) => imports.picture(id),
|
|
8543
|
+
resume: (worldId, language) => resumeImport({
|
|
8544
|
+
worlds,
|
|
8545
|
+
authoring
|
|
8546
|
+
}, worldId, language),
|
|
8547
|
+
draftStatus: (worldId) => draftStatus(worlds, worldId),
|
|
8548
|
+
actOnDraft: (worldId, action, language) => actOnDraft({
|
|
8549
|
+
worlds,
|
|
8550
|
+
authoring,
|
|
8551
|
+
root: () => root.path
|
|
8552
|
+
}, worldId, action, language),
|
|
8372
8553
|
updateStatus: async (worldId) => await updateStatus((await editableWorld(worlds, worldId, root.path)).directory),
|
|
8373
8554
|
revertUpdate: async (worldId) => {
|
|
8374
8555
|
const directory = (await editableWorld(worlds, worldId, root.path)).directory;
|