@shellui/core 0.3.0 → 0.4.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.
Files changed (75) hide show
  1. package/package.json +2 -2
  2. package/src/app.tsx +31 -3
  3. package/src/components/ui/dialog.tsx +26 -6
  4. package/src/components/ui/sonner.tsx +9 -5
  5. package/src/features/admin/AdminView.tsx +5 -49
  6. package/src/features/admin/config.ts +15 -0
  7. package/src/features/admin/index.ts +4 -0
  8. package/src/features/admin/routes.tsx +14 -0
  9. package/src/features/admin/utils.ts +79 -0
  10. package/src/features/auth/AuthProvider.tsx +68 -13
  11. package/src/features/auth/backends/shellui.ts +8 -1
  12. package/src/features/auth/components/AccessPendingView.tsx +112 -0
  13. package/src/features/auth/components/LoginButton.tsx +5 -10
  14. package/src/features/auth/components/LoginView.tsx +20 -2
  15. package/src/features/auth/components/OAuthCallbackView.tsx +211 -50
  16. package/src/features/auth/hooks/useAuth.tsx +8 -1
  17. package/src/features/auth/utils/authRequestError.spec.ts +52 -0
  18. package/src/features/auth/utils/authRequestError.ts +45 -0
  19. package/src/features/auth/utils/buildAuthUrlWithNext.spec.ts +18 -0
  20. package/src/features/auth/utils/buildAuthUrlWithNext.ts +12 -0
  21. package/src/features/auth/utils/index.ts +8 -0
  22. package/src/features/auth/utils/isTokenAutoRefreshDisabled.spec.ts +71 -0
  23. package/src/features/auth/utils/isTokenAutoRefreshDisabled.ts +18 -0
  24. package/src/features/config/ConfigProvider.ts +1 -1
  25. package/src/features/config/types.ts +46 -5
  26. package/src/features/layouts/AppLayout.tsx +3 -3
  27. package/src/features/layouts/OverlayShell.tsx +17 -28
  28. package/src/features/layouts/resolveSdkNavigatePath.spec.ts +55 -0
  29. package/src/features/layouts/resolveSdkNavigatePath.ts +68 -0
  30. package/src/features/settings/SettingsIcons.tsx +35 -0
  31. package/src/features/settings/SettingsProvider.tsx +79 -10
  32. package/src/features/settings/SettingsRoutes.tsx +14 -6
  33. package/src/features/settings/SettingsView.tsx +11 -5
  34. package/src/features/settings/components/Advanced.tsx +117 -44
  35. package/src/features/settings/components/Develop.tsx +38 -0
  36. package/src/features/settings/components/ServiceWorker.tsx +52 -25
  37. package/src/features/settings/components/Storage.tsx +138 -0
  38. package/src/features/settings/components/UpdateApp.tsx +1 -1
  39. package/src/features/settings/components/develop/StoragePickerTestButtons.tsx +148 -0
  40. package/src/features/settings/components/develop/UploadToastTestButton.tsx +29 -0
  41. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +55 -1
  42. package/src/features/settings/utils/buildSettingsForPropagation.ts +34 -0
  43. package/src/features/settings/utils/mergePreferencesIntoSettings.spec.ts +1 -1
  44. package/src/features/settings/utils/toSettingsUser.spec.ts +4 -0
  45. package/src/features/settings/utils/toSettingsUser.ts +2 -0
  46. package/src/features/sonner/SonnerContext.tsx +44 -60
  47. package/src/features/storage/StorageBridge.tsx +50 -0
  48. package/src/features/storage/StoragePickerContext.tsx +214 -0
  49. package/src/features/storage/api.spec.ts +303 -0
  50. package/src/features/storage/api.ts +414 -0
  51. package/src/features/storage/handleRequest.spec.ts +88 -0
  52. package/src/features/storage/handleRequest.ts +53 -0
  53. package/src/features/storage/quota.spec.ts +151 -0
  54. package/src/features/storage/quota.ts +104 -0
  55. package/src/features/storage/uploads/UploadToastCard.tsx +442 -0
  56. package/src/features/storage/uploads/UploadToaster.tsx +41 -0
  57. package/src/features/storage/uploads/handleTrackedUpload.spec.ts +170 -0
  58. package/src/features/storage/uploads/handleTrackedUpload.ts +97 -0
  59. package/src/features/storage/uploads/types.ts +24 -0
  60. package/src/features/storage/uploads/uploadQueue.spec.ts +118 -0
  61. package/src/features/storage/uploads/uploadQueue.ts +349 -0
  62. package/src/features/storage/uploads/useUploadQueue.ts +30 -0
  63. package/src/i18n/translations/en/common.json +33 -0
  64. package/src/i18n/translations/en/settings.json +56 -4
  65. package/src/i18n/translations/fr/common.json +33 -0
  66. package/src/i18n/translations/fr/settings.json +56 -4
  67. package/src/index.css +2 -1
  68. package/src/index.ts +2 -0
  69. package/src/lib/z-index.ts +9 -3
  70. package/src/routes/components/NavigationItemRoute.tsx +2 -1
  71. package/src/routes/routes.tsx +2 -13
  72. package/src/service-worker/register.ts +217 -101
  73. package/src/service-worker/sw-dev.ts +5 -1
  74. package/src/service-worker/sw.ts +5 -1
  75. package/src/shellui-target.d.ts +2 -0
@@ -45,6 +45,34 @@ interface SonnerProviderProps {
45
45
  children: ReactNode;
46
46
  }
47
47
 
48
+ /** Root-window toasts store callbacks locally; iframe toasts route via postMessage. */
49
+ function createToastButtonHandler(
50
+ toastId: string | undefined,
51
+ from: string[] | undefined,
52
+ kind: 'action' | 'cancel',
53
+ ): (() => void) | undefined {
54
+ if (!toastId) return undefined;
55
+ let sent = false;
56
+ return () => {
57
+ if (sent) return;
58
+ sent = true;
59
+ if (!from?.length) {
60
+ if (kind === 'action') {
61
+ shellui.callbackRegistry.triggerAction(toastId);
62
+ } else {
63
+ shellui.callbackRegistry.triggerCancel(toastId);
64
+ }
65
+ shellui.callbackRegistry.clear(toastId);
66
+ return;
67
+ }
68
+ shellui.sendMessage({
69
+ type: kind === 'action' ? 'SHELLUI_TOAST_ACTION' : 'SHELLUI_TOAST_CANCEL',
70
+ payload: { id: toastId },
71
+ to: from,
72
+ });
73
+ };
74
+ }
75
+
48
76
  export const SonnerProvider = ({ children }: SonnerProviderProps) => {
49
77
  const toast = useCallback((options: ToastOptions) => {
50
78
  const {
@@ -192,38 +220,16 @@ export const SonnerProvider = ({ children }: SonnerProviderProps) => {
192
220
  },
193
221
  action:
194
222
  payload.action &&
195
- (() => {
196
- let actionSent = false;
197
- return {
198
- label: payload.action?.label ?? undefined,
199
- onClick: () => {
200
- if (actionSent) return;
201
- actionSent = true;
202
- shellui.sendMessage({
203
- type: 'SHELLUI_TOAST_ACTION',
204
- payload: { id: payload.id },
205
- to: data.from,
206
- });
207
- },
208
- };
209
- })(),
223
+ (() => ({
224
+ label: payload.action?.label ?? undefined,
225
+ onClick: createToastButtonHandler(payload.id, data.from, 'action') ?? (() => {}),
226
+ }))(),
210
227
  cancel:
211
228
  payload.cancel &&
212
- (() => {
213
- let cancelSent = false;
214
- return {
215
- label: payload.cancel?.label ?? undefined,
216
- onClick: () => {
217
- if (cancelSent) return;
218
- cancelSent = true;
219
- shellui.sendMessage({
220
- type: 'SHELLUI_TOAST_CANCEL',
221
- payload: { id: payload.id },
222
- to: data.from,
223
- });
224
- },
225
- };
226
- })(),
229
+ (() => ({
230
+ label: payload.cancel?.label ?? undefined,
231
+ onClick: createToastButtonHandler(payload.id, data.from, 'cancel') ?? (() => {}),
232
+ }))(),
227
233
  });
228
234
  });
229
235
 
@@ -240,38 +246,16 @@ export const SonnerProvider = ({ children }: SonnerProviderProps) => {
240
246
  // These handlers send messages that trigger the callbackRegistry
241
247
  action:
242
248
  payload.action &&
243
- (() => {
244
- let actionSent = false;
245
- return {
246
- label: payload.action?.label ?? undefined,
247
- onClick: () => {
248
- if (actionSent) return;
249
- actionSent = true;
250
- shellui.sendMessage({
251
- type: 'SHELLUI_TOAST_ACTION',
252
- payload: { id: payload.id },
253
- to: data.from,
254
- });
255
- },
256
- };
257
- })(),
249
+ (() => ({
250
+ label: payload.action?.label ?? undefined,
251
+ onClick: createToastButtonHandler(payload.id, data.from, 'action') ?? (() => {}),
252
+ }))(),
258
253
  cancel:
259
254
  payload.cancel &&
260
- (() => {
261
- let cancelSent = false;
262
- return {
263
- label: payload.cancel?.label ?? undefined,
264
- onClick: () => {
265
- if (cancelSent) return;
266
- cancelSent = true;
267
- shellui.sendMessage({
268
- type: 'SHELLUI_TOAST_CANCEL',
269
- payload: { id: payload.id },
270
- to: data.from,
271
- });
272
- },
273
- };
274
- })(),
255
+ (() => ({
256
+ label: payload.cancel?.label ?? undefined,
257
+ onClick: createToastButtonHandler(payload.id, data.from, 'cancel') ?? (() => {}),
258
+ }))(),
275
259
  });
276
260
  },
277
261
  );
@@ -0,0 +1,50 @@
1
+ import { useEffect } from 'react';
2
+ import { shellui, type ShellUIMessage, type StorageRequestPayload } from '@shellui/sdk';
3
+ import { useAuth } from '../auth/hooks/useAuth';
4
+ import { useConfig } from '../config/useConfig';
5
+ import { handleStorageRequest } from './handleRequest';
6
+ import { getStorageBaseUrl } from './quota';
7
+ import { handleTrackedUpload, isUploadPayload } from './uploads/handleTrackedUpload';
8
+
9
+ /**
10
+ * Root-window bridge: iframe `SHELLUI_STORAGE_REQUEST` messages are handled here
11
+ * with `storage.url` and the signed-in user's access token.
12
+ */
13
+ export const StorageBridge = () => {
14
+ const { config } = useConfig();
15
+ const { session } = useAuth();
16
+ const storageUrl = getStorageBaseUrl(config);
17
+ const accessToken = session?.accessToken ?? null;
18
+
19
+ useEffect(() => {
20
+ if (typeof window === 'undefined' || window.parent !== window) {
21
+ return;
22
+ }
23
+
24
+ const listener = (message: ShellUIMessage) => {
25
+ const payload = message.payload as StorageRequestPayload | undefined;
26
+ if (!payload?.id || !payload.op) return;
27
+
28
+ const run = isUploadPayload(payload)
29
+ ? handleTrackedUpload({ storageUrl, accessToken, payload })
30
+ : handleStorageRequest({ storageUrl, accessToken, payload });
31
+
32
+ void run.then((response) => {
33
+ const reply = {
34
+ type: 'SHELLUI_STORAGE_RESPONSE' as const,
35
+ payload: response,
36
+ };
37
+ const from = message.from?.filter(Boolean) as string[] | undefined;
38
+ if (from?.length) {
39
+ shellui.sendMessage({ ...reply, to: from });
40
+ return;
41
+ }
42
+ window.postMessage(reply, '*');
43
+ });
44
+ };
45
+
46
+ return shellui.addMessageListener('SHELLUI_STORAGE_REQUEST', listener);
47
+ }, [storageUrl, accessToken]);
48
+
49
+ return null;
50
+ };
@@ -0,0 +1,214 @@
1
+ import {
2
+ createContext,
3
+ useCallback,
4
+ useContext,
5
+ useEffect,
6
+ useRef,
7
+ useState,
8
+ type ReactNode,
9
+ } from 'react';
10
+ import { useTranslation } from 'react-i18next';
11
+ import {
12
+ shellui,
13
+ type ShellUIMessage,
14
+ type StorageSelectMode,
15
+ type StorageSelectRequestPayload,
16
+ type StorageSelectResponsePayload,
17
+ } from '@shellui/sdk';
18
+ import { ContentView } from '../../components/ContentView';
19
+ import { Dialog, DialogContent, DialogDescription, DialogTitle } from '../../components/ui/dialog';
20
+ import { Z_INDEX } from '../../lib/z-index';
21
+ import type { NavigationItem } from '../config/types';
22
+ import { useConfig } from '../config/useConfig';
23
+ import { validateAndNormalizeUrl } from '../modal/ModalContext';
24
+
25
+ type PendingSelect = {
26
+ id: string;
27
+ from?: string[];
28
+ url: string;
29
+ };
30
+
31
+ interface StoragePickerContextValue {
32
+ isOpen: boolean;
33
+ closePicker: (cancelled?: boolean) => void;
34
+ }
35
+
36
+ const StoragePickerContext = createContext<StoragePickerContextValue | undefined>(undefined);
37
+
38
+ export function useStoragePicker(): StoragePickerContextValue {
39
+ const context = useContext(StoragePickerContext);
40
+ if (!context) {
41
+ throw new Error('useStoragePicker must be used within a StoragePickerProvider');
42
+ }
43
+ return context;
44
+ }
45
+
46
+ function buildPickerUrl(filesUrl: string, payload: StorageSelectRequestPayload): string {
47
+ const base = filesUrl.replace(/\/+$/, '');
48
+ const params = new URLSearchParams({
49
+ requestId: payload.id,
50
+ mode: payload.mode,
51
+ multiple: payload.multiple ? '1' : '0',
52
+ });
53
+ return `${base}/#/select?${params.toString()}`;
54
+ }
55
+
56
+ function replyToRequester(pending: PendingSelect, payload: StorageSelectResponsePayload): void {
57
+ const message = {
58
+ type: 'SHELLUI_SELECT_STORAGE_RESULT' as const,
59
+ payload,
60
+ };
61
+ const to = pending.from?.filter(Boolean);
62
+ if (to?.length) {
63
+ shellui.sendMessage({ ...message, to });
64
+ return;
65
+ }
66
+ if (typeof window !== 'undefined') {
67
+ window.postMessage(message, '*');
68
+ }
69
+ }
70
+
71
+ interface StoragePickerProviderProps {
72
+ children: ReactNode;
73
+ }
74
+
75
+ export const StoragePickerProvider = ({ children }: StoragePickerProviderProps) => {
76
+ const { config } = useConfig();
77
+ const { t } = useTranslation('common');
78
+ const [pending, setPending] = useState<PendingSelect | null>(null);
79
+ const pendingRef = useRef<PendingSelect | null>(null);
80
+ pendingRef.current = pending;
81
+
82
+ const closePicker = useCallback((cancelled = true) => {
83
+ const current = pendingRef.current;
84
+ if (!current) return;
85
+ if (cancelled) {
86
+ replyToRequester(current, { id: current.id, cancelled: true });
87
+ }
88
+ pendingRef.current = null;
89
+ setPending(null);
90
+ }, []);
91
+
92
+ const failRequest = useCallback((message: ShellUIMessage, errorMessage: string, status = 503) => {
93
+ const payload = message.payload as StorageSelectRequestPayload | undefined;
94
+ const id = payload?.id ?? '';
95
+ const reply = {
96
+ type: 'SHELLUI_SELECT_STORAGE_RESULT' as const,
97
+ payload: {
98
+ id,
99
+ error: { message: errorMessage, status },
100
+ },
101
+ };
102
+ const to = message.from?.filter(Boolean);
103
+ if (to?.length) {
104
+ shellui.sendMessage({ ...reply, to });
105
+ return;
106
+ }
107
+ window.postMessage(reply, '*');
108
+ }, []);
109
+
110
+ useEffect(() => {
111
+ if (typeof window === 'undefined' || window.parent !== window) {
112
+ return;
113
+ }
114
+
115
+ const stopOpen = shellui.addMessageListener('SHELLUI_SELECT_STORAGE', (message) => {
116
+ const payload = message.payload as StorageSelectRequestPayload | undefined;
117
+ if (!payload?.id) return;
118
+
119
+ const filesUrl = config?.storage?.filesUrl?.trim();
120
+ if (!filesUrl) {
121
+ failRequest(
122
+ message,
123
+ 'Storage picker is not configured. Set storage.filesUrl in shellui.config.ts.',
124
+ 503,
125
+ );
126
+ return;
127
+ }
128
+
129
+ const mode: StorageSelectMode =
130
+ payload.mode === 'files' || payload.mode === 'any' ? payload.mode : 'folders';
131
+ const rawUrl = buildPickerUrl(filesUrl, {
132
+ id: payload.id,
133
+ multiple: Boolean(payload.multiple),
134
+ mode,
135
+ });
136
+ const url = validateAndNormalizeUrl(rawUrl);
137
+ if (!url) {
138
+ failRequest(message, 'Storage picker URL is not allowed.', 400);
139
+ return;
140
+ }
141
+
142
+ const previous = pendingRef.current;
143
+ if (previous) {
144
+ replyToRequester(previous, { id: previous.id, cancelled: true });
145
+ }
146
+
147
+ const next: PendingSelect = {
148
+ id: payload.id,
149
+ from: message.from,
150
+ url,
151
+ };
152
+ pendingRef.current = next;
153
+ setPending(next);
154
+ });
155
+
156
+ const stopResult = shellui.addMessageListener('SHELLUI_SELECT_STORAGE_RESULT', (message) => {
157
+ const payload = message.payload as StorageSelectResponsePayload | undefined;
158
+ const current = pendingRef.current;
159
+ if (!payload?.id || !current || payload.id !== current.id) return;
160
+ // The files iframe posted the result. Forward to the original requester, then close.
161
+ replyToRequester(current, payload);
162
+ pendingRef.current = null;
163
+ setPending(null);
164
+ });
165
+
166
+ return () => {
167
+ stopOpen();
168
+ stopResult();
169
+ };
170
+ }, [config?.storage?.filesUrl, failRequest]);
171
+
172
+ const pickerNavItem = {
173
+ path: '__storage-picker',
174
+ url: pending?.url ?? '',
175
+ label: 'Select',
176
+ useHashRouter: true,
177
+ } as NavigationItem;
178
+
179
+ return (
180
+ <StoragePickerContext.Provider value={{ isOpen: Boolean(pending), closePicker }}>
181
+ {children}
182
+ <Dialog
183
+ open={Boolean(pending)}
184
+ onOpenChange={(open) => {
185
+ if (!open) closePicker(true);
186
+ }}
187
+ >
188
+ <DialogContent
189
+ className="flex h-[min(90vh,720px)] w-full max-w-5xl flex-col overflow-hidden p-0"
190
+ overlayZIndex={Z_INDEX.STORAGE_PICKER_OVERLAY}
191
+ contentZIndex={Z_INDEX.STORAGE_PICKER_CONTENT}
192
+ >
193
+ <DialogTitle className="sr-only">
194
+ {t('storagePicker.title') ?? 'Select files or folders'}
195
+ </DialogTitle>
196
+ <DialogDescription className="sr-only">
197
+ {t('storagePicker.description') ?? 'Choose items, then confirm.'}
198
+ </DialogDescription>
199
+ {pending ? (
200
+ <div className="min-h-0 flex-1">
201
+ <ContentView
202
+ key={pending.id}
203
+ url={pending.url}
204
+ pathPrefix="storage-picker"
205
+ ignoreMessages={true}
206
+ navItem={pickerNavItem}
207
+ />
208
+ </div>
209
+ ) : null}
210
+ </DialogContent>
211
+ </Dialog>
212
+ </StoragePickerContext.Provider>
213
+ );
214
+ };
@@ -0,0 +1,303 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import {
3
+ encodeObjectPath,
4
+ executeStorageOp,
5
+ FOLDER_PLACEHOLDER,
6
+ isFolderPlaceholderPath,
7
+ normalizeStoragePath,
8
+ } from './api';
9
+
10
+ const baseUrl = 'http://localhost:8001';
11
+ const token = 'token-1';
12
+
13
+ function jsonResponse(body: unknown, status = 200): Response {
14
+ return {
15
+ ok: status >= 200 && status < 300,
16
+ status,
17
+ statusText: 'OK',
18
+ headers: new Headers({ 'Content-Type': 'application/json' }),
19
+ json: async () => body,
20
+ blob: async () => new Blob(),
21
+ } as Response;
22
+ }
23
+
24
+ describe('encodeObjectPath', () => {
25
+ it('encodes nested folder segments', () => {
26
+ expect(encodeObjectPath('company', 'docs/reports/2024/q1.pdf')).toBe(
27
+ 'company/docs/reports/2024/q1.pdf',
28
+ );
29
+ expect(encodeObjectPath('company', '/docs/reports/q1.pdf/')).toBe(
30
+ 'company/docs/reports/q1.pdf',
31
+ );
32
+ expect(encodeObjectPath('my bucket', 'a b/c.pdf')).toBe('my%20bucket/a%20b/c.pdf');
33
+ });
34
+ });
35
+
36
+ describe('normalizeStoragePath', () => {
37
+ it('strips slashes', () => {
38
+ expect(normalizeStoragePath('/docs/reports/')).toBe('docs/reports');
39
+ });
40
+ });
41
+
42
+ describe('isFolderPlaceholderPath', () => {
43
+ it('detects the folder marker at any depth', () => {
44
+ expect(isFolderPlaceholderPath(FOLDER_PLACEHOLDER)).toBe(true);
45
+ expect(isFolderPlaceholderPath(`docs/${FOLDER_PLACEHOLDER}`)).toBe(true);
46
+ expect(isFolderPlaceholderPath('docs/q1.pdf')).toBe(false);
47
+ });
48
+ });
49
+
50
+ describe('executeStorageOp', () => {
51
+ afterEach(() => {
52
+ vi.unstubAllGlobals();
53
+ });
54
+
55
+ it('lists buckets', async () => {
56
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse([{ name: 'company' }]));
57
+ vi.stubGlobal('fetch', fetchMock);
58
+ await expect(executeStorageOp(baseUrl, token, { op: 'listBuckets' })).resolves.toEqual([
59
+ { name: 'company' },
60
+ ]);
61
+ expect(fetchMock).toHaveBeenCalledWith('http://localhost:8001/storage/v1/bucket', {
62
+ headers: expect.any(Headers),
63
+ });
64
+ });
65
+
66
+ it('lists a nested prefix and hides folder placeholders', async () => {
67
+ const fetchMock = vi.fn().mockResolvedValue(
68
+ jsonResponse([
69
+ { name: 'q1.pdf', id: '1' },
70
+ { name: FOLDER_PLACEHOLDER, id: '2' },
71
+ { name: '2024', id: null },
72
+ ]),
73
+ );
74
+ vi.stubGlobal('fetch', fetchMock);
75
+
76
+ await expect(
77
+ executeStorageOp(baseUrl, token, {
78
+ op: 'list',
79
+ bucket: 'company',
80
+ prefix: 'docs/reports',
81
+ options: { limit: 200 },
82
+ }),
83
+ ).resolves.toEqual([
84
+ { name: 'q1.pdf', id: '1' },
85
+ { name: '2024', id: null },
86
+ ]);
87
+
88
+ expect(fetchMock).toHaveBeenCalledWith(
89
+ 'http://localhost:8001/storage/v1/object/list/company',
90
+ expect.objectContaining({
91
+ method: 'POST',
92
+ body: JSON.stringify({
93
+ prefix: 'docs/reports',
94
+ limit: 200,
95
+ offset: 0,
96
+ sortBy: { column: 'name', order: 'asc' },
97
+ }),
98
+ }),
99
+ );
100
+ });
101
+
102
+ it('uploads a file into a nested path with upsert', async () => {
103
+ const fetchMock = vi.fn().mockResolvedValue({
104
+ ok: true,
105
+ status: 200,
106
+ headers: new Headers(),
107
+ });
108
+ vi.stubGlobal('fetch', fetchMock);
109
+ const file = new Blob(['pdf'], { type: 'application/pdf' });
110
+
111
+ await expect(
112
+ executeStorageOp(baseUrl, token, {
113
+ op: 'upload',
114
+ bucket: 'company',
115
+ path: 'docs/reports/2024/q1.pdf',
116
+ file,
117
+ upsert: true,
118
+ contentType: 'application/pdf',
119
+ }),
120
+ ).resolves.toEqual({ path: 'docs/reports/2024/q1.pdf' });
121
+
122
+ expect(fetchMock).toHaveBeenCalledWith(
123
+ 'http://localhost:8001/storage/v1/object/company/docs/reports/2024/q1.pdf',
124
+ expect.objectContaining({
125
+ method: 'POST',
126
+ body: file,
127
+ }),
128
+ );
129
+ const headers = fetchMock.mock.calls[0][1].headers as Headers;
130
+ expect(headers.get('Authorization')).toBe('Bearer token-1');
131
+ expect(headers.get('Content-Type')).toBe('application/pdf');
132
+ expect(headers.get('x-upsert')).toBe('true');
133
+ });
134
+
135
+ it('downloads nested objects as blobs', async () => {
136
+ const blob = new Blob(['bytes']);
137
+ const fetchMock = vi.fn().mockResolvedValue({
138
+ ok: true,
139
+ status: 200,
140
+ headers: new Headers(),
141
+ blob: async () => blob,
142
+ });
143
+ vi.stubGlobal('fetch', fetchMock);
144
+ await expect(
145
+ executeStorageOp(baseUrl, token, {
146
+ op: 'download',
147
+ bucket: 'company',
148
+ path: 'docs/reports/q1.pdf',
149
+ }),
150
+ ).resolves.toBe(blob);
151
+ expect(fetchMock).toHaveBeenCalledWith(
152
+ 'http://localhost:8001/storage/v1/object/company/docs/reports/q1.pdf',
153
+ expect.objectContaining({
154
+ headers: { Authorization: 'Bearer token-1' },
155
+ }),
156
+ );
157
+ });
158
+
159
+ it('moves a file with bucket-qualified nested paths', async () => {
160
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({}));
161
+ vi.stubGlobal('fetch', fetchMock);
162
+ await executeStorageOp(baseUrl, token, {
163
+ op: 'move',
164
+ bucket: 'company',
165
+ fromPath: 'docs/reports/q1.pdf',
166
+ toPath: 'archive/2024/q1.pdf',
167
+ });
168
+ expect(fetchMock).toHaveBeenCalledWith(
169
+ 'http://localhost:8001/storage/v1/object/move',
170
+ expect.objectContaining({
171
+ method: 'POST',
172
+ body: JSON.stringify({
173
+ from: 'company/docs/reports/q1.pdf',
174
+ to: 'company/archive/2024/q1.pdf',
175
+ }),
176
+ }),
177
+ );
178
+ });
179
+
180
+ it('moves a folder prefix', async () => {
181
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ moved: 3 }));
182
+ vi.stubGlobal('fetch', fetchMock);
183
+ await executeStorageOp(baseUrl, token, {
184
+ op: 'move',
185
+ bucket: 'company',
186
+ fromPath: 'docs/reports',
187
+ toPath: 'archive/reports',
188
+ folder: true,
189
+ });
190
+ expect(fetchMock).toHaveBeenCalledWith(
191
+ 'http://localhost:8001/storage/v1/object/prefix/company',
192
+ expect.objectContaining({
193
+ method: 'POST',
194
+ body: JSON.stringify({ from: 'docs/reports', to: 'archive/reports' }),
195
+ }),
196
+ );
197
+ });
198
+
199
+ it('creates a nested folder via placeholder upload', async () => {
200
+ const fetchMock = vi.fn().mockResolvedValue(
201
+ jsonResponse({
202
+ Id: 'folder-uuid-1',
203
+ Key: 'company/docs/reports/2024/.emptyFolderPlaceholder',
204
+ }),
205
+ );
206
+ vi.stubGlobal('fetch', fetchMock);
207
+ await expect(
208
+ executeStorageOp(baseUrl, token, {
209
+ op: 'createFolder',
210
+ bucket: 'company',
211
+ path: 'docs/reports/2024',
212
+ }),
213
+ ).resolves.toEqual({ path: 'docs/reports/2024', id: 'folder-uuid-1' });
214
+ expect(fetchMock.mock.calls[0][0]).toBe(
215
+ `http://localhost:8001/storage/v1/object/company/docs/reports/2024/${FOLDER_PLACEHOLDER}`,
216
+ );
217
+ });
218
+
219
+ it('resolves a storage item by id', async () => {
220
+ const fetchMock = vi.fn().mockResolvedValue(
221
+ jsonResponse({
222
+ id: 'folder-uuid-1',
223
+ bucket: 'company',
224
+ path: 'docs/reports',
225
+ name: 'reports',
226
+ type: 'folder',
227
+ }),
228
+ );
229
+ vi.stubGlobal('fetch', fetchMock);
230
+ await expect(
231
+ executeStorageOp(baseUrl, token, { op: 'get', objectId: 'folder-uuid-1' }),
232
+ ).resolves.toEqual({
233
+ id: 'folder-uuid-1',
234
+ bucket: 'company',
235
+ path: 'docs/reports',
236
+ name: 'reports',
237
+ type: 'folder',
238
+ });
239
+ expect(fetchMock).toHaveBeenCalledWith(
240
+ 'http://localhost:8001/storage/v1/object/id/folder-uuid-1',
241
+ expect.objectContaining({ headers: expect.any(Headers) }),
242
+ );
243
+ });
244
+
245
+ it('removes files and folder prefixes', async () => {
246
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ count: 2 }, 200));
247
+ vi.stubGlobal('fetch', fetchMock);
248
+ await executeStorageOp(baseUrl, token, {
249
+ op: 'remove',
250
+ bucket: 'company',
251
+ paths: ['docs/a.pdf'],
252
+ });
253
+ expect(fetchMock.mock.calls[0][0]).toBe(
254
+ 'http://localhost:8001/storage/v1/object/company/docs/a.pdf',
255
+ );
256
+ expect(fetchMock.mock.calls[0][1]).toEqual(expect.objectContaining({ method: 'DELETE' }));
257
+
258
+ await executeStorageOp(baseUrl, token, {
259
+ op: 'removeFolder',
260
+ bucket: 'company',
261
+ path: 'docs/reports',
262
+ });
263
+ expect(fetchMock.mock.calls[1][0]).toBe(
264
+ 'http://localhost:8001/storage/v1/object/prefix/company',
265
+ );
266
+ expect(fetchMock.mock.calls[1][1]).toEqual(
267
+ expect.objectContaining({
268
+ method: 'DELETE',
269
+ body: JSON.stringify({ prefix: 'docs/reports' }),
270
+ }),
271
+ );
272
+ });
273
+
274
+ it('requests folder stats for a nested prefix', async () => {
275
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ file_count: 4 }));
276
+ vi.stubGlobal('fetch', fetchMock);
277
+ await executeStorageOp(baseUrl, token, {
278
+ op: 'folderStats',
279
+ bucket: 'company',
280
+ path: 'docs/reports/2024',
281
+ });
282
+ expect(fetchMock.mock.calls[0][0]).toBe(
283
+ 'http://localhost:8001/storage/v1/object/prefix/company?prefix=docs%2Freports%2F2024',
284
+ );
285
+ });
286
+
287
+ it('throws mapped http errors', async () => {
288
+ vi.stubGlobal(
289
+ 'fetch',
290
+ vi.fn().mockResolvedValue({
291
+ ok: false,
292
+ status: 403,
293
+ statusText: 'Forbidden',
294
+ json: async () => ({ message: 'Denied', error: 'access_denied' }),
295
+ }),
296
+ );
297
+ await expect(executeStorageOp(baseUrl, token, { op: 'listBuckets' })).rejects.toMatchObject({
298
+ status: 403,
299
+ code: 'access_denied',
300
+ message: 'Denied',
301
+ });
302
+ });
303
+ });