{"version":3,"file":"index.cjs","sources":["../../../../packages/php-wasm/fs-journal/src/lib/fs-journal.ts"],"sourcesContent":["import type { PHP, UniversalPHP } from '@php-wasm/universal';\nimport { __private__dont__use } from '@php-wasm/universal';\nimport { Semaphore, basename, isParentOf, joinPaths } from '@php-wasm/util';\nimport { logger } from '@php-wasm/logger';\n\nexport type EmscriptenFS = any;\n\n/**\n * Represents a stream in the Emscripten file system.\n */\nexport type EmscriptenFSStream = {\n\t/** The path of the node associated with this stream. */\n\tpath: string;\n\t/** The node associated with the stream. */\n\tnode: EmscriptenFSNode;\n};\n\n/**\n * Represents a node in the Emscripten file system.\n */\nexport type EmscriptenFSNode = {\n\t/**\n\t * The name of the file or directory.\n\t */\n\tname: string;\n\t/**\n\t * A binary flag encoding information about this note,\n\t * e.g. whether it's file or a directory.\n\t */\n\tmode: number;\n\t/**\n\t * A dictionary of functions representing operations\n\t * that can be performed on the node.\n\t */\n\tnode_ops: any;\n};\n\n/**\n * Represents the type of node in PHP file system.\n */\nexport type FSNodeType = 'file' | 'directory' | 'symlink';\n\n/**\n * Represents an update operation on a file system node.\n */\nexport type UpdateFileOperation = {\n\t/** The type of operation being performed. */\n\toperation: 'WRITE';\n\t/** The path of the node being updated. */\n\tpath: string;\n\t/** Optional. The new contents of the file. */\n\tdata?: Uint8Array;\n\tnodeType: 'file';\n};\n\n/**\n * Represents creation of a file, directory, or symbolic link.\n */\nexport type CreateOperation = {\n\t/** The type of operation being performed. */\n\toperation: 'CREATE';\n\t/** The path of the node being created. */\n\tpath: string;\n\t/** The type of the node being created. */\n\tnodeType: FSNodeType;\n} & (\n\t| { nodeType: 'file' | 'directory' }\n\t| {\n\t\t\tnodeType: 'symlink';\n\t\t\t/** The link target as written, without resolving relative paths. */\n\t\t\ttarget: string;\n\t  }\n);\n\nexport type DeleteOperation = {\n\t/** The type of operation being performed. */\n\toperation: 'DELETE';\n\t/** The path of the node being updated. */\n\tpath: string;\n\t/** The type of the node being updated. */\n\tnodeType: FSNodeType;\n};\n\n/**\n * Represents a rename operation on a file, directory, or symbolic link.\n */\nexport type RenameOperation = {\n\t/** The type of operation being performed. */\n\toperation: 'RENAME';\n\t/** The original path of the file or directory being renamed. */\n\tpath: string;\n\t/** The new path of the file or directory after the rename operation. */\n\ttoPath: string;\n\t/** The type of node being renamed (file, directory, or symbolic link). */\n\tnodeType: FSNodeType;\n} & (\n\t| { nodeType: 'file' | 'directory' }\n\t| {\n\t\t\tnodeType: 'symlink';\n\t\t\t/** The link target as written, without resolving relative paths. */\n\t\t\ttarget: string;\n\t  }\n);\n\n/**\n * Represents a node in the file system.\n */\nexport type FSNode = {\n\t/** The name of this file or directory. */\n\tname: string;\n\t/** The type of this node (file, directory, or symbolic link). */\n\ttype: FSNodeType;\n\t/** The contents of the file, if it is a file and it's stored in memory. */\n\tcontents?: string;\n\t/** The child nodes of the directory, if it is a directory. */\n\tchildren?: FSNode[];\n};\n\nexport type FilesystemOperation =\n\t| CreateOperation\n\t| UpdateFileOperation\n\t| DeleteOperation\n\t| RenameOperation;\n\n/**\n * Reports successful filesystem changes at or below `fsRoot`.\n *\n * Holds records from nested FS calls until the outer call succeeds. A move\n * into this root records the source tree before it moves, using destination\n * paths. Links carry their raw targets rather than their targets' contents.\n *\n * Hooks follow PHP runtime restarts. The returned function stops listening\n * for runtime changes and restores the current runtime's original FS methods.\n */\nexport function journalFSEvents(\n\tphp: PHP,\n\tfsRoot: string,\n\tonEntry: (entry: FilesystemOperation) => void = () => {}\n) {\n\tfunction bindToCurrentRuntime() {\n\t\tfsRoot = normalizePath(fsRoot);\n\t\tconst FS = php[__private__dont__use].FS;\n\t\tconst pendingBatches: FilesystemOperation[][] = [];\n\t\tconst FSHooks = createFSHooks(FS, (entry: FilesystemOperation) => {\n\t\t\tconst batch = pendingBatches[pendingBatches.length - 1];\n\t\t\t// Only journal entries inside the specified root directory.\n\t\t\tif (isParentOf(fsRoot, entry.path)) {\n\t\t\t\tbatch.push(entry);\n\t\t\t} else if (\n\t\t\t\tentry.operation === 'RENAME' &&\n\t\t\t\tisParentOf(fsRoot, entry.toPath)\n\t\t\t) {\n\t\t\t\tfor (const op of recordExistingPath(\n\t\t\t\t\tphp,\n\t\t\t\t\tentry.path,\n\t\t\t\t\tentry.toPath\n\t\t\t\t)) {\n\t\t\t\t\tbatch.push(op);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t/**\n\t\t * Override the original FS functions with ones running the hooks.\n\t\t * We could use a Proxy object here if the Emscripten JavaScript module\n\t\t * did not use hard-coded references to the FS object.\n\t\t */\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\t\tconst originalFunctions: Record<string, Function> = {};\n\t\tfor (const [name] of Object.entries(FSHooks)) {\n\t\t\toriginalFunctions[name] = FS[name];\n\t\t}\n\n\t\t/**\n\t\t * Wraps FS calls with a stack of batches for their pending records.\n\t\t * Cleanup always pops the batch. Publishing follows the try/finally, so a\n\t\t * thrown error discards that call's records and leaves the stack ready for\n\t\t * the next call. Successful nested calls append to their parent's batch.\n\t\t */\n\t\t// eslint-disable-next-line no-inner-declarations\n\t\tfunction bind() {\n\t\t\tfor (const [name, hook] of Object.entries(FSHooks)) {\n\t\t\t\tFS[name] = function (...args: any[]) {\n\t\t\t\t\tconst batch: FilesystemOperation[] = [];\n\t\t\t\t\tpendingBatches.push(batch);\n\t\t\t\t\tlet result;\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// Moves need the old path while it still exists. Keep their\n\t\t\t\t\t\t// records pending until the call succeeds, including nested\n\t\t\t\t\t\t// FS calls, so a failed move cannot erase a saved directory.\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\thook(...args);\n\t\t\t\t\t\tresult = originalFunctions[name].apply(this, args);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tpendingBatches.pop();\n\t\t\t\t\t}\n\t\t\t\t\tconst parentBatch =\n\t\t\t\t\t\tpendingBatches[pendingBatches.length - 1];\n\t\t\t\t\tif (parentBatch) parentBatch.push(...batch);\n\t\t\t\t\telse for (const entry of batch) onEntry(entry);\n\t\t\t\t\treturn result;\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\t// eslint-disable-next-line no-inner-declarations\n\t\tfunction unbind() {\n\t\t\t// Restore the original FS functions.\n\t\t\tfor (const [name, fn] of Object.entries(originalFunctions)) {\n\t\t\t\tphp[__private__dont__use].FS[name] = fn;\n\t\t\t}\n\t\t}\n\n\t\tphp[__private__dont__use].journal = {\n\t\t\tbind,\n\t\t\tunbind,\n\t\t};\n\t\tbind();\n\t}\n\tphp.addEventListener('runtime.initialized', bindToCurrentRuntime);\n\tif (php[__private__dont__use]) {\n\t\tbindToCurrentRuntime();\n\t}\n\n\tfunction unbindFromOldRuntime() {\n\t\tphp[__private__dont__use].journal.unbind();\n\t\tdelete php[__private__dont__use].journal;\n\t}\n\tphp.addEventListener('runtime.beforeExit', unbindFromOldRuntime);\n\n\treturn function unbind() {\n\t\tphp.removeEventListener('runtime.initialized', bindToCurrentRuntime);\n\t\tphp.removeEventListener('runtime.beforeExit', unbindFromOldRuntime);\n\t\treturn php[__private__dont__use].journal.unbind();\n\t};\n}\n\n/**\n * Builds observers that describe FS calls without changing the filesystem.\n *\n * All hooks run before the original call, while source entries still exist.\n * Create hooks resolve only the parent because the new node may not exist yet.\n * `journalFSEvents` buffers these records and publishes them only on success.\n */\nconst createFSHooks = (\n\tFS: EmscriptenFS,\n\trecordEntry: (entry: FilesystemOperation) => void = () => {}\n) => ({\n\twrite(stream: EmscriptenFSStream) {\n\t\trecordEntry({\n\t\t\toperation: 'WRITE',\n\t\t\tpath: stream.path,\n\t\t\tnodeType: 'file',\n\t\t});\n\t},\n\ttruncate(path: string) {\n\t\tlet node;\n\t\tif (typeof path == 'string') {\n\t\t\tconst lookup = FS.lookupPath(path, {\n\t\t\t\tfollow: true,\n\t\t\t});\n\t\t\tnode = lookup.node;\n\t\t} else {\n\t\t\tnode = path;\n\t\t}\n\t\trecordEntry({\n\t\t\toperation: 'WRITE',\n\t\t\tpath: FS.getPath(node),\n\t\t\tnodeType: 'file',\n\t\t});\n\t},\n\tunlink(path: string) {\n\t\tconst lookup = FS.lookupPath(path, { follow: false });\n\t\trecordEntry({\n\t\t\toperation: 'DELETE',\n\t\t\tpath: lookup.path,\n\t\t\tnodeType: FS.isLink(lookup.node.mode) ? 'symlink' : 'file',\n\t\t});\n\t},\n\t/**\n\t * Records link creation before the original FS.symlink call.\n\t * Resolves parent links without looking up the new node or its target.\n\t * Keeps the raw target, even if it is broken or points to another link,\n\t * so the journal can outlive the link itself.\n\t */\n\tsymlink(target: string, path: string) {\n\t\trecordEntry({\n\t\t\toperation: 'CREATE',\n\t\t\tpath: resolveEntryPath(FS, path),\n\t\t\tnodeType: 'symlink',\n\t\t\ttarget,\n\t\t});\n\t},\n\tmknod(path: string, mode: number) {\n\t\tif (FS.isFile(mode)) {\n\t\t\trecordEntry({\n\t\t\t\toperation: 'CREATE',\n\t\t\t\tpath: resolveEntryPath(FS, path),\n\t\t\t\tnodeType: 'file',\n\t\t\t});\n\t\t}\n\t},\n\tmkdir(path: string) {\n\t\trecordEntry({\n\t\t\toperation: 'CREATE',\n\t\t\tpath: resolveEntryPath(FS, path),\n\t\t\tnodeType: 'directory',\n\t\t});\n\t},\n\trmdir(path: string) {\n\t\trecordEntry({\n\t\t\toperation: 'DELETE',\n\t\t\tpath: resolveEntryPath(FS, path),\n\t\t\tnodeType: 'directory',\n\t\t});\n\t},\n\trename(old_path: string, new_path: string) {\n\t\ttry {\n\t\t\tconst oldLookup = FS.lookupPath(old_path, {\n\t\t\t\tfollow: false,\n\t\t\t});\n\t\t\tconst newParentPath = FS.lookupPath(new_path, {\n\t\t\t\tparent: true,\n\t\t\t}).path;\n\n\t\t\trecordEntry({\n\t\t\t\toperation: 'RENAME',\n\t\t\t\t...(FS.isLink(oldLookup.node.mode)\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tnodeType: 'symlink' as const,\n\t\t\t\t\t\t\ttarget: FS.readlink(oldLookup.path),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tnodeType: FS.isDir(oldLookup.node.mode)\n\t\t\t\t\t\t\t\t? ('directory' as const)\n\t\t\t\t\t\t\t\t: ('file' as const),\n\t\t\t\t\t\t}),\n\t\t\t\tpath: oldLookup.path,\n\t\t\t\ttoPath: joinPaths(newParentPath, basename(new_path)),\n\t\t\t});\n\t\t} catch {\n\t\t\t// We're running a bunch of FS lookups that may fail at this point.\n\t\t\t// Let's ignore the failures and let the actual rename operation\n\t\t\t// fail if it needs to.\n\t\t}\n\t},\n});\n\n/**\n * Resolves parent links while keeping the final entry, which may not exist yet.\n *\n * For example, creating `/site/alias/new` below `alias -> real` must record\n * `/site/real/new`. If lookup fails, leaves the path unchanged so the original\n * FS call reports its own error. Failed calls do not publish journal entries.\n */\nfunction resolveEntryPath(FS: EmscriptenFS, path: string) {\n\ttry {\n\t\treturn joinPaths(\n\t\t\tFS.lookupPath(path, { parent: true }).path,\n\t\t\tbasename(path)\n\t\t);\n\t} catch {\n\t\treturn path;\n\t}\n}\n\n/**\n * Replays a list of filesystem operations on a PHP instance.\n *\n * @param php\n * @param entries\n */\nexport function replayFSJournal(php: PHP, entries: FilesystemOperation[]) {\n\t// We need to restore the original functions to the FS object\n\t// before proceeding, or each replayed FS operation will be journaled.\n\t//\n\t// Unfortunately we can't just call the non-journaling versions directly,\n\t// because they call other low-level FS functions like `FS.mkdir()`\n\t// and will trigger the journaling hooks anyway.\n\tphp[__private__dont__use].journal.unbind();\n\ttry {\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.operation === 'CREATE') {\n\t\t\t\tif (entry.nodeType === 'file') {\n\t\t\t\t\tphp.writeFile(entry.path, ' ');\n\t\t\t\t} else if (entry.nodeType === 'symlink') {\n\t\t\t\t\tphp.symlink(entry.target, entry.path);\n\t\t\t\t} else {\n\t\t\t\t\tphp.mkdir(entry.path);\n\t\t\t\t}\n\t\t\t} else if (entry.operation === 'DELETE') {\n\t\t\t\tif (entry.nodeType !== 'directory') {\n\t\t\t\t\tphp.unlink(entry.path);\n\t\t\t\t} else {\n\t\t\t\t\tphp.rmdir(entry.path);\n\t\t\t\t}\n\t\t\t} else if (entry.operation === 'WRITE') {\n\t\t\t\tphp.writeFile(entry.path, entry.data!);\n\t\t\t} else if (entry.operation === 'RENAME') {\n\t\t\t\tphp.mv(entry.path, entry.toPath);\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tphp[__private__dont__use].journal.bind();\n\t}\n}\n\n/**\n * Describes an existing source tree as creations at the destination path.\n *\n * Called before a move into the journal root, while `fromPath` still exists.\n * Traverses directories but records links without following their targets.\n * File WRITE records contain only paths, not a snapshot of the bytes; callers\n * read the destination contents later. These records may be published only\n * after the move succeeds.\n */\nexport function* recordExistingPath(\n\tphp: PHP,\n\tfromPath: string,\n\ttoPath: string\n): Generator<FilesystemOperation> {\n\tconst FS = php[__private__dont__use].FS;\n\tconst node = FS.lookupPath(fromPath, { follow: false }).node;\n\tif (FS.isLink(node.mode)) {\n\t\tyield {\n\t\t\toperation: 'CREATE',\n\t\t\tpath: toPath,\n\t\t\tnodeType: 'symlink',\n\t\t\ttarget: php.readlink(fromPath),\n\t\t};\n\t} else if (FS.isDir(node.mode)) {\n\t\t// The rename operation moved a directory from outside root directory\n\t\t// into the root directory. We need to traverse the entire tree\n\t\t// and provide a create operation for each file and directory.\n\t\tyield {\n\t\t\toperation: 'CREATE',\n\t\t\tpath: toPath,\n\t\t\tnodeType: 'directory',\n\t\t};\n\t\tfor (const file of php.listFiles(fromPath)) {\n\t\t\tyield* recordExistingPath(\n\t\t\t\tphp,\n\t\t\t\tjoinPaths(fromPath, file),\n\t\t\t\tjoinPaths(toPath, file)\n\t\t\t);\n\t\t}\n\t} else {\n\t\t// The rename operation moved a file from outside root directory\n\t\t// into the root directory. Let's rewrite it as a create operation.\n\t\tyield {\n\t\t\toperation: 'CREATE',\n\t\t\tpath: toPath,\n\t\t\tnodeType: 'file',\n\t\t};\n\t\tyield {\n\t\t\toperation: 'WRITE',\n\t\t\tnodeType: 'file',\n\t\t\tpath: toPath,\n\t\t};\n\t}\n}\n\nfunction normalizePath(path: string) {\n\treturn path.replace(/\\/$/, '').replace(/\\/\\/+/g, '/');\n}\n\n/**\n * Normalizes a list of filesystem operations to remove\n * redundant operations.\n *\n * This is crucial because the journal doesn't store the file contents\n * on write, but only the information that the write happened. We only\n * read the contents of the file on flush. However, at that time the file\n * could have been moved to another location so we need this function to\n * rewrite the journal to reflect the current file location. Only then\n * will the hydrateUpdateFileOps() function be able to do its job.\n *\n * @param journal The original journal.\n * @returns The normalized journal.\n */\nexport function normalizeFilesystemOperations(\n\tinput: FilesystemOperation[]\n): FilesystemOperation[] {\n\tlet journal = input;\n\twhile (true) {\n\t\tconst substitutions: Record<number, any> = {};\n\t\t// Most download records only affect one file. Looking up that path\n\t\t// avoids comparing every chunk write with every other file in the site.\n\t\t// Rebuild after each substitution pass because renames change paths.\n\t\tconst entriesByPath = new Map<string, number[]>();\n\t\tconst directoryRenames: number[] = [];\n\t\tfor (let i = 0; i < journal.length; i++) {\n\t\t\tconst entry = journal[i];\n\t\t\tconst path =\n\t\t\t\tentry.operation === 'RENAME' ? entry.toPath : entry.path;\n\t\t\tif (!entriesByPath.has(path)) entriesByPath.set(path, []);\n\t\t\tentriesByPath.get(path)!.push(i);\n\t\t\tif (\n\t\t\t\tentry.operation === 'RENAME' &&\n\t\t\t\tentry.nodeType === 'directory'\n\t\t\t) {\n\t\t\t\tdirectoryRenames.push(i);\n\t\t\t}\n\t\t}\n\t\tfor (let i = journal.length - 1; i >= 0; i--) {\n\t\t\tconst entry = journal[i];\n\t\t\tlet candidates: Iterable<number>;\n\t\t\tif (\n\t\t\t\tentry.operation === 'RENAME' &&\n\t\t\t\tentry.nodeType === 'directory'\n\t\t\t) {\n\t\t\t\t// Moving a directory may rewrite any earlier descendant path.\n\t\t\t\tcandidates = (function* () {\n\t\t\t\t\tfor (let j = i - 1; j >= 0; j--) {\n\t\t\t\t\t\tyield j;\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t} else {\n\t\t\t\tlet matchingEntries = entriesByPath.get(entry.path) ?? [];\n\t\t\t\tif (entry.operation === 'RENAME') {\n\t\t\t\t\t// Keep detecting unsupported rename chains through a parent.\n\t\t\t\t\tmatchingEntries = [\n\t\t\t\t\t\t...new Set([...matchingEntries, ...directoryRenames]),\n\t\t\t\t\t];\n\t\t\t\t}\n\t\t\t\tcandidates = [...matchingEntries].sort((a, b) => b - a);\n\t\t\t}\n\t\t\t// Substitutions depend on visiting earlier records newest-first.\n\t\t\tfor (const j of candidates) {\n\t\t\t\tif (j >= i) continue;\n\t\t\t\tconst formerType = checkRelationship(journal[i], journal[j]);\n\t\t\t\tif (formerType === 'none') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst latter = journal[i];\n\t\t\t\tconst former = journal[j];\n\t\t\t\tif (\n\t\t\t\t\tlatter.operation === 'RENAME' &&\n\t\t\t\t\tformer.operation === 'RENAME'\n\t\t\t\t) {\n\t\t\t\t\t// Normalizing a double rename is a complex scenario so let's just give\n\t\t\t\t\t// up. There's just too many possible scenarios to handle.\n\t\t\t\t\t//\n\t\t\t\t\t// For example, the following scenario may not be possible to normalize:\n\t\t\t\t\t// RENAME /dir_a /dir_b\n\t\t\t\t\t// RENAME /dir_b/subdir /dir_c\n\t\t\t\t\t// RENAME /dir_b /dir_d\n\t\t\t\t\t//\n\t\t\t\t\t// Similarly, how should we normalize the following list?\n\t\t\t\t\t// CREATE_FILE /file\n\t\t\t\t\t// CREATE_DIR /dir_a\n\t\t\t\t\t// RENAME /file /dir_a/file\n\t\t\t\t\t// RENAME /dir_a /dir_b\n\t\t\t\t\t// RENAME /dir_b/file /dir_b/file_2\n\t\t\t\t\t//\n\t\t\t\t\t// The shortest way to recreate the same structure would be this:\n\t\t\t\t\t// CREATE_DIR /dir_b\n\t\t\t\t\t// CREATE_FILE /dir_b/file_2\n\t\t\t\t\t//\n\t\t\t\t\t// But that's not a straightforward transformation so let's just not\n\t\t\t\t\t// handle it for now.\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t'[FS Journal] Normalizing a double rename is not yet supported:',\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcurrent: latter,\n\t\t\t\t\t\t\tlast: former,\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tformer.operation === 'CREATE' ||\n\t\t\t\t\tformer.operation === 'WRITE'\n\t\t\t\t) {\n\t\t\t\t\tif (latter.operation === 'RENAME') {\n\t\t\t\t\t\tif (formerType === 'same_node') {\n\t\t\t\t\t\t\t// Creating a node and then renaming it is equivalent to creating\n\t\t\t\t\t\t\t// it in the new location.\n\t\t\t\t\t\t\tsubstitutions[j] = [];\n\t\t\t\t\t\t\tsubstitutions[i] = [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t...former,\n\t\t\t\t\t\t\t\t\tpath: latter.toPath,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t...(substitutions[i] || []).filter(\n\t\t\t\t\t\t\t\t\t(op: FilesystemOperation) => op !== latter\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t];\n\t\t\t\t\t\t} else if (formerType === 'descendant') {\n\t\t\t\t\t\t\t// Creating a node and then renaming its parent directory is\n\t\t\t\t\t\t\t// equivalent to creating it in the new location.\n\t\t\t\t\t\t\tsubstitutions[j] = [];\n\t\t\t\t\t\t\tconst previous = substitutions[i] || [latter];\n\t\t\t\t\t\t\tsubstitutions[i] = [\n\t\t\t\t\t\t\t\t// Keep the directory move before its rewritten children.\n\t\t\t\t\t\t\t\t// Otherwise journal replay writes to a parent that does not exist.\n\t\t\t\t\t\t\t\t...(previous[0] === latter ? [latter] : []),\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t...former,\n\t\t\t\t\t\t\t\t\tpath: joinPaths(\n\t\t\t\t\t\t\t\t\t\tlatter.toPath,\n\t\t\t\t\t\t\t\t\t\tformer.path.substring(\n\t\t\t\t\t\t\t\t\t\t\tlatter.path.length\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t...previous.filter(\n\t\t\t\t\t\t\t\t\t(op: FilesystemOperation) => op !== latter\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t];\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (\n\t\t\t\t\t\tlatter.operation === 'WRITE' &&\n\t\t\t\t\t\tformerType === 'same_node'\n\t\t\t\t\t) {\n\t\t\t\t\t\t// Updating the same node twice is equivalent to updating it once\n\t\t\t\t\t\t// at the later time.\n\t\t\t\t\t\tsubstitutions[j] = [];\n\t\t\t\t\t} else if (\n\t\t\t\t\t\tlatter.operation === 'DELETE' &&\n\t\t\t\t\t\tformerType === 'same_node'\n\t\t\t\t\t) {\n\t\t\t\t\t\t// A CREATE/WRITE followed by a DELETE on the same node.\n\t\t\t\t\t\t// The CREATE/WRITE is redundant.\n\t\t\t\t\t\tsubstitutions[j] = [];\n\n\t\t\t\t\t\t// The DELETE is redundant only if the node was created\n\t\t\t\t\t\t// in this journal.\n\t\t\t\t\t\tif (former.operation === 'CREATE') {\n\t\t\t\t\t\t\tsubstitutions[i] = [];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (Object.keys(substitutions).length === 0) {\n\t\t\treturn journal;\n\t\t}\n\n\t\tjournal = journal.flatMap((op, index) => {\n\t\t\tif (!(index in substitutions)) {\n\t\t\t\treturn [op];\n\t\t\t}\n\t\t\treturn substitutions[index];\n\t\t});\n\t}\n}\n\ntype RelatedOperationInfo = 'same_node' | 'ancestor' | 'descendant' | 'none';\nfunction checkRelationship(\n\tlatter: FilesystemOperation,\n\tformer: FilesystemOperation\n): RelatedOperationInfo {\n\tconst latterPath = latter.path;\n\tconst latterIsDir =\n\t\tlatter.operation !== 'WRITE' && latter.nodeType === 'directory';\n\tconst formerIsDir =\n\t\tformer.operation !== 'WRITE' && former.nodeType === 'directory';\n\tconst formerPath =\n\t\tformer.operation === 'RENAME' ? former.toPath : former.path;\n\n\tif (formerPath === latterPath) {\n\t\treturn 'same_node';\n\t} else if (formerIsDir && latterPath.startsWith(formerPath + '/')) {\n\t\treturn 'ancestor';\n\t} else if (latterIsDir && formerPath.startsWith(latterPath + '/')) {\n\t\treturn 'descendant';\n\t}\n\treturn 'none';\n}\n\n/**\n * Populates each WRITE operation with the contents of\n * said file.\n *\n * Mutates the original array.\n *\n * @param php\n * @param entries\n */\nexport async function hydrateUpdateFileOps(\n\tphp: UniversalPHP,\n\tentries: FilesystemOperation[]\n) {\n\tconst updateFileOps = entries.filter(\n\t\t(op): op is UpdateFileOperation => op.operation === 'WRITE'\n\t);\n\tconst updates = updateFileOps.map((op) => hydrateOp(php, op));\n\tawait Promise.all(updates);\n\treturn entries;\n}\n\nconst hydrateLock = new Semaphore({ concurrency: 15 });\nasync function hydrateOp(php: UniversalPHP, op: UpdateFileOperation) {\n\tconst release = await hydrateLock.acquire();\n\n\t// There is a race condition here:\n\t// The file could have been removed from the filesystem\n\t// between the flush() call and now. If that happens, we won't\n\t// be able to read it here.\n\t//\n\t// If the file was DELETEd, we're fine as the next flush() will\n\t// propagate the DELETE operation.\n\t//\n\t// If the file was RENAMEd, we're in trouble as we're about to\n\t// tell the other peer to create an empty file and the next\n\t// flush() will rename that empty file.\n\t//\n\t// This issue requires a particular timing and is unlikely to ever happen,\n\t// but is definitely possible. We could mitigate it by either:\n\t//\n\t// * Peeking into the buffered journal entries since the last flush() to\n\t//   source the file path from\n\t// * Storing the data at the journaling stage instead of the flush() stage,\n\t//   (and using potentially a lot of additional memory to keep track of all\n\t//    the intermediate stages)\n\t//\n\t// For now, htough, let's just add error logging and keep an eye on this\n\t// to see if this actually ever happens.\n\ttry {\n\t\top.data = await php.readFileAsBuffer(op.path);\n\t} catch (e) {\n\t\t// Log the error but don't throw.\n\t\tlogger.warn(\n\t\t\t`Journal failed to hydrate a file on flush: the ` +\n\t\t\t\t`path ${op.path} no longer exists`\n\t\t);\n\t\tlogger.error(e);\n\t}\n\n\trelease();\n}\n"],"names":["journalFSEvents","php","fsRoot","onEntry","bindToCurrentRuntime","normalizePath","FS","__private__dont__use","pendingBatches","FSHooks","createFSHooks","entry","batch","isParentOf","op","recordExistingPath","originalFunctions","name","bind","hook","args","result","parentBatch","unbind","fn","unbindFromOldRuntime","recordEntry","stream","path","node","lookup","target","resolveEntryPath","mode","old_path","new_path","oldLookup","newParentPath","joinPaths","basename","replayFSJournal","entries","fromPath","toPath","file","normalizeFilesystemOperations","input","journal","substitutions","entriesByPath","directoryRenames","i","candidates","j","matchingEntries","a","b","formerType","checkRelationship","latter","former","logger","previous","index","latterPath","latterIsDir","formerIsDir","formerPath","hydrateUpdateFileOps","updates","hydrateOp","hydrateLock","Semaphore","release","e"],"mappings":"iLAsIO,SAASA,EACfC,EACAC,EACAC,EAAgD,IAAM,CAAC,EACtD,CACD,SAASC,GAAuB,CAC/BF,EAASG,EAAcH,CAAM,EAC7B,MAAMI,EAAKL,EAAIM,EAAAA,oBAAoB,EAAE,GAC/BC,EAA0C,CAAA,EAC1CC,EAAUC,EAAcJ,EAAKK,GAA+B,CACjE,MAAMC,EAAQJ,EAAeA,EAAe,OAAS,CAAC,EAEtD,GAAIK,aAAWX,EAAQS,EAAM,IAAI,EAChCC,EAAM,KAAKD,CAAK,UAEhBA,EAAM,YAAc,UACpBE,EAAAA,WAAWX,EAAQS,EAAM,MAAM,EAE/B,UAAWG,KAAMC,EAChBd,EACAU,EAAM,KACNA,EAAM,MAAA,EAENC,EAAM,KAAKE,CAAE,CAGhB,CAAC,EAQKE,EAA8C,CAAA,EACpD,SAAW,CAACC,CAAI,IAAK,OAAO,QAAQR,CAAO,EAC1CO,EAAkBC,CAAI,EAAIX,EA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