@webiny/app-file-manager-s3 0.0.0-mt-3 → 0.0.0-unstable.06b2ede40f

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.
@@ -0,0 +1,26 @@
1
+ import type { UploadedFile } from "@webiny/app/types";
2
+ export interface CreateUploadParams {
3
+ data: {
4
+ size: number;
5
+ name: string;
6
+ type: string;
7
+ };
8
+ numberOfParts: number;
9
+ }
10
+ export interface CompleteUploadParams {
11
+ fileKey: string;
12
+ uploadId: string;
13
+ }
14
+ export interface FilePart {
15
+ partNumber: number;
16
+ url: string;
17
+ }
18
+ export interface MultiPartUpload {
19
+ file: UploadedFile;
20
+ uploadId: string;
21
+ parts: FilePart[];
22
+ }
23
+ export interface MultiPartUploadAPI {
24
+ createUpload(params: CreateUploadParams): Promise<MultiPartUpload>;
25
+ completeUpload(params: CompleteUploadParams): Promise<boolean>;
26
+ }
@@ -0,0 +1,3 @@
1
+ export {};
2
+
3
+ //# sourceMappingURL=MultiPartUploadAPI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":[],"sources":["MultiPartUploadAPI.ts"],"sourcesContent":["import type { UploadedFile } from \"@webiny/app/types\";\n\nexport interface CreateUploadParams {\n data: {\n size: number;\n name: string;\n type: string;\n };\n numberOfParts: number;\n}\n\nexport interface CompleteUploadParams {\n fileKey: string;\n uploadId: string;\n}\n\nexport interface FilePart {\n partNumber: number;\n url: string;\n}\n\nexport interface MultiPartUpload {\n file: UploadedFile;\n uploadId: string;\n parts: FilePart[];\n}\n\nexport interface MultiPartUploadAPI {\n createUpload(params: CreateUploadParams): Promise<MultiPartUpload>;\n completeUpload(params: CompleteUploadParams): Promise<boolean>;\n}\n"],"mappings":"","ignoreList":[]}
@@ -0,0 +1,8 @@
1
+ import type { UploadOptions } from "@webiny/app/types";
2
+ import type { CompleteUploadParams, CreateUploadParams, MultiPartUpload, MultiPartUploadAPI } from "./MultiPartUploadAPI";
3
+ export declare class MultiPartUploadGraphQLAPI implements MultiPartUploadAPI {
4
+ private client;
5
+ constructor(client: UploadOptions["apolloClient"]);
6
+ createUpload(params: CreateUploadParams): Promise<MultiPartUpload>;
7
+ completeUpload(params: CompleteUploadParams): Promise<boolean>;
8
+ }
@@ -0,0 +1,77 @@
1
+ import gql from "graphql-tag";
2
+ export class MultiPartUploadGraphQLAPI {
3
+ constructor(client) {
4
+ this.client = client;
5
+ }
6
+ async createUpload(params) {
7
+ const {
8
+ data,
9
+ errors
10
+ } = await this.client.mutate({
11
+ mutation: CREATE_UPLOAD,
12
+ variables: params
13
+ });
14
+ if (!data) {
15
+ console.error(errors);
16
+ throw new Error(`Failed to initialize a multi-part file upload!`);
17
+ }
18
+ return data.fileManager.createMultiPartUpload.data;
19
+ }
20
+ async completeUpload(params) {
21
+ const {
22
+ data,
23
+ errors
24
+ } = await this.client.mutate({
25
+ mutation: COMPLETE_UPLOAD,
26
+ variables: params
27
+ });
28
+ if (!data) {
29
+ console.error(errors);
30
+ throw new Error(`Failed to complete a multi-part file upload!`);
31
+ }
32
+ return data.fileManager.completeMultiPartUpload.data;
33
+ }
34
+ }
35
+ const CREATE_UPLOAD = gql`
36
+ mutation CreateMultiPartUpload($data: PreSignedPostPayloadInput!, $numberOfParts: Number!) {
37
+ fileManager {
38
+ createMultiPartUpload(data: $data, numberOfParts: $numberOfParts) {
39
+ data {
40
+ file {
41
+ id
42
+ key
43
+ name
44
+ size
45
+ type
46
+ }
47
+ uploadId
48
+ parts {
49
+ partNumber
50
+ url
51
+ }
52
+ }
53
+ error {
54
+ code
55
+ message
56
+ data
57
+ }
58
+ }
59
+ }
60
+ }
61
+ `;
62
+ const COMPLETE_UPLOAD = gql`
63
+ mutation CompleteMultiPartUpload($fileKey: String!, $uploadId: String!) {
64
+ fileManager {
65
+ completeMultiPartUpload(fileKey: $fileKey, uploadId: $uploadId) {
66
+ data
67
+ error {
68
+ code
69
+ message
70
+ data
71
+ }
72
+ }
73
+ }
74
+ }
75
+ `;
76
+
77
+ //# sourceMappingURL=MultiPartUploadGraphQLAPI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["gql","MultiPartUploadGraphQLAPI","constructor","client","createUpload","params","data","errors","mutate","mutation","CREATE_UPLOAD","variables","console","error","Error","fileManager","createMultiPartUpload","completeUpload","COMPLETE_UPLOAD","completeMultiPartUpload"],"sources":["MultiPartUploadGraphQLAPI.ts"],"sourcesContent":["import type { UploadOptions } from \"@webiny/app/types\";\nimport gql from \"graphql-tag\";\nimport type {\n CompleteUploadParams,\n CreateUploadParams,\n MultiPartUpload,\n MultiPartUploadAPI\n} from \"~/MultiPartUploadAPI\";\n\nexport class MultiPartUploadGraphQLAPI implements MultiPartUploadAPI {\n private client: UploadOptions[\"apolloClient\"];\n\n constructor(client: UploadOptions[\"apolloClient\"]) {\n this.client = client;\n }\n\n async createUpload(params: CreateUploadParams): Promise<MultiPartUpload> {\n const { data, errors } = await this.client.mutate<CreateUploadResponse>({\n mutation: CREATE_UPLOAD,\n variables: params\n });\n\n if (!data) {\n console.error(errors);\n throw new Error(`Failed to initialize a multi-part file upload!`);\n }\n\n return data.fileManager.createMultiPartUpload.data;\n }\n\n async completeUpload(params: CompleteUploadParams): Promise<boolean> {\n const { data, errors } = await this.client.mutate<CompleteUploadResponse>({\n mutation: COMPLETE_UPLOAD,\n variables: params\n });\n\n if (!data) {\n console.error(errors);\n throw new Error(`Failed to complete a multi-part file upload!`);\n }\n\n return data.fileManager.completeMultiPartUpload.data;\n }\n}\n\nconst CREATE_UPLOAD = gql`\n mutation CreateMultiPartUpload($data: PreSignedPostPayloadInput!, $numberOfParts: Number!) {\n fileManager {\n createMultiPartUpload(data: $data, numberOfParts: $numberOfParts) {\n data {\n file {\n id\n key\n name\n size\n type\n }\n uploadId\n parts {\n partNumber\n url\n }\n }\n error {\n code\n message\n data\n }\n }\n }\n }\n`;\n\ninterface CreateUploadResponse {\n fileManager: {\n createMultiPartUpload: {\n data: MultiPartUpload;\n error: {\n code: string;\n message: string;\n data: Record<string, any>;\n };\n };\n };\n}\n\nconst COMPLETE_UPLOAD = gql`\n mutation CompleteMultiPartUpload($fileKey: String!, $uploadId: String!) {\n fileManager {\n completeMultiPartUpload(fileKey: $fileKey, uploadId: $uploadId) {\n data\n error {\n code\n message\n data\n }\n }\n }\n }\n`;\n\ninterface CompleteUploadResponse {\n fileManager: {\n completeMultiPartUpload: {\n data: boolean;\n error: {\n code: string;\n message: string;\n data: Record<string, any>;\n };\n };\n };\n}\n"],"mappings":"AACA,OAAOA,GAAG,MAAM,aAAa;AAQ7B,OAAO,MAAMC,yBAAyB,CAA+B;EAGjEC,WAAWA,CAACC,MAAqC,EAAE;IAC/C,IAAI,CAACA,MAAM,GAAGA,MAAM;EACxB;EAEA,MAAMC,YAAYA,CAACC,MAA0B,EAA4B;IACrE,MAAM;MAAEC,IAAI;MAAEC;IAAO,CAAC,GAAG,MAAM,IAAI,CAACJ,MAAM,CAACK,MAAM,CAAuB;MACpEC,QAAQ,EAAEC,aAAa;MACvBC,SAAS,EAAEN;IACf,CAAC,CAAC;IAEF,IAAI,CAACC,IAAI,EAAE;MACPM,OAAO,CAACC,KAAK,CAACN,MAAM,CAAC;MACrB,MAAM,IAAIO,KAAK,CAAC,gDAAgD,CAAC;IACrE;IAEA,OAAOR,IAAI,CAACS,WAAW,CAACC,qBAAqB,CAACV,IAAI;EACtD;EAEA,MAAMW,cAAcA,CAACZ,MAA4B,EAAoB;IACjE,MAAM;MAAEC,IAAI;MAAEC;IAAO,CAAC,GAAG,MAAM,IAAI,CAACJ,MAAM,CAACK,MAAM,CAAyB;MACtEC,QAAQ,EAAES,eAAe;MACzBP,SAAS,EAAEN;IACf,CAAC,CAAC;IAEF,IAAI,CAACC,IAAI,EAAE;MACPM,OAAO,CAACC,KAAK,CAACN,MAAM,CAAC;MACrB,MAAM,IAAIO,KAAK,CAAC,8CAA8C,CAAC;IACnE;IAEA,OAAOR,IAAI,CAACS,WAAW,CAACI,uBAAuB,CAACb,IAAI;EACxD;AACJ;AAEA,MAAMI,aAAa,GAAGV,GAAG;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AAeD,MAAMkB,eAAe,GAAGlB,GAAG;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC","ignoreList":[]}
@@ -0,0 +1,7 @@
1
+ import type { UploadedFile, UploadOptions } from "@webiny/app/types";
2
+ import type { FileUploadStrategy } from "./index";
3
+ export declare class MultiPartUploadStrategy implements FileUploadStrategy {
4
+ upload(file: File, options: UploadOptions): Promise<UploadedFile>;
5
+ private detectChunkSize;
6
+ private detectParallelChunks;
7
+ }
@@ -0,0 +1,47 @@
1
+ import { MultiPartUploader } from "./MultiPartUploader";
2
+ import { MultiPartUploadGraphQLAPI } from "./MultiPartUploadGraphQLAPI";
3
+ export class MultiPartUploadStrategy {
4
+ async upload(file, options) {
5
+ const api = new MultiPartUploadGraphQLAPI(options.apolloClient);
6
+ const uploader = new MultiPartUploader(api, {
7
+ chunkSize: this.detectChunkSize(),
8
+ parallelUploads: this.detectParallelChunks()
9
+ });
10
+ if (options.onProgress) {
11
+ uploader.onProgress(options.onProgress);
12
+ }
13
+ return uploader.uploadFile(file);
14
+ }
15
+ detectChunkSize() {
16
+ const envSize = parseInt(process.env.WEBINY_FILE_UPLOAD_CHUNK_SIZE || "0");
17
+
18
+ // For dev purposes, we take this global var into consideration.
19
+ if (process.env.NODE_ENV === "development") {
20
+ // @ts-expect-error
21
+ const windowSize = window["fmUploadChunkSize"];
22
+ if (windowSize) {
23
+ return windowSize;
24
+ }
25
+ }
26
+
27
+ // As a last resort, we check the baked in value, or fall back to 50MB chunk size.
28
+ return envSize || 50;
29
+ }
30
+ detectParallelChunks() {
31
+ const envChunks = parseInt(process.env.WEBINY_FILE_UPLOAD_PARALLEL_CHUNKS || "0");
32
+
33
+ // For dev purposes, we take this global var into consideration.
34
+ if (process.env.NODE_ENV === "development") {
35
+ // @ts-expect-error
36
+ const windowChunks = window["fmUploadParallelChunks"];
37
+ if (windowChunks) {
38
+ return windowChunks;
39
+ }
40
+ }
41
+
42
+ // As a last resort, we check the baked in value, or fall back to 5 parallel chunks.
43
+ return envChunks || 5;
44
+ }
45
+ }
46
+
47
+ //# sourceMappingURL=MultiPartUploadStrategy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["MultiPartUploader","MultiPartUploadGraphQLAPI","MultiPartUploadStrategy","upload","file","options","api","apolloClient","uploader","chunkSize","detectChunkSize","parallelUploads","detectParallelChunks","onProgress","uploadFile","envSize","parseInt","process","env","WEBINY_FILE_UPLOAD_CHUNK_SIZE","NODE_ENV","windowSize","window","envChunks","WEBINY_FILE_UPLOAD_PARALLEL_CHUNKS","windowChunks"],"sources":["MultiPartUploadStrategy.ts"],"sourcesContent":["import type { UploadedFile, UploadOptions } from \"@webiny/app/types\";\nimport type { FileUploadStrategy } from \"~/index\";\nimport { MultiPartUploader } from \"~/MultiPartUploader\";\nimport { MultiPartUploadGraphQLAPI } from \"~/MultiPartUploadGraphQLAPI\";\n\nexport class MultiPartUploadStrategy implements FileUploadStrategy {\n async upload(file: File, options: UploadOptions): Promise<UploadedFile> {\n const api = new MultiPartUploadGraphQLAPI(options.apolloClient);\n\n const uploader = new MultiPartUploader(api, {\n chunkSize: this.detectChunkSize(),\n parallelUploads: this.detectParallelChunks()\n });\n\n if (options.onProgress) {\n uploader.onProgress(options.onProgress);\n }\n return uploader.uploadFile(file);\n }\n\n private detectChunkSize(): number {\n const envSize = parseInt(process.env.WEBINY_FILE_UPLOAD_CHUNK_SIZE || \"0\");\n\n // For dev purposes, we take this global var into consideration.\n if (process.env.NODE_ENV === \"development\") {\n // @ts-expect-error\n const windowSize = window[\"fmUploadChunkSize\"];\n if (windowSize) {\n return windowSize;\n }\n }\n\n // As a last resort, we check the baked in value, or fall back to 50MB chunk size.\n return envSize || 50;\n }\n\n private detectParallelChunks(): number {\n const envChunks = parseInt(process.env.WEBINY_FILE_UPLOAD_PARALLEL_CHUNKS || \"0\");\n\n // For dev purposes, we take this global var into consideration.\n if (process.env.NODE_ENV === \"development\") {\n // @ts-expect-error\n const windowChunks = window[\"fmUploadParallelChunks\"];\n if (windowChunks) {\n return windowChunks;\n }\n }\n\n // As a last resort, we check the baked in value, or fall back to 5 parallel chunks.\n return envChunks || 5;\n }\n}\n"],"mappings":"AAEA,SAASA,iBAAiB;AAC1B,SAASC,yBAAyB;AAElC,OAAO,MAAMC,uBAAuB,CAA+B;EAC/D,MAAMC,MAAMA,CAACC,IAAU,EAAEC,OAAsB,EAAyB;IACpE,MAAMC,GAAG,GAAG,IAAIL,yBAAyB,CAACI,OAAO,CAACE,YAAY,CAAC;IAE/D,MAAMC,QAAQ,GAAG,IAAIR,iBAAiB,CAACM,GAAG,EAAE;MACxCG,SAAS,EAAE,IAAI,CAACC,eAAe,CAAC,CAAC;MACjCC,eAAe,EAAE,IAAI,CAACC,oBAAoB,CAAC;IAC/C,CAAC,CAAC;IAEF,IAAIP,OAAO,CAACQ,UAAU,EAAE;MACpBL,QAAQ,CAACK,UAAU,CAACR,OAAO,CAACQ,UAAU,CAAC;IAC3C;IACA,OAAOL,QAAQ,CAACM,UAAU,CAACV,IAAI,CAAC;EACpC;EAEQM,eAAeA,CAAA,EAAW;IAC9B,MAAMK,OAAO,GAAGC,QAAQ,CAACC,OAAO,CAACC,GAAG,CAACC,6BAA6B,IAAI,GAAG,CAAC;;IAE1E;IACA,IAAIF,OAAO,CAACC,GAAG,CAACE,QAAQ,KAAK,aAAa,EAAE;MACxC;MACA,MAAMC,UAAU,GAAGC,MAAM,CAAC,mBAAmB,CAAC;MAC9C,IAAID,UAAU,EAAE;QACZ,OAAOA,UAAU;MACrB;IACJ;;IAEA;IACA,OAAON,OAAO,IAAI,EAAE;EACxB;EAEQH,oBAAoBA,CAAA,EAAW;IACnC,MAAMW,SAAS,GAAGP,QAAQ,CAACC,OAAO,CAACC,GAAG,CAACM,kCAAkC,IAAI,GAAG,CAAC;;IAEjF;IACA,IAAIP,OAAO,CAACC,GAAG,CAACE,QAAQ,KAAK,aAAa,EAAE;MACxC;MACA,MAAMK,YAAY,GAAGH,MAAM,CAAC,wBAAwB,CAAC;MACrD,IAAIG,YAAY,EAAE;QACd,OAAOA,YAAY;MACvB;IACJ;;IAEA;IACA,OAAOF,SAAS,IAAI,CAAC;EACzB;AACJ","ignoreList":[]}
@@ -0,0 +1,43 @@
1
+ import type { MultiPartUploadAPI } from "./MultiPartUploadAPI";
2
+ interface MultiPartUploaderOptions {
3
+ /**
4
+ * Chunk size in MB. Must be >=5MB (enforced by AWS).
5
+ */
6
+ chunkSize?: number;
7
+ /**
8
+ * Number of parallel uploads. Must be >=5 && <=15.
9
+ */
10
+ parallelUploads?: number;
11
+ }
12
+ interface OnProgressCallback {
13
+ (params: {
14
+ sent: number;
15
+ total: number;
16
+ percentage: number;
17
+ }): void;
18
+ }
19
+ interface OnErrorCallback {
20
+ (error: Error): void;
21
+ }
22
+ export declare class MultiPartUploader {
23
+ private readonly api;
24
+ private readonly chunkSize;
25
+ private readonly parallelUploads;
26
+ private readonly activeConnections;
27
+ private readonly progressTracker;
28
+ private upload;
29
+ private file;
30
+ private onErrorFn;
31
+ private onProgressFn;
32
+ constructor(api: MultiPartUploadAPI, options?: MultiPartUploaderOptions);
33
+ uploadFile(file: File): Promise<import("@webiny/app/types").UploadedFile>;
34
+ onProgress(onProgress: OnProgressCallback): this;
35
+ onError(onError: OnErrorCallback): this;
36
+ private complete;
37
+ private sendCompleteRequest;
38
+ private progressListener;
39
+ private uploadNextPart;
40
+ private uploadPart;
41
+ private assertIsDefined;
42
+ }
43
+ export {};
@@ -0,0 +1,165 @@
1
+ import pRetry from "p-retry";
2
+ export class MultiPartUploader {
3
+ activeConnections = new Map();
4
+ progressTracker = new Map();
5
+ onErrorFn = error => console.error(error);
6
+ constructor(api, options = {}) {
7
+ this.api = api;
8
+ const chunkSize = options.chunkSize || 50;
9
+ const parallelUploads = options.parallelUploads || 5;
10
+ this.chunkSize = Math.max(1024 * 1024 * chunkSize, 1024 * 1024 * 5);
11
+ this.parallelUploads = Math.min(parallelUploads, 15);
12
+ }
13
+ async uploadFile(file) {
14
+ this.file = file;
15
+ const numberOfParts = Math.ceil(file.size / this.chunkSize);
16
+ try {
17
+ /**
18
+ * Initialize the file upload on AWS S3.
19
+ */
20
+ this.upload = await this.api.createUpload({
21
+ data: {
22
+ name: file.name,
23
+ size: file.size,
24
+ type: file.type
25
+ },
26
+ numberOfParts
27
+ });
28
+
29
+ /**
30
+ * Run the defined number of parallel uploads. Each thread will continue to process parts
31
+ * for as long as there are parts to upload. The promise will resolve once there's no more parts to upload.
32
+ */
33
+ const threads = Math.min(numberOfParts, this.parallelUploads);
34
+ await Promise.all(Array.from({
35
+ length: threads
36
+ }).map(() => this.uploadNextPart()));
37
+ await this.complete();
38
+ return this.upload.file;
39
+ } catch (error) {
40
+ await this.complete(error);
41
+ throw error;
42
+ }
43
+ }
44
+ onProgress(onProgress) {
45
+ this.onProgressFn = onProgress;
46
+ return this;
47
+ }
48
+ onError(onError) {
49
+ this.onErrorFn = onError;
50
+ return this;
51
+ }
52
+ async complete(error) {
53
+ if (error) {
54
+ this.onErrorFn(error);
55
+ return;
56
+ }
57
+ try {
58
+ await this.sendCompleteRequest();
59
+ } catch (error) {
60
+ this.onErrorFn(error);
61
+ }
62
+ }
63
+ async sendCompleteRequest() {
64
+ this.assertIsDefined(this.upload, `Upload must be created before calling "sendCompleteRequest"!`);
65
+ return this.api.completeUpload({
66
+ fileKey: this.upload.file.key,
67
+ uploadId: this.upload.uploadId
68
+ });
69
+ }
70
+ progressListener(part, event) {
71
+ if (!this.file) {
72
+ return;
73
+ }
74
+ this.progressTracker.set(part.partNumber, event.loaded);
75
+ const uploaded = Array.from(this.progressTracker.values()).reduce((sum = 0, value) => sum + value);
76
+ const uploadedSize = Math.min(uploaded, this.file.size);
77
+ if (this.onProgressFn) {
78
+ try {
79
+ this.onProgressFn({
80
+ sent: uploadedSize,
81
+ total: this.file.size,
82
+ percentage: Math.round(uploadedSize / this.file.size * 100)
83
+ });
84
+ } catch (err) {
85
+ console.error(`Error executing the "onProgress" callback`, err);
86
+ }
87
+ }
88
+ }
89
+ async uploadNextPart() {
90
+ if (!this.upload) {
91
+ return;
92
+ }
93
+ const part = this.upload.parts.shift();
94
+ if (!part) {
95
+ return;
96
+ }
97
+ return executeWithRetry(() => this.uploadPart(part)).then(() => this.uploadNextPart());
98
+ }
99
+ uploadPart(part) {
100
+ this.assertIsDefined(this.upload, `Upload must be created before calling "sendCompleteRequest"!`);
101
+ this.assertIsDefined(this.file, `File must be set before calling "uploadPart"!`);
102
+ const sentSize = (part.partNumber - 1) * this.chunkSize;
103
+ const nextChunkSize = Math.min(sentSize + this.chunkSize, this.file.size);
104
+ const chunk = this.file.slice(sentSize, nextChunkSize, this.upload.file.type);
105
+ console.log(`Chunk for part #${part.partNumber}`, chunk.size);
106
+ return new Promise((resolve, reject) => {
107
+ const throwXHRError = error => {
108
+ this.activeConnections.delete(part.partNumber);
109
+ reject(error);
110
+ };
111
+ if (!window.navigator.onLine) {
112
+ return reject(new Error("Browser is offline!"));
113
+ }
114
+ const xhr = new XMLHttpRequest();
115
+ this.activeConnections.set(part.partNumber, xhr);
116
+ const abortXHR = () => xhr.abort();
117
+ xhr.upload.addEventListener("progress", event => this.progressListener(part, event));
118
+ window.addEventListener("offline", abortXHR);
119
+ const removeListeners = () => {
120
+ window.removeEventListener("offline", abortXHR);
121
+ };
122
+ xhr.open("PUT", part.url);
123
+ xhr.onreadystatechange = () => {
124
+ if (xhr.readyState === 4 && xhr.status === 200) {
125
+ try {
126
+ this.activeConnections.delete(part.partNumber);
127
+ window.removeEventListener("offline", abortXHR);
128
+ resolve(xhr.status);
129
+ } catch (err) {
130
+ console.error(`Error in "onreadystatechange"`, err);
131
+ }
132
+ }
133
+ };
134
+ xhr.onerror = () => {
135
+ removeListeners();
136
+ throwXHRError(new Error(`Failed to upload file part #${part.partNumber}`));
137
+ };
138
+ xhr.ontimeout = () => {
139
+ removeListeners();
140
+ throwXHRError(new Error(`Request timed out for file part #${part.partNumber}!`));
141
+ };
142
+ xhr.onabort = () => {
143
+ removeListeners();
144
+ throwXHRError(new Error(`Upload was cancelled for part #${part.partNumber}!`));
145
+ };
146
+ xhr.send(chunk);
147
+ });
148
+ }
149
+ assertIsDefined(upload, message) {
150
+ if (!upload) {
151
+ throw new Error(message);
152
+ }
153
+ }
154
+ }
155
+ const executeWithRetry = (execute, options) => {
156
+ return pRetry(execute, {
157
+ maxRetryTime: 300000,
158
+ retries: 5,
159
+ minTimeout: 1500,
160
+ maxTimeout: 30000,
161
+ ...options
162
+ });
163
+ };
164
+
165
+ //# sourceMappingURL=MultiPartUploader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["pRetry","MultiPartUploader","activeConnections","Map","progressTracker","onErrorFn","error","console","constructor","api","options","chunkSize","parallelUploads","Math","max","min","uploadFile","file","numberOfParts","ceil","size","upload","createUpload","data","name","type","threads","Promise","all","Array","from","length","map","uploadNextPart","complete","onProgress","onProgressFn","onError","sendCompleteRequest","assertIsDefined","completeUpload","fileKey","key","uploadId","progressListener","part","event","set","partNumber","loaded","uploaded","values","reduce","sum","value","uploadedSize","sent","total","percentage","round","err","parts","shift","executeWithRetry","uploadPart","then","sentSize","nextChunkSize","chunk","slice","log","resolve","reject","throwXHRError","delete","window","navigator","onLine","Error","xhr","XMLHttpRequest","abortXHR","abort","addEventListener","removeListeners","removeEventListener","open","url","onreadystatechange","readyState","status","onerror","ontimeout","onabort","send","message","execute","maxRetryTime","retries","minTimeout","maxTimeout"],"sources":["MultiPartUploader.ts"],"sourcesContent":["import pRetry from \"p-retry\";\nimport type { MultiPartUpload, MultiPartUploadAPI, FilePart } from \"./MultiPartUploadAPI\";\n\ninterface MultiPartUploaderOptions {\n /**\n * Chunk size in MB. Must be >=5MB (enforced by AWS).\n */\n chunkSize?: number;\n /**\n * Number of parallel uploads. Must be >=5 && <=15.\n */\n parallelUploads?: number;\n}\n\ninterface OnProgressCallback {\n (params: { sent: number; total: number; percentage: number }): void;\n}\n\ninterface OnErrorCallback {\n (error: Error): void;\n}\n\nexport class MultiPartUploader {\n private readonly api: MultiPartUploadAPI;\n private readonly chunkSize: number;\n private readonly parallelUploads: number;\n private readonly activeConnections: Map<number, XMLHttpRequest> = new Map();\n private readonly progressTracker: Map<number, number> = new Map();\n private upload: MultiPartUpload | undefined;\n private file: File | undefined;\n private onErrorFn: OnErrorCallback = error => console.error(error);\n private onProgressFn: OnProgressCallback | undefined;\n\n constructor(api: MultiPartUploadAPI, options: MultiPartUploaderOptions = {}) {\n this.api = api;\n const chunkSize = options.chunkSize || 50;\n const parallelUploads = options.parallelUploads || 5;\n\n this.chunkSize = Math.max(1024 * 1024 * chunkSize, 1024 * 1024 * 5);\n this.parallelUploads = Math.min(parallelUploads, 15);\n }\n\n async uploadFile(file: File) {\n this.file = file;\n const numberOfParts = Math.ceil(file.size / this.chunkSize);\n\n try {\n /**\n * Initialize the file upload on AWS S3.\n */\n this.upload = await this.api.createUpload({\n data: { name: file.name, size: file.size, type: file.type },\n numberOfParts\n });\n\n /**\n * Run the defined number of parallel uploads. Each thread will continue to process parts\n * for as long as there are parts to upload. The promise will resolve once there's no more parts to upload.\n */\n const threads = Math.min(numberOfParts, this.parallelUploads);\n await Promise.all(Array.from({ length: threads }).map(() => this.uploadNextPart()));\n\n await this.complete();\n\n return this.upload.file;\n } catch (error) {\n await this.complete(error);\n throw error;\n }\n }\n\n onProgress(onProgress: OnProgressCallback) {\n this.onProgressFn = onProgress;\n return this;\n }\n\n onError(onError: OnErrorCallback) {\n this.onErrorFn = onError;\n return this;\n }\n\n private async complete(error?: Error) {\n if (error) {\n this.onErrorFn(error);\n return;\n }\n\n try {\n await this.sendCompleteRequest();\n } catch (error) {\n this.onErrorFn(error);\n }\n }\n\n private async sendCompleteRequest() {\n this.assertIsDefined(\n this.upload,\n `Upload must be created before calling \"sendCompleteRequest\"!`\n );\n\n return this.api.completeUpload({\n fileKey: this.upload.file.key,\n uploadId: this.upload.uploadId\n });\n }\n\n private progressListener(part: FilePart, event: ProgressEvent<XMLHttpRequestEventTarget>) {\n if (!this.file) {\n return;\n }\n\n this.progressTracker.set(part.partNumber, event.loaded);\n\n const uploaded = Array.from(this.progressTracker.values()).reduce(\n (sum = 0, value) => sum + value\n );\n\n const uploadedSize = Math.min(uploaded, this.file.size);\n\n if (this.onProgressFn) {\n try {\n this.onProgressFn({\n sent: uploadedSize,\n total: this.file.size,\n percentage: Math.round((uploadedSize / this.file.size) * 100)\n });\n } catch (err) {\n console.error(`Error executing the \"onProgress\" callback`, err);\n }\n }\n }\n\n private async uploadNextPart(): Promise<void> {\n if (!this.upload) {\n return;\n }\n\n const part = this.upload.parts.shift();\n\n if (!part) {\n return;\n }\n\n return executeWithRetry(() => this.uploadPart(part)).then(() => this.uploadNextPart());\n }\n\n private uploadPart(part: FilePart) {\n this.assertIsDefined(\n this.upload,\n `Upload must be created before calling \"sendCompleteRequest\"!`\n );\n\n this.assertIsDefined(this.file, `File must be set before calling \"uploadPart\"!`);\n\n const sentSize = (part.partNumber - 1) * this.chunkSize;\n const nextChunkSize = Math.min(sentSize + this.chunkSize, this.file.size);\n const chunk = this.file.slice(sentSize, nextChunkSize, this.upload.file.type);\n console.log(`Chunk for part #${part.partNumber}`, chunk.size);\n\n return new Promise((resolve, reject) => {\n const throwXHRError = (error: Error) => {\n this.activeConnections.delete(part.partNumber);\n reject(error);\n };\n\n if (!window.navigator.onLine) {\n return reject(new Error(\"Browser is offline!\"));\n }\n\n const xhr = new XMLHttpRequest();\n this.activeConnections.set(part.partNumber, xhr);\n const abortXHR = () => xhr.abort();\n\n xhr.upload.addEventListener(\"progress\", event => this.progressListener(part, event));\n\n window.addEventListener(\"offline\", abortXHR);\n const removeListeners = () => {\n window.removeEventListener(\"offline\", abortXHR);\n };\n\n xhr.open(\"PUT\", part.url);\n\n xhr.onreadystatechange = () => {\n if (xhr.readyState === 4 && xhr.status === 200) {\n try {\n this.activeConnections.delete(part.partNumber);\n window.removeEventListener(\"offline\", abortXHR);\n resolve(xhr.status);\n } catch (err) {\n console.error(`Error in \"onreadystatechange\"`, err);\n }\n }\n };\n\n xhr.onerror = () => {\n removeListeners();\n throwXHRError(new Error(`Failed to upload file part #${part.partNumber}`));\n };\n xhr.ontimeout = () => {\n removeListeners();\n throwXHRError(new Error(`Request timed out for file part #${part.partNumber}!`));\n };\n xhr.onabort = () => {\n removeListeners();\n throwXHRError(new Error(`Upload was cancelled for part #${part.partNumber}!`));\n };\n xhr.send(chunk);\n });\n }\n\n private assertIsDefined<T>(upload: T, message: string): asserts upload is NonNullable<T> {\n if (!upload) {\n throw new Error(message);\n }\n }\n}\n\nconst executeWithRetry = (execute: () => void, options?: Parameters<typeof pRetry>[1]) => {\n return pRetry(execute, {\n maxRetryTime: 300000,\n retries: 5,\n minTimeout: 1500,\n maxTimeout: 30000,\n ...options\n });\n};\n"],"mappings":"AAAA,OAAOA,MAAM,MAAM,SAAS;AAsB5B,OAAO,MAAMC,iBAAiB,CAAC;EAIVC,iBAAiB,GAAgC,IAAIC,GAAG,CAAC,CAAC;EAC1DC,eAAe,GAAwB,IAAID,GAAG,CAAC,CAAC;EAGzDE,SAAS,GAAoBC,KAAK,IAAIC,OAAO,CAACD,KAAK,CAACA,KAAK,CAAC;EAGlEE,WAAWA,CAACC,GAAuB,EAAEC,OAAiC,GAAG,CAAC,CAAC,EAAE;IACzE,IAAI,CAACD,GAAG,GAAGA,GAAG;IACd,MAAME,SAAS,GAAGD,OAAO,CAACC,SAAS,IAAI,EAAE;IACzC,MAAMC,eAAe,GAAGF,OAAO,CAACE,eAAe,IAAI,CAAC;IAEpD,IAAI,CAACD,SAAS,GAAGE,IAAI,CAACC,GAAG,CAAC,IAAI,GAAG,IAAI,GAAGH,SAAS,EAAE,IAAI,GAAG,IAAI,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O,CAACQ,GAAG,CAACW,MAAM,CAAC;UACvB,CAAC,CAAC,OAAO9B,GAAG,EAAE;YACVrD,OAAO,CAACD,KAAK,CAAC,+BAA+B,EAAEsD,GAAG,CAAC;UACvD;QACJ;MACJ,CAAC;MAEDmB,GAAG,CAACY,OAAO,GAAG,MAAM;QAChBP,eAAe,CAAC,CAAC;QACjBX,aAAa,CAAC,IAAIK,KAAK,CAAC,+BAA+BjC,IAAI,CAACG,UAAU,EAAE,CAAC,CAAC;MAC9E,CAAC;MACD+B,GAAG,CAACa,SAAS,GAAG,MAAM;QAClBR,eAAe,CAAC,CAAC;QACjBX,aAAa,CAAC,IAAIK,KAAK,CAAC,oCAAoCjC,IAAI,CAACG,UAAU,GAAG,CAAC,CAAC;MACpF,CAAC;MACD+B,GAAG,CAACc,OAAO,GAAG,MAAM;QAChBT,eAAe,CAAC,CAAC;QACjBX,aAAa,CAAC,IAAIK,KAAK,CAAC,kCAAkCjC,IAAI,CAACG,UAAU,GAAG,CAAC,CAAC;MAClF,CAAC;MACD+B,GAAG,CAACe,IAAI,CAAC1B,KAAK,CAAC;IACnB,CAAC,CAAC;EACN;EAEQ7B,eAAeA,CAAIlB,MAAS,EAAE0E,OAAe,EAAoC;IACrF,IAAI,CAAC1E,MAAM,EAAE;MACT,MAAM,IAAIyD,KAAK,CAACiB,OAAO,CAAC;IAC5B;EACJ;AACJ;AAEA,MAAMhC,gBAAgB,GAAGA,CAACiC,OAAmB,EAAEtF,OAAsC,KAAK;EACtF,OAAOV,MAAM,CAACgG,OAAO,EAAE;IACnBC,YAAY,EAAE,MAAM;IACpBC,OAAO,EAAE,CAAC;IACVC,UAAU,EAAE,IAAI;IAChBC,UAAU,EAAE,KAAK;IACjB,GAAG1F;EACP,CAAC,CAAC;AACN,CAAC","ignoreList":[]}
@@ -0,0 +1,11 @@
1
+ import type { UploadedFile, UploadOptions } from "@webiny/app/types";
2
+ import type { FileUploadStrategy } from "./index";
3
+ declare global {
4
+ interface File {
5
+ key?: string;
6
+ keyPrefix?: string;
7
+ }
8
+ }
9
+ export declare class SimpleUploadStrategy implements FileUploadStrategy {
10
+ upload(file: File, { apolloClient, onProgress }: UploadOptions): Promise<UploadedFile>;
11
+ }
@@ -0,0 +1,59 @@
1
+ import { GET_PRE_SIGNED_POST_PAYLOAD } from "./graphql";
2
+ export class SimpleUploadStrategy {
3
+ async upload(file, {
4
+ apolloClient,
5
+ onProgress
6
+ }) {
7
+ // 1. GET PreSignedPostPayload
8
+ const response = await apolloClient.query({
9
+ query: GET_PRE_SIGNED_POST_PAYLOAD,
10
+ fetchPolicy: "no-cache",
11
+ variables: {
12
+ data: {
13
+ size: file.size,
14
+ name: file.name,
15
+ type: file.type,
16
+ key: file.key,
17
+ keyPrefix: file.keyPrefix
18
+ }
19
+ }
20
+ });
21
+ const {
22
+ getPreSignedPostPayload
23
+ } = response.data.fileManager;
24
+ if (getPreSignedPostPayload.error) {
25
+ console.error(getPreSignedPostPayload);
26
+ throw Error(getPreSignedPostPayload.error);
27
+ }
28
+
29
+ // 2. upload file to S3
30
+ return new Promise((resolve, reject) => {
31
+ const formData = new window.FormData();
32
+ Object.keys(getPreSignedPostPayload.data.data.fields).forEach(key => {
33
+ formData.append(key, getPreSignedPostPayload.data.data.fields[key]);
34
+ });
35
+ formData.append("file", file);
36
+ const xhr = new window.XMLHttpRequest();
37
+ xhr.upload.addEventListener("progress", event => {
38
+ if (onProgress) {
39
+ onProgress({
40
+ sent: event.loaded,
41
+ total: file.size,
42
+ percentage: event.loaded / file.size * 100
43
+ });
44
+ }
45
+ }, false);
46
+ xhr.open("POST", getPreSignedPostPayload.data.data.url, true);
47
+ xhr.send(formData);
48
+ xhr.onload = function () {
49
+ if (this.status === 204) {
50
+ resolve(getPreSignedPostPayload.data.file);
51
+ return;
52
+ }
53
+ reject(this.responseText);
54
+ };
55
+ });
56
+ }
57
+ }
58
+
59
+ //# sourceMappingURL=SimpleUploadStrategy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["GET_PRE_SIGNED_POST_PAYLOAD","SimpleUploadStrategy","upload","file","apolloClient","onProgress","response","query","fetchPolicy","variables","data","size","name","type","key","keyPrefix","getPreSignedPostPayload","fileManager","error","console","Error","Promise","resolve","reject","formData","window","FormData","Object","keys","fields","forEach","append","xhr","XMLHttpRequest","addEventListener","event","sent","loaded","total","percentage","open","url","send","onload","status","responseText"],"sources":["SimpleUploadStrategy.ts"],"sourcesContent":["import type { UploadedFile, UploadOptions } from \"@webiny/app/types\";\nimport { GET_PRE_SIGNED_POST_PAYLOAD } from \"./graphql\";\nimport type { FileUploadStrategy } from \"~/index\";\n\ndeclare global {\n interface File {\n key?: string;\n keyPrefix?: string;\n }\n}\n\nexport class SimpleUploadStrategy implements FileUploadStrategy {\n async upload(file: File, { apolloClient, onProgress }: UploadOptions): Promise<UploadedFile> {\n // 1. GET PreSignedPostPayload\n const response = await apolloClient.query({\n query: GET_PRE_SIGNED_POST_PAYLOAD,\n fetchPolicy: \"no-cache\",\n variables: {\n data: {\n size: file.size,\n name: file.name,\n type: file.type,\n key: file.key,\n keyPrefix: file.keyPrefix\n }\n }\n });\n\n const { getPreSignedPostPayload } = response.data.fileManager;\n if (getPreSignedPostPayload.error) {\n console.error(getPreSignedPostPayload);\n throw Error(getPreSignedPostPayload.error);\n }\n\n // 2. upload file to S3\n return new Promise((resolve, reject) => {\n const formData = new window.FormData();\n Object.keys(getPreSignedPostPayload.data.data.fields).forEach(key => {\n formData.append(key, getPreSignedPostPayload.data.data.fields[key]);\n });\n\n formData.append(\"file\", file);\n\n const xhr = new window.XMLHttpRequest();\n xhr.upload.addEventListener(\n \"progress\",\n event => {\n if (onProgress) {\n onProgress({\n sent: event.loaded,\n total: file.size,\n percentage: (event.loaded / file.size) * 100\n });\n }\n },\n false\n );\n xhr.open(\"POST\", getPreSignedPostPayload.data.data.url, true);\n xhr.send(formData);\n xhr.onload = function () {\n if (this.status === 204) {\n resolve(getPreSignedPostPayload.data.file);\n return;\n }\n\n reject(this.responseText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AACQ,cAAc,CAAC,CAAC;MACvCD,GAAG,CAAC9B,MAAM,CAACgC,gBAAgB,CACvB,UAAU,EACVC,KAAK,IAAI;QACL,IAAI9B,UAAU,EAAE;UACZA,UAAU,CAAC;YACP+B,IAAI,EAAED,KAAK,CAACE,MAAM;YAClBC,KAAK,EAAEnC,IAAI,CAACQ,IAAI;YAChB4B,UAAU,EAAGJ,KAAK,CAACE,MAAM,GAAGlC,IAAI,CAACQ,IAAI,GAAI;UAC7C,CAAC,CAAC;QACN;MACJ,CAAC,EACD,KACJ,CAAC;MACDqB,GAAG,CAACQ,IAAI,CAAC,MAAM,EAAExB,uBAAuB,CAACN,IAAI,CAACA,IAAI,CAAC+B,GAAG,EAAE,IAAI,CAAC;MAC7DT,GAAG,CAACU,IAAI,CAAClB,QAAQ,CAAC;MAClBQ,GAAG,CAACW,MAAM,GAAG,YAAY;QACrB,IAAI,IAAI,CAACC,MAAM,KAAK,GAAG,EAAE;UACrBtB,OAAO,CAACN,uBAAuB,CAACN,IAAI,CAACP,IAAI,CAAC;UAC1C;QACJ;QAEAoB,MAAM,CAAC,IAAI,CAACsB,YAAY,CAAC;MAC7B,CAAC;IACL,CAAC,CAAC;EACN;AACJ","ignoreList":[]}
package/graphql.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare const GET_PRE_SIGNED_POST_PAYLOAD: import("graphql").DocumentNode;
package/graphql.js ADDED
@@ -0,0 +1,24 @@
1
+ import gql from "graphql-tag";
2
+ export const GET_PRE_SIGNED_POST_PAYLOAD = gql`
3
+ query getPreSignedPostPayload($data: PreSignedPostPayloadInput!) {
4
+ fileManager {
5
+ getPreSignedPostPayload(data: $data) {
6
+ data {
7
+ data
8
+ file {
9
+ id
10
+ type
11
+ name
12
+ size
13
+ key
14
+ }
15
+ }
16
+ error {
17
+ message
18
+ }
19
+ }
20
+ }
21
+ }
22
+ `;
23
+
24
+ //# sourceMappingURL=graphql.js.map
package/graphql.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"names":["gql","GET_PRE_SIGNED_POST_PAYLOAD"],"sources":["graphql.ts"],"sourcesContent":["import gql from \"graphql-tag\";\n\nexport const GET_PRE_SIGNED_POST_PAYLOAD = gql`\n query getPreSignedPostPayload($data: PreSignedPostPayloadInput!) {\n fileManager {\n getPreSignedPostPayload(data: $data) {\n data {\n data\n file {\n id\n type\n name\n size\n key\n }\n }\n error {\n message\n }\n }\n }\n }\n`;\n"],"mappings":"AAAA,OAAOA,GAAG,MAAM,aAAa;AAE7B,OAAO,MAAMC,2BAA2B,GAAGD,GAAG;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC","ignoreList":[]}
package/index.d.ts CHANGED
@@ -1,3 +1,6 @@
1
- import { AppFileManagerStorageS3 } from "./types";
2
- declare const _default: () => AppFileManagerStorageS3;
1
+ import type { FileUploaderPlugin } from "@webiny/app/types";
2
+ export interface FileUploadStrategy {
3
+ upload: FileUploaderPlugin["upload"];
4
+ }
5
+ declare const _default: () => FileUploaderPlugin;
3
6
  export default _default;
package/index.js CHANGED
@@ -1,89 +1,19 @@
1
- import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
2
- import _taggedTemplateLiteral from "@babel/runtime/helpers/taggedTemplateLiteral";
3
-
4
- var _templateObject;
5
-
6
- import _regeneratorRuntime from "@babel/runtime/regenerator";
7
- import gql from "graphql-tag";
8
- var GET_PRE_SIGNED_POST_PAYLOAD = gql(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n query getPreSignedPostPayload($data: PreSignedPostPayloadInput!) {\n fileManager {\n getPreSignedPostPayload(data: $data) {\n data {\n data\n file {\n type\n name\n size\n key\n }\n }\n error {\n message\n }\n }\n }\n }\n"])));
9
- export default (function () {
10
- return {
11
- type: "app-file-manager-storage",
12
- name: "app-file-manager-storage",
13
- upload: function () {
14
- var _upload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(file, _ref) {
15
- var apolloClient, response, getPreSignedPostPayload;
16
- return _regeneratorRuntime.wrap(function _callee$(_context) {
17
- while (1) {
18
- switch (_context.prev = _context.next) {
19
- case 0:
20
- apolloClient = _ref.apolloClient;
21
- _context.next = 3;
22
- return apolloClient.query({
23
- query: GET_PRE_SIGNED_POST_PAYLOAD,
24
- fetchPolicy: "no-cache",
25
- variables: {
26
- data: {
27
- size: file.size,
28
- name: file.name,
29
- type: file.type
30
- }
31
- }
32
- });
33
-
34
- case 3:
35
- response = _context.sent;
36
- getPreSignedPostPayload = response.data.fileManager.getPreSignedPostPayload;
37
-
38
- if (!getPreSignedPostPayload.error) {
39
- _context.next = 8;
40
- break;
41
- }
42
-
43
- console.log(getPreSignedPostPayload); // eslint-disable-line
44
-
45
- return _context.abrupt("return");
46
-
47
- case 8:
48
- _context.next = 10;
49
- return new Promise(function (resolve, reject) {
50
- var formData = new window.FormData();
51
- Object.keys(getPreSignedPostPayload.data.data.fields).forEach(function (key) {
52
- formData.append(key, getPreSignedPostPayload.data.data.fields[key]);
53
- });
54
- formData.append("file", file);
55
- var xhr = new window.XMLHttpRequest(); // eslint-disable-line
56
-
57
- // eslint-disable-line
58
- xhr.open("POST", getPreSignedPostPayload.data.data.url, true);
59
- xhr.send(formData);
60
-
61
- xhr.onload = function () {
62
- if (this.status === 204) {
63
- resolve(getPreSignedPostPayload.data.file);
64
- return;
65
- }
66
-
67
- reject(this.responseText);
68
- };
69
- });
70
-
71
- case 10:
72
- return _context.abrupt("return", _context.sent);
73
-
74
- case 11:
75
- case "end":
76
- return _context.stop();
77
- }
78
- }
79
- }, _callee);
80
- }));
81
-
82
- function upload(_x, _x2) {
83
- return _upload.apply(this, arguments);
84
- }
85
-
86
- return upload;
87
- }()
88
- };
89
- });
1
+ import { SimpleUploadStrategy } from "./SimpleUploadStrategy";
2
+ import { MultiPartUploadStrategy } from "./MultiPartUploadStrategy";
3
+ export default () => {
4
+ class S3FileUploader {
5
+ type = "file-uploader";
6
+ name = "file-uploader";
7
+ upload(file, options) {
8
+ // Use "simple" strategy for files smaller than ~100MB
9
+ // @ts-expect-error
10
+ const multiPartThreshold = window["fmUploadMultiPartThreshold"] ?? 100;
11
+ const simple = file.size < multiPartThreshold * 1024 * 1024;
12
+ const strategy = simple ? new SimpleUploadStrategy() : new MultiPartUploadStrategy();
13
+ return strategy.upload(file, options);
14
+ }
15
+ }
16
+ return new S3FileUploader();
17
+ };
18
+
19
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"names":["SimpleUploadStrategy","MultiPartUploadStrategy","S3FileUploader","type","name","upload","file","options","multiPartThreshold","window","simple","size","strategy"],"sources":["index.ts"],"sourcesContent":["import type { FileUploaderPlugin, UploadOptions } from \"@webiny/app/types\";\nimport { SimpleUploadStrategy } from \"~/SimpleUploadStrategy\";\nimport { MultiPartUploadStrategy } from \"~/MultiPartUploadStrategy\";\n\nexport interface FileUploadStrategy {\n upload: FileUploaderPlugin[\"upload\"];\n}\n\nexport default (): FileUploaderPlugin => {\n class S3FileUploader implements FileUploaderPlugin {\n public readonly type = \"file-uploader\";\n public readonly name = \"file-uploader\";\n\n upload(file: File, options: UploadOptions) {\n // Use \"simple\" strategy for files smaller than ~100MB\n // @ts-expect-error\n const multiPartThreshold = window[\"fmUploadMultiPartThreshold\"] ?? 100;\n const simple = file.size < multiPartThreshold * 1024 * 1024;\n\n const strategy: FileUploadStrategy = simple\n ? new SimpleUploadStrategy()\n : new MultiPartUploadStrategy();\n\n return strategy.upload(file, options);\n }\n }\n\n return new S3FileUploader();\n};\n"],"mappings":"AACA,SAASA,oBAAoB;AAC7B,SAASC,uBAAuB;AAMhC,eAAe,MAA0B;EACrC,MAAMC,cAAc,CAA+B;IAC/BC,IAAI,GAAG,eAAe;IACtBC,IAAI,GAAG,eAAe;IAEtCC,MAAMA,CAACC,IAAU,EAAEC,OAAsB,EAAE;MACvC;MACA;MACA,MAAMC,kBAAkB,GAAGC,MAAM,CAAC,4BAA4B,CAAC,IAAI,GAAG;MACtE,MAAMC,MAAM,GAAGJ,IAAI,CAACK,IAAI,GAAGH,kBAAkB,GAAG,IAAI,GAAG,IAAI;MAE3D,MAAMI,QAA4B,GAAGF,MAAM,GACrC,IAAIV,oBAAoB,CAAC,CAAC,GAC1B,IAAIC,uBAAuB,CAAC,CAAC;MAEnC,OAAOW,QAAQ,CAACP,MAAM,CAACC,IAAI,EAAEC,OAAO,CAAC;IACzC;EACJ;EAEA,OAAO,IAAIL,cAAc,CAAC,CAAC;AAC/B,CAAC","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webiny/app-file-manager-s3",
3
- "version": "0.0.0-mt-3",
3
+ "version": "0.0.0-unstable.06b2ede40f",
4
4
  "main": "index.js",
5
5
  "repository": {
6
6
  "type": "git",
@@ -10,26 +10,22 @@
10
10
  "author": "Webiny Ltd",
11
11
  "license": "MIT",
12
12
  "dependencies": {
13
- "@webiny/plugins": "0.0.0-mt-3",
14
- "apollo-client": "2.6.10",
15
- "graphql": "14.7.0",
16
- "graphql-tag": "2.12.5"
13
+ "@webiny/app": "0.0.0-unstable.06b2ede40f",
14
+ "graphql-tag": "2.12.6",
15
+ "p-retry": "4.6.2"
17
16
  },
18
17
  "devDependencies": {
19
- "@babel/cli": "^7.5.5",
20
- "@babel/core": "^7.5.5",
21
- "@webiny/cli": "^0.0.0-mt-3",
22
- "@webiny/project-utils": "^0.0.0-mt-3",
23
- "rimraf": "^3.0.2",
24
- "typescript": "^4.1.3"
18
+ "@webiny/project-utils": "0.0.0-unstable.06b2ede40f",
19
+ "rimraf": "6.0.1",
20
+ "typescript": "5.3.3"
25
21
  },
26
22
  "publishConfig": {
27
23
  "access": "public",
28
24
  "directory": "dist"
29
25
  },
30
26
  "scripts": {
31
- "build": "yarn webiny run build",
32
- "watch": "yarn webiny run watch"
27
+ "build": "node ../cli/bin.js run build",
28
+ "watch": "node ../cli/bin.js run watch"
33
29
  },
34
- "gitHead": "ebea815be2be99404591cba465cc1fe88355bd48"
30
+ "gitHead": "06b2ede40fc2212a70eeafd74afd50b56fb0ce82"
35
31
  }
package/types.d.ts DELETED
@@ -1,9 +0,0 @@
1
- import { Plugin } from "@webiny/plugins/types";
2
- import { ApolloClient } from "apollo-client";
3
- export declare type AppFileManagerStorageS3 = Plugin & {
4
- type: "app-file-manager-storage";
5
- name: "app-file-manager-storage";
6
- upload(file: File, options: {
7
- apolloClient: ApolloClient<Record<string, any>>;
8
- }): Promise<any>;
9
- };
package/types.js DELETED
@@ -1 +0,0 @@
1
- export {};