← Files Flows by plugin.spaceARCHIVED FILE

lib/library.mjs

15 KB · Nov 30, 2026 · 00:17 UTC

↓ Download file

import { flowUserRoles } from './user-roles.mjs';
import { adoptLibrary, flowsEnv, isFlowFile } from './brand-compat.mjs';
import { createHash } from 'node:crypto';
import { readFile, readdir, realpath, stat } from 'node:fs/promises';
import { basename, dirname, join, resolve } from 'node:path';
import { homedir } from 'node:os';
import { readDocument } from './document.mjs';
import { withLibraryLock, writeState } from './local-state.mjs';
import { createLocalAccess, defaultCloudOrigin } from './local-access.mjs';
import { createCapturePreferences } from './capture-preferences.mjs';
import { applicationWithIcon } from './project-icon.mjs';

export const defaultLibraryRoot = () => flowsEnv('LIBRARY_DIR') || adoptLibrary(join(homedir(), '.local', 'share'));
const key = value => createHash('sha256').update(value).digest('hex').slice(0, 24);
export async function inferProjectRoot(file, project) {
  let root = project ? await realpath(project) : dirname(file);
  if (!project) {
    let candidate = root;
    while (true) {
      if (await stat(join(candidate, 'package.json')).catch(() => false) || await stat(join(candidate, '.git')).catch(() => false)) { root = candidate; break; }
      const parent = dirname(candidate);
      if (parent === candidate) { if (basename(root) === 'flows') root = dirname(root); break; }
      candidate = parent;
    }
  }
  return root;
}
export async function inferApplication(file, project, name) {
  const root = await inferProjectRoot(file, project);
  let packageName;
  try { packageName = JSON.parse(await readFile(join(root, 'package.json'), 'utf8')).name; } catch { /* Folder name is sufficient. */ }
  return { id: key(root), name: (name?.trim() || (typeof packageName === 'string' && packageName.trim()) || basename(root)).slice(0, 200) };
}
// `limited: false` is for auxiliary registries (such as native panel sync
// switches) that record preferences only; quota lives in the computer library.
export function createLibrary(root = defaultLibraryRoot(), { origin = defaultCloudOrigin(), now = Date.now, limited = true } = {}) {
  const access = limited ? createLocalAccess(root, origin, now) : { current: async () => ({ limit: null, paid: false, connected: false }) };
  const live = list => list.filter(item => !item.reservedUntil || item.reservedUntil > now());
  const activeIds = (list, limit) => new Set(live(list).filter(item => item.active !== false).slice(0, limit ?? undefined).map(item => item.id));
  const limitError = () => Object.assign(new Error('Your local library has no free active slots. Archive an active flow, or connect an account with access to a larger local library.'), { status: 403, code: 'LOCAL_FLOW_LIMIT' });
  const readOnlyError = () => Object.assign(new Error('This local flow is read-only. Activate it in your library before editing.'), { status: 403, code: 'LOCAL_FLOW_READ_ONLY' });
  const indexPath = join(root, 'library.json');
  async function entries(path = indexPath) {
    try { const value = JSON.parse(await readFile(path, 'utf8')); if (!Array.isArray(value)) throw new Error('Invalid library index.'); return value; }
    catch (error) { if (error.code === 'ENOENT') return []; throw error; }
  }
  async function normalized() {
    const previous = await entries();
    // Missing source files cannot occupy slots forever. Preserve their records
    // for restoration, and preserve reservations until generation completes.
    const list = await Promise.all(live(previous).map(async item => {
      if (!limited || item.active === false || item.reservedUntil) return item;
      try { if (await realpath(item.path) === item.path && (await stat(item.path)).isFile()) return item; }
      catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) return item; }
      return { ...item, active: false };
    }));
    const ids = activeIds(list, (await access.current()).limit);
    const next = list.map(item => ({ ...item, active: ids.has(item.id) }));
    if (JSON.stringify(next) !== JSON.stringify(previous)) await writeState(indexPath, next);
    return next;
  }
  const snapshot = () => withLibraryLock(root, normalized);
  async function mutate(change, path = indexPath) {
    return withLibraryLock(root, async () => {
      const previous = path === indexPath ? await normalized() : await entries(path);
      const next = await change(previous);
      if (JSON.stringify(next) !== JSON.stringify(previous)) await writeState(path, next);
    });
  }
  async function quota(list) {
    const entitlement = await access.current();
    const ids = activeIds(list, entitlement.limit);
    const reserved = live(list).filter(item => item.reservedUntil && ids.has(item.id)).length;
    return { ...entitlement, active: ids.size - reserved, reserved, remaining: entitlement.limit === null ? null : entitlement.limit - ids.size };
  }
  return {
    access,
    capturePreferences: createCapturePreferences(root),
    async status() { return withLibraryLock(root, async () => quota(await normalized())); },
    // Slot management exposes registered metadata only, without opening other
    // projects, reading documents/captures or returning filesystem paths.
    async slots() {
      return withLibraryLock(root, async () => {
        const list = await normalized(), entitlement = await quota(list);
        const ids = activeIds(list, entitlement.limit);
        const flows = await Promise.all(list.map(async entry => ({
          id: entry.id, name: entry.name, application: entry.application,
          available: await realpath(entry.path).then(async path => path === entry.path && (await stat(path)).isFile()).catch(() => false),
          readOnly: !ids.has(entry.id), reserved: Boolean(entry.reservedUntil),
        })));
        return { flows, access: entitlement };
      });
    },
    async assertCapacity() { const value = await this.status(); if (value.remaining === 0) throw limitError(); return value; },
    async reserve(file, application) {
      // Canonicalize the existing parent before reserving a not-yet-created file.
      const path = await realpath(file).catch(async error => { if (error.code !== 'ENOENT') throw error; return join(await realpath(dirname(resolve(file))), basename(file)); });
      const id = key(path);
      await mutate(async previous => {
        const list = live(previous), existing = list.find(item => item.id === id);
        const { limit } = await access.current(), active = activeIds(list, limit);
        if (existing) { if (!active.has(id)) throw readOnlyError(); return list.map(item => item.id === id && item.reservedUntil ? { ...item, reservedUntil: now() + 30 * 60000 } : item); }
        if (limit !== null && active.size >= limit) throw limitError();
        return [...list, { id, path, application, name: basename(file), active: true, reservedUntil: now() + 30 * 60000 }];
      });
      return { id, ...(await this.status()) };
    },
    // Read-only membership and quota, without reading every document.
    async membership() {
      return withLibraryLock(root, async () => {
        const list = await normalized(), ids = activeIds(list, (await access.current()).limit);
        return { access: await quota(list), registered: new Set(list.map(item => item.id)), readOnly: new Set(list.filter(item => !ids.has(item.id)).map(item => item.id)) };
      });
    },
    // Drops an unused reservation (for example when the file could not be created).
    async release(id) {
      await mutate(async previous => live(previous).filter(item => item.id !== id || !item.reservedUntil));
    },
    // Serialize deletion with enrollment and edits so discovery cannot retain a deleted flow.
    async remove(id, beforeRemove = async () => {}) {
      await mutate(async previous => {
        await beforeRemove(previous.find(item => item.id === id));
        return previous.filter(item => item.id !== id);
      });
    },
    async setActive(id, active) {
      if (typeof active !== 'boolean') throw Object.assign(new Error('Choose whether the flow is active.'), { status: 422 });
      await mutate(async previous => {
        const list = live(previous);
        if (!list.some(item => item.id === id)) throw Object.assign(new Error('Flow not in your library.'), { status: 404 });
        const selected = list.find(item => item.id === id);
        if (active && !(await realpath(selected.path).then(async path => path === selected.path && (await stat(path)).isFile()).catch(() => false))) throw Object.assign(new Error('The source file is unavailable. Restore it on disk before activating this flow.'), { status: 404 });
        const ids = activeIds(list, (await access.current()).limit);
        if (active && !ids.has(id) && (await quota(list)).remaining === 0) throw limitError();
        // Put a reactivated flow ahead of overflow entries from an expired plan.
        const updated = { ...selected, active };
        return active ? [...list.filter(item => item.id !== id && ids.has(item.id)), updated, ...list.filter(item => item.id !== id && !ids.has(item.id))] : list.map(item => item.id === id ? updated : item);
      });
      return this.status();
    },
    async withWritable(id, action) {
      return withLibraryLock(root, async () => {
        const list = await normalized();
        if (!activeIds(list, (await access.current()).limit).has(id)) throw readOnlyError();
        return action();
      });
    },
    async cloudBootstrap(account, flowIds, completedId) {
      if (typeof account !== 'string' || !account.trim() || account.length > 500) throw Object.assign(new Error('Choose a connected account.'), { status: 422 });
      if (!Array.isArray(flowIds) || flowIds.length > 3 || flowIds.some(id => typeof id !== 'string') || (completedId !== undefined && typeof completedId !== 'string')) throw Object.assign(new Error('Choose up to three local flows.'), { status: 422 });
      const known = new Set((await entries()).map(entry => entry.id));
      if (flowIds.some(id => !known.has(id))) throw Object.assign(new Error('Flow not in your library.'), { status: 404 });
      let pending;
      await mutate(list => {
        const previous = list.find(item => item.account === account);
        pending = (previous?.pending || [...new Set(flowIds)]).filter(id => id !== completedId);
        return [...list.filter(item => item.account !== account), { account, pending }];
      }, join(root, 'cloud-bootstrap.json'));
      return { pending };
    },
    async register(file, application) {
      const path = await realpath(file);
      const { document } = await readDocument(path);
      const id = key(path);
      const app = document.application || application;
      await mutate(async previous => {
        const list = live(previous), existing = list.find(item => item.id === id);
        const { limit } = await access.current();
        const entry = { ...existing, id, path, application: app, name: document.name, active: existing ? existing.active !== false : (limit === null || activeIds(list, limit).size < limit) };
        delete entry.reservedUntil;
        // Preserve activation order when names or documents change.
        return existing ? list.map(item => item.id === id ? entry : item) : [...list, entry];
      });
      return id;
    },
    async discover(file, application) {
      const folder = await realpath(dirname(file));
      const files = (await readdir(folder)).filter(isFlowFile).slice(0, 200);
      for (const name of files) {
        const path = resolve(folder, name);
        // Never index escaping symlinks discovered beside a document.
        if (await realpath(path).catch(() => '') !== path) continue;
        try { await this.register(path, application); } catch { /* Invalid siblings do not block the current flow. */ }
      }
    },
    // Raw index entries, without reading each document (used for cheap preference lookups).
    async index() { return entries(); },
    async resolve(id) { const list = await snapshot(), entry = list.find(item => item.id === id); if (!entry) throw Object.assign(new Error('Flow not in your library.'), { status: 404 }); return { ...entry, readOnly: !activeIds(list, (await access.current()).limit).has(id) }; },
    async setAutoSync(id, autoSync, autoSyncAccount = null, autoSyncCloudId, mode = 'set') {
      if (autoSyncAccount !== null && (typeof autoSyncAccount !== 'string' || autoSyncAccount.length > 750)) throw Object.assign(new Error('Invalid snapshot account.'), { status: 422 });
      if (autoSyncCloudId !== undefined && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(autoSyncCloudId)) throw Object.assign(new Error('Choose a saved account flow.'), { status: 422 });
      if (typeof autoSync !== 'boolean') throw Object.assign(new Error('Choose whether to automatically update snapshots.'), { status: 422 });
      if (!['set', 'default', 'remember'].includes(mode)) throw Object.assign(new Error('Invalid snapshot preference action.'), { status: 422 });
      let preference;
      await mutate(async list => {
        if (!activeIds(list, (await access.current()).limit).has(id)) throw readOnlyError();
        if (!list.some(item => item.id === id)) throw Object.assign(new Error('Flow not in your library.'), { status: 404 });
        return list.map(item => {
          if (item.id !== id) return item;
          // A delayed default or upload completion must preserve another panel's
          // opt-out/account change. Inspect and update under the same file lock.
          const preserve = mode === 'remember' || (mode === 'default' && item.autoSync !== undefined);
          preference = preserve
            ? { autoSync: item.autoSync, autoSyncAccount: item.autoSyncAccount, autoSyncCloudId: mode === 'remember' && item.autoSyncAccount === autoSyncAccount ? autoSyncCloudId ?? item.autoSyncCloudId : item.autoSyncCloudId }
            : { autoSync, autoSyncAccount, autoSyncCloudId: autoSyncCloudId ?? (item.autoSyncAccount === autoSyncAccount ? item.autoSyncCloudId : undefined) };
          return { ...item, ...preference };
        });
      });
      return preference;
    },
    async list() {
      const list = await snapshot(), ids = activeIds(list, (await access.current()).limit);
      return Promise.all(list.filter(entry => !entry.reservedUntil).map(async entry => {
        try {
          if (await realpath(entry.path) !== entry.path) throw new Error('The registered source path has changed.');
          const { document, revision } = await readDocument(entry.path);
          const application = await applicationWithIcon(document.application || entry.application, await inferProjectRoot(entry.path));
          return { id: entry.id, documentId: document.id, name: document.name, description: document.description, application, userRoles: flowUserRoles(document), nodes: document.nodes.length, updatedAt: (await stat(entry.path)).mtime.toISOString(), revision, available: true, storage: 'local', readOnly: !ids.has(entry.id), autoSync: entry.autoSync, autoSyncAccount: entry.autoSyncAccount, autoSyncCloudId: entry.autoSyncCloudId };
        } catch { return { id: entry.id, name: entry.name, application: entry.application, nodes: 0, available: false, storage: 'local', readOnly: !ids.has(entry.id) }; }
      }));
    },
  };
}

SHA-256: 19f5aa4e3c71b90197c4f5e884d671661d1c053fa149f488d4cdcb6d029d33bb