@struktoai/mirage-core
Version:
A Unified Virtual Filesystem For AI Agents
133 lines • 5.99 kB
JavaScript
// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
import { CONDITION_SUPPORT } from "./constants.js";
import { requireSupported, writesConditioned } from "../../cache/context.js";
import { chunks } from "../../io/cooperative.js";
import { ByteSpool } from "../../io/spool.js";
import { closeQuietly } from "../../io/stream.js";
import { nativeCondition, writeCondition } from "../../cache/context.js";
import { record, startOp } from "../../observe/context.js";
import { FileType } from "../../types.js";
import { eisdir } from "../../errors/fs.js";
import { uploadStat } from "../../utils/upload.js";
import { refused, uploadFileVersion, uploadNewFile } from "./api.js";
import { BoxApiError } from "./client.js";
import { CONFLICT_STATUS } from "./constants.js";
import { liveOf } from "./fingerprint.js";
import { statFromItem } from "./readdir.js";
import { itemOf, liveItem, liveItemOf, parentFolder, pathParts } from "./resolve.js";
/**
* Upload `data` as a new file at `path`, plainly. The listing named nothing
* there; Box holding a file by that name now means the listing is older than
* it, so the file found live gets a new version, as a write to a listed file
* would. Mirrors Python's `_upload_new`.
*/
async function uploadNew(accessor, path, data, folderId) {
const tm = accessor.tokenManager;
const parts = pathParts(path);
try {
return await uploadNewFile(tm, folderId, parts[parts.length - 1] ?? '', data);
}
catch (err) {
if (!(err instanceof BoxApiError) ||
err.status !== CONFLICT_STATUS ||
(err.conflict !== null && err.conflict !== 'file'))
throw err;
const found = await liveItem(accessor, path, null);
if (found?.type !== 'file')
throw err;
return uploadFileVersion(tm, found.id, found.name, data, null);
}
}
/**
* Upload a new file, or a new version of an existing one. A held version goes
* out as the file's etag. A stream is spooled first, as an upload sends its
* length; `signal` stops it. Answers the stored file's stat, null for a reply
* that names none. Mirrors Python's `write`.
*/
export async function write(accessor, path, data, handed = {}, signal) {
if (!(data instanceof Uint8Array) && !(data instanceof ByteSpool)) {
const spool = new ByteSpool();
try {
await spool.fill(chunks(data, signal));
return await write(accessor, path, spool, handed);
}
finally {
await spool.close();
}
}
const condition = await writeCondition(path, 'put');
return uploadPrepared(accessor, path, data, condition, handed);
}
export async function replace(accessor, request, handed = {}, signal) {
try {
requireSupported(CONDITION_SUPPORT, 'box', request.path, 'put', request.condition);
}
catch (error) {
await closeQuietly(request.body);
throw error;
}
if (!(request.body instanceof Uint8Array)) {
const spool = new ByteSpool();
try {
await spool.fill(chunks(request.body, signal));
return await uploadPrepared(accessor, request.path, spool, request.condition, handed);
}
finally {
await spool.close();
}
}
return uploadPrepared(accessor, request.path, request.body, request.condition, handed);
}
async function uploadPrepared(accessor, path, data, cond, handed = {}) {
const parts = pathParts(path);
if (parts.length === 0 || handed.entry?.type === FileType.DIRECTORY)
throw eisdir(path.virtual);
const tm = accessor.tokenManager;
requireSupported(CONDITION_SUPPORT, 'box', path, 'put', cond);
const timer = startOp();
// What is there now: the listed row can be older than the path's file, and
// older than the read a held version came from.
const existing = writesConditioned(path) || cond.kind !== 'any'
? await liveItem(accessor, path, itemOf(handed.entry))
: await liveItemOf(accessor, path, handed.entry);
const etag = await nativeCondition(path, cond, liveOf(existing), 'put');
let reply;
try {
if (existing?.type === 'file') {
// Overwrite uploads a new version under the same id, keeping Box's own
// name so a box-native file isn't renamed with the vfs suffix.
reply = await uploadFileVersion(tm, existing.id, existing.name, data, etag);
}
else if (!writesConditioned(path) && cond.kind === 'any') {
reply = await uploadNew(accessor, path, data, parentFolder(accessor, path, handed.parent));
}
else {
reply = await uploadNewFile(tm, parentFolder(accessor, path, handed.parent), parts[parts.length - 1] ?? '', data);
}
}
catch (err) {
throw (await refused(path, err, cond, etag)) ?? err;
}
const entries = typeof reply === 'object' && reply !== null && !Array.isArray(reply)
? reply.entries
: undefined;
const first = Array.isArray(entries) ? entries[0] : undefined;
const stored = uploadStat(first, statFromItem, path.virtual);
record('write', path.virtual, 'box', data instanceof ByteSpool ? data.size : data.length, timer, {
fingerprint: stored?.fingerprint ?? null,
});
return stored;
}
//# sourceMappingURL=write.js.map