@visulima/storage 1.0.0-alpha.33 → 1.0.0-alpha.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/adapter/nuxt/module.d.ts +4 -4
- package/dist/ai/ai-sdk/index.d.ts +5 -5
- package/dist/ai/claude/index.d.ts +4 -4
- package/dist/ai/openai/index.d.ts +5 -5
- package/dist/ai/tanstack/index.d.ts +4 -4
- package/dist/handler/http/fetch/index.d.ts +7 -7
- package/dist/handler/http/fetch/index.js +1 -1
- package/dist/handler/http/hono/index.d.ts +4 -4
- package/dist/handler/http/hono/index.js +1 -1
- package/dist/handler/http/nextjs/index.d.ts +4 -4
- package/dist/handler/http/nextjs/index.js +1 -1
- package/dist/handler/http/node/index.d.ts +7 -7
- package/dist/handler/http/node/index.js +1 -1
- package/dist/handler/http/solid-start/index.d.ts +4 -4
- package/dist/handler/http/solid-start/index.js +1 -1
- package/dist/index.d.ts +6 -6
- package/dist/index.js +1 -1
- package/dist/packem_shared/{AwsLightStorage-6Z1ovz9R.js → AwsLightStorage-CWBRVcn5.js} +1 -1
- package/dist/packem_shared/{AzureStorage-CbAN4vPm.js → AzureStorage-nhAojuEU.js} +1 -1
- package/dist/packem_shared/{BoxMetaStorage-BGBPZWoL.js → BoxMetaStorage-XMZn5yvp.js} +1 -1
- package/dist/packem_shared/{BoxStorage-DitlyKVB.js → BoxStorage-C3--16du.js} +1 -1
- package/dist/packem_shared/{BunS3MetaStorage-DAskpG_G.js → BunS3MetaStorage-DomG8mVK.js} +1 -1
- package/dist/packem_shared/{BunS3Storage-D1gxh5Tt.js → BunS3Storage-0oYNi2Os.js} +1 -1
- package/dist/packem_shared/{BunnyMetaStorage-ByUvvuPc.js → BunnyMetaStorage-luemw1pL.js} +1 -1
- package/dist/packem_shared/{BunnyStorage-r6DptjUt.js → BunnyStorage-CIkpp1Rc.js} +1 -1
- package/dist/packem_shared/{CloudinaryMetaStorage-DsJyN0iQ.js → CloudinaryMetaStorage-DpxjshXZ.js} +1 -1
- package/dist/packem_shared/{CloudinaryStorage-BR8CZhlL.js → CloudinaryStorage-9Y1Gq0gr.js} +1 -1
- package/dist/packem_shared/DiskStorage-BkP8c0MY.js +1 -0
- package/dist/packem_shared/{DiskStorageWithChecksum--U7zOz-0.js → DiskStorageWithChecksum-CUXj5mE9.js} +1 -1
- package/dist/packem_shared/{DropboxMetaStorage-B7eY16fU.js → DropboxMetaStorage-h0eTJuk5.js} +1 -1
- package/dist/packem_shared/{DropboxStorage-9-jj7H8C.js → DropboxStorage-CuA9MkpH.js} +1 -1
- package/dist/packem_shared/{FirebaseMetaStorage-BpYykWhG.js → FirebaseMetaStorage-CCBnEE8_.js} +1 -1
- package/dist/packem_shared/{FirebaseStorage-DB87abIF.js → FirebaseStorage-DUskfjh_.js} +1 -1
- package/dist/packem_shared/{FtpMetaStorage-v2wXTwqX.js → FtpMetaStorage-DxHcXk9x.js} +1 -1
- package/dist/packem_shared/{FtpStorage-DdRf0Wg6.js → FtpStorage-DMpDY7oG.js} +1 -1
- package/dist/packem_shared/{GCSMetaStorage-BMtou9o7.js → GCSMetaStorage-DCBR02C7.js} +1 -1
- package/dist/packem_shared/{GCStorage-CRVpuZ5_.js → GCStorage-RCw58CoD.js} +1 -1
- package/dist/packem_shared/{GoogleDriveMetaStorage-BT9N1Wji.js → GoogleDriveMetaStorage-koEiYfFw.js} +1 -1
- package/dist/packem_shared/{GoogleDriveStorage-BzuSZZzN.js → GoogleDriveStorage-DNlVE5Uo.js} +1 -1
- package/dist/packem_shared/{LocalMetaStorage-BFQz8VPm.js → LocalMetaStorage-BKC34woF.js} +1 -1
- package/dist/packem_shared/{MemoryStorage-BuNY963D.js → MemoryStorage-CgEFb9yw.js} +1 -1
- package/dist/packem_shared/{Multipart-IE3j_gAJ.js → Multipart-D2eF0kMq.js} +1 -1
- package/dist/packem_shared/{Multipart-UIRqOPCf.js → Multipart-mlcj2Wm8.js} +1 -1
- package/dist/packem_shared/{NetlifyBlobMetaStorage-DNgncijZ.js → NetlifyBlobMetaStorage-DLJLr0fD.js} +1 -1
- package/dist/packem_shared/{NetlifyBlobStorage-eP0pkR0o.js → NetlifyBlobStorage-DqeW_OGE.js} +1 -1
- package/dist/packem_shared/{OneDriveMetaStorage-CkaFJFHe.js → OneDriveMetaStorage-Cuw5g3cr.js} +1 -1
- package/dist/packem_shared/{OneDriveStorage-3Iq5vBfd.js → OneDriveStorage-D41BZtkz.js} +1 -1
- package/dist/packem_shared/{PocketBaseMetaStorage-CxnGde_n.js → PocketBaseMetaStorage-BkzeMDP0.js} +1 -1
- package/dist/packem_shared/{PocketBaseStorage-DHphg8yi.js → PocketBaseStorage-CdvEL3YX.js} +1 -1
- package/dist/packem_shared/{Rest-DItHKz-N.js → Rest-08Oi3-WZ.js} +1 -1
- package/dist/packem_shared/{Rest-B_E4TrqF.js → Rest-BpyZYW-e.js} +1 -1
- package/dist/packem_shared/{S3Storage-Bc9eq5vJ.js → S3Storage-adY1XLfH.js} +1 -1
- package/dist/packem_shared/{SftpMetaStorage-CBcUhZRU.js → SftpMetaStorage-DN00oxqH.js} +1 -1
- package/dist/packem_shared/{SftpStorage-DSsMhTZC.js → SftpStorage-CDKtnw6a.js} +1 -1
- package/dist/packem_shared/{SharePointMetaStorage-yzxvwgKr.js → SharePointMetaStorage-WkQcni-I.js} +1 -1
- package/dist/packem_shared/{SharePointStorage-C6KIGN2r.js → SharePointStorage-CZkO7FSl.js} +1 -1
- package/dist/packem_shared/{SupabaseMetaStorage-D26wob-R.js → SupabaseMetaStorage-FaEVpmT5.js} +1 -1
- package/dist/packem_shared/{SupabaseStorage-B_knTpFQ.js → SupabaseStorage-O29RNXWx.js} +1 -1
- package/dist/packem_shared/{Tus-KQ8J2WF3.js → Tus-B7k9LUeY.js} +1 -1
- package/dist/packem_shared/{Tus-CAestp2j.js → Tus-BZT2Jhl5.js} +1 -1
- package/dist/packem_shared/UploadControl-jgusdgDN.js +1 -0
- package/dist/packem_shared/{UploadThingMetaStorage-DPIokkHa.js → UploadThingMetaStorage-CdDfhiyy.js} +1 -1
- package/dist/packem_shared/{UploadThingStorage-B3aIKSMh.js → UploadThingStorage-ByryGerX.js} +1 -1
- package/dist/packem_shared/{VercelBlobMetaStorage-Bx0l9Xt6.js → VercelBlobMetaStorage-CC1zy35k.js} +1 -1
- package/dist/packem_shared/{VercelBlobStorage-CGxoGkv4.js → VercelBlobStorage-C4QUjBfu.js} +1 -1
- package/dist/packem_shared/{approval.d-3sw7wbPG.d.ts → approval.d-CMAYH9GF.d.ts} +1 -1
- package/dist/packem_shared/{base-handler-core-OdTz4-Pm.js → base-handler-core-ty4J6Ji6.js} +1 -1
- package/dist/packem_shared/{base-handler-fetch-B0FWPun7.js → base-handler-fetch-BAjJyP84.js} +1 -1
- package/dist/packem_shared/{base-handler-node-CR2Bg43M.js → base-handler-node-BCqhH22o.js} +1 -1
- package/dist/packem_shared/{defaultCloudStorageFileNameValidation-De0HFP7m.js → defaultCloudStorageFileNameValidation-DSAf6C4S.js} +1 -1
- package/dist/packem_shared/detect-file-type-DRWGvQW4.js +1 -0
- package/dist/packem_shared/disk-storage-DJ2Nic2v.js +1 -0
- package/dist/packem_shared/{disk-storage-with-checksum.d-Z_Z-OQpm.d.ts → disk-storage-with-checksum.d-BT_ll5b8.d.ts} +1 -1
- package/dist/packem_shared/{executors.d-CRI3jlk4.d.ts → executors.d-D8esmhum.d.ts} +2 -2
- package/dist/packem_shared/{gcs-meta-storage-Dh0TAqB_.js → gcs-meta-storage-BXcsC7xV.js} +1 -1
- package/dist/packem_shared/{index.d-C4o9jVLx.d.ts → index.d-DB1VD8RP.d.ts} +1 -1
- package/dist/packem_shared/{local-meta-storage-Bvl0Flac.js → local-meta-storage-tayO1ARY.js} +1 -1
- package/dist/packem_shared/{local-meta-storage.d-CobcjyWu.d.ts → local-meta-storage.d-DUuLtPik.d.ts} +1 -1
- package/dist/packem_shared/{media-transformer.d-B5cQJz30.d.ts → media-transformer.d-B9dfBdoV.d.ts} +2 -2
- package/dist/packem_shared/{memory-storage.d-CunLnxmE.d.ts → memory-storage.d-BpxSYO-D.d.ts} +1 -1
- package/dist/packem_shared/{rest-base-DHkzq0rj.js → rest-base-BG0e-6E0.js} +1 -1
- package/dist/packem_shared/{s3-base-storage-o_zkj15Y.js → s3-base-storage-FiC4s91g.js} +1 -1
- package/dist/packem_shared/{s3-base-storage.d-ByfwKeid.d.ts → s3-base-storage.d-CoYAf_hG.d.ts} +1 -1
- package/dist/packem_shared/storage-CI88PmRw.js +1 -0
- package/dist/packem_shared/{storage.d-D5UN5mRz.d.ts → storage.d-C6HtvSoY.d.ts} +1 -1
- package/dist/packem_shared/{tus-base.d-D7UPhqdW.d.ts → tus-base.d-Dv25OXL0.d.ts} +3 -3
- package/dist/packem_shared/{types.d-GogSTfRh.d.ts → types.d-Cd2-3e-F.d.ts} +1 -1
- package/dist/packem_shared/{types.d-CPUyyEj9.d.ts → types.d-CmBrgo0d.d.ts} +2 -2
- package/dist/packem_shared/{types.d-BsjUOfBJ.d.ts → types.d-CmT_ubPu.d.ts} +2 -2
- package/dist/storage/aws/index.d.ts +2 -2
- package/dist/storage/aws/index.js +1 -1
- package/dist/storage/aws-light/index.d.ts +2 -2
- package/dist/storage/aws-light/index.js +1 -1
- package/dist/storage/azure/index.d.ts +1 -1
- package/dist/storage/azure/index.js +1 -1
- package/dist/storage/box/index.d.ts +2 -2
- package/dist/storage/box/index.js +1 -1
- package/dist/storage/bun-s3/index.d.ts +2 -2
- package/dist/storage/bun-s3/index.js +1 -1
- package/dist/storage/bunny/index.d.ts +2 -2
- package/dist/storage/bunny/index.js +1 -1
- package/dist/storage/cloudinary/index.d.ts +2 -2
- package/dist/storage/cloudinary/index.js +1 -1
- package/dist/storage/dropbox/index.d.ts +2 -2
- package/dist/storage/dropbox/index.js +1 -1
- package/dist/storage/firebase/index.d.ts +2 -2
- package/dist/storage/firebase/index.js +1 -1
- package/dist/storage/ftp/index.d.ts +2 -2
- package/dist/storage/ftp/index.js +1 -1
- package/dist/storage/gcs/index.d.ts +1 -1
- package/dist/storage/gcs/index.js +1 -1
- package/dist/storage/google-drive/index.d.ts +2 -2
- package/dist/storage/google-drive/index.js +1 -1
- package/dist/storage/local/index.d.ts +3 -3
- package/dist/storage/local/index.js +1 -1
- package/dist/storage/memory/index.d.ts +2 -2
- package/dist/storage/memory/index.js +1 -1
- package/dist/storage/netlify-blob/index.d.ts +2 -2
- package/dist/storage/netlify-blob/index.js +1 -1
- package/dist/storage/onedrive/index.d.ts +4 -4
- package/dist/storage/onedrive/index.js +1 -1
- package/dist/storage/pocketbase/index.d.ts +2 -2
- package/dist/storage/pocketbase/index.js +1 -1
- package/dist/storage/sftp/index.d.ts +2 -2
- package/dist/storage/sftp/index.js +1 -1
- package/dist/storage/sharepoint/index.d.ts +3 -3
- package/dist/storage/sharepoint/index.js +1 -1
- package/dist/storage/supabase/index.d.ts +2 -2
- package/dist/storage/supabase/index.js +1 -1
- package/dist/storage/uploadthing/index.d.ts +2 -2
- package/dist/storage/uploadthing/index.js +1 -1
- package/dist/storage/vercel-blob/index.d.ts +2 -2
- package/dist/storage/vercel-blob/index.js +1 -1
- package/dist/transformer/audio-transformer.d.ts +2 -2
- package/dist/transformer/image-transformer.d.ts +2 -2
- package/dist/transformer/index.d.ts +3 -3
- package/dist/transformer/video-transformer.d.ts +2 -2
- package/package.json +2 -2
- package/dist/packem_shared/DiskStorage-DHcHDZeO.js +0 -1
- package/dist/packem_shared/UploadControl-Otw_5jxw.js +0 -1
- package/dist/packem_shared/detect-file-type-5JhzC9RU.js +0 -1
- package/dist/packem_shared/disk-storage-CklneE2m.js +0 -1
- package/dist/packem_shared/storage-z0o24zmZ.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var N=Object.defineProperty;var u=(d,e)=>N(d,"name",{value:e,configurable:!0});import{n as i}from"./headers-DC2MEOrK.js";import{B}from"./storage-
|
|
1
|
+
var N=Object.defineProperty;var u=(d,e)=>N(d,"name",{value:e,configurable:!0});import{n as i}from"./headers-DC2MEOrK.js";import{B}from"./storage-CI88PmRw.js";import{ERRORS as g}from"./ERRORS-vMSqlI69.js";import{b as p}from"./base-handler-core-ty4J6Ji6.js";import{O as x}from"./base-handler-fetch-BAjJyP84.js";import{M as F,c as m}from"./rest-base-BG0e-6E0.js";var I=Object.defineProperty,f=u((d,e)=>I(d,"name",{value:e,configurable:!0}),"u");class y extends x{static{u(this,"m")}static{f(this,"RestFetch")}static methods=["delete","download","get","head","options","patch","post","put"];restBase;constructor(e){super(e);const r=this;this.restBase=new class extends F{get storage(){return r.storage}buildFileUrl(s,t){return r.buildFileUrl({url:s},t)}}}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("PUT",this.put.bind(this)),this.registeredHandlers.set("PATCH",this.patch.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("HEAD",this.head.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}async post(e){const r=e.headers.get("x-chunked-upload")==="true",s=e.headers.get("content-length"),t=s?Number.parseInt(s,10):0;if(!r){if(!s||Number.isNaN(t)||t===0)throw i(400,"Content-Length is required and must be greater than 0");if(e.body===null)throw i(400,"Request body is required")}if(t>this.storage.maxUploadSize)throw i(413,`File size exceeds maximum allowed size of ${this.storage.maxUploadSize} bytes`);const n=e.headers.get("content-type")||"application/octet-stream",o=O(e,t,n),a=e.url,h=e.body?p(e):void 0;return this.restBase.handlePost(o,r,a,h,t)}async put(e){const r=l(e.url);if(!r)throw i(400,"File ID is required in URL path");if(e.body===null)throw i(400,"Request body is required");const s=e.headers.get("content-length"),t=s?Number.parseInt(s,10):0;if(t===0)throw i(400,"Content-Length is required and must be greater than 0");if(t>this.storage.maxUploadSize)throw i(413,`File size exceeds maximum allowed size of ${this.storage.maxUploadSize} bytes`);const n=e.headers.get("content-type")||"application/octet-stream",o=e.headers.get("x-file-metadata");let a;if(o)try{a=JSON.parse(o)}catch{}const h=m(e.headers.get("content-disposition")),c={contentType:n,metadata:a||{},originalName:h,size:t},b=e.url,w=p(e);return this.restBase.handlePut(r,c,b,w,t,a)}async delete(e){const r=new URL(e.url).searchParams.get("ids");if(r){const t=r.split(",").map(n=>n.trim()).filter(Boolean);if(t.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(t)}if((e.headers.get("content-type")||"").includes("application/json"))try{const t=Number.parseInt(e.headers.get("content-length")??"",10);if(Number.isFinite(t)&&t>1048576)throw i(413,"Batch delete body exceeds 1 MiB");const n=await e.text();if(Buffer.byteLength(n,"utf8")>1048576)throw i(413,"Batch delete body exceeds 1 MiB");const o=JSON.parse(n);if(Array.isArray(o)){if(o.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(o)}if(typeof o=="object"&&o!==null&&"ids"in o&&Array.isArray(o.ids)){const a=o.ids;if(a.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(a)}}catch(t){if(t.statusCode===400)throw t}const s=l(e.url);if(!s)throw i(404,"File not found");try{return this.restBase.deleteSingle(s)}catch(t){const n=t;throw n.UploadErrorCode===g.FILE_NOT_FOUND||n.code==="ENOENT"?i(404,"File not found"):t}}async patch(e){const r=l(e.url);if(!r)throw i(404,"File not found");if(e.body===null)throw i(400,"Request body is required");const s=e.headers.get("content-length"),t=s?Number.parseInt(s,10):0;if(t===0)throw i(400,"Content-Length is required and must be greater than 0");const n=e.headers.get("x-chunk-offset"),o=n?Number.parseInt(n,10):void 0;if(o===void 0)throw i(400,"X-Chunk-Offset header is required");const a=e.headers.get("x-chunk-checksum")||void 0,h=e.url,c=p(e);return this.restBase.handlePatch(r,o,t,a,h,c)}async head(e){const r=l(e.url);if(!r)throw i(404,"File not found");try{return this.restBase.handleHead(r)}catch(s){const t=s;throw t.UploadErrorCode===g.FILE_NOT_FOUND||t.code==="ENOENT"?i(404,"File not found"):s}}async options(e){return this.restBase.handleOptions(y.methods,this.storage.maxUploadSize)}async get(e){throw i(500,"GET requests should be handled via fetch() method")}}const O=f((d,e,r)=>{const s=d.headers.get("x-total-size"),t=s?Number.parseInt(s,10):e,n=d.headers.get("x-file-metadata");let o={};if(n)try{o=JSON.parse(n)}catch{}const a=m(d.headers.get("content-disposition"));return{contentType:r,metadata:o,originalName:a,size:t}},"extractFileInitFromRequest"),l=f(d=>{let e;try{const r=new URL(d).pathname.split("/").filter(Boolean),s=r[r.length-1];if(!s)return null;e=s.replace(/\.[^.]+$/,"")||void 0}catch{return null}if(!e)return null;try{B.assertSafeId(e)}catch{throw i(400,`Invalid file id: "${e}"`)}return e},"getIdFromRequestUrl");export{y as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var w=Object.defineProperty;var l=(r,e)=>w(r,"name",{value:e,configurable:!0});import{CreateMultipartUploadCommand as b,UploadPartCommand as y,CompleteMultipartUploadCommand as B,AbortMultipartUploadCommand as S,ListPartsCommand as T,GetObjectCommand as h,HeadObjectCommand as E,DeleteObjectCommand as x,CopyObjectCommand as U,ListObjectsV2Command as K,waitUntilBucketExists as P,S3Client as L,PutObjectCommand as I}from"@aws-sdk/client-s3";import{fromIni as M}from"@aws-sdk/credential-providers";import{getSignedUrl as g}from"@aws-sdk/s3-request-presigner";import{S as O,b as A}from"./s3-base-storage-
|
|
1
|
+
var w=Object.defineProperty;var l=(r,e)=>w(r,"name",{value:e,configurable:!0});import{CreateMultipartUploadCommand as b,UploadPartCommand as y,CompleteMultipartUploadCommand as B,AbortMultipartUploadCommand as S,ListPartsCommand as T,GetObjectCommand as h,HeadObjectCommand as E,DeleteObjectCommand as x,CopyObjectCommand as U,ListObjectsV2Command as K,waitUntilBucketExists as P,S3Client as L,PutObjectCommand as I}from"@aws-sdk/client-s3";import{fromIni as M}from"@aws-sdk/credential-providers";import{getSignedUrl as g}from"@aws-sdk/s3-request-presigner";import{S as O,b as A}from"./s3-base-storage-FiC4s91g.js";import{Readable as m}from"node:stream";import{ReadableStream as C}from"node:stream/web";import v from"./S3File-BfmCOET4.js";import j from"./S3MetaStorage-vcriiosn.js";var N=Object.defineProperty,f=l((r,e)=>N(r,"name",{value:e,configurable:!0}),"d");const s=f(r=>r?.signal?{abortSignal:r.signal}:void 0,"sendOptions");class R{static{l(this,"T")}constructor(e,t){this.client=e}client;static{f(this,"S3ClientAdapter")}async createMultipartUpload(e,t){const a=new b({ACL:e.ACL,Bucket:e.Bucket,ContentType:e.ContentType,Key:e.Key,Metadata:e.Metadata}),n=await this.client.send(a,s(t));if(!n.UploadId)throw new Error("Failed to create multipart upload");return{UploadId:n.UploadId}}async uploadPart(e,t){const a=e.Body instanceof C?m.fromWeb(e.Body):e.Body,n=new y({Body:a,Bucket:e.Bucket,ContentLength:e.ContentLength,ContentMD5:e.ContentMD5,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId}),o=await this.client.send(n,s(t));if(!o.ETag)throw new Error("Failed to upload part");return{ETag:o.ETag}}async completeMultipartUpload(e,t){const a=new B({Bucket:e.Bucket,Key:e.Key,MultipartUpload:{Parts:e.Parts.map(({ETag:o,PartNumber:i})=>({ETag:o,PartNumber:i}))},UploadId:e.UploadId}),n=await this.client.send(a,s(t));if(!n.Location)throw new Error("Failed to complete multipart upload");return{ETag:n.ETag,Location:n.Location}}async abortMultipartUpload(e,t){const a=new S({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId});await this.client.send(a,s(t))}async listParts(e,t){const a=new T({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId}),n=await this.client.send(a,s(t)),o=[];if(n.Parts)for(const i of n.Parts)i.ETag&&i.PartNumber&&o.push({ETag:i.ETag,PartNumber:i.PartNumber,Size:i.Size});return{Parts:o.length>0?o:void 0}}async getObject(e,t){const a=new h({Bucket:e.Bucket,Key:e.Key,...e.Range!==void 0&&{Range:e.Range}}),n=await this.client.send(a,s(t));let o;if(n.Body){const i=n.Body;i instanceof m||typeof i=="object"&&"transform"in i&&i instanceof C?o=i:o=m.from(i)}return{Body:o,ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified,Metadata:n.Metadata}}async headObject(e,t){const a=new E({Bucket:e.Bucket,Key:e.Key}),n=await this.client.send(a,s(t));return{ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified}}async deleteObject(e,t){const a=new x({Bucket:e.Bucket,Key:e.Key});await this.client.send(a,s(t))}async copyObject(e,t){const a={Bucket:e.Bucket,CopySource:e.CopySource,Key:e.Key};e.StorageClass&&(a.StorageClass=e.StorageClass);const n=new U(a);await this.client.send(n,s(t))}async listObjectsV2(e,t){const a=new K({Bucket:e.Bucket,ContinuationToken:e.ContinuationToken,Delimiter:e.Delimiter,MaxKeys:e.MaxKeys,Prefix:e.Prefix}),n=await this.client.send(a,s(t));return{CommonPrefixes:n.CommonPrefixes?.map(o=>({Prefix:o.Prefix})),Contents:n.Contents?.map(o=>({Key:o.Key,LastModified:o.LastModified})),IsTruncated:n.IsTruncated,NextContinuationToken:n.NextContinuationToken}}async getPresignedUrl(e){const t=new y({Bucket:e.Bucket,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId});return g(this.client,t,{expiresIn:e.expiresIn})}async checkBucketAccess(e){await P({client:this.client,maxWaitTime:30},{Bucket:e.Bucket})}}var D=Object.defineProperty,z=l((r,e)=>D(r,"name",{value:e,configurable:!0}),"m");class q extends O{static name="s3";s3Api;rawClient;constructor(e){const{bucket:t=process.env.S3_BUCKET,region:a=process.env.S3_REGION}=e;if(!t)throw new Error("S3 bucket is not defined");if(!a)throw new Error("S3 region is not defined");e.region=a;const n=e.keyFile||process.env.S3_KEYFILE;n&&(e.credentials=M({configFilepath:n}));const o=new L(e);super({bucket:t,clientDirectUpload:e.clientDirectUpload,expiration:e.expiration?.maxAge?{maxAge:String(e.expiration.maxAge)}:void 0,filename:e.filename,logger:e.logger,metaStorage:e.metaStorage,metaStorageConfig:e.metaStorageConfig?{...e.metaStorageConfig,...e}:{...e},partSize:e.partSize,retryConfig:{...e.retryConfig,shouldRetry:z(d=>{const c=d;if(c.$metadata){const p=c.$metadata.httpStatusCode;if(p&&[408,429,500,502,503,504].includes(p)||c.$fault==="server")return!0}return c.retryable??!1},"shouldRetry")}}),this.s3Api=new R(o,t),this.rawClient=o;const{metaStorage:i,metaStorageConfig:u}=e;if(!i){const d={...e,...u,logger:this.logger};"directory"in d||(this.meta=new j(d))}this.config.clientDirectUpload&&(this.onCreate=async()=>{})}normalizeError(e){return e.$metadata?{code:e.Code||e.name,message:e.message,name:e.name,statusCode:e.$metadata.httpStatusCode||500}:super.normalizeError(e)}async update({id:e},t){if(this.config.clientDirectUpload){const a=await this.getMeta(e);return this.buildPresigned({...a,...t})}return super.update({id:e},t)}async getStream({id:e},t){return this.instrumentOperation("getStream",async()=>{const a=this.getS3Api(),n=A(t?.range),{Body:o,ContentLength:i,ContentType:u,ETag:d,Expires:c,LastModified:p}=await this.runOperation(t,k=>a.getObject({Bucket:this.bucket,Key:e,...n!==void 0&&{Range:n}},{signal:k}));return await this.checkIfExpired({expiredAt:c}),{headers:{"Content-Length":i?.toString()??"0","Content-Type":u,...d&&{ETag:d},...c&&{"X-Upload-Expires":c.toString()},...p&&{"Last-Modified":p.toString()}},size:Number(i),stream:o}})}get raw(){return this.rawClient}async getReadUrl(e,t){const a=new h({Bucket:this.bucket,Key:e,...t?.responseContentDisposition&&{ResponseContentDisposition:t.responseContentDisposition},...t?.responseContentType&&{ResponseContentType:t.responseContentType}});return g(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}async getUploadUrl(e,t){const a=new I({Bucket:this.bucket,Key:e,...t?.contentType&&{ContentType:t.contentType},...t?.contentLength!==void 0&&{ContentLength:t.contentLength}});return g(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}getS3Api(){return this.s3Api}getFileClass(){return v}getAcl(){return this.config.acl}async accessCheck(e=30){await this.s3Api.checkBucketAccess({Bucket:this.bucket})}}export{q as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-
|
|
1
|
+
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-tayO1ARY.js";var o=Object.defineProperty,c=a((t,e)=>o(t,"name",{value:e,configurable:!0}),"e");class f extends s{static{a(this,"p")}static{c(this,"SftpMetaStorage")}constructor(e){super(e)}}export{f as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var v=Object.defineProperty;var O=(h,a)=>v(h,"name",{value:a,configurable:!0});import{S as k}from"./index-B4ETk0Lu.js";import F from"ssh2-sftp-client";import{throwErrorCode as m,ERRORS as p}from"./ERRORS-vMSqlI69.js";import{B as E}from"./storage-
|
|
1
|
+
var v=Object.defineProperty;var O=(h,a)=>v(h,"name",{value:a,configurable:!0});import{S as k}from"./index-B4ETk0Lu.js";import F from"ssh2-sftp-client";import{throwErrorCode as m,ERRORS as p}from"./ERRORS-vMSqlI69.js";import{B as E}from"./storage-CI88PmRw.js";import P from"./SftpFile-CQCxZNVq.js";import M from"./SftpMetaStorage-DN00oxqH.js";import{i as w,n as S,o as l}from"./posix-dirname-CiHXPPnw.js";import{o as b}from"./get-file-status-DLS18Zvd.js";import{u as A}from"./update-size-DANV7aa2.js";import{r as $}from"./part-match-D_NwyoF3.js";import{o as x}from"./has-content-Bx2p8Okx.js";var L=Object.defineProperty,T=O((h,a)=>L(h,"name",{value:a,configurable:!0}),"l");const f=T(h=>{const a=h?.code,e=h instanceof Error?h.message:String(h);return a===2||a==="ENOENT"||/no such file|not exist|no such path/i.test(e)},"isNotFoundError"),g=T(h=>{if(h instanceof Error&&h.name==="AbortError")return h;const a=new Error(h instanceof Error&&h.message?h.message:"The operation was aborted",{cause:h});return a.name="AbortError",a},"toAbortError");class B extends E{static name="sftp";checksumTypes=[];supportsRange=!0;meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=w(a.rootFolderPath??""),this.meta=a.metaStorage??new M(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new P(a);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const i=await this.getMeta(t.id);if(i.status==="completed")return i}catch{}return t.bytesWritten=0,t.status=b(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(a,e){return this.instrumentOperation("write",async()=>{let t;if("contentType"in a&&"metadata"in a&&!("body"in a)&&!("start"in a)?t=a:(t=await this.getMeta(a.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(a.size!==void 0&&A(t,a.size),!$(a,t))return m(p.FILE_CONFLICT);const i=await this.lock(a.id);try{if(x(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return m(p.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return m(p.METHOD_NOT_ALLOWED,"SFTP storage does not support chunked or resumable uploads; send the file in a single request.");const r=await S(a.body),n=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,s=>this.run(s,async o=>{const c=l(n);c&&await o.mkdir(c,!0),await o.put(r,n)})),t.bytesWritten=r.length,t.size=r.length,t.path=n,t.ETag=k(r)}return t.status=b(t),await this.saveMeta(t),t}finally{await this.unlock(a.id,i)}})}async get({id:a},e){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(a)),i=t.path??this.keyToPath(t.name||a),{range:r}=e??{},n=await this.runOperation(e,s=>this.run(s,async o=>{try{const c=r?{readStreamOptions:{start:r.start,...r.end===void 0?{}:{end:r.end}}}:void 0;return await o.get(i,void 0,c)}catch(c){if(f(c))return m(p.FILE_NOT_FOUND);throw c}}));return{content:n,contentType:t.contentType,ETag:t.ETag??k(n),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:r?n.length:t.size??n.length}})}async delete({id:a},e){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(a),i=t.path??this.keyToPath(t.name||a);await this.runOperation(e,n=>this.run(n,async s=>{try{await s.delete(i)}catch(o){if(!f(o))throw o}})),await this.deleteMeta(a);const r={...t,status:"deleted"};return await this.onDelete(r),r})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(a),r=i.path??this.keyToPath(i.name||a),n=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async c=>{const u=await c.get(r),d=l(n);d&&await c.mkdir(d,!0),await c.put(u,n)}));const s={...i,id:e,name:e,path:n};return await this.saveMeta(s),s})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const i=await this.getMeta(a),r=i.path??this.keyToPath(i.name||a),n=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async c=>{const u=l(n);u&&await c.mkdir(u,!0);try{await c.rename(r,n)}catch(d){try{const y=await c.get(r);await c.put(y,n),await c.delete(r)}catch(y){throw new AggregateError([d,y],`SFTP move failed: rename and copy+delete fallback both failed for "${r}" → "${n}"`)}}}));const s={...i,id:e,name:e,path:n};await this.saveMeta(s);try{await this.deleteMeta(a)}catch{}return s})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,i=>this.run(i,async r=>{const n=[];return await this.walkList(r,t,n),n}))})}async exists({id:a},e){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(a)}catch{return!1}const i=t.path??this.keyToPath(t.name||a);return this.runOperation(e,r=>this.run(r,async n=>{const s=await n.exists(i);return s==="-"||s==="l"}))})}async walkList(a,e,t){let i;try{i=await a.list(e||".")}catch(r){if(f(r))return;throw r}for(const r of i){const n=e?`${e}/${r.name}`:r.name;if(r.type==="d"){await this.walkList(a,n,t);continue}if(r.type!=="-")continue;const s=this.pathToKey(n);if(!s)continue;const o=new P({contentType:"application/octet-stream",metadata:{},originalName:r.name});o.id=s,o.name=s,o.path=n,o.size=r.size,o.modifiedAt=new Date(r.modifyTime).toISOString(),t.push(o)}}async run(a,e){const t=new F;if(a?.aborted)throw g(a.reason);const i=T(()=>{t.end()},"onAbort");a?.addEventListener("abort",i,{once:!0});try{if(await t.connect(this.connection),a?.aborted)throw g(a.reason);return await e(t)}catch(r){throw a?.aborted?g(r):r}finally{a?.removeEventListener("abort",i),await t.end()}}keyToPath(a){const e=w(a);e&&E.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":this.rootFolderPath.startsWith("/")?`/${t.join("/")}`:t.join("/")}pathToKey(a){const e=w(a);if(!this.rootFolderPath)return e;if(e===this.rootFolderPath)return"";const t=`${this.rootFolderPath}/`;return e.startsWith(t)?e.slice(t.length):e}}export{B as default};
|
package/dist/packem_shared/{SharePointMetaStorage-yzxvwgKr.js → SharePointMetaStorage-WkQcni-I.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-
|
|
1
|
+
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-tayO1ARY.js";var s=Object.defineProperty,i=a((t,e)=>s(t,"name",{value:e,configurable:!0}),"e");class u extends o{static{a(this,"i")}static{i(this,"SharePointMetaStorage")}constructor(e){super(e)}}export{u as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var I=Object.defineProperty;var h=(i,e)=>I(i,"name",{value:e,configurable:!0});import{throwErrorCode as c,ERRORS as d}from"./ERRORS-vMSqlI69.js";import u,{buildGraphClient as g}from"./OneDriveStorage-
|
|
1
|
+
var I=Object.defineProperty;var h=(i,e)=>I(i,"name",{value:e,configurable:!0});import{throwErrorCode as c,ERRORS as d}from"./ERRORS-vMSqlI69.js";import u,{buildGraphClient as g}from"./OneDriveStorage-D41BZtkz.js";import{B as v}from"./storage-CI88PmRw.js";import E from"./SharePointMetaStorage-WkQcni-I.js";var m=Object.defineProperty,l=h((i,e)=>m(i,"name",{value:e,configurable:!0}),"d");const p=l(i=>{if(!i)return;const e=i.replace(/\/+$/,"").split("/").pop();if(e)try{return decodeURIComponent(e)}catch{return e}},"webUrlLeaf"),S=l(i=>{let e;try{e=new URL(i)}catch{return c(d.BAD_REQUEST,`SharePoint storage: invalid \`siteUrl\` "${i}".`)}const t=e.pathname.replace(/\/+$/,"");return{hostname:e.host,sitePath:t===""?"/":t}},"parseSiteUrl");class C extends v{static name="sharepoint";checksumTypes=[];meta;client;inner;innerPromise;oneDriveAuth;resolvedConfig;constructor(e){super(e);const t=e.accessToken??process.env.SHAREPOINT_ACCESS_TOKEN??process.env.ONEDRIVE_ACCESS_TOKEN,r=e.clientCredentials??(()=>{const o=process.env.SHAREPOINT_TENANT_ID??process.env.ONEDRIVE_TENANT_ID,a=process.env.SHAREPOINT_CLIENT_ID??process.env.ONEDRIVE_CLIENT_ID,n=process.env.SHAREPOINT_CLIENT_SECRET??process.env.ONEDRIVE_CLIENT_SECRET;if(o&&a&&n)return{clientId:a,clientSecret:n,tenantId:o}})();this.oneDriveAuth={...e.client&&{client:e.client},...t!==void 0&&{accessToken:t},...r&&{clientCredentials:r},...e.oauth&&{oauth:e.oauth}},this.resolvedConfig={...e,...e.driveId??process.env.SHAREPOINT_DRIVE_ID?{driveId:e.driveId??process.env.SHAREPOINT_DRIVE_ID}:{},...e.siteId??process.env.SHAREPOINT_SITE_ID?{siteId:e.siteId??process.env.SHAREPOINT_SITE_ID}:{},...e.siteUrl??process.env.SHAREPOINT_SITE_URL?{siteUrl:e.siteUrl??process.env.SHAREPOINT_SITE_URL}:{},...e.hostname??process.env.SHAREPOINT_HOSTNAME?{hostname:e.hostname??process.env.SHAREPOINT_HOSTNAME}:{}},this.client=g(this.oneDriveAuth),this.meta=e.metaStorage??new E(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,t){return(await this.getInner()).create(e,t)}async write(e,t){return(await this.getInner()).write(e,t)}async delete(e,t){return(await this.getInner()).delete(e,t)}async get(e,t){return(await this.getInner()).get(e,t)}async copy(e,t,r){return(await this.getInner()).copy(e,t,r)}async move(e,t,r){return(await this.getInner()).move(e,t,r)}async exists(e,t){return(await this.getInner()).exists(e)}async list(e=1e3,t){return(await this.getInner()).list(e,t)}async update(e,t,r){return(await this.getInner()).update(e,t)}async getStream(e,t){return(await this.getInner()).getStream(e)}async getReadUrl(e,t){return(await this.getInner()).getReadUrl(e,t)}async getUploadUrl(e,t){return(await this.getInner()).getUploadUrl(e,t)}async getInner(){return this.inner?this.inner:(this.innerPromise??=this.buildInner(),this.inner=await this.innerPromise,this.inner)}async buildInner(){const e=await this.resolveDriveId(),{documentLibrary:t,hostname:r,siteId:o,sitePath:a,siteUrl:n,...s}=this.genericConfig;return new u({...s,...this.oneDriveAuth,driveId:e,...this.resolvedConfig.copyTimeoutMs!==void 0&&{copyTimeoutMs:this.resolvedConfig.copyTimeoutMs},...this.resolvedConfig.metaStorageConfig&&{metaStorageConfig:this.resolvedConfig.metaStorageConfig},metaStorage:this.meta,...this.resolvedConfig.publicByDefault!==void 0&&{publicByDefault:this.resolvedConfig.publicByDefault},...this.resolvedConfig.rootFolderPath!==void 0&&{rootFolderPath:this.resolvedConfig.rootFolderPath}})}async resolveDriveId(){const e=this.resolvedConfig;if(e.driveId)return e.driveId;const t=await this.resolveSiteId();if(e.documentLibrary){const o=await this.client.api(`/sites/${t}/drives`).get(),a=e.documentLibrary.toLowerCase(),n=(o.value??[]).find(s=>s.name===e.documentLibrary)??(o.value??[]).find(s=>s.name?.toLowerCase()===a||p(s.webUrl)?.toLowerCase()===a);return n?n.id:c(d.FILE_NOT_FOUND,`SharePoint storage: document library "${e.documentLibrary}" not found in site "${t}".`)}const r=await this.client.api(`/sites/${t}/drive`).get();return r?.id?r.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site "${t}" has no default drive.`)}async resolveSiteId(){const e=this.resolvedConfig;if(e.siteId)return e.siteId;let t,r;if(e.siteUrl?{hostname:t,sitePath:r}=S(e.siteUrl):e.hostname&&(t=e.hostname,r=e.sitePath??"/"),!t||!r)return c(d.BAD_REQUEST,"SharePoint storage: missing site targeting. Provide `driveId`, `siteId`, `siteUrl`, or `hostname` (+ `sitePath`).");const o=r==="/"?"":r.replace(/^\/+/,""),a=o?`/sites/${t}:/${o}`:`/sites/${t}`;let n;try{n=await this.client.api(a).get()}catch(s){return c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}" (${s instanceof Error?s.message:String(s)}).`)}return n?.id?n.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}".`)}}export{C as default};
|
package/dist/packem_shared/{SupabaseMetaStorage-D26wob-R.js → SupabaseMetaStorage-FaEVpmT5.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-
|
|
1
|
+
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-tayO1ARY.js";var o=Object.defineProperty,u=a((t,e)=>o(t,"name",{value:e,configurable:!0}),"t");class i extends s{static{a(this,"p")}static{u(this,"SupabaseMetaStorage")}constructor(e){super(e)}}export{i as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=Object.defineProperty;var d=(o,t)=>g(o,"name",{value:t,configurable:!0});import{StorageClient as w}from"@supabase/storage-js";import{throwErrorCode as u,ERRORS as h}from"./ERRORS-vMSqlI69.js";import{B as y}from"./storage-
|
|
1
|
+
var g=Object.defineProperty;var d=(o,t)=>g(o,"name",{value:t,configurable:!0});import{StorageClient as w}from"@supabase/storage-js";import{throwErrorCode as u,ERRORS as h}from"./ERRORS-vMSqlI69.js";import{B as y}from"./storage-CI88PmRw.js";import c from"./SupabaseFile-DZ1iv9gM.js";import b from"./SupabaseMetaStorage-FaEVpmT5.js";import{o as l}from"./get-file-status-DLS18Zvd.js";import{u as E}from"./update-size-DANV7aa2.js";import{r as S}from"./part-match-D_NwyoF3.js";import{o as k}from"./has-content-Bx2p8Okx.js";var U=Object.defineProperty,p=d((o,t)=>U(o,"name",{value:t,configurable:!0}),"p");const f=3600*24*7,O=p(o=>{if(!o||!/^attachment(\s*;|\s*$)/i.test(o.trim()))return;const t=o.match(/filename\*?=(?:UTF-8'')?(?:"([^"]+)"|([^;]+))/i),a=t?.[1]??t?.[2];if(!a)return!0;try{return decodeURIComponent(a.trim())}catch{return a.trim()}},"parseDownloadOption"),C=p(async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},"collectStream");class I extends y{static name="supabase";checksumTypes=[];meta;bucket;defaultUrlExpiresIn;storageClient;constructor(t){if(super(t),this.bucket=t.bucket,this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,f),t.client)this.storageClient=t.client;else{const a=t.url??process.env.SUPABASE_URL,e=t.serviceKey??process.env.SUPABASE_SERVICE_ROLE_KEY??process.env.SUPABASE_KEY;if(!a)throw new Error("Supabase storage: `url` is required (or set SUPABASE_URL).");if(!e)throw new Error("Supabase storage: `serviceKey` is required (or set SUPABASE_SERVICE_ROLE_KEY / SUPABASE_KEY).");const i=a.replace(/\/+$/,"")+(a.endsWith("/storage/v1")?"":"/storage/v1");this.storageClient=new w(i,{apikey:e,Authorization:`Bearer ${e}`},t.fetch)}this.meta=t.metaStorage??new b(t.metaStorageConfig),this.isReady=!0}get raw(){return this.storageClient}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new c(t);e.name=this.namingFunction(e),e.bucket=this.bucket,e.path=e.name,await this.validate(e);try{const i=await this.getMeta(e.id);if(i.bytesWritten>=0)return i}catch{}return e.bytesWritten=0,e.status=l(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&E(e,t.size),!S(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(k(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await C(t.body),n=e.path??e.name,{data:s,error:m}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).upload(n,r,{contentType:e.contentType,upsert:!0}));if(m)throw m;e.bytesWritten=r.length,e.size=r.length,e.path=s?.path??n,e.ETag=s?.id}return e.status=l(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,i)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const i=e?.path??e?.name??t,{error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).remove([i]));if(r&&r.message&&!/not.*found/i.test(r.message))throw r;return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.bucket,id:t,name:t,path:i,status:"deleted"})})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}const{data:i,error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).exists(e));return r?!1:!!i})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e=t,i;try{i=await this.checkIfExpired(await this.getMeta(t)),e=i.path??i.name??t}catch{}const{data:r,error:n}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).download(e));if(n||!r)throw n??new Error(`Supabase: object not found at "${e}"`);const s=Buffer.from(await this.runOperation(a,()=>r.arrayBuffer()));return{content:s,contentType:i?.contentType??r.type??"application/octet-stream",ETag:i?.ETag,expiredAt:i?.expiredAt,id:t,metadata:i?.metadata??{},modifiedAt:i?.modifiedAt,name:i?.name??e,originalName:i?.originalName??e,size:i?.size??s.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(t))?.path??t,r=a,{error:n}=await this.runOperation(e,()=>this.storageClient.from(this.bucket).copy(i,r));if(n)throw n;const s=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return s.id=a,s.name=a,s.path=r,s.bucket=this.bucket,s})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=(await this.getMetaSafe(t))?.path??t,{error:r}=await this.runOperation(e,()=>this.storageClient.from(this.bucket).move(i,a));if(r)throw r;const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});n.id=a,n.name=a,n.path=a,n.bucket=this.bucket;try{await this.deleteMeta(t)}catch{}return n})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const{data:e,error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).list("",{limit:t}));if(i)throw i;return(e??[]).map(r=>{const n=new c({contentType:r.metadata?.mimetype??"application/octet-stream",metadata:r.metadata??{},originalName:r.name});return n.id=r.name,n.name=r.name,n.path=r.name,n.bucket=this.bucket,n.size=typeof r.metadata?.size=="number"?r.metadata.size:void 0,n.createdAt=r.created_at??void 0,n.modifiedAt=r.updated_at??void 0,n.ETag=r.metadata?.eTag??r.id??void 0,n})},{limit:t})}async getReadUrl(t,a){const e=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,f),{data:i,error:r}=await this.storageClient.from(this.bucket).createSignedUrl(t,e,{download:O(a?.responseContentDisposition)});return r||!i?u(h.METHOD_NOT_ALLOWED,r?.message??"Supabase: createSignedUrl failed"):i.signedUrl}async getUploadUrl(t,a){if(a?.contentType!==void 0||a?.contentLength!==void 0)return u(h.BAD_REQUEST,"Supabase: `contentType`/`contentLength` are not supported for upload URLs. A Supabase signed upload URL does not bind the request Content-Type into the signature and cannot enforce a size limit; validate both at your application gateway/proxy before issuing the URL.");const{data:e,error:i}=await this.storageClient.from(this.bucket).createSignedUploadUrl(t);return i||!e?u(h.METHOD_NOT_ALLOWED,i?.message??"Supabase: createSignedUploadUrl failed"):e.signedUrl}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=p(t=>this.deleteMeta(t.id),"internalOnComplete")}export{I as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var E=Object.defineProperty;var g=(i,e)=>E(i,"name",{value:e,configurable:!0});import{n as a}from"./headers-DC2MEOrK.js";import{B as w}from"./storage-
|
|
1
|
+
var E=Object.defineProperty;var g=(i,e)=>E(i,"name",{value:e,configurable:!0});import{n as a}from"./headers-DC2MEOrK.js";import{B as w}from"./storage-CI88PmRw.js";import{O as B}from"./base-handler-fetch-BAjJyP84.js";import{TusBase as H,TUS_RESUMABLE as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_VERSION as k}from"./TUS_RESUMABLE-B7KtPVeC.js";var R=Object.defineProperty,b=g((i,e)=>R(i,"name",{value:e,configurable:!0}),"g");const l=b(i=>{let e;try{const t=new URL(i).pathname.split("/").filter(Boolean);e=t[t.length-1]||void 0}catch{return}if(e){try{w.assertSafeId(e)}catch{throw a(400,`Invalid file id: "${e}"`)}return e}},"getIdFromRequestUrl");class T extends B{static{g(this,"Tus")}static{b(this,"Tus")}static methods=["delete","download","get","head","options","patch","post"];tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const t=this;this.tusBase=new class extends H{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads??!1}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async fetch(e){const t=await super.fetch(e);if(t.headers.has("Tus-Resumable"))return t;const s=new Headers(t.headers);return s.set("Tus-Resumable",O),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})}async options(){return this.tusBase.handleOptions(T.methods)}async post(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=e.headers.get("upload-length")||void 0,r=e.headers.get("upload-defer-length")||void 0,o=e.headers.get("upload-concat")||void 0,d=e.headers.get("upload-metadata")||void 0,u=e.headers.get("content-type")||"",n=e.headers.get("content-length"),h=n?Number.parseInt(n,10):0,c=e.url,p=e.body;return this.tusBase.handlePost(s,r,o,d,c,p,h,u)}async patch(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");const r=e.headers.get("upload-offset");if(!r)throw a(412,"Missing Upload-Offset header");const o=e.headers.get("content-type");if(!o)throw a(412,"Content-Type header required");if(o!=="application/offset+octet-stream")throw a(415,"Unsupported Media Type");const d=Number.parseInt(r,10),u=e.headers.get("upload-length")||void 0,n=e.headers.get("upload-metadata")||void 0,h=e.headers.get("content-length"),c=h?Number.parseInt(h,10):0,p=e.headers.get("upload-checksum")||void 0,{checksum:U,checksumAlgorithm:F}=this.tusBase.extractChecksum(p),v=e.url,y=e.body;try{return this.tusBase.handlePatch(s,d,u,n,U,F,v,y,c)}catch(m){const f=m;throw f.UploadErrorCode==="GONE"||f.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):m}}async head(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleHead(s)}catch(r){const o=r;throw o.UploadErrorCode==="GONE"||o.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):r}}async get(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleGet(s)}catch(r){throw r.UploadErrorCode==="GONE"?a(410,"Upload expired"):r}}async delete(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleDelete(s)}catch(r){throw r.code==="ENOENT"?a(404,"File not found"):r}}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("PATCH",this.patch.bind(this)),this.registeredHandlers.set("HEAD",this.head.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}buildFileUrlForTus(e,t){const s=new URL(e),{pathname:r,search:o}=s,d=`${r}/${t.id}${o}`;return this.storage.config.useRelativeLocation?d:s.origin+d}}export{O as TUS_RESUMABLE,k as TUS_VERSION,T as Tus};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var U=Object.defineProperty;var p=(h,e)=>U(h,"name",{value:e,configurable:!0});import{format as F}from"node:url";import{n as d}from"./headers-DC2MEOrK.js";import{a,b as m,g as n,c as T}from"./base-handler-core-
|
|
1
|
+
var U=Object.defineProperty;var p=(h,e)=>U(h,"name",{value:e,configurable:!0});import{format as F}from"node:url";import{n as d}from"./headers-DC2MEOrK.js";import{a,b as m,g as n,c as T}from"./base-handler-core-ty4J6Ji6.js";import{F as E}from"./base-handler-node-BCqhH22o.js";import{TusBase as y,TUS_RESUMABLE as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_VERSION as w}from"./TUS_RESUMABLE-B7KtPVeC.js";var B=Object.defineProperty,H=p((h,e)=>B(h,"name",{value:e,configurable:!0}),"h");class g extends E{static{p(this,"Tus")}static{H(this,"Tus")}static methods=["delete","download","get","head","options","patch","post"];disableTerminationForFinishedUploads=!1;tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const t=this;this.tusBase=new class extends y{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async options(){return this.tusBase.handleOptions(g.methods)}async post(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));const t=e.headers["upload-length"],s=e.headers["upload-defer-length"],r=e.headers["upload-concat"],o=a(e,"upload-metadata",!0),i=a(e,"content-type")||"",l=Number.parseInt(a(e,"content-length")||"0",10),u=e.originalUrl||e.url||"",c=m(e);return this.tusBase.handlePost(t,s,r,o,u,c,l,i)}async patch(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);if(e.headers["upload-offset"]===void 0)throw d(412,"Missing Upload-Offset header");if(e.headers["content-type"]===void 0)throw d(412,"Content-Type header required");if(e.headers["content-type"]!=="application/offset+octet-stream")throw d(415,"Unsupported Media Type");const s=Number.parseInt(a(e,"upload-offset"),10),r=e.headers["upload-length"],o=a(e,"upload-metadata",!0),i=Number(a(e,"content-length")),l=a(e,"upload-checksum"),{checksum:u,checksumAlgorithm:c}=this.tusBase.extractChecksum(l),b=e.originalUrl||e.url||"",f=m(e);return this.tusBase.handlePatch(t,s,r,o,u,c,b,f,i)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async head(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleHead(t)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async get(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleGet(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.UploadErrorCode==="GONE"?d(410,"Upload expired"):t}}async delete(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleDelete(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.code==="ENOENT"?d(404,"File not found"):t}}send(e,{body:t="",headers:s={},statusCode:r=200}){const o={body:t,headers:{...s,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control","Tus-Resumable":O},statusCode:r||200};super.send(e,o)}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("PATCH",this.patch.bind(this)),this.registeredHandlers.set("HEAD",this.head.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}buildFileUrlForTus(e,t){const s=new URL(e,"http://localhost"),{pathname:r}=s,o=Object.fromEntries(s.searchParams.entries()),i=F({pathname:`${r}/${t.id}`,query:o});return this.storage.config.useRelativeLocation?i:T({url:e})+i}}export{O as TUS_RESUMABLE,w as TUS_VERSION,g as Tus};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var V=Object.defineProperty;var C=(s,t)=>V(s,"name",{value:t,configurable:!0});import{PassThrough as J,Readable as R}from"node:stream";import{B as P}from"./storage-CI88PmRw.js";import{throwErrorCode as W,ERRORS as K}from"./ERRORS-vMSqlI69.js";var Y=Object.defineProperty,m=C((s,t)=>Y(s,"name",{value:t,configurable:!0}),"y");class ${static{C(this,"UploadControl")}static{m(this,"UploadControl")}key;controller=new AbortController;internalState="idle";loadedBytes;startPaused=!1;boundStream;constructor(t){this.loadedBytes=t?.loaded??0,this.key=t?.key}static from(t){const e=typeof t=="string"?JSON.parse(t):t;return new $({key:e.key,loaded:e.loaded})}get signal(){return this.controller.signal}get state(){return this.internalState}get loaded(){return this.loadedBytes}pause(){(this.internalState==="uploading"||this.internalState==="idle")&&(this.internalState="paused",this.startPaused=!0,this.boundStream?.pause())}resume(){this.internalState==="paused"&&(this.internalState="uploading",this.startPaused=!1,this.boundStream?.resume())}abort(t){this.internalState!=="completed"&&this.internalState!=="aborted"&&(this.internalState="aborted",this.controller.abort(t))}serialize(){return{key:this.key,loaded:this.loadedBytes,version:1}}_bind(t,e){this.boundStream=t,this.key??=e,this.internalState!=="aborted"&&(this.internalState=this.startPaused?"paused":"uploading"),this.startPaused&&t.pause()}_progress(t){this.loadedBytes=t}_complete(){this.internalState!=="aborted"&&(this.internalState="completed"),this.boundStream=void 0}}const U=8,q=m(s=>typeof s=="object"&&s!==null&&typeof s.getReader=="function","isWebReadableStream"),G=m(s=>typeof s=="object"&&s!==null&&typeof s.pipe=="function"&&typeof s.read=="function","isNodeReadable"),Q=m(async(s,t)=>{if(typeof s=="string"){const e=Buffer.from(s);return{size:e.byteLength,stream:R.from(e)}}if(Buffer.isBuffer(s))return{size:s.byteLength,stream:R.from(s)};if(s instanceof Uint8Array){const e=Buffer.from(s.buffer,s.byteOffset,s.byteLength);return{size:e.byteLength,stream:R.from(e)}}if(s instanceof ArrayBuffer){const e=Buffer.from(s);return{size:e.byteLength,stream:R.from(e)}}if(ArrayBuffer.isView(s)){const e=s,r=Buffer.from(e.buffer,e.byteOffset,e.byteLength);return{size:r.byteLength,stream:R.from(r)}}if(typeof Blob<"u"&&s instanceof Blob)return{size:s.size,stream:R.fromWeb(s.stream())};if(q(s))return{size:t,stream:R.fromWeb(s)};if(G(s))return{size:t,stream:s};throw new TypeError(`Unsupported body type: ${Object.prototype.toString.call(s)}`)},"normalizeBody"),I=m((s,t)=>({contentType:s.contentType??"application/octet-stream",etag:s.ETag,key:s.name||s.id||t||"",lastModified:s.modifiedAt??s.createdAt,metadata:s.metadata,size:typeof s.size=="number"?s.size:void 0}),"toFileObject"),j=m((s,t)=>{s.split("/").some(e=>e==="."||e==="..")&&W(K.INVALID_FILE_NAME,`${K.INVALID_FILE_NAME}: ${t} must not contain "." or ".." path segments: "${s}"`)},"assertNoRelativeSegments"),X=m(s=>{if(!s)return"";const t=s.split("/").filter(e=>e.length>0).join("/");return j(t,"prefix"),t},"normalizePrefix"),Z=m((s,t)=>{if(!t&&!s.signal&&s.timeout===void 0&&s.retries===void 0)return;const e={...s};return t&&(t.signal!==void 0&&(e.signal=t.signal),t.timeout!==void 0&&(e.timeout=t.timeout),t.retries!==void 0&&(e.retries=t.retries)),s.signal&&t?.signal&&(e.signal=AbortSignal.any([s.signal,t.signal])),e},"mergeOperationOptions"),D=m(async(s,t,e)=>{const r=Array.from({length:s.length});let n=0,o=!1;const u=m(async()=>{for(;n<s.length;){if(o||e.signal?.aborted)return;const a=n;n+=1;try{const i=await t(s[a],a);r[a]={status:"fulfilled",value:i}}catch(i){r[a]={reason:i,status:"rejected"},e.stopOnError&&(o=!0)}}},"worker"),c=Math.max(1,Math.min(e.concurrency,s.length)),l=Array.from({length:c},()=>u());return await Promise.all(l),r},"runConcurrent"),b=m((s,t)=>t instanceof Error?{error:t,key:s}:{error:new Error(typeof t=="string"?t:"Unknown error",{cause:t}),key:s},"toBulkError"),_=m((s,t)=>{if(s)try{s(t)}catch{}},"safeInvoke");class F{static{C(this,"Files")}static{m(this,"Files")}adapter;defaults;hooks;prefix;readonlyMode;constructor(t){this.adapter=t.adapter,this.defaults=t.defaults??{},this.hooks=t.hooks??{},this.prefix=X(t.prefix??""),this.readonlyMode=t.readonly??!1}get capabilities(){return{cacheControl:this.adapter.supportsCacheControl,metadata:this.adapter.supportsMetadata,range:this.adapter.supportsRange,readonly:this.readonlyMode}}readonly(){return new F({adapter:this.adapter,defaults:this.defaults,hooks:this.hooks,prefix:this.prefix,readonly:!0})}assertWritable(){this.readonlyMode&&W(K.READ_ONLY,"This Files instance is read-only")}get raw(){return this.adapter.raw}resolveKey(t){const e=t.replace(/^\/+/u,"");return j(e,"key"),this.prefix?`${this.prefix}/${e}`:t}stripPrefix(t){const e=t.startsWith("/")?t.slice(1):t;if(!this.prefix)return e;const r=`${this.prefix}/`;return e.startsWith(r)?e.slice(r.length):null}mergeOptions(t,e){const r=Z(this.defaults,t);if(!e||!this.hooks.onRetry)return r;const n=r?.retries,o=typeof n=="number"?{maxRetries:n}:{...n},u=o.onRetry,c=this.hooks.onRetry;return o.onRetry=(l,a)=>{if(u)try{u(l,a)}catch{}try{const i=typeof a=="string"?a:"Unknown error",d=a instanceof Error?a:new Error(i,{cause:a});c({...e,attempt:l,error:d})}catch{}},{...r,retries:o}}emitAction(t,e){if(this.hooks.onAction)try{this.hooks.onAction({type:t,...e})}catch{}}emitError(t,e,r){if(this.hooks.onError)try{this.hooks.onError({error:r,type:t,...e})}catch{}}async withHooks(t,e,r){const n=Date.now();try{const o=await r();return this.emitAction(t,{...e,durationMs:Date.now()-n}),o}catch(o){const u=typeof o=="string"?o:"Unknown error",c=o instanceof Error?o:new Error(u,{cause:o});throw this.emitError(t,{...e,durationMs:Date.now()-n},c),c}}async upload(t,e,r){return Array.isArray(t)?this.uploadMany(t,e):this.uploadOne(t,e,r)}async uploadOne(t,e,r){this.assertWritable(),r?.metadata&&Object.keys(r.metadata).length>0&&!this.adapter.supportsMetadata&&W(K.METHOD_NOT_ALLOWED,`Adapter ${this.adapter.constructor.name} does not persist custom metadata`);const n=r?.control;return this.withHooks("upload",{key:t},async()=>{const o=this.resolveKey(t);P.assertSafeId(o);const{size:u,stream:c}=await Q(e,r?.size),l=r?.size??u,a={...r?.metadata??{},name:o,...r?.contentType?{type:r.contentType}:{},...l===void 0?{}:{size:l}},i=n?{...r,signal:r?.signal?AbortSignal.any([r.signal,n.signal]):n.signal}:r,d=this.mergeOptions(i,{key:t,type:"upload"}),p=r?.multipart;n?._bind(c,t);const y=await this.adapter.create({contentType:r?.contentType,id:o,metadata:a,originalName:o,size:l,storageClass:r?.storageClass},d),f=this.adapter.reportsUploadProgress,h=r?.onProgress,S=!!h||!!n;let w=c;if(S&&!f){let N=0;const M=new J;l!==void 0&&h&&_(h,{loaded:0,total:l}),c.on("data",T=>{const O=typeof T=="string"?Buffer.byteLength(T):T.byteLength;N+=O,n?._progress(N),h&&_(h,{loaded:N,total:l})}),c.pipe(M),w=M}const E={body:w,contentLength:l,id:y.id,start:0,...p!==void 0&&{multipart:p},...f&&h&&{onProgress:h}},k=await this.adapter.write(E,d);n?._complete();const A=I(k,o),g=this.stripPrefix(A.key);return g!==null&&(A.key=g),A})}async uploadMany(t,e){this.assertWritable();const{concurrency:r=U,multipart:n,onProgress:o,stopOnError:u=!1,...c}=e??{},l=await D(t,async({body:d,key:p,...y})=>{const f=y.onProgress??(o?h=>{o({...h,key:p})}:void 0);return this.uploadOne(p,d,{...c,multipart:n,...y,...f&&{onProgress:f}})},{concurrency:r,signal:c.signal,stopOnError:u}),a=[],i=[];for(const[d,p]of l.entries()){const y=t[d];if(!p){i.push(b(y.key,new Error("Operation skipped (stopOnError)")));continue}p.status==="fulfilled"?a.push(p.value):i.push(b(y.key,p.reason))}return i.length>0?{errors:i,uploaded:a}:{uploaded:a}}async download(t,e){return Array.isArray(t)?this.downloadMany(t,e):this.downloadOne(t,e)}assertRangeSupported(t){if(t){if(!Number.isFinite(t.start)||t.start<0)throw new TypeError(`Invalid range.start: ${String(t.start)}`);if(t.end!==void 0&&(!Number.isFinite(t.end)||t.end<t.start))throw new TypeError(`Invalid range.end: ${String(t.end)}`);if(!this.adapter.supportsRange)throw new Error(`Adapter ${this.adapter.constructor.name} does not support range downloads`)}}async downloadOne(t,e){return this.withHooks("download",{key:t},async()=>{const r=this.resolveKey(t);P.assertSafeId(r),this.assertRangeSupported(e?.range);const n=this.mergeOptions(e,{key:t,type:"download"})??{},o=e?.range?{...n,range:e.range}:n,u=await this.adapter.get({id:r},o);return{body:u.content,contentType:u.contentType??"application/octet-stream",etag:u.ETag,key:t,lastModified:u.modifiedAt,metadata:u.metadata,size:typeof u.size=="number"?u.size:void 0}})}async downloadMany(t,e){const{concurrency:r=U,range:n,stopOnError:o=!1,...u}=e??{},c=await D(t,async i=>this.downloadOne(i,n?{...u,range:n}:u),{concurrency:r,signal:u.signal,stopOnError:o}),l=[],a=[];for(const[i,d]of c.entries()){const p=t[i];if(!d){a.push(b(p,new Error("Operation skipped (stopOnError)")));continue}d.status==="fulfilled"?l.push(d.value):a.push(b(p,d.reason))}return a.length>0?{downloaded:l,errors:a}:{downloaded:l}}async head(t,e){return Array.isArray(t)?this.headMany(t,e):this.headOne(t,e)}async headOne(t,e){return this.withHooks("head",{key:t},async()=>{const r=this.resolveKey(t);P.assertSafeId(r);const n=await this.adapter.getMeta(r,this.mergeOptions(e,{key:t,type:"head"})),o=I(n,r);return o.key=t,o})}async headMany(t,e){const{concurrency:r=U,stopOnError:n=!1,...o}=e??{},u=await D(t,async a=>this.headOne(a,o),{concurrency:r,signal:o.signal,stopOnError:n}),c=[],l=[];for(const[a,i]of u.entries()){const d=t[a];if(!i){l.push(b(d,new Error("Operation skipped (stopOnError)")));continue}i.status==="fulfilled"?c.push(i.value):l.push(b(d,i.reason))}return l.length>0?{errors:l,files:c}:{files:c}}async exists(t,e){return Array.isArray(t)?this.existsMany(t,e):this.existsOne(t,e)}async existsOne(t,e){return this.withHooks("exists",{key:t},async()=>{const r=this.resolveKey(t);return P.assertSafeId(r),this.adapter.exists({id:r},this.mergeOptions(e,{key:t,type:"exists"}))})}async existsMany(t,e){const{concurrency:r=U,stopOnError:n=!1,...o}=e??{},u=await D(t,async i=>this.existsOne(i,o),{concurrency:r,signal:o.signal,stopOnError:n}),c=[],l=[],a=[];for(const[i,d]of u.entries()){const p=t[i];if(!d){a.push(b(p,new Error("Operation skipped (stopOnError)")));continue}d.status==="fulfilled"?d.value?c.push(p):l.push(p):a.push(b(p,d.reason))}return a.length>0?{errors:a,existing:c,missing:l}:{existing:c,missing:l}}async delete(t,e){if(this.assertWritable(),Array.isArray(t))return this.deleteMany(t,e);await this.deleteOne(t,e)}async deleteOne(t,e){await this.withHooks("delete",{key:t},async()=>{const r=this.resolveKey(t);P.assertSafeId(r),await this.adapter.delete({id:r},this.mergeOptions(e,{key:t,type:"delete"}))})}async deleteMany(t,e){const{concurrency:r=U,stopOnError:n=!1,...o}=e??{},u=this.mergeOptions(o,{keys:t,type:"delete"});if(!n&&typeof this.adapter.deleteBatch=="function"){const i=[],d=[],p=[];for(const y of t)try{const f=this.resolveKey(y);P.assertSafeId(f),i.push(y),d.push(f)}catch(f){p.push(b(y,f))}return this.withHooks("delete",{keys:i},async()=>{const y=d.length>0?await this.adapter.deleteBatch(d,u):{failed:[],successful:[]},f=new Map(d.map((w,E)=>[w,E])),h=y.successful.map(w=>this.stripPrefix(w.id)??w.id),S=[...p,...y.failed.map(({error:w,id:E})=>{const k=f.get(E),A=k===void 0?E:i[k];return b(A,new Error(w))})];return S.length>0?{deleted:h,errors:S}:{deleted:h}})}const c=await D(t,async i=>this.deleteOne(i,o),{concurrency:r,signal:o.signal,stopOnError:n}),l=[],a=[];for(const[i,d]of c.entries()){const p=t[i];if(!d){a.push(b(p,new Error("Operation skipped (stopOnError)")));continue}d.status==="fulfilled"?l.push(p):a.push(b(p,d.reason))}return a.length>0?{deleted:l,errors:a}:{deleted:l}}async copy(t,e,r){return this.assertWritable(),this.withHooks("copy",{from:t,to:e},async()=>{const n=this.resolveKey(t),o=this.resolveKey(e);P.assertSafeId(n),P.assertSafeId(o);const u=await this.adapter.copy(n,o,{...this.mergeOptions(r,{from:t,to:e,type:"copy"}),storageClass:r?.storageClass}),c=I(u,o);return c.key=e,c})}async move(t,e,r){return this.assertWritable(),Array.isArray(t)?this.moveMany(t,e):this.moveOne(t,e,r)}async moveOne(t,e,r){return this.withHooks("move",{from:t,to:e},async()=>{const n=this.resolveKey(t);if(P.assertSafeId(n),t===e){const a=await this.adapter.getMeta(n,this.mergeOptions(r,{from:t,to:e,type:"move"})),i=I(a,n);return i.key=t,i}const o=this.resolveKey(e);P.assertSafeId(o);const u={...this.mergeOptions(r,{from:t,to:e,type:"move"}),...r?.storageClass!==void 0&&{storageClass:r.storageClass}},c=await this.adapter.move(n,o,u),l=I(c,o);return l.key=e,l})}async moveMany(t,e){const{concurrency:r=U,stopOnError:n=!1,...o}=e??{},u=await D(t,async({from:a,to:i})=>this.moveOne(a,i,o),{concurrency:r,signal:o.signal,stopOnError:n}),c=[],l=[];for(const[a,i]of u.entries()){const d=t[a];if(!i){l.push(b(d.from,new Error("Operation skipped (stopOnError)")));continue}i.status==="fulfilled"?c.push(i.value):l.push(b(d.from,i.reason))}return l.length>0?{errors:l,moved:c}:{moved:c}}async list(t={}){return this.withHooks("list",{},async()=>{const{delimiter:e,limit:r,prefix:n,...o}=t;if(e!==void 0&&this.adapter.supportsDelimiter)return this.listDirectoryNative(e,n,r,o);const u=await this.adapter.list(r??1e3,this.mergeOptions(o,{type:"list"})),c=[];for(const p of u){const y=I(p),f=this.stripPrefix(y.key);f!==null&&(y.key=f,c.push(y))}const l=n?c.filter(p=>p.key.startsWith(n)):c;if(e===void 0)return l;const a=n??"",i=[],d=new Set;for(const p of l){const y=p.key.slice(a.length),f=y.indexOf(e);f===-1?i.push(p):d.add(a+y.slice(0,f+e.length))}return{files:i,prefixes:[...d].toSorted()}})}async listDirectoryNative(t,e,r,n){const o=[this.prefix,e].filter(Boolean).join("/"),{files:u,prefixes:c}=await this.adapter.listDirectory({delimiter:t,...r!==void 0&&{limit:r},...o&&{prefix:o},...this.mergeOptions(n,{type:"list"})}),l=[];for(const i of u){const d=I(i),p=this.stripPrefix(d.key);p!==null&&(d.key=p,l.push(d))}const a=[];for(const i of c){const d=this.stripPrefix(i);d!==null&&a.push(d)}return{files:l,prefixes:a.toSorted()}}async*listAll(t={}){const{limit:e,prefix:r,...n}=t,o=Math.max(1,e??1e3),u=Date.now(),c=new Set;let l;try{for(;;){const a=await this.adapter.list(o,this.mergeOptions(n,{type:"listAll"}));let i=0;for(const d of a){const p=I(d),y=this.stripPrefix(p.key);y!==null&&(p.key=y,!(r&&!p.key.startsWith(r))&&(c.has(p.key)||(c.add(p.key),i+=1,yield p)))}if(i===0||a.length<o)break}}catch(a){const i=typeof a=="string"?a:"Unknown error";throw l=a instanceof Error?a:new Error(i,{cause:a}),l}finally{const a=Date.now()-u;l?this.emitError("listAll",{durationMs:a},l):this.emitAction("listAll",{durationMs:a})}}async url(t,e){return this.withHooks("url",{key:t},async()=>{const r=this.resolveKey(t);return P.assertSafeId(r),this.adapter.getReadUrl(r,{...this.mergeOptions(e,{key:t,type:"url"}),...e})})}async signedUploadUrl(t,e){return this.assertWritable(),this.withHooks("signedUploadUrl",{key:t},async()=>{const r=this.resolveKey(t);return P.assertSafeId(r),this.adapter.getUploadUrl(r,{...this.mergeOptions(e,{key:t,type:"signedUploadUrl"}),...e})})}}const ot=m(async(s,t,e={})=>{const{concurrency:r=U,limit:n,onProgress:o,overwrite:u=!1,prefix:c,signal:l,stopOnError:a=!1,transformKey:i}=e,d=[],p=[],y=[];let f=!1,h=0;const S=m(g=>{if(o)try{o(g)}catch{}},"emit"),w=s.listAll({...c!==void 0&&{prefix:c},...n!==void 0&&{limit:n}}),E=m(async g=>{if(f||l?.aborted)return;const N=i?i(g):g;try{if(!u&&await t.exists(N,{signal:l})){p.push(g),h+=1,S({done:h,key:g,status:"skipped"});return}const M=await s.download(g,{signal:l});await t.upload(N,M.body,{...M.contentType&&{contentType:M.contentType},...M.metadata&&{metadata:M.metadata},signal:l}),d.push(g),h+=1,S({done:h,key:g,status:"transferred"})}catch(M){const T=b(g,M);if(y.push(T),h+=1,S({done:h,error:T.error,key:g,status:"errored"}),a)throw f=!0,T.error}},"transferOne");if(a){try{for await(const g of w){if(f||l?.aborted)break;try{await E(g.key)}catch{break}}}finally{await w.return?.()}return y.length>0?{errors:y,skipped:p,transferred:d}:{skipped:p,transferred:d}}const k=Math.max(1,r),A=m(async()=>{for(;!f&&!l?.aborted;){const g=await w.next();if(g.done)return;await E(g.value.key)}},"worker");try{await Promise.all(Array.from({length:k},()=>A()))}finally{await w.return?.()}return y.length>0?{errors:y,skipped:p,transferred:d}:{skipped:p,transferred:d}},"transfer"),tt=m((s,t)=>{if(typeof s.size=="number"&&typeof t.size=="number"&&s.size!==t.size)return!1;if(s.etag&&t.etag)return s.etag===t.etag;if(typeof s.size=="number"&&typeof t.size=="number")return!0;const e=s.lastModified===void 0?void 0:Number(new Date(s.lastModified)),r=t.lastModified===void 0?void 0:Number(new Date(t.lastModified));return e!==void 0&&r!==void 0&&!Number.isNaN(e)&&!Number.isNaN(r)?e<=r:!0},"objectsMatch"),it=m(async(s,t,e={})=>{const{concurrency:r=U,dryRun:n=!1,limit:o,onProgress:u,prefix:c,prune:l=!1,signal:a,stopOnError:i=!1,transformKey:d}=e,p=[],y=[],f=[],h=[],S=[],w=new Set;let E=!1,k=0;const A=m(O=>{if(u)try{u(O)}catch{}},"emit"),g=s.listAll({...c!==void 0&&{prefix:c},...o!==void 0&&{limit:o}}),N=m(async O=>{if(E||a?.aborted)return;const x=O.key,L=d?d(x):x;w.add(L);try{let v;try{v=await t.head(L,{signal:a})}catch{v=void 0}if(v){let z=O;if(O.size===void 0&&O.etag===void 0)try{z=await s.head(x,{signal:a})}catch{}if(tt(z,v)){f.push(x),k+=1,A({done:k,key:x,status:"unchanged"});return}}const B=v!==void 0;if(!n){const z=await s.download(x,{signal:a});await t.upload(L,z.body,{...z.contentType&&{contentType:z.contentType},...z.metadata&&{metadata:z.metadata},signal:a})}B?y.push(x):p.push(x),k+=1,A({done:k,key:x,status:B?"updated":"uploaded"})}catch(v){const B=b(x,v);if(S.push(B),k+=1,A({done:k,error:B.error,key:x,status:"errored"}),i)throw E=!0,B.error}},"syncOne"),M=Math.max(1,r),T=m(async()=>{for(;!E&&!a?.aborted;){const O=await g.next();if(O.done)return;await N(O.value)}},"worker");try{await Promise.all(Array.from({length:M},()=>T()))}finally{await g.return?.()}if(l&&!E&&!a?.aborted){const O=[],x=t.listAll({...c!==void 0&&{prefix:c},...o!==void 0&&{limit:o}});try{for await(const v of x)w.has(v.key)||O.push(v.key)}finally{await x.return?.()}const L=await D(O,async v=>(n||await t.delete(v,{signal:a}),v),{concurrency:M,signal:a,stopOnError:i});for(const[v,B]of L.entries()){const z=O[v];if(B)if(B.status==="fulfilled")h.push(z),k+=1,A({done:k,key:z,status:"deleted"});else{const H=b(z,B.reason);S.push(H),k+=1,A({done:k,error:H.error,key:z,status:"errored"})}}}return S.length>0?{deleted:h,errors:S,unchanged:f,updated:y,uploaded:p}:{deleted:h,unchanged:f,updated:y,uploaded:p}},"sync");export{F as Files,$ as UploadControl,F as default,it as sync,ot as transfer};
|
package/dist/packem_shared/{UploadThingMetaStorage-DPIokkHa.js → UploadThingMetaStorage-CdDfhiyy.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=Object.defineProperty;var r=(a,e)=>t(a,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-
|
|
1
|
+
var t=Object.defineProperty;var r=(a,e)=>t(a,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-tayO1ARY.js";var s=Object.defineProperty,c=r((a,e)=>s(a,"name",{value:e,configurable:!0}),"a");class u extends o{static{r(this,"r")}static{c(this,"UploadThingMetaStorage")}constructor(e){super(e)}}export{u as default};
|
package/dist/packem_shared/{UploadThingStorage-B3aIKSMh.js → UploadThingStorage-ByryGerX.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var T=Object.defineProperty;var l=(r,t)=>T(r,"name",{value:t,configurable:!0});import{UTApi as U,UTFile as h}from"uploadthing/server";import{throwErrorCode as m,ERRORS as f}from"./ERRORS-vMSqlI69.js";import{B as I}from"./storage-
|
|
1
|
+
var T=Object.defineProperty;var l=(r,t)=>T(r,"name",{value:t,configurable:!0});import{UTApi as U,UTFile as h}from"uploadthing/server";import{throwErrorCode as m,ERRORS as f}from"./ERRORS-vMSqlI69.js";import{B as I}from"./storage-CI88PmRw.js";import d from"./UploadThingFile-BpG9mE8K.js";import O from"./UploadThingMetaStorage-CdDfhiyy.js";import{o as y}from"./get-file-status-DLS18Zvd.js";import{u as E}from"./update-size-DANV7aa2.js";import{r as k}from"./part-match-D_NwyoF3.js";import{o as v}from"./has-content-Bx2p8Okx.js";var b=Object.defineProperty,u=l((r,t)=>b(r,"name",{value:t,configurable:!0}),"c");const w=3600*24*7,x=u(r=>{let t;try{t=typeof atob=="function"?atob(r):Buffer.from(r,"base64").toString("utf8")}catch(e){throw new Error(`UploadThing: token is not valid base64: ${e.message}`)}let a;try{a=JSON.parse(t)}catch(e){throw new Error(`UploadThing: token does not decode to JSON: ${e.message}`)}if(!a||typeof a!="object"||typeof a.apiKey!="string"||typeof a.appId!="string")throw new Error("UploadThing: token missing `apiKey` or `appId`");return a},"decodeToken"),N=u(async r=>{const t=[];for await(const a of r)t.push(Buffer.from(a));return Buffer.concat(t)},"collectStream"),g=u(r=>{const t=r.lastIndexOf("/");return t===-1?r:r.slice(t+1)},"basename");class B extends I{static name="uploadthing";checksumTypes=[];meta;acl;appId;defaultUrlExpiresIn;utapi;constructor(t){super(t);const a=t.token??process.env.UPLOADTHING_TOKEN;if(t.client)this.utapi=t.client;else{if(!a)throw new Error("UploadThing: missing token. Pass `token` or set UPLOADTHING_TOKEN.");this.utapi=new U({defaultKeyType:"customId",token:a})}if(!a)throw new Error("UploadThing: `token` is required even when passing `client` so the adapter can derive `appId` for CDN URLs.");this.appId=x(a).appId,this.acl=t.acl??"public-read",this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,w),this.meta=t.metaStorage??new O(t.metaStorageConfig),this.isReady=!0}get raw(){return this.utapi}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new d(t);e.name=this.namingFunction(e),e.customId=e.name,await this.validate(e);try{const i=await this.getMeta(e.id);if(i.bytesWritten>=0)return i}catch{}return e.bytesWritten=0,e.status=y(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&E(e,t.size),!k(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(v(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await N(t.body),p=new Blob([new Uint8Array(n)],{type:e.contentType}),o=new h([p],g(e.name||e.id),{customId:e.name||e.id,type:e.contentType}),s=await this.runOperation(a,()=>this.utapi.uploadFiles(o,{acl:this.acl}));if(s.error)throw new Error(s.error.message);const{data:c}=s;e.bytesWritten=n.length,e.size=n.length,e.ufsKey=c.key,e.url=c.ufsUrl??c.url,e.ETag=c.fileHash,e.fileHash=c.fileHash}return e.status=y(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,i)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const i=e?.customId??e?.name??t;return await this.runOperation(a,()=>this.utapi.deleteFiles(i)),e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new d({contentType:"application/octet-stream",metadata:{},originalName:t}),{customId:i,id:t,name:t,status:"deleted"})})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e,i=t;try{e=await this.checkIfExpired(await this.getMeta(t)),i=e.customId??e.name??t}catch{}const n=await this.resolveFetchUrl(i,a),p=await this.runOperation(a,()=>fetch(n));if(!p.ok)throw new Error(`UploadThing: fetch failed: ${p.status} ${p.statusText} for ${i}`);const o=Buffer.from(await p.arrayBuffer());return{content:o,contentType:e?.contentType??p.headers.get("content-type")??"application/octet-stream",ETag:e?.ETag??p.headers.get("etag")??void 0,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt,name:e?.name??i,originalName:e?.originalName??i,size:e?.size??o.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=await this.get({id:t},e),n=new Blob([new Uint8Array(i.content)],{type:i.contentType}),p=new h([n],g(a),{customId:a,type:i.contentType}),o=await this.runOperation(e,()=>this.utapi.uploadFiles(p,{acl:this.acl}));if(o.error)throw new Error(o.error.message);const s=new d({contentType:i.contentType,metadata:{},originalName:a});return s.id=a,s.name=a,s.customId=a,s.size=typeof i.size=="string"?Number(i.size):i.size,s.ufsKey=o.data.key,s.url=o.data.ufsUrl??o.data.url,s.ETag=o.data.fileHash,s})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=await this.copy(t,a,e);return await this.delete({id:t},e),i})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>(await this.runOperation(a,()=>this.utapi.listFiles({limit:t}))).files.map(e=>{const i=e.customId??e.key,n=new d({contentType:"application/octet-stream",metadata:{},originalName:i});return n.id=i,n.name=i,n.customId=e.customId??void 0,n.ufsKey=e.key,n.size=e.size,n.modifiedAt=e.uploadedAt?new Date(e.uploadedAt).toISOString():void 0,n}),{limit:t})}async getReadUrl(t,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return m(f.METHOD_NOT_ALLOWED,"UploadThing: `responseContentDisposition`/`responseContentType` are not supported — no override exists on UploadThing CDN/signed URLs.");if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const e=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,w),{ufsUrl:i}=await this.utapi.generateSignedURL(t,{expiresIn:e,keyType:"customId"});return i}async getUploadUrl(t,a){return m(f.METHOD_NOT_ALLOWED,"UploadThing: presigned PUT URLs require the UFS ingest signing scheme — use the file-router pattern via `storage.raw` instead.")}async resolveFetchUrl(t,a){if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const{ufsUrl:e}=await this.runOperation(a,()=>this.utapi.generateSignedURL(t,{expiresIn:this.defaultUrlExpiresIn,keyType:"customId"}));return e}internalOnComplete=u(t=>this.deleteMeta(t.id),"internalOnComplete")}export{B as default};
|
package/dist/packem_shared/{VercelBlobMetaStorage-Bx0l9Xt6.js → VercelBlobMetaStorage-CC1zy35k.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-
|
|
1
|
+
var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-tayO1ARY.js";var s=Object.defineProperty,c=t((r,e)=>s(r,"name",{value:e,configurable:!0}),"e");class i extends o{static{t(this,"l")}static{c(this,"VercelBlobMetaStorage")}constructor(e){super(e)}}export{i as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var E=Object.defineProperty;var u=(c,e)=>E(c,"name",{value:e,configurable:!0});import{put as d,list as m,del as h,copy as p}from"@vercel/blob";import{a as g}from"./detect-file-type-
|
|
1
|
+
var E=Object.defineProperty;var u=(c,e)=>E(c,"name",{value:e,configurable:!0});import{put as d,list as m,del as h,copy as p}from"@vercel/blob";import{a as g}from"./detect-file-type-DRWGvQW4.js";import{B as v,t as T}from"./storage-CI88PmRw.js";import{v as b}from"./local-meta-storage-tayO1ARY.js";import f from"./VercelBlobFile-Cni_1qwD.js";import{o as w}from"./get-file-status-DLS18Zvd.js";import{u as B}from"./update-size-DANV7aa2.js";import{r as _}from"./part-match-D_NwyoF3.js";import{o as k}from"./has-content-Bx2p8Okx.js";var I=Object.defineProperty,C=u((c,e)=>I(c,"name",{value:e,configurable:!0}),"p");class y extends v{static name="vercel-blob";checksumTypes=["md5"];get raw(){return{copy:p,credentials:this.credentials,del:h,list:m,put:d}}meta;credentials;multipart;access;constructor(e){super(e),this.credentials=y.resolveCredentials(e),this.multipart=e.multipart??!1,this.access=e.access??"public";const{metaStorage:i,metaStorageConfig:t}=e;this.meta=i||new b(t),this.isReady=!0}static resolveCredentials(e){if(e.token)return{token:e.token};const i=e.oidcToken??process.env.VERCEL_OIDC_TOKEN,t=e.storeId??process.env.BLOB_STORE_ID,r=t?.startsWith("store_")?t.slice(6):t;if(i&&r)return{oidcToken:i,storeId:r};if(i||r)throw new Error(`Vercel Blob OIDC auth requires both \`oidcToken\` and \`storeId\` (or \`VERCEL_OIDC_TOKEN\` and \`BLOB_STORE_ID\` env vars). Got: oidcToken=${i?"set":"missing"}, storeId=${r?"set":"missing"}.`);const a=process.env.BLOB_READ_WRITE_TOKEN||process.env.VERCEL_BLOB_TOKEN;if(a)return{token:a};throw new Error("Vercel Blob credentials are required. Provide `token`, an `oidcToken`+`storeId` pair, or set BLOB_READ_WRITE_TOKEN / (VERCEL_OIDC_TOKEN + BLOB_STORE_ID) env vars.")}async create(e,i){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const a=typeof e.ttl=="string"?T(e.ttl):e.ttl;t.expiredAt=a===void 0?void 0:Date.now()+a}const r=new f(t);r.name=this.namingFunction(r),await this.validate(r);try{const a=await this.getMeta(r.id);if(a.bytesWritten>=0)return a}catch{}return r.bytesWritten=0,r.status=w(r),await this.saveMeta(r),await this.onCreate(r),r})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&B(t,e.size),!_(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(k(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],n=e.body;for await(const o of n)a.push(Buffer.from(o));const s=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await g(s);o?.mime&&(t.contentType=o.mime)}catch{}const O=new Blob([s],{type:t.contentType}),l=await this.runOperation(i,()=>d(t.name,O,{access:this.access,multipart:this.shouldUseMultipart(t),...this.credentials}));t.url=l.url,t.pathname=l.pathname,t.downloadUrl=l.downloadUrl,t.bytesWritten=s.length}return t.status=w(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.url)throw new Error(`File ${e} does not have a valid URL`);const{url:r}=t;t.status="deleted";try{await this.runOperation(i,()=>h(r,{...this.credentials}))}catch(n){this.logger?.error("Failed to delete blob from Vercel Blob:",n);const s=this.normalizeError(n instanceof Error?n:new Error(String(n)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},i){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);if(!t.url||t.url.length===0)return!1;const{url:r}=t;return(await this.runOperation(i,()=>fetch(r,{method:"HEAD"}))).ok}catch{return!1}})}async get({id:e},i){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e));if(!t.url||t.url.length===0)throw new Error("File URL not found");const{url:r}=t,a=await this.runOperation(i,()=>fetch(r)),n=Buffer.from(await this.runOperation(i,()=>a.arrayBuffer()));return{content:n,contentType:t.contentType,ETag:t.ETag,expiredAt:t.expiredAt,id:e,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size||n.length}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const r=await this.getMeta(e);if(!r.url)throw new Error("Source file URL not found");const a=r.url,n=await this.runOperation(t,()=>p(a,i,{access:"public",...this.credentials}));return{...r,id:i,name:i,pathname:n.pathname,url:n.url}})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const r=await this.copy(e,i,t);return await this.delete({id:e},t),r})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>(await this.runOperation(i,()=>m({limit:e,...this.credentials}))).blobs.map(t=>{const r=new f({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return r.createdAt=t.uploadedAt?.toISOString(),r.id=t.pathname,r.modifiedAt=t.uploadedAt?.toISOString(),r.name=t.pathname,r.pathname=t.pathname,r.size=t.size,r.url=t.url,r.downloadUrl=t.downloadUrl,r}),{limit:e})}internalOnComplete=C(e=>this.deleteMeta(e.id),"internalOnComplete");shouldUseMultipart(e){return typeof this.multipart=="boolean"?this.multipart:typeof this.multipart=="number"&&e.size!==void 0?e.size>=this.multipart:!1}}export{y as default};
|
|
@@ -72,4 +72,4 @@ type SignUploadUrlInput = z.infer<typeof signUploadUrlInputSchema>;
|
|
|
72
72
|
* - object — per-tool override; unspecified write tools default to `true`
|
|
73
73
|
*/
|
|
74
74
|
type ApprovalConfig = boolean | Partial<Record<FileWriteToolName, boolean>>;
|
|
75
|
-
export { ApprovalConfig as A, CopyFileInput as C, DeleteFileInput as D,
|
|
75
|
+
export { ApprovalConfig as A, CopyFileInput as C, DeleteFileInput as D, FileToolName as F, GetFileMetadataInput as G, ListFilesInput as L, SignUploadUrlInput as S, TOOL_SCHEMAS as T, UploadFileInput as U, DownloadFileInput as a, GetFileUrlInput as b, FileReadToolName as c, FileWriteToolName as d };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var b=Object.defineProperty;var u=(r,e)=>b(r,"name",{value:e,configurable:!0});import{EventEmitter as y}from"node:events";import{format as w}from"node:url";import R from"mime";import{ErrorMap as E}from"./ERRORS-vMSqlI69.js";import{H as v}from"./headers-DC2MEOrK.js";import{Readable as p}from"node:stream";import U,{hasBody as I}from"type-is";import{B as h}from"./storage-
|
|
1
|
+
var b=Object.defineProperty;var u=(r,e)=>b(r,"name",{value:e,configurable:!0});import{EventEmitter as y}from"node:events";import{format as w}from"node:url";import R from"mime";import{ErrorMap as E}from"./ERRORS-vMSqlI69.js";import{H as v}from"./headers-DC2MEOrK.js";import{Readable as p}from"node:stream";import U,{hasBody as I}from"type-is";import{B as h}from"./storage-CI88PmRw.js";var H=Object.defineProperty,L=u((r,e)=>H(r,"name",{value:e,configurable:!0}),"a");const $=L(r=>r.at(-1),"getLastOne");var B=Object.defineProperty,i=u((r,e)=>B(r,"name",{value:e,configurable:!0}),"n");const N=i(r=>{let e="",t="";const s=c(r,"forwarded");return s&&s.split(";").forEach(a=>{const[n,o]=a.split("=");n==="proto"&&(e=o),n==="host"&&(t=o)}),{host:t,proto:e}},"extractForwarded"),x=i((r,e="utf8",t)=>new Promise((s,a)=>{const n=[];let o=0;r.on("data",l=>{const d=Buffer.isBuffer(l)?l:Buffer.from(l,e);if(o+=d.length,t!==void 0&&o>t){a(new Error("Request body length limit exceeded")),r.destroy();return}n.push(d)}),r.once("end",()=>{s(Buffer.concat(n).toString(e))}),r.once("error",a)}),"readBody"),c=i((r,e,t=!1)=>{const s=r.headers?.[e.toLowerCase()];if(!s||s.length===0)return"";if(t)return s.toString().trim();const a=Array.isArray(s)?s:s.split(",");return $(a).trim()},"getHeader");i(async(r,e=16777216)=>{if(!U(r,["json"]))return{};if(r.body)return{...r.body};if(I(r)){const s=Number.parseInt(c(r,"content-length"),10);if(!Number.isNaN(s)&&s>e)throw new Error("body length limit")}const t=await x(r,"utf8",e);return{...JSON.parse(t)}},"getMetadata");const P=i((r,e,t)=>{const s=[r.getHeader(e),t].flat().filter(Boolean).toString();r.setHeader(e,s)},"appendHeader"),V=i((r,e={})=>{const t=Object.keys(e);t.length>0&&P(r,"Access-Control-Expose-Headers",t),t.forEach(s=>{if(["link","location"].includes(s.toLowerCase())){const a=encodeURI(e[s].toString()).replaceAll("#","%23");r.setHeader(s,a)}else r.setHeader(s,e[s])})},"setHeaders"),q=i(r=>c(r,"host")||c(r,"x-forwarded-host"),"extractHost"),F=i(r=>c(r,"x-forwarded-proto").toLowerCase(),"extractProto"),T=i(r=>{let{host:e,proto:t}=N(r);return e||=q(r),t||=F(r),e?t?`${t}://${e}`:`//${e}`:""},"getBaseUrl"),S=i(r=>{let e=(r.originalUrl||r.url||"").split("?")[0];if(!e)throw new TypeError("Invalid request URL");return e.startsWith("/")||(e=`/${e}`),e.startsWith("http")&&(e=new URL(e).pathname),e},"getRealPath"),O=/^[\da-z]{4,}(?:-[\da-z]{4,}){2,}$/i,X=i(r=>{const e=S(r).split("/").filter(Boolean);if(e.length===0)throw new Error("Invalid request URL");for(let a=e.length-1;a>=0;a-=1){const n=e[a];if(!n)continue;const o=n.replace(/\.[^/.]+$/,"");if(!["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(o.toLowerCase())&&O.test(o))return h.assertSafeId(o),o}const t=e[e.length-1];if(!t)throw new Error("Invalid request URL");const s=t.replace(/\.[^/.]+$/,"");if(["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(s.toLowerCase()))throw new Error("Invalid request URL");if(s.length<8)throw new Error("Invalid request URL");if(e.length>1)return h.assertSafeId(s),s;throw new Error("Invalid request URL")},"getIdFromRequest"),Y=i(r=>"body"in r&&r.body&&typeof r.body.getReader=="function"?p.fromWeb(r.body):"body"in r&&r.body&&r.body instanceof Uint8Array?p.from(Buffer.from(r.body)):r instanceof p?r:p.from(new Uint8Array(0)),"getRequestStream");var j=Object.defineProperty,C=u((r,e)=>j(r,"name",{value:e,configurable:!0}),"r");const Z=C((r,e)=>{const t={};return e.forEach(s=>{t[s]=r[s]}),t},"pick");var k=Object.defineProperty,m=u((r,e)=>k(r,"name",{value:e,configurable:!0}),"d");class _ extends y{static{u(this,"E")}static{m(this,"BaseHandlerCore")}responseType="json";storage;mediaTransformer;disableTerminationForFinishedUploads;logger;get loggerInstance(){return this.logger}internalErrorResponses={};get errorResponses(){return this.internalErrorResponses}constructor({disableTerminationForFinishedUploads:e,mediaTransformer:t,storage:s}){super(),this.storage=s,this.mediaTransformer=t,this.disableTerminationForFinishedUploads=e,this.logger=this.storage?.logger,this.assembleErrors()}set errorResponses(e){this.assembleErrors(e)}assembleErrors=m((e={})=>{this.internalErrorResponses={...E,...this.internalErrorResponses,...this.storage.errorResponses,...e}},"assembleErrors");parseRangeHeader(e,t){if(!e?.startsWith("bytes="))return;const s=e.slice(6).split(",");if(s.length!==1)return;const a=s[0]?.trim();if(!a)return;const n=a.split("-");if(n.length!==2)return;const[o,l]=n;let d,f;if(o&&l)d=Number.parseInt(o,10),f=Number.parseInt(l,10);else if(o&&!l)d=Number.parseInt(o,10),f=t-1;else if(!o&&l){const g=Number.parseInt(l,10);d=Math.max(0,t-g),f=t-1}else return;if(!(Number.isNaN(d)||Number.isNaN(f)||d>=t||f>=t||d>f))return{end:f,start:d}}buildFileUrlFromString(e,t){const s=new URL(e,"http://localhost"),{pathname:a}=s,n=Object.fromEntries(s.searchParams.entries()),o=w({pathname:`${a}/${t.id}`,query:n});return`${this.storage.config.useRelativeLocation?"":T({url:e})}${o}.${R.getExtension(t.contentType)}`}negotiateContentTypeFromHeader(e,t){if(e)return v.getPreferredMediaType(e,t)}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw e}}export{_ as E,Z as T,c as a,Y as b,T as c,S as d,X as g,x as r,V as s,O as u};
|
package/dist/packem_shared/{base-handler-fetch-B0FWPun7.js → base-handler-fetch-BAjJyP84.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var E=Object.defineProperty;var u=(h,t)=>E(h,"name",{value:t,configurable:!0});import{H as m,h as b}from"./headers-DC2MEOrK.js";import{ERRORS as g,isUploadError as R}from"./ERRORS-vMSqlI69.js";import{E as v,T as O}from"./base-handler-core-
|
|
1
|
+
var E=Object.defineProperty;var u=(h,t)=>E(h,"name",{value:t,configurable:!0});import{H as m,h as b}from"./headers-DC2MEOrK.js";import{ERRORS as g,isUploadError as R}from"./ERRORS-vMSqlI69.js";import{E as v,T as O}from"./base-handler-core-ty4J6Ji6.js";import{i as H}from"./storage-CI88PmRw.js";import{waitForStorage as w}from"./waitForStorage-ChSBLhLc.js";var T=Object.defineProperty,x=u((h,t)=>T(h,"name",{value:t,configurable:!0}),"m");class z extends v{static{u(this,"O")}static{x(this,"BaseHandlerFetch")}static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(t){super(t),this.compose()}get handlers(){return this.registeredHandlers}async fetch(t){this.logger?.debug("[fetch request]: %s %s",t.method,t.url);const e=this.registeredHandlers.get(t.method||"GET");if(!e)return this.createErrorResponse({UploadErrorCode:g.METHOD_NOT_ALLOWED});try{await w(this.storage)}catch{return this.createErrorResponse({UploadErrorCode:g.STORAGE_ERROR})}try{const r=await e.call(this,t);return this.handleFetchResponse(t,r)}catch(r){const s=r instanceof Error?r:new Error(String(r)),o={...O(s,["name",...Object.getOwnPropertyNames(s)]),request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}};return this.listenerCount("error")>0&&this.emit("error",o),this.logger?.error("[fetch error]: %O",o),this.createErrorResponse(s)}}async handleFetchResponse(t,e){if(t.method==="HEAD"||t.method==="OPTIONS"){const{headers:n,statusCode:d}=e;return new Response(void 0,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}if(t.method==="GET"){const{headers:n,statusCode:d}=e;let c="";return e.content!==void 0?c=new Uint8Array(e.content):typeof e=="object"&&"data"in e&&(c=JSON.stringify(e.data)),new Response(c,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}const{headers:r,statusCode:s,...o}=e;if(o.status!==void 0&&this.listenerCount(o.status)>0&&this.emit(o.status,{...o,request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}}),o.status==="completed"){const n=e;n.headers===void 0&&(n.headers={}),n.statusCode===void 0&&(n.statusCode=200);try{await this.storage.onComplete(o,n)}catch(p){throw this.logger?.error("[onComplete error]: %O",p),p}const{headers:d,statusCode:c,...f}=n,{content:j,stream:S,...C}=f;return this.createResponse({body:C,headers:d||r,statusCode:c||s||200})}const y={...r,...e.headers},a=this.convertHeaders({...y,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control",...o.hash===void 0?{}:{[`X-Range-${o.hash?.algorithm.toUpperCase()}`]:o.hash?.value}}),l=e.headers||{};l.Location&&!a.location&&!a.Location?a.location=String(l.Location):l.location&&!a.location&&!a.Location?a.location=String(l.location):r.Location&&!a.location&&!a.Location?a.location=String(r.Location):r.location&&!a.location&&!a.Location&&(a.location=String(r.location));let i;return s>=200&&s<300&&(i=Object.keys(o).length>0?{...o}:{},"content"in i&&delete i.content,"stream"in i&&delete i.stream,Object.keys(i).length===0&&(i={})),this.createResponse({body:i,headers:a,statusCode:s||200})}convertHeaders(t){const e={};for(const[r,s]of Object.entries(t))e[r]=Array.isArray(s)?s.join(", "):String(s);return e}createResponse(t){const{body:e,headers:r={},statusCode:s}=t;let o;return s===204?o=null:typeof e=="string"?o=e:e instanceof Buffer?o=new Uint8Array(e):e&&typeof e=="object"?(o=JSON.stringify(e),r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))):e===void 0&&s!==void 0&&s>=200&&s<300&&(o="{}",r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))),new Response(o,{headers:this.convertHeaders(r),status:s})}async createErrorResponse(t){let e;R(t)?e=this.internalErrorResponses[t.UploadErrorCode]:!H(t)&&!b.isHttpError(t)?e=this.storage.normalizeError(t):e={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(e);let r;return e.body?typeof e.body=="object"&&e.body!==null?r={body:e.body,headers:e.headers,statusCode:e.statusCode}:r={body:{error:{code:e.code||e.name||"Error",message:e.body||e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500}:r={body:{error:{code:e.code||e.name||"Error",message:e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500},this.createResponse(r)}buildFileUrl(t,e){return this.buildFileUrlFromString(t.url,e)}negotiateContentType(t,e){return super.negotiateContentTypeFromHeader(t.headers.get("accept")||void 0,e)}}export{z as O};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var M=Object.defineProperty;var C=(i,e)=>M(i,"name",{value:e,configurable:!0});import{paginate as P}from"@visulima/pagination";import{H as T,h as z,n as y}from"./headers-DC2MEOrK.js";import O from"mime";import{isUploadError as $,ERRORS as m}from"./ERRORS-vMSqlI69.js";import{match as k}from"path-to-regexp";import{T as S,E as q,s as A,d as U,u as x}from"./base-handler-core-OdTz4-Pm.js";import{i as D}from"./storage-z0o24zmZ.js";import{waitForStorage as _}from"./waitForStorage-ChSBLhLc.js";import{PassThrough as I}from"node:stream";import{e as H}from"./response-builder-Wdo_fvcF.js";var X=Object.defineProperty,G=C((i,e)=>X(i,"name",{value:e,configurable:!0}),"n");const W=k(["/:uuid","/*path/:uuid.:ext/:metadata","/*path/:uuid/:metadata","/*path/:uuid.:ext","/*path/:uuid"],{decode:decodeURIComponent}),L=G(i=>{const e=W(i);if(!e)return;const{params:t}=e;if(!t.uuid)return;const r={uuid:t.uuid};return t.metadata!==void 0&&(r.metadata=t.metadata),t.path!==void 0&&(r.path=t.path),t.ext!==void 0&&(r.ext=t.ext),{params:r,path:e.path}},"filePathUrlMatcher");var B=Object.defineProperty,v=C((i,e)=>B(i,"name",{value:e,configurable:!0}),"a");const J=v((i,e,t)=>{let r=0,a=0;const o=t-e+1;return new I({highWaterMark:Math.min(64*1024,o),transform(n,h,s){const l=n.length,d=r,p=d+l-1;if(r+=l,p<e){s();return}if(d>t){this.end(),s();return}const u=Math.max(0,e-d),f=Math.min(l,t-d+1);if(u<f){const b=n.subarray(u,f);a+=b.length,this.push(b)||i.pause()}a>=o&&(this.end(),i.destroy()),s()}})},"createRangeLimitedStream"),V=v((i,e,t)=>{let r=!1;const a=v(()=>{r||(r=!0,i.destroy())},"cleanup");e.on("drain",()=>{i.resume()}),e.on("close",a),e.on("finish",a),e.on("error",a),i.on("end",()=>{e.end()}),i.on("error",async o=>{r||(await t(e,o),a())}),i.on("data",o=>{e.write(o)||i.pause()}),typeof e.listeners=="function"&&e.listeners("close")?.length===0&&e.on("close",a)},"pipeWithBackpressure");v((i,e,t={})=>({headers:t,size:e,stream:i}),"createStreamResponse");var K=Object.defineProperty,w=C((i,e)=>K(i,"name",{value:e,configurable:!0}),"u");const Q=w((i,e,t)=>{const{headers:r,statusCode:a}=i;e(t,{headers:r,statusCode:a})},"handleHeadOptionsRequest"),Y=w((i,e,t,r,a,o,n)=>{e.body=i?.data===void 0?i:i.data;const{headers:h,statusCode:s}=i,l=i;if(l.stream)if(typeof r=="function")r();else{const d=n(e.headers.range,l.size||0);o(t,l.stream,{headers:h,range:d||void 0,size:l.size,statusCode:s})}else{let d="";i.content!==void 0?d=i.content:typeof i=="object"&&"data"in i&&(d=i.data),typeof r=="function"?r():a(t,{body:d,headers:h,statusCode:s})}},"handleGetRequest"),Z=w(async(i,e,t,r,a,o,n)=>{const{headers:h,statusCode:s,...l}=i;if(typeof r=="function")e._body=!0,e.body=l,r();else{const d=i,p=d.headers?{...d.headers}:{};d.headers===void 0&&(d.headers={}),d.statusCode===void 0&&(d.statusCode=200);try{const u=a.onComplete(l,d,e);u instanceof Promise&&await u}catch(u){throw o?.error&&o.error("[onComplete error]: %O",u),u}Object.keys(d.headers||{}).length===0&&Object.keys(p).length>0?d.headers=p:d.headers&&Object.keys(p).length>0&&(d.headers={...p,...d.headers}),n(e,t,d)}},"handleCompletedUpload"),ee=w((i,e,t,r)=>{const{headers:a,statusCode:o,...n}=i,h=a||{},s=h["X-Chunked-Upload"]==="true"||h["x-chunked-upload"]==="true";let l;const d={...H(h),...a?H(a):{},...n.hash===void 0?{}:{[`X-Range-${n.hash?.algorithm.toUpperCase()}`]:String(n.hash?.value)}};s&&(l=JSON.stringify(n),!d["Content-Type"]&&!d["content-type"]&&(d["Content-Type"]="application/json; charset=utf-8")),e.method==="HEAD"&&(l=""),r(t,{body:l,headers:d,statusCode:o||200})},"handlePartialUpload"),te=w(async(i,e,t,r,a,o,n)=>{const h=i instanceof Error?i:new Error(String(i)),s={...S(h,["name",...Object.getOwnPropertyNames(h)]),request:S(e,["headers","method","url"])};r("error")>0&&t("error",s),a?.error&&a.error("[error]: %O",s),await o(n,h)},"handleUploadError");var re=Object.defineProperty,R=C((i,e)=>re(i,"name",{value:e,configurable:!0}),"C");const g="Content-Type";class N extends q{static{C(this,"F")}static{R(this,"BaseHandlerNode")}static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(e){super(e),this.compose()}get handlers(){return this.registeredHandlers}handle=R(async(e,t)=>this.upload(e,t),"handle");upload=R(async(e,t,r)=>{e.on("error",o=>this.logger?.error("[request error]: %O",o)),this.logger?.debug("[request]: %s %s",e.method,e.url);const a=this.registeredHandlers.get(e.method);if(!a){await this.sendError(t,{UploadErrorCode:m.METHOD_NOT_ALLOWED});return}try{await _(this.storage)}catch{await this.sendError(t,{UploadErrorCode:m.STORAGE_ERROR});return}try{const o=await a.call(this,e,t);if(["HEAD","OPTIONS"].includes(e.method))Q(o,this.send.bind(this),t);else if(e.method==="GET"){const n=o;n&&Y(n,e,t,r,this.send.bind(this),this.sendStream.bind(this),this.parseRangeHeader.bind(this))}else{const{headers:n,statusCode:h,...s}=o;this.logger?.debug("[%s]: %s: %d/%d",s.status,s.name,s.bytesWritten,s.size),s.status!==void 0&&this.listenerCount(s.status)>0&&this.emit(s.status,{...s,request:S(e,["headers","method","url"])}),s.status==="completed"?await Z(o,e,t,r,this.storage,this.logger,(l,d,p)=>{this.finish(l,d,p)}):ee(o,e,t,(l,d)=>{this.send(l,{body:d.body,headers:d.headers,statusCode:d.statusCode})})}}catch(o){await te(o,e,this.emit.bind(this),this.listenerCount.bind(this),this.logger,this.sendError.bind(this),t)}},"upload");send(e,{body:t="",headers:r={},statusCode:a=200}){let o;const n={...r};if(typeof t=="string"){if(o=t,n[g]===void 0)n[g]=T.createContentType({mediaType:"text/plain"});else{const h=Array.isArray(n[g])?n[g].join(", "):String(n[g]);n[g]=T.ensureCharset(h)}n["Content-Length"]===void 0&&(n["Content-Length"]=Buffer.byteLength(t))}else t instanceof Buffer?o=t:(o=JSON.stringify(t),n[g]||(n[g]=T.createContentType({charset:"utf8",mediaType:"application/json"})));A(e,n),e.statusCode=a,e.end(o)}async sendError(e,t){let r;$(t)?r=this.internalErrorResponses[t.UploadErrorCode]:!D(t)&&!z.isHttpError(t)?r=this.storage.normalizeError(t):r={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(r);let a;r.body?typeof r.body=="object"&&r.body!==null?a={body:r.body,headers:r.headers,statusCode:r.statusCode}:a={body:{error:{code:r.code||r.name||"Error",message:r.body||r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500}:a={body:{error:{code:r.code||r.name||"Error",message:r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500},this.send(e,a)}sendStream(e,t,{headers:r={},range:a,size:o,statusCode:n=200}){A(e,r),e.statusCode=n;let h=t;a&&o?(e.statusCode=206,e.setHeader("Content-Range",`bytes ${a.start}-${a.end}/${o}`),e.setHeader("Content-Length",a.end-a.start+1),e.setHeader("Accept-Ranges","bytes"),h=J(t,a.start,a.end)):(o&&e.setHeader("Content-Length",o),e.setHeader("Accept-Ranges","bytes")),V(h,e,(s,l)=>this.sendError(s,l))}finish(e,t,r){const a="id"in r&&"headers"in r&&!("body"in r);let o,n,h;if(a){const s=r,l=s.headers||{},d=s.statusCode||200,{headers:p,statusCode:u,...f}=s;o=f,n={...l},h=d}else{const s=r;o=s.body,n=s.headers||{},h=s.statusCode||200}if(o&&typeof o=="object"&&o.content!==void 0){const{content:s,contentType:l}=o;o=s,n={...n,"Content-Type":l}}this.send(t,{body:o||r,headers:n,statusCode:h})}buildFileUrl(e,t){return this.buildFileUrlFromString(e.originalUrl||e.url,t)}negotiateContentType(e,t){return super.negotiateContentTypeFromHeader(e.headers.accept,t)}async options(e,t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||N.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(e,t){const r=L(U(e));if(r?.params.uuid){const{ext:a,metadata:o,uuid:n}=r.params,h=a?n.replace(new RegExp(String.raw`\.${a}$`),""):n;if(o==="metadata"&&U(e).endsWith("/metadata"))try{const s=await this.storage.getMeta(h);return{...s,content:JSON.stringify(s),headers:{"Content-Type":T.createContentType({charset:"utf8",mediaType:"application/json"}),...s.expiredAt===void 0?{}:{"X-Upload-Expires":s.expiredAt.toString()},...s.modifiedAt===void 0?{}:{"Last-Modified":s.modifiedAt.toString()}},statusCode:200}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File metadata not found"):s}if(!x.test(h))return this.list(e,t);try{const s=new URL(e.url||"","http://localhost"),l=Object.fromEntries(s.searchParams.entries());if(Object.keys(l).length>0&&this.mediaTransformer&&this.mediaTransformer)try{const c=await this.mediaTransformer.handle(h,l);return{content:c.buffer,headers:{"Content-Length":String(c.size),"Content-Type":`${c.mediaType}/${c.format}`,"X-Media-Type":c.mediaType,"X-Original-Format":c.originalFile?.contentType?.split("/")[1]||"","X-Transformed-Format":c.format,...c.originalFile?.expiredAt===void 0?{}:{"X-Upload-Expires":c.originalFile.expiredAt.toString()},...c.originalFile?.modifiedAt===void 0?{}:{"Last-Modified":c.originalFile.modifiedAt.toString()},...c.originalFile?.ETag===void 0?{}:{ETag:c.originalFile.ETag}},statusCode:200}}catch(c){if(c.name==="ValidationError")throw y(400,c.message);this.logger?.warn(`Media transformation failed: ${c.message}`)}const d=await this.storage.getMeta(h);if((e.headers.range||d.size&&d.size>1024*1024)&&this.storage.getStream)try{const c=await this.storage.getStream({id:h});let E=c.headers?.["Content-Type"]||d.contentType;return E.includes("image")&&typeof a=="string"&&(E=O.getType(a)||E),{headers:{...c.headers,"Accept-Ranges":"bytes","Content-Type":E},size:c.size,statusCode:200,stream:c.stream,...d,contentType:E}}catch(c){this.logger?.warn(`Streaming failed, falling back to buffer: ${c}`)}const p=await this.storage.get({id:h});let{contentType:u}=p;u.includes("image")&&typeof a=="string"&&(u=O.getType(a)||u);const{ETag:f,expiredAt:b,modifiedAt:F,size:j}=p;return{headers:{"Accept-Ranges":"bytes","Content-Length":String(j),"Content-Type":u,...b===void 0?{}:{"X-Upload-Expires":b.toString()},...F===void 0?{}:{"Last-Modified":F.toString()},...f===void 0?{}:{ETag:f}},statusCode:200,...p,contentType:u}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File not found"):s}}return this.list(e,t)}async list(e,t){const r=new URL(e.url||"","http://localhost"),a=r.searchParams.get("limit"),o=r.searchParams.get("page"),n=await this.storage.list(Number(a||1e3));return n.length===0?{data:[],headers:{},statusCode:200}:o!==void 0&&a!==void 0?{data:P(Number(o),Number(a),n.length,n),headers:{},statusCode:200}:{data:n,headers:{},statusCode:200}}async download(e,t){const r=L(U(e));if(!r?.params.uuid||!x.test(r.params.uuid))throw y(404,"File not found");const{ext:a,uuid:o}=r.params;try{const n=await this.storage.getMeta(o);if(!this.storage.getStream){await this.sendError(t,y(501,"Streaming download not supported"));return}const h=await this.storage.getStream({id:o});let s=h.headers?.["Content-Type"]||n.contentType;s.includes("image")&&typeof a=="string"&&(s=O.getType(a)||s);const l=this.parseRangeHeader(e.headers.range,h.size||0),d={...h.headers,"Accept-Ranges":"bytes","Content-Disposition":T.createContentDisposition({filename:n.originalName||o,type:"attachment"}),"Content-Type":s};this.sendStream(t,h.stream,{headers:d,range:l||void 0,size:h.size,statusCode:l?206:200})}catch(n){const h=n;if(h.UploadErrorCode===m.FILE_NOT_FOUND||h.UploadErrorCode===m.GONE){await this.sendError(t,y(404,"File not found"));return}await this.sendError(t,n)}}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw y(404,"File not found")}}export{N as F};
|
|
1
|
+
var M=Object.defineProperty;var C=(i,e)=>M(i,"name",{value:e,configurable:!0});import{paginate as P}from"@visulima/pagination";import{H as T,h as z,n as y}from"./headers-DC2MEOrK.js";import O from"mime";import{isUploadError as $,ERRORS as m}from"./ERRORS-vMSqlI69.js";import{match as k}from"path-to-regexp";import{T as S,E as q,s as A,d as U,u as x}from"./base-handler-core-ty4J6Ji6.js";import{i as D}from"./storage-CI88PmRw.js";import{waitForStorage as _}from"./waitForStorage-ChSBLhLc.js";import{PassThrough as I}from"node:stream";import{e as H}from"./response-builder-Wdo_fvcF.js";var X=Object.defineProperty,G=C((i,e)=>X(i,"name",{value:e,configurable:!0}),"n");const W=k(["/:uuid","/*path/:uuid.:ext/:metadata","/*path/:uuid/:metadata","/*path/:uuid.:ext","/*path/:uuid"],{decode:decodeURIComponent}),L=G(i=>{const e=W(i);if(!e)return;const{params:t}=e;if(!t.uuid)return;const r={uuid:t.uuid};return t.metadata!==void 0&&(r.metadata=t.metadata),t.path!==void 0&&(r.path=t.path),t.ext!==void 0&&(r.ext=t.ext),{params:r,path:e.path}},"filePathUrlMatcher");var B=Object.defineProperty,v=C((i,e)=>B(i,"name",{value:e,configurable:!0}),"a");const J=v((i,e,t)=>{let r=0,a=0;const o=t-e+1;return new I({highWaterMark:Math.min(64*1024,o),transform(n,h,s){const l=n.length,d=r,p=d+l-1;if(r+=l,p<e){s();return}if(d>t){this.end(),s();return}const u=Math.max(0,e-d),f=Math.min(l,t-d+1);if(u<f){const b=n.subarray(u,f);a+=b.length,this.push(b)||i.pause()}a>=o&&(this.end(),i.destroy()),s()}})},"createRangeLimitedStream"),V=v((i,e,t)=>{let r=!1;const a=v(()=>{r||(r=!0,i.destroy())},"cleanup");e.on("drain",()=>{i.resume()}),e.on("close",a),e.on("finish",a),e.on("error",a),i.on("end",()=>{e.end()}),i.on("error",async o=>{r||(await t(e,o),a())}),i.on("data",o=>{e.write(o)||i.pause()}),typeof e.listeners=="function"&&e.listeners("close")?.length===0&&e.on("close",a)},"pipeWithBackpressure");v((i,e,t={})=>({headers:t,size:e,stream:i}),"createStreamResponse");var K=Object.defineProperty,w=C((i,e)=>K(i,"name",{value:e,configurable:!0}),"u");const Q=w((i,e,t)=>{const{headers:r,statusCode:a}=i;e(t,{headers:r,statusCode:a})},"handleHeadOptionsRequest"),Y=w((i,e,t,r,a,o,n)=>{e.body=i?.data===void 0?i:i.data;const{headers:h,statusCode:s}=i,l=i;if(l.stream)if(typeof r=="function")r();else{const d=n(e.headers.range,l.size||0);o(t,l.stream,{headers:h,range:d||void 0,size:l.size,statusCode:s})}else{let d="";i.content!==void 0?d=i.content:typeof i=="object"&&"data"in i&&(d=i.data),typeof r=="function"?r():a(t,{body:d,headers:h,statusCode:s})}},"handleGetRequest"),Z=w(async(i,e,t,r,a,o,n)=>{const{headers:h,statusCode:s,...l}=i;if(typeof r=="function")e._body=!0,e.body=l,r();else{const d=i,p=d.headers?{...d.headers}:{};d.headers===void 0&&(d.headers={}),d.statusCode===void 0&&(d.statusCode=200);try{const u=a.onComplete(l,d,e);u instanceof Promise&&await u}catch(u){throw o?.error&&o.error("[onComplete error]: %O",u),u}Object.keys(d.headers||{}).length===0&&Object.keys(p).length>0?d.headers=p:d.headers&&Object.keys(p).length>0&&(d.headers={...p,...d.headers}),n(e,t,d)}},"handleCompletedUpload"),ee=w((i,e,t,r)=>{const{headers:a,statusCode:o,...n}=i,h=a||{},s=h["X-Chunked-Upload"]==="true"||h["x-chunked-upload"]==="true";let l;const d={...H(h),...a?H(a):{},...n.hash===void 0?{}:{[`X-Range-${n.hash?.algorithm.toUpperCase()}`]:String(n.hash?.value)}};s&&(l=JSON.stringify(n),!d["Content-Type"]&&!d["content-type"]&&(d["Content-Type"]="application/json; charset=utf-8")),e.method==="HEAD"&&(l=""),r(t,{body:l,headers:d,statusCode:o||200})},"handlePartialUpload"),te=w(async(i,e,t,r,a,o,n)=>{const h=i instanceof Error?i:new Error(String(i)),s={...S(h,["name",...Object.getOwnPropertyNames(h)]),request:S(e,["headers","method","url"])};r("error")>0&&t("error",s),a?.error&&a.error("[error]: %O",s),await o(n,h)},"handleUploadError");var re=Object.defineProperty,R=C((i,e)=>re(i,"name",{value:e,configurable:!0}),"C");const g="Content-Type";class N extends q{static{C(this,"F")}static{R(this,"BaseHandlerNode")}static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(e){super(e),this.compose()}get handlers(){return this.registeredHandlers}handle=R(async(e,t)=>this.upload(e,t),"handle");upload=R(async(e,t,r)=>{e.on("error",o=>this.logger?.error("[request error]: %O",o)),this.logger?.debug("[request]: %s %s",e.method,e.url);const a=this.registeredHandlers.get(e.method);if(!a){await this.sendError(t,{UploadErrorCode:m.METHOD_NOT_ALLOWED});return}try{await _(this.storage)}catch{await this.sendError(t,{UploadErrorCode:m.STORAGE_ERROR});return}try{const o=await a.call(this,e,t);if(["HEAD","OPTIONS"].includes(e.method))Q(o,this.send.bind(this),t);else if(e.method==="GET"){const n=o;n&&Y(n,e,t,r,this.send.bind(this),this.sendStream.bind(this),this.parseRangeHeader.bind(this))}else{const{headers:n,statusCode:h,...s}=o;this.logger?.debug("[%s]: %s: %d/%d",s.status,s.name,s.bytesWritten,s.size),s.status!==void 0&&this.listenerCount(s.status)>0&&this.emit(s.status,{...s,request:S(e,["headers","method","url"])}),s.status==="completed"?await Z(o,e,t,r,this.storage,this.logger,(l,d,p)=>{this.finish(l,d,p)}):ee(o,e,t,(l,d)=>{this.send(l,{body:d.body,headers:d.headers,statusCode:d.statusCode})})}}catch(o){await te(o,e,this.emit.bind(this),this.listenerCount.bind(this),this.logger,this.sendError.bind(this),t)}},"upload");send(e,{body:t="",headers:r={},statusCode:a=200}){let o;const n={...r};if(typeof t=="string"){if(o=t,n[g]===void 0)n[g]=T.createContentType({mediaType:"text/plain"});else{const h=Array.isArray(n[g])?n[g].join(", "):String(n[g]);n[g]=T.ensureCharset(h)}n["Content-Length"]===void 0&&(n["Content-Length"]=Buffer.byteLength(t))}else t instanceof Buffer?o=t:(o=JSON.stringify(t),n[g]||(n[g]=T.createContentType({charset:"utf8",mediaType:"application/json"})));A(e,n),e.statusCode=a,e.end(o)}async sendError(e,t){let r;$(t)?r=this.internalErrorResponses[t.UploadErrorCode]:!D(t)&&!z.isHttpError(t)?r=this.storage.normalizeError(t):r={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(r);let a;r.body?typeof r.body=="object"&&r.body!==null?a={body:r.body,headers:r.headers,statusCode:r.statusCode}:a={body:{error:{code:r.code||r.name||"Error",message:r.body||r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500}:a={body:{error:{code:r.code||r.name||"Error",message:r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500},this.send(e,a)}sendStream(e,t,{headers:r={},range:a,size:o,statusCode:n=200}){A(e,r),e.statusCode=n;let h=t;a&&o?(e.statusCode=206,e.setHeader("Content-Range",`bytes ${a.start}-${a.end}/${o}`),e.setHeader("Content-Length",a.end-a.start+1),e.setHeader("Accept-Ranges","bytes"),h=J(t,a.start,a.end)):(o&&e.setHeader("Content-Length",o),e.setHeader("Accept-Ranges","bytes")),V(h,e,(s,l)=>this.sendError(s,l))}finish(e,t,r){const a="id"in r&&"headers"in r&&!("body"in r);let o,n,h;if(a){const s=r,l=s.headers||{},d=s.statusCode||200,{headers:p,statusCode:u,...f}=s;o=f,n={...l},h=d}else{const s=r;o=s.body,n=s.headers||{},h=s.statusCode||200}if(o&&typeof o=="object"&&o.content!==void 0){const{content:s,contentType:l}=o;o=s,n={...n,"Content-Type":l}}this.send(t,{body:o||r,headers:n,statusCode:h})}buildFileUrl(e,t){return this.buildFileUrlFromString(e.originalUrl||e.url,t)}negotiateContentType(e,t){return super.negotiateContentTypeFromHeader(e.headers.accept,t)}async options(e,t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||N.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(e,t){const r=L(U(e));if(r?.params.uuid){const{ext:a,metadata:o,uuid:n}=r.params,h=a?n.replace(new RegExp(String.raw`\.${a}$`),""):n;if(o==="metadata"&&U(e).endsWith("/metadata"))try{const s=await this.storage.getMeta(h);return{...s,content:JSON.stringify(s),headers:{"Content-Type":T.createContentType({charset:"utf8",mediaType:"application/json"}),...s.expiredAt===void 0?{}:{"X-Upload-Expires":s.expiredAt.toString()},...s.modifiedAt===void 0?{}:{"Last-Modified":s.modifiedAt.toString()}},statusCode:200}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File metadata not found"):s}if(!x.test(h))return this.list(e,t);try{const s=new URL(e.url||"","http://localhost"),l=Object.fromEntries(s.searchParams.entries());if(Object.keys(l).length>0&&this.mediaTransformer&&this.mediaTransformer)try{const c=await this.mediaTransformer.handle(h,l);return{content:c.buffer,headers:{"Content-Length":String(c.size),"Content-Type":`${c.mediaType}/${c.format}`,"X-Media-Type":c.mediaType,"X-Original-Format":c.originalFile?.contentType?.split("/")[1]||"","X-Transformed-Format":c.format,...c.originalFile?.expiredAt===void 0?{}:{"X-Upload-Expires":c.originalFile.expiredAt.toString()},...c.originalFile?.modifiedAt===void 0?{}:{"Last-Modified":c.originalFile.modifiedAt.toString()},...c.originalFile?.ETag===void 0?{}:{ETag:c.originalFile.ETag}},statusCode:200}}catch(c){if(c.name==="ValidationError")throw y(400,c.message);this.logger?.warn(`Media transformation failed: ${c.message}`)}const d=await this.storage.getMeta(h);if((e.headers.range||d.size&&d.size>1024*1024)&&this.storage.getStream)try{const c=await this.storage.getStream({id:h});let E=c.headers?.["Content-Type"]||d.contentType;return E.includes("image")&&typeof a=="string"&&(E=O.getType(a)||E),{headers:{...c.headers,"Accept-Ranges":"bytes","Content-Type":E},size:c.size,statusCode:200,stream:c.stream,...d,contentType:E}}catch(c){this.logger?.warn(`Streaming failed, falling back to buffer: ${c}`)}const p=await this.storage.get({id:h});let{contentType:u}=p;u.includes("image")&&typeof a=="string"&&(u=O.getType(a)||u);const{ETag:f,expiredAt:b,modifiedAt:F,size:j}=p;return{headers:{"Accept-Ranges":"bytes","Content-Length":String(j),"Content-Type":u,...b===void 0?{}:{"X-Upload-Expires":b.toString()},...F===void 0?{}:{"Last-Modified":F.toString()},...f===void 0?{}:{ETag:f}},statusCode:200,...p,contentType:u}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File not found"):s}}return this.list(e,t)}async list(e,t){const r=new URL(e.url||"","http://localhost"),a=r.searchParams.get("limit"),o=r.searchParams.get("page"),n=await this.storage.list(Number(a||1e3));return n.length===0?{data:[],headers:{},statusCode:200}:o!==void 0&&a!==void 0?{data:P(Number(o),Number(a),n.length,n),headers:{},statusCode:200}:{data:n,headers:{},statusCode:200}}async download(e,t){const r=L(U(e));if(!r?.params.uuid||!x.test(r.params.uuid))throw y(404,"File not found");const{ext:a,uuid:o}=r.params;try{const n=await this.storage.getMeta(o);if(!this.storage.getStream){await this.sendError(t,y(501,"Streaming download not supported"));return}const h=await this.storage.getStream({id:o});let s=h.headers?.["Content-Type"]||n.contentType;s.includes("image")&&typeof a=="string"&&(s=O.getType(a)||s);const l=this.parseRangeHeader(e.headers.range,h.size||0),d={...h.headers,"Accept-Ranges":"bytes","Content-Disposition":T.createContentDisposition({filename:n.originalName||o,type:"attachment"}),"Content-Type":s};this.sendStream(t,h.stream,{headers:d,range:l||void 0,size:h.size,statusCode:l?206:200})}catch(n){const h=n;if(h.UploadErrorCode===m.FILE_NOT_FOUND||h.UploadErrorCode===m.GONE){await this.sendError(t,y(404,"File not found"));return}await this.sendError(t,n)}}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw y(404,"File not found")}}export{N as F};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"node:stream";import"node:timers";import"node:util";import{B as u,d as F,a as g}from"./storage-
|
|
1
|
+
import"node:stream";import"node:timers";import"node:util";import{B as u,d as F,a as g}from"./storage-CI88PmRw.js";import"./path-D7rMc9nq-B718mbm6.js";import"type-is";import"./NoOpMetrics-Dky06sf1.js";import"./cache-qV_5Umeq.js";import"./ERRORS-vMSqlI69.js";import"./isRetryableError-CBZ65V6T.js";import"./is-expired-1JuZjDtb.js";export{u as BaseStorage,F as defaultCloudStorageFileNameValidation,g as defaultFilesystemFileNameValidation};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var F=Object.defineProperty;var h=(r,o)=>F(r,"name",{value:o,configurable:!0});import{PassThrough as w,Transform as P}from"node:stream";import{fileTypeFromBuffer as f}from"file-type";var g=Object.defineProperty,d=h((r,o)=>g(r,"name",{value:o,configurable:!0}),"u");const S=d(async r=>{try{return await f(r)}catch{return}},"detectFileTypeFromBuffer"),j=d(async(r,o)=>{const p=o?.sampleSize??4100;let m;const s=[];let u=0,a=!1,i;const n=new w({highWaterMark:0}),c=new P({objectMode:!1,transform(e,t,y){if(!a&&(s.push(e),u+=e.length,u>=p)){a=!0;const T=Buffer.concat(s);i=f(T).then(l=>(m=l,l)).catch(()=>{})}y(void 0,e)},flush(e){!a&&s.length>0&&(a=!0,i=f(Buffer.concat(s)).then(t=>(m=t,t)).catch(()=>{})),e()}});return r.pipe(c).pipe(n),r.on("error",e=>{c.destroy(e),n.destroy(e)}),c.on("error",e=>{n.destroyed||n.destroy(e)}),await Promise.race([new Promise(e=>{if(a){e();return}const t=setTimeout(e,10);c.once("data",()=>{clearTimeout(t),e()}),c.once("end",()=>{clearTimeout(t),e()})}),new Promise(e=>{setTimeout(e,10)})]),i&&await Promise.race([i.then(()=>{}),new Promise(e=>{setTimeout(e,150)})]).catch(()=>{}),{fileType:m,stream:n}},"detectFileTypeFromStream");export{S as a,j as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var mt=Object.defineProperty;var d=(e,t)=>mt(e,"name",{value:t,configurable:!0});import{createReadStream as ht,createWriteStream as dt}from"node:fs";import{truncate as yt,stat as U,copyFile as B}from"node:fs/promises";import{Transform as X,PassThrough as ft,pipeline as gt}from"node:stream";import{f as C,l as pt,w as q,U as v,_ as wt,i as bt,v as vt,E as Et,y as V}from"./local-meta-storage-tayO1ARY.js";import{createRequire as _}from"node:module";import{K as b,C as P,M as Y,L as $t,Q as St,O as Ot}from"./path-D7rMc9nq-B718mbm6.js";import{S as Tt}from"./index-B4ETk0Lu.js";import{d as Ft}from"./detect-file-type-DRWGvQW4.js";import{throwErrorCode as w,ERRORS as y,isUploadError as kt}from"./ERRORS-vMSqlI69.js";import{createHash as Nt}from"node:crypto";import{B as Pt,a as Dt,t as It}from"./storage-CI88PmRw.js";import Mt from"./File-BhfUgJjs.js";import{o as Q}from"./get-file-status-DLS18Zvd.js";import{u as _t}from"./update-size-DANV7aa2.js";import{r as Rt}from"./part-match-D_NwyoF3.js";import{o as xt}from"./has-content-Bx2p8Okx.js";var Lt=Object.defineProperty,jt=d((e,t)=>Lt(e,"name",{value:t,configurable:!0}),"i$4"),At=Object.defineProperty,G=jt((e,t)=>At(e,"name",{value:t,configurable:!0}),"t");const Ct=_(import.meta.url),F=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,zt=G(e=>{if(typeof F<"u"&&F.versions&&F.versions.node){const[t,r]=F.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return F.getBuiltinModule(e)}return Ct(e)},"__cjs_getBuiltinModule"),{lstat:Wt,writeFile:Ut}=zt("node:fs/promises");var Bt=Object.defineProperty,Vt=G((e,t)=>Bt(e,"name",{value:t,configurable:!0}),"o");const A=Vt(async e=>{C(e);try{const t=await Wt(e);if(!t.isFile())throw new Error(`Ensure path exists, expected 'file', got '${String(pt(t))}'`)}catch(t){if(t.code==="ENOENT"){await q(b(v(e))),await Ut(e,new Uint8Array);return}throw t}},"ensureFile");var Qt=Object.defineProperty,J=d((e,t)=>Qt(e,"name",{value:t,configurable:!0}),"t$1"),Ht=Object.defineProperty,Z=J((e,t)=>Ht(e,"name",{value:t,configurable:!0}),"t"),Kt=Object.defineProperty,Xt=Z((e,t)=>Kt(e,"name",{value:t,configurable:!0}),"t");let H=class extends Error{static{d(this,"l")}static{J(this,"c")}static{Z(this,"i")}static{Xt(this,"WalkError")}root;constructor(t,r){super(`${t instanceof Error?t.message:String(t)} for path "${r}"`),this.cause=t,this.root=r}get name(){return"WalkError"}set name(t){throw new Error("Cannot overwrite name of WalkError")}};var qt=Object.defineProperty,Yt=d((e,t)=>qt(e,"name",{value:t,configurable:!0}),"l$1"),Gt=Object.defineProperty,tt=Yt((e,t)=>Gt(e,"name",{value:t,configurable:!0}),"c"),Jt=Object.defineProperty,Zt=tt((e,t)=>Jt(e,"name",{value:t,configurable:!0}),"g");const K=Zt(e=>{const t=e.replace(/[$()+\\^]/g,String.raw`\$&`).replace(/\.\*/g,".([^/]*)").replace(/\*\*/g,"(.*)").replace(/(?<!\.)\*(?!\*)/g,"([^/]*)").replace(/\?/g,"[^/]").replace(/\.(?!\*)/g,String.raw`\.`).replace(/\{/g,"(").replace(/\}/g,")").replace(/,/g,"|").replace(/\[!(.*?)\]/g,"[^$1]");try{return new RegExp(`^${t}$`)}catch(r){throw new Error(`Invalid glob pattern: ${e}`,{cause:r})}},"globToRegExp");var te=Object.defineProperty,ee=tt((e,t)=>te(e,"name",{value:t,configurable:!0}),"t");const I=ee((e,t,r,i)=>{if(Array.isArray(t)&&t.length>0&&!t.some(a=>e.endsWith(a)))return!1;const o=e.includes("\\")?e.replaceAll("\\","/"):e;return r&&!r.some(a=>a.test(o))?!1:!i?.some(a=>a.test(o))},"walkInclude");var re=Object.defineProperty,et=d((e,t)=>re(e,"name",{value:t,configurable:!0}),"f$1"),ie=Object.defineProperty,z=et((e,t)=>ie(e,"name",{value:t,configurable:!0}),"y");const ae=_(import.meta.url),k=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,se=z(e=>{if(typeof k<"u"&&k.versions&&k.versions.node){const[t,r]=k.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return k.getBuiltinModule(e)}return ae(e)},"__cjs_getBuiltinModule"),{readdir:ne,realpath:oe,stat:ce}=se("node:fs/promises");var le=Object.defineProperty,p=z((e,t)=>le(e,"name",{value:t,configurable:!0}),"r");const ue=p(async e=>{const t=$t(e),r=St(t),i=await ce(t);return{isDirectory:p(()=>i.isDirectory(),"isDirectory"),isFile:p(()=>i.isFile(),"isFile"),isSymbolicLink:p(()=>i.isSymbolicLink(),"isSymbolicLink"),name:r,path:t}},"_createWalkEntry");async function*D(e,{extensions:t,followSymlinks:r=!1,includeDirs:i=!0,includeFiles:o=!0,includeSymlinks:a=!0,match:s,maxDepth:u=Number.POSITIVE_INFINITY,skip:l}={}){if(C(e),u<0)return;const m=s?s.map(c=>typeof c=="string"?K(c):c):void 0,h=l?l.map(c=>typeof c=="string"?K(c):c):void 0;if(e=P(v(e)),i&&I(e,t,m,h)&&(yield await ue(e)),!(u<1||!I(e,void 0,void 0,h)))try{const c=await ne(e,{withFileTypes:!0});for(const n of c){let g=Y(e,n.name);if(n.isSymbolicLink())if(r)g=await oe(g);else if(a&&I(g,t,m,h)){yield{isDirectory:p(()=>n.isDirectory(),"isDirectory"),isFile:p(()=>n.isFile(),"isFile"),isSymbolicLink:p(()=>n.isSymbolicLink(),"isSymbolicLink"),name:n.name,path:g};continue}else continue;n.isDirectory()?yield*D(g,{extensions:t,followSymlinks:r,includeDirs:i,includeFiles:o,includeSymlinks:a,match:m,maxDepth:u-1,skip:h}):n.isFile()&&o&&I(g,t,m,h)&&(yield{isDirectory:p(()=>n.isDirectory(),"isDirectory"),isFile:p(()=>n.isFile(),"isFile"),isSymbolicLink:p(()=>n.isSymbolicLink(),"isSymbolicLink"),name:n.name,path:g})}}catch(c){throw c instanceof H?c:new H(c,e)}}d(D,"p$2");et(D,"D");z(D,"g");p(D,"walk");var me=Object.defineProperty,rt=d((e,t)=>me(e,"name",{value:t,configurable:!0}),"t"),he=Object.defineProperty,W=rt((e,t)=>he(e,"name",{value:t,configurable:!0}),"t");const de=_(import.meta.url),N=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,ye=W(e=>{if(typeof N<"u"&&N.versions&&N.versions.node){const[t,r]=N.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return N.getBuiltinModule(e)}return de(e)},"__cjs_getBuiltinModule"),{accessSync:fe}=ye("node:fs");var ge=Object.defineProperty,pe=W((e,t)=>ge(e,"name",{value:t,configurable:!0}),"o");function R(e,t=wt){C(e),e=v(e);try{return fe(e,t),!0}catch{return!1}}d(R,"i$1");rt(R,"d");W(R,"m");pe(R,"isAccessibleSync");var we=Object.defineProperty,it=d((e,t)=>we(e,"name",{value:t,configurable:!0}),"v"),be=Object.defineProperty,T=it((e,t)=>be(e,"name",{value:t,configurable:!0}),"i");const ve=_(import.meta.url),S=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,at=T(e=>{if(typeof S<"u"&&S.versions&&S.versions.node){const[t,r]=S.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return S.getBuiltinModule(e)}return ve(e)},"__cjs_getBuiltinModule"),{cwd:x}=S,{mkdir:Ee,rename:$e,copyFile:Se,unlink:Oe}=at("node:fs/promises"),{mkdirSync:Te,renameSync:Fe,copyFileSync:ke,unlinkSync:Ne}=at("node:fs");var Pe=Object.defineProperty,st=T((e,t)=>Pe(e,"name",{value:t,configurable:!0}),"o");class De extends Error{static{d(this,"V")}static{it(this,"O")}static{T(this,"a")}static{st(this,"SameDirectoryError")}constructor(t,r){super(`Source directory "${b(t)}" does not match destination directory "${b(r)}"`),this.name="SameDirectoryError"}}const nt=st((e,t)=>{if(!e||!t)throw new Error("Source and destination paths must not be empty");if(b(e)!==b(t))throw new De(e,t)},"validateSameDirectory");var Ie=Object.defineProperty,Me=T((e,t)=>Ie(e,"name",{value:t,configurable:!0}),"m$1");const ot=Me(async(e,t,{cwd:r,directoryMode:i,overwrite:o,validateDirectory:a})=>{if(r&&(e=P(r,e),t=P(r,t)),a&&nt(e,t),!o&&await bt(t))throw new Error(`The destination file exists: ${t}`);await Ee(b(t),{mode:i,recursive:!0});try{await $e(e,t)}catch(s){if(s.code==="EXDEV")await Se(e,t),await Oe(e);else throw s}},"internalMoveFile");var _e=Object.defineProperty,Re=T((e,t)=>_e(e,"name",{value:t,configurable:!0}),"m");const ct=Re((e,t,{cwd:r,directoryMode:i,overwrite:o,validateDirectory:a})=>{if(r&&(e=P(r,e),t=P(r,t)),a&&nt(e,t),!o&&R(t))throw new Error(`The destination file exists: ${t}`);Te(b(t),{mode:i,recursive:!0});try{Fe(e,t)}catch(s){if(s.code==="EXDEV")ke(e,t),Ne(e);else throw s}},"internalMoveFileSync");var xe=Object.defineProperty,L=T((e,t)=>xe(e,"name",{value:t,configurable:!0}),"i");const Le=L(async(e,t,r={})=>{const i={overwrite:!0,validateDirectory:!1,...r,cwd:r.cwd?v(r.cwd):x()};await ot(e,t,i)},"move");L((e,t,r)=>{const i={overwrite:!0,validateDirectory:!1,...r};i.cwd=i.cwd?v(i.cwd):x(),ct(e,t,i)},"moveSync");L(async(e,t,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?v(i.cwd):x(),await ot(e,t,i)},"rename");L((e,t,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?v(i.cwd):x(),ct(e,t,i)},"renameSync");var je=Object.defineProperty,lt=d((e,t)=>je(e,"name",{value:t,configurable:!0}),"r");class Ae extends X{static{d(this,"StreamChecksum")}constructor(t,r,i="base64"){super(),this.checksum=t,this.algorithm=r,this.encoding=i,this.hash=Nt(r)}checksum;algorithm;encoding;static{lt(this,"StreamChecksum")}length=0;digest="";hash;get calculatedDigest(){return this.digest}_transform(t,r,i){this.push(t),this.hash.update(t),this.length+=t.length,i()}_flush(t){this.digest=this.hash.digest(this.encoding),this.checksum&&this.checksum!==this.digest?t(new Error("Checksum mismatch")):t()}}const Ce=lt((e,t,r="base64")=>t?new Ae(e,t,r):new ft,"streamChecksum");var ze=Object.defineProperty,We=d((e,t)=>ze(e,"name",{value:t,configurable:!0}),"o");class Ue extends X{static{d(this,"m")}constructor(t=Number.POSITIVE_INFINITY){super(),this.limit=t}limit;static{We(this,"StreamLength")}length=0;_transform(t,r,i){const o=this.length+t.length;this.limit>=o?(this.push(t),this.length=o,i()):i(new Error("Stream length limit exceeded"))}}var Be=Object.defineProperty,M=d((e,t)=>Be(e,"name",{value:t,configurable:!0}),"F");class O extends Pt{static name="disk";checksumTypes=["md5","sha1"];supportsRange=!0;get raw(){return{directory:this.directory}}directory;meta;constructor(t){const r={...t,fileNameValidation:t.fileNameValidation??Dt};if(super(r),this.directory=r.directory,r.metaStorage)this.meta=r.metaStorage;else{const i={...r,...r.metaStorageConfig,logger:this.logger};this.meta=new vt(i)}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(i=>{this.logger?.error("Storage access check failed: %O",i)})}normalizeError(t){return super.normalizeError(t)}async create(t){return this.instrumentOperation("create",async()=>{const r={...t};if(t.ttl){const a=typeof t.ttl=="string"?It(t.ttl):t.ttl;a!==void 0&&(r.expiredAt=Date.now()+a)}r.size!==void 0&&Number(r.size)<0&&w(y.REQUEST_ENTITY_TOO_LARGE,"Request entity too large");const i=new Mt(r);try{const a=await this.getMeta(i.id);if(a.status==="completed")return a}catch{}i.name=this.namingFunction(i),(i.size===void 0||Number.isNaN(i.size))&&(i.size===void 0||(i.size=this.maxUploadSize)),await this.validate(i);const o=this.getFilePath(i.name);try{await A(o),i.bytesWritten=0}catch(a){const s=this.normalizeError(a instanceof Error?a:new Error(String(a)));await this.onError(s),w(y.FILE_ERROR,s.message)}return i.status=Q(i),await this.saveMeta(i),await this.onCreate(i),i})}async write(t){return this.instrumentOperation("write",async()=>{let r;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?r=t:(r=await this.getMeta(t.id),await this.checkIfExpired(r)),r.status==="completed")return r;if(t.size!==void 0&&_t(r,t.size),!Rt(t,r))return w(y.FILE_CONFLICT);const i=this.getFilePath(r.name),o=await this.lock(i);try{const a=t.start||0;if(await A(i),r.bytesWritten===0&&(r.bytesWritten=a),xt(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return w(y.UNSUPPORTED_CHECKSUM_ALGORITHM);if((t.start===0||t.start===void 0)&&(r.bytesWritten===0||Number.isNaN(r.bytesWritten))&&(!r.contentType||r.contentType==="application/octet-stream"))try{const{fileType:c,stream:n}=await Ft(t.body);c?.mime&&(r.contentType=c.mime),t.body=n}catch{}const s=t.signal,u={...r,...t,body:t.body};s&&(u.signal=s);const[l,m]=await this.lazyWrite(u);if(m)return await yt(i,r.bytesWritten),w(m);const h=a+(t.contentLength||0);r.bytesWritten=Math.max(r.bytesWritten||0,h),r.bytesWritten=Math.max(r.bytesWritten||0,l),r.status=Q(r),await this.saveMeta(r)}else await A(i),r.bytesWritten=0;return r}catch(a){if(kt(a))throw a;const s=this.normalizeError(a instanceof Error?a:new Error(String(a)));return await this.onError(s),w(y.FILE_ERROR,(typeof s.message=="string"?s.message:String(a))||String(a))}finally{await this.unlock(i,o)}})}async get({id:t},r){return this.instrumentOperation("get",async()=>{const i=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:o,contentType:a,expiredAt:s,metadata:u,modifiedAt:l,name:m,originalName:h,size:c}=i;let n;try{n=await Et(this.getFilePath(m),{buffer:!0})}catch(f){const $=f;if($.code==="ENOENT"||$.code==="EPERM"){const j=this.normalizeError(f instanceof Error?f:new Error($.message||String(f)));return await this.onError(j),w(y.FILE_NOT_FOUND,(typeof j.message=="string"?j.message:String(f))||String(f))}const ut=this.normalizeError(f instanceof Error?f:new Error(String(f)));throw await this.onError(ut),f}const g=Tt(n),E=r?.range;if(E){const f=Math.max(0,E.start),$=E.end===void 0?n.length-1:Math.min(n.length-1,E.end);if(f>$||f>=n.length)return w(y.BAD_REQUEST,`Invalid range ${f}-${E.end??""}`);n=n.subarray(f,$+1)}return{content:n,contentType:a,ETag:g,expiredAt:s,id:t,metadata:u,modifiedAt:l,name:m,originalName:h,size:E?n.length:c||o}})}async exists({id:t}){return this.instrumentOperation("exists",async()=>{try{const r=await this.getMeta(t),i=this.getFilePath(r.name);return await U(i),!0}catch{return!1}})}async getStream({id:t}){return this.instrumentOperation("getStream",async()=>{try{const r=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:i,contentType:o,expiredAt:a,modifiedAt:s,name:u,size:l}=r,m=ht(this.getFilePath(u));return{headers:{"Content-Length":String(l||i),"Content-Type":o,...a&&{"X-Upload-Expires":a.toString()},...s&&{"Last-Modified":s.toString()}},size:l||i,stream:m}}catch(r){const i=this.normalizeError(r instanceof Error?r:new Error(String(r)));throw await this.onError(i),w(y.FILE_NOT_FOUND,(typeof i.message=="string"?i.message:String(r))||String(r))}})}async delete({id:t}){return this.instrumentOperation("delete",async()=>{const r=await this.getMeta(t);await V(this.getFilePath(r.name)),await this.deleteMeta(t);const i={...r,status:"deleted"};return await this.onDelete(i),i})}async copy(t,r){return this.instrumentOperation("copy",async()=>{O.assertSafeId(t),O.assertSafeId(r);const i=await this.getMeta(t);return await B(this.getFilePath(i.name),this.getFilePath(r)),{...i,name:r}})}async move(t,r){return this.instrumentOperation("move",async()=>{O.assertSafeId(t),O.assertSafeId(r);const i=await this.getMeta(t),o=this.getFilePath(i.name),a=this.getFilePath(r);try{await Le(o,a)}catch(s){if(s?.code==="EXDEV")await B(o,a),await V(o);else{const u=this.normalizeError(s instanceof Error?s:new Error(String(s)));throw await this.onError(u),s}}return{...i,id:i.id,name:r}})}async list(){return this.instrumentOperation("list",async()=>{const t={followSymlinks:!1,includeDirs:!1,includeFiles:!0,skip:["*.META$"]},r=[],{directory:i}=this,o=M(s=>s.replaceAll("\\","/"),"toPosix"),a=o(i);for await(const s of D(i,t)){const{suffix:u}=this.meta,{path:l}=s;if(!l.includes(u)){const{birthtime:m,ctime:h,mtime:c}=await U(l),n=o(l),g=n.startsWith(a)?n.slice(a.length):n;r.push({createdAt:m||h,id:g,modifiedAt:c})}}return r})}getFilePath(t){return O.assertSafeId(t),Ot(t)&&w(y.INVALID_FILE_NAME,`Invalid file id: "${t}"`),Y(this.directory,t)}lazyWrite(t){return new Promise((r,i)=>{const o=dt(this.getFilePath(t.name),{flags:"r+",start:t.start}),a=new Ue(t.contentLength||t.size-t.start),s=Ce(t.checksum,t.checksumAlgorithm),u=!t.checksum,{signal:l}=t,m=M(()=>{o.close(),a.destroy(),s.destroy()},"cleanupStreams"),h=M(n=>{m(),r([Number.NaN,n])},"failWithCode");if(a.on("error",()=>{h(y.FILE_CONFLICT)}),s.on("error",()=>{h(y.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{h(u?void 0:y.REQUEST_ABORTED)}),t.body.on("error",n=>{m(),i(n)}),l?.aborted){h(u?void 0:y.REQUEST_ABORTED);return}let c;l&&(c=M(()=>{m(),o.destroy(),a.destroy(),s.destroy(),t.body.destroy(),r([Number.NaN,u?void 0:y.REQUEST_ABORTED])},"onAbort"),l.addEventListener("abort",c,{once:!0})),gt(t.body,a,s,o,n=>{if(l&&c&&l.removeEventListener("abort",c),n){if(m(),l?.aborted){r([Number.NaN,u?void 0:y.REQUEST_ABORTED]);return}r([Number.NaN,y.FILE_ERROR]);return}r([t.start+o.bytesWritten])})})}async accessCheck(){await q(this.directory)}}export{Ue as m,O as p,Ce as s,A as y};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as File, M as MetaStorage, D as DiskStorageOptions, H as HttpError,
|
|
1
|
+
import { F as File, M as MetaStorage, D as DiskStorageOptions, H as HttpError, b as FileInit, d as FilePart, e as FileQuery, O as OperationOptions, a as FileReturn, E as ERRORS, B as BaseStorage, h as DiskStorageWithChecksumOptions } from "./storage.d-C6HtvSoY.js";
|
|
2
2
|
import { Readable } from 'node:stream';
|
|
3
3
|
/**
|
|
4
4
|
* Local disk-based storage implementation.
|