@conloca/content-api-client 0.1.16 → 0.2.1

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 (45) hide show
  1. package/README.md +190 -105
  2. package/dist/client.d.ts +12 -14
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +26 -25
  5. package/dist/client.js.map +1 -0
  6. package/dist/data-bindings.d.ts +13 -0
  7. package/dist/data-bindings.d.ts.map +1 -0
  8. package/dist/data-bindings.js +71 -0
  9. package/dist/data-bindings.js.map +1 -0
  10. package/dist/hooks.d.ts +42 -39
  11. package/dist/hooks.d.ts.map +1 -1
  12. package/dist/hooks.js +93 -47
  13. package/dist/hooks.js.map +1 -0
  14. package/dist/index.d.ts +5 -5
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +5 -4
  17. package/dist/index.js.map +1 -0
  18. package/dist/lib/content-api-client.js +1 -0
  19. package/dist/lib/content-api-client.js.map +1 -0
  20. package/dist/test-helpers.d.ts +1 -2
  21. package/dist/test-helpers.d.ts.map +1 -1
  22. package/dist/test-helpers.js +2 -2
  23. package/dist/test-helpers.js.map +1 -0
  24. package/dist/testing.d.ts +1 -1
  25. package/dist/testing.d.ts.map +1 -1
  26. package/dist/testing.js +2 -1
  27. package/dist/testing.js.map +1 -0
  28. package/package.json +44 -44
  29. package/src/client.ts +513 -0
  30. package/src/data-bindings.ts +104 -0
  31. package/src/hooks.tsx +959 -0
  32. package/src/index.ts +50 -0
  33. package/src/lib/content-api-client.ts +3 -0
  34. package/src/test-helpers.ts +282 -0
  35. package/src/testing.ts +8 -0
  36. package/dist/index.d.mts +0 -234
  37. package/dist/index.d.mts.map +0 -1
  38. package/dist/index.mjs +0 -1106
  39. package/dist/index.mjs.map +0 -1
  40. package/dist/test-helpers-BFyjmKzv.mjs +0 -221
  41. package/dist/test-helpers-BFyjmKzv.mjs.map +0 -1
  42. package/dist/test-helpers-B_YQhpE2.d.mts +0 -93
  43. package/dist/test-helpers-B_YQhpE2.d.mts.map +0 -1
  44. package/dist/testing.d.mts +0 -2
  45. package/dist/testing.mjs +0 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@conloca/content-api-client",
3
- "version": "0.1.16",
3
+ "version": "0.2.1",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -10,82 +10,82 @@
10
10
  "directory": "packages/content-api-client"
11
11
  },
12
12
  "type": "module",
13
- "main": "./dist/index.mjs",
14
- "module": "./dist/index.mjs",
15
- "types": "./dist/index.d.mts",
13
+ "main": "./dist/index.js",
14
+ "module": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
16
  "exports": {
17
17
  "./package.json": "./package.json",
18
18
  ".": {
19
- "types": "./dist/index.d.mts",
20
- "import": "./dist/index.mjs",
21
- "default": "./dist/index.mjs"
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "default": "./dist/index.js"
22
22
  },
23
23
  "./testing": {
24
- "types": "./dist/testing.d.mts",
25
- "import": "./dist/testing.mjs",
26
- "default": "./dist/testing.mjs"
24
+ "types": "./dist/testing.d.ts",
25
+ "import": "./dist/testing.js",
26
+ "default": "./dist/testing.js"
27
27
  }
28
28
  },
29
29
  "files": [
30
30
  "dist",
31
- "!**/*.tsbuildinfo",
32
- "!dist/test"
31
+ "src",
32
+ "!**/*.tsbuildinfo"
33
33
  ],
34
34
  "scripts": {
35
35
  "test": "nx run content-api-client:test --outputStyle=stream"
36
36
  },
37
37
  "dependencies": {
38
- "@conloca/content-api": "0.1.16",
39
- "@tanstack/react-query": "^5.100.6",
38
+ "@conloca/content-api": "0.2.1",
39
+ "@tanstack/react-query": "^5.102.8",
40
40
  "tslib": "^2.8.1"
41
41
  },
42
42
  "peerDependencies": {
43
- "react": "^19.2.5",
44
- "react-dom": "^19.2.5"
43
+ "react": "^19.0.0",
44
+ "react-dom": "^19.0.0"
45
45
  },
46
46
  "devDependencies": {
47
- "@happy-dom/global-registrator": "20.6.1",
48
- "@testing-library/jest-dom": "^6.9.1",
49
- "@testing-library/react": "^16.3.2",
50
- "@types/react": "19.2.14"
47
+ "@happy-dom/global-registrator": "20.13.2",
48
+ "@testing-library/react": "^16.3.3",
49
+ "@types/react": "19.2.18"
51
50
  },
52
51
  "nx": {
53
52
  "targets": {
54
53
  "clean": {},
55
54
  "lint": {},
56
- "tsdown-js": {
57
- "executor": "nx:run-commands",
58
- "cache": true,
59
- "dependsOn": [
60
- "^build"
61
- ],
62
- "inputs": [
63
- "{projectRoot}/src/**/*",
64
- "{projectRoot}/tsdown.config.ts",
65
- "{projectRoot}/tsconfig.lib.json",
66
- "{projectRoot}/package.json"
67
- ],
68
- "outputs": [
69
- "{projectRoot}/dist/**/*.mjs",
70
- "{projectRoot}/dist/**/*.js",
71
- "{projectRoot}/dist/**/*.d.mts"
72
- ],
73
- "options": {
74
- "command": "tsdown",
75
- "cwd": "{projectRoot}"
76
- }
77
- },
78
55
  "test": {
79
56
  "executor": "@smoothbricks/nx-plugin:bounded-exec",
80
57
  "dependsOn": [
81
58
  "typecheck-tests",
82
- "^build"
59
+ "^build",
60
+ "test-packed"
83
61
  ],
84
62
  "options": {
85
63
  "command": "bun test --timeout=30000",
86
64
  "cwd": "{projectRoot}",
87
65
  "timeoutMs": 120000,
88
- "killAfterMs": 1e4
66
+ "killAfterMs": 10000
67
+ }
68
+ },
69
+ "test-packed": {
70
+ "//": "The packed shape is a function of the built outputs, the manifest and the locked dependency closure; cached on exactly those.",
71
+ "executor": "nx:run-commands",
72
+ "cache": true,
73
+ "inputs": [
74
+ {
75
+ "dependentTasksOutputFiles": "**/*",
76
+ "transitive": true
77
+ },
78
+ "{projectRoot}/package.json",
79
+ "{workspaceRoot}/bun.lock",
80
+ "{workspaceRoot}/tooling/packaging/**/*"
81
+ ],
82
+ "dependsOn": [
83
+ "build",
84
+ "^build"
85
+ ],
86
+ "options": {
87
+ "command": "bun tooling/packaging/test-packed.ts content-api-client",
88
+ "cwd": "{workspaceRoot}"
89
89
  }
90
90
  }
91
91
  },
package/src/client.ts ADDED
@@ -0,0 +1,513 @@
1
+ import type {
2
+ APIError,
3
+ AssetEntry,
4
+ AssetMetadataPatch,
5
+ AssetUsage,
6
+ BatchResult,
7
+ ContentEntry,
8
+ ContentListResult,
9
+ ContentManifest,
10
+ CreateContentInput,
11
+ CreateResult,
12
+ DeleteResult,
13
+ ErrorCode,
14
+ FolderListing,
15
+ FolderTreeNode,
16
+ GitCommitResult,
17
+ GitPullResult,
18
+ GitPushResult,
19
+ GitStatus,
20
+ GlobalFilters,
21
+ LocalizedEntry,
22
+ MDXCompileResponse,
23
+ MoveResult,
24
+ SitesConfig,
25
+ UpdateLocaleInput,
26
+ UpdateResult,
27
+ } from '@conloca/content-api';
28
+ import { ErrorCodes } from '@conloca/content-api';
29
+
30
+ export interface ContentAPIClientOptions {
31
+ baseUrl?: string;
32
+ fetch?: typeof fetch;
33
+ }
34
+
35
+ export class ContentAPIClient {
36
+ private baseUrl: string;
37
+ private fetch: typeof fetch;
38
+
39
+ constructor(options: ContentAPIClientOptions = {}) {
40
+ // Bind fetch to maintain its context
41
+ if (options.fetch) {
42
+ this.fetch = options.fetch;
43
+ } else if (typeof globalThis !== 'undefined' && globalThis.fetch) {
44
+ // Use globalThis for better compatibility
45
+ this.fetch = globalThis.fetch.bind(globalThis);
46
+ } else {
47
+ this.fetch = fetch;
48
+ }
49
+ this.baseUrl = options.baseUrl || '/__conloca/api';
50
+ }
51
+
52
+ private encodeAssetPath(path: string): string {
53
+ return path
54
+ .split('/')
55
+ .map((s) => encodeURIComponent(s))
56
+ .join('/');
57
+ }
58
+
59
+ private async fetchAPI<T>(url: string, options?: RequestInit): Promise<T> {
60
+ const response = await this.fetch(url, {
61
+ ...options,
62
+ headers: {
63
+ 'Content-Type': 'application/json',
64
+ ...options?.headers,
65
+ },
66
+ });
67
+
68
+ if (!response.ok) {
69
+ let errorData: any;
70
+ try {
71
+ errorData = await response.json();
72
+ } catch {
73
+ // If JSON parsing fails, throw generic error
74
+ throw new Error(`API error: ${response.status} ${response.statusText}`);
75
+ }
76
+
77
+ // Check if it's an APIError format
78
+ if (errorData?.error?.code) {
79
+ const apiError = errorData as APIError;
80
+
81
+ // Special handling for stale writes
82
+ if (apiError.error.code === ErrorCodes.STALE_WRITE) {
83
+ throw new StaleWriteError({
84
+ code: apiError.error.code,
85
+ message: apiError.error.message,
86
+ currentEtag: apiError.error.details?.currentEtag,
87
+ });
88
+ }
89
+
90
+ // Create a proper error with code and details
91
+ const error = new APIClientError(
92
+ apiError.error.message,
93
+ apiError.error.code as ErrorCode,
94
+ apiError.error.details,
95
+ );
96
+ throw error;
97
+ }
98
+
99
+ // Fallback for non-standard error responses
100
+ throw new Error(`API error: ${response.status} ${response.statusText}`);
101
+ }
102
+
103
+ return (await response.json()) as Promise<T>;
104
+ }
105
+
106
+ // Core content operations
107
+ async getContent(id: string): Promise<ContentEntry | null> {
108
+ try {
109
+ const response = await this.fetch(`${this.baseUrl}/content/${id}`);
110
+ if (response.status === 404) {
111
+ return null;
112
+ }
113
+ if (!response.ok) {
114
+ throw new Error(`Failed to fetch content: ${response.statusText}`);
115
+ }
116
+ return (await response.json()) as ContentEntry;
117
+ } catch (error) {
118
+ console.error('Error fetching content:', error);
119
+ throw error;
120
+ }
121
+ }
122
+
123
+ async getLocalized(id: string, locale: string): Promise<LocalizedEntry | null> {
124
+ try {
125
+ const response = await this.fetch(`${this.baseUrl}/content/${id}/${locale}`);
126
+ if (response.status === 404) {
127
+ return null;
128
+ }
129
+ if (!response.ok) {
130
+ throw new Error(`Failed to fetch localized content: ${response.statusText}`);
131
+ }
132
+ return (await response.json()) as LocalizedEntry;
133
+ } catch (error) {
134
+ console.error('Error fetching localized content:', error);
135
+ throw error;
136
+ }
137
+ }
138
+
139
+ async createContent(data: CreateContentInput): Promise<CreateResult> {
140
+ return this.fetchAPI<CreateResult>(`${this.baseUrl}/content`, {
141
+ method: 'POST',
142
+ body: JSON.stringify(data),
143
+ });
144
+ }
145
+
146
+ async updateLocalized(input: UpdateLocaleInput): Promise<UpdateResult> {
147
+ const { id, locale, data, etag } = input;
148
+ const params = new URLSearchParams({ locale, etag });
149
+ return this.fetchAPI<UpdateResult>(`${this.baseUrl}/content/${id}?${params}`, {
150
+ method: 'PUT',
151
+ body: JSON.stringify(data),
152
+ });
153
+ }
154
+
155
+ async deleteContent(id: string, etag: string): Promise<DeleteResult> {
156
+ return this.fetchAPI<DeleteResult>(`${this.baseUrl}/content/${id}`, {
157
+ method: 'DELETE',
158
+ headers: {
159
+ 'If-Match': etag,
160
+ },
161
+ });
162
+ }
163
+
164
+ async deleteLocalized(input: { id: string; locale: string; etag: string }): Promise<DeleteResult> {
165
+ return this.fetchAPI<DeleteResult>(`${this.baseUrl}/content/${input.id}?locale=${input.locale}`, {
166
+ method: 'DELETE',
167
+ headers: {
168
+ 'If-Match': input.etag,
169
+ },
170
+ });
171
+ }
172
+
173
+ // Site operations
174
+ async getSitePages(site: string, locale?: string): Promise<ContentListResult> {
175
+ const url = locale ? `${this.baseUrl}/${site}/pages?locale=${locale}` : `${this.baseUrl}/${site}/pages`;
176
+ return this.fetchAPI<ContentListResult>(url);
177
+ }
178
+
179
+ async getPageByPathname(site: string, pathname: string, locale?: string): Promise<ContentManifest | null> {
180
+ try {
181
+ const url = locale
182
+ ? `${this.baseUrl}/sites/${site}/pathname${pathname}?locale=${locale}`
183
+ : `${this.baseUrl}/sites/${site}/pathname${pathname}`;
184
+ const response = await this.fetch(url);
185
+ if (response.status === 404) {
186
+ return null;
187
+ }
188
+ if (!response.ok) {
189
+ throw new Error(`Failed to fetch page: ${response.statusText}`);
190
+ }
191
+ return (await response.json()) as ContentManifest;
192
+ } catch (error) {
193
+ console.error('Error fetching page by pathname:', error);
194
+ throw error;
195
+ }
196
+ }
197
+
198
+ async isPathnameAvailable(site: string, pathname: string, excludeId?: string, locale?: string): Promise<boolean> {
199
+ const params = new URLSearchParams({
200
+ pathname,
201
+ ...(excludeId && { excludeId }),
202
+ ...(locale && { locale }),
203
+ });
204
+
205
+ const response = await this.fetch(`${this.baseUrl}/${site}/pathname-available?${params}`);
206
+ if (!response.ok) {
207
+ throw new Error(`Failed to check pathname availability: ${response.statusText}`);
208
+ }
209
+
210
+ const data = (await response.json()) as { available: boolean };
211
+ return data.available;
212
+ }
213
+
214
+ async movePage(site: string, id: string, pathname: string, locale: string, etag: string): Promise<MoveResult> {
215
+ return this.fetchAPI<MoveResult>(`${this.baseUrl}/${site}/move`, {
216
+ method: 'POST',
217
+ body: JSON.stringify({ id, pathname, locale, etag }),
218
+ });
219
+ }
220
+
221
+ // Fragment operations
222
+ async getFragments(collection?: string, locale?: string): Promise<ContentListResult> {
223
+ const params = new URLSearchParams();
224
+ if (collection) params.set('collection', collection);
225
+ if (locale) params.set('locale', locale);
226
+
227
+ const url = `${this.baseUrl}/fragments${params.toString() ? `?${params}` : ''}`;
228
+ return this.fetchAPI<ContentListResult>(url);
229
+ }
230
+
231
+ async getFragmentByName(name: string, collection?: string, locale?: string): Promise<ContentManifest | null> {
232
+ try {
233
+ const params = new URLSearchParams();
234
+ if (collection) params.set('collection', collection);
235
+ if (locale) params.set('locale', locale);
236
+
237
+ const url = `${this.baseUrl}/fragments/${name}${params.toString() ? `?${params}` : ''}`;
238
+ const response = await this.fetch(url);
239
+ if (response.status === 404) {
240
+ return null;
241
+ }
242
+ if (!response.ok) {
243
+ throw new Error(`Failed to fetch fragment: ${response.statusText}`);
244
+ }
245
+ return (await response.json()) as ContentManifest;
246
+ } catch (error) {
247
+ console.error('Error fetching fragment by name:', error);
248
+ throw error;
249
+ }
250
+ }
251
+
252
+ async compileMDX(mdxContent: string): Promise<MDXCompileResponse> {
253
+ return this.fetchAPI<MDXCompileResponse>(`${this.baseUrl}/mdx/compile`, {
254
+ method: 'POST',
255
+ body: JSON.stringify({ mdxContent }),
256
+ });
257
+ }
258
+
259
+ // Data operations
260
+ async getData(collection?: string, locale?: string): Promise<ContentListResult> {
261
+ const params = new URLSearchParams();
262
+ if (collection) params.set('collection', collection);
263
+ if (locale) params.set('locale', locale);
264
+
265
+ const url = `${this.baseUrl}/data${params.toString() ? `?${params}` : ''}`;
266
+ return this.fetchAPI<ContentListResult>(url);
267
+ }
268
+
269
+ async getDataByName(name: string, collection: string, locale?: string): Promise<ContentManifest | null> {
270
+ try {
271
+ const params = new URLSearchParams();
272
+ params.set('collection', collection);
273
+ if (locale) params.set('locale', locale);
274
+
275
+ const url = `${this.baseUrl}/data/${name}?${params}`;
276
+ const response = await this.fetch(url);
277
+ if (response.status === 404) {
278
+ return null;
279
+ }
280
+ if (!response.ok) {
281
+ throw new Error(`Failed to fetch data entry: ${response.statusText}`);
282
+ }
283
+ return (await response.json()) as ContentManifest;
284
+ } catch (error) {
285
+ console.error('Error fetching data entry by name:', error);
286
+ throw error;
287
+ }
288
+ }
289
+
290
+ async isDataNameAvailable(name: string, collection: string, excludeId?: string): Promise<boolean> {
291
+ const params = new URLSearchParams({
292
+ name,
293
+ collection,
294
+ ...(excludeId && { excludeId }),
295
+ });
296
+
297
+ const response = await this.fetch(`${this.baseUrl}/data/name-available?${params}`);
298
+ if (!response.ok) {
299
+ throw new Error(`Failed to check data name availability: ${response.statusText}`);
300
+ }
301
+
302
+ const data = (await response.json()) as { available: boolean };
303
+ return data.available;
304
+ }
305
+
306
+ async getDataCollections(): Promise<string[]> {
307
+ const response = await this.fetchAPI<{ collections: string[] }>(`${this.baseUrl}/data/collections`);
308
+ return response.collections;
309
+ }
310
+
311
+ // Global operations
312
+ async listAllContent(filters?: GlobalFilters): Promise<ContentListResult> {
313
+ const params = new URLSearchParams();
314
+ if (filters?.site) params.set('site', filters.site);
315
+ if (filters?.collection) params.set('collection', filters.collection);
316
+ if (filters?.locales?.length) params.set('locales', filters.locales.join(','));
317
+ if (filters?.type) params.set('type', filters.type);
318
+ if (filters?.published !== undefined) params.set('published', String(filters.published));
319
+ if (filters?.kind) params.set('kind', filters.kind);
320
+ if (filters?.localization) params.set('localization', filters.localization);
321
+ if (filters?.missingLocales?.length) params.set('missingLocales', filters.missingLocales.join(','));
322
+
323
+ const url = `${this.baseUrl}/content${params.toString() ? `?${params}` : ''}`;
324
+ return this.fetchAPI<ContentListResult>(url);
325
+ }
326
+
327
+ async findUntranslatedContent(
328
+ targetLocale: string,
329
+ excludeSites?: string[],
330
+ includeUnpublished?: boolean,
331
+ ): Promise<ContentListResult> {
332
+ const params = new URLSearchParams();
333
+ if (excludeSites?.length) params.set('excludeSites', excludeSites.join(','));
334
+ if (includeUnpublished) params.set('includeUnpublished', 'true');
335
+
336
+ const url = `${this.baseUrl}/untranslated/${targetLocale}${params.toString() ? `?${params}` : ''}`;
337
+ return this.fetchAPI<ContentListResult>(url);
338
+ }
339
+
340
+ async getSitesConfig(): Promise<SitesConfig> {
341
+ return this.fetchAPI<SitesConfig>(`${this.baseUrl}/sites`);
342
+ }
343
+
344
+ // Batch operations
345
+ async batchUpdate(operations: UpdateLocaleInput[]): Promise<BatchResult> {
346
+ return this.fetchAPI<BatchResult>(`${this.baseUrl}/content/batch`, {
347
+ method: 'POST',
348
+ body: JSON.stringify({ operations }),
349
+ });
350
+ }
351
+
352
+ // Git operations
353
+ async getGitStatus(): Promise<GitStatus> {
354
+ return this.fetchAPI<GitStatus>(`${this.baseUrl}/git/status`);
355
+ }
356
+
357
+ async commitChanges(message?: string): Promise<GitCommitResult> {
358
+ return this.fetchAPI<GitCommitResult>(`${this.baseUrl}/git/commit`, {
359
+ method: 'POST',
360
+ body: JSON.stringify(message ? { message } : {}),
361
+ });
362
+ }
363
+
364
+ async pushChanges(): Promise<GitPushResult> {
365
+ return this.fetchAPI<GitPushResult>(`${this.baseUrl}/git/push`, {
366
+ method: 'POST',
367
+ body: JSON.stringify({}),
368
+ });
369
+ }
370
+
371
+ async pullChanges(): Promise<GitPullResult> {
372
+ return this.fetchAPI<GitPullResult>(`${this.baseUrl}/git/pull`, {
373
+ method: 'POST',
374
+ body: JSON.stringify({}),
375
+ });
376
+ }
377
+
378
+ // Asset operations
379
+ async listAssets(): Promise<{ assets: AssetEntry[] }> {
380
+ return this.fetchAPI<{ assets: AssetEntry[] }>(`${this.baseUrl}/assets`);
381
+ }
382
+
383
+ /** An asset by its path from the assets root: `trip/beach.png`, or `beach.png` for one at the top. */
384
+ async getAsset(path: string): Promise<AssetEntry | null> {
385
+ try {
386
+ const response = await this.fetch(`${this.baseUrl}/assets/meta/${this.encodeAssetPath(path)}`);
387
+ if (response.status === 404) {
388
+ return null;
389
+ }
390
+ if (!response.ok) {
391
+ throw new Error(`Failed to fetch asset: ${response.statusText}`);
392
+ }
393
+ return (await response.json()) as AssetEntry;
394
+ } catch (error) {
395
+ console.error('Error fetching asset:', error);
396
+ throw error;
397
+ }
398
+ }
399
+
400
+ async uploadAsset(formData: FormData): Promise<AssetEntry> {
401
+ const response = await this.fetch(`${this.baseUrl}/assets/upload`, {
402
+ method: 'POST',
403
+ body: formData,
404
+ // No Content-Type header — browser sets multipart boundary automatically
405
+ });
406
+
407
+ if (!response.ok) {
408
+ let errorData: { error?: { message?: string } } | undefined;
409
+ try {
410
+ errorData = (await response.json()) as { error?: { message?: string } };
411
+ } catch {
412
+ // ignore
413
+ }
414
+ throw new Error(errorData?.error?.message || `Upload failed: ${response.status} ${response.statusText}`);
415
+ }
416
+
417
+ return (await response.json()) as AssetEntry;
418
+ }
419
+
420
+ async importAssetUrl(url: string, alt?: string, folder?: string): Promise<AssetEntry> {
421
+ return this.fetchAPI<AssetEntry>(`${this.baseUrl}/assets/import-url`, {
422
+ method: 'POST',
423
+ body: JSON.stringify({ url, alt, folder }),
424
+ });
425
+ }
426
+
427
+ /** Delete the asset at a path from the assets root, as `getAsset` takes it. */
428
+ async deleteAsset(path: string): Promise<{ success: boolean }> {
429
+ return this.fetchAPI<{ success: boolean }>(`${this.baseUrl}/assets/meta/${this.encodeAssetPath(path)}`, {
430
+ method: 'DELETE',
431
+ });
432
+ }
433
+
434
+ // Folder operations
435
+ async listFolder(path = '/'): Promise<FolderListing> {
436
+ const params = new URLSearchParams({ path });
437
+ return this.fetchAPI<FolderListing>(`${this.baseUrl}/assets/folders?${params}`);
438
+ }
439
+
440
+ async createFolder(path: string): Promise<void> {
441
+ await this.fetchAPI<{ success: true }>(`${this.baseUrl}/assets/folders`, {
442
+ method: 'POST',
443
+ body: JSON.stringify({ path }),
444
+ });
445
+ }
446
+
447
+ // Asset metadata operations
448
+ /** Merge alt text and tags onto the asset at a path from the assets root, as `getAsset` takes it. */
449
+ async updateAssetMetadata(path: string, updates: AssetMetadataPatch): Promise<AssetEntry> {
450
+ return this.fetchAPI<AssetEntry>(`${this.baseUrl}/assets/meta/${this.encodeAssetPath(path)}`, {
451
+ method: 'PATCH',
452
+ body: JSON.stringify(updates),
453
+ });
454
+ }
455
+
456
+ /** The content that links to the asset at a path from the assets root, as `getAsset` takes it. */
457
+ async getAssetUsage(path: string): Promise<AssetUsage[]> {
458
+ const response = await this.fetchAPI<{ usage: AssetUsage[] }>(
459
+ `${this.baseUrl}/assets/usage/${this.encodeAssetPath(path)}`,
460
+ );
461
+ return response.usage;
462
+ }
463
+
464
+ // Move assets between folders
465
+ async moveAssets(
466
+ filenames: string[],
467
+ sourceFolder: string,
468
+ targetFolder: string,
469
+ ): Promise<{ success: boolean; moved?: number; error?: string }> {
470
+ return this.fetchAPI<{ success: boolean; moved?: number; error?: string }>(`${this.baseUrl}/assets/move`, {
471
+ method: 'POST',
472
+ body: JSON.stringify({ filenames, sourceFolder, targetFolder }),
473
+ });
474
+ }
475
+
476
+ // Get folder tree structure
477
+ async getFolderTree(): Promise<{ tree: FolderTreeNode[] }> {
478
+ return this.fetchAPI<{ tree: FolderTreeNode[] }>(`${this.baseUrl}/assets/folder-tree`);
479
+ }
480
+
481
+ // Auth operations
482
+ async getCurrentUser(): Promise<{ authenticated: boolean; user?: { email: string; sub: string } }> {
483
+ const response = await this.fetch(`${this.baseUrl}/auth/user`);
484
+ if (!response.ok) {
485
+ return { authenticated: false };
486
+ }
487
+ return response.json() as Promise<{ authenticated: boolean; user?: { email: string; sub: string } }>;
488
+ }
489
+ }
490
+
491
+ // Custom error for API responses
492
+ export class APIClientError extends Error {
493
+ constructor(
494
+ message: string,
495
+ public code: ErrorCode,
496
+ public details?: any,
497
+ ) {
498
+ super(message);
499
+ this.name = 'APIClientError';
500
+ }
501
+ }
502
+
503
+ // Custom error for stale writes
504
+ export class StaleWriteError extends APIClientError {
505
+ constructor(public data: { code: ErrorCode; message: string; currentEtag?: string }) {
506
+ super(data.message, data.code, { currentEtag: data.currentEtag });
507
+ this.name = 'StaleWriteError';
508
+ }
509
+
510
+ get currentEtag(): string | undefined {
511
+ return this.details?.currentEtag;
512
+ }
513
+ }