@phroun/paged-buffer
Version:
High-performance buffer system for editing massive files with intelligent memory management and undo/redo capabilities
455 lines • 13.2 kB
TypeScript
/**
* @fileoverview Enhanced PagedBuffer with page coordinate-based marks
* @description High-performance buffer with line-aware operations and page coordinate marks support
* @author Jeffrey R. Day
* @version 2.3.0 - Page coordinate marks system
*/
/// <reference types="node" />
/// <reference types="node" />
import { BufferUndoSystem } from './undo-system';
import { VirtualPageManager } from './virtual-page-manager';
import { LineAndMarksManager, ExtractedContent } from './utils/line-marks-manager';
import { type IBuffer, type MarkInfo, type LineCharPosition, type RelativeMarkTuple } from './types/common';
declare enum BufferState {
CLEAN = "clean",
DETACHED = "detached",
CORRUPTED = "corrupted"
}
declare enum FileChangeStrategy {
REBASE = "rebase",
WARN = "warn",
DETACH = "detach"
}
declare enum NotificationType {
BUFFER_DETACHED = "buffer_detached",
FILE_MODIFIED_ON_DISK = "file_modified_on_disk",
PAGE_SPLIT = "page_split",
PAGE_MERGED = "page_merged",
STORAGE_ERROR = "storage_error"
}
interface BufferNotification {
type: string;
severity: string;
message: string;
metadata: any;
timestamp: Date;
}
interface ChangeStrategy {
noEdits: FileChangeStrategy;
withEdits: FileChangeStrategy;
sizeChanged: FileChangeStrategy;
}
interface Storage {
savePage(pageKey: string, data: Buffer): Promise<void>;
loadPage(pageKey: string): Promise<Buffer>;
deletePage(pageKey: string): Promise<void>;
}
interface SaveOptions {
forcePartialSave?: boolean;
allowDetached?: boolean;
isAtomicSave?: boolean;
}
interface UndoConfig {
maxUndoLevels?: number;
[key: string]: any;
}
interface UndoTransactionOptions {
[key: string]: any;
}
interface LineOperationResult {
lineNumber: number;
byteStart: number;
byteEnd: number;
length: number;
marks: Array<[string, number]>;
isExact: boolean;
}
interface FileChangeInfo {
changed: boolean;
sizeChanged?: boolean;
mtimeChanged?: boolean;
newSize?: number;
newMtime?: Date;
deleted?: boolean;
}
interface BufferStatus {
state: BufferState;
hasUnsavedChanges: boolean;
canSaveToOriginal: boolean;
isDetached: boolean;
isCorrupted: boolean;
missingDataRanges: number;
totalSize: number;
filename: string | null;
}
interface DetachmentInfo {
isDetached: boolean;
reason: string | null;
missingRanges: number;
totalMissingBytes: number;
ranges: Array<{
virtualStart: number;
virtualEnd: number;
size: number;
reason: string;
}>;
}
interface MemoryStats {
totalPages: number;
loadedPages: number;
dirtyPages: number;
detachedPages: number;
memoryUsed: number;
maxMemoryPages: number;
totalLines: number;
globalMarksCount: number;
pageIndexSize: number;
linesMemory: number;
marksMemory: number;
lineStartsCacheValid: boolean;
state: BufferState;
hasUnsavedChanges: boolean;
virtualSize: number;
sourceSize: number;
undo: {
undoGroups: number;
redoGroups: number;
totalUndoOperations: number;
totalRedoOperations: number;
currentGroupOperations: number;
memoryUsage: number;
};
}
/**
* Tracks missing data ranges in detached buffers
*/
declare class MissingDataRange {
virtualStart: number;
virtualEnd: number;
originalFileStart: number | null;
originalFileEnd: number | null;
reason: string;
size: number;
constructor(virtualStart: number, virtualEnd: number, originalFileStart?: number | null, originalFileEnd?: number | null, reason?: string);
/**
* Generate human-readable description of missing data
*/
toDescription(): string;
}
/**
* Enhanced PagedBuffer with page coordinate-based marks
*/
declare class PagedBuffer implements IBuffer {
pageSize: number;
storage: Storage;
maxMemoryPages: number;
filename: string | null;
fileSize: number;
fileMtime: Date | null;
fileChecksum: string | null;
virtualPageManager: VirtualPageManager;
lineAndMarksManager: LineAndMarksManager;
totalSize: number;
state: BufferState;
hasUnsavedChanges: boolean;
missingDataRanges: MissingDataRange[];
detachmentReason: string | null;
notifications: BufferNotification[];
notificationCallbacks: Array<(notification: BufferNotification) => void>;
changeStrategy: ChangeStrategy;
lastFileCheck: number | null;
fileCheckInterval: number;
undoSystem: BufferUndoSystem | null;
constructor(pageSize?: number, storage?: Storage | null, maxMemoryPages?: number);
/**
* Mark buffer as detached due to data loss
*/
_markAsDetached(reason: string, missingRanges?: MissingDataRange[]): void;
/**
* Mark buffer as having unsaved changes
*/
markAsModified(): void;
/**
* Mark buffer as saved (no unsaved changes)
*/
private _markAsSaved;
/**
* Merge overlapping missing data ranges
*/
private _mergeMissingRanges;
/**
* Add notification callback
*/
onNotification(callback: (notification: BufferNotification) => void): void;
/**
* Emit a notification
*/
_notify(type: string, severity: string, message: string, metadata?: any): void;
/**
* Load a file into the buffer
*/
loadFile(filename: string): Promise<void>;
/**
* Enhanced loadContent with proper initial state
*/
loadContent(content: string): void;
/**
* Enhanced loadBinaryContent with proper initial state
*/
loadBinaryContent(content: Buffer): void;
/**
* Calculate file checksum for change detection
*/
private _calculateFileChecksum;
/**
* Check for file changes
*/
checkFileChanges(): Promise<FileChangeInfo>;
/**
* Get bytes from absolute position with optional marks extraction
*/
getBytes(start: number, end: number, includeMarks?: boolean): Promise<Buffer | ExtractedContent>;
/**
* Enhanced insertBytes with marks support - FIXED parameter handling
*/
insertBytes(position: number, data: Buffer, marks?: MarkInfo[] | RelativeMarkTuple[]): Promise<void>;
/**
* Enhanced deleteBytes with marks reporting - FIXED to handle tuples
*/
deleteBytes(start: number, end: number, reportMarks?: boolean): Promise<Buffer | ExtractedContent>;
/**
* Enhanced overwriteBytes with marks support - FIXED to handle tuples
*/
overwriteBytes(position: number, data: Buffer, marks?: MarkInfo[] | RelativeMarkTuple[]): Promise<Buffer | ExtractedContent>;
/**
* Set a named mark at a byte address
*/
setMark(markName: string, byteAddress: number): void;
/**
* Get the byte address of a named mark
*/
getMark(markName: string): number | null;
/**
* Remove a named mark
*/
removeMark(markName: string): boolean;
/**
* Get all marks between two byte addresses
*/
getMarksInRange(startAddress: number, endAddress: number): Array<[string, number]>;
/**
* Get all marks in the buffer
*/
getAllMarks(): Record<string, number>;
/**
* Set marks from a key-value object (for persistence)
*/
setMarks(marksObject: Record<string, number>): void;
/**
* Clear all marks
*/
clearAllMarks(): void;
/**
* Enable undo/redo functionality
*/
enableUndo(config?: UndoConfig): void;
/**
* Disable undo/redo functionality
*/
disableUndo(): void;
/**
* Begin a named undo transaction
*/
beginUndoTransaction(name: string, options?: UndoTransactionOptions): void;
/**
* Commit the current undo transaction
*/
commitUndoTransaction(finalName?: string | null): boolean;
/**
* Rollback the current undo transaction
*/
rollbackUndoTransaction(): Promise<boolean>;
/**
* Check if currently in an undo transaction
*/
inUndoTransaction(): boolean;
/**
* Get current undo transaction info
*/
getCurrentUndoTransaction(): any;
/**
* Undo the last operation
*/
undo(): Promise<boolean>;
/**
* Redo the last undone operation
*/
redo(): Promise<boolean>;
/**
* Check if undo is available
*/
canUndo(): boolean;
/**
* Check if redo is available
*/
canRedo(): boolean;
/**
* Get total size of buffer
*/
getTotalSize(): number;
/**
* Get buffer state (data integrity)
*/
getState(): BufferState;
/**
* Check if buffer has unsaved changes
*/
hasChanges(): boolean;
/**
* Check if buffer can be saved to its original location
*/
canSaveToOriginal(): boolean;
/**
* Get comprehensive buffer status
*/
getStatus(): BufferStatus;
/**
* Get enhanced memory usage stats with line and marks information
*/
getMemoryStats(): MemoryStats;
/**
* Get detachment information
*/
getDetachmentInfo(): DetachmentInfo;
/**
* Get all notifications
*/
getNotifications(): BufferNotification[];
/**
* Clear notifications
*/
clearNotifications(type?: string | null): void;
/**
* Set file change handling strategy
*/
setChangeStrategy(strategies: Partial<ChangeStrategy>): void;
/**
* Generate missing data summary for save operations
*/
private _generateMissingDataSummary;
/**
* Create marker for missing data at a specific position
*/
private _createMissingDataMarker;
/**
* Create marker for missing data at end of file
*/
private _createEndOfFileMissingMarker;
/**
* Create emergency marker for data that became unavailable during save
*/
private _createEmergencyMissingMarker;
/**
* Write data with markers indicating where missing data belongs - FIXED for large files
*/
private _writeDataWithMissingMarkers;
/**
* Write a segment of data in manageable chunks
*/
private _writeSegmentInChunks;
/**
* Enhanced save method with smart behavior and atomic operations
*/
saveFile(filename?: string | null, options?: SaveOptions): Promise<void>;
/**
* Enhanced saveAs that handles detached buffers gracefully
*/
saveAs(filename: string, forcePartialOrOptions?: boolean | SaveOptions, options?: SaveOptions): Promise<void>;
/**
* Enhanced save method with positional missing data markers
*/
private _performSave;
/**
* Atomic save that uses temporary copy to prevent corruption
*/
private _performAtomicSave;
/**
* Create a temporary copy of the original file
*/
private _createTempCopy;
/**
* Update VPM to use a different source file path
*/
private _updateVPMSourceFile;
/**
* Cleanup temporary copy
*/
private _cleanupTempCopy;
/**
* Update metadata after successful save
*/
private _updateMetadataAfterSave;
/**
* Check if file exists
*/
private _fileExists;
/**
* Method to manually mark buffer as clean (for testing/special cases)
*/
_markAsClean(): void;
/**
* Method to check if buffer has been modified
* @deprecated Use hasChanges() instead
*/
isModified(): boolean;
/**
* Method to check if buffer is detached
*/
isDetached(): boolean;
/**
* Method to check if buffer is clean
*/
isClean(): boolean;
/**
* Get total number of lines in the buffer (SYNCHRONOUS)
*/
getLineCount(): number;
/**
* Get information about a specific line (SYNCHRONOUS)
*/
getLineInfo(lineNumber: number): LineOperationResult | null;
/**
* Get information about multiple lines at once (SYNCHRONOUS)
*/
getMultipleLines(startLine: number, endLine: number): LineOperationResult[];
/**
* Convert byte address to line number (SYNCHRONOUS)
*/
getLineNumberFromAddress(byteAddress: number): number;
/**
* Convert line/character position to absolute byte position (SYNCHRONOUS)
*/
lineCharToBytePosition(pos: LineCharPosition): number;
/**
* Convert absolute byte position to line/character position (SYNCHRONOUS)
*/
byteToLineCharPosition(bytePos: number): LineCharPosition;
/**
* Ensure page containing address is loaded (ASYNC)
*/
seekAddress(address: number): Promise<boolean>;
/**
* Insert content with line/character position (convenience method)
*/
insertTextAtPosition(pos: LineCharPosition, text: string): Promise<{
newPosition: LineCharPosition;
}>;
/**
* Delete content between line/character positions (convenience method)
*/
deleteTextBetweenPositions(startPos: LineCharPosition, endPos: LineCharPosition): Promise<{
deletedText: string;
}>;
}
export { PagedBuffer, MissingDataRange, BufferState, FileChangeStrategy, NotificationType };
//# sourceMappingURL=paged-buffer.d.ts.map