-
Notifications
You must be signed in to change notification settings - Fork 190
Expand file tree
/
Copy pathcontext.ts
More file actions
888 lines (770 loc) · 27 KB
/
Copy pathcontext.ts
File metadata and controls
888 lines (770 loc) · 27 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
import { AsyncLocalStorage } from 'node:async_hooks';
import type { Dirent } from 'node:fs';
import { copyFile, mkdir, open, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { homedir, hostname } from 'node:os';
import { join, resolve } from 'node:path';
import { ENV_VAR_NAME_PATTERN, type CollaborationProfile } from './collaboration';
import { CliError } from './errors';
import { asRecord, isRecord, pathExists } from './guards';
import { validateSessionId } from './session';
import { type CliIO, type DocumentRuntimeKind, type ExecutionMode, type UserIdentity } from './types';
const CONTEXT_VERSION = 'v1';
const ACTIVE_SESSION_FILENAME = 'active-session';
const DEFAULT_LOCK_TIMEOUT_MS = 5_000;
const LOCK_RETRY_INTERVAL_MS = 50;
const STATE_DIR_OVERRIDE_STORAGE = new AsyncLocalStorage<string>();
export type SourceSnapshot = {
mtimeMs: number;
size: number;
checksum: string;
};
export type SessionType = 'local' | 'collab';
export type TrackChangesOpenOptions = {
replacements?: 'paired' | 'independent';
};
export type ContextMetadata = {
contextId: string;
projectRoot: string;
source: 'path' | 'stdin' | 'blank';
sourcePath?: string;
workingDocPath: string;
dirty: boolean;
revision: number;
sessionType: SessionType;
/**
* Runtime kind selected at open time. Metadata files written by older
* CLIs may omit this field — readers normalize the absence to `v1`.
*/
runtime: DocumentRuntimeKind;
collaboration?: CollaborationProfile;
trackChanges?: TrackChangesOpenOptions;
user?: UserIdentity;
openedAt: string;
updatedAt: string;
lastSavedAt?: string;
sourceSnapshot?: SourceSnapshot;
};
export type ContextPaths = {
stateRoot: string;
contextDir: string;
metadataPath: string;
originalDocPath: string;
workingDocPath: string;
lockPath: string;
};
export type ProjectSessionSummary = {
sessionId: string;
source: 'path' | 'stdin' | 'blank';
sourcePath?: string;
dirty: boolean;
revision: number;
sessionType: SessionType;
runtime: DocumentRuntimeKind;
collaboration?: CollaborationProfile;
trackChanges?: TrackChangesOpenOptions;
openedAt: string;
updatedAt: string;
lastSavedAt?: string;
};
type ProjectPaths = {
projectHash: string;
projectDir: string;
activeSessionPath: string;
};
type LockMetadata = {
pid: number;
hostname: string;
startedAt: string;
projectRoot: string;
command: string;
};
function getStateRoot(): string {
const scopedOverride = STATE_DIR_OVERRIDE_STORAGE.getStore();
if (scopedOverride && scopedOverride.length > 0) {
return scopedOverride;
}
const override = process.env.SUPERDOC_CLI_STATE_DIR;
if (override && override.length > 0) {
return resolve(override);
}
return join(homedir(), '.superdoc-cli', 'state', CONTEXT_VERSION);
}
export async function withStateDirOverride<T>(stateDir: string | undefined, operation: () => Promise<T>): Promise<T> {
if (stateDir == null || stateDir.length === 0) {
return operation();
}
return STATE_DIR_OVERRIDE_STORAGE.run(resolve(stateDir), operation);
}
export function getContextPaths(contextId: string): ContextPaths {
const normalizedContextId = validateSessionId(contextId, 'session id');
const stateRoot = getStateRoot();
const contextDir = join(stateRoot, 'contexts', normalizedContextId);
return {
stateRoot,
contextDir,
metadataPath: join(contextDir, 'metadata.json'),
originalDocPath: join(contextDir, 'original.docx'),
workingDocPath: join(contextDir, 'working.docx'),
lockPath: join(contextDir, 'lock'),
};
}
export function getProjectRoot(): string {
return resolve(process.cwd());
}
function getProjectPaths(projectRoot = getProjectRoot()): ProjectPaths {
const stateRoot = getStateRoot();
const projectHash = createHash('sha256').update(projectRoot).digest('hex').slice(0, 16);
const projectDir = join(stateRoot, 'projects', projectHash);
return {
projectHash,
projectDir,
activeSessionPath: join(projectDir, ACTIVE_SESSION_FILENAME),
};
}
function nowIso(io: CliIO): string {
return new Date(io.now()).toISOString();
}
function normalizeSessionType(value: unknown): SessionType {
if (value === 'collab') return 'collab';
return 'local';
}
function normalizeRuntime(value: unknown): DocumentRuntimeKind {
// Session metadata may outlive older runtime labels, but this CLI no longer
// offers runtime selection. Rehydrate every session as v1.
void value;
return 'v1';
}
function normalizeUser(value: unknown): UserIdentity | undefined {
const record = asRecord(value);
if (!record) return undefined;
if (typeof record.name !== 'string' || record.name.length === 0) return undefined;
if (typeof record.email !== 'string') return undefined;
return { name: record.name, email: record.email };
}
function isOptionalNonEmptyString(value: unknown): value is string | undefined {
return value == null || (typeof value === 'string' && value.length > 0);
}
function isOptionalPositiveNumber(value: unknown): value is number | undefined {
return value == null || (typeof value === 'number' && Number.isFinite(value) && value > 0);
}
function isValidOnMissing(value: unknown): value is CollaborationProfile['onMissing'] {
return value == null || value === 'seedFromDoc' || value === 'blank' || value === 'error';
}
type SharedProfileFields = {
syncTimeoutMs: number | undefined;
onMissing: CollaborationProfile['onMissing'];
bootstrapSettlingMs: number | undefined;
};
function normalizeSharedFields(record: Record<string, unknown>): SharedProfileFields | null {
if (!isOptionalPositiveNumber(record.syncTimeoutMs)) return null;
if (!isValidOnMissing(record.onMissing)) return null;
if (!isOptionalPositiveNumber(record.bootstrapSettlingMs)) return null;
return {
syncTimeoutMs: typeof record.syncTimeoutMs === 'number' ? record.syncTimeoutMs : undefined,
onMissing: record.onMissing as CollaborationProfile['onMissing'],
bootstrapSettlingMs: typeof record.bootstrapSettlingMs === 'number' ? record.bootstrapSettlingMs : undefined,
};
}
function normalizeWebSocketParams(value: unknown): Record<string, string> | null | undefined {
if (value == null) return undefined;
if (!isRecord(value)) return null;
const result: Record<string, string> = {};
for (const [key, val] of Object.entries(value)) {
if (typeof key !== 'string' || key.length === 0) return null;
if (typeof val !== 'string') return null;
result[key] = val;
}
return result;
}
function normalizeWebSocketProfile(record: Record<string, unknown>): CollaborationProfile | undefined {
const { providerType, url, documentId, tokenEnv } = record;
if (typeof url !== 'string' || url.length === 0) return undefined;
if (typeof documentId !== 'string' || documentId.length === 0) return undefined;
if (!isOptionalNonEmptyString(tokenEnv)) return undefined;
const shared = normalizeSharedFields(record);
if (!shared) return undefined;
const params = normalizeWebSocketParams(record.params);
if (params === null) return undefined;
return {
providerType: providerType as 'hocuspocus' | 'y-websocket',
url,
documentId,
tokenEnv: typeof tokenEnv === 'string' ? tokenEnv : undefined,
params,
...shared,
};
}
function isValidEnvVarName(value: unknown): value is string {
return typeof value === 'string' && ENV_VAR_NAME_PATTERN.test(value);
}
function normalizeLiveblocksProfile(record: Record<string, unknown>): CollaborationProfile | undefined {
const { documentId, publicApiKey, authEndpoint, authHeadersEnv } = record;
if (typeof documentId !== 'string' || documentId.length === 0) return undefined;
if (!isOptionalNonEmptyString(publicApiKey)) return undefined;
if (!isOptionalNonEmptyString(authEndpoint)) return undefined;
// Must have exactly one auth mode
const hasPublicKey = typeof publicApiKey === 'string';
const hasEndpoint = typeof authEndpoint === 'string';
if (hasPublicKey === hasEndpoint) return undefined; // both or neither
// authEndpoint must be absolute (matches parser contract)
if (hasEndpoint && !authEndpoint!.startsWith('http://') && !authEndpoint!.startsWith('https://')) {
return undefined;
}
// authHeadersEnv must be a valid env var name and only present with authEndpoint
const hasHeadersEnv = authHeadersEnv != null;
if (hasHeadersEnv) {
if (!isValidEnvVarName(authHeadersEnv)) return undefined;
if (!hasEndpoint) return undefined; // authHeadersEnv without authEndpoint is invalid
}
const shared = normalizeSharedFields(record);
if (!shared) return undefined;
return {
providerType: 'liveblocks',
documentId,
publicApiKey: hasPublicKey ? publicApiKey : undefined,
authEndpoint: hasEndpoint ? authEndpoint : undefined,
authHeadersEnv: isValidEnvVarName(authHeadersEnv) ? authHeadersEnv : undefined,
...shared,
};
}
function normalizeCollaborationProfile(value: unknown): CollaborationProfile | undefined {
const record = asRecord(value);
if (!record) return undefined;
const { providerType } = record;
if (providerType === 'liveblocks') return normalizeLiveblocksProfile(record);
if (providerType === 'hocuspocus' || providerType === 'y-websocket') return normalizeWebSocketProfile(record);
return undefined;
}
function normalizeTrackChangesOpenOptions(value: unknown): TrackChangesOpenOptions | undefined {
const record = asRecord(value);
if (!record) return undefined;
const replacements = record.replacements;
if (replacements === 'paired' || replacements === 'independent') return { replacements };
return undefined;
}
export function normalizeContextMetadata(metadata: ContextMetadata): ContextMetadata {
const sessionType = normalizeSessionType(metadata.sessionType);
const collaboration = normalizeCollaborationProfile(metadata.collaboration);
const trackChanges = normalizeTrackChangesOpenOptions(metadata.trackChanges);
const user = normalizeUser(metadata.user);
const runtime = normalizeRuntime(metadata.runtime);
if (sessionType === 'collab' && collaboration) {
return {
...metadata,
sessionType,
runtime,
collaboration,
trackChanges,
user,
};
}
return {
...metadata,
sessionType: 'local',
runtime,
collaboration: undefined,
trackChanges,
user,
};
}
function sleep(ms: number): Promise<void> {
return new Promise((resolveSleep) => {
setTimeout(resolveSleep, ms);
});
}
function isLockAlive(pid: number): boolean {
if (!Number.isInteger(pid) || pid <= 0) return false;
try {
process.kill(pid, 0);
return true;
} catch (error) {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
if (code === 'ESRCH') return false;
if (code === 'EPERM') return true;
return true;
}
}
async function readLockMetadata(lockPath: string): Promise<LockMetadata | null> {
let raw: string;
try {
raw = await readFile(lockPath, 'utf8');
} catch (error) {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
if (code === 'ENOENT') return null;
throw new CliError('FILE_READ_ERROR', `Could not read context lock file: ${lockPath}`, {
message: error instanceof Error ? error.message : String(error),
});
}
try {
const parsed = JSON.parse(raw) as LockMetadata;
if (typeof parsed?.pid !== 'number') return null;
return parsed;
} catch {
return null;
}
}
async function writeLockMetadata(lockPath: string, metadata: LockMetadata): Promise<void> {
try {
const handle = await open(lockPath, 'wx');
try {
await handle.writeFile(`${JSON.stringify(metadata, null, 2)}\n`, 'utf8');
} finally {
await handle.close();
}
} catch (error) {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
if (code === 'EEXIST') {
throw new CliError('CONTEXT_LOCK_TIMEOUT', 'Context lock already exists.', {
lockPath,
});
}
throw new CliError('FILE_WRITE_ERROR', `Could not acquire context lock: ${lockPath}`, {
message: error instanceof Error ? error.message : String(error),
});
}
}
async function tryRemoveLock(lockPath: string): Promise<void> {
try {
await unlink(lockPath);
} catch (error) {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
if (code === 'ENOENT') return;
throw new CliError('FILE_WRITE_ERROR', `Could not release context lock: ${lockPath}`, {
message: error instanceof Error ? error.message : String(error),
});
}
}
function assertProjectMatch(metadata: ContextMetadata): void {
const currentProjectRoot = getProjectRoot();
if (metadata.projectRoot === currentProjectRoot) return;
throw new CliError(
'PROJECT_CONTEXT_MISMATCH',
'Active context belongs to a different project root than the current working directory.',
{
expectedProjectRoot: metadata.projectRoot,
actualProjectRoot: currentProjectRoot,
},
);
}
async function writeAtomic(path: string, content: string): Promise<void> {
const tempPath = `${path}.${process.pid}.${Date.now()}.tmp`;
await writeFile(tempPath, content, 'utf8');
await rename(tempPath, path);
}
export async function getActiveSessionId(projectRoot = getProjectRoot()): Promise<string | null> {
const paths = getProjectPaths(projectRoot);
let raw: string;
try {
raw = await readFile(paths.activeSessionPath, 'utf8');
} catch (error) {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
if (code === 'ENOENT') return null;
throw new CliError('FILE_READ_ERROR', `Unable to read active session pointer: ${paths.activeSessionPath}`, {
message: error instanceof Error ? error.message : String(error),
});
}
const sessionId = raw.trim();
if (!sessionId) return null;
try {
return validateSessionId(sessionId, 'active session id');
} catch (error) {
if (error instanceof CliError) {
return null;
}
throw error;
}
}
export async function setActiveSessionId(sessionId: string, projectRoot = getProjectRoot()): Promise<void> {
const normalizedSessionId = validateSessionId(sessionId, 'session id');
const paths = getProjectPaths(projectRoot);
await mkdir(paths.projectDir, { recursive: true });
try {
await writeAtomic(paths.activeSessionPath, `${normalizedSessionId}\n`);
} catch (error) {
throw new CliError('FILE_WRITE_ERROR', `Unable to write active session pointer: ${paths.activeSessionPath}`, {
message: error instanceof Error ? error.message : String(error),
projectHash: paths.projectHash,
});
}
}
export async function clearActiveSessionId(projectRoot = getProjectRoot()): Promise<void> {
const paths = getProjectPaths(projectRoot);
try {
await unlink(paths.activeSessionPath);
} catch (error) {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
if (code === 'ENOENT') return;
throw new CliError('FILE_WRITE_ERROR', `Unable to clear active session pointer: ${paths.activeSessionPath}`, {
message: error instanceof Error ? error.message : String(error),
projectHash: paths.projectHash,
});
}
}
export async function withContextLock<T>(
io: CliIO,
command: string,
action: (paths: ContextPaths) => Promise<T>,
timeoutMs = DEFAULT_LOCK_TIMEOUT_MS,
contextId?: string,
): Promise<T> {
const resolvedContextId = contextId ?? 'default';
const paths = getContextPaths(resolvedContextId);
await mkdir(paths.contextDir, { recursive: true });
const startedAt = io.now();
const lockMetadata: LockMetadata = {
pid: process.pid,
hostname: hostname(),
startedAt: nowIso(io),
projectRoot: getProjectRoot(),
command,
};
let acquired = false;
while (!acquired) {
try {
await writeLockMetadata(paths.lockPath, lockMetadata);
acquired = true;
break;
} catch (error) {
if (!(error instanceof CliError) || error.code !== 'CONTEXT_LOCK_TIMEOUT') {
throw error;
}
const owner = await readLockMetadata(paths.lockPath);
const ownerAlive = owner ? isLockAlive(owner.pid) : false;
if (!ownerAlive) {
await tryRemoveLock(paths.lockPath);
continue;
}
if (io.now() - startedAt >= timeoutMs) {
throw new CliError('CONTEXT_LOCK_TIMEOUT', `Timed out waiting for context lock after ${timeoutMs}ms.`, {
timeoutMs,
lockPath: paths.lockPath,
owner,
});
}
await sleep(LOCK_RETRY_INTERVAL_MS);
}
}
try {
return await action(paths);
} finally {
if (acquired) {
await tryRemoveLock(paths.lockPath);
}
}
}
export async function readContextMetadata(paths: ContextPaths): Promise<ContextMetadata | null> {
let raw: string;
try {
raw = await readFile(paths.metadataPath, 'utf8');
} catch (error) {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
if (code === 'ENOENT') return null;
throw new CliError('FILE_READ_ERROR', `Unable to read active context metadata: ${paths.metadataPath}`, {
message: error instanceof Error ? error.message : String(error),
});
}
try {
const parsed = JSON.parse(raw) as ContextMetadata;
return normalizeContextMetadata(parsed);
} catch (error) {
throw new CliError('JSON_PARSE_ERROR', `Active context metadata is invalid JSON: ${paths.metadataPath}`, {
message: error instanceof Error ? error.message : String(error),
});
}
}
export async function writeContextMetadata(paths: ContextPaths, metadata: ContextMetadata): Promise<void> {
await mkdir(paths.contextDir, { recursive: true });
try {
await writeFile(paths.metadataPath, `${JSON.stringify(metadata, null, 2)}\n`, 'utf8');
} catch (error) {
throw new CliError('FILE_WRITE_ERROR', `Unable to write active context metadata: ${paths.metadataPath}`, {
message: error instanceof Error ? error.message : String(error),
});
}
}
export async function readContextMetadataById(contextId: string): Promise<ContextMetadata | null> {
const paths = getContextPaths(contextId);
return readContextMetadata(paths);
}
export async function listProjectSessions(): Promise<ProjectSessionSummary[]> {
const stateRoot = getStateRoot();
const contextsDir = join(stateRoot, 'contexts');
const projectRoot = getProjectRoot();
let entries: Dirent[] = [];
try {
entries = await readdir(contextsDir, { withFileTypes: true });
} catch (error) {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
if (code === 'ENOENT') return [];
throw new CliError('FILE_READ_ERROR', `Unable to read sessions directory: ${contextsDir}`, {
message: error instanceof Error ? error.message : String(error),
});
}
const sessions: ProjectSessionSummary[] = [];
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const sessionId = entry.name;
let metadata: ContextMetadata | null = null;
try {
metadata = await readContextMetadataById(sessionId);
} catch {
continue;
}
if (!metadata) continue;
if (metadata.projectRoot !== projectRoot) continue;
sessions.push({
sessionId: metadata.contextId,
source: metadata.source,
sourcePath: metadata.sourcePath,
dirty: metadata.dirty,
revision: metadata.revision,
sessionType: metadata.sessionType,
runtime: metadata.runtime,
collaboration: metadata.collaboration,
openedAt: metadata.openedAt,
updatedAt: metadata.updatedAt,
lastSavedAt: metadata.lastSavedAt,
});
}
sessions.sort((a, b) => {
if (a.updatedAt === b.updatedAt) {
return a.sessionId.localeCompare(b.sessionId);
}
return b.updatedAt.localeCompare(a.updatedAt);
});
return sessions;
}
export async function ensureSessionExistsForProject(sessionId: string): Promise<ContextMetadata> {
const metadata = await readContextMetadataById(sessionId);
if (!metadata) {
throw new CliError('SESSION_NOT_FOUND', `Session not found: ${sessionId}`, {
sessionId,
});
}
if (metadata.projectRoot !== getProjectRoot()) {
throw new CliError('SESSION_NOT_FOUND', `Session not found in this project: ${sessionId}`, {
sessionId,
});
}
return metadata;
}
export async function clearContext(paths: ContextPaths): Promise<void> {
await rm(paths.contextDir, { recursive: true, force: true });
}
/**
* Resolve the target session id for an operation, respecting execution mode.
*
* - If an explicit session id is provided, return it immediately.
* - In host mode, an explicit session id is **required** — never fall back to
* the project-global active-session file. This prevents cross-document
* contamination between SDK clients sharing the same project root.
* - In oneshot (CLI) mode, fall back to the active-session file as a
* convenience for single-terminal workflows.
*/
export async function resolveSessionId(
sessionId: string | undefined,
executionMode: ExecutionMode | undefined,
): Promise<string> {
if (sessionId) return sessionId;
if (executionMode === 'host') {
throw new CliError(
'SESSION_REQUIRED',
'Host-mode operations require an explicit session id. Use the SDK document handle or pass --session.',
);
}
const activeSessionId = await getActiveSessionId();
if (!activeSessionId) {
throw new CliError('NO_ACTIVE_DOCUMENT', 'No active document. Run "superdoc open <doc>" first.');
}
return activeSessionId;
}
export async function withActiveContext<T>(
io: CliIO,
command: string,
action: (state: { metadata: ContextMetadata; paths: ContextPaths }) => Promise<T>,
contextId?: string,
executionMode?: ExecutionMode,
): Promise<T> {
const resolvedContextId = await resolveSessionId(contextId, executionMode);
return withContextLock(
io,
command,
async (paths) => {
const metadata = await readContextMetadata(paths);
if (!metadata) {
throw new CliError('NO_ACTIVE_DOCUMENT', 'No active document. Run "superdoc open <doc>" first.');
}
assertProjectMatch(metadata);
return action({ metadata, paths });
},
DEFAULT_LOCK_TIMEOUT_MS,
resolvedContextId,
);
}
export function resolveSourcePathForMetadata(docArg: string): string {
return resolve(getProjectRoot(), docArg);
}
export async function snapshotSourceFile(path: string): Promise<SourceSnapshot> {
let bytes: Uint8Array;
let sourceStat: Awaited<ReturnType<typeof stat>>;
try {
const buffer = await readFile(path);
bytes = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
sourceStat = await stat(path);
} catch (error) {
throw new CliError('FILE_READ_ERROR', `Unable to read source file snapshot: ${path}`, {
message: error instanceof Error ? error.message : String(error),
});
}
const checksum = createHash('sha256').update(bytes).digest('hex');
return {
mtimeMs: sourceStat.mtimeMs,
size: sourceStat.size,
checksum,
};
}
export async function detectSourceDrift(metadata: ContextMetadata): Promise<{
drifted: boolean;
expected?: SourceSnapshot;
actual?: SourceSnapshot;
reason?: string;
}> {
if (metadata.source !== 'path' || !metadata.sourcePath || !metadata.sourceSnapshot) {
return { drifted: false };
}
if (!(await pathExists(metadata.sourcePath))) {
return {
drifted: true,
expected: metadata.sourceSnapshot,
reason: 'SOURCE_MISSING',
};
}
const actual = await snapshotSourceFile(metadata.sourcePath);
const expected = metadata.sourceSnapshot;
const drifted =
actual.mtimeMs !== expected.mtimeMs || actual.size !== expected.size || actual.checksum !== expected.checksum;
return {
drifted,
expected,
actual,
};
}
export async function copyWorkingDocumentToPath(
paths: ContextPaths,
outputPath: string,
force = false,
): Promise<{ path: string; byteLength: number }> {
const exists = await pathExists(outputPath);
if (exists && !force) {
throw new CliError('OUTPUT_EXISTS', `Output path already exists: ${outputPath}`, {
path: outputPath,
hint: 'Use --force to overwrite.',
});
}
try {
await copyFile(paths.workingDocPath, outputPath);
} catch (error) {
throw new CliError('FILE_WRITE_ERROR', `Failed to write output file: ${outputPath}`, {
message: error instanceof Error ? error.message : String(error),
});
}
const outputStat = await stat(outputPath);
return {
path: outputPath,
byteLength: outputStat.size,
};
}
export async function copyOriginalDocumentToPath(
paths: ContextPaths,
outputPath: string,
force = false,
): Promise<{ path: string; byteLength: number }> {
const exists = await pathExists(outputPath);
if (exists && !force) {
throw new CliError('OUTPUT_EXISTS', `Output path already exists: ${outputPath}`, {
path: outputPath,
hint: 'Use --force to overwrite.',
});
}
try {
await copyFile(paths.originalDocPath, outputPath);
} catch (error) {
throw new CliError('FILE_WRITE_ERROR', `Failed to write output file: ${outputPath}`, {
message: error instanceof Error ? error.message : String(error),
});
}
const outputStat = await stat(outputPath);
return {
path: outputPath,
byteLength: outputStat.size,
};
}
export async function getWorkingDocumentSize(paths: ContextPaths): Promise<number> {
try {
const info = await stat(paths.workingDocPath);
return info.size;
} catch (error) {
throw new CliError('FILE_READ_ERROR', `Failed to read working document: ${paths.workingDocPath}`, {
message: error instanceof Error ? error.message : String(error),
});
}
}
export function markContextUpdated(
io: CliIO,
metadata: ContextMetadata,
patch: Partial<ContextMetadata>,
): ContextMetadata {
return {
...metadata,
...patch,
updatedAt: nowIso(io),
};
}
export function assertExpectedRevision(metadata: ContextMetadata, expectedRevision: number | undefined): void {
if (expectedRevision == null) return;
if (!Number.isInteger(expectedRevision) || expectedRevision < 0) {
throw new CliError('VALIDATION_ERROR', '--expected-revision must be a non-negative integer.');
}
if (metadata.revision !== expectedRevision) {
throw new CliError('REVISION_MISMATCH', 'Document revision did not match --expected-revision.', {
expectedRevision,
actualRevision: metadata.revision,
});
}
}
export function createInitialContextMetadata(
io: CliIO,
paths: ContextPaths,
contextId: string,
input: {
source: 'path' | 'stdin' | 'blank';
sourcePath?: string;
sourceSnapshot?: SourceSnapshot;
sessionType?: SessionType;
collaboration?: CollaborationProfile;
trackChanges?: TrackChangesOpenOptions;
user?: UserIdentity;
runtime?: DocumentRuntimeKind;
},
): ContextMetadata {
const timestamp = nowIso(io);
const sessionType = input.sessionType ?? 'local';
return {
contextId,
projectRoot: getProjectRoot(),
source: input.source,
sourcePath: input.sourcePath,
workingDocPath: paths.workingDocPath,
dirty: false,
revision: 0,
sessionType,
runtime: input.runtime ?? 'v1',
collaboration: sessionType === 'collab' ? input.collaboration : undefined,
trackChanges: input.trackChanges,
user: input.user,
openedAt: timestamp,
updatedAt: timestamp,
sourceSnapshot: input.sourceSnapshot,
};
}