aicommunicator 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +93 -2
  3. package/bin/aic.js +20427 -0
  4. package/host-ui/host.js +5151 -0
  5. package/host-ui/index.html +483 -0
  6. package/host-ui/lang-en.js +631 -0
  7. package/package.json +30 -4
  8. package/plugin-guide.md +997 -0
  9. package/plugins/plugin-animation/LICENSE +55 -0
  10. package/plugins/plugin-animation/dist/logic.js +2225 -0
  11. package/plugins/plugin-animation/docs/manual.md +217 -0
  12. package/plugins/plugin-animation/manifest.json +31 -0
  13. package/plugins/plugin-animation/ui/icon.svg +6 -0
  14. package/plugins/plugin-animation/ui/index.html +2266 -0
  15. package/plugins/plugin-html-design/LICENSE +55 -0
  16. package/plugins/plugin-html-design/dist/logic.js +972 -0
  17. package/plugins/plugin-html-design/docs/manual.md +100 -0
  18. package/plugins/plugin-html-design/manifest.json +39 -0
  19. package/plugins/plugin-html-design/samples/exhibition-page.json +570 -0
  20. package/plugins/plugin-html-design/ui/icon.svg +5 -0
  21. package/plugins/plugin-html-design/ui/index.html +1241 -0
  22. package/plugins/plugin-html-slides/LICENSE +55 -0
  23. package/plugins/plugin-html-slides/dist/logic.js +1323 -0
  24. package/plugins/plugin-html-slides/docs/manual.md +121 -0
  25. package/plugins/plugin-html-slides/manifest.json +39 -0
  26. package/plugins/plugin-html-slides/samples/first-week-lecture.json +1129 -0
  27. package/plugins/plugin-html-slides/ui/icon.svg +5 -0
  28. package/plugins/plugin-html-slides/ui/index.html +1349 -0
  29. package/plugins/plugin-mindmap/LICENSE +55 -0
  30. package/plugins/plugin-mindmap/dist/logic.js +966 -0
  31. package/plugins/plugin-mindmap/docs/manual.md +145 -0
  32. package/plugins/plugin-mindmap/manifest.json +39 -0
  33. package/plugins/plugin-mindmap/samples/book-club.json +480 -0
  34. package/plugins/plugin-mindmap/ui/icon.svg +5 -0
  35. package/plugins/plugin-mindmap/ui/index.html +1774 -0
  36. package/plugins/plugin-plan/LICENSE +55 -0
  37. package/plugins/plugin-plan/dist/logic.js +1029 -0
  38. package/plugins/plugin-plan/docs/manual.md +261 -0
  39. package/plugins/plugin-plan/manifest.json +51 -0
  40. package/plugins/plugin-plan/samples/kimchi-day.json +1514 -0
  41. package/plugins/plugin-plan/samples/meeting-outline.json +653 -0
  42. package/plugins/plugin-plan/samples/reading-class.json +1577 -0
  43. package/plugins/plugin-plan/ui/icon.svg +7 -0
  44. package/plugins/plugin-plan/ui/index.html +1523 -0
  45. package/plugins/plugin-png/LICENSE +55 -0
  46. package/plugins/plugin-png/dist/logic.js +1758 -0
  47. package/plugins/plugin-png/docs/manual.md +344 -0
  48. package/plugins/plugin-png/manifest.json +35 -0
  49. package/plugins/plugin-png/ui/icon.svg +5 -0
  50. package/plugins/plugin-png/ui/index.html +2885 -0
  51. package/plugins/plugin-process-log/LICENSE +55 -0
  52. package/plugins/plugin-process-log/dist/logic.js +406 -0
  53. package/plugins/plugin-process-log/docs/manual.md +131 -0
  54. package/plugins/plugin-process-log/manifest.json +43 -0
  55. package/plugins/plugin-process-log/samples/design-decisions.json +241 -0
  56. package/plugins/plugin-process-log/ui/icon.svg +7 -0
  57. package/plugins/plugin-process-log/ui/index.html +721 -0
  58. package/plugins/plugin-story/LICENSE +55 -0
  59. package/plugins/plugin-story/dist/logic.js +2201 -0
  60. package/plugins/plugin-story/docs/manual.md +428 -0
  61. package/plugins/plugin-story/manifest.json +49 -0
  62. package/plugins/plugin-story/samples/scene-body.json +758 -0
  63. package/plugins/plugin-story/samples/time-and-groups.json +989 -0
  64. package/plugins/plugin-story/ui/icon.svg +4 -0
  65. package/plugins/plugin-story/ui/index.html +2783 -0
  66. package/plugins/plugin-svg/LICENSE +55 -0
  67. package/plugins/plugin-svg/dist/logic.js +2150 -0
  68. package/plugins/plugin-svg/docs/manual.md +314 -0
  69. package/plugins/plugin-svg/manifest.json +45 -0
  70. package/plugins/plugin-svg/samples/rocket-icon.json +1305 -0
  71. package/plugins/plugin-svg/samples/yard-cat.json +7796 -0
  72. package/plugins/plugin-svg/ui/icon.svg +4 -0
  73. package/plugins/plugin-svg/ui/index.html +2017 -0
  74. package/plugins/plugin-tree/LICENSE +55 -0
  75. package/plugins/plugin-tree/dist/logic.js +505 -0
  76. package/plugins/plugin-tree/docs/manual.md +140 -0
  77. package/plugins/plugin-tree/manifest.json +45 -0
  78. package/plugins/plugin-tree/samples/book-club.json +473 -0
  79. package/plugins/plugin-tree/samples/sort-memos.json +604 -0
  80. package/plugins/plugin-tree/ui/icon.svg +7 -0
  81. package/plugins/plugin-tree/ui/index.html +1305 -0
  82. package/schema/aic_describe.input.json +11 -0
  83. package/schema/aic_describe.output.json +67 -0
  84. package/schema/aic_observe.input.json +14 -0
  85. package/schema/aic_observe.output.json +47 -0
  86. package/schema/aic_send.input.json +15 -0
  87. package/schema/aic_send.output.json +38 -0
  88. package/schema/aic_update.input.json +19 -0
  89. package/schema/aic_update.output.json +39 -0
  90. package/schema/common.json +127 -0
  91. package/template/plugin/LICENSE +55 -0
  92. package/template/plugin/README.md +27 -0
  93. package/template/plugin/docs/manual.md +31 -0
  94. package/template/plugin/logic.js +337 -0
  95. package/template/plugin/manifest.json +27 -0
  96. package/template/plugin/ui/icon.svg +4 -0
  97. package/template/plugin/ui/index.html +269 -0
@@ -0,0 +1,2201 @@
1
+ "use strict";
2
+ (() => {
3
+ // packages/plugin-sdk/src/index.ts
4
+ var SEPARATOR = " ";
5
+ var ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
6
+ function sortKey(order, id) {
7
+ return `${order}${SEPARATOR}${id}`;
8
+ }
9
+ function boundAfterOrder(order) {
10
+ return `${order}!`;
11
+ }
12
+ function between(lo, hi) {
13
+ const out = [];
14
+ for (const c of ALPHABET) {
15
+ if ((lo === void 0 || c > lo) && (hi === void 0 || c < hi)) out.push(c);
16
+ }
17
+ return out;
18
+ }
19
+ function orderBetween(left, right) {
20
+ if (left === void 0 && right === void 0) return "V";
21
+ const L = left ?? "";
22
+ const U = right;
23
+ if (U !== void 0 && !(L < U)) throw new Error(`orderBetween: \uC67C\uCABD ${L} \uC774 \uC624\uB978\uCABD ${U} \uBCF4\uB2E4 \uC55E\uC774\uC5B4\uC57C \uD55C\uB2E4`);
24
+ let i = 0;
25
+ while (U !== void 0 && i < L.length && i < U.length && L[i] === U[i]) i += 1;
26
+ if (U === void 0) i = 0;
27
+ if (i >= L.length && U !== void 0) {
28
+ let prefix = U.slice(0, i);
29
+ for (let k = i; k < U.length; k += 1) {
30
+ const uc2 = U[k];
31
+ const cands2 = between(void 0, uc2);
32
+ if (cands2.length > 0) return prefix + cands2[cands2.length - 1];
33
+ if (prefix !== "" && !prefix.endsWith(SEPARATOR) && uc2 > SEPARATOR) return prefix;
34
+ prefix += uc2;
35
+ }
36
+ throw new Error(`orderBetween: ${L} \uACFC ${U} \uC0AC\uC774\uC5D0 \uAC12\uC744 \uB9CC\uB4E4 \uC218 \uC5C6\uB2E4`);
37
+ }
38
+ const lc = L[i];
39
+ const uc = U === void 0 ? void 0 : U[i];
40
+ const cands = between(lc, uc);
41
+ if (cands.length > 0) {
42
+ if (uc === void 0) return L.slice(0, i) + cands[0];
43
+ return L.slice(0, i) + cands[Math.floor(cands.length / 2)];
44
+ }
45
+ for (let j = i + 1; j < L.length; j += 1) {
46
+ const up = between(L[j], void 0);
47
+ if (up.length > 0) return L.slice(0, j) + up[0];
48
+ }
49
+ return `${L}V`;
50
+ }
51
+ var MARK = /\[([^\[\]]*)\]\((\$[^\s)]+|[A-Za-z]+\d+)\)/g;
52
+ function parseMarks(text) {
53
+ const out = [];
54
+ let at = 0;
55
+ for (const m of text.matchAll(MARK)) {
56
+ const idx = m.index ?? 0;
57
+ if (idx > at) out.push(text.slice(at, idx));
58
+ out.push({ mark: { id: m[2], text: m[1] } });
59
+ at = idx + m[0].length;
60
+ }
61
+ if (at < text.length) out.push(text.slice(at));
62
+ return out;
63
+ }
64
+ function formatMarks(segments, names2) {
65
+ return segments.map((s) => {
66
+ if (typeof s === "string") return s;
67
+ if ("node" in s) return `[${s.text ?? names2.node(s.node) ?? s.node}](${s.node})`;
68
+ return `[${names2.row(s.row) ?? s.row}](${s.row})`;
69
+ }).join("");
70
+ }
71
+ function plainText(segments, names2) {
72
+ return segments.map((s) => {
73
+ if (typeof s === "string") return s;
74
+ if ("node" in s) return s.text ?? names2.node(s.node) ?? s.node;
75
+ return names2.row(s.row) ?? s.row;
76
+ }).join("");
77
+ }
78
+
79
+ // packages/plugin-story/logic/calendar.ts
80
+ var EARTH_ID = "earth";
81
+ var NS_PER_SECOND = 1000000000n;
82
+ var EARTH_EPOCH = (-719162n * 86400n * NS_PER_SECOND).toString();
83
+ function freeze(v) {
84
+ if (v && typeof v === "object") {
85
+ for (const x of Object.values(v)) freeze(x);
86
+ Object.freeze(v);
87
+ }
88
+ return v;
89
+ }
90
+ var earth = {
91
+ name: "\uC9C0\uAD6C \uB2EC\uB825",
92
+ epoch: EARTH_EPOCH,
93
+ secondNs: NS_PER_SECOND.toString(),
94
+ day: [
95
+ { name: "\uC2DC", count: 24 },
96
+ { name: "\uBD84", count: 60 },
97
+ { name: "\uCD08", count: 60 }
98
+ ],
99
+ months: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].map((days, i) => ({ name: `${i + 1}\uC6D4`, days })),
100
+ leap: [{ rule: "4,!100,400", month: 2, days: 1 }],
101
+ eras: [
102
+ { name: "\uAE30\uC6D0\uD6C4", start: EARTH_EPOCH, direction: 1 },
103
+ { name: "\uAE30\uC6D0\uC804", direction: -1 }
104
+ ]
105
+ };
106
+ var EARTH = freeze(earth);
107
+ var HIDDEN_ERA = "\uAE30\uC6D0\uD6C4";
108
+ var MAX_PERIOD = 1e5;
109
+ var TOP_KEYS = ["name", "epoch", "secondNs", "day", "months", "leap", "eras"];
110
+ var DECIMAL = /^-?\d+$/;
111
+ var Bad = class extends Error {
112
+ };
113
+ var bad = (reason) => {
114
+ throw new Bad(reason);
115
+ };
116
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
117
+ var isCount = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 1;
118
+ var absent = (v) => v === void 0 || v === null;
119
+ function onlyKeys(o, keys, where) {
120
+ for (const k of Object.keys(o)) if (!keys.includes(k)) bad(`${where} has an unknown field: ${k}`);
121
+ }
122
+ function decimal(v, reason) {
123
+ if (typeof v !== "string" || !DECIMAL.test(v)) bad(reason);
124
+ return BigInt(v).toString();
125
+ }
126
+ function label(v, what) {
127
+ if (typeof v !== "string" || v === "" || v !== v.replace(/\s+/g, " ").trim() || /쯤|\?/.test(v)) {
128
+ bad(`The name of ${what} is empty or has characters that cannot be used (spaces at the start or end, double spaces, \uCBE4, ?).`);
129
+ }
130
+ return v;
131
+ }
132
+ function ruleTerms(rule) {
133
+ const unreadable = () => bad(`Could not read the leap year rule: ${JSON.stringify(rule)}. Write it like "4,!100,400".`);
134
+ if (typeof rule !== "string") return unreadable();
135
+ const terms = [];
136
+ const seen = /* @__PURE__ */ new Set();
137
+ for (const part of rule.split(",")) {
138
+ const m = /^\s*(!?)([1-9]\d*)\s*$/.exec(part);
139
+ if (!m) return unreadable();
140
+ if (seen.has(m[2])) bad(`The leap year rule has the same interval twice: ${JSON.stringify(rule)}`);
141
+ seen.add(m[2]);
142
+ const big = BigInt(m[2]);
143
+ terms.push({ n: big > BigInt(MAX_PERIOD) ? MAX_PERIOD + 1 : Number(big), neg: m[1] === "!" });
144
+ }
145
+ return terms;
146
+ }
147
+ var gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
148
+ function normalize(input) {
149
+ if (!isObject(input)) return bad("The calendar data must be an object.");
150
+ const o = input;
151
+ onlyKeys(o, TOP_KEYS, "The calendar data");
152
+ if (typeof o.name !== "string" || o.name.trim() === "") bad("The name of the calendar is empty.");
153
+ const epoch = decimal(o.epoch, "The time of year 1 (epoch) must be decimal integer text.");
154
+ const secondNs = decimal(o.secondNs, "The length of one second (secondNs) must be decimal integer text.");
155
+ if (BigInt(secondNs) <= 0n) bad("The length of one second (secondNs) must be 1 or more.");
156
+ if (!Array.isArray(o.day) || o.day.length === 0) bad("The units of a day (day) are empty.");
157
+ const day = o.day.map((u) => {
158
+ if (!isObject(u)) return bad("A unit of a day must be { name, count }.");
159
+ onlyKeys(u, ["name", "count"], "A unit of a day");
160
+ const name = label(u.name, "a unit of a day");
161
+ if (/^\d/.test(name)) bad(`The name of a unit of a day cannot start with a digit: ${name}`);
162
+ if (!isCount(u.count)) bad(`The count of the unit of a day ${name} must be an integer of 1 or more.`);
163
+ return { name, count: u.count };
164
+ });
165
+ if (!Array.isArray(o.months) || o.months.length === 0) bad("The months (months) are empty.");
166
+ const months = o.months.map((m) => {
167
+ if (!isObject(m)) return bad("A month must be { name, days }.");
168
+ onlyKeys(m, ["name", "days"], "A month");
169
+ const name = label(m.name, "a month");
170
+ if (!isCount(m.days)) bad(`The number of days (days) of the month ${name} must be an integer of 1 or more.`);
171
+ return { name, days: m.days };
172
+ });
173
+ const monthNames = /* @__PURE__ */ new Set();
174
+ for (const m of months) {
175
+ if (monthNames.has(m.name)) bad(`A month name appears twice: ${m.name}`);
176
+ monthNames.add(m.name);
177
+ }
178
+ const leap = [];
179
+ let period = 1;
180
+ if (!absent(o.leap)) {
181
+ if (!Array.isArray(o.leap)) bad("The leap years (leap) must be a list.");
182
+ for (const l of o.leap) {
183
+ if (!isObject(l)) return bad("A leap year rule must be { rule, month, days }.");
184
+ onlyKeys(l, ["rule", "month", "days"], "A leap year rule");
185
+ const terms = ruleTerms(l.rule);
186
+ const month = l.month;
187
+ if (typeof month !== "number" || !Number.isSafeInteger(month) || month < 1 || month > months.length) {
188
+ bad(`The month that gets the extra day in a leap year (month) must be from 1 to ${months.length}.`);
189
+ }
190
+ if (l.days !== 1) bad("The number of days added in a leap year (days) can only be 1 in this version.");
191
+ for (const t of terms) {
192
+ period = period / gcd(period, t.n) * t.n;
193
+ if (period > MAX_PERIOD) bad(`The cycle of the leap year rules (the least common multiple of the intervals) is over ${MAX_PERIOD} years.`);
194
+ }
195
+ leap.push({ rule: terms.map((t) => (t.neg ? "!" : "") + t.n).join(","), month, days: 1 });
196
+ }
197
+ }
198
+ const eras = [];
199
+ if (!absent(o.eras)) {
200
+ if (!Array.isArray(o.eras)) bad("The eras (eras) must be a list.");
201
+ const names2 = /* @__PURE__ */ new Set();
202
+ for (const e of o.eras) {
203
+ if (!isObject(e)) return bad("An era must be { name, start?, direction }.");
204
+ onlyKeys(e, ["name", "start", "direction"], "An era");
205
+ const name = label(e.name, "an era");
206
+ if (/^[\d-]/.test(name)) bad(`The name of an era cannot start with a digit or -: ${name}`);
207
+ if (names2.has(name)) bad(`An era name appears twice: ${name}`);
208
+ names2.add(name);
209
+ if (e.direction !== 1 && e.direction !== -1) bad(`The direction (direction) of the era ${name} must be 1 or -1.`);
210
+ const era = { name, direction: e.direction };
211
+ if (!absent(e.start)) era.start = decimal(e.start, `The start (start) of the era ${name} must be decimal integer text.`);
212
+ eras.push(era);
213
+ }
214
+ if (eras.filter((e) => e.direction === -1).length > 1) bad("There can be only one era that counts backward (direction -1).");
215
+ }
216
+ const data = { name: o.name.trim(), epoch, secondNs, day, months };
217
+ if (leap.length > 0) data.leap = leap;
218
+ if (eras.length > 0) data.eras = eras;
219
+ return data;
220
+ }
221
+ function checkCalendar(input) {
222
+ try {
223
+ return { ok: true, data: normalize(input) };
224
+ } catch (e) {
225
+ if (e instanceof Bad) return { ok: false, reason: e.message };
226
+ throw e;
227
+ }
228
+ }
229
+ function withBase(base, patch) {
230
+ const out = { ...base, ...patch };
231
+ delete out.base;
232
+ return out;
233
+ }
234
+ var floorDiv = (a, b) => {
235
+ const q = a / b;
236
+ return a % b < 0n ? q - 1n : q;
237
+ };
238
+ var mod = (a, b) => {
239
+ const r = a % b;
240
+ return r < 0n ? r + b : r;
241
+ };
242
+ function leapAt(terms, r) {
243
+ for (const t of terms) if (r % t.n === 0) return !t.neg;
244
+ return false;
245
+ }
246
+ function build(d) {
247
+ const second = BigInt(d.secondNs);
248
+ const units = d.day.map((u) => ({ name: u.name, count: BigInt(u.count) }));
249
+ const unitNs = new Array(units.length);
250
+ let len = second;
251
+ for (let i = units.length - 1; i >= 0; i--) {
252
+ unitNs[i] = len;
253
+ len *= units[i].count;
254
+ }
255
+ const months = d.months.map((m) => ({ name: m.name, days: BigInt(m.days) }));
256
+ const base = months.reduce((a, m) => a + m.days, 0n);
257
+ const leaps = (d.leap ?? []).map((l) => ({
258
+ terms: ruleTerms(l.rule).sort((a, b) => b.n - a.n),
259
+ month: l.month - 1,
260
+ days: BigInt(l.days)
261
+ }));
262
+ let periodNum = 1;
263
+ for (const l of leaps) for (const t of l.terms) periodNum = periodNum / gcd(periodNum, t.n) * t.n;
264
+ const cum = new Array(periodNum + 1);
265
+ cum[0] = 0n;
266
+ for (let r = 0; r < periodNum; r++) {
267
+ let extra = 0n;
268
+ for (const l of leaps) if (leapAt(l.terms, r)) extra += l.days;
269
+ cum[r + 1] = cum[r] + base + extra;
270
+ }
271
+ const c = {
272
+ data: d,
273
+ epoch: BigInt(d.epoch),
274
+ dayNs: len,
275
+ unitNs,
276
+ units,
277
+ months,
278
+ base,
279
+ leaps,
280
+ period: BigInt(periodNum),
281
+ periodNum,
282
+ cum,
283
+ cycle: cum[periodNum],
284
+ g1: 0n,
285
+ forward: [],
286
+ backward: null,
287
+ eras: []
288
+ };
289
+ c.g1 = daysTo(c, 1n);
290
+ const list = d.eras ?? [];
291
+ const forward = [];
292
+ list.forEach((e, index) => {
293
+ if (e.direction !== 1) return;
294
+ const start = e.start !== void 0 ? BigInt(e.start) : c.epoch;
295
+ const ys = split(c, start).y;
296
+ forward.push({ name: e.name, dir: 1, ys, start, index, hidden: e.name === HIDDEN_ERA && ys === 1n });
297
+ });
298
+ const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
299
+ forward.sort((a, b) => cmp(b.ys, a.ys) || cmp(b.start, a.start) || a.index - b.index);
300
+ c.forward = forward;
301
+ const bi = list.findIndex((e) => e.direction === -1);
302
+ if (bi >= 0) {
303
+ const e = list[bi];
304
+ let yb = 1n;
305
+ let start = c.epoch;
306
+ if (e.start !== void 0) {
307
+ start = BigInt(e.start);
308
+ yb = split(c, start).y;
309
+ } else if (forward.length > 0) {
310
+ yb = forward.reduce((a, f) => f.ys < a ? f.ys : a, forward[0].ys);
311
+ }
312
+ c.backward = { name: e.name, dir: -1, ys: yb, start, index: bi, hidden: false };
313
+ }
314
+ c.eras = [...forward, ...c.backward ? [c.backward] : []].sort((a, b) => a.index - b.index);
315
+ return c;
316
+ }
317
+ function daysTo(c, y) {
318
+ const q = floorDiv(y, c.period);
319
+ return q * c.cycle + c.cum[Number(y - q * c.period)];
320
+ }
321
+ function yearLength(c, y) {
322
+ const r = Number(mod(y, c.period));
323
+ return c.cum[r + 1] - c.cum[r];
324
+ }
325
+ function yearOfDay(c, d) {
326
+ const q = floorDiv(d, c.cycle);
327
+ const rem = d - q * c.cycle;
328
+ let lo = 0;
329
+ let hi = c.periodNum - 1;
330
+ while (lo < hi) {
331
+ const mid = lo + hi + 1 >> 1;
332
+ if (c.cum[mid] <= rem) lo = mid;
333
+ else hi = mid - 1;
334
+ }
335
+ return q * c.period + BigInt(lo);
336
+ }
337
+ function monthLengths(c, y) {
338
+ const lens = c.months.map((m) => m.days);
339
+ if (c.leaps.length > 0) {
340
+ const r = Number(mod(y, c.period));
341
+ for (const l of c.leaps) if (leapAt(l.terms, r)) lens[l.month] += l.days;
342
+ }
343
+ return lens;
344
+ }
345
+ function split(c, t) {
346
+ const rel = t - c.epoch;
347
+ const dayIndex = floorDiv(rel, c.dayNs);
348
+ let within2 = rel - dayIndex * c.dayNs;
349
+ const d = dayIndex + c.g1;
350
+ const y = yearOfDay(c, d);
351
+ let left = d - daysTo(c, y);
352
+ const lens = monthLengths(c, y);
353
+ let m = 0;
354
+ while (left >= lens[m]) {
355
+ left -= lens[m];
356
+ m++;
357
+ }
358
+ const units = c.unitNs.map((u) => {
359
+ const v = within2 / u;
360
+ within2 -= v * u;
361
+ return v;
362
+ });
363
+ return { y, m, day: left + 1n, units };
364
+ }
365
+ function spanOf(c, p, depth) {
366
+ const at = (days2) => c.epoch + days2 * c.dayNs;
367
+ let days = daysTo(c, p.y) - c.g1;
368
+ if (depth === 0) return { lo: at(days), hi: at(days + yearLength(c, p.y)) };
369
+ const lens = monthLengths(c, p.y);
370
+ for (let i = 0; i < p.m; i++) days += lens[i];
371
+ if (depth === 1) return { lo: at(days), hi: at(days + lens[p.m]) };
372
+ let lo = at(days + p.day - 1n);
373
+ if (depth === 2) return { lo, hi: lo + c.dayNs };
374
+ for (let i = 0; i < depth - 2; i++) lo += p.units[i] * c.unitNs[i];
375
+ return { lo, hi: lo + c.unitNs[depth - 3] };
376
+ }
377
+ var cache = /* @__PURE__ */ new Map();
378
+ var CACHE_SIZE = 64;
379
+ function compile(cal) {
380
+ let key = null;
381
+ try {
382
+ key = JSON.stringify(cal);
383
+ } catch {
384
+ key = null;
385
+ }
386
+ const hit = key !== null ? cache.get(key) : void 0;
387
+ if (hit) return hit;
388
+ const checked = checkCalendar(cal);
389
+ if (!checked.ok) throw new Error(`The calendar data is wrong: ${checked.reason}`);
390
+ const c = build(checked.data);
391
+ if (key !== null) {
392
+ if (cache.size >= CACHE_SIZE) cache.delete(cache.keys().next().value);
393
+ cache.set(key, c);
394
+ }
395
+ return c;
396
+ }
397
+ var depthOf = (c, depth) => Math.max(0, Math.min(c.units.length + 2, Number.isFinite(depth) ? Math.trunc(depth) : 0));
398
+ function yearText(c, y) {
399
+ const f = c.forward.find((e) => e.ys <= y);
400
+ if (f) {
401
+ const n = y - f.ys + 1n;
402
+ return f.hidden ? `${n}\uB144` : `${f.name} ${n}\uB144`;
403
+ }
404
+ const b = c.backward;
405
+ if (b && y < b.ys) return `${b.name} ${b.ys - y}\uB144`;
406
+ return `${y}\uB144`;
407
+ }
408
+ function partsText(c, p, depth) {
409
+ const out = [yearText(c, p.y)];
410
+ if (depth >= 1) out.push(c.months[p.m].name);
411
+ if (depth >= 2) out.push(`${p.day}\uC77C`);
412
+ for (let i = 0; i < depth - 2; i++) out.push(`${p.units[i]}${c.units[i].name}`);
413
+ return out.join(" ");
414
+ }
415
+ function formatAt(t, cal, depth) {
416
+ const c = compile(cal);
417
+ return partsText(c, split(c, t), depthOf(c, depth));
418
+ }
419
+ function formatSpan(lo, hi, cal) {
420
+ const c = compile(cal);
421
+ const p = split(c, lo);
422
+ const max = c.units.length + 2;
423
+ for (let d = 0; d <= max; d++) {
424
+ const s = spanOf(c, p, d);
425
+ if (s.lo === lo && s.hi === hi) return partsText(c, p, d);
426
+ }
427
+ return `${partsText(c, p, max)} ~ ${partsText(c, split(c, hi), max)}`;
428
+ }
429
+ var BIG_UNITS = [
430
+ { name: "\uB9CC", value: 10n ** 4n },
431
+ { name: "\uC5B5", value: 10n ** 8n },
432
+ { name: "\uC870", value: 10n ** 12n },
433
+ { name: "\uACBD", value: 10n ** 16n }
434
+ ];
435
+ var roundDiv = (a, b) => (2n * a + b) / (2n * b);
436
+ function amount(ns, len, word) {
437
+ const v = roundDiv(ns, len);
438
+ if (v < 10000n) return `${v}${word}`;
439
+ let i = 0;
440
+ while (i + 1 < BIG_UNITS.length && v >= BIG_UNITS[i + 1].value) i++;
441
+ for (; ; ) {
442
+ const tenths = roundDiv(ns * 10n, len * BIG_UNITS[i].value);
443
+ if (tenths >= 100000n && i + 1 < BIG_UNITS.length) {
444
+ i++;
445
+ continue;
446
+ }
447
+ const frac = tenths % 10n;
448
+ return `${tenths / 10n}${frac === 0n ? "" : `.${frac}`}${BIG_UNITS[i].name} ${word}`;
449
+ }
450
+ }
451
+ function formatGap(ns, cal) {
452
+ const c = compile(cal);
453
+ const n = ns < 0n ? -ns : ns;
454
+ const scale = [
455
+ { len: c.base * c.dayNs, word: "\uB144" },
456
+ { len: c.dayNs, word: "\uC77C" },
457
+ ...c.units.map((u, i) => ({ len: c.unitNs[i], word: u.name === "\uC2DC" ? "\uC2DC\uAC04" : u.name }))
458
+ ];
459
+ const pick = scale.find((s) => n >= s.len) ?? scale[scale.length - 1];
460
+ return `\u2248 ${amount(n, pick.len, pick.word)}`;
461
+ }
462
+ function exampleText(cal) {
463
+ const c = compile(cal);
464
+ const earthLike = c.forward.some((e) => e.hidden);
465
+ const era = earthLike ? void 0 : c.eras.find((e) => e.dir === 1 && !e.hidden);
466
+ const y = earthLike ? 1999n : era ? era.ys : 1n;
467
+ const m = Math.min(2, c.months.length - 1);
468
+ const lens = monthLengths(c, y);
469
+ const day = lens[m] < 4n ? lens[m] : 4n;
470
+ const year = earthLike ? "1999\uB144" : era ? `${era.name} 1\uB144` : "1\uB144";
471
+ return `${year} ${c.months[m].name} ${day}\uC77C`;
472
+ }
473
+ var GROUP = /(\d{1,3}(?:,\d{3})+|\d+) ?([만억조경])?/y;
474
+ var DIGITS = /\d+/y;
475
+ var DAY = /(\d+) ?일/y;
476
+ var sp = (s, pos) => s[pos] === " " ? pos + 1 : pos;
477
+ function candidates(names2, s, pos) {
478
+ const edge = (n) => pos + n.length === s.length || s[pos + n.length] === " " ? 0 : 1;
479
+ return names2.map((name, index) => ({ name, index })).filter((x) => s.startsWith(x.name, pos)).sort((a, b) => edge(a.name) - edge(b.name) || b.name.length - a.name.length || a.index - b.index).map((x) => x.name);
480
+ }
481
+ function readYearNumber(s, pos) {
482
+ let total = 0n;
483
+ let last = null;
484
+ let p = pos;
485
+ let any = false;
486
+ for (; ; ) {
487
+ GROUP.lastIndex = p;
488
+ const g = GROUP.exec(s);
489
+ if (!g) break;
490
+ const v = BigInt(g[1].replace(/,/g, ""));
491
+ any = true;
492
+ p = GROUP.lastIndex;
493
+ if (!g[2]) {
494
+ total += v;
495
+ break;
496
+ }
497
+ const u = BIG_UNITS.find((b) => b.name === g[2]).value;
498
+ if (last !== null && u >= last) return null;
499
+ total += v * u;
500
+ last = u;
501
+ if (s[p] === " " && /\d/.test(s[p + 1] ?? "")) p++;
502
+ else if (!/\d/.test(s[p] ?? "")) break;
503
+ }
504
+ if (!any) return null;
505
+ p = sp(s, p);
506
+ if (s[p] !== "\uB144") return null;
507
+ return { n: total, end: p + 1 };
508
+ }
509
+ function readRest(c, s, pos, y) {
510
+ if (pos === s.length) return spanOf(c, { y, m: 0, day: 1n, units: [] }, 0);
511
+ const p = sp(s, pos);
512
+ const names2 = c.months.map((m) => m.name);
513
+ for (const name of candidates(names2, s, p)) {
514
+ const r = readDay(c, s, p + name.length, y, names2.indexOf(name));
515
+ if (r) return r;
516
+ }
517
+ return null;
518
+ }
519
+ function readDay(c, s, pos, y, m) {
520
+ if (pos === s.length) return spanOf(c, { y, m, day: 1n, units: [] }, 1);
521
+ DAY.lastIndex = sp(s, pos);
522
+ const dm = DAY.exec(s);
523
+ if (!dm) return null;
524
+ const day = BigInt(dm[1]);
525
+ if (day < 1n || day > monthLengths(c, y)[m]) return null;
526
+ let at = DAY.lastIndex;
527
+ const units = [];
528
+ while (at !== s.length) {
529
+ const unit = c.units[units.length];
530
+ if (!unit) return null;
531
+ DIGITS.lastIndex = sp(s, at);
532
+ const nm = DIGITS.exec(s);
533
+ if (!nm) return null;
534
+ let e = DIGITS.lastIndex;
535
+ if (!s.startsWith(unit.name, e)) {
536
+ if (s[e] === " " && s.startsWith(unit.name, e + 1)) e++;
537
+ else return null;
538
+ }
539
+ const v = BigInt(nm[0]);
540
+ if (v >= unit.count) return null;
541
+ units.push(v);
542
+ at = e + unit.name.length;
543
+ }
544
+ return spanOf(c, { y, m, day, units }, 2 + units.length);
545
+ }
546
+ function readTime(c, s, pos, era) {
547
+ let neg = false;
548
+ if (!era && s[pos] === "-") {
549
+ neg = true;
550
+ pos++;
551
+ }
552
+ const num = readYearNumber(s, pos);
553
+ if (!num) return null;
554
+ let y;
555
+ if (era) {
556
+ if (num.n < 1n) return null;
557
+ y = era.dir === 1 ? era.ys + num.n - 1n : era.ys - num.n;
558
+ } else {
559
+ y = neg ? -num.n : num.n;
560
+ }
561
+ return readRest(c, s, num.end, y);
562
+ }
563
+ function parseTime(text, cal) {
564
+ const c = compile(cal);
565
+ if (typeof text !== "string") return null;
566
+ const s = text.replace(/쯤|\?/g, "").replace(/\s+/g, " ").trim();
567
+ if (s === "") return null;
568
+ const names2 = c.eras.map((e) => e.name);
569
+ for (const name of candidates(names2, s, 0)) {
570
+ const r = readTime(c, s, sp(s, name.length), c.eras[names2.indexOf(name)]);
571
+ if (r) return r;
572
+ }
573
+ const plain = readTime(c, s, 0, null);
574
+ if (plain) return plain;
575
+ if (c.backward && s.endsWith("\uC804")) return readTime(c, s.slice(0, -1).trimEnd(), 0, c.backward);
576
+ return null;
577
+ }
578
+
579
+ // packages/plugin-story/logic/index.ts
580
+ var PACKAGE_ID = "aic.story";
581
+ var VERSION = "0.4.5";
582
+ var SELECTION_FORMAT = "aic.story/selection-1";
583
+ var SELECTION_LINES = 12;
584
+ var MEMO_ID = /^memo\d+$/;
585
+ var Reject = class extends Error {
586
+ constructor(code, message) {
587
+ super(message);
588
+ this.code = code;
589
+ }
590
+ code;
591
+ };
592
+ var all = (s, type) => Object.values(s.records).filter((r) => r.type === type);
593
+ var byIdNumber = (a, b) => {
594
+ const na = Number(a.id.replace(/\D/g, ""));
595
+ const nb = Number(b.id.replace(/\D/g, ""));
596
+ return na - nb || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
597
+ };
598
+ var keyOf = (r) => sortKey(r.content.order, r.id);
599
+ function rowsOf(s, list) {
600
+ return all(s, "row").filter((r) => r.content.list === list).sort((a, b) => keyOf(a) < keyOf(b) ? -1 : 1);
601
+ }
602
+ function containerOf(s, r) {
603
+ const g = r.type === "group" ? r.content.parent : r.type === "row" ? r.content.group ?? null : null;
604
+ return g && s.records[g]?.type === "group" ? g : null;
605
+ }
606
+ var isSceneOrGroup = (r) => r.type === "group" || r.type === "row" && r.content.list === "scene";
607
+ function sceneTree(s) {
608
+ const children = /* @__PURE__ */ new Map();
609
+ for (const r of Object.values(s.records)) {
610
+ if (!isSceneOrGroup(r)) continue;
611
+ const c = containerOf(s, r);
612
+ const xs = children.get(c);
613
+ if (xs) xs.push(r);
614
+ else children.set(c, [r]);
615
+ }
616
+ for (const xs of children.values()) xs.sort((a, b) => keyOf(a) < keyOf(b) ? -1 : 1);
617
+ const scenes = [];
618
+ const groups = [];
619
+ const depth = /* @__PURE__ */ new Map();
620
+ const flat = [];
621
+ const placed = /* @__PURE__ */ new Map();
622
+ const seen = /* @__PURE__ */ new Set();
623
+ const place = (container, r) => {
624
+ const xs = placed.get(container);
625
+ if (xs) xs.push(r);
626
+ else placed.set(container, [r]);
627
+ };
628
+ const walk = (container, d) => {
629
+ for (const r of children.get(container) ?? []) {
630
+ if (seen.has(r.id)) continue;
631
+ seen.add(r.id);
632
+ depth.set(r.id, d);
633
+ flat.push({ r, depth: d });
634
+ place(container, r);
635
+ if (r.type === "group") {
636
+ groups.push(r);
637
+ walk(r.id, d + 1);
638
+ } else scenes.push(r);
639
+ }
640
+ };
641
+ walk(null, 0);
642
+ const stray = Object.values(s.records).filter((r) => r.type === "group" && !seen.has(r.id)).sort(byIdNumber);
643
+ for (const r of stray) {
644
+ if (seen.has(r.id)) continue;
645
+ seen.add(r.id);
646
+ depth.set(r.id, 0);
647
+ flat.push({ r, depth: 0 });
648
+ place(null, r);
649
+ groups.push(r);
650
+ walk(r.id, 1);
651
+ }
652
+ return { children, placed, scenes, groups, depth, flat };
653
+ }
654
+ var scenesOf = (s) => sceneTree(s).scenes;
655
+ function within(s, container, group) {
656
+ const seen = /* @__PURE__ */ new Set();
657
+ for (let g = container; g && !seen.has(g); g = s.records[g]?.content?.parent ?? null) {
658
+ if (g === group) return true;
659
+ seen.add(g);
660
+ }
661
+ return false;
662
+ }
663
+ function groupName(s, id) {
664
+ if (id === null) return "the top level";
665
+ const c = s.records[id]?.content;
666
+ return c ? `group "${c.title}"` : `group ${id}`;
667
+ }
668
+ function sceneCount(t, group) {
669
+ let n = 0;
670
+ for (const r of t.placed.get(group) ?? []) n += r.type === "group" ? sceneCount(t, r.id) : 1;
671
+ return n;
672
+ }
673
+ function withGroup(c, container) {
674
+ const { group: _g, ...rest } = c;
675
+ return container ? { ...rest, group: container } : rest;
676
+ }
677
+ function placeInput(s, input, key, self, none) {
678
+ const after = afterInput(input);
679
+ let a;
680
+ if (typeof after === "string") {
681
+ a = need(s, after, ["row", "group"], "previous scene or group");
682
+ if (a.type === "row" && a.content.list !== "scene") throw new Reject("INVALID_INPUT", `${after} is a fact row. Give a scene or a group in the scene list`);
683
+ if (self && a.id === self.id) throw new Reject("INVALID_INPUT", "Cannot move it after itself");
684
+ }
685
+ let container;
686
+ if (key in input && input[key] !== void 0) {
687
+ const v = input[key];
688
+ container = v === null ? null : need(s, v, ["group"], "group").id;
689
+ } else if (a) container = containerOf(s, a);
690
+ else if (after === null) container = self ? containerOf(s, self) : null;
691
+ else return none();
692
+ if (a && containerOf(s, a) !== container) throw new Reject("INVALID_INPUT", `${a.id} is not in ${groupName(s, container)}`);
693
+ if (self?.type === "group" && within(s, container, self.id)) throw new Reject("INVALID_INPUT", `Cannot move ${groupName(s, self.id)} into itself`);
694
+ return { container, after };
695
+ }
696
+ function linesOf(s, parent) {
697
+ return all(s, "line").filter((r) => r.content.parent === parent).sort((a, b) => keyOf(a) < keyOf(b) ? -1 : 1);
698
+ }
699
+ function parasOf(s, scene) {
700
+ return all(s, "para").filter((r) => r.content.scene === scene).sort((a, b) => keyOf(a) < keyOf(b) ? -1 : 1);
701
+ }
702
+ function isScene(s, id) {
703
+ const r = s.records[id];
704
+ return r?.type === "row" && r.content.list === "scene";
705
+ }
706
+ function paraLabel(s, id) {
707
+ const scene = s.records[id]?.content?.scene;
708
+ const k = scene ? scenesOf(s).findIndex((x) => x.id === scene) : -1;
709
+ return k >= 0 ? `paragraph ${id} of scene ${k + 1}` : `paragraph ${id}`;
710
+ }
711
+ function rowLabel(s, id) {
712
+ const r = s.records[id];
713
+ if (!r || r.type !== "row") return void 0;
714
+ const c = r.content;
715
+ if (c.list === "fact") return c.title ? `Fact: ${c.title}` : "Fact";
716
+ const k = scenesOf(s).findIndex((x) => x.id === id);
717
+ return c.title ? `Scene ${k + 1}: ${c.title}` : `Scene ${k + 1}`;
718
+ }
719
+ function names(s) {
720
+ return {
721
+ node: (id) => s.records[id]?.content?.name,
722
+ row: (id) => rowLabel(s, id)
723
+ };
724
+ }
725
+ function need(s, id, types, what) {
726
+ if (typeof id !== "string" || id === "") throw new Reject("INVALID_INPUT", `The ${what} id is required`);
727
+ const r = s.records[id];
728
+ if (!r) throw new Reject("TARGET_NOT_FOUND", `Cannot find the ${what} ${id}`);
729
+ if (!types.includes(r.type)) throw new Reject("INVALID_INPUT", `${id} is not a ${what}`);
730
+ return r;
731
+ }
732
+ function textInput(input, key, ctx, what) {
733
+ const v = input[key];
734
+ if (typeof v !== "string" || v.trim() === "") throw new Reject("INVALID_INPUT", `The ${what} is empty`);
735
+ guardTemp(v, ctx);
736
+ return v;
737
+ }
738
+ function optText(input, key, ctx) {
739
+ const v = input[key];
740
+ if (v === void 0 || v === null) return void 0;
741
+ if (typeof v !== "string") throw new Reject("INVALID_INPUT", `${key} must be text`);
742
+ guardTemp(v, ctx);
743
+ return v;
744
+ }
745
+ function guardTemp(text, ctx) {
746
+ if (ctx.tempNames.includes(text)) throw new Reject("INVALID_INPUT", `"${text}" is the same as a temporary name in this request, so it cannot be used as text`);
747
+ }
748
+ function toSegments(s, text, ctx) {
749
+ const out = [];
750
+ for (const part of parseMarks(text)) {
751
+ if (typeof part === "string") {
752
+ guardTemp(part, ctx);
753
+ out.push(part);
754
+ continue;
755
+ }
756
+ const { id, text: shown } = part.mark;
757
+ const rec = s.records[id];
758
+ if (!rec) throw new Reject("TARGET_NOT_FOUND", `Cannot find ${id} that a mark in the text points to: [${shown}](${id})`);
759
+ if (rec.type === "node") {
760
+ const name = rec.content.name;
761
+ out.push(shown === "" || shown === name ? { node: id } : { node: id, text: shown });
762
+ } else if (rec.type === "row") {
763
+ out.push({ row: id });
764
+ } else {
765
+ throw new Reject("INVALID_INPUT", `A mark in the text can point only to a node, a fact or a scene: ${id}`);
766
+ }
767
+ }
768
+ return out;
769
+ }
770
+ function positionInput(input) {
771
+ const p = input.position;
772
+ if (p === void 0 || p === null) return void 0;
773
+ if (!Array.isArray(p) || p.length !== 2 || !p.every((x) => typeof x === "number" && Number.isFinite(x))) {
774
+ throw new Reject("INVALID_INPUT", "position must be a list of two numbers");
775
+ }
776
+ return [p[0], p[1]];
777
+ }
778
+ var ATTACHED_POS = [1, 0];
779
+ var DETACHED_POS = [0.95, 0.05];
780
+ function newOrder(sibs, afterId, self) {
781
+ const list = sibs.filter((r) => r.id !== self);
782
+ let leftIdx;
783
+ if (afterId === void 0) leftIdx = list.length - 1;
784
+ else if (afterId === null) leftIdx = -1;
785
+ else leftIdx = list.findIndex((r) => r.id === afterId);
786
+ const left = leftIdx >= 0 ? list[leftIdx] : void 0;
787
+ const right = list[leftIdx + 1];
788
+ const leftKey2 = left ? left.id.startsWith("$") ? boundAfterOrder(left.content.order) : keyOf(left) : void 0;
789
+ const rightKey2 = right ? right.id.startsWith("$") ? right.content.order : keyOf(right) : void 0;
790
+ return orderBetween(leftKey2, rightKey2);
791
+ }
792
+ var leftKey = (r) => r.id.startsWith("$") ? boundAfterOrder(r.content.order) : keyOf(r);
793
+ var rightKey = (r) => r.id.startsWith("$") ? r.content.order : keyOf(r);
794
+ function itemsInput(s, v) {
795
+ if (v === void 0) return [];
796
+ if (!Array.isArray(v)) throw new Reject("INVALID_INPUT", "items must be a list of scene and group ids");
797
+ const out = [];
798
+ for (const x of v) {
799
+ const r = need(s, x, ["row", "group"], "scene or group to put in");
800
+ if (r.type === "row" && r.content.list !== "scene") throw new Reject("INVALID_INPUT", `${r.id} is a fact row. A group holds only scenes and groups`);
801
+ if (!out.some((y) => y.id === r.id)) out.push(r);
802
+ }
803
+ return out;
804
+ }
805
+ var countOf = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
806
+ function countText(items) {
807
+ const scenes = items.filter((x) => x.type === "row").length;
808
+ return [scenes ? countOf(scenes, "scene") : "", items.length - scenes ? countOf(items.length - scenes, "group") : ""].filter(Boolean).join(" and ");
809
+ }
810
+ function intoGroup(items, container, lo, hi) {
811
+ let prev = lo;
812
+ return items.map((r) => {
813
+ const order = orderBetween(prev, hi);
814
+ prev = boundAfterOrder(order);
815
+ return r.type === "group" ? { id: r.id, type: "group", after: { ...r.content, parent: container, order }, moved: true } : { id: r.id, type: "row", after: withGroup({ ...r.content, order }, container), moved: true };
816
+ });
817
+ }
818
+ function afterInput(input) {
819
+ const v = input.after;
820
+ if (v === void 0 || v === null) return v;
821
+ if (typeof v !== "string") throw new Reject("INVALID_INPUT", "after must be the id of the item before");
822
+ return v;
823
+ }
824
+ function posRefs(after) {
825
+ return typeof after === "string" ? { after } : void 0;
826
+ }
827
+ function sceneInput(s, v) {
828
+ const r = need(s, v, ["row"], "scene");
829
+ if (r.content.list !== "scene") throw new Reject("INVALID_INPUT", `${r.id} is not a scene. Only scenes have body text`);
830
+ return r;
831
+ }
832
+ var CLIP = 40;
833
+ var clip = (t) => t.length > CLIP ? `${t.slice(0, CLIP)}...` : t;
834
+ var AROUND = 12;
835
+ var SPAN = 80;
836
+ function changedParts(before, after) {
837
+ const a = Array.from(before);
838
+ const b = Array.from(after);
839
+ let p = 0;
840
+ while (p < a.length && p < b.length && a[p] === b[p]) p += 1;
841
+ let q = 0;
842
+ while (q < a.length - p && q < b.length - p && a[a.length - 1 - q] === b[b.length - 1 - q]) q += 1;
843
+ const part = (x) => {
844
+ const from = Math.max(0, p - AROUND);
845
+ const to = Math.min(x.length, x.length - q + AROUND);
846
+ const mid = x.slice(from, to);
847
+ const cut = mid.length > SPAN;
848
+ return `${from > 0 ? "..." : ""}${(cut ? mid.slice(0, SPAN) : mid).join("")}${cut || to < x.length ? "..." : ""}`;
849
+ };
850
+ return [part(a), part(b)];
851
+ }
852
+ var quote = (s, text) => `"${plainText(text, names(s))}"`;
853
+ function replaceMark(segments, match) {
854
+ const out = [];
855
+ for (const seg of segments) {
856
+ const replaced = typeof seg === "string" ? seg : match(seg) ?? seg;
857
+ const last = out[out.length - 1];
858
+ if (typeof replaced === "string" && typeof last === "string") out[out.length - 1] = last + replaced;
859
+ else out.push(replaced);
860
+ }
861
+ return out;
862
+ }
863
+ function unmarkChanges(s, removed, match) {
864
+ const out = [];
865
+ for (const r of [...all(s, "line"), ...all(s, "para")]) {
866
+ if (removed.has(r.id)) continue;
867
+ const c = r.content;
868
+ const next = replaceMark(c.text, match);
869
+ if (JSON.stringify(next) !== JSON.stringify(c.text)) out.push({ id: r.id, type: r.type, after: { ...c, text: next } });
870
+ }
871
+ return out;
872
+ }
873
+ function splitParagraphs(text) {
874
+ return text.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "");
875
+ }
876
+ function adopt(s, input, id, ctx) {
877
+ const art = ctx.artifact;
878
+ if (!art) throw new Reject("INVALID_INPUT", "artifact_required: send body.adopt with an artifact attached to the apply_operation request");
879
+ const mode = input.mode === void 0 || input.mode === null ? "replace" : input.mode;
880
+ if (mode !== "replace" && mode !== "append") throw new Reject("INVALID_INPUT", "mode must be replace or append");
881
+ const changes = [];
882
+ const done = [];
883
+ const skipped = [];
884
+ let k = 0;
885
+ for (const sec of art.sections) {
886
+ if (!isScene(s, sec.key)) {
887
+ skipped.push(`Skipped ${sec.label} because it was removed`);
888
+ continue;
889
+ }
890
+ const texts = splitParagraphs(sec.text);
891
+ if (texts.length === 0) {
892
+ skipped.push(`Skipped ${sec.label} because its text in the output is empty`);
893
+ continue;
894
+ }
895
+ for (const t of texts) guardTemp(t, ctx);
896
+ const old = parasOf(s, sec.key);
897
+ if (mode === "replace") for (const b of old) changes.push({ id: b.id, type: "para", after: null });
898
+ const last = mode === "append" ? old[old.length - 1] : void 0;
899
+ let prev;
900
+ texts.forEach((t, i) => {
901
+ const order = i === 0 ? orderBetween(last ? keyOf(last) : void 0, void 0) : orderBetween(boundAfterOrder(prev), void 0);
902
+ prev = order;
903
+ changes.push({ id: id(k), type: "para", prefix: "b", after: { scene: sec.key, order, text: [t] } });
904
+ k += 1;
905
+ });
906
+ done.push(`${rowLabel(s, sec.key) ?? sec.key} (${countOf(texts.length, "paragraph")}, ${mode === "replace" ? "replaced" : "appended"})`);
907
+ }
908
+ if (done.length === 0) throw new Reject("INVALID_INPUT", `No scene to adopt. Every scene given was removed or has empty text: ${skipped.join(", ")}`);
909
+ return { changes, summary: `Adopted from output ${art.id}: ${done.join(", ")}${skipped.length ? `. ${skipped.join(". ")}` : ""}` };
910
+ }
911
+ function calendarData(s, id) {
912
+ if (!id) return void 0;
913
+ if (id === EARTH_ID) return EARTH;
914
+ const r = s.records[id];
915
+ return r?.type === "calendar" ? r.content.data : void 0;
916
+ }
917
+ function settingsOf(s) {
918
+ return all(s, "settings").sort(byIdNumber)[0];
919
+ }
920
+ function defaultCalendarId(s) {
921
+ const id = settingsOf(s)?.content?.defaultCalendar;
922
+ return calendarData(s, id) ? id : EARTH_ID;
923
+ }
924
+ function worldCalendarId(s, world) {
925
+ const r = world ? s.records[world] : void 0;
926
+ if (r?.type === "world") {
927
+ const c = r.content.calendar;
928
+ if (calendarData(s, c)) return c;
929
+ }
930
+ return defaultCalendarId(s);
931
+ }
932
+ var calendarOf = (s, world) => calendarData(s, worldCalendarId(s, world));
933
+ var worldName = (s, id) => s.records[id]?.content?.name ?? id;
934
+ var byName = (s) => (a, b) => {
935
+ const x = worldName(s, a);
936
+ const y = worldName(s, b);
937
+ return x < y ? -1 : x > y ? 1 : a < b ? -1 : a > b ? 1 : 0;
938
+ };
939
+ function liveWorlds(s, ids) {
940
+ return (ids ?? []).filter((id) => s.records[id]?.type === "world").sort(byName(s));
941
+ }
942
+ var primaryWorld = (s, r) => liveWorlds(s, r.content.meta?.worlds)[0] ?? null;
943
+ var timeKey = (t) => [BigInt(t.lo), BigInt(t.hi)];
944
+ function cmpTime(a, b) {
945
+ const [al, ah] = timeKey(a);
946
+ const [bl, bh] = timeKey(b);
947
+ return al < bl ? -1 : al > bl ? 1 : ah < bh ? -1 : ah > bh ? 1 : 0;
948
+ }
949
+ var shownTime = (s, t, world) => formatSpan(BigInt(t.lo), BigInt(t.hi), calendarOf(s, world));
950
+ function factsInTimeOrder(s) {
951
+ const facts = rowsOf(s, "fact");
952
+ const timed = facts.filter((r) => r.content.time).sort((a, b) => cmpTime(a.content.time, b.content.time));
953
+ return [...timed, ...facts.filter((r) => !r.content.time)];
954
+ }
955
+ function sceneTime(s, r) {
956
+ const meta = r.content.meta;
957
+ if (meta?.time) return { lo: meta.time.lo, hi: meta.time.hi, shown: shownTime(s, meta.time, meta.time.written.world), from: "own", to: null };
958
+ const facts = (meta?.facts ?? []).map((id) => s.records[id]).filter((f) => f?.type === "row" && f.content.list === "fact" && !!f.content.time).sort((a, b) => cmpTime(a.content.time, b.content.time));
959
+ if (facts.length === 0) return null;
960
+ const first = facts[0];
961
+ const last = facts[facts.length - 1];
962
+ const ft = first.content.time;
963
+ let hi = BigInt(ft.hi);
964
+ for (const f of facts) hi = BigInt(f.content.time.hi) > hi ? BigInt(f.content.time.hi) : hi;
965
+ return { lo: ft.lo, hi: hi.toString(), shown: shownTime(s, ft, primaryWorld(s, first)), from: "facts", to: facts.length > 1 ? last.id : null };
966
+ }
967
+ function sceneWorlds(s, r) {
968
+ const meta = r.content.meta;
969
+ const own = liveWorlds(s, meta?.worlds);
970
+ if (own.length) return { worlds: own, from: "own" };
971
+ const set = /* @__PURE__ */ new Set();
972
+ for (const id of meta?.facts ?? []) {
973
+ const f = s.records[id];
974
+ if (f?.type === "row") for (const w of liveWorlds(s, f.content.meta?.worlds)) set.add(w);
975
+ }
976
+ return set.size ? { worlds: liveWorlds(s, [...set]), from: "facts" } : { worlds: [], from: null };
977
+ }
978
+ function factName(s, id) {
979
+ const r = s.records[id];
980
+ if (!r) return id;
981
+ const c = r.content;
982
+ if (c.title) return c.title;
983
+ const first = linesOf(s, id)[0];
984
+ return first ? clip(plainText(first.content.text, names(s))) : id;
985
+ }
986
+ function timeInput(s, v, fallbackWorld, ctx) {
987
+ if (v === void 0) return void 0;
988
+ if (v === null) return null;
989
+ if (typeof v !== "object" || Array.isArray(v)) throw new Reject("INVALID_INPUT", "time is { text, world? }. To clear it, send null");
990
+ const o = v;
991
+ for (const k of Object.keys(o)) if (k !== "text" && k !== "world") throw new Reject("INVALID_INPUT", `The fields of time are text and world: ${k}`);
992
+ const text = textInput(o, "text", ctx, "time text").trim();
993
+ let world;
994
+ if (o.world === void 0) world = fallbackWorld;
995
+ else if (o.world === null) world = null;
996
+ else world = need(s, o.world, ["world"], "world line").id;
997
+ const cal = calendarOf(s, world);
998
+ const span = parseTime(text, cal);
999
+ if (!span) {
1000
+ throw new Reject(
1001
+ "INVALID_INPUT",
1002
+ `time_unreadable: could not read "${text}" with the calendar ${cal.name}. Write it from the largest unit, like "${exampleText(cal)}". Text such as "the morning of the second day" is not a time. Write it in a line instead`
1003
+ );
1004
+ }
1005
+ return { lo: span.lo.toString(), hi: span.hi.toString(), written: { world, text } };
1006
+ }
1007
+ var META_KEYS = { fact: ["worlds"], scene: ["facts", "pov", "time", "worlds"] };
1008
+ function pruneMeta(s, meta) {
1009
+ if (!meta) return void 0;
1010
+ const out = {};
1011
+ const facts = meta.facts?.filter((id) => s.records[id]?.type === "row");
1012
+ if (facts?.length) out.facts = facts;
1013
+ if (meta.pov && s.records[meta.pov]?.type === "node") out.pov = meta.pov;
1014
+ if (meta.time) out.time = meta.time;
1015
+ const worlds = meta.worlds?.filter((id) => s.records[id]?.type === "world");
1016
+ if (worlds?.length) out.worlds = worlds;
1017
+ return Object.keys(out).length ? out : void 0;
1018
+ }
1019
+ var idList = (v, what) => {
1020
+ if (!Array.isArray(v) || !v.every((x) => typeof x === "string" && x !== "")) throw new Reject("INVALID_INPUT", `${what} must be a list of ids. To clear it, send null`);
1021
+ return [...new Set(v)];
1022
+ };
1023
+ function metaInput(s, list, v, current, label2, ctx) {
1024
+ const parts = [];
1025
+ if (v === void 0) return { meta: current, parts };
1026
+ if (v === null || typeof v !== "object" || Array.isArray(v)) throw new Reject("INVALID_INPUT", `meta is a set of field names and values (${META_KEYS[list].join(", ")})`);
1027
+ const o = v;
1028
+ for (const k of Object.keys(o)) {
1029
+ if (!META_KEYS[list].includes(k)) {
1030
+ throw new Reject("INVALID_INPUT", `The metadata fields of a ${list} are ${META_KEYS[list].join(", ")}: ${k}${list === "fact" && k === "time" ? ". Write the time of a fact with time, not meta" : ""}`);
1031
+ }
1032
+ }
1033
+ const meta = { ...current ?? {} };
1034
+ if ("facts" in o) {
1035
+ if (o.facts === null) {
1036
+ delete meta.facts;
1037
+ parts.push(`Cleared the facts of ${label2}`);
1038
+ } else {
1039
+ const ids = idList(o.facts, "facts");
1040
+ for (const id of ids) {
1041
+ const f = need(s, id, ["row"], "fact");
1042
+ if (f.content.list !== "fact") throw new Reject("INVALID_INPUT", `${id} is not a fact. A scene covers fact rows`);
1043
+ }
1044
+ if (ids.length) meta.facts = ids;
1045
+ else delete meta.facts;
1046
+ parts.push(ids.length ? `Facts of ${label2}: ${ids.map((id) => `${factName(s, id)}(${id})`).join(", ")}` : `Cleared the facts of ${label2}`);
1047
+ }
1048
+ }
1049
+ if ("pov" in o) {
1050
+ if (o.pov === null) {
1051
+ delete meta.pov;
1052
+ parts.push(`Cleared the point of view of ${label2}`);
1053
+ } else {
1054
+ const n = need(s, o.pov, ["node"], "point of view character");
1055
+ meta.pov = n.id;
1056
+ parts.push(`Point of view of ${label2}: ${n.content.name}`);
1057
+ }
1058
+ }
1059
+ if ("worlds" in o) {
1060
+ if (o.worlds === null) {
1061
+ delete meta.worlds;
1062
+ parts.push(`Cleared the world lines of ${label2}`);
1063
+ } else {
1064
+ const ids = idList(o.worlds, "worlds").map((id) => need(s, id, ["world"], "world line").id);
1065
+ if (ids.length) meta.worlds = ids;
1066
+ else delete meta.worlds;
1067
+ parts.push(ids.length ? `World lines of ${label2}: ${[...ids].sort(byName(s)).map((id) => worldName(s, id)).join(", ")}` : `Cleared the world lines of ${label2}`);
1068
+ }
1069
+ }
1070
+ if ("time" in o) {
1071
+ const t = timeInput(s, o.time, null, ctx);
1072
+ if (t) meta.time = t;
1073
+ else delete meta.time;
1074
+ parts.push(t ? `Time of ${label2}: ${shownTime(s, t, t.written.world)}` : `Cleared the time of ${label2}`);
1075
+ }
1076
+ return { meta: pruneMeta(s, meta), parts };
1077
+ }
1078
+ function withMeta(c, meta, time) {
1079
+ const { meta: _m, time: _t, ...rest } = c;
1080
+ const out = { ...rest };
1081
+ const t = time === void 0 ? c.time : time;
1082
+ if (t) out.time = t;
1083
+ if (meta) out.meta = meta;
1084
+ return out;
1085
+ }
1086
+ function calendarIdInput(s, v) {
1087
+ if (v === EARTH_ID) return EARTH_ID;
1088
+ return need(s, v, ["calendar"], "calendar").id;
1089
+ }
1090
+ var calendarName = (s, id) => calendarData(s, id)?.name ?? id;
1091
+ function calendarText(d) {
1092
+ const days = new Set(d.months.map((m) => m.days));
1093
+ const months = days.size === 1 ? `${countOf(d.months.length, "month")} a year, ${countOf(d.months[0].days, "day")} each` : `${countOf(d.months.length, "month")} a year (${d.months.map((m) => `${m.name} ${countOf(m.days, "day")}`).join(", ")})`;
1094
+ const leap = d.leap?.length ? `leap years: ${d.leap.map((l) => `in years that match "${l.rule}", add ${countOf(l.days, "day")} to ${d.months[l.month - 1]?.name ?? l.month}`).join(", ")}` : "no leap years";
1095
+ const eraText = (e) => `${e.name} (${e.direction === 1 ? `counted from ${e.start === void 0 ? "year 1" : formatAt(BigInt(e.start), EARTH, 2)}` : "counted backward"})`;
1096
+ const eras = d.eras?.length ? `Eras: ${d.eras.map(eraText).join(", ")}` : "No eras";
1097
+ return `${months}, a day is ${d.day.map((u) => `${u.count}${u.name}`).join(" ")}, ${leap}. Year 1 (its first day) is ${formatAt(BigInt(d.epoch), EARTH, 2)} on the Earth calendar. ${eras}. Written like "${exampleText(d)}"`;
1098
+ }
1099
+ var TIME_OPERATIONS = {
1100
+ "world.add": (s, input, id, ctx) => {
1101
+ const name = textInput(input, "name", ctx, "name");
1102
+ const calendar = input.calendar === void 0 || input.calendar === null ? defaultCalendarId(s) : calendarIdInput(s, input.calendar);
1103
+ const note = optText(input, "note", ctx) ?? "";
1104
+ return {
1105
+ changes: [{ id: id(0), type: "world", prefix: "w", after: { name, calendar, note } }],
1106
+ summary: `Created world line: ${name}, calendar ${calendarName(s, calendar)}`
1107
+ };
1108
+ },
1109
+ "world.update": (s, input, _id, ctx) => {
1110
+ const r = need(s, input.world, ["world"], "world line");
1111
+ const c = r.content;
1112
+ const next = {
1113
+ name: input.name === void 0 ? c.name : textInput(input, "name", ctx, "name"),
1114
+ calendar: input.calendar === void 0 ? c.calendar : calendarIdInput(s, input.calendar),
1115
+ note: optText(input, "note", ctx) ?? c.note
1116
+ };
1117
+ const parts = [];
1118
+ if (next.name !== c.name) parts.push(`name from "${c.name}" to "${next.name}"`);
1119
+ if (next.calendar !== c.calendar) parts.push(`calendar ${calendarName(s, next.calendar)}. Saved times stay the same, and only the shown text changes`);
1120
+ if (next.note !== c.note) parts.push("note changed");
1121
+ return { changes: [{ id: r.id, type: "world", after: next }], summary: `Changed world line (${r.id}): ${parts.join(", ") || "nothing changed"}` };
1122
+ },
1123
+ "world.remove": (s, input) => {
1124
+ const r = need(s, input.world, ["world"], "world line");
1125
+ return {
1126
+ changes: [{ id: r.id, type: "world", after: null }],
1127
+ summary: `Removed world line: ${r.content.name}(${r.id}). It is taken out of the world lines of facts. Times written in that world line stay and are shown with the default calendar`
1128
+ };
1129
+ },
1130
+ "calendar.set": (s, input, id, ctx) => {
1131
+ const raw = input.data;
1132
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) throw new Reject("INVALID_INPUT", 'data is the calendar data. To start from the Earth calendar, set data.base to "earth" and write only the fields to change');
1133
+ const d = raw;
1134
+ let merged = d;
1135
+ if (d.base !== void 0) {
1136
+ const base = calendarData(s, typeof d.base === "string" ? d.base : void 0);
1137
+ if (!base) throw new Reject("INVALID_INPUT", `Cannot find the base calendar ${String(d.base)}. Use "earth" or a calendar id`);
1138
+ merged = withBase(base, d);
1139
+ }
1140
+ const absolute = (v, what) => {
1141
+ if (v === null || typeof v !== "object" || Array.isArray(v)) return v;
1142
+ const o = v;
1143
+ const cal = calendarData(s, typeof o.calendar === "string" ? o.calendar : EARTH_ID);
1144
+ if (!cal) throw new Reject("INVALID_INPUT", `Cannot find the calendar ${String(o.calendar)} to read ${what}`);
1145
+ const span = typeof o.text === "string" ? parseTime(o.text, cal) : null;
1146
+ if (!span) throw new Reject("INVALID_INPUT", `time_unreadable: could not read ${what} "${String(o.text)}" with the calendar ${cal.name}. Write it like "${exampleText(cal)}"`);
1147
+ return span.lo.toString();
1148
+ };
1149
+ merged = { ...merged, epoch: absolute(merged.epoch, "the epoch") };
1150
+ if (Array.isArray(merged.eras)) {
1151
+ merged.eras = merged.eras.map((e) => e && typeof e === "object" && "start" in e ? { ...e, start: absolute(e.start, "the start of the era") } : e);
1152
+ }
1153
+ const checked = checkCalendar(merged);
1154
+ if (!checked.ok) throw new Reject("INVALID_INPUT", `calendar_invalid: ${checked.reason}`);
1155
+ guardTemp(checked.data.name, ctx);
1156
+ if (input.calendar === EARTH_ID) throw new Reject("INVALID_INPUT", 'The Earth calendar cannot be changed. Set data.base to "earth" to make a new calendar copied from it');
1157
+ if (input.calendar === void 0 || input.calendar === null) {
1158
+ return {
1159
+ changes: [{ id: id(0), type: "calendar", prefix: "cal", after: { data: checked.data } }],
1160
+ summary: `Created calendar: ${checked.data.name}`
1161
+ };
1162
+ }
1163
+ const r = need(s, input.calendar, ["calendar"], "calendar");
1164
+ return {
1165
+ changes: [{ id: r.id, type: "calendar", after: { data: checked.data } }],
1166
+ summary: `Changed calendar (${r.id}): ${checked.data.name}. Saved times stay the same, and only the shown text changes`
1167
+ };
1168
+ },
1169
+ "calendar.remove": (s, input) => {
1170
+ const r = need(s, input.calendar, ["calendar"], "calendar");
1171
+ const users = all(s, "world").filter((w) => w.content.calendar === r.id);
1172
+ if (users.length) throw new Reject("INVALID_STATE", `World lines use the calendar ${r.id}: ${users.map((w) => `${w.content.name}(${w.id})`).join(", ")}. Change the calendar of those world lines first`);
1173
+ if (defaultCalendarId(s) === r.id) throw new Reject("INVALID_STATE", `The calendar ${r.id} is the default calendar of the work. Change it first with calendar.setDefault`);
1174
+ return { changes: [{ id: r.id, type: "calendar", after: null }], summary: `Removed calendar: ${r.content.data.name}(${r.id})` };
1175
+ },
1176
+ "calendar.setDefault": (s, input, id) => {
1177
+ const calendar = calendarIdInput(s, input.calendar);
1178
+ const cfg = settingsOf(s);
1179
+ const after = { ...cfg?.content ?? {}, defaultCalendar: calendar };
1180
+ return {
1181
+ changes: [cfg ? { id: cfg.id, type: "settings", after } : { id: id(0), type: "settings", prefix: "cfg", after }],
1182
+ summary: `Default calendar: ${calendarName(s, calendar)}. The shown time of facts without a world line changes`
1183
+ };
1184
+ }
1185
+ };
1186
+ var OPERATIONS = {
1187
+ "node.add": (s, input, id, ctx) => {
1188
+ const name = textInput(input, "name", ctx, "name");
1189
+ const kind = optText(input, "kind", ctx) ?? "character";
1190
+ const note = optText(input, "note", ctx) ?? "";
1191
+ return {
1192
+ changes: [{ id: id(0), type: "node", prefix: "n", after: { name, kind, note } }],
1193
+ summary: `Created ${kind}: ${name}`
1194
+ };
1195
+ },
1196
+ "node.update": (s, input, _id, ctx) => {
1197
+ const r = need(s, input.node, ["node"], "node");
1198
+ const c = r.content;
1199
+ const name = input.name === void 0 ? c.name : textInput(input, "name", ctx, "name");
1200
+ const next = { name, kind: optText(input, "kind", ctx) ?? c.kind, note: optText(input, "note", ctx) ?? c.note };
1201
+ return {
1202
+ changes: [{ id: r.id, type: "node", after: next }],
1203
+ summary: name !== c.name ? `Renamed (${r.id}): from "${c.name}" to "${name}"` : `Changed: ${c.name}(${r.id})`
1204
+ };
1205
+ },
1206
+ "node.remove": (s, input) => {
1207
+ const r = need(s, input.node, ["node"], "node");
1208
+ const c = r.content;
1209
+ const rels = all(s, "relation").filter((x) => {
1210
+ const rc = x.content;
1211
+ return rc.a === r.id || rc.b === r.id;
1212
+ });
1213
+ const removed = /* @__PURE__ */ new Set([r.id, ...rels.map((x) => x.id)]);
1214
+ return {
1215
+ changes: [
1216
+ { id: r.id, type: "node", after: null },
1217
+ ...rels.map((x) => ({ id: x.id, type: "relation", after: null })),
1218
+ ...unmarkChanges(s, removed, (seg) => "node" in seg && seg.node === r.id ? seg.text ?? c.name : null)
1219
+ ],
1220
+ summary: `Removed: ${c.name}(${r.id})`
1221
+ };
1222
+ },
1223
+ "relation.add": (s, input, id, ctx) => {
1224
+ const a = need(s, input.a, ["node"], "node");
1225
+ const b = need(s, input.b, ["node"], "node");
1226
+ if (a.id === b.id) throw new Reject("INVALID_INPUT", "The two nodes of a relation must be different");
1227
+ const name = optText(input, "name", ctx) ?? "related";
1228
+ return {
1229
+ changes: [{ id: id(0), type: "relation", prefix: "r", after: { a: a.id, b: b.id, name } }],
1230
+ summary: `${a.content.name}, ${b.content.name}: ${name}`
1231
+ };
1232
+ },
1233
+ "relation.update": (s, input, _id, ctx) => {
1234
+ const r = need(s, input.relation, ["relation"], "relation");
1235
+ const name = textInput(input, "name", ctx, "name");
1236
+ return {
1237
+ changes: [{ id: r.id, type: "relation", after: { ...r.content, name } }],
1238
+ summary: `Renamed relation (${r.id}): ${name}`
1239
+ };
1240
+ },
1241
+ "relation.remove": (s, input) => {
1242
+ const r = need(s, input.relation, ["relation"], "relation");
1243
+ return { changes: [{ id: r.id, type: "relation", after: null }], summary: `Removed relation: ${r.id}` };
1244
+ },
1245
+ "row.add": (s, input, id, ctx) => {
1246
+ const list = input.list;
1247
+ if (list !== "fact" && list !== "scene") throw new Reject("INVALID_INPUT", "list must be fact or scene");
1248
+ if (list === "fact" && input.group !== void 0) throw new Reject("INVALID_INPUT", "Facts are not grouped. Only scenes go into groups");
1249
+ const after = afterInput(input);
1250
+ if (list === "fact" && typeof after === "string") {
1251
+ const a = need(s, after, ["row"], "previous row");
1252
+ if (a.content.list !== list) throw new Reject("INVALID_INPUT", `${after} is a row in the other list`);
1253
+ }
1254
+ const place = list === "scene" ? placeInput(s, input, "group", null, () => {
1255
+ const last = scenesOf(s).at(-1);
1256
+ return last ? { container: containerOf(s, last), after: last.id } : { container: null, after: void 0 };
1257
+ }) : null;
1258
+ const rowId = id(0);
1259
+ const title = optText(input, "title", ctx);
1260
+ if (list === "scene" && input.time !== void 0) throw new Reject("INVALID_INPUT", "Write the time of a scene with meta.time, not time");
1261
+ const label2 = list === "fact" ? `fact ${rowId}` : "the new scene";
1262
+ const m = metaInput(s, list, input.meta, void 0, label2, ctx);
1263
+ const time = list === "fact" ? timeInput(s, input.time, liveWorlds(s, m.meta?.worlds)[0] ?? null, ctx) : void 0;
1264
+ const order = place ? newOrder(sceneTree(s).children.get(place.container) ?? [], place.after) : newOrder(rowsOf(s, list), after);
1265
+ const content = withGroup(withMeta({ list, order, ...title ? { title } : {} }, m.meta, time), place?.container ?? null);
1266
+ const changes = [{ id: rowId, type: "row", prefix: list === "fact" ? "f" : "s", after: content, refs: posRefs(after) }];
1267
+ const texts = input.lines === void 0 ? [] : input.lines;
1268
+ if (!Array.isArray(texts)) throw new Reject("INVALID_INPUT", "lines must be a list of text");
1269
+ let prevOrder;
1270
+ const planning = { records: { ...s.records, [rowId]: { id: rowId, type: "row", owner: null, content } } };
1271
+ texts.forEach((t, i) => {
1272
+ if (typeof t !== "string" || t.trim() === "") throw new Reject("INVALID_INPUT", "A line is empty");
1273
+ const order2 = orderBetween(prevOrder === void 0 ? void 0 : boundAfterOrder(prevOrder), void 0);
1274
+ prevOrder = order2;
1275
+ changes.push({ id: id(i + 1), type: "line", prefix: "l", after: { parent: rowId, order: order2, text: toSegments(planning, t, ctx) } });
1276
+ });
1277
+ const shown = texts.length ? `: ${texts.map((t) => plainText(toSegments(planning, t, ctx), names(planning))).join(" / ")}` : "";
1278
+ const extra = [...time ? [`Time ${shownTime(s, time, time.written.world)}`] : [], ...place?.container ? [`In ${groupName(s, place.container)}`] : [], ...m.parts];
1279
+ return { changes, summary: `Added ${list} (${rowId})${shown}${extra.length ? `. ${extra.join(". ")}` : ""}` };
1280
+ },
1281
+ "row.move": (s, input) => {
1282
+ const r = need(s, input.row, ["row"], "row");
1283
+ const c = r.content;
1284
+ if (c.list === "scene") {
1285
+ const from = containerOf(s, r);
1286
+ const { container, after: after2 } = placeInput(s, input, "group", r, () => {
1287
+ throw new Reject("INVALID_INPUT", "after or group is required. To move it to the front, send after as null");
1288
+ });
1289
+ const order = newOrder(sceneTree(s).children.get(container) ?? [], after2, r.id);
1290
+ const where = container !== from ? ` into ${groupName(s, container)}` : "";
1291
+ return {
1292
+ changes: [{ id: r.id, type: "row", after: withGroup(withMeta({ ...c, order }, pruneMeta(s, c.meta), void 0), container), refs: posRefs(after2), moved: true }],
1293
+ summary: `Moved (${r.id})${where}: ${after2 ? `after ${after2}` : after2 === null ? "to the front" : "to the end"}`
1294
+ };
1295
+ }
1296
+ if (input.group !== void 0) throw new Reject("INVALID_INPUT", "Facts are not grouped. Only scenes go into groups");
1297
+ const after = afterInput(input);
1298
+ if (after === void 0) throw new Reject("INVALID_INPUT", "after is required. To move it to the front, send null");
1299
+ if (typeof after === "string") {
1300
+ const a = need(s, after, ["row"], "previous row");
1301
+ if (a.id === r.id) throw new Reject("INVALID_INPUT", "Cannot move it after itself");
1302
+ if (a.content.list !== c.list) throw new Reject("INVALID_INPUT", `${after} is a row in the other list`);
1303
+ }
1304
+ const fixed = c.list === "fact" && c.time ? ". It has a time, so its shown position does not change" : "";
1305
+ return {
1306
+ changes: [{ id: r.id, type: "row", after: withMeta({ ...c, order: newOrder(rowsOf(s, c.list), after, r.id) }, pruneMeta(s, c.meta), void 0), refs: posRefs(after), moved: true }],
1307
+ summary: `Moved (${r.id}): ${after ? `after ${after}` : "to the front"}${fixed}`
1308
+ };
1309
+ },
1310
+ "row.update": (s, input, _id, ctx) => {
1311
+ const r = need(s, input.row, ["row"], "row");
1312
+ const c = r.content;
1313
+ if (!("title" in input) && !("time" in input) && !("meta" in input)) throw new Reject("INVALID_INPUT", "One of title, time or meta is required. To clear the title, send title as empty text");
1314
+ if (c.list === "scene" && "time" in input) throw new Reject("INVALID_INPUT", "Write the time of a scene with meta.time, not time. Write it only for a scene that covers no facts");
1315
+ const parts = [];
1316
+ let base = c;
1317
+ if ("title" in input) {
1318
+ const title = optText(input, "title", ctx);
1319
+ const { title: _old, ...rest } = c;
1320
+ base = title ? { ...rest, title } : rest;
1321
+ parts.push(title ? `Changed title (${r.id}): ${title}` : `Cleared title (${r.id})`);
1322
+ }
1323
+ const label2 = c.list === "fact" ? `fact ${r.id}` : (rowLabel(s, r.id) ?? r.id).split(":")[0].toLowerCase();
1324
+ const m = metaInput(s, c.list, input.meta, pruneMeta(s, c.meta), label2, ctx);
1325
+ parts.push(...m.parts);
1326
+ let time;
1327
+ if (c.list === "fact" && "time" in input) {
1328
+ time = timeInput(s, input.time, liveWorlds(s, m.meta?.worlds)[0] ?? null, ctx);
1329
+ parts.push(time ? `Changed time (${r.id}): ${shownTime(s, time, time.written.world)}` : `Removed time (${r.id})`);
1330
+ }
1331
+ return { changes: [{ id: r.id, type: "row", after: withMeta(base, m.meta, time) }], summary: parts.join(". ") };
1332
+ },
1333
+ "row.remove": (s, input) => {
1334
+ const r = need(s, input.row, ["row"], "row");
1335
+ const lines = linesOf(s, r.id);
1336
+ const paras = parasOf(s, r.id);
1337
+ const label2 = rowLabel(s, r.id) ?? r.id;
1338
+ const removed = /* @__PURE__ */ new Set([r.id, ...lines.map((l) => l.id), ...paras.map((b) => b.id)]);
1339
+ const gone = lines.map((l) => plainText(l.content.text, names(s))).join(" / ");
1340
+ return {
1341
+ changes: [
1342
+ { id: r.id, type: "row", after: null },
1343
+ ...lines.map((l) => ({ id: l.id, type: "line", after: null })),
1344
+ ...paras.map((b) => ({ id: b.id, type: "para", after: null })),
1345
+ ...unmarkChanges(s, removed, (seg) => "row" in seg && seg.row === r.id ? label2 : null)
1346
+ ],
1347
+ summary: `Removed: ${label2}(${r.id})${gone ? `, ${gone}` : ""}${paras.length ? `, ${countOf(paras.length, "body paragraph")}` : ""}`
1348
+ };
1349
+ },
1350
+ "group.add": (s, input, id, ctx) => {
1351
+ const title = textInput(input, "title", ctx, "name");
1352
+ const items = itemsInput(s, input.items);
1353
+ const moving = new Set(items.map((x) => x.id));
1354
+ const t = sceneTree(s);
1355
+ const place = placeInput(s, input, "parent", null, () => {
1356
+ if (items.length === 0) return { container: null, after: void 0 };
1357
+ const flat = new Map(t.flat.map((x, i) => [x.r.id, i]));
1358
+ const first = [...items].sort((a, b) => (flat.get(a.id) ?? 0) - (flat.get(b.id) ?? 0))[0];
1359
+ const container = containerOf(s, first);
1360
+ const sibs2 = t.children.get(container) ?? [];
1361
+ const at = sibs2.findIndex((x) => x.id === first.id);
1362
+ const prev = sibs2.slice(0, at).filter((x) => !moving.has(x.id)).at(-1);
1363
+ return { container, after: prev ? prev.id : null };
1364
+ });
1365
+ if (typeof place.after === "string" && moving.has(place.after)) throw new Reject("INVALID_INPUT", `${place.after} goes into the new group, so the new group cannot be placed after it`);
1366
+ for (const it of items) {
1367
+ if (it.type === "group" && (place.container === it.id || within(s, place.container, it.id))) {
1368
+ throw new Reject("INVALID_INPUT", `Cannot put ${groupName(s, it.id)} into a new group made inside it`);
1369
+ }
1370
+ }
1371
+ const gid = id(0);
1372
+ const sibs = (t.children.get(place.container) ?? []).filter((x) => !moving.has(x.id));
1373
+ const changes = [
1374
+ { id: gid, type: "group", prefix: "g", after: { title, parent: place.container, order: newOrder(sibs, place.after) }, refs: posRefs(afterInput(input)) },
1375
+ ...intoGroup(items, gid, void 0, void 0)
1376
+ ];
1377
+ return {
1378
+ changes,
1379
+ summary: `Created group (${gid}): "${title}"${place.container ? `, in ${groupName(s, place.container)}` : ""}${items.length ? `. Put ${countText(items)} into it` : ""}`
1380
+ };
1381
+ },
1382
+ "group.update": (s, input, _id, ctx) => {
1383
+ const g = need(s, input.group, ["group"], "group");
1384
+ const c = g.content;
1385
+ const title = textInput(input, "title", ctx, "name");
1386
+ return { changes: [{ id: g.id, type: "group", after: { ...c, title } }], summary: `Renamed group (${g.id}): from "${c.title}" to "${title}"` };
1387
+ },
1388
+ "group.move": (s, input) => {
1389
+ const g = need(s, input.group, ["group"], "group");
1390
+ const c = g.content;
1391
+ const from = containerOf(s, g);
1392
+ const { container, after } = placeInput(s, input, "parent", g, () => {
1393
+ throw new Reject("INVALID_INPUT", "after or parent is required. To move it to the front, send after as null");
1394
+ });
1395
+ const order = newOrder(sceneTree(s).children.get(container) ?? [], after, g.id);
1396
+ const where = container !== from ? ` into ${groupName(s, container)}` : "";
1397
+ return {
1398
+ changes: [{ id: g.id, type: "group", after: { ...c, parent: container, order }, refs: posRefs(after), moved: true }],
1399
+ summary: `Moved group (${g.id})${where}: ${after ? `after ${after}` : after === null ? "to the front" : "to the end"}`
1400
+ };
1401
+ },
1402
+ "group.remove": (s, input) => {
1403
+ const g = need(s, input.group, ["group"], "group");
1404
+ const c = g.content;
1405
+ const t = sceneTree(s);
1406
+ const container = containerOf(s, g);
1407
+ const sibs = t.children.get(container) ?? [];
1408
+ const at = sibs.findIndex((x) => x.id === g.id);
1409
+ const left = at > 0 ? sibs[at - 1] : void 0;
1410
+ const right = sibs[at + 1];
1411
+ const kids = t.children.get(g.id) ?? [];
1412
+ return {
1413
+ changes: [{ id: g.id, type: "group", after: null }, ...intoGroup(kids, container, left && leftKey(left), right && rightKey(right))],
1414
+ summary: `Removed group (${g.id}): "${c.title}"${kids.length ? `. Moved the ${countText(kids)} inside it up to ${groupName(s, container)}` : ""}`
1415
+ };
1416
+ },
1417
+ "line.add": (s, input, id, ctx) => {
1418
+ const p = need(s, input.parent, ["row"], "row");
1419
+ const after = afterInput(input);
1420
+ if (typeof after === "string") {
1421
+ const a = need(s, after, ["line"], "previous line");
1422
+ if (a.content.parent !== p.id) throw new Reject("INVALID_INPUT", `${after} is not a line of ${p.id}`);
1423
+ }
1424
+ const text = toSegments(s, textInput(input, "text", ctx, "text"), ctx);
1425
+ return {
1426
+ changes: [
1427
+ {
1428
+ id: id(0),
1429
+ type: "line",
1430
+ prefix: "l",
1431
+ after: { parent: p.id, order: newOrder(linesOf(s, p.id), after), text },
1432
+ refs: posRefs(after)
1433
+ }
1434
+ ],
1435
+ summary: `Added line (${p.id}): ${plainText(text, names(s))}`
1436
+ };
1437
+ },
1438
+ "line.update": (s, input, _id, ctx) => {
1439
+ const r = need(s, input.line, ["line"], "line");
1440
+ const c = r.content;
1441
+ const text = toSegments(s, textInput(input, "text", ctx, "text"), ctx);
1442
+ return {
1443
+ changes: [{ id: r.id, type: "line", after: { ...c, text } }],
1444
+ summary: `${r.id}: from ${quote(s, c.text)} to ${quote(s, text)}`
1445
+ };
1446
+ },
1447
+ "line.remove": (s, input) => {
1448
+ const r = need(s, input.line, ["line"], "line");
1449
+ const c = r.content;
1450
+ return {
1451
+ changes: [{ id: r.id, type: "line", after: null }],
1452
+ summary: `Removed line (${r.id}): ${plainText(c.text, names(s))}`
1453
+ };
1454
+ },
1455
+ "para.add": (s, input, id, ctx) => {
1456
+ const scene = sceneInput(s, input.scene);
1457
+ const after = afterInput(input);
1458
+ if (typeof after === "string") {
1459
+ const a = need(s, after, ["para"], "previous paragraph");
1460
+ if (a.content.scene !== scene.id) throw new Reject("INVALID_INPUT", `${after} is not a paragraph of ${scene.id}`);
1461
+ }
1462
+ const text = toSegments(s, textInput(input, "text", ctx, "text"), ctx);
1463
+ return {
1464
+ changes: [
1465
+ {
1466
+ id: id(0),
1467
+ type: "para",
1468
+ prefix: "b",
1469
+ after: { scene: scene.id, order: newOrder(parasOf(s, scene.id), after), text },
1470
+ refs: posRefs(after)
1471
+ }
1472
+ ],
1473
+ summary: `Added paragraph (${scene.id}): ${clip(plainText(text, names(s)))}`
1474
+ };
1475
+ },
1476
+ "para.update": (s, input, _id, ctx) => {
1477
+ const r = need(s, input.para, ["para"], "paragraph");
1478
+ const c = r.content;
1479
+ const text = toSegments(s, textInput(input, "text", ctx, "text"), ctx);
1480
+ const was = plainText(c.text, names(s));
1481
+ const now = plainText(text, names(s));
1482
+ let summary;
1483
+ if (JSON.stringify(c.text) === JSON.stringify(text)) summary = `${r.id}: nothing changed`;
1484
+ else if (was === now) summary = `${r.id}: only the marks in the text changed "${clip(now)}"`;
1485
+ else summary = ((x, y) => `${r.id}: from "${x}" to "${y}"`)(...changedParts(was, now));
1486
+ return { changes: [{ id: r.id, type: "para", after: { ...c, text } }], summary };
1487
+ },
1488
+ "para.remove": (s, input) => {
1489
+ const r = need(s, input.para, ["para"], "paragraph");
1490
+ const c = r.content;
1491
+ return {
1492
+ changes: [{ id: r.id, type: "para", after: null }],
1493
+ summary: `Removed paragraph (${r.id}): ${clip(plainText(c.text, names(s)))}`
1494
+ };
1495
+ },
1496
+ "para.move": (s, input) => {
1497
+ const r = need(s, input.para, ["para"], "paragraph");
1498
+ const c = r.content;
1499
+ const after = afterInput(input);
1500
+ if (after === void 0) throw new Reject("INVALID_INPUT", "after is required. To move it to the front, send null");
1501
+ if (typeof after === "string") {
1502
+ const a = need(s, after, ["para"], "previous paragraph");
1503
+ if (a.id === r.id) throw new Reject("INVALID_INPUT", "Cannot move it after itself");
1504
+ if (a.content.scene !== c.scene) throw new Reject("INVALID_INPUT", `${after} is a paragraph of another scene. To move a paragraph to another scene, remove it and add it there`);
1505
+ }
1506
+ return {
1507
+ changes: [{ id: r.id, type: "para", after: { ...c, order: newOrder(parasOf(s, c.scene), after, r.id) }, refs: posRefs(after), moved: true }],
1508
+ summary: `Moved paragraph (${r.id}): ${after ? `after ${after}` : "to the front"}`
1509
+ };
1510
+ },
1511
+ "body.adopt": (s, input, id, ctx) => adopt(s, input, id, ctx),
1512
+ "sticker.add": (s, input, id) => {
1513
+ const memo = memoInput(s, input);
1514
+ const target = targetInput(s, input);
1515
+ const sticker = { memo, target, basis: target ? "target" : "canvas", pos: positionInput(input) ?? (target ? ATTACHED_POS : DETACHED_POS) };
1516
+ return {
1517
+ changes: [{ id: id(0), type: "sticker", prefix: "st", after: sticker }],
1518
+ summary: `Attached sticker (${memo}${target ? `, to ${target}` : ", on the work area"})`
1519
+ };
1520
+ },
1521
+ "sticker.attach": (s, input) => {
1522
+ const r = need(s, input.sticker, ["sticker"], "sticker");
1523
+ const target = targetInput(s, input);
1524
+ const c = r.content;
1525
+ return {
1526
+ changes: [
1527
+ {
1528
+ id: r.id,
1529
+ type: "sticker",
1530
+ after: { memo: c.memo, target, basis: target ? "target" : "canvas", pos: positionInput(input) ?? (target ? ATTACHED_POS : DETACHED_POS) }
1531
+ }
1532
+ ],
1533
+ summary: target ? `Moved sticker (${r.id}) to ${target}` : `Put sticker (${r.id}) on the work area`
1534
+ };
1535
+ },
1536
+ "sticker.move": (s, input) => {
1537
+ const r = need(s, input.sticker, ["sticker"], "sticker");
1538
+ const pos = positionInput(input);
1539
+ if (!pos) throw new Reject("INVALID_INPUT", "position is required");
1540
+ return { changes: [{ id: r.id, type: "sticker", after: { ...r.content, pos } }], summary: `Moved sticker (${r.id})` };
1541
+ },
1542
+ "sticker.remove": (s, input) => {
1543
+ const r = need(s, input.sticker, ["sticker"], "sticker");
1544
+ return {
1545
+ changes: [{ id: r.id, type: "sticker", after: null }],
1546
+ summary: `Removed sticker (${r.id}). Memo ${r.content.memo} stays in the memo box`
1547
+ };
1548
+ },
1549
+ ...TIME_OPERATIONS
1550
+ };
1551
+ function memoInput(s, input) {
1552
+ const m = input.memo;
1553
+ if (typeof m !== "string" || m === "") throw new Reject("INVALID_INPUT", "The memo id is required");
1554
+ if (s.records[m] || !(MEMO_ID.test(m) || m.startsWith("$"))) throw new Reject("INVALID_INPUT", `${m} is not a memo in the memo box`);
1555
+ return m;
1556
+ }
1557
+ function targetInput(s, input) {
1558
+ return input.target === void 0 || input.target === null ? null : need(s, input.target, ["row", "line", "node", "para"], "target to attach to").id;
1559
+ }
1560
+ function segmentsOf(r) {
1561
+ return r.content.text ?? [];
1562
+ }
1563
+ function refsOf(r) {
1564
+ const out = [];
1565
+ const add = (to, kind, soft = false) => {
1566
+ if (to) out.push({ from: r.id, to, kind, ...soft ? { soft: true } : {} });
1567
+ };
1568
+ if (r.type === "relation") {
1569
+ const c = r.content;
1570
+ add(c.a, "relation_end");
1571
+ add(c.b, "relation_end");
1572
+ } else if (r.type === "sticker") {
1573
+ const c = r.content;
1574
+ add(c.memo, "sticker_memo", true);
1575
+ add(c.target, "sticker_target", true);
1576
+ } else if (r.type === "row") {
1577
+ const c = r.content;
1578
+ for (const f of c.meta?.facts ?? []) add(f, "meta_fact", true);
1579
+ add(c.meta?.pov, "meta_pov", true);
1580
+ for (const w of c.meta?.worlds ?? []) add(w, "meta_world", true);
1581
+ add(c.time?.written.world, "time_world", true);
1582
+ add(c.meta?.time?.written.world, "time_world", true);
1583
+ add(c.group, "in_group");
1584
+ } else if (r.type === "group") {
1585
+ add(r.content.parent, "in_group");
1586
+ } else if (r.type === "world") {
1587
+ const cal = r.content.calendar;
1588
+ if (cal !== EARTH_ID) add(cal, "world_calendar");
1589
+ } else if (r.type === "settings") {
1590
+ const cal = r.content.defaultCalendar;
1591
+ if (cal !== EARTH_ID) add(cal, "default_calendar");
1592
+ } else if (r.type === "line" || r.type === "para") {
1593
+ add(r.type === "line" ? r.content.parent : r.content.scene, "parent");
1594
+ for (const seg of segmentsOf(r)) {
1595
+ if (typeof seg === "string") continue;
1596
+ if ("node" in seg) add(seg.node, "node_mark");
1597
+ else add(seg.row, "row_mark");
1598
+ }
1599
+ }
1600
+ return out;
1601
+ }
1602
+ function validate(candidate, changed) {
1603
+ const out = [];
1604
+ const err = (record, code, message) => out.push({ level: "error", code, record, message });
1605
+ const changedSet = new Set(changed);
1606
+ for (const id of changed) {
1607
+ const r = candidate.records[id];
1608
+ if (!r) continue;
1609
+ for (const ref of refsOf(r)) {
1610
+ if (ref.kind === "sticker_memo") continue;
1611
+ if (ref.kind === "time_world") continue;
1612
+ if (!candidate.records[ref.to]) err(id, "dangling_ref", `${ref.to}, which ${id} points to, does not exist`);
1613
+ }
1614
+ if (r.type === "sticker" && !MEMO_ID.test(r.content.memo)) {
1615
+ err(id, "sticker_not_memo", `Sticker ${id} must point to a memo in the memo box`);
1616
+ }
1617
+ if (r.type === "relation") {
1618
+ const c = r.content;
1619
+ if (c.a === c.b) err(id, "relation_same_node", "The two nodes of a relation must be different");
1620
+ }
1621
+ const into = r.type === "group" ? r.content.parent : r.type === "row" ? r.content.group : void 0;
1622
+ if (into) {
1623
+ const g = candidate.records[into];
1624
+ if (r.type === "row" && r.content.list !== "scene") err(id, "group_not_scene", `Fact ${id} cannot be in a group`);
1625
+ else if (g && g.type !== "group") err(id, "group_not_group", `${into}, which holds ${id}, is not a group`);
1626
+ else if (r.type === "group" && within(candidate, into, id)) err(id, "group_cycle", `Group ${id} is inside itself`);
1627
+ }
1628
+ if (r.type === "para") {
1629
+ const scene = r.content.scene;
1630
+ if (candidate.records[scene] && !isScene(candidate, scene)) err(id, "para_not_in_scene", `Paragraph ${id} can be only in a scene`);
1631
+ }
1632
+ if (r.type === "line" || r.type === "para") {
1633
+ for (const seg of segmentsOf(r)) {
1634
+ if (typeof seg === "string" || !("node" in seg) || seg.text === void 0) continue;
1635
+ const node = candidate.records[seg.node];
1636
+ const name = node?.content?.name;
1637
+ if (name !== void 0 && name !== seg.text) {
1638
+ out.push({
1639
+ level: "notice",
1640
+ code: "display_text_differs",
1641
+ record: id,
1642
+ message: `The text of [${seg.text}](${seg.node}) differs from the name ${name}`,
1643
+ notice: { kind: "display_text_differs", record: id, detail: { node: seg.node, text: seg.text, name } }
1644
+ });
1645
+ }
1646
+ }
1647
+ }
1648
+ }
1649
+ const gone = changed.filter((id) => !candidate.records[id]);
1650
+ if (gone.length > 0) {
1651
+ const goneSet = new Set(gone);
1652
+ for (const r of Object.values(candidate.records)) {
1653
+ if (changedSet.has(r.id)) continue;
1654
+ for (const ref of refsOf(r)) {
1655
+ if (!ref.soft && goneSet.has(ref.to)) err(r.id, "dangling_ref", `${r.id} points to ${ref.to}, which was removed`);
1656
+ }
1657
+ }
1658
+ }
1659
+ return out;
1660
+ }
1661
+ function sceneScope(s, scope) {
1662
+ const ids = scope?.targets ?? (scope?.target !== void 0 ? [scope.target] : null);
1663
+ if (ids === null) return null;
1664
+ const scenes = scenesOf(s);
1665
+ for (const id of ids) {
1666
+ if (!scenes.some((r) => r.id === id)) throw new Reject("TARGET_NOT_FOUND", `Cannot find the scene ${id}`);
1667
+ }
1668
+ const set = new Set(ids);
1669
+ return scenes.filter((r) => set.has(r.id)).map((r) => r.id);
1670
+ }
1671
+ function scopeParts(s, sceneIds) {
1672
+ let nodes = all(s, "node").sort(byIdNumber);
1673
+ let relations = all(s, "relation").sort(byIdNumber);
1674
+ let stickers = all(s, "sticker").sort(byIdNumber);
1675
+ if (sceneIds) {
1676
+ const lineIds = new Set(sceneIds.flatMap((id) => [...linesOf(s, id), ...parasOf(s, id)].map((l) => l.id)));
1677
+ const sceneSet = new Set(sceneIds);
1678
+ const mentioned = /* @__PURE__ */ new Set();
1679
+ for (const id of sceneIds) {
1680
+ for (const l of [...linesOf(s, id), ...parasOf(s, id)]) {
1681
+ for (const seg of l.content.text) {
1682
+ if (typeof seg !== "string" && "node" in seg) mentioned.add(seg.node);
1683
+ }
1684
+ }
1685
+ }
1686
+ nodes = nodes.filter((x) => mentioned.has(x.id));
1687
+ relations = relations.filter((x) => {
1688
+ const c = x.content;
1689
+ return mentioned.has(c.a) && mentioned.has(c.b);
1690
+ });
1691
+ stickers = stickers.filter((x) => {
1692
+ const t = x.content.target;
1693
+ return t !== null && (sceneSet.has(t) || lineIds.has(t));
1694
+ });
1695
+ }
1696
+ return { nodes, relations, stickers };
1697
+ }
1698
+ function firstSentence(t) {
1699
+ const m = /^.*?[.!?。?!](?=\s|$)/.exec(t);
1700
+ return (m ? m[0] : t).trim();
1701
+ }
1702
+ function conceptText(s, sceneIds, mine, withStickers, body) {
1703
+ const starred = new Set(mine.flatMap((m) => m.changes.filter((c) => c.after !== null).map((c) => c.record)));
1704
+ const star = (id) => starred.has(id) ? " *" : "";
1705
+ const n = names(s);
1706
+ const fmt = (text) => formatMarks(text, n);
1707
+ const tree = sceneTree(s);
1708
+ const num = new Map(tree.scenes.map((r, i) => [r.id, i + 1]));
1709
+ const { nodes, relations, stickers } = scopeParts(s, sceneIds);
1710
+ const lines = ["Characters and places"];
1711
+ for (const r of nodes) {
1712
+ const c = r.content;
1713
+ lines.push(`- [${c.name}](${r.id})${star(r.id)} ${c.kind}${c.note ? `: ${c.note}` : ""}`);
1714
+ }
1715
+ for (const r of relations) {
1716
+ const c = r.content;
1717
+ lines.push(`- (${r.id})${star(r.id)} [${n.node(c.a)}](${c.a}), [${n.node(c.b)}](${c.b}): ${c.name}`);
1718
+ }
1719
+ const metaText = (r) => {
1720
+ const c = r.content;
1721
+ const parts = [];
1722
+ if (c.list === "fact") {
1723
+ if (c.time) parts.push(`time ${shownTime(s, c.time, primaryWorld(s, r))}`);
1724
+ const ws = liveWorlds(s, c.meta?.worlds);
1725
+ if (ws.length) parts.push(`world lines ${ws.map((w) => `${worldName(s, w)}(${w})`).join(", ")}`);
1726
+ } else {
1727
+ const order = new Map(factsInTimeOrder(s).map((f, i) => [f.id, i]));
1728
+ const fs = (c.meta?.facts ?? []).filter((f) => order.has(f)).sort((a, b) => order.get(a) - order.get(b));
1729
+ if (fs.length) parts.push(`facts ${fs.join(", ")}`);
1730
+ if (c.meta?.pov && s.records[c.meta.pov]) parts.push(`point of view ${n.node(c.meta.pov)}(${c.meta.pov})`);
1731
+ const own = liveWorlds(s, c.meta?.worlds);
1732
+ if (own.length) parts.push(`world lines ${own.map((w) => `${worldName(s, w)}(${w})`).join(", ")}`);
1733
+ const t = sceneTime(s, r);
1734
+ if (t) parts.push(`time ${t.shown}${t.to ? ` ~ until ${t.to}` : ""}${t.from === "facts" ? " (from facts)" : ""}`);
1735
+ }
1736
+ return parts.length ? ` [${parts.join(". ")}]` : "";
1737
+ };
1738
+ const rowText = (r, head) => {
1739
+ const c = r.content;
1740
+ const ls = linesOf(s, r.id);
1741
+ const title = `${c.title ? ` title "${c.title}"` : ""}${metaText(r)}`;
1742
+ if (ls.length === 0) {
1743
+ lines.push(`${head} (${r.id})${star(r.id)}${title}: (no lines)`);
1744
+ return;
1745
+ }
1746
+ ls.forEach((l, i) => {
1747
+ const body2 = `${l.id}${star(l.id)}: ${fmt(l.content.text)}`;
1748
+ if (i === 0) lines.push(`${head} (${r.id})${star(r.id)}${title} ${body2}`);
1749
+ else lines.push(`${" ".repeat(head.length + r.id.length + 3)} ${body2}`);
1750
+ });
1751
+ };
1752
+ const bodyText = (r, head) => {
1753
+ const ps = parasOf(s, r.id);
1754
+ const pad = " ".repeat(head.length + 1);
1755
+ if (ps.length === 0) {
1756
+ if (body === "all") lines.push(`${pad}Body (none)`);
1757
+ return;
1758
+ }
1759
+ if (body === "head") {
1760
+ const first = firstSentence(plainText(ps[0].content.text, n));
1761
+ lines.push(`${pad}Body: ${countOf(ps.length, "paragraph")}. First paragraph: ${first}`);
1762
+ return;
1763
+ }
1764
+ const label2 = body === "settled" ? "Settled body" : "Body";
1765
+ ps.forEach((b, i) => {
1766
+ const text = `${b.id}${star(b.id)}: ${fmt(b.content.text)}`;
1767
+ lines.push(i === 0 ? `${pad}${label2} ${text}` : `${pad}${" ".repeat(label2.length + 1)}${text}`);
1768
+ });
1769
+ };
1770
+ const worlds = all(s, "world").map((w) => w.id).sort(byName(s));
1771
+ const calendars = all(s, "calendar").sort(byIdNumber);
1772
+ const defaultCal = defaultCalendarId(s);
1773
+ if (worlds.length || calendars.length || defaultCal !== EARTH_ID) {
1774
+ lines.push("", "World lines and calendars");
1775
+ lines.push(`- Default calendar: ${calendarName(s, defaultCal)}(${defaultCal})`);
1776
+ for (const w of worlds) {
1777
+ const c = s.records[w].content;
1778
+ lines.push(`- (${w})${star(w)} world line ${c.name}: calendar ${calendarName(s, worldCalendarId(s, w))}(${worldCalendarId(s, w)})${c.note ? `. ${c.note}` : ""}`);
1779
+ }
1780
+ for (const r of calendars) {
1781
+ const d = r.content.data;
1782
+ lines.push(`- (${r.id})${star(r.id)} calendar ${d.name}: ${calendarText(d)}`);
1783
+ }
1784
+ }
1785
+ lines.push("", "Facts");
1786
+ for (const r of factsInTimeOrder(s)) rowText(r, "-");
1787
+ lines.push("", "Scenes");
1788
+ const shown = sceneIds ? new Set(sceneIds) : null;
1789
+ const shownGroups = /* @__PURE__ */ new Set();
1790
+ if (shown) {
1791
+ for (const id of shown) {
1792
+ for (let g = containerOf(s, s.records[id]); g && !shownGroups.has(g); g = containerOf(s, s.records[g])) shownGroups.add(g);
1793
+ }
1794
+ }
1795
+ for (const { r, depth } of tree.flat) {
1796
+ const indent = " ".repeat(depth);
1797
+ if (r.type === "group") {
1798
+ if (shown && !shownGroups.has(r.id)) continue;
1799
+ const k = sceneCount(tree, r.id);
1800
+ lines.push(`${indent}Group (${r.id})${star(r.id)} "${r.content.title}": ${k ? countOf(k, "scene") : "no scenes"}`);
1801
+ continue;
1802
+ }
1803
+ if (shown && !shown.has(r.id)) continue;
1804
+ const head = `${indent}${num.get(r.id)}.`;
1805
+ rowText(r, head);
1806
+ if (body === "settled") {
1807
+ const meta = r.content.meta;
1808
+ const pad = " ".repeat(head.length + 1);
1809
+ const fs = factsInTimeOrder(s).filter((f) => meta?.facts?.includes(f.id));
1810
+ if (fs.length) {
1811
+ lines.push(`${pad}Facts this scene covers: ${fs.map((f) => {
1812
+ const t = f.content.time;
1813
+ return `${factName(s, f.id)}(${f.id}${t ? `, ${shownTime(s, t, primaryWorld(s, f))}` : ""})`;
1814
+ }).join(", ")}`);
1815
+ }
1816
+ if (meta?.pov && s.records[meta.pov]) lines.push(`${pad}Point of view: ${n.node(meta.pov)}`);
1817
+ }
1818
+ bodyText(r, head);
1819
+ }
1820
+ if (withStickers) {
1821
+ lines.push("", "Stickers");
1822
+ if (stickers.length === 0) lines.push("(none)");
1823
+ for (const x of stickers) {
1824
+ const c = x.content;
1825
+ const t = c.target;
1826
+ const where = t ? s.records[t] ? `attached to ${targetText(s, t)}` : `attached to ${t}, but the target was removed so it is not shown` : "on the work area";
1827
+ lines.push(`- (${x.id})${star(x.id)} memo ${c.memo}, ${where}`);
1828
+ }
1829
+ }
1830
+ return lines.join("\n");
1831
+ }
1832
+ var GAP_FACTOR = 10n;
1833
+ function timeline(s, world) {
1834
+ const facts = factsInTimeOrder(s).filter((f) => world === null || liveWorlds(s, f.content.meta?.worlds).includes(world));
1835
+ const lo = (f) => {
1836
+ const t = f.content.time;
1837
+ return t ? BigInt(t.lo) : null;
1838
+ };
1839
+ const diffs = [];
1840
+ for (let i = 1; i < facts.length; i++) {
1841
+ const a = lo(facts[i - 1]);
1842
+ const b = lo(facts[i]);
1843
+ if (a !== null && b !== null && b > a) diffs.push(b - a);
1844
+ }
1845
+ diffs.sort((x, y) => x < y ? -1 : x > y ? 1 : 0);
1846
+ const typical = diffs.length ? diffs[diffs.length - 1 >> 1] : 0n;
1847
+ return facts.map((f, i) => {
1848
+ const a = i > 0 ? lo(facts[i - 1]) : null;
1849
+ const b = lo(f);
1850
+ if (a === null || b === null || typical === 0n || b - a <= typical * GAP_FACTOR) return { fact: f.id };
1851
+ const cal = calendarOf(s, world ?? primaryWorld(s, f));
1852
+ return { fact: f.id, gap: `gap of ${formatGap(b - a, cal)}` };
1853
+ });
1854
+ }
1855
+ function scopeRecords(s, sceneIds) {
1856
+ const { nodes, relations, stickers } = scopeParts(s, sceneIds);
1857
+ return [
1858
+ ...sceneIds.flatMap((id) => [id, ...linesOf(s, id).map((l) => l.id), ...parasOf(s, id).map((b) => b.id)]),
1859
+ ...nodes.map((x) => x.id),
1860
+ ...relations.map((x) => x.id),
1861
+ ...rowsOf(s, "fact").flatMap((f) => [f.id, ...linesOf(s, f.id).map((l) => l.id)]),
1862
+ ...stickers.map((x) => x.id)
1863
+ ];
1864
+ }
1865
+ function project(s, scope, mine) {
1866
+ const n = names(s);
1867
+ const sceneIds = sceneScope(s, scope);
1868
+ const tree = sceneTree(s);
1869
+ const scenes = tree.scenes;
1870
+ const shownScenes = sceneIds ? scenes.filter((r) => sceneIds.includes(r.id)) : scenes;
1871
+ const { nodes, relations, stickers } = scopeParts(s, sceneIds);
1872
+ const lineJson = (l) => ({
1873
+ id: l.id,
1874
+ text: l.content.text,
1875
+ display: plainText(l.content.text, n)
1876
+ });
1877
+ const rowJson = (r, label2) => ({
1878
+ id: r.id,
1879
+ label: label2 ?? rowLabel(s, r.id),
1880
+ title: r.content.title ?? null,
1881
+ lines: linesOf(s, r.id).map(lineJson)
1882
+ });
1883
+ const timeJson = (t, world, worlds) => t ? { lo: t.lo, hi: t.hi, shown: shownTime(s, t, world), written: t.written, shownIn: Object.fromEntries(worlds.map((w) => [w, shownTime(s, t, w)])) } : null;
1884
+ const timeOrder = new Map(factsInTimeOrder(s).map((f, i) => [f.id, i]));
1885
+ const factJson = (r) => {
1886
+ const c = r.content;
1887
+ const worlds = liveWorlds(s, c.meta?.worlds);
1888
+ return { ...rowJson(r), time: timeJson(c.time, primaryWorld(s, r), worlds), meta: { worlds } };
1889
+ };
1890
+ const sceneJson = (r) => {
1891
+ const c = r.content;
1892
+ const t = sceneTime(s, r);
1893
+ const facts = (c.meta?.facts ?? []).filter((f) => timeOrder.has(f)).sort((a, b) => timeOrder.get(a) - timeOrder.get(b));
1894
+ const ws = sceneWorlds(s, r);
1895
+ return {
1896
+ ...rowJson(r),
1897
+ group: containerOf(s, r),
1898
+ body: parasOf(s, r.id).map(lineJson),
1899
+ meta: { facts, pov: c.meta?.pov && s.records[c.meta.pov] ? c.meta.pov : null, time: c.meta?.time ? timeJson(c.meta.time, c.meta.time.written.world, []) : null, worlds: liveWorlds(s, c.meta?.worlds) },
1900
+ worlds: ws.worlds,
1901
+ worldsFrom: ws.from,
1902
+ time: t ? { lo: t.lo, hi: t.hi, shown: t.shown } : null,
1903
+ timeFrom: t?.from ?? null,
1904
+ timeTo: t?.to ?? null
1905
+ };
1906
+ };
1907
+ const named = sceneIds ? sceneIds.join(", ") : "";
1908
+ const worldIds = all(s, "world").map((w) => w.id).sort(byName(s));
1909
+ return {
1910
+ text: conceptText(s, sceneIds, mine, true, sceneIds ? "all" : "head"),
1911
+ scopeLabel: sceneIds ? `Read scenes ${named}, the nodes and relations in them, all facts, and the stickers attached to them` : "Read everything",
1912
+ json: {
1913
+ nodes: nodes.map((r) => ({ id: r.id, ...r.content })),
1914
+ relations: relations.map((r) => ({ id: r.id, ...r.content })),
1915
+ // 사실은 일어난 차례다(16.2.4절). 시각이 있는 사실이 먼저다
1916
+ facts: factsInTimeOrder(s).map(factJson),
1917
+ scenes: shownScenes.map(sceneJson),
1918
+ // 장면의 묶음(novel.md 18절). 펼친 차례이고, items 는 그 안에 든 장면과 묶음의 id 를 차례대로 적는다. 맨 위 단계는 sceneRoot 다
1919
+ groups: tree.groups.map((g) => ({
1920
+ id: g.id,
1921
+ title: g.content.title,
1922
+ parent: [...tree.placed].find(([, xs]) => xs.includes(g))?.[0] ?? null,
1923
+ depth: tree.depth.get(g.id) ?? 0,
1924
+ items: (tree.placed.get(g.id) ?? []).map((x) => x.id),
1925
+ scenes: sceneCount(tree, g.id)
1926
+ })),
1927
+ sceneRoot: (tree.placed.get(null) ?? []).map((x) => x.id),
1928
+ worlds: worldIds.map((w) => {
1929
+ const c = s.records[w].content;
1930
+ return { id: w, name: c.name, note: c.note, calendar: worldCalendarId(s, w) };
1931
+ }),
1932
+ // epochText 는 원년을 지구 달력의 날로 적은 것이다. 화면의 달력 편집이 글로 보이고 글로 보낸다
1933
+ calendars: [
1934
+ { id: EARTH_ID, name: EARTH.name, builtin: true, data: EARTH, example: exampleText(EARTH), epochText: formatAt(BigInt(EARTH.epoch), EARTH, 2) },
1935
+ ...all(s, "calendar").sort(byIdNumber).map((r) => {
1936
+ const d = r.content.data;
1937
+ return { id: r.id, name: d.name, builtin: false, data: d, example: exampleText(d), epochText: formatAt(BigInt(d.epoch), EARTH, 2) };
1938
+ })
1939
+ ],
1940
+ defaultCalendar: defaultCalendarId(s),
1941
+ // 세로 배열과 비어 있는 시간의 띠(16.7절). 모두 볼 때와 세계선마다
1942
+ timeline: Object.fromEntries([["", timeline(s, null)], ...worldIds.map((w) => [w, timeline(s, w)])]),
1943
+ stickers: stickers.map((x) => {
1944
+ const c = x.content;
1945
+ return { id: x.id, memo: c.memo, target: c.target, targetGone: c.target !== null && !s.records[c.target], basis: c.basis, pos: c.pos };
1946
+ })
1947
+ },
1948
+ ...sceneIds ? { records: scopeRecords(s, sceneIds) } : {}
1949
+ };
1950
+ }
1951
+ function prepareGeneration(s, scope, medium) {
1952
+ if (medium !== "text") throw new Reject("UNSUPPORTED_CAPABILITY", `The medium ${medium} cannot be generated yet`);
1953
+ const sceneIds = sceneScope(s, { targets: scope.targets ?? void 0 }) ?? scenesOf(s).map((r) => r.id);
1954
+ if (sceneIds.length === 0) throw new Reject("INVALID_STATE", "There is no scene to generate");
1955
+ return {
1956
+ material: `${LANGUAGE_NOTE}
1957
+
1958
+ ${conceptText(s, sceneIds, [], false, "settled")}`,
1959
+ // content 는 장면 자신의 내용이다. 글 줄의 저장 형식(표시는 id)을 그대로 쓰므로 인물 이름이 바뀌어도 장면은 그대로다.
1960
+ // 이름이 바뀐 것은 재료 글에서 잡힌다(030 6.5절).
1961
+ sections: sceneIds.map((id) => {
1962
+ const c = s.records[id].content;
1963
+ const lines = linesOf(s, id).map((l) => ({ id: l.id, text: l.content.text }));
1964
+ const body = parasOf(s, id).map((b) => ({ id: b.id, text: b.content.text }));
1965
+ return { key: id, label: rowLabel(s, id) ?? id, content: JSON.stringify({ title: c.title ?? null, lines, ...body.length ? { body } : {} }) };
1966
+ }),
1967
+ records: scopeRecords(s, sceneIds)
1968
+ };
1969
+ }
1970
+ function interpretSelection(s, sel) {
1971
+ const n = names(s);
1972
+ const nodes = all(s, "node").sort(byIdNumber).filter((r) => {
1973
+ const name = r.content.name;
1974
+ return name !== "" && sel.text.includes(name);
1975
+ }).map((r) => ({ id: r.id, label: r.content.name, why: "The name appears in the selected text" }));
1976
+ const picked = sel.text.trim();
1977
+ const paras = picked === "" ? [] : sel.targets.filter((id) => isScene(s, id)).flatMap((id) => parasOf(s, id)).filter((b) => plainText(b.content.text, n).includes(picked)).map((b) => ({ id: b.id, label: paraLabel(s, b.id), why: "The selected text is in this paragraph" }));
1978
+ return { candidates: [...nodes, ...paras] };
1979
+ }
1980
+ function describeSelection(s, input) {
1981
+ const sel = input?.selection;
1982
+ if (!sel || typeof sel !== "object" || sel.format !== SELECTION_FORMAT) return { error: "INVALID_INPUT", summary: `The selection is not in the ${SELECTION_FORMAT} shape` };
1983
+ if (typeof sel.rev !== "string" || !Array.isArray(sel.records) || !sel.records.every((x) => typeof x === "string")) {
1984
+ return { error: "INVALID_INPUT", summary: "The selection needs rev and a records list of ids" };
1985
+ }
1986
+ const labels = sel.labels && typeof sel.labels === "object" ? sel.labels : {};
1987
+ const n = names(s);
1988
+ const targets = [];
1989
+ const gone = [];
1990
+ const now = typeof input.current === "string" && input.current !== sel.rev ? ` Something changed after that (now ${input.current}). What follows is the current state.` : "";
1991
+ const out = [`Revision when selected: ${sel.rev}.${now}`];
1992
+ for (const id of sel.records) {
1993
+ const r = s.records[id];
1994
+ if (r?.type === "row") {
1995
+ targets.push(id);
1996
+ const c = r.content;
1997
+ const lines = linesOf(s, id);
1998
+ const time = c.list === "fact" ? c.time : c.meta?.time;
1999
+ out.push(`Selected row: [${rowLabel(s, id)}](${id})${time ? `, time ${time.written.text}` : ""}${c.list === "scene" && c.group ? `, in group ${groupName(s, c.group)}` : ""}.`);
2000
+ if (!lines.length) out.push(" It has no lines yet.");
2001
+ for (const l of lines.slice(0, SELECTION_LINES)) out.push(` - (${l.id}) ${plainText(l.content.text, n)}`);
2002
+ if (lines.length > SELECTION_LINES) out.push(` ... and ${countOf(lines.length - SELECTION_LINES, "more line")}`);
2003
+ if (c.list === "scene") {
2004
+ const paras = parasOf(s, id);
2005
+ out.push(paras.length ? ` The scene has body text in ${countOf(paras.length, "paragraph")}. Read it with this scene id in scope.` : " The scene has no body text yet.");
2006
+ }
2007
+ } else if (r?.type === "node") {
2008
+ targets.push(id);
2009
+ const c = r.content;
2010
+ out.push(`Selected ${c.kind || "node"}: [${c.name}](${id})${c.note ? `. Note: ${c.note}` : ""}`);
2011
+ } else {
2012
+ gone.push(id);
2013
+ out.push(`${typeof labels[id] === "string" ? labels[id] : id} (${id}) was selected but has been removed since.`);
2014
+ }
2015
+ }
2016
+ if (!sel.records.length) out.push("Nothing is selected. The words are about the whole story.");
2017
+ return { text: out.join("\n"), targets, gone };
2018
+ }
2019
+ function targetText(s, id) {
2020
+ const r = s.records[id];
2021
+ if (!r) return id;
2022
+ if (r.type === "row") return `[${rowLabel(s, id)}](${id})`;
2023
+ if (r.type === "node") return `[${r.content.name}](${id})`;
2024
+ if (r.type === "para") return paraLabel(s, id);
2025
+ return `line ${id}`;
2026
+ }
2027
+ var BODY_GUIDE = ' The lines of a scene settle what happens in that scene, and the body text is the prose of that scene. Both are settled. When you write the body text for the first time or rewrite a whole scene, make an output with begin_generation so the person can look at it. When you change one or two sentences in a scene that already has body text, change them with para.update. Keep the "Settled body" in the material as it is, unless the person asked you to rewrite that part. A full read shows only the start of the body text. If you need the body text, read again with the scene ids in scope. If you change the lines of a scene and the body text no longer matches them, ask the person whether to change the body text too. Sentences in the body text are not fact rows. To make something written in the body text a fact of the world, copy it to a fact row. Write the body text in the language the person writes in, which is the language of the facts and lines. Do not switch it to English.';
2028
+ var ADOPT_GUIDE = ' When the person looks at an output and says to use it, adopt it with body.adopt. Do not adopt an output unless the person told you to put it in. An output is not settled until it is adopted. Changes the person has not confirmed yet appear as text under "\uB2E4\uB978 \uCC38\uC5EC\uC790\uC758 \uBCC0\uACBD" (Changes by other participants). Treat them as text the person settled, and continue from them. When you call body.adopt, attach the artifact to the apply_operation request, and put only the scenes to adopt in keys.';
2029
+ var LANGUAGE_NOTE = "Write the body text in the language the person writes in, which is the language of the facts and lines below. Do not switch it to English because these notes are in English.";
2030
+ var TIME_GUIDE = ' A fact can have a time in the story. Write the time with the calendar of its world line, from the largest unit. On the Earth calendar write "1999\uB144 12\uC6D4 31\uC77C". In another world use the era and units of its calendar, like "Imperial 65300\uB144 3\uC6D4". The markers \uB144 (year) and \uC77C (day) and the month names of the calendar are part of how a time is written, so keep them even when the person writes in another language. Times are saved as absolute time, so a fact stays the same when the calendar changes. Facts that have a time are listed in the order of events. Write which world a fact belongs to in the fact metadata worlds. Write which facts a scene covers, and through whose eyes it is seen, in the scene metadata facts and pov. Put in facts only the facts that actually happen in that scene. Do not put in background facts that a character only remembers or mentions. If you do, the time of the scene widens to cover that background. The time of a scene comes from those facts, so do not write it separately. Write a scene time only for a scene that covers no facts. When the person says "that happened after the war", change the time of the fact, not the order of the scenes. The world of the story decides the calendar. Unless the person says otherwise, write times with the default Earth calendar (the Gregorian calendar), and tell the person you used it. If the person wants a special calendar, make it with calendar.set (you may start from the Earth calendar and write only the fields to change), and tell the person what the calendar looks like. If there is only one world, do not make a world line. Make that calendar the default calendar of the work with calendar.setDefault. Make world lines when there are two or more worlds with different calendars or flows of time. When there are two or more versions of the same story, give each version a world line, and put facts used in both versions into both world lines. Write which version a scene belongs to in the scene meta.worlds. A scene without it follows the world lines of the facts it covers. Filtering by a world line leaves only the facts and scenes of that world line, which gives the reading order of each version.';
2031
+ var GROUP_GUIDE = ' Scenes are put into groups. Like folders, a group can hold other groups (chapters inside a part), and one scene is in only one group. The reading order is the order you get by opening the groups from the top, and scene numbers follow it. In the text you read, a group appears as a "Group (g1)" line, and what is inside it is indented. To group a few scenes, put them in the items of group.add. If you give no position, the group appears where the first of those scenes was. To move a scene to another group, give group to row.move. To move a group, give parent to group.move. Removing a group does not remove the scenes inside it. They move up one level. If the person did not ask for groups, show how you would group the scenes and ask before you make any group.';
2032
+ var DESCRIPTION = {
2033
+ id: PACKAGE_ID,
2034
+ version: VERSION,
2035
+ title: "Story List",
2036
+ aiGuide: `What the person says or corrects is settled. Write it in a fact or a scene. Even when the scope is unclear, do not put it off as a memo. Write it in the narrower place, then ask. A fact row applies to the whole story, and the lines of a scene apply only to that scene. Memos are in the memo box of the core (core.memo.add), and a sticker attaches a memo to a row on this screen. Ask the person before you attach a memo as a sticker or remove one. To move the text of a memo into a fact or a scene, send line.add and core.memo.remove in one request. When you read a narrower scope, put scene ids in scope. Do not copy the person's words letter by letter. Write the meaning you understood. Make it clear which winter "that winter" is, and who "he" is. Then the person can look at the screen and check your understanding.` + BODY_GUIDE + ADOPT_GUIDE + TIME_GUIDE + GROUP_GUIDE,
2037
+ markGuide: 'In text, write characters and places like [Mina](n1). If the text in the brackets is the same as the name, it changes when the name changes. If it is different, like [she](n1), that text stays. Do not write the numbers of scenes and facts as text. Point to them by id, like [Scene 1](s1). The screen always shows the current number. For something made in the same request, give it a $name with "as" and point to it like [Uptown]($village). In memos and messages, point to a body paragraph like [paragraph](b3). Marks in lines and paragraphs point only to characters, places, facts and scenes.',
2038
+ operations: [
2039
+ { op: "node.add", input: { name: "name", kind: "kind (a character or a place, any word)", note: "short note" }, summary: "Makes a node" },
2040
+ { op: "node.update", input: { node: "node id", name: "name", kind: "kind", note: "note" }, summary: "Changes the name, kind and note" },
2041
+ { op: "node.remove", input: { node: "node id" }, summary: "Removes a node. Its marks in lines become plain text, and its relations are removed with it. Memos and stickers stay" },
2042
+ { op: "relation.add", input: { a: "node id", b: "node id", name: "name (any words)" }, summary: "Makes a relation" },
2043
+ { op: "relation.update", input: { relation: "relation id", name: "name" }, summary: "Changes the name" },
2044
+ { op: "relation.remove", input: { relation: "relation id" }, summary: "Removes it" },
2045
+ {
2046
+ op: "row.add",
2047
+ input: {
2048
+ list: "fact or scene",
2049
+ after: "id of the row before it (for a scene, a scene or group id in the same group). null for the front, leave it out for the end. For a scene, leaving out both group and after puts it right after the last scene in reading order",
2050
+ group: "Scenes only. The id of the group to put it in. null for the top level. Leave it out to use the place of after",
2051
+ title: "title (optional)",
2052
+ lines: "lines",
2053
+ time: "Facts only. { text: the time in the story, world: world line id (leave it out for the first world line of the fact, null for the default calendar) }",
2054
+ meta: "Metadata. For a fact { worlds: list of world line ids }. For a scene { facts: list of ids of the facts it covers, pov: node id of the point of view character, time: the time of a scene that covers no facts { text, world? }, worlds: list of ids of the world lines the scene belongs to (leave it out to follow the world lines of the facts it covers) }"
2055
+ },
2056
+ summary: "Makes a fact row or a scene row",
2057
+ example: [
2058
+ { op: "row.add", as: "$fact", input: { list: "fact", after: "f2", lines: ["In the winter [Mina](n1) was twelve, she lived in the upper village"], time: { text: "1999\uB144 12\uC6D4" } } },
2059
+ { op: "row.add", input: { list: "scene", lines: ["[Mina](n1) walks along a snowy road"], meta: { facts: ["$fact"], pov: "n1" } } }
2060
+ ]
2061
+ },
2062
+ {
2063
+ op: "row.move",
2064
+ input: {
2065
+ row: "row id",
2066
+ after: "id of the row before it (for a scene, a scene or group id in the group it moves to). null for the front",
2067
+ group: "Scenes only. The id of the group to move it to, null for the top level. Leave it out to use the place of after. If after is also left out, it goes to the end of that group"
2068
+ },
2069
+ summary: "Changes the order, or moves a scene to another group. A fact with a time is shown in the order of events, so its position does not change",
2070
+ example: { op: "row.move", input: { row: "s7", group: "g2", after: null } }
2071
+ },
2072
+ {
2073
+ op: "row.update",
2074
+ input: { row: "row id", title: "title (empty text clears it)", time: "Facts only. The time { text, world? }, null to remove it", meta: "Metadata. Only the fields given change, and null removes that field" },
2075
+ summary: "Changes the title, the time of a fact, and the metadata. Only what is given changes",
2076
+ example: [
2077
+ { op: "row.update", input: { row: "f3", time: { text: "Imperial 65300\uB144 3\uC6D4", world: "w1" }, meta: { worlds: ["w1", "w2"] } } },
2078
+ { op: "row.update", input: { row: "s2", meta: { facts: ["f3", "f2"], pov: "n1" } } }
2079
+ ]
2080
+ },
2081
+ { op: "row.remove", input: { row: "row id" }, summary: "Removes a row and its lines. For a scene, its body paragraphs are removed too. Marks that point to it elsewhere become plain text" },
2082
+ {
2083
+ op: "group.add",
2084
+ input: {
2085
+ title: "group name",
2086
+ items: "list of scene and group ids to put in (they go in this order, optional)",
2087
+ parent: "id of the group this group goes into. null for the top level. Leave it out to use the place of after",
2088
+ after: "id of the scene or group before it in the same place. null for the front. If both parent and after are left out, it goes where the first scene of items was, and with no items, to the end of the top level"
2089
+ },
2090
+ summary: "Makes a group of scenes. If items are given, they are put into this group",
2091
+ example: [
2092
+ { op: "group.add", as: "$part", input: { title: "Part 1 Earth", items: [] } },
2093
+ { op: "group.add", input: { title: "Chapter 1 Awakening", parent: "$part", items: ["s1", "s2", "s3"] } }
2094
+ ]
2095
+ },
2096
+ { op: "group.update", input: { group: "group id", title: "name" }, summary: "Changes the name of a group" },
2097
+ {
2098
+ op: "group.move",
2099
+ input: { group: "group id", parent: "id of the group to move it to, null for the top level. Leave it out to use the place of after", after: "id of the scene or group before it in the same place. null for the front" },
2100
+ summary: "Moves a group with everything inside it. A group cannot move into itself"
2101
+ },
2102
+ { op: "group.remove", input: { group: "group id" }, summary: "Removes only the group. The scenes and groups inside are not removed and move up one level, to where the group was" },
2103
+ { op: "line.add", input: { parent: "row id or $name", after: "id of the line before it. null for the front, leave it out for the end", text: "text" }, summary: "Adds a line" },
2104
+ { op: "line.update", input: { line: "line id", text: "text" }, summary: "Changes the text" },
2105
+ { op: "line.remove", input: { line: "line id" }, summary: "Removes a line" },
2106
+ {
2107
+ op: "para.add",
2108
+ input: { scene: "scene id or $name", after: "id of the paragraph before it. null for the front, leave it out for the end", text: "text" },
2109
+ summary: "Adds a paragraph to the body text of a scene",
2110
+ example: { op: "para.add", input: { scene: "s2", after: "b4", text: "[Jisu](n3) stood at the door for a long time." } }
2111
+ },
2112
+ { op: "para.update", input: { para: "paragraph id", text: "text" }, summary: "Changes the text of a paragraph" },
2113
+ { op: "para.remove", input: { para: "paragraph id" }, summary: "Removes a paragraph" },
2114
+ { op: "para.move", input: { para: "paragraph id", after: "id of the paragraph before it in the same scene. null for the front" }, summary: "Changes the order inside the same scene. To move a paragraph to another scene, remove it and add it there" },
2115
+ {
2116
+ op: "body.adopt",
2117
+ input: { mode: "replace (replaces all current paragraphs, the default) or append (adds after them)" },
2118
+ summary: "Adopts the text of each scene in the output given with the request as the body paragraphs of that scene. Each line becomes a paragraph. Use it only when the person says to use that output",
2119
+ usesArtifact: true,
2120
+ example: { op: "body.adopt", input: { mode: "replace" } }
2121
+ },
2122
+ {
2123
+ op: "sticker.add",
2124
+ input: { memo: "id of a memo in the memo box, or $name", target: "the row, line, paragraph or node to attach to (none for the work area)", position: "[x, y] (optional)" },
2125
+ summary: "Attaches a memo from the memo box to the screen as a sticker. Ask the person first",
2126
+ example: [
2127
+ { op: "core.memo.add", as: "$m", input: { text: "We do not know yet why Jisu is late" } },
2128
+ { op: "sticker.add", input: { memo: "$m", target: "s1" } }
2129
+ ]
2130
+ },
2131
+ { op: "sticker.attach", input: { sticker: "sticker id", target: "target to attach to. None puts it on the work area", position: "[x, y] (optional)" }, summary: "Attaches it to another target, or takes it off and puts it on the work area" },
2132
+ { op: "sticker.move", input: { sticker: "sticker id", position: "[x, y]" }, summary: "Moves it within the same base" },
2133
+ { op: "sticker.remove", input: { sticker: "sticker id" }, summary: "Removes a sticker. The memo stays in the memo box" },
2134
+ { op: "world.add", input: { name: "name", calendar: "calendar id (earth or an id that starts with cal, leave it out for the default calendar)", note: "note" }, summary: "Makes a world line. Use it when there are two or more worlds with different calendars or flows of time, or two or more versions of the story. Facts and scenes belong to world lines through meta.worlds" },
2135
+ { op: "world.update", input: { world: "world line id", name: "name", calendar: "calendar id", note: "note" }, summary: "Changes a world line. Changing the calendar changes only the shown text" },
2136
+ { op: "world.remove", input: { world: "world line id" }, summary: "Removes a world line. It is taken out of the world lines of facts, and the times written in it are shown with the default calendar" },
2137
+ {
2138
+ op: "calendar.set",
2139
+ input: {
2140
+ calendar: "id of the calendar to change (leave it out to make a new one)",
2141
+ data: `Calendar data. name: name, epoch: 0 o'clock on the first day of year 1 of this calendar (absolute time as decimal text in nanoseconds, or text like { text: "2026\uB144", calendar?: "earth" }), secondNs: nanoseconds in one second ("1000000000"), day: the units inside a day from the largest [{ name: "\uC2DC", count: 24 }, { name: "\uBD84", count: 60 }, { name: "\uCD08", count: 60 }], months: [{ name: "1\uC6D4", days: 30 }, ...], leap: [{ rule: "4,!100,400", month: 2, days: 1 }] or null (no leap years), eras: [{ name: "Imperial", start: same shape as epoch, direction: 1 }, { name: "Pre-Imperial", direction: -1 }] or null (no eras). With base: "earth", write only the fields to change from the Earth calendar. Fields you leave out then (leap years, eras, epoch) keep the Earth calendar values, so send null to remove them`
2142
+ },
2143
+ summary: "Makes or changes a calendar. Wrong data is rejected. After making it, tell the person what the calendar looks like",
2144
+ example: {
2145
+ op: "calendar.set",
2146
+ input: { data: { base: "earth", name: "Imperial", epoch: { text: "2026\uB144" }, eras: [{ name: "Imperial", start: { text: "2026\uB144" }, direction: 1 }, { name: "Pre-Imperial", direction: -1 }] } }
2147
+ }
2148
+ },
2149
+ { op: "calendar.remove", input: { calendar: "calendar id" }, summary: "Removes a calendar. It is rejected if a world line uses it or it is the default calendar" },
2150
+ { op: "calendar.setDefault", input: { calendar: "calendar id (earth or a calendar id)" }, summary: "Sets the default calendar of the work, which facts without a world line use" }
2151
+ ]
2152
+ };
2153
+ var logic = {
2154
+ describe: () => DESCRIPTION,
2155
+ initialize: () => [],
2156
+ plan(state, op, ctx) {
2157
+ const handler = OPERATIONS[op.op];
2158
+ if (!handler) return { error: "INVALID_INPUT", summary: `Unknown operation ${op.op}. See the list of operations in describe_document` };
2159
+ try {
2160
+ const id = (k) => k === 0 && op.as ? op.as : `$~${ctx.stepIndex}.${k}`;
2161
+ return handler(state, op.input ?? {}, id, ctx);
2162
+ } catch (e) {
2163
+ if (e instanceof Reject) return { error: e.code, summary: e.message };
2164
+ throw e;
2165
+ }
2166
+ },
2167
+ validate,
2168
+ project(state, scope, mine) {
2169
+ try {
2170
+ return project(state, scope, mine);
2171
+ } catch (e) {
2172
+ if (e instanceof Reject) return { error: e.code, summary: e.message };
2173
+ throw e;
2174
+ }
2175
+ },
2176
+ extractRefs: refsOf,
2177
+ prepareGeneration(state, scope, medium) {
2178
+ try {
2179
+ return prepareGeneration(state, scope, medium);
2180
+ } catch (e) {
2181
+ if (e instanceof Reject) return { error: e.code, summary: e.message };
2182
+ throw e;
2183
+ }
2184
+ },
2185
+ interpretSelection,
2186
+ describeSelection,
2187
+ resolveTarget(state, target) {
2188
+ const r = state.records[target.id];
2189
+ if (!r) return { found: false };
2190
+ if (r.type === "node") return { found: true, label: r.content.name };
2191
+ if (r.type === "row") return { found: true, label: rowLabel(state, r.id) ?? r.id };
2192
+ if (r.type === "para") return { found: true, label: paraLabel(state, r.id) };
2193
+ if (r.type === "world") return { found: true, label: `world line ${r.content.name}` };
2194
+ if (r.type === "calendar") return { found: true, label: `calendar ${r.content.data.name}` };
2195
+ if (r.type === "settings") return { found: true, label: "plugin settings" };
2196
+ if (r.type === "group") return { found: true, label: groupName(state, r.id) };
2197
+ return { found: true, label: `line ${r.id}` };
2198
+ }
2199
+ };
2200
+ globalThis.__aicPlugin = logic;
2201
+ })();