main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

View File

@@ -0,0 +1,114 @@
import { StorageError } from '../lib/errors';
import { Fetch } from '../lib/fetch';
import { Bucket } from '../lib/types';
export default class StorageBucketApi {
protected url: string;
protected headers: {
[key: string]: string;
};
protected fetch: Fetch;
constructor(url: string, headers?: {
[key: string]: string;
}, fetch?: Fetch);
/**
* Retrieves the details of all Storage buckets within an existing project.
*/
listBuckets(): Promise<{
data: Bucket[];
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Retrieves the details of an existing Storage bucket.
*
* @param id The unique identifier of the bucket you would like to retrieve.
*/
getBucket(id: string): Promise<{
data: Bucket;
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Creates a new Storage bucket
*
* @param id A unique identifier for the bucket you are creating.
* @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private.
* @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.
* The global file size limit takes precedence over this value.
* The default value is null, which doesn't set a per bucket file size limit.
* @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.
* The default value is null, which allows files with all mime types to be uploaded.
* Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.
* @returns newly created bucket id
*/
createBucket(id: string, options?: {
public: boolean;
fileSizeLimit?: number | string | null;
allowedMimeTypes?: string[] | null;
}): Promise<{
data: Pick<Bucket, 'name'>;
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Updates a Storage bucket
*
* @param id A unique identifier for the bucket you are updating.
* @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations.
* @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.
* The global file size limit takes precedence over this value.
* The default value is null, which doesn't set a per bucket file size limit.
* @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.
* The default value is null, which allows files with all mime types to be uploaded.
* Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.
*/
updateBucket(id: string, options: {
public: boolean;
fileSizeLimit?: number | string | null;
allowedMimeTypes?: string[] | null;
}): Promise<{
data: {
message: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Removes all objects inside a single bucket.
*
* @param id The unique identifier of the bucket you would like to empty.
*/
emptyBucket(id: string): Promise<{
data: {
message: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Deletes an existing bucket. A bucket can't be deleted with existing objects inside it.
* You must first `empty()` the bucket.
*
* @param id The unique identifier of the bucket you would like to delete.
*/
deleteBucket(id: string): Promise<{
data: {
message: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
}
//# sourceMappingURL=StorageBucketApi.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"StorageBucketApi.d.ts","sourceRoot":"","sources":["../../../src/packages/StorageBucketApi.ts"],"names":[],"mappings":"AACA,OAAO,EAAkB,YAAY,EAAE,MAAM,eAAe,CAAA;AAC5D,OAAO,EAAE,KAAK,EAA0B,MAAM,cAAc,CAAA;AAE5D,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAErC,MAAM,CAAC,OAAO,OAAO,gBAAgB;IACnC,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;IAC5C,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;gBAEV,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAO,EAAE,KAAK,CAAC,EAAE,KAAK;IAM/E;;OAEG;IACG,WAAW,IAAI,OAAO,CACxB;QACE,IAAI,EAAE,MAAM,EAAE,CAAA;QACd,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAA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AAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;IAkBD;;;;;OAKG;IACG,YAAY,CAChB,EAAE,EAAE,MAAM,GACT,OAAO,CACN;QACE,IAAI,EAAE;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,CAAA;QACzB,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;CAiBF"}

View File

@@ -0,0 +1,166 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("../lib/constants");
const errors_1 = require("../lib/errors");
const fetch_1 = require("../lib/fetch");
const helpers_1 = require("../lib/helpers");
class StorageBucketApi {
constructor(url, headers = {}, fetch) {
this.url = url;
this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers);
this.fetch = (0, helpers_1.resolveFetch)(fetch);
}
/**
* Retrieves the details of all Storage buckets within an existing project.
*/
listBuckets() {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket`, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Retrieves the details of an existing Storage bucket.
*
* @param id The unique identifier of the bucket you would like to retrieve.
*/
getBucket(id) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Creates a new Storage bucket
*
* @param id A unique identifier for the bucket you are creating.
* @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private.
* @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.
* The global file size limit takes precedence over this value.
* The default value is null, which doesn't set a per bucket file size limit.
* @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.
* The default value is null, which allows files with all mime types to be uploaded.
* Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.
* @returns newly created bucket id
*/
createBucket(id, options = {
public: false,
}) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, {
id,
name: id,
public: options.public,
file_size_limit: options.fileSizeLimit,
allowed_mime_types: options.allowedMimeTypes,
}, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Updates a Storage bucket
*
* @param id A unique identifier for the bucket you are updating.
* @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations.
* @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.
* The global file size limit takes precedence over this value.
* The default value is null, which doesn't set a per bucket file size limit.
* @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.
* The default value is null, which allows files with all mime types to be uploaded.
* Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.
*/
updateBucket(id, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield (0, fetch_1.put)(this.fetch, `${this.url}/bucket/${id}`, {
id,
name: id,
public: options.public,
file_size_limit: options.fileSizeLimit,
allowed_mime_types: options.allowedMimeTypes,
}, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Removes all objects inside a single bucket.
*
* @param id The unique identifier of the bucket you would like to empty.
*/
emptyBucket(id) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Deletes an existing bucket. A bucket can't be deleted with existing objects inside it.
* You must first `empty()` the bucket.
*
* @param id The unique identifier of the bucket you would like to delete.
*/
deleteBucket(id) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
}
exports.default = StorageBucketApi;
//# sourceMappingURL=StorageBucketApi.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"StorageBucketApi.js","sourceRoot":"","sources":["../../../src/packages/StorageBucketApi.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,gDAAkD;AAClD,0CAA4D;AAC5D,wCAA4D;AAC5D,4CAA6C;AAG7C,MAAqB,gBAAgB;IAKnC,YAAY,GAAW,EAAE,UAAqC,EAAE,EAAE,KAAa;QAC7E,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,mCAAQ,2BAAe,GAAK,OAAO,CAAE,CAAA;QACjD,IAAI,CAAC,KAAK,GAAG,IAAA,sBAAY,EAAC,KAAK,CAAC,CAAA;IAClC,CAAC;IAED;;OAEG;IACG,WAAW;;YAUf,IAAI;gBACF,MAAM,IAAI,GAAG,MAAM,IAAA,WAAG,EAAC,IAAI,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,GAAG,SAAS,EAAE,EAAE,OAAO,EA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IAAI,IAAA,uBAAc,EAAC,KAAK,CAAC,EAAE;oBACzB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;iBAC7B;gBAED,MAAM,KAAK,CAAA;aACZ;QACH,CAAC;KAAA;IAED;;;;;OAKG;IACG,YAAY,CAChB,EAAU;;YAWV,IAAI;gBACF,MAAM,IAAI,GAAG,MAAM,IAAA,cAAM,EACvB,IAAI,CAAC,KAAK,EACV,GAAG,IAAI,CAAC,GAAG,WAAW,EAAE,EAAE,EAC1B,EAAE,EACF,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAC1B,CAAA;gBACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;aAC7B;YAAC,OAAO,KAAK,EAAE;gBACd,IAAI,IAAA,uBAAc,EAAC,KAAK,CAAC,EAAE;oBACzB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;iBAC7B;gBAED,MAAM,KAAK,CAAA;aACZ;QACH,CAAC;KAAA;CACF;AAhPD,mCAgPC"}

View File

@@ -0,0 +1,258 @@
/// <reference types="node" />
import { StorageError } from '../lib/errors';
import { Fetch } from '../lib/fetch';
import { FileObject, FileOptions, SearchOptions, FetchParameters, TransformOptions, DestinationOptions, FileObjectV2, Camelize } from '../lib/types';
declare type FileBody = ArrayBuffer | ArrayBufferView | Blob | Buffer | File | FormData | NodeJS.ReadableStream | ReadableStream<Uint8Array> | URLSearchParams | string;
export default class StorageFileApi {
protected url: string;
protected headers: {
[key: string]: string;
};
protected bucketId?: string;
protected fetch: Fetch;
constructor(url: string, headers?: {
[key: string]: string;
}, bucketId?: string, fetch?: Fetch);
/**
* Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one.
*
* @param method HTTP method.
* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param fileBody The body of the file to be stored in the bucket.
*/
private uploadOrUpdate;
/**
* Uploads a file to an existing bucket.
*
* @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param fileBody The body of the file to be stored in the bucket.
*/
upload(path: string, fileBody: FileBody, fileOptions?: FileOptions): Promise<{
data: {
id: string;
path: string;
fullPath: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Upload a file with a token generated from `createSignedUploadUrl`.
* @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param token The token generated from `createSignedUploadUrl`
* @param fileBody The body of the file to be stored in the bucket.
*/
uploadToSignedUrl(path: string, token: string, fileBody: FileBody, fileOptions?: FileOptions): Promise<{
data: {
path: string;
fullPath: any;
};
error: null;
} | {
data: null;
error: any;
}>;
/**
* Creates a signed upload URL.
* Signed upload URLs can be used to upload files to the bucket without further authentication.
* They are valid for 2 hours.
* @param path The file path, including the current file name. For example `folder/image.png`.
* @param options.upsert If set to true, allows the file to be overwritten if it already exists.
*/
createSignedUploadUrl(path: string, options?: {
upsert: boolean;
}): Promise<{
data: {
signedUrl: string;
token: string;
path: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Replaces an existing file at the specified path with a new one.
*
* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update.
* @param fileBody The body of the file to be stored in the bucket.
*/
update(path: string, fileBody: ArrayBuffer | ArrayBufferView | Blob | Buffer | File | FormData | NodeJS.ReadableStream | ReadableStream<Uint8Array> | URLSearchParams | string, fileOptions?: FileOptions): Promise<{
data: {
id: string;
path: string;
fullPath: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Moves an existing file to a new path in the same bucket.
*
* @param fromPath The original file path, including the current file name. For example `folder/image.png`.
* @param toPath The new file path, including the new file name. For example `folder/image-new.png`.
* @param options The destination options.
*/
move(fromPath: string, toPath: string, options?: DestinationOptions): Promise<{
data: {
message: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Copies an existing file to a new path in the same bucket.
*
* @param fromPath The original file path, including the current file name. For example `folder/image.png`.
* @param toPath The new file path, including the new file name. For example `folder/image-copy.png`.
* @param options The destination options.
*/
copy(fromPath: string, toPath: string, options?: DestinationOptions): Promise<{
data: {
path: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Creates a signed URL. Use a signed URL to share a file for a fixed amount of time.
*
* @param path The file path, including the current file name. For example `folder/image.png`.
* @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute.
* @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
* @param options.transform Transform the asset before serving it to the client.
*/
createSignedUrl(path: string, expiresIn: number, options?: {
download?: string | boolean;
transform?: TransformOptions;
}): Promise<{
data: {
signedUrl: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time.
*
* @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`.
* @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute.
* @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
*/
createSignedUrls(paths: string[], expiresIn: number, options?: {
download: string | boolean;
}): Promise<{
data: {
error: string | null;
path: string | null;
signedUrl: string;
}[];
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead.
*
* @param path The full path and file name of the file to be downloaded. For example `folder/image.png`.
* @param options.transform Transform the asset before serving it to the client.
*/
download(path: string, options?: {
transform?: TransformOptions;
}): Promise<{
data: Blob;
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Retrieves the details of an existing file.
* @param path
*/
info(path: string): Promise<{
data: Camelize<FileObjectV2>;
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Checks the existence of a file.
* @param path
*/
exists(path: string): Promise<{
data: boolean;
error: null;
} | {
data: boolean;
error: StorageError;
}>;
/**
* A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset.
* This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset.
*
* @param path The path and name of the file to generate the public URL for. For example `folder/image.png`.
* @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
* @param options.transform Transform the asset before serving it to the client.
*/
getPublicUrl(path: string, options?: {
download?: string | boolean;
transform?: TransformOptions;
}): {
data: {
publicUrl: string;
};
};
/**
* Deletes files within the same bucket
*
* @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`].
*/
remove(paths: string[]): Promise<{
data: FileObject[];
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Get file metadata
* @param id the file id to retrieve metadata
*/
/**
* Update file metadata
* @param id the file id to update metadata
* @param meta the new file metadata
*/
/**
* Lists all the files within a bucket.
* @param path The folder path.
*/
list(path?: string, options?: SearchOptions, parameters?: FetchParameters): Promise<{
data: FileObject[];
error: null;
} | {
data: null;
error: StorageError;
}>;
protected encodeMetadata(metadata: Record<string, any>): string;
toBase64(data: string): string;
private _getFinalPath;
private _removeEmptyFolders;
private transformOptsToQueryString;
}
export {};
//# sourceMappingURL=StorageFileApi.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"StorageFileApi.d.ts","sourceRoot":"","sources":["../../../src/packages/StorageFileApi.ts"],"names":[],"mappings":";AAAA,OAAO,EAAkB,YAAY,EAAuB,MAAM,eAAe,CAAA;AACjF,OAAO,EAAE,KAAK,EAA2B,MAAM,cAAc,CAAA;AAE7D,OAAO,EACL,UAAU,EACV,WAAW,EACX,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,YAAY,EACZ,QAAQ,EACT,MAAM,cAAc,CAAA;AAiBrB,aAAK,QAAQ,GACT,WAAW,GACX,eAAe,GACf,IAAI,GACJ,MAAM,GACN,IAAI,GACJ,QAAQ,GACR,M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O,CAAC,mBAAmB;IAI3B,OAAO,CAAC,0BAA0B;CAwBnC"}

View File

@@ -0,0 +1,553 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const errors_1 = require("../lib/errors");
const fetch_1 = require("../lib/fetch");
const helpers_1 = require("../lib/helpers");
const DEFAULT_SEARCH_OPTIONS = {
limit: 100,
offset: 0,
sortBy: {
column: 'name',
order: 'asc',
},
};
const DEFAULT_FILE_OPTIONS = {
cacheControl: '3600',
contentType: 'text/plain;charset=UTF-8',
upsert: false,
};
class StorageFileApi {
constructor(url, headers = {}, bucketId, fetch) {
this.url = url;
this.headers = headers;
this.bucketId = bucketId;
this.fetch = (0, helpers_1.resolveFetch)(fetch);
}
/**
* Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one.
*
* @param method HTTP method.
* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param fileBody The body of the file to be stored in the bucket.
*/
uploadOrUpdate(method, path, fileBody, fileOptions) {
return __awaiter(this, void 0, void 0, function* () {
try {
let body;
const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions);
let headers = Object.assign(Object.assign({}, this.headers), (method === 'POST' && { 'x-upsert': String(options.upsert) }));
const metadata = options.metadata;
if (typeof Blob !== 'undefined' && fileBody instanceof Blob) {
body = new FormData();
body.append('cacheControl', options.cacheControl);
if (metadata) {
body.append('metadata', this.encodeMetadata(metadata));
}
body.append('', fileBody);
}
else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) {
body = fileBody;
body.append('cacheControl', options.cacheControl);
if (metadata) {
body.append('metadata', this.encodeMetadata(metadata));
}
}
else {
body = fileBody;
headers['cache-control'] = `max-age=${options.cacheControl}`;
headers['content-type'] = options.contentType;
if (metadata) {
headers['x-metadata'] = this.toBase64(this.encodeMetadata(metadata));
}
}
if (fileOptions === null || fileOptions === void 0 ? void 0 : fileOptions.headers) {
headers = Object.assign(Object.assign({}, headers), fileOptions.headers);
}
const cleanPath = this._removeEmptyFolders(path);
const _path = this._getFinalPath(cleanPath);
const res = yield this.fetch(`${this.url}/object/${_path}`, Object.assign({ method, body: body, headers }, ((options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {})));
const data = yield res.json();
if (res.ok) {
return {
data: { path: cleanPath, id: data.Id, fullPath: data.Key },
error: null,
};
}
else {
const error = data;
return { data: null, error };
}
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Uploads a file to an existing bucket.
*
* @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param fileBody The body of the file to be stored in the bucket.
*/
upload(path, fileBody, fileOptions) {
return __awaiter(this, void 0, void 0, function* () {
return this.uploadOrUpdate('POST', path, fileBody, fileOptions);
});
}
/**
* Upload a file with a token generated from `createSignedUploadUrl`.
* @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param token The token generated from `createSignedUploadUrl`
* @param fileBody The body of the file to be stored in the bucket.
*/
uploadToSignedUrl(path, token, fileBody, fileOptions) {
return __awaiter(this, void 0, void 0, function* () {
const cleanPath = this._removeEmptyFolders(path);
const _path = this._getFinalPath(cleanPath);
const url = new URL(this.url + `/object/upload/sign/${_path}`);
url.searchParams.set('token', token);
try {
let body;
const options = Object.assign({ upsert: DEFAULT_FILE_OPTIONS.upsert }, fileOptions);
const headers = Object.assign(Object.assign({}, this.headers), { 'x-upsert': String(options.upsert) });
if (typeof Blob !== 'undefined' && fileBody instanceof Blob) {
body = new FormData();
body.append('cacheControl', options.cacheControl);
body.append('', fileBody);
}
else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) {
body = fileBody;
body.append('cacheControl', options.cacheControl);
}
else {
body = fileBody;
headers['cache-control'] = `max-age=${options.cacheControl}`;
headers['content-type'] = options.contentType;
}
const res = yield this.fetch(url.toString(), {
method: 'PUT',
body: body,
headers,
});
const data = yield res.json();
if (res.ok) {
return {
data: { path: cleanPath, fullPath: data.Key },
error: null,
};
}
else {
const error = data;
return { data: null, error };
}
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Creates a signed upload URL.
* Signed upload URLs can be used to upload files to the bucket without further authentication.
* They are valid for 2 hours.
* @param path The file path, including the current file name. For example `folder/image.png`.
* @param options.upsert If set to true, allows the file to be overwritten if it already exists.
*/
createSignedUploadUrl(path, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
let _path = this._getFinalPath(path);
const headers = Object.assign({}, this.headers);
if (options === null || options === void 0 ? void 0 : options.upsert) {
headers['x-upsert'] = 'true';
}
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers });
const url = new URL(this.url + data.url);
const token = url.searchParams.get('token');
if (!token) {
throw new errors_1.StorageError('No token returned by API');
}
return { data: { signedUrl: url.toString(), path, token }, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Replaces an existing file at the specified path with a new one.
*
* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update.
* @param fileBody The body of the file to be stored in the bucket.
*/
update(path, fileBody, fileOptions) {
return __awaiter(this, void 0, void 0, function* () {
return this.uploadOrUpdate('PUT', path, fileBody, fileOptions);
});
}
/**
* Moves an existing file to a new path in the same bucket.
*
* @param fromPath The original file path, including the current file name. For example `folder/image.png`.
* @param toPath The new file path, including the new file name. For example `folder/image-new.png`.
* @param options The destination options.
*/
move(fromPath, toPath, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/move`, {
bucketId: this.bucketId,
sourceKey: fromPath,
destinationKey: toPath,
destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket,
}, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Copies an existing file to a new path in the same bucket.
*
* @param fromPath The original file path, including the current file name. For example `folder/image.png`.
* @param toPath The new file path, including the new file name. For example `folder/image-copy.png`.
* @param options The destination options.
*/
copy(fromPath, toPath, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/copy`, {
bucketId: this.bucketId,
sourceKey: fromPath,
destinationKey: toPath,
destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket,
}, { headers: this.headers });
return { data: { path: data.Key }, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Creates a signed URL. Use a signed URL to share a file for a fixed amount of time.
*
* @param path The file path, including the current file name. For example `folder/image.png`.
* @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute.
* @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
* @param options.transform Transform the asset before serving it to the client.
*/
createSignedUrl(path, expiresIn, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
let _path = this._getFinalPath(path);
let data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${_path}`, Object.assign({ expiresIn }, ((options === null || options === void 0 ? void 0 : options.transform) ? { transform: options.transform } : {})), { headers: this.headers });
const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download)
? `&download=${options.download === true ? '' : options.download}`
: '';
const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`);
data = { signedUrl };
return { data, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time.
*
* @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`.
* @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute.
* @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
*/
createSignedUrls(paths, expiresIn, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${this.bucketId}`, { expiresIn, paths }, { headers: this.headers });
const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download)
? `&download=${options.download === true ? '' : options.download}`
: '';
return {
data: data.map((datum) => (Object.assign(Object.assign({}, datum), { signedUrl: datum.signedURL
? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`)
: null }))),
error: null,
};
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead.
*
* @param path The full path and file name of the file to be downloaded. For example `folder/image.png`.
* @param options.transform Transform the asset before serving it to the client.
*/
download(path, options) {
return __awaiter(this, void 0, void 0, function* () {
const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined';
const renderPath = wantsTransformation ? 'render/image/authenticated' : 'object';
const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {});
const queryString = transformationQuery ? `?${transformationQuery}` : '';
try {
const _path = this._getFinalPath(path);
const res = yield (0, fetch_1.get)(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, {
headers: this.headers,
noResolveJson: true,
});
const data = yield res.blob();
return { data, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Retrieves the details of an existing file.
* @param path
*/
info(path) {
return __awaiter(this, void 0, void 0, function* () {
const _path = this._getFinalPath(path);
try {
const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/object/info/${_path}`, {
headers: this.headers,
});
return { data: (0, helpers_1.recursiveToCamel)(data), error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Checks the existence of a file.
* @param path
*/
exists(path) {
return __awaiter(this, void 0, void 0, function* () {
const _path = this._getFinalPath(path);
try {
yield (0, fetch_1.head)(this.fetch, `${this.url}/object/${_path}`, {
headers: this.headers,
});
return { data: true, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error) && error instanceof errors_1.StorageUnknownError) {
const originalError = error.originalError;
if ([400, 404].includes(originalError === null || originalError === void 0 ? void 0 : originalError.status)) {
return { data: false, error };
}
}
throw error;
}
});
}
/**
* A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset.
* This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset.
*
* @param path The path and name of the file to generate the public URL for. For example `folder/image.png`.
* @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
* @param options.transform Transform the asset before serving it to the client.
*/
getPublicUrl(path, options) {
const _path = this._getFinalPath(path);
const _queryString = [];
const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download)
? `download=${options.download === true ? '' : options.download}`
: '';
if (downloadQueryParam !== '') {
_queryString.push(downloadQueryParam);
}
const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined';
const renderPath = wantsTransformation ? 'render/image' : 'object';
const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {});
if (transformationQuery !== '') {
_queryString.push(transformationQuery);
}
let queryString = _queryString.join('&');
if (queryString !== '') {
queryString = `?${queryString}`;
}
return {
data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) },
};
}
/**
* Deletes files within the same bucket
*
* @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`].
*/
remove(paths) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Get file metadata
* @param id the file id to retrieve metadata
*/
// async getMetadata(
// id: string
// ): Promise<
// | {
// data: Metadata
// error: null
// }
// | {
// data: null
// error: StorageError
// }
// > {
// try {
// const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers })
// return { data, error: null }
// } catch (error) {
// if (isStorageError(error)) {
// return { data: null, error }
// }
// throw error
// }
// }
/**
* Update file metadata
* @param id the file id to update metadata
* @param meta the new file metadata
*/
// async updateMetadata(
// id: string,
// meta: Metadata
// ): Promise<
// | {
// data: Metadata
// error: null
// }
// | {
// data: null
// error: StorageError
// }
// > {
// try {
// const data = await post(
// this.fetch,
// `${this.url}/metadata/${id}`,
// { ...meta },
// { headers: this.headers }
// )
// return { data, error: null }
// } catch (error) {
// if (isStorageError(error)) {
// return { data: null, error }
// }
// throw error
// }
// }
/**
* Lists all the files within a bucket.
* @param path The folder path.
*/
list(path, options, parameters) {
return __awaiter(this, void 0, void 0, function* () {
try {
const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || '' });
const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters);
return { data, error: null };
}
catch (error) {
if ((0, errors_1.isStorageError)(error)) {
return { data: null, error };
}
throw error;
}
});
}
encodeMetadata(metadata) {
return JSON.stringify(metadata);
}
toBase64(data) {
if (typeof Buffer !== 'undefined') {
return Buffer.from(data).toString('base64');
}
return btoa(data);
}
_getFinalPath(path) {
return `${this.bucketId}/${path}`;
}
_removeEmptyFolders(path) {
return path.replace(/^\/|\/$/g, '').replace(/\/+/g, '/');
}
transformOptsToQueryString(transform) {
const params = [];
if (transform.width) {
params.push(`width=${transform.width}`);
}
if (transform.height) {
params.push(`height=${transform.height}`);
}
if (transform.resize) {
params.push(`resize=${transform.resize}`);
}
if (transform.format) {
params.push(`format=${transform.format}`);
}
if (transform.quality) {
params.push(`quality=${transform.quality}`);
}
return params.join('&');
}
}
exports.default = StorageFileApi;
//# sourceMappingURL=StorageFileApi.js.map

File diff suppressed because one or more lines are too long