### Basic Flystorage Setup with Local Adapter Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Demonstrates the basic setup of Flystorage using the LocalStorageAdapter. It initializes the storage with a specified root directory and prepares it for file operations. ```typescript import {FileStorage} from '@flystorage/file-storage'; import {LocalStorageAdapter} from '@flystorage/local-fs'; import {resolve} from 'path'; const rootDirectory = resolve(process.cwd(), 'my-files'); const adapter = new LocalStorageAdapter(rootDirectory); const storage = new FileStorage(adapter); // Now use storage for all file operations ``` -------------------------------- ### Setup In-Memory Storage Adapter with Flystorage Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Demonstrates how to set up an in-memory storage adapter for Flystorage, suitable for testing and caching. It shows the installation process and basic usage, including file writing and existence checks. This adapter stores all data in memory and requires no configuration. ```bash npm install --save @flystorage/file-storage @flystorage/in-memory ``` ```typescript import {FileStorage} from '@flystorage/file-storage'; import {InMemoryStorageAdapter} from '@flystorage/in-memory'; // Create in-memory adapter (no configuration needed) const adapter = new InMemoryStorageAdapter(); const storage = new FileStorage(adapter); // Use normally - all data stored in memory await storage.write('test/file.txt', 'Test data'); const exists = await storage.fileExists('test/file.txt'); // true // Perfect for unit tests import {describe, it, beforeEach} from 'mocha'; import {expect} from 'chai'; describe('File upload service', () => { let storage: FileStorage; beforeEach(() => { const adapter = new InMemoryStorageAdapter(); storage = new FileStorage(adapter); }); it('should upload file', async () => { await storage.write('uploads/test.txt', 'data'); expect(await storage.fileExists('uploads/test.txt')).to.be.true; }); }); ``` -------------------------------- ### Install Flystorage Local FS Adapter Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/adapter/local-fs.md Installs the necessary Flystorage packages for local filesystem operations using npm. ```bash npm install --save @flystorage/file-storage @flystorage/local-fs ``` -------------------------------- ### Setup Google Cloud Storage Adapter for Flystorage Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Integrate Flystorage with Google Cloud Storage. This involves installing the required packages and configuring the GCS client with project and key details. ```bash npm install --save @flystorage/file-storage @flystorage/google-cloud-storage @google-cloud/storage ``` ```typescript import {FileStorage} from '@flystorage/file-storage'; import {GoogleCloudStorageStorageAdapter, LegacyVisibilityHandling} from '@flystorage/google-cloud-storage'; import {Storage} from '@google-cloud/storage'; // Configure GCS client const client = new Storage({ projectId: 'my-project', keyFilename: './service-account-key.json', }); // Get bucket reference const bucket = client.bucket('my-bucket', { userProject: 'my-project', }); // Create adapter const adapter = new GoogleCloudStorageStorageAdapter(bucket, { prefix: 'app-data/', // Optional path prefix }); const storage = new FileStorage(adapter); // For legacy buckets with ACL-based visibility const legacyAdapter = new GoogleCloudStorageStorageAdapter( bucket, {prefix: 'app-data/'}, new LegacyVisibilityHandling( 'allUsers', // ACL entity 'publicRead', // ACL for PUBLIC 'projectPrivate' // ACL for PRIVATE ) ); const legacyStorage = new FileStorage(legacyAdapter); ``` -------------------------------- ### Install Flystorage Chaos Adapter Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/tools/chaos.md Installs the necessary packages for the Flystorage Chaos adapter using npm. ```bash npm install --save @flystorage/file-storage @flystorage/chaos ``` -------------------------------- ### Setup Flystorage Local FS Adapter Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/adapter/local-fs.md Demonstrates setting up the Flystorage LocalStorageAdapter with a specified root directory. ```typescript import {FileStorage} from '@flystorage/file-storage'; import {LocalStorageAdapter} from '@flystorage/local-fs'; const rootDirectory = resolve(process.cwd(), 'my-files'); const adapter = new LocalStorageAdapter(rootDirectory); const storage = new FileStorage(adapter); ``` -------------------------------- ### Install Flystorage and In-Memory Packages Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/adapter/in-memory.md Installs the necessary packages for Flystorage and the in-memory adapter using npm. This command ensures that both the core file storage library and the in-memory adapter are available for use in the project. ```bash npm install --save @flystorage/file-storage @flystorage/in-memory ``` -------------------------------- ### Setup AWS S3 Adapter for Flystorage Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Connect Flystorage to Amazon S3 using the AWS SDK v3. Requires installation of necessary packages and configuration of AWS credentials and bucket details. ```bash npm install --save @flystorage/file-storage @flystorage/aws-s3 @aws-sdk/client-s3 ``` ```typescript import {FileStorage} from '@flystorage/file-storage'; import {AwsS3StorageAdapter} from '@flystorage/aws-s3'; import {S3Client} from '@aws-sdk/client-s3'; // Configure S3 client (uses AWS credentials from environment) const client = new S3Client({ region: 'us-east-1', credentials: { accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }, }); // Create adapter with bucket and optional prefix const adapter = new AwsS3StorageAdapter(client, { bucket: 'my-app-bucket', prefix: 'uploads/', // Optional path prefix }); const storage = new FileStorage(adapter); // Use normally - all operations work the same await storage.write('user-files/document.pdf', pdfBuffer); const publicUrl = await storage.publicUrl('user-files/document.pdf'); ``` -------------------------------- ### Essential Astro Project Commands Source: https://github.com/duna-oss/flystorage-docs/blob/main/README.md A list of common commands used to manage and interact with an Astro project. These commands cover dependency installation, running a local development server, building for production, and previewing the build. ```bash npm install npm run dev npm run build npm run preview npm run astro ... npm run astro -- --help ``` -------------------------------- ### Setup Azure Blob Storage Adapter for Flystorage Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Connect Flystorage to Azure Blob Storage. This requires installing the relevant packages and configuring the BlobServiceClient with a connection string. ```bash npm install --save @flystorage/file-storage @flystorage/azure-storage-blob @azure/storage-blob ``` ```typescript import {FileStorage} from '@flystorage/file-storage'; import {AzureStorageBlobStorageAdapter} from '@flystorage/azure-storage-blob'; import {BlobServiceClient} from '@azure/storage-blob'; // Connect using connection string const blobService = BlobServiceClient.fromConnectionString( process.env.AZURE_STORAGE_CONNECTION_STRING ); // Get container client const container = blobService.getContainerClient('app-files'); // Create adapter const adapter = new AzureStorageBlobStorageAdapter(container); const storage = new FileStorage(adapter); // Use normally await storage.write('uploads/file.txt', 'Contents'); const tempUrl = await storage.temporaryUrl('uploads/file.txt', Date.now() + 3600000); ``` -------------------------------- ### Install Flystorage Google Cloud Storage Adapter Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/adapter/google-cloud-storage.md Installs the necessary packages for using the Flystorage adapter with Google Cloud Storage. This includes the core Flystorage library, the Google Cloud Storage adapter, and the official Google Cloud Storage client library. ```bash npm install --save @flystorage/file-storage @flystorage/google-cloud-storage @google-cloud/storage ``` -------------------------------- ### Create Astro Project with Starlight Tailwind Template Source: https://github.com/duna-oss/flystorage-docs/blob/main/README.md This command initiates the creation of a new Astro project using the official Starlight template, pre-configured with Tailwind CSS. It requires Node.js and npm (or yarn/pnpm) to be installed. ```bash npm create astro@latest -- --template starlight/tailwind ``` -------------------------------- ### Install Flystorage AWS S3 Adapter Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/adapter/aws-s3.md Installs the necessary packages for using the Flystorage AWS S3 adapter. This includes the core Flystorage library, the AWS S3 adapter, and the AWS SDK V3 client for S3. ```bash npm install --save @flystorage/file-storage @flystorage/aws-s3 @aws-sdk/client-s3 ``` -------------------------------- ### Setup Flystorage with Chaos Adapter (TypeScript) Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/tools/chaos.md Demonstrates how to set up a Flystorage instance using the ChaosStorageAdapterDecorator in TypeScript. It requires importing necessary classes and creating an instance of the strategy and the adapter. ```typescript import {FileStorage} from '@flystorage/file-storage'; import {ChaosStorageAdapterDecorator, TriggeredErrors} from '@flystorage/chaos'; const strategy = new TriggeredErrors(); const adapter = new ChaosStorageAdapterDecorator( createActualAdapter(), strategy, ); const storage = new FileStorage(adapter); ``` -------------------------------- ### Install Flystorage Azure Blob Dependencies Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/adapter/azure-storage-blob.md Installs the necessary packages for using the Flystorage Azure Storage Blob adapter. This includes the core Flystorage library, the Azure Blob adapter, and the official Azure Blob SDK. ```bash npm install --save @flystorage/file-storage @flystorage/azure-storage-blob @azure/storage-blob ``` -------------------------------- ### Install @flystorage/file-storage and @flystorage/multer-storage Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/tools/multer.md Installs the necessary packages for integrating FlyStorage with Multer in an Express application. This includes the core file storage library and the Multer-specific storage engine. ```bash npm install --save @flystorage/file-storage @flystorage/multer-storage ``` -------------------------------- ### Setup Flystorage Google Cloud Storage Adapter Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/adapter/google-cloud-storage.md Demonstrates how to initialize the Flystorage adapter for Google Cloud Storage. It requires creating a Google Cloud Storage client, specifying a bucket and optionally a user project, and then instantiating the adapter with the bucket and any desired prefix. ```typescript import { FileStorage } from '@flystorage/file-storage'; import { GoogleCloudStorageStorageAdapter } from '@flystorage/google-cloud-storage'; import { Storage } from '@google-cloud/storage'; const client = new Storage(); const bucket = googleStorage.bucket('{bucket-name}}', { userProject: '{user-project}}', }); const adapter = new GoogleCloudStorageStorageAdapter(bucket, { prefix: '{optional-path-prefix}', }); const storage = new FileStorage(adapter); ``` -------------------------------- ### Install @flystorage/stream-mime-type Package Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/tools/stream-mime-type.md Installs the @flystorage/stream-mime-type package using npm. This package is essential for using the stream mime-type resolution utilities. ```bash npm install --save @flystorage/stream-mime-type ``` -------------------------------- ### Setup Flystorage with AWS S3 Adapter Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/adapter/aws-s3.md Demonstrates how to set up the Flystorage with the AWS S3 adapter. It initializes an S3 client and an adapter instance with bucket and optional prefix configurations, then creates a FileStorage instance. ```typescript import {FileStorage} from '@flystorage/file-storage'; import {AwsS3StorageAdapter} from '@flystorage/aws-s3'; import {S3Client} from '@aws-sdk/client-s3'; const client = new S3Client(); const adapter = new AwsS3StorageAdapter(client, { bucket: '{your-bucket-name}', prefix: '{optional-path-prefix}', }); const storage = new FileStorage(adapter); ``` -------------------------------- ### Setup Flystorage with In-Memory Adapter Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/adapter/in-memory.md Demonstrates how to set up Flystorage with the in-memory adapter in TypeScript. It initializes an InMemoryStorageAdapter and then creates a new FileStorage instance using this adapter. This is a common pattern for testing or temporary storage needs. ```typescript import {FileStorage} from '@flystorage/file-storage'; import {InMemoryStorageAdapter} from '@flystorage/in-memory'; const adapter = new InMemoryStorageAdapter(); const storage = new FileStorage(adapter); ``` -------------------------------- ### Setup Flystorage Google Cloud Storage with Legacy Visibility Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/adapter/google-cloud-storage.md Configures the Flystorage Google Cloud Storage adapter to handle legacy visibility settings. This is achieved by passing an instance of `LegacyVisibilityHandling` to the adapter's constructor, allowing specification of ACL entities and default ACLs for public and private visibility. ```typescript import { GoogleCloudStorageStorageAdapter, LegacyVisibilityHandling } from '@flystorage/google-cloud-storage'; const adapter = new GoogleCloudStorageStorageAdapter(bucket, { prefix: '{optional-path-prefix}', }, new LegacyVisibilityHandling( 'allUsers', // acl entity, optional 'publicRead', // acl for Visibility.PUBLIC, optional, 'projectPrivate', // acl for Visibility.PRIVATE, optional, )); ``` -------------------------------- ### Get File/Directory Info with Flystorage Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md Retrieves file or directory information using `stat` or `statFile` methods. `statFile` ensures the result is a `FileInfo` and fails for directories. Handles potential errors during stat retrieval. ```typescript try { const stat = await storage.stat('path/to/file.txt'); } catch (err) { if (err instanceof UnableToGetStat) { // handle error } } ``` -------------------------------- ### Integrate Flystorage with Express and Multer Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Explains how to integrate Flystorage with Express.js for handling file uploads using Multer. It covers installation, setting up a Flystorage adapter, creating a Multer storage engine, and defining Express routes for single and multiple file uploads. Includes path resolution for uploaded files. ```bash npm install --save @flystorage/file-storage @flystorage/multer-storage multer express npm install --save-dev @types/multer @types/express ``` ```typescript import {FileStorage} from '@flystorage/file-storage'; import {FlystorageMulterStorageEngine} from '@flystorage/multer-storage'; import multer from 'multer'; import express from 'express'; // Setup storage adapter (any adapter) const adapter = new AwsS3StorageAdapter(s3Client, {bucket: 'uploads'}); const fileStorage = new FileStorage(adapter); // Create Multer storage engine with custom path resolver const storage = new FlystorageMulterStorageEngine( fileStorage, async (action, req: express.Request, file: Express.Multer.File) => { if (action === 'handle') { // Return the destination path for the uploaded file const timestamp = Date.now(); const safeName = file.originalname.replace(/[^a-z0-9.-]/gi, '_'); return `uploads/${timestamp}-${safeName}`; } else { // Return path for removal (if needed) return file.destination; } } ); // Create multer instance const uploader = multer({ storage, limits: {fileSize: 10 * 1024 * 1024}, // 10MB limit }); // Setup Express routes const app = express(); // Single file upload app.post('/upload/document', uploader.single('document'), (req, res) => { if (!req.file) { return res.status(400).json({error: 'No file uploaded'}); } res.json({ filename: req.file.filename, size: req.file.size, path: req.file.path, }); }); // Multiple files upload app.post('/upload/photos', uploader.array('photos', 5), (req, res) => { if (!req.files || req.files.length === 0) { return res.status(400).json({error: 'No files uploaded'}); } const files = req.files as Express.Multer.File[]; res.json({ count: files.length, files: files.map(f => ({ filename: f.filename, size: f.size, })), }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); ``` -------------------------------- ### Get File Size - TypeScript Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md Retrieves the size of a specified file using the `fileSize` method. It includes error handling for `UnableToGetFileSize` exceptions. ```typescript try { const size = await storage.fileSize('path/to/file.txt'); } catch (err) { if (err instanceof UnableToGetFileSize) { // handle error } } ``` -------------------------------- ### Get Stream Head (Sample) Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/tools/stream-mime-type.md Extracts a sample (head) from the beginning of a stream without consuming the entire stream. It takes the original stream and the desired sample size in bytes, returning the sample data and the remaining stream. ```typescript import {streamHead} from '@flystorage/stream-mime-type'; const originalStream = fs.createReadStream(pathToFile); const [sample, stream] = streamHead(originalStream, sizeInBytes); ``` -------------------------------- ### Get File Metadata (Stat) (TypeScript) Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Retrieves detailed metadata for a file or directory, including size, modification date, and MIME type. Includes a specific method for ensuring the target is a file. Handles errors if metadata cannot be retrieved. ```typescript try { // Get stat information const stat = await storage.stat('documents/report.txt'); if (stat.isFile) { console.log(`File size: ${stat.fileSize} bytes`); console.log(`Last modified: ${new Date(stat.lastModifiedMs)}`); console.log(`MIME type: ${stat.mimeType}`); } // Ensure it's a file (throws if directory) const fileStat = await storage.statFile('documents/report.txt'); console.log(`Confirmed file size: ${fileStat.fileSize}`); } catch (err) { if (err instanceof UnableToGetStat) { console.error('Failed to get stat:', err.message); } } ``` -------------------------------- ### Get File Last Modified Timestamp in TypeScript Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md The `lastModified` method retrieves the timestamp of the last modification for a specified file. It takes the file path as input. Errors can occur if the modification time cannot be determined. ```typescript try { const timestamp = await storage.lastModified('path/to/file.txt'); } catch (err) { if (err instanceof UnableToGetLastModified) { // handle error } } ``` -------------------------------- ### Get File MIME Type in TypeScript Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md The `mimeType` method resolves and returns the MIME type of a file based on its path. This operation might fail and throw an error if the MIME type cannot be determined by the storage adapter. ```typescript try { const mimetype = await storage.mimeType('path/to/file.txt'); } catch (err) { if (err instanceof UnableToGetMimeType) { // handle error } } ``` -------------------------------- ### Get File Checksum - TypeScript Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md Resolves the hash, checksum, or etag of a file using the `checksum` method. Supports optional `algo` and `encoding` options for custom checksum types and encodings. Includes error handling for `UnableToGetChecksum` exceptions. ```typescript try { const checksum = await storage.checksum('path/to/file.txt', optionalOptions); } catch (err) { if (err instanceof UnableToGetChecksum) { // handle error } } ``` -------------------------------- ### Get Public File URL in TypeScript Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md The `publicUrl` method generates a publicly accessible URL for a given file path. If the storage adapter does not support public URLs, an error may be thrown. Some adapters might require additional configuration for URL generation. ```typescript try { const url = await storage.publicUrl('path/to/file.txt'); } catch (err) { if (err instanceof UnableToGetPublicUrl) { // handle error } } ``` -------------------------------- ### Astro Project Structure Overview Source: https://github.com/duna-oss/flystorage-docs/blob/main/README.md This visual representation outlines the typical directory and file structure of an Astro project using the Starlight template. It highlights key directories like `public/` for static assets and `src/content/docs/` for documentation files. ```tree . ├── public/ ├── src/ │ ├── assets/ │ ├── content/ │ │ ├── docs/ │ │ └── config.ts │ └── env.d.ts ├── astro.config.ts ├── package.json ├── tailwind.config.mjs └── tsconfig.json ``` -------------------------------- ### Initialize Flystorage with Azure Blob Adapter Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/adapter/azure-storage-blob.md Demonstrates how to set up and initialize the Flystorage file storage system using the Azure Storage Blob adapter. It shows the instantiation of the BlobServiceClient, obtaining a container client, and then creating the adapter and FileStorage instance. ```typescript import {FileStorage} from '@flystorage/file-storage'; import {AzureStorageBlobStorageAdapter} from '@flystorage/azure-storage-blob'; import {BlobServiceClient} from '@azure/storage-blob'; const blobService = BlobServiceClient.fromConnectionString(process.env.AZURE_DSN!); const container = blobService.getContainerClient('flysystem'); const adapter = new AzureStorageBlobStorageAdapter(container); const storage = new FileStorage(adapter); ``` -------------------------------- ### Write Files with Flystorage (TypeScript) Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Shows how to write files to storage using various input types like strings, Buffers, or streams. It also demonstrates setting public visibility for files and includes error handling for write operations. ```typescript import {FileStorage} from '@flystorage/file-storage'; import {Visibility} from '@flystorage/file-storage'; const storage = new FileStorage(adapter); try { // Write a string await storage.write('documents/report.txt', 'File contents here'); // Write with visibility control await storage.write('public/avatar.jpg', imageBuffer, { visibility: Visibility.PUBLIC, }); // Write a stream const readStream = fs.createReadStream('source.dat'); await storage.write('data/backup.dat', readStream); } catch (err) { if (err instanceof UnableToWriteFile) { console.error('Failed to write file:', err.message); } } ``` -------------------------------- ### Create Directories with Flystorage (TypeScript) Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Shows how to explicitly create directories using Flystorage. The operation may be a no-op for storage systems that do not support directory structures. Nested directories are created automatically. ```typescript try { // Create directory with all parent directories await storage.createDirectory('projects/2024/reports'); } catch (err) { if (err instanceof UnableToCreateDirectory) { console.error('Failed to create directory:', err.message); } } ``` -------------------------------- ### Configure Express with Flystorage Multer Storage Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/tools/multer.md Sets up an Express application to handle file uploads using Multer and FlyStorage. It demonstrates initializing the FileStorage, creating a FlystorageMulterStorageEngine, configuring Multer, and defining an upload route. ```typescript import {FileStorage} from '@flystorage/file-storage'; import {FlystorageMulterStorageEngine} from '@flystorage/multer-storage'; import multer from 'multer'; import express from 'express'; const adapter = createYourAdapter(); const fileStorage = new FileStorage(adapter); const storage = new FlystorageMulterStorageEngine( uploadStorage, async (action, _req: express.Request, file: Express.Multer.File) => { if (action === 'handle') { return file.originalname; } else { return file.destination; } } ); const uploader = multer({storage}); const app = express(); app.post('/upload/document', uploader.single('document'), , (req, res, next) => { // req.file is the `document` file // req.body will hold the text fields, if there were any }); app.listen(3000); ``` -------------------------------- ### TypeScript Custom Storage Adapter Template Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/custom-adapter.md This TypeScript code provides a template for implementing a custom storage adapter for Flysystem. It includes all necessary methods from the StorageAdapter interface, allowing developers to fill in their specific logic. Dependencies include the '@flystorage/file-storage' package. ```typescript import {Readable} from 'stream'; import { StorageAdapter, ChecksumOptions, CreateDirectoryOptions, FileContents, MimeTypeOptions, PublicUrlOptions, StatEntry, TemporaryUrlOptions, WriteOptions, PathPrefixer, CopyFileOptions, MoveFileOptions, } from '@flystorage/file-storage'; export type AdapterFileStorageOptions = { prefix?: string, } export class AdapterFileStorage implements StorageAdapter { private readonly prefixer: PathPrefixer; constructor( private readonly options: AdapterFileStorageOptions = {}, ) { this.prefixer = new PathPrefixer(options.prefix || ''); } async write(path: string, contents: Readable, options: WriteOptions): Promise { throw new Error('Not implemented'); } async read(path: string): Promise { throw new Error('Not implemented'); } async deleteFile(path: string): Promise { throw new Error('Not implemented'); } async createDirectory(path: string, options: CreateDirectoryOptions): Promise { throw new Error('Not implemented'); } async stat(path: string): Promise { throw new Error('Not implemented'); } list(path: string, options: {deep: boolean}): AsyncGenerator { throw new Error('Not implemented'); } async changeVisibility(path: string, visibility: string): Promise { throw new Error('Not implemented'); } async visibility(path: string): Promise { throw new Error('Not implemented'); } async deleteDirectory(path: string): Promise { throw new Error('Not implemented'); } async fileExists(path: string): Promise { throw new Error('Not implemented'); } async directoryExists(path: string): Promise { throw new Error('Not implemented'); } async publicUrl(path: string, options: PublicUrlOptions): Promise { throw new Error('Not implemented'); } async temporaryUrl(path: string, options: TemporaryUrlOptions): Promise { throw new Error('Not implemented'); } async checksum(path: string, options: ChecksumOptions): Promise { throw new Error('Not implemented'); } async mimeType(path: string, options: MimeTypeOptions): Promise { throw new Error('Not implemented'); } async lastModified(path: string): Promise { throw new Error('Not implemented'); } async fileSize(path: string): Promise { throw new Error('Not implemented'); } async copyFile(from: string, to: string, options: CopyFileOptions): Promise { throw new Error('Not implemented'); } async moveFile(from: string, to: string, options: MoveFileOptions): Promise { throw new Error('Not implemented'); } } ``` -------------------------------- ### Implement Custom Storage Adapter in TypeScript Source: https://context7.com/duna-oss/flystorage-docs/llms.txt This snippet shows how to implement the StorageAdapter interface in TypeScript to create a custom adapter for FlyStorage. It covers essential methods like write, read, delete, stat, and list, demonstrating path prefixing and interaction with a hypothetical backend. Dependencies include `@flystorage/file-storage` and Node.js streams. ```typescript import {Readable} from 'stream'; import { StorageAdapter, ChecksumOptions, CreateDirectoryOptions, FileContents, MimeTypeOptions, PublicUrlOptions, StatEntry, TemporaryUrlOptions, WriteOptions, PathPrefixer, CopyFileOptions, MoveFileOptions, } from '@flystorage/file-storage'; export type CustomStorageOptions = { prefix?: string; apiKey: string; endpoint: string; } export class CustomStorageAdapter implements StorageAdapter { private readonly prefixer: PathPrefixer; constructor(private readonly options: CustomStorageOptions) { this.prefixer = new PathPrefixer(options.prefix || ''); } async write(path: string, contents: Readable, options: WriteOptions): Promise { const prefixedPath = this.prefixer.prefixPath(path); // Implement your write logic // Stream contents to your storage backend } async read(path: string): Promise { const prefixedPath = this.prefixer.prefixPath(path); // Return a Readable stream from your storage return createReadStreamFromYourBackend(prefixedPath); } async deleteFile(path: string): Promise { const prefixedPath = this.prefixer.prefixPath(path); // Delete file from your storage } async stat(path: string): Promise { const prefixedPath = this.prefixer.prefixPath(path); // Return file metadata return { type: 'file', path: this.prefixer.stripPrefix(prefixedPath), lastModifiedMs: 1234567890, fileSize: 1024, mimeType: 'text/plain', isFile: true, isDirectory: false, }; } async *list(path: string, options: {deep: boolean}): AsyncGenerator { const prefixedPath = this.prefixer.prefixPath(path); // Yield entries from your storage for (const item of await fetchListFromYourBackend(prefixedPath, options.deep)) { yield { type: item.isDirectory ? 'directory' : 'file', path: this.prefixer.stripPrefix(item.path), lastModifiedMs: item.lastModified, fileSize: item.size, isFile: !item.isDirectory, isDirectory: item.isDirectory, }; } } async fileExists(path: string): Promise { const prefixedPath = this.prefixer.prefixPath(path); // Check if file exists return checkExistsInYourBackend(prefixedPath); } // Implement remaining methods... async createDirectory(path: string, options: CreateDirectoryOptions): Promise {} async deleteDirectory(path: string): Promise {} async directoryExists(path: string): Promise { return false; } async changeVisibility(path: string, visibility: string): Promise {} async visibility(path: string): Promise { return 'private'; } async publicUrl(path: string, options: PublicUrlOptions): Promise { return ''; } async temporaryUrl(path: string, options: TemporaryUrlOptions): Promise { return ''; } async checksum(path: string, options: ChecksumOptions): Promise { return ''; } async mimeType(path: string, options: MimeTypeOptions): Promise { return ''; } async lastModified(path: string): Promise { return 0; } async fileSize(path: string): Promise { return 0; } async copyFile(from: string, to: string, options: CopyFileOptions): Promise {} async moveFile(from: string, to: string, options: MoveFileOptions): Promise {} } // Use your custom adapter const adapter = new CustomStorageAdapter({ apiKey: process.env.API_KEY, endpoint: 'https://api.example.com', prefix: 'my-app/', }); const storage = new FileStorage(adapter); ``` -------------------------------- ### Read Files with Flystorage (TypeScript) Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Illustrates different methods for reading files from storage, including reading as a stream, string, Buffer, or Uint8Array. It also includes error handling for read operations. ```typescript try { // Read as stream (memory efficient for large files) const stream = await storage.read('documents/report.txt'); stream.pipe(process.stdout); // Read as string const text = await storage.readToString('documents/report.txt'); console.log(text); // Read as Buffer const buffer = await storage.readToBuffer('images/photo.jpg'); // Read as Uint8Array const uint8 = await storage.readToUint8Array('data/binary.dat'); } catch (err) { if (err instanceof UnableToReadFile) { console.error('Failed to read file:', err.message); } } ``` -------------------------------- ### Move and Copy Files (TypeScript) Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Provides functionality to move and copy files between locations. Supports retaining or changing visibility settings during the operation. Includes error handling for move and copy failures. ```typescript try { // Move file (retains visibility by default) await storage.moveFile('temp/draft.txt', 'documents/final.txt'); // Move with explicit visibility await storage.moveFile('uploads/image.jpg', 'public/banner.jpg', { visibility: Visibility.PUBLIC, }); // Move without retaining visibility (uses default) await storage.moveFile('private/doc.pdf', 'archive/doc.pdf', { retainVisibility: false, }); // Copy file await storage.copyFile('documents/template.docx', 'documents/copy.docx'); // Copy with explicit visibility await storage.copyFile('images/logo.png', 'public/logo.png', { visibility: Visibility.PUBLIC, }); } catch (err) { if (err instanceof UnableToMoveFile) { console.error('Failed to move file:', err.message); } if (err instanceof UnableToCopyFile) { console.error('Failed to copy file:', err.message); } } ``` -------------------------------- ### Check File and Directory Existence with Flystorage (TypeScript) Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Demonstrates how to check if a file or directory exists in the storage system before performing operations. It includes error handling for existence checks. ```typescript try { // Check file existence const fileExists = await storage.fileExists('documents/report.txt'); if (fileExists) { console.log('File exists'); } // Check directory existence const dirExists = await storage.directoryExists('documents'); if (dirExists) { console.log('Directory exists'); } } catch (err) { if (err instanceof UnableToCheckFileExistence) { console.error('Failed to check file existence:', err.message); } } ``` -------------------------------- ### Configure Error Strategies for Chaos Adapter (TypeScript) Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/tools/chaos.md Shows how to configure different error-triggering strategies for the Chaos adapter using the TriggeredErrors class in TypeScript. This includes setting up errors for specific operations, a number of times, or after a certain number of calls. ```typescript import {TriggeredErrors} from '@flystorage/chaos'; const strategy = new TriggeredErrors(); // error on all write calls strategy.on('write', () => new Error()); // error on first 2 stat calls strategy.on('stat', () => new Error(), {times: 2}); // error after first 2 deleteFile calls strategy.on('deleteFile', () => new Error(), {after: 2}); // error on 2nd and 3rd call to any method strategy.on('*', () => new Error(), {after: 1, times: 2}); ``` -------------------------------- ### Create Directory with Flystorage Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md Explicitly creates a directory using the `createDirectory` method. This operation might be a no-op for implementations that do not support explicit directory creation. Nested directories are implicitly created if required. ```typescript try { await storage.createDirectory('path/to/directory'); } catch (err) { if (err instanceof UnableToCreateDirectory) { // handle error } } ``` -------------------------------- ### Copy File with Flystorage Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md Copies a file to a new location using `copyFile`. Visibility is retained by default but can be overridden. Explicit visibility setting is available for performance. ```typescript try { await storage.copyFile('from/here.txt', 'to/there.txt', { visibility: Visibility.PRIVATE, }); } catch (err) { if (err instanceof UnableToCopyFile) { // handle error } } ``` -------------------------------- ### Delete Files and Directories with Flystorage (TypeScript) Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Demonstrates how to delete individual files and entire directories recursively using Flystorage. It notes that attempting to delete a non-existent file does not produce an error and includes error handling for deletion operations. ```typescript try { // Delete a single file (no error if it doesn't exist) await storage.deleteFile('documents/old-report.txt'); // Delete entire directory and all contents recursively await storage.deleteDirectory('archive/2023'); } catch (err) { if (err instanceof UnableToDeleteFile) { console.error('Failed to delete file:', err.message); } if (err instanceof UnableToDeleteDirectory) { console.error('Failed to delete directory:', err.message); } } ``` -------------------------------- ### Write File with Flystorage Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md Writes content to a file using the `write` method. Supports string, Uint8Array, Buffer, or Readable stream inputs. Parent directories are automatically created if needed. File visibility can be specified. ```typescript try { await storage.write('path/to/file.txt', contents); } catch (err) { if (err instanceof UnableToWriteFile) { // handle error } } ``` ```typescript import {VISIBILITY} from '@flystorage/file-storage'; await storage.write('path/to/file.txt', contents, { visibility: Visibility.PUBLIC, }); ``` -------------------------------- ### List Directory Contents (TypeScript) Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Lists files and directories within a specified path. Supports shallow and deep recursive listing. The listing can be iterated over or converted to an array. Handles errors if the directory cannot be listed. ```typescript try { // Shallow listing const listing = storage.list('documents'); // Deep recursive listing const deepListing = storage.list('documents', {deep: true}); // Iterate through entries for await (const entry of deepListing) { if (entry.type === 'file' || entry.isFile) { console.log(`File: ${entry.path}, Size: ${entry.fileSize}`); } if (entry.type === 'directory' || entry.isDirectory) { console.log(`Directory: ${entry.path}`); } } // Convert to array const allFiles = await listing.toArray(); console.log(`Found ${allFiles.length} entries`); } catch (err) { if (err instanceof UnableToListDirectory) { console.error('Failed to list directory:', err.message); } } ``` -------------------------------- ### Generate Public and Temporary URLs (TypeScript) Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Generates publicly accessible URLs for files with public visibility or time-limited temporary URLs for any file. Supports specifying expiry time using milliseconds or Date objects. Includes error handling for URL generation failures. ```typescript try { // Get public URL (requires public visibility) const publicUrl = await storage.publicUrl('images/logo.png'); console.log(`Access at: ${publicUrl}`); // Generate temporary URL (expires in 24 hours) const expiresAt = Date.now() + (24 * 60 * 60 * 1000); const tempUrl = await storage.temporaryUrl('private/report.pdf', expiresAt); console.log(`Temporary access: ${tempUrl}`); // Temporary URL with Date object const expireDate = new Date(); expireDate.setHours(expireDate.getHours() + 2); const shortTempUrl = await storage.temporaryUrl('downloads/file.zip', expireDate); } catch (err) { if (err instanceof UnableToGetPublicUrl) { console.error('Failed to get public URL:', err.message); } if (err instanceof UnableToGetTemporaryUrl) { console.error('Failed to get temporary URL:', err.message); } } ``` -------------------------------- ### Move File with Flystorage Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md Moves a file from one location to another using `moveFile`. File visibility is retained by default but can be overridden. Supports explicit visibility setting for performance. Directory moving is not normalized across implementations. ```typescript try { await storage.moveFile('from/here.txt', 'to/there.txt', { visibility: Visibility.PRIVATE, }); } catch (err) { if (err instanceof UnableToMoveFile) { // handle error } } ``` -------------------------------- ### List Directory Contents in TypeScript Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md The `list` method retrieves the contents of a directory. The `deep` option can be set to `true` for recursive listings. The result is an `AsyncIterable` that can be iterated over to process entries. ```typescript try { const listing = storage.list('path/to/directory', {deep: true}); } catch (err) { if (err instanceof UnableToCheckDirectoryExistence) { // handle error } } ``` -------------------------------- ### Visibility Control (TypeScript) Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Allows changing and querying the visibility of files (public or private). Note that not all storage adapters support this feature. Handles errors related to visibility changes or queries. ```typescript try { // Change file visibility to public await storage.changeVisibility('documents/report.pdf', Visibility.PUBLIC); // Change to private await storage.changeVisibility('private/secret.txt', Visibility.PRIVATE); // Query current visibility const visibility = await storage.visibility('documents/report.pdf'); if (visibility === Visibility.PUBLIC) { console.log('File is publicly accessible'); } } catch (err) { if (err instanceof UnableToChangeVisibility) { console.error('Failed to change visibility:', err.message); } if (err instanceof UnableToGetVisibility) { console.error('Failed to get visibility:', err.message); } } ``` -------------------------------- ### Query File Properties with Flystorage Source: https://context7.com/duna-oss/flystorage-docs/llms.txt Retrieve various properties of a file, including size, MIME type, last modified timestamp, and checksums. Handles potential errors during retrieval. ```typescript try { // Get file size in bytes const size = await storage.fileSize('documents/report.pdf'); console.log(`File size: ${size} bytes`); // Get MIME type const mimeType = await storage.mimeType('images/photo.jpg'); console.log(`MIME type: ${mimeType}`); // Get last modified timestamp (milliseconds) const lastModified = await storage.lastModified('documents/report.pdf'); console.log(`Last modified: ${new Date(lastModified)}`); // Get checksum/hash (default algorithm, hex encoded) const checksum = await storage.checksum('data/file.bin'); console.log(`Checksum: ${checksum}`); // Get checksum with specific algorithm and encoding const sha256 = await storage.checksum('data/file.bin', { algo: 'sha256', encoding: 'base64', }); console.log(`SHA-256: ${sha256}`); } catch (err) { if (err instanceof UnableToGetFileSize) { console.error('Failed to get file size:', err.message); } if (err instanceof UnableToGetMimeType) { console.error('Failed to get MIME type:', err.message); } if (err instanceof UnableToGetChecksum) { console.error('Failed to get checksum:', err.message); } } ``` -------------------------------- ### Delete Directory with Flystorage Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md Deletes a directory and all its contents using the `deleteDirectory` method. For implementations not supporting directories, this emulates deletion by prefix. ```typescript try { await storage.deleteDirectory('path/to/directory'); } catch (err) { if (err instanceof UnableToDeleteDirectory) { // handle error } } ``` -------------------------------- ### Iterate and Collect Directory Listings in TypeScript Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md Directory listings obtained via the `list` method are `AsyncIterable` objects. You can loop through entries using `for await...of` and check entry types with `entry.type`, `entry.isFile`, or `entry.isDirectory`. The `toArray` method conveniently collects all entries into an array. ```typescript for await (const entry of listing) { if (entry.type === 'file' || entry.isFile) { // handle the file } if (entry.type === 'directory' || entry.isDirectory) { // handle a directory } } ``` ```typescript const listingAsArray = await listing.toArray(); ``` -------------------------------- ### Determine File Visibility in TypeScript Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md The `visibility` method is used to retrieve the visibility of a file. It accepts the file path and returns the visibility status. Some storage implementations may not support this feature and could throw an error. ```typescript try { const visibility = await storage.visibility('path/to/file.txt'); } catch (err) { if (err instanceof UnableToGetVisibility) { // handle error } } ``` -------------------------------- ### Read File with Flystorage Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md Reads file content using `read`, `readToString`, `readToBuffer`, or `readToUint8Array` methods. Handles potential errors during file reading. ```typescript try { /** * @type {Readable} */ const contents = await storage.read('path/to/file.txt'); } catch (err) { if (err instanceof UnableToReadFile) { // handle error } } ``` -------------------------------- ### Check Directory Existence in TypeScript Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md Use the `directoryExists` method to verify if a directory exists at a given path. This method returns a boolean. If the underlying storage system does not support actual directories, it may be emulated by checking for files with the directory's prefix. ```typescript try { const exists = await storage.directoryExists('path/to/directory'); } catch (err) { if (err instanceof UnableToCheckDirectoryExistence) { // handle error } } ``` -------------------------------- ### Check File Existence in TypeScript Source: https://github.com/duna-oss/flystorage-docs/blob/main/src/content/docs/api.md The `fileExists` method checks for the presence of a file at the specified path. It returns a boolean value indicating existence. An error will be thrown if the check fails. ```typescript try { const exists = await storage.fileExists('path/to/file.txt'); } catch (err) { if (err instanceof UnableToCheckFileExistence) { // handle error } } ```