@edgestore/react 0.6.0-canary.2 → 0.6.0

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/dist/index.js CHANGED
@@ -1,488 +1,7 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
3
+ var contextProvider = require('./contextProvider.js');
4
4
 
5
- var React = require('react');
6
- var shared = require('@edgestore/shared');
7
- var uploadAbortedError = require('./uploadAbortedError-fbfcc57b.js');
8
5
 
9
- function _interopNamespace(e) {
10
- if (e && e.__esModule) return e;
11
- var n = Object.create(null);
12
- if (e) {
13
- Object.keys(e).forEach(function (k) {
14
- if (k !== 'default') {
15
- var d = Object.getOwnPropertyDescriptor(e, k);
16
- Object.defineProperty(n, k, d.get ? d : {
17
- enumerable: true,
18
- get: function () { return e[k]; }
19
- });
20
- }
21
- });
22
- }
23
- n["default"] = e;
24
- return Object.freeze(n);
25
- }
26
6
 
27
- var React__namespace = /*#__PURE__*/_interopNamespace(React);
28
-
29
- class EdgeStoreClientError extends Error {
30
- constructor(message){
31
- super(message);
32
- this.name = 'EdgeStoreError';
33
- }
34
- }
35
-
36
- async function handleError(res) {
37
- let json = {};
38
- try {
39
- json = await res.json();
40
- } catch (err) {
41
- throw new EdgeStoreClientError(`Failed to parse response. Make sure the api is correctly configured at ${res.url}`);
42
- }
43
- throw new shared.EdgeStoreApiClientError({
44
- response: json
45
- });
46
- }
47
-
48
- function createNextProxy({ apiPath, uploadingCountRef, maxConcurrentUploads = 5, disableDevProxy }) {
49
- return new Proxy({}, {
50
- get (_, prop) {
51
- const bucketName = prop;
52
- const bucketFunctions = {
53
- upload: async (params)=>{
54
- try {
55
- params.onProgressChange?.(0);
56
- // This handles the case where the user cancels the upload while it's waiting in the queue
57
- const abortPromise = new Promise((resolve)=>{
58
- params.signal?.addEventListener('abort', ()=>{
59
- resolve();
60
- }, {
61
- once: true
62
- });
63
- });
64
- while(uploadingCountRef.current >= maxConcurrentUploads && uploadingCountRef.current > 0){
65
- await Promise.race([
66
- new Promise((resolve)=>setTimeout(resolve, 300)),
67
- abortPromise
68
- ]);
69
- if (params.signal?.aborted) {
70
- throw new uploadAbortedError.UploadAbortedError('File upload aborted');
71
- }
72
- }
73
- uploadingCountRef.current++;
74
- const fileInfo = await uploadFile(params, {
75
- bucketName: bucketName,
76
- apiPath
77
- }, disableDevProxy);
78
- return fileInfo;
79
- } finally{
80
- uploadingCountRef.current--;
81
- }
82
- },
83
- confirmUpload: async (params)=>{
84
- const { success } = await confirmUpload(params, {
85
- bucketName: bucketName,
86
- apiPath
87
- });
88
- if (!success) {
89
- throw new EdgeStoreClientError('Failed to confirm upload');
90
- }
91
- },
92
- delete: async (params)=>{
93
- const { success } = await deleteFile(params, {
94
- bucketName: bucketName,
95
- apiPath
96
- });
97
- if (!success) {
98
- throw new EdgeStoreClientError('Failed to delete file');
99
- }
100
- }
101
- };
102
- return bucketFunctions;
103
- }
104
- });
105
- }
106
- async function uploadFile({ file, signal, input, onProgressChange, options }, { apiPath, bucketName }, disableDevProxy) {
107
- try {
108
- onProgressChange?.(0);
109
- const res = await fetch(`${apiPath}/request-upload`, {
110
- method: 'POST',
111
- credentials: 'include',
112
- signal: signal,
113
- body: JSON.stringify({
114
- bucketName,
115
- input,
116
- fileInfo: {
117
- extension: file.name.split('.').pop(),
118
- type: file.type,
119
- size: file.size,
120
- fileName: options?.manualFileName,
121
- replaceTargetUrl: options?.replaceTargetUrl,
122
- temporary: options?.temporary
123
- }
124
- }),
125
- headers: {
126
- 'Content-Type': 'application/json'
127
- }
128
- });
129
- if (!res.ok) {
130
- await handleError(res);
131
- }
132
- const json = await res.json();
133
- if ('multipart' in json) {
134
- await multipartUpload({
135
- bucketName,
136
- multipartInfo: json.multipart,
137
- onProgressChange,
138
- signal,
139
- file,
140
- apiPath
141
- });
142
- } else if ('uploadUrl' in json) {
143
- // Single part upload
144
- // Upload the file to the signed URL and get the progress
145
- await uploadFileInner({
146
- file,
147
- uploadUrl: json.uploadUrl,
148
- onProgressChange,
149
- signal
150
- });
151
- } else {
152
- throw new EdgeStoreClientError('An error occurred');
153
- }
154
- return {
155
- url: getUrl(json.accessUrl, apiPath, disableDevProxy),
156
- thumbnailUrl: json.thumbnailUrl ? getUrl(json.thumbnailUrl, apiPath, disableDevProxy) : null,
157
- size: json.size,
158
- uploadedAt: new Date(json.uploadedAt),
159
- path: json.path,
160
- pathOrder: json.pathOrder,
161
- metadata: json.metadata
162
- };
163
- } catch (e) {
164
- if (e instanceof Error && e.name === 'AbortError') {
165
- throw new uploadAbortedError.UploadAbortedError('File upload aborted');
166
- }
167
- onProgressChange?.(0);
168
- throw e;
169
- }
170
- }
171
- /**
172
- * Protected files need third-party cookies to work.
173
- * Since third party cookies don't work on localhost,
174
- * we need to proxy the file through the server.
175
- */ function getUrl(url, apiPath, disableDevProxy) {
176
- const mode = typeof process !== 'undefined' ? process.env.NODE_ENV : undefined?.DEV ? 'development' : 'production';
177
- if (mode === 'development' && !url.includes('/_public/') && !disableDevProxy) {
178
- const proxyUrl = new URL(window.location.origin);
179
- proxyUrl.pathname = `${apiPath}/proxy-file`;
180
- proxyUrl.search = new URLSearchParams({
181
- url
182
- }).toString();
183
- return proxyUrl.toString();
184
- }
185
- return url;
186
- }
187
- async function uploadFileInner(props) {
188
- const { file, uploadUrl, onProgressChange, signal } = props;
189
- const promise = new Promise((resolve, reject)=>{
190
- if (signal?.aborted) {
191
- reject(new uploadAbortedError.UploadAbortedError('File upload aborted'));
192
- return;
193
- }
194
- const request = new XMLHttpRequest();
195
- request.open('PUT', uploadUrl);
196
- // This is for Azure provider. Specifies the blob type
197
- request.setRequestHeader('x-ms-blob-type', 'BlockBlob');
198
- request.addEventListener('loadstart', ()=>{
199
- onProgressChange?.(0);
200
- });
201
- request.upload.addEventListener('progress', (e)=>{
202
- if (e.lengthComputable) {
203
- // 2 decimal progress
204
- const progress = Math.round(e.loaded / e.total * 10000) / 100;
205
- onProgressChange?.(progress);
206
- }
207
- });
208
- request.addEventListener('error', ()=>{
209
- reject(new Error('Error uploading file'));
210
- });
211
- request.addEventListener('abort', ()=>{
212
- reject(new uploadAbortedError.UploadAbortedError('File upload aborted'));
213
- });
214
- request.addEventListener('loadend', ()=>{
215
- // Return the ETag header (needed to complete multipart upload)
216
- resolve(request.getResponseHeader('ETag'));
217
- });
218
- if (signal) {
219
- signal.addEventListener('abort', ()=>{
220
- request.abort();
221
- });
222
- }
223
- request.send(file);
224
- });
225
- return promise;
226
- }
227
- async function multipartUpload(params) {
228
- const { bucketName, multipartInfo, onProgressChange, file, signal, apiPath } = params;
229
- const { partSize, parts, totalParts, uploadId, key } = multipartInfo;
230
- const uploadingParts = [];
231
- const uploadPart = async (params)=>{
232
- const { part, chunk } = params;
233
- const { uploadUrl } = part;
234
- const eTag = await uploadFileInner({
235
- file: chunk,
236
- uploadUrl,
237
- signal,
238
- onProgressChange: (progress)=>{
239
- const uploadingPart = uploadingParts.find((p)=>p.partNumber === part.partNumber);
240
- if (uploadingPart) {
241
- uploadingPart.progress = progress;
242
- } else {
243
- uploadingParts.push({
244
- partNumber: part.partNumber,
245
- progress
246
- });
247
- }
248
- const totalProgress = Math.round(uploadingParts.reduce((acc, p)=>acc + p.progress * 100, 0) / totalParts) / 100;
249
- onProgressChange?.(totalProgress);
250
- }
251
- });
252
- if (!eTag) {
253
- throw new EdgeStoreClientError('Could not get ETag from multipart response');
254
- }
255
- return {
256
- partNumber: part.partNumber,
257
- eTag
258
- };
259
- };
260
- // Upload the parts in parallel
261
- const completedParts = await queuedPromises({
262
- items: parts.map((part)=>({
263
- part,
264
- chunk: file.slice((part.partNumber - 1) * partSize, part.partNumber * partSize)
265
- })),
266
- fn: uploadPart,
267
- maxParallel: 5,
268
- maxRetries: 10
269
- });
270
- // Complete multipart upload
271
- const res = await fetch(`${apiPath}/complete-multipart-upload`, {
272
- method: 'POST',
273
- credentials: 'include',
274
- body: JSON.stringify({
275
- bucketName,
276
- uploadId,
277
- key,
278
- parts: completedParts
279
- }),
280
- headers: {
281
- 'Content-Type': 'application/json'
282
- }
283
- });
284
- if (!res.ok) {
285
- await handleError(res);
286
- }
287
- }
288
- async function confirmUpload({ url }, { apiPath, bucketName }) {
289
- const res = await fetch(`${apiPath}/confirm-upload`, {
290
- method: 'POST',
291
- credentials: 'include',
292
- body: JSON.stringify({
293
- url,
294
- bucketName
295
- }),
296
- headers: {
297
- 'Content-Type': 'application/json'
298
- }
299
- });
300
- if (!res.ok) {
301
- await handleError(res);
302
- }
303
- return res.json();
304
- }
305
- async function deleteFile({ url }, { apiPath, bucketName }) {
306
- const res = await fetch(`${apiPath}/delete-file`, {
307
- method: 'POST',
308
- credentials: 'include',
309
- body: JSON.stringify({
310
- url,
311
- bucketName
312
- }),
313
- headers: {
314
- 'Content-Type': 'application/json'
315
- }
316
- });
317
- if (!res.ok) {
318
- await handleError(res);
319
- }
320
- return res.json();
321
- }
322
- async function queuedPromises({ items, fn, maxParallel, maxRetries = 0 }) {
323
- const results = new Array(items.length);
324
- const executeWithRetry = async (func, retries)=>{
325
- try {
326
- return await func();
327
- } catch (error) {
328
- if (error instanceof uploadAbortedError.UploadAbortedError) {
329
- throw error;
330
- }
331
- if (retries > 0) {
332
- await new Promise((resolve)=>setTimeout(resolve, 5000));
333
- return executeWithRetry(func, retries - 1);
334
- } else {
335
- throw error;
336
- }
337
- }
338
- };
339
- const semaphore = {
340
- count: maxParallel,
341
- async wait () {
342
- // If we've reached our maximum concurrency, or it's the last item, wait
343
- while(this.count <= 0)await new Promise((resolve)=>setTimeout(resolve, 500));
344
- this.count--;
345
- },
346
- signal () {
347
- this.count++;
348
- }
349
- };
350
- const tasks = items.map((item, i)=>(async ()=>{
351
- await semaphore.wait();
352
- try {
353
- const result = await executeWithRetry(()=>fn(item), maxRetries);
354
- results[i] = result;
355
- } finally{
356
- semaphore.signal();
357
- }
358
- })());
359
- await Promise.all(tasks);
360
- return results;
361
- }
362
-
363
- const DEFAULT_BASE_URL = (typeof process !== 'undefined' ? process.env.NEXT_PUBLIC_EDGE_STORE_BASE_URL : undefined?.EDGE_STORE_BASE_URL) ?? 'https://files.edgestore.dev';
364
- function createEdgeStoreProvider(opts) {
365
- const EdgeStoreContext = /*#__PURE__*/ React__namespace.createContext(undefined);
366
- const EdgeStoreProvider = ({ children, basePath })=>{
367
- return EdgeStoreProviderInner({
368
- children,
369
- context: EdgeStoreContext,
370
- basePath,
371
- maxConcurrentUploads: opts?.maxConcurrentUploads,
372
- disableDevProxy: opts?.disableDevProxy
373
- });
374
- };
375
- function useEdgeStore() {
376
- if (!EdgeStoreContext) {
377
- throw new Error('React Context is unavailable in Server Components');
378
- }
379
- // @ts-expect-error - We know that the context value should not be undefined
380
- const value = React__namespace.useContext(EdgeStoreContext);
381
- if (!value && process.env.NODE_ENV !== 'production') {
382
- throw new Error('[edgestore]: `useEdgeStore` must be wrapped in a <EdgeStoreProvider />');
383
- }
384
- return value;
385
- }
386
- return {
387
- EdgeStoreProvider,
388
- useEdgeStore
389
- };
390
- }
391
- function EdgeStoreProviderInner({ children, context, basePath, maxConcurrentUploads, disableDevProxy }) {
392
- const apiPath = basePath ? `${basePath}` : '/api/edgestore';
393
- const [state, setState] = React__namespace.useState({
394
- loading: true,
395
- initialized: false,
396
- error: false
397
- });
398
- const uploadingCountRef = React__namespace.useRef(0);
399
- const initExecuted = React__namespace.useRef(false); // to make sure we don't run init twice
400
- React__namespace.useEffect(()=>{
401
- if (!initExecuted.current) {
402
- void init();
403
- }
404
- return ()=>{
405
- initExecuted.current = true;
406
- };
407
- // eslint-disable-next-line react-hooks/exhaustive-deps
408
- }, []);
409
- async function init() {
410
- try {
411
- setState({
412
- loading: true,
413
- initialized: false,
414
- error: false
415
- });
416
- const res = await fetch(`${apiPath}/init`, {
417
- method: 'POST',
418
- credentials: 'include'
419
- });
420
- if (res.ok) {
421
- const json = await res.json();
422
- // Only call _init API if provider is edgestore
423
- if (json.providerName === 'edgestore') {
424
- const innerRes = await fetch(`${DEFAULT_BASE_URL}/_init`, {
425
- method: 'GET',
426
- credentials: 'include',
427
- headers: {
428
- 'x-edgestore-token': json.token
429
- }
430
- });
431
- if (innerRes.ok) {
432
- // update state
433
- setState({
434
- loading: false,
435
- initialized: true,
436
- error: false
437
- });
438
- } else {
439
- setState({
440
- loading: false,
441
- initialized: false,
442
- error: true
443
- });
444
- throw new EdgeStoreClientError("Couldn't initialize EdgeStore.");
445
- }
446
- } else {
447
- // For non-edgestore providers, just update state without calling _init
448
- setState({
449
- loading: false,
450
- initialized: true,
451
- error: false
452
- });
453
- }
454
- } else {
455
- setState({
456
- loading: false,
457
- initialized: false,
458
- error: true
459
- });
460
- await handleError(res);
461
- }
462
- } catch (err) {
463
- setState({
464
- loading: false,
465
- initialized: false,
466
- error: true
467
- });
468
- throw err;
469
- }
470
- }
471
- async function reset() {
472
- await init();
473
- }
474
- return /*#__PURE__*/ React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/ React__namespace.createElement(context.Provider, {
475
- value: {
476
- edgestore: createNextProxy({
477
- apiPath,
478
- uploadingCountRef,
479
- maxConcurrentUploads,
480
- disableDevProxy
481
- }),
482
- reset,
483
- state
484
- }
485
- }, children));
486
- }
487
-
488
- exports.createEdgeStoreProvider = createEdgeStoreProvider;
7
+ exports.createEdgeStoreProvider = contextProvider.createEdgeStoreProvider;