Repository navigation
Expand file tree
/
Copy pathstorage.js
More file actions
7179 lines (6367 loc) · 260 KB
/
Copy pathstorage.js
File metadata and controls
7179 lines (6367 loc) · 260 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
import path from 'path';
// The VFX contract. Imported HERE rather than reimplemented: the export
// bundle carries the compiled IR, and a second compiler in the backend is
// exactly the divergence vfx/ exists as a root directory to prevent. See
// vfx/index.js for the three build registrations that keep this resolvable
// in a packaged app and in Docker.
import { normalizeVfxDoc } from './vfx/doc.js';
import { normalizeBuildingDoc } from './building/doc.js';
import { compileBuilding } from './building/compile.js';
import { BUILDING_BUNDLE_FORMAT, bundleReferencePlan } from './building/bundle.js';
import { VFX_BUNDLE_FORMAT } from './vfx/bundle.js';
import { compileVfxGraph } from './vfx/compile.js';
import {
buildEngineMapping,
collectUsedEngineIds,
unsupportedFor,
} from './vfx/engineMapping.js';
import process from 'process';
import fs from 'fs/promises';
// The SQL engine lives behind db/index.js: SQLite for a desktop install,
// PostgreSQL when GENSTUDIO_DATABASE_URL is set for a shared server. Every
// query below is written once and runs on both -- see db/postgres.js for the
// three translations that make that true.
import {
openDatabase,
closeDatabase,
run,
get,
all,
exec,
tableExists,
columnExists,
withTransaction,
withKeyLock,
isUniqueViolation,
selectedDialect
} from './db/index.js';
// Re-exported so server.js can report which engine is in use without importing
// the db layer itself: storage.js stays the single door onto the database.
export { selectedDialect };
export const DATA_DIR = path.join(process.cwd(), 'data');
export const DB_FILE = path.join(DATA_DIR, 'app.db');
export const ASSETS_DIR = path.join(DATA_DIR, 'assets');
export const IMAGE_ASSETS_DIR = path.join(ASSETS_DIR, 'images');
export const MESH_ASSETS_DIR = path.join(ASSETS_DIR, 'meshes');
export const THUMBNAIL_ASSETS_DIR = path.join(ASSETS_DIR, 'thumbnails');
export const WORKFLOW_ASSETS_DIR = path.join(ASSETS_DIR, 'workflows');
export const BRUSH_ASSETS_DIR = path.join(ASSETS_DIR, 'brushes');
// Tree Generator parameter sets. The stored file is the TreeSpec JSON itself:
// ~2KB that regenerates the mesh exactly, so the spec IS the asset and the GLB
// is a separate, derived one.
export const TREE_ASSETS_DIR = path.join(ASSETS_DIR, 'trees');
export const PAINT_DOCS_DIR = path.join(ASSETS_DIR, 'paintdocs');
export const WIKI_ASSETS_DIR = path.join(ASSETS_DIR, 'wiki');
// Generated motion clips (Kimodo), as BVH text. Not under a project — see the
// Motions table for why.
export const MOTION_ASSETS_DIR = path.join(ASSETS_DIR, 'motions');
// Hand-edited animation clips saved from the mesh editor's animation dock, as
// JSON (a bone hierarchy + one clip). Not under a project — see the
// CustomAnimations table for why.
export const ANIMATION_ASSETS_DIR = path.join(ASSETS_DIR, 'animations');
// VFX graph documents. The stored file is the graph JSON itself: a few tens of
// kB that references image and mesh assets by id rather than embedding them, so
// the graph IS the asset. Held as a FILE and not in the metadata column because
// metadata is MERGED rather than replaced (see replaceAssetFileById below) - a
// document kept there could never lose a key, so deleting a block and saving
// would bring the block back.
export const VFX_ASSETS_DIR = path.join(ASSETS_DIR, 'vfx');
// Procedural building documents. Same "the spec IS the asset" reasoning as
// VFX_ASSETS_DIR above, and held as a FILE for the same reason: metadata is
// merged rather than replaced, so a document kept in the column could never
// lose a key - deleting a node and saving would bring the node back.
export const BUILDING_ASSETS_DIR = path.join(ASSETS_DIR, 'buildings');
// Bumped when a change would make an existing importer plugin MISREAD a
// bundle. A plugin declares the range it supports and must refuse anything
// outside it rather than half-importing - the same contract VFX_IR_FORMAT
// states for the IR inside.
//
// DEFINED IN vfx/bundle.js, re-exported here. The writer of a bundle is this
// file and the reader is that one, and a number stated twice is a number that
// eventually disagrees with itself.
export { VFX_BUNDLE_FORMAT };
const DATA_ASSETS_PREFIX = 'data/assets/';
const KANBAN_COLUMNS = [
{ id: 1, name: 'Images', position: 0 },
{ id: 2, name: 'Image Edit', position: 1 },
{ id: 3, name: 'Mesh Gen', position: 2 },
{ id: 4, name: 'Mesh Edit', position: 3 },
{ id: 5, name: 'Texturing', position: 4 },
{ id: 6, name: 'Rigging', position: 5 }
];
const ASSET_TYPES = [
{ id: 1, name: 'Image' },
{ id: 2, name: 'Mesh' },
{ id: 3, name: 'Workflow' },
{ id: 4, name: 'Brush' },
// Tree Generator parameter sets. The stored file is the spec JSON, not a mesh.
{ id: 5, name: 'Tree' },
// VFX graphs. Stored as 'Vfx', NOT 'VFX': normalizeAssetTypeName title-cases
// every lookup, and getAssetTypeIdByName compares against a plain
// (case-sensitive) column - so seeding 'VFX' would make every call throw
// "Unknown asset type: vfx". This is never user-visible: mapAssetRow
// lower-cases the wire type to 'vfx', and the label the user reads lives in
// ASSET_SECTIONS in src/pages/AssetsPage.jsx, which says "VFX".
{ id: 6, name: 'Vfx' },
// Procedural building documents. Like a Tree preset and a Vfx graph, the
// stored file is the SPEC (footprint + node graph + style binding), not the
// mesh it generates - a few tens of kB that regenerates its geometry
// deterministically from a seed. Title-cased for the same reason as 'Vfx'.
{ id: 7, name: 'Building' }
];
const ATTRIBUTE_TYPES = [
{ id: 1, name: 'Text' },
{ id: 2, name: 'Number' }
];
const NODE_TYPES = [
{ id: 1, name: 'Image' },
{ id: 3, name: 'Mesh' },
{ id: 4, name: 'Number' },
{ id: 5, name: 'Text' },
{ id: 6, name: 'Boolean' },
{ id: 7, name: 'Image Compare' },
{ id: 8, name: 'Rig Mesh' },
{ id: 9, name: 'Flatten to Albedo' }
];
export const DEFAULT_SETTINGS = {
profile: {
name: 'User',
avatar: null
},
initialSetupComplete: false,
apis: {
google: {
apiKey: '',
imageGeneration: {
headerName: 'x-goog-api-key',
payloadTemplate: {
contents: [
{
parts: [
{ text: '{prompt}' }
]
}
],
generationConfig: {
responseModalities: ['Image']
}
},
models: {
nanobana: {
name: 'Nanobanana',
url: 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent'
},
nanobana_pro: {
name: 'Nanobanana Pro',
url: 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:generateContent'
},
nanobana_2: {
name: 'Nanobanana 2',
url: 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent'
}
}
}
},
openai: {
apiKey: '',
imageGeneration: {
url: 'https://api.openai.com/v1/images/generations',
headers: {
Authorization: 'Bearer {apiKey}'
},
payloadTemplate: {
model: 'gpt-image-1.5',
prompt: '{prompt}',
n: 1,
size: '1024x1024'
},
models: {
openai_gpt_image_1: {
name: 'gpt-image-1',
model: 'gpt-image-1'
},
openai_gpt_image_1_5: {
name: 'gpt-image-1.5',
model: 'gpt-image-1.5'
},
openai_gpt_image_2: {
name: 'gpt-image-2',
model: 'gpt-image-2'
}
},
responseMapping: {
imageBase64Field: 'data[0].b64_json',
createdField: 'created',
usageField: 'usage'
}
},
imageEdit: {
url: 'https://api.openai.com/v1/images/edits',
headers: {
Authorization: 'Bearer {apiKey}'
},
payloadTemplate: {
model: 'gpt-image-1.5',
prompt: '{prompt}',
size: '1024x1024'
},
models: {
openai_gpt_image_1: {
name: 'gpt-image-1',
model: 'gpt-image-1'
},
openai_gpt_image_1_5: {
name: 'gpt-image-1.5',
model: 'gpt-image-1.5'
},
openai_gpt_image_2: {
name: 'gpt-image-2',
model: 'gpt-image-2'
}
},
responseMapping: {
imageBase64Field: 'data[0].b64_json',
createdField: 'created',
usageField: 'usage'
}
}
},
tencentcloud: {
secretId: '',
secretKey: '',
meshGeneration: {
models: {
meshgeneration: {
name: 'Hunyuan3D Pro',
model: 'meshgeneration'
}
}
}
},
tripoai: {
apiKey: '',
meshGeneration: {
models: {
meshgeneration: {
name: 'Tripo AI',
model: 'meshgeneration'
}
}
}
},
hitem3d: {
accessKey: '',
secretKey: '',
accessToken: ''
},
comfyui: {
path: '',
// Optional override for where models live, when it's not "{path}/models"
// (e.g. models are shared across ComfyUI installs via extra_model_paths.yaml).
modelsPath: '',
url: 'http://127.0.0.1',
port: '8188',
// Desktop app: true when this ComfyUI was installed BY the app (into the
// per-user data dir) and is therefore ours to start, stop and upgrade.
// False/absent means the user runs their own — the app only talks to it.
managed: false,
// Desktop app: start the managed ComfyUI at launch. Default off — it is a
// heavy process and most sessions start on demand instead.
autoStart: false
},
meshtools: {
url: 'http://127.0.0.1',
port: '8200',
// Desktop app: start this service automatically at launch (default off —
// services otherwise start on demand or from Settings).
autoStart: true,
// Desktop app: bind 0.0.0.0 instead of loopback so another computer (a
// frontend on a machine without a GPU) can use this one's service. Same
// flag on rigtools/motiontools/mocaptools. No auth on these services.
allowNetwork: false
},
rigtools: {
url: 'http://127.0.0.1',
port: '8300',
// Desktop app: start the rigging service at launch. Default off — it pins
// ~14GB of GPU memory for the whole session.
autoStart: false,
allowNetwork: false
},
motiontools: {
url: 'http://127.0.0.1',
port: '8400',
// Where the motion service keeps the weights it downloads: the 1.1 GB
// Kimodo checkpoint and the ~16 GB Llama-3 text-encoder base. Empty means
// the default folder inside the app's data dir (desktop) or
// thirdparty/kimodo/checkpoints (running from source). Set it to move 17 GB
// onto a drive that has room for it.
modelsPath: '',
// Desktop app: start the motion service at launch. Default off — the text
// encoder alone is ~16 GB of RAM once a prompt has been encoded.
autoStart: false,
allowNetwork: false
},
mocaptools: {
url: 'http://127.0.0.1',
port: '8401',
// Where the video-to-motion service keeps its ~460 MB checkpoint. Empty
// means the default folder inside the app's data dir (desktop) or
// thirdparty/mocapanything/MocapAnything/checkpoints (from source).
modelsPath: '',
// Desktop app: start the video-to-motion service at launch. Default off —
// a capture peaks around 10 GB of VRAM, which would sit next to rigging.
autoStart: false,
allowNetwork: false
},
custom: []
},
// MCP automation endpoint (POST /mcp on the backend). With no token set,
// only loopback clients may connect; a token allows remote MCP clients.
mcp: {
enabled: true,
token: ''
}
};
const DEFAULT_CUSTOM_API_TYPE = 'image-generation';
function normalizeCustomApiType(type) {
return ['image-generation', 'image-edit', 'mesh-generation', 'mesh-edit'].includes(type)
? type
: DEFAULT_CUSTOM_API_TYPE;
}
function normalizeSettingsValue(settings = DEFAULT_SETTINGS) {
return {
...settings,
apis: {
...settings?.apis,
custom: (settings?.apis?.custom || []).map(api => ({
...api,
type: normalizeCustomApiType(api?.type)
}))
}
};
}
function mapGraphNodeRow(row) {
const metadata = parseJson(row.metadata, {});
const filename = row.assetFilePath ? toAssetUrlPath(row.assetFilePath) : null;
const thumbnail = row.assetThumbnail ? toAssetUrlPath(row.assetThumbnail) : null;
const assetMetadata = parseJson(row.assetMetadata, {});
return {
id: row.id,
projectId: row.projectId,
nodeTypeId: row.nodeTypeId,
nodeTypeName: row.nodeTypeName || '',
name: row.name || '',
xPos: row.xPos ?? 0,
yPos: row.yPos ?? 0,
status: row.status || null,
progress: row.progress ?? null,
metadata,
assetId: row.assetId ?? null,
asset: row.assetId ? {
id: row.assetId,
name: row.assetName || '',
filePath: row.assetFilePath,
filename,
width: row.assetWidth ?? 0,
height: row.assetHeight ?? 0,
thumbnailPath: row.assetThumbnail || null,
thumbnail,
type: String(row.assetTypeName || '').toLowerCase(),
parentId: row.assetParentId ?? null,
metadata: assetMetadata,
createdAt: row.assetCreationDate ?? null
} : null,
createdAt: row.creationDate
};
}
function mapGraphConnectionRow(row) {
return {
sourceNodeId: row.sourceNodeId,
targetNodeId: row.targetNodeId,
inputId: row.inputId || 'image-input',
outputId: row.outputId || 'image-output'
};
}
let dbPromise;
function parseJson(value, fallback) {
if (!value) return fallback;
try {
return JSON.parse(value);
} catch {
return fallback;
}
}
function isPlainObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function mergeWithDefaults(defaultValue, currentValue) {
if (!isPlainObject(defaultValue) || !isPlainObject(currentValue)) {
return currentValue === undefined ? defaultValue : currentValue;
}
const merged = { ...defaultValue };
for (const [key, value] of Object.entries(currentValue)) {
merged[key] = key in defaultValue
? mergeWithDefaults(defaultValue[key], value)
: value;
}
return merged;
}
// Normalises a viewer id into "filter, or don't".
//
// Callers pass null for the two cases that see everything: a desktop install
// (no accounts exist) and an administrator. Everyone else gets their own rows
// plus the unowned ones. Keeping the decision here means a listing cannot
// accidentally forget the NULL case and hide legacy data.
export function ownerScope(viewerId) {
const id = Number(viewerId);
return Number.isFinite(id) && id > 0 ? id : null;
}
// SQL fragment + params for scoping a query, so the filter is written once.
function ownerFilter(viewerId, column) {
const id = ownerScope(viewerId);
return id === null
? { clause: '', params: [] }
: { clause: ` AND (${column} IS NULL OR ${column} = ?)`, params: [id] };
}
function mapProjectRow(row) {
return {
id: row.id,
name: row.name,
description: row.description || '',
preset: row.preset || '',
createdAt: row.creationDate,
status: row.status || 'active',
graphViewport: parseJson(row.graphViewport, null),
ownerId: row.ownerId ?? null,
// Joined in so the Projects page can label a card without a second request
// per project. Null for unowned projects and on desktop installs.
ownerName: row.ownerName || null
};
}
function mapChildAssetRow(row) {
const metadata = parseJson(row.metadata, {});
const thumbnail = row.thumbnail ? toAssetUrlPath(row.thumbnail) : null;
return {
id: row.id,
parentId: row.parentId ?? null,
parentProjectId: row.parentProjectId ?? null,
projectIds: Array.isArray(row.projectIds) ? row.projectIds : [],
tags: Array.isArray(row.tags) ? row.tags : [],
editId: metadata?.editId || null,
name: row.name || '',
filePath: row.filePath,
filename: toAssetUrlPath(row.filePath),
width: row.width ?? 0,
height: row.height ?? 0,
thumbnailPath: row.thumbnail || null,
thumbnail,
metadata,
createdAt: row.creationDate,
isEdit: true
};
}
function mapTaskRow(row) {
return {
id: row.id,
projectId: row.projectId,
name: row.name || `Task_${row.id}`,
progress: row.progress ?? 0,
status: row.status || 'processing',
metadata: parseJson(row.metadata, {}),
createdAt: row.creationDate
};
}
function mapProjectCardRow(row) {
const metadata = parseJson(row.metadata, {});
const processing = isPlainObject(metadata?.processing) ? metadata.processing : null;
return {
id: row.clientKey || String(row.id),
cardDbId: row.id,
projectId: row.projectId,
name: row.name || '',
kanbanColumnId: row.kanbanColumnId ?? null,
kanbanColumnName: row.kanbanColumnName || null,
position: row.position ?? 0,
status: row.status || null,
progress: row.progress ?? null,
metadata,
processing,
createdAt: row.creationDate
};
}
function mapAssetRow(row) {
const metadata = parseJson(row.metadata, {});
const cardMetadata = parseJson(row.cardMetadata, {});
const filename = toAssetUrlPath(row.filePath);
const thumbnail = row.thumbnail ? toAssetUrlPath(row.thumbnail) : null;
// Only surface a Kanban card id here. A graph asset is linked to a node-card
// (kanbanColumnId IS NULL); exposing that id as metadata.cardId would make the
// processing-snapshot machinery target the node-card, which has no column and
// must not be renamed/repurposed. Graph assets keep their own stored cardId.
if (row.cardId && row.kanbanColumnId != null) {
metadata.cardId = row.clientKey || String(row.cardId);
}
return {
id: row.id,
projectId: row.projectId ?? null,
// Every project this asset is linked to (Assets_Projects is many-to-many);
// `projectId` above is just the one this view was resolved for.
projectIds: Array.isArray(row.projectIds)
? row.projectIds
: (row.projectId != null ? [row.projectId] : []),
parentId: row.parentId ?? null,
type: String(row.assetTypeName || '').toLowerCase(),
name: row.name,
filePath: row.filePath,
filename,
width: row.width ?? 0,
height: row.height ?? 0,
thumbnailPath: row.thumbnail || null,
thumbnail,
cardDbId: row.cardId ?? null,
cardKey: row.cardId ? (row.clientKey || String(row.cardId)) : null,
cardName: row.cardName || '',
kanbanColumnId: row.kanbanColumnId ?? null,
kanbanColumnName: row.kanbanColumnName || null,
cardPosition: row.cardPosition ?? null,
assetPosition: row.assetPosition ?? null,
cardStatus: row.cardStatus || null,
cardProgress: row.cardProgress ?? null,
cardMetadata,
processing: isPlainObject(cardMetadata?.processing) ? cardMetadata.processing : null,
metadata,
createdAt: row.creationDate
};
}
function mapCardAttributeRow(row) {
return {
cardDbId: row.cardId,
cardId: row.clientKey || String(row.cardId),
position: row.position,
attributeTypeId: row.attributeTypeId,
attributeTypeName: row.attributeTypeName,
attributeValue: row.attributeValue ?? ''
};
}
function normalizeAssetTypeName(name) {
return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
}
async function migrateLegacyAssetEditsToAssets(db) {
if (!(await tableExists(db, 'Assets_Edits'))) {
return;
}
const legacyEditRows = await all(
db,
`SELECT ae.assetId AS sourceAssetId,
ae.editId,
ae.name,
ae.filePath,
ae.width,
ae.height,
ae.creationDate,
source.assetTypeId
FROM Assets_Edits ae
JOIN Assets source ON source.id = ae.assetId`
);
for (const legacyEditRow of legacyEditRows) {
const existingChildAsset = await get(
db,
`SELECT id
FROM Assets
WHERE filePath = ? AND parentId IS NOT NULL
LIMIT 1`,
[legacyEditRow.filePath]
);
if (existingChildAsset) {
continue;
}
await run(
db,
`INSERT INTO Assets (name, filePath, assetTypeId, creationDate, metadata, thumbnail, width, height, parentId)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
String(legacyEditRow.name || '').trim() || `Edit ${legacyEditRow.editId}`,
legacyEditRow.filePath,
legacyEditRow.assetTypeId,
legacyEditRow.creationDate,
JSON.stringify({
editId: legacyEditRow.editId,
migratedFrom: 'Assets_Edits'
}),
null,
Number(legacyEditRow.width) || 0,
Number(legacyEditRow.height) || 0,
legacyEditRow.sourceAssetId
]
);
}
}
// One-time backfill for databases created before Assets_Projects existed:
// project membership used to be derived as Assets -> Cards_Assets -> Cards.projectId,
// and child assets (image edits / mesh versions) had no link of their own — they
// inherited their root's project implicitly. Reproduce both here so nothing that
// was visible in a project before the upgrade disappears after it.
async function backfillAssetProjectLinks(db) {
await run(
db,
`INSERT INTO Assets_Projects (assetId, projectId, addedAt)
SELECT DISTINCT ca.assetId, c.projectId, COALESCE(a.creationDate, 0)
FROM Cards_Assets ca
JOIN Cards c ON c.id = ca.cardId
JOIN Assets a ON a.id = ca.assetId
WHERE c.projectId IS NOT NULL
ON CONFLICT DO NOTHING`
);
// Propagate every link down the full parentId tree, so edits/versions land in
// the same project(s) their root was in. Done level by level rather than with a
// recursive CTE: the seed set is the very table being inserted into, and
// reading a table while writing it is exactly the case a plain loop makes safe.
let inserted = 0;
let guard = 0;
do {
const result = await run(
db,
`INSERT INTO Assets_Projects (assetId, projectId, addedAt)
SELECT child.id, ap.projectId, COALESCE(child.creationDate, 0)
FROM Assets child
JOIN Assets_Projects ap ON ap.assetId = child.parentId
WHERE child.parentId IS NOT NULL
ON CONFLICT DO NOTHING`
);
inserted = result?.changes ?? 0;
guard += 1;
} while (inserted > 0 && guard < 100);
const linked = await get(db, 'SELECT COUNT(*) AS total FROM Assets_Projects');
console.log(`Assets_Projects backfill complete: ${linked?.total ?? 0} asset/project links.`);
// The "board-assets" container cards existed only to carry Cards_Assets rows
// for assets that must belong to a project without appearing on the Kanban
// board. Their links have just been copied into Assets_Projects, so the cards
// themselves are now dead weight — drop them (Cards_Assets cascades).
const removed = await run(
db,
`DELETE FROM Cards
WHERE clientKey = 'board-assets'
AND kanbanColumnId IS NULL
AND nodeTypeId IS NULL`
);
if (removed?.changes) {
console.log(`Removed ${removed.changes} legacy detached container card(s).`);
}
}
// --- Asset <-> project membership -------------------------------------------
// Every write that makes an asset part of a project funnels through these, so
// Assets_Projects can never drift from what the rest of the code believes.
async function linkAssetToProject(db, assetId, projectId, { cascadeChildren = false } = {}) {
const normalizedAssetId = Number(assetId);
const normalizedProjectId = Number(projectId);
if (!Number.isFinite(normalizedAssetId) || !Number.isFinite(normalizedProjectId)) {
return;
}
await run(
db,
'INSERT INTO Assets_Projects (assetId, projectId, addedAt) VALUES (?, ?, ?) ON CONFLICT DO NOTHING',
[normalizedAssetId, normalizedProjectId, Date.now()]
);
if (!cascadeChildren) return;
const children = await all(db, 'SELECT id FROM Assets WHERE parentId = ?', [normalizedAssetId]);
for (const child of children) {
await linkAssetToProject(db, child.id, normalizedProjectId, { cascadeChildren: true });
}
}
async function unlinkAssetFromProject(db, assetId, projectId, { cascadeChildren = true } = {}) {
const normalizedAssetId = Number(assetId);
const normalizedProjectId = Number(projectId);
if (!Number.isFinite(normalizedAssetId) || !Number.isFinite(normalizedProjectId)) {
return;
}
await run(
db,
'DELETE FROM Assets_Projects WHERE assetId = ? AND projectId = ?',
[normalizedAssetId, normalizedProjectId]
);
if (!cascadeChildren) return;
const children = await all(db, 'SELECT id FROM Assets WHERE parentId = ?', [normalizedAssetId]);
for (const child of children) {
await unlinkAssetFromProject(db, child.id, normalizedProjectId, { cascadeChildren: true });
}
}
// Copy every project a source asset belongs to onto a freshly created child, so
// a new edit/version is immediately part of the same project(s) as its parent.
async function inheritProjectLinks(db, fromAssetId, toAssetId) {
await run(
db,
`INSERT INTO Assets_Projects (assetId, projectId, addedAt)
SELECT ?, projectId, ? FROM Assets_Projects WHERE assetId = ?
ON CONFLICT DO NOTHING`,
[Number(toAssetId), Date.now(), Number(fromAssetId)]
);
}
export async function listAssetProjectIds(assetId) {
const db = await getDb();
const rows = await all(
db,
'SELECT projectId FROM Assets_Projects WHERE assetId = ? ORDER BY projectId ASC',
[Number(assetId)]
);
return rows.map(row => row.projectId);
}
// Batch variant used by the listings: assetId -> [projectId, …].
async function listProjectIdsByAssetIds(db, assetIds = []) {
const uniqueIds = [...new Set(assetIds.map(Number).filter(Number.isFinite))];
const byAssetId = new Map();
if (uniqueIds.length === 0) {
return byAssetId;
}
const rows = await all(
db,
`SELECT assetId, projectId FROM Assets_Projects
WHERE assetId IN (${uniqueIds.map(() => '?').join(', ')})
ORDER BY projectId ASC`,
uniqueIds
);
for (const row of rows) {
if (!byAssetId.has(row.assetId)) {
byAssetId.set(row.assetId, []);
}
byAssetId.get(row.assetId).push(row.projectId);
}
return byAssetId;
}
export async function isAssetInProject(projectId, assetId) {
const db = await getDb();
const row = await get(
db,
'SELECT 1 FROM Assets_Projects WHERE assetId = ? AND projectId = ? LIMIT 1',
[Number(assetId), Number(projectId)]
);
return Boolean(row);
}
// Attach an EXISTING asset (root, edit or version) to a project without going
// through a card. This is the operation the old model could not express.
export async function linkExistingAssetToProject(projectId, assetId, { cascadeChildren = false } = {}) {
const normalizedProjectId = await ensureProjectExists(projectId);
const asset = await getAssetRecordById(assetId);
if (!asset) {
throw new Error('Asset not found');
}
const db = await getDb();
await linkAssetToProject(db, asset.id, normalizedProjectId, { cascadeChildren });
return await getAssetViewById(asset.id, { projectId: normalizedProjectId });
}
export async function unlinkAssetFromProjectById(projectId, assetId, { cascadeChildren = true } = {}) {
const normalizedProjectId = Number(projectId);
const asset = await getAssetRecordById(assetId);
if (!asset) {
return { status: 'not-found' };
}
const db = await getDb();
await unlinkAssetFromProject(db, asset.id, normalizedProjectId, { cascadeChildren });
// Placement follows membership: an asset that is no longer part of the project
// must not stay on one of its cards/nodes either.
const links = await all(
db,
`SELECT ca.cardId
FROM Cards_Assets ca JOIN Cards c ON c.id = ca.cardId
WHERE ca.assetId = ? AND c.projectId = ?`,
[asset.id, normalizedProjectId]
);
if (links.length > 0) {
await run(
db,
`DELETE FROM Cards_Assets
WHERE assetId = ? AND cardId IN (${links.map(() => '?').join(', ')})`,
[asset.id, ...links.map(link => link.cardId)]
);
for (const link of links) {
await normalizeCardAssetPositions(db, link.cardId);
}
await deleteCardsIfEmpty(db, links.map(link => link.cardId));
}
return { status: 'unlinked', remainingProjectIds: await listAssetProjectIds(asset.id) };
}
// ---------------------------------------------------------------------------
// Asset tags (Assets_Tags)
// ---------------------------------------------------------------------------
// Longest tag we store. Long enough for "hand painted stylized", short enough
// that a tag stays a label and never becomes a description.
const MAX_TAG_LENGTH = 48;
// Per-asset ceiling, so a runaway caller cannot bury an asset under hundreds of
// tags and make the library filter useless.
const MAX_TAGS_PER_ASSET = 50;
// Tags are compared and stored in one canonical form: trimmed, inner whitespace
// collapsed, lower-cased. Without this "Sci-Fi", "sci-fi " and "sci fi" would
// all be distinct primary keys and the tag list would fill with near-duplicates.
export function normalizeTagValue(value) {
const text = String(value ?? '')
.replace(/\s+/g, ' ')
.trim()
.toLowerCase();
return text.slice(0, MAX_TAG_LENGTH).trim();
}
// Normalize a whole list, dropping empties and duplicates while preserving the
// order the caller gave (first occurrence wins), then cap it.
export function normalizeTagList(values = []) {
const seen = new Set();
const tags = [];
for (const value of Array.isArray(values) ? values : [values]) {
const tag = normalizeTagValue(value);
if (!tag || seen.has(tag)) continue;
seen.add(tag);
tags.push(tag);
if (tags.length >= MAX_TAGS_PER_ASSET) break;
}
return tags;
}
// Batch variant used by the listings: assetId -> [tag, …].
async function listTagsByAssetIds(db, assetIds = []) {
const uniqueIds = [...new Set(assetIds.map(Number).filter(Number.isFinite))];
const byAssetId = new Map();
if (uniqueIds.length === 0) {
return byAssetId;
}
const rows = await all(
db,
`SELECT assetId, tag FROM Assets_Tags
WHERE assetId IN (${uniqueIds.map(() => '?').join(', ')})
ORDER BY tag ASC`,
uniqueIds
);
for (const row of rows) {
if (!byAssetId.has(row.assetId)) {
byAssetId.set(row.assetId, []);
}
byAssetId.get(row.assetId).push(row.tag);
}
return byAssetId;
}
export async function listAssetTags(assetId) {
const db = await getDb();
const rows = await all(
db,
'SELECT tag FROM Assets_Tags WHERE assetId = ? ORDER BY tag ASC',
[Number(assetId)]
);
return rows.map(row => row.tag);
}
// Replace an asset's whole tag set. The UI edits tags as a list, so a single
// "here is the new set" call keeps add/remove/reorder from needing three routes.
export async function setAssetTags(assetId, tags = []) {
const asset = await getAssetRecordById(assetId);
if (!asset) {
return { status: 'not-found' };
}
const db = await getDb();
const normalized = normalizeTagList(tags);
const addedAt = Date.now();
await run(db, 'DELETE FROM Assets_Tags WHERE assetId = ?', [asset.id]);
for (const tag of normalized) {
await run(
db,
'INSERT INTO Assets_Tags (assetId, tag, addedAt) VALUES (?, ?, ?) ON CONFLICT DO NOTHING',
[asset.id, tag, addedAt]
);
}
return { status: 'ok', assetId: asset.id, tags: normalized };
}
// Add without disturbing what is already there (used by importers/automation
// that only know the tags they want to contribute).
export async function addAssetTags(assetId, tags = []) {
const asset = await getAssetRecordById(assetId);
if (!asset) {
return { status: 'not-found' };
}
const db = await getDb();
const addedAt = Date.now();
for (const tag of normalizeTagList(tags)) {
await run(
db,
'INSERT INTO Assets_Tags (assetId, tag, addedAt) VALUES (?, ?, ?) ON CONFLICT DO NOTHING',
[asset.id, tag, addedAt]
);
}
return { status: 'ok', assetId: asset.id, tags: await listAssetTags(asset.id) };
}
export async function removeAssetTag(assetId, tag) {
const db = await getDb();
await run(
db,
'DELETE FROM Assets_Tags WHERE assetId = ? AND tag = ?',
[Number(assetId), normalizeTagValue(tag)]
);
return { status: 'ok', tags: await listAssetTags(assetId) };
}
// The whole known vocabulary with usage counts, for the filter dropdown and the
// tag-input suggestions. Optionally scoped to one asset type so the Images
// section never suggests a tag that only meshes use.