cortico-world-fun 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,109 @@
1
+ import { areasNow, phaseLabelAt } from './phases.js';
2
+ import { hoursState } from './venues.js';
3
+
4
+ const DAY_MINUTES = 24 * 60;
5
+
6
+ function matchingWishes(wishes, venue) {
7
+ const placeId = venue?.id;
8
+ return (Array.isArray(wishes) ? wishes : []).filter((wish) => wish?.status === 'active'
9
+ && wish.placeId === placeId);
10
+ }
11
+
12
+ function feasible(wish, venue, nowMin) {
13
+ if (hoursState(venue, nowMin) === 'closed') return false;
14
+ if (wish.type === 'visit') return true;
15
+ if (wish.type === 'area') return areasNow(venue, nowMin).includes(wish.target);
16
+ if (wish.type === 'phase') return phaseLabelAt(venue, nowMin) === wish.target;
17
+ if (wish.type === 'souvenir') {
18
+ return (Array.isArray(venue?.souvenirs) ? venue.souvenirs : []).includes(wish.target);
19
+ }
20
+ return false;
21
+ }
22
+
23
+ function wishText(wish, venue) {
24
+ const action = wish.type === 'visit'
25
+ ? `想去${wish.placeName || venue.name}`
26
+ : `想${wish.type === 'souvenir' ? '拿到' : '看看'}${wish.target}`;
27
+ return `有个心愿:${action}${wish.reason ? `(${wish.reason})` : ''}`;
28
+ }
29
+
30
+ function minuteOfDay(value) {
31
+ const minute = Number(value);
32
+ if (!Number.isFinite(minute)) return 0;
33
+ return ((Math.floor(minute) % DAY_MINUTES) + DAY_MINUTES) % DAY_MINUTES;
34
+ }
35
+
36
+ function clockText(minute) {
37
+ const hour = String(Math.floor(minute / 60)).padStart(2, '0');
38
+ const mins = String(minute % 60).padStart(2, '0');
39
+ return `${hour}:${mins}`;
40
+ }
41
+
42
+ function nextWish(wishes, venue, nowMin) {
43
+ if (!wishes.length) return null;
44
+ const start = minuteOfDay(nowMin);
45
+ const boundaries = new Set();
46
+ const addBoundary = (hm) => {
47
+ const match = /^(\d{1,2}):(\d{2})$/.exec(String(hm ?? '').trim());
48
+ if (!match) return;
49
+ const hour = Number(match[1]);
50
+ const minute = Number(match[2]);
51
+ if (hour <= 23 && minute <= 59) boundaries.add(hour * 60 + minute);
52
+ };
53
+
54
+ // The shared hours and phase helpers use half-open intervals. Only their
55
+ // transition instants can change whether one of the wishes is feasible.
56
+ addBoundary(venue?.hours?.open);
57
+ addBoundary(venue?.hours?.close);
58
+ for (const phase of Array.isArray(venue?.phases) ? venue.phases : []) {
59
+ addBoundary(phase?.from);
60
+ addBoundary(phase?.to);
61
+ }
62
+
63
+ const candidates = [...boundaries].map((minute) => {
64
+ const distance = (minute - start + DAY_MINUTES) % DAY_MINUTES;
65
+ return distance || DAY_MINUTES;
66
+ }).sort((a, b) => a - b);
67
+
68
+ for (const minutesAway of candidates) {
69
+ const minute = (start + minutesAway) % DAY_MINUTES;
70
+ const wish = wishes.find((candidate) => feasible(candidate, venue, minute));
71
+ if (!wish) continue;
72
+ const day = Math.floor((start + minutesAway) / DAY_MINUTES) === 0 ? '今天' : '明天';
73
+ return {
74
+ text: `${wishText(wish, venue)};${day} ${clockText(minute)}`,
75
+ minutesAway,
76
+ };
77
+ }
78
+ return null;
79
+ }
80
+
81
+ /**
82
+ * Build a read-only snapshot of the venue's current phase, open areas, and wishes.
83
+ * `history` is the corresponding `historyFor()` result (or null).
84
+ */
85
+ export function recommendVenue(venue, nowMin, wishes, history) {
86
+ const isOpen = hoursState(venue, nowMin) !== 'closed';
87
+ const phase = isOpen ? phaseLabelAt(venue, nowMin) : '';
88
+ const areas = isOpen ? areasNow(venue, nowMin) : [];
89
+ const active = matchingWishes(wishes, venue);
90
+ const currentWish = active.find((wish) => feasible(wish, venue, nowMin));
91
+ const wishReason = currentWish ? wishText(currentWish, venue) : '';
92
+
93
+ let revisitReason = '';
94
+ if (isOpen && Number(history?.visitCount) > 0) {
95
+ const seen = new Set((Array.isArray(history.areas) ? history.areas : [])
96
+ .map((entry) => entry?.area)
97
+ .filter(Boolean));
98
+ const unvisited = areas.filter((area) => !seen.has(area)).slice(0, 2);
99
+ if (unvisited.length) revisitReason = `还没去过:${unvisited.join('、')}。`;
100
+ }
101
+
102
+ return {
103
+ phase,
104
+ areas,
105
+ wishReason,
106
+ revisitReason,
107
+ upcomingWish: currentWish ? null : nextWish(active, venue, nowMin),
108
+ };
109
+ }
package/src/state.js CHANGED
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * 状态形状(落 `<dataDir>/fun/state.json`):
7
7
  * {
8
- * day: '2026-11-15', // 本地日期,跨天就整份重来
8
+ * day: '2026-11-15', // 本地日期
9
9
  * session: null | { // 正在逛的这一趟;null = 没在逛
10
10
  * id, placeId, placeName, scene, outfit,
11
11
  * enteredAt, lastAt, // ms
@@ -14,6 +14,7 @@
14
14
  * photos: [string],
15
15
  * events: [string],
16
16
  * },
17
+ * draft: null, // 跨天超时、等待处理的行程
17
18
  * trips: [{ placeId, placeName, scene, outfit, enteredAt, leftAt, visited, souvenirs, photos, events }],
18
19
  * }
19
20
  *
@@ -23,6 +24,9 @@
23
24
 
24
25
  import { VENUES, hoursState, pickSome } from './venues.js';
25
26
  import { normalizeWishes } from './wishes.js';
27
+ import { normalizeStoryProgress } from './story-packs.js';
28
+ import { normalizeExploration, recordExploration } from './exploration.js';
29
+ import { normalizeTimeline, normalizeRoute, normalizeRoutes, addMoment, timelineFor } from './journeys.js';
26
30
 
27
31
  /** 纪念册最多留几趟。 */
28
32
  export const MAX_TRIPS = 40;
@@ -71,7 +75,7 @@ export function minutesIn(tz, nowMs) {
71
75
 
72
76
  /** 当天的新状态。 */
73
77
  export function newState(day) {
74
- return { day, session: null, trips: [], collection: [], keepsakeTrips: [], tripSeq: 0, wishes: [] };
78
+ return { day, session: null, draft: null, route: null, routes: [], routeSeq: 0, exploration: [], trips: [], collection: [], keepsakeTrips: [], tripSeq: 0, wishes: [] };
75
79
  }
76
80
 
77
81
  export function newTripId(placeId, enteredAt, leftAt) {
@@ -85,7 +89,7 @@ function seedCollection(trips, timezone = 'Asia/Shanghai') {
85
89
  const placeName = text(trip?.placeName, 40) || placeId;
86
90
  const day = tripDay(trip, timezone);
87
91
  for (const name of new Set(textList(trip?.souvenirs, 12, 40))) {
88
- entries.push({ placeId, placeName, name, day, at: Number(trip.leftAt) || 0, tripId: text(trip.id, 60) });
92
+ entries.push({ placeId, placeName, name, day, at: Number(trip.leftAt) || 0, tripId: text(trip.id, 100) });
89
93
  }
90
94
  }
91
95
  return mergeCollection([], entries);
@@ -102,7 +106,7 @@ function mergeKeptTrips(kept, recent) {
102
106
  }
103
107
 
104
108
  function stableTripId(raw) {
105
- const id = text(raw?.id, 60);
109
+ const id = text(raw?.id, 100);
106
110
  return id || newTripId(raw?.placeId, raw?.enteredAt, raw?.leftAt);
107
111
  }
108
112
 
@@ -116,13 +120,13 @@ function mergeCollection(existing, additions) {
116
120
  const day = text(item.day, 10);
117
121
  const at = Number(item.at) || 0;
118
122
  const cur = map.get(key);
119
- if (!cur) map.set(key, { key, placeId, placeName: text(item.placeName, 40) || placeId, name, firstDay: text(item.firstDay, 10) || day, lastDay: text(item.lastDay, 10) || day, firstAt: Number(item.firstAt) || at, lastAt: Number(item.lastAt) || at, times: Math.max(1, Number(item.times) || 1), tripIds: Array.isArray(item.tripIds) ? textList(item.tripIds, 100, 60) : (item.tripId ? [text(item.tripId, 60)] : []) });
123
+ if (!cur) map.set(key, { key, placeId, placeName: text(item.placeName, 40) || placeId, name, firstDay: text(item.firstDay, 10) || day, lastDay: text(item.lastDay, 10) || day, firstAt: Number(item.firstAt) || at, lastAt: Number(item.lastAt) || at, times: Math.max(1, Number(item.times) || 1), tripIds: Array.isArray(item.tripIds) ? textList(item.tripIds, 100, 100) : (item.tripId ? [text(item.tripId, 100)] : []) });
120
124
  else {
121
125
  cur.times += Math.max(1, Number(item.times) || 1);
122
- if (Array.isArray(item.tripIds)) for (const tripId of item.tripIds) if (!cur.tripIds.includes(tripId)) cur.tripIds.push(text(tripId, 60));
126
+ if (Array.isArray(item.tripIds)) for (const tripId of item.tripIds) if (!cur.tripIds.includes(tripId)) cur.tripIds.push(text(tripId, 100));
123
127
  if (day && (!cur.firstDay || day < cur.firstDay)) { cur.firstDay = day; cur.firstAt = at; }
124
128
  if (day && (!cur.lastDay || day > cur.lastDay)) { cur.lastDay = day; cur.lastAt = at; }
125
- if (item.tripId && !cur.tripIds.includes(item.tripId)) cur.tripIds.push(text(item.tripId, 60));
129
+ if (item.tripId && !cur.tripIds.includes(item.tripId)) cur.tripIds.push(text(item.tripId, 100));
126
130
  }
127
131
  }
128
132
  return [...map.values()].sort((a, b) => b.lastAt - a.lastAt || a.name.localeCompare(b.name));
@@ -189,8 +193,9 @@ function normalizeTrip(raw, fallbackId = '') {
189
193
  const placeId = text(raw.placeId, 40);
190
194
  if (!placeId) return null;
191
195
  return {
192
- id: fallbackId || text(raw.id, 60) || newTripId(placeId, raw.enteredAt, raw.leftAt),
196
+ id: fallbackId || text(raw.id, 100) || newTripId(placeId, raw.enteredAt, raw.leftAt),
193
197
  placeId,
198
+ sequence: Number.isSafeInteger(raw.sequence) && raw.sequence > 0 ? raw.sequence : 0,
194
199
  placeName: text(raw.placeName, 40) || placeId,
195
200
  scene: text(raw.scene, 40),
196
201
  outfit: text(raw.outfit, 40),
@@ -198,6 +203,14 @@ function normalizeTrip(raw, fallbackId = '') {
198
203
  company: text(raw.company, 40),
199
204
  enteredAt: Number.isFinite(Number(raw.enteredAt)) ? Number(raw.enteredAt) : 0,
200
205
  leftAt: Number.isFinite(Number(raw.leftAt)) ? Number(raw.leftAt) : 0,
206
+ pausedMs: Number.isFinite(raw.pausedMs) ? Math.max(0, raw.pausedMs) : 0,
207
+ routeId: text(raw.routeId, 100),
208
+ routeOrder: [1, 2].includes(raw.routeOrder) ? raw.routeOrder : 0,
209
+ phases: [...new Set(textList(raw.phases, 20, 40))],
210
+ branchSeen: [...new Set(textList(raw.branchSeen, 40, 100))],
211
+ storyProgress: normalizeStoryProgress(raw.storyProgress),
212
+ timelineTruncated: raw.timelineTruncated === true || (Array.isArray(raw.timeline) && raw.timeline.length > 240),
213
+ timeline: normalizeTimeline(raw.timeline?.length ? raw.timeline : timelineFor({ ...raw, placeName: text(raw.placeName, 40) || placeId })),
201
214
  /**
202
215
  * 收摊那天的**本地**日期(YYYY-MM-DD)。
203
216
  *
@@ -224,40 +237,27 @@ function normalizeSession(raw) {
224
237
  if (!trip) return null;
225
238
  return {
226
239
  ...trip,
227
- id: text(raw.id, 40) || `${trip.placeId}-${trip.enteredAt}`,
240
+ id: text(raw.id, 100) || `${trip.placeId}-${trip.enteredAt}`,
228
241
  lastAt: Number.isFinite(Number(raw.lastAt)) ? Number(raw.lastAt) : trip.enteredAt,
229
242
  pendingChoice: normalizePendingChoice(raw.pendingChoice),
230
243
  };
231
244
  }
232
245
 
233
- /**
234
- * 把磁盘上的旧状态补齐成当前形状(不信任文件内容)。
235
- *
236
- * ## 跨天为什么不再无脑清 session
237
- *
238
- * 0.1.5 及以前:`raw.day !== day` 就直接 `session = null`。这看起来合理
239
- * (「昨天没逛完就是不逛完了」),实际会踩一条真会发生的路:
240
- *
241
- * 夜市 17:30–01:00、KTV 18:00–02:00。23:50 进夜市逛着,过了午夜再
242
- * `fun_wander`,回执就是「你还没进门呢」——她正在逛的那一趟凭空消失,
243
- * 而那个地方本来就没打烊。
244
- *
245
- * 现在的判据是两条取或:
246
- *
247
- * 1. **还是同一天** → 留着。同一天里挂久了不算「没逛完」,`fun_wander`
248
- * 会提一句「挂得有点久了」,但绝不替她把这一趟收掉(这是 0.1.4 的行为,
249
- * 不能因为修跨午夜就一起改坏)。
250
- * 2. **跨了天,但上一次动在 TTL 之内** → 留着。这就是夜市/KTV 那条路。
251
- *
252
- * 跨了天、又挂过 TTL 的才丢(「逛到一半去睡觉,第二天回来发现不算了」)。
253
- *
254
- * 纪念册(`trips`)**任何时候都不清**——跨天该清的是「今天正在逛什么」,
255
- * 不是「她去过哪儿」。这一条是 0.1.5 修的,别改回去。
256
- */
246
+ /** 只读区分正在逛和跨天超时的未完行程。 */
247
+ export function outingStatus(state, day, nowMs, ttlMin, timezone = 'Asia/Shanghai') {
248
+ const session = state?.session ?? null;
249
+ const lastAt = session?.lastAt || session?.enteredAt;
250
+ const expired = session && !sessionAlive(session, nowMs, ttlMin)
251
+ && (lastAt ? dayIn(timezone, lastAt) : state.day) !== day;
252
+ return { session: expired ? null : session, draft: expired ? session : (state?.draft ?? null) };
253
+ }
254
+
255
+ /** 兼容旧状态,跨天超时只暂停行程,仍保留已发生的事。 */
257
256
  export function normalizeState(raw, day, nowMs = 0, ttlMin = DEFAULT_TTL_MIN, timezone = 'Asia/Shanghai') {
258
257
  if (!raw || typeof raw !== 'object') return newState(day);
259
- const session = normalizeSession(raw.session);
260
- const keep = session && (raw.day === day || sessionAlive(session, nowMs, ttlMin));
258
+ const { session, draft } = outingStatus({
259
+ day: raw.day, session: normalizeSession(raw.session), draft: normalizeSession(raw.draft),
260
+ }, day, nowMs, ttlMin, timezone);
261
261
  const rawTrips = Array.isArray(raw.trips) ? raw.trips : [];
262
262
  const used = new Set();
263
263
  const trips = rawTrips.map((t, i) => {
@@ -268,20 +268,37 @@ export function normalizeState(raw, day, nowMs = 0, ttlMin = DEFAULT_TTL_MIN, ti
268
268
  if (normalized && !t?.id) normalized.id = id;
269
269
  return normalized;
270
270
  }).filter(Boolean).slice(0, MAX_TRIPS);
271
- const nextTripSeq = Number.isInteger(raw.tripSeq) && raw.tripSeq >= 0
271
+ const routes = normalizeRoutes([...(Array.isArray(raw.routes) ? raw.routes : []), raw.route]);
272
+ const candidate = normalizeRoute(raw.route);
273
+ const route = raw.route === undefined
274
+ ? [...routes].reverse().find((r) => ['planned', 'active', 'between'].includes(r.status)) ?? null
275
+ : candidate && ['planned', 'active', 'between'].includes(candidate.status) ? candidate : null;
276
+ const exploration = normalizeExploration(raw.exploration, [...trips, ...mergeKeptTrips(raw.keepsakeTrips, trips)], timezone);
277
+ const priorTripSeq = Number.isInteger(raw.tripSeq) && raw.tripSeq >= 0
272
278
  ? raw.tripSeq
273
279
  : trips.length + (Array.isArray(raw.keepsakeTrips) ? raw.keepsakeTrips.length : 0);
280
+ const nextTripSeq = Math.max(priorTripSeq, exploration.reduce((n, row) => Math.max(n, row.lastSequence || 0), 0), trips.reduce((n, trip) => Math.max(n, trip.sequence || 0), 0));
274
281
  return {
275
282
  day,
276
- session: keep ? session : null,
283
+ session,
284
+ draft,
277
285
  trips,
278
286
  collection: Array.isArray(raw.collection) ? mergeCollection(raw.collection, []) : seedCollection(trips, timezone),
279
287
  keepsakeTrips: mergeKeptTrips(raw.keepsakeTrips, trips),
280
288
  tripSeq: nextTripSeq,
289
+ routeSeq: Math.max(0, Math.floor(Number(raw.routeSeq) || 0)),
290
+ route,
291
+ routes: routes.filter((r) => r.id === route?.id || r.id === session?.routeId || r.id === draft?.routeId || [...trips, ...mergeKeptTrips(raw.keepsakeTrips, trips)].some((t) => t.routeId === r.id)),
292
+ exploration,
281
293
  wishes: normalizeWishes(raw.wishes),
282
294
  };
283
295
  }
284
296
 
297
+ /** 逗留时间不包含上次活动到恢复之间的暂停。 */
298
+ export function outingMinutes(outing, endAt) {
299
+ return Math.max(0, Math.round((endAt - outing.enteredAt - (outing.pausedMs ?? 0)) / 60000));
300
+ }
301
+
285
302
  /** 和 config.js 的 `funSessionTTLMin` 默认值保持一致(纯函数不 import 配置,防循环依赖)。 */
286
303
  export const DEFAULT_TTL_MIN = 90;
287
304
 
@@ -332,6 +349,10 @@ export function enterVenue(state, venue, nowMs, random = Math.random, company =
332
349
  ate: [],
333
350
  events: [],
334
351
  choices: [],
352
+ phases: [],
353
+ branchSeen: [],
354
+ storyProgress: [],
355
+ timeline: [],
335
356
  };
336
357
  state.session = session;
337
358
  return { session, already: false };
@@ -435,7 +456,7 @@ export function buySouvenir(state, item, nowMs) {
435
456
  * 上海时间早上 8 点前收的摊会被算成前一天。不传就留空,读的一方回退到
436
457
  * 按插件当前时区读取 leftAt(不迁移、不改写旧记录)。
437
458
  */
438
- export function closeSession(state, nowMs, note = '', day = '') {
459
+ export function closeSession(state, nowMs, note = '', day = '', timezone = 'Asia/Shanghai') {
439
460
  const s = state.session;
440
461
  if (!s) return null;
441
462
  const said = text(note, 120);
@@ -443,6 +464,7 @@ export function closeSession(state, nowMs, note = '', day = '') {
443
464
  const trip = {
444
465
  id: `${newTripId(s.placeId, s.enteredAt, nowMs)}-${state.tripSeq}`,
445
466
  favorite: false,
467
+ sequence: state.tripSeq,
446
468
  placeId: s.placeId,
447
469
  placeName: s.placeName,
448
470
  scene: s.scene,
@@ -450,6 +472,14 @@ export function closeSession(state, nowMs, note = '', day = '') {
450
472
  company: text(s.company, 40),
451
473
  enteredAt: s.enteredAt,
452
474
  leftAt: nowMs,
475
+ pausedMs: s.pausedMs ?? 0,
476
+ routeId: text(s.routeId, 100),
477
+ routeOrder: [1, 2].includes(s.routeOrder) ? s.routeOrder : 0,
478
+ phases: [...(s.phases ?? [])],
479
+ branchSeen: [...(s.branchSeen ?? [])],
480
+ storyProgress: normalizeStoryProgress(s.storyProgress),
481
+ timelineTruncated: s.timelineTruncated === true || (s.timeline?.length ?? 0) >= 240,
482
+ timeline: normalizeTimeline(s.timeline),
453
483
  leftDay: DAY_RE.test(text(day, 10)) ? text(day, 10) : '',
454
484
  // 收摊这句话以前只出现在回执里,转头就没了:纪念册重看这一趟只剩「逛了哪儿」。
455
485
  // 「今天人很多,但很开心」这种话才是她自己的记录,必须存。
@@ -462,13 +492,15 @@ export function closeSession(state, nowMs, note = '', day = '') {
462
492
  events: [...s.events],
463
493
  choices: normalizeChoices(s.choices),
464
494
  };
495
+ addMoment(trip, 'close', said ? '收摊 · ' + said : '收摊', nowMs);
465
496
  state.session = null;
497
+ state.exploration = recordExploration(state.exploration, trip, timezone);
466
498
  state.trips.unshift(trip);
467
499
  state.collection = mergeCollection(state.collection, [...new Set(s.souvenirs)].map((name) => ({ placeId: s.placeId, placeName: s.placeName, name, day, at: nowMs, tripId: trip.id })));
468
500
  const savedTrip = state.keepsakeTrips?.find((x) => x.id === trip.id);
469
501
  if (savedTrip) state.keepsakeTrips = state.keepsakeTrips.map((x) => x.id === trip.id ? structuredClone(trip) : x);
470
502
  if (state.trips.length > MAX_TRIPS) state.trips.length = MAX_TRIPS;
471
- const stayedMin = Math.max(0, Math.round((nowMs - s.enteredAt) / 60000));
503
+ const stayedMin = outingMinutes(s, nowMs);
472
504
  return { trip, stayedMin, note: said };
473
505
  }
474
506
 
@@ -0,0 +1,111 @@
1
+ import { validateStoryPack } from './story-packs.js';
2
+
3
+ const drafts = [
4
+ {
5
+ version: 1,
6
+ id: 'riverside-late-lights',
7
+ title: '桥底下的灯影',
8
+ description: '江边夜里,桥下的一点回声把两种安静串到一起。',
9
+ placeId: 'riverside',
10
+ start: 'under-bridge',
11
+ nodes: [
12
+ {
13
+ id: 'under-bridge',
14
+ area: '桥底下',
15
+ event: '桥底的回声短了一拍,对岸的灯影正好从水面上慢慢移过去。',
16
+ prompt: '你想沿着哪一种安静继续?',
17
+ when: { from: '19:30', to: '23:30', phases: ['night'] },
18
+ choices: [
19
+ { id: 'sit-by-river', label: '去长椅边听一会儿', result: '把刚才那段回声留在身后,脚步慢下来。', next: 'bench-ending' },
20
+ { id: 'watch-lights', label: '看对岸的灯', result: '灯影被水纹拉长,远处的亮點也跟着轻轻晃。', next: 'shore-ending' },
21
+ ],
22
+ },
23
+ {
24
+ id: 'bench-ending',
25
+ area: '长椅上',
26
+ event: '长椅旁的风声盖过了桥下的回响,几盏路灯隔着水安静地亮着。',
27
+ when: { from: '19:30', to: '23:30', phases: ['night'] },
28
+ },
29
+ {
30
+ id: 'shore-ending',
31
+ area: '栏杆边',
32
+ event: '栏杆外的水面一圈圈散开,对岸的灯还在远处连成一条柔和的线。',
33
+ when: { from: '19:30', to: '23:30', phases: ['night'] },
34
+ },
35
+ ],
36
+ },
37
+ {
38
+ version: 1,
39
+ id: 'market-last-lantern',
40
+ title: '街尾最后一盏灯',
41
+ description: '夜市快收摊时,在台阶边做一个不着急的决定。',
42
+ placeId: 'market',
43
+ start: 'last-steps',
44
+ nodes: [
45
+ {
46
+ id: 'last-steps',
47
+ area: '街尾的台阶',
48
+ event: '街尾的台阶空出一小块位置,远处的串灯一盏接一盏暗下去。',
49
+ prompt: '最后再走向哪边看看?',
50
+ when: { from: '00:00', to: '01:00', phases: ['closing'] },
51
+ choices: [
52
+ { id: 'last-stall', label: '绕到还亮着的摊前', result: '卷帘门落下的声音渐渐远了,只剩一角暖光。', next: 'stall-ending' },
53
+ { id: 'quiet-corner', label: '在街尾多坐一会儿', result: '人声散开后,路面上只留下零星的脚步声。', next: 'steps-ending' },
54
+ ],
55
+ },
56
+ {
57
+ id: 'stall-ending',
58
+ area: '烧烤摊',
59
+ event: '摊前的灯还亮着,老板把空纸箱叠好,准备收起桌边的小牌子。',
60
+ when: { from: '00:00', to: '01:00', phases: ['closing'] },
61
+ },
62
+ {
63
+ id: 'steps-ending',
64
+ area: '糖水铺',
65
+ event: '糖水铺的白汽慢慢散掉,收摊的人把桌面擦了一遍又一遍。',
66
+ when: { from: '00:00', to: '01:00', phases: ['closing'] },
67
+ },
68
+ ],
69
+ },
70
+ {
71
+ version: 1,
72
+ id: 'con-poster-hour',
73
+ title: '海报墙的最后一小时',
74
+ description: '展馆快结束时,在熟悉的颜色里再留一小会儿。',
75
+ placeId: 'con',
76
+ start: 'poster-wall',
77
+ nodes: [
78
+ {
79
+ id: 'poster-wall',
80
+ area: '海报墙',
81
+ event: '海报墙上的彩色边缘被灯光照得发亮,胶带翘起一角,像还没说完的话。',
82
+ prompt: '接下来想去人声更近的地方,还是回到熟悉的摊位?',
83
+ when: { from: '17:00', to: '18:00' },
84
+ choices: [
85
+ { id: 'stage', label: '去舞台区听最后一段广播', result: '广播声在展馆顶上绕了一圈,慢慢淡下去。', next: 'stage-ending' },
86
+ { id: 'artists', label: '再看一眼同人展台', result: '隔板边的纸袋被轻轻收好,展台也渐渐空下来。', next: 'table-ending' },
87
+ ],
88
+ },
89
+ {
90
+ id: 'stage-ending',
91
+ area: '舞台区',
92
+ event: '舞台边的灯一盏盏熄下去,最后一段广播提醒大家慢慢离场。',
93
+ when: { from: '17:00', to: '18:00' },
94
+ },
95
+ {
96
+ id: 'table-ending',
97
+ area: '同人展台',
98
+ event: '同人展台的摊主把纸张理齐,隔壁通道里的脚步声稀疏下来。',
99
+ when: { from: '17:00', to: '18:00' },
100
+ },
101
+ ],
102
+ },
103
+ ];
104
+
105
+ function validateBuiltin(draft) {
106
+ const result = validateStoryPack(draft);
107
+ if (!result.ok) throw new Error(`Invalid built-in story pack ${draft.id}: ${result.errors.join('; ')}`);
108
+ return result.pack;
109
+ }
110
+
111
+ export const BUILTIN_STORY_PACKS = drafts.map(validateBuiltin);
@@ -0,0 +1,149 @@
1
+ import { mkdir, readFile, writeFile, rename } from 'node:fs/promises';
2
+ import { dirname } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { validateStoryPack, storyAvailability, pickStory } from './story-packs.js';
5
+ import { BUILTIN_STORY_PACKS } from './story-examples.js';
6
+ import { hmToMin } from './phases.js';
7
+
8
+ const MAX_BYTES = 32768;
9
+ const MAX_PACKS = 20;
10
+ const plain = (pack) => { const { revision, ...content } = pack; return content; };
11
+ const BUILTINS = BUILTIN_STORY_PACKS.map((pack) => validateStoryPack(plain(pack))).filter((r) => r.ok).map((r) => r.pack);
12
+ const failure = (error, errors = [error]) => ({ ok: false, error, errors });
13
+
14
+ /** Original local content library. Construction is pure; load is explicit. */
15
+ export class StoryLibrary {
16
+ constructor({ file, venues, visits = () => 0, nowMin = () => 0 }) {
17
+ this.file = file;
18
+ this.venues = venues;
19
+ this.visits = visits;
20
+ this.nowMin = nowMin;
21
+ this.data = { version: 1, packs: [], disabledIds: [] };
22
+ this.warnings = [];
23
+ this.damagedSource = null;
24
+ }
25
+
26
+ async load() {
27
+ this.data = { version: 1, packs: [], disabledIds: [] };
28
+ this.warnings = [];
29
+ this.damagedSource = null;
30
+ let source;
31
+ try {
32
+ source = await readFile(this.file, 'utf8');
33
+ if (Buffer.byteLength(source, 'utf8') > MAX_BYTES * (MAX_PACKS + 1)) throw new Error('剧情包文件过大');
34
+ const raw = JSON.parse(source);
35
+ if (!raw || raw.version !== 1 || !Array.isArray(raw.packs)) throw new Error('剧情包文件格式不受支持');
36
+ const packs = [], ids = new Set();
37
+ for (const value of raw.packs.slice(0, MAX_PACKS)) {
38
+ const result = validateStoryPack(value);
39
+ if (!result.ok || ids.has(result.pack.id)) {
40
+ this.warnings.push('有一个无效或重复剧情包已跳过:' + (result.errors?.[0] || 'ID 重复'));
41
+ continue;
42
+ }
43
+ ids.add(result.pack.id); packs.push(result.pack);
44
+ }
45
+ if (raw.packs.length > MAX_PACKS) this.warnings.push('超过 20 个自定义剧情包的部分未载入。');
46
+ this.data = { version: 1, packs, disabledIds: [...new Set((Array.isArray(raw.disabledIds) ? raw.disabledIds : []).filter((id) => ids.has(id) || BUILTINS.some((p) => p.id === id)))] };
47
+ if (this.warnings.length) this.damagedSource = source;
48
+ } catch (error) {
49
+ if (error?.code !== 'ENOENT') {
50
+ this.warnings.push('剧情包文件未载入;内置剧情仍可用。' + (error?.message || '读取失败'));
51
+ this.damagedSource = typeof source === 'string' ? source : null;
52
+ }
53
+ }
54
+ }
55
+
56
+ catalog() {
57
+ const userIds = new Set(this.data.packs.map((pack) => pack.id));
58
+ return [...this.data.packs.map((pack) => ({ pack, builtin: false })), ...BUILTINS.filter((pack) => !userIds.has(pack.id)).map((pack) => ({ pack, builtin: true }))]
59
+ .map((row) => ({ ...row, enabled: !this.data.disabledIds.includes(row.pack.id) }));
60
+ }
61
+
62
+ list() {
63
+ const venues = this.venues();
64
+ return {
65
+ ok: true,
66
+ packs: this.catalog().map(({ pack, enabled, builtin }) => ({ id: pack.id, title: pack.title, description: pack.description || '', placeId: pack.placeId, revision: pack.revision, nodeCount: pack.nodes.length, enabled, builtin, ...storyAvailability(pack, venues) })),
67
+ places: venues.map((v) => ({ id: v.id, name: v.name, areas: [...v.areas] })),
68
+ warnings: [...this.warnings],
69
+ };
70
+ }
71
+
72
+ parse(json) {
73
+ if (typeof json !== 'string' || Buffer.byteLength(json, 'utf8') > MAX_BYTES) return failure('请提供不超过 32 KB 的剧情包 JSON。');
74
+ try { return validateStoryPack(JSON.parse(json)); }
75
+ catch { return failure('JSON 格式不正确,请检查逗号、引号和括号。'); }
76
+ }
77
+
78
+ async save(next) {
79
+ await mkdir(dirname(this.file), { recursive: true });
80
+ if (this.damagedSource !== null) await writeFile(this.file + '.invalid-' + randomUUID() + '.bak', this.damagedSource, { encoding: 'utf8', flag: 'wx' });
81
+ const serialized = { version: 1, packs: next.packs.map(plain), disabledIds: next.disabledIds };
82
+ await writeFile(this.file + '.tmp', JSON.stringify(serialized, null, 2), 'utf8');
83
+ await rename(this.file + '.tmp', this.file);
84
+ this.data = next; this.warnings = []; this.damagedSource = null;
85
+ }
86
+
87
+ async act(args = {}) {
88
+ const action = args.action || 'list';
89
+ if (action === 'list') return this.list();
90
+ if (action === 'template') {
91
+ const venue = args.placeId ? this.venues().find((v) => v.id === args.placeId) : this.venues()[0];
92
+ if (!venue) return failure('没有找到模板要绑定的地点。');
93
+ const area = venue.areas[0], nextArea = venue.areas[1] || area;
94
+ const template = { version: 1, id: 'my-outing', title: venue.name + '的一段小事', description: '可编辑的原创剧情模板', placeId: venue.id, start: 'notice', nodes: [
95
+ { id: 'notice', area, event: '走到这里时,脚步慢了下来', prompt: '想多看一会儿,还是接着往前逛?', choices: [
96
+ { id: 'stay', label: '再看一会儿', result: '决定再看一会儿', next: 'stay-end' },
97
+ { id: 'walk', label: '接着逛', result: '决定接着去' + nextArea, next: 'walk-end' },
98
+ ] },
99
+ { id: 'stay-end', area, event: '又多停留了一会儿,才继续往前走' },
100
+ { id: 'walk-end', area: nextArea, event: '顺着刚才选的方向走到了下一处' },
101
+ ] };
102
+ return { ok: true, json: JSON.stringify(template, null, 2) };
103
+ }
104
+ const row = this.catalog().find((x) => x.pack.id === args.id);
105
+ if (action === 'validate' || action === 'preview' || action === 'import') {
106
+ const result = args.json !== undefined ? this.parse(args.json) : row ? { ok: true, pack: row.pack } : failure('请先提供剧情包 JSON 或已有剧情包 ID。');
107
+ if (!result.ok) return { ...result, error: result.errors?.join(';') || result.error || '剧情包校验失败。' };
108
+ const pack = result.pack;
109
+ const availability = storyAvailability(pack, this.venues());
110
+ if (action === 'validate') return { ok: true, pack: plain(pack), warnings: availability.warnings, available: availability.available, errors: [] };
111
+ if (action === 'preview') {
112
+ const nowMin = args.time === undefined || args.time === '' ? this.nowMin() : hmToMin(args.time);
113
+ if (nowMin === null) return failure('预览时间须为 HH:MM。');
114
+ const venue = this.venues().find((v) => v.id === pack.placeId);
115
+ const area = args.area || pack.nodes.find((n) => n.id === pack.start)?.area;
116
+ const pick = venue ? pickStory([{ pack, enabled: true }], venue, area, nowMin, { storyProgress: [] }, this.visits(pack.placeId)) : null;
117
+ return { ok: true, title: pack.title, eligible: Boolean(pick), warnings: availability.warnings, nodes: pack.nodes.map((n) => ({ id: n.id, area: n.area, event: n.event, when: n.when || {}, next: n.next || '', choices: (n.choices || []).map((c) => ({ id: c.id, label: c.label, next: c.next || '' })) })) };
118
+ }
119
+ const existing = this.data.packs.find((p) => p.id === pack.id);
120
+ if (!existing && BUILTINS.some((p) => p.id === pack.id)) return failure('这个 ID 属于内置剧情包,请换一个自定义 ID。');
121
+ if (existing && args.replace !== true) return failure('已有同 ID 剧情包;勾选明确覆盖后再导入。');
122
+ if (!existing && this.data.packs.length >= MAX_PACKS) return failure('最多保存 20 个自定义剧情包,请先移除一个不用的包。');
123
+ await this.save({ ...this.data, packs: [...this.data.packs.filter((p) => p.id !== pack.id), pack] });
124
+ return { ok: true, id: pack.id, warnings: availability.warnings, message: '剧情包已导入。' };
125
+ }
126
+ if (!row) return failure('没有找到这个剧情包,请刷新清单。');
127
+ if (action === 'export') return { ok: true, json: JSON.stringify(plain(row.pack), null, 2) };
128
+ if (action === 'enable' || action === 'disable') {
129
+ const disabled = new Set(this.data.disabledIds);
130
+ if (action === 'disable') disabled.add(row.pack.id); else disabled.delete(row.pack.id);
131
+ await this.save({ ...this.data, disabledIds: [...disabled] });
132
+ return { ok: true, id: row.pack.id, message: action === 'disable' ? '剧情包已停用,已有经历保留。' : '剧情包已启用;满足条件后才会出现。' };
133
+ }
134
+ if (action === 'remove') {
135
+ if (row.builtin) return failure('内置剧情包可以停用,不能移除。');
136
+ await this.save({ ...this.data, packs: this.data.packs.filter((p) => p.id !== row.pack.id), disabledIds: this.data.disabledIds.filter((id) => id !== row.pack.id) });
137
+ return { ok: true, id: row.pack.id, message: '已移除剧情包定义;旧行程和当时的选择保留。' };
138
+ }
139
+ return failure('不支持的剧情包操作。');
140
+ }
141
+ }
142
+
143
+ export function storyResultText(result) {
144
+ if (!result.ok) return result.error || (result.errors ?? []).join(';') || '剧情包操作失败。';
145
+ if (result.json) return result.json;
146
+ if (result.packs) return ['地点剧情包:', ...result.packs.map((p) => `- ${p.title}(${p.id}) · ${p.placeName || p.placeId} · ${p.enabled ? p.available ? '启用' : '暂不可用' : '停用'}${p.warnings.length ? ';' + p.warnings.join(';') : ''}`), ...(result.warnings ?? [])].join('\n');
147
+ if (result.nodes) return [`预览:${result.title}(当前测试条件${result.eligible ? '可触发' : '未满足'},不会推进真实行程)`, ...result.nodes.map((n) => `${n.id} · ${n.area}:${n.event}${n.choices.length ? ';' + n.choices.map((c) => c.label + ' → ' + (c.next || '结束')).join(' / ') : ' → ' + (n.next || '结束')}`), ...(result.warnings ?? [])].join('\n');
148
+ return result.message || ['剧情包结构校验通过。', ...(result.warnings ?? [])].join('\n');
149
+ }