-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
2458 lines (2168 loc) · 99.9 KB
/
server.mjs
File metadata and controls
2458 lines (2168 loc) · 99.9 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 express from 'express';
import fs from 'fs/promises'; // Use promises for async/await
import path from 'path';
import { fileURLToPath } from 'url';
import cors from 'cors';
import dotenv from 'dotenv';
import multer from 'multer';
import { spawn } from 'child_process';
import sanitizeFilename from 'sanitize-filename';
import fetch from 'node-fetch';
import { parseMjsExport } from './modules/data/parseMjsExport.mjs';
import { normalizeParserJobs, normalizeParserSkills, normalizeParserCategories } from './modules/data/parsedResumeAdapter.mjs';
import { atomicWriteWithLock, cleanStaleLock } from './modules/utils/atomicFileUtils.mjs';
// Load .env from project root (see docs/REPLICATE-PORTS-CONFIG.md)
dotenv.config({ path: path.join(process.cwd(), '.env') });
const PROJECT_ROOT = process.cwd();
const PALETTE_DIR_PATH = path.resolve(PROJECT_ROOT, 'static_content', 'colorPalettes');
const CSS_FILE_PATH = path.resolve(PROJECT_ROOT, 'static_content', 'css', 'palette-styles.css');
const STATE_FILE_PATH = path.resolve(PROJECT_ROOT, 'app_state.json');
const STATE_EXAMPLE_PATH = path.resolve(PROJECT_ROOT, 'app_state.example.json');
const STATIC_JOBS_PATH = path.resolve(PROJECT_ROOT, 'static_content', 'jobs', 'jobs.mjs');
const STATIC_SKILLS_PATH = path.resolve(PROJECT_ROOT, 'static_content', 'skills', 'skills.mjs');
const STATIC_CATEGORIES_PATH = path.resolve(PROJECT_ROOT, 'static_content', 'categories.mjs');
/** Overridable via process.env.PARSED_RESUMES_DIR for integration tests */
const PARSED_RESUMES_DIR = process.env.PARSED_RESUMES_DIR || path.resolve(PROJECT_ROOT, 'parsed_resumes');
const SYNC_LOGS_DIR = path.resolve(PROJECT_ROOT, 'sync-logs');
const SYNC_LOGS_INDEX_FILE = path.resolve(SYNC_LOGS_DIR, 'index.json');
const EVENT_DATA_DIR = path.resolve(PROJECT_ROOT, 'event-data');
const ANALYSIS_REPORTS_DIR = path.resolve(PROJECT_ROOT, 'analysis-reports');
const app = express();
// --- Middleware ---
// Enable CORS for all origins (adjust for production if needed)
app.use(cors());
// Parse JSON bodies for the state endpoint
app.use(express.json());
// Parse text bodies for the CSS endpoint
app.use(express.text());
/**
* Convert a display name to a slug suitable for use as a folder name.
* Lowercases, collapses non-alphanumeric runs to hyphens, trims leading/trailing hyphens.
*/
function slugifyDisplayName(name) {
return name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
|| 'resume';
}
/**
* Find a unique folder name under PARSED_RESUMES_DIR based on displayName.
* Returns the base slug if available, otherwise appends (1), (2), … until unique.
*/
async function generateUniqueResumeId(displayName) {
const base = slugifyDisplayName(displayName);
try {
await fs.access(path.join(PARSED_RESUMES_DIR, base));
// Base exists — find the next available suffix
let counter = 1;
while (true) {
const candidate = `${base} (${counter})`;
try {
await fs.access(path.join(PARSED_RESUMES_DIR, candidate));
counter++;
} catch {
return candidate;
}
}
} catch {
return base;
}
}
/** Parse resume data file: JSON.parse for .json, parseMjsExport for .mjs. */
function parseResumeFile(content, filePath, varName) {
if (filePath.endsWith('.json')) return JSON.parse(content);
return parseMjsExport(content, varName);
}
/**
* Read jobs, skills, and optional categories from paths and return normalized data
* for API consumption (jobs array, name-keyed skills, categories dict).
* Supports .json (parsed_resumes) and .mjs (static_content) formats.
*/
async function readAndNormalizeResumeData(jobsPath, skillsPath, categoriesPath = null) {
const jobsContent = await fs.readFile(jobsPath, 'utf-8');
const rawJobs = parseResumeFile(jobsContent, jobsPath, 'jobs');
let rawSkills = {};
try {
const skillsContent = await fs.readFile(skillsPath, 'utf-8');
rawSkills = parseResumeFile(skillsContent, skillsPath, 'skills') || {};
} catch (e) {
if (e.code !== 'ENOENT') throw e;
}
let rawCategories = {};
if (categoriesPath) {
try {
const categoriesContent = await fs.readFile(categoriesPath, 'utf-8');
rawCategories = parseResumeFile(categoriesContent, categoriesPath, 'categories') || {};
} catch (e) {
if (e.code !== 'ENOENT') throw e;
}
}
const jobs = normalizeParserJobs(rawJobs);
const skills = normalizeParserSkills(rawSkills);
const categories = normalizeParserCategories(rawCategories);
return { jobs, skills, categories };
}
/** If app_state.json is missing, initialize it from app_state.example.json (safe defaults, no user data). */
async function ensureAppStateFile() {
try {
await fs.access(STATE_FILE_PATH);
} catch (err) {
if (err.code === 'ENOENT') {
try {
const example = await fs.readFile(STATE_EXAMPLE_PATH, 'utf-8');
await fs.writeFile(STATE_FILE_PATH, example, 'utf-8');
console.log('📄 Initialized app_state.json from app_state.example.json');
} catch (e) {
console.error('[server] Could not initialize app_state.json from example:', e.message);
}
}
}
}
// --- API Endpoints ---
// These must be defined *before* the static file server.
// GET /api/state: Read application state from app_state.json (used at startup / hard-refresh)
// If app_state.json is missing, initialize it from app_state.example.json (committed; safe defaults, no user data) then return it.
app.get('/api/state', async (req, res) => {
try {
await ensureAppStateFile();
const stateData = await fs.readFile(STATE_FILE_PATH, 'utf-8');
const parsedState = JSON.parse(stateData);
const sizeKB = (Buffer.byteLength(stateData, 'utf8') / 1024).toFixed(1);
console.log('📖 Loaded app state from disk - size:', sizeKB, 'KB, at:', new Date().toISOString());
res.json(parsedState);
} catch (error) {
if (error.code === 'ENOENT') {
console.log('📖 State file not found and app_state.example.json missing; client will use defaults');
res.status(404).json({ error: 'State file not found.' });
} else {
console.error('Error reading state file:', error);
res.status(500).json({ error: 'Failed to read state file.' });
}
}
});
// POST /api/state: Write application state to app_state.json (whenever a persistent attribute is updated)
app.post('/api/state', async (req, res) => {
try {
const stateData = JSON.stringify(req.body, null, 2);
await atomicWriteWithLock(STATE_FILE_PATH, stateData);
const sizeKB = (Buffer.byteLength(stateData, 'utf8') / 1024).toFixed(1);
console.log('💾 Saved app state to disk - size:', sizeKB, 'KB, at:', new Date().toISOString());
res.json({ success: true });
} catch (error) {
console.error('Error writing state file:', error);
res.status(500).json({ error: 'Failed to write state file.' });
}
});
// GET /api/resumes/default/data: Jobs and skills from static_content (default resume)
app.get('/api/resumes/default/data', async (req, res) => {
try {
await fs.access(STATIC_JOBS_PATH);
await fs.access(STATIC_SKILLS_PATH);
const { jobs, skills, categories } = await readAndNormalizeResumeData(STATIC_JOBS_PATH, STATIC_SKILLS_PATH, STATIC_CATEGORIES_PATH);
res.json({ jobs, skills, categories });
} catch (error) {
if (error.code === 'ENOENT') {
res.status(404).json({ error: 'Default resume data not found (static_content/jobs, static_content/skills).' });
} else {
console.error('Error reading default resume data:', error);
res.status(500).json({ error: 'Failed to read default resume data.' });
}
}
});
// GET /api/resumes/:id/data: Jobs and skills for a parsed resume (parsed_resumes/<id>/)
// Flat layout, JSON format: jobs.json, skills.json, categories.json at folder root.
app.get('/api/resumes/:id/data', async (req, res) => {
const { id } = req.params;
if (!id || id === 'default') {
return res.status(400).json({ error: 'Invalid resume id.' });
}
const dir = path.join(PARSED_RESUMES_DIR, id);
try {
const jobsPath = path.join(dir, 'jobs.json');
await fs.access(jobsPath);
const skillsPath = path.join(dir, 'skills.json');
const categoriesPath = path.join(dir, 'categories.json');
const { jobs, skills, categories } = await readAndNormalizeResumeData(jobsPath, skillsPath, categoriesPath);
res.json({ jobs, skills, categories });
} catch (error) {
if (error.code === 'ENOENT') {
res.status(404).json({ error: `Resume "${id}" not found.` });
} else {
console.error('Error reading resume data:', error);
res.status(500).json({ error: 'Failed to read resume data.' });
}
}
});
// PATCH /api/resumes/:id/jobs/:jobIndex/skills: Update skillIDs for one job, sync skills.json jobIDs. Optional newSkills: names to create if missing.
app.patch('/api/resumes/:id/jobs/:jobIndex/skills', async (req, res) => {
const { id, jobIndex } = req.params;
const { skillIDs, newSkills } = req.body;
if (!id || jobIndex == null || !Array.isArray(skillIDs)) {
return res.status(400).json({ error: 'Missing id, jobIndex, or skillIDs array.' });
}
const dir = path.join(PARSED_RESUMES_DIR, id);
const jobsPath = path.join(dir, 'jobs.json');
const skillsPath = path.join(dir, 'skills.json');
try {
const [jobsContent, skillsContent] = await Promise.all([
fs.readFile(jobsPath, 'utf-8'),
fs.readFile(skillsPath, 'utf-8'),
]);
const jobs = parseResumeFile(jobsContent, jobsPath, 'jobs');
const skills = parseResumeFile(skillsContent, skillsPath, 'skills');
const idx = String(jobIndex);
if (!jobs[idx]) return res.status(404).json({ error: `Job index ${jobIndex} not found.` });
// Create any new skills so they exist before sync
const toCreate = Array.isArray(newSkills) ? newSkills : [];
for (const entry of toCreate) {
const name = typeof entry === 'string' ? entry.trim() : (entry?.name && String(entry.name).trim());
if (!name) continue;
if (skills[name] == null) {
skills[name] = { name, jobIDs: [] };
}
}
const oldSkillIDs = jobs[idx].skillIDs || [];
const newSkillIDs = skillIDs;
jobs[idx].skillIDs = newSkillIDs;
// Sync skills.jobIDs: remove jobIndex from removed skills, add to new ones
const jobNum = parseInt(jobIndex, 10);
const removed = oldSkillIDs.filter(s => !newSkillIDs.includes(s));
const added = newSkillIDs.filter(s => !oldSkillIDs.includes(s));
for (const sid of removed) {
if (skills[sid]) skills[sid].jobIDs = (skills[sid].jobIDs || []).filter(j => j !== jobNum);
}
for (const sid of added) {
if (skills[sid] && !skills[sid].jobIDs.includes(jobNum)) skills[sid].jobIDs.push(jobNum);
}
await Promise.all([
atomicWriteWithLock(jobsPath, JSON.stringify(jobs, null, 2)),
atomicWriteWithLock(skillsPath, JSON.stringify(skills, null, 2)),
]);
res.json({ ok: true, skillIDs: newSkillIDs });
} catch (err) {
console.error('[PATCH jobs skills]', err);
res.status(500).json({ error: err.message });
}
});
// Resolve skill key: use direct key if present, else find key where skill.name matches (handles id-keyed skills from parser).
function resolveSkillKey(skills, keyOrName) {
if (skills[keyOrName] != null) return keyOrName;
const want = (keyOrName && String(keyOrName).trim()) || '';
if (!want) return null;
for (const [k, s] of Object.entries(skills)) {
if (s && typeof s === 'object' && s.name != null && String(s.name).trim() === want) return k;
}
return null;
}
// PATCH /api/resumes/:id/skills/rename: Rename a skill (update key and all job references). If newName already exists, merge into it.
app.patch('/api/resumes/:id/skills/rename', async (req, res) => {
const { id } = req.params;
const { oldKey, newName } = req.body;
const newNameTrimmed = newName != null ? String(newName).trim() : '';
if (!id || id === 'default' || !oldKey || !newNameTrimmed) {
return res.status(400).json({ error: 'Missing id, oldKey, or newName.' });
}
if (oldKey === newNameTrimmed) {
return res.json({ ok: true, key: oldKey });
}
const dir = path.join(PARSED_RESUMES_DIR, id);
const jobsPath = path.join(dir, 'jobs.json');
const skillsPath = path.join(dir, 'skills.json');
try {
const [jobsContent, skillsContent] = await Promise.all([
fs.readFile(jobsPath, 'utf-8'),
fs.readFile(skillsPath, 'utf-8'),
]);
const jobs = parseResumeFile(jobsContent, jobsPath, 'jobs');
const skills = parseResumeFile(skillsContent, skillsPath, 'skills');
const resolvedOldKey = resolveSkillKey(skills, oldKey);
if (resolvedOldKey == null) {
return res.status(404).json({ error: `Skill "${oldKey}" not found.` });
}
const jobIDsFromOld = skills[resolvedOldKey].jobIDs || [];
delete skills[resolvedOldKey];
if (skills[newNameTrimmed] != null) {
const existingJobIDs = new Set(skills[newNameTrimmed].jobIDs || []);
jobIDsFromOld.forEach(j => existingJobIDs.add(j));
skills[newNameTrimmed].jobIDs = [...existingJobIDs];
} else {
skills[newNameTrimmed] = { name: newNameTrimmed, jobIDs: [...jobIDsFromOld] };
}
const jobEntries = Array.isArray(jobs) ? jobs.map((j, i) => [i, j]) : Object.entries(jobs);
for (const [, job] of jobEntries) {
const ids = job.skillIDs;
if (!Array.isArray(ids)) continue;
const out = [];
const seen = new Set();
for (const sid of ids) {
const use = (sid === resolvedOldKey || sid === oldKey) ? newNameTrimmed : sid;
if (!seen.has(use)) { out.push(use); seen.add(use); }
}
job.skillIDs = out;
}
await Promise.all([
atomicWriteWithLock(jobsPath, JSON.stringify(jobs, null, 2)),
atomicWriteWithLock(skillsPath, JSON.stringify(skills, null, 2)),
]);
res.json({ ok: true, key: newNameTrimmed });
} catch (err) {
console.error('[PATCH skills/rename]', err);
res.status(500).json({ error: err.message });
}
});
// PATCH /api/resumes/:id/skills/merge: Merge one skill into another (replace fromKey with toKey everywhere, then remove fromKey)
app.patch('/api/resumes/:id/skills/merge', async (req, res) => {
const { id } = req.params;
const { fromKey, toKey } = req.body;
if (!id || id === 'default' || !fromKey || !toKey) {
return res.status(400).json({ error: 'Missing id, fromKey, or toKey.' });
}
if (fromKey === toKey) {
return res.status(400).json({ error: 'fromKey and toKey must be different.' });
}
const dir = path.join(PARSED_RESUMES_DIR, id);
const jobsPath = path.join(dir, 'jobs.json');
const skillsPath = path.join(dir, 'skills.json');
try {
const [jobsContent, skillsContent] = await Promise.all([
fs.readFile(jobsPath, 'utf-8'),
fs.readFile(skillsPath, 'utf-8'),
]);
const jobs = parseResumeFile(jobsContent, jobsPath, 'jobs');
const skills = parseResumeFile(skillsContent, skillsPath, 'skills');
const resolvedFromKey = resolveSkillKey(skills, fromKey);
const resolvedToKey = resolveSkillKey(skills, toKey);
if (resolvedFromKey == null) {
return res.status(404).json({ error: `Skill "${fromKey}" not found.` });
}
if (resolvedToKey == null) {
return res.status(404).json({ error: `Target skill "${toKey}" not found.` });
}
if (resolvedFromKey === resolvedToKey) {
return res.status(400).json({ error: 'fromKey and toKey must be different.' });
}
const fromJobIDs = new Set(skills[resolvedFromKey].jobIDs || []);
const toJobIDsSet = new Set(skills[resolvedToKey].jobIDs || []);
fromJobIDs.forEach(j => toJobIDsSet.add(j));
skills[resolvedToKey].jobIDs = [...toJobIDsSet];
delete skills[resolvedFromKey];
const jobEntries = Array.isArray(jobs) ? jobs.map((j, i) => [i, j]) : Object.entries(jobs);
for (const [, job] of jobEntries) {
const ids = job.skillIDs;
if (!Array.isArray(ids)) continue;
const out = [];
const seen = new Set();
for (const sid of ids) {
if (sid === resolvedFromKey || sid === fromKey) {
if (!seen.has(resolvedToKey)) { out.push(resolvedToKey); seen.add(resolvedToKey); }
} else {
if (!seen.has(sid)) { out.push(sid); seen.add(sid); }
}
}
job.skillIDs = out;
}
await Promise.all([
atomicWriteWithLock(jobsPath, JSON.stringify(jobs, null, 2)),
atomicWriteWithLock(skillsPath, JSON.stringify(skills, null, 2)),
]);
res.json({ ok: true, mergedInto: toKey });
} catch (err) {
console.error('[PATCH skills/merge]', err);
res.status(500).json({ error: err.message });
}
});
// PATCH /api/resumes/:id/jobs/:jobIndex: Update one job's fields (label, role, start, end, Description)
app.patch('/api/resumes/:id/jobs/:jobIndex', async (req, res) => {
const { id, jobIndex } = req.params;
if (!id || id === 'default' || jobIndex == null) {
return res.status(400).json({ error: 'Invalid resume id or job index.' });
}
const allowed = ['label', 'role', 'employer', 'start', 'end', 'Description'];
const updates = {};
for (const key of allowed) {
if (req.body[key] !== undefined) updates[key] = req.body[key];
}
if (Object.keys(updates).length === 0) {
return res.status(400).json({ error: 'No allowed job fields provided.' });
}
const dir = path.join(PARSED_RESUMES_DIR, id);
const jobsPath = path.join(dir, 'jobs.json');
try {
await fs.access(jobsPath);
} catch (e) {
if (e.code === 'ENOENT') return res.status(404).json({ error: 'Resume or jobs.json not found.' });
throw e;
}
const content = await fs.readFile(jobsPath, 'utf-8');
const jobs = parseResumeFile(content, jobsPath, 'jobs');
const idx = Array.isArray(jobs) ? parseInt(jobIndex, 10) : String(jobIndex);
if (jobs[idx] == null) return res.status(404).json({ error: `Job index ${jobIndex} not found.` });
Object.assign(jobs[idx], updates);
await atomicWriteWithLock(jobsPath, JSON.stringify(jobs, null, 2));
res.json({ ok: true, job: jobs[idx] });
});
// GET /api/resumes/:id/meta: Return meta.json for a parsed resume
app.get('/api/resumes/:id/meta', async (req, res) => {
const { id } = req.params;
if (!id || id === 'default') return res.status(400).json({ error: 'Invalid or default resume id.' });
const metaPath = path.join(PARSED_RESUMES_DIR, id, 'meta.json');
try {
const content = await fs.readFile(metaPath, 'utf-8');
res.json(JSON.parse(content));
} catch (e) {
if (e.code === 'ENOENT') return res.status(404).json({ error: 'meta.json not found for this resume.' });
throw e;
}
});
// PATCH /api/resumes/:id/meta: Update displayName, fileName in meta.json
app.patch('/api/resumes/:id/meta', async (req, res) => {
const { id } = req.params;
if (!id || id === 'default') return res.status(400).json({ error: 'Cannot update meta for default resume.' });
const { displayName, fileName } = req.body;
const metaPath = path.join(PARSED_RESUMES_DIR, id, 'meta.json');
try {
let meta = {};
try {
const content = await fs.readFile(metaPath, 'utf-8');
meta = JSON.parse(content);
} catch (e) {
if (e.code === 'ENOENT') return res.status(404).json({ error: 'meta.json not found for this resume.' });
throw e;
}
if (displayName !== undefined) meta.displayName = displayName;
if (fileName !== undefined) meta.fileName = fileName;
await atomicWriteWithLock(metaPath, JSON.stringify(meta, null, 2));
res.json(meta);
} catch (err) {
console.error('[PATCH meta]', err);
res.status(500).json({ error: err.message });
}
});
// GET /api/resumes/:id/other-sections: Return other-sections.json data (contact, title, summary, etc.)
app.get('/api/resumes/:id/other-sections', async (req, res) => {
const { id } = req.params;
if (!id) return res.status(400).json({ error: 'Invalid resume id.' });
const filePath = path.join(PARSED_RESUMES_DIR, id, 'other-sections.json');
try {
const content = await fs.readFile(filePath, 'utf-8');
const data = JSON.parse(content);
res.json(data || {});
} catch {
res.status(404).json({ error: 'other-sections.json not found for this resume.' });
}
});
// PATCH /api/resumes/:id/other-sections: Update or create other-sections.json
app.patch('/api/resumes/:id/other-sections', async (req, res) => {
const { id } = req.params;
if (!id || id === 'default') return res.status(400).json({ error: 'Cannot update other-sections for default resume.' });
const payload = req.body;
if (!payload || typeof payload !== 'object') return res.status(400).json({ error: 'Invalid payload.' });
const dir = path.join(PARSED_RESUMES_DIR, id);
const filePath = path.join(dir, 'other-sections.json');
try {
await fs.mkdir(dir, { recursive: true });
await atomicWriteWithLock(filePath, JSON.stringify(payload, null, 2));
res.json(payload);
} catch (err) {
console.error('[PATCH other-sections]', err);
res.status(500).json({ error: err.message });
}
});
// PATCH /api/resumes/:id/categories: Update or create categories.json
app.patch('/api/resumes/:id/categories', async (req, res) => {
const { id } = req.params;
if (!id || id === 'default') return res.status(400).json({ error: 'Cannot update categories for default resume.' });
const { categories } = req.body;
if (!categories || typeof categories !== 'object') return res.status(400).json({ error: 'Invalid categories payload.' });
const dir = path.join(PARSED_RESUMES_DIR, id);
const filePath = path.join(dir, 'categories.json');
try {
await fs.mkdir(dir, { recursive: true });
await atomicWriteWithLock(filePath, JSON.stringify(categories, null, 2));
res.json({ categories });
} catch (err) {
console.error('[PATCH categories]', err);
res.status(500).json({ error: err.message });
}
});
// GET /api/resumes/:id/html: Serve the pre-rendered resume.html for printing
app.get('/api/resumes/:id/html', async (req, res) => {
const { id } = req.params;
if (!id) return res.status(400).json({ error: 'Invalid resume id.' });
const htmlPath = path.join(PARSED_RESUMES_DIR, id, 'resume.html');
try {
await fs.access(htmlPath);
res.sendFile(htmlPath);
} catch {
res.status(404).json({ error: 'resume.html not found for this resume.' });
}
});
// DELETE /api/resumes/:id: Remove a parsed resume folder entirely
app.delete('/api/resumes/:id', async (req, res) => {
const { id } = req.params;
if (!id || id === 'default') {
return res.status(400).json({ error: 'Cannot delete the default resume.' });
}
const dir = path.join(PARSED_RESUMES_DIR, id);
try {
await fs.rm(dir, { recursive: true, force: true });
console.log(`[DELETE resume] Removed: ${dir}`);
res.json({ ok: true });
} catch (err) {
console.error('[DELETE resume]', err);
res.status(500).json({ error: err.message });
}
});
// GET /api/resumes: List all parsed resumes with metadata
app.get('/api/resumes', async (req, res) => {
try {
const entries = await fs.readdir(PARSED_RESUMES_DIR, { withFileTypes: true });
const resumeFolders = entries.filter(entry => entry.isDirectory());
const resumes = [];
for (const folder of resumeFolders) {
const resumeId = folder.name;
const dir = path.join(PARSED_RESUMES_DIR, resumeId);
try {
// Read meta.json - skip if it doesn't exist (not a valid parsed resume)
let metadata = {};
const metaPath = path.join(dir, 'meta.json');
try {
const metaContent = await fs.readFile(metaPath, 'utf-8');
metadata = JSON.parse(metaContent);
} catch (e) {
// meta.json doesn't exist - skip this folder (not a parsed resume)
continue;
}
// Get jobs and skills data to count items (flat layout, JSON format)
const jobsPath = path.join(dir, 'jobs.json');
const skillsPath = path.join(dir, 'skills.json');
const categoriesPath = path.join(dir, 'categories.json');
const { jobs, skills } = await readAndNormalizeResumeData(jobsPath, skillsPath, categoriesPath);
// Get folder creation time
const stats = await fs.stat(dir);
// Skip hidden resumes (e.g., guide documents that aren't actual resumes)
if (metadata.hidden) {
continue;
}
resumes.push({
id: resumeId,
displayName: metadata.displayName || resumeId,
createdAt: metadata.createdAt || stats.birthtime.toISOString(),
jobCount: jobs.length,
skillCount: Object.keys(skills).length,
metadata
});
} catch (error) {
console.warn(`Failed to read resume ${resumeId}:`, error.message);
}
}
// Sort by creation date (newest first)
resumes.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
res.json(resumes);
} catch (error) {
console.error('Error listing resumes:', error);
res.status(500).json({ error: 'Failed to list resumes.' });
}
});
// Configure multer for file uploads
const upload = multer({
dest: path.join(PROJECT_ROOT, 'uploads'),
fileFilter: (req, file, cb) => {
const isDocx = file.mimetype === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
file.originalname.endsWith('.docx');
const isPdf = file.mimetype === 'application/pdf' || file.originalname.endsWith('.pdf');
if (isDocx || isPdf) {
cb(null, true);
} else {
cb(new Error('Only .docx and .pdf files are allowed'));
}
},
limits: {
fileSize: 10 * 1024 * 1024 // 10MB limit
}
});
// POST /api/resumes/upload: Upload and parse a .docx or .pdf resume (file or URL)
app.post('/api/resumes/upload', upload.single('resume'), async (req, res) => {
try {
let uploadedFile = req.file;
let originalFilename = null;
let fileSize = 0;
let tempFilePath = null;
// Check if URL is provided instead of file
if (!uploadedFile && req.body.resumeUrl) {
const resumeUrl = req.body.resumeUrl;
console.log(`🌐 Fetching resume from URL: ${resumeUrl}`);
try {
const response = await fetch(resumeUrl);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// Extract filename from URL or Content-Disposition header
const contentDisposition = response.headers.get('content-disposition');
if (contentDisposition) {
const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
if (filenameMatch) {
originalFilename = filenameMatch[1].replace(/['"]/g, '');
}
}
if (!originalFilename) {
originalFilename = path.basename(new URL(resumeUrl).pathname) || 'resume.pdf';
}
// Sanitize filename
originalFilename = sanitizeFilename(originalFilename);
// Ensure proper extension
if (!originalFilename.endsWith('.docx') && !originalFilename.endsWith('.pdf')) {
// Try to detect from Content-Type
const contentType = response.headers.get('content-type');
if (contentType?.includes('pdf')) {
originalFilename += '.pdf';
} else {
originalFilename += '.docx';
}
}
// Create temp file
const buffer = Buffer.from(await response.arrayBuffer());
fileSize = buffer.length;
tempFilePath = path.join(PARSED_RESUMES_DIR, `temp-${Date.now()}-${originalFilename}`);
await fs.writeFile(tempFilePath, buffer);
console.log(`✅ Downloaded resume: ${originalFilename} (${fileSize} bytes)`);
// Create a file-like object for consistent handling
uploadedFile = {
originalname: originalFilename,
path: tempFilePath,
size: fileSize
};
} catch (error) {
console.error('❌ Failed to fetch resume from URL:', error);
return res.status(400).json({
error: 'Failed to fetch resume from URL',
details: error.message
});
}
}
if (!uploadedFile) {
return res.status(400).json({ error: 'No file uploaded or URL provided' });
}
const displayName = req.body.displayName || path.basename(uploadedFile.originalname, path.extname(uploadedFile.originalname));
const resumeId = await generateUniqueResumeId(displayName);
const outputDir = path.join(PARSED_RESUMES_DIR, resumeId);
console.log(`📤 Processing resume: ${uploadedFile.originalname}`);
console.log(` Output directory: ${outputDir}`);
// Create output directory
await fs.mkdir(outputDir, { recursive: true });
// Move/copy uploaded file to output directory
const targetPath = path.join(outputDir, sanitizeFilename(uploadedFile.originalname));
if (tempFilePath) {
// URL fetch: move temp file
await fs.rename(uploadedFile.path, targetPath);
} else {
// Regular upload: move uploaded file
await fs.rename(uploadedFile.path, targetPath);
}
// Invoke resume-parser package (pip install -r requirements.txt). Module override via RESUME_PARSER_MODULE.
const parserModule = process.env.RESUME_PARSER_MODULE || 'resume_parser.resume_to_flock';
const pythonCommand = 'python3';
const cleanEnv = {};
for (const [key, value] of Object.entries(process.env)) {
if (!key.includes('API')) {
cleanEnv[key] = value;
}
}
console.log(` Using parser: python -m ${parserModule}`);
const pythonProcess = spawn(pythonCommand, [
'-m',
parserModule,
targetPath,
'-o',
outputDir
], {
env: cleanEnv,
});
let stdout = '';
let stderr = '';
pythonProcess.stdout.on('data', (data) => {
stdout += data.toString();
console.log(`[Parser stdout]: ${data.toString().trim()}`);
});
pythonProcess.stderr.on('data', (data) => {
stderr += data.toString();
console.error(`[Parser stderr]: ${data.toString().trim()}`);
});
await new Promise((resolve, reject) => {
pythonProcess.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`Parser exited with code ${code}. Error: ${stderr}`));
}
});
pythonProcess.on('error', (error) => {
reject(new Error(`Failed to run parser: ${error.message}`));
});
});
// Generate meta.json
const metadata = {
id: resumeId,
displayName: displayName,
originalFilename: uploadedFile.originalname,
sourceUrl: req.body.resumeUrl || null, // Original URL if fetched from web
sourceType: req.body.resumeUrl ? 'url' : 'upload', // 'url' or 'upload'
createdAt: new Date().toISOString(),
uploadedBy: req.body.uploadedBy || 'user',
fileSize: uploadedFile.size
};
const metaPath = path.join(outputDir, 'meta.json');
await fs.writeFile(metaPath, JSON.stringify(metadata, null, 2));
console.log(`✅ Resume parsed successfully: ${resumeId}`);
// Read the parsed data to return in response (parser outputs jobs.json, skills.json, categories.json)
const jobsPath = path.join(outputDir, 'jobs.json');
const skillsPath = path.join(outputDir, 'skills.json');
const categoriesPath = path.join(outputDir, 'categories.json');
const { jobs, skills } = await readAndNormalizeResumeData(jobsPath, skillsPath, categoriesPath);
res.json({
success: true,
resumeId: resumeId,
displayName: displayName,
jobCount: jobs.length,
skillCount: Object.keys(skills).length,
metadata: metadata
});
} catch (error) {
console.error('❌ Resume upload failed:', error);
// Clean up uploaded file if it exists
if (req.file && req.file.path) {
try {
await fs.unlink(req.file.path);
} catch (e) {
// Ignore cleanup errors
}
}
res.status(500).json({
error: 'Failed to process resume upload',
details: error.message
});
}
});
// GET /api/palette-manifest: Provides a sorted list of color palettes
app.get('/api/palette-manifest', async (req, res) => {
try {
const allEntries = await fs.readdir(PALETTE_DIR_PATH);
const jsonFiles = allEntries.filter(entry => entry.endsWith('.json'));
jsonFiles.sort((a, b) => {
const regex = /^(\d+)-/;
const matchA = a.match(regex);
const matchB = b.match(regex);
const numA = matchA ? parseInt(matchA[1], 10) : -1;
const numB = matchB ? parseInt(matchB[1], 10) : -1;
if (numA !== -1 && numB !== -1) return numA - numB;
if (numA !== -1) return -1;
if (numB !== -1) return 1;
return a.localeCompare(b);
});
res.json(jsonFiles);
} catch (error) {
res.status(error.code === 'ENOENT' ? 404 : 500).json({ error: 'Failed to read palette directory.' });
}
});
// POST /api/write-css: Writes dynamic CSS content to a file
app.post('/api/write-css', async (req, res) => {
try {
await fs.mkdir(path.dirname(CSS_FILE_PATH), { recursive: true });
await fs.writeFile(CSS_FILE_PATH, req.body);
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: 'Failed to write CSS file.' });
}
});
// === AUTOMATED BIDIRECTIONAL SYNC FIX ===
// Serve the auto-bidirectional fix script
app.get('/auto-bidirectional-fix', (req, res) => {
const script = `
// AUTO BIDIRECTIONAL FIX - Automatically loads when page loads
// This script will automatically run when you click any rDiv
(function() {
// Wait for DOM to be ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeAutoBidirectionalFix);
} else {
initializeAutoBidirectionalFix();
}
function initializeAutoBidirectionalFix() {
console.log('🤖 AUTO BIDIRECTIONAL FIX: Initializing...');
// Wait a bit for app components to load
setTimeout(() => {
setupAutomaticBidirectionalSync();
}, 2000);
}
function setupAutomaticBidirectionalSync() {
console.log('🤖 AUTO BIDIRECTIONAL FIX: Setting up automatic sync...');
// Function to apply the fix to all resume divs
function applyFixToResumeDivs() {
const resumeDivs = document.querySelectorAll('.biz-resume-div');
const sceneContainer = document.getElementById('scene-container');
if (resumeDivs.length === 0 || !sceneContainer) {
console.log('🤖 AUTO FIX: Waiting for elements to load...');
setTimeout(applyFixToResumeDivs, 1000);
return;
}
console.log('🤖 AUTO FIX: Found ' + resumeDivs.length + ' resume divs, applying automatic fix...');
resumeDivs.forEach(rDiv => {
const jobNumber = parseInt(rDiv.getAttribute('data-job-number'));
// Remove existing listeners by cloning
const newRDiv = rDiv.cloneNode(true);
rDiv.parentNode.replaceChild(newRDiv, rDiv);
// Add the automatic bidirectional sync
newRDiv.addEventListener('click', function(event) {
console.log('🎯 AUTO SYNC: Clicked rDiv job ' + jobNumber);
// Find target cDiv with multiple strategies
const targetCDiv = document.querySelector('#biz-card-div-' + jobNumber) ||
document.querySelector('#biz-card-div-' + jobNumber + '-clone') ||
document.querySelector('[data-job-number="' + jobNumber + '"].biz-card-div');
if (!targetCDiv) {
console.log('❌ AUTO SYNC: No cDiv found for job ' + jobNumber);
return;
}
console.log('✅ AUTO SYNC: Found target cDiv: ' + targetCDiv.id);
// Update selection state
if (window.selectionManager) {
try {
window.selectionManager.selectJobNumber(jobNumber, 'auto-bidirectional-fix');
} catch (error) {
console.log('⚠️ AUTO SYNC: Selection update failed: ' + error.message);
}
}
// Apply selected styling
document.querySelectorAll('.biz-resume-div').forEach(div => {
div.classList.remove('selected');
});
newRDiv.classList.add('selected');
// AUTOMATIC SCROLL TO CENTER THE cDiv
const sceneRect = sceneContainer.getBoundingClientRect();
const cDivRect = targetCDiv.getBoundingClientRect();
const scrollTop = sceneContainer.scrollTop + (cDivRect.top - sceneRect.top) - (sceneRect.height / 2) + (cDivRect.height / 2);
console.log('🔄 AUTO SYNC: Scrolling to center job ' + jobNumber + ' (position ' + Math.round(scrollTop) + 'px)');
sceneContainer.scrollTo({
top: scrollTop,
behavior: 'smooth'
});
// Verify the sync worked
setTimeout(() => {
const finalCDivRect = targetCDiv.getBoundingClientRect();
const finalSceneRect = sceneContainer.getBoundingClientRect();
const isVisible = finalCDivRect.top >= finalSceneRect.top &&
finalCDivRect.bottom <= finalSceneRect.bottom;
if (isVisible) {
console.log('✅ AUTO SYNC SUCCESS: Job ' + jobNumber + ' cDiv is now visible and centered!');
} else {
console.log('⚠️ AUTO SYNC PARTIAL: Job ' + jobNumber + ' cDiv scrolled but not fully centered');
}
}, 1000);
});
});
console.log('🎉 AUTO BIDIRECTIONAL FIX: All resume divs now have automatic sync!');
console.log('🎯 Click any resume item to see automatic bidirectional synchronization');
}
// Start applying the fix
applyFixToResumeDivs();
// Also watch for new resume divs being added dynamically
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (node.classList && node.classList.contains('biz-resume-div')) {
console.log('🤖 AUTO FIX: New resume div detected, applying fix...');
setTimeout(applyFixToResumeDivs, 100);
}
});
});
});
observer.observe(document.body, { childList: true, subtree: true });
}
console.log('🤖 AUTO BIDIRECTIONAL FIX: Loaded and ready!');
})();
`;
res.setHeader('Content-Type', 'application/javascript');
res.send(script);
});
// === AUTOMATED EVENT RECORDING AND ANALYSIS SYSTEM ===
// Serve the automated testing script automatically when requested
app.get('/automated-test-script', (req, res) => {
const script = `
// AUTOMATED BIDIRECTIONAL SYNC TESTER - Auto-injected by server
(function() {
console.log('🤖 SERVER-INJECTED AUTOMATED TESTER LOADING...');