Repository navigation
Expand file tree
/
Copy pathdbCore.ts
More file actions
2672 lines (2527 loc) · 94.8 KB
/
Copy pathdbCore.ts
File metadata and controls
2672 lines (2527 loc) · 94.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// The single implementation of the app's data operations, keyed by API channel.
// Both shells consume it:
// - Electron main (src/main/ipc.js) — persists to the JSON file on disk
// - browser-local backend (src/renderer/src/api/backends/local.ts) — IndexedDB
// A future HTTP/Supabase backend replaces this wholesale on the server side;
// until then this file IS the server, so desktop and web behave identically.
//
// Handlers mutate the raw DB object in place and return plain data (or throw).
// The shell wraps the result in the { success, data | error } envelope and
// persists after any channel listed in WRITE_CHANNELS.
//
// Channels NOT here (platform-specific, each shell provides its own):
// images:openDialog — native file dialog vs <input type="file">
// images:bytes — fs read vs fetch of a data: URL
import type {
AuthCtx,
CharacterDoc,
MapDoc,
DB,
EntityTag,
Env,
Era,
StoryEvent,
FieldDef,
ImageRecord,
Person,
Project,
ProjectOverview,
PublicUser,
Relationship,
RelationshipTypeDef,
Scene,
SceneLayout,
SceneTag,
Session,
SlotName,
Tag,
UsageInfo,
User
} from './types'
import {
CREATABLE_FIELD_TYPES,
adoptLegacyPersonData,
defsForProject,
ensureProjectFields,
isSingleSlot,
recomputeSnapshots,
removeValue,
sanitizeConfig,
slotAccepts,
upsertValue,
valuesForPerson
} from './fields'
export { migrateFieldSystem } from './fields'
import {
clampWeight,
coerceSymmetryRole,
ensureProjectRelTypes,
relTypeByKey,
relTypesForProject
} from './relTypes'
export { migrateRelationshipTypes } from './relTypes'
import { applyMapPatch } from './maps'
import { sanitizeModel3D } from './character3d'
import { applyEraPatch, applyEventPatch } from './chronicle'
import { UNDOABLE_CHANNELS, historyHandlers, withHistory } from './history'
export { UNDOABLE_CHANNELS } from './history'
import {
SESSION_DAYS,
addDays,
clearFailedLogins,
generateSessionToken,
hashPassword,
isLockedOut,
limitsFor,
pruneSessions,
recordFailedLogin,
validatePassword,
validateUsername,
verifyPassword
} from './auth'
/** The pre-overhaul faction shape — consumed only by migrateFactionsToTags. */
interface LegacyFaction {
id: string
project_id: string
scenario_id: string | null
name: string
color?: string
icon?: string
member_ids?: string[]
x?: number
y?: number
visible?: boolean
created_at: string
}
import { yearDate } from './calendarMath'
import { SHARE_ACCESS_LEVELS } from './types'
import {
BILLING_WRITE_CHANNELS,
EMPTY_BILLING,
billingHandlers,
settleSubscription
} from './billing'
function sortByDate<T extends { created_at: string }>(arr: T[]): T[] {
return arr.slice().sort((a, b) => (a.created_at > b.created_at ? 1 : -1))
}
/** Coerce a form value to a finite number, or null (empty / garbage input). */
function numOrNull(v: unknown): number | null {
if (v == null || v === '') return null
const n = Number(v)
return Number.isFinite(n) ? n : null
}
/** Filter a table down to rows belonging to the active project. */
function forProject<T extends { project_id: string }>(db: DB, table: Record<string, T>): T[] {
return Object.values(table).filter((item) => item.project_id === db.activeProjectId)
}
function primaryImageOf(db: DB, personId: string): string | null {
const primary = Object.values(db.images).find(
(img) => img.person_id === personId && img.is_primary
)
return primary ? primary.file_path : null
}
export const EMPTY_DB = (): DB => ({
users: {},
sessions: {},
projects: {},
activeProjectId: null,
persons: {},
field_defs: {},
field_values: {},
relationships: {},
rel_type_defs: {},
tags: {},
entity_tags: {},
scenes: {},
scene_tags: {},
images: {},
characters: {},
maps: {},
eras: {},
events: {},
settings: {},
globalSettings: {},
billing: EMPTY_BILLING()
})
/** Delete every entity_tags row touching the given tag or entity. */
function cascadeEntityTags(db: DB, { tagId, entityId }: { tagId?: string; entityId?: string }) {
for (const [id, row] of Object.entries(db.entity_tags)) {
if ((tagId && row.tag_id === tagId) || (entityId && row.entity_id === entityId)) {
delete db.entity_tags[id]
}
}
}
/** Delete every scene_tags placement touching the given scene or tag. */
function cascadeSceneTags(db: DB, { sceneId, tagId }: { sceneId?: string; tagId?: string }) {
for (const [id, row] of Object.entries(db.scene_tags)) {
if ((sceneId && row.scene_id === sceneId) || (tagId && row.tag_id === tagId)) {
delete db.scene_tags[id]
}
}
}
export function nowStr(): string {
return new Date().toISOString().replace('T', ' ').slice(0, 19)
}
// ── Migration: tree → project vocabulary ─────────────────────────────────────
// The container used to be called a "tree" (`trees`, `activeTreeId`, `tree_id`).
// Rename in place so old files keep loading. Idempotent — files already in the
// new format pass through untouched. Returns true when anything changed so the
// caller knows to persist. Both shells run this on load (db.js / local.ts).
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function migrateTreesToProjects(db: any): boolean {
let changed = false
if (db.trees) {
db.projects = { ...db.trees, ...(db.projects || {}) }
delete db.trees
changed = true
}
if ('activeTreeId' in db) {
db.activeProjectId = db.activeProjectId ?? db.activeTreeId
delete db.activeTreeId
changed = true
}
for (const table of ['persons', 'relationships', 'factions', 'scenarios', 'images']) {
for (const row of Object.values(db[table] || {})) {
const r = row as { tree_id?: string; project_id?: string }
if ('tree_id' in r) {
r.project_id = r.project_id ?? r.tree_id
delete r.tree_id
changed = true
}
}
}
return changed
}
// ── Migration: bare year numbers → DateValue ─────────────────────────────────
// Dates used to be stored as plain year numbers (`birth_year`, `death_year`,
// `formed_date`). Wrap them as year-precision Gregorian DateValues in place
// (null stays null). Idempotent — already-migrated rows pass through untouched.
// Returns true when anything changed. Both shells run this on load.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function migrateYearsToDateValues(db: any): boolean {
let changed = false
const move = (row: Record<string, unknown>, oldKey: string, newKey: string): void => {
if (!(newKey in row)) {
row[newKey] = yearDate(row[oldKey] as number | string | null)
changed = true
}
if (oldKey in row) {
delete row[oldKey]
changed = true
}
}
for (const p of Object.values(db.persons || {})) {
move(p as Record<string, unknown>, 'birth_year', 'birth')
move(p as Record<string, unknown>, 'death_year', 'death')
}
for (const r of Object.values(db.relationships || {})) {
move(r as Record<string, unknown>, 'formed_date', 'formed')
}
return changed
}
// ── Migration: scenarios → groups scenes ─────────────────────────────────────
// The Factions view's "scenarios" became per-view Scenes. Convert each
// scenario 1:1 into a `view:'groups'` scene KEEPING ITS ID, so factions'
// `scenario_id` (and the saved activeScenarioId setting) still resolve without
// rewriting them. Idempotent; returns true when anything changed.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function migrateScenariosToScenes(db: any): boolean {
let changed = false
db.scenes = db.scenes || {}
for (const row of Object.values(db.scenarios || {})) {
const s = row as {
id: string
project_id: string
created_at: string
updated_at: string
name?: string
}
if (!db.scenes[s.id]) {
const scene: Scene = {
id: s.id,
project_id: s.project_id,
view: 'groups',
name: s.name || 'Scenario',
type: null,
config: {},
positions: {},
created_at: s.created_at,
updated_at: s.updated_at
}
db.scenes[s.id] = scene
}
changed = true
}
if ('scenarios' in db) {
delete db.scenarios
changed = true
}
return changed
}
// ── Migration: factions → tags + entity_tags + scene_tags ────────────────────
// A faction mashed two jobs together: WHO belongs (member_ids, copied per
// scenario) and WHERE it sits (x/y/visible per scenario). Split them:
// - same-named factions across scenes collapse into ONE Tag per project
// (name key is trimmed + case-insensitive; colour/icon come from the
// first occurrence, oldest first)
// - member_ids become entity_tags rows (one per distinct person↔tag pair)
// - each faction becomes one scene_tags placement in the groups scene
// migrated from its scenario (same id), copying x/y/visible
// The legacy factions collection is removed once converted.
// Idempotent: reruns find the tag by label and skip existing rows; once the
// factions key is gone the whole migration is a no-op.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function migrateFactionsToTags(db: any, env: Env): boolean {
if (!('factions' in db)) return false
const factions = (Object.values(db.factions || {}) as LegacyFaction[])
.slice()
.sort((a, b) => (a.created_at > b.created_at ? 1 : a.created_at < b.created_at ? -1 : 0))
db.tags = db.tags || {}
db.entity_tags = db.entity_tags || {}
db.scene_tags = db.scene_tags || {}
// project id + normalized name → tag id (pre-seeded with existing tags so
// reruns and user-created tags dedupe against the same key space)
const nameKey = (projectId: string, label: string) =>
`${projectId}~${(label || '').trim().toLowerCase()}`
const tagByName = new Map<string, string>()
for (const t of Object.values(db.tags) as Tag[]) {
const key = nameKey(t.project_id, t.label)
if (!tagByName.has(key)) tagByName.set(key, t.id)
}
const hasJoin = (entityId: string, tagId: string) =>
(Object.values(db.entity_tags) as EntityTag[]).some(
(row) => row.entity_id === entityId && row.tag_id === tagId
)
const hasPlacement = (sceneId: string, tagId: string) =>
(Object.values(db.scene_tags) as SceneTag[]).some(
(row) => row.scene_id === sceneId && row.tag_id === tagId
)
for (const f of factions) {
const key = nameKey(f.project_id, f.name)
let tagId = tagByName.get(key)
if (!tagId) {
tagId = env.uuid()
const now = env.nowStr()
const tag: Tag = {
id: tagId,
project_id: f.project_id,
label: (f.name || '').trim() || 'Unnamed',
type: '',
source: 'manual',
color: f.color || '#6c8ef5',
icon: f.icon || '',
created_at: now,
updated_at: now
}
db.tags[tagId] = tag
tagByName.set(key, tagId)
}
for (const pid of f.member_ids || []) {
if (!db.persons[pid] || hasJoin(pid, tagId)) continue
const id = env.uuid()
db.entity_tags[id] = { id, entity_id: pid, tag_id: tagId, created_at: env.nowStr() }
}
if (f.scenario_id && db.scenes[f.scenario_id] && !hasPlacement(f.scenario_id, tagId)) {
const id = env.uuid()
const now = env.nowStr()
db.scene_tags[id] = {
id,
scene_id: f.scenario_id,
tag_id: tagId,
x: f.x ?? 0,
y: f.y ?? 0,
visible: f.visible !== false,
created_at: now,
updated_at: now
}
}
}
// Everything is converted — retire the legacy collection for good
delete db.factions
return true
}
// ── Migration: the serialized graphState setting → graph scenes ──────────────
// The Tree view used to keep its whole arrangement in one per-project setting:
// four mode buckets (custom/auto/age/generation), each holding named "states"
// with position snapshots. Flatten it: every saved state becomes ONE
// view:'graph' scene whose `type` is its former mode, carrying that state's
// node positions and any generation-row config in scene.config. The
// previously-active mode+state becomes the active graph scene (saved under the
// activeSceneId:graph setting) and the current-year override moves to its own
// userCurrentYear setting. Idempotent: a project that already has graph scenes
// is skipped. Scenes are the source of truth now, so the old graphState value
// is retired after conversion.
const MODE_TO_TYPE: Record<string, string> = {
custom: 'free',
auto: 'organic',
age: 'birth',
generation: 'generations'
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function migrateGraphStateToScenes(db: any, env: Env): boolean {
let changed = false
db.scenes = db.scenes || {}
db.settings = db.settings || {}
for (const pid of Object.keys(db.projects || {})) {
const stateKey = `${pid}:graphState`
const retireBlob = () => {
if (stateKey in db.settings) {
delete db.settings[stateKey]
changed = true
}
}
const hasGraphScenes = (Object.values(db.scenes) as Scene[]).some(
(s) => s.project_id === pid && s.view === 'graph'
)
if (hasGraphScenes) {
retireBlob() // already migrated (or born on the new model) — drop leftovers
continue
}
const raw = db.settings[stateKey]
if (typeof raw !== 'string') continue
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let state: any
try {
state = JSON.parse(raw)
} catch {
retireBlob() // unreadable — nothing to convert
continue
}
if (!state || typeof state !== 'object') {
retireBlob()
continue
}
// The old graphState kept a snapshot PER MODE for each saved "state" index
// — i.e. state i already meant one arrangement that had a layout in every
// mode. Group by that index so each becomes ONE scene holding all layout
// types (the unified model), instead of one scene per (mode × index).
const modes = ['custom', 'auto', 'age', 'generation']
const stateCount = modes.reduce(
(max, mode) =>
Math.max(
max,
(state.modeStateNames?.[mode] || []).length,
(state.modeStateSnapshots?.[mode] || []).length
),
0
)
const activeType = MODE_TO_TYPE[state.currentMode as string] || 'organic'
const now = env.nowStr()
let activeSceneId: string | null = null
for (let i = 0; i < stateCount; i++) {
const layouts: Record<
string,
{ positions: Record<string, { x: number; y: number }>; config: Record<string, unknown> }
> = {}
let sceneName = ''
for (const mode of modes) {
const snaps: unknown[] = state.modeStateSnapshots?.[mode] || []
const names: string[] = state.modeStateNames?.[mode] || []
if (names[i] && !sceneName) sceneName = names[i]
if (i >= snaps.length) continue
const snap = (snaps[i] || {}) as Record<string, { x?: number; y?: number } | unknown>
const positions: Record<string, { x: number; y: number }> = {}
for (const [key, v] of Object.entries(snap)) {
if (key.startsWith('_')) continue
const p = v as { x?: number; y?: number }
if (p && typeof p.x === 'number' && typeof p.y === 'number') {
positions[key] = { x: p.x, y: p.y }
}
}
const config: Record<string, unknown> = {}
const rows = (snap as { _genRowYValues?: number[] })._genRowYValues
const spacing = (snap as { _genRowSpacing?: number })._genRowSpacing
if (rows) config.genRowYValues = rows
if (spacing) config.genRowSpacing = spacing
else if (mode === 'generation' && state.genRowSpacing) {
config.genRowSpacing = state.genRowSpacing
}
const emphasis = state.modeEmphasis?.[mode]
if (emphasis && emphasis !== 'neutral') config.emphasis = emphasis
layouts[MODE_TO_TYPE[mode]] = { positions, config }
}
const id = env.uuid()
const active = layouts[activeType] ||
Object.values(layouts)[0] || { positions: {}, config: {} }
const scene: Scene = {
id,
project_id: pid,
view: 'graph',
name: sceneName || `Scene ${i + 1}`,
type: activeType,
config: JSON.parse(JSON.stringify(active.config)),
positions: JSON.parse(JSON.stringify(active.positions)),
layouts,
created_at: now,
updated_at: now
}
db.scenes[id] = scene
// The formerly-active state index (of the active mode) stays active.
const activeIdx = state.modeActiveStateIdx?.[state.currentMode as string] ?? 0
if (i === activeIdx) activeSceneId = id
changed = true
}
if (activeSceneId) {
db.settings[`${pid}:activeSceneId:graph`] = activeSceneId
changed = true
}
if (state.userCurrentYear != null && db.settings[`${pid}:userCurrentYear`] === undefined) {
db.settings[`${pid}:userCurrentYear`] = state.userCurrentYear
changed = true
}
retireBlob()
}
return changed
}
// Graph scenes gained a per-type `layouts` map (one scene holds Free/Organic/
// Birth/Generations/Space at once). Any graph scene still on the flat model
// gets its current type's arrangement folded into layouts[type]. Idempotent:
// scenes that already have `layouts` are left untouched.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function migrateSceneLayouts(db: any): boolean {
let changed = false
db.scenes = db.scenes || {}
for (const scene of Object.values(db.scenes) as Scene[]) {
if (scene.view !== 'graph' || scene.layouts) continue
const type = scene.type || 'organic'
scene.layouts = {
[type]: {
positions: JSON.parse(JSON.stringify(scene.positions || {})),
config: JSON.parse(JSON.stringify(scene.config || {}))
}
}
changed = true
}
return changed
}
// ── Sample family seeded on first run (shared so desktop and web start identical) ──
export function seedSampleData(db: DB, projectId: string, env: Env): void {
const now = env.nowStr()
const gp1 = env.uuid(),
gp2 = env.uuid()
const p1 = env.uuid(),
p2 = env.uuid()
const c1 = env.uuid(),
c2 = env.uuid()
const addP = (
id: string,
name: string,
birthYear: number,
gender: string,
bio: string,
occupation: string,
location: string
) => {
db.persons[id] = {
id,
project_id: projectId,
name,
birth: yearDate(birthYear),
death: null,
gender,
bio,
occupation,
location,
created_at: now,
updated_at: now
}
}
const addR = (a: string, b: string, type: string) => {
const id = env.uuid()
db.relationships[id] = {
id,
project_id: projectId,
person_a_id: a,
person_b_id: b,
type,
status: 'active',
formed: null,
created_at: now
}
}
addP(
gp1,
'Robert Anderson',
1948,
'male',
'Retired civil engineer who loved woodworking and jazz.',
'Civil Engineer',
'Chicago, IL'
)
addP(
gp2,
'Dorothy Anderson',
1950,
'female',
'Retired school teacher with a passion for gardening.',
'Teacher',
'Chicago, IL'
)
addP(
p1,
'James Anderson',
1975,
'male',
'Architect running his own firm in New York.',
'Architect',
'New York, NY'
)
addP(
p2,
'Sarah Anderson',
1977,
'female',
'Pediatrician at Brooklyn General Hospital.',
'Pediatrician',
'New York, NY'
)
addP(
c1,
'Lucas Anderson',
2005,
'male',
'High school student and basketball enthusiast.',
'Student',
'New York, NY'
)
addP(
c2,
'Olivia Anderson',
2008,
'female',
'Middle school student who loves reading and art.',
'Student',
'New York, NY'
)
addR(gp1, gp2, 'spouse')
addR(gp1, p1, 'parent_child')
addR(gp2, p1, 'parent_child')
addR(p1, p2, 'spouse')
addR(p1, c1, 'parent_child')
addR(p1, c2, 'parent_child')
addR(p2, c1, 'parent_child')
addR(p2, c2, 'parent_child')
// Stand the project up on the trait system: default locked defs (name/
// gender/birth/death slots + occupation/location/bio) and the sample
// persons' columns adopted as trait values.
ensureProjectFields(db, projectId, env)
// …and on the relationship-type registry (built-in defs).
ensureProjectRelTypes(db, projectId, env)
}
/** Fresh, seeded database for a first run (used by the browser-local backend). */
export function createInitialDB(env: Env): DB {
const db = EMPTY_DB()
const projectId = env.uuid()
const now = env.nowStr()
db.projects[projectId] = {
id: projectId,
name: 'Unnamed Project',
created_at: now,
updated_at: now
}
db.activeProjectId = projectId
seedSampleData(db, projectId, env)
return db
}
// ── Auth helpers ──────────────────────────────────────────────────────────────
function publicUser(u: User): PublicUser {
return {
id: u.id,
username: u.username,
plan: u.plan,
display_name: u.display_name ?? null,
bio: u.bio ?? null,
avatar_hue: u.avatar_hue ?? null,
created_at: u.created_at
}
}
/** All projects the user owns. Handlers scope everything else through the
* active project, so project ownership is the enforcement point. */
function projectsOf(db: DB, userId: string): Project[] {
return Object.values(db.projects).filter((p) => p.user_id === userId)
}
function usageOf(db: DB, user: User): UsageInfo {
const owned = new Set(projectsOf(db, user.id).map((p) => p.id))
const limits = limitsFor(user)
return {
projects: owned.size,
maxProjects: limits.maxProjects,
persons: Object.values(db.persons).filter((p) => owned.has(p.project_id)).length,
maxPersons: limits.maxPersons,
images: Object.values(db.images).filter((img) => owned.has(img.project_id)).length,
maxImages: limits.maxImages
}
}
/** Point activeProjectId at a project the user owns, creating (and seeding)
* one when they own none — every signed-in user always has a project. */
function ensureActiveProjectFor(db: DB, user: User, env: Env): void {
const active = db.activeProjectId ? db.projects[db.activeProjectId] : null
if (active && active.user_id === user.id) return
let target = projectsOf(db, user.id)[0]
if (!target) {
const id = env.uuid()
const now = env.nowStr()
target = { id, name: 'Unnamed Project', user_id: user.id, created_at: now, updated_at: now }
db.projects[id] = target
seedSampleData(db, id, env)
}
db.activeProjectId = target.id
}
function startSession(db: DB, user: User, env: Env): Session {
const now = env.nowStr()
const session: Session = {
token: generateSessionToken(),
user_id: user.id,
created_at: now,
expires_at: addDays(now, SESSION_DAYS)
}
db.sessions[session.token] = session
return session
}
// ── Channel handlers ─────────────────────────────────────────────────────────
/** One person-payload entry point for both the legacy column contract
* (name/birth/death/gender/bio/occupation/location keys → system defs) and
* the trait contract (`values: [{ field_id, value, timeframe?,
* display_in_graph? }]` + `removals: [fieldId]`), then refresh the person's
* derived snapshot columns. */
function applyPersonPayload(db: DB, env: Env, person: Person, data: Record<string, unknown>): void {
adoptLegacyPersonData(db, env, person, data)
if (Array.isArray(data.values)) {
for (const v of data.values as Array<Record<string, unknown>>) {
const fieldId = String(v.field_id ?? v.fieldId ?? '')
if (!db.field_defs[fieldId]) continue
upsertValue(db, env, person.id, fieldId, v)
}
}
if (Array.isArray(data.removals)) {
for (const fieldId of data.removals as string[]) removeValue(db, person.id, fieldId)
}
recomputeSnapshots(db, [person.id])
}
/** Throw when adding `count` people would pass the signed-in user's plan cap. */
function assertPersonQuota(db: DB, ctx: AuthCtx | undefined, count: number): void {
if (!ctx?.user) return
const usage = usageOf(db, ctx.user)
if (usage.persons + count > usage.maxPersons) {
throw new Error(`Free plan limit reached: ${usage.maxPersons} people`)
}
}
/** Insert a person in the active project from a create payload (legacy
* columns and/or a `values` array), trait values applied. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createPersonRow(db: DB, env: Env, data: Record<string, any>): Person {
const id = env.uuid()
const now = env.nowStr()
const person: Person = {
id,
project_id: db.activeProjectId as string,
name: data.name || '',
birth: data.birth ?? null,
death: data.death ?? null,
gender: data.gender || 'unknown',
bio: data.bio || '',
occupation: data.occupation || '',
location: data.location || '',
created_at: now,
updated_at: now
}
db.persons[id] = person
applyPersonPayload(db, env, person, data)
return person
}
/** Remove one person and everything hanging off them: relationships, trait
* values, images (files via env), character looks and tag memberships. */
function deletePersonCascade(db: DB, env: Env, id: string): void {
for (const [rid, rel] of Object.entries(db.relationships)) {
if (rel.person_a_id === id || rel.person_b_id === id) delete db.relationships[rid]
}
for (const [vid, v] of Object.entries(db.field_values)) {
if (v.person_id === id) delete db.field_values[vid]
}
for (const [iid, img] of Object.entries(db.images)) {
if (img.person_id === id) {
env.removeImageFile(img.file_path)
delete db.images[iid]
}
}
for (const [cid, c] of Object.entries(db.characters || {})) {
if (c.person_id === id) delete db.characters[cid]
}
// Story events outlive a participant — they just lose them from the cast.
for (const ev of Object.values(db.events || {})) {
if (ev.person_ids.includes(id)) ev.person_ids = ev.person_ids.filter((p) => p !== id)
}
cascadeEntityTags(db, { entityId: id })
delete db.persons[id]
}
/** A fresh, empty story event (the sanitizer fills it in). */
function blankEvent(id: string, projectId: string, now: string): StoryEvent {
return {
id,
project_id: projectId,
title: 'Untitled event',
kind: 'milestone',
icon: '',
color: '',
date: null,
end: null,
importance: 2,
person_ids: [],
place: '',
description: '',
created_at: now,
updated_at: now
}
}
/** Create or patch one era in the active project (sanitized). */
function upsertEra(db: DB, data: Record<string, unknown>, env: Env): Era {
db.eras = db.eras || {}
const now = env.nowStr()
const pid = db.activeProjectId as string
const existing = data.id ? db.eras[String(data.id)] : null
if (existing) {
if (existing.project_id !== pid) throw new Error('Era not found')
applyEraPatch(existing, data)
existing.updated_at = now
return existing
}
const id = env.uuid()
const era: Era = {
id,
project_id: pid,
name: 'Untitled era',
start: null,
end: null,
color: '#6c8ef5',
icon: '',
description: '',
created_at: now,
updated_at: now
}
applyEraPatch(era, { name: '', ...data })
db.eras[id] = era
return era
}
/** Ids of every person in the active project (snapshot-recompute targets). */
function projectPersonIds(db: DB): string[] {
return Object.values(db.persons)
.filter((p) => p.project_id === db.activeProjectId)
.map((p) => p.id)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Handler = (db: DB, data: any, env: Env, ctx?: AuthCtx) => unknown
// ── Project copy / file export / import ─────────────────────────────────────
// One remapping engine behind projects:duplicate, projects:import (a project
// file from projects:export) and anything else that needs a fresh-id copy:
// people (+ trait defs/values), relationships (+ the type registry,
// remapping custom-type keys), tags & memberships, scenes (+ placements,
// with position/style keys remapped onto the new person ids), characters,
// maps and project-scoped settings. Photos are NOT copied — image files belong
// to the source, and deleting a copy must never remove the original's files.
function copyProjectInto(
src: DB,
srcId: string,
dst: DB,
env: Env,
overrides: Partial<Project>
): Project {
const srcProject = src.projects[srcId]
const now = env.nowStr()
const pid = env.uuid()
const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v))
const project: Project = {
...clone(srcProject),
...overrides,
id: pid,
created_at: now,
updated_at: now
}
dst.projects[pid] = project
const personIds = new Map<string, string>()
for (const p of Object.values(src.persons)) {
if (p.project_id !== srcId) continue
const id = env.uuid()
personIds.set(p.id, id)
dst.persons[id] = { ...clone(p), id, project_id: pid }
}
const defIds = new Map<string, string>()
for (const def of Object.values(src.field_defs)) {
if (def.project_id !== srcId) continue
const id = env.uuid()
defIds.set(def.id, id)
dst.field_defs[id] = { ...clone(def), id, project_id: pid }
}
for (const v of Object.values(src.field_values)) {
const personId = personIds.get(v.person_id)
const fieldId = defIds.get(v.field_id)
if (!personId || !fieldId) continue
const id = env.uuid()
dst.field_values[id] = { ...clone(v), id, person_id: personId, field_id: fieldId }
}
// Custom relationship types use their id as their key, so remap both;
// builtin keys ('spouse', …) stay stable across projects.
const typeKeys = new Map<string, string>()
for (const def of Object.values(src.rel_type_defs || {})) {
if (def.project_id !== srcId) continue
const id = env.uuid()
const key = def.builtin ? def.key : id
typeKeys.set(def.key, key)
dst.rel_type_defs[id] = { ...clone(def), id, key, project_id: pid }
}
const relIds = new Map<string, string>()
for (const r of Object.values(src.relationships)) {
if (r.project_id !== srcId) continue
const a = personIds.get(r.person_a_id)
const b = personIds.get(r.person_b_id)
if (!a || !b) continue
const id = env.uuid()
relIds.set(r.id, id)
dst.relationships[id] = {
...clone(r),
id,
project_id: pid,
person_a_id: a,
person_b_id: b,
type: typeKeys.get(r.type) ?? r.type
}
}
const tagIds = new Map<string, string>()
for (const t of Object.values(src.tags)) {
if (t.project_id !== srcId) continue
const id = env.uuid()
tagIds.set(t.id, id)
dst.tags[id] = { ...clone(t), id, project_id: pid }
}
for (const et of Object.values(src.entity_tags)) {
const entityId = personIds.get(et.entity_id)
const tagId = tagIds.get(et.tag_id)
if (!entityId || !tagId) continue
const id = env.uuid()
dst.entity_tags[id] = { ...clone(et), id, entity_id: entityId, tag_id: tagId }
}
// Position/style records inside scenes are keyed by person id.
const remapKeys = (rec: unknown): unknown => {
if (!rec || typeof rec !== 'object') return rec
const out: Record<string, unknown> = {}
for (const [k, v] of Object.entries(rec as Record<string, unknown>)) {
out[personIds.get(k) ?? k] = v
}
return out
}
const sceneIds = new Map<string, string>()
for (const s of Object.values(src.scenes)) {
if (s.project_id !== srcId) continue
const id = env.uuid()
sceneIds.set(s.id, id)
const scene: Scene = { ...clone(s), id, project_id: pid }
scene.positions = remapKeys(scene.positions) as Scene['positions']
if (scene.layouts) {
// Besides the per-type arrangements, the graph keeps two scene-wide
// maps in the same bag: `styles` (per-node overrides, by person id)
// and `curves` (hand-shaped bezier links, by relationship id — each
// remembering the person it was shaped from as `s`).
const bag = scene.layouts as Record<string, unknown>
if (bag.styles) bag.styles = remapKeys(bag.styles)
if (bag.curves && typeof bag.curves === 'object') {
const curves: Record<string, unknown> = {}
for (const [relId, rec] of Object.entries(bag.curves as Record<string, unknown>)) {
const newRel = relIds.get(relId)
if (!newRel || !rec || typeof rec !== 'object') continue
const c = rec as { s?: string }
curves[newRel] = { ...c, ...(c.s ? { s: personIds.get(c.s) ?? c.s } : {}) }
}
bag.curves = curves
}
for (const [key, layout] of Object.entries(scene.layouts)) {
if (key === 'styles' || key === 'curves') continue
layout.positions = remapKeys(layout.positions) as SceneLayout['positions']
const extra = layout as SceneLayout & { styles?: unknown }
if (extra.styles) extra.styles = remapKeys(extra.styles)
}
}
dst.scenes[id] = scene
}
for (const st of Object.values(src.scene_tags)) {
const sceneId = sceneIds.get(st.scene_id)
const tagId = tagIds.get(st.tag_id)
if (!sceneId || !tagId) continue
const id = env.uuid()
dst.scene_tags[id] = { ...clone(st), id, scene_id: sceneId, tag_id: tagId }
}