cortico-world-fun 0.1.6 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/state.js CHANGED
@@ -22,6 +22,7 @@
22
22
  */
23
23
 
24
24
  import { VENUES, hoursState, pickSome } from './venues.js';
25
+ import { normalizeWishes } from './wishes.js';
25
26
 
26
27
  /** 纪念册最多留几趟。 */
27
28
  export const MAX_TRIPS = 40;
@@ -70,7 +71,61 @@ export function minutesIn(tz, nowMs) {
70
71
 
71
72
  /** 当天的新状态。 */
72
73
  export function newState(day) {
73
- return { day, session: null, trips: [] };
74
+ return { day, session: null, trips: [], collection: [], keepsakeTrips: [], tripSeq: 0, wishes: [] };
75
+ }
76
+
77
+ export function newTripId(placeId, enteredAt, leftAt) {
78
+ return `${text(placeId, 40)}-${Number(enteredAt) || 0}-${Number(leftAt) || 0}`;
79
+ }
80
+
81
+ function seedCollection(trips, timezone = 'Asia/Shanghai') {
82
+ const entries = [];
83
+ for (const trip of Array.isArray(trips) ? trips : []) {
84
+ const placeId = text(trip?.placeId, 40);
85
+ const placeName = text(trip?.placeName, 40) || placeId;
86
+ const day = tripDay(trip, timezone);
87
+ 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) });
89
+ }
90
+ }
91
+ return mergeCollection([], entries);
92
+ }
93
+
94
+ function mergeKeptTrips(kept, recent) {
95
+ const map = new Map();
96
+ for (const raw of [...(Array.isArray(kept) ? kept : []), ...(Array.isArray(recent) ? recent.filter((t) => t?.favorite) : [])]) {
97
+ const key = stableTripId(raw);
98
+ const trip = normalizeTrip(raw, key);
99
+ if (trip) map.set(trip.id, trip);
100
+ }
101
+ return [...map.values()].sort((a, b) => b.leftAt - a.leftAt);
102
+ }
103
+
104
+ function stableTripId(raw) {
105
+ const id = text(raw?.id, 60);
106
+ return id || newTripId(raw?.placeId, raw?.enteredAt, raw?.leftAt);
107
+ }
108
+
109
+ function mergeCollection(existing, additions) {
110
+ const map = new Map();
111
+ for (const item of [...(Array.isArray(existing) ? existing : []), ...(Array.isArray(additions) ? additions : [])]) {
112
+ const placeId = text(item?.placeId, 40);
113
+ const name = text(item?.name, 40);
114
+ if (!placeId || !name) continue;
115
+ const key = `${placeId}::${name}`;
116
+ const day = text(item.day, 10);
117
+ const at = Number(item.at) || 0;
118
+ 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)] : []) });
120
+ else {
121
+ 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));
123
+ if (day && (!cur.firstDay || day < cur.firstDay)) { cur.firstDay = day; cur.firstAt = at; }
124
+ 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));
126
+ }
127
+ }
128
+ return [...map.values()].sort((a, b) => b.lastAt - a.lastAt || a.name.localeCompare(b.name));
74
129
  }
75
130
 
76
131
  const text = (v, max) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, max) : '');
@@ -117,11 +172,24 @@ function normalizeAte(v) {
117
172
  return out;
118
173
  }
119
174
 
120
- function normalizeTrip(raw) {
175
+ function normalizeChoices(v) {
176
+ const arr = Array.isArray(v) ? v : [];
177
+ return arr.map((x) => ({ event: text(x?.event, 120), option: text(x?.option, 60), result: text(x?.result, 160), at: Number(x?.at) || 0 })).filter((x) => x.event && x.option).slice(0, 20);
178
+ }
179
+
180
+ function normalizePendingChoice(v) {
181
+ if (!v || typeof v !== 'object') return null;
182
+ const options = Array.isArray(v.options) ? v.options.map((x) => ({ id: text(x?.id, 50), label: text(x?.label, 100), result: text(x?.result, 160) })).filter((x) => x.id && x.label).slice(0, 4) : [];
183
+ const id = text(v.id, 100); const event = text(v.event, 120);
184
+ return id && event && options.length ? { id, event, area: text(v.area, 40), prompt: text(v.prompt, 160), options } : null;
185
+ }
186
+
187
+ function normalizeTrip(raw, fallbackId = '') {
121
188
  if (!raw || typeof raw !== 'object') return null;
122
189
  const placeId = text(raw.placeId, 40);
123
190
  if (!placeId) return null;
124
191
  return {
192
+ id: fallbackId || text(raw.id, 60) || newTripId(placeId, raw.enteredAt, raw.leftAt),
125
193
  placeId,
126
194
  placeName: text(raw.placeName, 40) || placeId,
127
195
  scene: text(raw.scene, 40),
@@ -141,11 +209,13 @@ function normalizeTrip(raw) {
141
209
  leftDay: DAY_RE.test(text(raw.leftDay, 10)) ? text(raw.leftDay, 10) : '',
142
210
  /** 收摊时说的那一句(和 `visited[].note` 不是一回事:那是逛某处时记的)。 */
143
211
  note: text(raw.note, 120),
212
+ favorite: raw.favorite === true,
144
213
  visited: normalizeVisited(raw.visited),
145
214
  souvenirs: textList(raw.souvenirs, 12, 40),
146
215
  photos: textList(raw.photos, 12, 60),
147
216
  ate: normalizeAte(raw.ate),
148
217
  events: textList(raw.events, 16, 120),
218
+ choices: normalizeChoices(raw.choices),
149
219
  };
150
220
  }
151
221
 
@@ -156,6 +226,7 @@ function normalizeSession(raw) {
156
226
  ...trip,
157
227
  id: text(raw.id, 40) || `${trip.placeId}-${trip.enteredAt}`,
158
228
  lastAt: Number.isFinite(Number(raw.lastAt)) ? Number(raw.lastAt) : trip.enteredAt,
229
+ pendingChoice: normalizePendingChoice(raw.pendingChoice),
159
230
  };
160
231
  }
161
232
 
@@ -183,14 +254,31 @@ function normalizeSession(raw) {
183
254
  * 纪念册(`trips`)**任何时候都不清**——跨天该清的是「今天正在逛什么」,
184
255
  * 不是「她去过哪儿」。这一条是 0.1.5 修的,别改回去。
185
256
  */
186
- export function normalizeState(raw, day, nowMs = 0, ttlMin = DEFAULT_TTL_MIN) {
257
+ export function normalizeState(raw, day, nowMs = 0, ttlMin = DEFAULT_TTL_MIN, timezone = 'Asia/Shanghai') {
187
258
  if (!raw || typeof raw !== 'object') return newState(day);
188
259
  const session = normalizeSession(raw.session);
189
260
  const keep = session && (raw.day === day || sessionAlive(session, nowMs, ttlMin));
261
+ const rawTrips = Array.isArray(raw.trips) ? raw.trips : [];
262
+ const used = new Set();
263
+ const trips = rawTrips.map((t, i) => {
264
+ const base = stableTripId(t);
265
+ const id = used.has(base) ? `${base}-legacy-${i}` : base;
266
+ used.add(base);
267
+ const normalized = normalizeTrip(t, id);
268
+ if (normalized && !t?.id) normalized.id = id;
269
+ return normalized;
270
+ }).filter(Boolean).slice(0, MAX_TRIPS);
271
+ const nextTripSeq = Number.isInteger(raw.tripSeq) && raw.tripSeq >= 0
272
+ ? raw.tripSeq
273
+ : trips.length + (Array.isArray(raw.keepsakeTrips) ? raw.keepsakeTrips.length : 0);
190
274
  return {
191
275
  day,
192
276
  session: keep ? session : null,
193
- trips: (Array.isArray(raw.trips) ? raw.trips : []).map(normalizeTrip).filter(Boolean).slice(0, MAX_TRIPS),
277
+ trips,
278
+ collection: Array.isArray(raw.collection) ? mergeCollection(raw.collection, []) : seedCollection(trips, timezone),
279
+ keepsakeTrips: mergeKeptTrips(raw.keepsakeTrips, trips),
280
+ tripSeq: nextTripSeq,
281
+ wishes: normalizeWishes(raw.wishes),
194
282
  };
195
283
  }
196
284
 
@@ -243,6 +331,7 @@ export function enterVenue(state, venue, nowMs, random = Math.random, company =
243
331
  photos: [],
244
332
  ate: [],
245
333
  events: [],
334
+ choices: [],
246
335
  };
247
336
  state.session = session;
248
337
  return { session, already: false };
@@ -267,7 +356,7 @@ export function wanderOnce(state, venue, nowMs, random = Math.random, areas = nu
267
356
  if (!pool.length) return null;
268
357
  const i = Math.floor(random() * pool.length) % pool.length;
269
358
  const area = pool[i];
270
- const evSource = Array.isArray(events) && events.length ? events : (venue.randomEvents || []);
359
+ const evSource = Array.isArray(events) ? events : (venue.randomEvents || []);
271
360
  const evPool = evSource.filter((e) => !s.events.includes(e));
272
361
  const ev = evPool.length
273
362
  ? evPool[Math.floor(random() * evPool.length) % evPool.length]
@@ -350,7 +439,10 @@ export function closeSession(state, nowMs, note = '', day = '') {
350
439
  const s = state.session;
351
440
  if (!s) return null;
352
441
  const said = text(note, 120);
442
+ state.tripSeq = (Number(state.tripSeq) || 0) + 1;
353
443
  const trip = {
444
+ id: `${newTripId(s.placeId, s.enteredAt, nowMs)}-${state.tripSeq}`,
445
+ favorite: false,
354
446
  placeId: s.placeId,
355
447
  placeName: s.placeName,
356
448
  scene: s.scene,
@@ -362,19 +454,37 @@ export function closeSession(state, nowMs, note = '', day = '') {
362
454
  // 收摊这句话以前只出现在回执里,转头就没了:纪念册重看这一趟只剩「逛了哪儿」。
363
455
  // 「今天人很多,但很开心」这种话才是她自己的记录,必须存。
364
456
  note: said,
457
+ favorite: false,
365
458
  visited: s.visited.map((v) => ({ ...v })),
366
459
  souvenirs: [...s.souvenirs],
367
460
  photos: [...s.photos],
368
461
  ate: (s.ate ?? []).map((x) => ({ ...x })),
369
462
  events: [...s.events],
463
+ choices: normalizeChoices(s.choices),
370
464
  };
371
465
  state.session = null;
372
466
  state.trips.unshift(trip);
467
+ 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
+ const savedTrip = state.keepsakeTrips?.find((x) => x.id === trip.id);
469
+ if (savedTrip) state.keepsakeTrips = state.keepsakeTrips.map((x) => x.id === trip.id ? structuredClone(trip) : x);
373
470
  if (state.trips.length > MAX_TRIPS) state.trips.length = MAX_TRIPS;
374
471
  const stayedMin = Math.max(0, Math.round((nowMs - s.enteredAt) / 60000));
375
472
  return { trip, stayedMin, note: said };
376
473
  }
377
474
 
475
+ export function favoriteTrip(state, id, keep = true) {
476
+ const trips = [...(state.trips ?? []), ...(state.keepsakeTrips ?? [])];
477
+ const trip = trips.find((t) => t.id === id);
478
+ if (!trip) return { ok: false, error: '找不到这趟行程,请先翻纪念册取得行程 ID。' };
479
+ state.keepsakeTrips = (state.keepsakeTrips ?? []).filter((t) => t.id !== id);
480
+ trip.favorite = keep;
481
+ if (keep) state.keepsakeTrips.unshift(structuredClone(trip));
482
+ state.keepsakeTrips.sort((a, b) => b.leftAt - a.leftAt);
483
+ const recent = state.trips?.find((t) => t.id === id);
484
+ if (recent) recent.favorite = keep;
485
+ return { ok: true, trip, kept: keep };
486
+ }
487
+
378
488
  /** 这一趟挂太久了没?超过 ttlMin 就该提醒收摊(但绝不替她收)。 */
379
489
  export function isStale(session, nowMs, ttlMin) {
380
490
  if (!session) return false;
package/src/venues.js CHANGED
@@ -1125,10 +1125,9 @@ function rankPlaces(nowMin, avoid = [], places = VENUES) {
1125
1125
  const stateRank = state === 'open' ? 0 : (state === 'closingSoon' ? 1 : 2);
1126
1126
  const avoidRank = avoidSet.has(venue.id) ? 1 : 0;
1127
1127
  const crowdRank = venue.crowd === 'packed' ? 2 : (venue.crowd === 'normal' ? 1 : 0);
1128
- // 用户自己加的地方排最前:那是他特意写的,不该被「拥挤度」算法挤到
1129
- // 默认列表后面,否则看起来像没加上。开着/关着仍然在它之后生效。
1128
+ // 营业状态优先;同一状态下,自填地点优先、最近去过的降权,再比较拥挤度。
1130
1129
  const customRank = String(venue.id).startsWith('user-') ? 0 : 1;
1131
- return { venue, state, rank: [customRank, avoidRank, stateRank, crowdRank, idx] };
1130
+ return { venue, state, rank: [stateRank, customRank, avoidRank, crowdRank, idx] };
1132
1131
  });
1133
1132
  scored.sort((a, b) => {
1134
1133
  for (let i = 0; i < a.rank.length; i += 1) {
package/src/wishes.js ADDED
@@ -0,0 +1,114 @@
1
+ const TYPES = new Set(['visit', 'area', 'phase', 'souvenir']);
2
+ const STATUSES = new Set(['active', 'paused', 'completed', 'cancelled']);
3
+ const LIMIT = 100;
4
+
5
+
6
+ function text(value, max = 200) {
7
+ return typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, max) : '';
8
+ }
9
+
10
+ function timestamp(value) {
11
+ try {
12
+ const date = value instanceof Date ? value : new Date(value ?? 0);
13
+ return Number.isNaN(date.getTime()) ? new Date(0).toISOString() : date.toISOString();
14
+ } catch {
15
+ return new Date(0).toISOString();
16
+ }
17
+ }
18
+
19
+ function uniqueId(now, used = new Set()) {
20
+ const stamp = new Date(timestamp(now)).getTime();
21
+ let id;
22
+ let sequence = 0;
23
+ do {
24
+ sequence += 1;
25
+ id = `wish-${Number.isFinite(stamp) ? stamp : 0}-${sequence}`;
26
+ } while (used.has(id));
27
+ return id;
28
+ }
29
+
30
+ function cleanWish(raw, used) {
31
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
32
+ const placeId = text(raw.placeId, 80);
33
+ const placeName = text(raw.placeName, 80);
34
+ const type = text(raw.type, 20);
35
+ const target = text(raw.target, 120);
36
+ if (!placeId || !placeName || !TYPES.has(type) || (type !== 'visit' && !target)) return null;
37
+ const status = STATUSES.has(raw.status) ? raw.status : 'active';
38
+ const createdAt = timestamp(raw.createdAt);
39
+ const updatedAt = timestamp(raw.updatedAt ?? raw.createdAt);
40
+ const id = text(raw.id, 120) || uniqueId(createdAt, used);
41
+ if (used.has(id)) return null;
42
+ used.add(id);
43
+ return {
44
+ id, placeId, placeName, type, target,
45
+ reason: text(raw.reason, 120), status, createdAt, updatedAt,
46
+ completedAt: status === 'completed' ? timestamp(raw.completedAt ?? updatedAt) : '',
47
+ };
48
+ }
49
+
50
+ export function normalizeWishes(raw) {
51
+ if (!Array.isArray(raw)) return [];
52
+ const result = [];
53
+ const used = new Set();
54
+ for (const item of raw) {
55
+ const wish = cleanWish(item, used);
56
+ if (wish) result.push(wish);
57
+ if (result.length >= LIMIT) break;
58
+ }
59
+ return result;
60
+ }
61
+
62
+ export function addWish(list, input, now = 0) {
63
+ const wishes = normalizeWishes(list);
64
+ const candidate = cleanWish({ ...input, id: '', status: 'active', completedAt: '', createdAt: now, updatedAt: now }, new Set(wishes.map((w) => w.id)));
65
+ if (!candidate) return { wishes, wish: null, duplicate: false, error: '心愿信息无效' };
66
+ const duplicate = wishes.find((w) => w.placeId === candidate.placeId && w.type === candidate.type && w.target === candidate.target && ['active', 'paused'].includes(w.status));
67
+ if (duplicate) return { wishes, wish: duplicate, duplicate: true };
68
+ if (wishes.length >= LIMIT) return { wishes, wish: null, duplicate: false, error: '心愿最多保存 100 条' };
69
+ const wish = { ...candidate, id: uniqueId(now, new Set(wishes.map((w) => w.id))) };
70
+ return { wishes: [...wishes, wish], wish, duplicate: false };
71
+ }
72
+
73
+ export function changeWish(list, id, action, now = 0) {
74
+ const wishes = normalizeWishes(list);
75
+ const index = wishes.findIndex((w) => w.id === id);
76
+ if (index < 0) return { wishes, wish: null, error: '找不到这个心愿' };
77
+ const current = wishes[index];
78
+ let status = current.status;
79
+ if (action === 'pause' && status === 'active') status = 'paused';
80
+ else if (action === 'resume' && status === 'paused') status = 'active';
81
+ else if (action === 'cancel' && ['active', 'paused'].includes(status)) status = 'cancelled';
82
+ else if (!['pause', 'resume', 'cancel'].includes(action)) return { wishes, wish: current, error: '不支持的操作' };
83
+ if (status === current.status) return { wishes, wish: current };
84
+ const wish = { ...current, status, updatedAt: timestamp(now) };
85
+ const next = [...wishes];
86
+ next[index] = wish;
87
+ return { wishes: next, wish };
88
+ }
89
+
90
+ export function fulfillWishes(list, facts, now = 0) {
91
+ const wishes = normalizeWishes(list);
92
+ const placeId = text(facts?.placeId, 80);
93
+ const area = text(facts?.area, 120);
94
+ const phase = text(facts?.phase, 120);
95
+ const souvenirs = Array.isArray(facts?.souvenirs) ? facts.souvenirs.map((x) => text(x, 120)).filter(Boolean) : [];
96
+ const completed = [];
97
+ const next = wishes.map((w) => {
98
+ if (w.status !== 'active' || w.placeId !== placeId) return w;
99
+ const matched = w.type === 'visit' || (w.type === 'area' && area === w.target) || (w.type === 'phase' && phase === w.target) || (w.type === 'souvenir' && souvenirs.includes(w.target));
100
+ if (!matched) return w;
101
+ const done = { ...w, status: 'completed', updatedAt: timestamp(now), completedAt: timestamp(now) };
102
+ completed.push(done);
103
+ return done;
104
+ });
105
+ return { wishes: next, completed };
106
+ }
107
+
108
+ export function wishReason(list, venue, nowMin) {
109
+ void nowMin;
110
+ const placeId = typeof venue === 'string' ? venue : venue?.placeId ?? venue?.id;
111
+ const wish = normalizeWishes(list).find((w) => w.status === 'active' && w.placeId === placeId);
112
+ if (!wish) return '';
113
+ return wish.reason || `还想在${wish.placeName}完成「${wish.target}」这个心愿。`;
114
+ }