Files
overleaf-cep/libraries/overleaf-editor-core/lib/file.js
T
Jakob AckermannandClaude Opus 5 04871d6049 [editor-core] extract more shared utils (#36954)
* [editor-core] share the blob hash and the doc-vs-file rule

The git blob hash and the rule that decides whether a file is a doc or a binary
file both have to reach the same answer in every service that writes to history,
so they move into overleaf-editor-core rather than being spelled out again on
each side.

blob_utils takes over lib/blob_string_length.js: hashing and the string-length
rule answered two halves of the same question -- what history needs to know
about content before it can store it -- and each carried the same warning about
staying off index.js, which is bundled for the browser. One module states it
once, and blobForFile joins them, describing content on disk as the blob it
amounts to. The hashing functions are flat rather than a namespace of their own:
in a module that also holds the string-length rule, a bare fromStream says
nothing about what it makes. history-v1's blob store and recover_zip follow the
module to its new name.

file_type_detector holds the doc-vs-file rule, Node-only and deep-imported for
the same reason. It takes textExtensions, editableFilenames and maxDocLength as
configuration rather than reading settings: the limit is web's 2 MiB and not
editor-core's own 3 MiB, and the surrogate check covers both halves of a pair
where editor-core's covers the high half.

buildSetContentOperations' test spelled the blob header out for itself, with the
separator as a literal NUL byte, which had git reading the file as binary. It
hashes through blobHashFromString now, so it does not spell the header at all.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* [editor-core] name the client a change came from on the origin itself

`EditorOrigin` carried an `editorId` that only an editor change could have. What
the id is for -- recognising a change again, so history does not apply a resend
twice and the client does not apply its own change back -- is a property of the
client that submitted it rather than of what it did, so it moves onto `Origin` as
an optional `historyClientId` and `EditorOrigin` goes.

- `Origin` takes `(kind, historyClientId)` and answers `getHistoryClientId()`;
  `dropHistoryClientId()` is what the chunk store uses to strip the id from all
  but a client's latest change, which now leaves the rest of the origin alone --
  a restore that a client submitted stays a restore.
- `toRaw` is built a layer at a time: the base writes the kind and the id, a
  subclass spreads that and adds the fields it owns.
- The named kinds are their own schemas and discriminate on `kind`, so a payload
  claiming one is checked against that shape and the error says what it got
  wrong. The catch-all cannot join them -- its kind is any string -- so it sits
  alongside and is refined to refuse the named kinds, which it used to swallow:
  `{kind: 'restore'}` validated as a kind and nothing else, then read back as a
  restore that recorded nothing about what it restored.
- `lib/origin/*.js` gains `// @ts-check`. Without it the annotations in there
  were decorative: the lazily required subclasses were `any`, so nothing handed
  to them was checked, and `fromRaw` narrows with `in` to drop the catch-all
  variant, which a kind check cannot.

The callers that stamp the id -- real-time's handshake flag, web's applyChange
body -- come with the rest of the branch.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* [editor-core] recognise a change a writer that is not an editor placed

The counterpart of `isSameEditorChange` for writers that are not an editor
client: an integration that commits a batch on a user's behalf has to recognise
that batch coming back, because a lost response does not say whether the commit
landed and resubmitting one that did applies its removes twice.

It compares the same three fields, and for the same reason -- a rebase rewrites a
change's operations but leaves its origin, authors and timestamp alone -- with
the timestamp compared as a point in time rather than as a string, so that two
spellings of the same instant cannot read as different changes. github-sync is
the first caller, and comes with the rest of the branch.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* [editor-core] load an editable file's content, or say it has none

Only an editable file has content: any other kind is bytes addressed by hash, and
hollow data records the size of content it does not have. Both answer
`getContent()` with null, so every caller that wants the content of a doc loaded
it, checked the data's class, and reached for its own error when the check failed.
`File#loadEager` does that once and answers the data that always has the content.

`buildSetContentOperations` takes a `ReadWriteBlobStore` -- everything but
looking a blob up by hash, which is all it takes to build operations over content
-- so a caller holding a store that cannot answer `getBlob` can still use it. Its
metadata argument is `FileMetadata` rather than `Object`, which is what the schema
already says a file's metadata is.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* [editor-core] say that a pair of operations that do not fit is unprocessable

compose and transform threw a bare Error when the two operations do not describe
the same content. Everything that answers a client for these -- history-v1's
import routes, the git-bridge push, project-history's resync -- decides on
UnprocessableError, so a bare Error reached them as an internal failure: a 500,
which reads as worth retrying, for a pair that fails the same way every time.
A client that resubmits on a 500 resubmits forever.

The guards that cannot be reached through the API keep their bare Error: a
TextOperation composed with something that is not one, and the branch whose
message says it should not happen.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* [history-v1] hash blobs with the rule editor-core holds

storage/lib/blob_hash.js was a bluebird-era implementation of the same git blob
hash editor-core holds, exported from the storage barrel and used across the
storage layer, the api and the tests. All of it reads the shared rule now, and
the test that existed only to check the copy is gone -- editor-core's suite
covers the same non-ASCII case.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
GitOrigin-RevId: 5a0c1e9a06170a0164c01a26a7bb2d205726d531
2026-09-17 12:07:15 +00:00

320 lines
8.2 KiB
JavaScript

// @ts-check
'use strict'
const _ = require('lodash')
const assert = require('check-types').assert
const OError = require('@overleaf/o-error')
const FileData = require('./file_data')
const HashFileData = require('./file_data/hash_file_data')
const StringFileData = require('./file_data/string_file_data')
/**
* @import Blob from "./blob"
* @import { BlobStore, ReadonlyBlobStore, RawFileData, RawFile, FileMetadata } from "./types"
* @import { StringFileRawData, CommentRawData } from "./types"
* @import CommentList from "./file_data/comment_list"
* @import TextOperation from "./operation/text_operation"
* @import TrackedChangeList from "./file_data/tracked_change_list"
*
* @typedef {{filterTrackedDeletes?: boolean}} FileGetContentOptions
*/
class NotEditableError extends OError {
constructor() {
super('File is not editable')
}
}
/**
* A file in a {@link Snapshot}. A file has both data and metadata. There
* are several classes of data that represent the various types of file
* data that are supported, namely text and binary, and also the various
* states that a file's data can be in, namely:
*
* 1. Hash only: all we know is the file's hash; this is how we encode file
* content in long term storage.
* 2. Lazily loaded: the hash of the file, its length, and its type are known,
* but its content is not loaded. Operations are cached for application
* later.
* 3. Eagerly loaded: the content of a text file is fully loaded into memory
* as a string.
* 4. Hollow: only the byte and/or UTF-8 length of the file are known; this is
* used to allow for validation of operations when editing collaboratively
* without having to keep file data in memory on the server.
*/
class File {
/**
* Blob hash for an empty file.
*
* Spelled out rather than read from `Blob.EMPTY_HASH`, which is the same value: a
* static field initialised from another module's class is `undefined` wherever the
* load order has that module still mid-load, and then everything comparing a hash
* against this fails without saying anything.
*
* @type {String}
*/
static EMPTY_FILE_HASH = 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391'
static NotEditableError = NotEditableError
/**
* @param {FileData} data
* @param {FileMetadata} [metadata]
*/
constructor(data, metadata) {
assert.instance(data, FileData, 'File: bad data')
this.data = data
/** @type {FileMetadata} */
this.metadata = {}
this.setMetadata(metadata || {})
}
/**
* @param {RawFile} raw
* @return {File|null}
*/
static fromRaw(raw) {
if (!raw) return null
return new File(FileData.fromRaw(raw), raw.metadata)
}
/**
* @param {string} hash
* @param {string} [rangesHash]
* @param {FileMetadata} [metadata]
* @return {File}
*/
static fromHash(hash, rangesHash, metadata) {
return new File(new HashFileData(hash, rangesHash), metadata)
}
/**
* @param {string} string
* @param {FileMetadata} [metadata]
* @return {File}
*/
static fromString(string, metadata) {
return new File(new StringFileData(string), metadata)
}
/**
* @param {number} byteLength
* @param {number} [stringLength]
* @param {FileMetadata} [metadata]
* @return {File}
*/
static createHollow(byteLength, stringLength, metadata) {
return new File(FileData.createHollow(byteLength, stringLength), metadata)
}
/**
* @param {Blob} blob
* @param {Blob} [rangesBlob]
* @param {FileMetadata} [metadata]
* @return {File}
*/
static createLazyFromBlobs(blob, rangesBlob, metadata) {
return new File(FileData.createLazyFromBlobs(blob, rangesBlob), metadata)
}
/**
* @returns {RawFile}
*/
toRaw() {
/** @type RawFile */
const rawFileData = this.data.toRaw()
storeRawMetadata(this.metadata, rawFileData)
return rawFileData
}
/**
* @returns {Record<string, number>}
*/
toStats() {
const stats = this.data.toStats()
if (!_.isEmpty(this.metadata)) {
stats.nMetadata = 1
// Note: Buffer does not exist in frontend. Use string length instead.
stats.metadataSize = JSON.stringify(this.metadata).length
}
return stats
}
/**
* Hexadecimal SHA-1 hash of the file's content, if known.
*
* @return {string | null | undefined}
*/
getHash() {
return this.data.getHash()
}
/**
* Hexadecimal SHA-1 hash of the ranges content (comments + tracked changes),
* if known.
*
* @return {string | null | undefined}
*/
getRangesHash() {
return this.data.getRangesHash()
}
/**
* The content of the file, if it is known and if this file has UTF-8 encoded
* content.
*
* @param {FileGetContentOptions} [opts]
* @return {string | null | undefined}
*/
getContent(opts = {}) {
return this.data.getContent(opts)
}
/**
* Whether this file has string content and is small enough to be edited using
* {@link TextOperation}s.
*
* @return {boolean | null | undefined} null if it is not currently known
*/
isEditable() {
return this.data.isEditable()
}
/**
* The length of the file's content in bytes, if known.
*
* @return {number | null | undefined}
*/
getByteLength() {
return this.data.getByteLength()
}
/**
* The length of the file's content in characters, if known.
*
* @return {number | null | undefined}
*/
getStringLength() {
return this.data.getStringLength()
}
/**
* Return the metadata object for this file.
*
* @return {FileMetadata}
*/
getMetadata() {
return this.metadata
}
/**
* Set the metadata object for this file.
*
* @param {FileMetadata} metadata
*/
setMetadata(metadata) {
assert.object(metadata, 'File: bad metadata')
this.metadata = metadata
}
/**
* Edit this file, if possible.
*
* @param {TextOperation} textOperation
*/
edit(textOperation) {
if (!this.data.isEditable()) throw new File.NotEditableError()
this.data.edit(textOperation)
}
/**
* Get the comments for this file.
*
* @return {CommentList}
*/
getComments() {
return this.data.getComments()
}
/**
* Get the tracked changes for this file.
* @return {TrackedChangeList}
*/
getTrackedChanges() {
return this.data.getTrackedChanges()
}
/**
* Clone a file.
*
* @return {File} a new object of the same type
*/
clone() {
return /** @type {File} */ (File.fromRaw(this.toRaw()))
}
/**
* Convert this file's data to the given kind. This may require us to load file
* size or content from the given blob store, so this is an asynchronous
* operation.
*
* @param {string} kind
* @param {ReadonlyBlobStore} blobStore
* @return {Promise.<File>} for this
*/
async load(kind, blobStore) {
const data = await this.data.load(kind, blobStore)
this.data = data
return this
}
/**
* Load the content of an editable file, answering with the data holding it.
*
* Only an editable file has content: any other kind is bytes addressed by
* hash, and hollow data records the size of content it does not have. Both
* answer {@link File#getContent} with null, which this rules out for its
* caller -- what it answers with is the data that always has the content.
*
* @param {ReadonlyBlobStore} blobStore
* @return {Promise<StringFileData>} the loaded data of this file
* @throws {NotEditableError} where the file is not an editable doc
*/
async loadEager(blobStore) {
await this.load('eager', blobStore)
if (!(this.data instanceof StringFileData)) {
throw new File.NotEditableError()
}
return this.data
}
/**
* Store the file's content in the blob store and return a raw file with
* the corresponding hash. As a side effect, make this object consistent with
* the hash.
*
* @param {BlobStore} blobStore
* @return {Promise<RawFile>} a raw HashFile
*/
async store(blobStore) {
/** @type RawFile */
const raw = await this.data.store(blobStore)
storeRawMetadata(this.metadata, raw)
return raw
}
}
/**
* @param {FileMetadata} metadata
* @param {RawFile} raw
*/
function storeRawMetadata(metadata, raw) {
if (!_.isEmpty(metadata)) {
raw.metadata = _.cloneDeep(metadata)
}
}
module.exports = File