The minimalistic document archiving platform.
feat(ingestion): added folder ingestion support (#215)
Corentin Thomasset9ddb7d545de7
diff --git a/.gitignore b/.gitignoreindex 4445e99c..6ee70aef 100644--- a/.gitignore+++ b/.gitignore@@ -37,5 +37,6 @@ cache*.sqlitelocal-documents+ingestion.cursorrules*.traineddata\ No newline at end of filediff --git a/apps/docs/src/content/docs/03-guides/03-setup-ingestion-folder.mdx b/apps/docs/src/content/docs/03-guides/03-setup-ingestion-folder.mdxnew file mode 100644index 00000000..43126b3e--- /dev/null+++ b/apps/docs/src/content/docs/03-guides/03-setup-ingestion-folder.mdx@@ -0,0 +1,105 @@+---+title: Setup Ingestion Folder+description: Step-by-step guide to setup an ingestion folder to automatically ingest documents into your Papra instance.+slug: guides/setup-ingestion-folder+---+import { Steps } from '@astrojs/starlight/components';+import { Aside } from '@astrojs/starlight/components';+import { FileTree } from '@astrojs/starlight/components';++The ingestion folder is a special folder that is watched by Papra for new files. When a new file is added to the ingestion folder, Papra will automatically import it.++## Multi-Organization Structure++Papra supports multiple organizations within a single instance, each requiring a dedicated ingestion folder. The ingestion system uses a hierarchical structure where:++<FileTree>+- ingestion-folder+ - org_abc123+ - document.pdf+ - report.docx+ - org_def456+ - file.txt+ - foo.txt # Ignored as it's not in an organization+</FileTree>+++This allows you to have a single instance of Papra watching multiple organizations' ingestion folders.++<Aside>+Files and folders that are within the `ingestion-root-folder` but not within an organization folder are ignored.+</Aside>++## Setup++Add the following to your `docker-compose.yml` file:++```yaml title="docker-compose.yml" ins={9,12}+services:+papra:+ container_name: papra+ image: ghcr.io/papra-hq/papra:latest+ restart: unless-stopped+ ports:+ - "1221:1221"+ environment:+ - INGESTION_FOLDER_IS_ENABLED=true+ volumes:+ - ./app-data:/app/app-data+ - <your-ingestion-folder>:/app/ingestion+ user: "${UID}:${GID}"+```++Then add files to a folder named with the organization id (available in Papra URL, e.g. `https://papra.example.com/organizations/<organization-id>`, the format is `org_<random>`).++```bash+mkdir -p <your-ingestion-folder>/<org_id>+touch <your-ingestion-folder>/<org_id>/hello.txt+```++## Post-processing++Once a file has been ingested in your Papra organization, you can configure what happens to it by setting the `INGESTION_FOLDER_POST_PROCESSING_STRATEGY` environment variable. There are two strategies:++- `delete`: The file is deleted from the ingestion folder (default strategy)+- `move`: The file is moved to the `INGESTION_FOLDER_POST_PROCESSING_MOVE_FOLDER_PATH` folder (default: `./ingestion-done`)++Note that the `INGESTION_FOLDER_POST_PROCESSING_MOVE_FOLDER_PATH` path is relative to the organization ingestion folder.++So with `INGESTION_FOLDER_POST_PROCESSING_MOVE_FOLDER_PATH=ingestion-done`, the file `<ingestion-folder>/<org_id>/file.pdf` will be moved to `<ingestion-folder>/<org_id>/ingestion-done/file.pdf` once ingested.++## Safeguards++To avoid accidental data loss, if for some reason the ingestion fails, the file is moved to the `INGESTION_FOLDER_ERROR_FOLDER_PATH` folder (default: `./ingestion-error`).++<Aside>+As for the `INGESTION_FOLDER_POST_PROCESSING_MOVE_FOLDER_PATH`, the `INGESTION_FOLDER_ERROR_FOLDER_PATH` path is relative to the organization ingestion folder.+</Aside>++## Polling++By default, Papra uses native file watchers to detect changes in the ingestion folder. On some OS (like Windows), this can be flaky with Docker. To avoid this issue, you can enable polling by setting the `INGESTION_FOLDER_WATCHER_USE_POLLING` environment variable to `true`.++The default polling interval is 2 seconds, you can change it by setting the `INGESTION_FOLDER_WATCHER_POLLING_INTERVAL_MS` environment variable.+++```yaml title="docker-compose.yml" ins={2-3}+environment:+ - INGESTION_FOLDER_WATCHER_USE_POLLING=true+ - INGESTION_FOLDER_WATCHER_POLLING_INTERVAL_MS=2000+```++## Configuration++You can find the list of all configuration options in the [configuration reference](/docs/configuration-reference), the related variables are prefixed with `INGESTION_FOLDER_`.+++## Edge cases and behaviors++- The ingestion folder is watched recursively.+- Files in the ingestion folder `done` and `error` folders are ignored.+- When a file from the ingestion folder is already present (and not in the trash) in the organization, no ingestion is done, but the file is post-processed (deleted or moved) as successfully ingested.+- When a file is moved to "done" or "error" folder+ - If a file with the same name and same content is present in the destination folder, the original file is deleted+ - If a file with the same name but different content is present in the destination folder, the original file is moved and a timestamp is added to the filename+- Some files are ignored by default (`.DS_Store`, `Thumbs.db`, `desktop.ini`, etc.) see [ingestion-folders.constants.ts](https://github.com/papra-hq/papra/blob/main/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.constants.ts) for the list of ignored files and patterns. You can change this by setting the `INGESTION_FOLDER_IGNORED_PATTERNS` environment variable.\ No newline at end of filediff --git a/apps/docs/src/content/navigation.ts b/apps/docs/src/content/navigation.tsindex a583037a..e9e6b5e0 100644--- a/apps/docs/src/content/navigation.ts+++ b/apps/docs/src/content/navigation.ts@@ -26,6 +26,10 @@ export const sidebar: StarlightUserConfig['sidebar'] = [label: 'Setup intake emails with CF Email Workers',slug: 'guides/intake-emails-with-cloudflare-email-workers',},+ {+ label: 'Setup Ingestion Folder',+ slug: 'guides/setup-ingestion-folder',+ },],},{diff --git a/apps/papra-server/package.json b/apps/papra-server/package.jsonindex 27428e6b..3b032568 100644--- a/apps/papra-server/package.json+++ b/apps/papra-server/package.json@@ -43,14 +43,18 @@"@paralleldrive/cuid2": "^2.2.2","better-auth": "catalog:","c12": "^3.0.2",+ "chokidar": "^4.0.3","date-fns": "^4.1.0","drizzle-kit": "^0.30.1","drizzle-orm": "^0.38.3","figue": "^2.2.3","hono": "^4.6.15","lodash-es": "^4.17.21",+ "mime-types": "^3.0.1","node-cron": "^3.0.3","p-limit": "^6.2.0",+ "p-queue": "^8.1.0",+ "picomatch": "^4.0.2","posthog-node": "^4.11.1","resend": "^4.1.2","stripe": "^17.7.0",@@ -62,11 +66,14 @@"@crowlog/pretty": "^1.1.1","@total-typescript/ts-reset": "^0.6.1","@types/lodash-es": "^4.17.12",+ "@types/mime-types": "^2.1.4","@types/node": "^22.10.2","@types/node-cron": "^3.0.11",+ "@types/picomatch": "^4.0.0","@vitest/coverage-v8": "catalog:","esbuild": "^0.24.2","eslint": "catalog:",+ "memfs": "^4.17.0","typescript": "catalog:","vitest": "catalog:"}diff --git a/apps/papra-server/src/index.ts b/apps/papra-server/src/index.tsindex 6770945b..8cf257e1 100644--- a/apps/papra-server/src/index.ts+++ b/apps/papra-server/src/index.ts@@ -4,6 +4,7 @@ import { serve } from '@hono/node-server';import { setupDatabase } from './modules/app/database/database';import { createServer } from './modules/app/server';import { parseConfig } from './modules/config/config';+import { createIngestionFolderWatcher } from './modules/ingestion-folders/ingestion-folders.usecases';import { createLogger } from './modules/shared/logger/logger';import { createTaskScheduler } from './modules/tasks/task-scheduler';import { taskDefinitions } from './modules/tasks/tasks.defiitions';@@ -24,6 +25,15 @@ const server = serve(({ port }) => logger.info({ port }, 'Server started'),);+if (config.ingestionFolder.isEnabled) {+ const { startWatchingIngestionFolders } = createIngestionFolderWatcher({+ config,+ db,+ });++ await startWatchingIngestionFolders();+}+taskScheduler.start();process.on('SIGINT', async () => {diff --git a/apps/papra-server/src/modules/config/config.ts b/apps/papra-server/src/modules/config/config.tsindex 9c2ea28e..958cdf65 100644--- a/apps/papra-server/src/modules/config/config.ts+++ b/apps/papra-server/src/modules/config/config.ts@@ -10,6 +10,7 @@ import { databaseConfig } from '../app/database/database.config';import { documentsConfig } from '../documents/documents.config';import { documentStorageConfig } from '../documents/storage/document-storage.config';import { emailsConfig } from '../emails/emails.config';+import { ingestionFolderConfig } from '../ingestion-folders/ingestion-folders.config';import { intakeEmailsConfig } from '../intake-emails/intake-emails.config';import { organizationsConfig } from '../organizations/organizations.config';import { organizationPlansConfig } from '../plans/plans.config';@@ -86,6 +87,7 @@ export const configDefinition = {documents: documentsConfig,documentsStorage: documentStorageConfig,auth: authConfig,+ ingestionFolder: ingestionFolderConfig,tasks: tasksConfig,intakeEmails: intakeEmailsConfig,emails: emailsConfig,diff --git a/apps/papra-server/src/modules/documents/documents.errors.ts b/apps/papra-server/src/modules/documents/documents.errors.tsindex 0e40dc5b..6ef05e39 100644--- a/apps/papra-server/src/modules/documents/documents.errors.ts+++ b/apps/papra-server/src/modules/documents/documents.errors.ts@@ -12,9 +12,10 @@ export const createDocumentIsNotDeletedError = createErrorFactory({statusCode: 400,});+export const DOCUMENT_ALREADY_EXISTS_ERROR_CODE = 'document.already_exists' as const;export const createDocumentAlreadyExistsError = createErrorFactory({message: 'Document already exists.',- code: 'document.already_exists',+ code: DOCUMENT_ALREADY_EXISTS_ERROR_CODE,statusCode: 409,});diff --git a/apps/papra-server/src/modules/documents/documents.usecases.ts b/apps/papra-server/src/modules/documents/documents.usecases.tsindex df5d8265..e66c1fc6 100644--- a/apps/papra-server/src/modules/documents/documents.usecases.ts+++ b/apps/papra-server/src/modules/documents/documents.usecases.ts@@ -1,22 +1,23 @@+import type { Database } from '../app/database/database.types';import type { Config } from '../config/config.types';-import type { PlansRepository } from '../plans/plans.repository';import type { Logger } from '../shared/logger/logger';-import type { SubscriptionsRepository } from '../subscriptions/subscriptions.repository';-import type { TaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';-import type { TagsRepository } from '../tags/tags.repository';-import type { TrackingServices } from '../tracking/tracking.services';-import type { DocumentsRepository } from './documents.repository';import type { Document } from './documents.types';-import type { DocumentStorageService } from './storage/documents.storage.services';import { safely } from '@corentinth/chisels';import { extractTextFromFile } from '@papra/lecture';import pLimit from 'p-limit';import { checkIfOrganizationCanCreateNewDocument } from '../organizations/organizations.usecases';+import { createPlansRepository, type PlansRepository } from '../plans/plans.repository';import { createLogger } from '../shared/logger/logger';+import { createSubscriptionsRepository, type SubscriptionsRepository } from '../subscriptions/subscriptions.repository';+import { createTaggingRulesRepository, type TaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';import { applyTaggingRules } from '../tagging-rules/tagging-rules.usecases';+import { createTagsRepository, type TagsRepository } from '../tags/tags.repository';+import { createTrackingServices, type TrackingServices } from '../tracking/tracking.services';import { createDocumentAlreadyExistsError, createDocumentNotDeletedError, createDocumentNotFoundError } from './documents.errors';import { buildOriginalDocumentKey, generateDocumentId as generateDocumentIdImpl } from './documents.models';+import { createDocumentsRepository, type DocumentsRepository } from './documents.repository';import { getFileSha256Hash } from './documents.services';+import { createDocumentStorageService, type DocumentStorageService } from './storage/documents.storage.services';const logger = createLogger({ namespace: 'documents:usecases' });@@ -107,6 +108,40 @@ export async function createDocument({return { document };}+export type CreateDocumentUsecase = Awaited<ReturnType<typeof createDocumentCreationUsecase>>;+export async function createDocumentCreationUsecase({+ db,+ config,+ logger = createLogger({ namespace: 'documents:usecases' }),+ generateDocumentId = generateDocumentIdImpl,+ documentsStorageService,+}: {+ db: Database;+ config: Config;+ logger?: Logger;+ documentsStorageService?: DocumentStorageService;+ generateDocumentId?: () => string;+}) {+ const deps = {+ documentsRepository: createDocumentsRepository({ db }),+ documentsStorageService: documentsStorageService ?? await createDocumentStorageService({ config }),+ plansRepository: createPlansRepository({ config }),+ subscriptionsRepository: createSubscriptionsRepository({ db }),+ trackingServices: createTrackingServices({ config }),+ taggingRulesRepository: createTaggingRulesRepository({ db }),+ tagsRepository: createTagsRepository({ db }),+ generateDocumentId,+ logger,+ };++ return async ({ file, userId, organizationId }: { file: File; userId?: string; organizationId: string }) => createDocument({+ file,+ userId,+ organizationId,+ ...deps,+ });+}+async function handleExistingDocument({existingDocument,fileName,diff --git a/apps/papra-server/src/modules/documents/storage/drivers/drivers.models.ts b/apps/papra-server/src/modules/documents/storage/drivers/drivers.models.tsindex 61e47dea..af95c3fd 100644--- a/apps/papra-server/src/modules/documents/storage/drivers/drivers.models.ts+++ b/apps/papra-server/src/modules/documents/storage/drivers/drivers.models.ts@@ -17,6 +17,6 @@ export type StorageDriver = {export type StorageDriverFactory = (args: { config: Config }) => Promise<StorageDriver>;-export function defineStorageDriver(factory: StorageDriverFactory) {+export function defineStorageDriver<T extends StorageDriverFactory>(factory: T) {return factory;}diff --git a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.ts b/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.tsindex 145340ab..c7cef015 100644--- a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.ts+++ b/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.ts@@ -2,20 +2,10 @@ import fs from 'node:fs';import { dirname, join } from 'node:path';import stream from 'node:stream';import { get } from 'lodash-es';+import { checkFileExists, deleteFile, ensureDirectoryExists } from '../../../../shared/fs/fs.services';import { defineStorageDriver } from '../drivers.models';import { createFileAlreadyExistsError } from './fs.storage-driver.errors';-function ensureDirectoryExists({ path }: { path: string }) {- return fs.promises.mkdir(- dirname(path),- { recursive: true },- );-}--function checkFileExists({ path }: { path: string }) {- return fs.promises.access(path, fs.constants.F_OK).then(() => true).catch(() => false);-}-export const FS_STORAGE_DRIVER_NAME = 'filesystem' as const;export const fsStorageDriverFactory = defineStorageDriver(async ({ config }) => {@@ -36,7 +26,7 @@ export const fsStorageDriverFactory = defineStorageDriver(async ({ config }) =>throw createFileAlreadyExistsError();}- await ensureDirectoryExists({ path: storagePath });+ await ensureDirectoryExists({ path: dirname(storagePath) });const writeStream = fs.createWriteStream(storagePath);stream.Readable.fromWeb(file.stream()).pipe(writeStream);@@ -69,7 +59,7 @@ export const fsStorageDriverFactory = defineStorageDriver(async ({ config }) =>const { storagePath } = getStoragePath({ storageKey });try {- await fs.promises.unlink(storagePath);+ await deleteFile({ filePath: storagePath });} catch (error) {if (get(error, 'code') === 'ENOENT') {throw new Error('File not found');diff --git a/apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.test.ts b/apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.test.tsindex 4eb8f525..367e1bd3 100644--- a/apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.test.ts+++ b/apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.test.ts@@ -1,11 +1,10 @@-import type { Config } from '../../../../config/config.types';import { describe, expect, test } from 'vitest';import { inMemoryStorageDriverFactory } from './memory.storage-driver';describe('memory storage-driver', () => {describe('inMemoryStorageDriver', () => {test('saves, retrieves and delete a file', async () => {- const inMemoryStorageDriver = await inMemoryStorageDriverFactory({ config: {} as Config });+ const inMemoryStorageDriver = await inMemoryStorageDriverFactory();const file = new File(['lorem ipsum'], 'text-file.txt', { type: 'text/plain' });@@ -28,5 +27,26 @@ describe('memory storage-driver', () => {await expect(inMemoryStorageDriver.getFileStream({ storageKey: 'org_1/text-file.txt' })).rejects.toThrow('File not found');});++ test('mainly for testing purposes, a _getStorage() method is available to access the internal storage map', async () => {+ const inMemoryStorageDriver = await inMemoryStorageDriverFactory();++ await inMemoryStorageDriver.saveFile({+ file: new File(['lorem ipsum'], 'text-file.txt', { type: 'text/plain' }),+ storageKey: 'org_1/text-file.txt',+ });++ const storage = inMemoryStorageDriver._getStorage();++ expect(storage).to.be.a('Map');+ const entries = Array.from(storage.entries());++ expect(entries).to.have.length(1);+ const [key, file] = entries[0];++ expect(key).to.eql('org_1/text-file.txt');+ expect(file).to.be.a('File');+ expect(await file.text()).to.eql('lorem ipsum');+ });});});diff --git a/apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.ts b/apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.tsindex eda0c141..e7b111eb 100644--- a/apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.ts+++ b/apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.ts@@ -29,5 +29,7 @@ export const inMemoryStorageDriverFactory = defineStorageDriver(async () => {deleteFile: async ({ storageKey }) => {storage.delete(storageKey);},++ _getStorage: () => storage,};});diff --git a/apps/papra-server/src/modules/ingestion-folders/ingestion-folder.models.test.ts b/apps/papra-server/src/modules/ingestion-folders/ingestion-folder.models.test.tsnew file mode 100644index 00000000..9b44fad0--- /dev/null+++ b/apps/papra-server/src/modules/ingestion-folders/ingestion-folder.models.test.ts@@ -0,0 +1,109 @@+import { describe, expect, test } from 'vitest';+import { addTimestampToFilename, isFileInDoneFolder, isFileInErrorFolder, normalizeFilePathToIngestionFolder } from './ingestion-folder.models';++describe('ingestion-folder models', () => {+ describe('normalizeFilePathToIngestionFolder', () => {+ test('get the path of a file relative to the ingestion folder', () => {+ expect(+ normalizeFilePathToIngestionFolder({+ filePath: '/home/foo/projects/papra/apps/papra-server/ingestion/org_1/yo.md',+ ingestionFolderPath: '/home/foo/projects/papra/apps/papra-server/ingestion',+ }),+ ).to.eql({ relativeFilePath: 'org_1/yo.md' });+ });+ });++ describe('isFileInErrorFolder', () => {+ test('the user can configure the error folder as a relative path, it is relative to the file organization ingestion folder', () => {+ // Here the error folder is /foo/bar/ingestion/org_1/error+ expect(+ isFileInErrorFolder({+ filePath: '/foo/bar/ingestion/org_1/yo.md',+ errorFolder: 'error',+ organizationIngestionFolderPath: '/foo/bar/ingestion/org_1',+ }),+ ).to.equal(false);++ expect(+ isFileInErrorFolder({+ filePath: '/foo/bar/ingestion/org_1/error/yo.md',+ errorFolder: 'error',+ organizationIngestionFolderPath: '/foo/bar/ingestion/org_1',+ }),+ ).to.equal(true);+ });++ test('the user can configure the error folder as an absolute path that can overlap with the organization ingestion folder', () => {+ expect(+ isFileInErrorFolder({+ filePath: '/foo/bar/ingestion/org_1/error/yo.md',+ errorFolder: '/foo/bar/ingestion/org_1/error',+ organizationIngestionFolderPath: '/foo/bar/ingestion/org_1',+ }),+ ).to.equal(true);++ expect(+ isFileInErrorFolder({+ filePath: '/foo/bar/ingestion/org_1/error/yo.md',+ errorFolder: '/error',+ organizationIngestionFolderPath: '/foo/bar/ingestion/org_1',+ }),+ ).to.equal(false);+ });+ });++ describe('isFileInDoneFolder', () => {+ test('the user can configure the done folder as a relative path, it is relative to the file organization ingestion folder', () => {+ // Here the done folder is /foo/bar/ingestion/org_1/done+ expect(+ isFileInDoneFolder({+ filePath: '/foo/bar/ingestion/org_1/yo.md',+ doneFolder: 'done',+ organizationIngestionFolderPath: '/foo/bar/ingestion/org_1',+ }),+ ).to.equal(false);++ expect(+ isFileInDoneFolder({+ filePath: '/foo/bar/ingestion/org_1/done/yo.md',+ doneFolder: 'done',+ organizationIngestionFolderPath: '/foo/bar/ingestion/org_1',+ }),+ ).to.equal(true);+ });++ test('the user can configure the done folder as an absolute path that can overlap with the organization ingestion folder', () => {+ expect(+ isFileInDoneFolder({+ filePath: '/foo/bar/ingestion/org_1/done/yo.md',+ doneFolder: '/foo/bar/ingestion/org_1/done',+ organizationIngestionFolderPath: '/foo/bar/ingestion/org_1',+ }),+ ).to.equal(true);++ expect(+ isFileInDoneFolder({+ filePath: '/foo/bar/ingestion/org_1/done/yo.md',+ doneFolder: '/done',+ organizationIngestionFolderPath: '/foo/bar/ingestion/org_1',+ }),+ ).to.equal(false);+ });+ });++ describe('addTimestampToFilename', () => {+ test('given a filename, it adds a timestamp to the name, before the extension', () => {+ expect(+ addTimestampToFilename({ fileName: 'yo.md', now: new Date('2024-04-14T12:00:00.000Z') }),+ ).to.equal('yo_1713096000000.md');++ expect(+ addTimestampToFilename({ fileName: '.config', now: new Date('2024-04-14T12:00:00.000Z') }),+ ).to.equal('.config_1713096000000');++ expect(+ addTimestampToFilename({ fileName: 'documents.models.tests.ts', now: new Date('2024-04-14T12:00:00.000Z') }),+ ).to.equal('documents.models.tests_1713096000000.ts');+ });+ });+});diff --git a/apps/papra-server/src/modules/ingestion-folders/ingestion-folder.models.ts b/apps/papra-server/src/modules/ingestion-folders/ingestion-folder.models.tsnew file mode 100644index 00000000..6cd17745--- /dev/null+++ b/apps/papra-server/src/modules/ingestion-folders/ingestion-folder.models.ts@@ -0,0 +1,47 @@+import { isAbsolute, join, parse, sep as pathSeparator, relative } from 'node:path';+import { organizationIdRegex } from '../organizations/organizations.constants';++export function normalizeFilePathToIngestionFolder({+ filePath,+ ingestionFolderPath,+}: {+ filePath: string;+ ingestionFolderPath: string;+}) {+ const relativeFilePath = relative(ingestionFolderPath, filePath);++ return { relativeFilePath };+}++export function getOrganizationIdFromFilePath({ relativeFilePath }: { relativeFilePath: string }) {+ const [maybeOrganizationId] = relativeFilePath.split(pathSeparator);++ if (!maybeOrganizationId || !organizationIdRegex.test(maybeOrganizationId)) {+ return { organizationId: undefined };+ }++ return { organizationId: maybeOrganizationId };+}++export function addTimestampToFilename({ fileName, now = new Date() }: { fileName: string; now?: Date }): string {+ const { name, ext } = parse(fileName);+ const timestamp = now.getTime();++ return `${name}_${timestamp}${ext}`;+}++export function getAbsolutePathFromFolderRelativeToOrganizationIngestionFolder({ path, organizationIngestionFolderPath }: { path: string; organizationIngestionFolderPath: string }) {+ return isAbsolute(path) ? path : join(organizationIngestionFolderPath, path);+}++export function isFileInErrorFolder({ filePath, errorFolder, organizationIngestionFolderPath }: { filePath: string; errorFolder: string; organizationIngestionFolderPath: string }) {+ const errorFolderPath = getAbsolutePathFromFolderRelativeToOrganizationIngestionFolder({ path: errorFolder, organizationIngestionFolderPath });++ return filePath.startsWith(errorFolderPath);+}++export function isFileInDoneFolder({ filePath, doneFolder, organizationIngestionFolderPath }: { filePath: string; doneFolder: string; organizationIngestionFolderPath: string }) {+ const doneFolderPath = getAbsolutePathFromFolderRelativeToOrganizationIngestionFolder({ path: doneFolder, organizationIngestionFolderPath });++ return filePath.startsWith(doneFolderPath);+}diff --git a/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.config.ts b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.config.tsnew file mode 100644index 00000000..6750c4e2--- /dev/null+++ b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.config.ts@@ -0,0 +1,68 @@+import type { ConfigDefinition } from 'figue';+import { z } from 'zod';+import { booleanishSchema } from '../config/config.schemas';+import { defaultIgnoredPatterns } from './ingestion-folders.constants';++export const ingestionFolderConfig = {+ isEnabled: {+ doc: 'Whether ingestion folders are enabled',+ schema: booleanishSchema,+ default: false,+ env: 'INGESTION_FOLDER_IS_ENABLED',+ },+ folderRootPath: {+ doc: 'The root directory in which ingestion folders for each organization are stored',+ schema: z.string(),+ default: './ingestion',+ env: 'INGESTION_FOLDER_ROOT_PATH',+ },+ watcher: {+ usePolling: {+ doc: 'Whether to use polling for the ingestion folder watcher',+ schema: booleanishSchema,+ default: false,+ env: 'INGESTION_FOLDER_WATCHER_USE_POLLING',+ },+ pollingInterval: {+ doc: 'When polling is used, this is the interval at which the watcher checks for changes in the ingestion folder (in milliseconds)',+ schema: z.number(),+ default: 2_000,+ env: 'INGESTION_FOLDER_WATCHER_POLLING_INTERVAL_MS',+ },+ },+ processingConcurrency: {+ doc: 'The number of files that can be processed concurrently by the server. Increasing this can improve processing speed, but it will also increase CPU and memory usage.',+ schema: z.number().int().positive().min(1),+ default: 1,+ env: 'INGESTION_FOLDER_PROCESSING_CONCURRENCY',+ },+ errorFolder: {+ doc: 'The folder to move the file when the ingestion fails, the path is relative to the organization ingestion folder (<ingestion root>/<organization id>)',+ schema: z.string(),+ default: './ingestion-error',+ env: 'INGESTION_FOLDER_ERROR_FOLDER_PATH',+ },+ postProcessing: {+ strategy: {+ doc: 'The action done on the file after it has been ingested',+ schema: z.enum(['delete', 'move']),+ default: 'delete',+ env: 'INGESTION_FOLDER_POST_PROCESSING_STRATEGY',+ },+ moveToFolderPath: {+ doc: 'The folder to move the file when the post-processing strategy is "move", the path is relative to the organization ingestion folder (<ingestion root>/<organization id>)',+ schema: z.string(),+ default: './ingestion-done',+ env: 'INGESTION_FOLDER_POST_PROCESSING_MOVE_FOLDER_PATH',+ },+ },+ ignoredPatterns: {+ doc: `Comma separated list of patterns to ignore when watching the ingestion folder. Note that if you update this variable, it'll override the default patterns, not merge them. Regarding the format and syntax, please refer to the [picomatch documentation](https://github.com/micromatch/picomatch/blob/bf6a33bd3db990edfbfd20b3b160eed926cd07dd/README.md#globbing-features)`,+ schema: z.union([+ z.string(),+ z.array(z.string()),+ ]).transform(value => (typeof value === 'string' ? value.split(',') : value)),+ default: defaultIgnoredPatterns,+ env: 'INGESTION_FOLDER_IGNORED_PATTERNS',+ },+} as const satisfies ConfigDefinition;diff --git a/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.constants.ts b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.constants.tsnew file mode 100644index 00000000..5641dd09--- /dev/null+++ b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.constants.ts@@ -0,0 +1,13 @@+export const defaultIgnoredPatterns = [+ // Files+ '**/.DS_Store',+ '**/.env',+ '**/desktop.ini',+ '**/Thumbs.db',++ // Directories+ '**/.git/**',+ '**/.idea/**',+ '**/.vscode/**',+ '**/node_modules/**',+];diff --git a/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.errors.ts b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.errors.tsnew file mode 100644index 00000000..0a918f87--- /dev/null+++ b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.errors.ts@@ -0,0 +1,10 @@+import { createError } from '../shared/errors/errors';++export function createInvalidPostProcessingStrategyError({ strategy }: { strategy: string }) {+ return createError({+ code: 'ingestion-folder.invalid-post-processing-strategy',+ message: `The post-processing strategy "${strategy}" is invalid`,+ statusCode: 501,+ isInternal: true,+ });+}diff --git a/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.services.test.ts b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.services.test.tsnew file mode 100644index 00000000..5ec19650--- /dev/null+++ b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.services.test.ts@@ -0,0 +1,35 @@+import { Buffer } from 'node:buffer';+import { describe, expect, test } from 'vitest';+import { getFile } from './ingestion-folders.services';++describe('ingestion-folders services', () => {+ describe('getFile', () => {+ const readFile = async () => Buffer.from('test');++ test('reads a file from the fs and returns a File instance', async () => {+ const { file } = await getFile({+ filePath: 'test.txt',+ fs: { readFile },+ });++ expect(file).instanceOf(File);+ expect(file.type).to.equal('text/plain');+ expect(file.name).to.equal('test.txt');+ expect(file.size).to.equal(4);+ expect(await file.text()).to.equal('test');+ });++ test('a file with a weird extension is considered a octet-stream', async () => {+ const { file } = await getFile({+ filePath: 'test.weird',+ fs: { readFile },+ });++ expect(file).instanceOf(File);+ expect(file.type).to.equal('application/octet-stream');+ expect(file.name).to.equal('test.weird');+ expect(file.size).to.equal(4);+ expect(await file.text()).to.equal('test');+ });+ });+});diff --git a/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.services.ts b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.services.tsnew file mode 100644index 00000000..80e776ca--- /dev/null+++ b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.services.ts@@ -0,0 +1,24 @@+import type {+ FsServices,+} from '../shared/fs/fs.services';+import { parse } from 'node:path';+import mime from 'mime-types';+import {+ createFsServices,+} from '../shared/fs/fs.services';++export async function getFile({+ filePath,+ fs = createFsServices(),+}: {+ filePath: string;+ fs?: Pick<FsServices, 'readFile'>;+}) {+ const buffer = await fs.readFile({ filePath });+ // OR pipes since lookup returns false if the mime type is not found+ const mimeType = mime.lookup(filePath) || 'application/octet-stream';+ const { base: fileName } = parse(filePath);++ const file = new File([buffer], fileName, { type: mimeType });+ return { file };+}diff --git a/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.test.ts b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.test.tsnew file mode 100644index 00000000..4256ae2e--- /dev/null+++ b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.test.ts@@ -0,0 +1,642 @@+import type { FsNative } from '../shared/fs/fs.services';+import { safely } from '@corentinth/chisels';+import { memfs } from 'memfs';+import { describe, expect, test } from 'vitest';+import { createInMemoryDatabase } from '../app/database/database.test-utils';+import { overrideConfig } from '../config/config.test-utils';+import { documentsTable } from '../documents/documents.table';+import { createDocumentCreationUsecase } from '../documents/documents.usecases';+import { inMemoryStorageDriverFactory } from '../documents/storage/drivers/memory/memory.storage-driver';+import { createOrganizationsRepository } from '../organizations/organizations.repository';+import { createInMemoryFsServices } from '../shared/fs/fs.in-memory';+import { createFsServices } from '../shared/fs/fs.services';+import { createTestLogger } from '../shared/logger/logger.test-utils';+import { createInvalidPostProcessingStrategyError } from './ingestion-folders.errors';+import { moveIngestionFile, processFile } from './ingestion-folders.usecases';++describe('ingestion-folders usecases', () => {+ describe('processFile', () => {+ describe('when a file is added to an organization ingestion folder', () => {+ test('if the post processing strategy is set to "move", the file is ingested and moved to the done folder', async () => {+ const { logger, getLogs } = createTestLogger();++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Org 1' }],+ });+ const organizationsRepository = createOrganizationsRepository({ db });++ const config = overrideConfig({+ ingestionFolder: {+ folderRootPath: '/apps/papra/ingestion',+ postProcessing: {+ strategy: 'move',+ moveToFolderPath: 'done',+ },+ },+ documentsStorage: {+ driver: 'in-memory',+ },+ });++ const documentsStorageService = await inMemoryStorageDriverFactory();+ let documentIdIndex = 1;+ const generateDocumentId = () => `doc_${documentIdIndex++}`;++ const { vol } = memfs({+ '/apps/papra/ingestion/org_111111111111111111111111/hello.md': 'lorem ipsum',+ });++ await processFile({+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/hello.md',+ ingestionFolderPath: '/apps/papra/ingestion',+ config,+ organizationsRepository,+ logger,+ fs: createFsServices({ fs: vol.promises as unknown as FsNative }),+ createDocument: await createDocumentCreationUsecase({ db, config, logger, documentsStorageService, generateDocumentId }),+ });++ // Check database+ const documents = await db.select().from(documentsTable);++ expect(documents).to.have.length(1);+ expect(documents[0]).to.deep.include({+ id: 'doc_1',+ organizationId: 'org_111111111111111111111111',+ createdBy: null,+ name: 'hello.md',+ originalName: 'hello.md',+ originalSize: 11,+ });++ // Check file storage+ const files = Array.from(documentsStorageService._getStorage().values());++ expect(files).to.have.length(1);++ const [file] = files;++ expect(file.name).to.equal('hello.md');+ expect(file.size).to.equal(11);+ expect(file.type).to.equal('text/markdown');+ expect(await file.text()).to.equal('lorem ipsum');++ // Check FS, ensure the file has been moved to the done folder+ expect(vol.toJSON()).to.deep.equal({+ '/apps/papra/ingestion/org_111111111111111111111111/done/hello.md': 'lorem ipsum',+ });++ // Check logs+ expect(getLogs({ excludeTimestampMs: true })).to.eql(+ [+ {+ data: {+ documentId: 'doc_1',+ organizationId: 'org_111111111111111111111111',+ userId: undefined,+ },+ level: 'info',+ message: 'Document created',+ namespace: 'test',+ },+ {+ data: {+ documentId: 'doc_1',+ },+ level: 'info',+ message: 'Document imported from ingestion folder',+ namespace: 'test',+ },+ {+ data: {+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/hello.md',+ },+ level: 'info',+ message: 'File moved after ingestion',+ namespace: 'test',+ },+ ],+ );+ });++ test('if the post processing strategy is set to "delete", the file is ingested and deleted', async () => {+ const { logger, getLogs } = createTestLogger();++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Org 1' }],+ });+ const organizationsRepository = createOrganizationsRepository({ db });++ const config = overrideConfig({+ ingestionFolder: {+ folderRootPath: '/apps/papra/ingestion',+ postProcessing: {+ strategy: 'delete',+ },+ },+ documentsStorage: {+ driver: 'in-memory',+ },+ });++ const documentsStorageService = await inMemoryStorageDriverFactory();+ let documentIdIndex = 1;+ const generateDocumentId = () => `doc_${documentIdIndex++}`;++ const { vol } = memfs({+ '/apps/papra/ingestion/org_111111111111111111111111/hello.md': 'lorem ipsum',+ });++ await processFile({+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/hello.md',+ ingestionFolderPath: '/apps/papra/ingestion',+ config,+ organizationsRepository,+ logger,+ fs: createFsServices({ fs: vol.promises as unknown as FsNative }),+ createDocument: await createDocumentCreationUsecase({ db, config, logger, documentsStorageService, generateDocumentId }),+ });++ // Check database+ const documents = await db.select().from(documentsTable);++ expect(documents).to.have.length(1);+ expect(documents[0]).to.deep.include({+ id: 'doc_1',+ organizationId: 'org_111111111111111111111111',+ createdBy: null,+ name: 'hello.md',+ originalName: 'hello.md',+ originalSize: 11,+ });++ // Check file storage+ const files = Array.from(documentsStorageService._getStorage().values());++ expect(files).to.have.length(1);++ const [file] = files;++ expect(file.name).to.equal('hello.md');+ expect(file.size).to.equal(11);+ expect(file.type).to.equal('text/markdown');+ expect(await file.text()).to.equal('lorem ipsum');++ // Check FS, ensure the file has been moved to the done folder+ expect(vol.toJSON()).to.deep.equal({+ '/apps/papra/ingestion/org_111111111111111111111111': null,+ });++ // Check logs+ expect(getLogs({ excludeTimestampMs: true })).to.eql(+ [+ {+ data: {+ documentId: 'doc_1',+ organizationId: 'org_111111111111111111111111',+ userId: undefined,+ },+ level: 'info',+ message: 'Document created',+ namespace: 'test',+ },+ {+ data: {+ documentId: 'doc_1',+ },+ level: 'info',+ message: 'Document imported from ingestion folder',+ namespace: 'test',+ },+ {+ data: {+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/hello.md',+ },+ level: 'info',+ message: 'File deleted after ingestion',+ namespace: 'test',+ },+ ],+ );+ });++ test('if the post processing strategy is not implemented, an error is thrown after the file has been ingested', async () => {+ const { logger } = createTestLogger();++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Org 1' }],+ });+ const organizationsRepository = createOrganizationsRepository({ db });++ const config = overrideConfig({+ ingestionFolder: {+ folderRootPath: '/apps/papra/ingestion',+ postProcessing: {+ strategy: 'unknown' as any,+ },+ },+ documentsStorage: {+ driver: 'in-memory',+ },+ });++ const documentsStorageService = await inMemoryStorageDriverFactory();+ let documentIdIndex = 1;+ const generateDocumentId = () => `doc_${documentIdIndex++}`;++ const { vol } = memfs({+ '/apps/papra/ingestion/org_111111111111111111111111/hello.md': 'lorem ipsum',+ });++ const [, error] = await safely(processFile({+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/hello.md',+ ingestionFolderPath: '/apps/papra/ingestion',+ config,+ organizationsRepository,+ logger,+ fs: createFsServices({ fs: vol.promises as unknown as FsNative }),+ createDocument: await createDocumentCreationUsecase({ db, config, logger, documentsStorageService, generateDocumentId }),+ }));++ expect(error).to.deep.equal(createInvalidPostProcessingStrategyError({ strategy: 'unknown' }));++ // Check database+ const documents = await db.select().from(documentsTable);++ expect(documents).to.have.length(1);+ expect(documents[0]).to.deep.include({+ id: 'doc_1',+ organizationId: 'org_111111111111111111111111',+ createdBy: null,+ name: 'hello.md',+ originalName: 'hello.md',+ originalSize: 11,+ });++ // Check file storage+ const files = Array.from(documentsStorageService._getStorage().values());++ expect(files).to.have.length(1);++ const [file] = files;++ expect(file.name).to.equal('hello.md');+ expect(file.size).to.equal(11);+ expect(file.type).to.equal('text/markdown');+ expect(await file.text()).to.equal('lorem ipsum');++ // Check FS, ensure the file is still in the ingestion folder+ expect(vol.toJSON()).to.deep.equal({+ '/apps/papra/ingestion/org_111111111111111111111111/hello.md': 'lorem ipsum',+ });+ });++ test('if for some reason the file cannot be read, a log is emitted and the processing stops', async () => {+ const { logger, getLogs } = createTestLogger();++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Org 1' }],+ });+ const organizationsRepository = createOrganizationsRepository({ db });++ const config = overrideConfig({+ ingestionFolder: {+ folderRootPath: '/apps/papra/ingestion',+ postProcessing: {+ strategy: 'unknown' as any,+ },+ },+ documentsStorage: {+ driver: 'in-memory',+ },+ });++ const documentsStorageService = await inMemoryStorageDriverFactory();+ let documentIdIndex = 1;+ const generateDocumentId = () => `doc_${documentIdIndex++}`;++ const { vol } = memfs({+ '/apps/papra/ingestion/org_111111111111111111111111/hello.md': 'lorem ipsum',+ });++ await processFile({+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/hello.md',+ ingestionFolderPath: '/apps/papra/ingestion',+ config,+ organizationsRepository,+ logger,+ fs: {+ ...createFsServices({ fs: vol.promises as unknown as FsNative }),+ readFile: async () => {+ throw new Error('File not found');+ },+ },+ createDocument: await createDocumentCreationUsecase({ db, config, logger, documentsStorageService, generateDocumentId }),+ });++ // Check logs+ expect(getLogs({ excludeTimestampMs: true })).to.eql(+ [+ {+ data: {+ error: new Error('File not found'),+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/hello.md',+ },+ level: 'error',+ message: 'Error reading file',+ namespace: 'test',+ },+ ],+ );++ // Check database+ const documents = await db.select().from(documentsTable);++ expect(documents).to.have.length(0);+ });++ test('if a file is located in the post-processed "done" folder or "error" folder, it is not processed nor ingested', async () => {+ const { logger, getLogs } = createTestLogger();++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Org 1' }],+ });+ const organizationsRepository = createOrganizationsRepository({ db });++ const config = overrideConfig({+ ingestionFolder: {+ folderRootPath: '/apps/papra/ingestion',+ postProcessing: {+ strategy: 'move',+ moveToFolderPath: 'done',+ },+ errorFolder: 'error',+ },+ documentsStorage: {+ driver: 'in-memory',+ },+ });++ const { vol } = memfs({+ '/apps/papra/ingestion/org_111111111111111111111111/done/hello.md': 'lorem ipsum',+ '/apps/papra/ingestion/org_111111111111111111111111/error/world.md': 'dolor sit amet',+ });++ await processFile({+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/done/hello.md',+ ingestionFolderPath: '/apps/papra/ingestion',+ config,+ organizationsRepository,+ logger,+ fs: createFsServices({ fs: vol.promises as unknown as FsNative }),+ createDocument: async () => expect.fail('Document should not be created'),+ });++ await processFile({+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/error/world.md',+ ingestionFolderPath: '/apps/papra/ingestion',+ config,+ organizationsRepository,+ logger,+ fs: createFsServices({ fs: vol.promises as unknown as FsNative }),+ createDocument: async () => expect.fail('Document should not be created'),+ });++ // Check database+ const documents = await db.select().from(documentsTable);++ expect(documents).to.have.length(0);++ // Check logs+ expect(getLogs({ excludeTimestampMs: true })).to.eql(+ [+ {+ data: {+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/done/hello.md',+ },+ level: 'debug',+ message: 'File from post-processing folder, skipping',+ namespace: 'test',+ },+ {+ data: {+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/error/world.md',+ },+ level: 'debug',+ message: 'File from error folder, skipping',+ namespace: 'test',+ },+ ],+ );+ });++ test('when the document already exists in the database, it is not ingested, but the post-processing is still executed', async () => {+ const { logger, getLogs } = createTestLogger();++ // This is the sha256 hash of the "lorem ipsum" text+ const loremIpsumSha256Hash = '5e2bf57d3f40c4b6df69daf1936cb766f832374b4fc0259a7cbff06e2f70f269';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Org 1' }],+ documents: [{ id: 'doc_1', organizationId: 'org_111111111111111111111111', name: 'hello.md', originalName: 'hello.md', originalStorageKey: 'hello.md', originalSha256Hash: loremIpsumSha256Hash, mimeType: 'text/markdown' }],+ });+ const organizationsRepository = createOrganizationsRepository({ db });++ const documentsStorageService = await inMemoryStorageDriverFactory();+ let documentIdIndex = 1;+ const generateDocumentId = () => `doc_${documentIdIndex++}`;++ const config = overrideConfig({+ ingestionFolder: {+ folderRootPath: '/apps/papra/ingestion',+ postProcessing: {+ strategy: 'move',+ moveToFolderPath: 'done',+ },+ },+ documentsStorage: {+ driver: 'in-memory',+ },+ });++ const { vol } = memfs({+ '/apps/papra/ingestion/org_111111111111111111111111/hello.md': 'lorem ipsum',+ });++ await processFile({+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/hello.md',+ ingestionFolderPath: '/apps/papra/ingestion',+ config,+ organizationsRepository,+ logger,+ fs: createFsServices({ fs: vol.promises as unknown as FsNative }),+ createDocument: await createDocumentCreationUsecase({ db, config, logger, documentsStorageService, generateDocumentId }),+ });++ // Check database+ const documents = await db.select().from(documentsTable);++ expect(documents).to.have.length(1);+ expect(documents[0].id).to.equal('doc_1');++ // Check fs+ expect(vol.toJSON()).to.deep.equal({+ '/apps/papra/ingestion/org_111111111111111111111111/done/hello.md': 'lorem ipsum',+ });++ // Check logs+ expect(getLogs({ excludeTimestampMs: true })).to.eql(+ [+ {+ data: {+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/hello.md',+ },+ level: 'info',+ message: 'Document not inserted because it already exists',+ namespace: 'test',+ },+ {+ data: {+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/hello.md',+ },+ level: 'info',+ message: 'File moved after ingestion',+ namespace: 'test',+ },+ ],+ );+ });++ test('when their is an issue with the document creation, the file is moved to the error folder', async () => {+ const { logger, getLogs } = createTestLogger();++ // This is the sha256 hash of the "lorem ipsum" text+ const loremIpsumSha256Hash = '5e2bf57d3f40c4b6df69daf1936cb766f832374b4fc0259a7cbff06e2f70f269';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Org 1' }],+ documents: [{ id: 'doc_1', organizationId: 'org_111111111111111111111111', name: 'hello.md', originalName: 'hello.md', originalStorageKey: 'hello.md', originalSha256Hash: loremIpsumSha256Hash, mimeType: 'text/markdown' }],+ });+ const organizationsRepository = createOrganizationsRepository({ db });++ const config = overrideConfig({+ ingestionFolder: {+ folderRootPath: '/apps/papra/ingestion',+ postProcessing: {+ strategy: 'move',+ moveToFolderPath: 'done',+ },+ errorFolder: 'error',+ },+ documentsStorage: {+ driver: 'in-memory',+ },+ });++ const { vol } = memfs({+ '/apps/papra/ingestion/org_111111111111111111111111/hello.md': 'lorem ipsum',+ });++ await processFile({+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/hello.md',+ ingestionFolderPath: '/apps/papra/ingestion',+ config,+ organizationsRepository,+ logger,+ fs: createFsServices({ fs: vol.promises as unknown as FsNative }),+ createDocument: async () => {+ throw new Error('Document creation failed');+ },+ });++ // Check database+ const documents = await db.select().from(documentsTable);++ expect(documents).to.have.length(1);+ expect(documents[0].id).to.equal('doc_1');++ // Check fs+ expect(vol.toJSON()).to.deep.equal({+ '/apps/papra/ingestion/org_111111111111111111111111/error/hello.md': 'lorem ipsum',+ });++ // Check logs+ expect(getLogs({ excludeTimestampMs: true })).to.eql(+ [+ {+ data: {+ error: new Error('Document creation failed'),+ filePath: '/apps/papra/ingestion/org_111111111111111111111111/hello.md',+ },+ level: 'error',+ message: 'Error creating document',+ namespace: 'test',+ },+ ],+ );+ });+ });+ });++ describe('moveIngestionFile', () => {+ describe(`a file from the ingestion folder can be moved+ - either to the done folder, when the post-processing strategy is set to "move"+ - or to the error folder, when an error occurs during the ingestion+ so this can lead to data loss if not handled properly`, () => {+ test('in best case, the file is moved to the destination folder', async () => {+ const { fs, getFsState } = createInMemoryFsServices({+ '/apps/hello.md': 'lorem ipsum',+ });++ await moveIngestionFile({+ filePath: '/apps/hello.md',+ moveToFolder: '/foo/destination',+ fs,+ });++ expect(getFsState()).to.deep.equal({+ '/apps': null,+ '/foo/destination/hello.md': 'lorem ipsum',+ });+ });++ test('if the destination file already exists, but has the same name and same content, the original file is deleted', async () => {+ const { fs, getFsState } = createInMemoryFsServices({+ '/apps/hello.md': 'lorem ipsum',+ '/foo/destination/hello.md': 'lorem ipsum',+ });++ await moveIngestionFile({+ filePath: '/apps/hello.md',+ moveToFolder: '/foo/destination',+ fs,+ });++ expect(getFsState()).to.deep.equal({+ '/apps': null,+ '/foo/destination/hello.md': 'lorem ipsum',+ });+ });++ test('if the destination file already exists, but has the same name and different content, the original file is renamed with a timestamp', async () => {+ const { fs, getFsState } = createInMemoryFsServices({+ '/apps/hello.md': 'lorem ipsum',+ '/foo/destination/hello.md': 'dolor sit amet',+ });++ await moveIngestionFile({+ filePath: '/apps/hello.md',+ moveToFolder: '/foo/destination',+ fs,+ now: new Date('2021-01-01'),+ });++ expect(getFsState()).to.deep.equal({+ '/apps': null,+ '/foo/destination/hello.md': 'dolor sit amet',+ '/foo/destination/hello_1609459200000.md': 'lorem ipsum',+ });+ });+ });+ });+});diff --git a/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.ts b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.tsnew file mode 100644index 00000000..b31112a5--- /dev/null+++ b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.ts@@ -0,0 +1,277 @@+import type { Stats } from 'node:fs';+import type { Database } from '../app/database/database.types';+import type { Config } from '../config/config.types';+import type { CreateDocumentUsecase } from '../documents/documents.usecases';+import type { FsServices } from '../shared/fs/fs.services';+import type { Logger } from '../shared/logger/logger';+import { isAbsolute, join, parse } from 'node:path';+import { safely } from '@corentinth/chisels';+import chokidar from 'chokidar';+import { uniq } from 'lodash-es';+import PQueue from 'p-queue';+import picomatch from 'picomatch';+import { DOCUMENT_ALREADY_EXISTS_ERROR_CODE } from '../documents/documents.errors';+import { createDocumentCreationUsecase } from '../documents/documents.usecases';+import { createOrganizationsRepository, type OrganizationsRepository } from '../organizations/organizations.repository';+import { isErrorWithCode } from '../shared/errors/errors';+import { createFsServices } from '../shared/fs/fs.services';+import { createLogger } from '../shared/logger/logger';+import { getRootDirPath } from '../shared/path';+import { addTimestampToFilename, getAbsolutePathFromFolderRelativeToOrganizationIngestionFolder, getOrganizationIdFromFilePath, isFileInDoneFolder, isFileInErrorFolder, normalizeFilePathToIngestionFolder } from './ingestion-folder.models';+import { createInvalidPostProcessingStrategyError } from './ingestion-folders.errors';+import { getFile } from './ingestion-folders.services';++export function createIngestionFolderWatcher({+ config,+ logger = createLogger({ namespace: 'ingestion-folder-watcher' }),+ db,+}: {+ config: Config;+ logger?: Logger;+ db: Database;+}) {+ const { folderRootPath, watcher: { usePolling, pollingInterval }, processingConcurrency } = config.ingestionFolder;++ const processingQueue = new PQueue({ concurrency: processingConcurrency });+ const cwd = getRootDirPath();+ const ingestionFolderPath = isAbsolute(folderRootPath) ? folderRootPath : join(cwd, folderRootPath);++ return {+ startWatchingIngestionFolders: async () => {+ const organizationsRepository = createOrganizationsRepository({ db });+ const createDocument = await createDocumentCreationUsecase({ db, config, logger });++ const ignored = await buildPathIgnoreFunction({ config, cwd, organizationsRepository });++ chokidar+ .watch(+ folderRootPath,+ {+ persistent: true,+ followSymlinks: true,+ awaitWriteFinish: true,+ atomic: true,+ cwd,+ usePolling,+ interval: pollingInterval,+ ignored,+ },+ )+ .on('add', (fileMaybeCwdRelativePath) => {+ processingQueue.add(async () => {+ const filePath = isAbsolute(fileMaybeCwdRelativePath) ? fileMaybeCwdRelativePath : join(cwd, fileMaybeCwdRelativePath);++ logger.info({ filePath }, 'Processing file');++ const [, error] = await safely(processFile({ filePath, ingestionFolderPath, createDocument, logger, config, organizationsRepository }));++ if (error) {+ logger.error({ filePath, error }, 'Error processing file');+ }+ });+ });++ logger.info(+ {+ folderRootPath,+ usePolling,+ pollingInterval,+ processingConcurrency,+ },+ 'Ingestion folder watcher started',+ );+ },+ };+}++export async function processFile({+ filePath,+ ingestionFolderPath,+ logger,+ organizationsRepository,+ config,+ createDocument,+ fs = createFsServices(),+}: {+ filePath: string;+ ingestionFolderPath: string;+ logger: Logger;+ config: Config;+ createDocument: CreateDocumentUsecase;+ organizationsRepository: OrganizationsRepository;+ fs?: FsServices;+}) {+ const { postProcessing: { moveToFolderPath: doneFolder }, errorFolder } = config.ingestionFolder;++ // Get the file from the ingestion folder as a File Instance+ const [getFileResult, getFileError] = await safely(getFile({ filePath, fs }));++ if (getFileError) {+ logger.error({ filePath, error: getFileError }, 'Error reading file');+ return;+ }++ const { file } = getFileResult;++ const { organizationId } = await getFileOrganizationId({ filePath, ingestionFolderPath, organizationsRepository });++ if (!organizationId) {+ logger.warn({ filePath }, 'A file in the ingestion folder is not located in an organization ingestion folder, skipping');+ return;+ }++ const organizationIngestionFolderPath = join(ingestionFolderPath, organizationId);++ if (isFileInDoneFolder({ filePath, doneFolder, organizationIngestionFolderPath })) {+ logger.debug({ filePath }, 'File from post-processing folder, skipping');+ return;+ }++ if (isFileInErrorFolder({ filePath, errorFolder, organizationIngestionFolderPath })) {+ logger.debug({ filePath }, 'File from error folder, skipping');+ return;+ }++ const [result, error] = await safely(createDocument({ file, organizationId }));++ const isNotInsertedBecauseAlreadyExists = isErrorWithCode({ error, code: DOCUMENT_ALREADY_EXISTS_ERROR_CODE });++ if (error && !isNotInsertedBecauseAlreadyExists) {+ logger.error({ filePath, error }, 'Error creating document');+ const errorFolderPath = getAbsolutePathFromFolderRelativeToOrganizationIngestionFolder({ path: errorFolder, organizationIngestionFolderPath });++ await moveIngestionFile({ filePath, moveToFolder: errorFolderPath, fs });+ return;+ }++ if (isNotInsertedBecauseAlreadyExists) {+ logger.info({ filePath }, 'Document not inserted because it already exists');+ }++ if (result) {+ const { document } = result;++ logger.info({ documentId: document.id }, 'Document imported from ingestion folder');+ }++ await postProcessFile({ filePath, organizationIngestionFolderPath, logger, config, fs });+}++async function postProcessFile({+ filePath,+ organizationIngestionFolderPath,+ logger,+ config,+ fs = createFsServices(),+}: {+ filePath: string;+ organizationIngestionFolderPath: string;+ logger: Logger;+ config: Config;+ fs?: FsServices;+}) {+ const { postProcessing: { strategy, moveToFolderPath } } = config.ingestionFolder;++ if (strategy === 'delete') {+ await fs.deleteFile({ filePath });+ logger.info({ filePath }, 'File deleted after ingestion');+ return;+ }++ if (strategy === 'move') {+ const path = getAbsolutePathFromFolderRelativeToOrganizationIngestionFolder({ path: moveToFolderPath, organizationIngestionFolderPath });++ await moveIngestionFile({ filePath, moveToFolder: path, fs });+ logger.info({ filePath }, 'File moved after ingestion');+ return;+ }++ throw createInvalidPostProcessingStrategyError({ strategy });+}++async function getFileOrganizationId({ filePath, ingestionFolderPath, organizationsRepository }: { filePath: string; ingestionFolderPath: string; organizationsRepository: OrganizationsRepository }) {+ const { relativeFilePath } = normalizeFilePathToIngestionFolder({ filePath, ingestionFolderPath });++ const { organizationId } = getOrganizationIdFromFilePath({ relativeFilePath });++ if (!organizationId) {+ return { organizationId: undefined };+ }++ const { organization } = await organizationsRepository.getOrganizationById({ organizationId });++ return { organizationId: organization.id };+}++async function buildPathIgnoreFunction({+ config,+ cwd = getRootDirPath(),+ organizationsRepository,+}: {+ config: Config;+ cwd?: string;+ organizationsRepository: OrganizationsRepository;+}) {+ const { ingestionFolder: { postProcessing: { strategy, moveToFolderPath }, errorFolder, ignoredPatterns, folderRootPath } } = config;++ const { organizationIds } = await organizationsRepository.getAllOrganizationIds();++ const doneFolders = strategy === 'move'+ ? isAbsolute(moveToFolderPath) ? moveToFolderPath : uniq(organizationIds.map(id => join(cwd, folderRootPath, id, moveToFolderPath)))+ : [];++ const errorFolders = isAbsolute(errorFolder) ? errorFolder : uniq(organizationIds.map(id => join(cwd, folderRootPath, id, errorFolder)));++ const ignoredFolders = [...doneFolders, ...errorFolders];+ const matchExcludedPatterns = picomatch(ignoredPatterns);++ return (path: string, stats?: Stats) => {+ const normalizedPath = isAbsolute(path) ? path : join(cwd, path);++ return Boolean(stats?.isFile()) && (ignoredFolders.some(folder => normalizedPath.startsWith(folder)) || matchExcludedPatterns(normalizedPath));+ };+}++export async function moveIngestionFile({+ filePath,+ moveToFolder,+ fs = createFsServices(),+ now = new Date(),+}: {+ filePath: string;+ moveToFolder: string;+ fs?: FsServices;+ now?: Date;+}) {+ const { base } = parse(filePath);+ const newFilePath = join(moveToFolder, base);++ await fs.ensureDirectoryExists({ path: moveToFolder });++ // Check if the destination file already exists+ const destinationFileExists = await fs.checkFileExists({ path: newFilePath });++ if (destinationFileExists) {+ // Check if the files have the same content+ const sameContent = await fs.areFilesContentIdentical({+ file1: filePath,+ file2: newFilePath,+ });++ if (sameContent) {+ // If same content, no need to move - just delete the source file+ await fs.deleteFile({ filePath });+ return;+ } else {+ // If different content, generate a new filename with timestamp+ const newFileName = addTimestampToFilename({ fileName: base, now });+ const timestampedFilePath = join(moveToFolder, newFileName);++ await fs.moveFile({ sourceFilePath: filePath, destinationFilePath: timestampedFilePath });+ return;+ }+ }++ // Default case: no conflict, simple move+ await fs.moveFile({ sourceFilePath: filePath, destinationFilePath: newFilePath });+}diff --git a/apps/papra-server/src/modules/organizations/organizations.repository.ts b/apps/papra-server/src/modules/organizations/organizations.repository.tsindex 4ebca1b4..aa0f3747 100644--- a/apps/papra-server/src/modules/organizations/organizations.repository.ts+++ b/apps/papra-server/src/modules/organizations/organizations.repository.ts@@ -22,6 +22,7 @@ export function createOrganizationsRepository({ db }: { db: Database }) {getUserOwnedOrganizationCount,getOrganizationOwner,getOrganizationMembersCount,+ getAllOrganizationIds,},{ db },);@@ -139,3 +140,11 @@ async function getOrganizationMembersCount({ organizationId, db }: { organizatiomembersCount,};}++async function getAllOrganizationIds({ db }: { db: Database }) {+ const organizationIds = await db.select({ id: organizationsTable.id }).from(organizationsTable);++ return {+ organizationIds: organizationIds.map(({ id }) => id),+ };+}diff --git a/apps/papra-server/src/modules/shared/errors/errors.ts b/apps/papra-server/src/modules/shared/errors/errors.tsindex 72a6ab93..63fa44a7 100644--- a/apps/papra-server/src/modules/shared/errors/errors.ts+++ b/apps/papra-server/src/modules/shared/errors/errors.ts@@ -1,7 +1,7 @@import type { ContentfulStatusCode } from 'hono/utils/http-status';import { get, isError, toString } from 'lodash-es';-export { createError, createErrorFactory, formatPublicErrorPayload, isCustomError };+export { createError, createErrorFactory, formatPublicErrorPayload, isCustomError, isErrorWithCode };type ErrorOptions = {message: string;@@ -45,3 +45,7 @@ function createErrorFactory(baseOption: ErrorOptions) {function isCustomError(error: unknown): error is CustomError {return get(error, 'isCustomError') === true && isError(error);}++function isErrorWithCode({ error, code }: { error: unknown; code: string }) {+ return isCustomError(error) && error.code === code;+}diff --git a/apps/papra-server/src/modules/shared/fs/fs.in-memory.ts b/apps/papra-server/src/modules/shared/fs/fs.in-memory.tsnew file mode 100644index 00000000..a08e9dea--- /dev/null+++ b/apps/papra-server/src/modules/shared/fs/fs.in-memory.ts@@ -0,0 +1,12 @@+import type { NestedDirectoryJSON } from 'memfs';+import { memfs } from 'memfs';+import { createFsServices, type FsNative } from './fs.services';++export function createInMemoryFsServices(volume: NestedDirectoryJSON) {+ const { vol } = memfs(volume);++ return {+ getFsState: () => vol.toJSON(),+ fs: createFsServices({ fs: vol.promises as unknown as FsNative }),+ };+}diff --git a/apps/papra-server/src/modules/shared/fs/fs.services.ts b/apps/papra-server/src/modules/shared/fs/fs.services.tsnew file mode 100644index 00000000..dc368868--- /dev/null+++ b/apps/papra-server/src/modules/shared/fs/fs.services.ts@@ -0,0 +1,67 @@+import { Buffer } from 'node:buffer';+import fsNative from 'node:fs/promises';+import { injectArguments } from '@corentinth/chisels';++export type FsNative = Pick<typeof fsNative, 'mkdir' | 'unlink' | 'rename' | 'readFile' | 'stat' | 'access' | 'constants'>;++export type FsServices = ReturnType<typeof createFsServices>;+export function createFsServices({ fs = fsNative }: { fs?: FsNative } = {}) {+ return injectArguments(+ {+ ensureDirectoryExists,+ checkFileExists,+ deleteFile,+ moveFile,+ readFile,+ areFilesContentIdentical,+ },+ {+ fs,+ },+ );+}++export async function ensureDirectoryExists({ path, fs = fsNative }: { path: string; fs?: FsNative }) {+ await fs.mkdir(path, { recursive: true });+}++export async function checkFileExists({ path, fs = fsNative }: { path: string; fs?: FsNative }) {+ try {+ await fs.access(path, fs.constants.F_OK);+ return true;+ } catch {+ return false;+ }+}++export async function deleteFile({ filePath, fs = fsNative }: { filePath: string; fs?: FsNative }) {+ await fs.unlink(filePath);+}++export async function moveFile({ sourceFilePath, destinationFilePath, fs = fsNative }: { sourceFilePath: string; destinationFilePath: string; fs?: FsNative }) {+ await fs.rename(sourceFilePath, destinationFilePath);+}++export async function readFile({ filePath, fs = fsNative }: { filePath: string; fs?: FsNative }) {+ return await fs.readFile(filePath);+}++export async function areFilesContentIdentical({ file1, file2, fs = fsNative }: { file1: string; file2: string; fs?: FsNative }): Promise<boolean> {+ try {+ // Check if file sizes are different (quick check before comparing content)+ const stats1 = await fs.stat(file1);+ const stats2 = await fs.stat(file2);++ if (stats1.size !== stats2.size) {+ return false;+ }++ // Compare file contents+ const content1 = await readFile({ filePath: file1, fs });+ const content2 = await readFile({ filePath: file2, fs });++ return Buffer.compare(content1, content2) === 0;+ } catch (_) {+ return false;+ }+}diff --git a/apps/papra-server/src/modules/shared/path.ts b/apps/papra-server/src/modules/shared/path.tsindex f8115eba..c7ef405c 100644--- a/apps/papra-server/src/modules/shared/path.ts+++ b/apps/papra-server/src/modules/shared/path.ts@@ -1,5 +1,4 @@import process from 'node:process';+import { memoize } from 'lodash-es';-export function getRootDirPath() {- return process.cwd();-}+export const getRootDirPath = memoize(() => process.cwd());diff --git a/docker/Dockerfile b/docker/Dockerfileindex fa8009f8..0cd068cb 100644--- a/docker/Dockerfile+++ b/docker/Dockerfile@@ -39,6 +39,6 @@ ENV DATABASE_URL=file:./app-data/db/db.sqliteENV DOCUMENT_STORAGE_FILESYSTEM_ROOT=./app-data/documentsENV PAPRA_CONFIG_DIR=./app-data-RUN mkdir -p ./app-data/db ./app-data/documents+RUN mkdir -p ./app-data/db ./app-data/documents ./ingestionCMD ["pnpm", "start:with-migrations"]diff --git a/docker/Dockerfile.rootless b/docker/Dockerfile.rootlessindex d40565f7..07d895bb 100644--- a/docker/Dockerfile.rootless+++ b/docker/Dockerfile.rootless@@ -48,5 +48,6 @@ ENV SERVER_SERVE_PUBLIC_DIR=trueENV DATABASE_URL=file:./app-data/db/db.sqliteENV DOCUMENT_STORAGE_FILESYSTEM_ROOT=./app-data/documentsENV PAPRA_CONFIG_DIR=./app-data+ENV INGESTION_FOLDER_ROOT=./ingestionCMD ["pnpm", "start:with-migrations"]\ No newline at end of filediff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8619cbde..0cd41c79 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -253,6 +253,9 @@ importers:c12:specifier: ^3.0.2version: 3.0.2([email protected])+ chokidar:+ specifier: ^4.0.3+ version: 4.0.3date-fns:specifier: ^4.1.0version: 4.1.0@@ -271,12 +274,21 @@ importers:lodash-es:specifier: ^4.17.21version: 4.17.21+ mime-types:+ specifier: ^3.0.1+ version: 3.0.1node-cron:specifier: ^3.0.3version: 3.0.3p-limit:specifier: ^6.2.0version: 6.2.0+ p-queue:+ specifier: ^8.1.0+ version: 8.1.0+ picomatch:+ specifier: ^4.0.2+ version: 4.0.2posthog-node:specifier: ^4.11.1version: 4.11.1@@ -305,12 +317,18 @@ importers:'@types/lodash-es':specifier: ^4.17.12version: 4.17.12+ '@types/mime-types':+ specifier: ^2.1.4+ version: 2.1.4'@types/node':specifier: ^22.10.2version: 22.13.10'@types/node-cron':specifier: ^3.0.11version: 3.0.11+ '@types/picomatch':+ specifier: ^4.0.0+ version: 4.0.0'@vitest/coverage-v8':specifier: 'catalog:'version: 3.0.2([email protected](@types/[email protected])(@types/[email protected])([email protected]))@@ -320,6 +338,9 @@ importers:eslint:specifier: 'catalog:'version: 9.22.0([email protected])+ memfs:+ specifier: ^4.17.0+ version: 4.17.0typescript:specifier: 'catalog:'version: 5.8.2@@ -1890,6 +1911,24 @@ packages:'@jridgewell/[email protected]':resolution: {integrity: sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==}+ '@jsonjoy.com/[email protected]':+ resolution: {integrity: sha512-q6XAnWQDIMA3+FTiOYajoYqySkO+JSat0ytXGSuRdq9uXE7o92gzuQwQM14xaCRlBLGq3v5miDGC4vkVTn54xA==}+ engines: {node: '>=10.0'}+ peerDependencies:+ tslib: '2'++ '@jsonjoy.com/[email protected]':+ resolution: {integrity: sha512-io1zEbbYcElht3tdlqEOFxZ0dMTYrHz9iMf0gqn1pPjZFTCgM5R4R5IMA20Chb2UPYYsxjzs8CgZ7Nb5n2K2rA==}+ engines: {node: '>=10.0'}+ peerDependencies:+ tslib: '2'++ '@jsonjoy.com/[email protected]':+ resolution: {integrity: sha512-ojoNsrIuPI9g6o8UxhraZQSyF2ByJanAY4cTFbc8Mf2AXEF4aQRGY1dJxyJpuyav8r9FGflEt/Ff3u5Nt6YMPA==}+ engines: {node: '>=10.0'}+ peerDependencies:+ tslib: '2'+'@kobalte/[email protected]':resolution: {integrity: sha512-+Ta2o2wEqZ2fCqLMkvjT40VHNmcFKdGe8TNDVQbbMPk66qoU6g/DDRFR/Ib7eAjb+C95VoIyk6zaafos2VOo0w==}peerDependencies:@@ -2826,6 +2865,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-+OWZQfAYyio6YkJb3HLxDrvnx6SWWDbC0zVPfBRzUk0/nqoDyf6dNxQi3eArPe8rJ473nobTMQ/8Zk+LxJ+Yuw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-lfU4b34HOri+kAY5UheuFMWPDOI+OPceBSHZKp69gEyTL/mmJ4cnU6Y/rlme3UL3GyOn6Y42hyIEw0/q8sWx5w==}+'@types/[email protected]':resolution: {integrity: sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==}@@ -2844,6 +2886,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-J1Bng+wlyEERWSgJQU1Pi0HObCLVcr994xT/M+1wcl/yNRTGBupsCxthgkdYG+GCOMaQH7iSVUY3LJVBBqG7MQ==}+'@types/[email protected]':resolution: {integrity: sha512-rO73L89PJxeYM3s3pPPjiPgVVcymqU490g0YO5n5By0k2Erzj6tay/4lr1CHAAU4JyOWd1rpQ8bCf6cZfHU96A==}@@ -4560,6 +4605,10 @@ packages:resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}engines: {node: '>= 14'}+ resolution: {integrity: sha512-Y93lCzHYgGWdrJ66yIktxiaGULYc6oGiABxhcO5AufBeOyoIdZF7bIfLaOrbM0iGIOXQQgxxRrFEnb+Y6w1n4A==}+ engines: {node: '>=10.18'}+resolution: {integrity: sha512-06r/TitrM88Mg5FdUXAKL96dJMzgqLE5dv3ryBAra4KCwD9mJ4ndOTS95ZuymIGoE+2hzfdaMak2X11/es7ZWg==}@@ -4971,6 +5020,10 @@ packages:resolution: {integrity: sha512-IEn+pegP1aManZuckezWCO+XZQDplx1366JoVhTpMpBB1sPey/SbveZQUosKiKiGYjg1wH4pMlNgXbCiYgihQA==}+ resolution: {integrity: sha512-4eirfZ7thblFmqFjywlTmuWVSvccHAJbn1r8qQLzmTO11qcqpohOjmY2mFce6x7x7WtskzRqApPD0hv+Oa74jg==}+ engines: {node: '>= 4.0.0'}+resolution: {integrity: sha512-eRtbOb1N5iyH0tkQDAoQ4Ipsp/5qSR79Dzrz8hEPxRX10RWWR/iQXdoKmBSRCThY1Fh5EhISDtpSc93fpxUniQ==}engines: {node: '>=12.13'}@@ -5104,10 +5157,18 @@ packages:resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==}+ engines: {node: '>= 0.6'}+resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==}+ engines: {node: '>= 0.6'}+resolution: {integrity: sha512-wXqjST+SLt7R009ySCglWBCFpjUygmCIfD790/kVbiGmUgfYGuB14PiTd5DwVxSV4NcYHjzMkoj5LjQZwTQLEA==}engines: {node: '>=8'}@@ -6087,6 +6148,12 @@ packages:resolution: {integrity: sha512-3/o9z3X0X0fTupwsYvR03pJ/DjWuqqrfwBgTQzdWDiQSm9KitAyz/9WqsT2JQW7KV2m+bC2ol/zqpW37NHxLaA==}+ resolution: {integrity: sha512-hsqsJsFMsV+aD4s3CWKk85ep/3I9XzYV/IXaSouJMYIoDlgyi11cBhsqYe9/geRfB0YIikBQg6raRaM+nIMP9g==}+ engines: {node: '>=10.18'}+ peerDependencies:+ tslib: ^2+resolution: {integrity: sha512-N5+AZWdBeHNSgTIaxvx0+9mFrnW4H1BbjQ84H7i3TuWSkno8Hju886hLaHZhE/hYEKrfrfl/uHurqpZJHDuYGQ==}@@ -6142,6 +6209,12 @@ packages:resolution: {integrity: sha512-IUWnUK7ADYR5Sl1fZlO1INDUhVhatWl7BtJWsIhwJ0UAK7ilzzIa8uIqOO/aYVWHZPJkKbEL+362wrzoeRF7bw==}engines: {node: '>=18'}+ resolution: {integrity: sha512-dpev9ABuLWdEubk+cIaI9cHwRNNDjkBBLXTwI4UCUFdQ5xXKqNXoK4FEciw/vxf+NQ7Cb7sGUyeUtORvHIdRXQ==}+ engines: {node: '>=10.0'}+ peerDependencies:+ tslib: '2'+resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}@@ -8343,6 +8416,22 @@ snapshots:'@jridgewell/resolve-uri': 3.1.2'@jridgewell/sourcemap-codec': 1.5.0+ '@jsonjoy.com/[email protected]([email protected])':+ dependencies:+ tslib: 2.8.1++ '@jsonjoy.com/[email protected]([email protected])':+ dependencies:+ '@jsonjoy.com/base64': 1.1.2([email protected])+ '@jsonjoy.com/util': 1.5.0([email protected])+ hyperdyperid: 1.2.0+ thingies: 1.21.0([email protected])+ tslib: 2.8.1++ '@jsonjoy.com/[email protected]([email protected])':+ dependencies:+ tslib: 2.8.1+'@kobalte/[email protected]([email protected])':dependencies:'@floating-ui/dom': 1.6.12@@ -9417,6 +9506,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]':@@ -9433,6 +9524,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]':dependencies:'@types/node': 22.13.10@@ -11760,6 +11853,8 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]: {}+dependencies:'@babel/runtime': 7.27.0@@ -12316,6 +12411,13 @@ snapshots:+ dependencies:+ '@jsonjoy.com/json-pack': 1.2.0([email protected])+ '@jsonjoy.com/util': 1.5.0([email protected])+ tree-dump: 1.0.2([email protected])+ tslib: 2.8.1+dependencies:is-what: 4.1.16@@ -12631,10 +12733,16 @@ snapshots:+ [email protected]: {}+dependencies:mime-db: 1.52.0+ dependencies:+ mime-db: 1.54.0+optional: true@@ -13828,6 +13936,10 @@ snapshots:dependencies:b4a: 1.6.7+ dependencies:+ tslib: 2.8.1+@@ -13871,6 +13983,10 @@ snapshots:dependencies:punycode: 2.3.1+ dependencies:+ tslib: 2.8.1+